//! Typed Aplicacao — the fourth caixa kind that turns a graph of
//! Servicos into a single declarative application (mesh).
//!
//! See `theory/MESH-COMPOSITION.md` for the design frame: an
//! Aplicacao composes [`crate::CaixaKind::Servico`] caixas via WIT-typed
//! `:contratos` (inter-Servico edges), declares mesh-level
//! `:politicas` (timeouts, retries, breakers, mTLS), pins
//! `:placement` strategy (single-node / replicated / sharded), and
//! exposes `:entrada` (gateway).
//!
//! ```lisp
//! (defcaixa
//! :nome "checkout"
//! :versao "0.1.0"
//! :kind Aplicacao
//! :membros ((:caixa "catalog" :versao "^0.1")
//! (:caixa "cart" :versao "^0.1")
//! (:caixa "payment" :versao "^0.2"))
//! :contratos ((:de "cart" :para "catalog"
//! :wit "wasi:http/proxy" :endpoint "/products/:id")
//! (:de "cart" :para "payment"
//! :wit "wasi:http/proxy" :endpoint "/charge"))
//! :politicas ((:timeout "30s")
//! (:retries 3)
//! (:circuit-breaker (:max-failures 5 :window "60s"))
//! (:mtls-required t))
//! :placement (:estrategia replicated
//! :clusters ("rio" "mar" "plo"))
//! :entrada (:host "checkout.quero.cloud"
//! :para "cart"
//! :paths ("/api/cart" "/api/products")))
//! ```
//!
//! All the typed slots compose with the M2 primitives the Servicos
//! they reference already declare (`:limits`, `:behavior`,
//! `:upgrade-from`). The Aplicacao adds the *graph-level*
//! standardization on top.
use std::time::Duration;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use crate::supervisor; // we reuse the duration-string codec at module scope
// ── inter-Servico contracts ──────────────────────────────────────────
/// One typed edge in the Aplicacao graph. The build refuses any
/// contract whose `:de` or `:para` doesn't appear in `:membros`, and
/// (M3+) cross-checks the `:wit` shape against both Servicos'
/// declared imports/exports.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct WitContract {
/// Caller Servico — must reference an entry in the Aplicacao's
/// `:membros`. The Servico's caixa.lisp must declare a matching
/// `:capabilities` import for the `:wit` world.
pub de: String,
/// Callee Servico — must reference an entry in `:membros`. The
/// Servico must declare a matching `:capabilities` export.
pub para: String,
/// WIT world reference — e.g. `"wasi:http/proxy"`,
/// `"wasi:keyvalue/store"`, `"nats:pub-sub"`. Strings for V0;
/// M4 promotes these to a typed enum once the WIT registry
/// stabilizes in tatara-lisp.
pub wit: String,
/// HTTP endpoint path, present when `:wit` is HTTP-shaped.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub endpoint: Option<String>,
/// NATS / event-stream subject, present when `:wit` is pub-sub-shaped.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub subject: Option<String>,
/// Key/value or queue slot, present when `:wit` is store-shaped.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub slot: Option<String>,
}
/// Canonical lowercase byte-prefix set the substrate's WIT-shape
/// dispatch routes `wasi:http/*` / `http:*` values through as the
/// HTTP-shaped arm. The single source of truth every consumer that
/// classifies a `:wit` value as HTTP-shaped consults —
/// [`WitContract::is_http`] on the typed contract, the
/// `AplicacaoSpec::validate` positive-sweep test's payload-dispatch
/// helper, and every future renderer that routes an L7 emission off a
/// bare `&str` (the M4 per-edge WIT registry resolver, the future
/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer). Spelled
/// exactly as the [`is_wit_world_ref`][iwr] predicate documents the
/// canonical lowercase prefixes ("`wasi:http/`, `nats:`,
/// `wasi:keyvalue/`, `kafka:`, `kv:`, `http:`") so drift between the
/// substrate's accept-set and this crate's dispatch-set is a
/// build-time compile error (unused-import), not a per-renderer
/// silent L7-→-L4 demotion at apply time.
///
/// [iwr]: crate::render::is_wit_world_ref
pub const WIT_HTTP_SHAPE_PREFIXES: &[&str] = &["wasi:http/", "http:"];
/// Canonical lowercase byte-prefix set the substrate's WIT-shape
/// dispatch routes `nats:*` / `kafka:*` values through as the
/// pub-sub-shaped arm. Peer of [`WIT_HTTP_SHAPE_PREFIXES`] /
/// [`WIT_STORE_SHAPE_PREFIXES`] on the shape-dispatch axis; see the
/// HTTP constant's docstring for the full lift rationale.
pub const WIT_PUBSUB_SHAPE_PREFIXES: &[&str] = &["nats:", "kafka:"];
/// Canonical lowercase byte-prefix set the substrate's WIT-shape
/// dispatch routes `wasi:keyvalue/*` / `kv:*` values through as the
/// key/value-store-shaped arm. Peer of [`WIT_HTTP_SHAPE_PREFIXES`] /
/// [`WIT_PUBSUB_SHAPE_PREFIXES`] on the shape-dispatch axis; see the
/// HTTP constant's docstring for the full lift rationale.
pub const WIT_STORE_SHAPE_PREFIXES: &[&str] = &["wasi:keyvalue/", "kv:"];
/// True when `wit` — a raw `:contratos :wit` value — starts with any
/// entry in the `prefixes` accept-set. The single canonical
/// prefix-driven WIT-shape classification combinator every peer
/// per-shape predicate ([`wit_shape_is_http`], [`wit_shape_is_pubsub`],
/// [`wit_shape_is_store`]) routes through, closing the 3-site
/// duplication of the `PREFIXES.iter().any(|p| wit.starts_with(p))`
/// combinator the prior open-coded implementations each carried.
///
/// A future 4th WIT-shape dispatch arm (a hypothetical `wasi:sockets/*`
/// / `tcp:*` transport-layer shape, an `oci:*` capability-import
/// carrier) becomes exactly one new [`WIT_*_SHAPE_PREFIXES`] const +
/// one new `wit_shape_is_<name>` one-liner routing through this
/// combinator, not a fourth copy of the `iter().any(starts_with)`
/// combinator paired to its own prefix-set. Same "one canonical
/// combinator, thin per-arm projections" discipline the peer
/// [`WitTarget::payload_pair`] (6788ed6) already established for the
/// downstream per-arm `(field, payload)` dispatch, extended to the
/// upstream per-arm `PREFIXES → bool` dispatch.
///
/// Declared `pub const fn` — the four peer classifiers
/// ([`wit_shape_is_http`] / [`wit_shape_is_pubsub`] /
/// [`wit_shape_is_store`] / [`wit_shape_is_capability`]) route through
/// this combinator in `const`-eval context, so the raw `&str → bool`
/// WIT-shape dispatch reaches every substrate-side `const`-context
/// consumer (the module-scope `const _: () = assert!(…)` canonical-
/// accept-set + partition-witness pins immediately below the four
/// peer classifiers, any future M4
/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer admission-
/// webhook `const fn` per-`:contratos :wit` shape-arm resolver over a
/// raw &str, any future `const fn` per-`:contratos`-edge WIT-registry
/// prefix-set overlay resolver over the substrate primitive that fans
/// on the shape arm at compile time) through the same typed dispatch
/// on the substrate primitive at const-eval time as at runtime. The
/// prior `prefixes.iter().any(|p| wit.starts_with(p))` body carried
/// non-`const` bounds on stable Rust 1.94 (`.iter()` / `.any()` /
/// `str::starts_with(&str)` via the non-`const` `Pattern` trait); the
/// new body routes the per-prefix probe through a manual byte-level
/// `starts_with` loop over the paired `str::as_bytes` (`pub const fn`)
/// slice projections, dispatching through primitive-`u8` `!=` and
/// `usize` comparison + `pub const fn` `<[u8]>::len` and const-stable
/// slice indexing (since Rust 1.79) — every operation `const`-eval-
/// callable on stable, no iterator methods, no `Pattern` trait.
#[must_use]
pub const fn wit_shape_matches(wit: &str, prefixes: &[&str]) -> bool {
let bytes = wit.as_bytes();
let mut i = 0;
while i < prefixes.len() {
let prefix = prefixes[i].as_bytes();
if prefix.len() <= bytes.len() {
let mut j = 0;
let mut matches = true;
while j < prefix.len() {
if bytes[j] != prefix[j] {
matches = false;
break;
}
j += 1;
}
if matches {
return true;
}
}
i += 1;
}
false
}
/// True when `wit` — a raw `:contratos :wit` value — targets an
/// HTTP-shaped WIT world (starts with any prefix in
/// [`WIT_HTTP_SHAPE_PREFIXES`]). The single dispatch predicate every
/// consumer routes L7-HTTP emission through, whether they carry a
/// full [`WitContract`] on hand ([`WitContract::is_http`] delegates
/// here) or only the raw `wit` string (the positive-sweep test's
/// payload-dispatch helper, future renderers that classify off a
/// bare `&str`). Lifting to a free function makes the shape-dispatch
/// arm reachable without materializing a scratch [`WitContract`] at
/// every classification point, and pins the six-prefix accept-set at
/// one place so future additions (e.g. an `"https:"` peer of
/// `"http:"`) reach every consumer by construction. Routes through
/// the lifted [`wit_shape_matches`] combinator so the
/// `PREFIXES.iter().any(|p| wit.starts_with(p))` scan lives at one
/// canonical primitive, not one open-coded copy per peer arm.
///
/// Declared `pub const fn` — routes through the peer `pub const fn`
/// [`wit_shape_matches`] combinator so every substrate-side
/// `const`-context WIT-shape-arm-classifier consumer (the module-scope
/// `const _: () = assert!(…)` canonical-accept-set + partition-witness
/// pins immediately below, any future M4 admission-webhook
/// `const fn` per-`:contratos :wit` HTTP-arm resolver over a raw &str)
/// reaches through the same typed dispatch on the substrate primitive
/// at const-eval time as at runtime.
#[must_use]
pub const fn wit_shape_is_http(wit: &str) -> bool {
matches!(WitShape::classify(wit), WitShape::Http)
}
/// True when `wit` — a raw `:contratos :wit` value — targets a
/// pub-sub-shaped WIT world (starts with any prefix in
/// [`WIT_PUBSUB_SHAPE_PREFIXES`]). Peer of [`wit_shape_is_http`] /
/// [`wit_shape_is_store`] on the shape-dispatch axis; see
/// [`wit_shape_is_http`] for the lift rationale. Routes through the
/// lifted [`wit_shape_matches`] combinator.
///
/// Declared `pub const fn` — sibling in `const`-eval posture to the
/// peer [`wit_shape_is_http`] classifier; see that function's `const`
/// posture-block for the full rationale.
#[must_use]
pub const fn wit_shape_is_pubsub(wit: &str) -> bool {
matches!(WitShape::classify(wit), WitShape::PubSub)
}
/// True when `wit` — a raw `:contratos :wit` value — targets a
/// key/value-store-shaped WIT world (starts with any prefix in
/// [`WIT_STORE_SHAPE_PREFIXES`]). Peer of [`wit_shape_is_http`] /
/// [`wit_shape_is_pubsub`] on the shape-dispatch axis; see
/// [`wit_shape_is_http`] for the lift rationale. Routes through the
/// lifted [`wit_shape_matches`] combinator.
///
/// Declared `pub const fn` — sibling in `const`-eval posture to the
/// peer [`wit_shape_is_http`] / [`wit_shape_is_pubsub`] classifiers;
/// see [`wit_shape_is_http`]'s `const` posture-block for the full
/// rationale.
#[must_use]
pub const fn wit_shape_is_store(wit: &str) -> bool {
matches!(WitShape::classify(wit), WitShape::Store)
}
/// True when `wit` — a raw `:contratos :wit` value — targets *none* of
/// the three known payload-shape WIT worlds; the payload-less
/// capability arm of the 4-way WIT-shape partition on the raw
/// `:contratos :wit` axis. Peer of [`wit_shape_is_http`] /
/// [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] on the shape-
/// dispatch axis — closes the free-function classifier family the
/// three payload-arm predicates opened onto the exact-inverse
/// disjunction of the trio, so any downstream consumer that must
/// classify a raw `:wit` `&str` onto the payload-less capability arm
/// (a future substrate-side capability-shape-only emitter — the M4
/// per-Aplicacao WIT-registry capability-import materializer, the
/// future `feira app graph --capability` filter, the future per-
/// cluster capability-scope reconciler that skips L4/L7 emission for
/// payload-less edges, the future `mesh.pleme.io/v1alpha1/Aplicacao`
/// CR admission webhook's per-shape histogram) reaches for exactly
/// one typed dispatch at the substrate primitive rather than an
/// open-coded per-consumer `!wit_shape_is_http(wit) &&
/// !wit_shape_is_pubsub(wit) && !wit_shape_is_store(wit)` triplet
/// negation — each of which would silently misclassify a future 4th
/// payload-arm addition (a hypothetical `wasi:sockets/*` transport-
/// layer shape, an `oci:*` capability-import carrier per the sibling
/// [`wit_shape_matches`] docstring's trajectory bullet) as
/// capability without a compile-time signal at the consumer site.
///
/// Fourth arm on the free-function WIT-shape-predicate family — closes
/// the {[`wit_shape_is_http`], [`wit_shape_is_pubsub`],
/// [`wit_shape_is_store`]} trio into a 4-way partition witness on the
/// raw `:contratos :wit` `&str` axis, mirroring the paired sibling
/// [`WitContract`]-surface [`WitContract::is_capability`] predicate and
/// the post-projection [`WitTarget`]-side
/// `gen_platform::IsVariant`-derived [`WitTarget::is_capability`]
/// (7f6aa98 `IsVariant` derive lift on the peer arm-set). Every
/// [`WitTarget`] variant now carries a matched peer predicate on both
/// the raw `&str` axis (this function + [`wit_shape_is_http`] /
/// [`wit_shape_is_pubsub`] / [`wit_shape_is_store`]) and the
/// [`WitContract`] surface (the sibling 4-arm predicate family
/// [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
/// [`WitContract::is_store`] / [`WitContract::is_capability`]),
/// pinned in load-bearing by the sibling
/// [`tests::wit_shape_is_capability_partitions_the_wit_shape_space_on_the_raw_str_axis`]
/// partition-witness pin and the peer
/// [`tests::wit_contract_shape_methods_delegate_to_free_functions`]
/// delegation pin.
///
/// Prior to this lift the "not one of the three known payload shapes"
/// classification only reached the raw `&str` axis by materializing a
/// scratch [`WitContract`] and delegating through
/// [`WitContract::is_capability`] — a five-field constructor at every
/// classification point for a pure `&str → bool` question, and a
/// dependency on the payload-carrier scalar layout the classifier
/// does not read. Same "one canonical combinator, thin per-arm
/// projections" discipline the peer [`wit_shape_is_http`] /
/// [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] trio already
/// established, extended to close the 4-arm partition on the raw
/// `&str` axis.
///
/// Note: purely syntactic classification on the negated `:wit` prefix-
/// set — unlike [`WitContract::target`], which additionally rejects
/// value-shape-invalid `:wit` strings (uppercase, hyphen-for-colon
/// typo, empty package) via [`crate::render::is_wit_world_ref`] and
/// payload-shape mismatches. An empty or structurally malformed `wit`
/// string returns `true` here (the prefix set matches nothing), and
/// the surrounding validate-side gate cascade is where the
/// [`AplicacaoError::EmptyWit`] / [`AplicacaoError::ContratoWitInvalid`]
/// diagnostic surfaces — this function is the classifier, not the
/// validator.
///
/// Declared `pub const fn` — closes the 4-arm classifier family's
/// `const`-eval-surface pass on the payload-less capability arm,
/// peer of the sibling `pub const fn` [`wit_shape_is_http`] /
/// [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] classifiers, so
/// the raw `&str → bool` WIT-shape partition on the capability arm
/// reaches every substrate-side `const`-context consumer through one
/// typed dispatch. See [`wit_shape_is_http`]'s `const` posture-block
/// for the full rationale.
#[must_use]
pub const fn wit_shape_is_capability(wit: &str) -> bool {
matches!(WitShape::classify(wit), WitShape::Capability)
}
// Compile-time pins on the 4-arm WIT-shape classifier family — the
// module-scope const-eval assertions below trip at caixa-core build
// time (not test time) if a future edit rewires any of the four
// classifier's arm-set away from the accept-set MESH-COMPOSITION §II.3
// pins. Anchor the `const`-eval-surface posture of the four peer
// classifiers on canonical accept-set samples (one per WIT_*_SHAPE_PREFIXES
// prefix) plus pairwise-exclusion samples asserting the trio partitions
// the payload-carrying arm-set and the capability arm carries the
// complementary payload-less remainder. Any future accidental downgrade
// of one classifier to non-`const` fails these items at caixa-core build
// time; any future prefix-set edit that overlaps two arms (e.g. a `kv:`
// prefix accidentally re-emitted under `WIT_HTTP_SHAPE_PREFIXES`) trips
// the corresponding partition-witness item. Peer of the sibling M3
// [`PlacementStrategy::requires_shard_key`] partition pins at
// aplicacao.rs:5121-5123 on the sibling closed-set typed-enum
// discriminator axis.
const _: () = assert!(wit_shape_is_http("wasi:http/proxy"));
const _: () = assert!(wit_shape_is_http("http:incoming"));
const _: () = assert!(wit_shape_is_pubsub("nats:events"));
const _: () = assert!(wit_shape_is_pubsub("kafka:topic"));
const _: () = assert!(wit_shape_is_store("wasi:keyvalue/store"));
const _: () = assert!(wit_shape_is_store("kv:cache"));
const _: () = assert!(wit_shape_is_capability("wasi:filesystem/preopens"));
const _: () = assert!(wit_shape_is_capability(""));
// Pairwise-exclusion pins — the three payload-carrying arms are
// pairwise disjoint on the canonical accept-set samples, and the
// capability arm is the exact-inverse disjunction of the trio
// (the free-function classifier family's 4-way partition witness).
const _: () = assert!(!wit_shape_is_http("nats:events"));
const _: () = assert!(!wit_shape_is_http("kv:cache"));
const _: () = assert!(!wit_shape_is_pubsub("wasi:http/proxy"));
const _: () = assert!(!wit_shape_is_pubsub("wasi:keyvalue/store"));
const _: () = assert!(!wit_shape_is_store("wasi:http/proxy"));
const _: () = assert!(!wit_shape_is_store("nats:events"));
const _: () = assert!(!wit_shape_is_capability("wasi:http/proxy"));
const _: () = assert!(!wit_shape_is_capability("nats:events"));
const _: () = assert!(!wit_shape_is_capability("wasi:keyvalue/store"));
/// Closed 4-arm typed classification of a raw `:contratos :wit` value's
/// WIT-shape membership — the single-dispatch typed source of truth for
/// the four-arm partition the free-function classifier family
/// ([`wit_shape_is_http`] / [`wit_shape_is_pubsub`] /
/// [`wit_shape_is_store`] / [`wit_shape_is_capability`]) opens on the
/// raw `&str` axis. Every peer free predicate now routes through
/// [`Self::classify`] via a `matches!` arm-check, so the raw `&str →
/// WIT-shape-arm` dispatch lives at one substrate primitive rather than
/// four open-coded prefix probes plus a triplet negation.
///
/// # Compounding
///
/// The free predicates fan out to four independent bodies, three of
/// which read one [`WIT_*_SHAPE_PREFIXES`] const each and one of which
/// re-negates the trio. A future fifth WIT-shape arm (a hypothetical
/// `wasi:sockets/*` / `tcp:*` transport-layer shape, an `oci:*`
/// capability-import carrier, per the sibling [`wit_shape_matches`]
/// docstring's trajectory bullet) previously required:
/// 1. one new [`WIT_*_SHAPE_PREFIXES`] const,
/// 2. one new `wit_shape_is_<name>` free predicate,
/// 3. an edit to [`wit_shape_is_capability`]'s negation to add the
/// new arm — which a future author can silently forget, at which
/// point every downstream capability-shape reader would
/// misclassify the new arm as capability without a compile-time
/// signal.
///
/// After this lift the third step becomes a compiler-checked
/// exhaustiveness error: adding a fifth [`WitShape`] variant without
/// growing [`Self::classify`]'s `match` fails at caixa-core build time
/// (unhandled arm), and the sibling accessors ([`Self::as_str`], the
/// [`std::fmt::Display`] and [`AsRef<str>`] impls, the
/// [`gen_platform::IsVariant`]-derived per-arm predicates) refuse to
/// compile until the new arm carries a body. The free predicate for
/// the new arm is then a thin one-line `matches!` on the classifier's
/// result, and [`wit_shape_is_capability`]'s definition stays a
/// zero-line delta.
///
/// # Peers
///
/// Peer of the closed-set typed enums the caixa surface already
/// carries on adjacent axes:
/// - [`crate::CaixaKind`] on the top-level `:kind` axis
/// - [`crate::dialeto::CaixaDialeto`] on the dialect-classification axis
/// - [`PlacementStrategy`] on the `:placement :estrategia` axis
/// - [`RateLimitUnit`] on the `:politicas :rate-limit :window` axis
/// - [`crate::supervisor::RestartStrategy`] /
/// [`crate::supervisor::RestartPolicy`] on the supervisor-strategy
/// axes
///
/// Distinct from [`WitTarget`] on the same overall `:contratos` slot:
/// [`WitTarget`] is the *post-validation* payload-carrying view (each
/// arm carries the payload field its shape requires — an endpoint, a
/// subject, a slot); [`WitShape`] is the *pre-validation* raw-`&str`
/// classification (four unit arms — a witness of "which arm would the
/// downstream validate consume this as?" without materializing the
/// payload). Both surfaces carry an [`gen_platform::IsVariant`]-derived
/// arm-predicate family and a `Capability` arm, so any downstream
/// consumer that pairs a raw `&str` shape witness with a validated
/// [`WitTarget`] view reads through matched per-arm predicates on both
/// sides.
///
/// # Not a validator
///
/// Purely syntactic classification on the raw `:contratos :wit` prefix
/// set — unlike [`WitContract::target`], which additionally rejects
/// value-shape-invalid `:wit` strings (uppercase, hyphen-for-colon
/// typo, empty package) via [`crate::render::is_wit_world_ref`] and
/// payload-shape mismatches. An empty or structurally malformed `wit`
/// string classifies here as [`Self::Capability`] (the prefix set
/// matches nothing), and the surrounding validate-side gate cascade is
/// where the [`AplicacaoError::EmptyWit`] /
/// [`AplicacaoError::ContratoWitInvalid`] diagnostic surfaces — this
/// enum is the classifier, not the validator.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant)]
pub enum WitShape {
/// HTTP-shaped WIT world — the raw `:contratos :wit` value starts
/// with any prefix in [`WIT_HTTP_SHAPE_PREFIXES`] (`wasi:http/`,
/// `http:`). Peer of [`WitTarget::Http`] on the paired
/// post-validation payload-carrying view.
Http,
/// Pub-sub-shaped WIT world — the raw `:contratos :wit` value
/// starts with any prefix in [`WIT_PUBSUB_SHAPE_PREFIXES`]
/// (`nats:`, `kafka:`). Peer of [`WitTarget::PubSub`] on the paired
/// post-validation payload-carrying view.
///
/// The `IsVariant` derive would auto-name the predicate
/// `is_pub_sub` (`discriminant_to_snake("PubSub") == "pub_sub"`);
/// the explicit `#[is_variant(name = "pubsub")]` override keeps the
/// emitted method name byte-identical to the sibling
/// [`WitTarget::is_pubsub`] and [`WitContract::is_pubsub`]
/// predicates so all three arm-discriminator axes — raw-`&str`,
/// post-validation payload view, and pre-projection `WitContract`
/// surface — reach every downstream consumer through the same
/// `is_pubsub()` name.
#[is_variant(name = "pubsub")]
PubSub,
/// Key/value-store-shaped WIT world — the raw `:contratos :wit`
/// value starts with any prefix in [`WIT_STORE_SHAPE_PREFIXES`]
/// (`wasi:keyvalue/`, `kv:`). Peer of [`WitTarget::Store`] on the
/// paired post-validation payload-carrying view.
Store,
/// Payload-less capability edge — none of the three payload-arm
/// prefix sets match. Peer of [`WitTarget::Capability`] on the
/// paired post-validation view; the fallback arm that catches
/// everything the payload-arm probes miss, including the empty
/// string and every structurally-malformed `:wit` value the
/// surrounding [`WitContract::target`] validator rejects
/// downstream.
Capability,
}
impl WitShape {
/// Exhaustive iteration surface for every consumer that walks the
/// closed four-arm [`WitShape`] partition — a future
/// `feira app graph --by-wit-shape` histogram column, the future M4
/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
/// admission-webhook rejection body naming the accepted-shape set,
/// any future round-trip fuzz harness that sweeps every arm's
/// canonical accept-set. A future variant addition (a hypothetical
/// `wasi:sockets/*` transport-layer shape, an `oci:*`
/// capability-import carrier per the sibling [`wit_shape_matches`]
/// docstring's trajectory bullet) extends this slice as one edit
/// and every consumer picks up the new entry through the shared
/// iteration; the compiler-checked exhaustiveness on the sibling
/// method `match` arms ([`Self::classify`] / [`Self::as_str`]) is
/// the build-time guarantee that no arm forgets to grow.
///
/// Peer of the sibling closed-set typed enums'
/// [`crate::CaixaKind::ALL`] /
/// [`crate::dialeto::CaixaDialeto::ALL`] /
/// [`PlacementStrategy::ALL`] / [`RateLimitUnit::ALL`] /
/// [`crate::supervisor::RestartStrategy::ALL`] /
/// [`crate::supervisor::RestartPolicy::ALL`] /
/// [`crate::dep::DepList::ALL`] exhaustive-iteration surfaces —
/// the next closed-set typed enum on the caixa surface to converge
/// onto the same one-canonical-arm-list-per-enum discipline, and
/// the first WIT-shape-classification axis (as distinct from an
/// OTP-shape M2 slot or an M3 mesh slot) to reach it. Order matches
/// variant declaration order verbatim (`Http` → `PubSub` → `Store`
/// → `Capability`) so the slice is the canonical ordering every
/// listing / rendering consumer defers to, and matches the arm
/// preference [`Self::classify`] dispatches on.
pub const ALL: &'static [Self] = &[Self::Http, Self::PubSub, Self::Store, Self::Capability];
/// Classify a raw `:contratos :wit` value into its closed four-arm
/// WIT-shape partition — the single canonical dispatch every free
/// [`wit_shape_is_http`] / [`wit_shape_is_pubsub`] /
/// [`wit_shape_is_store`] / [`wit_shape_is_capability`] predicate
/// routes through via a `matches!` arm-check, and the single
/// canonical dispatch every future consumer that needs the full
/// four-arm answer (rather than a per-arm boolean) reaches for.
///
/// Arm preference is `Http` → `PubSub` → `Store` → `Capability`,
/// matching the declaration order pinned in [`Self::ALL`]. Under
/// the disjointness pins immediately above the impl block
/// (`const _: () = assert!(!wit_shape_is_http("nats:events"))` and
/// peers), the preference order is unobservable — no `:wit` value
/// satisfies more than one payload-arm prefix set. If a future
/// prefix-set edit accidentally overlaps two arms (e.g. a `kv:`
/// prefix accidentally re-emitted under
/// [`WIT_HTTP_SHAPE_PREFIXES`]), the sibling `const _: () =
/// assert!(!wit_shape_is_http("kv:cache"))` pin trips at
/// caixa-core build time before the preference-order behavior
/// becomes observable at any consumer site.
///
/// # Const-eval posture
///
/// Declared `pub const fn` — routes through the peer `pub const
/// fn` [`wit_shape_matches`] combinator on each of the three
/// payload-arm prefix-set probes, so every substrate-side
/// `const`-context WIT-shape-arm-classifier consumer (any future
/// M4 admission-webhook `const fn` per-`:contratos :wit`
/// arm-resolver over a raw `&str`, any future `const fn`
/// per-`:contratos`-edge WIT-registry prefix-set overlay resolver
/// that fans on the classified arm at compile time) reaches
/// through the same typed dispatch on the substrate primitive at
/// const-eval time as at runtime. Pinned load-bearing by the
/// [`tests::wit_shape_classify_is_const_fn`] test's `const fn`
/// wrapper — any future accidental downgrade to non-`const` fails
/// with E0015 at the wrapper call site at caixa-core build time,
/// strictly stronger than a runtime `assert!`.
#[must_use]
pub const fn classify(wit: &str) -> Self {
if wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES) {
Self::Http
} else if wit_shape_matches(wit, WIT_PUBSUB_SHAPE_PREFIXES) {
Self::PubSub
} else if wit_shape_matches(wit, WIT_STORE_SHAPE_PREFIXES) {
Self::Store
} else {
Self::Capability
}
}
/// Canonical short kebab byte-string every consumer that formats a
/// [`WitShape`] as census-facing text lands on — returns
/// `"http"` / `"pubsub"` / `"store"` / `"capability"`, the same
/// byte-strings the [`std::fmt::Display`] and [`AsRef<str>`] impls
/// route through and every future histogram-column /
/// audit-report / admission-rejection-body reader reads.
///
/// Peer of the sibling closed-set typed enums'
/// [`crate::CaixaKind::as_str`] /
/// [`crate::dialeto::CaixaDialeto::as_str`] /
/// [`PlacementStrategy::as_str`] /
/// [`RateLimitUnit::as_suffix`] /
/// [`crate::supervisor::RestartStrategy::as_str`] /
/// [`crate::supervisor::RestartPolicy::as_str`] canonical-projection
/// accessors on the sibling closed-set typed-enum discriminator
/// axes.
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Http => "http",
Self::PubSub => "pubsub",
Self::Store => "store",
Self::Capability => "capability",
}
}
/// Reverse projection on the [`WitShape`] closed-set enum's
/// canonical-projection axis — parses a `"http"` / `"pubsub"` /
/// `"store"` / `"capability"` census-label byte-string back to the
/// typed enum, or returns [`None`] when `s` lies outside the four-
/// arm accept-set [`Self::as_str`] emits. The single `&str → Self`
/// projection every future re-entry point on the [`WitShape`]
/// census-label axis dispatches through (a future
/// `feira app graph --by-wit-shape=<http|pubsub|store|capability>`
/// CLI arg-parse that binds the wire byte-string into the typed
/// enum before dispatching to the per-arm histogram column, a
/// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR admission-webhook
/// rejection body re-parsing a prior emission's per-arm audit-column
/// tag back to the typed enum for accepted-shape policy classification,
/// a `tracing::field::Value::Str`-arm structured-log re-loader binding
/// a prior [`std::fmt::Display`]-formatted [`WitShape`] output back to the
/// typed enum for cross-run shape-flavor histogram diff) would have
/// had to re-inline a four-arm `match s` cascade that expressed no
/// compile-time link back to the substrate primitive.
///
/// Distinct axis from the peer [`Self::classify`] total classifier,
/// which takes the *raw* `:contratos :wit` identifier (`"wasi:http/proxy"`,
/// `"nats:events"`, `"wasi:keyvalue/store"`, everything else) and
/// returns the arm the payload-arm prefix-set dispatch resolves to —
/// a total function on the WIT-identifier axis. [`Self::from_wire`]
/// takes the *census-label* byte-string (`"http"` / `"pubsub"` /
/// `"store"` / `"capability"`, the paired output of [`Self::as_str`])
/// and returns the arm — a partial function on the closed four-string
/// census-label axis. The two axes carry different accept-sets by
/// design, not drift: [`Self::classify`] accepts every `&str` and
/// falls through to [`Self::Capability`] on the empty and every
/// structurally-malformed input; [`Self::from_wire`] accepts exactly
/// the four census labels [`Self::as_str`] emits and rejects
/// everything else (including every raw WIT identifier [`Self::classify`]
/// would classify — so a caller who accidentally routes a raw
/// `:contratos :wit` value through [`Self::from_wire`] instead of
/// [`Self::classify`] observes [`None`] rather than a plausibly-wrong
/// arm silently). The paired axis discipline mirrors the sibling
/// [`crate::CaixaKind::as_str`] / [`crate::CaixaKind::from_wire`]
/// pair on the top-level `:kind` axis.
///
/// Same closed-set-reverse-projection discipline the sibling
/// [`crate::CaixaKind::from_wire`] (2aa6d23) /
/// [`crate::dialeto::CaixaDialeto::from_wire`] (d0e65ea) /
/// [`crate::supervisor::RestartStrategy::from_wire`] (4eec29c) /
/// [`crate::supervisor::RestartPolicy::from_wire`] (dd32ccf) /
/// [`PlacementStrategy::from_wire`] (18c7342) /
/// [`crate::dep::DepList::from_wire`] (45ee563) /
/// [`crate::render::PathShapeViolation::from_wire`] (aebd9c6) /
/// `caixa_arch::invariants::InvariantKind::from_wire` (b9e4e61) /
/// `caixa_arch::report::ArchVerdict::from_wire` (6afe564) /
/// `caixa_lint::diagnostic::Severity::from_wire` (5afff0e) /
/// `caixa_lint::diagnostic::FixSafety::from_wire` (bd505a1) /
/// `caixa_theme::style::Semantic::from_wire` (e7bca7b) /
/// `caixa_provedor::ferrite::FerriteRuntime::from_wire` (1e4cc81)
/// typed enums carry on the peer wire-side `str → Self` axes —
/// extends the substrate-wide `(as_str, from_wire)` round-trip
/// family onto the first `:contratos :wit` raw-classification
/// axis to converge on the reverse-projection discipline, matching
/// the same two-way `str ↔ Self` round-trip every sibling closed-
/// set enum already carries. Method-named `from_wire` (not
/// `from_str`) to match the peer shapes verbatim and side-step a
/// `clippy::should_implement_trait` lint that a plain `from_str`
/// name would otherwise trigger without paired [`std::str::FromStr`]
/// impl scaffolding this axis does not carry today. Returns
/// `Option<Self>` (rather than `Result<Self, _>`) to match the peer
/// shapes: the caller picks the diagnostic form appropriate for its
/// use site (a future `feira app graph --by-wit-shape` CLI arg-parse
/// renders its own per-verb error message; a future admission-webhook
/// rejection body wraps the [`None`] outcome with the accepted-set
/// enumeration `WitShape::ALL.iter().map(WitShape::as_str)` for
/// operator diagnostics).
///
/// Pinned load-bearing at the substrate-primitive level by
/// [`tests::wit_shape_from_wire_accepts_every_as_str_output`]
/// (round-trip witness against the peer [`Self::as_str`] axis) and
/// [`tests::wit_shape_from_wire_rejects_unknown_byte_strings`]
/// (rejection witness against silent accept-set widening,
/// including the raw `:contratos :wit` identifiers [`Self::classify`]
/// consumes on the sibling axis — so a caller who confuses the two
/// axes trips the pin at caixa-core build time rather than at a
/// downstream consumer's silent misclassification).
#[must_use]
pub fn from_wire(s: &str) -> Option<Self> {
match s {
"http" => Some(Self::Http),
"pubsub" => Some(Self::PubSub),
"store" => Some(Self::Store),
"capability" => Some(Self::Capability),
_ => None,
}
}
}
/// Route [`std::fmt::Display`] through [`WitShape::as_str`], so every
/// consumer that formats a [`WitShape`] as user-facing text (future
/// histogram column headers on `feira app graph --by-wit-shape`,
/// future admission-webhook rejection bodies enumerating the accepted
/// shape set, future audit-report per-arm column headers) lands on the
/// same `"http"` / `"pubsub"` / `"store"` / `"capability"` byte-string
/// the paired [`AsRef<str>`] impl also routes through. Same
/// canonical-projection discipline the sibling
/// [`std::fmt::Display for crate::CaixaKind`] /
/// [`std::fmt::Display for crate::dialeto::CaixaDialeto`] /
/// [`std::fmt::Display for PlacementStrategy`] /
/// [`std::fmt::Display for RateLimitUnit`] impls carry — every text
/// projection on this closed-set typed enum's dispatch surface reaches
/// through one accessor.
impl std::fmt::Display for WitShape {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
/// Route [`AsRef<str>`] through [`WitShape::as_str`], so every
/// consumer that borrows a [`WitShape`] as `&str` (a future
/// `HashMap<&str, _>` keyed lookup, a `&str`-bounded generic that
/// takes a shape tag) lands on the same byte-string the sibling
/// [`std::fmt::Display`] impl routes through. Peer of the sibling
/// closed-set typed enums' [`AsRef<str>`] impls carrying the same
/// discipline.
impl AsRef<str> for WitShape {
fn as_ref(&self) -> &str {
self.as_str()
}
}
/// Standard-library trait-idiomatic reverse projection on the
/// [`WitShape`] closed-set typed enum. Routes byte-for-byte through the
/// paired substrate-primitive [`WitShape::from_wire`] `Option<Self>`
/// accessor so `s.try_into::<WitShape>()` /
/// `WitShape::try_from(&s)` reaches the same four-arm `"http"` /
/// `"pubsub"` / `"store"` / `"capability"` census-label accept-set the
/// sibling method-named resolver dispatches through and the sibling
/// [`WitShape::as_str`] emits.
///
/// `type Error = ()` — matches the sibling [`WitShape::from_wire`]'s
/// `Option<Self>` return-shape's deliberate deferral of error typing:
/// the caller picks the diagnostic form appropriate for its use site (a
/// future `feira app graph --by-wit-shape <arm>` CLI arg-parse composes
/// its own per-verb "unknown wit-shape: <arg> — accepted: {…}" message
/// enumerating [`WitShape::ALL`], a future M4
/// `mesh.pleme.io/v1alpha1/Aplicacao` CR admission-webhook wraps
/// `Err(())` with a per-CR structured refusal body enumerating the
/// four-arm census set, a `Result::map_err` at the call site lifts the
/// unit-error to a per-verb error type). Same shape the sibling
/// [`crate::CaixaKind`] (3c83606), [`crate::CaixaDialeto`] (bf33136),
/// [`PlacementStrategy`] (6fd00cd), [`crate::supervisor::RestartStrategy`]
/// (5b828ed), and [`crate::supervisor::RestartPolicy`] (6fdd0d9)
/// `TryFrom<&str>` impls carry.
///
/// Chosen over [`std::str::FromStr`] to sidestep both
/// `clippy::should_implement_trait` on the method-named
/// [`WitShape::from_wire`] and the two-axis discipline the paired
/// [`WitShape::classify`] total function keeps on the *raw* WIT
/// identifier axis — the sibling
/// `wit_shape_from_wire_and_classify_partition_the_axis` pin makes this
/// two-axis split load-bearing, and a `FromStr` impl on the census-label
/// axis would obscure which of the two axes a plain
/// `s.parse::<WitShape>()` reaches. `TryFrom<&str>` keeps the trait-
/// idiomatic reverse projection anchored to the same census-label axis
/// [`WitShape::from_wire`] resolves through, leaving the raw
/// [`WitShape::classify`] axis untouched.
///
/// The paired [`WitShape::from_wire`] resolver's accept-set is shared by
/// construction, so any future arm addition (a hypothetical
/// `wasi:sockets/*` transport-layer shape or `oci:*` capability-import
/// carrier the sibling [`wit_shape_matches`] docstring names as a
/// trajectory item) grows the trait-idiomatic axis by construction —
/// one caixa-core edit on [`WitShape::from_wire`] extends both the
/// method-named reverse projection every existing consumer keys off and
/// the trait-idiomatic reverse projection this impl exposes, without a
/// coordinated rewrite across every future `TryFrom<&str>`-bound
/// consumer's arm-set.
///
/// Extends the substrate-wide closed-set-enum trait-idiomatic reverse-
/// projection family ([`crate::CaixaKind`] via 3c83606,
/// [`crate::CaixaDialeto`] via bf33136, [`PlacementStrategy`] via
/// 6fd00cd, [`crate::supervisor::RestartStrategy`] via 5b828ed,
/// [`crate::supervisor::RestartPolicy`] via 6fdd0d9) onto the second
/// M3-mesh-primitive-defining slot enum on the caixa surface — the
/// `:contratos :wit` census-label closed set the caixa-mesh renderer
/// keys off end-to-end for per-edge programs.yaml fan-out.
///
/// Pinned load-bearing by
/// [`tests::wit_shape_try_from_str_routes_through_from_wire_accessor`]
/// (byte-parity pin against [`WitShape::from_wire`] across the four-arm
/// accept-set),
/// [`tests::wit_shape_try_from_str_rejects_unknown_byte_strings`]
/// (rejection witness against silent accept-set widening), and
/// [`tests::wit_shape_try_from_str_and_from_wire_partition_the_accept_set`]
/// (cross-axis partition pin locking trait and method-named projections
/// to the same `Option<Self>` output on every input).
impl TryFrom<&str> for WitShape {
type Error = ();
fn try_from(s: &str) -> Result<Self, Self::Error> {
Self::from_wire(s).ok_or(())
}
}
/// Standard-library trait-idiomatic forward projection on the
/// [`WitShape`] closed-set typed enum. Routes byte-for-byte through the
/// paired substrate-primitive [`WitShape::as_str`] `pub const fn`
/// accessor so `<&'static str>::from(shape)` / `shape.into::<&'static
/// str>()` reaches the same four-arm `"http"` / `"pubsub"` / `"store"`
/// / `"capability"` census-label emit-set the sibling method-named
/// accessor dispatches through and the sibling
/// [`std::fmt::Display for WitShape`] / [`AsRef<str> for WitShape`]
/// impls also route through.
///
/// Extends the substrate-wide closed-set-enum trait-idiomatic
/// forward-projection family
/// ([`crate::supervisor::RestartStrategy`] via 523157d,
/// [`crate::supervisor::RestartPolicy`] via 9fb37d0,
/// [`crate::CaixaKind`] via edb827b,
/// [`crate::CaixaDialeto`] via c189a6f,
/// [`PlacementStrategy`] via afa3562) onto the second
/// M3-mesh-primitive-defining slot enum on the caixa surface — the
/// `:contratos :wit` census-label closed set the caixa-mesh renderer
/// keys off end-to-end for per-edge programs.yaml fan-out. Pairs with
/// the sibling [`TryFrom<&str> for WitShape`] impl (5472902) to close
/// the two-way `Self ↔ &'static str` round-trip on the trait-idiomatic
/// axis pair, mirroring the pre-existing method-named
/// [`WitShape::as_str`] + [`WitShape::from_wire`] pair on the
/// substrate-primitive axis pair.
///
/// The paired [`WitShape::as_str`] accessor's four-arm emit-set is the
/// single source of truth — every future arm addition (a hypothetical
/// `wasi:sockets/*` transport-layer shape or `oci:*` capability-import
/// carrier the sibling [`wit_shape_matches`] docstring's trajectory
/// bullet names) grows the trait-idiomatic forward axis by
/// construction: one caixa-core edit on [`WitShape::as_str`] extends
/// every one of the sibling forward-projection paths
/// ([`std::fmt::Display`], [`AsRef<str>`], [`WitShape::as_str`]
/// itself, and this [`From<Self> for &'static str`]) without a
/// coordinated rewrite across every future `Into<&'static str>`-bound
/// consumer's arm-set.
///
/// Pinned load-bearing by
/// [`tests::wit_shape_from_into_static_str_routes_through_as_str_accessor`]
/// (byte-parity pin against [`WitShape::as_str`] across the four-arm
/// emit-set, plus a `const`-context materialization witness for the
/// `&'static str` lifetime promise routed through the paired
/// [`WitShape::as_str`] `pub const fn` accessor, plus a paired
/// `.into()` shape assertion covering the blanket-derived
/// `Into<&'static str>` shape) and
/// [`tests::wit_shape_from_into_static_str_and_as_str_partition_the_emit_set`]
/// (partition pin asserting `<&'static str as From<WitShape>>::from`
/// and [`WitShape::as_str`] agree on every arm, plus a two-way direct
/// round-trip witness through the paired trait-idiomatic
/// [`TryFrom<&str>`] axis that closes the two-way `Self ↔ &'static
/// str` round-trip on the trait-idiomatic axis pair — the emit-side
/// [`WitShape::as_str`] and the parse-side [`WitShape::from_wire`]
/// dispatch on the same four inline census-label byte-strings by
/// construction, so round-tripping composes the two trait impls
/// directly).
impl From<WitShape> for &'static str {
fn from(shape: WitShape) -> &'static str {
shape.as_str()
}
}
/// Trait-idiomatic *forward* projection on [`WitShape`] from a *borrowed*
/// input onto the `&'static str` axis — the borrowed-input companion to
/// the paired owned-input [`From<WitShape> for &'static str`] impl
/// immediately above. Routes byte-for-byte through the same substrate-
/// primitive [`WitShape::as_str`] `pub const fn` accessor so every
/// consumer that binds a `&WitShape` through the standard-library
/// `.into()` / [`From<&Self> for &'static str`] axis (a
/// `WitShape::ALL.iter().map(<&'static str>::from).collect::<Vec<_>>()`
/// per-arm accept-set materializer — whose iterator over
/// `&'static [WitShape]` yields `&WitShape`, not `WitShape`, so the
/// owned-input [`From<WitShape>`] axis alone forces every call site through
/// an explicit `.copied()` / dereference / [`Copy`]-bound restatement
/// rather than the direct trait-idiomatic projection; a future generic
/// `<T: Copy + for<'a> Into<&'static str>>`-bound diagnostic column over
/// the substrate-wide closed-set typed-enum family that walks the
/// `iter().map(Into::into)` shape verbatim; the future M4
/// `mesh.pleme.io/v1alpha1/Aplicacao` CR admission-webhook rejection body
/// that composes the accepted-`:contratos :wit` census-label enumeration
/// from an iterated `WitShape::ALL.iter().map(|s| s.into())` pipe rather
/// than a per-arm `match s { … }` cascade; a future
/// `HashMap::<&'static str, WitShape>::from_iter(
/// WitShape::ALL.iter().map(|s| (s.into(), *s)))`-style per-shape
/// reverse-lookup table the sibling [`TryFrom<&str>`] impl cannot compose
/// without this borrowed-input axis in place) reaches the same four-arm
/// `"http"` / `"pubsub"` / `"store"` / `"capability"` census-label
/// emit-set the paired owned-input [`From<WitShape> for &'static str`],
/// the sibling [`std::fmt::Display`], [`AsRef<str>`], and
/// [`WitShape::as_str`] surfaces already return.
///
/// Seventh peer on the substrate-wide trait-idiomatic *borrowed-input*
/// forward-projection family opened on [`crate::dep::DepList`]
/// (64aa742) and extended onto [`crate::CaixaKind`] (5ab993a),
/// [`crate::CaixaDialeto`] (807b0b5), the paired M2 OTP-shape
/// [`crate::supervisor::RestartStrategy`] (e941836) and
/// [`crate::supervisor::RestartPolicy`] (842c7f3), and the first M3
/// mesh-primitive slot enum [`PlacementStrategy`] (4d941d8). Rust's
/// `From` trait does not auto-derive the `From<&Self>` sibling from a
/// `From<Self>` impl (the blanket `impl<T, U> From<&T> for U where T:
/// Copy, U: From<T>` does not exist in `core`), so every closed-set
/// typed enum that carries the owned-input axis but not the borrowed-
/// input axis forces every borrowed-input call site through a
/// `.copied()` / `<&'static str>::from(*shape)` / `shape.as_str()`
/// detour whose type bounds have no compile-time link to the substrate
/// primitive. [`WitShape`] is the *second* M3-mesh-primitive-defining
/// closed-set typed enum to converge onto this borrowed-input campaign
/// — the [`PlacementStrategy`] first-mover (4d941d8) opened the M3-slot
/// arm, and [`WitShape`]'s `:contratos :wit` census-label axis (the
/// caixa-mesh renderer's per-edge programs.yaml fan-out key) closes the
/// next M3 slot ahead of the sibling [`RateLimitUnit`] `:politicas
/// :rate-limit` canonical-suffix axis whose owned-input forward-
/// projection axis (7fdfbf4) awaits the paired borrowed-input closure.
///
/// Same three-path convergence discipline as the paired owned-input
/// impl (this borrowed-input axis, the paired owned-input
/// [`From<WitShape> for &'static str`], and [`WitShape::as_str`] all
/// route through the same four-arm inline census-label byte-strings), so
/// a future variant rename or per-arm serde-attribute drift reaches
/// every one of the six sibling forward-projection paths
/// ([`std::fmt::Display`], [`AsRef<str>`], [`Self::as_str`],
/// [`From<Self> for &'static str`], this [`From<&Self> for &'static
/// str`], and the un-`rename`d [`serde::Serialize`] derive that also
/// emits [`Self::as_str`]'s bytes) through exactly one caixa-core edit.
///
/// The [`WitShape::as_str`] emit and [`WitShape::from_wire`] parse share
/// the same census-label vocabulary by construction — the same four
/// inline census-label byte-strings dispatch on both halves — so the
/// borrowed-input forward axis and the reverse axis compose directly
/// without the intermediate wire-vocab hop the peer [`crate::CaixaKind`]
/// axis pair requires. The round-trip witness pin below locks this
/// direct composition on the M3 slot enum's trait-idiomatic axis pair.
///
/// Pinned load-bearing by
/// [`tests::wit_shape_from_borrowed_into_static_str_routes_through_as_str_accessor`]
/// (byte-parity pin against [`WitShape::as_str`] across the four-arm
/// emit-set via a borrowed input, plus a `const`-context materialization
/// witness for the `&'static str` lifetime promise, plus a blanket
/// `.into()` shape) and
/// [`tests::wit_shape_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
/// (cross-axis partition pin against the paired owned-input
/// [`From<WitShape> for &'static str`] impl, plus a
/// `.iter().map(Into::into)` pipe witness over [`WitShape::ALL`], plus a
/// direct round-trip witness through [`TryFrom<&str>`] that closes the
/// two-way `&Self → &'static str → Self` round-trip on the M3 slot
/// enum's trait-idiomatic axis pair without the wire-vocab intermediate
/// the peer [`crate::CaixaKind`] axis pair requires).
impl From<&WitShape> for &'static str {
fn from(shape: &WitShape) -> &'static str {
shape.as_str()
}
}
/// Trait-idiomatic *forward* projection on the M3 mesh-primitive
/// `:contratos :wit` census-label [`WitShape`] closed-set typed enum from
/// an *owned* input onto the owned-[`String`] axis — routes byte-for-byte
/// through the substrate-primitive [`WitShape::as_str`] `pub const fn`
/// accessor so every consumer that binds a [`WitShape`] through the
/// standard-library `.into()` / [`From<Self> for String`] (equivalently
/// [`Into<String>`]) axis reaches the same four-arm `"http"` / `"pubsub"`
/// / `"store"` / `"capability"` census-label byte-string the paired
/// owned-input [`From<WitShape> for &'static str`] (56998ec), the
/// borrowed-input [`From<&WitShape> for &'static str`] (3187bd0), the
/// sibling [`std::fmt::Display`], [`AsRef<str>`], and [`WitShape::as_str`]
/// surfaces already return.
///
/// Extends the trait-idiomatic *owned-[`String`]* forward-projection
/// family (opened on [`crate::supervisor::RestartStrategy`] — 7baa18a —
/// the first-mover on the M2 OTP-shape sibling-restart-strategy axis,
/// extended onto [`crate::supervisor::RestartPolicy`] — 7851725 — the
/// second-of-two-in-M2 per-child restart-decision axis, then onto
/// [`crate::CaixaKind`] — 231a18c — the structurally most fundamental
/// closed-set fieldless typed enum on the caixa surface, then onto
/// [`crate::CaixaDialeto`] — 88942cd — the dialect-classification axis,
/// then onto [`crate::dep::DepList`] — 32b0ee8 — the two-list dep-graph
/// axis, then onto [`PlacementStrategy`] — 1154c2f — the first M3
/// mesh-primitive-defining slot enum on the caixa surface) onto the
/// seventh peer: the M3 mesh-primitive `:contratos :wit` census-label
/// axis [`WitShape`] carries. Second M3-mesh-primitive-defining closed-set
/// typed enum to converge onto this owned-[`String`] forward-projection
/// campaign — the caixa-mesh renderer's per-edge programs.yaml fan-out
/// keys off this axis end-to-end, so every future consumer that promotes
/// classification output onto an owned-heap-string carrier (the future M4
/// admission-webhook rejection body's accepted-`:contratos :wit`
/// enumeration, a future `HashMap::<String, WitShape>::from_iter(…)`
/// owned-key per-shape lookup) now reaches the substrate-primitive
/// accessor through one uniform trait dispatch.
///
/// Rust's standard library does not carry a blanket
/// `impl<T: AsRef<str>> From<T> for String` (nor an
/// `impl<T: fmt::Display> From<T> for String`), so every closed-set typed
/// enum that carries the paired [`AsRef<str>`] / [`std::fmt::Display`] /
/// [`From<Self> for &'static str`] / [`From<&Self> for &'static str`]
/// quadruple but not the owned-[`String`] axis forces every owned-string
/// call site through a `.to_string()` / `.as_str().to_owned()` /
/// `String::from(shape.as_str())` detour whose type bounds have no
/// compile-time link to the substrate primitive.
///
/// Same as the peer [`crate::supervisor::RestartStrategy`] /
/// [`crate::supervisor::RestartPolicy`] / [`crate::CaixaDialeto`] /
/// [`crate::dep::DepList`] / [`PlacementStrategy`] owned-[`String`] axis
/// pairs (whose forward emit and reverse parse share one vocabulary by
/// construction), [`WitShape`]'s [`WitShape::as_str`] emit and
/// [`WitShape::from_wire`] parse resolve through the same four inline
/// census-label byte-strings by construction (there is no wire/diagnostic
/// axis split on this enum), so the owned-[`String`] forward projection
/// this impl exposes composes directly with the paired trait-idiomatic
/// reverse [`TryFrom<&str>`] axis on the owned-[`String`]'s
/// [`String::as_str`] borrow — no intermediate wire-vocab hop like the
/// peer [`crate::CaixaKind`] axis pair requires.
///
/// The remaining eight closed-set typed enums on the caixa substrate
/// surface (`RateLimitUnit`, `PathShapeViolation`, `InvariantKind`,
/// `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`, `FerriteRuntime`)
/// are the future targets of this campaign — each carries the same paired
/// [`AsRef<str>`] / [`std::fmt::Display`] / [`From<Self> for &'static
/// str`] / [`From<&Self> for &'static str`] quadruple that this
/// owned-[`String`] axis extends onto.
///
/// Pinned load-bearing by
/// [`tests::wit_shape_from_into_owned_string_routes_through_as_str_accessor`]
/// (byte-parity pin against [`WitShape::as_str`] across the four-arm
/// [`WitShape::ALL`] emit-set plus a blanket `.into::<String>()` shape
/// witness) and
/// [`tests::wit_shape_from_into_owned_string_and_static_str_agree_on_every_arm`]
/// (cross-axis partition against the sibling owned-`&'static str` axis
/// and the [`ToString::to_string`] surface, a
/// `.iter().copied().map(String::from)` pipe witness over
/// [`WitShape::ALL`], plus a direct `Self → String → Self` round-trip via
/// [`TryFrom<&str>`] on the owned-[`String`]'s [`String::as_str`] borrow
/// — composes directly without the wire-vocab intermediate hop the peer
/// [`crate::CaixaKind`] axis pair requires).
impl From<WitShape> for String {
fn from(shape: WitShape) -> String {
shape.as_str().to_owned()
}
}
/// Trait-idiomatic *borrowed-input, owned-`String` output* forward
/// projection on the M3 mesh-primitive `:contratos :wit` census-label
/// [`WitShape`] closed-set typed enum — the fourth (and closing) corner
/// of the `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
/// projection family on this second M3-mesh-primitive-defining slot
/// enum. Routes byte-for-byte through the substrate-primitive
/// [`WitShape::as_str`] `pub const fn` accessor (via
/// [`str::to_owned`]) so every consumer that holds a borrowed
/// [`&WitShape`] and needs an owned [`String`] — a future
/// `serde_json::Value::String(String::from(&shape))` structured-payload
/// composer over a borrowed field, a future `Iterator::map` over
/// `&[WitShape]` that projects to owned keys through
/// `.iter().map(String::from)` (whose iterator yields `&WitShape`, not
/// `WitShape`, so the owned-input [`From<WitShape> for String`] axis
/// alone forces every call site through an explicit `.copied()` /
/// spurious [`Copy`] deref restatement rather than the direct
/// trait-idiomatic projection), a future
/// `HashMap::<String, WitShape>::from_iter` that keys off a borrowed-
/// iteration axis where dereferencing the shape would force an
/// unnecessary [`Copy`] at every step, the future M4
/// `mesh.pleme.io/v1alpha1/Aplicacao` CR admission-webhook rejection
/// body composer that names the accepted-`:contratos :wit` census-label
/// enumeration through an iterated
/// `WitShape::ALL.iter().map(String::from).collect()` pipe rather than
/// a per-arm cascade, the future caixa-mesh renderer
/// `contratos.wit`-column diagnostic composer whose borrowed-iteration
/// axis over declared shapes projects to owned keys by construction —
/// reaches the same four-arm `"http"` / `"pubsub"` / `"store"` /
/// `"capability"` census-label byte-string the paired
/// [`std::fmt::Display`], [`AsRef<str>`], [`WitShape::as_str`], and the
/// three other trait-idiomatic forward-projection impls
/// ([`From<WitShape> for &'static str`],
/// [`From<&WitShape> for &'static str`],
/// [`From<WitShape> for String`]) already return.
///
/// Seventh peer on the substrate-wide trait-idiomatic *borrowed-input,
/// owned-`String` output* forward-projection family opened on
/// [`crate::supervisor::RestartStrategy`] (579385f), closed on the M2
/// OTP-shape sibling axis pair by
/// [`crate::supervisor::RestartPolicy`] (8465740), extended onto the
/// two-list dep-graph peer by [`crate::dep::DepList`] (e0cb617), onto
/// the top-level [`crate::CaixaKind`] peer by (e76436d), onto the
/// dialect-classification peer by [`crate::CaixaDialeto`] (d3c0d1d),
/// and onto the first M3 mesh-slot peer by [`PlacementStrategy`]
/// (d3dc000) — extends the `{Self, &Self} × {&'static str, String}`
/// 2×2 projection corner off the first M3 slot enum onto the second M3
/// slot enum, keeping the M3 mesh-primitive triple's completion sweep
/// in lockstep with the M2 OTP-shape sibling pair's earlier closure.
/// Second M3-mesh-primitive-defining closed-set typed enum to reach the
/// 2×2-completion corner — the [`PlacementStrategy`] first-mover
/// (d3dc000) closed the `:placement :estrategia` distribution-strategy
/// axis, and [`WitShape`]'s `:contratos :wit` census-label axis (the
/// caixa-mesh renderer's per-edge programs.yaml fan-out key) closes the
/// next M3 slot ahead of the sibling [`RateLimitUnit`] `:politicas
/// :rate-limit` canonical-suffix axis whose 2×2-completion corner
/// remains a future target of this campaign.
///
/// Rust's standard library does not carry a blanket
/// `impl<T: AsRef<str>> From<&T> for String` (nor an
/// `impl<T: fmt::Display> From<&T> for String`), so every closed-set
/// typed enum that carries the paired [`AsRef<str>`] /
/// [`std::fmt::Display`] / [`From<Self> for &'static str`] /
/// [`From<&Self> for &'static str`] / [`From<Self> for String`]
/// quintuple but not the borrowed-input owned-[`String`] axis forces
/// every borrowed-input owned-string call site through a
/// `shape.as_str().to_owned()` / `String::from(*shape)` (with a
/// spurious [`Copy`]) / `shape.to_string()` (through
/// [`std::fmt::Display`]) detour whose type bounds have no compile-time
/// link to the substrate primitive.
///
/// Same three-path convergence discipline as the paired owned-input
/// impl (this borrowed-input axis, the paired owned-input
/// [`From<WitShape> for String`], and [`WitShape::as_str`] all route
/// through the same four-arm inline census-label byte-strings), so a
/// future variant rename or per-arm serde-attribute drift reaches every
/// one of the paired forward-projection paths through exactly one
/// caixa-core edit.
///
/// Same as the peer [`crate::supervisor::RestartStrategy`] /
/// [`crate::supervisor::RestartPolicy`] / [`crate::dep::DepList`] /
/// [`crate::CaixaDialeto`] / [`PlacementStrategy`] borrowed-input
/// owned-[`String`] axis pairs (whose forward emit and reverse parse
/// share one vocabulary by construction) and unlike the peer
/// [`crate::CaixaKind`] pair (whose forward emit lands on the lowercase
/// Portuguese diagnostic vocabulary while the reverse parse lands on
/// the `PascalCase` wire vocabulary, forcing the round-trip through an
/// intermediate [`crate::CaixaKind::wire_name`] hop), [`WitShape`]'s
/// [`WitShape::as_str`] emit and [`WitShape::from_wire`] parse resolve
/// through the same four inline census-label byte-strings by
/// construction (there is no wire/diagnostic axis split on this M3 slot
/// enum — both halves of the round-trip route through the same four
/// `pub const &str` values), so the borrowed-input owned-[`String`]
/// projection this impl exposes composes directly with the paired
/// trait-idiomatic reverse [`TryFrom<&str>`] axis on the
/// owned-[`String`]'s [`String::as_str`] borrow — no intermediate
/// wire-vocab hop required.
///
/// The remaining seven closed-set typed enums on the caixa substrate
/// surface (`RateLimitUnit`, `PathShapeViolation`, `InvariantKind`,
/// `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`, `FerriteRuntime`)
/// are the future targets of this 2×2-completion campaign — each
/// carries the same paired quintuple that this borrowed-input
/// owned-[`String`] axis extends onto.
///
/// Pinned load-bearing by
/// [`tests::wit_shape_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
/// (byte-parity pin against [`WitShape::as_str`] across the four-arm
/// emit-set through the borrowed-input surface) and
/// [`tests::wit_shape_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
/// (cross-axis partition pin against the paired owned-input owned-
/// [`String`] [`From<WitShape> for String`] impl, the paired
/// borrowed-input owned-[`&'static str`]
/// [`From<&WitShape> for &'static str`] impl, the paired owned-input
/// owned-[`&'static str`] [`From<WitShape> for &'static str`] impl, and
/// the sibling [`ToString::to_string`] surface routed through
/// [`std::fmt::Display`], plus a `.iter().map(String::from)` pipe
/// witness over [`WitShape::ALL`] (whose iterator yields `&WitShape` by
/// construction, so the borrowed-input owned-[`String`] axis is what
/// routes the pipe through the substrate-primitive
/// [`WitShape::as_str`] accessor without a spurious [`Copy`] deref),
/// plus a direct round-trip witness through [`TryFrom<&str>`] on the
/// owned-[`String`]'s [`String::as_str`] borrow that closes the two-way
/// `&Self → String → Self` round-trip on the trait-idiomatic
/// borrowed-input owned-[`String`] forward + reverse axis pair — no
/// intermediate wire-vocab hop like the peer [`crate::CaixaKind`] axis
/// pair requires).
impl From<&WitShape> for String {
fn from(shape: &WitShape) -> String {
shape.as_str().to_owned()
}
}
/// Trait-idiomatic *forward* projection on the M3 mesh-primitive
/// `:contratos :wit` census-label [`WitShape`] closed-set typed enum
/// from an *owned* input onto the [`std::borrow::Cow<'static, str>`]
/// axis — routes byte-for-byte through the substrate-primitive
/// [`WitShape::as_str`] `pub const fn` accessor (via
/// [`std::borrow::Cow::Borrowed`]) so every consumer that binds a
/// [`WitShape`] through the standard-library `.into()` /
/// [`From<Self> for std::borrow::Cow<'static, str>`] (equivalently
/// [`Into<std::borrow::Cow<'static, str>>`]) axis reaches the same
/// four-arm `"http"` / `"pubsub"` / `"store"` / `"capability"`
/// census-label byte-string the paired
/// [`From<WitShape> for &'static str`],
/// [`From<&WitShape> for &'static str`],
/// [`From<WitShape> for String`], and
/// [`From<&WitShape> for String`] 2×2 trait-idiomatic
/// forward-projection corners, the sibling [`std::fmt::Display`],
/// [`AsRef<str>`], and [`WitShape::as_str`] surfaces already return,
/// rather than an open-coded per-call-site
/// `std::borrow::Cow::Borrowed(shape.as_str())` /
/// `std::borrow::Cow::Owned(shape.to_string())` composition whose
/// type bounds have no compile-time link back to the substrate
/// primitive.
///
/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
/// [`std::borrow::Cow::Owned`] — the substrate-primitive
/// [`WitShape::as_str`] accessor's return carries the `&'static str`
/// lifetime by construction (each `match` arm resolves to an inline
/// `"http"` / `"pubsub"` / `"store"` / `"capability"` census-label
/// byte-string literal with static lifetime), so the zero-alloc
/// borrowed arm is the type-correct projection with no runtime
/// allocation. The paired [`std::borrow::Cow::Owned`] arm stays
/// reachable at the call site through the existing
/// [`From<WitShape> for String`] axis composed with
/// [`std::borrow::Cow::from`] on the resulting owned [`String`] —
/// a caller who chose to mutate the projection lands on the owned
/// arm by their own composition, not by the substrate-primitive
/// projection silently allocating on their behalf.
///
/// Rust's standard library carries no blanket `impl<T: AsRef<str>>
/// From<T> for Cow<'static, str>` (nor an `impl<T: fmt::Display>
/// From<T> for Cow<'static, str>`), so the paired sibling
/// [`From<WitShape> for &'static str`],
/// [`From<WitShape> for String`], [`AsRef<str>`], and
/// [`std::fmt::Display`] surfaces do not implicitly extend to a
/// [`Cow<'static, str>`]-bound call site — every such site is forced
/// through a `Cow::Borrowed(shape.as_str())` /
/// `Cow::Owned(shape.to_string())` open-code whose type bounds have
/// no compile-time link back to the substrate primitive until this
/// lift.
///
/// First-mover on the *M3 mesh-shape tier* of the substrate-wide
/// trait-idiomatic [`std::borrow::Cow<'static, str>`] forward-
/// projection campaign — the [`crate::CaixaKind`] first-mover (99c1735 owned-
/// input + d45c409 borrowed-input) opened the axis on the
/// structurally most fundamental closed-set fieldless typed enum;
/// the paired M2 OTP-shape [`crate::supervisor::RestartStrategy`]
/// (7dd28b3 owned-input + 9b3e4b3 borrowed-input) and
/// [`crate::supervisor::RestartPolicy`] (0612398 owned-input +
/// ee577fd borrowed-input) extended it onto the two M2 OTP-shape
/// sibling peers, closing the whole M2 OTP-shape tier. [`WitShape`]
/// is the *first* M3-mesh-primitive-defining closed-set fieldless
/// typed enum to converge onto this campaign — the caixa-mesh
/// renderer's per-edge programs.yaml fan-out and the
/// [`WitContract`] shape-dispatch surface both key off this axis
/// end-to-end, so every future consumer that binds through a
/// [`Cow<'static, str>`] boundary and holds a [`WitShape`] by value
/// reaches the substrate-primitive accessor through one uniform
/// trait dispatch. The remaining ten peers (`RestartStrategy` and
/// `RestartPolicy` closed on the M2 tier;
/// [`PlacementStrategy`], [`RateLimitUnit`],
/// [`crate::dep::DepList`], [`crate::CaixaDialeto`],
/// [`crate::render::PathShapeViolation`], and the outside-`caixa-core`
/// peers `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`,
/// `Semantic`, `FerriteRuntime`) are the remaining future targets
/// of this campaign.
///
/// Pinned load-bearing by
/// [`tests::wit_shape_from_into_static_cow_str_routes_through_as_str_accessor`]
/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
/// against [`WitShape::as_str`] across the four-arm
/// [`WitShape::ALL`]) and
/// [`tests::wit_shape_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
/// (cross-axis partition pin against the paired
/// [`From<WitShape> for &'static str`],
/// [`From<WitShape> for String`], and
/// [`ToString`]-through-[`std::fmt::Display`] axes, plus a
/// `.iter().copied().map(Cow::from)` pipe witness over
/// [`WitShape::ALL`] that materializes the four-arm accept-set
/// through the [`Cow<'static, str>`] axis alone and pins the
/// zero-alloc discipline on every element).
impl From<WitShape> for std::borrow::Cow<'static, str> {
fn from(shape: WitShape) -> std::borrow::Cow<'static, str> {
std::borrow::Cow::Borrowed(shape.as_str())
}
}
/// Trait-idiomatic *borrowed-input, [`std::borrow::Cow<'static, str>`]
/// output* forward projection on the M3-mesh-primitive-defining
/// `:contratos :wit` census-label [`WitShape`] closed-set typed enum —
/// the borrowed-input companion to the paired owned-input
/// [`From<WitShape> for std::borrow::Cow<'static, str>`] impl
/// immediately above (8634dec). Routes byte-for-byte through the same
/// substrate-primitive [`WitShape::as_str`] `pub const fn` accessor
/// (via [`std::borrow::Cow::Borrowed`]) so every consumer that holds
/// a `&WitShape` and needs a [`std::borrow::Cow<'static, str>`] — a
/// `WitShape::ALL.iter().map(std::borrow::Cow::from).collect::<Vec<_>>()`
/// per-arm accept-set materializer whose iterator over
/// `&'static [WitShape]` yields `&WitShape` (not `WitShape`, so the
/// paired owned-input [`From<WitShape> for std::borrow::Cow<'static, str>`]
/// axis alone forces every call site through an explicit `.copied()` /
/// dereference / [`Copy`]-bound restatement rather than the direct
/// trait-idiomatic projection), a future generic
/// `<T: for<'a> Into<std::borrow::Cow<'static, str>>>`-bound emitter
/// on a per-`:contratos :wit` diagnostic column that walks the
/// `iter().map(Into::into)` shape verbatim, the future M4
/// `mesh.pleme.io/v1alpha1/Aplicacao` CR admission-webhook rejection
/// body that composes the accepted-`:contratos :wit` census-label
/// enumeration from an iterated
/// `WitShape::ALL.iter().map(|s| s.into())` pipe rather than a per-arm
/// `match s { … }` cascade — reaches the same four-arm inline
/// `"http"` / `"pubsub"` / `"store"` / `"capability"` census-label
/// byte-string the paired [`std::fmt::Display`], [`AsRef<str>`],
/// [`WitShape::as_str`], the four
/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
/// forward-projection corners, and the paired owned-input
/// [`From<WitShape> for std::borrow::Cow<'static, str>`] impl already
/// return.
///
/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
/// [`std::borrow::Cow::Owned`] — the substrate-primitive
/// [`WitShape::as_str`] accessor's return carries the `&'static str`
/// lifetime by construction (each `match` arm resolves to an inline
/// `"http"` / `"pubsub"` / `"store"` / `"capability"` census-label
/// byte-string literal with static lifetime), so the zero-alloc
/// borrowed arm is the type-correct projection with no runtime
/// allocation on the borrowed-input surface just as on the paired
/// owned-input surface.
///
/// Closes the `{Self, &Self}` input-shape corner on the M3-mesh-shape
/// `:contratos :wit` census-label [`std::borrow::Cow<'static, str>`]
/// axis opened one commit prior (8634dec) on the paired owned-input
/// [`From<WitShape> for std::borrow::Cow<'static, str>`] impl —
/// first-of-`{PlacementStrategy, RateLimitUnit}`-plus-`WitShape` on
/// the M3-mesh-primitive-defining closed-set fieldless typed enum
/// tier of the campaign, exactly as d45c409 closed it on the
/// top-level [`crate::CaixaKind`] one commit after the owning half
/// (99c1735) landed and as 9b3e4b3 / ee577fd closed it on the M2
/// OTP-shape [`crate::supervisor::RestartStrategy`] /
/// [`crate::supervisor::RestartPolicy`] sibling peers one commit
/// after their owning halves (7dd28b3 / 0612398) landed. Rust's
/// standard library does not carry a blanket
/// `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor an
/// `impl<T: fmt::Display> From<&T> for Cow<'static, str>`), so every
/// closed-set fieldless typed enum peer on the substrate that carries
/// the paired owned-input [`Cow<'static, str>`] axis but not the
/// borrowed-input axis forces every borrowed-input
/// [`Cow<'static, str>`]-parameterized call site through a spurious
/// [`Copy`] deref (`std::borrow::Cow::from(*shape)`) or a
/// `std::borrow::Cow::Borrowed(shape.as_str())` open-code whose type
/// bounds have no compile-time link to the substrate primitive.
///
/// The remaining M3-mesh-primitive-defining peers
/// ([`PlacementStrategy`], [`RateLimitUnit`]) and the outside-M3
/// substrate-wide peers ([`crate::dep::DepList`],
/// [`crate::CaixaDialeto`], [`crate::render::PathShapeViolation`],
/// and the outside-`caixa-core` peers `InvariantKind`, `ArchVerdict`,
/// `Severity`, `FixSafety`, `Semantic`, `FerriteRuntime`) are the
/// remaining future targets of the campaign.
///
/// Pinned load-bearing by
/// [`tests::wit_shape_from_borrowed_into_static_cow_str_routes_through_as_str_accessor`]
/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
/// against [`WitShape::as_str`] across the four-arm
/// [`WitShape::ALL`] through the borrowed-input surface) and
/// [`tests::wit_shape_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
/// (cross-axis partition pin against the paired owned-input
/// [`From<WitShape> for std::borrow::Cow<'static, str>`], the paired
/// borrowed-input owned-`&'static str`
/// [`From<&WitShape> for &'static str`], and the paired
/// borrowed-input owned-`String` [`From<&WitShape> for String`]
/// impls, plus a `.iter().map(std::borrow::Cow::from)` pipe witness
/// over [`WitShape::ALL`] — whose iterator yields `&WitShape` by
/// construction, so the borrowed-input [`Cow<'static, str>`] axis is
/// what routes the pipe through the substrate-primitive
/// [`WitShape::as_str`] accessor with the zero-alloc
/// [`Cow::Borrowed`] arm by construction and without a spurious
/// [`Copy`] deref).
impl From<&WitShape> for std::borrow::Cow<'static, str> {
fn from(shape: &WitShape) -> std::borrow::Cow<'static, str> {
std::borrow::Cow::Borrowed(shape.as_str())
}
}
impl WitContract {
/// Substrate-canonical per-`:contratos` caller-Servico scalar
/// accessor every consumer that reads the edge's source endpoint
/// keys off — returns the author-declared `:contratos :de`
/// byte-string verbatim as a `&str`, borrowed from the typed slot's
/// own [`String`] storage.
///
/// The `:contratos :de` slot names the caller-side member Servico
/// on a typed inter-Servico edge (validated by
/// [`AplicacaoSpec::validate`] to be a [`Membro::caixa`] the
/// Aplicacao declares — a stray `:de` that doesn't name a member is
/// [`AplicacaoError::ContratoMemberMissing`], not a silent
/// caller-attachment miss at cluster-apply time). Peer of the
/// sibling [`WitContract::destination`] accessor on the same
/// per-`:contratos` entry — the pair `( source(), destination() )`
/// jointly names the typed edge every renderer that fans on the
/// caller-callee identity keys off (the
/// [`caixa_mesh::cilium_network_policies`] per-`(:de, :para)`
/// grouping, the [`AplicacaoSpec::detect_sync_cycles`] adjacency
/// map, the per-edge dedup key, the per-edge membership-lookup
/// diagnostic).
///
/// Prior to this lift the `.de` byte-string was accessed inline at
/// four caixa-core sites (the two validate-side membership lookups
/// at `!names.contains(c.de.as_str())`, the per-edge dedup-key
/// tuple's caller-arm at
/// `(c.de.as_str(), c.para.as_str(), c.wit.as_str(), ...)`, the
/// `detect_sync_cycles` adjacency `adj.entry(c.de.as_str())`) and
/// one caixa-mesh site (the per-`(:de, :para)` CNP grouping's
/// caller-arm at `groups.entry((c.de.as_str(), c.para.as_str()))`)
/// — five open-coded `.de.as_str()` field-accesses that expressed
/// no compile-time link back to the typed slot. A future extension
/// of the `:contratos :de` axis to a richer author surface (a
/// multi-caller weighted-fan-in overlay per MESH-COMPOSITION §III.2
/// canary flow, a per-cluster caller-alias table the operator pins
/// through a future `:placement`-scoped slot, the M4
/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
/// admission-webhook that promotes the scalar to a caller-set
/// projection) would have had to be threaded through every
/// open-coded copy in lockstep or one consumer would silently
/// disagree with the peers on which caller Servico a given edge
/// resolves to. Lifting the resolution rule to a typed method on
/// the substrate primitive means every downstream caller-facing
/// consumer reaches for one typed dispatch — the resolver's
/// accept-set migrates as a unit on any future axis addition.
///
/// Peer of the sibling per-`:entrada` [`Entrada::destination`]
/// (6db982c) accessor on the analogous per-ingress-Servico scalar
/// axis — same "one typed dispatch on the substrate primitive,
/// thin projections at each consumer" discipline extended onto the
/// per-`:contratos` caller-Servico byte-string axis.
///
/// Declared `pub const fn` — the body composes exclusively through
/// the `pub const fn` [`String::as_str`] projection (const-stable
/// since Rust 1.87, well within the workspace MSRV), so every
/// downstream `const`-context consumer of the per-`:contratos`
/// caller-Servico byte-string reaches through the same substrate-
/// primitive dispatch at const-eval time as at runtime. Peer of
/// the sibling `pub const fn` [`Self::destination`] /
/// [`Self::world_ref`] scalar accessors on the same
/// per-`:contratos` byte-string trio (the family closure the
/// [`wit_contract_pre_projection_accessor_family_is_const_fn`] pin
/// locks load-bearing), and mirror on the method-surface of the
/// sibling free-function [`wit_shape_matches`] +
/// [`wit_shape_is_http`] / [`wit_shape_is_pubsub`] /
/// [`wit_shape_is_store`] / [`wit_shape_is_capability`] `const`-
/// eval-surface pass (d46420c) on the raw `&str → bool` WIT-shape
/// dispatch family.
#[must_use]
pub const fn source(&self) -> &str {
self.de.as_str()
}
/// Substrate-canonical per-`:contratos` callee-Servico scalar
/// accessor every consumer that reads the edge's destination
/// endpoint keys off — returns the author-declared
/// `:contratos :para` byte-string verbatim as a `&str`, borrowed
/// from the typed slot's own [`String`] storage.
///
/// The `:contratos :para` slot names the callee-side member Servico
/// on a typed inter-Servico edge (validated by
/// [`AplicacaoSpec::validate`] to be a [`Membro::caixa`] the
/// Aplicacao declares — a stray `:para` that doesn't name a member
/// is [`AplicacaoError::ContratoMemberMissing`], not a silent
/// callee-attachment miss at cluster-apply time). Callee-side twin
/// of the sibling [`WitContract::source`] accessor — the pair
/// jointly names the typed edge every renderer that fans on the
/// caller-callee identity keys off, and this accessor is also the
/// per-`(:de, :para)` L4 port resolver's canonical destination arg:
/// under today's typed surface [`AplicacaoSpec::port_for_destination`]
/// composes with `destination()` at every emit site that projects a
/// per-edge destination Servico's L4 listener port.
///
/// Prior to this lift the `.para` byte-string was accessed inline
/// at five sites — four caixa-core (the validate-side membership
/// lookup at `!names.contains(c.para.as_str())`, the per-edge
/// dedup-key tuple's callee-arm, the `detect_sync_cycles`
/// adjacency `.insert(c.para.as_str())`, the CNP grouping's
/// callee-arm) and one caixa-mesh (the per-`(:de, :para)` CNP L4
/// port resolver's destination arg `spec.port_for_destination(&c.para)`)
/// — with no compile-time link back to the typed slot. A future
/// extension of the `:contratos :para` axis to a richer author
/// surface (a multi-callee weighted-fan-out overlay for canary /
/// blue-green routing on typed edges, a per-cluster callee-alias
/// table the operator pins through a future `:placement`-scoped
/// slot, the M4 CR materializer's per-CR admission-webhook that
/// promotes the scalar to a callee-set projection) would have had
/// to be threaded through every open-coded copy in lockstep or one
/// consumer would silently disagree on which callee Servico a given
/// edge resolves to (a per-CNP `endpointSelector` that names a
/// different destination than its L4 port resolver reads for, a
/// dedup-key that treats `(cart, catalog-v2)` and `(cart, catalog)`
/// as distinct while the adjacency map collapses them, or vice
/// versa). Lifting to a typed method on the substrate primitive
/// means every downstream callee-facing consumer reaches for one
/// typed dispatch.
///
/// Peer of the sibling per-`:entrada` [`Entrada::destination`]
/// (6db982c) accessor — both name the "destination-Servico
/// byte-string" concept on their respective mesh-slot atoms (per-
/// ingress apex vs. per-typed-edge callee), and both extend the
/// substrate-primitive-owns-the-resolver discipline onto the
/// per-slot destination-Servico scalar axis. Composes with
/// [`AplicacaoSpec::port_for_destination`] (9ca4896) at every
/// emit-side per-edge L4 port reader — the composition
/// `spec.port_for_destination(c.destination())` pins the CNP per-
/// `(:de, :para)` L4 port axis to the same typed dispatch the peer
/// `HTTPRoute` `backendRefs[0].port` axis reaches through with
/// `spec.port_for_destination(entrada.destination())`.
///
/// Declared `pub const fn` — sibling in `const`-eval posture to the
/// peer `pub const fn` [`Self::source`] / [`Self::world_ref`]
/// per-`:contratos` byte-string scalar accessors, all three
/// projecting through the `pub const fn` [`String::as_str`]
/// (const-stable since Rust 1.87). See [`Self::source`] for the
/// family-closure rationale.
#[must_use]
pub const fn destination(&self) -> &str {
self.para.as_str()
}
/// Substrate-canonical per-`:contratos` WIT-world-reference scalar
/// accessor every consumer that reads the edge's WIT world
/// discriminator keys off — returns the author-declared
/// `:contratos :wit` byte-string verbatim as a `&str`, borrowed from
/// the typed slot's own [`String`] storage.
///
/// The `:contratos :wit` slot names the WIT world the typed edge
/// carries (e.g. `"wasi:http/proxy"`, `"nats:pub-sub"`,
/// `"wasi:keyvalue/store"`); validated by [`WitContract::target`] to
/// be a well-shaped WIT world reference via
/// [`crate::render::is_wit_world_ref`] and by
/// [`AplicacaoSpec::validate`] to be non-empty via the narrower
/// [`AplicacaoError::EmptyWit`] variant. Peer of the sibling
/// [`WitContract::source`] / [`WitContract::destination`] accessors
/// on the same per-`:contratos` entry — the triple
/// `( source(), destination(), world_ref() )` jointly names the
/// typed edge every renderer that fans on the caller-callee-shape
/// identity keys off (the per-edge dedup key at
/// [`AplicacaoSpec::validate`]'s duplicate-`:contratos` gate, the
/// per-`(:de, :para)` CNP grouping's shape-arm classifier at
/// [`caixa_mesh::cilium_network_policies`], the
/// [`WitContract::is_http`] / [`is_pubsub`][WitContract::is_pubsub]
/// / [`is_store`][WitContract::is_store] shape-dispatch predicates,
/// the [`feira app graph`][fag] per-edge printer's WIT-shape label).
///
/// Prior to this lift the `.wit` byte-string was accessed inline at
/// five sites — three caixa-core (the `WitContract::is_*` shape-
/// dispatch predicates' `&self.wit` arg, the validate-side empty
/// check at `if c.wit.is_empty()`, the per-edge dedup-key tuple's
/// shape arm at `c.wit.as_str()`) and one caixa-feira (the app-graph
/// printer's `{}` format-slot at `c.wit`) — five open-coded
/// `.wit` field-accesses that expressed no compile-time link back to
/// the typed slot. A future extension of the `:contratos :wit` axis
/// to a richer author surface (an M4 promotion from `String` to a
/// typed WIT-world enum once the WIT registry stabilizes in tatara-
/// lisp per this struct's own `:wit` field docstring, a per-cluster
/// WIT-alias table the operator pins through a future
/// `:placement`-scoped slot, a canonicalization pass that lowercases
/// `wasi:*` prefixes) would have had to be threaded through every
/// open-coded copy in lockstep or one consumer would silently
/// disagree with the peers on which WIT shape a given edge resolves
/// to (a per-CNP L7 emission that read `wasi:http/proxy` while the
/// dedup key read the pre-canonicalized `WASI:HTTP/proxy`, an
/// empty-check that missed a whitespace-only string a peer accessor
/// stripped, or vice versa). Lifting to a typed method on the
/// substrate primitive means every downstream WIT-shape-facing
/// consumer reaches for one typed dispatch — the resolver's
/// accept-set migrates as a unit on any future axis addition.
///
/// Sibling of the peer per-`:contratos` [`WitContract::source`] /
/// [`WitContract::destination`] (7f0fd43), per-`:entrada`
/// [`Entrada::hostname`] / [`Entrada::destination`] (11f3dfe /
/// 6db982c), per-`:membros` [`Membro::nome`] /
/// [`Membro::versao_requirement`] (4a32abf / a40b0e3) accessors on
/// the mesh-slot-atom scalar-value axes — same "one typed dispatch
/// on the substrate primitive, thin projections at each consumer"
/// discipline extended onto the last unlifted per-`:contratos`
/// scalar (the WIT-world-reference arm).
///
/// [fag]: caixa-feira/src/cmd/app.rs
///
/// Declared `pub const fn` — sibling in `const`-eval posture to the
/// peer `pub const fn` [`Self::source`] / [`Self::destination`]
/// per-`:contratos` byte-string scalar accessors on the trio, and
/// the load-bearing enabler for the paired `pub const fn`
/// [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`] /
/// [`Self::is_capability`] WIT-shape-predicate family (each
/// composes as `wit_shape_is_<arm>(self.world_ref())` and inherits
/// the `const`-eval posture by construction once this accessor
/// carries it). See [`Self::source`] for the family-closure
/// rationale and the paired
/// [`wit_contract_pre_projection_accessor_family_is_const_fn`] pin
/// for the load-bearing witness.
#[must_use]
pub const fn world_ref(&self) -> &str {
self.wit.as_str()
}
/// Substrate-canonical per-`:contratos` `:endpoint` HTTP-shaped
/// payload-target scalar accessor every consumer that reads the
/// edge's L7 HTTP request path payload keys off — returns the
/// author-declared `:contratos :endpoint` byte-string verbatim as
/// an `Option<&str>`, borrowed from the typed slot's own
/// `Option<String>` storage; `None` when the slot is absent (the
/// canonical shape of a non-HTTP-`:wit`-world edge — pub-sub
/// `nats:*`/`kafka:*` carries `:subject` instead, key/value
/// `wasi:keyvalue/*`/`kv:*` carries `:slot` instead, and a plain
/// [`WitTarget::Capability`] edge carries none of the three).
///
/// The `:contratos :endpoint` slot carries the HTTP request path
/// payload (Cilium L7 `path:` + Gateway API v1 `PathPrefix` grammar
/// — same shape required of `:entrada :paths`, gated by the shared
/// [`crate::render::is_gateway_api_http_path`] predicate) that
/// [`WitContract::target`] projects onto the [`WitTarget::Http`]
/// arm's `endpoint: &'a str` payload when the edge's `:wit` world
/// matches the [`WIT_HTTP_SHAPE_PREFIXES`] accept-set. Every
/// downstream consumer that reads the payload keys off this scalar
/// (the [`WitContract::target`] Http-arm payload extraction that
/// materializes [`WitTarget::Http { endpoint }`] under the paired
/// [`WitTarget::HTTP_FIELD_NAME`] label, the
/// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
/// key's endpoint arm that pins the payload as part of the six-tuple
/// dedup key alongside the sibling `:subject`/`:slot` arms, the
/// future M4 per-edge WIT registry resolver's HTTP-arm materializer,
/// the future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
/// per-edge L7 admission webhook, the future caixa-mesh L7 CNP
/// emission path that lands the payload verbatim as a Cilium L7
/// `path:` rule).
///
/// Prior to this lift the `.endpoint` field was accessed inline at
/// two production sites in `caixa-core/src/aplicacao.rs` — the
/// [`WitContract::target`] payload-shape dispatch's `let endpoint =
/// self.endpoint.as_deref();` binding at the top of the method, and
/// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
/// tuple's `c.endpoint.as_deref()` HTTP-arm slot — two open-coded
/// field-accesses that expressed no compile-time link back to the
/// typed slot. A future extension of the `:contratos :endpoint`
/// axis to a richer author surface (an M4 promotion from
/// `Option<String>` to a typed HTTP path-template enum once the
/// WIT registry stabilizes path-parameter shapes in tatara-lisp per
/// this struct's own `:wit` field docstring, a per-cluster endpoint-
/// alias table the operator pins through a future `:placement`-
/// scoped slot, a canonicalization pass that percent-encodes non-
/// ASCII path segments, a per-CR fully-qualified rewrite the M4 CR
/// materializer applies per-tenant) would have had to be threaded
/// through both open-coded copies in lockstep or the two consumers
/// would silently disagree on which HTTP path a given edge resolves
/// to — the [`WitContract::target`] payload-extraction reading
/// `"/lookup"` while the [`AplicacaoSpec::validate`] dedup key read
/// the operator-resolved `"/tenant-a/lookup"` would silently split
/// the [`WitTarget::Http`]-arm rendered payload from the actual
/// dedup-key uniqueness axis, a two-consumer split at the validator
/// far from the source `caixa.lisp` with no field naming the
/// payload-drift root cause. Lifting the resolution rule to a typed
/// method on the substrate primitive means every downstream
/// HTTP-payload-facing consumer of the Aplicacao's per-`:contratos`
/// L7-payload surface reaches for exactly one typed dispatch — the
/// resolver's accept-set migrates as a unit on any future axis
/// addition.
///
/// Peer of the sibling per-`:placement` [`Placement::shard_key`]
/// (7cd2a28) / [`Placement::affinity`] (74ec2d3) `Option<&str>`
/// accessors on the M3 mesh-slot family — same "one typed dispatch
/// on the substrate primitive, thin projections at each consumer"
/// discipline extended onto the per-`:contratos` HTTP-shaped
/// payload-carrier `Option<String>` optional-scalar axis. First
/// `Option<&str>`-return accessor on the per-`:contratos` mesh-slot
/// atom — opens the "optional per-slot payload-carrier scalar"
/// projection pattern the sibling per-`:contratos` `:subject` /
/// `:slot` future lifts fold on, matching the closed
/// per-`:contratos` scalar-value accessor family
/// ([`WitContract::source`] / [`WitContract::destination`] /
/// [`WitContract::world_ref`]) already lifted onto the mandatory-
/// scalar `String` axes. Named `endpoint()` to match the storage
/// field's name and the paired [`WitTarget::HTTP_FIELD_NAME`]
/// author-facing label const; the accessor's identity name maps
/// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
/// docstring already carries.
#[must_use]
pub const fn endpoint(&self) -> Option<&str> {
match &self.endpoint {
Some(s) => Some(s.as_str()),
None => None,
}
}
/// Substrate-canonical per-`:contratos` `:subject` pub-sub-shaped
/// payload-target scalar accessor every consumer that reads the
/// edge's NATS / Kafka publish subject payload keys off — returns
/// the author-declared `:contratos :subject` byte-string verbatim
/// as an `Option<&str>`, borrowed from the typed slot's own
/// `Option<String>` storage; `None` when the slot is absent (the
/// canonical shape of a non-pub-sub-`:wit`-world edge — HTTP
/// `wasi:http/*`/`http:*` carries `:endpoint` instead, key/value
/// `wasi:keyvalue/*`/`kv:*` carries `:slot` instead, and a plain
/// [`WitTarget::Capability`] edge carries none of the three).
///
/// The `:contratos :subject` slot carries the NATS / Kafka publish
/// subject payload (the [`WIT_PUBSUB_SHAPE_PREFIXES`] dispatch arm's
/// per-edge target selector — `orders.paid`, `events.>`, whatever
/// subject namespace the author names on the pub-sub edge) that
/// [`WitContract::target`] projects onto the [`WitTarget::PubSub`]
/// arm's `subject: &'a str` payload when the edge's `:wit` world
/// matches the [`WIT_PUBSUB_SHAPE_PREFIXES`] accept-set. Every
/// downstream consumer that reads the payload keys off this scalar
/// (the [`WitContract::target`] PubSub-arm payload extraction that
/// materializes [`WitTarget::PubSub { subject }`] under the paired
/// [`WitTarget::PUBSUB_FIELD_NAME`] label, the
/// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
/// key's subject arm that pins the payload as part of the six-tuple
/// dedup key alongside the sibling `:endpoint`/`:slot` arms, the
/// future M4 per-edge WIT registry resolver's pub-sub-arm
/// materializer, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
/// materializer's per-edge NATS admission webhook, the future
/// caixa-mesh L4 CNP emission path that lands the payload verbatim
/// as a NATS subject the operator pins per-CR).
///
/// Prior to this lift the `.subject` field was accessed inline at
/// two production sites in `caixa-core/src/aplicacao.rs` — the
/// [`WitContract::target`] payload-shape dispatch's `let subject =
/// self.subject.as_deref();` binding at the top of the method, and
/// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
/// tuple's `c.subject.as_deref()` pub-sub-arm slot — two open-coded
/// field-accesses that expressed no compile-time link back to the
/// typed slot. A future extension of the `:contratos :subject` axis
/// to a richer author surface (an M4 promotion from `Option<String>`
/// to a typed NATS-subject-template enum once the WIT registry
/// stabilizes wildcard / hierarchy shapes in tatara-lisp per this
/// struct's own `:wit` field docstring, a per-cluster subject-alias
/// table the operator pins through a future `:placement`-scoped
/// slot, a canonicalization pass that lowercases / dedupes wildcard
/// segments, a per-CR fully-qualified rewrite the M4 CR materializer
/// applies per-tenant) would have had to be threaded through both
/// open-coded copies in lockstep or the two consumers would silently
/// disagree on which NATS subject a given edge resolves to — the
/// [`WitContract::target`] payload-extraction reading `"orders.paid"`
/// while the [`AplicacaoSpec::validate`] dedup key read the operator-
/// resolved `"tenant-a.orders.paid"` would silently split the
/// [`WitTarget::PubSub`]-arm rendered payload from the actual dedup-
/// key uniqueness axis, a two-consumer split at the validator far
/// from the source `caixa.lisp` with no field naming the payload-
/// drift root cause. Lifting the resolution rule to a typed method
/// on the substrate primitive means every downstream pub-sub-payload-
/// facing consumer of the Aplicacao's per-`:contratos` L4-payload
/// surface reaches for exactly one typed dispatch — the resolver's
/// accept-set migrates as a unit on any future axis addition.
///
/// Peer of the sibling per-`:contratos` [`WitContract::endpoint`]
/// (7020470) `Option<&str>` accessor on the M3 mesh-slot payload-
/// carrier axis — second `Option<&str>`-return accessor on the
/// per-`:contratos` mesh-slot atom, extending the "optional per-slot
/// payload-carrier scalar" projection pattern the [`WitContract::endpoint`]
/// HTTP-arm lift opened onto the pub-sub arm; leaves the [`WitContract::slot`]
/// key/value-store arm as the last unlifted per-`:contratos`
/// `Option<String>` axis. Named `subject()` to match the storage
/// field's name and the paired [`WitTarget::PUBSUB_FIELD_NAME`]
/// author-facing label const; the accessor's identity name maps
/// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
/// docstring already carries.
#[must_use]
pub const fn subject(&self) -> Option<&str> {
match &self.subject {
Some(s) => Some(s.as_str()),
None => None,
}
}
/// Substrate-canonical per-`:contratos` `:slot` key/value-store-
/// shaped payload-target scalar accessor every consumer that reads
/// the edge's `wasi:keyvalue/*` / `kv:*` key-template payload keys
/// off — returns the author-declared `:contratos :slot` byte-string
/// verbatim as an `Option<&str>`, borrowed from the typed slot's
/// own `Option<String>` storage; `None` when the slot is absent
/// (the canonical shape of a non-store-`:wit`-world edge — HTTP
/// `wasi:http/*`/`http:*` carries `:endpoint` instead, pub-sub
/// `nats:*`/`kafka:*` carries `:subject` instead, and a plain
/// [`WitTarget::Capability`] edge carries none of the three).
///
/// The `:contratos :slot` slot carries the key/value store
/// key-template payload (the [`WIT_STORE_SHAPE_PREFIXES`] dispatch
/// arm's per-edge target selector — `carts/{cart_id}`,
/// `sessions/{tenant}/{sid}`, whatever key-template the author
/// names on the store edge) that [`WitContract::target`] projects
/// onto the [`WitTarget::Store`] arm's `slot: &'a str` payload when
/// the edge's `:wit` world matches the [`WIT_STORE_SHAPE_PREFIXES`]
/// accept-set. Every downstream consumer that reads the payload
/// keys off this scalar (the [`WitContract::target`] Store-arm
/// payload extraction that materializes [`WitTarget::Store { slot }`]
/// under the paired [`WitTarget::STORE_FIELD_NAME`] label, the
/// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
/// key's store arm that pins the payload as part of the six-tuple
/// dedup key alongside the sibling `:endpoint`/`:subject` arms,
/// the future M4 per-edge WIT registry resolver's store-arm
/// materializer, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
/// materializer's per-edge key/value admission webhook, the future
/// caixa-mesh L4 CNP emission path that lands the payload verbatim
/// as a key-template the operator pins per-CR).
///
/// Prior to this lift the `.slot` field was accessed inline at two
/// production sites in `caixa-core/src/aplicacao.rs` — the
/// [`WitContract::target`] payload-shape dispatch's `let slot =
/// self.slot.as_deref();` binding at the top of the method, and
/// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
/// tuple's `c.slot.as_deref()` store-arm slot — two open-coded
/// field-accesses that expressed no compile-time link back to the
/// typed slot. A future extension of the `:contratos :slot` axis
/// to a richer author surface (an M4 promotion from `Option<String>`
/// to a typed key-template enum once the WIT registry stabilizes
/// key-template parameter shapes in tatara-lisp per this struct's
/// own `:wit` field docstring, a per-cluster slot-alias table the
/// operator pins through a future `:placement`-scoped slot, a
/// canonicalization pass that lowercases the bucket prefix, a
/// per-CR fully-qualified rewrite the M4 CR materializer applies
/// per-tenant) would have had to be threaded through both
/// open-coded copies in lockstep or the two consumers would
/// silently disagree on which key-template a given edge resolves
/// to — the [`WitContract::target`] payload-extraction reading
/// `"carts/{cart_id}"` while the [`AplicacaoSpec::validate`] dedup
/// key read the operator-resolved `"tenant-a/carts/{cart_id}"`
/// would silently split the [`WitTarget::Store`]-arm rendered
/// payload from the actual dedup-key uniqueness axis, a
/// two-consumer split at the validator far from the source
/// `caixa.lisp` with no field naming the payload-drift root cause.
/// Lifting the resolution rule to a typed method on the substrate
/// primitive means every downstream store-payload-facing consumer
/// of the Aplicacao's per-`:contratos` payload surface reaches for
/// exactly one typed dispatch — the resolver's accept-set migrates
/// as a unit on any future axis addition.
///
/// Peer of the sibling per-`:contratos` [`WitContract::endpoint`]
/// (7020470) / [`WitContract::subject`] (90de675) `Option<&str>`
/// accessors on the M3 mesh-slot payload-carrier axis — third and
/// final `Option<&str>`-return accessor on the per-`:contratos`
/// mesh-slot atom, closes the last unlifted per-`:contratos`
/// `Option<String>` axis and completes the "optional per-slot
/// payload-carrier scalar" projection pattern the peer HTTP /
/// pub-sub arms established across the three payload-shape
/// dispatch arms. Named `slot()` to match the storage field's
/// name and the paired [`WitTarget::STORE_FIELD_NAME`]
/// author-facing label const; the accessor's identity name maps
/// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
/// docstring already carries.
#[must_use]
pub const fn slot(&self) -> Option<&str> {
match &self.slot {
Some(s) => Some(s.as_str()),
None => None,
}
}
/// Substrate-canonical per-`:contratos` `(caller, callee)` owned-form
/// caller-callee-pair accessor every consumer that constructs an
/// [`AplicacaoError`] variant carrying the per-edge `(de, para)`
/// caller-callee pair keys off — returns the author-declared
/// `:contratos :de` / `:contratos :para` byte-strings verbatim as an
/// owned `(String, String)` tuple, projected through the lifted
/// [`WitContract::source`] / [`WitContract::destination`] scalar
/// accessors so any future rebrand on the caller-arm / callee-arm
/// projection axis (an M4 per-cluster caller-alias table the
/// operator pins through a future `:placement`-scoped slot, a
/// namespace-qualified rewrite the M4 CR materializer applies per-CR,
/// a per-`:membros` alias overlay from the future `:membros
/// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
/// acknowledges) reaches every diagnostic-construction site by
/// construction.
///
/// The `(de, para)` pair is the "typed-edge caller-callee identity in
/// owned form" primitive every per-`:contratos` diagnostic variant on
/// [`AplicacaoError`] carries alongside its payload-shape arm — the
/// nine variants [`AplicacaoError::EmptyWit`],
/// [`AplicacaoError::ContratoEndpointEmpty`],
/// [`AplicacaoError::ContratoEndpointNotAbsolute`],
/// [`AplicacaoError::ContratoEndpointInvalid`],
/// [`AplicacaoError::ContratoSubjectEmpty`],
/// [`AplicacaoError::ContratoSubjectInvalid`],
/// [`AplicacaoError::ContratoSlotEmpty`],
/// [`AplicacaoError::ContratoSlotInvalid`], and
/// [`AplicacaoError::ContratoDuplicate`] each carry a `de: String,
/// para: String` field pair the constructor site reads verbatim off
/// the [`WitContract`] the diagnostic points at, so a diagnostic
/// whose `de:` and `para:` labels silently drift off the source
/// caller/callee — a per-cluster caller-alias rewrite that landed on
/// one variant's inline `de: c.de.clone()` field access but not on
/// its sibling variant's, an accidental swap of the `de:` and `para:`
/// arms in a copy-paste of the constructor block — would emit a
/// build-time error whose "which caixa is at fault" question the
/// operator answers wrongly, far from the source `caixa.lisp`.
///
/// Prior to this lift the `(self.de.clone(), self.para.clone())`
/// pair was inlined at seven [`WitContract::target`] error-
/// construction sites (the [`AplicacaoError::ContratoEndpointEmpty`]
/// / [`AplicacaoError::ContratoEndpointNotAbsolute`] /
/// [`AplicacaoError::ContratoEndpointInvalid`] HTTP-arm variants,
/// the [`AplicacaoError::ContratoSubjectEmpty`] /
/// [`AplicacaoError::ContratoSubjectInvalid`] pub-sub-arm variants,
/// the [`AplicacaoError::ContratoSlotEmpty`] /
/// [`AplicacaoError::ContratoSlotInvalid`] store-arm variants) and
/// two [`AplicacaoSpec::validate`] error-construction sites (the
/// [`AplicacaoError::EmptyWit`] empty-`:wit` gate, the
/// [`AplicacaoError::ContratoDuplicate`] duplicate-`:contratos`
/// insert-first-seen closure) — nine open-coded `.de.clone() +
/// .para.clone()` pairs that expressed no compile-time contract that
/// the caller-arm and callee-arm arms of the same diagnostic
/// construction reach for the same [`WitContract`] instance or that
/// the `de:` and `para:` label pair binds to the fields the author
/// declared. Any future rebrand on the axis — an M4 per-cluster
/// caller/callee-alias rewrite the operator pins through a future
/// `:placement :caller-alias` / `:placement :callee-alias` slot, a
/// per-CR fully-qualified namespace prefix the M4
/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
/// per-tenant, a canonicalization pass that lowercases the caller +
/// callee identifiers post-parse — would have had to be threaded
/// through every open-coded copy in lockstep or one variant's
/// diagnostic would silently name a different caller/callee pair
/// than its peer, silently degrading the "which caixa is at fault"
/// self-locating signal every operator-facing typed diagnostic
/// exists to carry. Lifting the pair to a typed method on the
/// substrate primitive means every downstream diagnostic-construction
/// site reaches for exactly one typed dispatch — the resolver's
/// projection migrates as a unit on any future axis addition.
///
/// Peer of the sibling per-`:contratos` scalar accessor family
/// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43)
/// / [`WitContract::world_ref`] (6226bf4) on the mesh-slot-atom
/// scalar-value axes — first composite-projection accessor on the
/// per-`:contratos` mesh-slot atom, folds the two open-coded owned-
/// form `.clone()` field-accesses that pair the sibling
/// caller/callee accessors' `&str`-return borrowed-form outputs onto
/// one typed dispatch. Named `edge_pair()` to reflect the identity
/// name of the projected tuple (the typed-edge caller-callee pair,
/// distinct from the sibling triple-projection
/// [`WitContract::edge_triple`] accessor that folds the local `edge`
/// closure in [`WitContract::target`] + the paired
/// [`AplicacaoError::ContratoDuplicate`] diagnostic constructor
/// site's `(de, para, wit)` triple onto one typed dispatch).
#[must_use]
pub fn edge_pair(&self) -> (String, String) {
(self.source().to_string(), self.destination().to_string())
}
/// Owned form of the `(:contratos :de, :contratos :para, :contratos
/// :wit)` triple every per-edge diagnostic constructor that names
/// all three axes threads verbatim into its `de:` / `para:` /
/// `wit:` fields — the [`WitTarget::target`] dispatch's wrong-target
/// / missing-target / invalid-wit / capability-with-payload arms
/// (eight sites all shape `let (de, para, wit) = edge();
/// AplicacaoError::Contrato* { de, para, wit, .. }` before this
/// accessor landed) and the sibling
/// [`AplicacaoError::ContratoDuplicate`] duplicate-gate diagnostic
/// constructor (which paired `edge_pair()` for the `(de, para)`
/// prefix with a raw `c.wit.clone()` for the `wit:` tail — a mixed
/// typed-dispatch + raw-field-access shape the sibling accessor
/// family already flagged as a drift risk). Nine total call sites
/// collapse onto this helper.
///
/// Lifted with the same one-source-of-truth discipline
/// [`WitContract::edge_pair`] carries on the paired
/// caller-callee-only axis: the returned tuple's `.0` / `.1` / `.2`
/// arms compose through the lifted [`WitContract::source`] /
/// [`WitContract::destination`] / [`WitContract::world_ref`]
/// scalar accessors byte-for-byte (pinned by the paired
/// [`tests::wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`]
/// composition-pin), so any future rebrand on the per-`:contratos`
/// caller / callee / world-ref axis (an M4 per-cluster
/// caller/callee-alias rewrite the operator pins through a future
/// `:placement :caller-alias` / `:placement :callee-alias` slot, a
/// per-CR fully-qualified namespace prefix the M4
/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
/// per-tenant, an M4-typed-caller-enum `Display` re-canonicalization
/// on `source()` / `destination()`, a per-CR canonicalization pass
/// that lowercases the WIT world ref post-parse) migrates as a
/// single caixa-core edit rather than a coordinated rewrite of
/// nine open-coded triple-constructors.
///
/// Peer of the sibling per-`:contratos` composite-projection
/// [`WitContract::edge_pair`] accessor on the mesh-slot-atom
/// composite-value axes — closes the last unlifted owned-form
/// composite-tuple axis on the per-`:contratos` diagnostic-
/// construction surface. Named `edge_triple()` to reflect the
/// identity name of the projected tuple (the typed-edge
/// caller-callee-wit triple, sibling to the caller-callee-only
/// pair `edge_pair()` returns).
#[must_use]
pub fn edge_triple(&self) -> (String, String, String) {
(
self.source().to_string(),
self.destination().to_string(),
self.world_ref().to_string(),
)
}
/// Borrowed [`ContratoIdentity`] six-tuple every consumer that
/// dedups typed edges keys off — routes through the lifted
/// [`WitContract::source`] / [`WitContract::destination`] /
/// [`WitContract::world_ref`] / [`WitContract::endpoint`] /
/// [`WitContract::subject`] / [`WitContract::slot`] scalar
/// accessors so the tuple's six arms and the [`ContratoIdentity`]
/// type alias's six axes migrate as a unit on any future axis
/// addition (adding a seventh field to [`WitContract`] is one
/// [`ContratoIdentity`] alias edit + one accessor addition + one
/// arm here, not a coordinated rewrite of every open-coded
/// six-tuple builder that dedups on the identity axis).
///
/// Sibling of [`WitContract::edge_pair`] /
/// [`WitContract::edge_triple`] on the composite-projection axis:
/// the pair projects the caller-callee axes, the triple extends it
/// with the world-ref, this method extends it with the three
/// payload-carrier axes. Every projection returns the same six
/// scalar accessors' outputs; the three methods differ only in
/// which arms they surface.
///
/// Declared `pub const fn` — every callee is itself `pub const fn`
/// ([`Self::source`] / [`Self::destination`] / [`Self::world_ref`]
/// project through `pub const fn` [`String::as_str`], const-stable
/// since Rust 1.87; [`Self::endpoint`] / [`Self::subject`] /
/// [`Self::slot`] project through the same `String::as_str` under a
/// `match &self.<field> { Some(s) => Some(s.as_str()), None => None }`
/// arm — the sibling `Option<String> → Option<&str>` shape 0650f64
/// closed the const-eval surface on) and tuple construction from
/// borrowed-reference / `Option`-of-borrowed-reference arms is
/// itself trivially const. The `ContratoIdentity<'_>` alias
/// resolves to a `(&str, &str, &str, Option<&str>, Option<&str>,
/// Option<&str>)` tuple whose every arm is `Copy` — no destructor,
/// no heap allocation, no non-const call folded through the tuple's
/// construction. Sibling in `const`-eval posture to the peer
/// `pub const fn` [`WitContract::is_http`] / [`Self::is_pubsub`] /
/// [`Self::is_store`] / [`Self::is_capability`] WIT-shape-predicate
/// composite-projection family the sibling
/// [`wit_contract_pre_projection_accessor_family_is_const_fn`] pin
/// already anchors — this extends the same `const`-eval-surface
/// posture onto the peer six-arm composite-projection axis where
/// the projection surfaces the full identity tuple rather than a
/// per-`(:de, :para, :wit)`-triple boolean shape probe. Pinned load-
/// bearing by
/// [`wit_contract_identity_projection_accessor_is_const_fn`] below
/// (a future accidental downgrade fires E0015 at the wrapper at
/// caixa-core build time).
#[must_use]
pub const fn identity(&self) -> ContratoIdentity<'_> {
(
self.source(),
self.destination(),
self.world_ref(),
self.endpoint(),
self.subject(),
self.slot(),
)
}
/// True when this contract targets an HTTP-shaped WIT world.
///
/// Declared `pub const fn` — routes through the paired `pub const
/// fn` [`Self::world_ref`] scalar accessor and the substrate's
/// `pub const fn` free-function classifier [`wit_shape_is_http`]
/// (d46420c). Sibling in `const`-eval posture to the peer
/// `pub const fn` [`Self::is_pubsub`] / [`Self::is_store`] /
/// [`Self::is_capability`] WIT-shape-predicate family; the closed
/// 4-arm partition on the raw `:contratos :wit` axis now carries
/// the same `const`-eval-surface posture as the free-function
/// classifier family it composes through. Pinned load-bearing by
/// the [`wit_contract_pre_projection_accessor_family_is_const_fn`]
/// test (a future accidental downgrade to non-`const` fires E0015
/// at the corresponding `<arm>_via_const_fn` wrapper at caixa-core
/// build time).
#[must_use]
pub const fn is_http(&self) -> bool {
wit_shape_is_http(self.world_ref())
}
/// True when this contract targets a pub-sub-shaped WIT world.
///
/// Declared `pub const fn` — sibling in `const`-eval posture to
/// the peer `pub const fn` [`Self::is_http`] / [`Self::is_store`] /
/// [`Self::is_capability`] WIT-shape-predicate family. See
/// [`Self::is_http`] for the family-closure rationale.
#[must_use]
pub const fn is_pubsub(&self) -> bool {
wit_shape_is_pubsub(self.world_ref())
}
/// True when this contract targets a key/value-shaped WIT world.
///
/// Declared `pub const fn` — sibling in `const`-eval posture to
/// the peer `pub const fn` [`Self::is_http`] / [`Self::is_pubsub`] /
/// [`Self::is_capability`] WIT-shape-predicate family. See
/// [`Self::is_http`] for the family-closure rationale.
#[must_use]
pub const fn is_store(&self) -> bool {
wit_shape_is_store(self.world_ref())
}
/// True when this contract targets *none* of the three known payload-
/// shape WIT worlds — the fourth (payload-less) arm of the WIT-shape
/// partition [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`]
/// open on the [`WitContract`] surface. Returns the exact-inverse
/// disjunction of the peer trio — `true` when none of the three
/// prefix-set predicates matches the raw `:contratos :wit` value; the
/// author-declared WIT world is a pure typed capability edge with no
/// payload selector (the shape [`WitContract::target`] projects onto
/// the payload-less [`WitTarget::Capability`] arm, MESH-COMPOSITION
/// §II.3 — the fourth typed [`WitTarget`] arm the substrate admits).
///
/// The `:contratos :wit` shape-space is closed at four arms
/// ([`WIT_HTTP_SHAPE_PREFIXES`] / [`WIT_PUBSUB_SHAPE_PREFIXES`] /
/// [`WIT_STORE_SHAPE_PREFIXES`] on the payload-carrying arms;
/// everything else on the payload-less capability arm), and every
/// downstream consumer that must filter contratos by shape-class
/// keys off the four sibling predicates (the [`WitContract::target`]
/// dispatch's implicit `else` after the three payload-shape arm
/// checks at aplicacao.rs:959–1129 that admits [`WitTarget::Capability`],
/// every future substrate-side capability-shape-only emitter — the
/// M4 per-Aplicacao WIT-registry capability-import materializer, the
/// future `feira app graph --capability` per-Aplicacao capability-
/// column filter, the future per-cluster capability-scope reconciler
/// that skips L4/L7 emission for payload-less edges since Cilium
/// can't introspect WASI capability calls, the future
/// `mesh.pleme.io/v1alpha1/Aplicacao` CR admission webhook's per-
/// shape shape-count histogram). Every such consumer reaches for one
/// typed dispatch on the substrate primitive so the "which arm
/// carries the capability-only shape?" answer lives at one caixa-core
/// edit rather than open-coded across per-consumer
/// `!c.is_http() && !c.is_pubsub() && !c.is_store()` triplet
/// negations, each of which would silently drop a future fourth
/// payload-arm addition without a compile-time signal at the
/// consumer site.
///
/// Prior to this lift the "not one of the three known payload
/// shapes" classification sat inline at [`WitContract::target`]'s
/// implicit `else`-branch (aplicacao.rs:1131 — the payload-less
/// [`WitTarget::Capability`] admission arm after the three `if
/// self.is_http() { … } if self.is_pubsub() { … } if self.is_store()
/// { … }` guards) with no named accessor for downstream consumers
/// to reach through. A future substrate-side capability-only
/// filter or a future capability-scope reconciler would have had to
/// re-inline the same triplet negation at every emit site with no
/// compile-time link back to the sibling trio, and a future arm
/// addition (a hypothetical fourth payload-shape prefix set — a
/// `wasi:sockets/*` transport-layer shape or an `oci:*` capability-
/// import carrier per the sibling [`wit_shape_matches`] docstring's
/// trajectory bullet) would land the new predicate on the payload-
/// carrying trio and silently misclassify the new shape as
/// capability at every triplet-negation consumer site, propagating
/// the drift far from the caixa-core prefix-set commit.
///
/// Fourth arm on the [`WitContract`] WIT-shape-predicate family —
/// closes the {[`Self::is_http`], [`Self::is_pubsub`], [`Self::is_store`]}
/// trio into a 4-way partition witness on the raw `:contratos :wit`
/// axis, mirroring the paired post-projection [`WitTarget`]
/// `gen_platform::IsVariant`-derived 4-way predicate set
/// ([`WitTarget::is_http`] / [`WitTarget::is_pubsub`] /
/// [`WitTarget::is_store`] / [`WitTarget::is_capability`]) on the
/// typed-view surface (7f6aa98 `IsVariant` derive lift on the peer
/// arm-set). The two typed axes — pre-projection on the raw
/// `:contratos :wit` string, post-projection on the validated typed
/// view — now carry a matched 4-arm predicate discipline: every
/// arm on the closed [`WitTarget`] set has a peer pre-projection
/// predicate on the [`WitContract`] surface, and any future
/// [`WitTarget`] variant addition (an M4 `Rest` / `Grpc` split of
/// [`WitTarget::Http`] once the WIT registry stabilizes gRPC-shaped
/// worlds per [`WitTarget`]'s own docstring at aplicacao.rs:1341-1343,
/// a `Queue`-shaped peer of [`WitTarget::Store`]) reaches this
/// pre-projection axis through a matching peer prefix-set + peer
/// predicate lift by construction — the compile-time exhaustiveness
/// on [`WitTarget::payload_pair`]'s single dispatch already enforces
/// the post-projection accessor family stays in sync, and the sibling
/// [`tests::wit_contract_is_capability_partitions_the_wit_shape_space`]
/// partition-witness pin locks the pre-projection classification in
/// load-bearing so a peer prefix-set addition that widened one arm's
/// accept-set without shrinking the [`Self::is_capability`] accept-set
/// surfaces as a test failure at caixa-core build time rather than a
/// silent per-consumer split at renderer emit time.
///
/// Composes byte-for-byte through the lifted peer trio
/// [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`] so
/// any future rebrand of any prefix-set const flows through this
/// method by construction without a coordinated per-consumer rewrite
/// (pinned by the sibling
/// [`tests::wit_contract_is_capability_composes_through_shape_predicate_negation`]
/// composition-witness).
///
/// Note: purely syntactic classification on the `:wit` prefix-set —
/// unlike [`Self::target`], which additionally rejects value-shape-
/// invalid `:wit` strings (uppercase, hyphen-for-colon typo, empty
/// package) via [`crate::render::is_wit_world_ref`] and payload-
/// shape mismatches. A [`WitContract`] whose `:wit` is empty or
/// structurally malformed returns `true` from `is_capability()` (the
/// prefix set matches nothing), and the surrounding
/// [`AplicacaoSpec::validate`] / [`WitContract::target`] gate cascade
/// is where the [`AplicacaoError::EmptyWit`] /
/// [`AplicacaoError::ContratoWitInvalid`] diagnostic surfaces — this
/// predicate is the classifier, not the validator.
///
/// Declared `pub const fn` — closes the WIT-shape-predicate
/// family's `const`-eval-surface pass at the fourth (payload-less)
/// arm; peer of the sibling `pub const fn` [`Self::is_http`] /
/// [`Self::is_pubsub`] / [`Self::is_store`] payload-arm predicates.
/// See [`Self::is_http`] for the family-closure rationale.
#[must_use]
pub const fn is_capability(&self) -> bool {
wit_shape_is_capability(self.world_ref())
}
/// True when this contract's caller equals its callee — a
/// structurally degenerate typed edge that no `:contratos` entry can
/// legitimately carry (MESH-COMPOSITION §III.1 — "Servico A calls
/// Servico B" is an *inter*-Servico contract between two distinct
/// graph nodes). A Servico contracting with itself resolves to an
/// in-process call the wasm-engine never routes through the mesh at
/// all, so no rendered `CiliumNetworkPolicy` / `HTTPRoute` /
/// per-edge policy can express the intended shape — the pub-sub
/// path silently rendered a self-allow rule that is a no-op (intra-
/// pod traffic bypasses the mesh entirely), and the synchronous
/// paths surfaced as a misleading `ContratoCycle` whose path was
/// `["cart", "cart"]` — framing a self-edge as a multi-node
/// deadlock. Every downstream consumer that must reject the shape
/// (the [`AplicacaoSpec::validate`] per-`:contratos` self-loop
/// gate at caixa-core/src/aplicacao.rs:5559, every future
/// per-`:contratos`-edge policy resolver on the M4 CR materializer
/// axis, every future adjacency-graph builder that must skip self-
/// edges rather than fold them into an incidental cycle) now keys
/// off exactly one typed dispatch on the substrate primitive, so
/// any future rebrand on the axis (an M4-typed-caller enum whose
/// identity comparison rule the accessor could route through, an
/// operator-side per-cluster caller/callee-alias table the
/// materializer resolves per-CR before the equality probe, a
/// promotion of the pointwise `==` to a set-membership check once
/// SimpleOneForOne-shaped dynamic replicas come into typed scope
/// so a per-replica self-edge is rejected under the same predicate)
/// migrates as a single caixa-core edit rather than a coordinated
/// rewrite of every downstream self-edge consumer. Composes
/// byte-for-byte through the lifted [`Self::source`] /
/// [`Self::destination`] scalar accessors — the accessor pair every
/// per-`:contratos` scalar-value axis already routes through — so
/// any future rebrand of the underlying `:de` / `:para` storage
/// (a lift from `String` to a typed `ServicoName(String)` newtype,
/// a per-Aplicacao interning arena the M4 CR materializer authors,
/// a `smol_str::SmolStr` inline-buffer swap) flows through the
/// same one body without a coordinated per-consumer rewrite.
///
/// Sibling in shape to the peer per-`:contratos` shape-predicate
/// family [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`]
/// on the `:wit` world-ref axis — extended onto the per-edge
/// endpoint-equality axis: `is_http` / `is_pubsub` / `is_store`
/// partition the WIT-shape-space; `is_self_loop` partitions the
/// caller-callee identity-space. Named `is_self_loop()` to reflect
/// the graph-theoretic identity of the shape (a loop from a graph
/// node to itself, distinct from the sibling multi-node
/// `ContratoCycle` shape [`Self::detect_sync_cycles`] rejects) and
/// to match the [`AplicacaoError::ContratoSelfLoop`] diagnostic
/// variant already carrying the term.
///
/// Declared `pub const fn` — closes the last unlifted per-`:contratos`
/// shape-predicate on the substrate's `const`-eval surface. The peer
/// per-`:contratos` shape-predicate family [`Self::is_http`] /
/// [`Self::is_pubsub`] / [`Self::is_store`] / [`Self::is_capability`]
/// (d46420c / 84c2325 / 279823b) already carries the `pub const fn`
/// posture on the WIT-world-ref classifier axis; this lift extends it
/// onto the peer caller-callee identity-space predicate. The body
/// projects the `:de` / `:para` `String` storage through the sibling
/// `pub const fn` [`Self::source`] / [`Self::destination`] scalar
/// accessors, then compares the resulting `&str` byte-slices under a
/// manual `while`-loop through `str::as_bytes` (`pub const fn`,
/// const-stable since Rust 1.39), primitive-`usize` `!=` on
/// [`<[u8]>::len`], and const-stable slice indexing (since Rust 1.79)
/// — every operation `const`-eval-callable on stable Rust, no
/// iterator methods, no `PartialEq for str` trait dispatch (which
/// remains non-`const` on stable). Mirrors the peer `pub const fn`
/// [`wit_shape_matches`] combinator's manual byte-level `starts_with`
/// loop verbatim on the paired-slice-equality shape. Every downstream
/// substrate-side `const`-context consumer of the per-`:contratos`
/// self-edge partition (a future `const _: () = assert!(…)` module-
/// scope invariant pin over a per-fixture typed [`WitContract`] once
/// the type's carriers admit `const`-context construction, a future
/// M4 admission-webhook `const fn` self-edge resolver, any `const fn`
/// composer that fans on the identity-space partition at compile
/// time) reaches through the same typed dispatch on the substrate
/// primitive at const-eval time as at runtime. Pinned by
/// [`tests::wit_contract_is_self_loop_predicate_is_const_fn`] which
/// witnesses the `const`-eval posture via a `const fn` wrapper so any
/// future accidental downgrade to non-`const` trips at caixa-core
/// build time with E0015 (`cannot call non-const method`), strictly
/// stronger than a runtime `assert!`.
#[must_use]
pub const fn is_self_loop(&self) -> bool {
// Compose through the paired `pub const fn` [`Self::source`] /
// [`Self::destination`] scalar accessors so any future rebrand of
// the underlying `:de` / `:para` storage (a lift from `String` to
// a typed `ServicoName(String)` newtype, a per-Aplicacao interning
// arena the M4 CR materializer authors, a `smol_str::SmolStr`
// inline-buffer swap) flows through the same one body without a
// coordinated per-consumer rewrite. Peer of the sibling
// [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`] /
// [`Self::is_capability`] shape-predicate family — each of which
// composes through the paired [`Self::world_ref`] scalar accessor
// onto the peer `pub const fn` [`wit_shape_is_http`] /
// [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
// [`wit_shape_is_capability`] free-function classifier — the same
// "typed dispatch composes with typed dispatch, not raw field
// access" discipline extended onto the caller-callee identity-
// space partition. Pinned by
// [`tests::wit_contract_is_self_loop_routes_through_source_destination_accessors`]
// above.
let a = self.source().as_bytes();
let b = self.destination().as_bytes();
if a.len() != b.len() {
return false;
}
// Manual byte-level equality loop — mirrors the peer
// [`wit_shape_matches`] combinator's manual `starts_with` loop
// verbatim on the paired-slice-equality shape. `PartialEq for
// str` remains non-`const` on stable Rust 1.94 (the `Pattern`
// trait dispatch it routes through is not `const`), so a naive
// `self.source() == self.destination()` body would trip on
// `const`-eval-callability; the byte-slice loop dispatches
// through primitive-`u8` `!=`, primitive-`usize` comparison, and
// const-stable slice indexing (since Rust 1.79) — every
// operation `const`-eval-callable on stable.
let mut i = 0;
while i < a.len() {
if a[i] != b[i] {
return false;
}
i += 1;
}
true
}
/// Reject a `:contratos` entry whose `:de` or `:para` names a
/// caixa the `:membros` graph does not contain — the substrate-
/// primitive per-edge graph-membership gate every consumer of the
/// typed inter-Servico edge's endpoint-resolution axis reaches
/// through one dispatch.
///
/// A `:contratos` entry is a typed directed edge between two
/// declared members (MESH-COMPOSITION §III.1 — "the typed edges
/// address graph nodes, so a reference to a node the graph does
/// not contain is a build error"). Both endpoints must resolve
/// against the same [`AplicacaoSpec::membro_names`] oracle: the
/// paired [`AplicacaoError::ContratoMemberMissing`] diagnostic
/// framing does not distinguish `:de` from `:para` (both arms
/// carry the offending `caixa` name verbatim without a
/// slot-discriminator field, unlike the sibling per-arm shape
/// gate [`validate_contrato_caixa`] whose paired
/// [`AplicacaoError::ContratoCaixaEmpty`] / `ContratoCaixaInvalid`
/// variants each carry a `slot: &'static str` tag). So the two
/// arms are byte-identical modulo the accessor projection they
/// key off, and folding them into one per-edge dispatch preserves
/// every existing diagnostic-fired output byte-for-byte while
/// closing the last inline duplication the substrate-primitive
/// per-edge gate family carried inside
/// [`AplicacaoSpec::validate_contratos`].
///
/// Routes through the paired [`Self::source`] / [`Self::destination`]
/// scalar accessors so every future rebrand of the underlying
/// `:de` / `:para` storage (a lift from `String` to a typed
/// `ServicoName(String)` newtype, a per-Aplicacao interning arena
/// the M4 CR materializer authors, a per-cluster caller-alias
/// table the operator pins through a future `:placement`-scoped
/// slot, an M4 promotion from `String` to a typed edge-endpoint
/// enum) flows through the same body without a coordinated
/// per-consumer rewrite. Peer of the sibling per-edge substrate
/// primitives already lifted on the same `impl WitContract`
/// surface ([`Self::is_self_loop`] on the identity-space arm,
/// [`Self::target`] on the payload-shape ↔ target-consistency
/// arm, [`Self::identity`] on the dedup-key arm) — this run
/// extends the shape to the last per-edge axis
/// [`AplicacaoSpec::validate_contratos`] carried as an inline
/// twin-arm cascade.
///
/// Every future consumer that wants to re-check *one* edge's
/// graph-membership reaches through one call: the M4
/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
/// admission-webhook re-checking `:contratos` after a
/// per-`(:de, :para)` edge patch without re-walking the whole
/// `:contratos` list, the per-`:contratos`-edge `:politicas`
/// override MESH-COMPOSITION §III.2 #3 acknowledges — which
/// resolves an effective per-edge [`MeshPolicy`] and must
/// re-check the edge's endpoints against the same membership
/// oracle before it can key a per-edge override off the endpoint
/// tuple. Pre-lift each such consumer was structurally forced to
/// either re-inline the twin `if !names.contains(...)` cascade
/// (the duplication the PRIME DIRECTIVE names as a bug) or call
/// [`AplicacaoSpec::validate_contratos`] and pay a whole-list
/// walk to re-check one edge. Post-lift each reaches the axis
/// through one dispatch on the substrate primitive.
///
/// `:de` runs before `:para` per the canonical edge-direction
/// order the sibling per-arm shape gate
/// [`validate_contrato_caixa`] arm ordering, the self-loop
/// diagnostic string, and every peer arm ordering in
/// [`AplicacaoSpec::validate_contratos`] already use — a
/// well-shaped-but-phantom `:de` fires before a well-shaped-but-
/// phantom `:para`, preserving byte-equal ordering with the
/// pre-lift inline cascade.
fn require_endpoints_in(
&self,
names: &std::collections::HashSet<&str>,
) -> Result<(), AplicacaoError> {
if !names.contains(self.source()) {
return Err(AplicacaoError::contrato_member_missing(self.source()));
}
if !names.contains(self.destination()) {
return Err(AplicacaoError::contrato_member_missing(self.destination()));
}
Ok(())
}
/// Typed view of the contract's payload target. Enforces that the
/// `:wit` shape and the carried `:endpoint`/`:subject`/`:slot`
/// fields agree, and that each carried value is itself
/// value-shape valid:
///
/// - HTTP world (`wasi:http/*`, `http:*`) ⇒ exactly `:endpoint`,
/// non-empty, leading-`/` (Cilium L7 `path` + Gateway API
/// `PathPrefix` invariant — same shape required of `:entrada
/// :paths`)
/// - `PubSub` world (`nats:*`, `kafka:*`) ⇒ exactly `:subject`,
/// non-empty (NATS / Kafka publish without a subject is a
/// no-op subscribe, never the author's intent)
/// - Store world (`wasi:keyvalue/*`, `kv:*`) ⇒ exactly `:slot`,
/// non-empty (an empty slot template addresses the bucket
/// root, defeating the per-key isolation the slot exists for)
/// - Anything else ⇒ none of the three; the contract is a pure
/// typed capability edge with no payload selector.
///
/// Translates the Apollo Federation discipline ("conflicts are
/// errors at compile time, not warnings at runtime";
/// MESH-COMPOSITION §II.3) onto pleme-io's typed Aplicacao surface:
/// a contract whose WIT shape disagrees with its target field, or
/// whose target field carries a value-shape-invalid string, is a
/// build error — not a silent renderer drop. The returned
/// [`WitTarget`] view's `&str` payload is therefore guaranteed
/// non-empty (and absolute, for `Http`); every downstream consumer
/// (caixa-mesh's L7 emission, the M3 Gateway/HTTPRoute renderer,
/// the M4 per-edge policy resolver) can rely on that without
/// re-checking.
pub fn target(&self) -> Result<WitTarget<'_>, AplicacaoError> {
// Route the HTTP-shaped payload-target extraction through the
// lifted [`WitContract::endpoint`] accessor rather than the raw
// `self.endpoint.as_deref()` field access — the two production
// consumers of the per-`:contratos :endpoint` HTTP-shaped
// payload-carrier scalar (this method's Http-arm payload
// extraction, the [`AplicacaoSpec::validate`] duplicate-
// `:contratos` [`ContratoIdentity`] dedup-key HTTP arm) now key
// off exactly one typed dispatch on the substrate primitive, so
// any future rebrand on the axis (an M4 per-cluster endpoint-
// alias rewrite, a per-CR fully-qualified path prefix the M4
// materializer applies per-tenant, an M4 promotion from
// `Option<String>` to a typed HTTP path-template enum) migrates
// as a single caixa-core edit rather than a coordinated rewrite
// of the two call sites — peer of the sibling M3 per-`:placement`
// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
// (74ec2d3) `Option<&str>` typed-dispatch discipline extended
// onto the per-`:contratos` HTTP-shaped payload-carrier axis.
let endpoint = self.endpoint();
let subject = self.subject();
// Route the store-arm payload-carrier scalar through the
// lifted [`WitContract::slot`] accessor rather than the raw
// `self.slot.as_deref()` field access — the two production
// consumers of the per-`:contratos :slot` key/value-store-
// shaped payload-carrier scalar (this method's Store-arm
// payload extraction, the [`AplicacaoSpec::validate`]
// duplicate-`:contratos` [`ContratoIdentity`] dedup-key store
// arm) now key off exactly one typed dispatch on the substrate
// primitive. Closes the last unlifted per-`:contratos`
// `Option<String>` axis, completing the payload-carrier
// accessor family peer of the sibling per-`:contratos`
// [`WitContract::endpoint`] (7020470) / [`WitContract::subject`]
// (90de675) lifts across the HTTP / pub-sub arms.
let slot = self.slot();
// Route the local `(de, para, wit)` triple-projection closure
// through the lifted [`WitContract::edge_triple`] typed accessor
// rather than re-inlining `(self.de.clone(), self.para.clone(),
// self.wit.clone())` — the eight [`AplicacaoError::Contrato*`]
// triple-carrying diagnostic constructors below (wrong-target /
// missing-target on all three payload arms + capability-with-
// payload + invalid-wit) now key off exactly one typed dispatch
// on the substrate-primitive composite projection, sibling to
// the peer [`WitContract::edge_pair`]-routed
// [`AplicacaoError::Empty*`]/`ContratoEndpointEmpty`/
// `ContratoSubjectEmpty`/`ContratoSlotEmpty` pair-carrying
// diagnostic constructors on the same per-`:contratos`
// diagnostic-construction surface.
let edge = || self.edge_triple();
// The `:wit` value drives every downstream dispatch — the
// is_http/is_pubsub/is_store prefix matchers below, the
// caixa-mesh L7-vs-L4 emission, the cycle-detector's pub-sub
// exclusion. Until this gate landed `target()` accepted any
// non-empty string and silently demoted unrecognized shapes to
// a capability-only edge (`:wit "WASI:HTTP/proxy"` — uppercase
// typo, `:wit "wasi-http/proxy"` — hyphen-instead-of-colon typo,
// `:wit "wasi:http proxy"` — whitespace, `:wit "wasi:"` — empty
// package, the paste-from-binary footgun a multi-line blob
// accidentally landing in the slot, the un-percent-encoded
// non-ASCII byte) — the canonical "I thought I had L7 HTTP
// routing, got L4-only" footgun. Empty is still pre-checked at
// the [`AplicacaoSpec::validate`] call site via the narrower
// [`AplicacaoError::EmptyWit`] variant (and fires first at the
// validate layer); the value-shape gate here picks up the
// structurally-invalid non-empty cases the empty check misses,
// and remains correct under direct `target()` calls outside
// validate (the predicate's defensive empty arm returns a
// parser-shaped reason rather than silently falling through to
// the Capability arm). Same trajectory as c4213a4 (WitContract
// endpoint/subject/slot value-shape gates lifted into
// `target()`) on the peer payload axes.
//
// Routed through the lifted [`WitContract::world_ref`] accessor
// rather than the raw `&self.wit` field access — the two
// production consumers of the per-`:contratos :wit` world-ref
// byte-string on the value-shape axis (this method's invalid-
// wit gate, the [`AplicacaoSpec::validate`] duplicate-
// `:contratos` [`ContratoIdentity`] dedup-key world-ref arm via
// [`WitContract::identity`]) now key off exactly one typed
// dispatch on the substrate primitive, so any future rebrand on
// the axis (an M4 promotion from `String` to a typed WIT
// world-ref enum once the WIT registry stabilizes in
// tatara-lisp, a per-CR canonicalization pass that lowercases
// the WIT world ref post-parse, a promoted `smol_str::SmolStr`
// inline-buffer swap on the storage arm) migrates as a single
// caixa-core edit rather than a coordinated rewrite of the two
// call sites — sibling of the peer [`WitContract::endpoint`] /
// [`WitContract::subject`] / [`WitContract::slot`] accessor-
// routed payload-carrier extractions above on the same
// [`WitContract::target`] body, completing the per-`:contratos`
// scalar-accessor-routing pass at the last unlifted raw-field-
// access site inside `impl WitContract`. Same "typed dispatch
// composes with typed dispatch, not with raw field access"
// discipline the sibling [`WitContract::edge_pair`] /
// [`WitContract::edge_triple`] / [`WitContract::identity`]
// composite-projection accessors and the
// [`WitContract::is_self_loop`] identity-space predicate
// already route through. Pinned by
// [`tests::wit_contract_target_wit_shape_gate_routes_through_world_ref_accessor`].
if let Err(reason) = crate::render::is_wit_world_ref(self.world_ref()) {
return Err(AplicacaoError::contrato_wit_invalid(
self.edge_pair(),
self.world_ref(),
reason,
));
}
if self.is_http() {
if subject.is_some() || slot.is_some() {
return Err(AplicacaoError::contrato_wrong_target(
edge(),
WitTarget::HTTP_FIELD_NAME,
));
}
let ep = endpoint.ok_or_else(|| {
AplicacaoError::contrato_missing_target(edge(), WitTarget::HTTP_FIELD_NAME)
})?;
if ep.is_empty() {
return Err(AplicacaoError::contrato_endpoint_empty(self.edge_pair()));
}
if !ep.starts_with('/') {
return Err(AplicacaoError::contrato_endpoint_not_absolute(
self.edge_pair(),
ep,
));
}
// The `:endpoint` lands verbatim as a Cilium L7 `path:` rule
// (caixa-mesh/src/lib.rs:311) and shares the K8s Gateway
// API v1 HTTPPathMatch.value admission grammar with the
// sibling `:entrada :paths` axis. Until this gate landed
// `target()` only refused the empty string + the missing-
// leading-`/` form; a structurally invalid endpoint
// (`"/charge?token=X"` — query in path slot, `"/foo bar"` —
// un-percent-encoded whitespace, `"/api/café"` — non-ASCII,
// `"/api//bar"` — consecutive slash, `"/api/../etc"` —
// path-traversal segment, the >1024-byte slug) silently
// passed validate and the failure surfaced at apply time
// as a Cilium policy rejection / silent traffic drop, far
// from the source caixa.lisp. Same Gateway API HTTPPathMatch
// grammar `:entrada :paths` already gates (55410e4), now
// shared with `:contratos :endpoint` through the lifted
// `crate::render::is_gateway_api_http_path` predicate.
if let Err(reason) = crate::render::is_gateway_api_http_path(ep) {
return Err(AplicacaoError::contrato_endpoint_invalid(
self.edge_pair(),
ep,
reason,
));
}
return Ok(WitTarget::Http { endpoint: ep });
}
if self.is_pubsub() {
if endpoint.is_some() || slot.is_some() {
return Err(AplicacaoError::contrato_wrong_target(
edge(),
WitTarget::PUBSUB_FIELD_NAME,
));
}
let s = subject.ok_or_else(|| {
AplicacaoError::contrato_missing_target(edge(), WitTarget::PUBSUB_FIELD_NAME)
})?;
if s.is_empty() {
return Err(AplicacaoError::contrato_subject_empty(self.edge_pair()));
}
// The `:subject` lands at runtime as the NATS subject the
// producer publishes to and the consumer subscribes from.
// Until this gate landed `target()` only refused the
// empty string; a structurally invalid subject
// (`"foo..bar"` — empty token between separators,
// `"foo.>.bar"` — non-trailing `>` wildcard the NATS
// server's subject parser rejects, `"foo bar"` —
// un-percent-encoded whitespace, `"foo.café"` —
// un-percent-encoded non-ASCII, `".foo"` / `"foo."` —
// empty leading/trailing tokens, the >256-byte
// paste-from-binary slug) silently passed validate and
// the failure surfaced at runtime as a NATS server-side
// `-ERR 'Invalid Subject'` on publish / subscribe, or as
// a silent message drop, far from the source caixa.lisp.
// Same Gateway API HTTPPathMatch / WIT-IDL grammar
// trajectory `:contratos :endpoint` (4f0390b) and
// `:contratos :wit` (6226bf4) already gate, now shared
// with `:contratos :subject` through the lifted
// `crate::render::is_nats_subject` predicate.
if let Err(reason) = crate::render::is_nats_subject(s) {
return Err(AplicacaoError::contrato_subject_invalid(
self.edge_pair(),
s,
reason,
));
}
return Ok(WitTarget::PubSub { subject: s });
}
if self.is_store() {
if endpoint.is_some() || subject.is_some() {
return Err(AplicacaoError::contrato_wrong_target(
edge(),
WitTarget::STORE_FIELD_NAME,
));
}
let sl = slot.ok_or_else(|| {
AplicacaoError::contrato_missing_target(edge(), WitTarget::STORE_FIELD_NAME)
})?;
if sl.is_empty() {
return Err(AplicacaoError::contrato_slot_empty(self.edge_pair()));
}
// Value-shape gate on the third (and last) typed payload
// axis the `WitContract::target` dispatch carries — the
// peer of [`crate::render::is_gateway_api_http_path`] for
// `:endpoint` (4f0390b) and [`crate::render::is_nats_subject`]
// for `:subject` (63e18a0). Until this gate landed
// `target()` only refused the empty string; a structurally
// invalid slot (`"check out/$order"` — un-percent-encoded
// whitespace whose runtime behavior varies unpredictably
// across kv backends, `"checkout/\x01order"` — control
// character that Redis admits but corrupts on next read
// and DynamoDB rejects outright, `"chéckout/$order"` —
// un-percent-encoded non-ASCII byte each backend re-encodes
// differently, `"checkout\n/$order"` — embedded newline,
// the 513-byte paste-from-binary slug) silently passed
// validate and surfaced at runtime as a per-backend kv
// write rejection (DynamoDB / etcd) or as a silent
// next-read corruption (Redis-via-RESP3), far from the
// source caixa.lisp with no field naming which `:contratos`
// edge carried the typo. The lifted predicate makes the
// kv-backend intersection-floor a substrate-level
// invariant at validate time, not a runtime "this passed
// validate but the kv backend rejected on first write"
// surprise — closes the typed payload-axis value-shape
// trajectory across all three legs of the four
// [`WitTarget`] arms (HTTP / PubSub / Store / Capability)
// that caixa-mesh + the future kv emitters land in.
if let Err(reason) = crate::render::is_wasi_keyvalue_slot(sl) {
return Err(AplicacaoError::contrato_slot_invalid(
self.edge_pair(),
sl,
reason,
));
}
return Ok(WitTarget::Store { slot: sl });
}
// Unrecognized WIT world — must not carry any payload target.
if endpoint.is_some() || subject.is_some() || slot.is_some() {
return Err(AplicacaoError::contrato_wrong_target(
edge(),
WitTarget::CAPABILITY_EXPECTED,
));
}
Ok(WitTarget::Capability)
}
/// Substrate-canonical post-validation projection of the typed
/// [`WitTarget`] view — the panic-on-failure shorthand every renderer
/// downstream of an [`AplicacaoSpec`] that has already crossed the
/// [`AplicacaoSpec::validate`] gate (typically via a caixa-mesh
/// [`typed_view`]-shaped entry point that composes `validate` into
/// the projection) reaches through when it needs the typed
/// [`WitTarget`] and knows the containing [`AplicacaoSpec::validate`]
/// has already admitted the `(:wit, :endpoint/:subject/:slot)` shape
/// coherence for every `:contratos` entry. The peer accessor to the
/// [`Self::target`] `Result`-returning validator on the same
/// per-`:contratos` typed-projection axis — [`Self::target`] is the
/// pre-validation validator that computes the projection *and* raises
/// the [`AplicacaoError::Contrato*`] diagnostic cascade on any
/// (`:wit`, payload) mismatch; this method is the post-validation
/// projection every downstream consumer reaches through once the
/// pre-validation gate has succeeded.
///
/// [`typed_view`]: https://docs.rs/caixa-mesh/latest/caixa_mesh/fn.typed_view.html
///
/// Prior to this lift the "call `.target()` then `.expect(…)` with
/// the same message" pattern sat inline at two production sites with
/// no compile-time link between them: the
/// [`caixa_mesh::cilium_network_policies`] per-`(:de, :para)` CNP
/// L7 introspection branch at `caixa-mesh/src/lib.rs:2825`
/// (`c.target().expect("validated by typed_view").http_endpoint()`)
/// and the [`caixa_feira::cmd::app`] `feira app graph` per-`:contratos`
/// payload-column printer at `caixa-feira/src/cmd/app.rs:110`
/// (`c.target().expect("validated by typed_view").graph_label()`),
/// each open-coding the same `.target().expect("validated by
/// typed_view")` pair with the message spelled twice. A future
/// vocabulary shift on the panic-message axis (a tightening from
/// `"validated by typed_view"` to `"validated by AplicacaoSpec::
/// validate"` as the substrate's validator entry-point vocabulary
/// sharpens, a per-consumer disambiguation, an M4 promotion of the
/// panic to a `debug_assert` under a `--release` build profile) would
/// have had to be threaded through both open-coded call sites in
/// lockstep or one consumer would silently disagree with the peer on
/// which invariant the panic message names. Same "same shape written
/// verbatim ≥ 2 times becomes a typed helper" duplication-budget
/// discipline the sibling [`Self::edge_pair`] /
/// [`Self::edge_triple`] / [`Self::identity`] composite-projection
/// lifts already establish on the paired composite-projection axis;
/// this lift extends it onto the post-validation typed-view axis.
///
/// Every future downstream consumer of the projected typed view
/// (the future M4 per-`(:de, :para)` `mesh.pleme.io/v1alpha1/Aplicacao`
/// CR materializer's per-edge admission webhook, the future
/// Envoy-side per-typed-arm `local_rate_limit.descriptor_entries`
/// bucket-key resolver, the future per-`:contratos`-edge mTLS overlay
/// resolver, the future `feira app graph --l7` / `--pubsub` /
/// `--kv` per-shape column emitters) reaches through this one typed
/// dispatch on the substrate primitive rather than an open-coded
/// per-consumer `.target().expect(…)` pair with the message
/// re-inlined. The invariant the accessor's panic path pins — "this
/// call is only reachable after [`AplicacaoSpec::validate`] has
/// succeeded on the containing spec" — is the substrate's answer to
/// give exactly once, at the primitive, not once per consumer.
///
/// # Panics
///
/// Panics with [`Self::PROJECTED_INVARIANT_MSG`] if [`Self::target`]
/// would return an `Err` — i.e. if this contract's
/// (`:wit`, `:endpoint`/`:subject`/`:slot`) shape has not been
/// crossed by the [`AplicacaoSpec::validate`] gate cascade. Call
/// this accessor only from a code path that has already reached the
/// containing [`AplicacaoSpec`] through a validating entry-point
/// (caixa-mesh's [`typed_view`], caixa-feira's `feira app graph`'s
/// [`typed_view`] compose, the future M4 CR admission webhook's
/// per-CR validate). Use [`Self::target`] instead on any pre-
/// validation code path.
///
/// [`typed_view`]: https://docs.rs/caixa-mesh/latest/caixa_mesh/fn.typed_view.html
#[must_use]
pub fn target_projected(&self) -> WitTarget<'_> {
self.target().expect(Self::PROJECTED_INVARIANT_MSG)
}
/// Canonical panic message the [`Self::target_projected`]
/// post-validation projection accessor threads through when the
/// caller has violated the "call only after [`AplicacaoSpec::validate`]
/// has succeeded" precondition. Lifted as a `pub const` on the
/// [`WitContract`] surface so the byte-string lives in one place
/// across the substrate — the [`Self::target_projected`] method
/// body, the two prior production call sites' comments now naming
/// the const, and every future consumer that must format-match the
/// panic-message shape (a future test suite that asserts the panic-
/// message byte-string across a fuzzed invalid-contract corpus,
/// a future custom-panic hook in `caixa-operator` that surfaces the
/// message with per-`:contratos` telemetry, the future admission
/// webhook's per-CR validate-error report) reaches through the same
/// canonical `&'static str`. A future rebrand on the panic-message
/// axis (a tightening from `"validated by typed_view"` to `"validated
/// by AplicacaoSpec::validate"` as the substrate's validator
/// entry-point vocabulary sharpens once caixa-core grows a
/// `Caixa::validated_aplicacao_view` companion to caixa-mesh's
/// [`typed_view`]) lands at one caixa-core edit rather than a
/// coordinated per-consumer sweep — same "one canonical declaration
/// per axis, next to the accessor that reads it" discipline the peer
/// [`WitTarget::CAPABILITY_LABEL`] / [`WitTarget::CAPABILITY_EXPECTED`]
/// / [`WitTarget::CAPABILITY_GRAPH_LABEL`] payload-less-arm scalar-
/// const family already establishes on the paired per-consumer-axis
/// diagnostic-scalar surface.
pub const PROJECTED_INVARIANT_MSG: &'static str = "validated by typed_view";
}
/// Borrowed identity key for the typed-graph duplicate-`:contratos`
/// gate (see [`AplicacaoSpec::validate`]): every field that
/// distinguishes one contract from another, in declaration order
/// (`(de, para, wit, endpoint, subject, slot)`). Two [`WitContract`]s
/// with equal [`ContratoIdentity`]s are the same typed edge declared
/// twice — the graph-edge analogue of duplicate `:membros` /
/// `:placement :clusters` / `:entrada :paths` entries. Lifted as a
/// type alias so the duplicate-gate's `HashSet<…>` type doesn't trip
/// clippy's `type_complexity` lint (and so a future axis added to
/// `WitContract` is one alias edit, not a coordinated rewrite of
/// every set instantiation).
pub type ContratoIdentity<'a> = (
&'a str,
&'a str,
&'a str,
Option<&'a str>,
Option<&'a str>,
Option<&'a str>,
);
/// Typed view of a [`WitContract`]'s payload target. Each variant
/// carries the field its WIT shape requires; constructing a `Http`
/// view without an endpoint is impossible by the type system.
///
/// Renderers (caixa-mesh L7 rules, feira app graph) match on this
/// instead of probing `Option<String>` fields one by one — the
/// "which payload field is set?" question is answered once, at
/// validation time.
#[derive(Debug, Clone, Copy, PartialEq, Eq, gen_platform::IsVariant)]
pub enum WitTarget<'a> {
/// HTTP-shaped WIT world. Carries the configured request path.
Http { endpoint: &'a str },
/// Pub-sub-shaped WIT world. Carries the event-stream subject.
///
/// The `IsVariant` derive would auto-name the predicate `is_pub_sub`
/// (`discriminant_to_snake("PubSub") == "pub_sub"`); the explicit
/// `#[is_variant(name = "pubsub")]` override keeps the emitted
/// method name byte-identical to the sibling
/// [`WitContract::is_pubsub`] predicate (the paired shape-side
/// arm-discriminator that routes through
/// [`wit_shape_is_pubsub`] on the wit-world-ref scalar rather than
/// through `matches!` on the variant), so the two arm-discriminator
/// axes — target-side variant-arm and shape-side ref-prefix — reach
/// every downstream consumer through the same `is_pubsub()` name.
#[is_variant(name = "pubsub")]
PubSub { subject: &'a str },
/// Key-value-shaped WIT world. Carries the slot template.
Store { slot: &'a str },
/// A typed capability edge with no payload selector — the WIT
/// world stands on its own (rare; reserved for plain capability
/// imports or M4-and-later WIT worlds we haven't shaped yet).
Capability,
}
impl<'a> WitTarget<'a> {
/// Canonical author-facing `:contratos` payload field name for the
/// HTTP-shaped arm — the `expected: &'static str` scalar the
/// [`AplicacaoError::ContratoMissingTarget`] /
/// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
/// through, the `:endpoint "…"` keyword the [`WitTarget::label`]
/// duplicate-edge diagnostic emits, and the `endpoint=…` prefix
/// the `feira app graph` verb prints. Peer of
/// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
/// on the payload-field-name axis; declared as a peer const next
/// to the [`WitTarget::Http`] variant so a future rename on the
/// author-surface `(defcaixa … :contratos ((:de … :para … :wit …
/// :endpoint …)))` field lands in exactly one place, not scattered
/// across the [`WitContract::target`] gate's six `expected:`
/// literals, the label template, and every downstream consumer
/// that prints a per-arm prefix. Same trajectory as the peer
/// [`WitTarget::label`] lift (174e96a): a single source of truth
/// for the arm's shape, next to the variant declaration.
pub const HTTP_FIELD_NAME: &'static str = "endpoint";
/// Canonical author-facing `:contratos` payload field name for the
/// pub-sub-shaped arm. Peer of [`WitTarget::HTTP_FIELD_NAME`] /
/// [`WitTarget::STORE_FIELD_NAME`] on the payload-field-name axis;
/// see [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
pub const PUBSUB_FIELD_NAME: &'static str = "subject";
/// Canonical author-facing `:contratos` payload field name for the
/// key/value-store-shaped arm. Peer of
/// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`]
/// on the payload-field-name axis; see
/// [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
pub const STORE_FIELD_NAME: &'static str = "slot";
/// Canonical stable human-readable label the payload-less
/// [`WitTarget::Capability`] arm renders as under [`Self::label`] —
/// the byte-string every consumer that formats a payload-less
/// typed capability edge as text lands on (the
/// [`AplicacaoSpec::validate`] duplicate-`:contratos` diagnostic
/// naming which identical edge was declared twice, the future
/// `feira app graph` verb's per-arm prefix, the future M4 per-edge
/// policy resolver's audit view, the operator's mesh-graph audit).
/// Peer of the payload-arm [`Self::HTTP_FIELD_NAME`] /
/// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`]
/// author-facing label-scalar consts — the same
/// "one canonical declaration per arm, next to the variant, so a
/// future rename lands in one place" discipline extended to the
/// payload-less arm. Until this lift landed the byte-string sat
/// twice — once inline in [`Self::label`]'s [`WitTarget::Capability`]
/// match arm, once in the pin test asserting the label's
/// [`WitTarget::Capability`] output — with no compile-time link
/// between the two: a rebrand on either side (an operator-facing
/// vocabulary shift, a per-consumer disambiguation like
/// `"(capability — no payload; typed edge only)"`) would silently
/// desynchronize until a downstream consumer surfaced the drift at
/// runtime.
pub const CAPABILITY_LABEL: &'static str = "(capability — no payload)";
/// Canonical `expected:` scalar the
/// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
/// through for the payload-less [`WitTarget::Capability`] arm — the
/// byte-string authors read as "this WIT world's shape is not one
/// of {`HTTP`, `PubSub`, `Store`}, so it must not carry
/// `:endpoint` / `:subject` / `:slot`". Peer of the payload-arm
/// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
/// [`Self::STORE_FIELD_NAME`] consts on the
/// `ContratoWrongTarget::expected` axis — the fourth arm of the
/// same "which payload field name goes in the diagnostic" dispatch
/// the three payload-arm consts cover, extended to the payload-less
/// arm. Until this lift landed the byte-string sat twice — once
/// inline in the [`Self::target`] Capability-arm rejection at the
/// production dispatch, once in the pin test asserting the
/// diagnostic's `expected:` scalar carries `"none"` verbatim — with
/// no compile-time link between the two: a rebrand on either side
/// (an author-facing vocabulary shift to `"capability"` /
/// `"(none)"` / `"no-payload"` as the WIT registry's shape
/// vocabulary sharpens, a per-consumer disambiguation as M4 splits
/// [`WitTarget::Capability`] into per-shape peers) would silently
/// desynchronize until a downstream consumer surfaced the drift at
/// runtime. Same "one canonical declaration per arm, next to the
/// variant, so a future rename lands in one place" discipline the
/// peer [`Self::CAPABILITY_LABEL`] lift (7ed03a3-era) already
/// established for the payload-less arm's human-readable label
/// axis; this lift extends it onto the peer diagnostic-scalar axis
/// so both halves of the "how does the Capability arm surface at
/// its two consumer axes (human-readable label, wrong-target
/// diagnostic)" pipeline route through peer consts declared next
/// to the variant.
///
/// Pairwise-distinctness against the three payload-arm scalars
/// ([`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
/// [`Self::STORE_FIELD_NAME`]) is pinned by the sibling
/// `wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`
/// test — the 4-way closure of the 3-way
/// `wit_target_field_names_are_pairwise_distinct` sibling pin onto
/// the `ContratoWrongTarget::expected` axis, matching the peer
/// `m3_placement_estrategia_consts_are_pairwise_distinct` closed-set
/// scalar-value distinctness discipline the sibling M3 typed-enum
/// discriminator axis already carries.
pub const CAPABILITY_EXPECTED: &'static str = "none";
/// Canonical `feira app graph` per-`:contratos`-edge payload-column
/// byte-string the payload-less [`WitTarget::Capability`] arm renders
/// as under [`Self::graph_label`] — the sibling
/// [`WitTarget::CAPABILITY_LABEL`] scalar on the peer graph-verb
/// payload-column axis (the graph verb spells payload-less as
/// `(capability-only)`, distinct from the duplicate-`:contratos`
/// diagnostic's `(capability — no payload)` on the human-readable
/// [`Self::label`] axis). Peer of [`Self::CAPABILITY_LABEL`] /
/// [`Self::CAPABILITY_EXPECTED`] on the payload-less-arm scalar-const
/// family — extends the "one canonical declaration per arm, next to
/// the variant, so a future rename lands in one place" discipline
/// onto the third payload-less-arm consumer axis (`feira app graph`
/// payload column, joining the [`Self::label`] duplicate-`:contratos`
/// diagnostic axis and the [`Self::target`] wrong-target diagnostic
/// axis).
///
/// Until this lift landed the byte-string sat inline in
/// [`caixa-feira`]'s `cmd::app::GraphArgs::run` per-`:contratos` payload-
/// column match at `caixa-feira/src/cmd/app.rs:111` as a raw
/// `"(capability-only)".to_string()` literal, with no compile-time link
/// back to the [`WitTarget::Capability`] variant declaration nor to
/// the sibling [`Self::CAPABILITY_LABEL`] / [`Self::CAPABILITY_EXPECTED`]
/// peer consts already carrying the "one canonical declaration per
/// payload-less-arm consumer axis" discipline. A rebrand on either
/// side (the graph verb's operator-facing vocabulary tightening from
/// `"(capability-only)"` to `"capability"` / `"(capability edge)"` as
/// the WIT registry vocabulary sharpens, an M4 split of
/// [`Self::Capability`] into per-shape peers) would silently
/// desynchronize the graph-verb byte-string from the paired
/// per-arm-adjacent const and land two spellings of the same axis in
/// two spots.
pub const CAPABILITY_GRAPH_LABEL: &'static str = "(capability-only)";
/// The `(author-facing field name, payload)` pair this typed target
/// arm carries — `Some((HTTP_FIELD_NAME, endpoint))` for
/// [`Self::Http`], `Some((PUBSUB_FIELD_NAME, subject))` for
/// [`Self::PubSub`], `Some((STORE_FIELD_NAME, slot))` for
/// [`Self::Store`], `None` for the payload-less
/// [`Self::Capability`] arm.
///
/// Lifted as the single 4-arm dispatch that both [`Self::label`]
/// (formats `":{field} {payload:?}"` on `Some`, falls to
/// [`Self::CAPABILITY_LABEL`] on `None`) and [`Self::field_name`]
/// (returns the first component) route through, so a future
/// [`WitTarget`] variant addition — the M4-and-later per-edge WIT
/// registry may split [`Self::Http`] into `Rest` / `Grpc` peers,
/// or extend [`Self::Store`] with a `Queue`-shaped peer — becomes
/// exactly one new match-arm here (a compile-time exhaustiveness
/// error otherwise), not a coordinated three-way rewrite of the
/// prior [`Self::label`] template + [`Self::field_name`] dispatch
/// + every downstream consumer that reaches for the pair.
///
/// Until this lift landed the three payload arms sat in
/// [`Self::label`] as three near-identical `format!(":{} {…:?}", …)`
/// invocations (one per variant, each hand-quoting the paired
/// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
/// [`Self::STORE_FIELD_NAME`] const) — the canonical
/// "same shape, written N times" duplication THEORY.md §I.3.5
/// ("Generation first, composition second, hand-authoring last;
/// the duplication budget is zero") promotes to a build-time
/// concern, with each per-arm site paired to its own const with no
/// compile-time link between the format template and the arm's
/// payload extraction.
#[must_use]
pub const fn payload_pair(&self) -> Option<(&'static str, &'a str)> {
match *self {
WitTarget::Http { endpoint } => Some((Self::HTTP_FIELD_NAME, endpoint)),
WitTarget::PubSub { subject } => Some((Self::PUBSUB_FIELD_NAME, subject)),
WitTarget::Store { slot } => Some((Self::STORE_FIELD_NAME, slot)),
WitTarget::Capability => None,
}
}
/// The canonical author-facing `:contratos` payload field name
/// this typed target arm carries (`Http` → `Some("endpoint")`,
/// `PubSub` → `Some("subject")`, `Store` → `Some("slot")`), or
/// `None` for the payload-less `Capability` arm.
///
/// Routes through [`Self::payload_pair`] — the single 4-arm
/// dispatch [`Self::label`] also reads — so a future variant
/// addition is one match-arm edit at [`Self::payload_pair`], not a
/// per-consumer rewrite. Same "exhaustive-match at one canonical
/// dispatch, thin projections at each consumer" trajectory the
/// peer [`PlacementStrategy::as_str`] / [`std::fmt::Display`]
/// pair (0a2f653) landed on the sibling M3 typed-enum axis.
#[must_use]
pub const fn field_name(&self) -> Option<&'static str> {
match self.payload_pair() {
Some((f, _)) => Some(f),
None => None,
}
}
/// The underlying scalar the payload-carrying arm carries — the
/// per-arm request path ([`Self::Http`] `:endpoint`), event-stream
/// subject ([`Self::PubSub`] `:subject`), or slot template
/// ([`Self::Store`] `:slot`), borrowed from the typed slot's own
/// `&'a str` storage — or `None` on the payload-less
/// [`Self::Capability`] arm.
///
/// Thin projection onto the single 4-arm [`Self::payload_pair`]
/// dispatch (`self.payload_pair().map(|(_, p)| p)` in `const fn`
/// form) — peer of [`Self::field_name`] (`.payload_pair().0`) on
/// the paired sub-selector axis. Both per-half accessors read from
/// one authoritative match, so a future [`WitTarget`] variant
/// addition (`Rest`/`Grpc` split of [`Self::Http`], `Queue`-shaped
/// peer of [`Self::Store`]) lands at exactly one caixa-core edit
/// on [`Self::payload_pair`] and both per-half projections + every
/// downstream consumer picks the new arm up by construction — no
/// coordinated N-way rewrite across the paired accessor dispatches,
/// the [`Self::label`] / [`Self::graph_label`] format templates,
/// and every future WIT-registry-shaped consumer.
///
/// Peer of the sibling [`caixa-flux`][caixa-flux-crate]
/// `GitRefSpec::ref_value` projection on the `FluxCD` source-
/// controller `spec.ref.<field>` axis — same "one paired dispatch,
/// both per-half projections as thin readers, every downstream
/// consumer through the same match" discipline extended onto the
/// M3 `:contratos` payload-arm axis. Closes the discipline-parity
/// gap between the two paired-dispatch surfaces: the peer
/// [`Self::payload_pair`] + [`Self::field_name`] pair carried only
/// the first-component projection until this lift; the second-
/// component sibling now sits alongside so both halves reach every
/// future consumer through the same substrate-primitive dispatch.
///
/// [caixa-flux-crate]: https://docs.rs/caixa-flux/latest/caixa_flux/enum.GitRefSpec.html#method.ref_value
#[must_use]
pub const fn payload(&self) -> Option<&'a str> {
match self.payload_pair() {
Some((_, p)) => Some(p),
None => None,
}
}
/// Substrate-canonical per-arm HTTP-endpoint scalar accessor every
/// consumer that fans on the L7-HTTP-shaped payload keys off —
/// returns the [`Self::Http`]-arm's author-declared request path
/// verbatim as an `Option<&'a str>`, `Some(endpoint)` when the
/// projected target is [`Self::Http { endpoint }`], `None` on the
/// three sibling arms ([`Self::PubSub`] / [`Self::Store`] /
/// [`Self::Capability`], each of which carries no HTTP endpoint by
/// definition).
///
/// The [`Self::Http`] arm carries the Cilium L7 `HTTPNetworkPolicy`
/// `path:` rule payload every substrate-side L7-introspecting
/// per-`(:de, :para)` `CiliumNetworkPolicy` emitter reads (today: the
/// [`caixa_mesh::cilium_network_policies`] per-edge `toPorts[].rules
/// .http[0].path` scalar the HTTP-shape-only L7 rule builder emits
/// on the L7 introspection branch; every peer WIT shape stays
/// L4-only because Cilium can't introspect NATS / key-value / plain
/// capability edges), and every future L7-introspecting consumer
/// of the projected target's HTTP endpoint (the future M4
/// per-`(:de, :para)` `mesh.pleme.io/v1alpha1/Aplicacao` CR
/// materializer's per-edge L7 admission-webhook overlay, the
/// future Envoy-side `local_rate_limit.descriptor_entries` per-HTTP-
/// path bucket-key resolver, the future per-`:contratos`-edge
/// mTLS-required overlay's HTTP-shape scope filter, the future
/// `feira app graph --l7` per-Aplicacao HTTP-path column) reaches
/// through the same typed dispatch.
///
/// Prior to this lift the sole production consumer of the projected-
/// target HTTP endpoint — the [`caixa_mesh::cilium_network_policies`]
/// per-edge L7 introspection branch at `caixa-mesh/src/lib.rs:2759`
/// (`if let WitTarget::Http { endpoint } = c.target().expect(…) {
/// http_rule.insert_string(CILIUM_KEY_PATH, endpoint.to_string()); …
/// }`) — reached the payload through a raw per-arm `if let` pattern-
/// match that expressed no compile-time link back to the substrate
/// primitive's typed dispatch, sibling to the [`WitContract`] pre-
/// projection [`WitContract::endpoint`] (7020470) `Option<&str>`
/// scalar accessor on the peer per-`:contratos` raw-field axis but
/// with no post-projection peer on the typed-view surface. A future
/// [`WitTarget`] variant addition that splits [`Self::Http`] into
/// peers (a `Rest`/`Grpc` split once the WIT registry stabilizes
/// gRPC-shaped worlds per this enum's own docstring at
/// aplicacao.rs:1341-1343 — with a `Rest`-arm `endpoint: &'a str`
/// payload alongside a `Grpc`-arm `service_method: &'a str` payload)
/// would have had to be threaded through the caixa-mesh L7 emit
/// branch's raw `if let` in lockstep — either coalescing the two
/// L7-HTTP-family arms under a shared `path:` emit, or splitting the
/// emit path per-arm — with no substrate-primitive dispatch making
/// the "which arms count as L7-HTTP-shaped for path-emission
/// purposes" question the substrate's answer to give. Lifting the
/// resolution to a typed method on the substrate primitive means
/// every downstream L7-HTTP-facing consumer of the Aplicacao's
/// projected-target HTTP endpoint reaches for exactly one typed
/// dispatch — the resolver's accept-set migrates as a unit on any
/// future arm-family widening, and the caixa-mesh L7 emit branch
/// reads through the same substrate primitive.
///
/// Peer of the sibling pre-projection [`WitContract::endpoint`]
/// (7020470) `Option<&str>` scalar accessor on the raw
/// `:contratos :endpoint` field-access axis — same "one typed
/// dispatch on the substrate primitive, thin projections at each
/// consumer" discipline extended onto the peer post-projection typed-
/// view surface (the [`WitContract::endpoint`] pre-projection
/// accessor returns `Some` for any author-declared `:endpoint`
/// value regardless of the paired `:wit` world's HTTP-shape
/// classification — the raw slot before validation crosses it —
/// while this post-projection [`Self::http_endpoint`] accessor
/// returns `Some` iff the target has been projected onto the
/// [`Self::Http`] arm, i.e. only after the [`WitContract::target`]
/// gate has admitted the `(:wit, :endpoint/:subject/:slot)` shape
/// coherence; the two accessors close the pre-projection /
/// post-projection pair on the HTTP-endpoint axis). Sibling of the
/// unified pan-arm [`Self::payload`] (`Option<&'a str>` for any of
/// the three payload-carrying arms) — extends the per-arm
/// projection family onto the [`Self::Http`] specialization axis
/// that the pan-arm accessor's shape blends into a single arm-
/// agnostic view; paired with [`Self::pubsub_subject`] /
/// [`Self::store_slot`] on the sibling per-arm axes so every
/// per-payload-arm shape carries a named post-projection accessor
/// on the same shape as `http_endpoint`, closing the per-arm-shape
/// accept-set the substrate primitive owns.
#[must_use]
pub const fn http_endpoint(&self) -> Option<&'a str> {
match *self {
WitTarget::Http { endpoint } => Some(endpoint),
WitTarget::PubSub { .. } | WitTarget::Store { .. } | WitTarget::Capability => None,
}
}
/// Substrate-canonical per-arm pub-sub-subject scalar accessor every
/// consumer that fans on the pub-sub-shaped payload keys off —
/// returns the [`Self::PubSub`]-arm's author-declared event-stream
/// subject verbatim as an `Option<&'a str>`, `Some(subject)` when
/// the projected target is [`Self::PubSub { subject }`], `None` on
/// the three sibling arms ([`Self::Http`] / [`Self::Store`] /
/// [`Self::Capability`], each of which carries no NATS-shaped
/// subject by definition).
///
/// The [`Self::PubSub`] arm carries the NATS-server-accepted subject
/// the future substrate-side pub-sub-introspecting per-`(:de, :para)`
/// consumer keys off (the M4 per-Aplicacao NATS `Stream` / `Consumer`
/// CR materializer's `spec.subjects[]` projection, the future
/// Envoy-side per-subject `local_rate_limit.descriptor_entries`
/// bucket-key resolver, the future `feira app graph --pubsub`
/// per-Aplicacao subject column, any future substrate-lifted
/// pub-sub-shape emitter that reads a projected `WitTarget` in the
/// same shape [`caixa_mesh::cilium_network_policies`] reads the
/// HTTP-shape one at `caixa-mesh/src/lib.rs:2780` today). Every
/// future pub-sub-shape consumer reaches for the same typed
/// dispatch this accessor exposes so the "which arm carries the
/// subject scalar?" answer lives at one caixa-core edit rather
/// than open-coded across per-consumer `if let WitTarget::PubSub
/// { subject } = c.target()…` pattern-matches.
///
/// Peer of the sibling [`Self::http_endpoint`] (5d6dc92 trajectory)
/// per-arm HTTP-endpoint accessor on the peer per-arm axis and of
/// the pre-projection [`WitContract::subject`] scalar accessor on
/// the raw `:contratos :subject` field-access axis — same "one
/// typed dispatch on the substrate primitive, thin projections at
/// each consumer" discipline extended onto the per-arm pub-sub
/// post-projection axis. The pre-projection accessor returns
/// `Some` for any author-declared `:subject` value regardless of
/// the paired `:wit` world's pub-sub-shape classification (the raw
/// slot before validation crosses it); this post-projection
/// accessor returns `Some` iff the target has been projected onto
/// the [`Self::PubSub`] arm, i.e. only after the
/// [`WitContract::target`] gate has admitted the
/// `(:wit, :endpoint/:subject/:slot)` shape coherence — closing
/// the pre-/post-projection pair on the pub-sub-subject axis to
/// match the pair the [`WitContract::endpoint`] +
/// [`Self::http_endpoint`] surfaces already close on the peer
/// HTTP-endpoint axis.
///
/// Sibling of the unified pan-arm [`Self::payload`]
/// (`Option<&'a str>` for any of the three payload-carrying arms) —
/// extends the per-arm projection family onto the [`Self::PubSub`]
/// specialization axis that the pan-arm accessor's shape blends
/// into a single arm-agnostic view; the pair
/// (`pubsub_subject`, `store_slot`) closes the trio
/// (`http_endpoint`, `pubsub_subject`, `store_slot`) so every
/// payload arm now carries its own per-arm-shape post-projection
/// accessor.
#[must_use]
pub const fn pubsub_subject(&self) -> Option<&'a str> {
match *self {
WitTarget::PubSub { subject } => Some(subject),
WitTarget::Http { .. } | WitTarget::Store { .. } | WitTarget::Capability => None,
}
}
/// Substrate-canonical per-arm key/value-store-slot scalar accessor
/// every consumer that fans on the store-shaped payload keys off —
/// returns the [`Self::Store`]-arm's author-declared slot template
/// verbatim as an `Option<&'a str>`, `Some(slot)` when the
/// projected target is [`Self::Store { slot }`], `None` on the
/// three sibling arms ([`Self::Http`] / [`Self::PubSub`] /
/// [`Self::Capability`], each of which carries no
/// key/value-store slot by definition).
///
/// The [`Self::Store`] arm carries the WASI-key/value-accepted slot
/// template (validated by [`crate::render::is_wasi_keyvalue_slot`])
/// every future substrate-side store-introspecting per-`(:de,
/// :para)` consumer keys off (the M4 per-Aplicacao WASI-key/value
/// namespace / prefix reconciler's per-slot projection, the future
/// per-store-backend routing overlay's slot-shape gate, the future
/// `feira app graph --store` per-Aplicacao slot column, any future
/// substrate-lifted store-shape emitter that reads a projected
/// `WitTarget` in the same shape [`caixa_mesh::cilium_network_policies`]
/// reads the HTTP-shape one at `caixa-mesh/src/lib.rs:2780` today).
/// Every future store-shape consumer reaches for the same typed
/// dispatch this accessor exposes so the "which arm carries the
/// slot scalar?" answer lives at one caixa-core edit rather than
/// open-coded across per-consumer
/// `if let WitTarget::Store { slot } = c.target()…`
/// pattern-matches.
///
/// Peer of the sibling [`Self::http_endpoint`] +
/// [`Self::pubsub_subject`] per-arm accessors on the peer per-arm
/// axes and of the pre-projection [`WitContract::slot`] scalar
/// accessor on the raw `:contratos :slot` field-access axis — same
/// "one typed dispatch on the substrate primitive, thin projections
/// at each consumer" discipline extended onto the per-arm store
/// post-projection axis. Closes the pre-/post-projection pair on
/// the store-slot axis to match the pairs the
/// [`WitContract::endpoint`] + [`Self::http_endpoint`] and
/// [`WitContract::subject`] + [`Self::pubsub_subject`] surfaces
/// already close on the peer HTTP-endpoint and pub-sub-subject
/// axes; the substrate-side pre-/post-projection accessor family
/// now spans all three payload arms as a matched trio, so any
/// future arm-shape widening (a `Rest`/`Grpc` split of
/// [`Self::Http`], a `Queue`-shaped peer of [`Self::Store`]) that
/// lands one accessor without threading through the sibling
/// pre-projection or the peer per-arm post-projection surfaces a
/// compile-time exhaustiveness error at the substrate primitive,
/// not a silent per-consumer split at renderer emit time.
///
/// Sibling of the unified pan-arm [`Self::payload`]
/// (`Option<&'a str>` for any of the three payload-carrying arms) —
/// closes the per-arm projection family onto the [`Self::Store`]
/// specialization axis that the pan-arm accessor's shape blends
/// into a single arm-agnostic view. The trio
/// (`http_endpoint`, `pubsub_subject`, `store_slot`) partitions the
/// pan-arm accept-set on every payload-carrying arm: exactly one
/// per-arm accessor returns `Some(payload)` and the two peers
/// return `None`, and every payload-less [`Self::Capability`]
/// input returns `None` on all three — the partition the sibling
/// `wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set`
/// pin locks in load-bearing.
#[must_use]
pub const fn store_slot(&self) -> Option<&'a str> {
match *self {
WitTarget::Store { slot } => Some(slot),
WitTarget::Http { .. } | WitTarget::PubSub { .. } | WitTarget::Capability => None,
}
}
/// Render this typed target as a stable human-readable label
/// (`:endpoint "/charge"`, `:subject "events.x"`,
/// `:slot "checkout/$order"`, or `(capability — no payload)` when
/// the WIT world is a pure capability edge).
///
/// Used by the [`AplicacaoSpec::validate`] duplicate-`:contratos`
/// gate so the diagnostic names *which* identical edge was
/// declared twice (not just which `(de, para, wit)` triple).
/// Routes through the single 4-arm [`Self::payload_pair`] dispatch
/// on the payload-carrying arms (`Some((field, payload)) →
/// format!(":{field} {payload:?}")`) and through the lifted
/// [`Self::CAPABILITY_LABEL`] const on the payload-less
/// [`Self::Capability`] arm — so a future variant addition (the
/// M4-and-later per-edge WIT registry may split [`Self::Http`]
/// into `Rest` / `Grpc`, or extend [`Self::Store`] with a
/// `Queue`-shaped peer) becomes a single new match-arm on
/// [`Self::payload_pair`] rather than a rewrite of this template
/// (and every downstream consumer that reaches for the label
/// shape: the per-edge policy resolver in M4, the `feira app
/// graph` view, the operator's mesh-graph audit). Until this
/// lift landed the three payload arms carried three near-identical
/// per-arm `format!(":{} {…:?}", …)` invocations, and the
/// [`Self::Capability`] arm carried the payload-less byte-string
/// twice (once inline here, once in the pin test) — closing the
/// duplication trajectory the peer [`Self::HTTP_FIELD_NAME`] /
/// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`] (174e96a
/// / 4a1e490) peer-const lifts already established for the
/// payload-carrying arms.
#[must_use]
pub fn label(&self) -> String {
match self.payload_pair() {
Some((field, payload)) => format!(":{field} {payload:?}"),
None => Self::CAPABILITY_LABEL.to_string(),
}
}
/// Render this typed target as the `feira app graph` per-`:contratos`
/// payload-column byte-string (`endpoint=/charge`, `subject=events.x`,
/// `slot=checkout/$order`, or [`Self::CAPABILITY_GRAPH_LABEL`] on the
/// payload-less arm).
///
/// Routes through the single 4-arm [`Self::payload_pair`] dispatch
/// on the payload-carrying arms (`Some((field, payload)) →
/// format!("{field}={payload}")`) and through the lifted
/// [`Self::CAPABILITY_GRAPH_LABEL`] const on the payload-less
/// [`Self::Capability`] arm — so a future variant addition
/// (the M4-and-later per-edge WIT registry may split [`Self::Http`]
/// into `Rest` / `Grpc`, or extend [`Self::Store`] with a
/// `Queue`-shaped peer) becomes one match-arm edit at
/// [`Self::payload_pair`], propagating through this graph-verb
/// projection at zero call-site cost, sibling to the peer
/// [`Self::label`] duplicate-`:contratos` diagnostic emission on the
/// same 4-arm dispatch.
///
/// Until this lift landed the [`caixa-feira`]
/// `cmd::app::GraphArgs::run` per-`:contratos` payload column
/// (`caixa-feira/src/cmd/app.rs:101-112`) hand-rolled the same 4-arm
/// dispatch inline, re-projecting `HTTP_FIELD_NAME` /
/// `PUBSUB_FIELD_NAME` / `STORE_FIELD_NAME` under a per-arm
/// `format!("{}={endpoint}", ...)` template and hard-coding
/// `"(capability-only)"` as a fifth payload-less scalar with no link
/// back to the paired [`WitTarget::Capability`] variant declaration.
/// A future variant addition would have had to be threaded through
/// both [`Self::label`] (via [`Self::payload_pair`]) *and* the graph
/// verb's inline match in lockstep or the two projections would
/// silently disagree on the arm-set the graph verb prints — the
/// duplicate-`:contratos` diagnostic reading one shape while the
/// graph verb's payload column silently dropped the new arm to
/// `(capability-only)`. Lifting the graph-verb projection onto the
/// same substrate-primitive [`Self::payload_pair`] dispatch closes
/// the axis: both projections migrate as a unit.
///
/// The `field=payload` (no colon prefix, `=` separator, no `Debug`
/// quoting) shape is graph-verb-canonical — distinct from the
/// sibling [`Self::label`] `":{field} {payload:?}"` shape the
/// duplicate-`:contratos` diagnostic seeds (see
/// [`Self::CAPABILITY_LABEL`] vs. [`Self::CAPABILITY_GRAPH_LABEL`]
/// on the payload-less axis for the paired distinction).
#[must_use]
pub fn graph_label(&self) -> String {
match self.payload_pair() {
Some((field, payload)) => format!("{field}={payload}"),
None => Self::CAPABILITY_GRAPH_LABEL.to_string(),
}
}
}
/// [`std::fmt::Display`] routed through [`WitTarget::label`], so the
/// pretty-printed byte-string every consumer that formats a typed
/// payload target as user-facing text lands on (the
/// [`AplicacaoError::ContratoDuplicate`] diagnostic's `target:` carry
/// the [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds via
/// [`WitTarget::label`] at aplicacao.rs:5491, the future `feira app
/// graph` per-`:contratos`-edge payload column that reaches the graph
/// verb through `format!("{target}")`, the future M4 per-edge policy
/// resolver's per-edge audit-log line, the operator's mesh-graph
/// per-edge inspection view) reaches for the same lifted
/// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`] /
/// [`WitTarget::STORE_FIELD_NAME`] / [`WitTarget::CAPABILITY_LABEL`]
/// const set the [`WitTarget::payload_pair`] 4-arm dispatch already
/// routes through — extending the three-path-convergence
/// (`Debug` for structural inspection, `Display` for user-facing text,
/// per-arm typed accessor for the canonical byte-string) discipline the
/// sibling M3 [`PlacementStrategy`] and M2 [`crate::supervisor::RestartStrategy`]
/// / [`crate::supervisor::RestartPolicy`] OTP-shape typed enums carry
/// onto the fourth (and only remaining) typed-shape-discriminator axis
/// on the caixa surface.
///
/// Pre-lift the two paths were structurally independent — every consumer
/// reaching for a payload byte-string past the [`WitTarget::label`]
/// helper had to pick between three paths ([`WitTarget::label`],
/// `format!("{v:?}")` on the `Debug` derive, hand-rolled per-arm
/// formatting through the [`WitTarget::HTTP_FIELD_NAME`] /
/// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`] /
/// [`WitTarget::CAPABILITY_LABEL`] const set), and a future consumer
/// that reached for `format!("{target}")` — the canonical shape every
/// user-facing pretty-print site on the sibling typed-enum axes already
/// uses — would silently land on the `Debug` derive's structural output
/// (`Http { endpoint: "/charge" }` — Rust struct-literal syntax) rather
/// than the `label()` helper's stable byte-string (`:endpoint
/// "/charge"` — the author-facing `:contratos` keyword form) the
/// substrate-side duplicate-`:contratos` gate at aplicacao.rs:5491
/// already threads through. The two spellings would diverge silently in
/// every downstream diagnostic / graph / audit line reached through
/// `format!` rather than through the `label()` helper. Routing
/// [`std::fmt::Display`] through [`WitTarget::label`] closes the third
/// path: every `format!("{v}")` call reaches the same
/// [`WitTarget::payload_pair`]-shaped byte-string the `label()` helper
/// and the duplicate-`:contratos` gate already route through, so a
/// future variant addition (the M4-and-later per-edge WIT registry may
/// split [`WitTarget::Http`] into `Rest` / `Grpc` peers, or extend
/// [`WitTarget::Store`] with a `Queue`-shaped peer) reaches every
/// consumer at exactly one place — the [`WitTarget::payload_pair`]
/// match — rather than fanning out through hand-rolled per-arm
/// [`std::fmt::Display`] arms.
///
/// The dispatcher-catalog identity remains unaffected — [`WitTarget`]
/// is the typed view returned by [`WitContract::target`], not a
/// closed-set discriminator enum with a gen-platform Discriminant
/// registration, so the `Debug` derive's structural output (which every
/// `{v:?}` consumer still reaches) stays distinct from the `Display`
/// helper's stable pretty-printed byte-string. `Debug` reveals variant
/// shape for structural inspection; `Display` (via `label`) reveals the
/// stable author-facing payload projection.
///
/// Pin tests
/// [`tests::wit_target_display_routes_through_label_helper`] and
/// [`tests::wit_target_display_matches_duplicate_contratos_diagnostic_carrier`]
/// assert the two paths agree byte-for-byte on every variant, so a
/// future variant addition or `label()` reimplementation that hand-rolls
/// the arms instead of delegating to [`WitTarget::payload_pair`] is a
/// build error visible at caixa-core test time, not a silent
/// per-consumer dispatch miss at diagnostic / audit / graph time.
impl std::fmt::Display for WitTarget<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.label())
}
}
// ── one Aplicacao member ─────────────────────────────────────────────
/// A Servico participating in the Aplicacao. Same shape as
/// `crate::supervisor::ChildSpec` but without a restart policy —
/// supervision is per-Servico (each member has its own
/// `:supervisor`), the Aplicacao orchestrates *placement*.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct Membro {
/// Member caixa's `:nome`. Resolves through the same dep
/// resolution path as `crate::dep::Dep`.
pub caixa: String,
/// Semver constraint.
pub versao: String,
}
impl Membro {
/// Substrate-canonical per-`:membros` member-caixa `:nome` scalar
/// accessor every consumer that reads the member's Servico identity
/// keys off — returns the author-declared `:membros :caixa`
/// byte-string verbatim as a `&str`, borrowed from the typed slot's
/// own [`String`] storage.
///
/// The `:membros :caixa` slot carries the caixa `:nome` of a Servico
/// participating in the Aplicacao — validated by
/// [`AplicacaoSpec::validate`] to be a non-empty DNS-1123 label
/// (via [`validate_membro_caixa`]), unique across the Aplicacao's
/// `:membros` list, distinct from the Aplicacao's own `:nome` (via
/// [`validate_no_self_membership`]) — and every downstream consumer
/// that fans on the member's identity keys off this scalar (the
/// [`AplicacaoSpec::validate`] `:contratos`/`:entrada` member-set
/// lookup, the per-`:membros` duplicate gate's dedup key, the
/// [`AplicacaoSpec::detect_sync_cycles`] adjacency map's node
/// identity, the self-membership gate, the
/// [`caixa_mesh::fleet_programs`] per-member programs.yaml entry
/// `name:` axis, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
/// CR materializer's per-member resolver).
///
/// Prior to this lift the `.caixa` byte-string was read inline at
/// five caixa-core sites (the [`AplicacaoSpec::validate`] member-name
/// set collector at
/// `self.membros.iter().map(|m| m.caixa.as_str())`, the
/// [`validate_membros`] validation-side member-caixa gate at
/// `validate_membro_caixa(&m.caixa)`, the [`validate_membros`]
/// per-member duplicate-gate dedup key at
/// `insert_first_seen(&mut seen, m.caixa.as_str(), …)`, the
/// [`AplicacaoSpec::detect_sync_cycles`] adjacency-map seed at
/// `adj.entry(m.caixa.as_str()).or_default()`, and the
/// [`validate_no_self_membership`] self-loop gate at
/// `m.caixa == parent_nome`) — five open-coded field-accesses that
/// expressed no compile-time link back to the typed slot. Every
/// caixa-mesh `metadata.name` derived from a `:membros :caixa`
/// value flows through the [`caixa_mesh::fleet_programs`] per-entry
/// `name:` axis, so a future extension of the `:membros :caixa`
/// axis to a richer author surface — a per-cluster alias table the
/// operator pins through a future `:placement`-scoped slot, a
/// namespace-qualified rewrite the M4 CR materializer applies
/// per-CR, a per-member overlay from the future `:membros
/// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
/// acknowledges — would have had to be threaded through every
/// open-coded copy in lockstep or one consumer would silently
/// disagree with the peers on which caixa a given member resolves
/// to. A member-set lookup that treated the name as `"cart"` while
/// the peer adjacency map treated it as `"tenant-a/cart"` would
/// silently split the `:contratos` membership-lookup diagnostic from
/// the cycle-detector's node identity — a two-consumer split at the
/// validator far from the source `caixa.lisp` with no field naming
/// the identity-drift root cause. Lifting the resolution rule to a
/// typed method on the substrate primitive means every downstream
/// consumer of the Aplicacao's per-`:membros` identity surface
/// reaches for exactly one typed dispatch — the resolver's
/// accept-set migrates as a unit on any future axis addition.
///
/// Peer of the sibling per-`:contratos` [`WitContract::source`] /
/// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
/// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
/// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
/// destination-Servico scalar accessors — same "one typed dispatch
/// on the substrate primitive, thin projections at each consumer"
/// discipline extended onto the per-`:membros` member-caixa `:nome`
/// byte-string axis. Named `nome()` to match the tatara-lisp
/// author-surface term the field's docstring already reaches for
/// ("Member caixa's `:nome`") and the peer [`crate::Caixa::nome`] /
/// [`crate::dep::Dep::nome`] field-name discipline the substrate
/// already carries — the accessor's name maps directly onto the
/// canonical caixa-identity vocabulary rather than shadowing the
/// field's storage-side `caixa` label.
#[must_use]
pub const fn nome(&self) -> &str {
self.caixa.as_str()
}
/// Substrate-canonical per-`:membros` member-caixa `:versao` semver-
/// requirement scalar accessor every consumer that reads the
/// member's version pin keys off — returns the author-declared
/// `:membros :versao` byte-string verbatim as a `&str`, borrowed
/// from the typed slot's own [`String`] storage.
///
/// The `:membros :versao` slot carries the Cargo-shaped semver
/// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that
/// pins which release of the member-caixa the Aplicacao composes
/// against — the same requirement grammar the peer `:deps :versao`
/// / `:children :versao` axes carry, resolved through the shared
/// [`crate::render::require_valid_versao_requirement`] cascade and
/// the shared [`crate::version::parse_requirement`] parser. Every
/// downstream consumer that fans on the member's version pin keys
/// off this scalar (the [`validate_membros`] per-member requirement
/// gate at `require_valid_versao_requirement(m.versao_requirement(),
/// …)`, the [`feira app graph`] per-member `println!(" - {} {}",
/// m.nome(), m.versao_requirement())` line, every future per-cluster
/// version-lock overlay the operator pins through a future
/// `:placement`-scoped slot, the future
/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-member
/// version resolver, the future `feira app deploy` pipeline's
/// per-member lacre BLAKE3-closure lookup).
///
/// Prior to this lift the `.versao` byte-string was accessed inline
/// at two `&str`-shaped sites — the [`validate_membros`]
/// requirement-gate call `require_valid_versao_requirement(&m.versao,
/// …)` and the `feira app graph` per-member printer's `println!(
/// " - {} {}", m.caixa, m.versao)` (caixa-feira/src/cmd/app.rs:78
/// prior to this lift) — two open-coded field-accesses that expressed
/// no compile-time link back to the typed slot. A future extension of
/// the `:membros :versao` axis to a richer author surface (a
/// per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
/// flow, a lacre-projected concrete-version rewrite the operator
/// materializes at CR-admission time, a future `:membros :versao-lock`
/// per-cluster override slot) would have had to be threaded through
/// every open-coded copy in lockstep or one consumer would silently
/// disagree with the peers on which release constraint a given
/// member resolves to. Lifting the resolution rule to a typed method
/// on the substrate primitive means every downstream requirement-
/// facing consumer reaches for exactly one typed dispatch — the
/// resolver's accept-set migrates as a unit on any future axis
/// addition.
///
/// Sibling of the peer per-`:membros` [`Membro::nome`] (4a32abf)
/// member-caixa `:nome` scalar accessor — the pair
/// `(nome(), versao_requirement())` jointly projects the
/// `(caixa, versao)` field pair every renderer that fans on
/// per-member identity + version pin keys off, closing the last
/// unlifted per-`:membros` scalar axis so every downstream
/// per-`:membros` reader now routes through a typed dispatch on the
/// substrate primitive. Named `versao_requirement()` rather than
/// `versao()` because the field's storage-side `.versao` label is
/// already the author-surface term (`:versao`); the accessor's name
/// carries the semantic role — the semver *requirement* string the
/// shared [`crate::version::parse_requirement`] entry-point consumes
/// — so a raw field access and a typed dispatch read differently at
/// every consumer site.
///
/// Peer of the sibling per-`:contratos` [`WitContract::source`] /
/// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
/// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
/// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
/// destination-Servico scalar accessors — same "one typed dispatch
/// on the substrate primitive, thin projections at each consumer"
/// discipline extended onto the per-`:membros` member-`:versao`
/// semver-requirement byte-string axis.
#[must_use]
pub const fn versao_requirement(&self) -> &str {
self.versao.as_str()
}
}
// ── mesh-level policies ──────────────────────────────────────────────
/// Mesh policies that apply to every `:contratos` edge unless
/// overridden per-edge in M4. V0 is a single global policy block.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct MeshPolicy {
/// Per-call timeout. Authored as a duration string (`"30s"`).
#[serde(
default,
skip_serializing_if = "Option::is_none",
with = "supervisor::duration_codec"
)]
pub timeout: Option<Duration>,
/// Number of retries on transient failure. None = no retries.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub retries: Option<u32>,
/// Circuit breaker config. Trips after N failures within W
/// duration; closes after a cooldown.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub circuit_breaker: Option<CircuitBreaker>,
/// Whether mTLS is required for every contrato. Default: true
/// (sandboxing-by-default; explicit opt-out only).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub mtls_required: Option<bool>,
/// Token-bucket rate limit. Authored as `"100/s"` or
/// `"5000/m"`; stored as `(rate, window)`.
#[serde(
default,
skip_serializing_if = "Option::is_none",
with = "rate_limit_codec"
)]
pub rate_limit: Option<RateLimit>,
}
/// Route the derived-style [`Default`] impl on [`MeshPolicy`] through
/// the substrate-canonical [`MeshPolicy::empty`] `pub const fn`
/// constructor rather than the derive-generated per-field
/// `<Option<_> as Default>::default` cascade — one source of truth for
/// the "canonical unset per-`:politicas` slot" shape across the two
/// paths every downstream consumer already reaches through (the
/// derived-until-now [`Default::default`] the `..Default::default()`
/// struct-update-syntax on every one-axis-under-test fixture in this
/// crate's test module rests on, and the `pub const fn`
/// [`MeshPolicy::empty`] constructor every `const`-context consumer
/// reaches through).
///
/// Prior to this fold the two paths were byte-equal by *coincidence*
/// under the pinning test
/// [`tests::mesh_policy_empty_byte_equals_default`] rather than
/// byte-equal by *construction* — the derive-generated
/// [`Default::default`] resolved each `Option<_>` field through its
/// own `<Option<_> as Default>::default` (which returns `None`) and
/// the lifted `pub const fn` [`MeshPolicy::empty`] named the same five
/// `None` arms verbatim in its struct-literal. Two hand-authored (or
/// derive-authored) sources of the same "canonical unset baseline"
/// shape on the same primitive is exactly the substrate-canonical-
/// source-of-truth duplication the [`crate::LimitsSpec::empty`]
/// (9739971) / [`MeshPolicy::empty`] (6df969b) /
/// [`crate::BehaviorSpec::empty`] (f9b18e3) lifts closed on the
/// forward `const`-context path — extending the same discipline onto
/// the paired [`Default`] impl means every consumer of the derived-
/// until-now [`Default::default`] surface (every `..Default::default()`
/// struct-update-syntax fixture in this crate's test module — the
/// five per-axis-only pins at [`tests::mesh_policy_with_only_timeout_is_not_empty`],
/// [`tests::mesh_policy_with_only_retries_is_not_empty`],
/// [`tests::mesh_policy_with_only_circuit_breaker_is_not_empty`],
/// [`tests::mesh_policy_with_only_mtls_required_is_not_empty`],
/// [`tests::mesh_policy_with_only_rate_limit_is_not_empty`] — and the
/// entry pin at [`tests::mesh_policy_default_is_empty`], the future
/// M4 per-edge `:politicas` overlay CR materializer's admission-time
/// default-overlay-emit gate, every future `..Default::default()`
/// struct-update-syntax fixture-builder arm) also routes through the
/// substrate primitive's single source of truth.
///
/// A future extension of the `:politicas` axis set (a per-edge
/// `:politicas` overlay the M4 roadmap grows once per-`:contratos`-
/// edge overrides land, a sixth `:politicas` sub-slot the roadmap
/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
/// grows past the five-arm Envoy/Cilium-shape §III.2 axis set)
/// reaches this impl's return value through exactly one edit on
/// [`MeshPolicy::empty`] — the derived path could silently disagree
/// with the constructor's shape on any new field whose
/// `Default::default` is not `None` (a future non-`Option<_>` field
/// with a non-`Default::default`-equivalent baseline, a `Vec<_>` field
/// defaulting to an empty vector, an enum arm-carrying field with a
/// non-`Default::default` canonical unset arm), while this delegated
/// impl reaches the constructor directly and picks up every future
/// extension by construction.
///
/// Direct peer of [`crate::LimitsSpec`]'s
/// [`Default`]-through-[`crate::LimitsSpec::empty`] fold (abd52c2) on
/// the M2 `:limits` typed slot — same "one source of truth for the
/// canonical unset baseline" discipline extended onto the M3
/// `:politicas` typed slot. The sibling [`crate::BehaviorSpec`] impl
/// on the M2 `:behavior` slot is the third and last established
/// candidate for the same delegation fold once the per-slot peer pin
/// on this axis lands in a future run. Pinned load-bearing by
/// [`tests::mesh_policy_default_routes_through_empty_ctor`]
/// (byte-parity pin against [`MeshPolicy::empty`] under `PartialEq`,
/// sharpening the pre-existing
/// [`tests::mesh_policy_empty_byte_equals_default`] pin from a "two
/// paths byte-equal by coincidence" invariant into a "two paths
/// byte-equal by construction — one delegates to the other" invariant)
/// and by [`tests::mesh_policy_empty_validates_ok`] (the canonical
/// unset baseline must pass [`MeshPolicy::validate`] — every per-axis
/// value-shape gate is `if let Some(_)` guarded and every cross-axis
/// arm on [`MeshPolicy::first_cross_axis_violation`] is a
/// `let (Some(_), Some(_))` pattern, so an all-`None` input
/// structurally short-circuits every arm; the pin makes the invariant
/// load-bearing so a future extension that adds a non-`Option`-guarded
/// gate to [`MeshPolicy::validate`] trips at caixa-core test time
/// rather than at a downstream consumer that composed
/// [`MeshPolicy::default`]/[`MeshPolicy::empty`] with
/// [`MeshPolicy::validate`] as its "no-op axis short-circuit").
impl Default for MeshPolicy {
#[inline]
fn default() -> Self {
Self::empty()
}
}
impl MeshPolicy {
/// Substrate-canonical `const`-context peer of the derived
/// [`Default::default`] on [`MeshPolicy`] — returns the fully-empty
/// per-`:politicas` slot (every one of the five `Option<_>`-carrying
/// per-axis fields set to `None`), materializable at `const`-eval
/// time.
///
/// Named `empty()` (not `default()` / `new()`) to match the sibling
/// `is_empty()` predicate on the same primitive: the pair
/// (`empty()` / `is_empty()`) forms the round-trip discipline
/// `MeshPolicy::empty().is_empty() == true` the pin
/// [`tests::mesh_policy_empty_is_the_all_none_arm_and_is_empty`]
/// locks load-bearing, and every `const`-context consumer that
/// wants a canonical unset baseline reads through this constructor
/// rather than the derived (non-`const`) [`Default::default`] or
/// the five-field struct-literal `MeshPolicy { timeout: None,
/// retries: None, circuit_breaker: None, mtls_required: None,
/// rate_limit: None }` open-coded per-site.
///
/// Direct peer of [`crate::LimitsSpec::empty`] (9739971) on the
/// M2 `:limits` typed slot — same "`const`-context peer of the
/// derived non-`const` [`Default::default`]" discipline extended
/// onto the M3 `:politicas` typed slot. The two lifted `pub const
/// fn` constructors together now cover the two per-slot
/// [`Default`]-carrying M2/M3 typed slots that also carry an
/// `is_empty()` emptiness predicate: every `const`-context consumer
/// of a canonical unset per-slot baseline reads through the same
/// paired-`(empty(), is_empty())` shape on either slot without a
/// runtime dispatch on the derived [`Default::default`].
///
/// Prior to this lift the "canonical unset [`MeshPolicy`]" shape
/// was reached through one of two paths — the derived
/// [`Default::default`] (`fn`, not `const fn` — a downstream
/// `const _: MeshPolicy = MeshPolicy::default();` cannot compile
/// because [`Default::default`] is not `const`-stable on stable
/// Rust; the tracking issue on `const Default` still blocks the
/// promotion) or an open-coded struct-literal with five `None`
/// arms threaded verbatim at every call site (the five
/// `MeshPolicy { timeout: Some(_), ..Default::default() }` /
/// `MeshPolicy { retries: Some(_), ..Default::default() }` /
/// sibling per-axis-only fixtures in this crate's own test module
/// each rest on `..Default::default()` for the four peer arms; a
/// future axis addition silently drifts the fixture's intent from
/// "one axis under test, the other four unset" to "one axis under
/// test, N axes unset, one field forgotten"). A future extension
/// of the axis (a per-edge `:politicas` overlay the M4 roadmap
/// grows once per-`:contratos`-edge overrides land, a sixth
/// `:politicas` sub-slot the roadmap
/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
/// grows past the five-arm Envoy/Cilium-shape §III.2 axis set)
/// reaches this constructor at one edit (one added struct field
/// on the type + one added `<axis>: None` line here) rather than
/// a coordinated rewrite of every open-coded struct-literal at
/// every downstream consumer.
///
/// `pub const fn` — matches the sibling
/// [`MeshPolicy::is_empty`] `pub const fn` shape verbatim, so
/// every downstream consumer that folds a canonical unset
/// baseline into a `const` position (a `const EMPTY: MeshPolicy =
/// MeshPolicy::empty();` module-scope binding a future per-edge
/// `:politicas` overlay reads through as its "no override
/// declared" arm, a compile-time per-fixture-builder default the
/// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
/// admission-time default-overlay-emit gate consults, a
/// compile-time lookup table the LSP hover renderer materializes
/// per typed-slot fixture) reads through one `const` dispatch
/// rather than being forced onto the runtime code path. Pinned
/// load-bearing at the substrate-primitive level by
/// [`tests::mesh_policy_empty_is_the_all_none_arm_and_is_empty`]
/// (round-trip pin against [`Self::is_empty`]),
/// [`tests::mesh_policy_empty_byte_equals_default`] (byte-parity
/// pin against the derived [`Default::default`]), and
/// [`tests::mesh_policy_empty_ctor_is_const_fn`] (const-eval-surface
/// pin via `const` binding — any future accidental downgrade to
/// `pub fn` fires E0015 at the binding at caixa-core build time,
/// strictly stronger than a runtime `assert!`).
#[must_use]
pub const fn empty() -> Self {
Self {
timeout: None,
retries: None,
circuit_breaker: None,
mtls_required: None,
rate_limit: None,
}
}
/// True when no `:politicas` axis carries a value — every field is
/// `None`. The same emptiness contract every other M2/M3 typed
/// surface carries ([`crate::LimitsSpec::is_empty`],
/// [`crate::BehaviorSpec::is_empty`]): renderers that overlay the
/// typed slot onto a cluster artifact key off this predicate to
/// decide "emit the slot" vs "skip the slot entirely", so an
/// authored-but-unset `:politicas (())` round-trips to a rendered
/// artifact that's structurally identical to one that omits the
/// slot. Lifted as a typed predicate (rather than per-renderer
/// inline `politicas.timeout.is_none() && politicas.retries.is_none()
/// && …` chains) so a future axis added to `MeshPolicy` (per-edge
/// :politicas overlay in M4, per-Aplicacao traffic-shaping in M5)
/// is one struct-field edit + one `&& self.<axis>.is_none()` here,
/// not a coordinated rewrite of every consumer that's reaching
/// for the emptiness semantic.
#[must_use]
pub const fn is_empty(&self) -> bool {
self.timeout().is_none()
&& self.retries().is_none()
&& self.circuit_breaker().is_none()
&& self.mtls_required().is_none()
&& self.rate_limit().is_none()
}
/// Substrate-canonical cross-axis coherence predicate on the
/// `:politicas` slot: does the `:circuit-breaker :window` rolling
/// failure-observation interval span at least one full
/// `:timeout`-bounded call?
///
/// The first *cross-axis* invariant on the `:politicas` surface —
/// every prior gate ([`AplicacaoSpec::validate_politicas`]'s four
/// zero-floor + canonical-form + cap brackets) validates one axis
/// in isolation, so a `MeshPolicy` whose axes are each individually
/// well-formed could still name a structurally inert pair. The
/// pair `{ timeout: 30s, circuit_breaker: { window: 10s, .. } }`
/// passes every per-axis bracket (30s ≤ [`POLICY_TIMEOUT_MAX`],
/// 10s ≤ [`POLICY_BREAKER_WINDOW_MAX`], both integer-millisecond,
/// both above the zero floor) and is nonetheless a breaker that
/// cannot trip on the failure mode it exists to catch: a call
/// dispatched at t=0 is declared failed at t=30s, by which point
/// the 10s window open at dispatch has rolled twice over, so no
/// window can ever hold even one timeout-derived failure however
/// high the call volume. Envoy's `outlier_detection.interval`
/// carries the identical relation against the per-route request
/// timeout; Hystrix ships the canonical ratio in its defaults
/// (10s `metrics.rollingStats.timeInMilliseconds` against a 1s
/// `execution.isolation.thread.timeoutInMilliseconds`).
///
/// Vacuously `true` when either axis is absent — a `:politicas`
/// that names only one of the pair declares no relation for the
/// substrate to hold it to (`:timeout` alone is a per-call deadline
/// with no breaker; `:circuit-breaker` alone is a breaker whose
/// failures arrive from the transport's own error signal rather
/// than from a substrate-imposed deadline, so no dispatch-to-report
/// lag is knowable at author time). This is the same
/// "unset means the cluster default applies, not zero" partition
/// [`MeshPolicy::is_empty`] and every per-axis accessor's `None`
/// arm already carry.
///
/// Lifted as a typed predicate on the substrate primitive rather
/// than open-coded at the validate gate so every downstream
/// consumer of the pair reaches the invariant through one dispatch:
/// the [`AplicacaoSpec::validate_politicas`] gate below, the future
/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
/// (MESH-COMPOSITION §III.2 #3) that must emit
/// `outlier_detection.interval` and the per-route `timeout` as one
/// coherent Envoy block, the future M4
/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
/// webhook, and the future per-`:contratos`-edge `:politicas`
/// override that same roadmap acknowledges — which resolves an
/// *effective* pair per edge (edge-level `:timeout` against the
/// Aplicacao-level `:window`, or vice versa) and so must re-check
/// the relation on a pair neither axis's declaration site can see
/// whole. Naming the invariant once means that resolver folds this
/// predicate over its resolved pair instead of re-deriving the
/// comparison, exactly as the sibling cross-slot
/// [`PlacementStrategy::is_shard_keyed`] predicate names the
/// `:placement`/`:shard-key` relation for its own consumers.
#[must_use]
pub const fn breaker_window_observes_timeout(&self) -> bool {
match (self.timeout(), self.circuit_breaker()) {
(Some(timeout), Some(cb)) => cb.window().as_nanos() >= timeout.as_nanos(),
_ => true,
}
}
/// Substrate-canonical cross-axis coherence predicate on the
/// `:politicas` slot: can the token-bucket rate declared by
/// `:rate-limit` dispatch enough calls inside `:circuit-breaker
/// :window` to reach `:max-failures`?
///
/// The second cross-axis invariant on the `:politicas` surface —
/// sibling to [`MeshPolicy::breaker_window_observes_timeout`] on
/// the `(:timeout, :circuit-breaker :window)` pair, extended onto
/// the `(:rate-limit, :circuit-breaker)` pair. Each axis in the
/// pair is validated in isolation by the per-axis brackets in
/// [`AplicacaoSpec::validate_politicas`] (rate zero-floor + cap,
/// max-failures zero-floor + cap, both windows zero-floor +
/// integer-millisecond + cap, rate-limit window canonical-form),
/// so a `MeshPolicy` whose axes are each individually well-formed
/// can still name a structurally inert pair. The pair
/// `{ rate-limit: "1/h", circuit-breaker: (:max-failures 5 :window
/// "10s") }` passes every per-axis bracket and is nonetheless a
/// breaker that cannot trip on the failure mode it exists to
/// catch: the token bucket admits `rate × (cb.window / rl.window)`
/// = `1 × (10s / 3600s)` ≈ 0 calls per rolling breaker window, so
/// no window can accumulate five failures however catastrophically
/// the upstream is failing. Envoy's
/// `outlier_detection.consecutive_5xx` paired against
/// `local_rate_limit.token_bucket.max_tokens` /
/// `fill_interval` carries the identical relation; every
/// production playbook that pairs the two axes (Envoy, Istio, AWS
/// App Mesh, Kong) recommends sizing the rate at or above the
/// breaker's minimum-request-volume threshold for exactly this
/// reason.
///
/// The typed test is the integer inequality
/// `rate × cb.window.as_nanos() >= max_failures × rl.window.as_nanos()`
/// (rearranged from `rate × cb.window / rl.window >= max_failures`
/// so no floating-point division mediates the comparison and so
/// the sub-second `rl.window` arms — `"n/s"` = 1s — are treated
/// exactly). Both multiplicands are `saturating_mul`'d into
/// [`u128`] so a struct-literal `MeshPolicy` whose per-axis fields
/// have not yet passed [`AplicacaoSpec::validate_politicas`]
/// (e.g. `rate: u32::MAX, cb_window: Duration::MAX`) does not
/// panic the predicate; a saturated pair collapses to the
/// "vacuously coherent" branch the peer per-axis brackets reject
/// via their own zero-floor / cap arms first.
///
/// Vacuously `true` when either axis is absent — a `:politicas`
/// that names only one of the pair declares no relation for the
/// substrate to hold it to (`:rate-limit` alone is a per-edge
/// token-bucket declaration with no failure counter to starve;
/// `:circuit-breaker` alone is a rolling-window failure counter
/// whose call rate is unconstrained by the substrate, so no
/// bucket-derived upper bound on calls-per-window is knowable at
/// author time). Same "unset means the cluster default applies,
/// not zero" partition [`MeshPolicy::is_empty`] and the sibling
/// [`MeshPolicy::breaker_window_observes_timeout`] predicate
/// carry.
///
/// Lifted as a typed predicate on the substrate primitive rather
/// than open-coded at the validate gate so every downstream
/// consumer of the pair reaches the invariant through one
/// dispatch: the [`AplicacaoSpec::validate_politicas`] gate
/// below, the future `CiliumClusterwideEnvoyConfig`
/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) that
/// must emit `local_rate_limit.token_bucket.{max_tokens,
/// fill_interval}` alongside `outlier_detection.consecutive_5xx`
/// / `outlier_detection.interval` as one coherent Envoy block,
/// the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
/// materializer's admission webhook, and the future
/// per-`:contratos`-edge `:politicas` override the same roadmap
/// acknowledges — which resolves an *effective* pair per edge
/// (edge-level `:rate-limit` against the Aplicacao-level
/// `:circuit-breaker`, or vice versa) and so must re-check the
/// relation on a pair neither axis's declaration site can see
/// whole. Naming the invariant once means that resolver folds
/// this predicate over its resolved pair instead of re-deriving
/// the comparison, exactly as the sibling cross-axis
/// [`MeshPolicy::breaker_window_observes_timeout`] predicate
/// names the `(:timeout, :window)` relation for its own consumers.
#[must_use]
pub const fn breaker_can_trip_under_rate_limit(&self) -> bool {
match (self.rate_limit(), self.circuit_breaker()) {
(Some(rl), Some(cb)) => {
let calls_per_cb_window =
(rl.rate() as u128).saturating_mul(cb.window().as_nanos());
let trip_threshold_per_cb_window =
(cb.max_failures() as u128).saturating_mul(rl.window().as_nanos());
calls_per_cb_window >= trip_threshold_per_cb_window
}
_ => true,
}
}
/// Substrate-canonical cross-axis coherence predicate on the
/// `:politicas` slot: can one client's declared `:retries` all
/// complete before `:circuit-breaker :max-failures` trips the
/// breaker mid-retry?
///
/// The third cross-axis invariant on the `:politicas` surface —
/// sibling to [`MeshPolicy::breaker_window_observes_timeout`] on
/// the `(:timeout, :circuit-breaker :window)` pair and
/// [`MeshPolicy::breaker_can_trip_under_rate_limit`] on the
/// `(:rate-limit, :circuit-breaker)` pair, extended onto the
/// `(:retries, :circuit-breaker :max-failures)` pair. Each axis in
/// the pair is validated in isolation by the per-axis brackets in
/// [`AplicacaoSpec::validate_politicas`] (retries zero-floor + cap,
/// max-failures zero-floor + cap), so a `MeshPolicy` whose axes
/// are each individually well-formed can still name a
/// structurally-inert retry policy. The pair
/// `{ :retries 3, :circuit-breaker (:max-failures 3 :window "1s") }`
/// passes every per-axis bracket and is nonetheless a retry
/// policy the substrate cannot honor: one client's initial attempt
/// plus three retries is four attempts, but the breaker trips on
/// the third failure — the fourth attempt (the last declared
/// retry) is blocked by the open breaker, so the substrate
/// declared four attempts and structurally allows three.
///
/// The typed test is the integer inequality
/// `cb.max_failures() > retries` — the retries count is the
/// *number of retry attempts beyond the initial* (Envoy's
/// `retry_policy.num_retries` semantics), so a client makes at
/// most `retries + 1` attempts per client call, each of which may
/// fail. For the breaker to *admit* the retry policy through
/// completion, its trip threshold must not be reached by one
/// client's failures alone: `retries + 1 <= max_failures`,
/// equivalently `retries < max_failures`, equivalently
/// `max_failures > retries`. The boundary case
/// `max_failures == retries + 1` accepts (the R+1th failure — the
/// last retry — trips the breaker exactly as it completes; retries
/// are fully executed). The strict-below case
/// `max_failures <= retries` rejects (the breaker trips before
/// retries exhaust, silently truncating the declared retry policy
/// mid-run — the same declared-but-structurally-inert footgun the
/// sibling per-axis cap arms close on the single-axis surfaces).
///
/// Vacuously `true` when either axis is absent — a `:politicas`
/// that names only one of the pair declares no relation for the
/// substrate to hold it to (`:retries` alone is a client-retry
/// policy with no failure counter to trip; `:circuit-breaker`
/// alone is a failure counter whose per-client attempt count is
/// unconstrained by the substrate, so no per-client saturation
/// bound on failures-per-client-call is knowable at author time).
/// Same "unset means the cluster default applies, not zero"
/// partition [`MeshPolicy::is_empty`] and the sibling
/// [`MeshPolicy::breaker_window_observes_timeout`] /
/// [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicates
/// carry.
///
/// Lifted as a typed predicate on the substrate primitive rather
/// than open-coded at the validate gate so every downstream
/// consumer of the pair reaches the invariant through one
/// dispatch: the [`AplicacaoSpec::validate_politicas`] gate
/// below, the future `CiliumClusterwideEnvoyConfig`
/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) that
/// must emit `retry_policy.num_retries` alongside
/// `outlier_detection.consecutive_5xx` as one coherent Envoy
/// block, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
/// materializer's admission webhook, and the future
/// per-`:contratos`-edge `:politicas` override the same roadmap
/// acknowledges — which resolves an *effective* pair per edge
/// (edge-level `:retries` against the Aplicacao-level
/// `:circuit-breaker`, or vice versa) and so must re-check the
/// relation on a pair neither axis's declaration site can see
/// whole. Naming the invariant once means that resolver folds
/// this predicate over its resolved pair instead of re-deriving
/// the comparison, exactly as the sibling cross-axis
/// [`MeshPolicy::breaker_window_observes_timeout`] and
/// [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicates
/// name the `(:timeout, :window)` and `(:rate-limit,
/// :circuit-breaker)` relations for their own consumers.
#[must_use]
pub const fn retries_fit_under_breaker_trip_threshold(&self) -> bool {
match (self.retries(), self.circuit_breaker()) {
(Some(retries), Some(cb)) => cb.max_failures() > retries,
_ => true,
}
}
/// Substrate-canonical cross-axis coherence predicate on the
/// `:politicas` slot: does the `:rate-limit` token-bucket capacity
/// admit one client's full `:retries + 1` attempt burst inside a
/// single refill window?
///
/// The fourth cross-axis invariant on the `:politicas` surface,
/// completing the triangle of pairs the three sibling gates carve
/// out — sibling to [`MeshPolicy::breaker_window_observes_timeout`]
/// on the `(:timeout, :circuit-breaker :window)` pair,
/// [`MeshPolicy::breaker_can_trip_under_rate_limit`] on the
/// `(:rate-limit, :circuit-breaker)` pair, and
/// [`MeshPolicy::retries_fit_under_breaker_trip_threshold`] on the
/// `(:retries, :circuit-breaker :max-failures)` pair, extended onto
/// the `(:retries, :rate-limit)` pair — the last cross-axis relation
/// among the three scalar `:politicas` axes (`:retries`,
/// `:rate-limit`, `:circuit-breaker`) whose axis-triple defines the
/// coherence surface every production overlay (Envoy, Istio,
/// resilience4j, AWS App Mesh) resolves as one block. Each axis in
/// the pair is validated in isolation by the per-axis brackets in
/// [`AplicacaoSpec::validate_politicas`] (retries zero-floor + cap,
/// rate zero-floor + cap, window canonical-form), so a `MeshPolicy`
/// whose axes are each individually well-formed can still name a
/// structurally-truncated retry policy the rate limiter refuses to
/// admit. The pair `{ :retries 5, :rate-limit "3/s" }` passes every
/// per-axis bracket and is nonetheless a retry policy the substrate
/// cannot honor: one client's initial attempt plus five retries is
/// six attempts, but the token bucket admits at most three tokens
/// per one-second refill window, so the fourth attempt onward is
/// blocked by the rate limiter itself — the substrate declared six
/// attempts and structurally allows three. Envoy's
/// `local_rate_limit.token_bucket.max_tokens` paired against
/// `retry_policy.num_retries` carries the identical relation; every
/// production playbook that pairs the two axes recommends sizing
/// the bucket capacity above any single client's retry budget so
/// the retry policy is not silently truncated by the same rate
/// limiter it feeds through.
///
/// The typed test is the integer inequality
/// `rl.rate() >= retries + 1` — the retries count is the *number of
/// retry attempts beyond the initial* (Envoy's
/// `retry_policy.num_retries` semantics), so a client makes at most
/// `retries + 1` attempts per client call, each of which consumes
/// one token from the local rate-limit bucket. For the bucket to
/// *admit* the retry burst without dropping tokens, its capacity
/// must not be reached by one client's attempts alone:
/// `retries + 1 <= rate`, equivalently `rate >= retries + 1`. The
/// boundary case `rate == retries + 1` accepts (the bucket admits
/// exactly one client's full retry sequence per refill window —
/// retries fully executed). The strict-below case `rate <= retries`
/// rejects (the bucket exhausts before retries complete, silently
/// truncating the declared retry policy mid-run — the same
/// declared-but-structurally-inert footgun the sibling per-axis cap
/// arms close on the single-axis surfaces). The equivalent
/// coherent-direction form `rl.rate() > retries` sidesteps the
/// `retries + 1` addition entirely (both `rate` and `retries` are
/// `u32`; the `>` comparison is total on the type with no overflow
/// against past-the-guard struct-literal `retries` values a caller
/// might pass before `validate` runs), matching the peer
/// [`MeshPolicy::retries_fit_under_breaker_trip_threshold`] direct-
/// `>`-comparison discipline on the sibling
/// `(:retries, :max-failures)` pair.
///
/// Vacuously `true` when either axis is absent — a `:politicas`
/// that names only one of the pair declares no relation for the
/// substrate to hold it to (`:retries` alone is a client-retry
/// policy with no rate limiter to saturate; `:rate-limit` alone is
/// a token-bucket declaration whose per-client attempt count is
/// unconstrained by the substrate, so no per-client saturation
/// bound on tokens-per-client-call is knowable at author time).
/// Same "unset means the cluster default applies, not zero"
/// partition [`MeshPolicy::is_empty`] and the three sibling
/// cross-axis predicates
/// ([`MeshPolicy::breaker_window_observes_timeout`],
/// [`MeshPolicy::breaker_can_trip_under_rate_limit`],
/// [`MeshPolicy::retries_fit_under_breaker_trip_threshold`]) carry.
///
/// Lifted as a typed predicate on the substrate primitive rather
/// than open-coded at the validate gate so every downstream
/// consumer of the pair reaches the invariant through one dispatch:
/// the [`AplicacaoSpec::validate_politicas`] gate below, the future
/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
/// (MESH-COMPOSITION §III.2 #3) that must emit
/// `local_rate_limit.token_bucket.max_tokens` alongside
/// `retry_policy.num_retries` as one coherent Envoy block, the
/// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
/// admission webhook, and the future per-`:contratos`-edge
/// `:politicas` override the same roadmap acknowledges — which
/// resolves an *effective* pair per edge (edge-level `:retries`
/// against the Aplicacao-level `:rate-limit`, or vice versa) and
/// so must re-check the relation on a pair neither axis's
/// declaration site can see whole. Naming the invariant once means
/// that resolver folds this predicate over its resolved pair
/// instead of re-deriving the comparison, exactly as the three
/// sibling cross-axis predicates name the
/// `(:timeout, :window)` / `(:rate-limit, :circuit-breaker)` /
/// `(:retries, :max-failures)` relations for their own consumers,
/// closing the fourth and last cross-axis relation on the scalar
/// `:politicas` axis-triple.
#[must_use]
pub const fn rate_limit_admits_retry_burst(&self) -> bool {
match (self.retries(), self.rate_limit()) {
(Some(retries), Some(rl)) => rl.rate() > retries,
_ => true,
}
}
/// Substrate-canonical fold over the four cross-axis coherence
/// predicates on the `:politicas` slot — returns the *first*
/// cross-axis violation (as its [`AplicacaoError`] variant) in the
/// canonical "more-foundational-cross-axis first" ordering
/// [`MeshPolicy::breaker_window_observes_timeout`] on
/// `(:timeout, :circuit-breaker :window)` →
/// [`MeshPolicy::breaker_can_trip_under_rate_limit`] on
/// `(:rate-limit, :circuit-breaker)` →
/// [`MeshPolicy::retries_fit_under_breaker_trip_threshold`] on
/// `(:retries, :circuit-breaker :max-failures)` →
/// [`MeshPolicy::rate_limit_admits_retry_burst`] on `(:retries,
/// :rate-limit)`. Returns `None` when every cross-axis relation
/// holds (the vacuous shape [`MeshPolicy::is_empty`] and the fully-
/// coherent shape both land here).
///
/// The ordering discipline this method encodes was open-coded four
/// times at [`AplicacaoSpec::validate_politicas`] — each cross-axis
/// gate was an `if !<predicate>() { let <a> = self.<axis>().expect(
/// "cross-axis gate fires only when :<axis> is present"); let <b>
/// = self.<axis>().expect(…); return Err(<variant>) }` block whose
/// axis-fetch step depended on the predicate having just returned
/// `false` (structurally guaranteed both paired axes are `Some`,
/// but the compiler cannot see through the predicate body, so
/// every arm re-called the accessor with `.expect(…)` to reach
/// the axis it just tested). Two unsound consequences: (1) the
/// validate gate carried eight `.expect(…)` panic call sites the
/// predicate contract already forbids on every well-typed input
/// but the type system does not enforce; (2) the
/// "which-cross-axis-fires-first-when-two-apply" contract lived
/// twice — once in each predicate's own doc comments and once at
/// the validate call site's four-arm cascade. Lifting the four-arm
/// cascade onto this substrate primitive collapses both
/// duplications: the predicate contract and the axis-fetch step
/// live in the same body (no `.expect(…)` — the pattern match at
/// each arm rebinds the paired axes so their `Some` presence is a
/// compile-time property of the local scope), and the ordering
/// discipline lives once at the top of the primitive rather than
/// scattered across four sibling doc-comment blocks that must
/// stay in lockstep.
///
/// Every downstream cross-axis consumer (the [`AplicacaoSpec::
/// validate_politicas`] gate below, the future M4 `mesh.pleme.io/
/// v1alpha1/Aplicacao` CR materializer's admission webhook, the
/// per-`:contratos`-edge `:politicas` override MESH-COMPOSITION
/// §III.2 #3 acknowledges — the last of which resolves an
/// *effective* per-edge pair and must emit *the same* diagnostic
/// on the same paired-axis input as `feira build`) reaches through
/// one call rather than re-inlining the four pattern-matches +
/// accessor-fetches + variant-constructions + ordering-cascade.
///
/// Returns owned copies of every axis carried into the diagnostic:
/// [`Duration`] and [`u32`] are `Copy`, so no `String` allocation
/// occurs on the happy path when no violation fires.
#[must_use]
pub fn first_cross_axis_violation(&self) -> Option<AplicacaoError> {
// Ordering discipline this fold encodes matches the four
// per-arm predicate doc comments' pairwise-ordering contract:
// window-below-timeout wins over every arm that names `:rate-
// limit` or `:retries` (its diagnostic is more self-locating —
// the pair is a per-call-deadline invariant every synchronous
// edge carries whether or not `:rate-limit`/`:retries` is
// declared); the starve arm wins over the two retry arms (its
// diagnostic reasons across the token-bucket-vs-breaker
// relation, an axis the retry arms do not touch); the
// retries-saturate arm wins over the retries-burst arm (its
// diagnostic reasons across the per-client-vs-breaker
// relation, which carries whether or not `:rate-limit` is
// declared). Each arm rebinds the paired axes through the
// pattern match, so the `.expect(…)` panics the four-block
// cascade at `validate_politicas` carried collapse to no-op
// pattern rebindings the compiler statically proves exhaust.
if let (Some(t), Some(cb)) = (self.timeout(), self.circuit_breaker())
&& !self.breaker_window_observes_timeout()
{
return Some(AplicacaoError::policy_breaker_window_below_timeout(&cb, t));
}
if let (Some(rl), Some(cb)) = (self.rate_limit(), self.circuit_breaker())
&& !self.breaker_can_trip_under_rate_limit()
{
return Some(AplicacaoError::policy_breaker_cannot_trip_under_rate_limit(
&rl, &cb,
));
}
if let (Some(retries), Some(cb)) = (self.retries(), self.circuit_breaker())
&& !self.retries_fit_under_breaker_trip_threshold()
{
return Some(
AplicacaoError::policy_breaker_trips_before_retries_exhausted(retries, &cb),
);
}
if let (Some(retries), Some(rl)) = (self.retries(), self.rate_limit())
&& !self.rate_limit_admits_retry_burst()
{
return Some(AplicacaoError::policy_rate_limit_cannot_admit_retry_burst(
retries, &rl,
));
}
None
}
/// Substrate-canonical compound entry gate over the whole
/// `:politicas` typed slot — folds every per-axis bracket
/// (`:timeout` / `:retries` / `:circuit-breaker :max-failures` /
/// `:circuit-breaker :window` / `:rate-limit` rate / `:rate-limit`
/// window-canonical-form) *and* the compound cross-axis fold
/// [`MeshPolicy::first_cross_axis_violation`] into one call every
/// consumer of a validated [`MeshPolicy`] reaches through.
///
/// Returns the first violation as its [`AplicacaoError`] variant,
/// or `Ok(())` when every per-axis value lies in its accept-set and
/// every cross-axis relation holds. Per-axis brackets run strictly
/// before the cross-axis fold — the sibling
/// [`AplicacaoSpec::validate_politicas`] gate carried the same
/// ordering discipline for the same reason: a per-axis
/// structurally-invalid value (a `Duration::ZERO` `:window`, an
/// above-cap `:rate-limit` rate) surfaces its own self-locating
/// diagnostic first, ahead of any cross-axis arm that would send
/// the author to reconcile two values one of which is not a
/// meaningful window at all. Within the per-axis phase, arms fire
/// in the same slot-order the peer per-axis brackets carry
/// (`:timeout` → `:retries` → `:circuit-breaker` → `:rate-limit`,
/// each internally ordered zero-floor before canonical-form before
/// cap by [`crate::render::require_positive_bounded_u32`] /
/// [`crate::render::require_positive_canonical_bounded_duration`]);
/// within the cross-axis phase, arms fire in the canonical
/// more-foundational-cross-axis-first ordering
/// [`MeshPolicy::first_cross_axis_violation`] encodes.
///
/// Lifted as a typed method on the substrate primitive so every
/// downstream consumer of a validated [`MeshPolicy`] reaches the
/// invariant through one dispatch: the
/// [`AplicacaoSpec::validate_politicas`] gate below (whose whole
/// body collapses to `self.politicas().validate()`), the future
/// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
/// admission webhook, the future per-`:contratos`-edge `:politicas`
/// override MESH-COMPOSITION §III.2 #3 acknowledges — the last of
/// which resolves an *effective* per-edge [`MeshPolicy`] and must
/// emit *the same* diagnostic on the same input as `feira build`.
/// Naming the compound gate once on the substrate primitive means
/// every downstream consumer inherits both the per-axis brackets
/// *and* the cross-axis fold through one call, rather than
/// re-inlining the four-per-axis + one-cross-axis cascade in
/// lockstep with `validate_politicas`.
///
/// Peer of the per-kind compound entry gates lifted at
/// [`crate::render::require_aplicacao_view`] (7242d45 / 3aefefb),
/// [`crate::render::require_supervisor_view`] (8d8a5c3), and
/// [`crate::render::require_v0_servico_shape`] on the per-Caixa
/// layout axis, and the sibling compound cross-axis fold
/// [`MeshPolicy::first_cross_axis_violation`] on the same
/// `:politicas` axis — extended here onto the per-slot per-axis +
/// cross-axis compound entry gate that folds both surfaces.
pub fn validate(&self) -> Result<(), AplicacaoError> {
if let Some(t) = self.timeout() {
crate::render::require_positive_canonical_bounded_duration(
t,
POLICY_TIMEOUT_MAX,
|| AplicacaoError::PolicyTimeoutZero,
AplicacaoError::policy_timeout_not_canonical,
AplicacaoError::policy_timeout_exceeds_cap,
)?;
}
if let Some(r) = self.retries() {
crate::render::require_positive_bounded_u32(
r,
POLICY_RETRIES_MAX,
|| AplicacaoError::PolicyRetriesZero,
AplicacaoError::policy_retries_exceeds_cap,
)?;
}
if let Some(cb) = self.circuit_breaker() {
crate::render::require_positive_bounded_u32(
cb.max_failures(),
POLICY_BREAKER_MAX_FAILURES_MAX,
|| AplicacaoError::PolicyBreakerZeroFailures,
AplicacaoError::policy_breaker_max_failures_exceeds_cap,
)?;
crate::render::require_positive_canonical_bounded_duration(
cb.window(),
POLICY_BREAKER_WINDOW_MAX,
|| AplicacaoError::PolicyBreakerZeroWindow,
AplicacaoError::policy_breaker_window_not_canonical,
AplicacaoError::policy_breaker_window_exceeds_cap,
)?;
}
if let Some(rl) = self.rate_limit() {
crate::render::require_positive_bounded_u32(
rl.rate(),
POLICY_RATE_LIMIT_MAX,
|| AplicacaoError::PolicyRateLimitZero,
AplicacaoError::policy_rate_limit_exceeds_cap,
)?;
if rl.canonical_unit().is_none() {
return Err(AplicacaoError::policy_rate_limit_window_not_canonical(
rl.window(),
));
}
}
if let Some(err) = self.first_cross_axis_violation() {
return Err(err);
}
Ok(())
}
/// Substrate-canonical per-`:politicas` `:timeout` Gateway-API-mesh
/// per-call-deadline scalar accessor every consumer of the
/// Aplicacao's Gateway API v1.x per-rule request-timeout keys off —
/// returns the author-declared `:politicas :timeout` typed
/// [`Duration`] verbatim as an `Option<Duration>`, copied out of the
/// typed slot's own `Option<Duration>` storage (`Option<Duration>`
/// is `Copy`, so the accessor returns by value; no borrow of
/// `&self` past the call). `None` when the slot is absent (the
/// "cluster default applies — typically the gateway class's
/// implementation-side per-request wall-clock cap" arm caixa-mesh's
/// `timeout_overlay` builder documents at caixa-mesh/src/lib.rs:2911
/// — [`MeshPolicy::is_empty`]'s `timeout.is_none()` arm reads this
/// predicate too, so an authored-but-unset `:politicas (:timeout ())`
/// round-trips to a rendered `HTTPRoute` structurally identical to
/// one that omits the slot).
///
/// The `:politicas :timeout` slot carries the "no infinite blocking"
/// per-call deadline contract (MESH-COMPOSITION §V CSE invariant) —
/// the typed slot's `Option<Duration>` accept-set (zero-floor
/// rejected through [`AplicacaoError::PolicyTimeoutZero`], canonical-
/// form rejected through [`AplicacaoError::PolicyTimeoutNotCanonical`],
/// upper-bounded by [`POLICY_TIMEOUT_MAX`]) maps onto the Gateway API
/// v1.x `HTTPRoute.spec.rules[].timeouts.request` per-rule request-
/// deadline scalar the caixa-mesh `timeout_overlay` builder writes.
/// Every downstream consumer that reads the per-call cap keys off
/// this scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
/// renderers key off to decide "emit :politicas overlay" vs "skip
/// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
/// `timeouts.request` builder at caixa-mesh/src/lib.rs:2979 that
/// fans the deadline into every rule via
/// [`crate::render::single_field_overlay`], the future M4 per-
/// Aplicacao Gateway API reconciler materialization pass, the
/// future per-`:contratos`-edge timeout-override overlay the
/// MESH-COMPOSITION §III.2 roadmap acknowledges).
///
/// Prior to this lift the `.timeout` field was accessed inline at
/// two sites — [`MeshPolicy::is_empty`]'s `self.timeout.is_none()`
/// arm and caixa-mesh's `single_field_overlay(spec.politicas.timeout,
/// …)` call — two open-coded field-accesses that expressed no
/// compile-time link back to the typed slot. A future extension of
/// the `:politicas :timeout` axis to a richer author surface — a
/// per-`:contratos`-edge timeout override the operator pins through
/// a future `:contratos :timeout` slot the MESH-COMPOSITION §III.2
/// roadmap acknowledges, a per-cluster timeout-default overlay the
/// M4 CR materializer resolves per-CR, a split of the single
/// per-call `Duration` into a richer `{request, backendRequest}`
/// pair once the Gateway API's per-rule `timeouts` block grows the
/// upstream-facing backendRequest arm alongside the client-facing
/// request arm — would have had to be threaded through both open-
/// coded copies in lockstep or the emptiness predicate and the
/// caixa-mesh emit path would silently disagree on which per-call
/// deadline a given [`MeshPolicy`] resolves to (a `:politicas` block
/// whose only axis is a `Some :timeout` would satisfy `is_empty()
/// == false` while the renderer's overlay-emit path silently read
/// a drifted other value, or vice versa: an author's `:timeout
/// "30s"` would omit the `HTTPRoute` `timeouts.request` block while
/// the emptiness predicate still classified the policy as non-
/// empty, and every `kubectl -n tatara-system get httproute -o yaml
/// | grep -A2 timeouts` audit would land on a route whose author's
/// typed slot value silently vanished at the renderer layer).
/// Lifting the resolution to a typed method on the substrate
/// primitive means every downstream consumer of the Aplicacao's
/// per-`:politicas` deadline surface reaches for exactly one typed
/// dispatch — the resolver's accept-set migrates as a unit on any
/// future axis addition.
///
/// Third `Option<Copy-T>`-return accessor on the M3 mesh-slot
/// family (sibling of the peer per-`:politicas`
/// [`MeshPolicy::retries`] bdfb399 `Option<u32>` accessor and the
/// per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1
/// `Option<bool>` accessor — same "one typed dispatch on the
/// substrate primitive, thin projections at each consumer"
/// discipline extended onto the peer per-`:politicas` typed-
/// [`Duration`] optional-scalar axis; closes the "optional per-slot
/// numeric-Copy-T scalar" projection pattern the sibling
/// `Option<u32>` / `Option<bool>` lifts opened, since every
/// remaining `MeshPolicy` axis (`circuit_breaker: Option<CircuitBreaker>`,
/// `rate_limit: Option<RateLimit>`) carries a struct payload rather
/// than a scalar). Named `timeout()` to match the storage field's
/// name; the accessor's identity maps onto the canonical MESH-
/// COMPOSITION §III.2 vocabulary the slot's docstring already carries.
#[must_use]
pub const fn timeout(&self) -> Option<Duration> {
self.timeout
}
/// Substrate-canonical per-`:politicas` `:retries` transient-failure-
/// retry-budget scalar accessor every consumer of the Aplicacao's
/// Gateway API v1.x per-rule retry-cap keys off — returns the
/// author-declared `:politicas :retries` typed `u32` verbatim as an
/// `Option<u32>`, copied out of the typed slot's own `Option<u32>`
/// storage (`Option<u32>` is `Copy`, so the accessor returns by
/// value; no borrow of `&self` past the call). `None` when the slot
/// is absent (the "cluster default applies — typically 'no retries
/// beyond a single dispatch attempt'" arm the caixa-mesh
/// `retry_overlay` builder documents at caixa-mesh/src/lib.rs:2985
/// — [`MeshPolicy::is_empty`]'s `retries.is_none()` arm reads
/// this predicate too, so an authored-but-unset `:politicas
/// (:retries ())` round-trips to a rendered `HTTPRoute` structurally
/// identical to one that omits the slot).
///
/// The `:politicas :retries` slot carries the "transient failure
/// retry cap" contract (MESH-COMPOSITION §III.2 #2) — the typed
/// slot's `Option<u32>` accept-set (lower-bounded by 1 through
/// [`AplicacaoSpec::validate_politicas`], upper-bounded by
/// [`POLICY_RETRIES_MAX`]) maps onto the Gateway API v1.x
/// `HTTPRoute.spec.rules[].retry.attempts` per-rule retry-attempt-
/// count scalar the caixa-mesh `retry_overlay` builder writes.
/// Every downstream consumer that reads the retry cap keys off this
/// scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
/// renderers key off to decide "emit :politicas overlay" vs "skip
/// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
/// `retry.attempts` builder at caixa-mesh/src/lib.rs:3007 that fans
/// the value into every rule via [`crate::render::single_field_overlay`],
/// the future M4 per-Aplicacao Gateway API reconciler
/// materialization pass, the future per-`:contratos`-edge retry-
/// override overlay the MESH-COMPOSITION §III.2 #2 roadmap
/// acknowledges).
///
/// Prior to this lift the `.retries` field was accessed inline at
/// two sites — [`MeshPolicy::is_empty`]'s `self.retries.is_none()`
/// arm and caixa-mesh's `single_field_overlay(spec.politicas.retries,
/// …)` call — two open-coded field-accesses that expressed no
/// compile-time link back to the typed slot. A future extension of
/// the `:politicas :retries` axis to a richer author surface — a
/// per-`:contratos`-edge retry override the operator pins through a
/// future `:contratos :retries` slot, a per-cluster retry-default
/// overlay the M4 CR materializer resolves per-CR, a promotion of
/// the plain `u32` attempt-count to a richer `{attempts, codes,
/// backoff}` sub-block once the Gateway API grows the peer
/// `retry.codes` / `retry.backoff` axes — would have had to be
/// threaded through both open-coded copies in lockstep or the
/// emptiness predicate and the caixa-mesh emit path would silently
/// disagree on which retry budget a given [`MeshPolicy`] resolves to
/// (a `:politicas` block whose only axis is a `Some :retries` would
/// satisfy `is_empty() == false` while the renderer's overlay-emit
/// path silently read a drifted other value, or vice versa: an
/// author's `:retries 3` would omit the `HTTPRoute` `retry.attempts`
/// block while the emptiness predicate still classified the policy
/// as non-empty). Lifting the resolution to a typed method on the
/// substrate primitive means every downstream consumer of the
/// Aplicacao's per-`:politicas` retry surface reaches for exactly
/// one typed dispatch — the resolver's accept-set migrates as a
/// unit on any future axis addition.
///
/// Second `Option<Copy-T>`-return accessor on the M3 mesh-slot
/// family (sibling of the peer per-`:politicas`
/// [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` accessor —
/// same "one typed dispatch on the substrate primitive, thin
/// projections at each consumer" discipline extended onto the
/// peer per-`:politicas` typed-`u32` optional-scalar axis; opens
/// the "optional per-slot numeric-Copy-T scalar" projection pattern
/// the sibling per-`:politicas` `:timeout` (Option<Duration>) /
/// per-`CircuitBreaker` `:max-failures` / `:window` future lifts
/// fold on). Named `retries()` to match the storage field's name;
/// the accessor's identity maps onto the canonical MESH-COMPOSITION
/// §III.2 vocabulary the slot's docstring already carries.
#[must_use]
pub const fn retries(&self) -> Option<u32> {
self.retries
}
/// Substrate-canonical per-`:politicas` `:mtls-required` mTLS-
/// enforcement-toggle scalar accessor every consumer of the
/// Aplicacao's Cilium-mesh L4 mutual-authentication policy keys off
/// — returns the author-declared `:politicas :mtls-required` typed
/// bool verbatim as an `Option<bool>`, copied out of the typed
/// slot's own `Option<bool>` storage (`Option<bool>` is `Copy`, so
/// the accessor returns by value; no borrow of `&self` past the
/// call). `None` when the slot is absent (the "cluster default
/// applies — typically 'disabled' cluster-wide" arm the caixa-mesh
/// `mtls_overlay` builder documents at caixa-mesh/src/lib.rs:2540
/// — [`MeshPolicy::is_empty`]'s `mtls_required.is_none()` arm reads
/// this predicate too, so an authored-but-unset `:politicas
/// (:mtls-required ())` round-trips to a rendered
/// `CiliumNetworkPolicy` structurally identical to one that omits
/// the slot).
///
/// The `:politicas :mtls-required` slot carries the "explicit opt-
/// out only, sandboxing-by-default" mTLS-enforcement toggle
/// (MESH-COMPOSITION §III.2 #3) — the typed slot's three-way
/// `{None, Some(true), Some(false)}` accept-set maps onto the
/// Cilium `authentication.mode` bijection through
/// [`crate::cilium_auth_mode`]: `Some(true) → "required"` (mTLS
/// handshake enforced), `Some(false) → "disabled"` (handshake
/// skipped — the debug-edge opt-out), `None` → omit the block
/// (cluster default applies). Every downstream consumer that
/// reads the toggle keys off this scalar (the
/// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
/// off to decide "emit :politicas overlay" vs "skip entirely", the
/// caixa-mesh per-`(:de, :para)` CNP `mtls_overlay` builder at
/// caixa-mesh/src/lib.rs:2549 that fans the toggle into every
/// ingress rule via [`crate::render::single_field_overlay`], the
/// future M4 per-Aplicacao Cilium `authentication.mode` reconciler
/// materialization pass, the future per-`:contratos`-edge mTLS
/// override MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
///
/// Prior to this lift the `.mtls_required` field was accessed
/// inline at two sites — [`MeshPolicy::is_empty`]'s
/// `self.mtls_required.is_none()` arm and caixa-mesh's
/// `single_field_overlay(spec.politicas.mtls_required, …)` call —
/// two open-coded field-accesses that expressed no compile-time
/// link back to the typed slot. A future extension of the
/// `:politicas :mtls-required` axis to a richer author surface —
/// a per-`:contratos`-edge mTLS override the operator pins through
/// a future `:contratos :mtls` slot the MESH-COMPOSITION §III.2
/// #3 roadmap acknowledges, a per-cluster mTLS-default overlay the
/// M4 CR materializer resolves per-CR, a three-valued
/// `{None, Some(true), Some(false), Some(Optional)}` promotion
/// once Cilium's `authentication.mode` grows an `"optional"` arm —
/// would have had to be threaded through both open-coded copies in
/// lockstep or the emptiness predicate and the caixa-mesh emit
/// path would silently disagree on which toggle a given
/// [`MeshPolicy`] resolves to (a `:politicas` block whose only
/// axis is a `Some`
/// `:mtls-required` would satisfy `is_empty() == false` while the
/// renderer's overlay-emit path silently read a drifted other
/// value, or vice versa). Lifting the resolution to a typed method
/// on the substrate primitive means every downstream consumer of
/// the Aplicacao's per-`:politicas` mTLS-toggle surface reaches
/// for exactly one typed dispatch — the resolver's accept-set
/// migrates as a unit on any future axis addition.
///
/// First `Option<Copy-T>`-return accessor on the M3 mesh-slot
/// family (peer of the sibling per-`:placement`
/// [`Placement::shard_key`] 7cd2a28 `Option<&str>` accessor —
/// same "one typed dispatch on the substrate primitive, thin
/// projections at each consumer" discipline extended onto the
/// peer per-`:politicas` typed-bool optional-scalar axis; opens
/// the "optional per-slot Copy-T scalar" projection pattern the
/// sibling per-`:politicas` `:retries` (Option<u32>) /
/// `:timeout` (Option<Duration>) future lifts fold on). Named
/// `mtls_required()` to match the storage field's name; the
/// accessor's identity maps onto the canonical MESH-COMPOSITION
/// §III.2 vocabulary the slot's docstring already carries.
#[must_use]
pub const fn mtls_required(&self) -> Option<bool> {
self.mtls_required
}
/// Substrate-canonical per-`:politicas` `:rate-limit` Envoy-
/// `local_rate_limit`-mesh token-bucket-declaration scalar
/// accessor every consumer of the Aplicacao's per-`:politicas`
/// per-`(rate, window)` rate-limit surface keys off — returns the
/// author-declared `:politicas :rate-limit` typed [`RateLimit`]
/// verbatim as an `Option<RateLimit>`, copied out of the typed
/// slot's own `Option<RateLimit>` storage ([`RateLimit`] is
/// `Copy`, so the accessor returns by value; no borrow of `&self`
/// past the call). `None` when the slot is absent (the "cluster
/// default applies — typically 'no per-Aplicacao rate declaration,
/// gateway-class per-listener default applies'" arm the future
/// caixa-mesh `local_rate_limit_overlay` emitter MESH-COMPOSITION
/// §III.2 #3 names — [`MeshPolicy::is_empty`]'s
/// `rate_limit().is_none()` arm reads this predicate too, so an
/// authored-but-unset `:politicas (:rate-limit ())` round-trips
/// to a rendered `CiliumClusterwideEnvoyConfig` structurally
/// identical to one that omits the slot).
///
/// The `:politicas :rate-limit` slot carries the "per-Aplicacao
/// token-bucket rate declaration" contract (MESH-COMPOSITION
/// §III.2 #3) — the typed slot's `Option<RateLimit>` accept-set
/// (rate lower-bounded by 1 through
/// [`AplicacaoSpec::validate_politicas`], upper-bounded by
/// [`POLICY_RATE_LIMIT_MAX`], window canonically bijected to the
/// three-unit `{"s", "m", "h"}` [`rate_limit_codec`] table through
/// [`is_canonical_rate_limit_window`]) maps onto the Envoy
/// `local_rate_limit.token_bucket.{max_tokens, fill_interval}`
/// bijection the future `CiliumClusterwideEnvoyConfig` per-
/// `:politicas` overlay emits. Every downstream consumer that
/// reads the rate declaration keys off this scalar (the
/// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
/// off to decide "emit :politicas overlay" vs "skip entirely", the
/// [`AplicacaoSpec::validate_politicas`] per-value-shape gate that
/// brackets `rl.rate` against [`POLICY_RATE_LIMIT_MAX`] and pins
/// `rl.window` against [`is_canonical_rate_limit_window`], the
/// future M4 per-Aplicacao Envoy reconciler materialization pass,
/// the future per-`:contratos`-edge rate-limit override the
/// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
///
/// Prior to this lift the `.rate_limit` field was accessed inline
/// at two sites — [`MeshPolicy::is_empty`]'s
/// `self.rate_limit.is_none()` arm and the `validate_politicas`
/// gate's `if let Some(rl) = &p.rate_limit` bind — two open-coded
/// field-accesses that expressed no compile-time link back to the
/// typed slot. A future extension of the `:politicas :rate-limit`
/// axis to a richer author surface — a per-`:contratos`-edge
/// rate-limit override the operator pins through a future
/// `:contratos :rate-limit` slot the MESH-COMPOSITION §III.2 #3
/// roadmap acknowledges, a per-cluster rate-limit-default overlay
/// the M4 CR materializer resolves per-CR, a promotion of the
/// plain `(rate, window)` scalar pair to a richer
/// `{rate, window, burst, key}` sub-block once Envoy's
/// `local_rate_limit` grows the peer `burst_size` /
/// `descriptor_key` axes — would have had to be threaded through
/// both open-coded copies in lockstep or the emptiness predicate
/// and the validate gate would silently disagree on which rate
/// declaration a given [`MeshPolicy`] resolves to (a `:politicas`
/// block whose only axis is a `Some :rate-limit` would satisfy
/// `is_empty() == false` while the validate path silently read a
/// drifted other value, or vice versa: an author's
/// `:rate-limit "100/s"` would omit the value-shape gate while the
/// emptiness predicate still classified the policy as non-empty).
/// Lifting the resolution to a typed method on the substrate
/// primitive means every downstream consumer of the Aplicacao's
/// per-`:politicas` rate-limit surface reaches for exactly one
/// typed dispatch — the resolver's accept-set migrates as a unit
/// on any future axis addition.
///
/// First `Option<Copy-composite-T>`-return accessor on the M3
/// mesh-slot family — closes the last un-lifted per-`:politicas`
/// scalar-value axis. Peer of the sibling per-`:politicas`
/// [`MeshPolicy::timeout`] (7073d0f) / [`MeshPolicy::retries`]
/// (bdfb399) / [`MeshPolicy::mtls_required`] (c0110f1)
/// `Option<Copy-T>` accessors on the primitive-Copy axes — same
/// "one typed dispatch on the substrate primitive, thin
/// projections at each consumer" discipline extended onto the
/// peer per-`:politicas` composite-Copy shape (`RateLimit` is
/// `#[derive(Copy)]`; peer of [`CircuitBreaker`] which lives
/// behind [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
/// sub-accessors rather than a top-level accessor because
/// consumers reach for the axes not the aggregate). Named
/// `rate_limit()` to match the storage field's name; the
/// accessor's identity maps onto the canonical MESH-COMPOSITION
/// §III.2 vocabulary the slot's docstring already carries.
#[must_use]
pub const fn rate_limit(&self) -> Option<RateLimit> {
self.rate_limit
}
/// Substrate-canonical per-`:politicas` `:circuit-breaker`
/// Envoy-`outlier_detection`-mesh consecutive-failure-ejection-
/// declaration scalar accessor every consumer of the Aplicacao's
/// per-`:politicas` breaker declaration keys off — returns the
/// author-declared `:politicas :circuit-breaker` typed
/// [`CircuitBreaker`] verbatim as an `Option<CircuitBreaker>`,
/// copied out of the typed slot's own `Option<CircuitBreaker>`
/// storage ([`CircuitBreaker`] is `Copy`, so the accessor returns
/// by value; no borrow of `&self` past the call). `None` when the
/// slot is absent (the "cluster default applies — typically 'no
/// per-Aplicacao breaker declaration, gateway-class per-listener
/// default applies'" arm the future caixa-mesh
/// `outlier_detection_overlay` emitter MESH-COMPOSITION §III.2 #3
/// names — [`MeshPolicy::is_empty`]'s `circuit_breaker().is_none()`
/// arm reads this predicate too, so an authored-but-unset
/// `:politicas (:circuit-breaker ())` round-trips to a rendered
/// `CiliumClusterwideEnvoyConfig` structurally identical to one
/// that omits the slot).
///
/// The `:politicas :circuit-breaker` slot carries the
/// "per-Aplicacao consecutive-transient-failure trip declaration"
/// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
/// `Option<CircuitBreaker>` accept-set (per-`:max-failures`
/// zero-floor rejected through
/// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
/// [`POLICY_BREAKER_MAX_FAILURES_MAX`]; per-`:window` zero-floor
/// rejected through [`AplicacaoError::PolicyBreakerZeroWindow`],
/// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`],
/// canonical-form pinned through
/// [`AplicacaoError::PolicyBreakerWindowNotCanonical`]) maps onto
/// the Envoy `outlier_detection.{consecutive_5xx, interval}`
/// bijection the future `CiliumClusterwideEnvoyConfig`
/// per-`:politicas` overlay emits. Every downstream consumer that
/// reads the breaker declaration keys off this scalar (the
/// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
/// off to decide "emit :politicas overlay" vs "skip entirely", the
/// [`AplicacaoSpec::validate_politicas`] per-sub-struct-axis gate
/// that brackets `cb.max_failures()` against
/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] and `cb.window()` against
/// [`POLICY_BREAKER_WINDOW_MAX`] via
/// [`crate::render::require_positive_canonical_bounded_duration`],
/// the future M4 per-Aplicacao Envoy reconciler materialization
/// pass, the future per-`:contratos`-edge breaker override the
/// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
///
/// Prior to this lift the `.circuit_breaker` field was accessed
/// inline at two sites — [`MeshPolicy::is_empty`]'s
/// `self.circuit_breaker.is_none()` arm and the
/// `validate_politicas` gate's `if let Some(cb) = &p.circuit_breaker`
/// bind — two open-coded field-accesses that expressed no
/// compile-time link back to the typed slot. A future extension of
/// the `:politicas :circuit-breaker` axis to a richer author
/// surface — a per-`:contratos`-edge breaker override the operator
/// pins through a future `:contratos :circuit-breaker` slot the
/// MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a per-cluster
/// breaker-default overlay the M4 CR materializer resolves per-CR,
/// a promotion of the plain `(max_failures, window)` scalar pair to
/// a richer `{max_failures, window, base_ejection_time, max_ejection_percent}`
/// sub-block once Envoy's `outlier_detection` grows the peer
/// ejection-percentage / ejection-time axes — would have had to be
/// threaded through both open-coded copies in lockstep or the
/// emptiness predicate and the validate gate would silently
/// disagree on which breaker declaration a given [`MeshPolicy`]
/// resolves to (a `:politicas` block whose only axis is a
/// `Some :circuit-breaker` would satisfy `is_empty() == false` while
/// the validate path silently read a drifted other value, or vice
/// versa: an author's `(:circuit-breaker (:max-failures 5 :window
/// "60s"))` would omit the value-shape gate while the emptiness
/// predicate still classified the policy as non-empty). Lifting
/// the resolution to a typed method on the substrate primitive
/// means every downstream consumer of the Aplicacao's
/// per-`:politicas` breaker surface reaches for exactly one typed
/// dispatch — the resolver's accept-set migrates as a unit on any
/// future axis addition.
///
/// Second `Option<Copy-composite-T>`-return accessor on the M3
/// mesh-slot family (sibling of the peer per-`:politicas`
/// [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>` accessor
/// on the same composite-Copy shape, and of the sibling per-
/// `:politicas` [`MeshPolicy::timeout`] 7073d0f
/// `Option<Duration>` / [`MeshPolicy::retries`] bdfb399
/// `Option<u32>` / [`MeshPolicy::mtls_required`] c0110f1
/// `Option<bool>` accessors on the sibling primitive-Copy axes —
/// same "one typed dispatch on the substrate primitive, thin
/// projections at each consumer" discipline extended onto the last
/// unlifted per-`:politicas` scalar-value axis (the composite-Copy
/// `Option<CircuitBreaker>` arm). Named `circuit_breaker()` to
/// match the storage field's name; the accessor's identity maps
/// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
/// docstring already carries. Closes the last unlifted
/// [`MeshPolicy`] accessor axis so every downstream per-`:politicas`
/// reader now routes through a typed dispatch on the substrate
/// primitive.
#[must_use]
pub const fn circuit_breaker(&self) -> Option<CircuitBreaker> {
self.circuit_breaker
}
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct CircuitBreaker {
pub max_failures: u32,
#[serde(with = "supervisor::duration_codec_required")]
pub window: Duration,
}
impl CircuitBreaker {
/// Substrate-canonical per-`:politicas :circuit-breaker`
/// `:max-failures` Envoy-outlier-detection trip-threshold scalar
/// accessor every consumer of the Aplicacao's per-`:contratos`-edge
/// breaker trip-count keys off — returns the author-declared
/// `:politicas :circuit-breaker :max-failures` typed `u32` verbatim,
/// copied out of the typed slot's own `u32` storage (`u32` is `Copy`,
/// so the accessor returns by value; no borrow of `&self` past the
/// call). Non-optional (the surrounding `Option<CircuitBreaker>` is
/// the "slot present?" projection at the parent [`MeshPolicy::circuit_breaker`]
/// axis; a `CircuitBreaker` past pattern-match is definitionally
/// present, and its `:max-failures` field carries the trip count as a
/// required-axis scalar).
///
/// The `:politicas :circuit-breaker :max-failures` axis carries the
/// "consecutive-transient-failure trip threshold" contract
/// (MESH-COMPOSITION §III.2 #3) — the typed slot's `u32` accept-set
/// (zero-floor rejected through
/// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
/// [`POLICY_BREAKER_MAX_FAILURES_MAX`]) maps onto the Envoy
/// `outlier_detection.consecutive_5xx` per-cluster ejection-threshold
/// scalar (equivalently the future `CiliumClusterwideEnvoyConfig`
/// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 acknowledges).
/// Every downstream consumer that reads the trip threshold keys off
/// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
/// cap bracket at caixa-core/src/aplicacao.rs:4022 that gates on the
/// canonical `require_positive_bounded_u32` helper, the future M4
/// per-Aplicacao Envoy config reconciler materialization pass, the
/// future per-`:contratos`-edge breaker-override overlay the
/// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
///
/// Prior to this lift the `.max_failures` field was accessed inline
/// at one production site — [`AplicacaoSpec::validate_politicas`]'s
/// `require_positive_bounded_u32(cb.max_failures, …)` call — one
/// open-coded field-access that expressed no compile-time link back
/// to the typed sub-struct axis. A future extension of the
/// `:max-failures` axis to a richer author surface — a
/// per-`:contratos`-edge breaker override the operator pins through a
/// future `:contratos :max-failures` slot the MESH-COMPOSITION §III.2
/// #3 roadmap acknowledges, a per-cluster max-failures-default
/// overlay the M4 CR materializer resolves per-CR, a promotion of the
/// plain `u32` trip count to a richer
/// `{consecutive_5xx, consecutive_gateway_failure, consecutive_local_origin_failure}`
/// tuple once Envoy's `outlier_detection` block's peer axes come into
/// scope, a per-Envoy-cluster minimum-request-volume gate before the
/// count arms — would have had to be threaded through every open-
/// coded copy in lockstep or the validate gate and the future M4
/// emit path would silently disagree on which trip threshold a given
/// [`CircuitBreaker`] resolves to (an author's `:max-failures 5`
/// would satisfy validate while the emit path silently read a drifted
/// other value, or vice versa: a validated typed slot would land at
/// the emit boundary as a no-op breaker whose trip threshold is
/// structurally never reached). Lifting the resolution to a typed
/// method on the substrate primitive means every downstream consumer
/// of the Aplicacao's per-`:politicas :circuit-breaker`
/// trip-threshold surface reaches for exactly one typed dispatch —
/// the resolver's accept-set migrates as a unit on any future axis
/// addition.
///
/// First sub-struct scalar accessor on the M3 mesh-slot family
/// (opens the "per-`CircuitBreaker` / per-`RateLimit` required-axis
/// scalar" projection pattern the sibling `CircuitBreaker::window` /
/// `RateLimit::rate` / `RateLimit::window` future lifts fold on —
/// closes the last unlifted per-`:politicas` scalar-value axis after
/// the c0110f1 / bdfb399 / 7073d0f trajectory closed every scalar-
/// shaped axis on the parent [`MeshPolicy`] optional-slot surface).
/// Same "one typed dispatch on the substrate primitive, thin
/// projections at each consumer" discipline the peer
/// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
/// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
/// [`Membro::versao_requirement`] (a40b0e3),
/// [`Entrada::destination`] (6db982c) accessors carry on their
/// respective per-mesh-slot-atom scalar-value axes, extended onto the
/// per-sub-struct required-`u32` axis. Named `max_failures()` to
/// match the storage field's name; the accessor's identity maps onto
/// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
/// docstring already carries.
#[must_use]
pub const fn max_failures(&self) -> u32 {
self.max_failures
}
/// Substrate-canonical per-`:politicas :circuit-breaker` `:window`
/// Envoy-outlier-detection rolling-observation-interval scalar
/// accessor every consumer of the Aplicacao's per-`:contratos`-edge
/// breaker rolling-window duration keys off — returns the
/// author-declared `:politicas :circuit-breaker :window` typed
/// `Duration` verbatim, copied out of the typed slot's own
/// `Duration` storage (`Duration` is `Copy`, so the accessor returns
/// by value; no borrow of `&self` past the call). Non-optional (the
/// surrounding `Option<CircuitBreaker>` is the "slot present?"
/// projection at the parent [`MeshPolicy::circuit_breaker`] axis; a
/// `CircuitBreaker` past pattern-match is definitionally present,
/// and its `:window` field carries the rolling-observation interval
/// as a required-axis scalar).
///
/// The `:politicas :circuit-breaker :window` axis carries the
/// "consecutive-transient-failure rolling-observation interval"
/// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
/// `Duration` accept-set (zero-floor rejected through
/// [`AplicacaoError::PolicyBreakerZeroWindow`], sub-millisecond
/// residue rejected through
/// [`AplicacaoError::PolicyBreakerWindowNotCanonical`],
/// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`]) maps onto the
/// Envoy `outlier_detection.interval` per-cluster
/// ejection-observation-interval scalar (equivalently the future
/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
/// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
/// consumer that reads the rolling-observation interval keys off
/// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
/// integer-millisecond canonical-form + cap bracket at
/// caixa-core/src/aplicacao.rs:4121 that gates on the canonical
/// [`crate::render::require_positive_canonical_bounded_duration`]
/// helper, the future M4 per-Aplicacao Envoy config reconciler
/// materialization pass, the future per-`:contratos`-edge
/// breaker-override overlay the MESH-COMPOSITION §III.2 #3 roadmap
/// acknowledges).
///
/// Prior to this lift the `.window` field was accessed inline at
/// one production site — [`AplicacaoSpec::validate_politicas`]'s
/// `require_positive_canonical_bounded_duration(cb.window, …)`
/// call — one open-coded field-access that expressed no compile-
/// time link back to the typed sub-struct axis. A future extension
/// of the `:window` axis to a richer author surface — a
/// per-`:contratos`-edge window override the operator pins through
/// a future `:contratos :window` slot the MESH-COMPOSITION §III.2
/// #3 roadmap acknowledges, a per-cluster window-default overlay
/// the M4 CR materializer resolves per-CR, a promotion of the plain
/// `Duration` observation interval to a richer
/// `{interval, base_ejection_time, max_ejection_percent}` tuple
/// once Envoy's `outlier_detection` block's peer axes come into
/// scope, a per-Envoy-cluster minimum-request-volume gate before
/// the window arms — would have had to be threaded through every
/// open-coded copy in lockstep or the validate gate and the future
/// M4 emit path would silently disagree on which observation
/// interval a given [`CircuitBreaker`] resolves to (an author's
/// `:window "60s"` would satisfy validate while the emit path
/// silently read a drifted other value, or vice versa: a validated
/// typed slot would land at the emit boundary as a breaker whose
/// observation window is structurally so wide that no realistic
/// failure-rate shape can trip it). Lifting the resolution to a
/// typed method on the substrate primitive means every downstream
/// consumer of the Aplicacao's per-`:politicas :circuit-breaker`
/// observation-window surface reaches for exactly one typed
/// dispatch — the resolver's accept-set migrates as a unit on any
/// future axis addition.
///
/// Second sub-struct scalar accessor on the M3 mesh-slot family —
/// sibling in shape to the just-landed [`CircuitBreaker::max_failures`]
/// (3a74062) required-`u32` accessor on the peer per-`CircuitBreaker`
/// required-axis, extended onto the per-sub-struct required-`Duration`
/// axis; closes the last unlifted per-`CircuitBreaker` scalar-value
/// axis. Same "one typed dispatch on the substrate primitive, thin
/// projections at each consumer" discipline the peer
/// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
/// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
/// [`Membro::versao_requirement`] (a40b0e3),
/// [`Entrada::destination`] (6db982c) accessors carry on their
/// respective per-mesh-slot-atom scalar-value axes, extended onto
/// the per-sub-struct required-`Duration` axis. Named `window()` to
/// match the storage field's name; the accessor's identity maps onto
/// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
/// docstring already carries.
#[must_use]
pub const fn window(&self) -> Duration {
self.window
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RateLimit {
/// Requests per window.
pub rate: u32,
/// Window duration.
pub window: Duration,
}
impl RateLimit {
/// Substrate-canonical per-`:politicas :rate-limit` `:rate`
/// Envoy-local-rate-limit-mesh token-bucket capacity scalar accessor
/// every consumer of the Aplicacao's per-`:contratos`-edge
/// rate-limit-bucket capacity keys off — returns the author-declared
/// `:politicas :rate-limit` typed `u32` verbatim, copied out of the
/// typed slot's own `u32` storage (`u32` is `Copy`, so the accessor
/// returns by value; no borrow of `&self` past the call). Non-optional
/// (the surrounding `Option<RateLimit>` is the "slot present?"
/// projection at the parent [`MeshPolicy::rate_limit`] axis; a
/// `RateLimit` past pattern-match is definitionally present, and its
/// `:rate` field carries the token-bucket capacity as a required-axis
/// scalar).
///
/// The `:politicas :rate-limit` `:rate` axis carries the
/// "token-bucket capacity" contract (MESH-COMPOSITION §III.2 #3) —
/// the typed slot's `u32` accept-set (zero-floor rejected through
/// [`AplicacaoError::PolicyRateLimitZero`], upper-bounded by
/// [`POLICY_RATE_LIMIT_MAX`]) maps onto the Envoy
/// `local_rate_limit.token_bucket.max_tokens` per-cluster
/// token-bucket-capacity scalar (equivalently the future
/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
/// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
/// consumer that reads the token-bucket capacity keys off this
/// scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
/// cap bracket that gates on the canonical
/// [`crate::render::require_positive_bounded_u32`] helper, the
/// [`rate_limit_codec::render`] `Duration → unit` projection that
/// emits the `<n>/<s|m|h>` author surface, the future M4
/// per-Aplicacao Envoy config reconciler materialization pass, the
/// future per-`:contratos`-edge rate-limit-override overlay the
/// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
///
/// Prior to this lift the `.rate` field was accessed inline at three
/// production sites — [`AplicacaoSpec::validate_politicas`]'s
/// `require_positive_bounded_u32(rl.rate, …)` call, and the two
/// [`rate_limit_codec::render`] format-arm arms (canonical-window
/// `format!("{}/{unit}", rl.rate)` and non-canonical-window
/// `format!("{}/{}s", rl.rate, …)` fallback). Three open-coded
/// field-accesses that expressed no compile-time link back to the
/// typed sub-struct axis. A future extension of the `:rate` axis
/// to a richer author surface — a per-`:contratos`-edge rate
/// override the operator pins through a future `:contratos :rate`
/// slot the MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a
/// per-cluster rate-default overlay the M4 CR materializer resolves
/// per-CR, a promotion of the plain `u32` token capacity to a
/// richer `{max_tokens, tokens_per_fill}` tuple once Envoy's
/// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
/// axis comes into scope, a per-Envoy-cluster descriptor-key gate
/// before the token arms — would have had to be threaded through
/// every open-coded copy in lockstep or the validate gate, the
/// codec's render path, and the future M4 emit path would silently
/// disagree on which token capacity a given [`RateLimit`] resolves
/// to (an author's `:rate-limit "100/s"` would satisfy validate
/// while the render / emit paths silently read a drifted other
/// value, or vice versa: a validated typed slot would land at the
/// emit boundary as a no-op limiter whose token capacity is
/// structurally so high that no realistic per-edge traffic shape
/// can drain it). Lifting the resolution to a typed method on the
/// substrate primitive means every downstream consumer of the
/// Aplicacao's per-`:politicas :rate-limit` token-capacity surface
/// reaches for exactly one typed dispatch — the resolver's
/// accept-set migrates as a unit on any future axis addition.
///
/// First sub-struct scalar accessor on the `RateLimit` axis — sibling
/// in shape to the peer per-`CircuitBreaker`
/// [`CircuitBreaker::max_failures`] (3a74062) required-`u32` accessor
/// on the peer per-sub-struct required-axis, extended onto the
/// per-`RateLimit` required-`u32` axis; opens the "per-`RateLimit`
/// required-axis scalar" projection pattern the sibling
/// [`RateLimit::window`] future lift folds on. Same "one typed
/// dispatch on the substrate primitive, thin projections at each
/// consumer" discipline the peer [`WitContract::source`] /
/// [`WitContract::destination`] (7f0fd43), [`WitContract::world_ref`]
/// (0804823), [`Membro::nome`] (4a32abf),
/// [`Membro::versao_requirement`] (a40b0e3),
/// [`Entrada::destination`] (6db982c),
/// [`CircuitBreaker::max_failures`] (3a74062),
/// [`CircuitBreaker::window`] (373957f) accessors carry on their
/// respective per-mesh-slot-atom scalar-value axes. Named `rate()`
/// to match the storage field's name; the accessor's identity maps
/// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
/// docstring already carries.
#[must_use]
pub const fn rate(&self) -> u32 {
self.rate
}
/// Substrate-canonical per-`:politicas :rate-limit` `:window`
/// Envoy-local-rate-limit-mesh token-bucket refill-period scalar
/// accessor every consumer of the Aplicacao's per-`:contratos`-edge
/// rate-limit-bucket refill period keys off — returns the
/// author-declared `:politicas :rate-limit` typed `Duration`
/// verbatim, copied out of the typed slot's own `Duration` storage
/// (`Duration` is `Copy`, so the accessor returns by value; no
/// borrow of `&self` past the call). Non-optional (the surrounding
/// `Option<RateLimit>` is the "slot present?" projection at the
/// parent [`MeshPolicy::rate_limit`] axis; a `RateLimit` past
/// pattern-match is definitionally present, and its `:window`
/// field carries the token-bucket refill period as a required-axis
/// scalar).
///
/// The `:politicas :rate-limit` `:window` axis carries the
/// "token-bucket refill period" contract (MESH-COMPOSITION §III.2 #3)
/// — the typed slot's `Duration` accept-set (constrained to the
/// three canonical windows `{1s, 60s, 3600s}` the
/// [`RATE_LIMIT_UNIT_TABLE`] lifts, rejected off-set through
/// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]) maps
/// onto the Envoy `local_rate_limit.token_bucket.fill_interval`
/// per-cluster token-bucket-refill-period scalar (equivalently the
/// future `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
/// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
/// consumer that reads the token-bucket refill period keys off
/// this scalar (the [`AplicacaoSpec::validate_politicas`]
/// canonical-window gate that keys off
/// [`is_canonical_rate_limit_window`], the
/// [`rate_limit_codec::render`] `Duration → unit` projection that
/// emits the `<n>/<s|m|h>` author surface — canonical arm via
/// [`rate_limit_window_unit`] and non-canonical fallback via
/// `.as_secs()`, the future M4 per-Aplicacao Envoy config
/// reconciler materialization pass, the future per-`:contratos`-
/// edge rate-limit-override overlay the MESH-COMPOSITION §III.2 #3
/// roadmap acknowledges).
///
/// Prior to this lift the `.window` field was accessed inline at
/// three production sites — [`AplicacaoSpec::validate_politicas`]'s
/// `is_canonical_rate_limit_window(rl.window)` shape-gate call
/// plus the sibling [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]
/// error-payload construction on refusal, and the two
/// [`rate_limit_codec::render`] arms
/// (canonical-window `rate_limit_window_unit(rl.window)` dispatch
/// and non-canonical-window `rl.window.as_secs()` fallback). Three
/// open-coded field-accesses that expressed no compile-time link
/// back to the typed sub-struct axis. A future extension of the
/// `:window` axis to a richer author surface — a per-`:contratos`-
/// edge window override the operator pins through a future
/// `:contratos :window` slot the MESH-COMPOSITION §III.2 #3 roadmap
/// acknowledges, a per-cluster window-default overlay the M4 CR
/// materializer resolves per-CR, a promotion of the plain
/// `Duration` refill period to a richer
/// `{fill_interval, tokens_per_fill}` tuple once Envoy's
/// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
/// axis comes into scope, an addition of a `"d"` day suffix once
/// Envoy's `rate_limit_action` grows daily-bucket support — would
/// have had to be threaded through every open-coded copy in
/// lockstep or the validate gate, the codec's render path, and
/// the future M4 emit path would silently disagree on which
/// refill period a given [`RateLimit`] resolves to (an author's
/// `:rate-limit "100/s"` would satisfy validate while the render
/// / emit paths silently read a drifted other value, or vice
/// versa: a validated typed slot would land at the emit boundary
/// as a limiter whose refill period is structurally so long that
/// no realistic per-edge traffic shape stays inside the token
/// budget). Lifting the resolution to a typed method on the
/// substrate primitive means every downstream consumer of the
/// Aplicacao's per-`:politicas :rate-limit` refill-period surface
/// reaches for exactly one typed dispatch — the resolver's
/// accept-set migrates as a unit on any future axis addition.
///
/// Second sub-struct scalar accessor on the `RateLimit` axis —
/// sibling in shape to the just-landed [`RateLimit::rate`]
/// (7f81a60) required-`u32` accessor on the peer per-`RateLimit`
/// required-axis, extended onto the per-sub-struct
/// required-`Duration` axis; closes the last unlifted
/// per-`RateLimit` scalar-value axis (the M3 mesh-slot family's
/// per-sub-struct accessor coverage is now complete across both
/// `CircuitBreaker` and `RateLimit`). Same "one typed dispatch on
/// the substrate primitive, thin projections at each consumer"
/// discipline the peer [`CircuitBreaker::max_failures`] (3a74062),
/// [`CircuitBreaker::window`] (373957f), [`RateLimit::rate`]
/// (7f81a60), [`WitContract::source`] / [`WitContract::destination`]
/// (7f0fd43), [`WitContract::world_ref`] (0804823),
/// [`Membro::nome`] (4a32abf),
/// [`Membro::versao_requirement`] (a40b0e3),
/// [`Entrada::destination`] (6db982c) accessors carry on their
/// respective per-mesh-slot-atom scalar-value axes. Named
/// `window()` to match the storage field's name; the accessor's
/// identity maps onto the canonical MESH-COMPOSITION §III.2
/// vocabulary the slot's docstring already carries.
#[must_use]
pub const fn window(&self) -> Duration {
self.window
}
/// Recognize this rate-limit's `:window` as a canonical
/// [`RateLimitUnit`] arm — `Some(RateLimitUnit)` when the window
/// exactly matches one of the three closed-set arm-Durations
/// (`1s` / `60s` / `3600s`), `None` when the window carries a
/// non-canonical magnitude the codec's round-trip would break on
/// (sub-second residue, or a second-magnitude outside the set
/// [`RateLimitUnit::ALL`] enumerates).
///
/// Every validated [`RateLimit`] past [`AplicacaoSpec::validate_politicas`]
/// returns `Some` here — the validate gate's
/// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`] arm
/// rejects every window this accessor returns `None` on. Downstream
/// consumers past validate (the codec's [`rate_limit_codec::render`]
/// path, the future M4 per-Aplicacao Envoy config reconciler's
/// materialization pass, the future per-`:contratos`-edge rate-limit-
/// override overlay the MESH-COMPOSITION §III.2 #3 roadmap
/// acknowledges) that read the typed unit off a validated slot can
/// pattern-match on the returned `Some` without re-checking
/// canonicality at the consumer layer — the typed enum surface is
/// the load-bearing carrier of the canonicality invariant.
///
/// Preferred over the free [`is_canonical_rate_limit_window`]
/// module-private helper at any call site that has the typed
/// [`RateLimit`] in hand (the codec's `render` arm at
/// [`rate_limit_codec::render`], the validate gate's canonical-form
/// arm in [`AplicacaoSpec::validate_politicas`], any future
/// per-`:contratos` edge-override overlay resolver): those consumers
/// reach for the typed enum without going through the
/// `.window()` scalar-projection layer, and get the enum value
/// directly (which the codec's render arm can then format via
/// [`RateLimitUnit::as_suffix`] / [`std::fmt::Display`]). Same
/// "typed sub-struct scalar accessor, one dispatch on the substrate
/// primitive" discipline the sibling [`RateLimit::rate`] and
/// [`RateLimit::window`] accessors carry on the peer per-sub-struct
/// scalar-value axes, extended onto the per-`RateLimit` typed-unit
/// projection axis (the third scalar accessor on the [`RateLimit`]
/// axis, first typed-enum-return projection).
///
/// `pub const fn` — the typed-`RateLimit`-projection dispatch onto
/// the canonical [`RateLimitUnit`] arm now carries the same
/// `const`-eval-surface posture the sibling `pub const fn`
/// [`Self::rate`] / [`Self::window`] scalar-projection accessors on
/// this typed sub-struct already carry, composing through the
/// peer-lifted `pub const fn` [`RateLimitUnit::from_window`]
/// reverse-resolver in `const` context. Any downstream substrate-
/// side `const`-context consumer of the typed unit (a module-scope
/// `const _:() = assert!(matches!(rl.canonical_unit(), Some(RateLimitUnit::Second)))`
/// invariant pin on a typed fixture, a future M4 admission-webhook
/// `const fn` per-`:politicas :rate-limit :window` canonical-arm
/// resolver over a typed [`RateLimit`], any future `const fn`
/// per-`:contratos`-edge rate-limit-override overlay resolver over
/// the substrate primitive) now reaches the same typed dispatch on
/// the substrate primitive at const-eval time as at runtime.
///
/// Pinned load-bearing at the substrate-primitive level by
/// [`tests::rate_limit_canonical_unit_accessor_is_const_fn`] (const-
/// eval-surface pin via `const fn` wrapper).
#[must_use]
pub const fn canonical_unit(&self) -> Option<RateLimitUnit> {
RateLimitUnit::from_window(self.window)
}
}
/// Typed closed-set enum for the three canonical `:politicas :rate-limit`
/// `:window` units — `Second` / `Minute` / `Hour` — the `rate_limit_codec`
/// round-trips losslessly (`"<n>/s"` / `"<n>/m"` / `"<n>/h"`).
///
/// The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer of
/// the `:politicas :rate-limit` unit surface reads from
/// ([`rate_limit_codec::parse`]'s `unit → Duration` dispatch,
/// [`rate_limit_codec::render`]'s `Duration → unit` projection, the
/// [`is_canonical_rate_limit_window`] predicate the
/// [`AplicacaoSpec::validate_politicas`] gate keys off, the future M4
/// per-Aplicacao Envoy config reconciler's `local_rate_limit.token_bucket.fill_interval`
/// projection) now lives inside this typed enum's `match self` arms — a
/// future rate-limit-unit addition (a `"d"` day suffix once Envoy's
/// `rate_limit_action` grows daily-bucket support) is one new variant
/// plus the exhaustiveness arms on the four methods, so every consumer
/// picks it up by compile-time construction rather than a runtime
/// table-scan miss.
///
/// The prior `RATE_LIMIT_UNIT_TABLE: &[(&str, u64)]` slice-of-tuples was
/// scanned via `find_map` at every projection call — an untyped runtime
/// walk that carried no compile-time link between the parse arm's
/// accepted suffixes, the render arm's emitted suffixes, and the
/// validate gate's accepted windows. A future rate-limit-unit addition
/// that landed one row without threading through the other consumers
/// (or a copy-paste flip that collapsed two rows onto one suffix) would
/// silently split the accepted-set across the three consumers — the
/// parse arm accepts `"d"` and rejects `"s"`, the render arm emits `"h"`
/// for a 24h window that parse can't round-trip, the validate gate
/// misses one canonical window. Lifting the pairs onto a typed
/// closed-set enum with exhaustive `match` arms makes any such
/// half-landed extension a caixa-core build error (the compiler enforces
/// arm coverage on every method), not a silent per-consumer drift
/// surfacing at apply time. Same "closed-set typed-enum discriminator"
/// discipline the sibling [`PlacementStrategy`] (cc8f749),
/// [`crate::supervisor::RestartStrategy`],
/// [`crate::supervisor::RestartPolicy`],
/// [`crate::upgrade::UpgradeInstruction`], and [`crate::CaixaKind`]
/// closed-set typed enums carry on their respective closed-set axes —
/// extended onto the seventh closed-set typed-enum discriminator axis
/// on the caixa typed surface (the `:politicas :rate-limit :window`
/// canonical-unit axis).
#[derive(
Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
)]
pub enum RateLimitUnit {
/// 1-second window — canonical author-surface suffix `"s"`
/// (`"<n>/s"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
/// with a 1s magnitude.
Second,
/// 1-minute window — canonical author-surface suffix `"m"`
/// (`"<n>/m"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
/// with a 60s magnitude.
Minute,
/// 1-hour window — canonical author-surface suffix `"h"`
/// (`"<n>/h"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
/// with a 3600s magnitude.
Hour,
}
impl RateLimitUnit {
/// Exhaustive iteration surface for every consumer that reads the
/// full canonical-unit set (the byte-parity witness against the
/// prior `RATE_LIMIT_UNIT_TABLE` shape, the future M4 admission
/// webhook's accepted-suffix listing in its rejection body, any
/// future round-trip fuzz harness). A future variant addition to
/// [`RateLimitUnit`] extends this slice as a single edit and every
/// consumer picks up the new entry by construction — the compiler-
/// checked exhaustiveness on the sibling method `match` arms is the
/// build-time guarantee that no arm forgets to grow.
pub const ALL: &'static [Self] = &[Self::Second, Self::Minute, Self::Hour];
/// Canonical author-surface suffix — the `"s"` / `"m"` / `"h"` byte-
/// string every `<n>/<unit>` rate-limit shape carries after its
/// `/` separator. The single source of truth the codec's parse and
/// render arms both dispatch on: the parse arm matches an incoming
/// suffix against every [`RateLimitUnit::ALL`] entry's `as_suffix`
/// output; the render arm emits the entry's `as_suffix` verbatim
/// after the rate magnitude.
#[must_use]
pub const fn as_suffix(self) -> &'static str {
match self {
Self::Second => "s",
Self::Minute => "m",
Self::Hour => "h",
}
}
/// Canonical `Duration` for this unit — the token-bucket refill
/// period the [`RateLimit::window`] axis carries when the surrounding
/// slot's `:rate-limit` author surface named this unit.
#[must_use]
pub const fn window(self) -> Duration {
Duration::from_secs(match self {
Self::Second => 1,
Self::Minute => 60,
Self::Hour => 3_600,
})
}
/// Parse the `<n>/<unit>`-shaped suffix into the typed enum, or
/// `None` when `suffix` is outside the closed-set arm-string set
/// [`Self::as_suffix`] emits. The single `str → Self` projection
/// [`rate_limit_codec::parse`] consumes.
#[must_use]
pub fn from_suffix(suffix: &str) -> Option<Self> {
Self::ALL.iter().copied().find(|u| u.as_suffix() == suffix)
}
/// Recognize a canonical rate-limit `Duration` as one of the three
/// arms, or `None` when `window` carries sub-second residue or a
/// second-magnitude outside the closed-set arm-window set
/// [`Self::window`] emits. The single `Duration → Self` projection
/// [`rate_limit_codec::render`] + [`is_canonical_rate_limit_window`]
/// both consume.
///
/// `pub const fn` — the reverse `Duration → Self` projection now
/// carries the same `const`-eval-surface posture the sibling
/// `pub const fn` [`Self::as_suffix`] / [`Self::window`] scalar-
/// projection accessors on this closed-set typed enum already
/// carry, and the paired `pub const fn` [`RateLimit::canonical_unit`]
/// typed-`RateLimit`-projection sibling composes through in `const`
/// context. Routes byte-for-byte through the peer `pub const fn`
/// [`Self::window`] canonical-`Duration` projection so any future
/// arm-magnitude edit on the sibling accessor reaches this reverse
/// resolver by construction — the `s == Self::<Arm>.window().as_secs()`
/// per-arm probes each dispatch through one `pub const fn` on the
/// substrate primitive rather than a hand-authored per-arm second-
/// magnitude literal that would silently drift on any future
/// [`Self::window`] arm-magnitude edit.
///
/// Prior to the `const` lift the body dispatched through
/// `Self::ALL.iter().copied().find(|u| u.window() == window)` — an
/// iterator-driven linear scan whose iterator methods
/// (`.iter()` / `.copied()` / `.find()`) and `Duration`-side
/// `PartialEq` dispatch each carry non-`const` bounds on stable
/// Rust 1.94, so any downstream substrate-side `const`-context
/// consumer of the reverse resolver (a module-scope
/// `const _:() = assert!(RateLimitUnit::from_window(<canonical>).is_some())`
/// invariant pin on a typed fixture, a future M4
/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer admission-
/// webhook `const fn` per-`:politicas` canonical-window floor over a
/// typed [`RateLimit`] scalar, any future `const fn`
/// per-`:contratos`-edge rate-limit-override overlay resolver over
/// the substrate primitive that wants to fan on the canonical unit
/// at compile time) surfaced as a downstream E0015 far from the
/// resolver's own declaration. The `pub const fn` posture closes
/// the drift structurally at caixa-core build time.
///
/// Pinned load-bearing at the substrate-primitive level by
/// [`tests::rate_limit_unit_from_window_accessor_is_const_fn`] (const-
/// eval-surface pin via `const fn` wrapper) and
/// [`tests::rate_limit_unit_from_window_composes_through_window_accessor`]
/// (composition-witness pin against the peer `Self::window` scalar
/// dispatch).
#[must_use]
pub const fn from_window(window: Duration) -> Option<Self> {
if window.subsec_nanos() != 0 {
return None;
}
// Route through the peer `pub const fn` [`Self::window`]
// canonical-`Duration` projection so any future arm-magnitude
// edit on the sibling accessor reaches this reverse resolver by
// construction — the per-arm `secs` comparison keys off
// `Duration::as_secs` (`pub const fn`), not a hand-authored
// per-arm second-magnitude literal that would silently drift.
let secs = window.as_secs();
if secs == Self::Second.window().as_secs() {
Some(Self::Second)
} else if secs == Self::Minute.window().as_secs() {
Some(Self::Minute)
} else if secs == Self::Hour.window().as_secs() {
Some(Self::Hour)
} else {
None
}
}
/// Canonical rate-limit `Duration` for a unit suffix, or `None` when
/// `suffix` is outside the closed-set arm-string set [`Self::as_suffix`]
/// emits. Composes [`Self::from_suffix`] with [`Self::window`] — the
/// single `&str → Duration` projection [`rate_limit_codec::parse`]
/// consumes.
///
/// The peer `Duration → &'static str` axis folded onto the substrate
/// primitive [`RateLimit::canonical_unit`] typed accessor once both
/// production consumers ([`rate_limit_codec::render`] and
/// [`AplicacaoSpec::validate_politicas`]'s canonical-window gate)
/// migrated (61421a6): the free helper's `Duration → &str` projection
/// is now the two-step composition
/// `rl.canonical_unit().map(RateLimitUnit::as_suffix)` every consumer
/// reads through the typed accessor. This lift closes the peer
/// `&str → Duration` axis by folding the vestigial module-private
/// `rate_limit_window_from_unit` delegate onto this associated method
/// — the codec's parse arm and every future wire-side consumer of the
/// `&str → Duration` projection (a future admission-webhook that
/// reads a `:rate-limit` shape off a CR spec's `raw string` value
/// before it's promoted to a validated typed slot, a future
/// `feira lint` shape-probe that reads the author-surface bytes
/// verbatim) now reach for exactly one typed dispatch on the
/// substrate primitive.
///
/// Same "closed-set typed-enum discriminator with canonical
/// projections per axis" discipline the sibling [`Self::as_suffix`]
/// / [`Self::window`] / [`Self::from_suffix`] / [`Self::from_window`]
/// methods carry — this associated method closes the fifth (and last
/// unlifted) projection axis on the arm-table, so the closed-set enum
/// now owns every `str ↔ Duration ↔ Self` typed dispatch every
/// consumer of the `:politicas :rate-limit :window` axis reaches
/// through. A future rate-limit-unit addition (a `"d"` day suffix
/// once Envoy's `rate_limit_action` grows daily-bucket support, a
/// `"ms"` sub-second window once high-throughput per-edge policies
/// come into scope per MESH-COMPOSITION §III.2 #3) is one new
/// variant plus one arm per method — the compiler enforces
/// exhaustiveness on every consumer's `match self` arms and picks
/// the new unit up by construction across all five projections.
#[must_use]
pub fn window_from_suffix(suffix: &str) -> Option<Duration> {
Self::from_suffix(suffix).map(Self::window)
}
}
/// Route [`std::fmt::Display`] through [`RateLimitUnit::as_suffix`], so
/// every consumer that formats a canonical rate-limit unit as user-
/// facing text (future M4 admission-webhook rejection bodies naming
/// the accepted-suffix set, future `feira app graph` per-`:politicas`
/// unit column) lands on the same `"s"` / `"m"` / `"h"` byte-string the
/// codec's parse arm accepts and the render arm emits. Same
/// as_str-through-Display convergence discipline the sibling
/// [`PlacementStrategy`], [`crate::CaixaKind`],
/// [`crate::supervisor::RestartStrategy`], and
/// [`crate::supervisor::RestartPolicy`] closed-set typed enums carry.
impl std::fmt::Display for RateLimitUnit {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_suffix())
}
}
/// Substrate-canonical [`AsRef<str>`] projection on the M3
/// `:politicas :rate-limit` closed-set typed unit-suffix enum —
/// routes through the same [`RateLimitUnit::as_suffix`] `pub const fn`
/// scalar accessor the paired [`std::fmt::Display`] impl already
/// delegates through, so any future consumer that binds a
/// [`RateLimitUnit`] through the standard-library `impl AsRef<str>`
/// bound (a [`std::process::Command::arg`] shell-out that composes the
/// canonical suffix into an Envoy sidecar config-CLI's per-`:politicas`
/// `--rate-limit-unit <s|m|h>` arg on the future
/// `CiliumClusterwideEnvoyConfig` overlay MESH-COMPOSITION §III.2 #3
/// names, a `tracing::field::Value::Str`-arm structured-log recorder
/// on the future `app-operator`'s per-`:politicas :rate-limit`
/// reconcile step, a [`std::collections::HashMap`] lookup keyed on
/// the canonical suffix through `map.get::<str>(unit.as_ref())` on a
/// future per-unit token-bucket-refill dispatch table the future M4
/// admission-webhook rejection body composes) reaches the paired
/// `"s"` / `"m"` / `"h"` byte-string through one substrate-primitive
/// dispatch rather than an open-coded `.as_suffix()` re-inlining at
/// every wire-up.
///
/// Deliberately routes through the canonical suffix axis, not the
/// second-magnitude [`RateLimitUnit::window`] axis — `AsRef<str>` and
/// [`fmt::Display`] land on the same author-surface-canonical byte-
/// string the codec's parse and render arms both dispatch on, while
/// the token-bucket-refill period stays reachable only through the
/// explicit [`RateLimitUnit::window`] / [`RateLimitUnit::from_window`]
/// paths.
///
/// Same "route the trait impl through the substrate-primitive
/// accessor" discipline the sibling [`crate::CaixaVersion`]
/// [`AsRef<str>`] impl (16d5c7e), the paired M2
/// [`crate::supervisor::RestartStrategy`] [`AsRef<str>`] impl
/// (63eb1a4), the paired M2 [`crate::supervisor::RestartPolicy`]
/// [`AsRef<str>`] impl (419ea81), the M3
/// [`PlacementStrategy`] [`AsRef<str>`] impl (d86edd2), and the
/// top-level [`crate::CaixaKind`] [`AsRef<str>`] impl (cd2091f) carry
/// — closes the substrate primitive's [`AsRef<str>`] projection axis
/// onto the last remaining closed-set typed enum with a
/// [`fmt::Display`] surface, so every closed-set typed enum / newtype
/// on the caixa surface (top-level `:kind`, both M2
/// `:supervisor`-slot per-child and sibling-restart typed enums, the
/// M3 `:placement :estrategia` typed enum, the M3
/// `:politicas :rate-limit` unit-suffix typed enum, and the `:versao`
/// typed newtype) now carries the paired [`AsRef<str>`] +
/// [`fmt::Display`] + `as_*` triple through one lifted-const family.
///
/// Pinned load-bearing by
/// [`tests::rate_limit_unit_as_ref_str_routes_through_as_suffix_accessor`]
/// (byte-parity pin against [`RateLimitUnit::as_suffix`] across the
/// three-arm closed set) and
/// [`tests::rate_limit_unit_as_ref_str_routes_through_display_via_shared_accessor`]
/// (three-path convergence: `AsRef<str>` + `Display` + `as_suffix`
/// all resolve to the same byte-string per arm) — any future silent
/// detour that routes the impl through a divergent projection (a
/// per-arm inline `match self { … }` re-inlining that opens a compile-
/// time link to the un-lifted arm-literal, a swap onto the
/// second-magnitude [`RateLimitUnit::window`] axis that would collide
/// the canonical-suffix / token-bucket-refill two-axis split) trips at
/// caixa-core test time under `assert_eq!` rather than at a downstream
/// `impl AsRef<str>`-bound consumer's silent split.
impl AsRef<str> for RateLimitUnit {
fn as_ref(&self) -> &str {
self.as_suffix()
}
}
/// Trait-idiomatic reverse projection on the M3-mesh-primitive-defining
/// [`RateLimitUnit`] closed-set typed enum — routes byte-for-byte through
/// the paired substrate-primitive [`RateLimitUnit::from_suffix`]
/// `Option<Self>` accessor so every future consumer that binds a
/// canonical `:politicas :rate-limit` unit-suffix byte-string through the
/// standard-library `.try_into()` / [`TryFrom`] axis (a future
/// `feira app policy --rate-limit-unit <s|m|h>` CLI arg-parse that
/// composes into `let unit: RateLimitUnit = s.try_into()?`, a future
/// `mesh.pleme.io/v1alpha1/Aplicacao` CR admission-webhook that folds a
/// `spec.politicas.rateLimit.unit: String` field through
/// `RateLimitUnit::try_from(&s)?`, a generic `<T: TryFrom<&str>>`-bound
/// loader over any of the substrate's closed-set typed enums) reaches
/// the same three-arm accept-set the sibling
/// [`RateLimitUnit::from_suffix`] resolver parses through and the sibling
/// [`RateLimitUnit::as_suffix`] emits, rather than an open-coded per-arm
/// `match s { "s" => …, "m" => …, "h" => …, _ => … }` cascade whose
/// arm-set has no compile-time link back to the substrate primitive.
///
/// Complements the pre-existing forward-projection triple
/// ([`std::fmt::Display`], [`AsRef<str>`], [`RateLimitUnit::as_suffix`])
/// with the paired trait-idiomatic reverse-projection axis: Rust-side
/// newtype/typed-enum convention pairs [`AsRef<str>`] with either
/// [`std::str::FromStr`] or [`TryFrom<&str>`] on the same primitive so
/// a caller who can project *out to* a `&str` can also project *in
/// from* one. The [`TryFrom<&str>`] axis is deliberately chosen over
/// [`std::str::FromStr`] to sidestep the `clippy::should_implement_trait`
/// lint the sibling method-named [`RateLimitUnit::from_suffix`] would
/// trigger under a `FromStr` impl (the same design tradeoff the peer
/// [`crate::CaixaKind`] (3c83606), [`crate::CaixaDialeto`] (bf33136),
/// [`PlacementStrategy`] (6fd00cd), [`crate::supervisor::RestartStrategy`]
/// (5b828ed), [`crate::supervisor::RestartPolicy`] (6fdd0d9), and
/// [`WitShape`] (5472902) blocks note) — this impl closes the trait-
/// idiomatic reverse axis without disturbing the method-named
/// `from_suffix` shape the peer closed-set typed enums already carry.
///
/// `type Error = ()` matches the sibling [`RateLimitUnit::from_suffix`]'s
/// `Option<Self>` return-shape's deliberate deferral of error typing:
/// the caller picks the diagnostic form appropriate for its use site (a
/// future `feira app policy --rate-limit-unit` arg-parse composes its
/// own per-verb "unknown rate-limit unit: <arg> — accepted: {…}"
/// message enumerating [`RateLimitUnit::ALL`], a future M4 admission-
/// webhook rejection body wraps the `Err(())` outcome with the accepted-
/// set enumeration for operator diagnostics, a `Result::map_err` at the
/// call site lifts the unit-error to a per-verb error type). Same shape
/// the peer sibling reverse-projection axes carry.
///
/// The paired [`TryFrom<&str>`] impl reaches the same three-arm accept-
/// set the [`RateLimitUnit::from_suffix`] resolver dispatches through,
/// so any future arm addition (a `"d"` day suffix once Envoy's
/// `rate_limit_action` grows daily-bucket support, a `"ms"` sub-second
/// window once high-throughput per-edge policies come into scope per
/// MESH-COMPOSITION §III.2 #3 — both trajectory items the sibling
/// [`RateLimitUnit::window_from_suffix`] doc block already names) grows
/// the trait-idiomatic axis by construction — one caixa-core edit on
/// [`RateLimitUnit::from_suffix`] extends both the method-named reverse
/// projection every existing consumer keys off and the trait-idiomatic
/// reverse projection this impl exposes, without a coordinated rewrite
/// across every future `TryFrom<&str>`-bound consumer's arm-set.
///
/// Extends the substrate-wide closed-set-enum trait-idiomatic reverse-
/// projection family ([`crate::CaixaKind`] via 3c83606,
/// [`crate::CaixaDialeto`] via bf33136, [`PlacementStrategy`] via
/// 6fd00cd, [`crate::supervisor::RestartStrategy`] via 5b828ed,
/// [`crate::supervisor::RestartPolicy`] via 6fdd0d9, [`WitShape`] via
/// 5472902) onto the third M3-mesh-primitive-defining slot enum on the
/// caixa surface — the `:politicas :rate-limit` unit-suffix closed set
/// the caixa-mesh renderer keys off end-to-end for per-Aplicacao Envoy
/// `local_rate_limit.token_bucket.fill_interval` overlay emission, and
/// the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR admission-
/// webhook's per-`:politicas` accept-set validation.
///
/// Pinned load-bearing by
/// [`tests::rate_limit_unit_try_from_str_routes_through_from_suffix_accessor`]
/// (byte-parity pin against [`RateLimitUnit::from_suffix`] across the
/// three-arm accept-set) and
/// [`tests::rate_limit_unit_try_from_str_rejects_unknown_byte_strings`]
/// (rejection witness against silent accept-set widening).
impl TryFrom<&str> for RateLimitUnit {
type Error = ();
fn try_from(s: &str) -> Result<Self, Self::Error> {
Self::from_suffix(s).ok_or(())
}
}
/// Standard-library trait-idiomatic forward projection on the
/// [`RateLimitUnit`] closed-set typed enum. Routes byte-for-byte through
/// the paired substrate-primitive [`RateLimitUnit::as_suffix`]
/// `pub const fn` accessor so `<&'static str>::from(unit)` /
/// `unit.into::<&'static str>()` reaches the same three-arm `"s"` /
/// `"m"` / `"h"` canonical-suffix emit-set the sibling method-named
/// accessor dispatches through and the sibling
/// [`std::fmt::Display for RateLimitUnit`] / [`AsRef<str> for RateLimitUnit`]
/// impls also route through.
///
/// Extends the substrate-wide closed-set-enum trait-idiomatic
/// forward-projection family
/// ([`crate::supervisor::RestartStrategy`] via 523157d,
/// [`crate::supervisor::RestartPolicy`] via 9fb37d0,
/// [`crate::CaixaKind`] via edb827b,
/// [`crate::CaixaDialeto`] via c189a6f,
/// [`PlacementStrategy`] via afa3562,
/// [`WitShape`] via 56998ec) onto the third
/// M3-mesh-primitive-defining slot enum on the caixa surface — the
/// `:politicas :rate-limit` canonical-unit-suffix closed set the
/// caixa-mesh renderer keys off end-to-end for per-Aplicacao Envoy
/// `local_rate_limit.token_bucket.fill_interval` overlay emission.
/// Pairs with the sibling [`TryFrom<&str> for RateLimitUnit`] impl
/// (bf78400) to close the two-way `Self ↔ &'static str` round-trip on
/// the trait-idiomatic axis pair, mirroring the pre-existing
/// method-named [`RateLimitUnit::as_suffix`] +
/// [`RateLimitUnit::from_suffix`] pair on the substrate-primitive axis
/// pair.
///
/// Return type is `&'static str` by construction — every
/// [`RateLimitUnit::as_suffix`] arm resolves to an inline
/// `"s"` / `"m"` / `"h"` `&'static str` literal, so the trait's
/// return-type promise is upheld structurally without a
/// [`String::leak`] cast or a per-arm inline literal outside the paired
/// [`RateLimitUnit::as_suffix`] dispatch.
///
/// Deliberately routes through the canonical-suffix axis, not the
/// second-magnitude [`RateLimitUnit::window`] axis — every closed-set
/// forward-projection path on the caixa surface lands on the same
/// author-surface-canonical byte-string the codec's parse and render
/// arms both dispatch on, while the token-bucket-refill period stays
/// reachable only through the explicit [`RateLimitUnit::window`] /
/// [`RateLimitUnit::from_window`] paths.
///
/// The paired [`RateLimitUnit::as_suffix`] accessor's three-arm emit-set
/// is the single source of truth — every future arm addition (a `"d"`
/// day suffix once Envoy's `rate_limit_action` grows daily-bucket
/// support, a `"ms"` sub-second window once high-throughput per-edge
/// policies come into scope per MESH-COMPOSITION §III.2 #3 — both
/// trajectory items the sibling [`RateLimitUnit::window_from_suffix`]
/// doc block already names) grows the trait-idiomatic forward axis by
/// construction: one caixa-core edit on [`RateLimitUnit::as_suffix`]
/// extends every one of the sibling forward-projection paths
/// ([`std::fmt::Display`], [`AsRef<str>`], [`RateLimitUnit::as_suffix`]
/// itself, and this [`From<Self> for &'static str`]) without a
/// coordinated rewrite across every future `Into<&'static str>`-bound
/// consumer's arm-set.
///
/// Pinned load-bearing by
/// [`tests::rate_limit_unit_from_into_static_str_routes_through_as_suffix_accessor`]
/// (byte-parity pin against [`RateLimitUnit::as_suffix`] across the
/// three-arm emit-set, plus a `const`-context materialization witness
/// for the `&'static str` lifetime promise routed through the paired
/// [`RateLimitUnit::as_suffix`] `pub const fn` accessor, plus a paired
/// `.into()` shape assertion covering the blanket-derived
/// `Into<&'static str>` shape) and
/// [`tests::rate_limit_unit_from_into_static_str_and_as_suffix_partition_the_emit_set`]
/// (partition pin asserting `<&'static str as
/// From<RateLimitUnit>>::from` and [`RateLimitUnit::as_suffix`] agree on
/// every arm, plus a two-way direct round-trip witness through the
/// paired trait-idiomatic [`TryFrom<&str>`] axis that closes the
/// two-way `Self ↔ &'static str` round-trip on the trait-idiomatic axis
/// pair — the emit-side [`RateLimitUnit::as_suffix`] and the parse-side
/// [`RateLimitUnit::from_suffix`] dispatch on the same three inline
/// canonical-suffix byte-strings by construction, so round-tripping
/// composes the two trait impls directly).
impl From<RateLimitUnit> for &'static str {
fn from(unit: RateLimitUnit) -> &'static str {
unit.as_suffix()
}
}
/// Trait-idiomatic *forward* projection on [`RateLimitUnit`] from a
/// *borrowed* input onto the `&'static str` axis — the borrowed-input
/// companion to the paired owned-input [`From<RateLimitUnit> for &'static
/// str`] impl immediately above. Routes byte-for-byte through the same
/// substrate-primitive [`RateLimitUnit::as_suffix`] `pub const fn`
/// accessor so every consumer that binds a `&RateLimitUnit` through the
/// standard-library `.into()` / [`From<&Self> for &'static str`] axis (a
/// `RateLimitUnit::ALL.iter().map(<&'static str>::from).collect::<Vec<_>>()`
/// per-arm accept-set materializer — whose iterator over
/// `&'static [RateLimitUnit]` yields `&RateLimitUnit`, not
/// `RateLimitUnit`, so the owned-input [`From<RateLimitUnit>`] axis alone
/// forces every call site through an explicit `.copied()` / dereference /
/// [`Copy`]-bound restatement rather than the direct trait-idiomatic
/// projection; a future generic `<T: Copy + for<'a> Into<&'static str>>`-
/// bound diagnostic column over the substrate-wide closed-set typed-enum
/// family that walks the `iter().map(Into::into)` shape verbatim; the
/// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR admission-webhook
/// rejection body that composes the accepted-`:politicas :rate-limit`
/// canonical-suffix enumeration from an iterated
/// `RateLimitUnit::ALL.iter().map(|u| u.into())` pipe rather than a per-
/// arm `match u { … }` cascade; a future
/// `HashMap::<&'static str, RateLimitUnit>::from_iter(
/// RateLimitUnit::ALL.iter().map(|u| (u.into(), *u)))`-style per-unit
/// reverse-lookup table the sibling [`TryFrom<&str>`] impl cannot compose
/// without this borrowed-input axis in place) reaches the same three-arm
/// `"s"` / `"m"` / `"h"` canonical-suffix emit-set the paired owned-input
/// [`From<RateLimitUnit> for &'static str`], the sibling
/// [`std::fmt::Display`], [`AsRef<str>`], and [`RateLimitUnit::as_suffix`]
/// surfaces already return.
///
/// Eighth peer on the substrate-wide trait-idiomatic *borrowed-input*
/// forward-projection family opened on [`crate::dep::DepList`] (64aa742)
/// and extended onto [`crate::CaixaKind`] (5ab993a),
/// [`crate::CaixaDialeto`] (807b0b5), the paired M2 OTP-shape
/// [`crate::supervisor::RestartStrategy`] (e941836) and
/// [`crate::supervisor::RestartPolicy`] (842c7f3), and the M3
/// mesh-primitive slot enums [`PlacementStrategy`] (4d941d8) and
/// [`WitShape`] (3187bd0). Rust's `From` trait does not auto-derive the
/// `From<&Self>` sibling from a `From<Self>` impl (the blanket
/// `impl<T, U> From<&T> for U where T: Copy, U: From<T>` does not exist
/// in `core`), so every closed-set typed enum that carries the owned-
/// input axis but not the borrowed-input axis forces every borrowed-input
/// call site through a `.copied()` / `<&'static str>::from(*unit)` /
/// `unit.as_suffix()` detour whose type bounds have no compile-time link
/// to the substrate primitive. [`RateLimitUnit`] is the *third* (and
/// last) M3-mesh-primitive-defining closed-set typed enum to converge
/// onto the substrate-wide borrowed-input campaign — the
/// [`PlacementStrategy`] first-mover (4d941d8) opened the M3-slot arm on
/// the `:placement :estrategia` axis, the [`WitShape`] follow-on
/// (3187bd0) closed the `:contratos :wit` census-label axis, and this
/// lift closes the `:politicas :rate-limit` canonical-suffix axis the
/// caixa-mesh renderer keys off end-to-end for per-Aplicacao Envoy
/// `local_rate_limit.token_bucket.fill_interval` overlay emission.
///
/// Same three-path convergence discipline as the paired owned-input impl
/// (this borrowed-input axis, the paired owned-input
/// [`From<RateLimitUnit> for &'static str`], and
/// [`RateLimitUnit::as_suffix`] all route through the same three-arm
/// inline canonical-suffix byte-strings), so a future variant rename or
/// per-arm serde-attribute drift reaches every one of the six sibling
/// forward-projection paths ([`std::fmt::Display`], [`AsRef<str>`],
/// [`Self::as_suffix`], [`From<Self> for &'static str`], this
/// [`From<&Self> for &'static str`], and the un-`rename`d
/// [`serde::Serialize`] derive that also emits [`Self::as_suffix`]'s
/// bytes) through exactly one caixa-core edit.
///
/// Deliberately routes through the canonical-suffix axis, not the
/// second-magnitude [`RateLimitUnit::window`] axis — the borrowed-input
/// `From` lands on the same author-surface-canonical byte-string the
/// codec's parse and render arms both dispatch on, while the token-
/// bucket-refill period stays reachable only through the explicit
/// [`RateLimitUnit::window`] / [`RateLimitUnit::from_window`] paths, so
/// the canonical-suffix / token-bucket-refill two-axis split the sibling
/// [`AsRef<str>`] impl already carries reaches the borrowed-input axis
/// by construction.
///
/// The [`RateLimitUnit::as_suffix`] emit and
/// [`RateLimitUnit::from_suffix`] parse share the same three inline
/// canonical-suffix byte-strings by construction — so the borrowed-input
/// forward axis and the reverse [`TryFrom<&str>`] axis compose directly
/// without the intermediate wire-vocab hop the peer [`crate::CaixaKind`]
/// axis pair requires. The round-trip witness pin below locks this
/// direct composition on the M3 slot enum's trait-idiomatic axis pair.
///
/// Pinned load-bearing by
/// [`tests::rate_limit_unit_from_borrowed_into_static_str_routes_through_as_suffix_accessor`]
/// (byte-parity pin against [`RateLimitUnit::as_suffix`] across the
/// three-arm emit-set via a borrowed input, plus a `const`-context
/// materialization witness for the `&'static str` lifetime promise, plus
/// a blanket `.into()` shape) and
/// [`tests::rate_limit_unit_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
/// (cross-axis partition pin against the paired owned-input
/// [`From<RateLimitUnit> for &'static str`] impl, plus a
/// `.iter().map(Into::into)` pipe witness over [`RateLimitUnit::ALL`],
/// plus a direct round-trip witness through [`TryFrom<&str>`] that closes
/// the two-way `&Self → &'static str → Self` round-trip on the M3 slot
/// enum's trait-idiomatic axis pair without the wire-vocab intermediate
/// the peer [`crate::CaixaKind`] axis pair requires).
impl From<&RateLimitUnit> for &'static str {
fn from(unit: &RateLimitUnit) -> &'static str {
unit.as_suffix()
}
}
/// Trait-idiomatic *forward* projection on the M3 mesh-primitive
/// `:politicas :rate-limit` canonical-suffix [`RateLimitUnit`] closed-set
/// typed enum from an *owned* input onto the owned-[`String`] axis —
/// routes byte-for-byte through the substrate-primitive
/// [`RateLimitUnit::as_suffix`] `pub const fn` accessor so every consumer
/// that binds a [`RateLimitUnit`] through the standard-library `.into()` /
/// [`From<Self> for String`] (equivalently [`Into<String>`]) axis reaches
/// the same three-arm `"s"` / `"m"` / `"h"` canonical-suffix byte-string
/// the paired owned-input [`From<RateLimitUnit> for &'static str`]
/// (7fdfbf4), the borrowed-input [`From<&RateLimitUnit> for &'static str`]
/// (f4b9e6b), the sibling [`std::fmt::Display`], [`AsRef<str>`], and
/// [`RateLimitUnit::as_suffix`] surfaces already return.
///
/// Extends the trait-idiomatic *owned-[`String`]* forward-projection
/// family (opened on [`crate::supervisor::RestartStrategy`] — 7baa18a —
/// the first-mover on the M2 OTP-shape sibling-restart-strategy axis,
/// extended onto [`crate::supervisor::RestartPolicy`] — 7851725 — the
/// second-of-two-in-M2 per-child restart-decision axis, then onto
/// [`crate::CaixaKind`] — 231a18c — the structurally most fundamental
/// closed-set fieldless typed enum on the caixa surface, then onto
/// [`crate::CaixaDialeto`] — 88942cd — the dialect-classification axis,
/// then onto [`crate::dep::DepList`] — 32b0ee8 — the two-list dep-graph
/// axis, then onto [`PlacementStrategy`] — 1154c2f — the first M3
/// mesh-primitive-defining slot enum, then onto [`WitShape`] — 79a8723 —
/// the second M3 mesh-primitive-defining slot enum on the caixa surface)
/// onto the eighth peer: the M3 mesh-primitive `:politicas :rate-limit`
/// canonical-suffix axis [`RateLimitUnit`] carries. Third (and last)
/// M3-mesh-primitive-defining closed-set typed enum to converge onto this
/// owned-[`String`] forward-projection campaign — the caixa-mesh renderer
/// keys off this axis end-to-end for per-Aplicacao Envoy
/// `local_rate_limit.token_bucket.fill_interval` overlay emission, so
/// every future consumer that promotes canonical-suffix output onto an
/// owned-heap-string carrier (the future M4 admission-webhook rejection
/// body's accepted-`:politicas :rate-limit` enumeration, a future
/// `HashMap::<String, RateLimitUnit>::from_iter(…)` owned-key per-unit
/// lookup, a future `serde_json::Value::String(unit.into())` structured-
/// payload composer) now reaches the substrate-primitive accessor
/// through one uniform trait dispatch.
///
/// Rust's standard library does not carry a blanket
/// `impl<T: AsRef<str>> From<T> for String` (nor an
/// `impl<T: fmt::Display> From<T> for String`), so every closed-set typed
/// enum that carries the paired [`AsRef<str>`] / [`std::fmt::Display`] /
/// [`From<Self> for &'static str`] / [`From<&Self> for &'static str`]
/// quadruple but not the owned-[`String`] axis forces every owned-string
/// call site through a `.to_string()` / `.as_suffix().to_owned()` /
/// `String::from(unit.as_suffix())` detour whose type bounds have no
/// compile-time link to the substrate primitive.
///
/// Same as the peer [`crate::supervisor::RestartStrategy`] /
/// [`crate::supervisor::RestartPolicy`] / [`crate::CaixaDialeto`] /
/// [`crate::dep::DepList`] / [`PlacementStrategy`] / [`WitShape`]
/// owned-[`String`] axis pairs (whose forward emit and reverse parse
/// share one vocabulary by construction), [`RateLimitUnit`]'s
/// [`RateLimitUnit::as_suffix`] emit and [`RateLimitUnit::from_suffix`]
/// parse resolve through the same three inline canonical-suffix
/// byte-strings by construction (there is no wire/diagnostic axis split
/// on this enum — both halves route through the same three `match`-arm-
/// inline `&'static str` values `"s"` / `"m"` / `"h"`), so the
/// owned-[`String`] forward projection this impl exposes composes directly
/// with the paired trait-idiomatic reverse [`TryFrom<&str>`] axis on the
/// owned-[`String`]'s [`String::as_str`] borrow — no intermediate
/// wire-vocab hop like the peer [`crate::CaixaKind`] axis pair requires.
///
/// Deliberately routes through the canonical-suffix axis, not the
/// second-magnitude [`RateLimitUnit::window`] axis — the owned-[`String`]
/// `From` lands on the same author-surface-canonical byte-string the
/// codec's parse and render arms both dispatch on, while the token-
/// bucket-refill period stays reachable only through the explicit
/// [`RateLimitUnit::window`] / [`RateLimitUnit::from_window`] paths, so
/// the canonical-suffix / token-bucket-refill two-axis split the sibling
/// owned-input and borrowed-input `&'static str` axes already carry
/// reaches the owned-[`String`] axis by construction.
///
/// The remaining seven closed-set typed enums on the caixa substrate
/// surface (`PathShapeViolation`, `InvariantKind`, `ArchVerdict`,
/// `Severity`, `FixSafety`, `Semantic`, `FerriteRuntime`) are the future
/// targets of this campaign — each carries the same paired [`AsRef<str>`]
/// / [`std::fmt::Display`] / [`From<Self> for &'static str`] /
/// [`From<&Self> for &'static str`] quadruple that this owned-[`String`]
/// axis extends onto.
///
/// Pinned load-bearing by
/// [`tests::rate_limit_unit_from_into_owned_string_routes_through_as_suffix_accessor`]
/// (byte-parity pin against [`RateLimitUnit::as_suffix`] across the
/// three-arm [`RateLimitUnit::ALL`] emit-set plus a blanket
/// `.into::<String>()` shape witness) and
/// [`tests::rate_limit_unit_from_into_owned_string_and_static_str_agree_on_every_arm`]
/// (cross-axis partition against the sibling owned-`&'static str` axis
/// and the [`ToString::to_string`] surface, a
/// `.iter().copied().map(String::from)` pipe witness over
/// [`RateLimitUnit::ALL`], plus a direct `Self → String → Self`
/// round-trip via [`TryFrom<&str>`] on the owned-[`String`]'s
/// [`String::as_str`] borrow — composes directly without the wire-vocab
/// intermediate hop the peer [`crate::CaixaKind`] axis pair requires).
impl From<RateLimitUnit> for String {
fn from(unit: RateLimitUnit) -> String {
unit.as_suffix().to_owned()
}
}
/// Trait-idiomatic *borrowed-input, owned-`String` output* forward
/// projection on the M3 mesh-primitive `:politicas :rate-limit`
/// canonical-suffix [`RateLimitUnit`] closed-set typed enum — the fourth
/// (and closing) corner of the `{Self, &Self} × {&'static str, String}`
/// 2×2 trait-idiomatic projection family on this third (and last)
/// M3-mesh-primitive-defining slot enum. Routes byte-for-byte through the
/// substrate-primitive [`RateLimitUnit::as_suffix`] `pub const fn`
/// accessor (via [`str::to_owned`]) so every consumer that holds a
/// borrowed [`&RateLimitUnit`] and needs an owned [`String`] — a future
/// `serde_json::Value::String(String::from(&unit))` structured-payload
/// composer over a borrowed field, a future `Iterator::map` over
/// `&[RateLimitUnit]` that projects to owned keys through
/// `.iter().map(String::from)` (whose iterator yields `&RateLimitUnit`,
/// not `RateLimitUnit`, so the owned-input [`From<RateLimitUnit> for
/// String`] axis alone forces every call site through an explicit
/// `.copied()` / spurious [`Copy`] deref restatement rather than the
/// direct trait-idiomatic projection), a future
/// `HashMap::<String, RateLimitUnit>::from_iter` that keys off a borrowed-
/// iteration axis where dereferencing the unit would force an unnecessary
/// [`Copy`] at every step, the future M4
/// `mesh.pleme.io/v1alpha1/Aplicacao` CR admission-webhook rejection body
/// composer that names the accepted-`:politicas :rate-limit`
/// canonical-suffix enumeration through an iterated
/// `RateLimitUnit::ALL.iter().map(String::from).collect()` pipe rather
/// than a per-arm cascade, the future caixa-mesh renderer per-Aplicacao
/// Envoy `local_rate_limit.token_bucket.fill_interval` overlay composer
/// whose borrowed-iteration axis over declared units projects to owned
/// keys by construction — reaches the same three-arm `"s"` / `"m"` /
/// `"h"` canonical-suffix byte-string the paired
/// [`std::fmt::Display`], [`AsRef<str>`], [`RateLimitUnit::as_suffix`],
/// and the three other trait-idiomatic forward-projection impls
/// ([`From<RateLimitUnit> for &'static str`],
/// [`From<&RateLimitUnit> for &'static str`],
/// [`From<RateLimitUnit> for String`]) already return.
///
/// Eighth peer on the substrate-wide trait-idiomatic *borrowed-input,
/// owned-`String` output* forward-projection family opened on
/// [`crate::supervisor::RestartStrategy`] (579385f), closed on the M2
/// OTP-shape sibling axis pair by [`crate::supervisor::RestartPolicy`]
/// (8465740), extended onto the two-list dep-graph peer by
/// [`crate::dep::DepList`] (e0cb617), onto the top-level
/// [`crate::CaixaKind`] peer by (e76436d), onto the
/// dialect-classification peer by [`crate::CaixaDialeto`] (d3c0d1d),
/// onto the first M3 mesh-slot peer by [`PlacementStrategy`] (d3dc000),
/// and onto the second M3 mesh-slot peer by [`WitShape`] (d638fd3) —
/// closes the `{Self, &Self} × {&'static str, String}` 2×2 projection
/// corner across the whole M3 mesh-primitive triple, keeping the M3
/// slot-enum sweep in lockstep with the M2 OTP-shape sibling pair's
/// earlier closure. Third (and last) M3-mesh-primitive-defining
/// closed-set typed enum to reach the 2×2-completion corner — the
/// [`PlacementStrategy`] first-mover (d3dc000) closed the `:placement
/// :estrategia` distribution-strategy axis, [`WitShape`] (d638fd3)
/// closed the `:contratos :wit` census-label axis, and this lift closes
/// the `:politicas :rate-limit` canonical-suffix axis the caixa-mesh
/// renderer keys off end-to-end for per-Aplicacao Envoy
/// `local_rate_limit.token_bucket.fill_interval` overlay emission.
///
/// Rust's standard library does not carry a blanket
/// `impl<T: AsRef<str>> From<&T> for String` (nor an
/// `impl<T: fmt::Display> From<&T> for String`), so every closed-set
/// typed enum that carries the paired [`AsRef<str>`] /
/// [`std::fmt::Display`] / [`From<Self> for &'static str`] /
/// [`From<&Self> for &'static str`] / [`From<Self> for String`]
/// quintuple but not the borrowed-input owned-[`String`] axis forces
/// every borrowed-input owned-string call site through a
/// `unit.as_suffix().to_owned()` / `String::from(*unit)` (with a
/// spurious [`Copy`]) / `unit.to_string()` (through
/// [`std::fmt::Display`]) detour whose type bounds have no compile-time
/// link to the substrate primitive.
///
/// Same three-path convergence discipline as the paired owned-input
/// impl (this borrowed-input axis, the paired owned-input
/// [`From<RateLimitUnit> for String`], and [`RateLimitUnit::as_suffix`]
/// all route through the same three-arm inline canonical-suffix
/// byte-strings), so a future variant rename or per-arm serde-attribute
/// drift reaches every one of the paired forward-projection paths
/// through exactly one caixa-core edit.
///
/// Same as the peer [`crate::supervisor::RestartStrategy`] /
/// [`crate::supervisor::RestartPolicy`] / [`crate::dep::DepList`] /
/// [`crate::CaixaDialeto`] / [`PlacementStrategy`] / [`WitShape`]
/// borrowed-input owned-[`String`] axis pairs (whose forward emit and
/// reverse parse share one vocabulary by construction) and unlike the
/// peer [`crate::CaixaKind`] pair (whose forward emit lands on the
/// lowercase Portuguese diagnostic vocabulary while the reverse parse
/// lands on the `PascalCase` wire vocabulary, forcing the round-trip
/// through an intermediate [`crate::CaixaKind::wire_name`] hop),
/// [`RateLimitUnit`]'s [`RateLimitUnit::as_suffix`] emit and
/// [`RateLimitUnit::from_suffix`] parse resolve through the same three
/// inline canonical-suffix byte-strings by construction (there is no
/// wire/diagnostic axis split on this M3 slot enum — both halves of the
/// round-trip route through the same three `match`-arm-inline `&'static
/// str` values `"s"` / `"m"` / `"h"`), so the borrowed-input
/// owned-[`String`] projection this impl exposes composes directly with
/// the paired trait-idiomatic reverse [`TryFrom<&str>`] axis on the
/// owned-[`String`]'s [`String::as_str`] borrow — no intermediate
/// wire-vocab hop required.
///
/// Deliberately routes through the canonical-suffix axis, not the
/// second-magnitude [`RateLimitUnit::window`] axis — the borrowed-input
/// owned-[`String`] `From` lands on the same author-surface-canonical
/// byte-string the codec's parse and render arms both dispatch on, while
/// the token-bucket-refill period stays reachable only through the
/// explicit [`RateLimitUnit::window`] / [`RateLimitUnit::from_window`]
/// paths, so the canonical-suffix / token-bucket-refill two-axis split
/// the sibling axes already carry reaches the borrowed-input owned-
/// [`String`] axis by construction.
///
/// The remaining six closed-set typed enums on the caixa substrate
/// surface (`PathShapeViolation`, `InvariantKind`, `ArchVerdict`,
/// `Severity`, `FixSafety`, `Semantic`, `FerriteRuntime`) are the
/// future targets of this 2×2-completion campaign — each carries the
/// same paired quintuple that this borrowed-input owned-[`String`] axis
/// extends onto.
///
/// Pinned load-bearing by
/// [`tests::rate_limit_unit_from_into_borrowed_owned_string_routes_through_as_suffix_accessor`]
/// (byte-parity pin against [`RateLimitUnit::as_suffix`] across the
/// three-arm emit-set through the borrowed-input surface) and
/// [`tests::rate_limit_unit_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
/// (cross-axis partition pin against the paired owned-input owned-
/// [`String`] [`From<RateLimitUnit> for String`] impl, the paired
/// borrowed-input owned-[`&'static str`]
/// [`From<&RateLimitUnit> for &'static str`] impl, the paired owned-
/// input owned-[`&'static str`] [`From<RateLimitUnit> for &'static
/// str`] impl, and the sibling [`ToString::to_string`] surface routed
/// through [`std::fmt::Display`], plus a `.iter().map(String::from)`
/// pipe witness over [`RateLimitUnit::ALL`] (whose iterator yields
/// `&RateLimitUnit` by construction, so the borrowed-input owned-
/// [`String`] axis is what routes the pipe through the substrate-
/// primitive [`RateLimitUnit::as_suffix`] accessor without a spurious
/// [`Copy`] deref), plus a direct round-trip witness through
/// [`TryFrom<&str>`] on the owned-[`String`]'s [`String::as_str`]
/// borrow that closes the two-way `&Self → String → Self` round-trip
/// on the trait-idiomatic borrowed-input owned-[`String`] forward +
/// reverse axis pair — no intermediate wire-vocab hop like the peer
/// [`crate::CaixaKind`] axis pair requires).
impl From<&RateLimitUnit> for String {
fn from(unit: &RateLimitUnit) -> String {
unit.as_suffix().to_owned()
}
}
/// Trait-idiomatic *forward* projection on the M3 mesh-primitive
/// `:politicas :rate-limit` canonical-suffix [`RateLimitUnit`]
/// closed-set typed enum from an *owned* input onto the
/// [`std::borrow::Cow<'static, str>`] axis — routes byte-for-byte
/// through the substrate-primitive [`RateLimitUnit::as_suffix`]
/// `pub const fn` accessor (via [`std::borrow::Cow::Borrowed`]) so
/// every consumer that binds a [`RateLimitUnit`] through the
/// standard-library `.into()` / [`From<Self> for
/// std::borrow::Cow<'static, str>`] (equivalently
/// [`Into<std::borrow::Cow<'static, str>>`]) axis reaches the same
/// three-arm inline `"s"` / `"m"` / `"h"` canonical-suffix byte-
/// string the paired [`From<RateLimitUnit> for &'static str`],
/// [`From<&RateLimitUnit> for &'static str`],
/// [`From<RateLimitUnit> for String`], and
/// [`From<&RateLimitUnit> for String`] 2×2 trait-idiomatic
/// forward-projection corners, the sibling [`std::fmt::Display`],
/// [`AsRef<str>`], and [`RateLimitUnit::as_suffix`] surfaces already
/// return, rather than an open-coded per-call-site
/// `std::borrow::Cow::Borrowed(unit.as_suffix())` /
/// `std::borrow::Cow::Owned(unit.to_string())` composition whose
/// type bounds have no compile-time link back to the substrate
/// primitive.
///
/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
/// [`std::borrow::Cow::Owned`] — the substrate-primitive
/// [`RateLimitUnit::as_suffix`] accessor's return carries the
/// `&'static str` lifetime by construction (each `match` arm
/// resolves to one of the three inline `"s"` / `"m"` / `"h"` byte-
/// strings with static lifetime), so the zero-alloc borrowed arm
/// is the type-correct projection with no runtime allocation. The
/// paired [`std::borrow::Cow::Owned`] arm stays reachable at the
/// call site through the existing [`From<RateLimitUnit> for
/// String`] axis composed with [`std::borrow::Cow::from`] on the
/// resulting owned [`String`] — a caller who chose to mutate the
/// projection lands on the owned arm by their own composition, not
/// by the substrate-primitive projection silently allocating on
/// their behalf.
///
/// Rust's standard library carries no blanket `impl<T: AsRef<str>>
/// From<T> for Cow<'static, str>` (nor an `impl<T: fmt::Display>
/// From<T> for Cow<'static, str>`), so the paired sibling
/// [`From<RateLimitUnit> for &'static str`],
/// [`From<RateLimitUnit> for String`], [`AsRef<str>`], and
/// [`std::fmt::Display`] surfaces do not implicitly extend to a
/// [`Cow<'static, str>`]-bound call site — every such site is
/// forced through a `Cow::Borrowed(unit.as_suffix())` /
/// `Cow::Owned(unit.to_string())` open-code whose type bounds have
/// no compile-time link back to the substrate primitive until this
/// lift.
///
/// Third — and last — M3-mesh-primitive-defining peer on the
/// substrate-wide trait-idiomatic [`std::borrow::Cow<'static, str>`]
/// forward-projection campaign, closing the M3-mesh-shape tier of
/// the axis onto its final closed-set fieldless typed enum. The
/// [`WitShape`] `:contratos :wit` census-label first-mover (8634dec
/// owned-input + 25690ef borrowed-input) opened the tier on the
/// first M3-mesh-primitive peer; the paired [`PlacementStrategy`]
/// `:placement :estrategia` distribution-strategy peer (eee504d
/// owned-input + afdf0f4 borrowed-input) extended it onto the
/// second peer. The [`CaixaKind`](crate::CaixaKind) top-level
/// first-mover (99c1735 owned-input + d45c409 borrowed-input) opened
/// the axis on the structurally most fundamental closed-set
/// fieldless typed enum; the paired M2 OTP-shape
/// [`crate::supervisor::RestartStrategy`] (7dd28b3 + 9b3e4b3) and
/// [`crate::supervisor::RestartPolicy`] (0612398 + ee577fd) closed
/// the M2 OTP-shape tier. The outside-M3 substrate-wide peers
/// ([`crate::dep::DepList`], [`crate::CaixaDialeto`],
/// [`crate::render::PathShapeViolation`], and the outside-
/// `caixa-core` peers `InvariantKind`, `ArchVerdict`, `Severity`,
/// `FixSafety`, `Semantic`, `FerriteRuntime`) are the remaining
/// future targets of this campaign; closing the owned-input corner
/// on [`RateLimitUnit`] leaves only the paired borrowed-input
/// [`From<&RateLimitUnit> for std::borrow::Cow<'static, str>`]
/// `{Self, &Self}`-closer as the last un-lifted axis on the
/// M3-mesh-primitive triple.
///
/// Same three-path convergence discipline as the paired sibling
/// [`From<RateLimitUnit> for &'static str`] /
/// [`From<RateLimitUnit> for String`] / [`std::fmt::Display`] /
/// [`AsRef<str>`] surfaces (this [`Cow<'static, str>`] axis, the
/// paired sibling surfaces, and [`RateLimitUnit::as_suffix`] all
/// route through the same three inline `"s"` / `"m"` / `"h"` byte-
/// strings by construction), so a future variant addition, rename,
/// or per-arm suffix drift reaches every forward-projection path
/// through exactly one caixa-core edit at the
/// [`RateLimitUnit::as_suffix`] `match` head.
///
/// Pinned load-bearing by
/// [`tests::rate_limit_unit_from_into_static_cow_str_routes_through_as_suffix_accessor`]
/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
/// against [`RateLimitUnit::as_suffix`] across the three-arm
/// [`RateLimitUnit::ALL`]) and
/// [`tests::rate_limit_unit_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
/// (cross-axis partition pin against the paired
/// [`From<RateLimitUnit> for &'static str`],
/// [`From<RateLimitUnit> for String`], and
/// [`ToString`]-through-[`std::fmt::Display`] axes, plus a
/// `.iter().copied().map(Cow::from)` pipe witness over
/// [`RateLimitUnit::ALL`] that materializes the three-arm
/// accept-set through the [`Cow<'static, str>`] axis alone and pins
/// the zero-alloc discipline on every element).
impl From<RateLimitUnit> for std::borrow::Cow<'static, str> {
fn from(unit: RateLimitUnit) -> std::borrow::Cow<'static, str> {
std::borrow::Cow::Borrowed(unit.as_suffix())
}
}
/// Trait-idiomatic *borrowed-input, [`std::borrow::Cow<'static, str>`]
/// output* forward projection on the M3-mesh-primitive-defining
/// `:politicas :rate-limit` canonical-suffix [`RateLimitUnit`]
/// closed-set typed enum — the borrowed-input companion to the paired
/// owned-input [`From<RateLimitUnit> for std::borrow::Cow<'static,
/// str>`] impl immediately above (1d59925). Routes byte-for-byte
/// through the same substrate-primitive [`RateLimitUnit::as_suffix`]
/// `pub const fn` accessor (via [`std::borrow::Cow::Borrowed`]) so
/// every consumer that holds a `&RateLimitUnit` and needs a
/// [`std::borrow::Cow<'static, str>`] — a
/// `RateLimitUnit::ALL.iter().map(std::borrow::Cow::from).collect::<Vec<_>>()`
/// per-arm accept-set materializer whose iterator over
/// `&'static [RateLimitUnit]` yields `&RateLimitUnit` (not
/// `RateLimitUnit`, so the paired owned-input
/// [`From<RateLimitUnit> for std::borrow::Cow<'static, str>`] axis
/// alone forces every call site through an explicit `.copied()` /
/// dereference / [`Copy`]-bound restatement rather than the direct
/// trait-idiomatic projection), a future generic
/// `<T: for<'a> Into<std::borrow::Cow<'static, str>>>`-bound emitter
/// on a per-`:politicas :rate-limit` diagnostic column that walks the
/// `iter().map(Into::into)` shape verbatim, the future M4
/// `mesh.pleme.io/v1alpha1/Aplicacao` CR admission-webhook rejection
/// body that composes the accepted-`:politicas :rate-limit`
/// canonical-suffix enumeration from an iterated
/// `RateLimitUnit::ALL.iter().map(|u| u.into())` pipe rather than a
/// per-arm `match u { … }` cascade — reaches the same three-arm
/// inline `"s"` / `"m"` / `"h"` canonical-suffix byte-string the
/// paired [`std::fmt::Display`], [`AsRef<str>`],
/// [`RateLimitUnit::as_suffix`], the four
/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
/// forward-projection corners, and the paired owned-input
/// [`From<RateLimitUnit> for std::borrow::Cow<'static, str>`] impl
/// already return.
///
/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
/// [`std::borrow::Cow::Owned`] — the substrate-primitive
/// [`RateLimitUnit::as_suffix`] accessor's return carries the
/// `&'static str` lifetime by construction (each `match` arm resolves
/// to one of the three inline `"s"` / `"m"` / `"h"` byte-strings with
/// static lifetime), so the zero-alloc borrowed arm is the type-correct
/// projection with no runtime allocation on the borrowed-input surface
/// just as on the paired owned-input surface.
///
/// Closes the `{Self, &Self}` input-shape corner on the M3-mesh-shape
/// `:politicas :rate-limit` canonical-suffix
/// [`std::borrow::Cow<'static, str>`] axis opened one commit prior
/// (1d59925) on the paired owned-input [`From<RateLimitUnit> for
/// std::borrow::Cow<'static, str>`] impl — third-and-last
/// M3-mesh-primitive-defining peer on the axis, closing the whole
/// M3-mesh-shape tier of the substrate-wide
/// [`std::borrow::Cow<'static, str>`] forward-projection campaign.
/// One commit after the sibling [`PlacementStrategy`] `:placement
/// :estrategia` distribution-strategy peer (eee504d owned-input +
/// afdf0f4 borrowed-input) and the first-mover [`WitShape`]
/// `:contratos :wit` census-label peer (8634dec owned-input + 25690ef
/// borrowed-input) closed the first and second M3-mesh-primitive-
/// defining slot enums, exactly as d45c409 closed the axis on the
/// top-level [`crate::CaixaKind`] one commit after the owning half
/// (99c1735) landed and as 9b3e4b3 / ee577fd closed it on the M2
/// OTP-shape [`crate::supervisor::RestartStrategy`] /
/// [`crate::supervisor::RestartPolicy`] sibling peers one commit
/// after their owning halves (7dd28b3 / 0612398) landed. Rust's
/// standard library does not carry a blanket
/// `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor an
/// `impl<T: fmt::Display> From<&T> for Cow<'static, str>`), so every
/// closed-set fieldless typed enum peer on the substrate that carries
/// the paired owned-input [`Cow<'static, str>`] axis but not the
/// borrowed-input axis forces every borrowed-input
/// [`Cow<'static, str>`]-parameterized call site through a spurious
/// [`Copy`] deref (`std::borrow::Cow::from(*unit)`) or a
/// `std::borrow::Cow::Borrowed(unit.as_suffix())` open-code whose
/// type bounds have no compile-time link to the substrate primitive.
///
/// The outside-M3 substrate-wide peers ([`crate::render::PathShapeViolation`]
/// and the outside-`caixa-core` peers `InvariantKind`, `ArchVerdict`)
/// are the remaining future targets of the campaign; closing this
/// borrowed-input corner on [`RateLimitUnit`] closes the whole
/// M3-mesh-shape tier of the substrate-wide
/// [`std::borrow::Cow<'static, str>`] axis on the
/// M3-mesh-primitive-defining triple.
///
/// Pinned load-bearing by
/// [`tests::rate_limit_unit_from_borrowed_into_static_cow_str_routes_through_as_suffix_accessor`]
/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
/// against [`RateLimitUnit::as_suffix`] across the three-arm
/// [`RateLimitUnit::ALL`] through the borrowed-input surface) and
/// [`tests::rate_limit_unit_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
/// (cross-axis partition pin against the paired owned-input
/// [`From<RateLimitUnit> for std::borrow::Cow<'static, str>`], the
/// paired borrowed-input owned-`&'static str`
/// [`From<&RateLimitUnit> for &'static str`], and the paired
/// borrowed-input owned-`String` [`From<&RateLimitUnit> for String`]
/// impls, plus a `.iter().map(std::borrow::Cow::from)` pipe witness
/// over [`RateLimitUnit::ALL`] — whose iterator yields
/// `&RateLimitUnit` by construction, so the borrowed-input
/// [`Cow<'static, str>`] axis is what routes the pipe through the
/// substrate-primitive [`RateLimitUnit::as_suffix`] accessor with the
/// zero-alloc [`Cow::Borrowed`] arm by construction and without a
/// spurious [`Copy`] deref).
impl From<&RateLimitUnit> for std::borrow::Cow<'static, str> {
fn from(unit: &RateLimitUnit) -> std::borrow::Cow<'static, str> {
std::borrow::Cow::Borrowed(unit.as_suffix())
}
}
/// Upper-bound ceiling on the `:politicas :timeout` axis — every
/// validated [`MeshPolicy::timeout`] past
/// [`AplicacaoSpec::validate_politicas`] lies in `1ms..=POLICY_TIMEOUT_MAX`
/// (inclusive on both ends, integer-millisecond magnitudes by the
/// canonical-form gate immediately preceding).
///
/// The typed field is `Option<Duration>` (the zero-floor arm
/// [`AplicacaoError::PolicyTimeoutZero`] already rejects
/// `Duration::ZERO`, and the canonical-form arm
/// [`AplicacaoError::PolicyTimeoutNotCanonical`] already rejects
/// sub-millisecond residue), so a programmatic struct literal
/// (`MeshPolicy { timeout: Some(Duration::from_secs(86_400)), .. }` —
/// 24h) and the equivalent author-surface form
/// (`(:politicas (:timeout "24h"))` — the codec emits `"h"` for any
/// integer-hour magnitude) both round-trip cleanly through serde — a
/// structurally unbounded `Duration` ceiling. A `:timeout` value far
/// above the documented production-playbook band (Envoy default `15s`,
/// Istio per-route typical `≤ 30s`, AWS App Mesh `httpRouteTimeout`
/// schema typical `≤ 60s`, Linkerd `request_timeout` typical `10s`,
/// Kubernetes ingress-nginx `proxy_read_timeout` default `60s` capped
/// at `~3600s`) silently degenerates the mesh-policy contract: the
/// per-call deadline is structurally so long that no realistic
/// synchronous-`:contratos` traversal can reach it, so the typed slot
/// becomes a no-op carried on every emitted Envoy / Cilium L7 timeout
/// overlay — the MESH-COMPOSITION §V CSE invariant "no infinite
/// blocking" degenerates to a nominal-only contract on the
/// synchronous-call path. Pairs with the [`POLICY_RETRIES_MAX`] cap on
/// the sibling `:politicas :retries` axis and the
/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] cap on the sibling
/// `:politicas :circuit-breaker :max-failures` axis — all three close
/// the "structurally unbounded ceiling on a typed `:politicas` axis"
/// footgun the prior zero-floor-and-canonical-form-only checks left
/// open.
///
/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
/// shared duration codec emits (`"<n>h"` for any integer-hour
/// magnitude) — every value in the canonical authoring form's
/// `<integer><unit>` grammar at or below this cap renders to a clean
/// canonical string. The cap sits an order of magnitude above every
/// documented production-playbook recommendation band (Envoy default
/// `15s`, Istio production `≤ 30s`, Linkerd production `≤ 10s`, AWS
/// App Mesh production `≤ 60s`) and at the Kubernetes ingress-nginx
/// configured maximum (`proxy_read_timeout` typical max `3600s`),
/// below the clearly-pathological "effectively no timeout" floor
/// (`24h`, `7d`, `Duration::MAX`): a value the author can plausibly
/// want for a long-running synchronous workflow, but a hard wall above
/// which the mesh-level deadline is structurally a non-deadline.
/// Lifted as a typed `pub const` so the bound has exactly one source
/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
/// materializer's admission webhook and the caixa-mesh-side
/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
/// other typed upper bound in this crate carries
/// ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
pub const POLICY_TIMEOUT_MAX: Duration = Duration::from_secs(3600);
/// Upper-bound ceiling on the `:politicas :retries` axis — every
/// validated [`MeshPolicy::retries`] past
/// [`AplicacaoSpec::validate_politicas`] lies in `1..=POLICY_RETRIES_MAX`.
///
/// The typed slot is `Option<u32>` (`None` = no retries on transient
/// failure; `Some(0)` already rejected by the
/// [`AplicacaoError::PolicyRetriesZero`] zero-floor arm), so a
/// programmatic struct literal (`MeshPolicy { retries: Some(100_000),
/// .. }`) and the equivalent author-surface form
/// (`(:politicas (:retries 100000))`) both round-trip cleanly through
/// serde / the codec — a structurally unbounded `u32` ceiling. The
/// runtime substrate that consumes the value (Envoy's
/// `retry_policy.num_retries`, the `CiliumClusterwideEnvoyConfig`
/// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 names, AWS
/// App Mesh's `gRPCRouteRetryPolicy.maxRetries` whose schema-side
/// admission cap is 10) translates a four-billion-retry policy into a
/// thundering-herd amplification vector on transient failure — the
/// caller's one request fans out to `retries` server-side calls per
/// edge per traversal, multiplying load by `(retries+1)^depth` across
/// the synchronous-`:contratos` subgraph. The MESH-COMPOSITION §V CSE
/// invariant "no infinite blocking" pairs with a no-runaway-amplification
/// invariant on the retry axis; both belong at the typed-slot layer.
///
/// The `10` ceiling matches AWS App Mesh's explicit hard cap (the only
/// upstream mesh-policy schema that documents one) and sits above the
/// Envoy / Istio practical-recommendation band (`num_retries ≤ 5` in
/// every documented production playbook): a value the author can
/// plausibly want, but a hard wall above which the policy is
/// structurally a footgun. Lifted as a typed `pub const` so the bound
/// has exactly one source of truth — a future axis reaching for the
/// same value (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
/// materializer's admission webhook, the caixa-mesh-side
/// `CiliumClusterwideEnvoyConfig` overlay's per-edge cap) reads from
/// one place. Same shape every other typed upper bound in this crate
/// carries ([`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`],
/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
pub const POLICY_RETRIES_MAX: u32 = 10;
/// Upper-bound ceiling on the `:politicas :circuit-breaker :max-failures`
/// axis — every validated [`CircuitBreaker::max_failures`] past
/// [`AplicacaoSpec::validate_politicas`] lies in
/// `1..=POLICY_BREAKER_MAX_FAILURES_MAX`.
///
/// The typed field is `u32` (the zero-floor arm
/// [`AplicacaoError::PolicyBreakerZeroFailures`] already rejects
/// `0` — a breaker that trips on the first call), so a programmatic
/// struct literal (`CircuitBreaker { max_failures: u32::MAX, .. }`)
/// and the equivalent author-surface form
/// (`(:circuit-breaker (:max-failures 4294967295))`) both round-trip
/// cleanly through serde — a structurally unbounded `u32` ceiling. A
/// `max_failures` value far above the documented production-playbook
/// band (Hystrix `circuitBreaker.requestVolumeThreshold` default 20,
/// Istio `outlierDetection.consecutive5xxErrors` default 5, Envoy
/// `outlier_detection.consecutive_5xx` default 5, Polly / Resilience4j
/// typical 5–50) silently disables the breaker's protection role:
/// the threshold is structurally so high that no realistic
/// failures-per-`:window` traffic shape can reach it, so the breaker
/// never trips and the typed slot becomes a no-op carried on every
/// emitted Envoy / Cilium L7 overlay. Pairs with the
/// [`POLICY_RETRIES_MAX`] cap on the sibling `:politicas :retries`
/// axis — both close the "structurally unbounded `u32` ceiling on a
/// typed policy axis" footgun the prior zero-floor-only checks left
/// open.
///
/// The `1000` ceiling sits an order of magnitude above every
/// documented upstream production-playbook recommendation band (the
/// highest is Hystrix's 20-default `requestVolumeThreshold`, the
/// Istio / Envoy / Polly / Resilience4j ones all sit ≤ 50) and below
/// the clearly-pathological "effectively no protection"
/// floor (`10_000`, `100_000`, `u32::MAX`): a value the author can
/// plausibly want at hyperscale, but a hard wall above which the
/// policy is structurally a no-op. Lifted as a typed `pub const` so
/// the bound has exactly one source of truth — the future M4
/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
/// one place. Same shape every other typed upper bound in this crate
/// carries ([`POLICY_RETRIES_MAX`],
/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
pub const POLICY_BREAKER_MAX_FAILURES_MAX: u32 = 1000;
/// Upper-bound ceiling on the `:politicas :circuit-breaker :window` axis —
/// every validated [`CircuitBreaker::window`] past
/// [`AplicacaoSpec::validate_politicas`] lies in
/// `1ms..=POLICY_BREAKER_WINDOW_MAX` (inclusive on both ends,
/// integer-millisecond magnitudes by the canonical-form gate
/// immediately preceding).
///
/// The typed field is `Duration` (the zero-floor arm
/// [`AplicacaoError::PolicyBreakerZeroWindow`] already rejects
/// `Duration::ZERO`, and the canonical-form arm
/// [`AplicacaoError::PolicyBreakerWindowNotCanonical`] already rejects
/// sub-millisecond residue), so a programmatic struct literal
/// (`CircuitBreaker { window: Duration::from_secs(86_400), .. }` — 24h)
/// and the equivalent author-surface form
/// (`(:circuit-breaker (:window "24h"))` — the codec emits `"h"` for any
/// integer-hour magnitude) both round-trip cleanly through serde — a
/// structurally unbounded `Duration` ceiling. A `:window` value far
/// above the documented production-playbook band (Hystrix
/// `metrics.rollingStats.timeInMilliseconds` default `10s`,
/// resilience4j `slidingWindowSize` time-based typical `10s..=60s`,
/// Istio `outlierDetection.interval` default `10s`, Envoy
/// `outlier_detection.interval` default `10s`, AWS App Mesh
/// circuit-breaker time-window typical `30s..=300s`) degenerates the
/// breaker's role: a rolling-window failure counter whose window is
/// hours long is operationally a lifetime counter, the breaker's
/// "recent failures" memory is structurally so long that transient
/// failures are never forgotten, and the typed slot becomes a no-op
/// trigger that trips once and stays tripped for the lifetime of the
/// component carried on every emitted Envoy / Cilium L7 overlay.
///
/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
/// shared duration codec emits (`"<n>h"` for any integer-hour
/// magnitude) — every value in the canonical authoring form's
/// `<integer><unit>` grammar at or below this cap renders to a clean
/// canonical string — and matches the sibling [`POLICY_TIMEOUT_MAX`]
/// cap on the first typed-`Duration` `:politicas` axis: the two
/// duration-typed `:politicas` axes now share a single uniform top
/// edge so the next typed-slot wiring (the future caixa-mesh
/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay, the M4
/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-policy
/// admission webhook) reaches for either field knowing the value is
/// in `1ms..=1h` without re-validating at the renderer layer. The cap
/// sits two orders of magnitude above every documented upstream
/// production-playbook recommendation band (Hystrix / resilience4j /
/// Istio / Envoy all default to 10s; AWS App Mesh maxes out at ~5m)
/// and below the clearly-pathological "rolling window degenerates to
/// lifetime counter" floor (`24h`, `7d`, `Duration::MAX`): a value the
/// author can plausibly want for a very-low-traffic long-tail
/// failure-detection window, but a hard wall above which the breaker's
/// rolling-window contract is structurally a lifetime-counter contract.
/// Lifted as a typed `pub const` so the bound has exactly one source
/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
/// materializer's admission webhook and the caixa-mesh-side
/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
/// other typed upper bound in this crate carries
/// ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
/// [`POLICY_BREAKER_MAX_FAILURES_MAX`],
/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
pub const POLICY_BREAKER_WINDOW_MAX: Duration = Duration::from_secs(3600);
/// Upper-bound ceiling on the `:politicas :rate-limit` rate axis —
/// every validated [`RateLimit::rate`] past
/// [`AplicacaoSpec::validate_politicas`] lies in
/// `1..=POLICY_RATE_LIMIT_MAX`.
///
/// The typed field is `u32` (the zero-floor arm
/// [`AplicacaoError::PolicyRateLimitZero`] already rejects `0` — a
/// zero-rate limit denies every request, the canonical "I forgot
/// that 0 means deny-everything" footgun), so a programmatic struct
/// literal (`RateLimit { rate: u32::MAX, window: Duration::from_secs(1) }`)
/// and the equivalent author-surface form (`(:rate-limit "4294967295/s")`
/// — the `rate_limit_codec` parses any `u32`-shaped magnitude) both
/// round-trip cleanly through serde — a structurally unbounded `u32`
/// ceiling. The runtime substrate consuming the value (Envoy's
/// `local_rate_limit.token_bucket.max_tokens`, the future
/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
/// MESH-COMPOSITION §III.2 #3 names) translates a four-billion-token
/// rate-limit into a no-op rate-limiter: the bucket capacity is
/// structurally so high no realistic per-edge traffic shape can
/// drain it, the limiter never trips, and the typed slot becomes a
/// "rate-limit declared, no enforcement" footgun — the canonical
/// declared-but-inert shape every other `:politicas` cap arm
/// closes ([`POLICY_RETRIES_MAX`] thundering-herd amplification,
/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] no-op-breaker, etc.).
///
/// The `1_000_000` (1M) ceiling sits two-to-three orders of magnitude
/// above every documented upstream production-playbook recommendation
/// band (Envoy `local_rate_limit` typical `10..=10_000` RPS, Istio
/// `RateLimitFilter` typical `10..=10_000` RPS, Cloudflare WAF
/// rate-rule Free / Pro `10_000` req/min, AWS API Gateway account
/// default `10_000` RPS, Kong typical `100..=10_000`, NGINX
/// `limit_req_zone` typical `1..=1_000` RPS) and below the
/// clearly-pathological "paste-from-binary blob" floor (`100_000_000`,
/// `u32::MAX`): a value the author can plausibly want at hyperscale
/// (Cloudflare Enterprise rate-plans run to ~6M/min ≈ 1M/h on the
/// /h-window arm), but a hard wall above which the policy is
/// structurally a no-op carried verbatim on every emitted Envoy /
/// Cilium L7 overlay. The cap brackets all three canonical windows
/// the [`rate_limit_codec`] accepts: at `1M/s` (absurd hyperscale
/// ceiling, ~1M RPS per edge), at `1M/m` (~16.7k RPS, the
/// hyperscale-tier WAF band), at `1M/h` (~277 RPS, the common
/// per-endpoint API band). Lifted as a typed `pub const` so the bound
/// has exactly one source of truth — the future M4
/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
/// one place. Same shape every other typed upper bound in this crate
/// carries ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
/// [`crate::LIMITS_WALL_CLOCK_MAX`],
/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
pub const POLICY_RATE_LIMIT_MAX: u32 = 1_000_000;
// `:entrada :host` total-length and per-label cap axes route through
// the lifted [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] (253) and
// [`crate::render::DNS_1123_LABEL_MAX_LEN`] (63) canonical bounds. The
// pair of aplicacao-private aliases the previous `validate_entrada_host`
// arms consumed (`ENTRADA_HOST_MAX_LEN = 253`, `ENTRADA_HOST_LABEL_MAX_LEN
// = 63`) were structurally the same K8s Gateway API v1 Hostname
// admission-schema bounds — the total-length cap on the OpenAPI
// `Hostname` type and the per-`.`-separated-label DNS-1123 cap on the
// same regex — that the peer axes at the caixa-core::render level pin,
// so hoisting both readers onto the shared lifted constants closes the
// third-occurrence duplication threshold structurally: the M4
// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-host / per-
// label validator, the future per-`Certificate` SAN emitter, and every
// other per-Gateway-API-Hostname landing site reach the same one place
// as the `:entrada :host` gate does — no per-axis alias drift surface
// between them, by construction.
/// Max byte length for an Akka-cluster-sharding `:placement :shard-key`
/// extractor expression — the upper bound `validate_placement_shard_key`
/// enforces on every well-shaped shard-key past validate. The realistic
/// shard-key forms in the wild (`tenantId`, `customerId`, `$tenantId`,
/// `metadata.tenantId`, `${tenant}`, `$.user.id`) all sit well under 64
/// bytes; the 63-byte cap mirrors the DNS-1123 label cap on the peer
/// `:placement :affinity` / `:placement :clusters` identifier-shaped
/// axes and surfaces the canonical "paste-from-doc multi-line blob landed
/// in `:shard-key`" footgun at validate time rather than at the future
/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass.
const PLACEMENT_SHARD_KEY_MAX_LEN: usize = 63;
/// Reject `:membros :caixa` values the K8s apiserver would refuse at
/// admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
/// that maps the shared parser-shaped reason into the
/// [`AplicacaoError::MembroCaixaInvalid`] variant, so the diagnostic
/// is self-locating (the offending `caixa:` is named verbatim) and
/// the author can grep their caixa.lisp for `:caixa "<name>"` and
/// fix it in one edit. Same diagnostic shape as
/// [`AplicacaoError::EntradaHostInvalid`] (c7d05ec) and
/// [`AplicacaoError::MembroVersaoInvalid`] (9888b13).
fn validate_membro_caixa(caixa: &str) -> Result<(), AplicacaoError> {
// Empty is already gated by `MembroCaixaEmpty` at the call site;
// re-checking here keeps the predicate usable from any future
// call site (the M4 CR materializer) without an empty-check
// footgun. The shared
// [`crate::render::require_valid_dns_1123_label`] helper brackets
// the empty-first + shape cascade every peer name axis
// (`:placement :clusters`, `:placement :affinity`, `:contratos
// :de`/`:para`, `:entrada :para`, `:children :caixa`, `:nome`,
// `:upgrade-from :module`) routes through, so drift between the
// eight axes' accepted DNS-1123-label sets is structurally
// impossible.
crate::render::require_valid_dns_1123_label(
caixa,
|| AplicacaoError::MembroCaixaEmpty,
|reason| AplicacaoError::membro_caixa_invalid(caixa, reason),
)
}
/// Reject `:placement :clusters` entries the K8s apiserver would refuse
/// at admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
/// that maps the shared parser-shaped reason into the
/// [`AplicacaoError::PlacementClusterInvalid`] variant.
///
/// Cluster names land in DNS-1123-label territory across every consumer:
/// the K8s context name keying `kubeconfig`, the `clusters[]` filter
/// the `lareira-fleet-programs` aggregator applies to scope programs to
/// their owning cluster (caixa-mesh's `placement.clusters` overlay,
/// 4d91c0b), the namespace prefix the future cross-cluster fan-out
/// emits per entry, and the `cluster.x-k8s.io/v1beta1/Cluster.metadata.name`
/// cluster identity the M4 CR materializer round-trips. Each apiserver-
/// side schema enforces the DNS-1123 label rule on admission; a
/// structurally invalid cluster name (`"Rio"`, `"my_cluster"`,
/// `"team.rio"`, `"-rio"`, `"rio-"`, the >63-byte UUID-shaped
/// mistaken-identity slug) silently passes the prior empty-/duplicate-
/// only gate and the failure surfaces as a no-match at filter time —
/// the workload doesn't land in the named cluster, with no diagnostic
/// naming the offending `:clusters` entry. Lifting the gate to caixa-
/// build time mirrors the `:membros :caixa` value-shape trajectory
/// (3f9d7a0) on the peer name axis.
///
/// The diagnostic carries the offending `cluster:` verbatim plus a
/// parser-shaped `reason:` naming the specific violation, so the
/// author can grep their caixa.lisp for `:clusters` and fix it in
/// one edit. Same diagnostic shape as
/// [`AplicacaoError::MembroCaixaInvalid`] (3f9d7a0).
fn validate_placement_cluster(cluster: &str) -> Result<(), AplicacaoError> {
// Empty is already gated by `PlacementClusterEmpty` at the call
// site; re-checking here keeps the predicate usable from any
// future call site (the M4 CR materializer's per-cluster validator)
// without an empty-check footgun. Routes through the shared
// [`crate::render::require_valid_dns_1123_label`] gate the peer
// name axes each land on.
crate::render::require_valid_dns_1123_label(
cluster,
|| AplicacaoError::PlacementClusterEmpty,
|reason| AplicacaoError::placement_cluster_invalid(cluster, reason),
)
}
/// Reject `:placement :affinity` hints whose shape can never legitimately
/// land in any downstream selector or label-keyed routing axis. Thin
/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
/// shared parser-shaped reason into the
/// [`AplicacaoError::PlacementAffinityInvalid`] variant, so the
/// diagnostic is self-locating (the offending `:affinity` is named
/// verbatim) and the author can grep their caixa.lisp for
/// `:affinity "<hint>"` and fix it in one edit.
///
/// The `:affinity` slot carries a placement-engine hint — canonical
/// examples in the M3 surface are `"data-locality"`, `"low-latency"`,
/// `"anti-affinity"` — that flows verbatim into the M3 Adaptive
/// compression overlay and the future M4 placement-engine's per-hint
/// routing axis. Each downstream consumer (caixa-mesh's
/// `placement.affinity` overlay at caixa-mesh/src/lib.rs:126, the
/// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
/// `spec.placement.affinity` admission rule, the future M4 per-hint
/// node-affinity / pod-affinity rule generator keying off the same
/// value as a K8s `app.pleme.io/affinity-hint=<value>` label
/// selector) requires the value to be a DNS-1123 label — K8s label
/// values are bounded by `[a-z0-9A-Z_.-]{,63}` with a stricter
/// `[a-z0-9]([-a-z0-9]*[a-z0-9])?` floor in every identity-keyed
/// admission rule the apiserver enforces.
///
/// Until this gate landed an `:affinity "DataLocality"` (the canonical
/// TitleCase-from-an-ADR typo), `:affinity "data_locality"` (the
/// Python-module-name leak), `:affinity "data.locality"` (the
/// namespace-dot-on-a-label confusion), `:affinity "-data-locality"` /
/// `:affinity "data-locality-"` (boundary-hyphen violation),
/// `:affinity "data locality"` (paste-from-doc whitespace),
/// `:affinity "data-localité"` (un-Punycode-encoded IDN), or the
/// 64-byte over-cap slug silently passed the empty-only check and the
/// failure surfaced as a no-match at the M3 Adaptive compression
/// overlay's filter time (`placement.affinity` carried a malformed
/// value, no node matched, the workload landed on the default
/// heuristic) — the canonical "declared-but-inert" footgun mirroring
/// the empty-:affinity / empty-shard-key / zero-:politicas /
/// empty-:contratos-target gates already close on every other
/// declare-but-no-opinion axis. Lifting the rejection to a build-time
/// gate closes the fifth typed slot on the Aplicacao surface to land
/// on the canonical DNS-1123 label floor (after the four Servico-name
/// reference axes: `:membros :caixa` 3f9d7a0, `:placement :clusters`
/// 6c8c00b, `:contratos :de`/`:para` 8d5af6b, `:entrada :para`
/// b0e8748).
///
/// Same diagnostic shape as [`AplicacaoError::PlacementClusterInvalid`]
/// (6c8c00b) on the sibling `:placement :clusters` axis — both axes'
/// validated values are guaranteed-accepted by the apiserver without
/// re-validation at any downstream renderer or admission layer.
fn validate_placement_affinity(affinity: &str) -> Result<(), AplicacaoError> {
// Empty is gated separately at the call site for a self-locating
// diagnostic; re-checking here keeps the predicate usable from any
// future call site (the M4 CR materializer's per-affinity
// validator) without an empty-check footgun. Routes through the
// shared [`crate::render::require_valid_dns_1123_label`] gate the
// peer name axes each land on.
crate::render::require_valid_dns_1123_label(
affinity,
|| AplicacaoError::PlacementAffinityEmpty,
|reason| AplicacaoError::placement_affinity_invalid(affinity, reason),
)
}
/// Reject `:placement :shard-key` extractor expressions whose shape can
/// never legitimately drive the future M4 Akka-style cluster-sharding
/// reconciler's hash-extractor pass. Maps the per-byte / length checks
/// into the [`AplicacaoError::ShardKeyInvalid`] variant, so the
/// diagnostic is self-locating (the offending `:shard-key` value is
/// named verbatim alongside the parser-shaped reason) and the author can
/// grep their caixa.lisp for `:shard-key "<expr>"` and fix it in one
/// edit.
///
/// The `:shard-key` slot is the Akka-cluster-sharding `ExtractEntityId`
/// axis (MESH-COMPOSITION §II.4) — a single-token entity-id extractor
/// expression naming the message property to hash on. The realistic
/// shapes in the wild (`tenantId` / `customerId` / `userId` — bare
/// property name; `$tenantId` — Akka entity-id placeholder;
/// `metadata.tenantId` / `$.user.id` — JSONPath-style nested reference;
/// `${tenant}` — interpolation-style template) all sit in the printable
/// ASCII subset; the realistic *non-shapes* (a paste-from-doc
/// multi-line blob landing in `:shard-key`, an embedded space from a
/// paste-from-aligned-doc, a trailing newline from a paste-from-shell
/// heredoc, a non-ASCII byte from a paste-from-Unicode-doc, the
/// `:shard-key "tenant Id"` typo) silently passed the prior empty-only
/// check and the failure surfaces at the future M4 reconciler's hash
/// pass as a runtime extractor-evaluation error far from the source
/// `caixa.lisp`, with no field naming which member's `:shard-key`
/// carried the offending value.
///
/// The contract — the printable ASCII single-token intersection-floor
/// every Akka-style entity-id extractor implementation admits:
///
/// - 1..=[`PLACEMENT_SHARD_KEY_MAX_LEN`] (63) bytes — same cap as the
/// peer DNS-1123-label-shaped `:placement :affinity` /
/// `:placement :clusters` identifier axes; realistic shard-keys sit
/// well under 32 bytes, the cap surfaces paste-from-doc multi-line
/// blob footguns at validate time;
/// - every byte in the printable ASCII range `0x21..=0x7E` —
/// rejects whitespace (space, tab, CR, LF — `"$tenant Id"` /
/// `"$tenantId\n"` from paste-from-aligned-doc /
/// paste-from-shell-heredoc), control characters (`\x00..\x1F`,
/// `\x7F` — the canonical "embedded null from a copy-paste-binary
/// footgun"), and non-ASCII bytes (`"$tenàntId"` —
/// un-Punycode-encoded IDN that round-trips inconsistently across
/// NFC/NFD normalization).
///
/// The accepted set is broader than the DNS-1123 label floor the peer
/// `:placement :clusters` / `:placement :affinity` axes use because the
/// `:shard-key` value is not a K8s `metadata.name` / label-selector
/// landing site; it's an extractor expression the future Akka-style
/// reconciler reads as a property reference. The realistic forms
/// (`$tenantId`, `metadata.tenantId`, `${tenant}`, `$.user.id`) carry
/// `$` / `.` / `{` / `}` characters that the DNS-1123 grammar forbids
/// but every Akka-style entity-id extractor parses. The
/// printable-ASCII-token floor accepts every shape any such extractor
/// would accept while rejecting the cross-implementation footguns
/// (whitespace breaks token boundaries; non-ASCII round-trips
/// inconsistently across YAML emitters and NFC/NFD normalization;
/// control characters silently corrupt the next read).
///
/// Until this gate landed `validate_placement` only refused the
/// `Some("")` empty arm via [`AplicacaoError::ShardedKeyEmpty`]; a
/// structurally invalid `:shard-key` (`":shard-key \" $tenantId\""` —
/// leading space from paste-from-aligned-doc, `":shard-key \"$tenant
/// Id\""` — embedded space, `":shard-key \"$tenantId\\n\""` — trailing
/// newline from paste-from-shell-heredoc, `":shard-key \"$tenàntId\""`
/// — un-Punycode-encoded IDN, `":shard-key \"$tenantId\\x01\""` —
/// control character from paste-from-binary, the 64-byte over-cap
/// paste-from-doc multi-line slug) silently passed validate. The future
/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass
/// would then surface the malformed value either as a runtime
/// extractor-evaluation error (whitespace breaks the extractor's token
/// boundary, no match) or as a silently-different shard assignment
/// across YAML emitters (non-ASCII normalizes differently between the
/// caixa-mesh-side YAML emitter and the in-cluster reconciler's YAML
/// parser, the same entity ID maps to two distinct shards on a
/// re-render). Lifting the shape gate to caixa-build time makes the
/// extractor-floor invariant a structural property of every validated
/// `Placement`: every `Sharded` placement past `validate_placement` has
/// a `:shard-key` the future M4 reconciler can hash without
/// re-validating at the runtime layer.
///
/// Mirrors the [`AplicacaoError::ContratoSlotInvalid`] /
/// [`AplicacaoError::ContratoSubjectInvalid`] /
/// [`AplicacaoError::ContratoEndpointInvalid`] payload-axis shape gates
/// on the peer `:contratos` payload axes — each lifts the
/// runtime-side parser's intersection-floor to a caixa-build-time gate,
/// closing the canonical "this passed validate but the runtime parser
/// rejected it" surprise.
fn validate_placement_shard_key(key: &str) -> Result<(), AplicacaoError> {
// Empty is gated separately at the call site via the more
// self-locating [`AplicacaoError::ShardedKeyEmpty`] diagnostic;
// re-checking here keeps the predicate usable from any future call
// site (the M4 CR materializer's per-shard-key validator) without
// an empty-check footgun.
if key.is_empty() {
return Err(AplicacaoError::ShardedKeyEmpty);
}
if key.len() > PLACEMENT_SHARD_KEY_MAX_LEN {
return Err(AplicacaoError::shard_key_invalid(
key,
format!(
"exceeds :shard-key max length of {PLACEMENT_SHARD_KEY_MAX_LEN} bytes \
(got {} bytes; realistic Akka-style entity-id extractor expressions \
— `tenantId`, `$tenantId`, `metadata.tenantId`, `${{tenant}}` — sit \
well under 32 bytes, this length suggests a paste-from-doc \
multi-line blob landed in `:shard-key` instead of a single-token \
extractor expression)",
key.len()
),
));
}
for &b in key.as_bytes() {
if (0x21..=0x7E).contains(&b) {
continue;
}
let reason = if b == b' ' {
"contains a space (Akka-style entity-id extractor expressions are \
single-token references like `tenantId` / `$tenantId` / `metadata.tenantId`; \
whitespace breaks the extractor's token boundary at the runtime layer, \
and the paste-from-aligned-doc / paste-from-CSV footgun silently lands \
a multi-token blob in one `:shard-key` slot)"
.to_string()
} else if b == b'\t' {
"contains a tab character (paste-from-aligned-doc footgun; the \
Akka-style entity-id extractor reads `:shard-key` as a single-token \
reference, embedded whitespace breaks the token boundary at the \
runtime hash-extractor pass)"
.to_string()
} else if b == b'\n' || b == b'\r' {
format!(
"contains line terminator 0x{b:02x} (paste-from-shell-heredoc / \
paste-from-multiline-doc footgun; the Akka-style entity-id \
extractor reads `:shard-key` as a single-token reference, embedded \
newlines either truncate the value at the YAML emitter layer or \
break the token boundary at the runtime hash-extractor pass)"
)
} else if b < 0x20 || b == 0x7F {
format!(
"contains control character 0x{b:02x} (the canonical \
paste-from-binary / paste-from-screen-cleared-terminal footgun; \
control characters silently corrupt round-trip serialization \
across YAML emitters and break the runtime hash-extractor's \
single-token parser)"
)
} else {
format!(
"contains non-ASCII byte 0x{b:02x} (the canonical \
paste-from-Unicode-doc footgun; non-ASCII bytes round-trip \
inconsistently across NFC/NFD normalization on APFS / ext4 / \
across YAML emitter implementations — the same entity ID can \
silently map to two distinct shards on a re-render. Use a \
printable-ASCII extractor expression like `tenantId`, \
`$tenantId`, or `metadata.tenantId`)"
)
};
return Err(AplicacaoError::shard_key_invalid(key, reason));
}
Ok(())
}
/// Reject `:contratos :de` / `:contratos :para` values whose shape
/// can never legitimately match a validated `:membros :caixa`. Thin
/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
/// shared parser-shaped reason into the
/// [`AplicacaoError::ContratoCaixaInvalid`] variant, so the per-edge
/// diagnostic is self-locating (which slot — `:de` or `:para` — and
/// the offending value verbatim) and the author can grep their
/// caixa.lisp for `:de "<name>"` / `:para "<name>"` and fix it in
/// one edit.
///
/// Until this gate landed an empty or DNS-1123-malformed `:de` /
/// `:para` (`:de ""`, `:de "Cart"` the canonical TitleCase-from-an-ADR
/// typo, `:de "my_cart"` the Python-module-name leak, `:de "team.cart"`
/// the namespace-dot-on-a-label confusion, `:de "-cart"` / `:de "cart-"`
/// the boundary-hyphen violation, the 64-byte over-cap slug, `:de "café"`
/// un-Punycode-encoded IDN) silently passed the per-axis check and
/// surfaced as [`AplicacaoError::ContratoMemberMissing`] at the
/// membership lookup — diagnostic-framed as "this caixa is not in
/// `:membros`" when the root cause is "this `:de` value is not a
/// well-shaped Servico-name identifier and could never legitimately
/// match any validated member". Because every `:membros :caixa` is
/// shape-validated through [`validate_membro_caixa`] (3f9d7a0), the
/// `names` HashSet structurally never contains an empty / malformed
/// string, so the membership lookup arm misframes every empty /
/// malformed input. Lifting the shape arm ahead of the lookup
/// preserves the legitimate `ContratoMemberMissing` arm (a
/// well-shaped `:de` that simply isn't in `:membros` — a phantom
/// reference) while routing every structurally-impossible-to-match
/// input through the narrower self-locating shape diagnostic.
///
/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
/// (3f9d7a0) and [`AplicacaoError::PlacementClusterInvalid`]
/// (6c8c00b) — the third Aplicacao-level Servico-name reference axis
/// to land on the canonical [`crate::render::is_dns_1123_label`]
/// floor. The `slot: &'static str` field carries the kebab-case
/// `:de` / `:para` tag verbatim, mirroring [`BehaviorSpec::validate`]'s
/// per-callback-slot diagnostic shape and the
/// [`ManifestError::CodePathDuplicate`] (e113ace) / [`DepError::DepIsSelf`]
/// (85f102c) cross-list-tag pattern.
fn validate_contrato_caixa(slot: &'static str, caixa: &str) -> Result<(), AplicacaoError> {
// Routes through the shared
// [`crate::render::require_valid_dns_1123_label`] gate the peer
// name axes each land on. The `slot: &'static str` field flows
// through both error variants so the diagnostic names which
// per-edge axis (`:de` vs `:para`) the offending value came from.
crate::render::require_valid_dns_1123_label(
caixa,
|| AplicacaoError::contrato_caixa_empty(slot),
|reason| AplicacaoError::contrato_caixa_invalid(slot, caixa, reason),
)
}
/// Reject `:entrada :para` values whose shape can never legitimately
/// match a validated `:membros :caixa`. Thin wrapper around
/// [`crate::render::is_dns_1123_label`] that maps the shared parser-
/// shaped reason into the [`AplicacaoError::EntradaParaInvalid`]
/// variant, so the diagnostic is self-locating (the offending
/// `:entrada :para` value is named verbatim) and the author can grep
/// their caixa.lisp for `:para "<name>"` and fix it in one edit.
///
/// Until this gate landed an empty or DNS-1123-malformed `:entrada
/// :para` (`:para ""`, `:para "Cart"` the canonical TitleCase-from-an-
/// ADR typo, `:para "my_cart"` the Python-module-name leak,
/// `:para "team.cart"` the namespace-dot-on-a-label confusion,
/// `:para "-cart"` / `:para "cart-"` the boundary-hyphen violation,
/// the 64-byte over-cap slug, `:para "café"` un-Punycode-encoded IDN)
/// silently passed the per-axis check and surfaced as
/// [`AplicacaoError::EntradaMemberMissing`] at the membership lookup
/// — diagnostic-framed as "this caixa is not in `:membros`" when the
/// root cause is "this `:entrada :para` value is not a well-shaped
/// Servico-name identifier and could never legitimately match any
/// validated member". Because every `:membros :caixa` is shape-
/// validated through [`validate_membro_caixa`] (3f9d7a0), the `names`
/// `HashSet` structurally never contains an empty / malformed string,
/// so the membership lookup arm misframes every empty / malformed
/// input. Lifting the shape arm ahead of the lookup preserves the
/// legitimate `EntradaMemberMissing` arm (a well-shaped `:para` that
/// simply isn't in `:membros` — a phantom reference) while routing
/// every structurally-impossible-to-match input through the narrower
/// self-locating shape diagnostic.
///
/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
/// (3f9d7a0), [`AplicacaoError::PlacementClusterInvalid`] (6c8c00b),
/// and [`AplicacaoError::ContratoCaixaInvalid`] (8d5af6b) — the
/// fourth and last Aplicacao-level Servico-name reference axis to
/// land on the canonical [`crate::render::is_dns_1123_label`] floor.
/// No `slot: &'static str` field because there is only one axis
/// (`:entrada :para`), unlike the dual-axis `:contratos :de`/`:para`;
/// the simpler shape mirrors [`validate_membro_caixa`] and
/// [`validate_placement_cluster`].
fn validate_entrada_para(para: &str) -> Result<(), AplicacaoError> {
// Empty is gated separately at the call site for a self-locating
// diagnostic; re-checking here keeps the predicate usable from any
// future call site (the M4 CR materializer's per-`:entrada`
// validator) without an empty-check footgun. Routes through the
// shared [`crate::render::require_valid_dns_1123_label`] gate the
// peer name axes each land on.
crate::render::require_valid_dns_1123_label(
para,
|| AplicacaoError::EntradaParaEmpty,
|reason| AplicacaoError::entrada_para_invalid(para, reason),
)
}
/// Reject `:entrada :host` values the K8s Gateway API v1 apiserver
/// would refuse at admission time. The contract — exactly the regex
/// the Gateway API CRD's OpenAPI schema enforces on `Listener.hostname`
/// and `HTTPRoute.spec.hostnames[]`,
/// `^(\*\.)?[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$`
/// (max length 253; per-label max length 63):
///
/// - lowercase RFC 1123 DNS subdomain (`[a-z0-9-]` only; no
/// uppercase, no underscore, no Unicode/IDN — IDN must be
/// pre-encoded as Punycode `xn--…` by the author);
/// - exactly one optional leading wildcard label (`*.`); a wildcard
/// in any non-leading label position is rejected;
/// - each `.`-separated label is 1..=63 bytes, with non-hyphen
/// alphanumeric at both boundaries (no `-foo`, no `foo-`);
/// - total length 1..=253 bytes;
/// - no IPv4 literal (Gateway API forbids IP literals);
/// - no scheme (`https://`, `http://`), no port (`:8080`), no
/// whitespace, no path (`/`).
///
/// Lifted as a typed gate (rather than an inline cascade in
/// `validate()`) so the contract lives in one place — every future
/// per-host axis (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
/// materializer's host validator, the future per-`:entrada` SAN
/// emission for cert-manager Certificates, the multi-`:entrada`
/// host-collision gate when M4 lands `:entrada` as a `Vec`) reaches
/// for the same predicate, not its own. Same compounding shape as
/// `is_canonical_rate_limit_window` (808017c) and
/// [`WitTarget::label`] (previously the free `contrato_target_label`
/// helper, 5dbcfaf; lifted onto the typed [`WitTarget`] enum so the
/// per-variant label match is compiler-checked-exhaustive).
///
/// The diagnostic carries the offending `host:` verbatim plus a
/// parser-shaped `reason:` naming the specific violation, so the
/// author can grep their caixa.lisp for `:host "<host>"` and fix it
/// in one edit. Same diagnostic shape as `MembroVersaoInvalid`
/// (9888b13).
fn validate_entrada_host(host: &str) -> Result<(), AplicacaoError> {
// Empty is already gated by `EmptyEntradaHost` at the call site;
// re-checking here keeps the predicate usable from any future
// call site (M4 CR materializer) without an empty-check footgun.
if host.is_empty() {
return Err(AplicacaoError::EmptyEntradaHost);
}
if host.len() > crate::render::GATEWAY_API_HOSTNAME_MAX_LEN {
return Err(AplicacaoError::entrada_host_invalid(
host,
format!(
"exceeds Gateway API v1 Hostname max length of {cap} bytes \
(got {} bytes; the K8s apiserver rejects longer hostnames at admission time)",
host.len(),
cap = crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
),
));
}
if host.contains("://") {
return Err(AplicacaoError::entrada_host_invalid(
host,
"must not carry a scheme (drop the `https://` or `http://` prefix; \
Gateway API takes the bare hostname)",
));
}
if host.contains('/') {
return Err(AplicacaoError::entrada_host_invalid(
host,
"must not carry a path (drop the `/…` suffix; Gateway API path \
matching is in `:entrada :paths`)",
));
}
// After the `://` scheme-prefix and `/` path arms have ruled out the
// two `:`-bearing shapes the Gateway API actively rejects with
// location-shaped diagnostics, any remaining `:` in the host body is
// either the canonical "I put the port in the `:host` slot"
// authoring footgun (`"checkout.quero.cloud:8080"` — the `:port`
// slot lives one axis away on the same `:entrada` block) or an
// unbracketed IPv6 literal (`"2001:db8::1"`) which Gateway API v1
// Hostname forbids identically to the IPv4-literal arm below. Both
// shapes silently fell through the `://` and `/` arms before this
// lift and surfaced as a deep `label "<rest>:<port>" contains
// invalid character ':'` diagnostic from the per-byte loop near the
// bottom of this predicate, which named the offending byte but not
// the canonical authoring fix — for the port case the author has to
// know the `:entrada` block carries a separate `:port u16` slot
// (`caixa-core/src/aplicacao.rs:1667`, `default_port = 8080`) and
// move the value over; for the IPv6 case the author has to know
// Gateway API v1 forbids IP literals across the board. The contract
// doc-comment above already promises "no port (`:8080`)" verbatim
// in the rejected-shape enumeration but the predicate's
// implementation refused the `:` only as a side-effect of the
// per-label `[a-z0-9-]` character-class loop; this arm brings the
// implementation in line with the documented contract by surfacing
// the canonical fix at the top-level shape gate, peer with how the
// `://` arm names the scheme prefix and the `/` arm names the
// `:entrada :paths` axis. Same compounding trajectory the recent
// `is_gateway_api_http_path` (6a17961) per-byte tightening followed
// — the typed slot's rejected set matches the apiserver's rejected
// set, structurally, with a self-locating diagnostic at the
// offending axis instead of a deep parser-shape leak.
if host.contains(':') {
return Err(AplicacaoError::entrada_host_invalid(
host,
"must not contain `:` (the port belongs in the `:entrada :port` \
slot — a separate `u16` axis on the same `:entrada` block, \
defaulting to 8080 — not in the host body; drop the `:<port>` \
suffix and author the bare hostname. If you intended an IPv6 \
literal (`2001:db8::1` / `::1` / `fe80::1`), Gateway API v1 \
Hostname forbids IP literals identically to the IPv4-literal \
arm — use a DNS name)",
));
}
// Routed through the lifted [`crate::render::find_ascii_whitespace_byte`]
// predicate — the same single source of truth every peer
// ASCII-whitespace scan in caixa-core flows through: the four
// typed-magnitude codec sites (`limits::parse_byte_size` backing
// `:limits :memory`, `limits::parse_duration` backing `:limits
// :wall-clock`, `limits::parse_millicores` backing `:limits :cpu`,
// `aplicacao::rate_limit_codec::parse` backing `:politicas
// :rate-limit`) and the shared duration codec
// (`supervisor::duration_codec::parse`) backing `:supervisor
// :restart-window` / `:politicas :timeout` / `:politicas
// :circuit-breaker :window`. This landing closes the last string-typed
// slot in caixa-core still calling `.bytes().any(|b|
// b.is_ascii_whitespace())` inline — every ASCII-whitespace scan
// across every typed slot now shares one predicate, so a future
// stricter classification (BOM `\u{FEFF}` / ZWSP `\u{200B}` / ZWJ
// `\u{200D}` — the "invisible but not `char::is_whitespace`" class
// deliberately excluded from the peer non-ASCII predicate) can
// extend at this shared site in one edit rather than seven
// independent scans diverging over time. Naming the offending byte
// in the diagnostic (`0x20` space / `0x09` tab / `0x0a` LF / `0x0c`
// FF / `0x0d` CR) matches the substrate-wide "the diagnostic carries
// the offending byte verbatim" discipline every peer codec site
// already carries (`limits.rs:722` / `limits.rs:784` / `limits.rs:845`
// / `supervisor.rs:823` / `aplicacao.rs:1640`).
if let Some(b) = crate::render::find_ascii_whitespace_byte(host) {
return Err(AplicacaoError::entrada_host_invalid(
host,
format!(
"contains ASCII whitespace byte 0x{b:02x} (Gateway API v1 \
Hostname is a single-token DNS name — leading, trailing, \
or embedded whitespace breaks the K8s apiserver's Hostname \
regex at admission time; the paste-from-aligned-doc / \
paste-from-shell-history / paste-from-CSV footgun silently \
lands a multi-token blob in `:entrada :host`. Strip every \
whitespace byte and author the bare hostname — space \
`0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d` all \
refuse identically)"
),
));
}
// Peer of the ASCII-whitespace scan above: route the non-ASCII
// subset of Unicode `White_Space` through the shared
// [`crate::render::find_non_ascii_whitespace_char`] predicate — the
// single source of truth every peer non-ASCII-whitespace scan in
// caixa-core flows through: `limits::parse_byte_size` (`:limits
// :memory`), `limits::parse_duration` (`:limits :wall-clock`),
// `limits::parse_millicores` (`:limits :cpu`),
// `aplicacao::rate_limit_codec::parse` (`:politicas :rate-limit`),
// and `supervisor::duration_codec::parse` (`:supervisor
// :restart-window` / `:politicas :timeout` / `:politicas
// :circuit-breaker :window`). Before this arm, a NBSP-prefixed host
// (`"\u{00A0}checkout.quero.cloud"` — paste-from-typography), a
// LINE-SEPARATOR-suffixed host (`"checkout.quero.cloud\u{2028}"` —
// paste-from-web-doc), or an EM-SPACE-split host
// (`"checkout.\u{2003}quero.cloud"` — paste-from-typography)
// survived this predicate's ASCII byte-scan (none of the UTF-8
// bytes of `\u{00A0}` / `\u{2028}` / `\u{2003}` match
// `u8::is_ascii_whitespace`), then landed on the per-label
// `bytes[0].is_ascii_alphanumeric()` arm near the bottom of this
// predicate with the generic `label "…" must start and end with an
// alphanumeric` diagnostic — a "far from source at build-time"
// leak that names the label-shape violation but not the
// paste-from-typography origin the author actually needs to fix.
// Peer with the four codec sites the 1b75b38 landing pinned: the
// typed slot's diagnostic axis names the offending codepoint
// (`U+XXXX`) verbatim rather than laundering the value through a
// downstream label-shape arm, so the author can grep their
// caixa.lisp for the invisible codepoint at the surfaced position
// rather than eyeball a multi-byte host for embedded NBSP / LINE
// SEPARATOR / EM-SPACE. Same "single lifted source of truth"
// discipline the peer ASCII-whitespace arm (720ac3b) carries:
// drift between any two typed-slot sites' non-ASCII-whitespace
// rejection set becomes a single-edit fix at the shared predicate
// rather than N independent inline scans diverging over time, and
// a future stricter classification (BOM `\u{FEFF}` / ZWSP
// `\u{200B}` / ZWJ `\u{200D}` — the "invisible but not
// `char::is_whitespace`" class the peer non-ASCII predicate's
// doc-comment names as the follow-up trajectory) extends at the
// shared predicate in one edit rather than seven.
if let Some(ch) = crate::render::find_non_ascii_whitespace_char(host) {
return Err(AplicacaoError::entrada_host_invalid(
host,
format!(
"contains non-ASCII Unicode whitespace character {ch:?} \
(U+{codepoint:04X}) — Gateway API v1 Hostname is a \
single-token DNS name limited to `[a-z0-9-]` labels; \
the paste-from-typography footgun silently lands an \
invisible codepoint (NBSP `U+00A0`, LINE SEPARATOR \
`U+2028`, EM-SPACE `U+2003`, IDEOGRAPHIC SPACE \
`U+3000`, and every other member of the Unicode \
`White_Space` property outside the ASCII byte range) \
in `:entrada :host`, which the K8s apiserver's \
Hostname regex refuses at admission time far from the \
caixa.lisp source line. Strip every non-ASCII \
whitespace character and author the bare hostname \
with only ASCII bytes (write \"checkout.quero.cloud\" \
verbatim)",
codepoint = ch as u32,
),
));
}
// Strip the optional single leading wildcard label *before* the
// trailing-dot check so the bare `"*."` form surfaces the more
// self-locating "wildcard without domain" diagnostic instead of
// the generic "trailing dot" one.
let (had_wildcard, rest) = match host.strip_prefix("*.") {
Some(r) => (true, r),
None => (false, host),
};
if had_wildcard && rest.is_empty() {
return Err(AplicacaoError::entrada_host_invalid(
host,
"wildcard `*.` must be followed by a domain (e.g. `*.example.com`)",
));
}
if rest.contains('*') {
return Err(AplicacaoError::entrada_host_invalid(
host,
"wildcard `*` is allowed only as the first label (`*.example.com`); \
no inner or trailing `*` labels",
));
}
if rest.ends_with('.') {
return Err(AplicacaoError::entrada_host_invalid(
host,
"must not have a trailing `.` (Gateway API hostnames are not \
fully-qualified with a root dot; the apiserver regex rejects \
trailing dots)",
));
}
// Reject pure IPv4 literals: four dot-separated labels, every
// label all-ASCII-digits. Gateway API v1 explicitly forbids IP
// literals as Hostnames.
let labels: Vec<&str> = rest.split('.').collect();
if labels.len() == 4
&& labels
.iter()
.all(|l| !l.is_empty() && l.bytes().all(|b| b.is_ascii_digit()))
{
return Err(AplicacaoError::entrada_host_invalid(
host,
"must not be an IPv4 literal (Gateway API v1 Hostname forbids IP \
literals; use a DNS name)",
));
}
// Per-label shape: 1..=63 bytes, lowercase ASCII alphanumeric +
// hyphen, with non-hyphen at both boundaries.
for label in &labels {
if label.is_empty() {
return Err(AplicacaoError::entrada_host_invalid(
host,
"has an empty label (consecutive `..` or a leading `.`)",
));
}
if label.len() > crate::render::DNS_1123_LABEL_MAX_LEN {
return Err(AplicacaoError::entrada_host_invalid(
host,
format!(
"label {label:?} exceeds DNS-1123 label max length of \
{cap} bytes (got {} bytes)",
label.len(),
cap = crate::render::DNS_1123_LABEL_MAX_LEN,
),
));
}
let bytes = label.as_bytes();
if !bytes[0].is_ascii_alphanumeric() || !bytes[bytes.len() - 1].is_ascii_alphanumeric() {
return Err(AplicacaoError::entrada_host_invalid(
host,
format!(
"label {label:?} must start and end with an alphanumeric \
(no leading or trailing `-`)"
),
));
}
for &b in bytes {
let valid = b.is_ascii_digit() || b.is_ascii_lowercase() || b == b'-';
if !valid {
let msg = if b.is_ascii_uppercase() {
format!(
"label {label:?} contains uppercase character {ch:?} \
(Gateway API hostnames are lowercase-only; use {lower:?})",
ch = b as char,
lower = label.to_ascii_lowercase()
)
} else if b == b'_' {
format!(
"label {label:?} contains `_` (Gateway API hostnames \
allow only `[a-z0-9-]`; use `-` instead)"
)
} else {
format!(
"label {label:?} contains invalid character {ch:?} \
(Gateway API hostnames allow only `[a-z0-9-]`)",
ch = b as char
)
};
return Err(AplicacaoError::entrada_host_invalid(host, msg));
}
}
}
Ok(())
}
/// Reject `:entrada :paths` entries the K8s Gateway API v1 apiserver
/// would refuse at admission time. Thin wrapper around
/// [`crate::render::is_gateway_api_http_path`] that maps the shared
/// parser-shaped reason into the [`AplicacaoError::EntradaPathInvalid`]
/// variant, preserving the more self-locating
/// [`AplicacaoError::EntradaPathEmpty`] /
/// [`AplicacaoError::EntradaPathNotAbsolute`] diagnostics when the
/// path fails those narrower invariants first.
///
/// The contract is the canonical HTTP-path grammar — `1..=
/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`] (1024) bytes,
/// leading `/`, no consecutive `/`, no `.`/`..` segments, no `?`/`#`/
/// whitespace/control/non-ASCII bytes — shared with the
/// `:contratos :endpoint` axis through the lifted predicate so drift
/// between either landing site and the K8s apiserver-side
/// HTTPPathMatch.value OpenAPI schema is a build error visible at
/// the predicate, not a per-renderer "this passed validate but failed
/// admission" surprise. The diagnostic carries the offending `path:`
/// verbatim plus a parser-shaped `reason:` naming the specific
/// violation, so the author can grep their caixa.lisp for `:paths`
/// and fix it in one edit. Same diagnostic shape as
/// [`AplicacaoError::ContratoEndpointInvalid`] on the peer HTTP-path
/// axis.
fn validate_entrada_path(path: &str) -> Result<(), AplicacaoError> {
// Empty and missing-leading-`/` are already gated at the call
// site by `EntradaPathEmpty` and `EntradaPathNotAbsolute`; re-
// checking here keeps the per-axis narrower diagnostics in force
// when the predicate is reached directly (and `is_gateway_api_http_path`
// itself defends against `bytes[0]`-style indexing on empty
// input).
if path.is_empty() {
return Err(AplicacaoError::EntradaPathEmpty);
}
if !path.starts_with('/') {
return Err(AplicacaoError::entrada_path_not_absolute(path));
}
crate::render::is_gateway_api_http_path(path)
.map_err(|reason| AplicacaoError::entrada_path_invalid(path, reason))
}
mod rate_limit_codec {
// `Duration` is no longer named here — the codec routes through
// the substrate primitive [`super::RateLimitUnit::window_from_suffix`]
// (parse arm, `&str → Duration`) and [`super::RateLimit::canonical_unit`]
// (render arm, `Duration → RateLimitUnit`) typed dispatches that carry
// the canonical `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection on the
// closed-set enum's arm-table rather than through vestigial free-helper
// delegates.
use super::{RateLimit, RateLimitUnit};
use serde::{Deserializer, Serializer};
pub fn serialize<S: Serializer>(v: &Option<RateLimit>, s: S) -> Result<S::Ok, S::Error> {
// Route through the canonical [`crate::render::serialize_option_via_str`]
// — the substrate-side single-owner primitive for the forward
// arm of the typed-magnitude codec family. See its docstring
// for the full sibling roster.
crate::render::serialize_option_via_str(v, s, render)
}
pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<RateLimit>, D::Error> {
// Route through the canonical [`crate::render::deserialize_option_via_str`]
// — the substrate-side single-owner primitive for the reverse
// arm of the typed-magnitude codec family. See its docstring
// for the full sibling roster.
crate::render::deserialize_option_via_str(d, parse)
}
fn parse(s: &str) -> Result<RateLimit, String> {
// Paired whitespace-rejection arm — same canonical-form
// render-determinism discipline as the peer
// `limits::parse_byte_size` / `limits::parse_duration` /
// `limits::parse_millicores` /
// `supervisor::duration_codec::parse` sites: the ASCII
// byte-scan closes the WhatWG-conformant whitespace bytes
// (`0x20`, `0x09`, `0x0A`, `0x0C`, `0x0D`), the non-ASCII
// `char::is_whitespace` scan closes the strictly-complementary
// Unicode `White_Space` class (NBSP `\u{00A0}`, LINE SEPARATOR
// `\u{2028}`, EM-SPACE `\u{2003}`, and the peer typography
// codepoints) that `str::trim` at parse entry silently strips.
// Either drift class would round-trip through `render` to a
// *different* canonical form on next emit — breaking the
// THEORY.md Part V render-determinism contract on
// `:politicas :rate-limit`.
//
// Routed through the lifted [`crate::render::reject_whitespace`]
// primitive — the substrate-side single-owner paired-arm gate
// every typed-magnitude codec in caixa-core shares.
crate::render::reject_whitespace::<String, _, _>(
s,
|b| {
format!(
"rate-limit: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
authoring form for `:politicas :rate-limit` is `<integer>/<s|m|h>` (e.g. \
`\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) with no whitespace bytes \
anywhere. A whitespace-carrying shape (`\" 100/s\"`, `\"100/s \"`, \
`\"100 /s\"`, `\"100/ s\"`, `\"100 / s\"`, `\"100/s\\n\"`, `\"\\t100/s\"`) \
round-trips through `render` to a *different* canonical form (`\"100/s\"`) \
on first serialize — breaking the THEORY.md Part V render-determinism \
contract every typed slot carries. Strip every whitespace byte (write \
`\"100/s\"` verbatim)"
)
},
|ch| {
format!(
"rate-limit: value {s:?} contains non-ASCII Unicode whitespace character \
{ch:?} (U+{cp:04X}) — the canonical authoring form for `:politicas \
:rate-limit` is `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, \
`\"10000/h\"`) with no whitespace characters anywhere (ASCII or Unicode). \
A non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}100/s\"`, \
`\"100/s\\u{{2028}}\"`, `\"100\\u{{2003}}/s\"`) survives the ASCII \
byte-scan but `str::trim` (which uses `char::is_whitespace` — the \
Unicode `White_Space` property, strictly wider than the ASCII byte set) \
silently strips it at parse entry, and the value round-trips through \
`render` to a *different* canonical form (`\"100/s\"`) on first \
serialize — breaking the THEORY.md Part V render-determinism contract \
every typed slot carries. Strip every non-ASCII whitespace character \
(write `\"100/s\"` verbatim with only ASCII bytes)",
cp = ch as u32
)
},
)?;
let s = s.trim();
let (rate_str, unit) = s
.split_once('/')
.ok_or_else(|| format!("rate-limit must be `<n>/<unit>`, got {s:?}"))?;
let rate_trim = rate_str.trim();
// The canonical authoring form for `:politicas :rate-limit` is
// `<integer>/<s|m|h>` — every magnitude [`render`] emits is a
// non-negative integer with no decimal point and no leading
// sign, so the parser's accepted set must match for
// serialize/deserialize to round-trip without canonical-form
// drift. Until this gate landed the parser accepted any
// `u32::from_str`-shaped magnitude — and current Rust
// `u32::from_str` permissively accepts a leading `+` (`"+100"`
// → 100), so `"+100/s"` parsed to `RateLimit { 100, 1s }` and
// serde silently round-tripped to `"100/s"` on the next emit
// (a *different* canonical string) — breaking the THEORY.md
// Part V render-determinism contract on the fifth typed-codec
// surface in caixa-core (peer with the four duration codecs the
// 1c55a2a / 818dd38 / d1fd67b / 737a676 / d53c922 trajectory
// already covered: `supervisor::duration_codec` backing three
// typed-duration slots, `limits::parse_duration` backing
// `:limits :wall-clock`, `limits::parse_byte_size` backing
// `:limits :memory`). The fractional / decimal-shaped sibling
// (`"1.5/s"`, `"1.0/s"`, `"0.5/m"`) lands on `u32::from_str`'s
// existing rejection arm, but the diagnostic is value-laundered
// (the bare `"rate-limit rate \"1.5\" not a u32"` wording
// doesn't name the canonical-form remediation or the round-trip
// drift the next emit would produce); this gate lifts the
// fractional arm onto the same canonical-form diagnostic the
// peer codecs carry.
//
// Strict canonical form: every byte of the magnitude is an
// ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
// inputs the gate distinguishes "non-canonical-but-numeric"
// (parses as f64 or i64 — surfaced with a self-locating
// diagnostic naming the canonical authoring form and the
// round-trip drift the rejected shape would produce on first
// serialize) from "garbage" (parses as neither — surfaced with
// the existing narrower `"not a u32"` wording so its
// diagnostic shape remains stable for the parser-shape footgun
// case).
//
// Routed through the lifted
// [`crate::render::is_digit_only_magnitude`] predicate — the
// same source of truth the four peer typed-magnitude codec
// sites share.
let digit_only = crate::render::is_digit_only_magnitude(rate_trim);
if !digit_only {
let numeric = rate_trim.parse::<f64>().is_ok() || rate_trim.parse::<i64>().is_ok();
if numeric {
return Err(format!(
"rate-limit: rate {rate_trim:?} is not a non-negative integer — the \
canonical authoring form for `:politicas :rate-limit` is \
`<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
with no decimal point and no leading `+` / `-` sign. A fractional / \
signed magnitude (`\"1.5/s\"`, `\"+100/s\"`, `\"-1/s\"`) round-trips \
through `render` to a *different* canonical form (`\"1/s\"`, \
`\"100/s\"`, parser-reject) on first serialize — breaking the \
THEORY.md Part V render-determinism contract every typed slot \
carries. Pick an integer rate that fits the desired window \
(write `\"6000/m\"` instead of `\"1.66/s\"`)"
));
}
return Err(format!("rate-limit rate {rate_str:?} not a u32"));
}
// Leading-zero arm — peer with the prior `"+100/s"` arm above
// (4eeae98's predecessor) on the same canonical-form
// render-determinism axis. The digit-only gate accepts
// `"0100/s"`, `"00/s"`, `"007/h"` as `u32::from_str` parses
// them losslessly (= 100, 0, 7), but `render` emits the
// leading-zero-stripped form (`"100/s"`, `"0/s"`, `"7/h"`) —
// a *different* canonical string on the next emit, breaking
// the THEORY.md Part V render-determinism contract the same
// way `"+100/s"` did before the leading-`+` arm landed. The
// single-byte magnitude `"0"` itself round-trips losslessly
// through `render` (`render(0)` emits `"0/s"`) — the
// downstream [`AplicacaoError::PolicyRateLimitZero`] gate is
// what refuses rate-zero authoring, so `"0/s"` stays in the
// accepted set at this codec layer and the diagnostic
// partitioning between canonical-form drift (this arm) and
// semantic-zero (the downstream gate) remains stable.
// Peer with the future leading-zero arms on the three peer
// typed-magnitude codecs the trajectory acknowledges:
// `supervisor::duration_codec`, `limits::parse_duration`,
// `limits::parse_byte_size` — each carries the same
// canonical-form-drift class today; this gate lands the
// discipline on the fourth typed-magnitude codec in
// caixa-core first because the peer `"+100/s"` arm above is
// the closest predecessor on the trajectory.
//
// Routed through the lifted
// [`crate::render::is_leading_zero_padded_magnitude`]
// predicate — the same source of truth the four peer
// typed-magnitude codec sites share.
if crate::render::is_leading_zero_padded_magnitude(rate_trim) {
return Err(format!(
"rate-limit: rate {rate_trim:?} has a non-canonical leading zero — the \
canonical authoring form for `:politicas :rate-limit` is \
`<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
with no leading-zero padding on the magnitude. A leading-zero magnitude \
(`\"0100/s\"`, `\"00/s\"`, `\"007/h\"`) round-trips through `render` to \
a *different* canonical form (`\"100/s\"`, `\"0/s\"`, `\"7/h\"`) on \
first serialize — breaking the THEORY.md Part V render-determinism \
contract every typed slot carries. Strip the leading zeros (write \
`\"100/s\"` instead of `\"0100/s\"`)"
));
}
// The digit-only gate guarantees every byte is `[0-9]`, and
// the leading-zero arm above guarantees the magnitude is
// either the single byte `"0"` or starts with `[1-9]`, so
// the only way `u32::from_str` can fail here is overflow
// (the magnitude exceeds `u32::MAX`). Surface that with an
// overflow-shaped wording so the diagnostic names the
// offending magnitude verbatim rather than collapsing onto
// the non-canonical arm. Same shape
// `supervisor::duration_codec` (1c55a2a) carries on the peer
// duration-codec axis.
let rate: u32 = rate_trim.parse::<u32>().map_err(|_| {
format!("rate-limit rate {rate_trim:?} (digit-only magnitude overflows u32)")
})?;
// The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives on
// the closed-set typed enum [`super::RateLimitUnit`]; this parse
// arm reads the `&str → Duration` projection through the
// substrate primitive [`super::RateLimitUnit::window_from_suffix`]
// (a two-step typed dispatch composing [`super::RateLimitUnit::from_suffix`]
// with [`super::RateLimitUnit::window`]) rather than the vestigial
// module-private `rate_limit_window_from_unit` free helper the
// predecessor 61421a6 left as the last unlifted delegate on this
// axis. One typed dispatch on the substrate primitive instead of
// one runtime call through the free-helper delegate; the sole
// production consumer of the `&str → Duration` axis (this parse
// arm) now reaches for exactly one typed method on the closed-set
// enum, sibling to the codec's render arm's
// [`super::RateLimit::canonical_unit`] dispatch on the paired
// `Duration → RateLimitUnit` axis and to the validate gate's
// [`super::RateLimit::canonical_unit`] shape-probe on the
// canonical-window axis. A future rate-limit-unit addition (a
// `"d"` day suffix once Envoy's `rate_limit_action` grows
// daily-bucket support, a `"ms"` sub-second window once
// high-throughput per-edge policies come into scope per
// MESH-COMPOSITION §III.2 #3) is one variant + one arm per method
// on the closed-set enum, and the compiler enforces exhaustiveness
// on every consumer's `match self` arms — this parse arm's
// accepted-suffix set, the render arm's emitted-suffix set, the
// validate gate's canonical-window set, and every future
// per-`:contratos`-edge rate-limit-override overlay all pick it up
// by construction.
let unit = unit.trim();
let window = RateLimitUnit::window_from_suffix(unit)
.ok_or_else(|| format!("unknown rate-limit window unit {unit:?}"))?;
Ok(RateLimit { rate, window })
}
fn render(rl: RateLimit) -> String {
// The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives at
// module scope on the closed-set typed enum [`super::RateLimitUnit`];
// this render arm reads the `Duration → RateLimitUnit` projection
// through the substrate primitive [`super::RateLimit::canonical_unit`]
// (returns `None` on every non-canonical window — the sub-second /
// non-`{1, 60, 3600}` shapes the validate gate rejects), then
// formats the returned typed enum through its
// [`std::fmt::Display`] impl (which routes through
// [`super::RateLimitUnit::as_suffix`]). Two typed dispatches on
// the substrate primitive instead of one runtime `find_map`
// walk through the free-helper delegate chain
// [`super::rate_limit_window_unit`] (the vestigial free helper's
// sole production consumer was this arm; every other consumer of
// the `Duration → unit` axis — the validate gate below and the
// future M4 per-Aplicacao Envoy config reconciler — now reads
// the same typed method).
//
// A future rate-limit-unit addition (a `"d"` day suffix once
// Envoy's `rate_limit_action` grows daily-bucket support) is
// one variant + one arm per method on the closed-set enum, and
// the compiler enforces exhaustiveness on every consumer's
// `match self` arms — the codec's `parse` accepted-suffix set,
// this render arm's emitted-suffix set, the validate gate's
// canonical-window set, and every future per-`:contratos`-edge
// rate-limit-override overlay all pick it up by construction.
if let Some(unit) = rl.canonical_unit() {
format!("{}/{unit}", rl.rate())
} else {
// Defensive fallback for non-canonical windows. Note:
// [`AplicacaoSpec::validate_politicas`] rejects any
// non-canonical `:rate-limit :window` via
// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`], so
// a validated `RateLimit` never reaches this branch. The
// emitted `<n>/<k>s` form is *not* round-trippable through
// [`parse`] (which accepts only the closed-set
// [`super::RateLimitUnit`] suffixes, not `<k>s` with an
// explicit count) — the validate gate is what makes the
// round-trip a structural property; this branch exists only
// so a programmatic non-validated serialize doesn't panic.
format!("{}/{}s", rl.rate(), rl.window().as_secs())
}
}
}
// ── placement strategy ───────────────────────────────────────────────
/// How the Aplicacao distributes across clusters. Three options:
///
/// - `SingleNode` — one cluster runs the app at a time; takeover on
/// death (Erlang/OTP distributed-app semantics).
/// - `Replicated` — every named cluster runs an instance (active-active).
/// - `Sharded` — entities distribute by hash key across clusters
/// (Akka cluster sharding).
#[derive(
Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
)]
pub enum PlacementStrategy {
SingleNode,
Replicated,
Sharded,
}
/// Substrate-canonical M3-mesh-shaped per-`:placement :estrategia`
/// distribution-strategy default for the `:placement :estrategia` axis —
/// the [`PlacementStrategy::Replicated`] active-active-across-every-named-
/// cluster arm (MESH-COMPOSITION §II.2), extracted as a typed `pub const`
/// so every substrate-side consumer that resolves "what
/// [`PlacementStrategy`] variant does an author-omitted `:placement
/// :estrategia` slot degrade onto?" reaches for exactly one substrate-
/// primitive [`PlacementStrategy`].
///
/// The `:placement :estrategia` default axis has three production
/// consumers on the substrate side today: the [`Default for
/// PlacementStrategy`] impl's return arm, the [`Default for Placement`]
/// impl's struct-literal `estrategia` field, and the serde-side
/// `#[serde(default)]` on [`Placement::estrategia`] that resolves an
/// author-omitted `:placement :estrategia` scalar through the [`Default
/// for PlacementStrategy`] impl. Prior to this lift the three folded onto
/// a raw `Self::Replicated` arm at the [`Default for PlacementStrategy`]
/// impl and implicit `PlacementStrategy::default()` routes at the sibling
/// consumers, with no compile-time link back to the paired
/// [`crate::manifest::Caixa::aplicacao_view`] fold's
/// `.unwrap_or_default()` `Option<Placement>` collapse arm — the fourth
/// production consumer that resolves an author-omitted `:placement` slot
/// (entirely omitted, not just the `:estrategia` scalar within a declared
/// `:placement` block) through [`Placement::default`] which then routes
/// through this same discriminator. A future coherent rebrand of the
/// `:placement :estrategia` default (a widening to `Sharded` once the
/// substrate discovers hash-keyed distribution as the more common
/// production shape, a tightening to `SingleNode` for stateful Erlang/OTP
/// distributed-app-takeover semantics MESH-COMPOSITION §II.1 already
/// names, a per-cluster overlay the operator pins through a future
/// `:placement-overrides` slot) would have had to migrate a lifted
/// discriminator on one path and open-coded discriminators on the peers
/// in lockstep or the four consumers would silently drift out of
/// pairing. Lifting the resolution rule to a typed `pub const` on the
/// substrate primitive means the M3-mesh-canonical `:placement
/// :estrategia` default migrates as one unit on any future axis change.
///
/// The [`PlacementStrategy::Replicated`] value pins MESH-COMPOSITION
/// §II.2's active-active-across-every-named-cluster arm — the closest
/// canonical M3 production reference the substrate carries, matching the
/// caixa-mesh default axis every M3 renderer already keys off (a
/// `programs.yaml` fan-out that emits one `HelmRelease` per cluster is
/// the canonical shape a `:membros`+`:contratos`-declared Aplicacao lands on
/// under the substrate's fleet-programs aggregator without an explicit
/// `:placement :estrategia` override). The two alternatives the closed
/// [`PlacementStrategy::ALL`] accept-set carries
/// ([`PlacementStrategy::SingleNode`] — Erlang/OTP distributed-app
/// takeover, MESH-COMPOSITION §II.1; [`PlacementStrategy::Sharded`] —
/// Akka-style hash-keyed distribution across clusters,
/// MESH-COMPOSITION §II.4) express deliberate takeover / hash-keyed
/// postures an author declares explicitly, never a posture an omitted
/// slot should silently assume.
///
/// Lifted as a typed `pub const` so the M3-mesh-canonical default has
/// exactly one source of truth on the `:placement :estrategia` axis, on
/// the same substrate-primitive lift discipline the sibling M2
/// per-supervisor default set carries
/// ([`crate::supervisor::SUPERVISOR_ESTRATEGIA_DEFAULT`],
/// [`crate::supervisor::SUPERVISOR_MAX_RESTARTS_DEFAULT`],
/// [`crate::supervisor::SUPERVISOR_RESTART_WINDOW_DEFAULT`],
/// [`crate::supervisor::SUPERVISOR_CHILD_RESTART_DEFAULT`]) and the peer
/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes
/// ([`crate::render::DEFAULT_NAMESPACE`],
/// [`crate::render::DEFAULT_LIBRARY_NAME`],
/// [`crate::render::DEFAULT_SERVICO_PORT`]). The first typed default on
/// the M3 mesh-primitive-defining slot family to converge onto the
/// substrate-primitive-lift discipline the M2 supervisor-slot family
/// already carries end-to-end.
pub const PLACEMENT_ESTRATEGIA_DEFAULT: PlacementStrategy = PlacementStrategy::Replicated;
impl Default for PlacementStrategy {
fn default() -> Self {
// Route the [`Default for PlacementStrategy`] impl through the
// substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed
// `pub const` rather than a raw `Self::Replicated` arm — one
// source of truth for the M3-mesh-canonical active-active-
// across-every-named-cluster `:placement :estrategia` default
// (MESH-COMPOSITION §II.2), on the same substrate-primitive
// lift discipline the sibling M2 per-supervisor default set
// ([`crate::supervisor::SUPERVISOR_ESTRATEGIA_DEFAULT`] +
// paired halves) carries end-to-end. Pinned by
// `placement_strategy_default_routes_through_lifted_default`.
PLACEMENT_ESTRATEGIA_DEFAULT
}
}
impl PlacementStrategy {
/// Exhaustive iteration surface for every consumer that reads the
/// full closed-set (the future M4 admission-webhook's accepted-
/// strategy listing in its rejection body, a future `feira app
/// placement --list` CLI-side surfacing of the accepted arm-set,
/// any future round-trip fuzz harness). A future variant addition
/// (an `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint
/// names as a trajectory item) extends this slice as a single edit
/// and every consumer picks up the new entry by construction — the
/// compiler-checked exhaustiveness on the sibling method `match`
/// arms is the build-time guarantee that no arm forgets to grow.
/// Same shape as the sibling closed-set typed enums'
/// [`RateLimitUnit::ALL`] (6bce03d) and
/// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
/// surfaces — the third closed-set typed enum on the caixa surface
/// to converge onto the same discipline.
pub const ALL: &'static [Self] = &[Self::SingleNode, Self::Replicated, Self::Sharded];
/// Canonical camelCase-schema discriminator scalar this variant
/// serializes as under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. The
/// three arms return the paired [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
/// / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
/// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] lifted constants so
/// every substrate consumer that dispatches on the strategy (the
/// `lareira-fleet-programs` aggregator, the future `app-operator`
/// reconciler, the M3 Adaptive compression pass) reads the same
/// byte-string the `Serialize` derive emits — the pin test in
/// [`tests::placement_strategy_variants_serialize_to_lifted_scalar_values`]
/// asserts the two paths agree.
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::SingleNode => crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
Self::Replicated => crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
Self::Sharded => crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
}
}
/// Substrate-canonical reverse projection on the `:placement
/// :estrategia` closed-set axis — parses the camelCase-schema
/// discriminator scalar back to the typed variant, or `None` when
/// `s` is outside the closed-set arm-string set [`Self::as_str`]
/// emits. Dispatches on the same lifted
/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] constants the
/// [`Self::as_str`] emitter walks, so the parse and emit halves of
/// the round-trip migrate through one caixa-core edit on any future
/// arm addition (an `Anycast` mesh-anycast arm the MESH-COMPOSITION
/// §II.5 hint names as a trajectory item lands one variant + one
/// arm per method and the compiler enforces exhaustiveness on every
/// consumer's `match self` arms).
///
/// Prior to this lift the substrate carried only the forward
/// `Self → &str` projection (the [`Self::as_str`] emitter, the
/// [`std::fmt::Display`] impl routed through it, the `Serialize`
/// derive that emits the same byte-string under
/// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]) — every non-serde
/// consumer that wanted to parse a wire-form strategy scalar had to
/// re-inline a three-arm `match s { "SingleNode" => …, "Replicated"
/// => …, "Sharded" => …, _ => … }` cascade that expressed no
/// compile-time link back to the typed variant's canonical lifted
/// constant. A future variant rename or a per-arm serde-attribute
/// drift would silently split the wire byte-string one non-serde
/// consumer parsed from the one the emitter wrote, with the
/// failure surfacing at parse time far from the rebrand commit.
///
/// Same closed-set-reverse-projection discipline the sibling
/// [`crate::CaixaKind::from_wire`] (2aa6d23) and
/// [`RateLimitUnit::from_suffix`] typed enums carry on the peer
/// wire-side `str → Self` axes — extended onto the M3 mesh-primitive-
/// defining `:placement :estrategia` closed-set axis, the third
/// substrate-side closed-set typed enum to converge on the two-way
/// `str ↔ Self` round-trip. Method-named `from_wire` (not `from_str`)
/// to match the peer [`crate::CaixaKind::from_wire`] shape verbatim
/// and side-step the [`std::str::FromStr`]-collision clippy
/// (`clippy::should_implement_trait`) the plain `from_str` name
/// carries; a future explicit [`std::str::FromStr`] impl can layer
/// on top by delegating to this canonical arm-dispatch method.
///
/// Returns `Option<Self>` (rather than `Result<Self, _>`) to match
/// the sibling [`crate::CaixaKind::from_wire`] shape: the caller
/// picks the diagnostic form appropriate for its use site — a
/// future `feira app placement --set` CLI-side arg-parse that wants
/// an `"unknown strategy: {s} (accepted: SingleNode, Replicated,
/// Sharded)"` diagnostic builds one on top by iterating
/// [`Self::ALL`], while the future M4 admission-webhook's rejection
/// path folds `None` onto its per-CR structured refusal body.
#[must_use]
pub fn from_wire(s: &str) -> Option<Self> {
match s {
crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE => Some(Self::SingleNode),
crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED => Some(Self::Replicated),
crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED => Some(Self::Sharded),
_ => None,
}
}
/// Substrate-canonical per-arm predicate naming the cross-slot
/// `:placement :estrategia` ↔ `:placement :shard-key` invariant on the
/// closed-set typed [`PlacementStrategy`] enum: `true` iff the strategy
/// consumes the paired [`Placement::shard_key`] axis (and therefore
/// requires — and is the only strategy that permits — a non-empty
/// `:shard-key` on the paired slot). Today the accept-set is the
/// singleton `{Sharded}` — `Sharded` is the sole Akka-style
/// hash-keyed distribution arm (MESH-COMPOSITION §II.4) that keys off a
/// per-entity extractor expression; `SingleNode` (Erlang/OTP
/// distributed-app takeover — §II.1) and `Replicated` (active-active
/// across every named cluster) have no hash-keyed routing axis to
/// consume the slot and refuse a declared-but-inert `:shard-key`
/// through [`AplicacaoError::ShardKeyOnNonSharded`].
///
/// Every validated [`Placement`] past [`AplicacaoSpec::validate_placement`]
/// satisfies `placement.shard_key().is_some() ==
/// placement.estrategia().requires_shard_key()` by construction — the
/// cross-slot partition the pin
/// [`tests::validate_placement_admits_paired_shape_iff_strategy_requires_shard_key`]
/// locks load-bearing, so every downstream consumer that reaches for
/// the paired shape (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
/// CR materializer's per-CR shard-key resolver, the future
/// [`feira app graph --shard-key`] per-Aplicacao column, the future
/// per-cluster Akka-style cluster-sharding reconciler's per-entity
/// hash-routing gate, the M5 adaptive-placement engine's per-strategy
/// shard-key requirement probe, a future author-facing tatara-lisp
/// linter that flags `(:placement (:estrategia Replicated :shard-key
/// "tenantId"))` shapes before `feira lint` reaches
/// [`AplicacaoSpec::validate`]) can reach for one typed dispatch on
/// the substrate primitive — the predicate names *the cross-slot
/// invariant*, not the arm identity.
///
/// Prior to this lift the "does this strategy consume `:shard-key`"
/// classification lived under the `gen_platform::IsVariant`-derived
/// [`Self::is_sharded`] predicate at three fixture-builder sites in
/// this crate (the [`tests::placement_strategy_variants_round_trip`]
/// per-variant `Placement`-builder's `if s.is_sharded() { Some("$key"…)
/// } else { None }` cascade, the
/// [`tests::estrategia_returns_placement_estrategia_verbatim_across_permutations`]
/// per-variant `Placement`-builder's `estrategia.is_sharded().then(||
/// "tenantId".to_string())` cascade, and the
/// [`tests::validate_placement_reads_through_lifted_estrategia_accessor`]
/// per-variant spec-mutator's identical `.is_sharded().then(…)`
/// cascade). Each site conflated two semantically distinct questions:
/// "is the variant `Sharded`?" (arm-identity, what
/// [`Self::is_sharded`] answers) and "does the variant consume
/// `:shard-key`?" (cross-slot-invariant, what this predicate answers).
/// The two questions land on the same three-way answer under today's
/// closed accept-set (both trip on the singleton `{Sharded}`), but a
/// future arm addition that consumed `:shard-key` under a different
/// name (a hypothetical `Anycast` mesh-anycast arm the MESH-COMPOSITION
/// §II.5 roadmap-hint names that hash-partitions across the cluster
/// pool by client-IP hash rather than an author-declared extractor
/// expression, a hypothetical `WeightedShard` variant that carries a
/// shard-key + per-cluster weight table under a promoted M5
/// adaptive-placement engine) or an addition that did *not* consume
/// `:shard-key` on a semantically Sharded-shaped arm would silently
/// split the two questions. Any consumer that read
/// `.is_sharded().then(…)` for the shard-key requirement gate would
/// silently misclassify the new arm as non-consuming — a fixture
/// builder would omit `:shard-key` where the new arm required one and
/// [`AplicacaoSpec::validate_placement`] would refuse the fixture with
/// [`AplicacaoError::ShardedWithoutKey`] far from the arm-addition
/// commit, a future M4 CR materializer would fall through the
/// `.is_sharded()`-only branch to the non-shard-key resolver arm and
/// silently emit an empty extractor at the Akka reconciler layer.
///
/// Lifting the classification as a substrate-primitive method on the
/// closed-set typed enum names the cross-slot invariant on the
/// primitive that owns the partition: every future arm addition
/// declares its `:shard-key` consumption in one place (this predicate's
/// `match self` arm-set), and every downstream consumer that reaches
/// for the paired shape reads through one typed dispatch. Same
/// discipline as the sibling [`WitContract::is_capability`] (7b97d26)
/// per-arm predicate on the pre-projection WIT-shape axis and the
/// [`WitTarget::is_capability`] `gen_platform::IsVariant`-derived
/// paired predicate on the post-projection typed-view axis — a
/// per-arm semantic-classification predicate paired with the
/// arm-identity predicate the derive already emits, closing the drift
/// footgun on the cross-slot invariant axis.
///
/// Method-named `requires_shard_key` (not `has_shard_key`, not
/// `is_shard_keyed`, not `takes_shard_key`) because the cross-slot
/// invariant reads as "this strategy *requires* the paired
/// `:shard-key` axis" — the `SingleNode`/`Replicated` arms *refuse*
/// the axis through [`AplicacaoError::ShardKeyOnNonSharded`], not
/// merely omit it. The `has_*` framing would read as an accessor
/// (returning the presence of an already-carried value) rather than a
/// requirement (naming the invariant the paired slot must satisfy).
/// Returns `bool` (not `Option<()>` or a marker-type witness), same
/// shape as the sibling [`WitContract::is_capability`] /
/// [`Self::is_sharded`] per-arm boolean predicates on the closed-set
/// arm-family, so every consumer reaches for `.requires_shard_key()`
/// as a drop-in replacement for the `.is_sharded()` conflated read
/// without a return-shape migration.
#[must_use]
pub const fn requires_shard_key(self) -> bool {
match self {
Self::Sharded => true,
Self::SingleNode | Self::Replicated => false,
}
}
}
// Compile-time pins on the [`PlacementStrategy::requires_shard_key`]
// cross-slot-invariant per-arm predicate: the module-scope const-eval
// assertions below trip at caixa-core build time (not test time) if a
// future edit rewires the predicate's arm-set away from the singleton
// `{Sharded}` accept-set MESH-COMPOSITION §II.4 pins. The
// [`tests::placement_strategy_requires_shard_key_partitions_the_arm_set`]
// runtime pin covers the same truth-table with a more descriptive
// diagnostic on failure; these const-eval items add a build-time failure
// surface strictly stronger than the runtime pin (a downstream renderer's
// `const`-context reader that composed against a rebound predicate would
// still surface here before the test suite even ran) and side-step the
// `clippy::assertions_on_constants` lint the runtime `assert!(CONST)` pin
// would otherwise accumulate on the caixa-core module baseline.
const _: () = assert!(!PlacementStrategy::SingleNode.requires_shard_key());
const _: () = assert!(!PlacementStrategy::Replicated.requires_shard_key());
const _: () = assert!(PlacementStrategy::Sharded.requires_shard_key());
/// [`std::fmt::Display`] routed through [`PlacementStrategy::as_str`], so
/// the pretty-printed byte-string every consumer that formats the strategy
/// as user-facing text lands on (the M3 [`AplicacaoError::PlacementWithoutClusters`]
/// / [`AplicacaoError::ShardKeyOnNonSharded`] `#[error(":placement
/// {estrategia} …")]` diagnostic templates, the future `feira app graph`
/// per-Aplicacao strategy line, the future M4 CR materializer's per-
/// admission-webhook rejection body) reaches for the same lifted
/// [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
/// [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
/// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] const the wire-format
/// `Serialize` derive already emits under
/// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] and the
/// [`PlacementStrategy::as_str`] helper already returns.
///
/// Until this lift landed the sibling OTP-shape typed enums —
/// [`crate::supervisor::RestartStrategy`] / [`crate::supervisor::RestartPolicy`]
/// (both derive `gen_platform::Discriminant` with `#[discriminant(also_display)]`
/// so [`std::fmt::Display`] routes through the same discriminant string
/// the wire format emits) — carried a stable [`std::fmt::Display`]
/// surface but [`PlacementStrategy`] did not; every consumer reaching
/// for a strategy byte-string past the wire format had to pick between
/// three paths ([`PlacementStrategy::as_str`], the [`Serialize`] derive's
/// serialized string, `format!("{variant:?}")` on the [`std::fmt::Debug`]
/// derive), any two of which a future variant rename or
/// `#[serde(rename_all = "kebab-case")]` attribute would silently
/// desynchronize — with the failure surfacing as a downstream renderer /
/// operator's per-strategy dispatch reading one spelling while the wire
/// format emitted another, far from the source rebrand commit and with
/// no field naming the drift. Routing `Display` through
/// [`PlacementStrategy::as_str`] makes the three paths
/// (`Debug` for structural inspection, `Display` for user-facing text,
/// `Serialize` for the wire format) converge on the same lifted
/// [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const set: the wire byte-string,
/// the diagnostic byte-string, and the pretty-printed byte-string move
/// as a single unit through one canonical declaration each, by
/// construction. Same trajectory as [`PlacementStrategy::as_str`]
/// (cc8f749) on the sibling wire-vs-const single-source axis — this lift
/// closes the third path.
///
/// Pin tests
/// [`tests::placement_strategy_display_routes_through_as_str_helper`]
/// and
/// [`tests::placement_strategy_display_matches_serialized_wire_byte_string`]
/// assert the three paths agree byte-for-byte on every variant, so a
/// future variant rename or per-arm serde attribute drift is a build
/// error visible at caixa-core test time, not a silent per-consumer
/// dispatch miss at apply / reconcile time.
impl std::fmt::Display for PlacementStrategy {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
/// Substrate-canonical [`AsRef<str>`] projection on the M3
/// per-Aplicacao distribution-strategy [`PlacementStrategy`] closed-set
/// typed enum — routes through the same [`PlacementStrategy::as_str`]
/// `pub const fn` scalar accessor the paired [`std::fmt::Display`] impl
/// and the un-`rename`d [`serde::Serialize`] derive already key off, so
/// any future consumer that binds a [`PlacementStrategy`] through the
/// standard-library `impl AsRef<str>` bound (a future `feira app
/// placement --set <arm>` verb that composes the emitted
/// `PascalCase`/camelCase wire scalar into a
/// [`std::process::Command::arg`] shell-out of the future
/// `lareira-fleet-programs` aggregator's per-Aplicacao gate, a
/// per-Aplicacao structured-log recorder on the future `app-operator`'s
/// hierarchical reconciliation surface that accepts `impl AsRef<str>`
/// at the `tracing::field::Value` `Str`-arm, a
/// [`std::collections::HashMap`] lookup keyed on the strategy wire byte
/// through `map.get::<str>(strategy.as_ref())` on a future
/// per-strategy dispatch table the M5 adaptive-placement engine
/// composes) reaches the paired
/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] lifted-const
/// through one substrate-primitive dispatch rather than an open-coded
/// `.as_str()` projection at every wire-up.
///
/// Peer of the sibling [`std::fmt::Display`] impl on the same
/// primitive — both delegate to the shared
/// [`PlacementStrategy::as_str`] `pub const fn` accessor, so
/// [`format!("{v}")`], `v.as_str()`, and `<PlacementStrategy as
/// AsRef<str>>::as_ref(&v)` resolve to the same byte-string per
/// instance by construction. A future variant rename or `#[serde(rename_all
/// = "kebab-case")]` attribute-drift on the enum reaches every one of
/// the three paths (plus the wire-format `Serialize` derive that
/// already routes through the same lifted const) through exactly one
/// caixa-core edit.
///
/// Same "route the trait impl through the substrate-primitive
/// accessor" discipline the sibling [`crate::CaixaVersion`]
/// [`AsRef<str>`] impl (16d5c7e), the paired M2
/// [`crate::supervisor::RestartStrategy`] [`AsRef<str>`] impl
/// (63eb1a4), and the paired M2 [`crate::supervisor::RestartPolicy`]
/// [`AsRef<str>`] impl (419ea81) carry — closes the M2/M3
/// closed-set-typed-enum family's standard-library [`AsRef<str>`]
/// projection axis onto the last remaining M3 mesh-primitive-defining
/// slot, so every OTP/mesh-shape closed-set typed enum on the caixa
/// surface now carries the paired [`AsRef<str>`] + [`fmt::Display`] +
/// `as_str` triple through one lifted `M3_PLACEMENT_ESTRATEGIA_*` /
/// `SUPERVISOR_*` const. Rust-side newtype/typed-enum convention pairs
/// [`AsRef<str>`] and [`fmt::Display`] on the same primitive so a
/// caller who has one has both; before this lift,
/// [`PlacementStrategy`] carried [`fmt::Display`] but not the paired
/// [`AsRef<str>`] impl the convention names.
///
/// Pinned load-bearing by
/// [`tests::placement_strategy_as_ref_str_routes_through_as_str_accessor`]
/// (byte-parity pin against [`PlacementStrategy::as_str`] across the
/// three-arm closed set) and
/// [`tests::placement_strategy_as_ref_str_routes_through_display_via_shared_accessor`]
/// (three-path convergence: `AsRef<str>` + `Display` + `as_str` all
/// resolve to the same lifted `M3_PLACEMENT_ESTRATEGIA_*` const per
/// arm) — any future silent detour that routes the impl through a
/// divergent projection (a per-arm inline `match self { … }`
/// re-inlining that opens a compile-time link to the un-lifted
/// arm-literal, a swap onto the kebab-case
/// [`gen_platform::Discriminant`] catalog identity that would collide
/// the wire axis with the dispatcher-catalog axis) trips at
/// caixa-core test time under `assert_eq!` rather than at a downstream
/// `impl AsRef<str>`-bound consumer's silent split.
impl AsRef<str> for PlacementStrategy {
fn as_ref(&self) -> &str {
self.as_str()
}
}
/// Trait-idiomatic reverse projection on the M3-mesh-primitive-defining
/// [`PlacementStrategy`] closed-set typed enum — routes byte-for-byte
/// through the paired substrate-primitive [`PlacementStrategy::from_wire`]
/// `Option<Self>` accessor so every future consumer that binds a
/// camelCase-schema `:placement :estrategia` wire byte-string through the
/// standard-library `.try_into()` / [`TryFrom`] axis (a future `feira app
/// placement --set <SingleNode|Replicated|Sharded>` CLI arg-parse that
/// composes into `let estrategia: PlacementStrategy = s.try_into()?`, a
/// future `mesh.pleme.io/v1alpha1/Aplicacao` CR admission-webhook that
/// folds a `spec.placement.estrategia: String` field through
/// `PlacementStrategy::try_from(&s)?`, a generic `<T: TryFrom<&str>>`-
/// bound loader over any of the substrate's closed-set typed enums)
/// reaches the same three-arm accept-set the sibling
/// [`PlacementStrategy::from_wire`] resolver parses through and the
/// sibling [`PlacementStrategy::as_str`] emits, rather than an open-coded
/// per-arm `match s { "SingleNode" => …, "Replicated" => …, "Sharded" =>
/// …, _ => … }` cascade whose arm-set has no compile-time link back to
/// the substrate primitive.
///
/// Complements the pre-existing forward-projection triple
/// ([`std::fmt::Display`], [`AsRef<str>`], [`PlacementStrategy::as_str`])
/// with the paired trait-idiomatic reverse-projection axis: Rust-side
/// newtype/typed-enum convention pairs [`AsRef<str>`] with either
/// [`std::str::FromStr`] or [`TryFrom<&str>`] on the same primitive so a
/// caller who can project *out to* a `&str` can also project *in from*
/// one. The [`TryFrom<&str>`] axis is deliberately chosen over
/// [`std::str::FromStr`] to sidestep the `clippy::should_implement_trait`
/// lint the sibling method-named [`PlacementStrategy::from_wire`] would
/// trigger under a `FromStr` impl (the same design tradeoff the peer
/// [`crate::CaixaKind`] (3c83606), [`crate::CaixaDialeto`] (bf33136), and
/// [`crate::provedor::ferrite::FerriteRuntime::from_wire`] blocks note)
/// — this impl closes the trait-idiomatic reverse axis without
/// disturbing the method-named `from_wire` shape every sibling closed-set
/// typed enum on the substrate already carries.
///
/// `type Error = ()` matches the sibling [`PlacementStrategy::from_wire`]'s
/// `Option<Self>` return-shape's deliberate deferral of error typing:
/// the caller picks the diagnostic form appropriate for its use site (a
/// future `feira app placement --set` arg-parse composes its own per-verb
/// "unknown strategy: <arg> — accepted: {…}" message enumerating
/// [`PlacementStrategy::ALL`], a future M4 admission-webhook rejection
/// body wraps the `Err(())` outcome with the accepted-set enumeration for
/// operator diagnostics, a `Result::map_err` at the call site lifts the
/// unit-error to a per-verb error type).
///
/// The paired [`TryFrom<&str>`] impl reaches the same three-arm accept-
/// set the [`PlacementStrategy::from_wire`] resolver dispatches through,
/// so any future arm addition (an `Anycast` mesh-anycast arm the
/// MESH-COMPOSITION §II.5 hint names as a trajectory item) grows the
/// trait-idiomatic axis by construction — one caixa-core edit on
/// [`PlacementStrategy::from_wire`] extends both the method-named reverse
/// projection every existing consumer keys off and the trait-idiomatic
/// reverse projection this impl exposes, without a coordinated rewrite
/// across every future `TryFrom<&str>`-bound consumer's arm-set.
///
/// Extends the substrate-wide closed-set-enum reverse-projection family
/// ([`crate::CaixaKind`] via 3c83606, [`crate::CaixaDialeto`] via
/// bf33136) onto the first M3-mesh-primitive-defining slot enum on the
/// caixa surface — the `:placement :estrategia` closed set the
/// caixa-mesh renderer keys off end-to-end.
///
/// Pinned load-bearing by
/// [`tests::placement_strategy_try_from_str_routes_through_from_wire_accessor`]
/// (byte-parity pin against [`PlacementStrategy::from_wire`] across the
/// three-arm accept-set) and
/// [`tests::placement_strategy_try_from_str_rejects_unknown_byte_strings`]
/// (rejection witness against silent accept-set widening).
impl TryFrom<&str> for PlacementStrategy {
type Error = ();
fn try_from(s: &str) -> Result<Self, Self::Error> {
Self::from_wire(s).ok_or(())
}
}
/// Trait-idiomatic forward projection on the M3-mesh-primitive-defining
/// [`PlacementStrategy`] closed-set typed enum — routes byte-for-byte
/// through the paired substrate-primitive [`PlacementStrategy::as_str`]
/// `pub const fn` accessor via `strategy.as_str()`. Return type is
/// `&'static str` by construction — every [`PlacementStrategy::as_str`]
/// arm resolves to a paired lifted
/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] `pub const &str`
/// with static lifetime, so the trait's return-type promise is upheld
/// structurally without a `String::leak()` cast or a per-arm inline
/// literal.
///
/// Complements the pre-existing forward-projection triple
/// ([`std::fmt::Display`], [`AsRef<str>`], [`PlacementStrategy::as_str`])
/// with the trait-idiomatic forward-projection axis: Rust-side
/// newtype/typed-enum convention pairs [`TryFrom<&str>`] with the mirror-
/// image [`From<Self> for &'static str`] on the same primitive so a
/// caller who can project *in from* a `&str` via the trait axis can also
/// project *out to* one under a `'static`-lifetime bound. The
/// [`AsRef<str>`] impl already carries the same emit-set on the borrowed
/// return path; this impl closes the trait-idiomatic axis pair with the
/// stricter `&'static str` lifetime the sibling [`AsRef<str>`] cannot
/// promise (its return borrows from `&self`, not from the
/// [`PlacementStrategy::as_str`] `pub const fn`'s static-string result).
///
/// Same "route the trait impl through the substrate-primitive accessor"
/// discipline the sibling [`crate::supervisor::RestartStrategy`]
/// `From<Self> for &'static str` impl (523157d — first-mover on this
/// forward-projection family), [`crate::supervisor::RestartPolicy`]
/// `From<Self> for &'static str` impl (9fb37d0 — second peer, closing
/// the M2 OTP-shape sibling pair), [`crate::CaixaKind`]
/// `From<Self> for &'static str` impl (edb827b — third peer, opening
/// the campaign onto the top-level caixa surface), and
/// [`crate::CaixaDialeto`] `From<Self> for &'static str` impl (c189a6f
/// — fourth peer, extending onto the dialect-classification axis)
/// carry — extends the substrate primitive's trait-idiomatic forward-
/// projection axis onto the fifth closed-set fieldless typed enum on
/// the caixa surface: the M3-mesh-primitive-defining `:placement
/// :estrategia` closed-set axis the caixa-mesh renderer keys off end-
/// to-end, previously carrying the paired [`std::fmt::Display`] /
/// [`AsRef<str>`] / [`PlacementStrategy::as_str`] / [`TryFrom<&str>`] /
/// [`PlacementStrategy::from_wire`] forward+reverse projections but not
/// yet the trait-idiomatic forward projection with the `&'static str`
/// lifetime bound.
///
/// Same shape as the sibling [`crate::CaixaDialeto`] axis pair:
/// [`PlacementStrategy::as_str`] output and
/// [`PlacementStrategy::from_wire`] input share the same camelCase-
/// schema `PascalCase` vocabulary by construction (the same three
/// lifted [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`] constants
/// dispatch on both halves) — the trait-idiomatic axis pair
/// ([`From<Self> for &'static str`] + [`TryFrom<&str> for Self`])
/// therefore round-trips directly, without an intermediate wire-vocab
/// hop the peer [`crate::CaixaKind`] axis pair requires. This lift
/// extends the "direct round-trip" precedent
/// [`crate::CaixaDialeto`] (c189a6f) established onto the first M3-
/// mesh-primitive-defining slot enum.
///
/// The paired [`PlacementStrategy::as_str`] accessor's three-arm emit-
/// set is the single source of truth — every future arm addition (an
/// `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint names as
/// a trajectory item, a hypothetical `WeightedShard` variant that
/// carries a shard-key + per-cluster weight table under a promoted M5
/// adaptive-placement engine) grows the trait-idiomatic forward axis
/// by construction: one caixa-core edit on
/// [`PlacementStrategy::as_str`] extends every one of the sibling
/// forward-projection paths ([`std::fmt::Display`], [`AsRef<str>`],
/// [`PlacementStrategy::as_str`] itself, and this [`From<Self> for
/// &'static str`]) without a coordinated rewrite across every future
/// `Into<&'static str>`-bound consumer's arm-set. This lift closes the
/// fifth peer on the trait-idiomatic forward-projection campaign the
/// recently-landed peer commits opened; the remaining nine closed-set
/// typed enums on the caixa substrate surface (`WitShape`,
/// `RateLimitUnit`, `PathShapeViolation`, `InvariantKind`,
/// `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
/// `FerriteRuntime`) are the future targets of this campaign.
///
/// Pinned load-bearing by
/// [`tests::placement_strategy_from_into_static_str_routes_through_as_str_accessor`]
/// (byte-parity pin against [`PlacementStrategy::as_str`] across the
/// three-arm emit-set, plus a `const`-context materialization witness
/// for the `&'static str` lifetime promise routed through the paired
/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`] lifted constants, plus
/// a paired `.into()` shape assertion covering the blanket-derived
/// `Into<&'static str>` shape) and
/// [`tests::placement_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
/// (partition pin asserting `<&'static str as
/// From<PlacementStrategy>>::from` and [`PlacementStrategy::as_str`]
/// agree on every arm, plus a two-way direct round-trip witness through
/// the paired trait-idiomatic [`TryFrom<&str>`] axis that closes the
/// two-way `Self ↔ &'static str` round-trip on the trait-idiomatic
/// axis pair without the wire-vocab intermediate the peer
/// [`crate::CaixaKind`] axis pair requires — the emit-side
/// [`PlacementStrategy::as_str`] and the parse-side
/// [`PlacementStrategy::from_wire`] dispatch on the same three lifted
/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`] constants by
/// construction, so round-tripping composes the two trait impls
/// directly).
impl From<PlacementStrategy> for &'static str {
fn from(strategy: PlacementStrategy) -> &'static str {
strategy.as_str()
}
}
/// Trait-idiomatic *forward* projection on [`PlacementStrategy`] from a
/// *borrowed* input onto the `&'static str` axis — the borrowed-input
/// companion to the paired owned-input [`From<PlacementStrategy> for
/// &'static str`] impl immediately above. Routes byte-for-byte through
/// the same substrate-primitive [`PlacementStrategy::as_str`] `pub const
/// fn` accessor so every consumer that binds a `&PlacementStrategy`
/// through the standard-library `.into()` / [`From<&Self> for &'static
/// str`] axis (a `PlacementStrategy::ALL.iter().map(<&'static
/// str>::from).collect::<Vec<_>>()` per-arm accept-set materializer —
/// whose iterator over `&'static [PlacementStrategy]` yields
/// `&PlacementStrategy`, not `PlacementStrategy`, so the owned-input
/// [`From<PlacementStrategy>`] axis alone forces every call site through
/// an explicit `.copied()` / dereference / [`Copy`]-bound restatement
/// rather than the direct trait-idiomatic projection; a future generic
/// `<T: Copy + for<'a> Into<&'static str>>`-bound diagnostic column over
/// the substrate-wide closed-set typed-enum family that walks the
/// `iter().map(Into::into)` shape verbatim; the future M4
/// `mesh.pleme.io/v1alpha1/Aplicacao` CR admission-webhook rejection
/// body that composes the accepted-`:placement :estrategia` enumeration
/// from an iterated `PlacementStrategy::ALL.iter().map(|s| s.into())`
/// pipe rather than a per-arm `match s { … }` cascade; a future
/// `HashMap::<&'static str, PlacementStrategy>::from_iter(
/// PlacementStrategy::ALL.iter().map(|s| (s.into(), *s)))`-style
/// per-strategy reverse-lookup table the sibling [`TryFrom<&str>`] impl
/// cannot compose without this borrowed-input axis in place) reaches
/// the same three-arm lifted
/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] const the paired
/// owned-input [`From<PlacementStrategy> for &'static str`], the sibling
/// [`std::fmt::Display`], [`AsRef<str>`], and [`PlacementStrategy::as_str`]
/// surfaces already return.
///
/// Sixth peer on the substrate-wide trait-idiomatic *borrowed-input*
/// forward-projection family opened on [`crate::dep::DepList`]
/// (64aa742) and extended onto [`crate::CaixaKind`] (5ab993a),
/// [`crate::CaixaDialeto`] (807b0b5), the paired M2 OTP-shape
/// [`crate::supervisor::RestartStrategy`] (e941836), and
/// [`crate::supervisor::RestartPolicy`] (842c7f3). Rust's `From` trait
/// does not auto-derive the `From<&Self>` sibling from a `From<Self>`
/// impl (the blanket `impl<T, U> From<&T> for U where T: Copy, U:
/// From<T>` does not exist in `core`), so every closed-set typed enum
/// that carries the owned-input axis but not the borrowed-input axis
/// forces every borrowed-input call site through a `.copied()` /
/// `<&'static str>::from(*strategy)` / `strategy.as_str()` detour whose
/// type bounds have no compile-time link to the substrate primitive.
/// [`PlacementStrategy`] is the first M3-mesh-primitive-defining
/// closed-set typed enum to converge onto this borrowed-input campaign
/// — first-mover on the M3 mesh-slot family the caixa-mesh renderer
/// keys off end-to-end, ahead of the sibling
/// [`crate::aplicacao::WitShape`] `:contratos :wit` census-label axis
/// (56998ec) and [`crate::aplicacao::RateLimitUnit`]
/// `:politicas :rate-limit` canonical-suffix axis (7fdfbf4) whose owned-
/// input forward-projection axes landed earlier in the substrate-wide
/// campaign but await the paired borrowed-input closure.
///
/// Same three-path convergence discipline as the paired owned-input
/// impl (this borrowed-input axis, the paired owned-input
/// [`From<PlacementStrategy> for &'static str`], and
/// [`PlacementStrategy::as_str`] all route through the same lifted
/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`] const), so a future
/// variant rename or per-arm serde-attribute drift reaches every one
/// of the six sibling forward-projection paths
/// ([`std::fmt::Display`], [`AsRef<str>`], [`Self::as_str`],
/// [`From<Self> for &'static str`], this [`From<&Self> for &'static
/// str`], and the un-`rename`d [`serde::Serialize`] derive that also
/// emits [`Self::as_str`]'s bytes) through exactly one caixa-core
/// edit.
///
/// The [`PlacementStrategy::as_str`] emit and
/// [`PlacementStrategy::from_wire`] parse share the same `PascalCase`
/// vocabulary by construction — the same three lifted
/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`] constants dispatch on
/// both halves — so the borrowed-input forward axis and the reverse
/// axis compose directly without the intermediate wire-vocab hop the
/// peer [`crate::CaixaKind`] axis pair requires. The round-trip
/// witness pin below locks this direct composition on the M3 slot
/// enum's trait-idiomatic axis pair.
///
/// Pinned load-bearing by
/// [`tests::placement_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
/// (byte-parity pin against [`PlacementStrategy::as_str`] across the
/// three-arm emit-set via a borrowed input, plus a `const`-context
/// materialization witness for the `&'static str` lifetime promise,
/// plus a blanket `.into()` shape) and
/// [`tests::placement_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
/// (cross-axis partition pin against the paired owned-input
/// [`From<PlacementStrategy> for &'static str`] impl, plus a
/// `.iter().map(Into::into)` pipe witness over
/// [`PlacementStrategy::ALL`], plus a direct round-trip witness through
/// [`TryFrom<&str>`] that closes the two-way `&Self → &'static str →
/// Self` round-trip on the M3 slot enum's trait-idiomatic axis pair
/// without the wire-vocab intermediate the peer [`crate::CaixaKind`]
/// axis pair requires).
impl From<&PlacementStrategy> for &'static str {
fn from(strategy: &PlacementStrategy) -> &'static str {
strategy.as_str()
}
}
/// Trait-idiomatic *forward* projection on the M3 mesh-primitive
/// `:placement :estrategia` distribution-strategy [`PlacementStrategy`]
/// closed-set typed enum from an *owned* input onto the owned-[`String`]
/// axis — routes byte-for-byte through the substrate-primitive
/// [`PlacementStrategy::as_str`] `pub const fn` accessor so every consumer
/// that binds a [`PlacementStrategy`] through the standard-library
/// `.into()` / [`From<Self> for String`] (equivalently [`Into<String>`])
/// axis reaches the same three-arm lifted
/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] byte-string the
/// paired owned-input [`From<PlacementStrategy> for &'static str`] (afa3562),
/// the borrowed-input [`From<&PlacementStrategy> for &'static str`]
/// (4d941d8), the sibling [`std::fmt::Display`], [`AsRef<str>`], and
/// [`PlacementStrategy::as_str`] surfaces already return.
///
/// Extends the trait-idiomatic *owned-[`String`]* forward-projection
/// family (opened on [`crate::supervisor::RestartStrategy`] — 7baa18a —
/// the first-mover on the M2 OTP-shape sibling-restart-strategy axis,
/// extended onto [`crate::supervisor::RestartPolicy`] — 7851725 — the
/// second-of-two-in-M2 per-child restart-decision axis, then onto
/// [`crate::CaixaKind`] — 231a18c — the structurally most fundamental
/// closed-set fieldless typed enum on the caixa surface, then onto
/// [`crate::CaixaDialeto`] — 88942cd — the dialect-classification axis,
/// then onto [`crate::dep::DepList`] — 32b0ee8 — the two-list dep-graph
/// axis) onto the sixth peer: the M3 mesh-primitive
/// `:placement :estrategia` distribution-strategy axis
/// [`PlacementStrategy`] carries. First M3-mesh-primitive-defining
/// closed-set typed enum to converge onto this owned-[`String`]
/// forward-projection campaign — first-mover on the M3 mesh-slot family
/// the caixa-mesh renderer keys off end-to-end, ahead of the sibling
/// [`WitShape`] `:contratos :wit` census-label axis and
/// [`RateLimitUnit`] `:politicas :rate-limit` canonical-suffix axis whose
/// owned-[`String`] axis closures remain future targets of this campaign.
///
/// Rust's standard library does not carry a blanket
/// `impl<T: AsRef<str>> From<T> for String` (nor an
/// `impl<T: fmt::Display> From<T> for String`), so every closed-set typed
/// enum that carries the paired [`AsRef<str>`] / [`std::fmt::Display`] /
/// [`From<Self> for &'static str`] / [`From<&Self> for &'static str`]
/// quadruple but not the owned-[`String`] axis forces every owned-string
/// call site through a `.to_string()` / `.as_str().to_owned()` /
/// `String::from(strategy.as_str())` detour whose type bounds have no
/// compile-time link to the substrate primitive.
///
/// Same as the peer [`crate::supervisor::RestartStrategy`] /
/// [`crate::supervisor::RestartPolicy`] / [`crate::CaixaDialeto`] /
/// [`crate::dep::DepList`] owned-[`String`] axis pairs (whose forward
/// emit and reverse parse share one vocabulary by construction),
/// [`PlacementStrategy`]'s [`PlacementStrategy::as_str`] emit and
/// [`PlacementStrategy::from_wire`] parse resolve through the same
/// three lifted [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`] consts by
/// construction (there is no wire/diagnostic axis split on this enum —
/// both halves of the round-trip route through the same three
/// `pub const &str` values), so the owned-[`String`] forward projection
/// this impl exposes composes directly with the paired trait-idiomatic
/// reverse [`TryFrom<&str>`] axis on the owned-[`String`]'s
/// [`String::as_str`] borrow — no intermediate wire-vocab hop like the
/// peer [`crate::CaixaKind`] axis pair requires.
///
/// The remaining nine closed-set typed enums on the caixa substrate
/// surface (`WitShape`, `RateLimitUnit`, `PathShapeViolation`,
/// `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
/// `FerriteRuntime`) are the future targets of this campaign — each
/// carries the same paired [`AsRef<str>`] / [`std::fmt::Display`] /
/// [`From<Self> for &'static str`] / [`From<&Self> for &'static str`]
/// quadruple that this owned-[`String`] axis extends onto.
///
/// Pinned load-bearing by
/// [`tests::placement_strategy_from_into_owned_string_routes_through_as_str_accessor`]
/// (byte-parity pin against [`PlacementStrategy::as_str`] across the
/// three-arm [`PlacementStrategy::ALL`] emit-set plus a blanket
/// `.into::<String>()` shape witness) and
/// [`tests::placement_strategy_from_into_owned_string_and_static_str_agree_on_every_arm`]
/// (cross-axis partition against the sibling owned-`&'static str` axis
/// and the [`ToString::to_string`] surface, a
/// `.iter().copied().map(String::from)` pipe witness over
/// [`PlacementStrategy::ALL`], plus a direct `Self → String → Self`
/// round-trip via [`TryFrom<&str>`] on the owned-[`String`]'s
/// [`String::as_str`] borrow — composes directly without the wire-vocab
/// intermediate hop the peer [`crate::CaixaKind`] axis pair requires).
impl From<PlacementStrategy> for String {
fn from(strategy: PlacementStrategy) -> String {
strategy.as_str().to_owned()
}
}
/// Trait-idiomatic *borrowed-input, owned-`String` output* forward
/// projection on the M3 mesh-primitive `:placement :estrategia`
/// distribution-strategy [`PlacementStrategy`] closed-set typed enum —
/// the fourth (and closing) corner of the
/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
/// projection family on this first M3-mesh-primitive-defining slot enum.
/// Routes byte-for-byte through the substrate-primitive
/// [`PlacementStrategy::as_str`] `pub const fn` accessor (via
/// [`str::to_owned`]) so every consumer that holds a borrowed
/// [`&PlacementStrategy`] and needs an owned [`String`] — a future
/// `serde_json::Value::String(String::from(&strategy))` structured-
/// payload composer over a borrowed field, a future `Iterator::map` over
/// `&[PlacementStrategy]` that projects to owned keys through
/// `.iter().map(String::from)` (whose iterator yields
/// `&PlacementStrategy`, not `PlacementStrategy`, so the owned-input
/// [`From<PlacementStrategy> for String`] axis alone forces every call
/// site through an explicit `.copied()` / spurious [`Copy`] deref
/// restatement rather than the direct trait-idiomatic projection), a
/// future `HashMap::<String, PlacementStrategy>::from_iter` that keys off
/// a borrowed-iteration axis where dereferencing the strategy would
/// force an unnecessary [`Copy`] at every step, the future M4
/// `mesh.pleme.io/v1alpha1/Aplicacao` CR admission-webhook rejection
/// body composer that names the accepted-`:placement :estrategia`
/// enumeration through an iterated
/// `PlacementStrategy::ALL.iter().map(String::from).collect()` pipe
/// rather than a per-arm cascade, the future caixa-mesh renderer
/// `placement.estrategia`-column diagnostic composer whose borrowed-
/// iteration axis over declared strategies projects to owned keys by
/// construction — reaches the same three-arm lifted
/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] byte-strings the
/// paired [`std::fmt::Display`], [`AsRef<str>`],
/// [`PlacementStrategy::as_str`], and the three other trait-idiomatic
/// forward-projection impls
/// ([`From<PlacementStrategy> for &'static str`],
/// [`From<&PlacementStrategy> for &'static str`],
/// [`From<PlacementStrategy> for String`]) already return.
///
/// Sixth peer on the substrate-wide trait-idiomatic *borrowed-input,
/// owned-`String` output* forward-projection family opened on
/// [`crate::supervisor::RestartStrategy`] (579385f), closed on the M2
/// OTP-shape sibling axis pair by
/// [`crate::supervisor::RestartPolicy`] (8465740), extended onto the
/// two-list dep-graph peer by [`crate::dep::DepList`] (e0cb617), onto
/// the top-level [`crate::CaixaKind`] peer by (e76436d), and onto the
/// dialect-classification peer by [`crate::CaixaDialeto`] (d3c0d1d) —
/// extends the `{Self, &Self} × {&'static str, String}` 2×2 projection
/// corner off the caixa-surface enum axes onto the M3 mesh-slot family
/// the caixa-mesh renderer keys off end-to-end. First
/// M3-mesh-primitive-defining closed-set typed enum to reach the
/// 2×2-completion corner — first-mover on the M3 slot-enum triple,
/// ahead of the sibling [`WitShape`] `:contratos :wit` census-label axis
/// and [`RateLimitUnit`] `:politicas :rate-limit` canonical-suffix axis
/// whose 2×2-completion corners remain future targets of this campaign.
/// Rust's standard library does not carry a blanket
/// `impl<T: AsRef<str>> From<&T> for String` (nor an
/// `impl<T: fmt::Display> From<&T> for String`), so every closed-set
/// typed enum that carries the paired `AsRef<str>` / `Display` /
/// `From<Self> for &'static str` / `From<&Self> for &'static str` /
/// `From<Self> for String` quintuple but not the borrowed-input
/// owned-[`String`] axis forces every borrowed-input owned-string call
/// site through a `strategy.as_str().to_owned()` /
/// `String::from(*strategy)` (with a spurious [`Copy`]) /
/// `strategy.to_string()` (through [`std::fmt::Display`]) detour whose
/// type bounds have no compile-time link to the substrate primitive.
///
/// Same three-path convergence discipline as the paired owned-input
/// impl (this borrowed-input axis, the paired owned-input
/// [`From<PlacementStrategy> for String`], and
/// [`PlacementStrategy::as_str`] all route through the same lifted
/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`] const), so a future
/// variant rename or per-arm serde-attribute drift reaches every one
/// of the paired forward-projection paths through exactly one
/// caixa-core edit.
///
/// Same as the peer [`crate::supervisor::RestartStrategy`] /
/// [`crate::supervisor::RestartPolicy`] / [`crate::dep::DepList`] /
/// [`crate::CaixaDialeto`] borrowed-input owned-[`String`] axis pairs
/// (whose forward emit and reverse parse share one vocabulary by
/// construction — `PascalCase` on the M2 OTP-shape peers and on the
/// [`CaixaDialeto`] peer, the lifted
/// [`crate::render::DEP_AUTHOR_KEY_DEPS`] /
/// [`crate::render::DEP_AUTHOR_KEY_DEPS_DEV`] consts on the two-list
/// dep-graph peer) and unlike the peer [`crate::CaixaKind`] pair
/// (whose forward emit lands on the lowercase Portuguese diagnostic
/// vocabulary while the reverse parse lands on the `PascalCase` wire
/// vocabulary, forcing the round-trip through an intermediate
/// [`crate::CaixaKind::wire_name`] hop), [`PlacementStrategy`]'s
/// [`PlacementStrategy::as_str`] emit and
/// [`PlacementStrategy::from_wire`] parse resolve through the same
/// three lifted [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`] consts by
/// construction (there is no wire/diagnostic axis split on this M3
/// slot enum — both halves of the round-trip route through the same
/// three `pub const &str` values), so the borrowed-input
/// owned-[`String`] projection this impl exposes composes directly
/// with the paired trait-idiomatic reverse [`TryFrom<&str>`] axis on
/// the owned-[`String`]'s [`String::as_str`] borrow — no intermediate
/// wire-vocab hop required.
///
/// The remaining eight closed-set typed enums on the caixa substrate
/// surface (`WitShape`, `RateLimitUnit`, `PathShapeViolation`,
/// `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
/// `FerriteRuntime`) are the future targets of this 2×2-completion
/// campaign — each carries the same paired quintuple that this
/// borrowed-input owned-[`String`] axis extends onto.
///
/// Pinned load-bearing by
/// [`tests::placement_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
/// (byte-parity pin against [`PlacementStrategy::as_str`] across the
/// three-arm emit-set through the borrowed-input surface) and
/// [`tests::placement_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
/// (cross-axis partition pin against the paired owned-input owned-
/// [`String`] [`From<PlacementStrategy> for String`] impl, the paired
/// borrowed-input owned-[`&'static str`]
/// [`From<&PlacementStrategy> for &'static str`] impl, the paired
/// owned-input owned-[`&'static str`]
/// [`From<PlacementStrategy> for &'static str`] impl, and the sibling
/// [`ToString::to_string`] surface routed through
/// [`std::fmt::Display`], plus a `.iter().map(String::from)` pipe
/// witness over [`PlacementStrategy::ALL`] (whose iterator yields
/// `&PlacementStrategy` by construction, so the borrowed-input
/// owned-[`String`] axis is what routes the pipe through the
/// substrate-primitive [`PlacementStrategy::as_str`] accessor without
/// a spurious [`Copy`] deref), plus a direct round-trip witness through
/// [`TryFrom<&str>`] on the owned-[`String`]'s [`String::as_str`]
/// borrow that closes the two-way `&Self → String → Self` round-trip
/// on the trait-idiomatic borrowed-input owned-[`String`] forward +
/// reverse axis pair — no intermediate wire-vocab hop like the peer
/// [`crate::CaixaKind`] axis pair requires).
impl From<&PlacementStrategy> for String {
fn from(strategy: &PlacementStrategy) -> String {
strategy.as_str().to_owned()
}
}
/// Trait-idiomatic *forward* projection on the M3 mesh-primitive
/// `:placement :estrategia` distribution-strategy [`PlacementStrategy`]
/// closed-set typed enum from an *owned* input onto the
/// [`std::borrow::Cow<'static, str>`] axis — routes byte-for-byte
/// through the substrate-primitive [`PlacementStrategy::as_str`]
/// `pub const fn` accessor (via [`std::borrow::Cow::Borrowed`]) so
/// every consumer that binds a [`PlacementStrategy`] through the
/// standard-library `.into()` / [`From<Self> for
/// std::borrow::Cow<'static, str>`] (equivalently
/// [`Into<std::borrow::Cow<'static, str>>`]) axis reaches the same
/// three-arm lifted
/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] byte-string the
/// paired [`From<PlacementStrategy> for &'static str`],
/// [`From<&PlacementStrategy> for &'static str`],
/// [`From<PlacementStrategy> for String`], and
/// [`From<&PlacementStrategy> for String`] 2×2 trait-idiomatic
/// forward-projection corners, the sibling [`std::fmt::Display`],
/// [`AsRef<str>`], and [`PlacementStrategy::as_str`] surfaces already
/// return, rather than an open-coded per-call-site
/// `std::borrow::Cow::Borrowed(strategy.as_str())` /
/// `std::borrow::Cow::Owned(strategy.to_string())` composition whose
/// type bounds have no compile-time link back to the substrate
/// primitive.
///
/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
/// [`std::borrow::Cow::Owned`] — the substrate-primitive
/// [`PlacementStrategy::as_str`] accessor's return carries the
/// `&'static str` lifetime by construction (each `match` arm resolves
/// to one of the three lifted
/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`] `pub const &str`
/// byte-strings with static lifetime), so the zero-alloc borrowed arm
/// is the type-correct projection with no runtime allocation. The
/// paired [`std::borrow::Cow::Owned`] arm stays reachable at the call
/// site through the existing [`From<PlacementStrategy> for String`]
/// axis composed with [`std::borrow::Cow::from`] on the resulting
/// owned [`String`] — a caller who chose to mutate the projection
/// lands on the owned arm by their own composition, not by the
/// substrate-primitive projection silently allocating on their
/// behalf.
///
/// Rust's standard library carries no blanket `impl<T: AsRef<str>>
/// From<T> for Cow<'static, str>` (nor an `impl<T: fmt::Display>
/// From<T> for Cow<'static, str>`), so the paired sibling
/// [`From<PlacementStrategy> for &'static str`],
/// [`From<PlacementStrategy> for String`], [`AsRef<str>`], and
/// [`std::fmt::Display`] surfaces do not implicitly extend to a
/// [`Cow<'static, str>`]-bound call site — every such site is forced
/// through a `Cow::Borrowed(strategy.as_str())` /
/// `Cow::Owned(strategy.to_string())` open-code whose type bounds
/// have no compile-time link back to the substrate primitive until
/// this lift.
///
/// Second M3-mesh-primitive-defining peer on the substrate-wide
/// trait-idiomatic [`std::borrow::Cow<'static, str>`] forward-
/// projection campaign — extends the axis off the M3 mesh-shape tier
/// opened one commit prior by the paired [`WitShape`] `:contratos
/// :wit` census-label first-mover (8634dec owned-input + 25690ef
/// borrowed-input) onto the second M3-mesh-primitive-defining slot
/// enum. The [`CaixaKind`](crate::CaixaKind) top-level first-mover
/// (99c1735 owned-input + d45c409 borrowed-input) opened the axis
/// on the structurally most fundamental closed-set fieldless typed
/// enum; the paired M2 OTP-shape
/// [`crate::supervisor::RestartStrategy`] (7dd28b3 + 9b3e4b3) and
/// [`crate::supervisor::RestartPolicy`] (0612398 + ee577fd) closed
/// the M2 OTP-shape tier. The remaining M3-mesh-primitive-defining
/// peer ([`RateLimitUnit`]) and the outside-M3 substrate-wide peers
/// ([`crate::dep::DepList`], [`crate::CaixaDialeto`],
/// [`crate::render::PathShapeViolation`], and the outside-`caixa-core`
/// peers `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`,
/// `Semantic`, `FerriteRuntime`) are the remaining future targets of
/// this campaign.
///
/// Same three-path convergence discipline as the paired sibling
/// [`From<PlacementStrategy> for &'static str`] /
/// [`From<PlacementStrategy> for String`] / [`std::fmt::Display`] /
/// [`AsRef<str>`] surfaces (this [`Cow<'static, str>`] axis, the
/// paired sibling surfaces, and [`PlacementStrategy::as_str`] all
/// route through the same lifted
/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`] const), so a future
/// variant rename or per-arm serde-attribute drift reaches every
/// forward-projection path through exactly one caixa-core edit.
///
/// Pinned load-bearing by
/// [`tests::placement_strategy_from_into_static_cow_str_routes_through_as_str_accessor`]
/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
/// against [`PlacementStrategy::as_str`] across the three-arm
/// [`PlacementStrategy::ALL`]) and
/// [`tests::placement_strategy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
/// (cross-axis partition pin against the paired
/// [`From<PlacementStrategy> for &'static str`],
/// [`From<PlacementStrategy> for String`], and
/// [`ToString`]-through-[`std::fmt::Display`] axes, plus a
/// `.iter().copied().map(Cow::from)` pipe witness over
/// [`PlacementStrategy::ALL`] that materializes the three-arm
/// accept-set through the [`Cow<'static, str>`] axis alone and pins
/// the zero-alloc discipline on every element).
impl From<PlacementStrategy> for std::borrow::Cow<'static, str> {
fn from(strategy: PlacementStrategy) -> std::borrow::Cow<'static, str> {
std::borrow::Cow::Borrowed(strategy.as_str())
}
}
/// Trait-idiomatic *borrowed-input, [`std::borrow::Cow<'static, str>`]
/// output* forward projection on the M3-mesh-primitive-defining
/// `:placement :estrategia` distribution-strategy [`PlacementStrategy`]
/// closed-set typed enum — the borrowed-input companion to the paired
/// owned-input [`From<PlacementStrategy> for std::borrow::Cow<'static,
/// str>`] impl immediately above (eee504d). Routes byte-for-byte
/// through the same substrate-primitive [`PlacementStrategy::as_str`]
/// `pub const fn` accessor (via [`std::borrow::Cow::Borrowed`]) so
/// every consumer that holds a `&PlacementStrategy` and needs a
/// [`std::borrow::Cow<'static, str>`] — a
/// `PlacementStrategy::ALL.iter().map(std::borrow::Cow::from).collect::<Vec<_>>()`
/// per-arm accept-set materializer whose iterator over
/// `&'static [PlacementStrategy]` yields `&PlacementStrategy` (not
/// `PlacementStrategy`, so the paired owned-input
/// [`From<PlacementStrategy> for std::borrow::Cow<'static, str>`] axis
/// alone forces every call site through an explicit `.copied()` /
/// dereference / [`Copy`]-bound restatement rather than the direct
/// trait-idiomatic projection), a future generic
/// `<T: for<'a> Into<std::borrow::Cow<'static, str>>>`-bound emitter
/// on a per-`:placement :estrategia` diagnostic column that walks the
/// `iter().map(Into::into)` shape verbatim, the future M4
/// `mesh.pleme.io/v1alpha1/Aplicacao` CR admission-webhook rejection
/// body that composes the accepted-`:placement :estrategia`
/// enumeration from an iterated
/// `PlacementStrategy::ALL.iter().map(|s| s.into())` pipe rather than
/// a per-arm `match s { … }` cascade — reaches the same three-arm
/// lifted [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] byte-string the
/// paired [`std::fmt::Display`], [`AsRef<str>`],
/// [`PlacementStrategy::as_str`], the four
/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
/// forward-projection corners, and the paired owned-input
/// [`From<PlacementStrategy> for std::borrow::Cow<'static, str>`] impl
/// already return.
///
/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
/// [`std::borrow::Cow::Owned`] — the substrate-primitive
/// [`PlacementStrategy::as_str`] accessor's return carries the
/// `&'static str` lifetime by construction (each `match` arm resolves
/// to one of the three lifted
/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`] `pub const &str`
/// byte-strings with static lifetime), so the zero-alloc borrowed arm
/// is the type-correct projection with no runtime allocation on the
/// borrowed-input surface just as on the paired owned-input surface.
///
/// Closes the `{Self, &Self}` input-shape corner on the M3-mesh-shape
/// `:placement :estrategia` distribution-strategy
/// [`std::borrow::Cow<'static, str>`] axis opened one commit prior
/// (eee504d) on the paired owned-input [`From<PlacementStrategy> for
/// std::borrow::Cow<'static, str>`] impl — second M3-mesh-primitive-
/// defining peer on the axis, one commit after the sibling
/// [`WitShape`] `:contratos :wit` census-label first-mover (8634dec
/// owned-input + 25690ef borrowed-input) closed the first
/// M3-mesh-primitive-defining slot enum, exactly as d45c409 closed
/// the axis on the top-level [`crate::CaixaKind`] one commit after
/// the owning half (99c1735) landed and as 9b3e4b3 / ee577fd closed
/// it on the M2 OTP-shape [`crate::supervisor::RestartStrategy`] /
/// [`crate::supervisor::RestartPolicy`] sibling peers one commit
/// after their owning halves (7dd28b3 / 0612398) landed. Rust's
/// standard library does not carry a blanket
/// `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor an
/// `impl<T: fmt::Display> From<&T> for Cow<'static, str>`), so every
/// closed-set fieldless typed enum peer on the substrate that carries
/// the paired owned-input [`Cow<'static, str>`] axis but not the
/// borrowed-input axis forces every borrowed-input
/// [`Cow<'static, str>`]-parameterized call site through a spurious
/// [`Copy`] deref (`std::borrow::Cow::from(*strategy)`) or a
/// `std::borrow::Cow::Borrowed(strategy.as_str())` open-code whose
/// type bounds have no compile-time link to the substrate primitive.
///
/// The remaining M3-mesh-primitive-defining peer ([`RateLimitUnit`])
/// and the outside-M3 substrate-wide peers ([`crate::dep::DepList`],
/// [`crate::CaixaDialeto`], [`crate::render::PathShapeViolation`],
/// and the outside-`caixa-core` peers `InvariantKind`, `ArchVerdict`,
/// `Severity`, `FixSafety`, `Semantic`, `FerriteRuntime`) are the
/// remaining future targets of the campaign; closing this
/// borrowed-input corner on [`PlacementStrategy`] leaves
/// [`RateLimitUnit`] as the last un-lifted M3-mesh-primitive-defining
/// slot enum on the [`Cow<'static, str>`] axis.
///
/// Pinned load-bearing by
/// [`tests::placement_strategy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor`]
/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
/// against [`PlacementStrategy::as_str`] across the three-arm
/// [`PlacementStrategy::ALL`] through the borrowed-input surface) and
/// [`tests::placement_strategy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
/// (cross-axis partition pin against the paired owned-input
/// [`From<PlacementStrategy> for std::borrow::Cow<'static, str>`], the
/// paired borrowed-input owned-`&'static str`
/// [`From<&PlacementStrategy> for &'static str`], and the paired
/// borrowed-input owned-`String` [`From<&PlacementStrategy> for
/// String`] impls, plus a `.iter().map(std::borrow::Cow::from)` pipe
/// witness over [`PlacementStrategy::ALL`] — whose iterator yields
/// `&PlacementStrategy` by construction, so the borrowed-input
/// [`Cow<'static, str>`] axis is what routes the pipe through the
/// substrate-primitive [`PlacementStrategy::as_str`] accessor with the
/// zero-alloc [`Cow::Borrowed`] arm by construction and without a
/// spurious [`Copy`] deref).
impl From<&PlacementStrategy> for std::borrow::Cow<'static, str> {
fn from(strategy: &PlacementStrategy) -> std::borrow::Cow<'static, str> {
std::borrow::Cow::Borrowed(strategy.as_str())
}
}
/// Where the Aplicacao runs.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct Placement {
/// Distribution strategy.
#[serde(default)]
pub estrategia: PlacementStrategy,
/// Named clusters that host this Aplicacao. Required for
/// `Replicated` and `SingleNode`; for `Sharded` declares the
/// shard pool.
#[serde(default)]
pub clusters: Vec<String>,
/// Optional hint to the placement engine: `"data-locality"`,
/// `"low-latency"`, etc. Drives M3 Adaptive compression weights.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub affinity: Option<String>,
/// Sharding key — required when `:estrategia Sharded`. M3 deliverable.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub shard_key: Option<String>,
}
impl Placement {
/// Substrate-canonical per-`:placement` Akka-cluster-sharding
/// `:shard-key` extractor-expression scalar accessor every consumer
/// of the Aplicacao's hash-keyed distribution routing keys off —
/// returns the author-declared `:placement :shard-key` byte-string
/// verbatim as an `Option<&str>`, borrowed from the typed slot's
/// own `Option<String>` storage; `None` when the slot is absent
/// (the canonical shape under `:estrategia Replicated` /
/// `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
/// enforced `shard_key.is_some() == matches!(estrategia, Sharded)`
/// partition — `validate` refuses any `Placement` past this call
/// that lands `Some` on a non-`Sharded` strategy or `None` on
/// `Sharded`).
///
/// The `:placement :shard-key` slot carries the Akka-style
/// cluster-sharding entity-id extractor expression
/// (MESH-COMPOSITION §II.4) — validated by
/// [`validate_placement_shard_key`] to be a non-empty printable-
/// ASCII single-token reference (`tenantId`, `$tenantId`,
/// `metadata.tenantId`, `${tenant}` — the canonical shapes the
/// future M4 Akka-style cluster-sharding reconciler hashes without
/// re-validating at the runtime layer), and every downstream
/// consumer that reads the key keys off this scalar (the
/// [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape gate,
/// the [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
/// declared-but-inert refusal diagnostic, the caixa-mesh
/// per-Aplicacao `placement.shardKey` emit path the substrate
/// operator's per-entity hash-routing reader consumes, the future
/// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
/// per-shard-key resolver).
///
/// Prior to this lift the `.shard_key` field was accessed inline at
/// two caixa-core sites — the [`AplicacaoSpec::validate_placement`]
/// `Sharded` arm's `match &self.placement.shard_key { None => …,
/// Some(k) if k.is_empty() => …, Some(k) => … }` cascade and the
/// non-`Sharded` arm's `if let Some(k) = &self.placement.shard_key
/// { … ShardKeyOnNonSharded { shard_key: k.clone() } … }` refusal
/// — two open-coded field-accesses that expressed no compile-time
/// link back to the typed slot. A future extension of the
/// `:placement :shard-key` axis to a richer author surface — a
/// per-cluster override the operator pins through a future
/// `:placement :shard-key-overrides` slot the MESH-COMPOSITION
/// §II.4 roadmap acknowledges, a per-tenant extractor-expression
/// alias table the M4 CR materializer resolves per-CR, a
/// per-Aplicacao dynamic `:shard-key` derivation the future
/// adaptive placement engine computes from `:affinity` weights —
/// would have had to be threaded through both open-coded copies in
/// lockstep or the `Sharded`-arm shape gate and the non-`Sharded`-
/// arm refusal would silently disagree on which extractor
/// expression a given Placement resolves to. Lifting the resolution
/// rule to a typed method on the substrate primitive means every
/// downstream consumer of the Aplicacao's per-`:placement`
/// hash-key surface reaches for exactly one typed dispatch — the
/// resolver's accept-set migrates as a unit on any future axis
/// addition.
///
/// Peer of the sibling per-`:contratos` [`WitContract::source`] /
/// [`WitContract::destination`] / [`WitContract::world_ref`]
/// (7f0fd43, 0804823) scalar accessors, per-`:membros`
/// [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf,
/// a40b0e3), and per-`:entrada` [`Entrada::destination`] /
/// [`Entrada::hostname`] (6db982c, 11f3dfe) accessors — same "one
/// typed dispatch on the substrate primitive, thin projections at
/// each consumer" discipline extended onto the per-`:placement`
/// Akka-cluster-sharding-key `Option<String>` optional-scalar axis.
/// First `Option<&str>`-return accessor on the M3 mesh-slot family
/// — opens the "optional per-slot scalar" projection pattern the
/// sibling per-`:placement` `:affinity`, per-`:politicas`
/// `:rate-limit` future lifts fold on. Named `shard_key()` to
/// match the storage field's name; the accessor's identity name
/// maps onto the canonical MESH-COMPOSITION §II.4 vocabulary the
/// slot's docstring already carries.
#[must_use]
pub const fn shard_key(&self) -> Option<&str> {
match &self.shard_key {
Some(s) => Some(s.as_str()),
None => None,
}
}
/// Substrate-canonical per-`:placement` `:affinity` M3-Adaptive-
/// compression-hint scalar accessor every weighting-consumer of the
/// Aplicacao's per-hint routing surface keys off — returns the
/// author-declared `:placement :affinity` byte-string verbatim as
/// an `Option<&str>`, borrowed from the typed slot's own
/// `Option<String>` storage; `None` when the slot is absent (the
/// canonical shape of an Aplicacao that leaves the compression
/// weighting up to the placement engine's cluster-default arm — no
/// author-authored `data-locality` / `low-latency` / etc. hint
/// biases the routing).
///
/// The `:placement :affinity` slot carries the M3 Adaptive-
/// compression-weight bias hint (MESH-COMPOSITION §II.4) — validated
/// by [`validate_placement_affinity`] to be a DNS-1123 label
/// (`[a-z0-9]([-a-z0-9]*[a-z0-9])?`, 1..=63 bytes — the
/// K8s-conformant label-selector shape every apiserver-side pod-
/// affinity / node-affinity materializer already gates on
/// admission), and every downstream consumer that reads the hint
/// keys off this scalar (the [`AplicacaoSpec::validate_placement`]
/// per-hint value-shape gate, the caixa-mesh per-Aplicacao
/// `placement.affinity` overlay emit path the substrate operator's
/// per-hint weighting-consumer reads, the future M4
/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-hint
/// pod-affinity / node-affinity selector resolver).
///
/// Prior to this lift the `.affinity` field was accessed inline at
/// the sole caixa-core site — the
/// [`AplicacaoSpec::validate_placement`] per-hint value-shape gate's
/// `if let Some(a) = &self.placement.affinity { …
/// validate_placement_affinity(a)? … }` cascade — one open-coded
/// field-access that expressed no compile-time link back to the
/// typed slot. A future extension of the `:placement :affinity`
/// axis to a richer author surface — a per-cluster override the
/// operator pins through a future `:placement :affinity-overrides`
/// slot the MESH-COMPOSITION §II.4 roadmap acknowledges, a per-
/// tenant hint alias table the M4 CR materializer resolves per-CR,
/// a per-Aplicacao dynamic `:affinity` derivation the future
/// adaptive placement engine computes from `:clusters` topology —
/// would have had to be threaded through the open-coded copy in
/// lockstep with any future caixa-mesh / caixa-flux / M4 CR
/// materializer reader that landed on the axis, or the per-hint
/// value-shape gate and its downstream weighting consumers would
/// silently disagree on which hint a given Placement resolves to.
/// Lifting the resolution rule to a typed method on the substrate
/// primitive means every downstream consumer of the Aplicacao's
/// per-`:placement` compression-hint surface reaches for exactly
/// one typed dispatch — the resolver's accept-set migrates as a
/// unit on any future axis addition.
///
/// Peer of the sibling per-`:placement` [`Placement::shard_key`]
/// (7cd2a28) `Option<&str>` accessor on the sibling per-`:placement`
/// optional-scalar axis — same "one typed dispatch on the substrate
/// primitive, thin projections at each consumer" discipline extended
/// onto the per-`:placement` M3-Adaptive-compression-hint
/// `Option<String>` optional-scalar axis. Second `Option<&str>`-
/// return accessor on the M3 mesh-slot family; closes the last
/// un-lifted per-`:placement` `Option<String>` axis. Named
/// `affinity()` to match the storage field's name; the accessor's
/// identity name maps onto the canonical MESH-COMPOSITION §II.4
/// vocabulary the slot's docstring already carries.
#[must_use]
pub const fn affinity(&self) -> Option<&str> {
match &self.affinity {
Some(s) => Some(s.as_str()),
None => None,
}
}
/// Substrate-canonical per-`:placement` `:estrategia` distribution-
/// strategy scalar accessor every consumer that dispatches on the
/// Aplicacao's per-cluster distribution shape keys off — returns the
/// author-declared `:placement :estrategia` variant verbatim as a
/// [`PlacementStrategy`], `Copy`-projected from the typed slot's own
/// `PlacementStrategy` storage.
///
/// The `:placement :estrategia` slot carries the closed-set
/// distribution-strategy discriminator (`SingleNode` — Erlang/OTP
/// distributed-app takeover semantics per MESH-COMPOSITION §II.1;
/// `Replicated` — active-active across every named cluster; `Sharded`
/// — Akka-style hash-keyed entity distribution across the cluster pool
/// per §II.4) that every downstream consumer of the Aplicacao's
/// per-cluster fan-out shape keys off. Validated by
/// [`AplicacaoSpec::validate_placement`] to be paired coherently with
/// the sibling `:shard-key` axis (`shard_key.is_some() ==
/// matches!(estrategia, Sharded)` — the cross-slot partition the
/// [`Placement::shard_key`] accessor's docstring pins), and every
/// downstream consumer that reads the strategy keys off this scalar
/// (the [`AplicacaoSpec::validate_placement`]
/// [`AplicacaoError::PlacementWithoutClusters`] error carrier's
/// `estrategia:` field, the [`AplicacaoSpec::validate_placement`]
/// `Sharded ↔ non-Sharded` partition-dispatch `match` arm, the
/// [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
/// declared-but-inert refusal's
/// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
/// `estrategia:` field, the `feira app graph` per-Aplicacao strategy
/// print line, the caixa-mesh per-Aplicacao `placement.estrategia`
/// emit path the substrate operator's per-strategy fan-out reader
/// consumes, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
/// materializer's per-strategy admission-webhook resolver).
///
/// Prior to this lift the `.estrategia` field was accessed inline at
/// four sites — the [`AplicacaoSpec::validate_placement`]
/// [`AplicacaoError::PlacementWithoutClusters`] error carrier at
/// `estrategia: self.placement.estrategia`, the same method's
/// `Sharded ↔ non-Sharded` `match self.placement.estrategia { … }`
/// partition dispatch, the non-`Sharded`-arm
/// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier at
/// `estrategia: self.placement.estrategia`, and the `feira app graph`
/// per-Aplicacao strategy print line at
/// `println!("… {} …", spec.placement.estrategia, …)`
/// (caixa-feira/src/cmd/app.rs) — four open-coded field-accesses that
/// expressed no compile-time link back to the typed slot. A future
/// extension of the `:placement :estrategia` axis to a richer author
/// surface (a per-cluster override the operator pins through a future
/// `:placement :estrategia-overrides` slot the MESH-COMPOSITION §II.4
/// roadmap acknowledges, a per-tenant strategy-alias table the M4 CR
/// materializer resolves per-CR, a per-Aplicacao dynamic strategy
/// derivation the future adaptive placement engine computes from
/// `:affinity` + `:clusters` topology) would have had to be threaded
/// through every open-coded copy in lockstep — one consumer reading
/// the raw variant while a peer read the operator-resolved variant
/// would silently split the `PlacementWithoutClusters` /
/// `ShardKeyOnNonSharded` diagnostic quotes from the actual
/// partition-dispatch input, a two-consumer split at the validator
/// far from the source `caixa.lisp` with no field naming the
/// strategy-drift root cause. Lifting the resolution rule to a typed
/// method on the substrate primitive means every downstream consumer
/// of the Aplicacao's per-`:placement` distribution-strategy surface
/// reaches for exactly one typed dispatch — the resolver's accept-set
/// migrates as a unit on any future axis addition.
///
/// Peer of the sibling per-`:entrada` [`Entrada::port`] (9f9becd)
/// `Copy`-return `u16` scalar accessor on the M3 mesh-slot family —
/// same "one typed dispatch on the substrate primitive, thin
/// projections at each consumer" discipline extended onto the
/// per-`:placement` distribution-strategy `Copy`-composite-enum
/// scalar axis. Second `Copy`-return accessor on the M3 mesh-slot
/// family; first `Copy`-return accessor on the M3 mesh-slot
/// `Placement` type — companion to the sibling per-`:placement`
/// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
/// (74ec2d3) `Option<&str>` accessors on the sibling `Option<String>`
/// optional-scalar axes, closing the last unlifted per-`:placement`
/// scalar-value axis (the closed-set `PlacementStrategy`
/// distribution-strategy discriminator) so every downstream
/// per-`:placement` reader now routes through a typed dispatch on
/// the substrate primitive. Named `estrategia()` to match the storage
/// field's name; the accessor's identity name maps onto the
/// canonical MESH-COMPOSITION §II.4 vocabulary the slot's docstring
/// already carries. Declared `pub const fn` (matching the peer M3
/// mesh-slot `Copy`-return accessor family — [`MeshPolicy::timeout`]
/// / [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
/// [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`] on
/// the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`] /
/// [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
/// [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
/// [`RateLimit`] — every one a `pub const fn`) so every future
/// substrate-side `const`-context consumer of the resolved
/// distribution-strategy variant (a `const _: () = assert!(…)`
/// module-scope invariant pin on a per-fixture typed [`Placement`],
/// a future M4 admission-webhook `const fn` resolver over a typed
/// [`Placement`], any `const fn` composer that fans on the strategy
/// at compile time) reaches through the same typed dispatch on the
/// substrate primitive at const-eval time as at runtime. Pinned by
/// [`placement_estrategia_accessor_is_const_fn`] which witnesses the
/// const-eval posture at module scope via `const _:() = …` items so
/// any future accidental downgrade to non-`const` trips at caixa-core
/// build time.
#[must_use]
pub const fn estrategia(&self) -> PlacementStrategy {
self.estrategia
}
/// Substrate-canonical per-`:placement` `:clusters` MESH-COMPOSITION
/// per-cluster distribution-target slice accessor every consumer that
/// walks the Aplicacao's declared cluster-pool keys off — returns the
/// author-declared `:placement :clusters` `Vec<String>` verbatim as a
/// `&[String]` slice-view, borrowed from the typed slot's own
/// `Vec<String>` storage (a zero-copy slice-view over the same
/// backing buffer the `Serialize`/`Deserialize` derives round-trip
/// through). Non-optional: the empty slice is the load-bearing
/// pre-validation sentinel every downstream consumer of the paired
/// [`AplicacaoError::PlacementWithoutClusters`] refusal cascade keys
/// off — every strategy in the closed
/// [`PlacementStrategy::{SingleNode, Replicated, Sharded}`] accept-set
/// requires a non-empty list (`SingleNode` / `Replicated` use the
/// list as hosting / takeover candidates per Erlang/OTP distributed-
/// app convention, MESH-COMPOSITION §II.1; `Sharded` uses it as the
/// shard pool per Akka cluster-sharding convention, §II.4), so the
/// `.is_empty()` probe is the shared pre-condition every
/// [`AplicacaoSpec::validate_placement`] arm heads on.
///
/// The `:placement :clusters` slot carries the K8s-conformant DNS-
/// 1123-label per-cluster distribution-target list — the same
/// set-not-multiset shape the sibling `:membros :caixa` /
/// `:children :caixa` axes carry (`validate_placement`'s per-entry
/// [`validate_placement_cluster`] + [`insert_first_seen`] fan-out
/// pins the shape). Every downstream consumer that fans on the list
/// keys off this slice (the [`AplicacaoSpec::validate_placement`]
/// pre-flight `.is_empty()` probe that trips
/// [`AplicacaoError::PlacementWithoutClusters`], the same method's
/// per-cluster value-shape + duplicate-detection fan-out loop, the
/// caixa-mesh per-Aplicacao `placement.clusters` overlay emit path
/// that materializes the list verbatim onto every
/// programs.yaml entry the substrate operator's per-cluster
/// `placement.clusters | contains .Values.cluster` filter reads,
/// the `feira app graph` per-Aplicacao cluster print line, the
/// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
/// per-cluster admission-webhook fan-out, the future M5 adaptive-
/// placement engine's cluster-topology reader).
///
/// Prior to this lift the `.clusters` `Vec<String>` was accessed
/// inline at three production sites — the
/// [`AplicacaoSpec::validate_placement`] pre-flight
/// `self.placement.clusters.is_empty()` refusal probe, the same
/// method's per-cluster validate loop's
/// `for c in &self.placement.clusters` traversal head, and the
/// `feira app graph` per-Aplicacao print line's
/// `spec.placement.clusters` `{:?}` formatter argument
/// (caixa-feira/src/cmd/app.rs) — three open-coded field-accesses
/// that expressed no compile-time link back to the typed slot. A
/// future extension of the `:placement :clusters` axis to a richer
/// author surface (a per-tenant cluster-pool overlay the operator
/// pins through a future `:placement :clusters-overrides` slot the
/// MESH-COMPOSITION §V cross-cluster-federation roadmap
/// acknowledges, a per-Aplicacao dynamic cluster-pool derivation
/// the future M5 adaptive-placement engine computes from
/// `:affinity` weights + live cluster-topology probes, a promotion
/// of the plain `Vec<String>` to a richer `{static, dynamic}`
/// partition once the substrate operator's cluster-membership
/// reconciler comes into typed scope) would have had to be threaded
/// through all three open-coded copies in lockstep or one consumer
/// would silently disagree with the peers on which cluster-pool a
/// given Aplicacao resolves to — the pre-flight `.is_empty()` probe
/// reading the raw slot while the peer per-cluster validate loop
/// read an operator-resolved slot would silently split the paired
/// `PlacementWithoutClusters` / `PlacementClusterInvalid` /
/// `PlacementClusterDuplicate` refusal cascade's actual traversal
/// input from the pre-flight input, a three-consumer split at the
/// validator and formatter far from the source `caixa.lisp` with
/// no field naming the cluster-pool-drift root cause. Lifting the
/// resolution rule to a typed method on the substrate primitive
/// means every downstream consumer of the Aplicacao's
/// per-`:placement` cluster-pool surface reaches for exactly one
/// typed dispatch — the resolver's accept-set migrates as a unit
/// on any future axis addition.
///
/// Second slice-return (`&[T]`) accessor on any M2 or M3 typed
/// slot — sibling to the seed M2
/// [`crate::SupervisorSpec::children`] (bc92bce) `&[ChildSpec]`
/// slice-return accessor on the peer per-`:supervisor` static-
/// child-list `Vec`-carry axis, extended onto the first M3 mesh-
/// slot `Vec`-carry axis. Same "one typed dispatch on the substrate
/// primitive, thin projections at each consumer" discipline. The
/// three peer `Vec`-carry axes still unlifted at the time of this
/// lift — [`crate::AplicacaoSpec::membros`] (`Vec<Membro>`
/// per-Aplicacao member list), [`crate::AplicacaoSpec::contratos`]
/// (`Vec<WitContract>` per-Aplicacao WIT-typed edge list),
/// [`crate::UpgradeFromEntry::instructions`]
/// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
/// — inherit this accessor's discipline as future compounding runs
/// migrate their consumers onto the shared slice-return shape.
/// Fourth (and final) accessor on the M3 mesh-slot `Placement`
/// type, sibling to the two `Option<&str>`-return
/// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
/// (74ec2d3) accessors and the `Copy`-return
/// [`Placement::estrategia`] (921fe1b) accessor — closes the last
/// unlifted per-`:placement` field axis (the `Vec<String>`
/// distribution-target-list carrier) so every downstream
/// per-`:placement` reader now routes through a typed dispatch on
/// the substrate primitive. Named `clusters()` to match the storage
/// field's name verbatim and the tatara-lisp author-surface term
/// (`:clusters`) the field's own docstring already carries; the
/// accessor's identity maps onto the canonical MESH-COMPOSITION
/// §II.1 / §II.4 vocabulary the slot's docstring already reaches
/// for. Returns `&[String]` (not `&Vec<String>`) because every
/// downstream consumer of the cluster list treats it as a read-only
/// sequence — the slice-view is the narrowest borrow that supports
/// every present + roadmapped consumer (`.is_empty()`, `.iter()`,
/// `.len()`) without leaking the backing `Vec`'s
/// grow/push/reserve surface that no consumer of the typed view
/// reaches for (the storage-side `Vec` remains reachable through
/// the `pub clusters` field for the mutation-carrying serde
/// round-trip and per-test fixture-mutation paths).
#[must_use]
pub const fn clusters(&self) -> &[String] {
self.clusters.as_slice()
}
}
impl Default for Placement {
fn default() -> Self {
Self {
// Route the struct-literal `estrategia` default arm through
// the substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`]
// typed `pub const` rather than the transitively-derived
// [`PlacementStrategy::default`] route — one source of truth
// for the M3-mesh-canonical [`PlacementStrategy::Replicated`]
// active-active-across-every-named-cluster arm
// (MESH-COMPOSITION §II.2) that both this struct-literal
// altitude and the sibling [`Default for PlacementStrategy`]
// impl already key off through the same substrate primitive.
// Pinned by
// `placement_default_estrategia_routes_through_lifted_default`.
estrategia: PLACEMENT_ESTRATEGIA_DEFAULT,
clusters: Vec::new(),
affinity: None,
shard_key: None,
}
}
}
// ── external entry point ─────────────────────────────────────────────
/// External entry point — what an outside caller sees. Renders to a
/// Gateway / Ingress + a route to the named member Servico.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct Entrada {
/// Public hostname (e.g. `"checkout.quero.cloud"`).
pub host: String,
/// Member Servico the gateway routes to. Must be in `:membros`.
pub para: String,
/// Optional path filter — if set, only matching paths route to
/// this Aplicacao (the rest fall through to other route rules).
#[serde(default)]
pub paths: Vec<String>,
/// Default port on the destination Servico (the trigger.service.port).
#[serde(default = "default_port")]
pub port: u16,
}
impl Entrada {
/// Substrate-canonical per-`:entrada` URL-path fallback resolver
/// every HTTPRoute-aware renderer keys off — returns the author-
/// declared `:entrada :paths` list verbatim when non-empty, and the
/// singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] catch-
/// all fallback otherwise (so an Aplicacao author who declares an
/// external `:entrada` block but no per-path rule surface still
/// gets a route whose sole `HTTPPathMatch` matches every incoming
/// request under the paired
/// [`crate::GATEWAY_API_PATH_MATCH_TYPE_PATH_PREFIX`] discriminator).
///
/// Prior to this lift the "if `:entrada :paths` is empty use the
/// substrate catch-all; else return each declared path verbatim"
/// cascade lived inline at
/// [`caixa_mesh::gateway_routes`]'s per-rule path-list resolver
/// (caixa-mesh/src/lib.rs:2883 prior to this lift), the sole
/// per-Aplicacao HTTPRoute per-rule path-list emit site the
/// substrate ships today, with no typed method on the substrate
/// primitive that named the rule. A future path-resolution axis
/// addition — a per-cluster `:entrada :default-path` override the
/// operator pins through a future `:placement`-scoped slot, an
/// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
/// admission-webhook floor that materializes the catch-all before
/// the CR lands, a future per-`:entrada :paths` overlay from a
/// per-cluster policy the future `feira app deploy` pipeline
/// consumes — would have to be threaded through every renderer's
/// inline copy of the cascade in lockstep or one consumer would
/// silently disagree with the peers on which path list a given
/// `:entrada` block resolves to. Lifting the rule to a typed
/// method on the substrate primitive means every downstream
/// HTTPRoute-aware consumer (the M4 CR materializer, the future
/// per-cluster overlay resolver, every future per-Aplicacao
/// snapshot renderer) reaches for exactly one typed dispatch —
/// the resolver's accept-set moves as a unit on any future axis
/// addition.
///
/// Peer of the sibling [`crate::DEFAULT_SERVICO_PORT`] /
/// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] lifts on the
/// per-`:entrada` scalar-value axes — extends the "one typed
/// dispatch on the substrate primitive, thin projections at each
/// consumer" discipline onto the per-`:entrada` path-list
/// resolution axis every HTTPRoute-aware renderer consumes. Same
/// shape as the [`MeshPolicy::is_empty`] typed predicate on the
/// sibling `:politicas` primitive — one typed method on the
/// substrate primitive that names the cascade every renderer
/// otherwise re-inlines.
#[must_use]
pub fn resolved_paths(&self) -> Vec<&str> {
// Route the internal cascade-head + per-entry projection reads
// through the lifted [`Self::paths`] slice accessor rather than
// the raw `self.paths` field access — the substrate-primitive
// per-`:entrada` path-list resolver's two internal reads now
// key off the canonical raw-slot surface every downstream
// per-`:entrada` path-list consumer (`AplicacaoSpec::validate`'s
// per-entry value-shape gate, `feira app graph`'s per-Aplicacao
// entrada summary line's `{:?}` Debug print) routes through, so
// any future rebrand on the typed slot's raw-slot reader lands
// at exactly one place. Same two-consumer coherence discipline
// the sibling `Placement::clusters` (a6e18d7) accessor pins on
// the peer M3 mesh-slot `Vec<String>`-carry axis.
if self.paths().is_empty() {
vec![crate::render::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH]
} else {
self.paths().iter().map(String::as_str).collect()
}
}
/// Substrate-canonical per-`:entrada` DNS-hostname singular
/// accessor every Gateway-API `Listener.hostname` reader keys off
/// — returns the author-declared `:entrada :host` byte-string
/// verbatim as a `&str`, borrowed from the typed slot's own
/// [`String`] storage.
///
/// Named the "singular" half of the DNS-hostname resolver pair on
/// the substrate primitive: the parent-Gateway per-listener
/// `hostname:` axis of the K8s Gateway API v1.x is scalar-shaped
/// (`Listener.hostname: Option<PreciseHostname>` — at most one
/// hostname per listener), and this accessor is the typed dispatch
/// the [`caixa_mesh::gateway_routes`] Gateway-listener emit site
/// reaches for. Its plural sibling [`Entrada::hostnames`] carries
/// the per-HTTPRoute `spec.hostnames[]` list axis the same
/// per-Aplicacao ingress-hostname surface projects onto.
///
/// Prior to this lift the `entrada.host.clone()` byte-string was
/// accessed inline at two `caixa-mesh` sites — the parent-Gateway
/// per-listener singular `hostname:` axis
/// (`caixa-mesh/src/lib.rs:2775` prior to this lift) and the
/// per-HTTPRoute plural `spec.hostnames[]` axis
/// (`caixa-mesh/src/lib.rs:2969` prior to this lift). Both
/// consumers read the same `entrada.host` field but the two-site
/// duplication expressed no compile-time contract that the singular
/// Gateway-listener filter and the plural `HTTPRoute` filter list
/// stay in lockstep on future extensions of the `:entrada` slot to
/// a multi-hostname author surface (an `:entrada :alt-hosts` list
/// overlay, a per-cluster SNI fan-out the operator pins through a
/// future `:placement :hosts` slot, an M4 `mesh.pleme.io/v1alpha1/
/// Aplicacao` CR materializer's per-listener virtual-host filter
/// admission-webhook overlay). Any such extension would have to be
/// threaded through every renderer's inline copy of the resolution
/// in lockstep or the Gateway listener's `hostname:` filter would
/// silently disagree with the `HTTPRoute`'s `hostnames[]` filter list
/// — a Gateway-API-conformance divergence whose apply-time symptom
/// (the `HTTPRoute` `Accepted` condition flips to `False` with reason
/// `NoMatchingParent` — the API server rejects the route because
/// its `hostnames[]` filter doesn't intersect the parent listener's
/// `hostname` filter) is far from the source `caixa.lisp` and never
/// surfaces in the emitted YAML. Lifting the singular and plural
/// resolvers to typed methods on the substrate primitive means
/// every consumer of the Aplicacao's ingress-hostname surface
/// reaches for exactly one typed dispatch, and the pair-invariant
/// `hostnames() == vec![hostname()]` pinned by the sibling
/// [`tests::hostnames_returns_singleton_of_hostname_accessor`] test
/// keeps the two axes in lockstep by construction.
///
/// Peer of the sibling per-`:entrada` [`Entrada::resolved_paths`]
/// (1449891) path-list resolver on the per-HTTPRoute per-rule
/// `spec.rules[].matches[].path` axis. Same "one typed dispatch on
/// the substrate primitive, thin projections at each consumer"
/// discipline the [`crate::DEFAULT_SERVICO_PORT`] +
/// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
/// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
/// [`Entrada::resolved_paths`] lifts apply on the sibling per-
/// `:entrada` scalar-value + list-value axes.
#[must_use]
pub const fn hostname(&self) -> &str {
self.host.as_str()
}
/// Substrate-canonical per-`:entrada` DNS-hostname plural
/// accessor every Gateway-API `HTTPRoute.spec.hostnames[]` reader
/// keys off — returns the singleton `[hostname()]` list under
/// today's single-hostname-per-Aplicacao author surface, and the
/// authoritative multi-hostname list under a future
/// `:entrada :alt-hosts` / per-cluster SNI-fan-out extension.
///
/// Plural half of the DNS-hostname resolver pair — see the
/// companion [`Entrada::hostname`] docstring for the two-consumer
/// lift + pair-invariant discipline (`hostnames() ==
/// vec![hostname()]`, pinned load-bearing by the sibling
/// [`tests::hostnames_returns_singleton_of_hostname_accessor`]
/// test).
///
/// Peer of the sibling [`Entrada::resolved_paths`] (1449891)
/// per-`:entrada` plural-list resolver on the per-HTTPRoute
/// per-rule path-list axis — same `Vec<&str>` shape, same
/// substrate-primitive-owns-the-resolver discipline extended to
/// the per-HTTPRoute virtual-host filter-list axis.
#[must_use]
pub fn hostnames(&self) -> Vec<&str> {
vec![self.hostname()]
}
/// Substrate-canonical per-`:entrada` destination-Servico scalar
/// accessor every Gateway-API `HTTPRoute` reader keys off — returns
/// the author-declared `:entrada :para` byte-string verbatim as a
/// `&str`, borrowed from the typed slot's own [`String`] storage.
///
/// The `:entrada :para` slot names the single member Servico the
/// external Gateway routes to (validated by
/// [`AplicacaoSpec::validate`] to be a
/// [`Membro::caixa`] the Aplicacao declares — a stray
/// `:para` that doesn't name a member is
/// [`AplicacaoError::EntradaParaNotInMembros`], not a silent
/// backend-attachment miss at cluster-apply time). Under today's
/// single-destination author surface `:entrada :para` is the ingress
/// apex Servico's canonical identity; under a hypothetical
/// future multi-backend author surface (a `:entrada
/// :split :backends` weighted-fan-out overlay for canary /
/// blue-green traffic-split rollouts, per-path override for
/// path-based per-Servico routing beyond the single-apex model,
/// the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
/// per-CR admission-webhook that promotes the scalar to a
/// weighted list) this accessor is the substrate primitive's typed
/// dispatch every downstream `HTTPRoute`-aware consumer routes
/// through, so the resolution shape migrates as a unit on one
/// caixa-core edit rather than a coordinated rewrite across every
/// renderer's inline field-access.
///
/// Prior to this lift the `entrada.para` byte-string was accessed
/// inline at two `caixa-mesh` sites — the per-Aplicacao HTTPRoute
/// `metadata.name` composer's per-destination discriminator arg
/// (`gateway_api_http_route_name(&caixa.nome, &entrada.para)`,
/// `caixa-mesh/src/lib.rs:2845` prior to this lift) and the
/// per-HTTPRoute per-rule `backendRefs[0].name` axis
/// (`entrada.para.clone()`,
/// `caixa-mesh/src/lib.rs:2975` prior to this lift). Both
/// consumers read the same `entrada.para` field but the two-site
/// duplication expressed no compile-time contract that the HTTPRoute
/// name-discriminator and the per-rule backend name stay in
/// lockstep on future extensions of the `:entrada` slot to a
/// multi-destination author surface. Any such extension would have
/// to be threaded through every renderer's inline copy of the
/// destination projection in lockstep or the HTTPRoute
/// `metadata.name` would silently reference a different destination
/// than its own `backendRefs[]` — an operator-side
/// `kubectl get httproute -n tatara-system <aplicacao>-<destination>`
/// grep-by-name lookup would land on a route whose `backendRefs[]`
/// silently point at a peer Servico, dropping every external
/// `:entrada` flow at the gateway with the destination-drift root
/// cause invisible in the emitted YAML.
///
/// Peer of the sibling per-`:entrada` [`Entrada::hostname`] +
/// [`Entrada::hostnames`] (11f3dfe) DNS-hostname resolver pair on
/// the per-listener singular / per-HTTPRoute plural filter axes and
/// [`Entrada::resolved_paths`] (1449891) per-`:entrada` path-list
/// resolver on the per-HTTPRoute per-rule matches axis. Same "one
/// typed dispatch on the substrate primitive, thin projections at
/// each consumer" discipline the [`crate::DEFAULT_SERVICO_PORT`] +
/// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
/// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
/// [`Entrada::resolved_paths`] (1449891) lifts apply on the
/// sibling per-`:entrada` scalar-value + list-value axes — this
/// accessor closes the last unlifted per-`:entrada` scalar axis
/// (the destination-Servico byte-string) so every downstream
/// per-`:entrada` reader now routes through a typed dispatch on
/// the substrate primitive.
#[must_use]
pub const fn destination(&self) -> &str {
self.para.as_str()
}
/// Substrate-canonical per-`:entrada` L4-port scalar accessor every
/// Gateway-API `HTTPRoute.backendRefs[0].port` / Cilium
/// `CiliumNetworkPolicy.spec.ingress[].toPorts[0].ports[0].port`
/// reader keys off — returns the author-declared `:entrada :port`
/// value verbatim as a `u16`, `Copy`-projected from the typed slot's
/// own `u16` storage (validated by [`AplicacaoSpec::validate`] to lie
/// in [`SERVICO_PORT_MIN`]`..=u16::MAX` — a stray `:port 0` is
/// [`AplicacaoError::EntradaPortZero`], not a silent
/// admission-webhook rejection at cluster-apply time).
///
/// The `:entrada :port` slot carries the destination Servico's
/// canonical in-cluster L4 listener port (`trigger.service.port` on
/// the `pleme-computeunit` library chart), and every downstream
/// consumer that reads the port keys off this scalar (the
/// [`AplicacaoSpec::validate`] entrada-block structural-floor gate,
/// the [`AplicacaoSpec::port_for_destination`] typed-dispatch
/// resolver `caixa-mesh` HTTPRoute / CNP L4-fallback renderers
/// route through, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
/// CR materializer's per-Aplicacao gateway port resolver).
///
/// Prior to this lift the `.port` field was accessed inline at two
/// caixa-core sites — the [`AplicacaoSpec::validate`] entrada-block
/// structural-floor gate's `if e.port < SERVICO_PORT_MIN` check and
/// the [`AplicacaoSpec::port_for_destination`] resolver's
/// `.map_or(DEFAULT_SERVICO_PORT, |e| e.port)` cascade — two
/// open-coded field-accesses that expressed no compile-time link
/// back to the typed slot. A future extension of the `:entrada :port`
/// axis to a richer author surface — a per-cluster override the
/// operator pins through a future `:placement :default-port` slot the
/// [`DEFAULT_SERVICO_PORT`] docstring acknowledges, an
/// `Option<u16>`-shape migration once the substrate grows per-`:membros`
/// heterogeneous listener ports, an M4
/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
/// admission-webhook floor that promotes the scalar to a
/// per-destination map — would have had to be threaded through both
/// open-coded copies in lockstep or the structural-floor validator
/// and the [`AplicacaoSpec::port_for_destination`] resolver would
/// silently disagree on which port a given [`Entrada`] resolves to.
/// Lifting the resolution rule to a typed method on the substrate
/// primitive means every downstream consumer of the Aplicacao's
/// per-`:entrada` L4-port surface reaches for exactly one typed
/// dispatch — the resolver's accept-set migrates as a unit on any
/// future axis addition.
///
/// Peer of the sibling per-`:entrada` [`Entrada::hostname`] /
/// [`Entrada::destination`] (11f3dfe, 6db982c) `&str` scalar
/// accessors on the per-`:entrada` scalar-value axis — same "one
/// typed dispatch on the substrate primitive, thin projections at
/// each consumer" discipline extended onto the per-`:entrada`
/// L4-port `u16` `Copy`-scalar axis. First `Copy`-return accessor on
/// the M3 mesh-slot `Entrada` type — closes the last unlifted
/// per-`:entrada` scalar-value axis (the `u16` L4 port); companion
/// to the sibling per-`:politicas` `Option<Copy-T>` accessor family
/// [`MeshPolicy::mtls_required`] / [`MeshPolicy::retries`] /
/// [`MeshPolicy::timeout`] (c0110f1, bdfb399, 7073d0f) on the peer
/// M3 mesh-slot Copy-scalar axis. Named `port()` to match the
/// storage field's name; the accessor's identity name maps onto the
/// canonical MESH-COMPOSITION §II.5 vocabulary the slot's docstring
/// already carries. Declared `pub const fn` (matching the peer M3
/// mesh-slot `Copy`-return accessor family — [`MeshPolicy::timeout`]
/// / [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
/// [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`] on
/// the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`] /
/// [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
/// [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
/// [`RateLimit`], and the sibling per-`:placement`
/// [`Placement::estrategia`] on the peer M3 mesh-slot `Copy`-composite-
/// enum scalar axis — every one a `pub const fn`) so every future
/// substrate-side `const`-context consumer of the resolved
/// per-`:entrada` L4-port scalar (a `const _: () = assert!(…)`
/// module-scope pin on a per-fixture typed [`Entrada`] anchoring
/// `entrada.port() >= SERVICO_PORT_MIN` at compile time, a future M4
/// admission-webhook `const fn` per-CR gateway-port floor over a
/// typed [`Entrada`], any `const fn` composer that fans on the port
/// at compile time) reaches through the same typed dispatch on the
/// substrate primitive at const-eval time as at runtime. Pinned by
/// [`entrada_port_accessor_is_const_fn`] which witnesses the
/// const-eval posture at module scope via `const _:() = …` items so
/// any future accidental downgrade to non-`const` trips at caixa-core
/// build time.
#[must_use]
pub const fn port(&self) -> u16 {
self.port
}
/// Substrate-canonical per-`:entrada` URL-path-list `&[String]`
/// slice accessor every HTTPRoute-aware renderer keys off when it
/// wants the raw author-declared path-list (not the fallback-
/// applied projection [`Self::resolved_paths`] returns) — returns
/// the author-declared `:entrada :paths` list verbatim as `&[String]`,
/// borrowed from the typed slot's own [`Vec<String>`] storage.
///
/// Named the "raw slot" half of the per-`:entrada` path-list resolver
/// pair on the substrate primitive: the sibling [`Self::resolved_paths`]
/// (1449891) closes the fallback-applying arm every per-Aplicacao
/// HTTPRoute per-rule `matches[].path` emitter routes through (empty
/// slot → single [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
/// catch-all; non-empty slot → per-entry verbatim projection); this
/// accessor closes the raw-slot arm every consumer that must see the
/// author's declaration verbatim (the [`AplicacaoSpec::validate`]
/// per-entry value-shape gate — empty `:paths` must be `Ok(())`,
/// not `Err(EntradaPathEmpty)`, so it cannot route through the
/// fallback-applying sibling; the `feira app graph` per-Aplicacao
/// external-gateway summary line's `{:?}` Debug print — which must
/// name the author's declaration, not the substrate's fallback, so
/// an author reading their graph output can grep their caixa.lisp
/// for the exact list they authored) routes through.
///
/// Prior to this lift the `.paths` field was accessed inline at four
/// production sites: the two internal reads in [`Self::resolved_paths`]
/// (the `.is_empty()` cascade-head and the `.iter().map(String::as_str)`
/// per-entry projection), the [`AplicacaoSpec::validate`] per-entry
/// value-shape gate's `for p in &e.paths` traversal head, and the
/// `feira app graph` per-Aplicacao entrada summary line's `{:?}`
/// Debug print — four open-coded field-accesses that expressed no
/// compile-time link back to the typed slot. A future extension of
/// the `:entrada :paths` axis to a richer author surface — a
/// per-path per-method HTTP-verb filter overlay (`(:paths ((:path
/// "/api" :methods (:get :post))))` the Gateway API v1 HTTPRoute
/// spec supports through `matches[].method`), a per-path per-header
/// filter overlay (`matches[].headers[]`), a per-cluster override
/// the operator pins through a future `:placement :path-overlay`
/// slot, an M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
/// per-CR admission-webhook that normalized the list at admission
/// time — would have had to be threaded through every open-coded
/// copy in lockstep or the validator's per-entry gate would silently
/// disagree with the renderer's per-entry emit on which list a given
/// `:entrada` block resolves to. Lifting the resolution to a typed
/// method on the substrate primitive means every downstream consumer
/// of the Aplicacao's per-`:entrada` path-list surface reaches for
/// exactly one typed dispatch — the resolver's accept-set migrates
/// as a unit on any future axis addition.
///
/// Peer of the sibling [`crate::Placement::clusters`] (a6e18d7)
/// `&[String]` slice accessor on the peer M3 mesh-slot `Vec<String>`-
/// carry axis — same "one typed dispatch on the substrate primitive,
/// thin projections at each consumer" discipline extended onto the
/// per-`:entrada` `Vec<String>` slice-carry axis. Closes the last
/// unlifted per-`:entrada` field axis (the `Vec<String>` path-list
/// carrier) so every downstream per-`:entrada` reader now routes
/// through a typed dispatch on the substrate primitive. Returns
/// `&[String]` (not `&Vec<String>`) because every downstream consumer
/// treats the list as a read-only sequence — the slice-view is the
/// narrowest borrow that supports every present + roadmapped consumer
/// (`.is_empty()`, `.iter()`, `.len()`) without leaking the backing
/// `Vec`'s grow/push/reserve surface that no consumer of the typed
/// view reaches for (the storage-side `Vec` remains reachable through
/// the `pub paths` field for the mutation-carrying serde round-trip
/// and per-test fixture-mutation paths).
#[must_use]
pub const fn paths(&self) -> &[String] {
self.paths.as_slice()
}
}
/// Canonical default L4 port every typed Servico exposes on its
/// in-cluster K8s Service (the `trigger.service.port` axis the
/// `pleme-computeunit` library chart emits, the `:entrada :port` author
/// surface defaults to when the author omits the slot, and the
/// `caixa-mesh` `CiliumNetworkPolicy` L4-fallback substitutes when no
/// `:entrada` block matches the per-`:contratos` destination Servico).
/// The single source of truth all three typed-port consumers reach for:
///
/// - [`Entrada::port`]'s serde default (via the
/// [`default_port`] helper this constant feeds); the author surface
/// `(:entrada (:host … :para …))` without an explicit `:port` slot
/// reads back as a typed [`Entrada`] carrying this exact value;
/// - the
/// [`caixa_mesh::cilium_network_policies`][cm] `CiliumNetworkPolicy`
/// emitter's per-`(:de, :para)` L4 `toPorts[].ports[].port`
/// fallback, fired when the typed `:entrada` block doesn't name
/// the per-`:contratos` destination Servico — the typed
/// `:contratos` graph carries no per-destination port axis (the
/// destination port is the destination Servico's
/// `lareira-<nome>` chart's `trigger.service.port`, which the
/// Aplicacao-level renderer has no visibility into without a
/// resolver round-trip), so the renderer falls back to the
/// substrate's canonical Servico-port assumption — by
/// construction the same value the destination's own
/// `pleme-computeunit` chart emits, the same value the
/// destination's own typed `:entrada :port` slot defaults to;
/// - every future per-Servico renderer the absorption-roadmap
/// acknowledges (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
/// CR materializer's per-edge port resolver, the future
/// per-`:politicas :rate-limit` `CiliumClusterwideEnvoyConfig`
/// emitter's per-route bucket key, the future caixa-otel
/// collector-pipeline emitter's per-Servico scrape port).
///
/// Until this lift landed the value `8080` lived at two production-code
/// call-sites: the [`default_port`] helper at
/// `caixa-core/src/aplicacao.rs:1712` (the typed slot's serde default)
/// and the `.unwrap_or(8080)` literal at
/// `caixa-mesh/src/lib.rs:344` (the L4-fallback in
/// [`caixa_mesh::cilium_network_policies`]'s per-`(:de, :para)` port
/// resolver). A future Servico-port rebrand — the substrate moving the
/// canonical port to `80` (HTTP's IANA-assigned port) once the cluster
/// gateway grows direct `:80` listeners, to `8443` once the substrate
/// moves to mTLS-by-default at the Servico boundary, to a per-cluster
/// override the operator pins through a future
/// `:placement :default-port` slot — without a coordinated edit on
/// both sides would silently emit Servicos listening on one port and
/// their Aplicacao's `CiliumNetworkPolicy` whitelisting a drifted one.
/// The CNP's apply-time symptom (the policy is admitted but every L4
/// flow on the destination Servico's actual port silently drops because
/// it doesn't match the whitelisted port) is far from the rebrand
/// commit's source, and Cilium's per-L4-drop diagnostic surfaces only
/// in hubble traces, not in `kubectl describe`. Lifting the literal to
/// a shared constant closes the drift footgun structurally — both
/// consumers read from the same `u16`, so any rebrand reaches both
/// sites by construction.
///
/// Mirrors the [`crate::DEFAULT_NAMESPACE`] lift (a085b26) on the peer
/// per-renderer canonical-K8s-axis constant — the namespace string
/// and the canonical Servico port both lived as duplicated literals
/// across caixa-core / caixa-mesh / caixa-flux before their respective
/// lifts. Same "the typed constant lives in one place" discipline the
/// [`crate::PLEME_LABEL_PREFIX`] / [`crate::LAREIRA_CHART_NAME_PREFIX`]
/// / [`crate::KUBE_KEY_API_VERSION`] lifts apply on the peer
/// shared-string axes.
///
/// [cm]: ../../caixa_mesh/fn.cilium_network_policies.html
pub const DEFAULT_SERVICO_PORT: u16 = 8080;
/// Structural floor for the typed `:entrada :port` axis — every
/// validated [`Entrada::port`] past [`AplicacaoSpec::validate`] lies in
/// `SERVICO_PORT_MIN..=u16::MAX` (inclusive on both ends).
///
/// The IANA-registered TCP/UDP port space is `1..=65535` — port `0` is
/// the "any ephemeral" sentinel that the Berkeley-sockets `bind(0)` call
/// interprets as "let the kernel pick a free port at bind time", not a
/// well-defined destination the substrate's per-`:entrada` Gateway API
/// v1 `HTTPRoute.backendRefs[].port` axis can honor. A typed slot
/// carrying `port: 0` degenerates to a nominal-only routing target: the
/// K8s Gateway API v1 apiserver-side webhook rejects `port: 0` outright
/// (`spec.rules[].backendRefs[].port: Invalid value: 0` — the same
/// admission floor the peer `PolicyRetriesExceedsCap` cap-arm surfaces
/// at build time rather than at `kubectl apply` time), and the
/// substrate's per-`Entrada` `CiliumNetworkPolicy` L4-fallback resolver
/// (caixa-mesh/src/lib.rs:2657 through
/// [`DEFAULT_SERVICO_PORT`]) — the sole downstream reader of the
/// [`Entrada::port`] typed value — silently emits a policy whose
/// `toPorts[].ports[].port` scalar drifts off the destination Servico's
/// actual listener, dropping every L4 flow at the eBPF data plane far
/// from the source caixa.lisp with no field naming the port-zero-drift
/// root cause.
///
/// The typed field is `u16`, so `u16::MAX` (=65535) is the natural
/// structural ceiling — no `SERVICO_PORT_MAX` companion const is needed
/// on the top edge (unlike the peer capped-`u32` `:politicas` /
/// `:supervisor` / `:limits` axes where `POLICY_RETRIES_MAX` /
/// `SUPERVISOR_MAX_RESTARTS_MAX` / `LIMITS_CPU_MILLICORES_MAX` all sit
/// well below `u32::MAX` and therefore need explicit typed caps).
///
/// Pairs with [`DEFAULT_SERVICO_PORT`] on the same typed-port axis:
/// [`DEFAULT_SERVICO_PORT`] names the substrate's chosen default port
/// scalar every `(:entrada (:host … :para …))` slot without an explicit
/// `:port` inherits through the serde default hook; this constant names
/// the accept-set floor every declared port must satisfy. The pair is
/// invariantly ordered `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT` (the
/// substrate's default must satisfy its own accept-set floor by
/// construction) — a future rebrand that accidentally moved
/// [`DEFAULT_SERVICO_PORT`] below the floor (a hypothetical `0` /
/// negative-cast typo, a per-cluster override the operator pins through
/// a future `:placement :default-port` slot that lands out-of-range)
/// would silently invalidate the serde-default emission at every
/// author-side `(:entrada (:host … :para …))` slot — the compile-time
/// invariant pin
/// (`default_servico_port_satisfies_lifted_servico_port_min_floor`)
/// closes the drift footgun at caixa-core build time.
///
/// Lifted as a typed `pub const` (rather than an inline `0` literal at
/// the [`AplicacaoSpec::validate`] call site) so the accept-set floor
/// has exactly one source of truth — the future M4
/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-Aplicacao
/// gateway resolver, the future per-Servico
/// `computeunit.trigger.service.port` renderer's per-CR port-value
/// validator, and every downstream test-fixture navigator asserting
/// the accept-set floor all read from one place. Same shape every
/// other typed bracket-floor / bracket-ceiling in this crate carries
/// ([`LIMITS_MEMORY_WASM32_PAGE_BYTES`], [`LIMITS_MEMORY_WASM32_MAX_BYTES`],
/// [`LIMITS_WALL_CLOCK_MAX`], [`LIMITS_CPU_MILLICORES_MAX`],
/// [`LIMITS_FUEL_MAX`], [`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
/// [`POLICY_RATE_LIMIT_MAX`]).
pub const SERVICO_PORT_MIN: u16 = 1;
const fn default_port() -> u16 {
DEFAULT_SERVICO_PORT
}
// ── the typed view ───────────────────────────────────────────────────
/// Typed composition view of the flat Aplicacao slots on
/// [`crate::Caixa`]. Built via [`crate::Caixa::aplicacao_view`] for
/// validation + downstream renderer consumption.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct AplicacaoSpec {
pub membros: Vec<Membro>,
pub contratos: Vec<WitContract>,
pub politicas: MeshPolicy,
pub placement: Placement,
pub entrada: Option<Entrada>,
}
impl AplicacaoSpec {
/// Substrate-canonical per-`:membros` `Vec<Membro>` MESH-COMPOSITION
/// per-Aplicacao member-list slice-return accessor every
/// per-Aplicacao member-list reader keys off — returns the author-
/// declared `:membros` list verbatim as a `&[Membro]` slice-view
/// over the same backing buffer the raw `self.membros.as_slice()`
/// field access borrows from.
///
/// The `:membros` slot carries the M3 mesh-slot per-Aplicacao
/// member list — the load-bearing identity of the application graph
/// (MESH-COMPOSITION §III.1: the graph nodes are a set, not a
/// multiset). Every per-`:membros` entry pairs a `:caixa` member-
/// caixa name (through the lifted [`Membro::nome`] (4a32abf)
/// accessor) with a `:versao` semver-requirement string (through
/// the lifted [`Membro::versao_requirement`] (a40b0e3) accessor),
/// and every downstream consumer that fans on the member-set keys
/// off this slice (the [`AplicacaoSpec::validate`] `:contratos`
/// membership-lookup `HashSet<&str>` seed's collect input, the
/// [`AplicacaoSpec::validate_membros`] pre-flight `.is_empty()`
/// [`AplicacaoError::NoMembros`] refusal probe, the same method's
/// per-member DNS-1123 / semver-requirement / duplicate-detection
/// fan-out loop, the [`AplicacaoSpec::detect_sync_cycles`]
/// adjacency-list seed, the [`caixa_mesh::programs_for_aplicacao`]
/// programs.yaml per-`:membros` fan-out emitter's per-entry
/// mapping-composition loop, the `feira app graph` per-Aplicacao
/// member-count print line and per-member tree traversal,
/// every future wasm-operator (M4) per-Aplicacao CR materializer's
/// per-member `ComputeUnit` fan-out, the future M5 adaptive-
/// placement engine's per-member weight-topology reader).
///
/// Prior to this lift the `.membros` `Vec<Membro>` was accessed
/// inline at six production sites — the [`AplicacaoSpec::validate`]
/// `self.membros.iter().map(Membro::nome).collect()` name-set seed,
/// [`AplicacaoSpec::validate_membros`]'s pre-flight
/// `self.membros.is_empty()` [`AplicacaoError::NoMembros`] refusal
/// probe, the same method's per-member `for m in &self.membros`
/// validate-loop traversal head, the
/// [`AplicacaoSpec::detect_sync_cycles`]'s
/// `for m in &self.membros` adjacency-list seed, the
/// [`caixa_mesh::programs_for_aplicacao`] emitter's
/// `Vec::with_capacity(spec.membros.len())` output-buffer sizing
/// paired with the peer `for m in &spec.membros` per-entry fan-out
/// loop, and the `feira app graph` per-Aplicacao print line's
/// `spec.membros.len()` count formatter argument paired with the
/// peer `for m in &spec.membros` per-member tree traversal — six
/// open-coded field-accesses that expressed no compile-time link
/// back to the typed slot. A future extension of the `:membros`
/// axis to a richer author surface (a per-cluster member-set
/// overlay the operator pins through a future
/// `:membros-overrides` slot the MESH-COMPOSITION §V federation
/// roadmap acknowledges, a per-tenant member-alias table the M4
/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer resolves per-
/// CR at admission time, a per-Aplicacao dynamic member-set
/// derivation the future adaptive-placement engine computes from
/// weighted membership topology, a promotion of the plain
/// `Vec<Membro>` to a richer `{static, dynamic}` partition once
/// Orleans-style virtual-actor dynamic-membership comes into typed
/// scope) would have had to be threaded through all six open-coded
/// copies in lockstep or one consumer would silently disagree with
/// the peers on which member-set a given Aplicacao resolves to —
/// the `HashSet<&str>` name-set seed reading the raw slot while
/// the peer `.is_empty()` refusal probe read an operator-resolved
/// slot would silently split the `:contratos` membership-lookup
/// input from the pre-flight-refusal input, a six-consumer split
/// at the validator + programs.yaml emitter + graph printer far
/// from the source `caixa.lisp` with no field naming the member-
/// set-drift root cause. Lifting the resolution rule to a typed
/// method on the substrate primitive means every downstream
/// consumer of the Aplicacao's per-`:membros` member-list surface
/// reaches for exactly one typed dispatch — the resolver's accept-
/// set migrates as a unit on any future axis addition.
///
/// Third slice-return (`&[T]`) accessor on any M2 or M3 typed slot
/// — sibling to the seed M2 [`crate::SupervisorSpec::children`]
/// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
/// static-child-list `Vec`-carry axis, and to the M3
/// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
/// on the peer per-`:placement` distribution-target-list `Vec`-
/// carry axis. Same "one typed dispatch on the substrate primitive,
/// thin projections at each consumer" discipline. The two peer
/// `Vec`-carry axes still unlifted at the time of this lift —
/// [`AplicacaoSpec::contratos`] (`Vec<WitContract>` per-Aplicacao
/// WIT-typed edge list) and
/// [`crate::UpgradeFromEntry::instructions`]
/// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
/// — inherit this accessor's discipline as future compounding runs
/// migrate their consumers onto the shared slice-return shape.
/// First `&[T]`-return accessor on the top-level M3 mesh-slot
/// `AplicacaoSpec` type itself, extending the discipline beyond
/// the inner per-slot types ([`crate::Placement`],
/// [`crate::SupervisorSpec`]) onto the outermost typed composition
/// view every renderer consumes. Named `membros()` to match the
/// storage field's name verbatim and the tatara-lisp author-
/// surface term (`:membros`) the field's own docstring already
/// carries; the accessor's identity maps onto the canonical
/// MESH-COMPOSITION §III.1 vocabulary the slot's docstring already
/// reaches for. Returns `&[Membro]` (not `&Vec<Membro>`) because
/// every downstream consumer of the member list treats it as a
/// read-only sequence — the slice-view is the narrowest borrow
/// that supports every present + roadmapped consumer
/// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
/// backing `Vec`'s grow/push/reserve surface that no consumer of
/// the typed view reaches for (the storage-side `Vec` remains
/// reachable through the `pub membros` field for the mutation-
/// carrying serde round-trip and per-test fixture-mutation paths).
#[must_use]
pub const fn membros(&self) -> &[Membro] {
self.membros.as_slice()
}
/// Substrate-canonical per-`:contratos` `Vec<WitContract>`
/// MESH-COMPOSITION per-Aplicacao WIT-typed-edge-list slice-return
/// accessor every per-Aplicacao contract-list reader keys off —
/// returns the author-declared `:contratos` list verbatim as a
/// `&[WitContract]` slice-view over the same backing buffer the raw
/// `self.contratos.as_slice()` field access borrows from.
///
/// The `:contratos` slot carries the M3 mesh-slot per-Aplicacao
/// WIT-typed edge list — the load-bearing set of directed edges
/// on the application graph whose nodes are the `:membros` entries
/// (MESH-COMPOSITION §III.1: the graph edges are a set, not a
/// multiset; the `(:de, :para, :wit, :endpoint, :subject, :slot)`
/// six-tuple is the edge identity every downstream duplicate gate
/// keys off). Every per-`:contratos` entry pairs a `:de` source-
/// Servico caller name + a `:para` destination-Servico callee name
/// (through the lifted [`WitContract::source`] +
/// [`WitContract::destination`] (7f0fd43) accessor pair on the
/// caller/callee-Servico axis) with a `:wit` world-reference
/// (through the lifted [`WitContract::world_ref`] (0804823)
/// accessor) and the target-shape-appropriate payload-carrier
/// scalar (through the lifted [`WitContract::endpoint`] (7020470),
/// [`WitContract::subject`] (90de675), or [`WitContract::slot`]
/// (ed22b66) accessor on the per-target-shape payload-carrier
/// axis). Every downstream consumer that fans on the edge-set
/// keys off this slice (the [`AplicacaoSpec::validate`] per-edge
/// name-set / self-edge / target-shape / dedup fan-out loop, the
/// [`AplicacaoSpec::detect_sync_cycles`] per-edge sync-subgraph
/// adjacency-list seed, the [`caixa_mesh::cilium_network_policies`]
/// per-`(:de, :para)` `BTreeMap` group fan-out emitter's per-entry
/// grouping loop, the `feira app graph` per-Aplicacao contract-
/// count print line and per-contract tree traversal, every future
/// wasm-operator (M4) per-Aplicacao CR materializer's per-edge
/// `CiliumNetworkPolicy` fan-out, the future M5 per-edge
/// mesh-policy overlay resolver's per-contract typed-edge weight
/// reader).
///
/// Prior to this lift the `.contratos` `Vec<WitContract>` was
/// accessed inline at four production sites — the
/// [`AplicacaoSpec::validate`]'s `for c in &self.contratos`
/// per-edge validate-loop traversal head (which drives every
/// per-edge name-set membership lookup, self-edge check,
/// target-shape dispatch, and dedup `HashSet` insert), the
/// [`AplicacaoSpec::detect_sync_cycles`]'s
/// `for c in &self.contratos` adjacency-list seed head (which
/// drives every per-edge sync-vs-pub-sub partition and per-edge
/// adjacency insert), the [`caixa_mesh::cilium_network_policies`]
/// emitter's `for c in &spec.contratos` per-`(:de, :para)`
/// `BTreeMap` grouping loop head (which drives every per-CNP
/// fan-out emit), and the `feira app graph` per-Aplicacao print
/// line's `spec.contratos.len()` count formatter argument paired
/// with the peer `for c in &spec.contratos` per-contract tree
/// traversal — four open-coded field-accesses that expressed no
/// compile-time link back to the typed slot. A future extension
/// of the `:contratos` axis to a richer author surface (a
/// per-cluster contract overlay the operator pins through a
/// future `:contratos-overrides` slot the MESH-COMPOSITION §V
/// federation roadmap acknowledges, a per-tenant edge-policy
/// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
/// materializer resolves per-CR at admission time, a per-edge
/// weight scalar the future adaptive-placement engine reads to
/// bias sync-subgraph routing, a promotion of the plain
/// `Vec<WitContract>` to a richer `{static, dynamic}` partition
/// once virtual-actor-style dynamic-edge composition comes into
/// typed scope) would have had to be threaded through all four
/// open-coded copies in lockstep or one consumer would silently
/// disagree with the peers on which edge-set a given Aplicacao
/// resolves to — the validator's per-edge dedup `HashSet` seed
/// reading the raw slot while the peer sync-cycle adjacency-list
/// seed read an operator-resolved slot would silently split the
/// build-time edge-set gate from the runtime deadlock-detection
/// gate, a four-consumer split at the validator, the cycle
/// detector, the CNP emitter, and the graph printer far from
/// the source `caixa.lisp` with no field naming the edge-set-
/// drift root cause. Lifting the resolution rule to a typed method on the
/// substrate primitive means every downstream consumer of the
/// Aplicacao's per-`:contratos` edge-list surface reaches for
/// exactly one typed dispatch — the resolver's accept-set
/// migrates as a unit on any future axis addition.
///
/// Fourth slice-return (`&[T]`) accessor on any M2 or M3 typed
/// slot — sibling to the seed M2 [`crate::SupervisorSpec::children`]
/// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
/// static-child-list `Vec`-carry axis, to the M3
/// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
/// on the peer per-`:placement` distribution-target-list `Vec`-
/// carry axis, and to the immediately-adjacent sibling M3
/// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` accessor on
/// the peer per-`:membros` node-list `Vec`-carry axis — the
/// per-`:contratos` edge-list accessor is the natural pair of
/// the per-`:membros` node-list accessor (graph edges over graph
/// nodes; every graph-shaped consumer reads both). Same "one
/// typed dispatch on the substrate primitive, thin projections
/// at each consumer" discipline. The last remaining `Vec`-carry
/// axis still unlifted at the time of this lift —
/// [`crate::UpgradeFromEntry::instructions`]
/// (`Vec<UpgradeInstruction>` per-appup migration-instruction
/// list) — inherits this accessor's discipline as future
/// compounding runs migrate its consumers onto the shared slice-
/// return shape. Second `&[T]`-return accessor on the top-level
/// M3 mesh-slot `AplicacaoSpec` type itself, closing the last
/// unlifted per-`AplicacaoSpec` `Vec`-carry axis (`:membros` +
/// `:contratos` are the two `Vec` fields on the outer typed
/// composition view — `:politicas`, `:placement`, `:entrada` are
/// scalar/option-shaped and already route through their per-slot
/// accessor families). Named `contratos()` to match the storage
/// field's name verbatim and the tatara-lisp author-surface term
/// (`:contratos`) the field's own docstring already carries; the
/// accessor's identity maps onto the canonical MESH-COMPOSITION
/// §III.1 vocabulary the slot's docstring already reaches for.
/// Returns `&[WitContract]` (not `&Vec<WitContract>`) because
/// every downstream consumer of the contract list treats it as a
/// read-only sequence — the slice-view is the narrowest borrow
/// that supports every present + roadmapped consumer
/// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
/// backing `Vec`'s grow/push/reserve surface that no consumer of
/// the typed view reaches for (the storage-side `Vec` remains
/// reachable through the `pub contratos` field for the mutation-
/// carrying serde round-trip and per-test fixture-mutation paths).
#[must_use]
pub const fn contratos(&self) -> &[WitContract] {
self.contratos.as_slice()
}
/// Substrate-canonical per-`:politicas` `MeshPolicy` MESH-COMPOSITION
/// per-Aplicacao mesh-policy composite-reference accessor every
/// per-Aplicacao policy-block reader keys off — returns the author-
/// declared `:politicas` composite verbatim as a `&MeshPolicy`
/// reference over the same backing storage the raw `&self.politicas`
/// field access borrows from.
///
/// The `:politicas` slot carries the M3 mesh-slot per-Aplicacao
/// mesh-policy composite — the load-bearing container of every
/// mesh-level operational-policy axis every downstream mesh-artifact
/// emitter fans on (MESH-COMPOSITION §III.2 #3: the per-Aplicacao
/// mesh-policy overlay is the single typed surface a
/// `CiliumClusterwideEnvoyConfig` per-`:politicas` fan-out reads
/// from). Every per-`:politicas` axis threads through a lifted
/// per-slot accessor on the [`MeshPolicy`] type: the
/// [`MeshPolicy::mtls_required`] (c0110f1) Cilium-mesh mTLS-
/// enforcement-toggle scalar accessor, the [`MeshPolicy::retries`]
/// (bdfb399) Gateway-API-mesh transient-failure-retry-budget scalar
/// accessor, the [`MeshPolicy::timeout`] (7073d0f) Gateway-API-mesh
/// per-call-deadline scalar accessor, the [`MeshPolicy::circuit_breaker`]
/// (b0e741a) Envoy-outlier-detection consecutive-failure-ejection
/// composite accessor, and the [`MeshPolicy::rate_limit`] (21a6c3b)
/// Envoy-local-rate-limit-mesh token-bucket-declaration composite
/// accessor. Every downstream consumer that reaches for a policy
/// axis first passes through this outer accessor onto the composite
/// and then dispatches onto the per-axis accessor — the two-level
/// dispatch means every per-`:politicas` reader now routes through
/// a typed dispatch on the substrate primitive at both altitudes.
///
/// Prior to this lift the `.politicas` `MeshPolicy` composite was
/// accessed inline at four production sites — the
/// [`AplicacaoSpec::validate_politicas`] entry-side `let p =
/// &self.politicas;` traversal seed (which drives every per-axis
/// zero-floor + upper-cap + canonical-form bracket dispatch through
/// `p.timeout()`, `p.retries()`, `p.circuit_breaker()`,
/// `p.rate_limit()` on the axis-level lifted accessors), the
/// [`caixa_mesh::cilium_network_policies`] per-CNP mTLS-mode-overlay
/// emitter's `spec.politicas.mtls_required()` field-then-accessor
/// chain (which drives every per-`(:de, :para)` CNP
/// authentication-mode overlay onto the emitted `CiliumNetworkPolicy`),
/// and the [`caixa_mesh::gateway_routes`] per-HTTPRoute per-request
/// timeout + retry overlay emitter's paired
/// `spec.politicas.timeout()` + `spec.politicas.retries()` field-then-
/// accessor chain (which drives the per-Aplicacao Gateway-API-mesh
/// deadline + budget overlay onto the emitted `HTTPRoute`) — four
/// open-coded outer-field accesses that expressed no compile-time
/// link back to the typed slot at the [`AplicacaoSpec`] altitude. A
/// future extension of the `:politicas` outer axis to a richer
/// author surface (a per-cluster policy overlay the operator pins
/// through a future `:politicas-overrides` slot the MESH-COMPOSITION
/// §V federation roadmap acknowledges, a per-tenant policy-alias
/// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
/// resolves per-CR at admission time, a per-Aplicacao dynamic
/// policy-composite derivation the future adaptive-placement engine
/// computes from a per-cluster load-topology reader, a promotion of
/// the plain [`MeshPolicy`] to a richer `{static, dynamic}`
/// partition once virtual-actor-style dynamic-mesh-policy
/// composition comes into typed scope) would have had to be threaded
/// through all four open-coded copies in lockstep or one consumer
/// would silently disagree with the peers on which mesh-policy
/// composite a given Aplicacao resolves to — the validator's
/// per-axis bracket-dispatch seed reading the raw slot while the
/// peer CNP mTLS-overlay emitter read an operator-resolved slot
/// would silently split the build-time policy-shape gate from the
/// runtime CNP-emission gate, a four-consumer split at the
/// validator, the CNP emitter, and the `HTTPRoute` emitter far from
/// the source `caixa.lisp` with no field naming the policy-drift
/// root cause. Lifting the resolution rule to a typed method on the
/// substrate primitive means every downstream consumer of the
/// Aplicacao's per-`:politicas` mesh-policy composite surface
/// reaches for exactly one typed dispatch — the resolver's accept-
/// set migrates as a unit on any future axis addition.
///
/// First `&Composite`-return accessor on the top-level M3 mesh-slot
/// `AplicacaoSpec` type itself — sibling to the seed slice-return
/// accessors [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
/// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that
/// close the two `Vec`-carry axes on the outer typed composition
/// view; the outer `:politicas` composite-reference axis is the
/// natural pair to the paired outer `Vec`-carry accessors on the
/// two peer M3 mesh slots — every whole-Aplicacao mesh-artifact
/// emitter reads all four axes as one unit (graph nodes + graph
/// edges + mesh policy + placement pool). Peer to the same
/// [`crate::SupervisorSpec`] altitude on the sibling M2 supervisor-
/// slot: every M2 `SupervisorSpec`-scoped composite reader
/// ([`crate::SupervisorSpec::estrategia`], `max_restarts`,
/// `restart_window`, `children`) already routes through the M2
/// `SupervisorSpec` accessor family — this lift extends the same
/// "one typed dispatch on the substrate primitive at the outer
/// composition altitude" discipline to the M3 mesh-slot
/// `AplicacaoSpec`-scoped `:politicas` composite axis. The two
/// remaining peer outer-composite axes still unlifted at the time
/// of this lift — [`AplicacaoSpec::placement`] (`Placement`
/// per-Aplicacao distribution-composite) and [`AplicacaoSpec::entrada`]
/// (`Option<Entrada>` per-Aplicacao external-gateway composite) —
/// inherit this accessor's discipline as future compounding runs
/// migrate their consumers onto the shared reference-return shape.
/// Named `politicas()` to match the storage field's name verbatim
/// and the tatara-lisp author-surface term (`:politicas`) the
/// field's own docstring already carries; the accessor's identity
/// maps onto the canonical MESH-COMPOSITION §III.2 vocabulary the
/// slot's docstring already reaches for. Returns `&MeshPolicy`
/// (not the owning composite by copy or clone) because every
/// downstream consumer of the mesh-policy composite treats it as a
/// read-only per-axis dispatch source — the reference-view is the
/// narrowest borrow that supports every present + roadmapped
/// consumer (per-axis accessor dispatch, [`MeshPolicy::is_empty`]
/// emptiness probe) without cloning the composite through every
/// consumer's fast path.
#[must_use]
pub const fn politicas(&self) -> &MeshPolicy {
&self.politicas
}
/// Substrate-canonical per-`:placement` `Placement` MESH-COMPOSITION
/// per-Aplicacao distribution-composite composite-reference accessor
/// every per-Aplicacao placement-block reader keys off — returns the
/// author-declared `:placement` composite verbatim as a `&Placement`
/// reference over the same backing storage the raw `&self.placement`
/// field access borrows from.
///
/// The `:placement` slot carries the M3 mesh-slot per-Aplicacao
/// distribution composite — the load-bearing container of every
/// where-does-this-Aplicacao-run axis every downstream cluster-artifact
/// emitter fans on (MESH-COMPOSITION §II.1 for the `SingleNode` /
/// `Replicated` Erlang/OTP distributed-app takeover axes, §II.4 for the
/// `Sharded` Akka-cluster-sharding axis, §III.1 for the `:clusters`
/// hosting-pool identity, §V for the `M3-Adaptive`-compression
/// `:affinity` hint). Every per-`:placement` axis threads through a
/// lifted per-slot accessor on the [`Placement`] type: the
/// [`Placement::estrategia`] (921fe1b) MESH-COMPOSITION distribution-
/// strategy scalar accessor, the [`Placement::clusters`] (a6e18d7)
/// per-cluster distribution-target slice-return accessor, the
/// [`Placement::affinity`] (74ec2d3) M3-Adaptive-compression-hint
/// optional-scalar accessor, and the [`Placement::shard_key`]
/// (7cd2a28) Akka-cluster-sharding-key optional-scalar accessor. Every
/// downstream consumer that reaches for a placement axis first passes
/// through this outer accessor onto the composite and then dispatches
/// onto the per-axis accessor — the two-level dispatch means every
/// per-`:placement` reader now routes through a typed dispatch on the
/// substrate primitive at both altitudes.
///
/// Prior to this lift the `.placement` `Placement` composite was
/// accessed inline at three production sites — the
/// [`AplicacaoSpec::validate_placement`] per-axis bracket-dispatch
/// seed (six `self.placement.<axis>()` field-then-inner-accessor
/// chains: the pre-flight `.clusters().is_empty()` refusal probe
/// paired with the `.estrategia()` diagnostic-carry copy, the per-
/// cluster `.clusters()` validate-loop traversal head, the per-
/// hint `.affinity()` optional-scalar shape gate, and the `Sharded` ↔
/// non-`Sharded` partition's `.estrategia()` match arm scrutinee
/// paired with the shape-gate cascade's `.shard_key()` /
/// `.estrategia()` diagnostic-carry pair), the
/// [`caixa_mesh::programs_for_aplicacao`] per-Aplicacao programs.yaml
/// per-entry placement-block emitter's outer
/// `serde_yaml::to_value(&spec.placement)` composite-serialization
/// seed (which fans onto every per-cluster `programs[]` entry as a
/// self-describing distribution overlay the aggregator filters by),
/// and the `feira app graph` per-Aplicacao print line's paired
/// `spec.placement.estrategia()` + `spec.placement.clusters()` field-
/// then-inner-accessor chains (which drive the human-readable
/// distribution summary of the typed Aplicacao view) — three open-
/// coded outer-field accesses that expressed no compile-time link
/// back to the typed slot at the [`AplicacaoSpec`] altitude. A future
/// extension of the `:placement` outer axis to a richer author surface
/// (a per-cluster placement overlay the operator pins through a
/// future `:placement-overrides` slot the MESH-COMPOSITION §V
/// federation roadmap acknowledges, a per-tenant placement-alias
/// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
/// resolves per-CR at admission time, a per-Aplicacao dynamic
/// placement-composite derivation the future M5 adaptive-placement
/// engine computes from a per-cluster load-topology reader, a
/// promotion of the plain [`Placement`] to a richer `{static, dynamic}`
/// partition once Orleans-style virtual-actor dynamic-placement comes
/// into typed scope) would have had to be threaded through all three
/// open-coded copies in lockstep or one consumer would silently
/// disagree with the peers on which placement composite a given
/// Aplicacao resolves to — the validator's per-axis bracket-dispatch
/// seed reading the raw slot while the peer
/// `programs_for_aplicacao` emitter read an operator-resolved slot
/// would silently split the build-time distribution-shape gate from
/// the runtime programs.yaml distribution-annotation gate, a three-
/// consumer split at the validator, the programs.yaml emitter, and
/// the `feira app graph` printer far from the source `caixa.lisp`
/// with no field naming the placement-drift root cause. Lifting the
/// resolution rule to a typed method on the substrate primitive
/// means every downstream consumer of the Aplicacao's per-
/// `:placement` distribution composite surface reaches for exactly
/// one typed dispatch — the resolver's accept-set migrates as a unit
/// on any future axis addition.
///
/// Second `&Composite`-return accessor on the top-level M3 mesh-slot
/// `AplicacaoSpec` type itself — sibling to the seed
/// [`AplicacaoSpec::politicas`] (534dc21) `&MeshPolicy` mesh-policy
/// composite-reference accessor on the peer per-`:politicas` outer-
/// composite axis, and to the paired slice-return accessors
/// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
/// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that close
/// the two `Vec`-carry axes on the outer typed composition view; the
/// outer `:placement` composite-reference axis is the natural pair
/// to the peer `:politicas` composite-reference axis on the two
/// operationally-symmetric M3 mesh slots (`:politicas` carries the
/// how-to-run policy overlay, `:placement` carries the where-to-run
/// distribution composite — every whole-Aplicacao mesh-artifact
/// emitter reads both as one unit). Same "one typed dispatch on the
/// substrate primitive, thin projections at each consumer"
/// discipline the peer per-`:politicas` composite-reference axis
/// already routes through. The one remaining outer-composite axis
/// still unlifted at the time of this lift —
/// [`AplicacaoSpec::entrada`] (`Option<Entrada>` per-Aplicacao
/// external-gateway composite) — inherits this accessor's discipline
/// as the next compounding run migrates its consumers onto the shared
/// reference-return shape, closing the outer-composite altitude on
/// every M3 mesh-slot axis. Named `placement()` to match the storage
/// field's name verbatim and the tatara-lisp author-surface term
/// (`:placement`) the field's own docstring already carries; the
/// accessor's identity maps onto the canonical MESH-COMPOSITION §II
/// vocabulary the slot's docstring already reaches for. Returns
/// `&Placement` (not the owning composite by copy or clone) because
/// every downstream consumer of the placement composite treats it as
/// a read-only per-axis dispatch source — the reference-view is the
/// narrowest borrow that supports every present + roadmapped consumer
/// (per-axis accessor dispatch, serde composite-serialization) without
/// cloning the composite through every consumer's fast path.
#[must_use]
pub const fn placement(&self) -> &Placement {
&self.placement
}
/// Substrate-canonical per-`:entrada` `Entrada` MESH-COMPOSITION
/// per-Aplicacao external-gateway composite optional-composite-
/// reference accessor every per-Aplicacao gateway-block reader
/// keys off — returns the author-declared `:entrada` composite
/// verbatim as an `Option<&Entrada>` reference over the same
/// backing storage the raw `self.entrada.as_ref()` field access
/// borrows from, with `None` naming the internal-only mesh shape
/// (the author-omitted `:entrada` slot the K8s Gateway API v1
/// gateway_routes emitter treats as "emit nothing" and the peer
/// `feira app graph` printer treats as "internal-only mesh").
///
/// The `:entrada` slot carries the M3 mesh-slot per-Aplicacao
/// external-gateway composite — the load-bearing container of
/// every does-this-Aplicacao-expose-a-public-endpoint axis every
/// downstream cluster-artifact emitter fans on (MESH-COMPOSITION
/// §III.4 for the `:host` K8s Gateway API v1 apiserver-validated
/// hostname axis, §III.4 for the `:para` destination-Servico
/// axis, §III.4 for the `:paths` HTTPRoute path-list axis, §III.4
/// for the `:port` L4 backendRefs port axis). Every per-`:entrada`
/// axis threads through a lifted per-slot accessor on the
/// [`Entrada`] type: the [`Entrada::hostname`] (6db982c) K8s
/// Gateway-API `Listener.hostname` scalar accessor, the paired
/// [`Entrada::hostnames`] (`&HTTPRoute.spec.hostnames`)
/// singleton-list resolver, the [`Entrada::destination`] (821a80e)
/// backendRefs destination-Servico scalar accessor, the
/// [`Entrada::resolved_paths`] path-fallback resolver, and the
/// [`Entrada::port`] (9f9becd) Gateway-API-mesh L4 listener-port
/// scalar accessor. Every downstream consumer that reaches for
/// an entrada axis first passes through this outer accessor onto
/// the composite and then dispatches onto the per-axis accessor
/// — the two-level dispatch means every per-`:entrada` reader
/// now routes through a typed dispatch on the substrate primitive
/// at both altitudes.
///
/// Prior to this lift the `.entrada` `Option<Entrada>` composite
/// was accessed inline at four production sites — the
/// [`AplicacaoSpec::validate`] per-`:entrada` shape-and-membership
/// gate's `if let Some(e) = &self.entrada { … }` traversal head
/// (which drives every per-axis refusal on the composite: the
/// `validate_entrada_para` DNS-1123 shape gate on `e.para`, the
/// `EntradaMemberMissing` membership lookup against the
/// `:membros` accept-set, the `EmptyEntradaHost` refusal, the
/// `validate_entrada_host` K8s Gateway API v1 apiserver-shape
/// gate on `e.host`, and the `validate_entrada_path` HTTPRoute
/// per-path shape gate on each entry of `e.paths`), the
/// [`AplicacaoSpec::port_for_destination`] per-Aplicacao L4-port
/// fallback resolver's `self.entrada.as_ref().filter(…).map_or(…)`
/// composite-projection seed (which drives the destination-
/// facing `Entrada::port` lookup every per-Aplicacao HTTPRoute
/// backendRefs port emitter fans on), the
/// [`caixa_mesh::gateway_routes`] per-Aplicacao K8s Gateway API
/// v1 Gateway + HTTPRoute emitter's `spec.entrada.as_ref()`
/// early-return seed (which drives the "no `:entrada` ⇒ no
/// external artifacts" partition on the whole-Aplicacao Gateway-
/// API emitter's fan-out), and the `feira app graph` per-
/// Aplicacao print line's `if let Some(e) = &spec.entrada`
/// external-gateway summary emitter (which drives the human-
/// readable `entrada: host → para (paths=…, port=…)` /
/// `entrada: (internal-only mesh)` partition on the typed
/// Aplicacao view) — four open-coded outer-field accesses that
/// expressed no compile-time link back to the typed slot at the
/// [`AplicacaoSpec`] altitude. A future extension of the
/// `:entrada` outer axis to a richer author surface (a
/// multi-`:entrada` list the M4 CR materializer resolves per-CR
/// at admission time so an Aplicacao can expose a public-web +
/// admin-web pair, a per-cluster `:entrada-overrides` slot the
/// MESH-COMPOSITION §V federation roadmap acknowledges so an
/// operator can pin a per-cluster hostname override without
/// re-authoring the `caixa.lisp`, a promotion of the plain
/// `Option<Entrada>` to a richer `{single, multi}` partition once
/// the multi-`:entrada` roadmap lands) would have had to be
/// threaded through all four open-coded copies in lockstep or one
/// consumer would silently disagree with the peers on which
/// entrada composite a given Aplicacao resolves to — the
/// validator's per-axis bracket-dispatch seed reading the raw
/// slot while the peer `gateway_routes` emitter read an
/// operator-resolved slot would silently split the build-time
/// gateway-shape gate from the runtime Gateway + HTTPRoute
/// emission gate, a four-consumer split at the validator, the
/// `port_for_destination` L4-port resolver, the `gateway_routes`
/// emitter, and the `feira app graph` printer far from the
/// source `caixa.lisp` with no field naming the entrada-drift
/// root cause. Lifting the resolution rule to a typed method on
/// the substrate primitive means every downstream consumer of
/// the Aplicacao's per-`:entrada` external-gateway composite
/// surface reaches for exactly one typed dispatch — the
/// resolver's accept-set migrates as a unit on any future axis
/// addition.
///
/// Third and final `&Composite`-return accessor on the top-level
/// M3 mesh-slot `AplicacaoSpec` type itself — closes the last
/// unlifted outer-composite axis on the outer typed composition
/// view, sibling to the seed [`AplicacaoSpec::politicas`]
/// (534dc21) `&MeshPolicy` mesh-policy composite-reference
/// accessor on the per-`:politicas` outer-composite axis and to
/// the [`AplicacaoSpec::placement`] (9abb8f0) `&Placement`
/// distribution-composite composite-reference accessor on the
/// per-`:placement` outer-composite axis; extends the outer-
/// composite reference-return discipline the two peers already
/// route through onto the last unlifted per-`AplicacaoSpec`
/// outer-composite axis. The `:entrada` outer-composite axis is
/// the natural pair to the two peer outer-composite axes on the
/// three operationally-symmetric M3 mesh-slot outer composites
/// (`:politicas` carries the how-to-run policy overlay,
/// `:placement` carries the where-to-run distribution composite,
/// `:entrada` carries the who-can-reach-it external-gateway
/// composite — every whole-Aplicacao mesh-artifact emitter reads
/// all three as one unit). Same "one typed dispatch on the
/// substrate primitive, thin projections at each consumer"
/// discipline the peer outer-composite axes already route through.
/// Named `entrada()` to match the storage field's name verbatim
/// and the tatara-lisp author-surface term (`:entrada`) the
/// field's own docstring already carries; the accessor's
/// identity maps onto the canonical MESH-COMPOSITION §III.4
/// vocabulary the slot's docstring already reaches for. Returns
/// `Option<&Entrada>` (not the owning composite by copy or
/// clone) because every downstream consumer of the entrada
/// composite treats it as a read-only per-axis dispatch source
/// — the reference-view is the narrowest borrow that supports
/// every present + roadmapped consumer (per-axis accessor
/// dispatch, `.as_ref().filter(…).map_or(…)` per-destination
/// port-fallback projection, early-return partition on the
/// `None` arm) without cloning the composite through every
/// consumer's fast path. The `Option` half of the return-type
/// preserves the load-bearing "author-omitted `:entrada` ⇒
/// internal-only mesh" partition (not a default composite the
/// downstream must reject on emptiness) — the accessor projects
/// the raw `Option<Entrada>` slot's presence bit through the
/// reference-return unchanged.
#[must_use]
pub const fn entrada(&self) -> Option<&Entrada> {
self.entrada.as_ref()
}
/// Validate the typed shape:
/// - `:membros` is non-empty; every entry has a non-empty `:caixa`
/// and a non-empty `:versao`; no two entries share the same
/// `:caixa` (MESH-COMPOSITION §III.1 — the graph nodes are a set,
/// not a multiset)
/// - every `:contratos` :de + :para must be in `:membros`
/// - no `:contratos` edge is a self-edge (`:de == :para`) — a
/// contract is an inter-Servico edge, so a Servico contracting
/// with itself is a build error under every WIT shape
/// (MESH-COMPOSITION §III.1)
/// - no two `:contratos` entries agree on
/// `(de, para, wit, endpoint, subject, slot)` — the typed-graph
/// edges are a set, not a multiset (peer of the `:membros` /
/// `:placement :clusters` / `:entrada :paths` duplicate gates)
/// - `:entrada :para` must be in `:membros`
/// - `:placement Sharded` must declare `:shard-key` (non-empty);
/// `:placement Replicated`/`SingleNode` must NOT declare
/// `:shard-key` — only the hash-keyed Akka-cluster-sharding axis
/// consumes it (MESH-COMPOSITION §II.4), and the typed partition
/// between strategy and shard-key is symmetric: every validated
/// `Placement` has `shard_key.is_some()` iff `estrategia ==
/// Sharded`
/// - every `:placement` strategy must declare ≥1 `:clusters` entry —
/// `Replicated`/`SingleNode` need hosting clusters, `Sharded` needs
/// the shard pool (MESH-COMPOSITION §III.1)
/// - every `:clusters` entry is non-empty and unique
/// - `:placement :affinity`, when set, is non-empty
/// - the synchronous-`:contratos` subgraph is acyclic
/// (MESH-COMPOSITION §III.3)
/// - every declared `:politicas` value is operationally meaningful
/// (zero timeout, zero retries, zero breaker thresholds, zero rate
/// limit are all build errors — MESH-COMPOSITION §V CSE invariants;
/// omit the field instead to express "no policy on this axis")
pub fn validate(&self) -> Result<(), AplicacaoError> {
self.validate_membros()?;
// `:contratos` per-slot gate — folds both structural axes on the
// slot into one substrate primitive: the per-entry cascade (shape
// + membership + self-loop + `:wit` emptiness + WIT-shape ↔
// target + whole-edge dedup) and the cross-edge sync-cycle axis
// ([`AplicacaoSpec::detect_sync_cycles`], MESH-COMPOSITION §III.3
// — pub-sub edges excluded, "acyclic by construction"). Same
// fold-per-axis-plus-cross-axis discipline the sibling
// [`AplicacaoSpec::validate_politicas`] per-slot gate carries via
// [`MeshPolicy::validate`] (f03a154 / 90a6f87), extended here
// onto `:contratos` so every future consumer of the slot (the M4
// admission webhook re-checking `:contratos` after a per-edge
// patch, the per-edge policy resolver MESH-COMPOSITION §III.2 #3
// acknowledges) reaches *both* structural axes through one call.
self.validate_contratos()?;
self.validate_entrada()?;
self.validate_placement()?;
self.validate_politicas()?;
Ok(())
}
/// The `:membros` graph-node name set — the membership oracle every
/// per-Aplicacao name-reference axis resolves against.
///
/// Three per-Aplicacao axes carry a Servico-name *reference* rather
/// than a Servico-name *declaration*: `:contratos :de`, `:contratos
/// :para`, and `:entrada :para`. Each must resolve to a declared
/// `:membros :caixa` (MESH-COMPOSITION §III.1 — the typed edges and
/// the external gateway both address graph nodes, so a reference to
/// a node the graph does not contain is a build error). All three
/// resolve against *this* set, so the set's construction is the one
/// shared substrate primitive underneath the whole reference-
/// resolution surface.
///
/// Lifted out of [`AplicacaoSpec::validate`]'s inline
/// `self.membros().iter().map(Membro::nome).collect()` builder so
/// the two per-slot gates that consume it — the per-`:contratos`
/// membership arms still inline at `validate` and the lifted
/// [`AplicacaoSpec::validate_entrada`] below — reach the same
/// oracle through one dispatch rather than each open-coding the
/// projection. Every future consumer on the same axis (the M4
/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
/// reference resolver, the per-`:contratos`-edge `:politicas`
/// override MESH-COMPOSITION §III.2 #3 acknowledges — which
/// resolves an edge's endpoints against the same membership set
/// before it can key a per-edge policy off them) inherits the
/// projection through the same call, so a future rebrand of the
/// node-identity axis (a namespace-qualified member name the CR
/// materializer applies per-CR, the `:membros :nome-suffix`
/// overlay §III.2 acknowledges) lands at exactly one place rather
/// than at every reference-resolution site in lockstep. Peer of
/// the sibling per-slot substrate primitives
/// [`MeshPolicy::validate`] (f03a154) and
/// [`WitContract::identity`] on their own axes.
fn membro_names(&self) -> std::collections::HashSet<&str> {
self.membros().iter().map(Membro::nome).collect()
}
/// Reject `:contratos` entries whose endpoints are malformed,
/// reference a Servico outside the graph, self-loop, carry an
/// empty `:wit` shape, duplicate a prior entry on the six-axis
/// identity key, or close a synchronous-edge cycle in the
/// resulting typed graph.
///
/// The `:contratos` slot is the typed inter-Servico edge set
/// (MESH-COMPOSITION §III.1): each entry is a WIT-typed directed
/// edge whose `:de` / `:para` reference two distinct members and
/// whose `:wit` picks the payload shape the paired L4/L7 renderer
/// (caixa-mesh's per-`(:de, :para)` `CiliumNetworkPolicy` +
/// per-HTTP `HTTPRoute`) fans out on.
///
/// Two structural axes on the slot are folded into this per-slot
/// gate: the per-entry axis (six per-edge arms, listed below) and
/// the cross-edge synchronous-cycle axis (MESH-COMPOSITION §III.3,
/// dispatched to [`AplicacaoSpec::detect_sync_cycles`] after the
/// per-entry cascade). Same
/// per-axis-plus-cross-axis-fold-into-one-per-slot-gate discipline
/// the sibling [`AplicacaoSpec::validate_politicas`] per-slot gate
/// carries via [`MeshPolicy::validate`] (f03a154 / 90a6f87) on the
/// `:politicas` slot, extended here onto `:contratos`.
///
/// Six per-entry axes are gated first, in the canonical
/// edge-direction order the paired diagnostics already encode
/// (per-arm value shape before graph-membership lookup; structural
/// self-edge before payload-shape target dispatch; whole-edge dedup
/// last):
///
/// - per-arm `:de` / `:para` value shape via
/// [`validate_contrato_caixa`] (empty + DNS-1123 grammar),
/// `:de` before `:para`;
/// - per-edge graph-membership against the
/// [`AplicacaoSpec::membro_names`] oracle via
/// [`WitContract::require_endpoints_in`] (folds the twin
/// `:de` / `:para` arms onto one substrate-primitive
/// dispatch), `:de` before `:para`;
/// - structural self-edge via [`WitContract::is_self_loop`]
/// (caller-equals-callee under any WIT shape);
/// - `:wit` emptiness ([`AplicacaoError::EmptyWit`]);
/// - WIT shape ↔ target consistency via [`WitContract::target`]
/// (the four `WitTarget` arms — `Http` / `PubSub` / `Store` /
/// `Capability` — each carry their own required payload field);
/// - six-axis whole-edge dedup via [`WitContract::identity`]
/// ([`ContratoIdentity`]'s `(de, para, wit, endpoint, subject,
/// slot)` tuple).
///
/// One cross-edge axis is gated last, after the per-entry cascade
/// completes cleanly:
///
/// - synchronous-edge cycle detection via
/// [`AplicacaoSpec::detect_sync_cycles`] (iterative DFS with
/// three-coloring over the sync-only subgraph, pub-sub edges
/// skipped per MESH-COMPOSITION §III.3 —
/// [`AplicacaoError::ContratoCycle`]). Runs *after* the
/// per-entry cascade so a per-entry defect surfaces through its
/// narrower shape/membership/dedup arm before the cross-edge
/// cycle diagnostic, matching the pre-fold `validate`-side
/// dispatch ordering (`validate_contratos()? →
/// detect_sync_cycles()?`).
///
/// Lifted out of [`AplicacaoSpec::validate`]'s inline `let mut
/// seen_contracts = …; for c in self.contratos() { … }` block onto
/// a named per-slot gate, closing the last unlifted per-slot gate
/// on the M3 mesh-slot family. Every peer slot already carries the
/// shape ([`AplicacaoSpec::validate_membros`],
/// [`AplicacaoSpec::validate_entrada`],
/// [`AplicacaoSpec::validate_placement`],
/// [`AplicacaoSpec::validate_politicas`]).
///
/// Self-contained on `&self` — it resolves its own membership
/// oracle through [`AplicacaoSpec::membro_names`] rather than
/// borrowing one threaded down from `validate`, and runs its own
/// cross-edge cycle probe rather than deferring the axis to an
/// outer dispatch — so a future consumer that re-validates *one*
/// slot against a mutated spec (the M4 admission webhook
/// re-checking `:contratos` after a per-`(:de, :para)` edge patch
/// without re-walking `:membros` / `:entrada` / `:placement` /
/// `:politicas`, or the M4 per-edge policy resolver
/// MESH-COMPOSITION §III.2 #3 acknowledges — which resolves an
/// effective per-edge [`MeshPolicy`] and must re-check the edge's
/// own identity closure *and* the sync-cycle invariant before it
/// can key a per-edge override off the endpoint tuple) reaches
/// *both* structural axes on the slot through one call, exactly as
/// [`AplicacaoSpec::validate_politicas`] reaches both per-axis and
/// cross-axis surfaces on `:politicas` through
/// [`MeshPolicy::validate`].
fn validate_contratos(&self) -> Result<(), AplicacaoError> {
let names = self.membro_names();
// Identity key for the typed-edge duplicate gate below: every
// field that distinguishes one contract from another. Two
// entries that agree on all six are *the same edge declared
// twice*, the typed-graph analogue of duplicate `:membros` /
// `:placement :clusters` / `:entrada :paths` entries (which
// are already build errors at this layer). Rejecting it at the
// validate gate closes a renderer-side footgun: caixa-mesh's
// `cilium_network_policies` keys each emitted policy by
// `<aplicacao>-<de>-to-<para>`, so two contracts with identical
// (de, para) and identical payload would land as two K8s
// objects with colliding `metadata.name`, rejected at apply
// time far from the source caixa.lisp.
let mut seen_contracts: std::collections::HashSet<ContratoIdentity<'_>> =
std::collections::HashSet::new();
for c in self.contratos() {
// Per-axis value-shape gate on every `:contratos` name
// reference, before any graph-membership lookup. Empty +
// DNS-1123-malformed `:de`/`:para` values silently fell
// through to `ContratoMemberMissing` at the lookup arm
// because every `:membros :caixa` is shape-validated
// (3f9d7a0), so the `names` set structurally cannot contain
// an empty / malformed string and the membership-lookup
// diagnostic always misframed the root cause as
// "this caixa is not in `:membros`". The shape gate runs
// ahead of the lookup so structurally-impossible-to-match
// inputs route through the narrower self-locating
// diagnostic, preserving the legitimate "well-shaped
// phantom reference" arm. `:de` runs before `:para` per
// the canonical edge-direction order the existing
// membership lookup, self-edge check, target dispatch,
// and diagnostic strings already use.
validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_DE, c.source())?;
validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_PARA, c.destination())?;
// Per-edge graph-membership gate on the twin `:de` / `:para`
// arms — folded onto the substrate-primitive dispatch
// [`WitContract::require_endpoints_in`] so every per-edge
// consumer of the endpoint-resolution axis (this per-slot
// gate at build time, the M4 admission webhook re-checking
// one edge after a per-`(:de, :para)` patch, the per-edge
// `:politicas` override MESH-COMPOSITION §III.2 #3
// acknowledges) reaches the axis through one call rather
// than re-inlining the twin `if !names.contains(...)`
// cascade. `:de` fires before `:para` inside the primitive,
// preserving byte-equal diagnostic ordering with the
// pre-lift inline cascade.
c.require_endpoints_in(&names)?;
// A `:contratos` entry is an *inter*-Servico contract
// (MESH-COMPOSITION §III.1 — "Servico A calls Servico B"): a
// typed edge between two distinct graph nodes. An edge whose
// `:de` equals its `:para` is a Servico contracting with
// itself — a degenerate edge under every WIT shape. Firing
// the gate before the `:wit`/`target()` shape checks means
// the structural "this edge can't exist" error precedes the
// narrower payload-shape diagnostics, and shape-agnostically
// covers all four `WitTarget` arms (HTTP / Store / Capability
// / PubSub) at one point. Peer of the duplicate-`:contratos`
// / duplicate-`:membros` set gates: both reject a structurally
// ill-formed graph at the typed surface, before the renderer
// emits a K8s object that fails or no-ops far from the source
// caixa.lisp.
if c.is_self_loop() {
return Err(AplicacaoError::contrato_self_loop(c));
}
if c.world_ref().is_empty() {
return Err(AplicacaoError::empty_wit(c.edge_pair()));
}
// Shape ↔ target consistency — surfaces "HTTP wit without
// :endpoint", "NATS wit with :endpoint set", etc. as named
// build errors instead of silent renderer drops. Threaded
// through the duplicate-edge diagnostic below (via
// [`WitTarget::label`]) so the "which typed target arm did
// the duplicate carry" question is answered by the typed
// enum's variant discriminator, not by re-probing the raw
// `Option<String>` payload fields.
let target_view = c.target()?;
// Contract identity: (de, para, wit, endpoint, subject, slot).
// Two contracts that match on all six are the same typed edge
// declared twice — author error, not a legitimate variant of
// "same caller-callee pair, different payload" (e.g.
// cart→catalog at /products vs /search), which keeps distinct
// identity keys via the differing endpoint payloads.
let key = c.identity();
crate::render::insert_first_seen(&mut seen_contracts, key, || {
AplicacaoError::contrato_duplicate(c, &target_view)
})?;
}
// Cross-edge cycle axis on the `:contratos` slot — folded into
// the per-slot gate so the two structural axes on `:contratos`
// (per-entry shape + membership + dedup above; cross-edge sync-
// cycle detection here) reach every consumer through one call.
// Same discipline the sibling per-slot compound gate
// [`MeshPolicy::validate`] (f03a154) established on `:politicas`
// — one named per-slot gate that folds *both* per-axis and
// cross-axis surfaces on the same slot onto one substrate
// primitive — extended here onto `:contratos`, closing the last
// per-slot-axis-family that lived split across `validate` (the
// per-entry `validate_contratos` half here and the cross-edge
// `detect_sync_cycles` call the sibling below at `validate`
// dispatched separately).
//
// Runs after the per-entry cascade so a per-entry defect (empty
// arm, unknown endpoint, self-loop, empty `:wit`, WIT-shape ↔
// target inconsistency, whole-edge duplicate) surfaces first
// through its narrower [`AplicacaoError`] arm before the cross-
// edge cycle diagnostic. This matches the pre-lift ordering the
// `validate`-side dispatch used verbatim (`self.validate_contratos()?
// → self.detect_sync_cycles()?`) — the cycle detector was
// already the second `:contratos`-axis gate in the dispatch,
// just at the outer altitude; the fold moves it under the same
// named per-slot gate without reshaping the diagnostic order.
self.detect_sync_cycles()?;
Ok(())
}
/// Reject `:entrada` values that are operationally meaningless,
/// structurally malformed, or reference a Servico outside the
/// graph.
///
/// The `:entrada` slot is the Aplicacao's single external ingress
/// (MESH-COMPOSITION §III.1): `:host` + `:port` become a K8s
/// Gateway API v1 `Listener`, `:paths` become the paired
/// `HTTPRoute`'s `matches[].path.value` entries, and `:para` names
/// the member the route forwards to. Omitting the slot entirely is
/// the internal-only-mesh partition — an Aplicacao with no external
/// surface — so the `None` arm is a clean pass, not a refusal.
///
/// Five axes are gated here, in the canonical order the paired
/// diagnostics already encode (reference-resolution before value
/// shape, per-axis emptiness before per-axis grammar):
///
/// - `:para` — DNS-1123 value shape, then membership against the
/// [`AplicacaoSpec::membro_names`] oracle;
/// - `:host` — emptiness, then the Gateway API hostname grammar;
/// - `:port` — the [`SERVICO_PORT_MIN`] structural floor;
/// - `:paths` — per-entry emptiness, leading-`/`, the Gateway API
/// path grammar, and set-not-multiset uniqueness.
///
/// Lifted out of [`AplicacaoSpec::validate`]'s inline `if let
/// Some(e) = self.entrada() { … }` block onto a named per-slot
/// gate, the shape the three peer M3 mesh slots already carry
/// ([`AplicacaoSpec::validate_membros`],
/// [`AplicacaoSpec::validate_placement`],
/// [`AplicacaoSpec::validate_politicas`]). Self-contained on
/// `&self` — it resolves its own membership oracle through
/// [`AplicacaoSpec::membro_names`] rather than borrowing one
/// threaded down from `validate` — so a future consumer that
/// re-validates *one* slot against a mutated spec (the M4 admission
/// webhook re-checking `:entrada` after a gateway-host patch
/// without re-walking the whole `:contratos` graph) reaches the
/// axis through one call, exactly as `detect_sync_cycles` is
/// already self-contained for the M4 per-edge policy resolver.
fn validate_entrada(&self) -> Result<(), AplicacaoError> {
let names = self.membro_names();
if let Some(e) = self.entrada() {
// Route the per-`:entrada` composite-reference read
// through the lifted [`AplicacaoSpec::entrada`] accessor
// rather than the raw `&self.entrada` field access — the
// shape-and-membership gate's traversal head is now the
// canonical read-side surface every per-Aplicacao entrada
// consumer routes through, closing the fourth of four
// open-coded outer-field accesses on the per-`:entrada`
// outer-composite axis.
//
// Shape gate on `:entrada :para` runs ahead of the
// membership lookup. Every `:membros :caixa` past
// `validate_membro_caixa` is a valid DNS-1123 label
// (3f9d7a0), so the `names` set structurally cannot
// contain an empty / malformed string and the membership-
// lookup diagnostic always misframed the root cause as
// "this caixa is not in `:membros`". The shape gate
// routes structurally-impossible-to-match inputs through
// the narrower self-locating diagnostic, preserving the
// legitimate "well-shaped phantom reference" arm — the
// same trajectory the peer `:membros :caixa` (3f9d7a0),
// `:placement :clusters` (6c8c00b), and `:contratos :de`
// / `:para` (8d5af6b) axes already follow. This closes
// the fourth and last Aplicacao-level Servico-name
// reference axis on the canonical DNS-1123 floor.
// Route the per-`:entrada :para` byte-string reads through
// the lifted [`Entrada::destination`] accessor rather than
// the raw `e.para` field access — the three
// per-`AplicacaoSpec::validate` `:entrada :para` consumers
// (shape-gate `validate_entrada_para` arg, membership
// lookup, `EntradaMemberMissing` diagnostic carry) now key
// off exactly one typed dispatch on the substrate
// primitive, closing the last unlifted per-`:entrada :para`
// raw-field-access axis on the M3 mesh-slot validator.
// The `.destination().to_string()` at the diagnostic site
// is byte-identical to `.para.clone()` — pinned by the
// sibling `destination_returns_entrada_para_byte_equal` +
// `destination_borrows_from_entrada_para_storage` accessor
// tests — so a future rebrand of the underlying `:para`
// storage (a lift from `String` to a typed
// `ServicoName(String)` newtype, a per-Aplicacao interning
// arena the M4 CR materializer authors, a
// `smol_str::SmolStr` inline-buffer swap) flows through
// the accessor's one body without a coordinated
// per-consumer rewrite across the M3 mesh validator.
validate_entrada_para(e.destination())?;
if !names.contains(e.destination()) {
return Err(AplicacaoError::entrada_member_missing(e));
}
// Route the per-`:entrada :host` byte-string reads through
// the lifted [`Entrada::hostname`] accessor rather than
// the raw `e.host` field access — the emptiness gate and
// the shape-gate `validate_entrada_host` arg now key off
// exactly one typed dispatch on the substrate primitive,
// closing the last unlifted per-`:entrada :host` raw-
// field-access axis on the M3 mesh-slot validator. Peer
// of the sibling per-`:entrada :para` convergence above
// and pinned by the existing
// `hostname_returns_entrada_host_byte_equal` +
// `hostnames_returns_singleton_of_hostname_accessor`
// accessor tests, so any future
// Gateway-API-shaped host renormalization (a wildcard-
// label lift, a trailing-`.` FQDN substitution, an IDNA
// Punycode round-trip the SNI fan-out overlay authors)
// flows through the accessor's one body without a
// coordinated per-consumer rewrite across the M3 mesh
// validator.
if e.hostname().is_empty() {
return Err(AplicacaoError::EmptyEntradaHost);
}
// The `:host` lands verbatim as a K8s Gateway API v1
// `Listener.hostname` *and* `HTTPRoute.spec.hostnames[0]` —
// both apiserver-validated against the same restrictive
// pattern: lowercase RFC 1123 DNS subdomain, optional
// single leading wildcard label (`*.`), max length 253,
// per-label max length 63, no IP literals, no scheme,
// no port. Until this gate landed `validate()` only
// refused the empty string (`EmptyEntradaHost`); a
// structurally invalid hostname (`"https://example.com"`,
// `"checkout.quero.cloud:8080"`, `"1.2.3.4"`,
// `"_underscored.example.com"`, `"FOO.example.com"`,
// `"checkout.quero.cloud."`) silently passed validate
// and the apiserver `field is invalid` error surfaced at
// `kubectl apply` time, far from the source caixa.lisp.
// Lifting the gate to caixa-build time mirrors the
// `:entrada :paths` value-shape trajectory (eb3456d) and
// closes the last unstructured `:entrada` axis.
validate_entrada_host(e.hostname())?;
// Structural-floor gate on `:entrada :port`: every
// validated `Entrada::port` past this gate lies in
// `SERVICO_PORT_MIN..=u16::MAX` (the `u16` field's natural
// type-inferred ceiling closes the top edge, so no companion
// upper-cap arm is needed here — unlike the peer capped-
// `u32` `:politicas` / `:supervisor` / `:limits` axes whose
// `require_positive_bounded_u32` bracket covers both edges).
// Routes through the lifted [`SERVICO_PORT_MIN`] canonical
// accept-set-floor const rather than the prior inline
// `if e.port == 0` byte-check so a future rebrand of the
// accept-set floor (a hypothetical unprivileged-only
// migration lifting the floor to `1024`, a per-cluster
// scoping the operator pins through a future
// `:placement :port-floor` slot as the M4 typed-slot
// trajectory adds it, the future
// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
// per-Aplicacao gateway resolver reaching for the same
// floor) is a one-line edit on the canonical
// [`SERVICO_PORT_MIN`] declaration, not a coordinated
// rewrite across the emit site + the pin test + every
// future per-target renderer the substrate adds.
if e.port() < SERVICO_PORT_MIN {
return Err(AplicacaoError::EntradaPortZero);
}
// Each `:entrada :paths` entry becomes a K8s Gateway API
// HTTPRoute `matches[].path.value`. The Gateway API rejects
// values that don't start with `/` for `type: PathPrefix`,
// and an empty value is meaningless. Surface those as build
// errors (MESH-COMPOSITION §III.3) rather than apply-time
// failures. Empty `:paths` itself is fine — caixa-mesh
// falls back to a single `/` catch-all.
let mut seen = std::collections::HashSet::new();
// Route the per-entry value-shape gate's traversal head
// through the lifted [`Entrada::paths`] slice accessor
// rather than the raw `&e.paths` field access — the
// per-Aplicacao `:entrada :paths` validate loop now keys
// off the canonical raw-slot surface every downstream
// per-`:entrada` path-list consumer (the sibling
// [`Entrada::resolved_paths`] fallback-applying resolver
// internal reads, `feira app graph`'s per-Aplicacao entrada
// summary line's `{:?}` Debug print) routes through, so any
// future rebrand on the typed slot's raw-slot reader lands
// at exactly one place. Same convergence discipline as the
// sibling [`Placement::clusters`] (a6e18d7) reader-site
// convergences on the peer M3 mesh-slot `Vec<String>`-carry
// axis.
for p in e.paths() {
if p.is_empty() {
return Err(AplicacaoError::EntradaPathEmpty);
}
if !p.starts_with('/') {
return Err(AplicacaoError::entrada_path_not_absolute(p));
}
// Per-entry value-shape gate: the path lands verbatim
// as a K8s Gateway API HTTPRoute `matches[].path.value`
// (caixa-mesh/src/lib.rs:498), apiserver-validated
// against `maxLength: 1024` + the Gateway API webhook's
// path-grammar rules (no `//`, no `/./`, no `/../`, no
// query/fragment separators, no whitespace, no control
// characters, no non-ASCII bytes). Until this gate
// landed `validate` only refused the empty string and
// missing-leading-slash (eb3456d); a structurally
// invalid path (`"/api?q=1"`, `"/api#frag"`,
// `"/api bar"`, `"/api/../etc"`, `"/api//cart"`, a
// 1025-byte URL-shaped slug) silently passed validate
// and the failure surfaced at `kubectl apply` time as
// a Gateway API webhook rejection, far from the source
// caixa.lisp, with no field naming the offending
// `:paths` entry. Lifting the gate to caixa-build time
// mirrors the `:entrada :host` value-shape trajectory
// (c7d05ec) on the sibling axis — every author surface
// that emits a Gateway API field now matches the
// apiserver's accepted set at validate time.
validate_entrada_path(p)?;
crate::render::insert_first_seen(&mut seen, p.as_str(), || {
AplicacaoError::entrada_path_duplicate(p)
})?;
}
}
Ok(())
}
/// Reject `:membros` values that are operationally meaningless. The
/// `:membros` slot is the graph node set (MESH-COMPOSITION §III.1):
/// every entry names a Servico that participates in the Aplicacao,
/// and the rendered programs.yaml fan-out emits one entry per
/// `:membros`. Three authoring footguns are closed here:
///
/// - `:caixa ""` — caixa-mesh's `programs_for_aplicacao` would emit
/// a `programs:` entry whose `name:` is the empty string, which
/// downstream `lareira-fleet-programs` rejects at template time
/// with a non-localized error;
/// - `:versao ""` — caixa-resolver's lacre pipeline can't resolve
/// an empty semver constraint, so the failure surfaces far from
/// the source caixa.lisp;
/// - duplicate `:caixa` names — two entries with the same name
/// produce duplicate programs.yaml entries (one silently
/// overwrites the other in the cluster's HelmRelease values), and
/// contract membership lookups against `:contratos` collapse the
/// two onto one node, masking authoring mistakes.
///
/// Same value-shape discipline as `:placement :clusters` (where empty
/// + duplicate cluster names are rejected) and `:entrada :paths`
/// (where empty + duplicate path entries are rejected). Lifting these
/// invariants to the typed surface mirrors the MESH-COMPOSITION
/// §III.3 promise that the `:membros` set — the load-bearing identity
/// of the application graph — is well-formed by construction.
fn validate_membros(&self) -> Result<(), AplicacaoError> {
if self.membros().is_empty() {
return Err(AplicacaoError::NoMembros);
}
let mut seen = std::collections::HashSet::new();
for m in self.membros() {
// Every emitted cluster artifact's `metadata.name` derives
// from a `:membros :caixa` value verbatim — the rendered
// programs.yaml entry's `name:` (caixa-mesh/src/lib.rs:133),
// the [`crate::LABEL_PROGRAM`] label value on every CNP
// endpointSelector / fromEndpoints (caixa-mesh/src/lib.rs:263,
// 272), the composed `CiliumNetworkPolicy` `metadata.name`
// (caixa-mesh/src/lib.rs:250), and the Gateway API HTTPRoute
// `metadata.name` when the member is the `:entrada :para`
// target (caixa-mesh/src/lib.rs:423). Each apiserver-side
// schema enforces the DNS-1123 label rule on admission;
// a structurally invalid member name (`"Cart"`, `"my_cart"`,
// `"my.cart"`, `"-cart"`, `"cart-"`, the >63-byte UUID-shaped
// mistaken-identity slug) silently passes the prior empty-/
// duplicate-only gate and the failure surfaces at `kubectl
// apply` time as a `metadata.name: Invalid value` rejection,
// far from the source caixa.lisp, with no field naming the
// offending `:membros` entry. Lifting the gate to caixa-build
// time mirrors the `:entrada :host` value-shape trajectory
// (c7d05ec) on the peer axis — every author surface that
// emits a K8s name now matches the apiserver's accepted set
// at validate time.
validate_membro_caixa(m.nome())?;
// The author surface for `:versao` is the same Cargo-shaped
// semver requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`,
// `"*"`) every `:deps` entry carries — and the lacre pipeline
// resolves both axes through the same
// [`crate::version::parse_requirement`] entry-point. The
// shared [`crate::render::require_valid_versao_requirement`]
// helper brackets the empty-first + parse cascade both peer
// axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
// [`crate::SupervisorSpec::validate`] on `:children :versao`)
// route through, so drift between the three axes' accepted
// requirement sets is structurally impossible and the parse-
// side no-op the empty-first arm closes (semver's empty
// parse yields an implicit `*`) lives in exactly one
// predicate.
crate::render::require_valid_versao_requirement(
m.versao_requirement(),
|| AplicacaoError::membro_versao_empty(m.nome()),
|reason| {
AplicacaoError::membro_versao_invalid(m.nome(), m.versao_requirement(), reason)
},
)?;
crate::render::insert_first_seen(&mut seen, m.nome(), || {
AplicacaoError::membro_duplicate(m.nome())
})?;
}
Ok(())
}
/// Reject `:placement` values that are operationally meaningless or
/// internally contradictory. Each strategy variant has the same
/// invariants on `:clusters` (non-empty list, non-empty unique
/// entries) — the §III.1 author surface is uniform on this axis,
/// even though the *meaning* of the list differs by strategy
/// (`Replicated`/`SingleNode` host the app; `Sharded` defines the
/// shard pool).
///
/// Empty cluster names or a `Some("")` `:shard-key`/`:affinity`
/// are the same authoring footgun closed for `:politicas` zero
/// values and `:entrada` empty paths: the field is *declared* but
/// carries no meaning, so downstream renderers either skip it
/// silently (cluster-fanout drops the empty entry, no diagnostic)
/// or apply it literally and fail at admission time. Lifting both
/// to build errors mirrors MESH-COMPOSITION §III.3's "placement
/// violation is a build error" promise.
///
/// `:shard-key` and `:estrategia` are typed-partitioned: the slot
/// is required exactly when `:estrategia Sharded` (hash-keyed
/// distribution, Akka cluster-sharding convention, §II.4) and
/// refused on `:estrategia Replicated`/`SingleNode` (where no
/// hash-keyed routing axis consumes it). The partition closes the
/// "I think I configured sharding" footgun where an author writes
/// `:placement (:estrategia Replicated :shard-key "tenantId")` and
/// the typed slot's value silently vanishes at the renderer layer
/// — every validated `Placement` past this call satisfies
/// `shard_key.is_some() == matches!(estrategia, Sharded)`.
fn validate_placement(&self) -> Result<(), AplicacaoError> {
// Every strategy needs at least one named cluster: `Replicated`
// and `SingleNode` use the list as hosting/takeover candidates
// (Erlang/OTP distributed-app convention — see MESH-COMPOSITION
// §II.1), while `Sharded` uses it as the shard pool
// (Akka cluster-sharding convention — §II.4). An empty list is
// meaningless under any of the three.
//
// Route the paired pre-flight `.is_empty()` refusal probe and
// the per-cluster validate loop's traversal head through the
// lifted [`Placement::clusters`] slice-return accessor rather
// than the raw `self.placement.clusters` field access — the
// two production consumers of the per-`:placement` cluster-
// pool `Vec`-carry now key off exactly one typed dispatch on
// the substrate primitive, so any future rebrand on the axis
// (a per-tenant cluster-pool overlay the operator pins through
// a future `:placement :clusters-overrides` slot, a per-
// Aplicacao dynamic cluster-pool derivation the future M5
// adaptive-placement engine computes from `:affinity` weights)
// migrates as a single caixa-core edit rather than a
// coordinated rewrite of the paired arms — sibling of the
// peer M2 [`crate::SupervisorSpec::children`] (bc92bce) two-
// arm migration on the per-`:supervisor` static-child-list
// `Vec`-carry axis.
//
// Route the per-`:placement` outer-composite reference read
// through the lifted [`AplicacaoSpec::placement`] outer accessor
// rather than the raw `&self.placement` field access — the
// per-axis bracket-dispatch fan-out below (`p.clusters()`,
// `p.estrategia()`, `p.affinity()`, `p.shard_key()` on the
// axis-level lifted accessor family) now routes through the
// substrate-primitive typed dispatch at the outer composition
// altitude, the same shape the peer caixa-mesh
// `programs_for_aplicacao` per-Aplicacao programs.yaml emitter
// and the sibling `feira app graph` per-Aplicacao print line
// now key off after this accessor lift.
let p = self.placement();
if p.clusters().is_empty() {
// Route the per-`:placement` empty-clusters diagnostic
// through the substrate-primitive
// [`AplicacaoError::placement_without_clusters`] ctor rather
// than the pre-lift three-line open-coded
// `AplicacaoError::PlacementWithoutClusters { estrategia:
// p.estrategia() }` struct-literal — folds the sole in-crate
// wire-up on this variant onto one dispatch matching the
// sibling per-`:placement :clusters` dedup /
// per-`:contratos` self-edge / per-`:upgrade-from :from`
// duplicate substrate-primitive-projection ctors on the
// same `AplicacaoError` / `UpgradeError` envelopes.
return Err(AplicacaoError::placement_without_clusters(p));
}
let mut seen = std::collections::HashSet::new();
for c in p.clusters() {
// Per-entry value-shape gate: the cluster name lands in
// every K8s context / `lareira-fleet-programs` aggregator
// filter / future M4 CR materializer's per-cluster axis
// a validated `:clusters` entry passes through, each
// enforcing the DNS-1123 label rule on admission. Same
// typed-shape trajectory as `:membros :caixa` (3f9d7a0)
// on the peer name axis — both axes' validated values
// are guaranteed-accepted by the apiserver without
// re-validation at any downstream renderer or admission
// layer.
validate_placement_cluster(c)?;
crate::render::insert_first_seen(&mut seen, c.as_str(), || {
// Route the per-`:placement :clusters` dedup diagnostic
// through the substrate-primitive
// [`AplicacaoError::placement_cluster_duplicate`] ctor
// rather than the pre-lift three-line open-coded
// `AplicacaoError::PlacementClusterDuplicate { cluster:
// c.clone() }` struct-literal — folds the sole in-crate
// wire-up on this variant onto one dispatch matching the
// sibling per-`:membros :caixa` / per-`:entrada :paths` /
// per-`:politicas <scalar>` single-slot ctor families on
// the same [`AplicacaoError`] envelope.
AplicacaoError::placement_cluster_duplicate(c)
})?;
}
// Route the per-`:placement :affinity` per-hint value-shape
// gate through the typed [`Placement::affinity`] accessor rather
// than the raw `&self.placement.affinity` field access — the
// sole open-coded field-access site on the per-`:placement`
// M3-Adaptive-compression-hint axis the accessor lift now owns.
// The `Some(a)`-bound `a` narrows from `&String` to `&str` under
// the accessor's `Option<&str>` return type;
// [`validate_placement_affinity`]'s `&str` parameter accepts
// the narrower borrow without a re-allocation, so the routing
// change is byte-for-byte in the pass arm and remains
// byte-for-byte in every failure diagnostic
// ([`AplicacaoError::PlacementAffinityInvalid`]'s `affinity:
// String` field is populated inside
// [`validate_placement_affinity`] via the peer `.to_string()`
// path on the same borrowed slice). Peer of the sibling
// `PlacementStrategy::Sharded`-arm `:shard-key` shape-gate
// routing through [`Placement::shard_key`] at the caixa-core
// site above — extends the "read `:placement` optional-scalars
// through the typed accessor" discipline to the second
// `Option<String>`-shape slot on the M3 mesh-slot family.
//
// Per-hint value-shape gate: the `:affinity` value lands
// verbatim in the M3 Adaptive compression overlay
// (caixa-mesh's `placement.affinity` emission) and every
// future M4 placement-engine routing axis keying off the
// hint as a K8s `app.pleme.io/affinity-hint=<value>` label
// selector — each enforces the DNS-1123 label rule on
// admission. Same typed-shape trajectory as `:placement
// :clusters` (6c8c00b) on the sibling slot and the four
// Servico-name reference axes (`:membros :caixa` 3f9d7a0,
// `:placement :clusters` 6c8c00b, `:contratos :de`/`:para`
// 8d5af6b, `:entrada :para` b0e8748) — the fifth typed slot
// on the Aplicacao surface to land on the canonical
// [`crate::render::is_dns_1123_label`] floor.
if let Some(a) = p.affinity() {
validate_placement_affinity(a)?;
}
match p.estrategia() {
// Route the `Sharded`-arm shape-gate cascade through the
// typed [`Placement::shard_key`] accessor rather than the
// raw `&self.placement.shard_key` field access — one of the
// two open-coded field-access sites on the per-`:placement`
// Akka-cluster-sharding-key axis the accessor lift now
// owns. The `Some(k)`-bound `k` narrows from `&String` to
// `&str` under the accessor's `Option<&str>` return type;
// `str::is_empty` and [`validate_placement_shard_key`]'s
// `&str` parameter both accept the narrower borrow without
// a re-allocation.
PlacementStrategy::Sharded => match p.shard_key() {
None => return Err(AplicacaoError::ShardedWithoutKey),
Some(k) if k.is_empty() => return Err(AplicacaoError::ShardedKeyEmpty),
// Per-axis value-shape gate on the Akka-cluster-sharding
// `:shard-key` extractor expression. The shape gate runs
// after the more self-locating `ShardedKeyEmpty` arm so
// a `:shard-key ""` surfaces the narrower empty
// diagnostic first; every non-empty `:shard-key` past
// this call is guaranteed to be a printable-ASCII
// single-token reference the future M4 Akka-style
// cluster-sharding reconciler can hash without
// re-validating at the runtime layer. Mirrors the
// payload-axis shape gates on the peer `:contratos`
// `:endpoint`/`:subject`/`:slot` axes (4f0390b /
// 63e18a0 / c4213a4) — each lifts the runtime parser's
// intersection-floor to a caixa-build-time gate.
Some(k) => validate_placement_shard_key(k)?,
},
// `:shard-key` is the Akka-cluster-sharding axis
// (MESH-COMPOSITION §II.4) — hash-keyed entity distribution
// across the cluster pool. `Replicated` (active-active across
// every named cluster) and `SingleNode` (Erlang/OTP
// distributed-app takeover/failover, §II.1) have no hash-keyed
// routing axis to consume the slot; downstream renderers
// (caixa-mesh's `placement.shardKey` overlay at
// caixa-mesh/src/lib.rs:909, the future M4 Akka-style cluster-
// sharding reconciler) ignore `:shard-key` outside the
// `Sharded` arm by construction. Until this gate landed an
// author who wrote `:placement (:estrategia Replicated
// :shard-key "tenantId")` (an off-by-one strategy typo, a
// copy-paste from a Sharded sibling caixa, the "I think I
// configured sharding" footgun) silently passed validate and
// the typed slot's value vanished at the renderer layer with
// no diagnostic — the canonical "declared-but-inert" footgun
// the empty-:affinity / empty-shard-key / zero-:politicas /
// empty-:contratos-target gates already close on every other
// declare-but-no-opinion axis (2d71a9a / 5dbcfaf / c7c7799).
// Lifting the rejection to a build-time gate closes the
// Sharded ↔ non-Sharded partition over the typed
// `:placement` slot: every validated `Placement` past this
// call has `shard_key.is_some()` iff `estrategia ==
// Sharded`, structurally — the future Akka reconciler can
// reach for `placement.shard_key` knowing it's `Some` exactly
// when the strategy consumes it, without re-deriving the
// partition from inline strategy probes.
PlacementStrategy::Replicated | PlacementStrategy::SingleNode => {
// Route the non-`Sharded`-arm declared-but-inert refusal
// through the typed [`Placement::shard_key`] accessor —
// the second of the two open-coded field-access sites the
// accessor lift now owns. The `Some(k)`-bound `k` narrows
// from `&String` to `&str`; the `AplicacaoError::
// ShardKeyOnNonSharded { shard_key: String }` diagnostic
// materializes the owned `String` via `k.to_string()`
// (peer to the sibling per-Membro `String`-carry sites
// 4127bb6 routed through `m.nome().to_string()` /
// `m.versao_requirement().to_string()`), so the whole
// `Sharded` ↔ non-`Sharded` partition on the
// `:shard-key` axis now flows through the same typed
// dispatch as the sibling `Sharded`-arm shape gate.
if let Some(k) = p.shard_key() {
return Err(AplicacaoError::shard_key_on_non_sharded(p, k));
}
}
}
Ok(())
}
/// Reject `:politicas` values that are operationally meaningless.
/// Each axis is optional — omitting it expresses "no policy on this
/// axis". Carrying a *zero* value for a declared axis is the bug
/// this function rejects: zero is either
///
/// - re-interpreted as "infinite" by downstream proxies (Envoy's
/// `RouteAction.timeout = 0s` disables the timeout entirely),
/// directly contradicting MESH-COMPOSITION §V CSE invariant
/// "every Aplicacao declares :politicas :timeout (no infinite
/// blocking)", or
/// - a renderer footgun (a 0-failure circuit breaker trips on the
/// first call; a 0-rate rate-limit denies every request).
///
/// Lifting these "0 means the opposite of what you think" idioms to
/// the typed Aplicacao surface as build errors mirrors the §III.3
/// promise that contract drift, capability leaks, and cycles are all
/// build errors — not runtime surprises.
fn validate_politicas(&self) -> Result<(), AplicacaoError> {
// Route the whole per-axis + cross-axis `:politicas` cascade
// through the substrate primitive [`MeshPolicy::validate`],
// which folds all six per-axis brackets (`:timeout`,
// `:retries`, `:circuit-breaker :max-failures`,
// `:circuit-breaker :window`, `:rate-limit` rate, `:rate-limit`
// window-canonical-form) plus the compound cross-axis fold
// [`MeshPolicy::first_cross_axis_violation`] into one
// `Result<(), AplicacaoError>` return. The whole per-axis-
// brackets + cross-axis-fold cascade collapses to one call, and
// every future [`MeshPolicy`] consumer (the future M4
// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
// admission webhook, the per-`:contratos`-edge `:politicas`
// override MESH-COMPOSITION §III.2 #3 acknowledges — the last
// of which resolves an *effective* per-edge [`MeshPolicy`] and
// must emit *the same* diagnostic on the same input as `feira
// build`) reaches through the same substrate-primitive dispatch
// rather than re-inlining the four-per-axis + one-cross-axis
// cascade in lockstep with this validate gate. Same trajectory
// the peer per-kind compound entry gates
// [`crate::render::require_aplicacao_view`] (7242d45 / 3aefefb),
// [`crate::render::require_supervisor_view`] (8d8a5c3),
// [`crate::render::require_v0_servico_shape`] (per-Caixa
// layout axis) and the sibling compound cross-axis fold
// [`MeshPolicy::first_cross_axis_violation`] (90a6f87) carry —
// extended here onto the per-slot compound entry gate that
// folds both per-axis + cross-axis surfaces on the M3
// mesh-slot family.
self.politicas().validate()
}
/// Detect cycles in the synchronous-edge subgraph of `:contratos`.
/// A synchronous edge is any contract whose typed [`WitTarget`] is
/// `Http`, `Store`, or `Capability` — the caller blocks on the
/// callee, so a cycle would deadlock at runtime. Pub-sub edges
/// (`WitTarget::PubSub`) are skipped: an event publisher does not
/// block on its subscribers, so they can never close a sync loop.
///
/// Iterative DFS with three-coloring; the reported cycle is the
/// path of caixa names traversed from the back-edge target around
/// to itself, in declaration order. Adjacency lists and DFS roots
/// are visited in `BTreeMap` key order so the diagnostic is
/// deterministic across runs.
///
/// Now the cross-edge axis of the per-slot compound gate
/// [`AplicacaoSpec::validate_contratos`] — invoked at the tail of
/// the per-entry cascade rather than at the outer
/// [`AplicacaoSpec::validate`] dispatch, so both structural axes on
/// `:contratos` (per-entry shape + membership + dedup; cross-edge
/// sync-cycle) reach every consumer through one call. Kept
/// standalone (rather than inlined) so consumers that want only the
/// cross-edge axis (the M4 per-edge policy resolver
/// MESH-COMPOSITION §III.2 #3 acknowledges, whose per-edge patch
/// mutates one `:contratos` entry and needs to re-probe *just* the
/// cycle invariant against the post-patch adjacency without
/// re-running the per-entry shape/membership/dedup cascade the
/// per-entry-only [M4 admission] fast path already covered) still
/// have a self-contained entry point on the cycle axis.
fn detect_sync_cycles(&self) -> Result<(), AplicacaoError> {
use std::collections::{BTreeMap, BTreeSet};
#[derive(Clone, Copy, PartialEq, Eq)]
enum Mark {
White,
Gray,
Black,
}
let mut adj: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
for m in self.membros() {
adj.entry(m.nome()).or_default();
}
for c in self.contratos() {
// target() was already called by validate(); re-running here
// keeps detect_sync_cycles self-contained for callers that
// reuse it (M4 per-edge policy resolver) without revalidating.
//
// The pub-sub-arm check routes through the lifted
// [`WitTarget::is_pubsub`] `gen_platform::IsVariant`-derived
// arm-discriminator predicate rather than a raw `matches!(…,
// WitTarget::PubSub { .. })` on the variant so a future
// rebrand on the axis (an M4 per-edge WIT registry split of
// [`WitTarget::PubSub`] into shape-specific peers, a
// per-consumer rename that the accept-set already carries)
// reaches this call site through the derive rather than a
// scattered per-arm `matches!` rewrite — same
// `IsVariant`-derived-arm-discriminator discipline the
// peer closed-set typed enums ([`crate::CaixaKind`] via
// f5bba80, [`PlacementStrategy`] via 766ec63,
// [`crate::supervisor::RestartStrategy`] +
// [`crate::supervisor::RestartPolicy`],
// [`crate::upgrade::UpgradeInstruction`] via 915a934)
// already route through on the substrate's other typed-enum
// arm-discriminator axes.
if c.target()?.is_pubsub() {
continue;
}
adj.entry(c.source()).or_default().insert(c.destination());
}
let mut color: BTreeMap<&str, Mark> = adj.keys().map(|k| (*k, Mark::White)).collect();
let mut parent: BTreeMap<&str, &str> = BTreeMap::new();
// Stable DFS root order — BTreeMap iteration is sorted by key.
let roots: Vec<&str> = adj.keys().copied().collect();
// Frame: (node, sorted-neighbours snapshot, next-edge index).
for root in roots {
if color.get(root).copied().unwrap_or(Mark::White) != Mark::White {
continue;
}
let root_neighbors: Vec<&str> = adj
.get(root)
.map(|s| s.iter().copied().collect())
.unwrap_or_default();
let mut stack: Vec<(&str, Vec<&str>, usize)> = vec![(root, root_neighbors, 0)];
color.insert(root, Mark::Gray);
loop {
// Read+advance the top frame in one borrow scope so we
// can later mutate the stack (push/pop) without holding
// a borrow across.
let step: Option<(&str, Option<&str>)> = stack.last_mut().map(|top| {
let node = top.0;
if top.2 >= top.1.len() {
(node, None)
} else {
let nxt = top.1[top.2];
top.2 += 1;
(node, Some(nxt))
}
});
let Some((node, nxt_opt)) = step else { break };
let Some(nxt) = nxt_opt else {
color.insert(node, Mark::Black);
stack.pop();
continue;
};
let nxt_color = color.get(nxt).copied().unwrap_or(Mark::White);
match nxt_color {
Mark::Gray => {
// Reconstruct the cycle from `node` back through
// the parent chain to `nxt`, then close.
let mut cycle = Vec::new();
let mut cur = node;
cycle.push(cur.to_string());
while cur != nxt {
match parent.get(cur).copied() {
Some(p) => {
cur = p;
cycle.push(cur.to_string());
}
None => break,
}
}
cycle.reverse();
cycle.push(nxt.to_string());
return Err(AplicacaoError::contrato_cycle(cycle));
}
Mark::White => {
parent.insert(nxt, node);
color.insert(nxt, Mark::Gray);
let nxt_neighbors: Vec<&str> = adj
.get(nxt)
.map(|s| s.iter().copied().collect())
.unwrap_or_default();
stack.push((nxt, nxt_neighbors, 0));
}
Mark::Black => {}
}
}
}
Ok(())
}
/// Substrate-canonical destination-facing TCP port every emitted
/// per-Aplicacao artifact must key `destination`-shaped port axes
/// off. Returns the typed `:entrada :port` scalar when this
/// Aplicacao's `:entrada` block names `destination` under its
/// `:para` axis (the destination Servico *is* the ingress apex, so
/// the substrate honors the author-declared listener port
/// verbatim), and the lifted [`DEFAULT_SERVICO_PORT`] canonical
/// fallback otherwise (every non-apex destination — the internal
/// mesh Servicos `:contratos` reach across, the future per-edge
/// policy resolver's per-destination probe targets, the
/// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CNP
/// L4 port resolver — reads the same substrate-canonical port floor
/// by construction).
///
/// Prior to this lift the "if :entrada matches this destination use
/// its :port, else fall back to `DEFAULT_SERVICO_PORT`" cascade
/// lived inline at [`caixa_mesh::cilium_network_policies`]'s per-
/// `(:de, :para)` L4-port resolution site (caixa-mesh/src/lib.rs:2652
/// prior to this lift), with no typed method on the substrate primitive
/// that named the rule. A future per-destination port axis addition
/// — a per-`:contratos` explicit `:port` slot the M4 typed-edge
/// registry adds, a per-`:membros` `:port` overlay once heterogeneous
/// per-Servico listener ports land, a per-cluster override the operator
/// pins through a future `:placement :default-port` slot — would have
/// to be threaded through every renderer's inline cascade in lockstep
/// or one consumer would silently disagree on which port a given
/// destination Servico's ingress lands at. Lifting the rule to a
/// typed method on the substrate primitive means the M4 CR
/// materializer, the future per-edge policy resolver, and every
/// downstream test-fixture navigator reach for exactly one typed
/// dispatch — the resolver's accept-set moves as a unit on any
/// future axis addition.
///
/// Peer of the [`WitTarget::payload_pair`] (6788ed6) /
/// [`RATE_LIMIT_UNIT_TABLE`] (808017c) canonical "one dispatch on
/// the typed primitive, thin projections at each consumer"
/// discipline lifts on the sibling `:contratos` payload / `:politicas
/// :rate-limit` unit-suffix axes; extends the discipline onto the
/// destination-facing port-resolution axis every per-Aplicacao
/// L4-fallback renderer consumes.
#[must_use]
pub fn port_for_destination(&self, destination: &str) -> u16 {
// Route the per-`:entrada` composite-reference read through
// the lifted [`AplicacaoSpec::entrada`] accessor rather than
// the raw `self.entrada.as_ref()` field access — the
// per-destination L4-port fallback resolver's composite-
// projection seed is now the canonical read-side surface
// every per-Aplicacao entrada consumer routes through, peer
// of the sibling `validate` per-`:entrada` shape-and-
// membership gate migration on the same outer-composite
// axis.
// Route the per-`:entrada` apex-destination membership probe
// through the lifted [`Entrada::destination`] accessor rather
// than the raw `e.para == destination` field access — the last
// un-lifted `.para` production-code read site on the per-
// `:entrada` `:para` axis, sibling to the four caixa-core
// consumer sites the peer 15ddd8c converge already routed
// through the accessor (the three
// `AplicacaoSpec::validate`-side per-`:entrada` shape-and-
// membership gate sites: the `validate_entrada_para` DNS-1123
// shape gate, the per-`:membros` membership lookup, and the
// `EntradaTargetMissing` diagnostic-carry `String`-clone) and
// the peer emit-side per-Aplicacao `HTTPRoute` per-parent-refs
// `entrada.para`-projection converge at
// caixa-core/src/render.rs (the `gateway_api_http_route_name`
// route-name projection site). Prior to this converge the
// `port_for_destination` resolver was the solitary consumer
// bypassing the typed dispatch on the `.para` axis — the two
// `caixa-mesh` per-`(HTTPRoute, CNP)` emit sites at
// caixa-mesh/src/lib.rs:3173 (`entrada.destination()`) and
// caixa-mesh/src/lib.rs:2739 (`c.destination()`) that already
// reach through the same accessor family compose with this
// resolver at the emit boundary via the apex-identity
// invariant `spec.port_for_destination(entrada.destination())
// == entrada.port` the sibling
// [`port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`]
// pin pins across four permutations. A future extension of the
// `:entrada :para` axis to a richer author surface (a per-
// cluster alias overlay the operator pins through a future
// `:placement`-scoped slot, a namespace-qualified rewrite the
// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
// per-CR, a `:entrada :para-aliases` overlay MESH-COMPOSITION
// §III.2 acknowledges) that lands on the accessor would silently
// disagree between this resolver and the two `caixa-mesh` emit
// sites — an author-declared `:para "cart"` value the accessor
// rewrote to `"cart-v2"` under a future canary arm would leave
// the resolver's membership arm falling through to
// `DEFAULT_SERVICO_PORT` (matching against the raw un-aliased
// `.para`) while the peer emit-site consumers landed on the
// accessor-projected value at `caixa-mesh/src/lib.rs:3173` and
// silently disagreed on which destination port a given typed
// `:entrada` resolves to at cluster-apply time. Pinned by the
// drift-detection test
// [`port_for_destination_apex_arm_routes_through_destination_accessor`]
// below.
self.entrada()
.filter(|e| e.destination() == destination)
.map_or(DEFAULT_SERVICO_PORT, Entrada::port)
}
}
/// Cross-slot coherence gate on the Aplicacao graph: no `:membros :caixa`
/// entry may name the Aplicacao's own `:nome`.
///
/// An Aplicacao that lists itself as a member is a degenerate self-edge in
/// the typed graph — the application graph is a DAG rooted at the Aplicacao
/// (MESH-COMPOSITION §III.1 names `:membros` as the set of *constituent*
/// Servicos that compose the app; an Aplicacao is never its own constituent),
/// and the lacre pipeline's closure-resolution would otherwise be handed a
/// node that is its own parent: a one-node cycle it either rejects far from
/// the source `caixa.lisp` (the resolver detecting infinite recursion on the
/// closure walk) or, worse, recurses on until it exhausts the lacre stack.
/// Because every `:nome` is a globally-unique substrate identity (DNS-1123
/// label + lacre closure root), a member whose `:caixa` equals the
/// Aplicacao's `:nome` *is* the Aplicacao itself, not a coincidentally-named
/// peer.
///
/// Lives outside [`AplicacaoSpec::validate`] because the typed view carries
/// the membros but not the parent `:nome`; mirrors the cross-slot precedence
/// gate `validate_upgrade_from_against_versao` and the supervision-tree
/// self-parent gate `crate::supervisor::validate_no_self_supervision`
/// (ad4abf1) — the same "an edge from a graph node to itself is structurally
/// not a tree/mesh edge" discipline, here on the second typed-graph axis
/// (the Aplicacao :membros set; the supervision-tree :children list was the
/// first). Closes the kind ↔ self-edge coverage on both typed-graph kinds:
/// every validated Supervisor's children are distinct from its `:nome`,
/// every validated Aplicacao's membros are distinct from its `:nome`. The
/// transitive consequence is that `:entrada :para` and `:contratos`
/// `:de`/`:para` — already gated to be members of `:membros` — also cannot
/// name the Aplicacao itself, without re-deriving the partition.
pub fn validate_no_self_membership(
membros: &[Membro],
parent_nome: &str,
) -> Result<(), AplicacaoError> {
for m in membros {
if m.nome() == parent_nome {
return Err(AplicacaoError::membro_is_self_aplicacao(parent_nome));
}
}
Ok(())
}
#[derive(Debug, Error, PartialEq, Eq)]
pub enum AplicacaoError {
#[error("Aplicacao must declare at least one :membros entry")]
NoMembros,
#[error(
":membros entry has empty :caixa (every member must name a Servico; \
omit the entry instead of carrying an empty name)"
)]
MembroCaixaEmpty,
#[error(
":membros entry :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
(the K8s apiserver enforces this rule on every `metadata.name` / Service \
name / label value the member name lands in; use a lowercase \
alphanumeric + hyphen identifier like `\"checkout\"` or `\"cart-v2\"`)"
)]
MembroCaixaInvalid { caixa: String, reason: String },
#[error(
":membros entry {caixa:?} has empty :versao (every member must pin a \
semver constraint that resolves through the lacre pipeline)"
)]
MembroVersaoEmpty { caixa: String },
#[error(
":membros entry {caixa:?} :versao {versao:?} is not a valid semver \
requirement: {reason} (use Cargo-shaped forms like `\"^0.1\"`, \
`\"~0.1.2\"`, `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` \
carries; the lacre pipeline resolves both through the same parser)"
)]
MembroVersaoInvalid {
caixa: String,
versao: String,
reason: String,
},
#[error(
":membros entry {caixa:?} appears more than once (the graph node set \
is a set, not a multiset; duplicate members produce duplicate \
programs.yaml entries and ambiguous :contratos membership lookups)"
)]
MembroDuplicate { caixa: String },
#[error(
"aplicacao {caixa:?} lists itself as a :membros entry — an Aplicacao is \
never its own constituent Servico (the application graph is a DAG rooted \
at the Aplicacao; :membros names the *other* caixas that compose the \
app, not the app itself). Since every :nome is a globally-unique \
substrate identity, a member naming the Aplicacao's own :nome is a \
one-node lacre-closure recursion, not a coincidentally-named peer; \
drop the self-referential :membros entry or rename it to the actual \
constituent caixa."
)]
MembroIsSelfAplicacao { caixa: String },
#[error(
"contrato {slot} is empty (every :contratos entry's :de and :para must name a \
caixa declared in :membros; omit the contract or fill the {slot} field with a \
member name)"
)]
ContratoCaixaEmpty { slot: &'static str },
#[error(
"contrato {slot} {caixa:?} is not a valid DNS-1123 label: {reason} (every \
:contratos {slot} value names a member of :membros, which is itself a \
DNS-1123 label per the K8s apiserver's `metadata.name` rule on every \
object the member name lands in — Service, Pod, identity-based Cilium \
selector; use a lowercase alphanumeric + hyphen identifier like \
`\"checkout\"` or `\"cart-v2\"`)"
)]
ContratoCaixaInvalid {
slot: &'static str,
caixa: String,
reason: String,
},
#[error("contrato references caixa {caixa:?} not declared in :membros")]
ContratoMemberMissing { caixa: String },
#[error(
"contrato {caixa:?} → {caixa:?} (:wit {wit:?}) is a self-edge — a :contratos \
entry is an inter-Servico contract whose :de and :para must name distinct \
:membros; a Servico's calls to itself are in-process, not mesh edges (drop \
the contract, or point :para at the member it actually calls)"
)]
ContratoSelfLoop { caixa: String, wit: String },
#[error("contrato {de:?} → {para:?} has empty :wit")]
EmptyWit { de: String, para: String },
#[error(
"contrato {de:?} → {para:?} :wit {wit:?} is not a valid WIT world reference: \
{reason} (the substrate dispatches `:wit` values on the canonical \
lowercase `<namespace>:<package>(/<interface>)?(@<version>)?` shape — \
`wasi:http/proxy`, `nats:pub-sub`, `wasi:keyvalue/store` — and silently \
demotes unmatched shapes to a capability-only L4 edge; use a lowercase \
kebab-case identifier per segment)"
)]
ContratoWitInvalid {
de: String,
para: String,
wit: String,
reason: String,
},
#[error(
":entrada :para is empty (every :entrada must route to a caixa declared in \
:membros; fill the :para field with a member name)"
)]
EntradaParaEmpty,
#[error(
":entrada :para {para:?} is not a valid DNS-1123 label: {reason} (every \
:entrada :para value names a member of :membros, which is itself a DNS-1123 \
label per the K8s apiserver's `metadata.name` rule on every object the \
member name lands in — Service backendRefs, HTTPRoute spec, identity-based \
Cilium selector; use a lowercase alphanumeric + hyphen identifier like \
`\"checkout\"` or `\"cart-v2\"`)"
)]
EntradaParaInvalid { para: String, reason: String },
#[error(":entrada routes to caixa {para:?} not declared in :membros")]
EntradaMemberMissing { para: String },
#[error(":entrada must declare a non-empty :host")]
EmptyEntradaHost,
#[error(
":entrada :host {host:?} is not a valid Gateway API v1 Hostname: {reason} \
(the K8s apiserver enforces the same shape on Gateway `Listener.hostname` and \
`HTTPRoute.spec.hostnames` at admission time; use a lowercase RFC 1123 DNS name \
like `\"checkout.quero.cloud\"` or `\"*.quero.cloud\"`)"
)]
EntradaHostInvalid { host: String, reason: String },
#[error(":entrada :port must be in 1..=65535, got 0")]
EntradaPortZero,
#[error(":entrada :paths entry is empty (use the empty list to match all)")]
EntradaPathEmpty,
#[error(
":entrada :paths entry {path:?} must start with `/` (Gateway API PathPrefix invariant)"
)]
EntradaPathNotAbsolute { path: String },
#[error(
":entrada :paths entry {path:?} is not a valid Gateway API v1 HTTPPathMatch \
value: {reason} (the K8s apiserver enforces the same shape on \
`HTTPRoute.spec.rules[].matches[].path.value` at admission time; use a \
single-`/`-prefixed printable-ASCII path like `\"/api/cart\"` — RFC 3986 \
requires percent-encoding `%XX` for non-ASCII and whitespace)"
)]
EntradaPathInvalid { path: String, reason: String },
#[error(":entrada :paths entry {path:?} appears more than once")]
EntradaPathDuplicate { path: String },
#[error(
":placement {estrategia} requires at least one :clusters entry \
(Replicated/SingleNode: hosting/takeover candidates; Sharded: shard pool)"
)]
PlacementWithoutClusters { estrategia: PlacementStrategy },
#[error(":placement :clusters entry is empty (cluster names must be non-empty)")]
PlacementClusterEmpty,
#[error(
":placement :clusters entry {cluster:?} is not a valid DNS-1123 label: {reason} \
(cluster names land in the K8s context keying every per-cluster `kubeconfig`, \
in the `lareira-fleet-programs` aggregator's `clusters[]` filter, and in the \
future M4 cross-cluster fan-out's per-entry namespace prefix / cluster identity \
— each enforces the DNS-1123 label rule; use a lowercase alphanumeric + hyphen \
identifier like `\"rio\"` or `\"mar-east\"`)"
)]
PlacementClusterInvalid { cluster: String, reason: String },
#[error(":placement :clusters entry {cluster:?} appears more than once")]
PlacementClusterDuplicate { cluster: String },
#[error(
":placement :affinity must be non-empty when set (omit :affinity to express \
`no placement hint`)"
)]
PlacementAffinityEmpty,
#[error(
":placement :affinity {affinity:?} is not a valid DNS-1123 label: {reason} \
(placement hints land verbatim in the M3 Adaptive compression overlay's \
`placement.affinity` field and in every future M4 placement-engine routing \
axis keying off the hint as a K8s `app.pleme.io/affinity-hint=<value>` label \
selector — both enforce the DNS-1123 label rule on admission; use a \
lowercase alphanumeric + hyphen hint like `\"data-locality\"`, \
`\"low-latency\"`, or `\"anti-affinity\"`)"
)]
PlacementAffinityInvalid { affinity: String, reason: String },
#[error(":placement Sharded requires :shard-key")]
ShardedWithoutKey,
#[error(
":placement Sharded :shard-key must be non-empty (a `Some(\"\")` shard key \
hashes every entity onto the same shard, defeating sharding entirely)"
)]
ShardedKeyEmpty,
#[error(
":placement Sharded :shard-key {shard_key:?} is not a valid Akka-style \
entity-id extractor expression: {reason} (the future M4 Akka-style \
cluster-sharding reconciler — MESH-COMPOSITION §II.4 — reads `:shard-key` \
as a single-token property reference and hashes the extracted entity ID \
to compute shard placement; use a printable-ASCII extractor expression \
like `\"tenantId\"`, `\"$tenantId\"`, `\"metadata.tenantId\"`, or \
`\"${{tenant}}\"`)"
)]
ShardKeyInvalid { shard_key: String, reason: String },
#[error(
":placement {estrategia} carries :shard-key {shard_key:?} — only :estrategia \
Sharded consumes :shard-key (hash-keyed entity distribution, Akka cluster-sharding \
convention); :estrategia Replicated runs every cluster active-active and \
:estrategia SingleNode takes over a single cluster at a time (Erlang/OTP \
distributed-app convention) — both ignore the slot. Drop :shard-key, or switch \
to :estrategia Sharded if hash-keyed routing is the intent"
)]
ShardKeyOnNonSharded {
estrategia: PlacementStrategy,
shard_key: String,
},
#[error("contrato {de:?} → {para:?} (:wit {wit:?}) is missing required `:{expected}` field")]
ContratoMissingTarget {
de: String,
para: String,
wit: String,
expected: &'static str,
},
#[error(
"contrato {de:?} → {para:?} (:wit {wit:?}) carries the wrong target field — \
expected `:{expected}` only"
)]
ContratoWrongTarget {
de: String,
para: String,
wit: String,
expected: &'static str,
},
#[error(
"HTTP contrato {de:?} → {para:?} :endpoint is empty (use a non-empty path \
like `/charge`; an empty endpoint renders as a `path: \"\"` Cilium L7 rule \
that matches no traffic and silently drops every request)"
)]
ContratoEndpointEmpty { de: String, para: String },
#[error(
"HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} must start with `/` \
(Cilium L7 :path + Gateway API PathPrefix invariant — same shape required of \
:entrada :paths)"
)]
ContratoEndpointNotAbsolute {
de: String,
para: String,
endpoint: String,
},
#[error(
"HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} is not a valid \
Cilium L7 `path:` / Gateway API v1 HTTPPathMatch value: {reason} (caixa-mesh \
emits the :endpoint verbatim as the Cilium L7 `path:` rule at \
caixa-mesh/src/lib.rs:311; the K8s apiserver enforces the same HTTPPathMatch \
shape on `:entrada :paths`. Use a single-`/`-prefixed printable-ASCII path \
like `\"/charge\"` — RFC 3986 requires percent-encoding `%XX` for non-ASCII \
and whitespace)"
)]
ContratoEndpointInvalid {
de: String,
para: String,
endpoint: String,
reason: String,
},
#[error(
"pub-sub contrato {de:?} → {para:?} :subject is empty (publish without a \
subject is a no-op subscribe; omit :subject only if the WIT world is not \
pub-sub-shaped)"
)]
ContratoSubjectEmpty { de: String, para: String },
#[error(
"pub-sub contrato {de:?} → {para:?} :subject {subject:?} is not a valid \
NATS subject: {reason} (the NATS server's subject parser enforces the \
same shape — `.`-separated tokens of `[A-Za-z0-9_-]`, with the `*` \
single-token and `>` multi-token wildcards — at publish/subscribe time; \
use a token-by-token form like `\"checkout.events.charge.failed\"` or \
`\"orders.*.completed\"` — a malformed subject silently drops every \
message at runtime far from the source caixa.lisp)"
)]
ContratoSubjectInvalid {
de: String,
para: String,
subject: String,
reason: String,
},
#[error(
"store contrato {de:?} → {para:?} :slot is empty (an empty slot template \
addresses the bucket root, defeating the per-key isolation the slot exists \
for; omit :slot only if the WIT world is not store-shaped)"
)]
ContratoSlotEmpty { de: String, para: String },
#[error(
"store contrato {de:?} → {para:?} :slot {slot:?} is not a valid \
WASI keyvalue store slot template: {reason} (the substrate enforces \
the printable-ASCII intersection-floor every kv backend admits — \
use a single-token path / template expression like `\"checkout/$orderId\"`, \
`\"users:{{tenant}}/{{id}}\"`, or `\"session.tokens.<sid>\"`; RFC 3986 requires \
percent-encoding `%XX` for non-ASCII and whitespace — a malformed \
slot either gets rejected on write by strict backends or silently \
corrupts the next read on permissive ones, far from the source caixa.lisp)"
)]
ContratoSlotInvalid {
de: String,
para: String,
slot: String,
reason: String,
},
#[error(
"synchronous :contratos form a cycle ({}); break with a NATS pub-sub edge \
or an event-sourced indirection (MESH-COMPOSITION §III.3)",
cycle.join(" → ")
)]
ContratoCycle { cycle: Vec<String> },
#[error(
":contratos entry {de:?} → {para:?} (:wit {wit:?} {target}) appears more \
than once (the typed graph edges are a set, not a multiset; duplicate \
contracts would render as colliding `CiliumNetworkPolicy` `metadata.name` \
values that K8s admission rejects far from the source caixa.lisp)"
)]
ContratoDuplicate {
de: String,
para: String,
wit: String,
target: String,
},
#[error(
":politicas :timeout must be > 0 (Envoy interprets a zero timeout as `infinite`, \
contradicting MESH-COMPOSITION §V `no infinite blocking`); omit :timeout to \
express `no per-call deadline on this axis`"
)]
PolicyTimeoutZero,
#[error(
":politicas :retries must be > 0 when set; omit :retries to express \
`no retries on transient failure`"
)]
PolicyRetriesZero,
#[error(
":politicas :retries ({retries}) exceeds the mesh-policy ceiling \
(POLICY_RETRIES_MAX = 10) — a value above this cap turns the typed \
retry policy into a thundering-herd amplification vector on transient \
failure (one caller request fans out to `(retries+1)^depth` server-side \
calls across the synchronous-:contratos subgraph), exactly the failure \
mode AWS App Mesh's `maxRetries ≤ 10` schema cap exists to prevent. \
Pin a value in 1..=10 (Envoy / Istio production playbooks recommend ≤ 5) \
or omit :retries to disable retries entirely"
)]
PolicyRetriesExceedsCap { retries: u32 },
#[error(
":politicas :circuit-breaker :max-failures must be > 0 (a zero-threshold \
breaker trips on the first call); omit :circuit-breaker to disable it"
)]
PolicyBreakerZeroFailures,
#[error(
":politicas :circuit-breaker :max-failures ({max_failures}) exceeds the \
mesh-policy ceiling (POLICY_BREAKER_MAX_FAILURES_MAX = 1000) — a value \
above this cap turns the typed breaker policy into a no-op: the trip \
threshold is structurally so high that no realistic failures-per-:window \
traffic shape can reach it, so the breaker never trips and every typed-slot \
consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, \
Envoy's outlier_detection.consecutive_5xx) emits a protection that is \
structurally never enforced. Pin a value in 1..=1000 (Hystrix / Istio / \
Envoy / Polly / Resilience4j production playbooks recommend 5..=50) or \
omit :circuit-breaker to disable the breaker entirely"
)]
PolicyBreakerMaxFailuresExceedsCap { max_failures: u32 },
#[error(
":politicas :circuit-breaker :window must be > 0 (a zero-window breaker \
tracks no failures); omit :circuit-breaker to disable it"
)]
PolicyBreakerZeroWindow,
#[error(
":politicas :rate-limit rate must be > 0 (a zero-rate limit denies every \
request); omit :rate-limit to disable rate limiting"
)]
PolicyRateLimitZero,
#[error(
":politicas :rate-limit rate ({rate}) exceeds the mesh-policy ceiling \
(POLICY_RATE_LIMIT_MAX = 1000000) — a value above this cap turns the typed \
rate-limit policy into a no-op limiter: the token-bucket capacity is \
structurally so high that no realistic per-edge traffic shape can drain it, \
so the limiter never trips and every typed-slot consumer (the future \
CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
local_rate_limit.token_bucket.max_tokens) emits a rate-limit declaration \
that is structurally never enforced. Pin a value in 1..=1000000 (Envoy / \
Istio / Kong / NGINX production playbooks recommend 10..=10000 RPS; \
Cloudflare / AWS API Gateway typical 10000..=100000 per-minute; \
Cloudflare Enterprise rate-plans run to ~1M per-hour) or omit :rate-limit \
to disable rate limiting entirely"
)]
PolicyRateLimitExceedsCap { rate: u32 },
#[error(
":politicas :rate-limit :window must be exactly 1s, 1m (60s), or 1h (3600s) — \
the canonical authoring forms `\"<n>/s\"`, `\"<n>/m\"`, `\"<n>/h\"` the \
rate-limit codec round-trips losslessly; got {window:?} which renders to a \
non-round-trippable form (omit :rate-limit to disable, or pick one of the \
three canonical windows)"
)]
PolicyRateLimitWindowNotCanonical { window: Duration },
#[error(
":politicas :timeout must be an integer number of milliseconds — the canonical \
authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} the shared \
duration codec round-trips losslessly; got {timeout:?} which carries a \
sub-millisecond residue that either truncates to a different `Duration` on \
re-parse (e.g. `Duration::from_micros(1500)` → renders `\"1ms\"` → parses back \
to 1ms, not 1.5ms) or renders as `\"0s\"` (sub-millisecond magnitude) the \
zero-floor gate rejects on re-validate. Pick an integer-millisecond magnitude \
(e.g. `\"30s\"`, `\"1500ms\"`, `\"2m\"`, `\"1h\"`)"
)]
PolicyTimeoutNotCanonical { timeout: Duration },
#[error(
":politicas :timeout ({timeout:?}) exceeds the mesh-policy ceiling \
(POLICY_TIMEOUT_MAX = 1h = 3600s) — a value above this cap turns the typed \
per-call deadline into a nominal-only contract (Envoy / Cilium L7 timeout \
overlays carry a deadline so long no realistic synchronous-:contratos \
traversal can reach it), and the MESH-COMPOSITION §V \"no infinite blocking\" \
CSE invariant degenerates to enforcement only at the per-Servico \
`:limits :wall-clock` layer — far above the per-edge granularity the typed \
`:politicas :timeout` slot is meant to express. Pin a value in 1ms..=1h \
(Envoy / Istio / Linkerd / AWS App Mesh production playbooks all recommend \
≤ 60s; the Kubernetes ingress-nginx documented `proxy_read_timeout` band \
maxes out at the same `3600s` ceiling) or omit :timeout to express \
`no per-call deadline on this axis` (the synchronous-call deadline then \
relies entirely on the per-Servico `:limits :wall-clock` axis)"
)]
PolicyTimeoutExceedsCap { timeout: Duration },
#[error(
":politicas :circuit-breaker :window must be an integer number of milliseconds — \
the canonical authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} \
the shared duration codec round-trips losslessly; got {window:?} which carries a \
sub-millisecond residue that either truncates to a different `Duration` on \
re-parse or renders as `\"0s\"` the zero-floor gate rejects on re-validate. \
Pick an integer-millisecond magnitude (e.g. `\"60s\"`, `\"500ms\"`, `\"2m\"`)"
)]
PolicyBreakerWindowNotCanonical { window: Duration },
#[error(
":politicas :circuit-breaker :window ({window:?}) exceeds the mesh-policy ceiling \
(POLICY_BREAKER_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
rolling-window breaker into a lifetime-counter breaker: the failure-counting window \
is structurally so long that transient failures are never forgotten, the breaker \
trips once and stays tripped for the lifetime of the component, and every typed-slot \
consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
outlier_detection.interval) emits a \"rolling\" window that exists only nominally. \
Pin a value in 1ms..=1h (Hystrix / resilience4j / Istio / Envoy production playbooks \
default to 10s; AWS App Mesh maxes out at ~5m) or omit :circuit-breaker to disable \
the breaker entirely"
)]
PolicyBreakerWindowExceedsCap { window: Duration },
#[error(
":politicas :circuit-breaker :window ({window:?}) is shorter than :politicas \
:timeout ({timeout:?}) — the rolling failure-observation interval closes before \
a single timing-out call can be declared failed, so the dominant failure mode \
the breaker exists to catch is structurally never counted: a call dispatched at \
t=0 is only reported failed at t={timeout:?}, by which point the window that was \
open at dispatch has already rolled, and every typed-slot consumer (the future \
CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
outlier_detection.interval paired against the per-route request timeout) emits a \
breaker that cannot trip on timeouts however high the call volume. Pin :window \
at or above :timeout (Hystrix defaults 10s rolling window against a 1s execution \
timeout — a 10× ratio; Envoy / resilience4j production playbooks recommend the \
same shape), lower :timeout, or omit one of the two axes"
)]
PolicyBreakerWindowBelowTimeout { window: Duration, timeout: Duration },
#[error(
":politicas :rate-limit ({rate} per {rl_window:?}) starves :politicas \
:circuit-breaker so :max-failures ({max_failures}) cannot be reached inside \
:window ({cb_window:?}) — the token-bucket dispatches at most \
`rate × cb_window / rl_window` calls per rolling breaker window, which is \
structurally below the trip threshold, so the breaker cannot trip even under \
100% failure and every typed-slot consumer (the future \
CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
outlier_detection.consecutive_5xx paired against \
local_rate_limit.token_bucket.max_tokens) emits a protection that is \
structurally never enforced. Raise :rate, shorten :rate-limit :window, lower \
:max-failures, lengthen :circuit-breaker :window, or omit one of the two axes"
)]
PolicyBreakerCannotTripUnderRateLimit {
rate: u32,
rl_window: Duration,
max_failures: u32,
cb_window: Duration,
},
#[error(
":politicas :retries ({retries}) plus the initial attempt saturates :politicas \
:circuit-breaker :max-failures ({max_failures}) mid-retry — one client's failing \
attempts alone accumulate {retries}+1 failures, which reaches the trip threshold \
at or before the last retry, so the breaker opens with declared retries still \
unused and every typed-slot consumer (the future CiliumClusterwideEnvoyConfig \
per-:politicas overlay, Envoy's retry_policy.num_retries paired against \
outlier_detection.consecutive_5xx) emits a retry policy the substrate \
structurally truncates. Pin :max-failures strictly above :retries (Hystrix / \
Envoy / resilience4j production playbooks recommend the breaker's trip \
threshold be observably larger than any single client's retry budget so the \
breaker distinguishes one persistently-failing client from sustained \
multi-client failure), lower :retries, or omit one of the two axes"
)]
PolicyBreakerTripsBeforeRetriesExhausted { retries: u32, max_failures: u32 },
#[error(
":politicas :rate-limit ({rate} per window) cannot admit :politicas :retries \
({retries}) plus the initial attempt — one client's declared retry sequence is \
{retries}+1 attempts, each of which consumes one token from the local rate-limit \
bucket, but the bucket admits at most {rate} tokens per refill window, so the \
retry policy is silently truncated by the same rate limiter it feeds through and \
every typed-slot consumer (the future CiliumClusterwideEnvoyConfig per-:politicas \
overlay, Envoy's retry_policy.num_retries paired against \
local_rate_limit.token_bucket.max_tokens) emits a retry policy the substrate \
structurally throttles. Raise :rate strictly above :retries (Envoy / Istio / \
resilience4j / AWS App Mesh production playbooks recommend the local rate-limit \
bucket capacity be observably larger than any single client's retry budget so the \
limiter distinguishes one client's declared retries from sustained multi-client \
load), lower :retries, or omit one of the two axes"
)]
PolicyRateLimitCannotAdmitRetryBurst { retries: u32, rate: u32 },
}
// The `AplicacaoError::EntradaHostInvalid { host, reason }` variant's
// ctor `entrada_host_invalid` is folded onto the sibling
// [`aplicacao_field_reason_ctors!`] macro below alongside the six peer
// `{ <field>: String, reason: String }` variants
// (`MembroCaixaInvalid` / `EntradaParaInvalid` / `EntradaPathInvalid` /
// `PlacementClusterInvalid` / `PlacementAffinityInvalid` /
// `ShardKeyInvalid`), so every variant on the uniform two-slot
// `{ <field>: String, reason: String }` envelope on [`AplicacaoError`]
// reads through one substrate-primitive family rather than one macro
// closing six sites plus a hand-written seventh ctor closing the
// paired site alone. Prior separate-ctor rationale (17dd504) migrates
// verbatim to the macro's outer doc block.
// Fold the seven `AplicacaoError::Contrato{Wrong,Missing}Target { de, para,
// wit, expected }` wire-up sites at [`WitContract::target`] onto one
// substrate-primitive family per typed variant — the paired sibling on
// [`AplicacaoError`] of the four `LayoutError` constructor families
// [`layout_violation_ctors!`] (131ca0d, 16 variants on `{ caixa, issue }`),
// [`layout_slot_kind_ctors!`] (0419438, 4 variants on
// `{ caixa, kind, slots }`), [`LayoutError::missing_entry`] (1b09f9d,
// 1 variant on `{ kind, path }`), and [`layout_nome_only_ctors!`] (3fe3dd7,
// 6 variants on `<Variant>(String)`) each carry on the sibling layout-side
// envelope. Every one of the seven wire-up sites in [`WitContract::target`]
// (four `ContratoWrongTarget` arms on the payload-field-mismatch axis —
// HTTP with subject/slot, PubSub with endpoint/slot, Store with
// endpoint/subject, Capability with any payload; three
// `ContratoMissingTarget` arms on the payload-field-absent axis — HTTP
// without `:endpoint`, PubSub without `:subject`, Store without `:slot`)
// opened the identical six-line
// `AplicacaoError::Contrato<Wrong|Missing>Target { de, para, wit, expected:
// WitTarget::<label> }` struct-literal against the local `edge()` closure
// returning `(de, para, wit) = self.edge_triple()` — the exact "same block
// re-inlined at every consumer" shape the PRIME DIRECTIVE names as a bug,
// on the same altitude the peer four `LayoutError` constructor families
// each closed on their sibling envelopes.
//
// The macro below generates one `#[must_use]` inherent constructor per
// variant of shape `fn <ctor>(edge: (String, String, String), expected:
// &'static str) -> AplicacaoError`, collapsing the seven sites onto one
// dispatch per arm: `return
// Err(AplicacaoError::contrato_wrong_target(edge(), <label>));` / `.ok_or_else(||
// AplicacaoError::contrato_missing_target(edge(), <label>))?`, byte-equal to
// the pre-lift struct-literal on the same edge fixture. The uniform four-
// field construction (`de, para, wit` triple-destructure onto same-named
// fields + `expected` verbatim) is spelled once — inside the macro —
// rather than at every wire-up site. `#[must_use]` fires a compile warning
// at any wire-up that mistakenly discards the constructed error.
//
// Every future consumer that wants to construct one of these two variants
// outside [`WitContract::target`] (a deferred
// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-`:contratos`
// admission validator raising wrong-target / missing-target diagnostics
// on unrecognized shapes, a future `feira validate --contratos` per-caixa
// admission verb, a per-`WitContract` payload-axis pre-emitter probing
// the [`WitTarget`] arm against the declared `:endpoint`/`:subject`/`:slot`
// slots) reaches the variant through one call rather than re-inlining the
// six-line struct-literal block in lockstep with the seven in-crate
// wire-up sites.
macro_rules! contrato_target_ctors {
($($ctor:ident => $variant:ident),* $(,)?) => {
impl AplicacaoError {
$(
#[doc = concat!(
"Construct an [`AplicacaoError::",
stringify!($variant),
"`] naming the offending edge `(de, para, wit)` triple ",
"under the given `expected` payload-field-name label. ",
"Folds the uniform `{ de, para, wit, expected }` four-",
"slot struct-literal onto one substrate primitive so ",
"every [`WitContract::target`] wire-up on this variant ",
"reads through one dispatch rather than the pre-lift ",
"six-line open-coded block. The `edge` triple threads ",
"verbatim from [`WitContract::edge_triple`] via the ",
"local `edge()` closure at the call site."
)]
#[must_use]
pub fn $ctor(edge: (String, String, String), expected: &'static str) -> Self {
let (de, para, wit) = edge;
Self::$variant { de, para, wit, expected }
}
)*
}
};
}
contrato_target_ctors! {
contrato_wrong_target => ContratoWrongTarget,
contrato_missing_target => ContratoMissingTarget,
}
// Fold the four `AplicacaoError::{EmptyWit, ContratoEndpointEmpty,
// ContratoSubjectEmpty, ContratoSlotEmpty} { de, para }` wire-up sites
// onto one substrate-primitive family per typed variant — the paired
// `{ de: String, para: String }` two-slot sibling on [`AplicacaoError`]
// of the peer four-slot [`contrato_target_ctors!`] (14b81d5,
// `{ de, para, wit, expected }` on `ContratoWrongTarget` /
// `ContratoMissingTarget`) and of the two-slot
// [`AplicacaoError::entrada_host_invalid`] (17dd504, `{ host, reason }`)
// on the sibling per-`:entrada :host` envelope. Every one of the four
// wire-up sites — three under [`WitContract::target`] (the empty
// [`WitTarget::Http`] `:endpoint`, empty [`WitTarget::PubSub`]
// `:subject`, empty [`WitTarget::Store`] `:slot`) and one under
// [`AplicacaoSpec::validate`] (the empty `:contratos :wit` field the
// value-shape gate fires ahead of) — opened the identical two-line
// `let (de, para) = <contract>.edge_pair(); return Err(
// AplicacaoError::<Variant> { de, para });` block against the local
// [`WitContract::edge_pair`] composite-projection accessor, the exact
// "same block re-inlined at every consumer" shape the PRIME DIRECTIVE
// names as a bug, on the same altitude the peer [`contrato_target_ctors!`]
// and [`AplicacaoError::entrada_host_invalid`] each closed on their
// sibling envelopes.
//
// The macro below generates one `#[must_use]` inherent constructor per
// variant of shape `fn <ctor>(edge: (String, String)) -> AplicacaoError`,
// collapsing the four sites onto one dispatch per arm:
// `return Err(AplicacaoError::<ctor>(<contract>.edge_pair()));`, byte-
// equal to the pre-lift struct-literal on the same edge pair. The
// uniform two-field construction (`de, para` pair-destructure onto
// same-named fields) is spelled once — inside the macro — rather than
// at every wire-up site. `#[must_use]` fires a compile warning at any
// wire-up that mistakenly discards the constructed error.
//
// Every future consumer that wants to construct one of these four
// variants outside the two in-crate wire-up sites (a deferred
// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-`:contratos`
// admission validator raising empty-payload / empty-`:wit` diagnostics,
// a future `feira validate --contratos` per-caixa admission verb, an
// M4 typed WIT-registry-driven per-arm pre-emitter probing the
// [`WitContract`] payload slot against a canonical per-arm requirement
// table) reaches the variant through one call rather than re-inlining
// the two-line pair-destructure block in lockstep with the four
// in-crate wire-up sites.
macro_rules! contrato_empty_pair_ctors {
($($ctor:ident => $variant:ident),* $(,)?) => {
impl AplicacaoError {
$(
#[doc = concat!(
"Construct an [`AplicacaoError::",
stringify!($variant),
"`] naming the offending edge `(de, para)` pair. ",
"Folds the uniform `{ de, para }` two-slot struct-",
"literal onto one substrate primitive so every ",
"wire-up on this variant reads through one dispatch ",
"rather than the pre-lift two-line open-coded ",
"`let (de, para) = <contract>.edge_pair(); return ",
"Err(<Variant> { de, para });` block. The `edge` ",
"pair threads verbatim from [`WitContract::edge_pair`] ",
"at the call site."
)]
#[must_use]
pub fn $ctor(edge: (String, String)) -> Self {
let (de, para) = edge;
Self::$variant { de, para }
}
)*
}
};
}
contrato_empty_pair_ctors! {
empty_wit => EmptyWit,
contrato_endpoint_empty => ContratoEndpointEmpty,
contrato_subject_empty => ContratoSubjectEmpty,
contrato_slot_empty => ContratoSlotEmpty,
}
// Fold the last open-coded `AplicacaoError::ContratoEndpointNotAbsolute
// { de, para, endpoint: <val>.to_string() }` three-slot struct-literal
// wire-up site at [`WitContract::target`]'s HTTP-arm leading-slash gate
// onto one substrate primitive on [`AplicacaoError`] — sibling on the
// `{ de: String, para: String, <field>: String }` three-slot envelope of
// the peer [`contrato_empty_pair_ctors!`] macro just above (8580068, four
// variants on the paired `{ de, para }` two-slot envelope carrying the
// same `let (de, para) = <contract>.edge_pair(); return Err(<Variant>
// { de, para });` pair-destructure prelude), the peer four-slot
// [`contrato_pair_value_reason_ctors!`] macro (14e13f1, four variants on
// the paired `{ de, para, <field>: String, reason: String }` envelope
// carrying the parser-shaped `reason` trailer), and the peer four-slot
// [`contrato_target_ctors!`] macro (14b81d5, two variants on the paired
// `{ de, para, wit, expected: &'static str }` envelope carrying the
// canonical target-field-name label). The `ContratoEndpointNotAbsolute`
// variant is the sole occupant of the three-slot `{ de, para, <field>:
// String }` shape on [`AplicacaoError`] (no sibling
// `ContratoSubjectNotAbsolute` / `ContratoSlotNotAbsolute` — the `:subject`
// and `:slot` axes carry no "must start with /" invariant, since the
// NATS subject grammar and the WASI keyvalue slot template grammar don't
// share the Gateway-API-HTTPPathMatch leading-slash prelude the
// `:endpoint` axis does), so a full macro isn't warranted; a single
// `#[must_use]` inherent ctor matching the ambient
// `fn <ctor>(edge: (String, String), <field>: &str) -> Self` shape the
// peer per-`:contratos` ctor families each carry closes the last
// open-coded three-slot struct-literal on the envelope, matching the
// same standalone-ctor discipline the sibling
// [`crate::LayoutError::missing_entry`] (1b09f9d, one variant on the
// `{ kind: &'static str, path: PathBuf }` two-slot envelope),
// [`crate::SupervisorError::child_caixa_invalid`] /
// [`::child_versao_invalid`] (d2ef2ec, two variants on the paired
// `{ caixa: String, [versao: String,] reason: String }` two- and three-
// slot envelopes), and [`AplicacaoError::entrada_host_invalid`] (17dd504,
// one variant on the `{ host: String, reason: String }` two-slot
// envelope) apply on their sibling one-off variants.
//
// The one wire-up site on this variant — [`WitContract::target`]'s
// HTTP-arm leading-slash gate at `if !ep.starts_with('/')`, one of the
// six per-`:contratos` value-shape gates inside the same method body,
// where the other five (`ContratoWrongTarget`, `ContratoMissingTarget`,
// `ContratoEndpointEmpty`, `ContratoEndpointInvalid`,
// `ContratoWitInvalid`) each already reach through one of the three
// peer macro-generated ctor families above — opened the same five-line
// `let (de, para) = self.edge_pair(); return
// Err(AplicacaoError::ContratoEndpointNotAbsolute { de, para, endpoint:
// ep.to_string() });` struct-literal against the local
// [`WitContract::edge_pair`] composite-projection accessor and the
// caller-side `&str` endpoint — the exact "same block re-inlined at
// every consumer" shape the PRIME DIRECTIVE names as a bug, on the same
// altitude the six peer `AplicacaoError` constructor families each
// closed on their sibling envelopes. Every guarantee in MESH-COMPOSITION
// §III.3 (a `:contratos :endpoint` value that doesn't start with `/`
// becomes a caixa-build error, not a Cilium L7 policy-side path-match
// silent traffic drop far from the source caixa.lisp) now routes through
// one substrate primitive on the envelope.
//
// The ctor below folds the site onto one dispatch:
// `return Err(AplicacaoError::contrato_endpoint_not_absolute(
// self.edge_pair(), ep));`, byte-equal to the pre-lift struct-literal
// on the same `(edge_pair, endpoint)` pair. The uniform three-field
// construction (`de, para` pair-destructure onto same-named fields +
// `endpoint: endpoint.to_string()`) is spelled once — inside the ctor
// body — rather than at the wire-up site. `#[must_use]` fires a compile
// warning at any future wire-up that mistakenly discards the constructed
// error.
//
// Every future consumer that wants to construct this variant outside
// [`WitContract::target`] (a deferred `mesh.pleme.io/v1alpha1/Aplicacao`
// CR materializer's per-`:contratos` admission validator raising the
// leading-slash diagnostic on unrecognized `:endpoint` shapes, a future
// `feira validate --contratos` per-caixa admission verb re-running the
// leading-slash arm on demand, an M4 typed Cilium L7 rule pre-emitter
// probing each declared `:endpoint` against the same shared
// HTTPPathMatch grammar prelude, a per-tenant per-`Aplicacao` overlay
// resolver rejecting a leading-slash-missing `:endpoint` against a
// cluster-local Cilium snapshot the M4 CR materializer projects) now
// reaches this variant through one call rather than re-inlining the
// five-line pair-destructure + struct-literal block in lockstep with
// the sole in-crate wire-up site.
impl AplicacaoError {
/// Construct an [`AplicacaoError::ContratoEndpointNotAbsolute`]
/// naming the offending edge `(de, para)` pair and the per-payload
/// `endpoint` value. Folds the uniform `{ de, para, endpoint:
/// endpoint.to_string() }` three-slot struct-literal onto one
/// substrate primitive so every wire-up on this variant reads
/// through one dispatch rather than the pre-lift five-line
/// pair-destructure + struct-literal block. The `edge` pair threads
/// verbatim from [`WitContract::edge_pair`] at the call site,
/// matching the sibling [`AplicacaoError::contrato_endpoint_empty`] /
/// [`AplicacaoError::contrato_endpoint_invalid`] ctors' shape on the
/// paired two-slot and four-slot per-`:contratos :endpoint`
/// envelopes on the same [`AplicacaoError`] type.
#[must_use]
pub fn contrato_endpoint_not_absolute(edge: (String, String), endpoint: &str) -> Self {
let (de, para) = edge;
Self::ContratoEndpointNotAbsolute {
de,
para,
endpoint: endpoint.to_string(),
}
}
/// Construct an [`AplicacaoError::ContratoSelfLoop`] naming the
/// offending self-edge's owning `caixa` and its `:wit` world
/// reference, projecting both slots through the [`WitContract`]'s
/// own [`WitContract::source`] and [`WitContract::world_ref`]
/// scalar accessors on the substrate primitive.
///
/// Folds the uniform `{ caixa: contract.source().to_string(), wit:
/// contract.world_ref().to_string() }` two-slot struct-literal onto
/// one substrate primitive so every wire-up on this variant reads
/// through one dispatch rather than the pre-lift four-line
/// twin-`.to_string()` struct-literal block. The `contract` borrow
/// threads verbatim from the caller-side `for c in
/// self.contratos()` iteration at the sole in-crate wire-up site
/// [`AplicacaoSpec::validate_contratos`], matching the sibling
/// per-`:contratos` `WitContract`-projection ctor discipline the
/// peer [`AplicacaoError::empty_wit`] /
/// [`AplicacaoError::contrato_endpoint_empty`] /
/// [`AplicacaoError::contrato_subject_empty`] /
/// [`AplicacaoError::contrato_slot_empty`] ctors carry through
/// [`WitContract::edge_pair`] on the sibling two-slot `{ de, para }`
/// envelope.
///
/// The `caixa` slot is projected through [`WitContract::source`]
/// rather than [`WitContract::destination`] to preserve byte-equal
/// diagnostic ordering with the pre-lift open-coded body — a
/// [`WitContract::is_self_loop`]-gated call site has
/// `source() == destination()` by that predicate's own contract, so
/// the two accessors are exchange-symmetric at this call site, but
/// naming `source` at the ctor definition matches the pre-lift
/// site's field selection and pins the discipline for any future
/// consumer that constructs the variant against a not-yet-gated
/// candidate contract (e.g. an M4
/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
/// webhook re-checking a per-`(:de, :para)` patched contract, a
/// future `feira validate --contratos` per-caixa verb re-running
/// the self-loop diagnostic on demand, a per-tenant per-Aplicacao
/// overlay resolver rejecting a self-edge introduced by a
/// cluster-local `:contratos` override the M4 CR materializer
/// projects).
///
/// Peer of the sibling `WitContract`-projection ctors on the
/// per-`:contratos` envelopes on the same [`AplicacaoError`] type —
/// same "one typed dispatch on the substrate primitive, projecting
/// through the paired [`WitContract`] accessors, thin projections
/// at each consumer" discipline extended here onto the last unlifted
/// two-slot `{ caixa: String, wit: String }` per-self-edge envelope
/// inside [`AplicacaoSpec::validate_contratos`].
#[must_use]
pub fn contrato_self_loop(contract: &WitContract) -> Self {
Self::ContratoSelfLoop {
caixa: contract.source().to_string(),
wit: contract.world_ref().to_string(),
}
}
/// Construct an [`AplicacaoError::ContratoDuplicate`] naming the
/// offending duplicate edge's `(:de, :para, :wit)` triple and the
/// per-payload `:target` byte-string, projecting the first three slots
/// through the paired [`WitContract::edge_triple`] typed-accessor and
/// the trailing `target:` slot through [`WitTarget::label`] on the
/// substrate primitive.
///
/// Folds the uniform `let (de, para, wit) = contract.edge_triple();
/// Self::ContratoDuplicate { de, para, wit, target: target.label() }`
/// six-line pair-destructure + struct-literal onto one substrate
/// primitive so every wire-up on this variant reads through one
/// dispatch rather than the pre-lift open-coded block inside the
/// [`AplicacaoSpec::validate_contratos`] whole-edge dedup closure
/// passed to [`crate::render::insert_first_seen`]. Peer of the sibling
/// [`AplicacaoError::contrato_self_loop`] (b30edfe, projecting through
/// [`WitContract::source`] / [`WitContract::world_ref`] on the paired
/// per-`:contratos` self-edge two-slot envelope) and the sibling
/// [`AplicacaoError::empty_wit`] (projecting through
/// [`WitContract::edge_pair`] on the sibling per-`:contratos` empty-
/// `:wit` two-slot envelope) `WitContract`-projection ctors on the
/// same [`AplicacaoError`] type — extended here onto the last unlifted
/// four-slot `{ de: String, para: String, wit: String, target: String }`
/// per-`:contratos` whole-edge-dedup envelope inside
/// [`AplicacaoSpec::validate_contratos`], closing the paired
/// duplicate-gate diagnostic constructor site the peer
/// [`WitContract::edge_triple`] (5dbcfaf) lift's doc-block flagged as
/// the last unlifted composite-projection wire-up.
///
/// The `contract` borrow threads verbatim from the caller-side `for c
/// in self.contratos()` iteration at the sole in-crate wire-up site
/// [`AplicacaoSpec::validate_contratos`], and `target` threads
/// verbatim from the paired `let target_view = c.target()?` local
/// materialized upstream of the [`crate::render::insert_first_seen`]
/// dedup dispatch — both project onto their respective substrate-
/// primitive accessors ([`WitContract::edge_triple`] +
/// [`WitTarget::label`]) inside the ctor body, matching the sibling
/// [`AplicacaoError::contrato_self_loop`] `WitContract`-projection
/// posture verbatim on the paired self-edge envelope.
///
/// Every future consumer that wants to construct this variant outside
/// [`AplicacaoSpec::validate_contratos`] — a deferred
/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
/// webhook re-checking a per-`(:de, :para, :wit, :target)`-patched
/// candidate against a per-tenant `:contratos` overlay before the
/// whole-edge dedup gate re-fires, a future `feira validate
/// --contratos` per-caixa admission verb re-running the dedup check on
/// demand, an M4 per-cluster contrato-cap resolver rejecting a
/// cross-tenant duplicate-edge collision introduced by a fleet-local
/// overlay the M4 CR materializer projects — now reaches this variant
/// through one call rather than re-inlining the six-line pair-
/// destructure + struct-literal block in lockstep with the existing
/// wire-up.
#[must_use]
pub fn contrato_duplicate(contract: &WitContract, target: &WitTarget<'_>) -> Self {
let (de, para, wit) = contract.edge_triple();
Self::ContratoDuplicate {
de,
para,
wit,
target: target.label(),
}
}
/// Construct an [`AplicacaoError::MembroVersaoInvalid`] naming the
/// offending `:membros :caixa` and its `:versao` requirement under
/// the given `reason`. Folds the uniform `Self::MembroVersaoInvalid {
/// caixa: caixa.to_string(), versao: versao.to_string(), reason:
/// reason.into() }` three-slot struct-literal onto one substrate
/// primitive so every wire-up on this variant reads through one
/// dispatch, matching the peer
/// [`crate::SupervisorError::child_versao_invalid`] (d2ef2ec) ctor's
/// shape verbatim on the sibling `SupervisorError { caixa: String,
/// versao: String, reason: String }` envelope's per-`:children :versao`
/// axis. `reason` accepts both `&str` literals and `format!(…)`
/// outputs through the `impl Into<String>` bound so the sole
/// [`AplicacaoSpec::validate_membros`] wire-up's per-`:membros`
/// requirement-cascade closure (routing the shared
/// [`crate::render::require_valid_versao_requirement`]-delivered
/// `reason` verbatim) picks the ctor up without a per-arm wrapper
/// transformation on the caller-side `reason` axis. The
/// [`Membro::nome`] / [`Membro::versao_requirement`] typed-accessor
/// routing the sole wire-up already threads through remains verbatim
/// — the ctor's two `&str` parameters accept the two accessors'
/// returns as-is with no re-allocation at the call site.
#[must_use]
pub fn membro_versao_invalid(caixa: &str, versao: &str, reason: impl Into<String>) -> Self {
Self::MembroVersaoInvalid {
caixa: caixa.to_string(),
versao: versao.to_string(),
reason: reason.into(),
}
}
/// Construct an [`AplicacaoError::PlacementClusterDuplicate`] naming
/// the offending `:placement :clusters` entry.
///
/// Folds the uniform `Self::PlacementClusterDuplicate { cluster:
/// cluster.to_string() }` one-field struct-literal onto one substrate
/// primitive so every wire-up on this variant reads through one
/// dispatch rather than the pre-lift three-line open-coded
/// struct-literal block. The `cluster` slot threads verbatim from the
/// caller-side `for c in p.clusters()` iteration at the sole in-crate
/// wire-up site [`AplicacaoSpec::validate_placement_shape`], via the
/// per-entry dedup closure passed to
/// [`crate::render::insert_first_seen`] whose `FnOnce`-shaped ctor
/// bracket accepts the free function pointer as-is.
///
/// Sibling of the per-`:membros :caixa` / per-`:entrada :paths` /
/// per-`:politicas <scalar>` single-slot ctor families
/// ([`aplicacao_caixa_only_ctors!`] on `{ caixa: String }` at the
/// peer per-membership envelope, [`aplicacao_path_only_ctors!`] on
/// `{ path: String }` at the peer per-gateway envelope,
/// [`aplicacao_policy_scalar_ctors!`] on `{ <field>: Copy-scalar }`
/// at the peer per-`:politicas` cap-scalar envelope) on the same
/// [`AplicacaoError`] type — extends the "one typed dispatch per
/// substrate primitive on every single-slot per-M3-slot envelope"
/// discipline onto the last unlifted `{ cluster: String }` one-slot
/// per-`:placement :clusters` dedup-envelope inside
/// [`AplicacaoSpec::validate_placement_shape`].
///
/// Every future consumer that wants to construct this variant outside
/// [`AplicacaoSpec::validate_placement_shape`] — a deferred
/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
/// webhook re-checking a `:placement :clusters` overlay against a
/// per-tenant cluster-topology snapshot, a future `feira validate
/// --placement` per-caixa admission verb re-running the dedup check
/// on demand, an M4 per-cluster placement resolver rejecting a
/// duplicate cluster-name entry introduced by a fleet-local overlay
/// the M4 CR materializer projects — now reaches this variant through
/// one call rather than re-inlining the three-line struct-literal.
#[must_use]
pub fn placement_cluster_duplicate(cluster: &str) -> Self {
Self::PlacementClusterDuplicate {
cluster: cluster.to_string(),
}
}
/// Construct an [`AplicacaoError::PlacementWithoutClusters`] naming
/// the offending `:placement :estrategia` scalar the empty `:clusters`
/// list was declared against, projecting through the paired
/// [`Placement::estrategia`] `Copy`-scalar accessor on the substrate
/// primitive.
///
/// Folds the uniform `Self::PlacementWithoutClusters { estrategia:
/// placement.estrategia() }` one-field struct-literal onto one
/// substrate primitive so every wire-up on this variant reads through
/// one dispatch rather than the pre-lift three-line open-coded
/// `AplicacaoError::PlacementWithoutClusters { estrategia:
/// p.estrategia() }` block inside
/// [`AplicacaoSpec::validate_placement`]. Same substrate-primitive-
/// projection posture as the sibling
/// [`AplicacaoError::contrato_self_loop`] (b30edfe, projecting through
/// [`WitContract::source`] / [`WitContract::world_ref`] on the paired
/// per-`:contratos` self-edge envelope) and the peer
/// [`crate::UpgradeError::duplicate_from`] (7e52aec, projecting through
/// [`crate::UpgradeFromEntry::prior_versao`] on the sibling
/// per-`:upgrade-from :from` envelope) ctors — extended here onto the
/// last unlifted `{ estrategia: PlacementStrategy }` one-slot
/// per-`:placement` empty-clusters envelope inside
/// [`AplicacaoSpec::validate_placement`].
///
/// `#[must_use]` and `const fn` alike: the ctor threads the paired
/// [`Placement::estrategia`] `Copy`-scalar return through one
/// zero-runtime-work construction — no allocation, no owned-string
/// materialization — so the pre-lift `Copy`-pass-through property the
/// open-coded `p.estrategia()` field expression carried survives
/// verbatim through the substrate primitive. The sibling
/// [`AplicacaoError::placement_cluster_duplicate`] (92b1c92) ctor
/// carries the paired `.to_string()`-owned-String allocation on the
/// `{ cluster: String }` envelope; this ctor's `Copy`-scalar envelope
/// preserves the zero-alloc posture at the substrate-primitive
/// dispatch, matching the peer
/// [`aplicacao_policy_scalar_ctors!`] (7ef425e, eight variants on
/// `{ <scalar>: Copy }`) family's `const fn` posture on the sibling
/// per-`:politicas` cap-scalar envelopes.
///
/// Every future consumer that wants to construct this variant outside
/// [`AplicacaoSpec::validate_placement`] — a deferred
/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
/// webhook re-checking a `:placement :clusters` overlay against a
/// per-tenant cluster-topology snapshot when the overlay resolves to
/// an empty list, a future `feira validate --placement` per-caixa
/// admission verb re-running the empty-clusters check on demand, an
/// M4 per-cluster placement resolver rejecting an empty cluster pool
/// after a fleet-local overlay strips every declared cluster — now
/// reaches this variant through one call rather than re-inlining the
/// three-line struct-literal in lockstep with the one in-crate
/// wire-up site.
#[must_use]
pub const fn placement_without_clusters(placement: &Placement) -> Self {
Self::PlacementWithoutClusters {
estrategia: placement.estrategia(),
}
}
/// Construct an [`AplicacaoError::ShardKeyOnNonSharded`] naming the
/// offending `:placement :estrategia` scalar and the declared-but-
/// inert `:shard-key` value the non-`Sharded` arm refused, projecting
/// the strategy through the paired [`Placement::estrategia`]
/// `Copy`-scalar accessor on the substrate primitive.
///
/// Folds the uniform `Self::ShardKeyOnNonSharded { estrategia:
/// placement.estrategia(), shard_key: shard_key.to_string() }`
/// two-slot struct-literal onto one substrate primitive so every
/// wire-up on this variant reads through one dispatch rather than
/// the pre-lift four-line open-coded struct-literal block inside
/// [`AplicacaoSpec::validate_placement`]'s
/// `PlacementStrategy::Replicated | PlacementStrategy::SingleNode`
/// arm. Same substrate-primitive-projection posture as the sibling
/// [`AplicacaoError::placement_without_clusters`] (b0d24ba,
/// projecting through [`Placement::estrategia`] on the peer
/// `{ estrategia: PlacementStrategy }` one-slot per-`:placement`
/// empty-clusters envelope) and the peer
/// [`AplicacaoError::contrato_self_loop`] (b30edfe, projecting
/// through [`WitContract::source`] / [`WitContract::world_ref`] on
/// the paired per-`:contratos` self-edge envelope) ctors — extended
/// here onto the last unlifted `{ estrategia: PlacementStrategy,
/// shard_key: String }` two-slot per-`:placement :shard-key`
/// declared-but-inert envelope on the sibling non-`Sharded`-arm
/// partition.
///
/// The `shard_key: &str` parameter accepts both the `Some(k)`-bound
/// `&str` from the sole in-crate wire-up site (narrowed from
/// `Option<&str>` via [`Placement::shard_key`]) and any future
/// `&String` deref from a downstream consumer that reaches for the
/// slot through the paired accessor, materializing the owned
/// [`String`] via one `.to_string()` at the substrate primitive so
/// no per-arm `.to_string()` allocation lives at the caller. The
/// `estrategia` slot threads through [`Placement::estrategia`]'s
/// `Copy`-scalar return rather than accepting a bare
/// [`PlacementStrategy`] argument, matching the peer
/// [`AplicacaoError::placement_without_clusters`] discipline —
/// carrying the [`Placement`] borrow through one accessor call at
/// the substrate primitive is strictly stronger than accepting the
/// scalar as a separate argument (a future caller that constructs
/// the error against a candidate [`Placement`] whose
/// [`Placement::estrategia`] value the caller re-derives from
/// another source can silently disagree with the storage the
/// [`Placement`] carries; the accessor-projected primitive cannot).
///
/// Peer of the sibling per-`:placement` single-slot / two-slot ctor
/// families on the same [`AplicacaoError`] type — same "one typed
/// dispatch on the substrate primitive, projecting through the
/// paired [`Placement`] accessors, thin projections at each
/// consumer" discipline extended here onto the last unlifted
/// per-`:placement :shard-key` non-`Sharded`-arm envelope inside
/// [`AplicacaoSpec::validate_placement`].
///
/// Every future consumer that wants to construct this variant
/// outside [`AplicacaoSpec::validate_placement`] — a deferred
/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
/// webhook re-checking a `:placement (:estrategia Replicated
/// :shard-key …)` overlay against a per-tenant cluster-topology
/// snapshot, a future `feira validate --placement` per-caixa
/// admission verb re-running the non-`Sharded`-arm refusal on
/// demand, an M4 per-cluster placement resolver rejecting a
/// declared-but-inert `:shard-key` introduced by a fleet-local
/// overlay the M4 CR materializer projects — now reaches this
/// variant through one call rather than re-inlining the four-line
/// struct-literal in lockstep with the one in-crate wire-up site.
#[must_use]
pub fn shard_key_on_non_sharded(placement: &Placement, shard_key: &str) -> Self {
Self::ShardKeyOnNonSharded {
estrategia: placement.estrategia(),
shard_key: shard_key.to_string(),
}
}
/// Construct an [`AplicacaoError::EntradaMemberMissing`] naming the
/// offending `:entrada :para` value the membership lookup against the
/// [`AplicacaoSpec::membro_names`] oracle refused, projecting the
/// slot through the paired [`Entrada::destination`] byte-string
/// accessor on the substrate primitive.
///
/// Folds the uniform `Self::EntradaMemberMissing { para:
/// entrada.destination().to_string() }` one-field struct-literal onto
/// one substrate primitive so every wire-up on this variant reads
/// through one dispatch rather than the pre-lift three-line
/// open-coded `AplicacaoError::EntradaMemberMissing { para:
/// e.destination().to_string() }` block inside
/// [`AplicacaoSpec::validate_entrada`]. Same substrate-primitive-
/// projection posture as the sibling
/// [`AplicacaoError::placement_without_clusters`] (b0d24ba,
/// projecting through [`Placement::estrategia`] on the peer
/// `{ estrategia: PlacementStrategy }` one-slot per-`:placement`
/// empty-clusters envelope) and the sibling
/// [`AplicacaoError::contrato_self_loop`] (b30edfe, projecting
/// through [`WitContract::source`] / [`WitContract::world_ref`] on
/// the paired per-`:contratos` self-edge envelope) ctors — extended
/// here onto the last unlifted `{ para: String }` one-slot
/// per-`:entrada :para` phantom-reference envelope on the sibling
/// per-`:entrada` slot.
///
/// The `entrada: &Entrada` parameter threads verbatim from the
/// caller-side `if let Some(e) = self.entrada() { … }` traversal at
/// the sole in-crate wire-up site
/// [`AplicacaoSpec::validate_entrada`], matching the sibling
/// per-`:entrada` byte-string reads that already route through
/// [`Entrada::destination`] one accessor call earlier in the same
/// gate (`validate_entrada_para(e.destination())?;` +
/// `if !names.contains(e.destination()) …`). Carrying the [`Entrada`]
/// borrow through one accessor call at the substrate primitive is
/// strictly stronger than accepting the bare `&str` as a separate
/// argument — a future consumer that constructs the error against a
/// candidate [`Entrada`] whose [`Entrada::destination`] value the
/// caller re-derives from another source (a raw `e.para` field
/// access that skipped the accessor, a stale snapshot of the
/// pre-normalization storage) can silently disagree with the
/// storage the [`Entrada`] carries; the accessor-projected primitive
/// cannot. Matches the peer
/// [`AplicacaoError::placement_without_clusters`] and
/// [`AplicacaoError::shard_key_on_non_sharded`]
/// [`Placement`]-borrow-projection discipline on the sibling
/// per-`:placement` envelope, and matches the peer
/// [`AplicacaoError::contrato_self_loop`] and
/// [`AplicacaoError::contrato_endpoint_not_absolute`]
/// [`WitContract`]-borrow-projection discipline on the sibling
/// per-`:contratos` envelope.
///
/// Every future consumer that wants to construct this variant
/// outside [`AplicacaoSpec::validate_entrada`] — a deferred
/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
/// webhook re-checking a `:entrada :para` overlay against a
/// per-tenant `:membros` snapshot after a fleet-local overlay
/// renames a member, a future `feira validate --entrada` per-caixa
/// admission verb re-running the phantom-reference lookup on
/// demand, an M4 per-cluster Gateway API pre-emitter rejecting a
/// `:entrada :para` whose target Servico was stripped from the
/// cluster-local `:membros` overlay, a future authoring-surface
/// widening the field into a `(String, Vec<Suggestion>)` pair
/// carrying a "did-you-mean-<nearest-member>" hint — now reaches
/// this variant through one call rather than re-inlining the
/// three-line struct-literal in lockstep with the one in-crate
/// wire-up site.
#[must_use]
pub fn entrada_member_missing(entrada: &Entrada) -> Self {
Self::EntradaMemberMissing {
para: entrada.destination().to_string(),
}
}
/// Construct an [`AplicacaoError::ContratoCycle`] naming the
/// synchronous-`:contratos` cycle path the DFS-with-three-coloring
/// sync-only-subgraph gate at
/// [`AplicacaoSpec::detect_sync_cycles`] reconstructed from the
/// gray-arm's back-edge target through the parent chain, folding the
/// uniform `Self::ContratoCycle { cycle }` one-field struct-literal
/// onto one substrate primitive so every wire-up on this variant
/// reads through one dispatch rather than the pre-lift open-coded
/// `AplicacaoError::ContratoCycle { cycle }` block at the sole
/// in-crate wire-up site inside
/// [`AplicacaoSpec::detect_sync_cycles`]'s gray-arm cycle-close
/// return. Same substrate-primitive-projection posture as the
/// sibling [`AplicacaoError::entrada_member_missing`] (deeae5c,
/// projecting through [`Entrada::destination`] on the peer `{ para:
/// String }` one-slot per-`:entrada :para` phantom-reference
/// envelope) and [`AplicacaoError::placement_without_clusters`]
/// (b0d24ba, projecting through [`Placement::estrategia`] on the
/// sibling `{ estrategia: PlacementStrategy }` one-slot
/// per-`:placement` empty-clusters envelope) ctors — extended here
/// onto the last unlifted `{ cycle: Vec<String> }` one-slot
/// per-`:contratos` cross-edge sync-cycle envelope on the same
/// [`AplicacaoError`] type. Closes the last unlifted `AplicacaoError`
/// struct-literal wire-up under
/// [`AplicacaoSpec::detect_sync_cycles`].
///
/// The `cycle: Vec<String>` parameter threads verbatim from the
/// caller-side DFS traversal's reconstructed cycle path (built up by
/// walking `parent` from the gray-back-edge's source node back to
/// its target, reversing, then appending the target once more so the
/// first and last elements coincide by construction and the
/// `Display` rendering under the [`AplicacaoError::ContratoCycle`]
/// `cycle.join(" → ")` formatter reads as a closed loop), matching
/// the pre-lift open-coded body's field selection exactly. Taking
/// the owned [`Vec<String>`] rather than a borrowed slice + collect
/// on the ctor side keeps the pre-lift wire-up byte-identical (the
/// caller already owns the reconstructed [`Vec<String>`] at the
/// gray-arm return, so no per-arm re-allocation lands on the ctor
/// path).
///
/// Peer of the sibling per-`:contratos` single-slot / two-slot ctor
/// families on the same [`AplicacaoError`] type — same "one typed
/// dispatch on the substrate primitive, thin projections at each
/// consumer" discipline extended here onto the last unlifted
/// per-`:contratos` cross-edge cycle envelope inside
/// [`AplicacaoSpec::detect_sync_cycles`].
///
/// Every future consumer that wants to construct this variant
/// outside [`AplicacaoSpec::detect_sync_cycles`] — a deferred
/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
/// webhook re-checking a per-tenant `:contratos` overlay's
/// sync-cycle invariant after a fleet-local overlay adds or removes
/// a synchronous edge, a future `feira validate --contratos`
/// per-caixa admission verb re-running the cross-edge cycle detector
/// on demand, the M4 per-edge policy resolver MESH-COMPOSITION §III.2
/// #3 acknowledges (whose per-edge patch mutates one `:contratos`
/// entry and needs to re-probe *just* the cycle invariant against
/// the post-patch adjacency), a future authoring-surface widening
/// the field into a `(Vec<String>, Vec<WitTarget>)` pair carrying
/// the per-hop WIT shape for a richer "break here" hint — now
/// reaches this variant through one call rather than re-inlining the
/// open-coded struct-literal in lockstep with the one in-crate
/// wire-up site.
#[must_use]
pub fn contrato_cycle(cycle: Vec<String>) -> Self {
Self::ContratoCycle { cycle }
}
/// Construct an [`AplicacaoError::PolicyBreakerWindowBelowTimeout`]
/// naming the offending `:politicas :circuit-breaker :window` and
/// the paired `:politicas :timeout` scalars under the first-firing
/// cross-axis-violation gate at
/// [`MeshPolicy::first_cross_axis_violation`], projecting the
/// `window` slot through the [`CircuitBreaker::window`] scalar
/// accessor on the substrate primitive.
///
/// Folds the uniform `{ window: cb.window(), timeout: t }`
/// two-slot `Copy`-`Duration` struct-literal onto one substrate
/// primitive so every wire-up on this variant reads through one
/// dispatch rather than the pre-lift four-line struct-literal
/// block. The `cb` borrow threads verbatim from the caller-side
/// `if let (Some(t), Some(cb)) = (self.timeout(),
/// self.circuit_breaker())` pair-destructure at the sole in-crate
/// wire-up site inside [`MeshPolicy::first_cross_axis_violation`]'s
/// window-below-timeout arm; `timeout` threads verbatim from the
/// paired [`MeshPolicy::timeout`] accessor return already
/// destructured out of the same `if let` pair. `const fn`
/// preserves the pre-lift `Copy`-pass-through's zero-runtime-work
/// property verbatim (both fields are [`Duration`], the
/// [`CircuitBreaker::window`] accessor is itself `const fn`, and
/// no `.to_string()` / `.into()` allocation lands on the ctor
/// path).
///
/// The `window` slot is projected through [`CircuitBreaker::window`]
/// (not spelled out as a bare `Duration` parameter) so a future
/// widening of the `:circuit-breaker :window` axis — a
/// per-`:contratos`-edge `:circuit-breaker :window` override the
/// MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a promotion of
/// the plain [`Duration`] window to a richer per-status-class
/// window tuple once Envoy's `outlier_detection.interval` peers
/// come into scope — reaches the diagnostic through one accessor
/// swap rather than every wire-up in lockstep, matching the peer
/// substrate-primitive-projection posture of
/// [`AplicacaoError::contrato_self_loop`] (b30edfe, projecting
/// through [`WitContract::source`] / [`WitContract::world_ref`] on
/// the sibling `{ caixa: String, wit: String }` two-slot
/// per-`:contratos` self-edge envelope),
/// [`AplicacaoError::entrada_member_missing`] (deeae5c, projecting
/// through [`Entrada::destination`] on the sibling `{ para: String }`
/// one-slot per-`:entrada :para` phantom-reference envelope), and
/// [`AplicacaoError::shard_key_on_non_sharded`] (14bafca, projecting
/// through [`Placement::estrategia`] on the sibling `{ estrategia:
/// PlacementStrategy, shard_key: String }` two-slot per-`:placement`
/// envelope) ctors carry on the sibling `:contratos` / `:entrada`
/// / `:placement` envelopes.
///
/// Peer of the sibling per-axis [`aplicacao_policy_scalar_ctors!`]
/// (7ef425e) macro that folds the eight one-slot per-`:politicas`
/// `{ <field>: Copy-scalar }` envelopes on the per-axis
/// [`MeshPolicy::validate`] gate — extended here onto the
/// first-firing cross-axis compound variant, whose multi-slot
/// `{ window: Duration, timeout: Duration }` shape does not fit
/// that macro's one-`Copy`-scalar-per-variant arity. The three
/// remaining cross-axis variants
/// ([`AplicacaoError::PolicyBreakerCannotTripUnderRateLimit`] on
/// the four-slot `{ rate, rl_window, max_failures, cb_window }`
/// envelope, [`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
/// on the two-slot `{ retries, max_failures }` envelope, and
/// [`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] on the
/// two-slot `{ retries, rate }` envelope) each carry a distinct
/// substrate-primitive-projection shape and are folded on their
/// own axis by their own per-variant ctors as those wire-ups are
/// lifted.
///
/// Every future consumer that wants to construct this variant
/// outside [`MeshPolicy::first_cross_axis_violation`] — a deferred
/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
/// webhook re-checking a per-tenant `:politicas` overlay's
/// window-vs-timeout cross-axis invariant after a cluster-local
/// `:politicas` override the MESH-COMPOSITION §III.2 #3 roadmap
/// acknowledges resolves an *effective* per-edge [`MeshPolicy`], a
/// future per-`:contratos`-edge `:politicas` override the M4 CR
/// resolver projects, an M4 per-cluster `:politicas`-cap resolver
/// projecting a per-tenant per-axis ceiling into the same
/// diagnostic shape — now reaches this variant through one call
/// rather than re-inlining the open-coded struct-literal in
/// lockstep with the one in-crate wire-up site.
#[must_use]
pub const fn policy_breaker_window_below_timeout(
cb: &CircuitBreaker,
timeout: Duration,
) -> Self {
Self::PolicyBreakerWindowBelowTimeout {
window: cb.window(),
timeout,
}
}
/// Construct an [`AplicacaoError::PolicyBreakerCannotTripUnderRateLimit`]
/// naming the `(:politicas :rate-limit, :politicas :circuit-breaker)`
/// cross-axis pair whose token-bucket window structurally starves the
/// breaker so `:max-failures` cannot be reached inside `:circuit-breaker
/// :window`.
///
/// Folds the uniform `{ rate: rl.rate(), rl_window: rl.window(),
/// max_failures: cb.max_failures(), cb_window: cb.window() }`
/// four-slot `Copy`-`(u32 | Duration)` struct-literal onto one substrate
/// primitive so every wire-up on this variant reads through one dispatch
/// rather than the pre-lift six-line struct-literal block. Both `rl` and
/// `cb` borrows thread verbatim from the caller-side `if let (Some(rl),
/// Some(cb)) = (self.rate_limit(), self.circuit_breaker())`
/// pair-destructure at the sole in-crate wire-up site inside
/// [`MeshPolicy::first_cross_axis_violation`]'s starve-under-rate-limit
/// arm. `const fn` preserves the pre-lift `Copy`-pass-through's
/// zero-runtime-work property verbatim (all four fields are `u32` /
/// [`Duration`], every projected accessor is itself `const fn`, and no
/// `.to_string()` / `.into()` allocation lands on the ctor path).
///
/// Every slot is projected through its paired substrate-primitive
/// accessor ([`RateLimit::rate`], [`RateLimit::window`],
/// [`CircuitBreaker::max_failures`], [`CircuitBreaker::window`]) rather
/// than spelled out as bare `u32` / [`Duration`] parameters so a future
/// widening of either axis — a per-`:contratos`-edge `:rate-limit` or
/// `:circuit-breaker` override the MESH-COMPOSITION §III.2 #3 roadmap
/// acknowledges, a promotion of the plain scalar rate to a richer
/// per-status-class token bucket once Envoy's per-descriptor
/// `local_rate_limit` peers come into scope — reaches the diagnostic
/// through one accessor swap rather than every wire-up in lockstep.
/// Matches the peer substrate-primitive-projection posture of
/// [`AplicacaoError::policy_breaker_window_below_timeout`] (9b30c07,
/// projecting through [`CircuitBreaker::window`] on the sibling
/// two-slot `{ window, timeout }` cross-axis
/// `(:timeout, :circuit-breaker)` envelope) on the sibling
/// first-firing cross-axis compound variant.
///
/// Second cross-axis Policy* variant folded onto its own per-variant
/// substrate primitive — extending the peer
/// [`AplicacaoError::policy_breaker_window_below_timeout`] discipline
/// onto the second-firing cross-axis compound variant, whose four-slot
/// `{ rate, rl_window, max_failures, cb_window }` shape does not fit
/// the sibling two-slot ctor's arity. The two remaining cross-axis
/// variants ([`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
/// on the two-slot `{ retries, max_failures }` envelope and
/// [`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] on the
/// two-slot `{ retries, rate }` envelope) each carry a distinct
/// substrate-primitive-projection shape and are folded on their own
/// axis by their own per-variant ctors as those wire-ups are lifted.
///
/// Every future consumer that wants to construct this variant outside
/// [`MeshPolicy::first_cross_axis_violation`] — a deferred
/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
/// webhook re-checking a per-tenant `:politicas` overlay's
/// starve-under-rate-limit cross-axis invariant after a cluster-local
/// `:politicas` override the MESH-COMPOSITION §III.2 #3 roadmap
/// acknowledges resolves an *effective* per-edge [`MeshPolicy`], a
/// future per-`:contratos`-edge `:politicas` override the M4 CR
/// resolver projects, an M4 per-cluster `:politicas`-cap resolver
/// projecting a per-tenant per-axis ceiling into the same diagnostic
/// shape — now reaches this variant through one call rather than
/// re-inlining the open-coded struct-literal in lockstep with the one
/// in-crate wire-up site.
#[must_use]
pub const fn policy_breaker_cannot_trip_under_rate_limit(
rl: &RateLimit,
cb: &CircuitBreaker,
) -> Self {
Self::PolicyBreakerCannotTripUnderRateLimit {
rate: rl.rate(),
rl_window: rl.window(),
max_failures: cb.max_failures(),
cb_window: cb.window(),
}
}
/// Construct an
/// [`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
/// naming the offending `:politicas :retries` and the paired
/// `:politicas :circuit-breaker :max-failures` scalars under the
/// third-firing cross-axis-violation gate at
/// [`MeshPolicy::first_cross_axis_violation`], projecting the
/// `max_failures` slot through the [`CircuitBreaker::max_failures`]
/// scalar accessor on the substrate primitive.
///
/// Folds the uniform `{ retries, max_failures: cb.max_failures() }`
/// two-slot `Copy`-`u32` struct-literal onto one substrate
/// primitive so every wire-up on this variant reads through one
/// dispatch rather than the pre-lift four-line struct-literal
/// block. The `cb` borrow threads verbatim from the caller-side
/// `if let (Some(retries), Some(cb)) = (self.retries(),
/// self.circuit_breaker())` pair-destructure at the sole in-crate
/// wire-up site inside [`MeshPolicy::first_cross_axis_violation`]'s
/// retries-saturate arm; `retries` threads verbatim from the paired
/// [`MeshPolicy::retries`] accessor return already destructured out
/// of the same `if let` pair. `const fn` preserves the pre-lift
/// `Copy`-pass-through's zero-runtime-work property verbatim (both
/// fields are `u32`, the [`CircuitBreaker::max_failures`] accessor
/// is itself `const fn`, and no `.to_string()` / `.into()`
/// allocation lands on the ctor path).
///
/// The `max_failures` slot is projected through
/// [`CircuitBreaker::max_failures`] (not spelled out as a bare
/// `u32` parameter) so a future widening of the
/// `:circuit-breaker :max-failures` axis — a
/// per-`:contratos`-edge `:circuit-breaker :max-failures` override
/// the MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a per-tenant
/// `:max-failures` ceiling the M4 per-cluster `:politicas`-cap
/// resolver projects, a promotion of the plain `u32` count to a
/// richer per-status-class trip counter once Envoy's
/// `outlier_detection.consecutive_5xx` peers come into scope —
/// reaches the diagnostic through one accessor swap rather than
/// every wire-up in lockstep, matching the peer
/// substrate-primitive-projection posture of
/// [`AplicacaoError::policy_breaker_window_below_timeout`]
/// (9b30c07, projecting through [`CircuitBreaker::window`] on the
/// sibling two-slot `{ window, timeout }` first cross-axis
/// envelope) and
/// [`AplicacaoError::policy_breaker_cannot_trip_under_rate_limit`]
/// (6bb4e46, projecting through [`RateLimit::rate`] /
/// [`RateLimit::window`] / [`CircuitBreaker::max_failures`] /
/// [`CircuitBreaker::window`] on the sibling four-slot second
/// cross-axis envelope). `retries` remains a bare `u32` parameter,
/// matching the sibling first-arm ctor's bare `timeout: Duration`
/// parameter discipline: [`MeshPolicy::retries`] returns
/// `Option<u32>` and the caller-side `if let` already destructures
/// the inner `u32` out, so the ctor takes the destructured scalar
/// verbatim rather than re-wrapping it into an accessor call.
///
/// Peer of the sibling per-axis [`aplicacao_policy_scalar_ctors!`]
/// (7ef425e) macro that folds the eight one-slot per-`:politicas`
/// `{ <field>: Copy-scalar }` envelopes on the per-axis
/// [`MeshPolicy::validate`] gate — extended here onto the
/// third-firing cross-axis compound variant, whose multi-slot
/// `{ retries: u32, max_failures: u32 }` shape does not fit that
/// macro's one-`Copy`-scalar-per-variant arity. The one remaining
/// cross-axis variant
/// ([`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] on the
/// two-slot `{ retries, rate }` envelope) carries a distinct
/// substrate-primitive-projection shape (projecting through
/// [`RateLimit::rate`] rather than
/// [`CircuitBreaker::max_failures`]) and is folded on its own axis
/// by its own per-variant ctor as that wire-up is lifted in a
/// follow-up run.
///
/// Every future consumer that wants to construct this variant
/// outside [`MeshPolicy::first_cross_axis_violation`] — a deferred
/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
/// webhook re-checking a per-tenant `:politicas` overlay's
/// retries-vs-max-failures cross-axis invariant after a
/// cluster-local `:politicas` override the MESH-COMPOSITION §III.2
/// #3 roadmap acknowledges resolves an *effective* per-edge
/// [`MeshPolicy`], a future per-`:contratos`-edge `:politicas`
/// override the M4 CR resolver projects, an M4 per-cluster
/// `:politicas`-cap resolver projecting a per-tenant per-axis
/// ceiling into the same diagnostic shape — now reaches this
/// variant through one call rather than re-inlining the open-coded
/// struct-literal in lockstep with the one in-crate wire-up site.
#[must_use]
pub const fn policy_breaker_trips_before_retries_exhausted(
retries: u32,
cb: &CircuitBreaker,
) -> Self {
Self::PolicyBreakerTripsBeforeRetriesExhausted {
retries,
max_failures: cb.max_failures(),
}
}
/// Construct an
/// [`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] naming
/// the offending `:politicas :retries` and the paired `:politicas
/// :rate-limit` `:rate` scalars under the fourth-firing (and last-
/// remaining) cross-axis-violation gate at
/// [`MeshPolicy::first_cross_axis_violation`], projecting the `rate`
/// slot through the [`RateLimit::rate`] scalar accessor on the
/// substrate primitive.
///
/// Folds the uniform `{ retries, rate: rl.rate() }` two-slot
/// `Copy`-`u32` struct-literal onto one substrate primitive so every
/// wire-up on this variant reads through one dispatch rather than
/// the pre-lift four-line struct-literal block. The `rl` borrow
/// threads verbatim from the caller-side `if let (Some(retries),
/// Some(rl)) = (self.retries(), self.rate_limit())` pair-destructure
/// at the sole in-crate wire-up site inside
/// [`MeshPolicy::first_cross_axis_violation`]'s starve-under-rate-
/// limit arm; `retries` threads verbatim from the paired
/// [`MeshPolicy::retries`] accessor return already destructured out
/// of the same `if let` pair. `const fn` preserves the pre-lift
/// `Copy`-pass-through's zero-runtime-work property verbatim (both
/// fields are `u32`, the [`RateLimit::rate`] accessor is itself
/// `const fn`, and no `.to_string()` / `.into()` allocation lands on
/// the ctor path).
///
/// The `rate` slot is projected through [`RateLimit::rate`] (not
/// spelled out as a bare `u32` parameter) so a future widening of
/// the `:rate-limit` `:rate` axis — a per-`:contratos`-edge
/// `:rate-limit` `:rate` override the MESH-COMPOSITION §III.2 #3
/// roadmap acknowledges, a per-tenant `:rate` ceiling the M4
/// per-cluster `:politicas`-cap resolver projects, a promotion of
/// the plain `u32` token capacity to a richer
/// `{max_tokens, tokens_per_fill}` tuple once Envoy's
/// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
/// axis comes into scope — reaches the diagnostic through one
/// accessor swap rather than every wire-up in lockstep, matching
/// the peer substrate-primitive-projection posture of
/// [`AplicacaoError::policy_breaker_window_below_timeout`] (9b30c07,
/// projecting through [`CircuitBreaker::window`] on the sibling
/// two-slot `{ window, timeout }` first cross-axis envelope),
/// [`AplicacaoError::policy_breaker_cannot_trip_under_rate_limit`]
/// (6bb4e46, projecting through [`RateLimit::rate`] /
/// [`RateLimit::window`] / [`CircuitBreaker::max_failures`] /
/// [`CircuitBreaker::window`] on the sibling four-slot second
/// cross-axis envelope), and
/// [`AplicacaoError::policy_breaker_trips_before_retries_exhausted`]
/// (f54c539, projecting through [`CircuitBreaker::max_failures`] on
/// the sibling two-slot `{ retries, max_failures }` third cross-axis
/// envelope). `retries` remains a bare `u32` parameter, matching
/// the sibling third-arm ctor's bare `retries: u32` parameter
/// discipline: [`MeshPolicy::retries`] returns `Option<u32>` and the
/// caller-side `if let` already destructures the inner `u32` out, so
/// the ctor takes the destructured scalar verbatim rather than
/// re-wrapping it into an accessor call.
///
/// Peer of the sibling per-axis [`aplicacao_policy_scalar_ctors!`]
/// (7ef425e) macro that folds the eight one-slot per-`:politicas`
/// `{ <field>: Copy-scalar }` envelopes on the per-axis
/// [`MeshPolicy::validate`] gate — extended here onto the
/// fourth-firing (and final) cross-axis compound variant, whose
/// multi-slot `{ retries: u32, rate: u32 }` shape does not fit that
/// macro's one-`Copy`-scalar-per-variant arity. After this lift all
/// four cross-axis [`MeshPolicy::first_cross_axis_violation`] arms
/// read through one substrate-primitive ctor dispatch each; the
/// per-envelope compound cross-axis Policy* family closes on this
/// variant.
///
/// Every future consumer that wants to construct this variant
/// outside [`MeshPolicy::first_cross_axis_violation`] — a deferred
/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
/// webhook re-checking a per-tenant `:politicas` overlay's
/// retries-vs-rate cross-axis invariant after a cluster-local
/// `:politicas` override the MESH-COMPOSITION §III.2 #3 roadmap
/// acknowledges resolves an *effective* per-edge [`MeshPolicy`], a
/// future per-`:contratos`-edge `:politicas` override the M4 CR
/// resolver projects, an M4 per-cluster `:politicas`-cap resolver
/// projecting a per-tenant per-axis ceiling into the same diagnostic
/// shape — now reaches this variant through one call rather than
/// re-inlining the open-coded struct-literal in lockstep with the
/// one in-crate wire-up site.
#[must_use]
pub const fn policy_rate_limit_cannot_admit_retry_burst(retries: u32, rl: &RateLimit) -> Self {
Self::PolicyRateLimitCannotAdmitRetryBurst {
retries,
rate: rl.rate(),
}
}
/// Construct an [`AplicacaoError::ContratoCaixaInvalid`] naming the
/// offending `:contratos <slot>` (`:de` / `:para`) and the value
/// that broke the shared DNS-1123-label floor under the given
/// `reason`. Folds the uniform `Self::ContratoCaixaInvalid { slot,
/// caixa: caixa.to_string(), reason: reason.into() }` three-slot
/// struct-literal onto one substrate primitive so every wire-up on
/// this variant reads through one dispatch rather than the pre-lift
/// six-line struct-literal block inside
/// [`validate_contrato_caixa`]'s
/// [`crate::render::require_valid_dns_1123_label`]
/// `|reason| …` closure.
///
/// Sibling of the per-axis [`aplicacao_field_reason_ctors!`]
/// (981060b) macro-generated ctor family
/// ([`AplicacaoError::membro_caixa_invalid`],
/// [`AplicacaoError::entrada_para_invalid`],
/// [`AplicacaoError::entrada_host_invalid`],
/// [`AplicacaoError::entrada_path_invalid`],
/// [`AplicacaoError::placement_cluster_invalid`],
/// [`AplicacaoError::placement_affinity_invalid`],
/// [`AplicacaoError::shard_key_invalid`]) — extends the "one typed
/// dispatch per substrate primitive on every `{ <field>: String,
/// reason: String }` per-axis parser-shaped envelope" discipline
/// onto the sole unlifted three-slot `{ slot: &'static str, caixa:
/// String, reason: String }` sibling whose extra `slot: &'static
/// str` axis-tag distinguishes the two-arm `:de` / `:para` cascade
/// on the per-`:contratos`-edge value axis and so does not fit the
/// two-slot macro's arity.
///
/// `slot` carries the kebab-case `:de` / `:para` tag verbatim
/// (`&'static str` is `Copy`, no allocation), matching the caller-
/// side [`crate::render::CONTRATO_AUTHOR_KEY_DE`] /
/// [`crate::render::CONTRATO_AUTHOR_KEY_PARA`] `const` strings the
/// sole in-crate wire-up threads through. `reason: impl
/// Into<String>` accepts both `&str` literals and the shared
/// [`crate::render::require_valid_dns_1123_label`]-delivered
/// owned-`String` return verbatim so the closure picks the ctor up
/// without a per-arm wrapper transformation, matching the peer
/// [`aplicacao_field_reason_ctors!`] family's `reason: impl
/// Into<String>` bound. `#[must_use]` fires a compile warning at
/// any wire-up that mistakenly discards the constructed error
/// rather than routing it through `return Err(…)` / `.map_err(…)`
/// / a closure return.
///
/// Every future consumer that wants to construct this variant
/// outside the current in-crate wire-up (the deferred
/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
/// per-`:contratos`-edge admission validator projecting the same
/// diagnostic through the caller-facing `slot: &'static str` tag,
/// a future `feira validate --contratos` per-caixa admission verb,
/// an M4 per-`:contratos`-edge pre-emitter running the same
/// DNS-1123-label floor against a caller-supplied `:de` / `:para`
/// pair before hitting the apiserver-side selector, an M4
/// per-cluster contrato-cap resolver rejecting a cross-tenant
/// selector projection into the same diagnostic shape) — now
/// reaches this variant through one call rather than re-inlining
/// the six-line struct-literal block in lockstep with the one
/// in-crate wire-up site.
#[must_use]
pub fn contrato_caixa_invalid(
slot: &'static str,
caixa: &str,
reason: impl Into<String>,
) -> Self {
Self::ContratoCaixaInvalid {
slot,
caixa: caixa.to_string(),
reason: reason.into(),
}
}
/// Construct an [`AplicacaoError::ContratoCaixaEmpty`] naming the
/// offending `:contratos <slot>` (`:de` / `:para`) at which the
/// caixa-reference value is the empty string. Folds the uniform
/// `Self::ContratoCaixaEmpty { slot }` one-slot struct-literal onto
/// one substrate primitive so the sole in-crate closure passed to
/// [`crate::render::require_valid_dns_1123_label`] at
/// [`validate_contrato_caixa`] on this variant reads through one
/// dispatch rather than the pre-lift open-coded block. The `slot`
/// label threads verbatim from the caller-side
/// [`crate::render::CONTRATO_AUTHOR_KEY_DE`] /
/// [`crate::render::CONTRATO_AUTHOR_KEY_PARA`] `const` strings the
/// wire-up feeds through [`validate_contrato_caixa`]'s
/// `slot: &'static str` parameter.
///
/// Sibling of the paired three-slot [`Self::contrato_caixa_invalid`]
/// substrate primitive on the same
/// [`crate::render::require_valid_dns_1123_label`] two-closure
/// cascade — the empty-arm and invalid-arm now both reach the
/// `AplicacaoError` envelope through one substrate primitive per
/// typed variant, closing the pair. Same shape discipline as the
/// peer [`crate::behavior::BehaviorError::empty_path`] one-slot
/// `{ slot: &'static str }` sibling on the `BehaviorError`
/// envelope's four-arm sandboxed-lisp-path cascade
/// ([`crate::render::require_sandboxed_lisp_path`]) — extended here
/// onto the sibling `AplicacaoError` envelope's two-arm
/// DNS-1123-label cascade at the `:contratos <slot>` per-edge axis.
///
/// `slot` stays `&'static str` (not `&str`) — every `:contratos
/// <slot>` tag comes from the [`crate::render::CONTRATO_AUTHOR_KEY_*`]
/// `const` roster carrying program-lifetime storage, matching the
/// enum-field type and the [`validate_contrato_caixa`] wire-up's
/// per-axis dispatch. A runtime-borrowed `&str` would silently
/// downgrade the label lifetime and let a caller stash a
/// non-`'static` borrow into the returned error. `#[must_use]` fires
/// a compile warning at any wire-up that mistakenly discards the
/// constructed error rather than routing it through `return Err(…)`
/// / `.map_err(…)` / a closure return. `pub const fn` matches the
/// peer per-envelope one-slot `Copy`-scalar ctor family discipline
/// (`aplicacao_placement_scalar_ctors!`, `layout_nome_only_ctors!`,
/// `dep_nome_only_ctors!`) so the ctor is usable in `const` position
/// at every wire-up site.
///
/// Every future consumer that wants to construct this variant
/// outside the current in-crate wire-up (the deferred
/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
/// per-`:contratos`-edge admission validator projecting the same
/// diagnostic through the caller-facing `slot: &'static str` tag,
/// a future `feira validate --contratos` per-caixa admission verb,
/// an M4 per-`:contratos`-edge pre-emitter running the same
/// DNS-1123-label floor's empty-arm against a caller-supplied
/// `:de` / `:para` pair before hitting the apiserver-side selector,
/// a per-`Caixa` overlay resolver rejecting an author-supplied
/// `:contratos` overlay's empty `:de` / `:para` against a
/// cluster-local snapshot) — now reaches this variant through one
/// call rather than re-inlining the open-coded closure block in
/// lockstep with the one in-crate wire-up site.
#[must_use]
pub const fn contrato_caixa_empty(slot: &'static str) -> Self {
Self::ContratoCaixaEmpty { slot }
}
}
// Fold the seven `AplicacaoError::{MembroCaixa, EntradaPara, EntradaHost,
// EntradaPath, PlacementCluster, PlacementAffinity, ShardKey}Invalid
// { <field>: <val>.to_string(), reason: <expr> }` wire-up sites onto one
// substrate-primitive family per typed variant — the paired
// `{ <field>: String, reason: String }` two-slot sibling on
// [`AplicacaoError`] of the peer four-slot [`contrato_target_ctors!`]
// (14b81d5, `{ de, para, wit, expected }` on `ContratoWrongTarget` /
// `ContratoMissingTarget`) and the peer two-slot
// [`contrato_empty_pair_ctors!`] (8580068, `{ de, para }` on `EmptyWit` /
// `ContratoEndpointEmpty` / `ContratoSubjectEmpty` / `ContratoSlotEmpty`)
// on the sibling per-`:contratos` envelopes, plus the peer four-family
// `LayoutError` ctor set ([`layout_violation_ctors!`] 131ca0d — 16
// variants on `{ caixa, issue }`, [`layout_slot_kind_ctors!`] 0419438 —
// 4 variants on `{ caixa, kind, slots }`, [`LayoutError::missing_entry`]
// 1b09f9d — 1 variant on `{ kind, path }`, [`layout_nome_only_ctors!`]
// 3fe3dd7 — 6 variants on `<Variant>(String)`) each carry on the
// sibling layout-side envelope.
//
// Every one of the seven wire-up sites — six under the per-axis
// `validate_*` wrappers around [`crate::render::require_valid_dns_1123_label`]
// (`validate_membro_caixa` on `MembroCaixaInvalid`, `validate_entrada_para`
// on `EntradaParaInvalid`, `validate_placement_cluster` on
// `PlacementClusterInvalid`, `validate_placement_affinity` on
// `PlacementAffinityInvalid`) plus [`crate::render::is_gateway_api_http_path`]
// (`validate_entrada_path` on `EntradaPathInvalid`), and two under
// [`validate_placement_shard_key`] (the length-cap arm and the per-byte
// printable-ASCII arm on `ShardKeyInvalid`) — plus the fourteen wire-up
// sites at [`validate_entrada_host`] (17dd504 already folded onto the
// pre-macro standalone `entrada_host_invalid` ctor, now converged onto
// the macro-generated ctor of the same name), opened the identical
// four-line `AplicacaoError::<Variant>Invalid
// { <field>: <val>.to_string(), reason: <expr> }` struct-literal against
// the local `<field>: &str` argument — the exact "same block re-inlined
// at every consumer" shape the PRIME DIRECTIVE names as a bug, on the
// same altitude the peer three `AplicacaoError` constructor families
// and the four peer `LayoutError` constructor families each closed on
// their sibling envelopes.
//
// The macro below generates one `#[must_use]` inherent constructor per
// variant of shape `fn <ctor>(<field>: &str, reason: impl Into<String>)
// -> AplicacaoError`, collapsing every site onto one dispatch per arm:
// `return Err(AplicacaoError::<ctor>(<val>, <reason>));` /
// `|reason| AplicacaoError::<ctor>(<val>, reason)`, byte-equal to the
// pre-lift struct-literal on the same `(<field>, reason)` pair. The
// uniform two-field construction (`<field>: <val>.to_string()`,
// `reason: reason.into()`) is spelled once — inside the macro — rather
// than at every wire-up site. The `reason: impl Into<String>` bound
// accepts both `&str` literals (with or without a trailing
// `.to_string()` at the caller) and `format!(…)` outputs verbatim so no
// wire-up site changes its per-arm diagnostic shape at the lift.
// `#[must_use]` fires a compile warning at any wire-up that mistakenly
// discards the constructed error rather than routing it through
// `return Err(…)` / `.map_err(…)` / a closure return.
//
// Every future consumer that wants to construct one of these seven
// variants outside the current in-crate wire-up sites (the deferred
// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-slot
// admission validators, a future `feira validate --<axis>` per-caixa
// admission verb, a per-`Certificate` SAN pre-emitter for cert-manager
// on `:entrada :host`, an M4 typed placement-engine per-cluster /
// per-affinity / per-shard-key pre-emitter, an M4 typed Gateway API
// per-path pre-emitter) reaches the variant through one call rather
// than re-inlining the four-line struct-literal block in lockstep with
// the current in-crate wire-up sites.
macro_rules! aplicacao_field_reason_ctors {
($($ctor:ident => $variant:ident { $field:ident }),* $(,)?) => {
impl AplicacaoError {
$(
#[doc = concat!(
"Construct an [`AplicacaoError::",
stringify!($variant),
"`] naming the offending `",
stringify!($field),
"` under the given `reason`. Folds the uniform ",
"`{ ",
stringify!($field),
": ",
stringify!($field),
".to_string(), reason: reason.into() }` two-slot ",
"construction onto one substrate primitive so every ",
"wire-up on this variant reads through one dispatch ",
"rather than the pre-lift four-line struct-literal ",
"block. `reason` accepts both `&str` literals and ",
"`format!(…)` outputs through the `impl Into<String>` ",
"bound."
)]
#[must_use]
pub fn $ctor($field: &str, reason: impl Into<String>) -> Self {
Self::$variant {
$field: $field.to_string(),
reason: reason.into(),
}
}
)*
}
};
}
aplicacao_field_reason_ctors! {
membro_caixa_invalid => MembroCaixaInvalid { caixa },
entrada_para_invalid => EntradaParaInvalid { para },
entrada_host_invalid => EntradaHostInvalid { host },
entrada_path_invalid => EntradaPathInvalid { path },
placement_cluster_invalid => PlacementClusterInvalid { cluster },
placement_affinity_invalid => PlacementAffinityInvalid { affinity },
shard_key_invalid => ShardKeyInvalid { shard_key },
}
// Fold the four `AplicacaoError::Contrato{Endpoint,Subject,Slot,Wit}Invalid
// { de, para, <field>: <val>.to_string(), reason }` wire-up sites at
// [`WitContract::target`] onto one substrate-primitive family per typed
// variant — the paired `{ de: String, para: String, <field>: String,
// reason: String }` four-slot sibling on [`AplicacaoError`] of the peer
// four-slot [`contrato_target_ctors!`] (14b81d5, `{ de, para, wit,
// expected }` on `ContratoWrongTarget` / `ContratoMissingTarget`), the
// peer two-slot [`contrato_empty_pair_ctors!`] (8580068, `{ de, para }`
// on `EmptyWit` / `ContratoEndpointEmpty` / `ContratoSubjectEmpty` /
// `ContratoSlotEmpty`), and the peer two-slot
// [`aplicacao_field_reason_ctors!`] (981060b, `{ <field>: String,
// reason: String }` on `MembroCaixaInvalid` / `EntradaParaInvalid` /
// `EntradaHostInvalid` / `EntradaPathInvalid` / `PlacementClusterInvalid`
// / `PlacementAffinityInvalid` / `ShardKeyInvalid`) each carry on the
// sibling `AplicacaoError` envelopes, plus the peer four-family
// `LayoutError` ctor set on the sibling layout-side envelope.
//
// Every one of the four wire-up sites — four per-`:contratos` value-
// shape gates inside [`WitContract::target`] (the world-ref prefix
// [`crate::render::is_wit_world_ref`] failure on `:wit`, the HTTP arm's
// [`crate::render::is_gateway_api_http_path`] failure on `:endpoint`,
// the pub-sub arm's [`crate::render::is_nats_subject`] failure on
// `:subject`, the store arm's [`crate::render::is_wasi_keyvalue_slot`]
// failure on `:slot`) — opened the identical five-line
// `let (de, para) = self.edge_pair();
// return Err(AplicacaoError::Contrato<Field>Invalid { de, para,
// <field>: <val>.to_string(), reason });` block against the local
// [`WitContract::edge_pair`] composite-projection accessor and the
// per-arm `<val>: &str` argument — the exact "same block re-inlined at
// every consumer" shape the PRIME DIRECTIVE names as a bug, on the same
// altitude the peer three `AplicacaoError` constructor families and the
// four peer `LayoutError` constructor families each closed on their
// sibling envelopes. Absorbing `ContratoWitInvalid` onto the same
// macro closes the last unlifted `{ de, para, <field>: String, reason:
// String }` four-slot envelope inside `impl WitContract`, so every
// per-`:contratos` value-shape diagnostic on [`AplicacaoError`] now
// reads through this one substrate primitive.
//
// The macro below generates one `#[must_use]` inherent constructor per
// variant of shape `fn <ctor>(edge: (String, String), <field>: &str,
// reason: impl Into<String>) -> AplicacaoError`, collapsing the four
// sites onto one dispatch per arm:
// `return Err(AplicacaoError::<ctor>(self.edge_pair(), <val>, reason));`,
// byte-equal to the pre-lift struct-literal on the same
// `(edge_pair, <val>, reason)` triple. The uniform four-field
// construction (`de, para` pair-destructure onto same-named fields +
// `<field>: <val>.to_string()` + `reason: reason.into()`) is spelled
// once — inside the macro — rather than at every wire-up site. The
// `reason: impl Into<String>` bound accepts both `&str` literals and
// `format!(…)` outputs verbatim so no wire-up site changes its per-arm
// diagnostic shape at the lift, matching the peer
// [`aplicacao_field_reason_ctors!`] bound on the sibling two-slot
// envelope. `#[must_use]` fires a compile warning at any wire-up that
// mistakenly discards the constructed error.
//
// Every future consumer that wants to construct one of these four
// variants outside [`WitContract::target`] (a deferred
// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-`:contratos`
// admission validator raising per-payload value-shape diagnostics on
// unrecognized `:wit` / `:endpoint` / `:subject` / `:slot` shapes, a
// future `feira validate --contratos` per-caixa admission verb, an M4
// typed WIT-registry-driven per-arm pre-emitter probing each declared
// `:endpoint` / `:subject` / `:slot` payload against a canonical
// per-arm shape gate, a per-`Certificate` SAN pre-emitter for
// cert-manager on the `:endpoint` axis, an M4 typed Cilium L7 rule
// pre-emitter probing each `:endpoint` against the same shared
// HTTPPathMatch grammar) reaches the variant through one call rather
// than re-inlining the five-line pair-destructure + struct-literal
// block in lockstep with the four in-crate wire-up sites.
macro_rules! contrato_pair_value_reason_ctors {
($($ctor:ident => $variant:ident { $field:ident }),* $(,)?) => {
impl AplicacaoError {
$(
#[doc = concat!(
"Construct an [`AplicacaoError::",
stringify!($variant),
"`] naming the offending edge `(de, para)` pair, the ",
"per-payload `",
stringify!($field),
"` value, and the parser-shaped `reason`. Folds the ",
"uniform `{ de, para, ",
stringify!($field),
": ",
stringify!($field),
".to_string(), reason: reason.into() }` four-slot ",
"construction onto one substrate primitive so every ",
"wire-up on this variant reads through one dispatch ",
"rather than the pre-lift five-line pair-destructure ",
"+ struct-literal block. The `edge` pair threads ",
"verbatim from [`WitContract::edge_pair`] at the ",
"call site; `reason` accepts both `&str` literals ",
"and `format!(…)` outputs through the `impl ",
"Into<String>` bound."
)]
#[must_use]
pub fn $ctor(edge: (String, String), $field: &str, reason: impl Into<String>) -> Self {
let (de, para) = edge;
Self::$variant {
de,
para,
$field: $field.to_string(),
reason: reason.into(),
}
}
)*
}
};
}
contrato_pair_value_reason_ctors! {
contrato_endpoint_invalid => ContratoEndpointInvalid { endpoint },
contrato_subject_invalid => ContratoSubjectInvalid { subject },
contrato_slot_invalid => ContratoSlotInvalid { slot },
contrato_wit_invalid => ContratoWitInvalid { wit },
}
// Fold the five `AplicacaoError::{ContratoMemberMissing, MembroVersaoEmpty,
// MembroDuplicate, MembroIsSelfAplicacao} { caixa: <&str>.to_string() }`
// caixa-only struct-variant wire-up sites at
// [`WitContract::require_endpoints_in`] (two sites, the `:contratos :de` and
// `:contratos :para` arms of `ContratoMemberMissing`),
// [`AplicacaoSpec::validate_membros`] (two sites, the empty-`:versao` arm of
// `MembroVersaoEmpty` and the per-`:membros` dedup arm of `MembroDuplicate`),
// and [`validate_no_self_membership`] (one site, the parent-`:nome`
// self-membership arm of `MembroIsSelfAplicacao`) onto one substrate primitive
// per typed variant — the sibling on the M3 mesh `AplicacaoError` envelope of
// the peer [`crate::supervisor::supervisor_caixa_only_ctors!`] macro (db09650,
// three variants on `{ caixa: String }` at
// [`crate::SupervisorSpec::validate_children`] and
// [`crate::supervisor::validate_no_self_supervision`]) on the sibling M2
// `SupervisorError` envelope, extending the same "one substrate primitive per
// typed variant on the single-slot `{ <ident>: String }` envelope shape" fold
// discipline onto the M3 mesh side. Peers on peer envelopes: the M2 sibling
// [`crate::behavior::behavior_slot_path_ctors!`] (67c31ec, 3 variants on
// `{ slot: &'static str, path: PathBuf }`) two-slot fold on the `:behavior`
// envelope; the M2 sibling [`crate::upgrade::upgrade_from_script_ctors!`]
// (8e67041, 3 variants on `{ from: String, script: PathBuf }`) and
// [`crate::upgrade::upgrade_script_only_ctors!`] (7468ca9, 3 variants on
// `{ script: PathBuf }`) two folds on the sibling `:upgrade-from` envelope;
// the sibling [`crate::dep::dep_nome_only_ctors!`] (792aa92, 5 variants on
// `{ nome: String }`), [`crate::dep::fonte_caminho_ctors!`] (f85f145, 11
// variants on `{ nome, caminho }`), and
// [`crate::dep::fonte_caminho_byte_ctors!`] (0e35793, 12 variants on
// `{ nome, caminho, byte }`) folds on the sibling `DepError` envelope; the
// peer three `AplicacaoError` sub-family folds already lifted here
// ([`contrato_target_ctors!`] 14b81d5, [`contrato_empty_pair_ctors!`] 8580068,
// [`aplicacao_field_reason_ctors!`] 981060b,
// [`contrato_pair_value_reason_ctors!`] 14e13f1); the peer four `LayoutError`
// families ([`crate::layout::layout_violation_ctors!`] 131ca0d,
// [`crate::layout::layout_slot_kind_ctors!`] 0419438,
// [`crate::LayoutError::missing_entry`] 1b09f9d,
// [`crate::layout::layout_nome_only_ctors!`] 3fe3dd7); and the three
// [`crate::limits::limits_codec_value_*_ctors!`] codec families (81c856c).
//
// Each of the five wire-up sites on this shape (two on `ContratoMemberMissing`
// at the per-`:contratos :de`/`:para` unknown-member arms, one on
// `MembroVersaoEmpty` at the per-`:membros` empty-semver-requirement arm, one
// on `MembroDuplicate` at the per-`:membros` dedup arm, one on
// `MembroIsSelfAplicacao` at the parent-`:nome` self-membership arm) opened
// the identical `AplicacaoError::<Variant> { caixa: <&str>.to_string() }`
// three-line struct-literal against a caller-side `&str` — the exact "same
// block re-inlined at every consumer" shape the PRIME DIRECTIVE names as a
// bug, on the same altitude the peer `SupervisorError` /
// `AplicacaoError` (three prior sub-families) / `DepError` / `LayoutError` /
// `UpgradeError` / `BehaviorError` / `LimitsError` families each closed on
// their sibling envelopes. The four variants share one `{ caixa: String }`
// shape, so the fold routes each wire-up site through one dispatch per typed
// variant.
//
// The macro below generates one `#[must_use]` inherent constructor per
// variant of shape `fn <ctor>(caixa: &str) -> AplicacaoError`, so every
// wire-up site collapses onto one dispatch:
// `AplicacaoError::<ctor>(<&str>)`, byte-equal to the pre-lift struct-literal
// on the same `&str` fixture. The uniform one-field construction
// (`caixa: caixa.to_string()`) is spelled once — inside the macro — rather
// than at every wire-up site. Every constructor is `#[must_use]` so a caller
// who mistakenly discards the constructed error trips a compile warning at
// the wire-up site.
//
// Every future consumer that wants to construct one of these four variants
// outside the current in-crate wire-up sites — a deferred
// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission webhook
// re-checking one added/renamed `:membros` entry against the sibling
// `:contratos` graph, a future `feira validate --membros` per-caixa admission
// verb re-checking each declared `:membros` entry's `:caixa` name against the
// same axes, a per-tenant per-`Aplicacao` overlay resolver rejecting a
// duplicate / self-referencing / unknown-membered `:contratos` entry against
// a cluster-local snapshot the M4 CR materializer projects — now reaches each
// variant through one call rather than re-inlining the three-line
// struct-literal in lockstep with the five in-crate wire-up sites.
macro_rules! aplicacao_caixa_only_ctors {
($($ctor:ident => $variant:ident),* $(,)?) => {
impl AplicacaoError {
$(
#[doc = concat!(
"Construct an [`AplicacaoError::",
stringify!($variant),
"`] naming the offending `:membros :caixa` (or ",
"parent `:nome`, on the self-membership arm; or ",
"`:contratos :de`/`:para`, on the unknown-member ",
"arm). Folds the uniform `Self::",
stringify!($variant),
" { caixa: caixa.to_string() }` one-field ",
"struct-literal onto one substrate primitive so ",
"every wire-up on this variant reads through one ",
"dispatch rather than the pre-lift three-line ",
"open-coded struct-literal block."
)]
#[must_use]
pub fn $ctor(caixa: &str) -> Self {
Self::$variant { caixa: caixa.to_string() }
}
)*
}
};
}
aplicacao_caixa_only_ctors! {
contrato_member_missing => ContratoMemberMissing,
membro_versao_empty => MembroVersaoEmpty,
membro_duplicate => MembroDuplicate,
membro_is_self_aplicacao => MembroIsSelfAplicacao,
}
// Fold the three `AplicacaoError::{EntradaPathNotAbsolute,
// EntradaPathDuplicate} { path: <val>.to_string() | <val>.clone() }` wire-up
// sites onto one substrate-primitive family per typed variant — the direct
// per-`:entrada :paths` value-shape sibling of the peer
// `aplicacao_caixa_only_ctors!` (d9f6867, `{ caixa: String }` on
// `ContratoMemberMissing` / `MembroVersaoEmpty` / `MembroDuplicate` /
// `MembroIsSelfAplicacao`) on the sibling per-`:membros :caixa` envelope, and
// per-`:entrada :para` sibling of the peer `contrato_empty_pair_ctors!`
// (8580068, `{ de, para }` on `EmptyWit` / `ContratoEndpointEmpty` /
// `ContratoSubjectEmpty` / `ContratoSlotEmpty`) on the per-`:contratos` edge
// envelope. Same shape family as the [`crate::dep::dep_nome_only_ctors!`]
// (792aa92, `{ nome: String }` on five `DepError` variants) fold on the peer
// `:deps` envelope — every single-`String`-slot error family in caixa-core
// now reaches through one substrate primitive per typed variant.
//
// The three wire-up sites — one under [`validate_entrada_path`]'s
// leading-slash grammar arm (`EntradaPathNotAbsolute` against
// `path: &str`), one under the per-`:entrada :paths` loop's identical
// arm (`EntradaPathNotAbsolute` against a `&String` head via `.clone()`),
// and one under the per-`:entrada :paths` loop's dedup arm
// (`EntradaPathDuplicate` against the same `&String` via
// [`crate::render::insert_first_seen`]'s ctor closure) — opened the identical
// `AplicacaoError::EntradaPath<Variant> { path: <val>.to_string() | .clone() }`
// three-line struct-literal against a caller-side `&str` / `&String`, the
// exact "same block re-inlined at every consumer" shape the PRIME DIRECTIVE
// names as a bug. Every one of the compile-time guarantees in
// MESH-COMPOSITION.md §III.3 (a `:entrada :paths` entry whose value doesn't
// start with `/` becomes a caixa-build error, not a Gateway API webhook
// rejection at `kubectl apply` time; a duplicated `:entrada :paths` entry
// becomes a caixa-build error, not a silent last-writer-wins render) now
// routes through one dispatch per typed variant at every emit site.
//
// The macro below generates one `#[must_use]` inherent constructor per
// variant of shape `fn <ctor>(path: &str) -> AplicacaoError`, collapsing
// every wire-up site onto one dispatch:
// `AplicacaoError::<ctor>(<path>)` (byte-equal to the pre-lift struct-literal
// on the same `&str` fixture) or the `&String` sites through
// `p.as_str()` (byte-equal on the same slice-view). The uniform one-field
// construction (`path: path.to_string()`) is spelled once — inside the
// macro — rather than at every wire-up site. Every ctor is `#[must_use]` so
// a caller who mistakenly discards the constructed error trips a compile
// warning at the wire-up site.
//
// Every future consumer that wants to construct one of these two variants
// outside the current in-crate wire-up sites — a deferred
// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission webhook
// per-`:entrada :paths` re-check against a cluster-local Gateway API
// snapshot, a future `feira validate --entrada` per-caixa admission verb
// re-checking each declared `:paths` entry against the same axes, a
// per-tenant per-`Aplicacao` overlay resolver rejecting a
// duplicate / non-absolute `:paths` entry against a cluster-local Gateway
// snapshot the M4 CR materializer projects — now reaches each variant
// through one call rather than re-inlining the three-line struct-literal in
// lockstep with the three in-crate wire-up sites.
macro_rules! aplicacao_path_only_ctors {
($($ctor:ident => $variant:ident),* $(,)?) => {
impl AplicacaoError {
$(
#[doc = concat!(
"Construct an [`AplicacaoError::",
stringify!($variant),
"`] naming the offending `:entrada :paths` entry. ",
"Folds the uniform `Self::",
stringify!($variant),
" { path: path.to_string() }` one-field ",
"struct-literal onto one substrate primitive so ",
"every wire-up on this variant reads through one ",
"dispatch rather than the pre-lift three-line ",
"open-coded struct-literal block."
)]
#[must_use]
pub fn $ctor(path: &str) -> Self {
Self::$variant { path: path.to_string() }
}
)*
}
};
}
aplicacao_path_only_ctors! {
entrada_path_not_absolute => EntradaPathNotAbsolute,
entrada_path_duplicate => EntradaPathDuplicate,
}
// Fold the eight `AplicacaoError::Policy<Slot><Axis> { <field>: <val> }`
// one-slot `Copy`-scalar wire-up sites at [`MeshPolicy::validate`] onto one
// substrate-primitive family per typed variant — the per-`:politicas` copy-
// scalar `{ timeout | retries | max_failures | window | rate: Duration | u32 }`
// sibling of the peer per-`:membros :caixa` [`aplicacao_caixa_only_ctors!`]
// (d9f6867, `{ caixa: String }` on `ContratoMemberMissing` /
// `MembroVersaoEmpty` / `MembroDuplicate` / `MembroIsSelfAplicacao`) and the
// peer per-`:entrada :paths` [`aplicacao_path_only_ctors!`] (3ba8de6,
// `{ path: String }` on `EntradaPathNotAbsolute` / `EntradaPathDuplicate`) on
// the `String`-slot axis, and the peer per-`:politicas` cross-axis
// [`AplicacaoError::Policy*`] cascade [`MeshPolicy::first_cross_axis_violation`]
// carries at line 3064 on the same M3 mesh envelope.
//
// The eight wire-up sites inside [`MeshPolicy::validate`] at lines 3170-3218
// each opened the identical `|<slot>| AplicacaoError::Policy<Slot><Axis>
// { <slot> }` one-line struct-literal closure against the caller-side
// `<slot>: <ty>` argument that the shared
// [`crate::render::require_positive_bounded_u32`] /
// [`crate::render::require_positive_canonical_bounded_duration`] gate rebinds
// verbatim under the `impl FnOnce(u32) -> AplicacaoError` /
// `impl FnOnce(Duration) -> AplicacaoError` bracket-closure slots (plus one
// direct `return Err(AplicacaoError::PolicyRateLimitWindowNotCanonical
// { window: rl.window() })` at the `:rate-limit :window` canonical-form arm
// on line 3211) — the exact "same one-line struct-literal re-inlined at every
// consumer" shape the PRIME DIRECTIVE names as a bug, on the last remaining
// per-`:politicas` per-axis `AplicacaoError` variant family that had not yet
// been folded onto a substrate primitive.
//
// The macro below generates one `#[must_use] pub const fn <ctor>(<field>: <ty>)
// -> AplicacaoError` per variant of shape `Self::<variant> { <field> }`,
// collapsing every wire-up onto either one direct dispatch
// (`return Err(AplicacaoError::<ctor>(<val>))`, byte-equal to the pre-lift
// struct-literal on the same `Copy`-`<ty>` fixture) or one bare function
// pointer at the `impl FnOnce(<ty>) -> AplicacaoError` bracket-closure slot
// (`AplicacaoError::<ctor>` in the position where every pre-lift site spelled
// `|<slot>| AplicacaoError::<Variant> { <slot> }`) — Rust's function-pointer-
// to-`FnOnce` coercion on any `fn(<ty>) -> AplicacaoError` inherent
// constructor with matching arity and signature. The `const fn` qualifier
// preserves the pre-lift `Copy`-pass-through's zero-runtime-work property
// verbatim (no `.to_string()` / `.into()` allocation, no branching); the
// per-variant `$field:ident` axis re-uses the enum's canonical field name so
// the generated ctor's parameter name matches every wire-up's local binding
// (`|timeout|` calls `policy_timeout_not_canonical(timeout)`, etc.), matching
// the peer [`aplicacao_field_reason_ctors!`] / [`aplicacao_caixa_only_ctors!`]
// / [`aplicacao_path_only_ctors!`] convention. `#[must_use]` fires a compile
// warning at any wire-up that mistakenly discards the constructed error, on
// the same footing as every sibling `AplicacaoError` / `DepError` /
// `SupervisorError` / `LayoutError` / `LimitsError` / `BehaviorError` /
// `UpgradeError` ctor macro (14b81d5 / 8580068 / 981060b / 14e13f1 / 81c856c
// / 8e67041 / 7468ca9 / 67c31ec / d2ef2ec / f85f145 / 0e35793 / 792aa92 /
// 6f5e0cd / 3fe3dd7 / 1b09f9d / 131ca0d / 0419438).
//
// Every future consumer that wants to construct one of these eight variants
// outside [`MeshPolicy::validate`] — a deferred
// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission webhook re-
// checking each `:politicas` axis against a cluster-local `:politicas` cap
// overlay, a future per-`:contratos`-edge `:politicas` override the
// MESH-COMPOSITION §III.2 #3 roadmap acknowledges resolving an *effective*
// per-edge [`MeshPolicy`] and emitting the same per-axis diagnostic on the
// same input as `feira build`, an M4 per-cluster `:politicas`-cap resolver
// projecting a per-tenant per-axis ceiling into the same diagnostic shape,
// a future `feira validate --politicas` per-caixa admission verb re-checking
// each declared per-axis value against the same bounds — now reaches each
// variant through one call rather than re-inlining the one-line struct-
// literal in lockstep with the seven `MeshPolicy::validate` wire-up sites,
// which is exactly the invariant every prior ctor-macro lift already closed
// on its sibling envelope. Closes the last remaining per-`:politicas`
// per-axis `AplicacaoError` variant family that had not yet been folded onto
// a substrate primitive; the compound cross-axis variants
// ([`AplicacaoError::PolicyBreakerWindowBelowTimeout`] / `*RateLimit` /
// `*RetriesBurst`) each carry a distinct multi-slot field shape and are folded
// on a separate axis by [`MeshPolicy::first_cross_axis_violation`].
macro_rules! aplicacao_policy_scalar_ctors {
($($ctor:ident => $variant:ident { $field:ident: $ty:ty }),* $(,)?) => {
impl AplicacaoError {
$(
#[doc = concat!(
"Construct an [`AplicacaoError::",
stringify!($variant),
"`] naming the offending per-`:politicas` `",
stringify!($field),
"` scalar. Folds the uniform `Self::",
stringify!($variant),
" { ",
stringify!($field),
" }` one-field `Copy`-pass-through struct-literal onto ",
"one substrate primitive so every per-axis wire-up on ",
"this variant reads through one dispatch — as a direct ",
"call (`AplicacaoError::",
stringify!($ctor),
"(<val>)`, byte-equal to the pre-lift struct-literal on ",
"the same `Copy`-`",
stringify!($ty),
"` fixture) or as a bare function pointer in the ",
"`impl FnOnce(",
stringify!($ty),
") -> AplicacaoError` bracket-closure slot every ",
"`crate::render::require_positive_bounded_*` / ",
"`crate::render::require_positive_canonical_bounded_*` ",
"gate carries — rather than the pre-lift open-coded ",
"one-line closure over the same one-field struct-",
"literal. `const fn` preserves the `Copy`-pass-through's ",
"zero-runtime-work property verbatim."
)]
#[must_use]
pub const fn $ctor($field: $ty) -> Self {
Self::$variant { $field }
}
)*
}
};
}
aplicacao_policy_scalar_ctors! {
policy_timeout_not_canonical => PolicyTimeoutNotCanonical { timeout: Duration },
policy_timeout_exceeds_cap => PolicyTimeoutExceedsCap { timeout: Duration },
policy_retries_exceeds_cap => PolicyRetriesExceedsCap { retries: u32 },
policy_breaker_max_failures_exceeds_cap =>
PolicyBreakerMaxFailuresExceedsCap { max_failures: u32 },
policy_breaker_window_not_canonical =>
PolicyBreakerWindowNotCanonical { window: Duration },
policy_breaker_window_exceeds_cap =>
PolicyBreakerWindowExceedsCap { window: Duration },
policy_rate_limit_exceeds_cap => PolicyRateLimitExceedsCap { rate: u32 },
policy_rate_limit_window_not_canonical =>
PolicyRateLimitWindowNotCanonical { window: Duration },
}
#[cfg(test)]
mod tests {
use super::*;
fn membro(name: &str, ver: &str) -> Membro {
Membro {
caixa: name.into(),
versao: ver.into(),
}
}
fn contract_http(de: &str, para: &str, ep: &str) -> WitContract {
WitContract {
de: de.into(),
para: para.into(),
wit: "wasi:http/proxy".into(),
endpoint: Some(ep.into()),
subject: None,
slot: None,
}
}
fn three_member_spec() -> AplicacaoSpec {
AplicacaoSpec {
membros: vec![
membro("catalog", "^0.1"),
membro("cart", "^0.1"),
membro("payment", "^0.2"),
],
contratos: vec![
contract_http("cart", "catalog", "/products/:id"),
contract_http("cart", "payment", "/charge"),
],
politicas: MeshPolicy {
timeout: Some(Duration::from_secs(30)),
retries: Some(3),
mtls_required: Some(true),
..Default::default()
},
placement: Placement {
estrategia: PlacementStrategy::Replicated,
clusters: vec!["rio".into(), "mar".into()],
affinity: Some("data-locality".into()),
shard_key: None,
},
entrada: Some(Entrada {
host: "checkout.quero.cloud".into(),
para: "cart".into(),
paths: vec!["/api/cart".into(), "/api/products".into()],
port: 8080,
}),
}
}
#[test]
fn happy_path_validates() {
three_member_spec().validate().unwrap();
}
#[test]
fn rejects_empty_membros() {
let mut s = three_member_spec();
s.membros = vec![];
assert_eq!(s.validate().unwrap_err(), AplicacaoError::NoMembros);
}
#[test]
fn rejects_empty_membro_caixa() {
// A `:caixa ""` entry has no name to render into programs.yaml
// and no caixa.lisp to resolve at lacre time.
let mut s = three_member_spec();
s.membros[1].caixa = String::new();
assert_eq!(s.validate().unwrap_err(), AplicacaoError::MembroCaixaEmpty);
}
#[test]
fn rejects_empty_membro_versao() {
// A `:versao ""` entry can't pin a semver constraint, so the
// lacre pipeline fails far from the source.
let mut s = three_member_spec();
s.membros[2].versao = String::new();
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "payment"),
"got {err:?}"
);
}
#[test]
fn rejects_duplicate_membro_caixa() {
// Two `:membros` entries with the same `:caixa` collapse to one
// node in the membership HashSet, which masks `:contratos`
// membership errors and produces duplicate programs.yaml entries.
let mut s = three_member_spec();
s.membros.push(membro("cart", "^0.2"));
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
"got {err:?}"
);
}
#[test]
fn rejects_invalid_membro_versao_requirement() {
// The fail-before-pass-after pin: a non-empty but malformed
// semver requirement (`"^bad-version"`) silently passed
// `validate()` on every pre-gate codebase because the prior
// shape only refused the empty string. The parse failure
// surfaced far downstream at lacre-resolve time with a
// `semver::Error` that didn't name which `:membros` entry
// carried the typo. The new gate moves the check to caixa-build
// time at the source caixa.lisp.
let mut s = three_member_spec();
s.membros[2].versao = "^bad-version".into();
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
if caixa == "payment" && versao == "^bad-version"
),
"got {err:?}"
);
}
#[test]
fn rejects_membro_versao_with_double_caret_typo() {
// `"^^0.1"` is the canonical doubled-caret typo — looks like a
// Cargo-shaped requirement on first glance but fails the parser
// because semver doesn't accept stacked operators. Pin this
// adjacent-shape footgun explicitly so a future relaxation that
// accepts "looks-canonical-but-isn't" forms surfaces here.
let mut s = three_member_spec();
s.membros[0].versao = "^^0.1".into();
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
if caixa == "catalog" && versao == "^^0.1"
),
"got {err:?}"
);
}
#[test]
fn rejects_membro_versao_with_v_prefixed_tag() {
// `"v0.1"` is the canonical "git-tag-shape leaking into the
// semver requirement slot" typo — an author copies the
// publish-side git-tag string verbatim into `:versao`, but
// Cargo's semver parser rejects the leading `v` (only digits +
// canonical operators are valid in the major-version
// position). The gate's diagnostic names which member entry
// carried the v-prefix so the fix is one edit, not a grep
// through every member's `:versao`. (Note: bare `x`-glob
// shorthands like `^0.1.x` are *accepted* by the semver crate
// as an `*` wildcard on the patch axis — they're a Cargo-side
// valid shape, not a typo, so the gate intentionally lets them
// through.)
let mut s = three_member_spec();
s.membros[1].versao = "v0.1".into();
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
if caixa == "cart" && versao == "v0.1"
),
"got {err:?}"
);
}
#[test]
fn accepts_canonical_membro_versao_forms() {
// The four Cargo-shaped requirement forms `:deps :versao`
// already accepts via `crate::parse_requirement` must pass the
// membros gate without re-validating at the resolver layer.
// Pin every leg so a future tightening of the canonical set
// surfaces here as a test failure.
for form in [
"^0.1", // caret — minor-range pin (the most common shape)
"~0.1.2", // tilde — patch-range pin
"0.1.0", // exact — single-version pin
"*", // wildcard — explicitly any-version (semver::VersionReq::STAR)
">=0.1, <2", // multi-range — comma-separated comparators
] {
let mut s = three_member_spec();
for m in &mut s.membros {
m.versao = form.into();
}
s.validate()
.unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
}
}
#[test]
fn membro_versao_empty_takes_precedence_over_invalid() {
// Order pin: the existing `MembroVersaoEmpty` diagnostic
// (which doesn't try to parse) fires before the new
// `MembroVersaoInvalid` parse-side diagnostic, so an empty
// `:versao` keeps its narrower error message — `parse_requirement`
// would also reject `""`, but the empty-string arm is the more
// self-locating diagnostic for the author.
let mut s = three_member_spec();
s.membros[1].versao = String::new();
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "cart"),
"got {err:?}"
);
}
#[test]
fn membro_versao_invalid_fires_before_duplicate_check() {
// Order pin: a malformed requirement on a non-duplicate entry
// surfaces *its own* diagnostic (which names the offending
// `:versao` string), even when a later entry would otherwise
// collapse onto an earlier name. The per-entry shape gate runs
// inline before the duplicate-key insert, parallel to
// `membros_validation_runs_before_contratos_membership_check`
// and `duplicate_contrato_gate_runs_after_target_shape_check`.
let mut s = three_member_spec();
s.membros[0].versao = "^bad".into();
s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::MembroVersaoInvalid { ref caixa, .. } if caixa == "catalog"
),
"got {err:?}"
);
}
#[test]
fn membro_versao_invalid_diagnostic_carries_offending_versao() {
// The diagnostic-shape pin: the error names the offending
// `:versao` value verbatim so the author can grep their
// caixa.lisp without re-running the build, and carries a
// non-empty `reason` from `semver::VersionReq::parse` so the
// parser's own wording flows through to the diagnostic.
let mut s = three_member_spec();
s.membros[2].versao = "not-a-req".into();
let err = s.validate().unwrap_err();
let AplicacaoError::MembroVersaoInvalid {
caixa,
versao,
reason,
} = err
else {
panic!("expected MembroVersaoInvalid, got other variant");
};
assert_eq!(caixa, "payment");
assert_eq!(versao, "not-a-req");
assert!(
!reason.is_empty(),
"MembroVersaoInvalid `reason` must carry the parser's wording verbatim"
);
}
#[test]
fn membro_versao_invalid_runs_before_contratos_check() {
// A malformed `:versao` on any member must surface its own
// diagnostic (which names *which* member to fix) before any
// `:contratos` membership lookup raises `ContratoMemberMissing`.
// The `:contratos` gate runs after `validate_membros`, so this
// is structurally guaranteed — pin it explicitly so a future
// refactor that reorders the gates surfaces here.
let mut s = three_member_spec();
s.membros[1].versao = "^^0.1".into();
// Add a contrato whose `:para` doesn't exist — would normally
// raise ContratoMemberMissing at the membership lookup, but
// the membros gate must fire first.
s.contratos
.push(contract_http("cart", "phantom", "/never-reached"));
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::MembroVersaoInvalid { .. }),
"expected MembroVersaoInvalid to fire before ContratoMemberMissing, got {err:?}"
);
}
#[test]
fn membros_validation_runs_before_contratos_membership_check() {
// If `:membros` carries a duplicate, the membership-collapse
// would silently accept a `:contratos :para "phantom"` so long
// as some entry hashes to "phantom". Pinning order: the
// duplicate-membros error fires first, regardless of whether
// contratos reference real members.
let mut s = three_member_spec();
s.membros = vec![
membro("cart", "^0.1"),
membro("cart", "^0.2"),
membro("catalog", "^0.1"),
membro("payment", "^0.1"),
];
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
"got {err:?}"
);
}
#[test]
fn distinct_membros_validate() {
// Pin the happy-path: every `:membros` entry has a non-empty
// `:caixa`, a non-empty `:versao`, and the set is duplicate-free.
// The fixture already satisfies this; this test makes the
// invariant explicit so a future refactor of the fixture can't
// silently break the guarantee.
three_member_spec().validate().unwrap();
}
// ── :membros :caixa DNS-1123 label value-shape gate ───────────────────
#[test]
fn rejects_membro_caixa_with_uppercase() {
// The canonical "I copied the Servico's display name verbatim"
// typo — caixa names are lowercase per K8s DNS-1123 label rule,
// but author tools often round-trip a TitleCase or CamelCase
// identifier from an ADR or a sketch. Pin the diagnostic names
// the offending name and suggests the lower-cased fix in one
// edit, mirroring the `rejects_entrada_host_with_uppercase`
// gate's shape (c7d05ec).
let mut s = three_member_spec();
s.membros[1].caixa = "Cart".into();
let err = s.validate().unwrap_err();
let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
panic!("expected MembroCaixaInvalid, got other variant");
};
assert_eq!(caixa, "Cart");
assert!(
reason.contains("uppercase"),
"diagnostic must name the violation as `uppercase` (got: {reason:?})"
);
assert!(
reason.contains("\"cart\""),
"diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
);
}
#[test]
fn rejects_membro_caixa_with_underscore() {
// The canonical "I'm thinking of a Python module / Postgres
// table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
// label schema. K8s rejects `metadata.name: my_cart` at admission
// time with an opaque `field is invalid` (no source-citing
// diagnostic). The gate moves it to caixa-build time.
let mut s = three_member_spec();
s.membros[0].caixa = "my_cart".into();
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
if caixa == "my_cart" && reason.contains('_')
),
"got {err:?}"
);
}
#[test]
fn rejects_membro_caixa_with_dot() {
// A `:membros :caixa` entry is a single DNS-1123 *label*, not a
// subdomain — even though K8s `metadata.name` itself accepts
// dots (DNS-1123 subdomain rule), this string also lands as a
// K8s Service name (DNS-1035 label — no dots) and as a label
// value on identity-based Cilium selectors. The strictest floor
// among the use sites wins. The "I want to namespace my member
// names with `.`" intent is expressed via `-` (e.g. `cart-v2`).
let mut s = three_member_spec();
s.membros[2].caixa = "team.cart".into();
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
if caixa == "team.cart" && reason.contains('.')
),
"got {err:?}"
);
}
#[test]
fn rejects_membro_caixa_with_leading_hyphen() {
// DNS-1123 / DNS-1035 boundary rule: labels must start and end
// with an alphanumeric. The K8s apiserver rejects `-cart`
// outright; the renderer would emit a `metadata.name: "-cart"`
// that fails admission far from the source caixa.lisp.
let mut s = three_member_spec();
s.membros[0].caixa = "-cart".into();
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
if caixa == "-cart" && reason.contains("start and end")
),
"got {err:?}"
);
}
#[test]
fn rejects_membro_caixa_with_trailing_hyphen() {
// The symmetric arm of the boundary rule. Pin separately so
// both ends of the label are covered against a future relaxation
// that only checks one boundary.
let mut s = three_member_spec();
s.membros[1].caixa = "cart-".into();
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
if caixa == "cart-"
),
"got {err:?}"
);
}
#[test]
fn rejects_membro_caixa_with_unicode() {
// DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
// (`xn--…`) by the author before it reaches K8s. The byte-by-
// byte ASCII validity check rejects multi-byte UTF-8 sequences
// by the first byte that fails the `[a-z0-9-]` predicate.
let mut s = three_member_spec();
s.membros[2].caixa = "café".into();
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
if caixa == "café"
),
"got {err:?}"
);
}
#[test]
fn rejects_membro_caixa_with_whitespace() {
// Whitespace is the canonical "I pasted from a sketch / doc"
// footgun. The apiserver rejects every `metadata.name` value
// carrying whitespace; pin the gate fires at the right boundary.
let mut s = three_member_spec();
s.membros[0].caixa = "my cart".into();
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
if caixa == "my cart"
),
"got {err:?}"
);
}
#[test]
fn rejects_membro_caixa_too_long() {
// 64 bytes exceeds the DNS-1123 label cap by one — the boundary
// pin. K8s Service name + DNS-1123 label both cap at 63 bytes
// exactly. The gate's reason names both the cap and the actual
// length so the author can shorten in one edit.
let mut s = three_member_spec();
let too_long = "a".repeat(64);
s.membros[1].caixa = too_long.clone();
let err = s.validate().unwrap_err();
let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
panic!("expected MembroCaixaInvalid");
};
assert_eq!(caixa, too_long);
assert!(
reason.contains("63") && reason.contains("64"),
"diagnostic must name the cap (63) and the actual length (64): {reason:?}"
);
}
#[test]
fn membro_caixa_max_length_validates() {
// 63 bytes exactly — the K8s DNS-1123 label cap. Pin the boundary
// so a future tightening (e.g. dropping to 62) surfaces here as
// a regression, mirroring `entrada_host_max_length_validates`
// (c7d05ec).
let mut s = three_member_spec();
s.membros[2].caixa = "a".repeat(63);
s.entrada.as_mut().unwrap().para = "a".repeat(63);
// remove contratos referencing the renamed member; they'd
// raise ContratoMemberMissing otherwise
s.contratos
.retain(|c| c.de != "payment" && c.para != "payment");
s.validate().unwrap();
}
#[test]
fn accepts_canonical_membro_caixa_forms() {
// The DNS-1123 label shapes a caixa author is realistically
// going to write: single-word lowercase, hyphen-joined, ending
// in a digit-suffixed version (`cart-v2`), starting with a
// digit (`3rd-party-shim` — DNS-1123 allows this, unlike
// DNS-1035 which requires a letter at position 0), single-
// character (`a` — boundary). Pin every leg so a future
// tightening that bans (e.g.) digit-start identifiers surfaces
// here.
for form in [
"checkout",
"cart",
"cart-v2",
"a",
"c0",
"3rd-party-shim",
"x-1-2-3-4",
] {
let mut s = three_member_spec();
// Renaming a member also requires updating downstream refs;
// drop everything else and rebuild a minimal spec around
// just the one renamed member.
s.membros = vec![membro(form, "^0.1")];
s.contratos = vec![];
s.entrada = None;
s.validate()
.unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
}
}
#[test]
fn membro_caixa_empty_takes_precedence_over_invalid() {
// Order pin: the existing `MembroCaixaEmpty` diagnostic
// (which doesn't try to parse) fires before the new
// `MembroCaixaInvalid` parse-side diagnostic, so an empty
// `:caixa` keeps its narrower error message — the new gate
// would also reject `""`, but the empty-string arm is the more
// self-locating diagnostic for the author. Mirrors the
// `entrada_host_empty_takes_precedence_over_invalid` pin
// (c7d05ec).
let mut s = three_member_spec();
s.membros[1].caixa = String::new();
let err = s.validate().unwrap_err();
assert_eq!(err, AplicacaoError::MembroCaixaEmpty);
}
#[test]
fn membro_caixa_invalid_fires_before_versao_check() {
// Order pin: an invalid-shape `:caixa` surfaces *its own*
// diagnostic (which names the offending caixa name), even when
// the same entry's `:versao` is also empty/invalid. The shape
// gate runs first because the diagnostic is more self-locating —
// an empty/invalid `:versao` on an invalid-shape caixa name is
// a downstream-fix-after-the-caixa-rename concern.
let mut s = three_member_spec();
s.membros[1].caixa = "Cart".into();
s.membros[1].versao = String::new(); // would otherwise raise MembroVersaoEmpty
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Cart"
),
"got {err:?}"
);
}
#[test]
fn membro_caixa_invalid_fires_before_duplicate_check() {
// Order pin: a malformed-shape `:caixa` on an earlier entry
// surfaces *its own* diagnostic, even when a later entry would
// otherwise collapse onto a duplicate name. The per-entry shape
// gate runs inline before the duplicate-key insert, parallel
// to `membro_versao_invalid_fires_before_duplicate_check`.
let mut s = three_member_spec();
s.membros[0].caixa = "Catalog".into();
s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Catalog"
),
"got {err:?}"
);
}
#[test]
fn membro_caixa_invalid_diagnostic_carries_offending_caixa() {
// The diagnostic-shape pin: the error names the offending
// `:caixa` value verbatim so the author can grep their
// caixa.lisp without re-running the build, and carries a
// non-empty `reason` naming the specific violation. Same
// shape every typed-shape gate enshrines (c7d05ec's
// `entrada_host_diagnostic_carries_offending_host`,
// 9888b13's `membro_versao_invalid_diagnostic_carries_offending_versao`).
let mut s = three_member_spec();
s.membros[2].caixa = "BAD_NAME".into();
let err = s.validate().unwrap_err();
let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
panic!("expected MembroCaixaInvalid");
};
assert_eq!(caixa, "BAD_NAME");
assert!(
!reason.is_empty(),
"MembroCaixaInvalid `reason` must carry a parser-shaped wording"
);
}
#[test]
fn rejects_contrato_with_unknown_de() {
let mut s = three_member_spec();
s.contratos.push(contract_http("phantom", "catalog", "/x"));
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
);
}
#[test]
fn rejects_contrato_with_unknown_para() {
let mut s = three_member_spec();
s.contratos.push(contract_http("cart", "phantom", "/x"));
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
);
}
#[test]
fn contrato_unknown_de_diagnostic_routes_caixa_field_through_source_accessor() {
// The read-path pin: the phantom-`:de` refusal arm's
// `ContratoMemberMissing.caixa` carrier must be observed through
// the lifted [`WitContract::source`] accessor, not the raw
// `.de.clone()` field-access `String`-carry. Peer of the sibling
// per-`:contratos` self-loop arm's `.source().to_string()` /
// `.world_ref().to_string()` `String`-carry sites the earlier
// convergence lifted onto the same accessor pair. A future
// silent detour that reintroduced the raw `.de.clone()` at the
// wrap envelope while the shape-gate and membership lookup
// routed through the accessor would surface here as a byte-equal
// miss between the fired diagnostic's `caixa:` field and the
// offending edge's `.source()` — pinning the accessor as the
// sole read path across the phantom-name refusal arm's arg +
// wrap-envelope emit surface.
let mut s = three_member_spec();
let phantom = contract_http("phantom", "catalog", "/x");
s.contratos.push(phantom.clone());
let err = s.validate().unwrap_err();
let AplicacaoError::ContratoMemberMissing { caixa } = err else {
panic!("expected ContratoMemberMissing on phantom :de, got {err:?}");
};
assert_eq!(
caixa,
phantom.source(),
"ContratoMemberMissing.caixa on the phantom-:de arm must \
byte-equal WitContract::source — the wrap envelope must \
route through the lifted accessor rather than the raw \
.de.clone() field-access String-carry"
);
}
#[test]
fn contrato_unknown_para_diagnostic_routes_caixa_field_through_destination_accessor() {
// The symmetric read-path pin on the `:para` phantom-name
// refusal arm — same shape as the sibling `:de` pin above but
// on the callee-Servico axis. Pins the wrap envelope's
// `caixa:` field is observed through the lifted
// [`WitContract::destination`] accessor, not the raw
// `.para.clone()` field-access `String`-carry.
let mut s = three_member_spec();
let phantom = contract_http("cart", "phantom", "/x");
s.contratos.push(phantom.clone());
let err = s.validate().unwrap_err();
let AplicacaoError::ContratoMemberMissing { caixa } = err else {
panic!("expected ContratoMemberMissing on phantom :para, got {err:?}");
};
assert_eq!(
caixa,
phantom.destination(),
"ContratoMemberMissing.caixa on the phantom-:para arm must \
byte-equal WitContract::destination — the wrap envelope \
must route through the lifted accessor rather than the raw \
.para.clone() field-access String-carry"
);
}
#[test]
fn contrato_malformed_de_diagnostic_routes_caixa_field_through_source_accessor() {
// The read-path pin on the `:de` DNS-1123-malformed shape-gate
// refusal arm — the `validate_contrato_caixa` arg must be
// observed through the lifted [`WitContract::source`] accessor,
// not the raw `&c.de` `&String`-borrow. A `BAD_NAME` `:de`
// value routes through the shared
// [`crate::render::require_valid_dns_1123_label`] floor with the
// accessor-projected value; the fired
// `AplicacaoError::ContratoCaixaInvalid.caixa` carrier byte-equals
// the offending edge's `.source()`, pinning that the arg + the
// downstream `caixa: caixa.to_string()` wrap route through the
// same accessor's read path.
let mut s = three_member_spec();
let malformed = contract_http("BAD_NAME", "catalog", "/x");
s.contratos.push(malformed.clone());
let err = s.validate().unwrap_err();
let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
panic!("expected ContratoCaixaInvalid on malformed :de, got {err:?}");
};
assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
assert_eq!(
caixa,
malformed.source(),
"ContratoCaixaInvalid.caixa on the malformed-:de arm must \
byte-equal WitContract::source — the shape-gate arg + wrap \
envelope must route through the lifted accessor rather \
than the raw &c.de &String-borrow"
);
}
#[test]
fn contrato_malformed_para_diagnostic_routes_caixa_field_through_destination_accessor() {
// Symmetric arm to the sibling `:de` malformed-shape pin above,
// on the `:para` axis. Pins the shape-gate arg + wrap envelope
// route through the lifted [`WitContract::destination`]
// accessor. `:para` runs after the `:de` shape gate in the
// canonical edge-direction order, so the `:de` value must be
// well-shaped for the `:para` gate to fire — the `cart` :de is
// canonical.
let mut s = three_member_spec();
let malformed = contract_http("cart", "BAD_NAME", "/x");
s.contratos.push(malformed.clone());
let err = s.validate().unwrap_err();
let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
panic!("expected ContratoCaixaInvalid on malformed :para, got {err:?}");
};
assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
assert_eq!(
caixa,
malformed.destination(),
"ContratoCaixaInvalid.caixa on the malformed-:para arm must \
byte-equal WitContract::destination — the shape-gate arg + \
wrap envelope must route through the lifted accessor \
rather than the raw &c.para &String-borrow"
);
}
// ── :contratos :de / :para DNS-1123 label value-shape gate ──────────
#[test]
fn rejects_contrato_de_empty() {
// `:de ""` previously fell through to `ContratoMemberMissing`
// (with `caixa: ""`) because the validated `:membros :caixa`
// set never contains the empty string. The narrower
// `ContratoCaixaEmpty { slot: ":de" }` diagnostic now names
// the offending slot.
let mut s = three_member_spec();
s.contratos.push(contract_http("", "catalog", "/x"));
let err = s.validate().unwrap_err();
assert_eq!(
err,
AplicacaoError::ContratoCaixaEmpty {
slot: crate::render::CONTRATO_AUTHOR_KEY_DE
},
"got {err:?}"
);
}
#[test]
fn rejects_contrato_para_empty() {
// Symmetric arm to `:de ""` — `:para ""` previously fell
// through to `ContratoMemberMissing { caixa: "" }`.
let mut s = three_member_spec();
s.contratos.push(contract_http("cart", "", "/x"));
let err = s.validate().unwrap_err();
assert_eq!(
err,
AplicacaoError::ContratoCaixaEmpty {
slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
},
"got {err:?}"
);
}
#[test]
fn rejects_contrato_de_with_uppercase() {
// The canonical "I copied the Servico's TitleCase display
// name from an ADR" typo. Until this gate landed `:de "Cart"`
// surfaced `ContratoMemberMissing { caixa: "Cart" }` — framed
// as "this caixa isn't in `:membros`" when the root cause is
// "this `:de` value's shape can never legitimately match a
// validated member (DNS-1123 labels are lowercase)". The
// narrower diagnostic names the offending slot, the value
// verbatim, and the parser-shaped reason.
let mut s = three_member_spec();
s.contratos.push(contract_http("Cart", "catalog", "/x"));
let err = s.validate().unwrap_err();
let AplicacaoError::ContratoCaixaInvalid {
slot,
caixa,
reason,
} = err
else {
panic!("expected ContratoCaixaInvalid, got other variant");
};
assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
assert_eq!(caixa, "Cart");
assert!(
reason.contains("uppercase"),
"diagnostic must name the violation as `uppercase` (got: {reason:?})"
);
}
#[test]
fn rejects_contrato_para_with_underscore() {
// The canonical "I'm thinking of a Python module" leak —
// `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
// Pin the `:para` axis surfaces the same diagnostic shape as
// the `:de` axis on the underscore violation.
let mut s = three_member_spec();
s.contratos.push(contract_http("cart", "my_catalog", "/x"));
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "my_catalog" && reason.contains('_')
),
"got {err:?}"
);
}
#[test]
fn rejects_contrato_de_with_dot() {
// A `:contratos :de` value is a single DNS-1123 *label*, not
// a subdomain — mirroring the `:membros :caixa` floor. The
// strictest floor among the use sites wins.
let mut s = three_member_spec();
s.contratos
.push(contract_http("team.cart", "catalog", "/x"));
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "team.cart" && reason.contains('.')
),
"got {err:?}"
);
}
#[test]
fn rejects_contrato_para_with_unicode() {
// DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
// (`xn--…`) before it reaches K8s. The byte-by-byte ASCII
// validity check rejects multi-byte UTF-8 by the first
// non-`[a-z0-9-]` byte.
let mut s = three_member_spec();
s.contratos.push(contract_http("cart", "café", "/x"));
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "café"
),
"got {err:?}"
);
}
#[test]
fn rejects_contrato_de_with_leading_hyphen() {
// DNS-1123 boundary rule: labels must start and end with an
// alphanumeric. K8s rejects `-cart` outright; the narrower
// shape diagnostic now names the violation at caixa-build
// time rather than the misframed membership-lookup arm.
let mut s = three_member_spec();
s.contratos.push(contract_http("-cart", "catalog", "/x"));
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "-cart" && reason.contains("start and end")
),
"got {err:?}"
);
}
#[test]
fn contrato_de_empty_takes_precedence_over_invalid() {
// Order pin: the `ContratoCaixaEmpty` arm fires before the
// `ContratoCaixaInvalid` parse-side arm — same empty-first
// cascade `validate_membro_caixa` / `validate_placement_cluster`
// / `validate_entrada_host` already establish on their peer
// name axes. The empty string is a structurally distinct
// authoring footgun (the author left the field blank, vs.
// typed a malformed value), so it gets its own diagnostic.
let mut s = three_member_spec();
s.contratos.push(contract_http("", "catalog", "/x"));
let err = s.validate().unwrap_err();
assert_eq!(
err,
AplicacaoError::ContratoCaixaEmpty {
slot: crate::render::CONTRATO_AUTHOR_KEY_DE
}
);
}
#[test]
fn contrato_de_shape_fires_before_para_shape() {
// Per-axis order pin: within one `:contratos` entry, the `:de`
// shape gate fires before the `:para` shape gate — same
// edge-direction order the existing `ContratoMemberMissing` /
// `ContratoSelfLoop` / target-dispatch checks use, so the
// diagnostic for a contract with both `:de` and `:para`
// malformed is stable. Authors fixing the surfaced `:de`
// first will see `:para`'s diagnostic on re-run.
let mut s = three_member_spec();
s.contratos.push(contract_http("Cart", "Catalog", "/x"));
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
),
"got {err:?}"
);
}
#[test]
fn contrato_shape_fires_before_membership_lookup() {
// The load-bearing pin: an invalid-shape `:de` surfaces its
// *own* diagnostic, not the misframed `ContratoMemberMissing`.
// Because every `:membros :caixa` is shape-validated (3f9d7a0),
// an invalid-shape `:de` could never legitimately match any
// member — the prior `ContratoMemberMissing` diagnostic was
// a structural impossibility framed as a graph-membership
// failure. The shape gate now routes every such input through
// the narrower self-locating diagnostic.
let mut s = three_member_spec();
s.contratos.push(contract_http("Cart", "catalog", "/x"));
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_DE
),
"got {err:?}"
);
// And the symmetric case: an invalid-shape `:para` surfaces
// its own diagnostic too, even when `:de` is well-shaped.
let mut s = three_member_spec();
s.contratos.push(contract_http("cart", "Catalog", "/x"));
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA
),
"got {err:?}"
);
}
#[test]
fn contrato_shape_fires_before_self_edge_check() {
// A `:de "Cart" :para "Cart"` entry is two distinct authoring
// bugs: the shape violation (uppercase) and the self-edge
// violation. The narrower per-axis shape diagnostic surfaces
// first because fixing the shape may reveal that the author
// also meant to point `:para` at a different member — the
// self-edge framing is only useful once both endpoints have
// valid shape.
let mut s = three_member_spec();
s.contratos.push(contract_http("Cart", "Cart", "/x"));
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
),
"got {err:?}"
);
}
#[test]
fn contrato_well_shaped_phantom_still_raises_member_missing() {
// Strict-improvement pin: a well-shaped `:de` that simply
// isn't in `:membros` (a phantom reference — author meant
// to add the member but didn't, or renamed and missed an
// update) still surfaces `ContratoMemberMissing`, unchanged.
// The shape gate only intercepts inputs that could never
// legitimately match a validated member; legitimately-shaped
// phantom references remain on the graph-membership axis.
let mut s = three_member_spec();
s.contratos
.push(contract_http("phantom-shim", "catalog", "/x"));
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::ContratoMemberMissing { ref caixa }
if caixa == "phantom-shim"
),
"got {err:?}"
);
}
#[test]
fn contrato_caixa_invalid_diagnostic_carries_offending_slot_and_value() {
// The diagnostic-shape pin: the error names the offending
// slot (`:de` or `:para`) verbatim and the offending value
// verbatim plus a non-empty parser-shaped reason, so the
// author can grep their caixa.lisp for `:de "<name>"` /
// `:para "<name>"` and fix it in one edit. Same diagnostic
// shape as `MembroCaixaInvalid` (3f9d7a0) and
// `PlacementClusterInvalid` (6c8c00b).
let mut s = three_member_spec();
s.contratos.push(contract_http("cart", "BAD_NAME", "/x"));
let err = s.validate().unwrap_err();
let AplicacaoError::ContratoCaixaInvalid {
slot,
caixa,
reason,
} = err
else {
panic!("expected ContratoCaixaInvalid, got {err:?}");
};
assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
assert_eq!(caixa, "BAD_NAME");
assert!(
!reason.is_empty(),
"ContratoCaixaInvalid `reason` must carry a parser-shaped wording"
);
}
#[test]
fn contrato_author_key_consts_pin_canonical_kebab_case_labels() {
// Scalar-value pin: the two author-facing kebab-case labels the
// `(:contratos ((:de "<caixa>" :para "<caixa>" …) …))` surface
// admits on the `:contratos` per-entry endpoint-shape axis,
// one arm per typed sub-slot. Mirrors the peer scalar-value
// pin the sibling top-level M2 / M3 / Supervisor
// author-facing-label consts carry
// (`m3_top_level_author_key_consts_pin_canonical_kebab_case_labels`
// for the parent [`crate::render::M3_AUTHOR_KEY_CONTRATOS`]
// slot itself), so every altitude of the typed-slot algebra
// shares the same "one canonical byte-string per arm"
// discipline. A future rebrand (`:de` → `:from` matching the
// OTP `appup` [`crate::render::M2_UPGRADE_FROM_KEY_FROM`]
// sibling, `:para` → `:to` matching the same, or
// `:de`/`:para` → `:source`/`:target` matching the WIT
// world's `import`/`export` half-vocabulary) lands as an
// edit to exactly one const, and every consumer that reaches
// for the label picks it up at build time rather than at
// runtime as a downstream `ContratoCaixaEmpty` /
// `ContratoCaixaInvalid` `slot: <stale-kebab-case>`
// diagnostic mismatch far from the rename's commit.
assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_DE, ":de");
assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_PARA, ":para");
}
#[test]
fn contrato_shape_gate_routes_through_lifted_contrato_author_key_consts() {
// Production-through-const pin: the two per-axis labels the
// per-`:contratos` entry endpoint-shape gate at
// [`AplicacaoSpec::validate`] passes as the `slot: &'static str`
// argument to [`validate_contrato_caixa`] route through the
// lifted [`crate::render::CONTRATO_AUTHOR_KEY_DE`] /
// [`crate::render::CONTRATO_AUTHOR_KEY_PARA`] consts, so a
// future rebrand that reaches the const but not the gate (or
// vice versa) surfaces here at build time rather than at
// runtime as a downstream [`AplicacaoError::ContratoCaixaEmpty`]
// `slot: <stale-kebab-case>` diagnostic far from the rename's
// commit. Mirror of the peer
// [`manifest::declared_mesh_slots_route_through_lifted_m3_author_key_consts`]
// pin (882f498) on the sibling M3 top-level slot axis.
let mut s = three_member_spec();
s.contratos.push(contract_http("", "catalog", "/x"));
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::ContratoCaixaEmpty {
slot: crate::render::CONTRATO_AUTHOR_KEY_DE
}
);
let mut s = three_member_spec();
s.contratos.push(contract_http("cart", "", "/x"));
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::ContratoCaixaEmpty {
slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
}
);
}
#[test]
fn accepts_canonical_contrato_caixa_forms() {
// The DNS-1123 label shapes a caixa author is realistically
// going to write on a `:contratos :de` / `:para`. Pin every
// leg so a future tightening that bans (e.g.) digit-start
// identifiers surfaces here, mirroring
// `accepts_canonical_membro_caixa_forms` on the peer name
// axis.
for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
let mut s = three_member_spec();
s.membros = vec![membro("checkout", "^0.1"), membro(form, "^0.1")];
s.contratos = vec![contract_http("checkout", form, "/x")];
s.entrada = None;
s.validate().unwrap_or_else(|e| {
panic!("canonical form {form:?} must validate on `:para`, got {e:?}")
});
let mut s = three_member_spec();
s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
s.contratos = vec![contract_http(form, "catalog", "/x")];
s.entrada = None;
s.validate().unwrap_or_else(|e| {
panic!("canonical form {form:?} must validate on `:de`, got {e:?}")
});
}
}
#[test]
fn rejects_empty_wit() {
let mut s = three_member_spec();
s.contratos.push(WitContract {
de: "cart".into(),
para: "catalog".into(),
wit: String::new(),
endpoint: None,
subject: None,
slot: None,
});
let err = s.validate().unwrap_err();
assert!(matches!(err, AplicacaoError::EmptyWit { .. }));
}
#[test]
fn rejects_entrada_to_unknown_member() {
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().para = "phantom".into();
assert!(matches!(
s.validate().unwrap_err(),
AplicacaoError::EntradaMemberMissing { .. }
));
}
// ── :entrada :para DNS-1123 label value-shape gate ───────────────────
#[test]
fn rejects_entrada_para_empty() {
// `:para ""` previously fell through to
// `EntradaMemberMissing { para: "" }` because the validated
// `:membros :caixa` set never contains the empty string. The
// narrower `EntradaParaEmpty` diagnostic now names the
// offending slot directly — same empty-first cascade
// `MembroCaixaEmpty` / `PlacementClusterEmpty` /
// `ContratoCaixaEmpty` establish on the peer name axes.
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().para = String::new();
let err = s.validate().unwrap_err();
assert_eq!(err, AplicacaoError::EntradaParaEmpty, "got {err:?}");
}
#[test]
fn rejects_entrada_para_with_uppercase() {
// The canonical "I copied the Servico's TitleCase display
// name from an ADR" typo. Until this gate landed `:para "Cart"`
// surfaced `EntradaMemberMissing { para: "Cart" }` — framed
// as "this caixa isn't in `:membros`" when the root cause is
// "this `:para` value's shape can never legitimately match a
// validated member (DNS-1123 labels are lowercase)". The
// narrower diagnostic names the value verbatim plus the
// parser-shaped reason.
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().para = "Cart".into();
let err = s.validate().unwrap_err();
let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
panic!("expected EntradaParaInvalid, got other variant");
};
assert_eq!(para, "Cart");
assert!(
reason.contains("uppercase"),
"diagnostic must name the violation as `uppercase` (got: {reason:?})"
);
}
#[test]
fn rejects_entrada_para_with_underscore() {
// The canonical "I'm thinking of a Python module" leak —
// `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().para = "my_cart".into();
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::EntradaParaInvalid { ref para, ref reason }
if para == "my_cart" && reason.contains('_')
),
"got {err:?}"
);
}
#[test]
fn rejects_entrada_para_with_dot() {
// An `:entrada :para` value is a single DNS-1123 *label*, not
// a subdomain — mirroring the `:membros :caixa` floor. The
// strictest floor among the use sites wins.
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().para = "team.cart".into();
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::EntradaParaInvalid { ref para, ref reason }
if para == "team.cart" && reason.contains('.')
),
"got {err:?}"
);
}
#[test]
fn rejects_entrada_para_with_unicode() {
// DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
// (`xn--…`) before it reaches K8s.
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().para = "café".into();
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "café"
),
"got {err:?}"
);
}
#[test]
fn rejects_entrada_para_with_leading_hyphen() {
// DNS-1123 boundary rule: labels must start and end with an
// alphanumeric. K8s rejects `-cart` outright.
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().para = "-cart".into();
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::EntradaParaInvalid { ref para, ref reason }
if para == "-cart" && reason.contains("start and end")
),
"got {err:?}"
);
}
#[test]
fn rejects_entrada_para_with_trailing_hyphen() {
// Symmetric boundary arm.
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().para = "cart-".into();
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::EntradaParaInvalid { ref para, ref reason }
if para == "cart-" && reason.contains("start and end")
),
"got {err:?}"
);
}
#[test]
fn rejects_entrada_para_too_long() {
// 64-byte over-cap slug — the DNS-1123 label rule caps at 63
// bytes per label. K8s rejects longer names at admission on
// every `metadata.name` axis.
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().para = "a".repeat(64);
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::EntradaParaInvalid { ref para, ref reason }
if para.len() == 64 && reason.contains("max length")
),
"got {err:?}"
);
}
#[test]
fn entrada_para_empty_takes_precedence_over_invalid() {
// Order pin: the `EntradaParaEmpty` arm fires before the
// `EntradaParaInvalid` parse-side arm — same empty-first
// cascade `validate_membro_caixa` / `validate_placement_cluster`
// / `validate_contrato_caixa` already establish.
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().para = String::new();
assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaParaEmpty);
}
#[test]
fn entrada_para_shape_fires_before_membership_lookup() {
// The load-bearing pin: an invalid-shape `:para` surfaces its
// *own* diagnostic, not the misframed `EntradaMemberMissing`.
// Because every `:membros :caixa` is shape-validated (3f9d7a0),
// an invalid-shape `:para` could never legitimately match any
// member — the prior `EntradaMemberMissing` diagnostic framed
// a structural impossibility as a graph-membership failure.
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().para = "Cart".into();
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
),
"got {err:?}"
);
}
#[test]
fn entrada_para_shape_fires_before_host_gate() {
// Per-`:entrada` order pin: the `:para` shape gate fires
// before the `:host` gate, mirroring the existing
// `entrada_host_member_missing_takes_precedence_over_host_invalid`
// ordering where the member-lookup arm preceded the host gate.
// The shape gate slots ahead of that, so a malformed `:para`
// surfaces its own diagnostic even when `:host` is also wrong.
let mut s = three_member_spec();
let e = s.entrada.as_mut().unwrap();
e.para = "Cart".into();
e.host = "BAD HOST".into();
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
),
"got {err:?}"
);
}
#[test]
fn entrada_para_well_shaped_phantom_still_raises_member_missing() {
// Strict-improvement pin: a well-shaped `:para` that simply
// isn't in `:membros` (a phantom reference — author meant to
// add the member but didn't, or renamed and missed an
// update) still surfaces `EntradaMemberMissing`, unchanged.
// The shape gate only intercepts inputs that could never
// legitimately match a validated member.
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().para = "phantom-shim".into();
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::EntradaMemberMissing { ref para }
if para == "phantom-shim"
),
"got {err:?}"
);
}
#[test]
fn entrada_para_invalid_diagnostic_carries_offending_para() {
// The diagnostic-shape pin: the error names the offending
// `:para` value verbatim plus a non-empty parser-shaped
// reason, so the author can grep their caixa.lisp for
// `:para "<name>"` and fix it in one edit. Same diagnostic
// shape as `MembroCaixaInvalid` (3f9d7a0),
// `PlacementClusterInvalid` (6c8c00b), and
// `ContratoCaixaInvalid` (8d5af6b).
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().para = "BAD_NAME".into();
let err = s.validate().unwrap_err();
let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
panic!("expected EntradaParaInvalid, got {err:?}");
};
assert_eq!(para, "BAD_NAME");
assert!(
!reason.is_empty(),
"EntradaParaInvalid `reason` must carry a parser-shaped wording"
);
}
#[test]
fn accepts_canonical_entrada_para_forms() {
// Positive-control sweep covering the DNS-1123 label shapes a
// caixa author is realistically going to write on `:entrada
// :para`. Pin every leg so a future tightening that bans
// (e.g.) digit-start identifiers surfaces here, mirroring
// `accepts_canonical_membro_caixa_forms` and
// `accepts_canonical_contrato_caixa_forms` on the peer name
// axes.
for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
let mut s = three_member_spec();
s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
s.contratos = vec![contract_http(form, "catalog", "/x")];
s.entrada = Some(Entrada {
host: "checkout.quero.cloud".into(),
para: form.into(),
paths: vec!["/api".into()],
port: 8080,
});
s.validate().unwrap_or_else(|e| {
panic!("canonical form {form:?} must validate on `:entrada :para`, got {e:?}")
});
}
}
#[test]
fn rejects_replicated_without_clusters() {
let mut s = three_member_spec();
s.placement.clusters = vec![];
assert!(matches!(
s.validate().unwrap_err(),
AplicacaoError::PlacementWithoutClusters { .. }
));
}
#[test]
fn rejects_sharded_without_key() {
let mut s = three_member_spec();
s.placement.estrategia = PlacementStrategy::Sharded;
s.placement.shard_key = None;
s.placement.clusters = vec!["rio".into()];
assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedWithoutKey);
}
#[test]
fn sharded_with_key_validates() {
let mut s = three_member_spec();
s.placement.estrategia = PlacementStrategy::Sharded;
s.placement.shard_key = Some("$tenantId".into());
s.validate().unwrap();
}
#[test]
fn round_trip_via_json_preserves_shape() {
let s = three_member_spec();
let json = serde_json::to_string(&s.membros).unwrap();
let back: Vec<Membro> = serde_json::from_str(&json).unwrap();
assert_eq!(back, s.membros);
let json = serde_json::to_string(&s.contratos).unwrap();
let back: Vec<WitContract> = serde_json::from_str(&json).unwrap();
assert_eq!(back, s.contratos);
let json = serde_json::to_string(&s.placement).unwrap();
let back: Placement = serde_json::from_str(&json).unwrap();
assert_eq!(back, s.placement);
let json = serde_json::to_string(&s.entrada).unwrap();
let back: Option<Entrada> = serde_json::from_str(&json).unwrap();
assert_eq!(back, s.entrada);
}
#[test]
fn rate_limit_round_trip_seconds() {
let policy = MeshPolicy {
rate_limit: Some(RateLimit {
rate: 100,
window: Duration::from_secs(1),
}),
..Default::default()
};
let json = serde_json::to_string(&policy).unwrap();
assert!(json.contains("\"100/s\""));
let back: MeshPolicy = serde_json::from_str(&json).unwrap();
assert_eq!(back.rate_limit.unwrap().rate, 100);
assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(1));
}
#[test]
fn rate_limit_round_trip_minutes() {
let policy = MeshPolicy {
rate_limit: Some(RateLimit {
rate: 5000,
window: Duration::from_secs(60),
}),
..Default::default()
};
let json = serde_json::to_string(&policy).unwrap();
assert!(json.contains("\"5000/m\""));
}
#[test]
fn circuit_breaker_round_trip() {
let policy = MeshPolicy {
circuit_breaker: Some(CircuitBreaker {
max_failures: 5,
window: Duration::from_secs(60),
}),
..Default::default()
};
let json = serde_json::to_string(&policy).unwrap();
let back: MeshPolicy = serde_json::from_str(&json).unwrap();
assert_eq!(back.circuit_breaker.unwrap().max_failures, 5);
assert_eq!(
back.circuit_breaker.unwrap().window,
Duration::from_secs(60)
);
}
#[test]
fn rejects_http_contrato_without_endpoint() {
let mut s = three_member_spec();
s.contratos.push(WitContract {
de: "cart".into(),
para: "catalog".into(),
wit: "wasi:http/proxy".into(),
endpoint: None,
subject: None,
slot: None,
});
let err = s.validate().unwrap_err();
assert!(matches!(
err,
AplicacaoError::ContratoMissingTarget {
expected: WitTarget::HTTP_FIELD_NAME,
..
}
));
}
#[test]
fn rejects_http_contrato_with_subject() {
let mut s = three_member_spec();
s.contratos.push(WitContract {
de: "cart".into(),
para: "catalog".into(),
wit: "wasi:http/proxy".into(),
endpoint: Some("/x".into()),
subject: Some("not.allowed.here".into()),
slot: None,
});
let err = s.validate().unwrap_err();
assert!(matches!(
err,
AplicacaoError::ContratoWrongTarget {
expected: WitTarget::HTTP_FIELD_NAME,
..
}
));
}
#[test]
fn rejects_pubsub_contrato_without_subject() {
let mut s = three_member_spec();
s.contratos.push(WitContract {
de: "cart".into(),
para: "catalog".into(),
wit: "nats:pub-sub".into(),
endpoint: None,
subject: None,
slot: None,
});
let err = s.validate().unwrap_err();
assert!(matches!(
err,
AplicacaoError::ContratoMissingTarget {
expected: WitTarget::PUBSUB_FIELD_NAME,
..
}
));
}
#[test]
fn rejects_pubsub_contrato_with_endpoint() {
let mut s = three_member_spec();
s.contratos.push(WitContract {
de: "cart".into(),
para: "catalog".into(),
wit: "kafka:topic".into(),
endpoint: Some("/wrong".into()),
subject: Some("topic.x".into()),
slot: None,
});
let err = s.validate().unwrap_err();
assert!(matches!(
err,
AplicacaoError::ContratoWrongTarget {
expected: WitTarget::PUBSUB_FIELD_NAME,
..
}
));
}
#[test]
fn rejects_store_contrato_without_slot() {
let mut s = three_member_spec();
s.contratos.push(WitContract {
de: "cart".into(),
para: "catalog".into(),
wit: "wasi:keyvalue/store".into(),
endpoint: None,
subject: None,
slot: None,
});
let err = s.validate().unwrap_err();
assert!(matches!(
err,
AplicacaoError::ContratoMissingTarget {
expected: WitTarget::STORE_FIELD_NAME,
..
}
));
}
// ── value-shape on WitTarget payload (endpoint / subject / slot) ──────
#[test]
fn rejects_http_contrato_with_empty_endpoint() {
// `Some("")` for an HTTP endpoint passes the presence check
// (target() previously returned WitTarget::Http { endpoint: "" })
// but renders as a `path: ""` Cilium L7 rule that matches no
// traffic. Same value-shape footgun closed for :entrada :paths
// entries (eb3456d).
let mut s = three_member_spec();
s.contratos.push(WitContract {
de: "cart".into(),
para: "catalog".into(),
wit: "wasi:http/proxy".into(),
endpoint: Some(String::new()),
subject: None,
slot: None,
});
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::ContratoEndpointEmpty { ref de, ref para }
if de == "cart" && para == "catalog"),
"got {err:?}"
);
}
#[test]
fn rejects_http_contrato_with_relative_endpoint() {
// Cilium L7 :path + Gateway API PathPrefix both require a
// leading `/`. Same shape required of :entrada :paths
// (eb3456d). Lifted into target() so every consumer of the
// typed WitTarget view inherits the guarantee.
let mut s = three_member_spec();
s.contratos.push(WitContract {
de: "cart".into(),
para: "catalog".into(),
wit: "wasi:http/proxy".into(),
endpoint: Some("products/:id".into()),
subject: None,
slot: None,
});
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
if endpoint == "products/:id"),
"got {err:?}"
);
}
#[test]
fn rejects_pubsub_contrato_with_empty_subject() {
// NATS / Kafka publish without a subject is a no-op subscribe;
// never the author's intent. Same empty-string rejection as
// :membros :caixa, :placement :clusters entries, :entrada
// :paths entries — every value carried by every typed slot is
// value-shape-checked at validate().
let mut s = three_member_spec();
s.contratos.push(WitContract {
de: "cart".into(),
para: "catalog".into(),
wit: "nats:pub-sub".into(),
endpoint: None,
subject: Some(String::new()),
slot: None,
});
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::ContratoSubjectEmpty { ref de, ref para }
if de == "cart" && para == "catalog"),
"got {err:?}"
);
}
#[test]
fn rejects_store_contrato_with_empty_slot() {
// An empty slot template addresses the bucket root, defeating
// the per-key isolation the slot exists for — a footgun on
// `wasi:keyvalue/store` whose closest analog is the empty
// shard-key rejected on :placement Sharded (c7c7799).
let mut s = three_member_spec();
s.contratos.push(WitContract {
de: "cart".into(),
para: "catalog".into(),
wit: "wasi:keyvalue/store".into(),
endpoint: None,
subject: None,
slot: Some(String::new()),
});
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::ContratoSlotEmpty { ref de, ref para }
if de == "cart" && para == "catalog"),
"got {err:?}"
);
}
#[test]
fn http_contrato_root_endpoint_validates() {
// Pin the boundary case: a single-`/` endpoint is the catch-all
// form the Gateway HTTPRoute renderer falls back to when
// :entrada :paths is empty (caixa-mesh::gateway_routes), so it
// must remain a valid contrato endpoint too.
let mut s = three_member_spec();
s.contratos.push(contract_http("cart", "catalog", "/"));
s.validate().unwrap();
}
// ── :contratos :endpoint value-shape gate ────────────────────────────
//
// Mirrors the `:entrada :paths` value-shape suite on the peer
// HTTP-path axis. Until this gate landed `WitContract::target()`
// only refused the empty string + the missing-leading-`/` form
// (c4213a4); a structurally invalid endpoint passed validate and
// landed verbatim as a Cilium L7 `path:` rule
// (caixa-mesh/src/lib.rs:311) that either silently dropped all
// traffic or was rejected at apply time by Cilium policy admission.
// Every authoring footgun the K8s Gateway API webhook / Cilium
// policy validator would catch on admission now becomes a caixa-
// build-time `ContratoEndpointInvalid` with the offending
// `:endpoint` + `:de` + `:para` named verbatim. Same diagnostic
// shape as `EntradaPathInvalid` on the sibling axis; same shared
// predicate (`crate::render::is_gateway_api_http_path`) ensures
// drift between the two axes' rule enforcement is a build error
// at the predicate.
fn contrato_endpoint_err(ep: &str) -> AplicacaoError {
// Fresh spec per call so the would-be-duplicate edge
// `(cart, catalog, wasi:http/proxy, ep)` doesn't collide with
// `three_member_spec`'s pre-existing
// `(cart, catalog, …, /products/:id)` entry — only the
// endpoint payload differs.
let mut s = three_member_spec();
s.contratos.push(contract_http("cart", "catalog", ep));
s.validate().unwrap_err()
}
#[test]
fn rejects_http_contrato_endpoint_with_query() {
// Fail-before-pass-after pin — pre-gate the `?token=X` suffix
// silently rendered as a Cilium L7 `path: "/charge?token=X"`
// rule the L7 matcher would never satisfy.
let err = contrato_endpoint_err("/charge?token=X");
assert!(
matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
if endpoint == "/charge?token=X" && reason.contains("must not contain `?`")),
"got {err:?}"
);
}
#[test]
fn rejects_http_contrato_endpoint_with_fragment() {
let err = contrato_endpoint_err("/charge#frag");
assert!(
matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
if endpoint == "/charge#frag" && reason.contains("must not contain `#`")),
"got {err:?}"
);
}
#[test]
fn rejects_http_contrato_endpoint_with_whitespace() {
let err = contrato_endpoint_err("/foo bar");
assert!(
matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
if endpoint == "/foo bar" && reason.contains("whitespace")),
"got {err:?}"
);
}
#[test]
fn rejects_http_contrato_endpoint_with_control_char() {
let err = contrato_endpoint_err("/api/\x01bar");
assert!(
matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
if endpoint == "/api/\x01bar" && reason.contains("control character")),
"got {err:?}"
);
}
#[test]
fn rejects_http_contrato_endpoint_with_non_ascii() {
let err = contrato_endpoint_err("/api/café");
assert!(
matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
if endpoint == "/api/café" && reason.contains("non-ASCII")),
"got {err:?}"
);
}
#[test]
fn rejects_http_contrato_endpoint_with_consecutive_slashes() {
let err = contrato_endpoint_err("/api//cart");
assert!(
matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
if endpoint == "/api//cart" && reason.contains("consecutive `/`")),
"got {err:?}"
);
}
#[test]
fn rejects_http_contrato_endpoint_with_dot_segment() {
let err = contrato_endpoint_err("/api/./cart");
assert!(
matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
if endpoint == "/api/./cart" && reason.contains("`.` segment")),
"got {err:?}"
);
}
#[test]
fn rejects_http_contrato_endpoint_with_parent_segment() {
// Path-traversal in a contrato endpoint is the canonical
// "L7 rule that the workload's HTTP server's path-resolution
// logic interprets differently than the policy enforcer"
// footgun. Rejected outright at validate time.
let err = contrato_endpoint_err("/api/../etc");
assert!(
matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
if endpoint == "/api/../etc" && reason.contains("`..` parent-segment")),
"got {err:?}"
);
}
#[test]
fn rejects_http_contrato_endpoint_too_long() {
// 1025-byte endpoint — one over the Gateway API
// HTTPPathMatch.value `maxLength: 1024` cap. The Cilium L7
// path matcher has no inherent length limit but the policy
// CR itself rides through the K8s apiserver, which enforces
// ConfigMap-shaped limits; sharing the Gateway API cap is the
// conservative floor.
let big = format!("/api/{}", "a".repeat(1020));
assert_eq!(big.len(), 1025);
let err = contrato_endpoint_err(&big);
assert!(
matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
if endpoint == &big && reason.contains("max length of 1024")),
"got {err:?}"
);
}
#[test]
fn http_contrato_endpoint_max_length_validates() {
// 1024-byte endpoint — exactly the cap. Boundary pin: drift
// in the cap surfaces here and at
// `rejects_http_contrato_endpoint_too_long` simultaneously,
// mirroring `entrada_path_max_length_validates` on the peer
// axis.
let big = format!("/api/{}", "a".repeat(1019));
assert_eq!(big.len(), 1024);
let mut s = three_member_spec();
s.contratos.push(contract_http("cart", "catalog", &big));
s.validate().unwrap();
}
#[test]
fn http_contrato_endpoint_accepts_canonical_forms() {
// Positive-set sweep: every canonical HTTP-path shape the
// sibling `:entrada :paths` axis accepts (the bare-root `/`,
// plain paths, hidden-file-style `.config` segments distinct
// from the `.` segment, digit-bearing segments, the canonical
// route-template `:param` form, trailing-slash form,
// percent-encoded segments, the `/foo..bar` interior-`..`-
// substring forms that are NOT `..` segments) must remain a
// valid contrato endpoint too. Drift between this list and
// the entrada path positive sweep surfaces at the shared
// `is_gateway_api_http_path` substrate-side suite — one
// source of truth. Uses a fresh `(payment, catalog)` edge so
// none of the swept endpoints collide with the pre-existing
// `(cart, catalog, /products/:id)` / `(cart, payment,
// /charge)` entries in `three_member_spec`.
for ep in [
"/",
"/charge",
"/v1/charge",
"/api/.config",
"/products/:id",
"/api/cart/",
"/api/caf%C3%A9",
"/foo..bar",
"/...",
] {
let mut s = three_member_spec();
s.contratos.push(contract_http("payment", "catalog", ep));
s.validate()
.unwrap_or_else(|e| panic!("expected {ep:?} to validate, got {e:?}"));
}
}
#[test]
fn contrato_endpoint_empty_takes_precedence_over_invalid() {
// Ordering pin: `ContratoEndpointEmpty` is the more self-
// locating diagnostic on `""` and must lead — the value-
// shape gate is only reached after the empty-check fires.
// Mirrors `entrada_path_empty_takes_precedence_over_invalid`
// on the peer axis.
let mut s = three_member_spec();
s.contratos.push(WitContract {
de: "cart".into(),
para: "catalog".into(),
wit: "wasi:http/proxy".into(),
endpoint: Some(String::new()),
subject: None,
slot: None,
});
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
"got {err:?}"
);
}
#[test]
fn contrato_endpoint_not_absolute_takes_precedence_over_invalid() {
// Ordering pin: an endpoint without a leading `/` surfaces the
// narrower `ContratoEndpointNotAbsolute` diagnostic first; the
// value-shape gate is only consulted on endpoints that already
// satisfy the absolute-prefix invariant. Mirrors
// `entrada_path_not_absolute_takes_precedence_over_invalid`.
let err = contrato_endpoint_err("bad path");
assert!(
matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
if endpoint == "bad path"),
"got {err:?}"
);
}
#[test]
fn contrato_endpoint_invalid_diagnostic_carries_offending_endpoint() {
// Diagnostic-shape pin — the offending `:endpoint` + `:de` +
// `:para` + a non-empty reason flow through verbatim so the
// author can grep their caixa.lisp for the offending contrato
// block and fix it in one edit. Same shape as
// `entrada_path_diagnostic_carries_offending_path`.
let err = contrato_endpoint_err("/api?q=1");
match err {
AplicacaoError::ContratoEndpointInvalid {
de,
para,
endpoint,
reason,
} => {
assert_eq!(de, "cart");
assert_eq!(para, "catalog");
assert_eq!(endpoint, "/api?q=1");
assert!(!reason.is_empty(), "reason field must be non-empty");
}
other => panic!("expected ContratoEndpointInvalid, got {other:?}"),
}
}
#[test]
fn target_view_payload_is_guaranteed_nonempty_after_target_call() {
// The compounding theorem: every &str inside a WitTarget
// returned by target() is non-empty (and absolute, for Http).
// Renderers downstream of typed_view() can rely on this
// without re-checking — the type system carries the proof.
let http = contract_http("cart", "catalog", "/x");
match http.target().unwrap() {
WitTarget::Http { endpoint } => {
assert!(!endpoint.is_empty());
assert!(endpoint.starts_with('/'));
}
other => panic!("expected Http, got {other:?}"),
}
let nats = WitContract {
de: "a".into(),
para: "b".into(),
wit: "nats:pub-sub".into(),
endpoint: None,
subject: Some("topic.x".into()),
slot: None,
};
match nats.target().unwrap() {
WitTarget::PubSub { subject } => assert!(!subject.is_empty()),
other => panic!("expected PubSub, got {other:?}"),
}
let kv = WitContract {
de: "a".into(),
para: "b".into(),
wit: "wasi:keyvalue/store".into(),
endpoint: None,
subject: None,
slot: Some("checkout/$orderId".into()),
};
match kv.target().unwrap() {
WitTarget::Store { slot } => assert!(!slot.is_empty()),
other => panic!("expected Store, got {other:?}"),
}
}
#[test]
fn target_diagnostic_names_offending_endpoint_value() {
// When the malformed endpoint string is non-trivial, the
// diagnostic carries the actual value back to the author —
// not a generic "endpoint malformed" error.
let bad = WitContract {
de: "src".into(),
para: "dst".into(),
wit: "wasi:http/proxy".into(),
endpoint: Some("api/v1/charge".into()),
subject: None,
slot: None,
};
match bad.target().unwrap_err() {
AplicacaoError::ContratoEndpointNotAbsolute { de, para, endpoint } => {
assert_eq!(de, "src");
assert_eq!(para, "dst");
assert_eq!(endpoint, "api/v1/charge");
}
other => panic!("expected ContratoEndpointNotAbsolute, got {other:?}"),
}
}
#[test]
fn rejects_unknown_wit_with_target_set() {
let mut s = three_member_spec();
s.contratos.push(WitContract {
de: "cart".into(),
para: "catalog".into(),
wit: "custom:exchange".into(),
endpoint: Some("/leaked".into()),
subject: None,
slot: None,
});
let err = s.validate().unwrap_err();
assert!(matches!(
err,
AplicacaoError::ContratoWrongTarget {
expected: WitTarget::CAPABILITY_EXPECTED,
..
}
));
}
#[test]
fn wit_target_capability_expected_pins_wrong_target_diagnostic_scalar() {
// Pin the Capability-arm `ContratoWrongTarget::expected` scalar
// single-sourced onto [`WitTarget::CAPABILITY_EXPECTED`] — the
// fourth arm of the same "which payload field name goes in the
// diagnostic" dispatch the payload-arm [`WitTarget::HTTP_FIELD_NAME`]
// / [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
// consts cover on the peer HTTP / PubSub / Store arms
// (`wit_target_field_name_pins_per_variant`). Until this lift
// landed the byte-string sat twice — once inline in the
// [`WitContract::target`] Capability-arm rejection at the
// production dispatch, once in `rejects_unknown_wit_with_target_set`
// pinning against the same literal — with no compile-time link
// between them. Same "one canonical declaration, next to the
// variant" trajectory the peer [`WitTarget::CAPABILITY_LABEL`]
// lift established for the payload-less arm's human-readable
// label axis; this test is the shape peer of
// `wit_target_label_pins_per_variant`'s Capability-arm assertion
// pair (routes-through-const + scalar-value pin) on the
// wrong-target diagnostic-scalar axis.
//
// Fail-before-pass-after was verified locally by mutating the
// const declaration to `"capability"` — the scalar-value pin
// below fires (`"capability" != "none"`) and the routes-through
// assertion below still holds (production and const walk in
// lockstep), which is the correct behavior: a rename on the
// const drifts here first, not at a downstream consumer.
assert_eq!(WitTarget::CAPABILITY_EXPECTED, "none");
let mut s = three_member_spec();
s.contratos.push(WitContract {
de: "cart".into(),
para: "catalog".into(),
wit: "custom:exchange".into(),
endpoint: Some("/leaked".into()),
subject: None,
slot: None,
});
match s.validate().unwrap_err() {
AplicacaoError::ContratoWrongTarget { expected, .. } => {
assert_eq!(expected, WitTarget::CAPABILITY_EXPECTED);
}
other => panic!("expected ContratoWrongTarget, got {other:?}"),
}
}
#[test]
fn unknown_wit_capability_only_validates() {
let mut s = three_member_spec();
s.contratos.push(WitContract {
de: "cart".into(),
para: "catalog".into(),
// A WIT world we haven't yet shaped — accept it as a typed
// capability edge so authors aren't blocked while the WIT
// registry catches up. No payload field may be carried.
wit: "custom:exchange".into(),
endpoint: None,
subject: None,
slot: None,
});
s.validate().unwrap();
let added = s.contratos.last().unwrap();
assert_eq!(added.target().unwrap(), WitTarget::Capability);
}
#[test]
fn target_typed_view_round_trips_each_shape() {
let http = contract_http("cart", "catalog", "/products/:id");
assert_eq!(
http.target().unwrap(),
WitTarget::Http {
endpoint: "/products/:id"
}
);
let nats = WitContract {
de: "a".into(),
para: "b".into(),
wit: "nats:pub-sub".into(),
endpoint: None,
subject: Some("topic.x".into()),
slot: None,
};
assert_eq!(
nats.target().unwrap(),
WitTarget::PubSub { subject: "topic.x" }
);
let kv = WitContract {
de: "a".into(),
para: "b".into(),
wit: "wasi:keyvalue/store".into(),
endpoint: None,
subject: None,
slot: Some("checkout/$orderId".into()),
};
assert_eq!(
kv.target().unwrap(),
WitTarget::Store {
slot: "checkout/$orderId"
}
);
}
#[test]
fn wit_contract_kind_predicates() {
let http = contract_http("a", "b", "/x");
assert!(http.is_http());
assert!(!http.is_pubsub());
assert!(!http.is_store());
assert!(!http.is_capability());
let nats = WitContract {
de: "a".into(),
para: "b".into(),
wit: "nats:pub-sub".into(),
endpoint: None,
subject: Some("topic.x".into()),
slot: None,
};
assert!(nats.is_pubsub());
assert!(!nats.is_http());
assert!(!nats.is_capability());
let kv = WitContract {
de: "a".into(),
para: "b".into(),
wit: "wasi:keyvalue/store".into(),
endpoint: None,
subject: None,
slot: Some("checkout/$orderId".into()),
};
assert!(kv.is_store());
assert!(!kv.is_http());
assert!(!kv.is_capability());
// Fourth arm on the paired closed-set predicate family: the
// payload-less capability edge that projects to the payload-
// less [`WitTarget::Capability`] arm under [`WitContract::target`].
// Extends the 3-arm predicate sweep this test opened to cover
// the closed 4-way partition [`WitContract::is_capability`]
// closes on the pre-projection WIT-shape axis, matched with the
// sibling post-projection [`WitTarget`]-side `IsVariant`-derived
// 4-arm predicate set.
let cap = WitContract {
de: "a".into(),
para: "b".into(),
wit: "custom:capability-only".into(),
endpoint: None,
subject: None,
slot: None,
};
assert!(cap.is_capability());
assert!(!cap.is_http());
assert!(!cap.is_pubsub());
assert!(!cap.is_store());
}
// ── :contratos :wit value-shape gate ─────────────────────────────────
//
// Mirrors the `:contratos :endpoint` value-shape suite on the peer
// dispatch-discriminator axis. Until this gate landed
// `WitContract::target()` accepted any non-empty string and
// silently demoted unrecognized shapes to a capability-only L4
// edge — the canonical "I thought I had L7 HTTP routing, got
// L4-only" footgun. Every authoring footgun the WIT registry's
// own grammar rejects (uppercase, hyphen-for-colon typo,
// whitespace, empty package, doubled `@`, …) now becomes a
// caixa-build-time `ContratoWitInvalid` with the offending
// `:wit` + `:de` + `:para` named verbatim. Same diagnostic shape
// as `ContratoEndpointInvalid` on the sibling axis; same shared
// predicate (`crate::render::is_wit_world_ref`) ensures drift
// between any two axes' rule enforcement is a build error at the
// predicate, not piecemeal across renderers.
fn contrato_wit_err(wit: &str) -> AplicacaoError {
// Fresh spec per call so the new contract doesn't collide on
// identity with `three_member_spec`'s pre-existing entries.
// The new edge uses `(payment, catalog)` — a pair the fixture
// doesn't already declare — with no payload field set, so the
// wit-shape gate fires before any payload-shape arm.
let mut s = three_member_spec();
s.contratos.push(WitContract {
de: "payment".into(),
para: "catalog".into(),
wit: wit.into(),
endpoint: None,
subject: None,
slot: None,
});
s.validate().unwrap_err()
}
#[test]
fn rejects_wit_with_uppercase_namespace() {
// Fail-before-pass-after pin — pre-gate `:wit "WASI:http/proxy"`
// didn't match the lowercase `wasi:http/` prefix is_http() keys
// off, so the dispatch fell through to the capability arm and
// the contract silently rendered as an L4-only Cilium edge.
// The new gate surfaces the uppercase typo at validate time
// with the offending `:wit` named.
let err = contrato_wit_err("WASI:http/proxy");
assert!(
matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
if wit == "WASI:http/proxy" && reason.contains("lowercase")),
"got {err:?}"
);
}
#[test]
fn rejects_wit_with_hyphen_for_colon_typo() {
// The canonical "I forgot the `:` separator" typo — pre-gate
// this passed as Capability silently, so the renderer emitted
// an L4-only policy where the author expected L7 HTTP rules.
let err = contrato_wit_err("wasi-http/proxy");
assert!(
matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
if wit == "wasi-http/proxy" && reason.contains("must contain a `:`")),
"got {err:?}"
);
}
#[test]
fn rejects_wit_with_multiple_colons() {
// Doubled `:` — the namespace/package split has nowhere to
// anchor, so the dispatch silently demotes to Capability.
let err = contrato_wit_err("wasi:http:proxy");
assert!(
matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
if wit == "wasi:http:proxy" && reason.contains("exactly one `:`")),
"got {err:?}"
);
}
#[test]
fn rejects_wit_with_empty_package() {
// `wasi:` — namespace alone with no package. Pre-gate this
// failed neither the is_http nor is_pubsub nor is_store
// prefix check (none of `wasi:http/`, `wasi:keyvalue/` match
// a bare `wasi:`), so it silently demoted to Capability.
let err = contrato_wit_err("wasi:");
assert!(
matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
if wit == "wasi:" && reason.contains("package") && reason.contains("must not be empty")),
"got {err:?}"
);
}
#[test]
fn rejects_wit_with_underscore() {
// Underscore — WIT identifiers are kebab-case, same rule
// DNS-1123 enforces on its peer axes. The diagnostic carries
// the explicit "use `-` instead" remediation.
let err = contrato_wit_err("wasi:http_proxy");
assert!(
matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
if wit == "wasi:http_proxy" && reason.contains('_')),
"got {err:?}"
);
}
#[test]
fn rejects_wit_with_whitespace() {
// Whitespace mid-token — the prefix check matches but the
// package-and-onward parse silently demoted to Capability.
let err = contrato_wit_err("wasi:http proxy");
assert!(
matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
if wit == "wasi:http proxy" && reason.contains("whitespace")),
"got {err:?}"
);
}
#[test]
fn rejects_wit_with_non_ascii() {
// Un-percent-encoded non-ASCII byte — the canonical "I copied
// the package name from a doc with smart quotes / accented
// characters" footgun.
let err = contrato_wit_err("wasi:caf\u{e9}/proxy");
assert!(
matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
if wit == "wasi:caf\u{e9}/proxy" && reason.contains("non-ASCII")),
"got {err:?}"
);
}
#[test]
fn rejects_wit_with_consecutive_hyphens() {
// `pub--sub` — WIT identifiers join words with single hyphens.
let err = contrato_wit_err("nats:pub--sub");
assert!(
matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
if wit == "nats:pub--sub" && reason.contains("consecutive `-`")),
"got {err:?}"
);
}
#[test]
fn rejects_wit_with_trailing_at_no_version() {
// `wasi:http/proxy@` — the version-suffix author started to
// type `@0.2.0` and stopped, leaving a stray `@`. The WIT
// parser would reject this; surface it at validate time.
let err = contrato_wit_err("wasi:http/proxy@");
assert!(
matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
if wit == "wasi:http/proxy@" && reason.contains("trailing `@`")),
"got {err:?}"
);
}
#[test]
fn rejects_wit_too_long() {
// 129-byte WIT reference — one over the WIT_IDENT_MAX_LEN cap.
// The legitimate-shape arms all pass (lowercase, single `:`,
// kebab-case identifiers); only the cap arm fires. Surfaces
// the paste-from-binary / accidental-multi-line-blob landing
// footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
// on the peer axis.
let big = format!("wasi:{}", "a".repeat(124));
assert_eq!(big.len(), 129);
let err = contrato_wit_err(&big);
assert!(
matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
if wit == &big && reason.contains("max length of 128")),
"got {err:?}"
);
}
#[test]
fn wit_max_length_validates() {
// 128-byte WIT reference — exactly the cap. Boundary pin:
// drift in the cap surfaces here and at `rejects_wit_too_long`
// simultaneously, mirroring
// `http_contrato_endpoint_max_length_validates` on the peer
// axis.
let big = format!("wasi:{}", "a".repeat(123));
assert_eq!(big.len(), 128);
let mut s = three_member_spec();
s.contratos.push(WitContract {
de: "payment".into(),
para: "catalog".into(),
wit: big,
endpoint: None,
subject: None,
slot: None,
});
s.validate().unwrap();
}
#[test]
fn wit_accepts_canonical_forms_at_aplicacao_layer() {
// Positive-set sweep through the AplicacaoSpec::validate
// surface (rather than the substrate-side predicate directly)
// — pins every shape the existing test fixtures + the
// checkout-aplicacao example carry, so the gate's accept-set
// matches the substrate's emit-set. Drift between this list
// and `render::tests::wit_world_ref_accepts_canonical_forms`
// surfaces at the substrate layer's positive sweep — one
// source of truth for the rule.
for wit in [
"wasi:http/proxy",
"wasi:keyvalue/store",
"nats:pub-sub",
"kafka:topic",
"custom:exchange",
"pleme:cap/audit",
"wasi:http/proxy@0.2.0",
] {
// Payload field paired to the dispatched WIT shape so the
// shape-↔-target arm doesn't fire instead of the wit-shape
// arm we're exercising. Routes off the same
// `wit_shape_is_http` / `wit_shape_is_pubsub` /
// `wit_shape_is_store` free functions the production
// `WitContract::is_http` / `is_pubsub` / `is_store`
// methods delegate to (both consult the lifted
// `WIT_HTTP_SHAPE_PREFIXES` / `WIT_PUBSUB_SHAPE_PREFIXES`
// / `WIT_STORE_SHAPE_PREFIXES` prefix sets), so any
// future prefix addition to the routing accept-set
// reaches this test's payload-dispatch arm by
// construction — no per-test-site drift can hide a
// shape-→-target-slot mismatch that would silently
// demote a canonical `:wit` value to the
// `(None, None, None)` capability-only arm and let the
// `AplicacaoSpec::validate` positive sweep pass on a
// shape it should exercise as HTTP / pub-sub / store.
let (endpoint, subject, slot) = if wit_shape_is_http(wit) {
(Some("/x".into()), None, None)
} else if wit_shape_is_pubsub(wit) {
(None, Some("topic.x".into()), None)
} else if wit_shape_is_store(wit) {
(None, None, Some("bucket/$key".into()))
} else {
(None, None, None)
};
let mut s = three_member_spec();
s.contratos.push(WitContract {
de: "payment".into(),
para: "catalog".into(),
wit: wit.into(),
endpoint,
subject,
slot,
});
s.validate()
.unwrap_or_else(|e| panic!("canonical WIT {wit:?} must validate, got {e:?}"));
}
}
#[test]
fn wit_shape_predicates_accept_canonical_prefix_set() {
// Positive-set sweep pinning every prefix in
// WIT_HTTP_SHAPE_PREFIXES / WIT_PUBSUB_SHAPE_PREFIXES /
// WIT_STORE_SHAPE_PREFIXES against the three free-function
// dispatch predicates. The six prefixes are the load-bearing
// routing keys the substrate's WIT-shape dispatch consults
// (L7-HTTP-vs-L4, pub-sub-cycle exclusion,
// key/value-store-slot admission); any drift between the
// free-function accept-set and this list surfaces here
// rather than at apply time as a silent
// shape-→-capability-only demotion.
assert!(wit_shape_is_http("wasi:http/proxy"));
assert!(wit_shape_is_http("wasi:http/proxy@0.2.0"));
assert!(wit_shape_is_http("http:incoming"));
assert!(wit_shape_is_pubsub("nats:pub-sub"));
assert!(wit_shape_is_pubsub("kafka:topic"));
assert!(wit_shape_is_store("wasi:keyvalue/store"));
assert!(wit_shape_is_store("kv:cache/session"));
}
#[test]
fn wit_shape_predicates_reject_uncanonical_forms() {
// Negative-set pin: the six canonical prefixes are
// lowercase-only (mirrors the `is_wit_world_ref` substrate
// predicate's lowercase invariant — see its docstring on the
// "I thought I had L7 HTTP routing, got L4-only" footgun).
// The empty string, an uppercase-prefixed form, a hyphen-
// instead-of-colon typo, and a bare kebab identifier all miss
// every shape arm — reachable-by-construction only via the
// `is_wit_world_ref` gate that admission-checks the `:wit`
// value first, but pinned here so any future
// free-function change (e.g. a case-insensitive
// `wit.to_ascii_lowercase().starts_with(p)` slip) surfaces at
// this unit level.
for wit in ["", "WASI:HTTP/proxy", "wasi-http/proxy", "custom-shape"] {
assert!(!wit_shape_is_http(wit), "{wit:?} must not be HTTP");
assert!(!wit_shape_is_pubsub(wit), "{wit:?} must not be pubsub");
assert!(!wit_shape_is_store(wit), "{wit:?} must not be store");
}
}
#[test]
fn wit_shape_predicates_partition_canonical_set() {
// Every canonical prefix routes to exactly one shape arm —
// the three prefix sets are pairwise disjoint. Pins the
// routing property [`WitContract::target`] relies on: an
// `is_http()` return of `true` guarantees `is_pubsub()` and
// `is_store()` return `false`, so the shape-→-target-slot
// dispatch (endpoint vs subject vs slot) is unambiguous.
// Drift (e.g. a future `"kv:"` moved into the HTTP set
// without removal from the store set) would silently route
// one prefix to two arms and the first-matching-arm order
// becomes load-bearing — this pin surfaces it as a build
// error instead.
for prefix in WIT_HTTP_SHAPE_PREFIXES {
let sample = format!("{prefix}x");
assert!(wit_shape_is_http(&sample));
assert!(!wit_shape_is_pubsub(&sample));
assert!(!wit_shape_is_store(&sample));
}
for prefix in WIT_PUBSUB_SHAPE_PREFIXES {
let sample = format!("{prefix}x");
assert!(!wit_shape_is_http(&sample));
assert!(wit_shape_is_pubsub(&sample));
assert!(!wit_shape_is_store(&sample));
}
for prefix in WIT_STORE_SHAPE_PREFIXES {
let sample = format!("{prefix}x");
assert!(!wit_shape_is_http(&sample));
assert!(!wit_shape_is_pubsub(&sample));
assert!(wit_shape_is_store(&sample));
}
}
#[test]
fn wit_shape_matches_scans_prefix_set_with_starts_with_semantics() {
// Positive pin: [`wit_shape_matches`] is exactly the
// `PREFIXES.iter().any(|p| wit.starts_with(p))` combinator,
// parameterized on the accept-set. Two-prefix accept-set,
// one-prefix accept-set, and empty accept-set (which must
// reject everything, including the empty string — an empty
// `any()` fold returns `false`) all pinned so a future
// reimplementation that swaps `starts_with` for `contains`,
// `==`, or a case-folded comparator surfaces at unit-test
// time.
let two = &["wasi:http/", "http:"];
assert!(wit_shape_matches("wasi:http/proxy", two));
assert!(wit_shape_matches("http:incoming", two));
assert!(!wit_shape_matches("wasi:keyvalue/store", two));
let one = &["nats:"];
assert!(wit_shape_matches("nats:pub-sub", one));
assert!(!wit_shape_matches("kafka:topic", one));
// Empty accept-set matches nothing — the identity element
// for the disjunctive `any()` fold across the prefix set.
// Reachable via a future `wit_shape_is_<name>` const paired
// to a still-empty prefix table on a nascent shape-arm draft.
let empty: &[&str] = &[];
assert!(!wit_shape_matches("wasi:http/proxy", empty));
assert!(!wit_shape_matches("", empty));
// starts_with, not contains: a prefix embedded mid-string
// never matches. Pins the routing invariant [`WitContract::target`]
// relies on (an authored `:wit "custom:wasi:http/"` string
// does not silently route through the HTTP arm just because
// it happens to contain the canonical HTTP prefix).
assert!(!wit_shape_matches("custom:wasi:http/proxy", two));
}
#[test]
fn wit_shape_predicates_delegate_to_wit_shape_matches() {
// Equivalence pin: each per-shape predicate is exactly
// `wit_shape_matches(wit, WIT_<SHAPE>_SHAPE_PREFIXES)`. Sweeps
// every canonical prefix + the empty string + one negative
// sample against every peer so a future predicate that grew
// its own inline `iter().any(starts_with)` (rather than
// delegating through the lifted combinator) drifts loudly here
// — the peer-const table's contents must agree with the
// predicate's accept-set by construction.
let samples = [
String::new(),
"wasi:http/proxy".to_string(),
"http:incoming".to_string(),
"nats:pub-sub".to_string(),
"kafka:topic".to_string(),
"wasi:keyvalue/store".to_string(),
"kv:cache/session".to_string(),
"custom-shape".to_string(),
"WASI:HTTP/proxy".to_string(),
];
for wit in &samples {
assert_eq!(
wit_shape_is_http(wit),
wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
"wit_shape_is_http drifted from combinator on {wit:?}",
);
assert_eq!(
wit_shape_is_pubsub(wit),
wit_shape_matches(wit, WIT_PUBSUB_SHAPE_PREFIXES),
"wit_shape_is_pubsub drifted from combinator on {wit:?}",
);
assert_eq!(
wit_shape_is_store(wit),
wit_shape_matches(wit, WIT_STORE_SHAPE_PREFIXES),
"wit_shape_is_store drifted from combinator on {wit:?}",
);
}
}
#[test]
fn wit_contract_shape_methods_delegate_to_free_functions() {
// Equivalence pin: `WitContract::is_http` / `is_pubsub` /
// `is_store` are `&self` conveniences on top of the free
// functions — for every canonical prefix the method's return
// matches its free-function peer. Sweeps the union of the
// three prefix sets so a future method that grew its own
// inline prefix logic (rather than delegating) drifts loudly
// here on the first prefix the free function accepts and the
// method doesn't.
for shape_set in [
WIT_HTTP_SHAPE_PREFIXES,
WIT_PUBSUB_SHAPE_PREFIXES,
WIT_STORE_SHAPE_PREFIXES,
] {
for prefix in shape_set {
let c = WitContract {
de: "cart".into(),
para: "catalog".into(),
wit: format!("{prefix}x"),
endpoint: None,
subject: None,
slot: None,
};
assert_eq!(c.is_http(), wit_shape_is_http(&c.wit));
assert_eq!(c.is_pubsub(), wit_shape_is_pubsub(&c.wit));
assert_eq!(c.is_store(), wit_shape_is_store(&c.wit));
assert_eq!(c.is_capability(), wit_shape_is_capability(&c.wit));
}
}
// Capability-arm delegation sweep: two representative
// Capability-shaped `:wit` values (a bare non-prefix-matching
// WIT world, the deliberately-shaped empty string
// [`WitContract::is_capability`]'s docstring calls out as
// syntactically Capability). Extends the free-function
// delegation pin onto the fourth arm so a future
// [`WitContract::is_capability`] rewrite that grew an inline
// prefix-set scan (rather than delegating through
// [`wit_shape_is_capability`]) drifts loudly here on the first
// Capability-shaped sample.
for wit in ["custom:capability-only", ""] {
let c = WitContract {
de: "cart".into(),
para: "catalog".into(),
wit: wit.into(),
endpoint: None,
subject: None,
slot: None,
};
assert_eq!(c.is_capability(), wit_shape_is_capability(&c.wit));
}
}
#[test]
fn wit_shape_is_capability_partitions_the_wit_shape_space_on_the_raw_str_axis() {
// 4-way partition-witness pin on the raw `&str` axis: for every
// canonical prefix in the three payload-arm accept-sets,
// exactly one of the four [`wit_shape_is_http`] /
// [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
// [`wit_shape_is_capability`] free functions returns `true` and
// the other three return `false` — the four-arm partition
// witness that locks the free-function WIT-shape-classifier
// family into a partition of the `:contratos :wit` axis
// load-bearing. Peer of the sibling [`WitContract`]-surface
// [`wit_contract_is_capability_partitions_the_wit_shape_space`]
// partition pin — extends the discipline onto the raw `&str`
// axis so any future arm addition (a hypothetical
// `wasi:sockets/*` transport-layer shape, an `oci:*`
// capability-import carrier per the sibling
// [`wit_shape_matches`] docstring's trajectory bullet) that
// landed on one of the payload-arm free functions without
// shrinking [`wit_shape_is_capability`]'s accept-set surfaces
// here as two arms returning `true` simultaneously at
// caixa-core build time rather than a silent per-consumer
// misclassification at renderer emit time.
for shape_set in [
WIT_HTTP_SHAPE_PREFIXES,
WIT_PUBSUB_SHAPE_PREFIXES,
WIT_STORE_SHAPE_PREFIXES,
] {
for prefix in shape_set {
let wit = format!("{prefix}x");
let hits = [
wit_shape_is_http(&wit),
wit_shape_is_pubsub(&wit),
wit_shape_is_store(&wit),
wit_shape_is_capability(&wit),
]
.iter()
.filter(|&&b| b)
.count();
assert_eq!(
hits,
1,
"raw-&str WIT-shape 4-way predicate partition must \
admit exactly one arm per canonical prefix; got {hits} \
hits at wit={wit:?} (is_http={}, is_pubsub={}, is_store={}, \
is_capability={})",
wit_shape_is_http(&wit),
wit_shape_is_pubsub(&wit),
wit_shape_is_store(&wit),
wit_shape_is_capability(&wit),
);
}
}
// Capability-arm sweep on the raw `&str` axis: two
// representative Capability-shaped `:wit` values (a bare non-
// prefix-matching WIT world, the deliberately-shaped empty
// string the pure classifier still admits per
// [`wit_shape_is_capability`]'s docstring). Both must land on
// the fourth arm exclusively so the partition witness holds
// across the full 4-arm closure on the raw `&str` axis.
for wit in ["custom:capability-only", ""] {
let hits = [
wit_shape_is_http(wit),
wit_shape_is_pubsub(wit),
wit_shape_is_store(wit),
wit_shape_is_capability(wit),
]
.iter()
.filter(|&&b| b)
.count();
assert_eq!(
hits, 1,
"raw-&str WIT-shape 4-way predicate partition must \
admit exactly one arm on Capability-shaped wit={wit:?}"
);
assert!(
wit_shape_is_capability(wit),
"wit={wit:?} must project onto the Capability arm on the raw-&str axis"
);
}
}
#[test]
fn wit_shape_is_capability_composes_through_payload_arm_predicate_negation() {
// Composition-witness pin: [`wit_shape_is_capability`] is the
// exact-inverse disjunction of the sibling payload-arm free-
// function trio [`wit_shape_is_http`] / [`wit_shape_is_pubsub`]
// / [`wit_shape_is_store`]. A future reimplementation that
// grew its own prefix-set scan (e.g. inlining a fourth
// [`WIT_CAPABILITY_SHAPE_PREFIXES`] const the substrate does
// not own today) rather than delegating to the sibling trio
// would drift loudly here — the composition contract binds the
// fourth-arm free-function predicate to the exact-inverse of
// the three payload-arm free-function predicates, so any
// rebrand of any prefix-set const flows through
// [`wit_shape_is_capability`] by construction without a
// coordinated per-consumer rewrite. Peer of the sibling
// [`WitContract`]-surface
// [`wit_contract_is_capability_composes_through_shape_predicate_negation`]
// composition pin — extends the discipline onto the raw
// `&str` axis.
let mut cases: Vec<String> = Vec::new();
for shape_set in [
WIT_HTTP_SHAPE_PREFIXES,
WIT_PUBSUB_SHAPE_PREFIXES,
WIT_STORE_SHAPE_PREFIXES,
] {
for prefix in shape_set {
cases.push(format!("{prefix}x"));
}
}
cases.push("custom:capability-only".to_string());
cases.push(String::new());
for wit in cases {
assert_eq!(
wit_shape_is_capability(&wit),
!wit_shape_is_http(&wit) && !wit_shape_is_pubsub(&wit) && !wit_shape_is_store(&wit),
"wit_shape_is_capability must equal \
!wit_shape_is_http() && !wit_shape_is_pubsub() && !wit_shape_is_store() \
at wit={wit:?}"
);
}
}
#[test]
fn wit_shape_classifier_family_is_const_fn() {
// Fail-before-pass-after pin on the 4-arm free-function WIT-
// shape classifier family's `const`-eval posture. Each of the
// four peer classifiers ([`wit_shape_is_http`] /
// [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
// [`wit_shape_is_capability`]) and the underlying combinator
// [`wit_shape_matches`] must be `pub const fn` — any future
// accidental downgrade to non-`const` fails the `const fn`
// wrappers below at caixa-core build time with E0015
// (`cannot call non-const function`), strictly stronger than
// a runtime `assert!` and strictly stronger than the module-
// scope `const _: () = assert!(…)` pins immediately after the
// classifier declarations (those anchor specific accept-set
// truth-table entries; this pin anchors the `const` posture
// itself via `const fn` wrappers that are only well-formed
// when the callee is itself `const fn`).
//
// Verified fail-before-pass-after by locally reverting
// `pub const fn` → `pub fn` on each classifier and observing
// E0015 at every corresponding wrapper call site (build
// error, no test-time surface), then restoring `pub const fn`
// and observing the pin pass at test time. Peer of the
// sibling M3
// [`rate_limit_unit_from_window_accessor_is_const_fn`] /
// [`rate_limit_canonical_unit_accessor_is_const_fn`] (974bbd8),
// M2
// [`child_spec_restart_accessor_is_const_fn`] /
// [`supervisor_spec_estrategia_accessor_is_const_fn`] (152c868),
// and M3
// [`placement_estrategia_accessor_is_const_fn`] /
// [`entrada_port_accessor_is_const_fn`] (bafa004) pins on the
// sibling `const`-eval-surface-pass axes.
const fn matches_via_const_fn(wit: &str, prefixes: &[&str]) -> bool {
wit_shape_matches(wit, prefixes)
}
const fn http_via_const_fn(wit: &str) -> bool {
wit_shape_is_http(wit)
}
const fn pubsub_via_const_fn(wit: &str) -> bool {
wit_shape_is_pubsub(wit)
}
const fn store_via_const_fn(wit: &str) -> bool {
wit_shape_is_store(wit)
}
const fn capability_via_const_fn(wit: &str) -> bool {
wit_shape_is_capability(wit)
}
// Sweep one canonical accept-set sample per arm plus the
// payload-less/empty capability samples, asserting the
// wrapper and direct dispatches agree byte-for-byte across
// the closed 4-arm partition.
let cases: [(&str, bool, bool, bool, bool); 6] = [
("wasi:http/proxy", true, false, false, false),
("http:incoming", true, false, false, false),
("nats:events", false, true, false, false),
("kafka:topic", false, true, false, false),
("wasi:keyvalue/store", false, false, true, false),
("kv:cache", false, false, true, false),
];
for (wit, is_http, is_pubsub, is_store, _is_capability) in cases {
assert_eq!(
matches_via_const_fn(wit, WIT_HTTP_SHAPE_PREFIXES),
wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
"wit_shape_matches const fn wrapper disagrees at wit={wit:?}",
);
assert_eq!(http_via_const_fn(wit), wit_shape_is_http(wit));
assert_eq!(pubsub_via_const_fn(wit), wit_shape_is_pubsub(wit));
assert_eq!(store_via_const_fn(wit), wit_shape_is_store(wit));
assert_eq!(capability_via_const_fn(wit), wit_shape_is_capability(wit));
assert_eq!(wit_shape_is_http(wit), is_http);
assert_eq!(wit_shape_is_pubsub(wit), is_pubsub);
assert_eq!(wit_shape_is_store(wit), is_store);
}
// Payload-less capability arm (the 4th partition arm).
let capability_samples: [&str; 3] =
["wasi:filesystem/preopens", "custom:capability-only", ""];
for wit in capability_samples {
assert_eq!(capability_via_const_fn(wit), wit_shape_is_capability(wit));
assert!(wit_shape_is_capability(wit));
assert!(!wit_shape_is_http(wit));
assert!(!wit_shape_is_pubsub(wit));
assert!(!wit_shape_is_store(wit));
}
}
// Canonical `(wit, expected)` sweep the four [`WitShape`] pins below
// key off — one accept-set sample per prefix in each of the three
// payload-arm prefix sets [`WIT_HTTP_SHAPE_PREFIXES`] /
// [`WIT_PUBSUB_SHAPE_PREFIXES`] / [`WIT_STORE_SHAPE_PREFIXES`], plus
// three canonical Capability-arm samples (a non-prefix-matching WIT
// world, an empty string, a partial-match probe that lands after
// the accepted prefix boundary). Declared once so a future arm
// addition or prefix-set edit grows the truth table at one
// authored site and every downstream pin picks up the new row by
// construction.
const WIT_SHAPE_CLASSIFY_TRUTH_TABLE: &[(&str, WitShape)] = &[
("wasi:http/proxy", WitShape::Http),
("http:incoming", WitShape::Http),
("nats:events", WitShape::PubSub),
("kafka:topic", WitShape::PubSub),
("wasi:keyvalue/store", WitShape::Store),
("kv:cache", WitShape::Store),
("wasi:filesystem/preopens", WitShape::Capability),
("custom:capability-only", WitShape::Capability),
("", WitShape::Capability),
];
#[test]
fn wit_shape_all_matches_declaration_order_and_covers_every_arm() {
// Fail-before-pass-after pin on [`WitShape::ALL`]: the slice
// must enumerate every arm exactly once in declaration order
// (`Http` → `PubSub` → `Store` → `Capability`), so downstream
// consumers that walk the shape space through the const slice
// reach every arm and see them in the canonical order the
// paired [`WitShape::classify`] arm-preference dispatches on.
// A future variant addition that forgets to grow the slice
// trips here (the length no longer matches the number of arms
// touched by the `match self` below); a rearrangement of the
// declaration order without updating the slice trips too.
let expected: [WitShape; 4] = [
WitShape::Http,
WitShape::PubSub,
WitShape::Store,
WitShape::Capability,
];
assert_eq!(WitShape::ALL.len(), expected.len());
assert_eq!(WitShape::ALL, &expected[..]);
// Exhaustive-match witness: touch every arm so a future
// variant addition without a matching `WitShape::ALL` extension
// trips at compile time here on the missing arm.
for arm in WitShape::ALL {
match arm {
WitShape::Http | WitShape::PubSub | WitShape::Store | WitShape::Capability => {}
}
}
}
#[test]
fn wit_shape_classify_pins_the_canonical_truth_table() {
// Pin the [`WitShape::classify`] arm-dispatch against the
// shared truth table [`WIT_SHAPE_CLASSIFY_TRUTH_TABLE`]. A
// future prefix-set edit that reroutes any canonical sample
// onto the wrong arm trips at exactly the offending row.
for (wit, expected) in WIT_SHAPE_CLASSIFY_TRUTH_TABLE {
assert_eq!(
WitShape::classify(wit),
*expected,
"WitShape::classify({wit:?}) drifted from truth table",
);
}
}
#[test]
fn wit_shape_classify_partitions_via_is_variant_predicates() {
// Fail-before-pass-after pin: for every canonical truth-table
// row, the classified arm satisfies exactly one of the four
// [`gen_platform::IsVariant`]-derived arm-discriminator
// predicates ([`WitShape::is_http`] / [`is_pubsub`] /
// [`is_store`] / [`is_capability`]) — the observed 4-slot
// predicate row must equal a one-hot row with the `true` at
// exactly the same index as the declared arm's slot in
// [`WitShape::ALL`]. A future rebind (an `#[is_variant(name =
// "…")]` drift, a manual `impl` shadowing the derive, an arm
// rename that reroutes one arm through the wrong predicate
// lane) trips here at exactly the offending row rather than
// surfacing far from the derive commit.
for (wit, expected) in WIT_SHAPE_CLASSIFY_TRUTH_TABLE {
let arm = WitShape::classify(wit);
let observed = [
arm.is_http(),
arm.is_pubsub(),
arm.is_store(),
arm.is_capability(),
];
let mut expected_row = [false; 4];
let idx = WitShape::ALL
.iter()
.position(|a| a == expected)
.expect("truth-table arm appears in WitShape::ALL");
expected_row[idx] = true;
assert_eq!(
observed, expected_row,
"WitShape::classify({wit:?}).is_* row must be one-hot at slot {idx}",
);
}
}
#[test]
fn wit_shape_classify_agrees_with_free_predicates() {
// Equivalence pin against the four free classifier predicates
// ([`wit_shape_is_http`] / [`wit_shape_is_pubsub`] /
// [`wit_shape_is_store`] / [`wit_shape_is_capability`]) — after
// this lift the free predicates route through
// `matches!(WitShape::classify(wit), WitShape::<arm>)`, so this
// pin proves the delegation preserves each predicate's
// accept-set on the canonical truth table. A future accidental
// reintroduction of an open-coded free-predicate body (or a
// classify-side arm reorder that shifts arm preference in a
// way that breaks disjointness) trips here at the offending
// row rather than at a downstream consumer.
for (wit, _expected) in WIT_SHAPE_CLASSIFY_TRUTH_TABLE {
let arm = WitShape::classify(wit);
assert_eq!(arm.is_http(), wit_shape_is_http(wit));
assert_eq!(arm.is_pubsub(), wit_shape_is_pubsub(wit));
assert_eq!(arm.is_store(), wit_shape_is_store(wit));
assert_eq!(arm.is_capability(), wit_shape_is_capability(wit));
}
}
#[test]
fn wit_shape_as_str_display_and_asref_route_through_one_source() {
// Fail-before-pass-after pin on the canonical-projection triple
// [`WitShape::as_str`] / [`std::fmt::Display for WitShape`] /
// [`AsRef<str> for WitShape`]: every arm's `Display`-formatted
// and `AsRef<str>`-borrowed output must byte-equal its
// `as_str` output. Same discipline the sibling
// [`crate::CaixaKind`] / [`crate::dialeto::CaixaDialeto`] /
// [`PlacementStrategy`] / [`RateLimitUnit`] canonical-projection
// triples carry — a future accidental hand-rolled `Display`
// body that diverges from `as_str` trips here.
let expected: &[(WitShape, &str)] = &[
(WitShape::Http, "http"),
(WitShape::PubSub, "pubsub"),
(WitShape::Store, "store"),
(WitShape::Capability, "capability"),
];
for (arm, want) in expected {
assert_eq!(arm.as_str(), *want, "WitShape::as_str({arm:?}) drifted");
assert_eq!(
format!("{arm}"),
*want,
"Display for WitShape drifted from as_str at {arm:?}",
);
assert_eq!(
AsRef::<str>::as_ref(arm),
*want,
"AsRef<str> for WitShape drifted from as_str at {arm:?}",
);
}
}
#[test]
fn wit_shape_classify_is_const_fn() {
// Fail-before-pass-after pin on [`WitShape::classify`]'s
// `const`-eval posture. The classifier must be `pub const fn`
// — any future accidental downgrade to non-`const` fails the
// wrapper below with E0015 at caixa-core build time, strictly
// stronger than a runtime `assert!`. Peer of the sibling
// [`wit_shape_classifier_family_is_const_fn`] pin on the
// free-function classifier family.
const fn classify_via_const_fn(wit: &str) -> WitShape {
WitShape::classify(wit)
}
// Compile-time truth-table pin: every canonical row's
// classification is reachable at const-eval time, so any
// downstream `const`-context consumer (a module-scope
// `const _: () = assert!(matches!(WitShape::classify(<lit>),
// WitShape::<arm>))` invariant pin on a typed fixture, a
// future `const fn` per-`:contratos :wit` arm-resolver over a
// static wit literal) reaches the classifier through one
// dispatch on the substrate primitive without an intermediate
// non-`const` step.
const _: () = assert!(matches!(
classify_via_const_fn("wasi:http/proxy"),
WitShape::Http
));
const _: () = assert!(matches!(
classify_via_const_fn("nats:events"),
WitShape::PubSub
));
const _: () = assert!(matches!(
classify_via_const_fn("wasi:keyvalue/store"),
WitShape::Store
));
const _: () = assert!(matches!(classify_via_const_fn(""), WitShape::Capability));
// Also assert const `as_str` routes through the const `classify`
// on the same const path.
const _: () = assert!(matches!(
classify_via_const_fn("wasi:http/proxy").as_str().as_bytes(),
b"http"
));
}
#[test]
fn wit_shape_from_wire_accepts_every_as_str_output() {
// Fail-before-pass-after per-arm accept pin on the newly lifted
// [`WitShape::from_wire`] reverse projection: every arm in
// [`WitShape::ALL`] must parse back through `from_wire` when fed
// its own [`WitShape::as_str`] output, landing on
// `Some(same_variant)`. A regression that hand-rolled either
// side's per-arm match without threading through the shared
// four-string closed set would silently disagree on any future
// arm rename (or a new arm the WIT-shape space grows — a
// hypothetical `wasi:sockets/*` transport-layer shape, an
// `oci:*` capability-import carrier per the sibling
// [`wit_shape_matches`] docstring's trajectory bullet) and this
// pin flags it at caixa-core build time rather than at a
// downstream `feira app graph --by-wit-shape` consumer's silent
// tag misclassification.
//
// Peer of the sibling
// `caixa_provedor::ferrite::tests::ferrite_runtime_from_wire_accepts_every_variant_slug_output`
// (1e4cc81) /
// `caixa_theme::style::tests::semantic_from_wire_accepts_every_as_str_output`
// (e7bca7b) /
// `caixa_lint::diagnostic::tests::fix_safety_from_wire_accepts_every_as_str_output`
// (bd505a1) /
// `caixa_lint::diagnostic::tests::severity_from_wire_accepts_every_as_str_output`
// (5afff0e) /
// `caixa_arch::report::tests::arch_verdict_from_wire_accepts_every_as_str_output`
// (6afe564) /
// `caixa_arch::invariants::tests::invariant_kind_from_wire_accepts_every_as_str_output`
// (b9e4e61) round-trip pins on the peer caixa-provedor /
// caixa-theme / caixa-lint / caixa-arch closed-set-enum
// reverse-projection axes, and of the sibling
// `crate::kind::tests::caixa_kind_wire_round_trips_through_from_wire`
// (2aa6d23) /
// `crate::dialeto::tests::caixa_dialeto_from_wire_accepts_every_as_str_output`
// (d0e65ea) /
// `placement_strategy_from_wire_accepts_every_lifted_constant`
// (18c7342) /
// `crate::dep::tests::dep_list_round_trips_through_as_str_and_from_wire`
// (45ee563) /
// `crate::render::tests::path_shape_violation_from_wire_accepts_every_as_str_output`
// (aebd9c6) round-trip pins on the sibling caixa-core closed-
// set typed-enum reverse-projection axes.
for &variant in WitShape::ALL {
let wire = variant.as_str();
let parsed = WitShape::from_wire(wire).unwrap_or_else(|| {
panic!(
"WitShape::from_wire({wire:?}) must accept every \
WitShape::as_str output — got None for the wire \
byte-string of {variant:?}"
)
});
assert_eq!(
parsed, variant,
"WitShape::from_wire(WitShape::{variant:?}.as_str()) must \
return WitShape::{variant:?} — the (as_str, from_wire) \
pair must form a total round-trip on the closed four-arm \
WitShape arm-set",
);
}
// Pin the exact per-arm accept-set so a future rebrand of the
// census-label byte-strings ("http" / "pubsub" / "store" /
// "capability") surfaces at this pin rather than at a downstream
// consumer's silent tag drift.
assert_eq!(WitShape::from_wire("http"), Some(WitShape::Http));
assert_eq!(WitShape::from_wire("pubsub"), Some(WitShape::PubSub));
assert_eq!(WitShape::from_wire("store"), Some(WitShape::Store));
assert_eq!(
WitShape::from_wire("capability"),
Some(WitShape::Capability),
);
}
#[test]
fn wit_shape_from_wire_rejects_unknown_byte_strings() {
// Rejection pin on the [`WitShape::from_wire`] parser's
// accept-set: any string outside the four-arm
// [`WitShape::as_str`] output set must return [`None`]. A future
// accidental widening of the accept-set (a case-insensitive
// match that accepts `"HTTP"` / `"Http"`, a silent acceptance of
// the PascalCase Debug-derived shapes `"Http"` / `"PubSub"` /
// `"Store"` / `"Capability"` on the wire axis, a Levenshtein-
// forgiving arm-lookup that admits typos, a silent absorption of
// the sibling raw `:contratos :wit` identifiers [`Self::classify`]
// consumes on the peer classifier axis — `"wasi:http/proxy"`,
// `"nats:events"`, `"wasi:keyvalue/store"`, `"kafka:topic"`,
// `"kv:cache"`, `"http:incoming"` — a silent absorption of the
// paired [`WitTarget::label`] short-form tags every downstream
// renderer already handles on the post-validation axis) would
// silently drift the parser's accept-set from the emitter's — a
// downstream re-loader that bound a prior emission's
// [`Self::as_str`] output back to the typed enum through this
// parser would then bind a malformed byte-string to a
// plausibly-wrong typed arm the caller does not route through
// any fallback, silently misclassifying the reloaded row.
//
// The raw `:contratos :wit` identifier vectors are load-bearing:
// [`WitShape::classify`] is a *total* function on every `&str`
// (falling through to [`WitShape::Capability`] on unknown
// prefixes), so a caller who confuses the two axes and routes a
// raw WIT identifier through [`from_wire`] instead of
// [`classify`] must observe [`None`] here rather than a plausibly-
// wrong `Some(WitShape::Capability)` silently — the peer axes
// carry different accept-sets by design.
//
// Peer of the sibling
// `caixa_provedor::ferrite::tests::ferrite_runtime_from_wire_rejects_unknown_byte_strings`
// (1e4cc81) /
// `caixa_theme::style::tests::semantic_from_wire_rejects_unknown_byte_strings`
// (e7bca7b) /
// `caixa_lint::diagnostic::tests::fix_safety_from_wire_rejects_unknown_byte_strings`
// (bd505a1) /
// `caixa_lint::diagnostic::tests::severity_from_wire_rejects_unknown_byte_strings`
// (5afff0e) /
// `caixa_arch::report::tests::arch_verdict_from_wire_rejects_unknown_byte_strings`
// (6afe564) /
// `caixa_arch::invariants::tests::invariant_kind_from_wire_rejects_unknown_byte_strings`
// (b9e4e61) rejection pins on the peer caixa-provedor /
// caixa-theme / caixa-lint / caixa-arch axes, and of the sibling
// `caixa_kind_from_wire_rejects_unknown_byte_strings` (2aa6d23),
// `caixa_dialeto_from_wire_rejects_unknown_byte_strings`
// (d0e65ea),
// `placement_strategy_from_wire_rejects_unknown_byte_strings`
// (18c7342),
// `dep_list_from_wire_returns_none_on_unknown_wire_scalar`
// (45ee563), and
// `path_shape_violation_from_wire_rejects_unknown_byte_strings`
// (aebd9c6) rejection pins on the sibling caixa-core axes.
for bad in [
"",
" ",
"http ",
" http",
"HTTP",
"Http",
"PUBSUB",
"PubSub",
"pub_sub",
"pub-sub",
"STORE",
"Store",
"CAPABILITY",
"Capability",
"kv",
"nats",
"kafka",
"wasi:http/proxy",
"wasi:http/",
"http:",
"http:incoming",
"nats:events",
"kafka:topic",
"wasi:keyvalue/store",
"wasi:keyvalue/",
"kv:cache",
"kv:",
"oci:capability",
"wasi:sockets/tcp",
"\u{200b}http",
"http\u{200b}",
] {
assert!(
WitShape::from_wire(bad).is_none(),
"WitShape::from_wire({bad:?}) must reject byte-strings \
outside the four-arm WitShape::as_str output set — got \
{:?}",
WitShape::from_wire(bad),
);
}
}
#[test]
fn wit_shape_from_wire_and_classify_partition_the_axis() {
// Cross-axis discipline pin: [`WitShape::classify`] is a total
// function on the raw `:contratos :wit` identifier axis (every
// `&str` classifies), while [`WitShape::from_wire`] is a partial
// function on the census-label axis (the four
// [`WitShape::as_str`] outputs and nothing else). The two axes
// meet on exactly zero strings by construction — the four
// census labels (`"http"` / `"pubsub"` / `"store"` /
// `"capability"`) are not prefix-matched by any of
// [`WIT_HTTP_SHAPE_PREFIXES`] / [`WIT_PUBSUB_SHAPE_PREFIXES`] /
// [`WIT_STORE_SHAPE_PREFIXES`], so on the shared four-string
// census-label set:
//
// * [`WitShape::from_wire`] returns `Some(<matching arm>)`
// per [`WitShape::as_str`]'s output;
// * [`WitShape::classify`] falls through to the
// [`WitShape::Capability`] catch-all fallback (since none of
// the payload-arm prefix sets begin with `"http"` /
// `"pubsub"` / `"store"` / `"capability"`).
//
// A future WIT-prefix set edit that accidentally started with
// one of the four census labels (a hypothetical
// `"http"` prefix directly, a `"pubsub://"` scheme addition, a
// `"store:"` capability-carrier extension) would silently
// collide the two axes on the same string — [`from_wire`] would
// still yield the census-label arm while [`classify`] would
// route the payload-arm dispatch through the accidental overlap.
// Locking the partition here means such a prefix-set edit
// trips this pin at caixa-core build time before the collision
// becomes observable at any downstream consumer.
for &variant in WitShape::ALL {
let label = variant.as_str();
// The census-label axis half — [`from_wire`] resolves to
// the emitter's arm identity.
assert_eq!(
WitShape::from_wire(label),
Some(variant),
"WitShape::from_wire({label:?}) must resolve to the \
emitter's arm identity on the census-label axis",
);
// The raw-classifier axis half — [`classify`] falls through
// to [`WitShape::Capability`] on every census label under
// the current prefix set. Any future overlap trips here.
assert_eq!(
WitShape::classify(label),
WitShape::Capability,
"WitShape::classify({label:?}) must fall through to \
WitShape::Capability on every census label — a match \
to any payload arm here means a payload-prefix set \
has silently collided the census-label axis with the \
raw-classifier axis",
);
}
}
#[test]
fn wit_shape_try_from_str_routes_through_from_wire_accessor() {
// Fail-before-pass-after byte-parity pin on the newly lifted
// `impl TryFrom<&str> for WitShape` — asserts the standard-
// library trait impl and the substrate-primitive
// [`WitShape::from_wire`] `Option<Self>` accessor resolve to the
// same four-arm census-label accept-set across every arm the
// exhaustive [`WitShape::ALL`] slice enumerates. Any future
// silent detour that routes the trait impl through a divergent
// projection (a per-arm inline `match s { "http" =>
// Ok(Self::Http), … }` re-inlining that opens a compile-time
// link to the un-lifted arm-literal, a stray attribute drift
// that silently splits the wire byte-string from every consumer
// that reaches for this typed dispatch) trips at caixa-core test
// time under `assert_eq!` rather than at a downstream
// `impl TryFrom<&str>`-bound consumer's silent split. Sweeps
// every one of the four arms [`WitShape::ALL`] carries so no
// arm's projection is covered only by the sibling method-named
// `from_wire` path.
//
// Peer of the sibling
// [`crate::kind::tests::caixa_kind_try_from_str_routes_through_from_wire_accessor`]
// (3c83606),
// [`crate::dialeto::tests::caixa_dialeto_try_from_str_routes_through_from_wire_accessor`]
// (bf33136),
// [`tests::placement_strategy_try_from_str_routes_through_from_wire_accessor`]
// (6fd00cd),
// [`crate::supervisor::tests::restart_strategy_try_from_str_routes_through_from_wire_accessor`]
// (5b828ed), and
// [`crate::supervisor::tests::restart_policy_try_from_str_routes_through_from_wire_accessor`]
// (6fdd0d9) round-trip pins on the sibling caixa-core closed-
// set typed-enum trait-idiomatic reverse-projection axes.
for &variant in WitShape::ALL {
let wire = variant.as_str();
assert_eq!(
<WitShape as TryFrom<&str>>::try_from(wire),
Ok(variant),
"TryFrom<&str> impl on WitShape must round-trip \
WitShape::{variant:?}.as_str() = {wire:?} back to \
Ok(WitShape::{variant:?}) — divergence from \
WitShape::from_wire signals a silent detour off the \
substrate-primitive accessor"
);
assert_eq!(
<WitShape as TryFrom<&str>>::try_from(wire).ok(),
WitShape::from_wire(wire),
"TryFrom<&str> ok()-projection on {wire:?} must byte-equal \
WitShape::from_wire on the same input"
);
}
}
#[test]
fn wit_shape_try_from_str_rejects_unknown_byte_strings() {
// Rejection witness on the `impl TryFrom<&str> for WitShape` —
// sweeps a candidate set of byte-strings outside the four-arm
// census-label wire accept-set the sibling [`WitShape::as_str`]
// emits and asserts every one lands on `Err(())`, so a future
// accidental widening of the trait impl's accept-set (a stray
// additional `_ if s.eq_ignore_ascii_case("http") => Ok(…)`
// case-fold path, a silent inclusion of a PascalCase rebrand of
// the wire byte-string that would collide the two-axis split the
// sibling `wit_shape_from_wire_rejects_unknown_byte_strings` pin
// makes load-bearing, a silent overlap with the raw WIT
// identifier accept-set the paired [`WitShape::classify`] total
// function consumes on the sibling axis that the
// `wit_shape_from_wire_and_classify_partition_the_axis` cross-
// axis discipline pin locks the accept-sets against) trips at
// caixa-core test time. The candidate set includes the empty
// string, whitespace-only padding, PascalCase rebrand candidates
// (`"Http"`, `"PubSub"`), snake_case rebrand candidates
// (`"pub_sub"`), uppercase rebrand candidates (`"HTTP"`,
// `"CAPABILITY"`), kebab-case rebrand candidates (`"pub-sub"`),
// trailing/leading-whitespace-padded canonical scalars, the
// trailing-newline shape, English-rebrand candidates
// (`"messaging"`, `"cache"`), raw `:contratos :wit` identifiers
// the sibling [`WitShape::classify`] axis consumes
// (`"wasi:http/proxy"`, `"nats:events"`,
// `"wasi:keyvalue/store"`) that must not silently leak across
// the two-axis partition, the residual `"?"` and JSON-quoted
// `"\"http\""` shape.
//
// Peer of the sibling
// [`crate::kind::tests::caixa_kind_try_from_str_rejects_unknown_byte_strings`]
// (3c83606),
// [`crate::dialeto::tests::caixa_dialeto_try_from_str_rejects_unknown_byte_strings`]
// (bf33136),
// [`tests::placement_strategy_try_from_str_rejects_unknown_byte_strings`]
// (6fd00cd),
// [`crate::supervisor::tests::restart_strategy_try_from_str_rejects_unknown_byte_strings`]
// (5b828ed), and
// [`crate::supervisor::tests::restart_policy_try_from_str_rejects_unknown_byte_strings`]
// (6fdd0d9) rejection witnesses.
let rejected: &[&str] = &[
"",
" ",
"\n",
"\t",
"Http",
"HTTP",
"PubSub",
"PUBSUB",
"Store",
"STORE",
"Capability",
"CAPABILITY",
"pub-sub",
"pub_sub",
"pubSub",
"http ",
" http",
" store ",
"capability\n",
"http/",
"messaging",
"cache",
"wasi:http/proxy",
"wasi:keyvalue/store",
"nats:events",
"?",
"\"http\"",
];
for &input in rejected {
assert_eq!(
<WitShape as TryFrom<&str>>::try_from(input),
Err(()),
"TryFrom<&str> impl on WitShape must reject the \
non-wire byte-string {input:?} — silent acceptance \
signals an accept-set widening off the paired \
WitShape::from_wire resolver, or a cross-axis leak \
from the raw-identifier axis WitShape::classify consumes"
);
}
}
#[test]
fn wit_shape_try_from_str_and_from_wire_partition_the_accept_set() {
// Cross-axis partition pin locking the newly lifted
// `impl TryFrom<&str> for WitShape` and the substrate-primitive
// [`WitShape::from_wire`] accessor to the same `Option<Self>`
// output on every input — the two axes converge on the same
// partition of `&str` by construction, and this pin asserts
// that convergence directly rather than only through
// [`WitShape::ALL`]'s per-arm sweep. Any future divergence (a
// stray case-fold path on the trait axis that widens acceptance
// past what `from_wire` admits, a silent per-arm short-circuit
// that returns `Err(())` on an input `from_wire` accepts) trips
// here under `assert_eq!` on every input in the sweep.
//
// Sweeps the four accepted census labels plus a representative
// rejection set covering the same categories the sibling
// `wit_shape_try_from_str_rejects_unknown_byte_strings` pin
// enumerates, so a regression on either axis surfaces at the
// partition pin rather than at a downstream consumer's silent
// observation split.
//
// Peer of the sibling
// [`crate::supervisor::tests::restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
// (5b828ed) and
// [`crate::supervisor::tests::restart_policy_try_from_str_and_from_wire_partition_the_accept_set`]
// (6fdd0d9) cross-axis partition pins.
let inputs: &[&str] = &[
"http",
"pubsub",
"store",
"capability",
"",
" ",
"Http",
"PubSub",
"HTTP",
"pub-sub",
"http ",
"wasi:http/proxy",
"wasi:keyvalue/store",
"nats:events",
"messaging",
"?",
];
for &input in inputs {
assert_eq!(
<WitShape as TryFrom<&str>>::try_from(input).ok(),
WitShape::from_wire(input),
"TryFrom<&str> and from_wire must agree on WitShape \
for {input:?} — the trait-idiomatic and method-named \
axes must partition the accept-set identically"
);
}
}
#[test]
fn wit_shape_from_into_static_str_routes_through_as_str_accessor() {
// Fail-before-pass-after byte-parity pin on the newly lifted
// `impl From<WitShape> for &'static str` — asserts the standard-
// library trait impl and the substrate-primitive
// [`WitShape::as_str`] `pub const fn` accessor resolve to the
// same four-arm census-label emit-set across every arm the
// exhaustive [`WitShape::ALL`] slice enumerates. Any future
// silent detour that routes the trait impl through a divergent
// projection (a per-arm inline `match shape { Http => "http", …
// }` re-inlining that opens a compile-time link to the un-lifted
// arm-literal outside the paired [`WitShape::as_str`] dispatch,
// an accidental swap onto the sibling raw-identifier axis
// [`WitShape::classify`] consumes that would collide the two-axis
// wire/classifier split the sibling
// `wit_shape_from_wire_and_classify_partition_the_axis` pin makes
// load-bearing) trips at caixa-core test time under `assert_eq!`
// rather than at a downstream `impl Into<&'static str>`-bound
// consumer's silent split. Sweeps every one of the four arms
// [`WitShape::ALL`] carries so no arm's projection is covered
// only by the sibling method-named `as_str` /
// [`std::fmt::Display`] / [`AsRef<str>`] paths. Materializes the
// `<&'static str as From<WitShape>>::from` output in four
// `const`-shape bindings against the paired [`WitShape::as_str`]
// `pub const fn` accessor to make the `'static` lifetime promise
// a build-time invariant — a future accidental downgrade of any
// of the four arms' inline census-label byte-strings to a non-
// `&'static str` (a `String::leak()`-produced return, a
// `Box::leak`-cast, an intermediate lifetime-erasing helper)
// trips at caixa-core build time rather than at a downstream
// `'static`-bound consumer.
//
// Peer of the sibling
// [`crate::supervisor::tests::restart_strategy_from_into_static_str_routes_through_as_str_accessor`]
// (523157d),
// [`crate::supervisor::tests::restart_policy_from_into_static_str_routes_through_as_str_accessor`]
// (9fb37d0),
// [`crate::kind::tests::caixa_kind_from_into_static_str_routes_through_as_str_accessor`]
// (edb827b),
// [`crate::dialeto::tests::caixa_dialeto_from_into_static_str_routes_through_as_str_accessor`]
// (c189a6f), and
// [`tests::placement_strategy_from_into_static_str_routes_through_as_str_accessor`]
// (afa3562) pins on the sibling closed-set typed-enum forward-
// projection axes — extends the trait-idiomatic forward-
// projection axis onto the sixth closed-set fieldless typed
// enum on the caixa surface (the second M3-mesh-primitive-
// defining slot enum, the `:contratos :wit` census-label axis
// the caixa-mesh renderer keys off end-to-end).
const HTTP: &str = WitShape::Http.as_str();
const PUBSUB: &str = WitShape::PubSub.as_str();
const STORE: &str = WitShape::Store.as_str();
const CAPABILITY: &str = WitShape::Capability.as_str();
for &variant in WitShape::ALL {
let via_trait: &'static str = <&'static str as From<WitShape>>::from(variant);
let via_method: &'static str = variant.as_str();
assert_eq!(
via_trait, via_method,
"From<WitShape> for &'static str impl must round-trip \
WitShape::{variant:?} to the same census-label \
byte-string WitShape::as_str returns — divergence \
signals a silent detour off the substrate-primitive \
accessor"
);
let via_into: &'static str = variant.into();
assert_eq!(
via_into, via_method,
"Into<&'static str>::into on WitShape::{variant:?} must \
byte-equal WitShape::as_str on the same input — the \
blanket-derived Into shape must resolve to the same \
as_str dispatch as the explicit From impl"
);
}
assert_eq!(
[HTTP, PUBSUB, STORE, CAPABILITY],
["http", "pubsub", "store", "capability"],
"const-context WitShape::as_str must resolve to the four \
canonical census-label byte-strings — a future accidental \
downgrade of any arm to a non-const or non-static byte-\
string breaks the `&'static str`-lifetime promise the \
paired From<WitShape> for &'static str impl carries by \
construction"
);
}
#[test]
fn wit_shape_from_into_static_str_and_as_str_partition_the_emit_set() {
// Cross-axis partition pin: the paired trait-idiomatic
// `From<WitShape> for &'static str` forward projection and the
// method-named [`WitShape::as_str`] forward projection must
// resolve identically on *every* arm, not just the ones named
// in the primary byte-parity pin above. Sweeps every
// [`WitShape::ALL`] arm and asserts the trait's `From::from`
// output byte-equals the method-named accessor's return-value
// on each, locking the two forward-projection paths together by
// construction so any future detour (a stray `From` special-case
// that lands on a divergent per-arm literal outside the paired
// `as_str` dispatch, a hypothetical rebrand touching one axis
// without the other) trips at caixa-core test time.
//
// Peer of the sibling forward-projection partition pins
// [`crate::supervisor::tests::restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
// (523157d),
// [`crate::supervisor::tests::restart_policy_from_into_static_str_and_as_str_partition_the_emit_set`]
// (9fb37d0),
// [`crate::kind::tests::caixa_kind_from_into_static_str_and_as_str_partition_the_emit_set`]
// (edb827b),
// [`crate::dialeto::tests::caixa_dialeto_from_into_static_str_and_as_str_partition_the_emit_set`]
// (c189a6f), and
// [`tests::placement_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
// (afa3562) — extends the round-trip discipline onto the sixth
// closed-set typed enum on the caixa surface, closing the two-
// way `Self ↔ &'static str` round-trip on the trait-idiomatic
// pair (`From<Self> for &'static str` + `TryFrom<&str> for
// Self`) as well as the pre-existing method-named pair
// (`as_str` + `from_wire`).
for &variant in WitShape::ALL {
let via_trait: &'static str = <&'static str as From<WitShape>>::from(variant);
let via_method: &'static str = variant.as_str();
assert_eq!(
via_trait, via_method,
"From<WitShape> for &'static str and WitShape::as_str \
must resolve identically on WitShape::{variant:?} — \
divergence signals the two forward-projection paths \
have drifted onto different emit-sets"
);
}
// Round-trip witness: every arm's forward `From` output re-parses
// through the paired trait-idiomatic reverse `TryFrom<&str>` back
// to the original variant. Closes the two-way `WitShape ↔
// &'static str` round-trip on the trait-idiomatic axis pair
// directly (no wire-vocab intermediate the peer [`CaixaKind`]
// axis pair requires — the emit-side [`WitShape::as_str`] and
// the parse-side [`WitShape::from_wire`] dispatch on the same
// four inline census-label byte-strings by construction), and
// in the same way the peer [`PlacementStrategy`] axis pair
// (afa3562) closes on its three-arm surface — mirroring the
// pre-existing method-named `as_str` + `from_wire` round-trip
// on the substrate-primitive axis pair.
for &variant in WitShape::ALL {
let emitted: &'static str = variant.into();
let re_parsed: Result<WitShape, ()> = <WitShape as TryFrom<&str>>::try_from(emitted);
assert_eq!(
re_parsed,
Ok(variant),
"trait-idiomatic axis pair must round-trip \
WitShape::{variant:?} through `.into::<&'static \
str>()` and back through `TryFrom<&str>` — a break \
signals the forward-emit and reverse-parse axes have \
drifted onto different vocabularies"
);
}
}
#[test]
fn wit_shape_from_borrowed_into_static_str_routes_through_as_str_accessor() {
// Fail-before-pass-after byte-parity pin on the newly lifted
// `impl From<&WitShape> for &'static str` — asserts the
// borrowed-input standard-library trait impl and the
// substrate-primitive [`WitShape::as_str`] `pub const fn`
// accessor resolve to the same four-arm census-label emit-set
// across every arm the exhaustive [`WitShape::ALL`] slice
// enumerates. Rust's `From` trait does not auto-derive the
// borrowed-input sibling from a paired owned-input impl (no
// `impl<T, U> From<&T> for U where T: Copy, U: From<T>`
// blanket in `core`), so the borrowed-input axis is a distinct
// trait-idiomatic surface that a `.iter().map(Into::into)`
// shape over [`WitShape::ALL`] (whose iterator yields
// `&WitShape`, not `WitShape`) reaches through this impl and
// no other — the paired owned-input [`From<WitShape>`] impl
// requires an explicit `.copied()` / dereference before the
// trait fires. Materializes the `<&'static str as
// From<&WitShape>>::from` output in a `const`-shape binding to
// make the `'static` lifetime promise a build-time invariant.
// Peer of the sibling
// [`crate::dep::tests::dep_list_from_borrowed_into_static_str_routes_through_as_str_accessor`]
// (64aa742) /
// [`crate::kind::tests::caixa_kind_from_borrowed_into_static_str_routes_through_as_str_accessor`]
// (5ab993a) /
// [`crate::dialeto::tests::caixa_dialeto_from_borrowed_into_static_str_routes_through_as_str_accessor`]
// (807b0b5) /
// [`crate::supervisor::tests::restart_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
// (e941836) /
// [`crate::supervisor::tests::restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
// (842c7f3) /
// [`tests::placement_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
// (4d941d8) pins on the sibling closed-set typed-enum
// borrowed-input forward-projection axes — extends the
// borrowed-input axis onto the second M3-mesh-primitive-
// defining closed-set typed enum on the caixa surface (the
// `:contratos :wit` census-label axis the caixa-mesh renderer
// keys off end-to-end for per-edge programs.yaml fan-out).
const HTTP: &str = WitShape::Http.as_str();
const PUBSUB: &str = WitShape::PubSub.as_str();
const STORE: &str = WitShape::Store.as_str();
const CAPABILITY: &str = WitShape::Capability.as_str();
for variant in WitShape::ALL {
let via_trait: &'static str = <&'static str as From<&WitShape>>::from(variant);
let via_method: &'static str = variant.as_str();
assert_eq!(
via_trait, via_method,
"From<&WitShape> for &'static str impl must round-trip \
&WitShape::{variant:?} to the same census-label \
byte-string WitShape::as_str returns — divergence \
signals a silent detour off the substrate-primitive \
accessor"
);
let via_into: &'static str = variant.into();
assert_eq!(
via_into, via_method,
"Into<&'static str>::into on &WitShape::{variant:?} \
must byte-equal WitShape::as_str on the same input — \
the blanket-derived Into shape must resolve to the \
same as_str dispatch as the explicit From impl"
);
}
assert_eq!(
[HTTP, PUBSUB, STORE, CAPABILITY],
["http", "pubsub", "store", "capability"],
"const-context WitShape::as_str must resolve to the four \
canonical census-label byte-strings — the borrowed-input \
From<&WitShape> for &'static str impl inherits its \
`'static` lifetime promise from the same accessor the \
owned-input sibling routes through"
);
}
#[test]
fn wit_shape_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
// Cross-axis partition pin: the paired trait-idiomatic
// owned-input `From<WitShape> for &'static str` (56998ec
// campaign-shape) and borrowed-input `From<&WitShape> for
// &'static str` (this lift) forward projections must resolve
// identically on every arm, locking the two input-shape paths
// together so any future detour trips at caixa-core test time.
// Then a witness that a `.iter().map(Into::into)` pipe over
// [`WitShape::ALL`] (whose iterator yields `&WitShape`)
// materializes the four-arm accept-set through the borrowed-
// input axis alone — the exact shape a future M4 admission-
// webhook rejection body's accepted-set enumeration, a future
// substrate-wide per-arm diagnostic column, or a
// `HashMap::<&'static str, WitShape>::from_iter(
// WitShape::ALL.iter().map(|s| (s.into(), *s)))`-style
// per-shape lookup reaches through — closing the two-way
// owned/borrowed input-shape symmetry on the M3 slot enum's
// forward-projection trait-idiomatic axis. Peer of the sibling
// [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
// (64aa742) /
// [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
// (5ab993a) /
// [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
// (807b0b5) /
// [`crate::supervisor::tests::restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
// (e941836) /
// [`crate::supervisor::tests::restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
// (842c7f3) /
// [`tests::placement_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
// (4d941d8) partition pins on the sibling closed-set typed-
// enum discriminator axes — extends the borrowed-input axis
// discipline onto the second M3-mesh-primitive-defining
// closed-set typed enum on the caixa surface (the `:contratos
// :wit` census-label axis). Also closes the direct two-way
// `&Self → &'static str → Self` round-trip via the paired
// [`TryFrom<&str>`] axis — unlike the peer [`crate::CaixaKind`]
// axis pair (whose forward `From` emits lowercase Portuguese
// diagnostic bytes while the reverse `TryFrom` parses
// `PascalCase` wire bytes, forcing the round-trip through an
// intermediate wire-vocab hop), the [`WitShape::as_str`] emit
// and [`WitShape::from_wire`] parse share the same census-
// label vocabulary by construction, so the borrowed-input
// forward axis and the reverse axis compose directly.
for &variant in WitShape::ALL {
let owned: &'static str = <&'static str as From<WitShape>>::from(variant);
let borrowed: &'static str = <&'static str as From<&WitShape>>::from(&variant);
assert_eq!(
owned, borrowed,
"From<WitShape> and From<&WitShape> for &'static str \
must resolve identically on WitShape::{variant:?} — \
divergence signals the owned-input and borrowed-input \
forward-projection paths have drifted onto different \
emit-sets"
);
}
let via_iter: Vec<&'static str> = WitShape::ALL.iter().map(Into::into).collect();
let via_method: Vec<&'static str> = WitShape::ALL.iter().map(|s| s.as_str()).collect();
assert_eq!(
via_iter, via_method,
"`.iter().map(Into::into)` over WitShape::ALL must \
byte-equal `.iter().map(|s| s.as_str())` on every arm — \
the borrowed-input `From<&WitShape> for &'static str` \
axis is what makes the `.iter().map(Into::into)` shape \
route through the substrate-primitive `WitShape::as_str` \
accessor rather than through a per-call-site `.copied()` \
/ dereference detour"
);
for variant in WitShape::ALL {
let emitted: &'static str = variant.into();
let re_parsed: Result<WitShape, ()> = <WitShape as TryFrom<&str>>::try_from(emitted);
assert_eq!(
re_parsed,
Ok(*variant),
"trait-idiomatic borrowed-input forward-projection + \
reverse-projection axis pair must round-trip \
&WitShape::{variant:?} through `.into::<&'static \
str>()` (via the borrowed-input axis) and back \
through `TryFrom<&str>` — a break signals the \
borrowed-input forward-emit and reverse-parse axes \
have drifted onto different vocabularies"
);
}
}
#[test]
fn wit_shape_from_into_owned_string_routes_through_as_str_accessor() {
// Fail-before-pass-after byte-parity pin on the newly lifted
// `impl From<WitShape> for String` — asserts the owned-`String`-
// returning standard-library trait impl and the substrate-
// primitive [`WitShape::as_str`] `pub const fn` accessor
// resolve to the same four-arm census-label emit-set across
// every arm the exhaustive [`WitShape::ALL`] slice enumerates.
// Rust's standard library does not carry a blanket
// `impl<T: AsRef<str>> From<T> for String` (nor an
// `impl<T: fmt::Display> From<T> for String`), so the
// owned-`String` forward-projection axis is a distinct trait-
// idiomatic surface that a `let key: String = shape.into();`-
// shaped call site reaches through this impl and no other —
// the paired sibling `From<WitShape> for &'static str` impl
// forces every owned-`String` call site through an explicit
// `.to_owned()` / `String::from` restatement. Peer of the
// first-mover
// [`crate::supervisor::tests::restart_strategy_from_into_owned_string_routes_through_as_str_accessor`]
// (7baa18a), the second-peer
// [`crate::supervisor::tests::restart_policy_from_into_owned_string_routes_through_as_str_accessor`]
// (7851725), the third-peer
// [`crate::kind::tests::caixa_kind_from_into_owned_string_routes_through_as_str_accessor`]
// (231a18c), the fourth-peer
// [`crate::dialeto::tests::caixa_dialeto_from_into_owned_string_routes_through_as_str_accessor`]
// (88942cd), the fifth-peer
// [`crate::dep::tests::dep_list_from_into_owned_string_routes_through_as_str_accessor`]
// (32b0ee8), and the sixth-peer
// [`tests::placement_strategy_from_into_owned_string_routes_through_as_str_accessor`]
// (1154c2f) — extends the trait-idiomatic owned-`String`
// forward-projection axis onto the seventh closed-set fieldless
// typed enum on the caixa surface (the second
// M3-mesh-primitive-defining `:contratos :wit` census-label
// axis).
for &variant in WitShape::ALL {
let via_trait: String = <String as From<WitShape>>::from(variant);
let via_method: &'static str = variant.as_str();
assert_eq!(
via_trait.as_str(),
via_method,
"From<WitShape> for String impl must round-trip \
WitShape::{variant:?} to the same four-arm census-label \
byte-string WitShape::as_str returns — divergence \
signals a silent detour off the substrate-primitive \
accessor"
);
let via_into: String = variant.into();
assert_eq!(
via_into.as_str(),
via_method,
"Into<String>::into on WitShape::{variant:?} must \
byte-equal WitShape::as_str on the same input — the \
blanket-derived Into shape must resolve to the same \
as_str dispatch as the explicit From impl"
);
}
}
#[test]
fn wit_shape_from_into_owned_string_and_static_str_agree_on_every_arm() {
// Cross-axis partition pin: the paired trait-idiomatic
// owned-`String` `From<WitShape> for String` (this lift) and
// owned-`&'static str` `From<WitShape> for &'static str`
// (56998ec) forward projections must resolve identically on
// every arm, locking the two return-type-shape paths together
// so any future detour trips at caixa-core test time. Also
// byte-parity witness against the sibling
// [`ToString::to_string`] surface routed through
// [`std::fmt::Display`] — the three owned-heap-string paths
// (`.into::<String>()`, `String::from`, `.to_string()`) must
// resolve identically on every arm so a future consumer that
// picks any of the three lands on the same four-arm inline
// census-label accept-set. Then a
// `.iter().copied().map(String::from)` pipe witness over
// [`WitShape::ALL`] that materializes the four-arm accept-set
// through the owned-`String` axis alone — the exact shape a
// future M4 admission-webhook rejection body composer or a
// `HashMap::<String, WitShape>::from_iter(WitShape::ALL.iter()
// .copied().map(|s| (s.into(), s)))`-style owned-key
// per-shape lookup reaches through — closing the owned-`String`
// forward-projection axis's iterator-pipe shape. Then a direct
// round-trip witness through the paired trait-idiomatic reverse
// [`TryFrom<&str>`] axis on the owned-`String`'s
// [`String::as_str`] borrow that closes the two-way `Self →
// String → Self` round-trip on the trait-idiomatic
// owned-`String` forward + reverse axis pair.
//
// Unlike the peer [`crate::CaixaKind`] axis pair (whose forward
// `From` emit lands on the lowercase Portuguese `as_str`
// diagnostic vocabulary while the reverse `TryFrom<&str>`
// parses the `PascalCase` `wire_name` author-surface
// vocabulary, forcing the round-trip through an intermediate
// [`crate::CaixaKind::wire_name`] hop), [`WitShape`]'s
// [`WitShape::as_str`] emit and [`WitShape::from_wire`] parse
// resolve through the same four inline census-label
// byte-strings by construction (there is no wire/diagnostic
// axis split on this enum), so the owned-`String` forward axis
// and the reverse axis compose directly — matching the peer
// [`crate::supervisor::RestartStrategy`] /
// [`crate::supervisor::RestartPolicy`] /
// [`crate::CaixaDialeto`] / [`crate::dep::DepList`] /
// [`PlacementStrategy`] owned-`String` axis pairs.
for &variant in WitShape::ALL {
let owned_string: String = <String as From<WitShape>>::from(variant);
let owned_static: &'static str = <&'static str as From<WitShape>>::from(variant);
assert_eq!(
owned_string.as_str(),
owned_static,
"From<WitShape> for String and From<WitShape> for \
&'static str must resolve identically on \
WitShape::{variant:?} — divergence signals the \
owned-`String` and owned-`&'static str` forward-\
projection return-type-shape paths have drifted onto \
different emit-sets"
);
let via_to_string: String = variant.to_string();
assert_eq!(
owned_string, via_to_string,
"From<WitShape> for String must byte-equal \
WitShape::to_string on WitShape::{variant:?} — \
divergence signals the trait-idiomatic owned-`String` \
forward-projection axis and the ToString-through-\
Display axis have drifted onto different emit-sets"
);
}
let via_iter: Vec<String> = WitShape::ALL.iter().copied().map(String::from).collect();
let via_method: Vec<String> = WitShape::ALL
.iter()
.map(|s| s.as_str().to_owned())
.collect();
assert_eq!(
via_iter, via_method,
"`.iter().copied().map(String::from)` over WitShape::ALL \
must byte-equal `.iter().map(|s| s.as_str().to_owned())` \
on every arm — the owned-`String` `From<WitShape> for \
String` axis is what makes the `String::from` composition \
route through the substrate-primitive `WitShape::as_str` \
accessor rather than through a per-call-site `.to_owned()` \
/ `String::from(shape.as_str())` detour"
);
for &variant in WitShape::ALL {
let emitted: String = variant.into();
let re_parsed: Result<WitShape, ()> =
<WitShape as TryFrom<&str>>::try_from(emitted.as_str());
assert_eq!(
re_parsed,
Ok(variant),
"trait-idiomatic owned-`String` forward-projection + \
reverse-projection axis pair must round-trip \
WitShape::{variant:?} through `.into::<String>()` and \
back through `TryFrom<&str>` on the owned-`String`'s \
String::as_str borrow — a break signals the \
owned-`String` forward-emit and reverse-parse axes \
have drifted onto different vocabularies (unlike the \
peer CaixaKind axis pair, WitShape's forward emit and \
reverse parse share the same four inline census-label \
byte-strings by construction, so the round-trip \
composes directly)"
);
}
}
#[test]
fn wit_shape_from_into_borrowed_owned_string_routes_through_as_str_accessor() {
// Fail-before-pass-after byte-parity pin on the newly lifted
// `impl From<&WitShape> for String` — asserts the borrowed-input
// owned-`String`-returning standard-library trait impl and the
// substrate-primitive [`WitShape::as_str`] `pub const fn`
// accessor resolve to the same four-arm census-label emit-set
// across every arm the exhaustive [`WitShape::ALL`] slice
// enumerates. Rust's standard library does not carry a blanket
// `impl<T: AsRef<str>> From<&T> for String` (nor an
// `impl<T: fmt::Display> From<&T> for String`), so the
// borrowed-input owned-`String` forward-projection axis is a
// distinct trait-idiomatic surface that a
// `let key: String = (&shape).into();`-shaped call site reaches
// through this impl and no other — the paired sibling
// `From<WitShape> for String` impl forces every borrowed-input
// call site through an explicit `Copy` deref
// (`String::from(*shape)`) or an `.as_str().to_owned()` /
// `.to_string()` detour. Peer of the first-mover
// [`crate::supervisor::tests::restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
// (579385f), the second-peer
// [`crate::supervisor::tests::restart_policy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
// (8465740), the third-peer
// [`crate::dep::tests::dep_list_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
// (e0cb617), the fourth-peer
// [`crate::kind::tests::caixa_kind_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
// (e76436d), the fifth-peer
// [`crate::dialeto::tests::caixa_dialeto_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
// (d3c0d1d), and the sixth-peer
// [`tests::placement_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
// (d3dc000) — extends the trait-idiomatic borrowed-input owned-
// `String` forward-projection axis onto the seventh closed-set
// fieldless typed enum on the caixa surface (the second
// M3-mesh-primitive-defining `:contratos :wit` census-label
// axis).
for &variant in WitShape::ALL {
let via_trait: String = <String as From<&WitShape>>::from(&variant);
let via_method: &'static str = variant.as_str();
assert_eq!(
via_trait.as_str(),
via_method,
"From<&WitShape> for String impl must round-trip \
&WitShape::{variant:?} to the same four-arm census-\
label byte-string WitShape::as_str returns — \
divergence signals a silent detour off the substrate-\
primitive accessor"
);
let via_into: String = (&variant).into();
assert_eq!(
via_into.as_str(),
via_method,
"Into<String>::into on &WitShape::{variant:?} must \
byte-equal WitShape::as_str on the same input — the \
blanket-derived Into shape must resolve to the same \
as_str dispatch as the explicit From impl"
);
}
}
#[test]
fn wit_shape_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm() {
// Cross-axis partition pin: the newly lifted trait-idiomatic
// borrowed-input owned-`String` `From<&WitShape> for String`
// (this lift), the paired owned-input owned-`String`
// `From<WitShape> for String` (79a8723), the paired
// borrowed-input owned-`&'static str`
// `From<&WitShape> for &'static str` (3187bd0), and the paired
// owned-input owned-`&'static str` `From<WitShape> for &'static
// str` (56998ec) — every corner of the
// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
// projection family — must resolve identically on every arm,
// locking the four return-shape × input-shape paths together so
// any future detour trips at caixa-core test time. Also
// byte-parity witness against the sibling
// [`ToString::to_string`] surface routed through
// [`std::fmt::Display`] and a direct round-trip witness through
// the paired trait-idiomatic reverse [`TryFrom<&str>`] axis on
// the owned-`String`'s [`String::as_str`] borrow that closes
// the two-way `&Self → String → Self` round-trip on the trait-
// idiomatic borrowed-input owned-`String` forward + reverse
// axis pair. Peer of the first-mover
// [`crate::supervisor::tests::restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
// (579385f), the second-peer
// [`crate::supervisor::tests::restart_policy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
// (8465740), the third-peer
// [`crate::dep::tests::dep_list_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
// (e0cb617), the fourth-peer
// [`crate::kind::tests::caixa_kind_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
// (e76436d), the fifth-peer
// [`crate::dialeto::tests::caixa_dialeto_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
// (d3c0d1d), and the sixth-peer
// [`tests::placement_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
// (d3dc000) — closes the whole
// `{Self, &Self} × {&'static str, String}` 2×2 projection
// corner on the seventh substrate-wide closed-set fieldless
// typed enum peer (the second M3-mesh-primitive-defining
// `:contratos :wit` census-label axis, second M3 slot enum to
// reach the 2×2-completion corner).
//
// Unlike the peer [`crate::CaixaKind`] axis pair (whose forward
// `From` emit lands on the lowercase Portuguese `as_str`
// diagnostic vocabulary while the reverse `TryFrom<&str>`
// parses the `PascalCase` `wire_name` author-surface
// vocabulary, forcing the round-trip through an intermediate
// [`crate::CaixaKind::wire_name`] hop), [`WitShape`]'s
// [`WitShape::as_str`] emit and [`WitShape::from_wire`] parse
// resolve through the same four inline census-label byte-\
// strings by construction (there is no wire/diagnostic axis
// split on this M3 slot enum), so the borrowed-input owned-\
// `String` forward axis and the reverse axis compose directly
// — matching the peer [`crate::supervisor::RestartStrategy`] /
// [`crate::supervisor::RestartPolicy`] / [`crate::dep::DepList`]
// / [`crate::CaixaDialeto`] / [`PlacementStrategy`] borrowed-\
// input owned-`String` axis pairs.
for &variant in WitShape::ALL {
let borrowed_string: String = <String as From<&WitShape>>::from(&variant);
let owned_string: String = <String as From<WitShape>>::from(variant);
let borrowed_static: &'static str = <&'static str as From<&WitShape>>::from(&variant);
let owned_static: &'static str = <&'static str as From<WitShape>>::from(variant);
assert_eq!(
borrowed_string, owned_string,
"From<&WitShape> for String and From<WitShape> for \
String must resolve identically on WitShape::\
{variant:?} — divergence signals the borrowed-input \
and owned-input owned-`String` forward-projection \
input-shape paths have drifted onto different \
emit-sets"
);
assert_eq!(
borrowed_string.as_str(),
borrowed_static,
"From<&WitShape> for String and From<&WitShape> for \
&'static str must resolve identically on WitShape::\
{variant:?} — divergence signals the borrowed-input \
`&'static str` and owned-`String` return-shape paths \
have drifted onto different emit-sets"
);
assert_eq!(
borrowed_string.as_str(),
owned_static,
"From<&WitShape> for String and From<WitShape> for \
&'static str must resolve identically on WitShape::\
{variant:?} — divergence signals a break in the \
diagonal corner of the {{Self, &Self}} × {{&'static \
str, String}} 2×2 trait-idiomatic projection family"
);
let via_to_string: String = variant.to_string();
assert_eq!(
borrowed_string, via_to_string,
"From<&WitShape> for String must byte-equal WitShape::\
to_string on WitShape::{variant:?} — divergence \
signals the trait-idiomatic borrowed-input owned-\
`String` forward-projection axis and the ToString-\
through-Display axis have drifted onto different \
emit-sets"
);
}
let via_iter: Vec<String> = WitShape::ALL.iter().map(String::from).collect();
let via_method: Vec<String> = WitShape::ALL
.iter()
.map(|s| s.as_str().to_owned())
.collect();
assert_eq!(
via_iter, via_method,
"`.iter().map(String::from)` over WitShape::ALL — a call \
site whose iteration axis holds `&WitShape` by \
construction — must byte-equal `.iter().map(|s| \
s.as_str().to_owned())` on every arm — the borrowed-input \
owned-`String` `From<&WitShape> for String` axis is what \
makes the `String::from` composition route through the \
substrate-primitive `WitShape::as_str` accessor without a \
spurious `Copy` deref (which would only be reachable \
through the owned-input `From<WitShape> for String` axis \
by first calling `.copied()` on the iterator)"
);
for &variant in WitShape::ALL {
let emitted: String = (&variant).into();
let re_parsed: Result<WitShape, ()> =
<WitShape as TryFrom<&str>>::try_from(emitted.as_str());
assert_eq!(
re_parsed,
Ok(variant),
"trait-idiomatic borrowed-input owned-`String` \
forward-projection + reverse-projection axis pair \
must round-trip &WitShape::{variant:?} through \
`.into::<String>()` on the borrowed-input surface and \
back through `TryFrom<&str>` on the owned-`String`'s \
String::as_str borrow — a break signals the borrowed-\
input owned-`String` forward-emit and reverse-parse \
axes have drifted onto different vocabularies (unlike \
the peer CaixaKind axis pair, WitShape's forward emit \
and reverse parse share the same four inline census-\
label byte-strings by construction, so the round-trip \
composes directly)"
);
}
}
#[test]
fn wit_shape_from_into_static_cow_str_routes_through_as_str_accessor() {
// Fail-before-pass-after byte-parity pin on the newly lifted
// `impl From<WitShape> for std::borrow::Cow<'static, str>` —
// asserts the standard-library trait impl and the substrate-
// primitive [`super::WitShape::as_str`] `pub const fn`
// accessor resolve to the same four-arm emit-set across every
// arm the exhaustive [`super::WitShape::ALL`] slice
// enumerates. Rust's standard library does not carry a
// blanket `impl<T: AsRef<str>> From<T> for Cow<'static, str>`
// (nor an `impl<T: fmt::Display> From<T> for
// Cow<'static, str>`), so the `Cow<'static, str>` forward-
// projection axis is a distinct trait-idiomatic surface that
// a `let key: Cow<'static, str> = shape.into();`-shaped call
// site reaches through this impl and no other — the paired
// sibling `From<WitShape> for &'static str` and
// `From<WitShape> for String` impls force every
// `Cow<'static, str>`-parameterized call site through a
// `Cow::Borrowed(shape.as_str())` /
// `Cow::Owned(shape.to_string())` composition whose type
// bounds have no compile-time link back to the substrate
// primitive.
//
// Also asserts the projection lands on the zero-alloc
// [`std::borrow::Cow::Borrowed`] arm (not the
// [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
// [`super::WitShape::as_str`] accessor's `&'static str`
// return lifetime by construction (inline `"http"` /
// `"pubsub"` / `"store"` / `"capability"` byte-string
// literals) makes the borrowed arm the type-correct
// projection with no runtime allocation. Any future silent
// detour that routes the impl through the owned arm (an
// accidental `Cow::Owned(shape.to_string())` rewrite that
// would allocate on every call site where the `&'static str`
// return of [`super::WitShape::as_str`] makes the zero-alloc
// borrowed projection type-correct) trips at caixa-core test
// time under the [`std::borrow::Cow::Borrowed`] discriminator
// witness rather than at a downstream
// `Cow<'static, str>`-bound consumer's silent allocation.
//
// First-mover on the M3 mesh-shape tier of the substrate-wide
// trait-idiomatic [`std::borrow::Cow<'static, str>`] forward-
// projection campaign — extends the axis off the M2 OTP-shape
// tier (whose whole peer set — CaixaKind first-mover 99c1735
// + d45c409, RestartStrategy 7dd28b3 + 9b3e4b3, RestartPolicy
// 0612398 + ee577fd — closed on the {Self, &Self} corner)
// onto the first M3-mesh-primitive-defining slot enum. Every
// remaining M3 slot enum peer ([`PlacementStrategy`],
// [`RateLimitUnit`]) and the outside-M3 substrate-wide peers
// are future targets.
for &variant in WitShape::ALL {
let via_trait: std::borrow::Cow<'static, str> =
<std::borrow::Cow<'static, str> as From<WitShape>>::from(variant);
let via_method: &'static str = variant.as_str();
assert_eq!(
via_trait.as_ref(),
via_method,
"From<WitShape> for Cow<'static, str> impl must \
round-trip WitShape::{variant:?} to the same inline \
census-label byte-string WitShape::as_str returns — \
divergence signals a silent detour off the \
substrate-primitive accessor"
);
assert!(
matches!(via_trait, std::borrow::Cow::Borrowed(_)),
"From<WitShape> for Cow<'static, str> impl must land \
on the zero-alloc Cow::Borrowed arm on WitShape::\
{variant:?} — a Cow::Owned outcome signals the \
projection has silently allocated where the \
substrate-primitive WitShape::as_str `&'static str` \
return makes the borrowed arm the type-correct \
projection"
);
let via_into: std::borrow::Cow<'static, str> = variant.into();
assert_eq!(
via_into.as_ref(),
via_method,
"Into<Cow<'static, str>>::into on WitShape::\
{variant:?} must byte-equal WitShape::as_str on the \
same input — the blanket-derived Into shape must \
resolve to the same as_str dispatch as the explicit \
From impl"
);
assert!(
matches!(via_into, std::borrow::Cow::Borrowed(_)),
"Into<Cow<'static, str>>::into on WitShape::\
{variant:?} must land on the zero-alloc \
Cow::Borrowed arm — the blanket-derived Into shape \
must resolve to the same Cow::Borrowed dispatch as \
the explicit From impl"
);
}
}
#[test]
fn wit_shape_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
// Cross-axis partition pin: the newly lifted trait-idiomatic
// `From<WitShape> for std::borrow::Cow<'static, str>` (this
// lift), the paired owned-input `From<WitShape> for &'static
// str`, and the paired owned-input `From<WitShape> for
// String` forward projections must resolve identically on
// every arm, locking the three return-shape paths together by
// construction so any future detour trips at caixa-core test
// time. Also byte-parity witness against the sibling
// [`ToString::to_string`] surface routed through
// [`std::fmt::Display`] — every owned-heap-string path (the
// `Cow::Owned` promotion of this axis's `.into_owned()`,
// `From<WitShape> for String`, and `.to_string()`) resolves
// to the same four-arm inline census-label byte-string per
// arm.
//
// Then a `.iter().copied().map(std::borrow::Cow::from)` pipe
// witness over [`super::WitShape::ALL`] that materializes the
// four-arm accept-set through the [`std::borrow::Cow<'static,
// str>`] axis alone — the exact shape a future M4
// `mesh.pleme.io/v1alpha1/Aplicacao` CR admission-webhook
// rejection body's accepted-`:contratos :wit` census-label
// enumeration, a future substrate-wide per-arm diagnostic
// surface whose typing rules out the sibling [`AsRef<str>`]
// borrowed return, or a future per-arm WIT-shape emitter that
// binds through a [`Cow<'static, str>`] boundary reaches
// through — closing the composable-projection axis on the
// first M3 mesh-primitive-defining closed-set fieldless typed
// enum peer on the caixa surface. The pipe witness also pins
// the zero-alloc discipline: every element in the collected
// vector satisfies the [`std::borrow::Cow::Borrowed`] arm
// predicate, so a future accidental silent-allocation
// regression on the pipe's iteration axis is a caixa-core-
// test-time failure.
for &variant in WitShape::ALL {
let via_cow: std::borrow::Cow<'static, str> =
<std::borrow::Cow<'static, str> as From<WitShape>>::from(variant);
let via_static: &'static str = <&'static str as From<WitShape>>::from(variant);
let via_string: String = <String as From<WitShape>>::from(variant);
assert_eq!(
via_cow.as_ref(),
via_static,
"From<WitShape> for Cow<'static, str> and \
From<WitShape> for &'static str must resolve \
identically on WitShape::{variant:?} — divergence \
signals the Cow<'static, str> and &'static str \
return-shape paths have drifted onto different \
emit-sets"
);
assert_eq!(
via_cow.as_ref(),
via_string.as_str(),
"From<WitShape> for Cow<'static, str> and \
From<WitShape> for String must resolve identically \
on WitShape::{variant:?} — divergence signals the \
Cow<'static, str> and String return-shape paths \
have drifted onto different emit-sets"
);
let via_to_string: String = variant.to_string();
assert_eq!(
via_cow.as_ref(),
via_to_string.as_str(),
"From<WitShape> for Cow<'static, str> must byte-\
equal WitShape::to_string on WitShape::{variant:?} \
— divergence signals the trait-idiomatic \
Cow<'static, str> forward-projection axis and the \
ToString-through-Display axis have drifted onto \
different emit-sets"
);
}
let via_iter: Vec<std::borrow::Cow<'static, str>> = WitShape::ALL
.iter()
.copied()
.map(std::borrow::Cow::from)
.collect();
let via_method: Vec<std::borrow::Cow<'static, str>> = WitShape::ALL
.iter()
.map(|s| std::borrow::Cow::Borrowed(s.as_str()))
.collect();
assert_eq!(
via_iter, via_method,
"`.iter().copied().map(Cow::from)` over WitShape::ALL \
must byte-equal `.iter().map(|s| \
Cow::Borrowed(s.as_str()))` on every arm — the trait-\
idiomatic `From<WitShape> for Cow<'static, str>` axis \
is what makes the `Cow::from` composition route through \
the substrate-primitive `WitShape::as_str` accessor \
with the zero-alloc Cow::Borrowed arm by construction, \
rather than a per-call-site \
`Cow::Owned(shape.to_string())` allocation"
);
for cow in &via_iter {
assert!(
matches!(cow, std::borrow::Cow::Borrowed(_)),
"every element of the .iter().copied().map(Cow::from) \
pipe over WitShape::ALL must land on the zero-alloc \
Cow::Borrowed arm — a Cow::Owned outcome on any arm \
signals the pipe's iteration axis has silently \
allocated where the substrate-primitive \
WitShape::as_str `&'static str` return makes the \
borrowed arm the type-correct projection"
);
}
}
#[test]
fn wit_shape_from_borrowed_into_static_cow_str_routes_through_as_str_accessor() {
// Fail-before-pass-after byte-parity pin on the newly lifted
// `impl From<&WitShape> for std::borrow::Cow<'static, str>` —
// asserts the borrowed-input standard-library trait impl and
// the substrate-primitive [`super::WitShape::as_str`]
// `pub const fn` accessor resolve to the same four-arm emit-
// set across every arm the exhaustive
// [`super::WitShape::ALL`] slice enumerates. Rust's standard
// library does not carry a blanket
// `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor a
// `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
// so the borrowed-input `Cow<'static, str>` forward-
// projection axis is a distinct trait-idiomatic surface that
// a `let key: Cow<'static, str> = (&shape).into();`-shaped
// call site or a
// `WitShape::ALL.iter().map(Cow::from)`-shaped pipe reaches
// through this impl and no other — the paired owned-input
// `From<WitShape> for Cow<'static, str>` impl (8634dec)
// forces every borrowed-input call site through an explicit
// `Copy` deref (`Cow::from(*shape)`) or a
// `Cow::Borrowed(shape.as_str())` open-code whose type bounds
// have no compile-time link back to the substrate primitive.
//
// Also asserts the projection lands on the zero-alloc
// [`std::borrow::Cow::Borrowed`] arm (not the
// [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
// [`super::WitShape::as_str`] accessor's `&'static str`
// return lifetime by construction (inline `"http"` /
// `"pubsub"` / `"store"` / `"capability"` byte-string
// literals) makes the borrowed arm the type-correct
// projection with no runtime allocation on the borrowed-input
// surface just as on the paired owned-input surface.
//
// Closes the `{Self, &Self}` input-shape corner on the M3-
// mesh-shape `:contratos :wit` census-label
// [`Cow<'static, str>`] axis on the first M3-mesh-primitive-
// defining closed-set fieldless typed enum peer on the caixa
// surface, exactly as d45c409 closed it on the top-level
// [`super::CaixaKind`] one commit after the owning half
// (99c1735) landed and as 9b3e4b3 / ee577fd closed it on the
// M2 OTP-shape [`crate::supervisor::RestartStrategy`] /
// [`crate::supervisor::RestartPolicy`] sibling peers one
// commit after (7dd28b3 / 0612398) landed.
for &variant in WitShape::ALL {
let via_trait: std::borrow::Cow<'static, str> =
<std::borrow::Cow<'static, str> as From<&WitShape>>::from(&variant);
let via_method: &'static str = variant.as_str();
assert_eq!(
via_trait.as_ref(),
via_method,
"From<&WitShape> for Cow<'static, str> impl must \
round-trip &WitShape::{variant:?} to the same inline \
census-label byte-string WitShape::as_str returns — \
divergence signals a silent detour off the \
substrate-primitive accessor"
);
assert!(
matches!(via_trait, std::borrow::Cow::Borrowed(_)),
"From<&WitShape> for Cow<'static, str> impl must land \
on the zero-alloc Cow::Borrowed arm on \
&WitShape::{variant:?} — a Cow::Owned outcome \
signals the projection has silently allocated where \
the substrate-primitive WitShape::as_str `&'static \
str` return makes the borrowed arm the type-correct \
projection"
);
let via_into: std::borrow::Cow<'static, str> = (&variant).into();
assert_eq!(
via_into.as_ref(),
via_method,
"Into<Cow<'static, str>>::into on \
&WitShape::{variant:?} must byte-equal \
WitShape::as_str on the same input — the blanket-\
derived Into shape must resolve to the same as_str \
dispatch as the explicit From impl"
);
assert!(
matches!(via_into, std::borrow::Cow::Borrowed(_)),
"Into<Cow<'static, str>>::into on \
&WitShape::{variant:?} must land on the zero-alloc \
Cow::Borrowed arm — the blanket-derived Into shape \
must resolve to the same Cow::Borrowed dispatch as \
the explicit From impl"
);
}
}
#[test]
fn wit_shape_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
// Cross-axis partition pin: the newly lifted trait-idiomatic
// borrowed-input `From<&WitShape> for std::borrow::Cow<'static,
// str>` (this lift), the paired owned-input `From<WitShape>
// for std::borrow::Cow<'static, str>` (8634dec), the paired
// borrowed-input owned-`&'static str` `From<&WitShape> for
// &'static str`, and the paired borrowed-input owned-`String`
// `From<&WitShape> for String` must resolve identically on
// every arm, locking the four return-shape × input-shape
// paths together by construction so any future detour trips
// at caixa-core test time. Also byte-parity witness against
// the sibling [`ToString::to_string`] surface routed through
// [`std::fmt::Display`] — every owned-heap-string path (this
// axis's `.into_owned()` promotion, the paired
// [`From<&WitShape> for String`], and `.to_string()`)
// resolves to the same four-arm inline census-label byte-
// string per arm.
//
// Then a `.iter().map(std::borrow::Cow::from)` pipe witness
// over [`super::WitShape::ALL`] — whose iterator yields
// `&WitShape` by construction, so the borrowed-input
// [`Cow<'static, str>`] axis is what routes the pipe through
// the substrate-primitive [`super::WitShape::as_str`]
// accessor without a spurious [`Copy`] deref (which would
// only be reachable through the owned-input
// [`From<WitShape> for Cow<'static, str>`] axis by first
// calling `.copied()` on the iterator). The pipe witness
// also pins the zero-alloc discipline: every element in the
// collected vector satisfies the [`std::borrow::Cow::Borrowed`]
// arm predicate, so a future accidental silent-allocation
// regression on the pipe's iteration axis is a caixa-core-
// test-time failure. Peer of the sibling
// [`restart_policy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
// (ee577fd) on the M2 OTP-shape per-child-restart axis —
// extends the whole borrowed-input `Cow<'static, str>` +
// paired `{&'static str, String}` cross-axis-parity corner
// onto the first M3 mesh-primitive-defining closed-set
// fieldless typed enum peer on the caixa surface.
for &shape in WitShape::ALL {
let borrowed_cow: std::borrow::Cow<'static, str> =
<std::borrow::Cow<'static, str> as From<&WitShape>>::from(&shape);
let owned_cow: std::borrow::Cow<'static, str> =
<std::borrow::Cow<'static, str> as From<WitShape>>::from(shape);
let borrowed_static: &'static str = <&'static str as From<&WitShape>>::from(&shape);
let borrowed_string: String = <String as From<&WitShape>>::from(&shape);
assert_eq!(
borrowed_cow, owned_cow,
"From<&WitShape> for Cow<'static, str> and \
From<WitShape> for Cow<'static, str> must resolve \
identically on WitShape::{shape:?} — divergence \
signals the borrowed-input and owned-input \
Cow<'static, str> forward-projection input-shape \
paths have drifted onto different emit-sets"
);
assert_eq!(
borrowed_cow.as_ref(),
borrowed_static,
"From<&WitShape> for Cow<'static, str> and \
From<&WitShape> for &'static str must resolve \
identically on WitShape::{shape:?} — divergence \
signals the borrowed-input Cow<'static, str> and \
&'static str return-shape paths have drifted onto \
different emit-sets"
);
assert_eq!(
borrowed_cow.as_ref(),
borrowed_string.as_str(),
"From<&WitShape> for Cow<'static, str> and \
From<&WitShape> for String must resolve identically \
on WitShape::{shape:?} — divergence signals the \
borrowed-input Cow<'static, str> and owned-`String` \
return-shape paths have drifted onto different \
emit-sets"
);
let via_to_string: String = shape.to_string();
assert_eq!(
borrowed_cow.as_ref(),
via_to_string.as_str(),
"From<&WitShape> for Cow<'static, str> must byte-\
equal WitShape::to_string on WitShape::{shape:?} — \
divergence signals the trait-idiomatic borrowed-\
input Cow<'static, str> forward-projection axis and \
the ToString-through-Display axis have drifted onto \
different emit-sets"
);
}
let via_iter: Vec<std::borrow::Cow<'static, str>> =
WitShape::ALL.iter().map(std::borrow::Cow::from).collect();
let via_method: Vec<std::borrow::Cow<'static, str>> = WitShape::ALL
.iter()
.map(|s| std::borrow::Cow::Borrowed(s.as_str()))
.collect();
assert_eq!(
via_iter, via_method,
"`.iter().map(Cow::from)` over WitShape::ALL — a call \
site whose iteration axis holds `&WitShape` by \
construction — must byte-equal `.iter().map(|s| \
Cow::Borrowed(s.as_str()))` on every arm — the \
borrowed-input Cow<'static, str> `From<&WitShape> for \
Cow<'static, str>` axis is what makes the `Cow::from` \
composition route through the substrate-primitive \
`WitShape::as_str` accessor with the zero-alloc \
Cow::Borrowed arm by construction and without a \
spurious `Copy` deref (which would only be reachable \
through the owned-input `From<WitShape> for Cow<'static, \
str>` axis by first calling `.copied()` on the iterator)"
);
for cow in &via_iter {
assert!(
matches!(cow, std::borrow::Cow::Borrowed(_)),
"every element of the .iter().map(Cow::from) pipe \
over WitShape::ALL must land on the zero-alloc \
Cow::Borrowed arm — a Cow::Owned outcome on any arm \
signals the pipe's iteration axis has silently \
allocated where the substrate-primitive \
WitShape::as_str `&'static str` return makes the \
borrowed arm the type-correct projection"
);
}
}
#[test]
fn wit_shape_classify_matches_wit_contract_target_arm_on_valid_inputs() {
// Cross-surface equivalence pin: for every canonical
// truth-table row that also validates cleanly through
// [`WitContract::target`], the pre-projection [`WitShape`] arm
// matches the post-projection [`WitTarget`] arm — the pre- and
// post-validation classifications agree on the arm identity
// even though the payload-carrying view carries additional
// per-arm information. A future edit that reroutes
// `WitContract::target`'s HTTP/pubsub/store dispatch through a
// different predicate than the [`WitShape::classify`] the free
// predicates now route through would trip here at the offending
// row rather than at a downstream renderer.
//
// The Capability arm is excluded from the paired sweep: an
// arbitrary Capability-classified string need not pass
// [`crate::render::is_wit_world_ref`]'s value-shape gate, so
// `WitContract::target` would raise `ContratoWitInvalid`
// rather than return `WitTarget::Capability`; the arm-identity
// agreement lives in the payload-arm rows.
//
// Per-row shape: `(wit, endpoint, subject, slot)` — one row per
// payload arm with its shape's canonical payload field filled
// and the peer fields `None`. Named type-alias closes the
// `clippy::type_complexity` warning the raw tuple triggers.
type WitTargetArmRow = (
&'static str,
Option<&'static str>,
Option<&'static str>,
Option<&'static str>,
);
let cases: [WitTargetArmRow; 6] = [
("wasi:http/proxy", Some("/x"), None, None),
("http:incoming", Some("/x"), None, None),
("nats:events", None, Some("subject.x"), None),
("kafka:topic", None, Some("subject.x"), None),
("wasi:keyvalue/store", None, None, Some("bucket/x")),
("kv:cache", None, None, Some("bucket/x")),
];
for (wit, endpoint, subject, slot) in cases {
let c = WitContract {
de: "cart".into(),
para: "catalog".into(),
wit: wit.to_string(),
endpoint: endpoint.map(str::to_string),
subject: subject.map(str::to_string),
slot: slot.map(str::to_string),
};
let target = c.target().unwrap_or_else(|e| {
panic!("expected target() to validate for wit={wit:?}, got: {e}")
});
let shape = WitShape::classify(wit);
// Match arm-for-arm — the raw &str classifier and the
// validated payload view must agree on which arm carries
// the edge.
let agree = matches!(
(shape, target),
(WitShape::Http, WitTarget::Http { .. })
| (WitShape::PubSub, WitTarget::PubSub { .. })
| (WitShape::Store, WitTarget::Store { .. })
| (WitShape::Capability, WitTarget::Capability)
);
assert!(
agree,
"WitShape::classify({wit:?}) and WitContract::target arm-identity disagree",
);
}
}
#[test]
fn wit_shape_matches_composes_through_bytes_starts_with_across_boundary_lengths() {
// Composition-witness pin: [`wit_shape_matches`] agrees with
// the reference `prefixes.iter().any(|p| wit.starts_with(p))`
// dispatch (the prior non-`const` implementation) across
// boundary lengths — empty `wit`, empty prefix, one-byte
// slack, prefix longer than `wit`, one-byte trailing slack.
// The rewrite to a byte-level manual starts_with loop (the
// enabler for the `pub const fn` posture) must not change any
// truth-table entry on the canonical accept-set — this pin
// sweeps a targeted boundary corpus and asserts byte-for-byte
// agreement, locking the const-fn rewrite's semantics against
// the prior iterator body by construction.
let prefixes = &["wasi:http/", "http:"][..];
let cases: [(&str, bool); 12] = [
("wasi:http/proxy", true),
("wasi:http/", true), // exact-length match on prefix
("wasi:http", false), // one byte short
("http:", true),
("http:incoming", true),
("http", false), // one byte short
("", false),
("wasi:https/proxy", false),
("nats:events", false),
("HTTPS:", false), // uppercase — no case-fold in classifier
("wasi:HTTP/proxy", false),
("wasi:http", false),
];
for (wit, expected) in cases {
assert_eq!(
wit_shape_matches(wit, prefixes),
expected,
"wit_shape_matches disagrees with reference at wit={wit:?}",
);
// Byte-equal to the iterator body it replaced.
let via_iter = prefixes.iter().any(|p| wit.starts_with(p));
assert_eq!(
wit_shape_matches(wit, prefixes),
via_iter,
"wit_shape_matches must byte-equal iter().any(starts_with) at wit={wit:?}",
);
}
// Empty prefix set → always false regardless of `wit`.
let empty: &[&str] = &[];
assert!(!wit_shape_matches("", empty));
assert!(!wit_shape_matches("wasi:http/proxy", empty));
// Empty prefix inside a non-empty set → always true (every
// string starts with the empty string, matching the
// iterator body's semantics on `str::starts_with("")`).
let contains_empty: &[&str] = &["nats:", ""];
assert!(wit_shape_matches("", contains_empty));
assert!(wit_shape_matches("wasi:http/proxy", contains_empty));
}
#[test]
fn wit_contract_is_capability_partitions_the_wit_shape_space() {
// 4-way partition-witness pin: for every canonical prefix in
// the payload-arm accept-sets, exactly one of the four
// [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
// [`WitContract::is_store`] / [`WitContract::is_capability`]
// predicates returns `true` and the other three return `false`
// — the four-arm partition witness that locks the substrate's
// WIT-shape-space closure on the pre-projection axis load-
// bearing. A future arm addition (a hypothetical fourth
// payload-shape prefix set, a `wasi:sockets/*` transport-layer
// shape) that landed on one of the payload-arm predicates
// without shrinking [`WitContract::is_capability`]'s accept-set
// would surface here as two arms returning `true` simultaneously
// — a partition-witness break the pin catches at caixa-core
// build time rather than a silent per-consumer misclassification
// at renderer emit time. Peer of the sibling `WitTarget`-side
// [`tests::wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set`]
// partition-witness pin on the post-projection payload-scalar
// arm-set — extends the discipline onto the pre-projection
// 4-arm shape-space.
for shape_set in [
WIT_HTTP_SHAPE_PREFIXES,
WIT_PUBSUB_SHAPE_PREFIXES,
WIT_STORE_SHAPE_PREFIXES,
] {
for prefix in shape_set {
let c = WitContract {
de: "cart".into(),
para: "catalog".into(),
wit: format!("{prefix}x"),
endpoint: None,
subject: None,
slot: None,
};
let hits = [c.is_http(), c.is_pubsub(), c.is_store(), c.is_capability()]
.iter()
.filter(|&&b| b)
.count();
assert_eq!(
hits,
1,
"WitContract WIT-shape 4-way predicate partition must \
admit exactly one arm per canonical prefix; got {hits} \
hits at wit={:?} (is_http={}, is_pubsub={}, is_store={}, \
is_capability={})",
c.wit,
c.is_http(),
c.is_pubsub(),
c.is_store(),
c.is_capability(),
);
}
}
// Capability-arm sweep: two representative capability shapes
// (a bare WIT world outside the three payload-arm prefix sets,
// and the deliberately-shaped empty string that
// [`crate::render::is_wit_world_ref`] rejects at
// [`WitContract::target`] time but which the pure classifier
// still admits — see the method docstring's "purely syntactic
// classification" note). Both must land on the fourth arm
// exclusively, so the partition witness holds across the full
// 4-arm closure.
for wit in ["custom:capability-only", ""] {
let c = WitContract {
de: "cart".into(),
para: "catalog".into(),
wit: wit.into(),
endpoint: None,
subject: None,
slot: None,
};
let hits = [c.is_http(), c.is_pubsub(), c.is_store(), c.is_capability()]
.iter()
.filter(|&&b| b)
.count();
assert_eq!(
hits, 1,
"WitContract WIT-shape 4-way predicate partition must \
admit exactly one arm on Capability-shaped wit={wit:?}"
);
assert!(
c.is_capability(),
"wit={wit:?} must project onto the Capability arm"
);
}
}
#[test]
fn wit_contract_is_capability_composes_through_shape_predicate_negation() {
// Composition-witness pin: [`WitContract::is_capability`] is the
// exact-inverse disjunction of the sibling payload-arm predicate
// trio [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
// [`WitContract::is_store`]. A future reimplementation that
// grew its own prefix-set scan (e.g. inlining a fourth
// [`WIT_CAPABILITY_SHAPE_PREFIXES`] const the substrate does not
// own today) rather than delegating to the sibling trio would
// drift loudly here — the composition contract binds the
// fourth-arm predicate to the exact-inverse of the three
// payload-arm predicates, so any rebrand of any prefix-set const
// flows through this method by construction without a
// coordinated per-consumer rewrite. Sweeps the union of the
// three payload-arm prefix sets plus two Capability-shaped
// shapes (a bare non-prefix-matching WIT world, the deliberately-
// empty string the pure classifier still admits per the method
// docstring's "purely syntactic classification" note).
let mut cases: Vec<String> = Vec::new();
for shape_set in [
WIT_HTTP_SHAPE_PREFIXES,
WIT_PUBSUB_SHAPE_PREFIXES,
WIT_STORE_SHAPE_PREFIXES,
] {
for prefix in shape_set {
cases.push(format!("{prefix}x"));
}
}
cases.push("custom:capability-only".to_string());
cases.push(String::new());
for wit in cases {
let c = WitContract {
de: "cart".into(),
para: "catalog".into(),
wit: wit.clone(),
endpoint: None,
subject: None,
slot: None,
};
assert_eq!(
c.is_capability(),
!c.is_http() && !c.is_pubsub() && !c.is_store(),
"WitContract::is_capability must equal \
!is_http() && !is_pubsub() && !is_store() at wit={wit:?}"
);
}
}
#[test]
fn wit_contract_is_capability_agrees_with_projected_wit_target_capability_variant() {
// Cross-projection-witness pin: whenever [`WitContract::target`]
// succeeds, the pre-projection [`WitContract::is_capability`]
// classification agrees with the post-projection
// [`WitTarget::is_capability`] `gen_platform::IsVariant`-derived
// predicate — the 4-arm typed partition on the substrate's
// typed-view surface (7f6aa98 IsVariant lift) and the peer 4-arm
// partition on the pre-projection axis line up by construction.
// A future divergence between the two axes (a peer
// [`WitTarget`] variant addition that landed on the typed-view
// surface without a peer prefix-set + [`WitContract`] predicate
// extension, or vice versa) would surface here at caixa-core
// build time rather than a silent per-consumer split at renderer
// emit time. Peer of the sibling pre-/post-projection
// agreement pins the payload-carrier trio
// ([`WitContract::endpoint`] / [`WitContract::subject`] /
// [`WitContract::slot`] on pre-projection; [`WitTarget::http_endpoint`]
// / [`WitTarget::pubsub_subject`] / [`WitTarget::store_slot`] on
// post-projection — b11bb49 trio lift) already carry across the
// three payload arms — this pin closes the pair on the fourth
// payload-less arm.
let http = WitContract {
de: "cart".into(),
para: "catalog".into(),
wit: "wasi:http/proxy".into(),
endpoint: Some("/x".into()),
subject: None,
slot: None,
};
assert!(!http.is_capability());
assert!(!http.target().unwrap().is_capability());
let nats = WitContract {
de: "cart".into(),
para: "catalog".into(),
wit: "nats:pub-sub".into(),
endpoint: None,
subject: Some("events.x".into()),
slot: None,
};
assert!(!nats.is_capability());
assert!(!nats.target().unwrap().is_capability());
let kv = WitContract {
de: "cart".into(),
para: "catalog".into(),
wit: "wasi:keyvalue/store".into(),
endpoint: None,
subject: None,
slot: Some("checkout/$orderId".into()),
};
assert!(!kv.is_capability());
assert!(!kv.target().unwrap().is_capability());
let cap = WitContract {
de: "cart".into(),
para: "catalog".into(),
wit: "custom:capability-only".into(),
endpoint: None,
subject: None,
slot: None,
};
assert!(cap.is_capability());
assert!(cap.target().unwrap().is_capability());
}
#[test]
fn wit_contract_pre_projection_accessor_family_is_const_fn() {
// Fail-before-pass-after pin on the [`WitContract`] pre-
// projection accessor family's `const`-eval-surface posture.
// Each of the three per-`:contratos` byte-string scalar
// accessors ([`WitContract::source`] / [`WitContract::destination`]
// / [`WitContract::world_ref`], each projecting through
// `String::as_str` — const-stable since Rust 1.87, well within
// the workspace MSRV) and each of the four peer WIT-shape
// predicates ([`WitContract::is_http`] /
// [`WitContract::is_pubsub`] / [`WitContract::is_store`] /
// [`WitContract::is_capability`], each composing
// `wit_shape_is_<arm>(self.world_ref())` on the `pub const fn`
// free-function classifier family the sibling
// [`wit_shape_classifier_family_is_const_fn`] pin already
// anchors on the raw `&str → bool` axis) must be `pub const fn`
// — any future accidental downgrade to non-`const` fails the
// `const fn` wrappers below at caixa-core build time with E0015
// (`cannot call non-const function`), strictly stronger than a
// runtime `assert!` and strictly stronger than a
// module-scope `const _: () = assert!(…)` pin (which cannot be
// formed on a `&WitContract` fixture because the type's
// `String` / `Option<String>` carriers rule out `const`-context
// construction; the `const fn` wrapper is the load-bearing
// shape that side-steps the destructor-in-const restriction on
// the value axis while still pinning the `const`-fn posture on
// the callee).
//
// Peer of the sibling free-function classifier pin
// [`wit_shape_classifier_family_is_const_fn`] (d46420c) on the
// raw `&str → bool` axis — this pin extends the same
// `const`-eval-surface discipline onto the peer method surface
// that composes through those free-function classifiers, and
// simultaneously onto the underlying per-`:contratos`
// byte-string scalar-accessor trio each predicate reads
// through. Sibling of the peer M3
// [`rate_limit_unit_from_window_accessor_is_const_fn`] /
// [`rate_limit_canonical_unit_accessor_is_const_fn`] (974bbd8),
// M2
// [`child_spec_restart_accessor_is_const_fn`] /
// [`supervisor_spec_estrategia_accessor_is_const_fn`] (152c868),
// and M3
// [`placement_estrategia_accessor_is_const_fn`] /
// [`entrada_port_accessor_is_const_fn`] (bafa004) pins on the
// sibling `const`-eval-surface-pass axes.
const fn source_via_const_fn(c: &WitContract) -> &str {
c.source()
}
const fn destination_via_const_fn(c: &WitContract) -> &str {
c.destination()
}
const fn world_ref_via_const_fn(c: &WitContract) -> &str {
c.world_ref()
}
const fn is_http_via_const_fn(c: &WitContract) -> bool {
c.is_http()
}
const fn is_pubsub_via_const_fn(c: &WitContract) -> bool {
c.is_pubsub()
}
const fn is_store_via_const_fn(c: &WitContract) -> bool {
c.is_store()
}
const fn is_capability_via_const_fn(c: &WitContract) -> bool {
c.is_capability()
}
// Sweep one canonical accept-set sample per WIT-shape arm plus
// a payload-less capability sample, asserting the wrapper and
// direct dispatches agree byte-for-byte across the closed
// 4-arm partition on both the scalar-accessor trio and the
// WIT-shape-predicate family.
for (wit, is_http, is_pubsub, is_store, is_capability) in [
("wasi:http/proxy", true, false, false, false),
("http:incoming", true, false, false, false),
("nats:events", false, true, false, false),
("kafka:topic", false, true, false, false),
("wasi:keyvalue/store", false, false, true, false),
("kv:cache", false, false, true, false),
("custom:capability-only", false, false, false, true),
("", false, false, false, true),
] {
let c = WitContract {
de: "cart".into(),
para: "catalog".into(),
wit: wit.into(),
endpoint: None,
subject: None,
slot: None,
};
assert_eq!(source_via_const_fn(&c), c.source());
assert_eq!(destination_via_const_fn(&c), c.destination());
assert_eq!(world_ref_via_const_fn(&c), c.world_ref());
assert_eq!(is_http_via_const_fn(&c), c.is_http());
assert_eq!(is_pubsub_via_const_fn(&c), c.is_pubsub());
assert_eq!(is_store_via_const_fn(&c), c.is_store());
assert_eq!(is_capability_via_const_fn(&c), c.is_capability());
assert_eq!(c.source(), "cart");
assert_eq!(c.destination(), "catalog");
assert_eq!(c.world_ref(), wit);
assert_eq!(c.is_http(), is_http);
assert_eq!(c.is_pubsub(), is_pubsub);
assert_eq!(c.is_store(), is_store);
assert_eq!(c.is_capability(), is_capability);
}
}
#[test]
fn wit_contract_identity_projection_accessor_is_const_fn() {
// Fail-before-pass-after pin on the [`WitContract::identity`]
// six-arm composite-projection accessor's `const`-eval-surface
// posture. The accessor projects the typed edge's six identity
// arms (`:de` / `:para` / `:wit` / `:endpoint` / `:subject` /
// `:slot`) as a borrowed [`ContratoIdentity<'_>`] six-tuple —
// every callee is itself `pub const fn` ([`WitContract::source`]
// / [`WitContract::destination`] / [`WitContract::world_ref`]
// through `String::as_str`, const-stable since Rust 1.87;
// [`WitContract::endpoint`] / [`WitContract::subject`] /
// [`WitContract::slot`] through the sibling `match &self
// .<field> { Some(s) => Some(s.as_str()), None => None }` shape
// 0650f64 closed the const-eval surface on) and the tuple
// constructor from borrowed-reference / `Option`-of-borrowed-
// reference arms is trivially const. Any future accidental
// downgrade fails the `identity_via_const_fn` wrapper at
// caixa-core build time with E0015 (`cannot call non-const
// method`), strictly stronger than a runtime `assert!` and
// strictly stronger than a module-scope `const _: () =
// assert!(…)` pin (which cannot be formed on a `&WitContract`
// fixture because the type's `String` / `Option<String>`
// carriers rule out `const`-context value construction; the
// `const fn` wrapper is the load-bearing shape that side-steps
// the destructor-in-const restriction on the value axis while
// still pinning the `const`-fn posture on the callee — mirror
// of the sibling
// [`wit_contract_pre_projection_accessor_family_is_const_fn`]
// pin's discipline verbatim on the peer scalar-accessor
// surface).
//
// Peer of the sibling
// [`wit_contract_pre_projection_accessor_family_is_const_fn`]
// (279823b) pin on the six per-`:contratos` scalar-accessor
// callees this composite-projection reads through — where that
// pin anchors the const-eval surface at the six individual
// scalar-accessor arms, this pin extends the same posture onto
// the composite six-tuple projection every consumer that dedups
// typed edges on the [`ContratoIdentity`] axis keys off (the
// [`AplicacaoSpec::validate`]-side duplicate-`:contratos`
// scanner + its BTreeMap dedup key; a future per-Aplicacao CR
// materializer's per-edge identity-based admission webhook; a
// future L7 policy-emitter that shards CNPs by identity-tuple
// rather than by name). Same fail-before-pass-after wrapper
// discipline as the peer M2 / M3 accessor-family pins on the
// sibling `const`-eval-surface passes.
const fn identity_via_const_fn(c: &WitContract) -> ContratoIdentity<'_> {
c.identity()
}
// Sweep one canonical WIT-shape sample per payload-carrier arm
// plus a payload-less capability sample so the pin exercises
// both `Some(_)`-carrying and `None`-carrying arms on all three
// `Option<String>` payload-carrier axes (`:endpoint` / `:subject`
// / `:slot`) — every wrapper dispatch must agree byte-for-byte
// with the direct method call on every arm of the closed WIT-
// shape partition.
for (wit, endpoint, subject, slot) in [
("wasi:http/proxy", Some("/checkout"), None, None),
("http:incoming", Some("/api"), None, None),
("nats:events", None, Some("orders.placed"), None),
("kafka:topic", None, Some("orders.stream"), None),
("wasi:keyvalue/store", None, None, Some("carts/{id}")),
("kv:cache", None, None, Some("session/{token}")),
("custom:capability-only", None, None, None),
] {
let c = WitContract {
de: "cart".into(),
para: "catalog".into(),
wit: wit.into(),
endpoint: endpoint.map(str::to_string),
subject: subject.map(str::to_string),
slot: slot.map(str::to_string),
};
assert_eq!(identity_via_const_fn(&c), c.identity());
assert_eq!(
c.identity(),
("cart", "catalog", wit, endpoint, subject, slot,),
);
}
}
#[test]
fn m3_membros_and_entrada_string_scalar_accessor_family_is_const_fn() {
// Fail-before-pass-after pin on the four M3 mesh-slot
// `String → &str` scalar accessors ([`Membro::nome`] /
// [`Membro::versao_requirement`] on the per-`:membros` axis,
// [`Entrada::hostname`] / [`Entrada::destination`] on the
// per-`:entrada` axis) — each projects the typed slot's
// [`String`] storage through the `pub const fn`
// [`String::as_str`] (const-stable since Rust 1.87, well
// within the workspace MSRV) and any future accidental
// downgrade to non-`const` fails the corresponding
// `<name>_via_const_fn` wrapper at caixa-core build time with
// E0015 (`cannot call non-const method`), strictly stronger
// than a runtime `assert!` and strictly stronger than a
// module-scope `const _: () = assert!(…)` pin (which cannot
// be formed on `&Membro` / `&Entrada` fixtures because the
// types' `String` carriers rule out `const`-context value
// construction; the `const fn` wrapper is the load-bearing
// shape that side-steps the destructor-in-const restriction
// on the value axis while still pinning the `const`-fn
// posture on the callee — mirror of the sibling
// [`wit_contract_pre_projection_accessor_family_is_const_fn`]
// (279823b) pin on the per-`:contratos` axis). Peer of the
// sibling per-M2/M3/universal-axis `String → &str` accessor
// family pins on the sibling `const`-eval-surface passes
// ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
// top-level manifest, [`crate::CaixaVersion::as_str`] at the
// typed-newtype wrapper,
// [`crate::supervisor::ChildSpec::nome`] /
// [`crate::supervisor::ChildSpec::versao_requirement`] at the
// M2 supervisor-tree axis,
// [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
// M2 upgrade axis, [`crate::dep::Dep::nome`] /
// [`crate::dep::Dep::versao_requirement`] at the dep-graph
// axis, and the sibling per-`:contratos`
// [`WitContract::source`] / [`WitContract::destination`] /
// [`WitContract::world_ref`] trio at 279823b).
const fn membro_nome_via_const_fn(m: &Membro) -> &str {
m.nome()
}
const fn membro_versao_via_const_fn(m: &Membro) -> &str {
m.versao_requirement()
}
const fn entrada_hostname_via_const_fn(e: &Entrada) -> &str {
e.hostname()
}
const fn entrada_destination_via_const_fn(e: &Entrada) -> &str {
e.destination()
}
for (caixa, versao) in [
("cart", "^0.1"),
("catalog-v2", "~0.2.3"),
("checkout", "*"),
] {
let m = Membro {
caixa: caixa.into(),
versao: versao.into(),
};
assert_eq!(membro_nome_via_const_fn(&m), m.nome());
assert_eq!(membro_versao_via_const_fn(&m), m.versao_requirement());
assert_eq!(m.nome(), caixa);
assert_eq!(m.versao_requirement(), versao);
}
for (host, para) in [
("cart.example.com", "cart"),
("api.checkout.io", "checkout"),
] {
let e = Entrada {
host: host.into(),
para: para.into(),
paths: vec![],
port: DEFAULT_SERVICO_PORT,
};
assert_eq!(entrada_hostname_via_const_fn(&e), e.hostname());
assert_eq!(entrada_destination_via_const_fn(&e), e.destination());
assert_eq!(e.hostname(), host);
assert_eq!(e.destination(), para);
}
}
#[test]
fn m3_option_string_scalar_accessor_family_is_const_fn() {
// Fail-before-pass-after pin on the five M3 mesh-slot
// `Option<String> → Option<&str>` scalar accessors
// ([`WitContract::endpoint`] / [`WitContract::subject`] /
// [`WitContract::slot`] on the per-`:contratos` HTTP /
// pub-sub / key-value payload-carrier trio,
// [`Placement::shard_key`] / [`Placement::affinity`] on the
// per-`:placement` Akka-sharding-key + Adaptive-compression-
// hint pair). Each accessor destructures the typed slot's
// `Option<String>` storage through the `match &self.<field> {
// Some(s) => Some(s.as_str()), None => None }` shape —
// routing through [`String::as_str`] (const-stable since Rust
// 1.87, well within the workspace MSRV) rather than the
// non-const [`Option::as_deref`] the pre-lift bodies carried
// — and any future accidental downgrade to non-`const` fails
// the corresponding `<name>_via_const_fn` wrapper at
// caixa-core build time with E0015 (`cannot call non-const
// method`), strictly stronger than a runtime `assert!` and
// strictly stronger than a module-scope `const _: () =
// assert!(…)` pin (which cannot be formed on `&WitContract`
// / `&Placement` fixtures because the types' `String` /
// `Option<String>` carriers rule out `const`-context value
// construction; the `const fn` wrapper is the load-bearing
// shape that side-steps the destructor-in-const restriction
// on the value axis while still pinning the `const`-fn
// posture on the callee — mirror of the sibling
// [`wit_contract_pre_projection_accessor_family_is_const_fn`]
// (279823b) and
// [`m3_membros_and_entrada_string_scalar_accessor_family_is_const_fn`]
// (29c5d7e) pins on the peer `String → &str` axes at the same
// structs).
//
// Peer of the sibling per-`Caixa` `Option<String> →
// Option<&str>` accessor family pin
// [`crate::manifest::tests::caixa_option_string_scalar_accessor_family_is_const_fn`]
// on the top-level manifest's optional universal-axis surface
// (`:licenca` / `:repositorio` / `:descricao` / `:edicao` /
// `:restart-window`).
const fn wit_endpoint_via_const_fn(w: &WitContract) -> Option<&str> {
w.endpoint()
}
const fn wit_subject_via_const_fn(w: &WitContract) -> Option<&str> {
w.subject()
}
const fn wit_slot_via_const_fn(w: &WitContract) -> Option<&str> {
w.slot()
}
const fn placement_shard_key_via_const_fn(p: &Placement) -> Option<&str> {
p.shard_key()
}
const fn placement_affinity_via_const_fn(p: &Placement) -> Option<&str> {
p.affinity()
}
// Sweep every closed shape-arm partition on the
// per-`:contratos` payload-carrier trio: HTTP (`:endpoint`
// Some, sibling pair None), pub-sub (`:subject` Some, sibling
// pair None), key-value (`:slot` Some, sibling pair None),
// and Capability (all three None) so each accessor's
// Some/None arm carries a pin through the const dispatch.
for (wit, endpoint, subject, slot) in [
("wasi:http/proxy", Some("/api"), None, None),
("nats:pub-sub", None, Some("orders.paid"), None),
("wasi:keyvalue/store", None, None, Some("checkout/$orderId")),
("custom:capability-only", None, None, None),
] {
let c = WitContract {
de: "cart".into(),
para: "catalog".into(),
wit: wit.into(),
endpoint: endpoint.map(str::to_string),
subject: subject.map(str::to_string),
slot: slot.map(str::to_string),
};
assert_eq!(wit_endpoint_via_const_fn(&c), c.endpoint());
assert_eq!(wit_subject_via_const_fn(&c), c.subject());
assert_eq!(wit_slot_via_const_fn(&c), c.slot());
assert_eq!(c.endpoint(), endpoint);
assert_eq!(c.subject(), subject);
assert_eq!(c.slot(), slot);
}
// Sweep both `Some`/`None` arms on each per-`:placement`
// optional-scalar so the shard-key + affinity pair carries a
// const-dispatch pin on both arms.
for (shard_key, affinity) in [
(Some("tenantId"), Some("data-locality")),
(Some("$tenantId"), None),
(None, Some("low-latency")),
(None, None),
] {
let p = Placement {
estrategia: PlacementStrategy::default(),
clusters: vec![],
affinity: affinity.map(str::to_string),
shard_key: shard_key.map(str::to_string),
};
assert_eq!(placement_shard_key_via_const_fn(&p), p.shard_key());
assert_eq!(placement_affinity_via_const_fn(&p), p.affinity());
assert_eq!(p.shard_key(), shard_key);
assert_eq!(p.affinity(), affinity);
}
}
#[test]
fn m3_placement_entrada_slice_return_accessor_pair_is_const_fn() {
// Fail-before-pass-after pin on the two M3-mesh-slot inner-
// composite `Vec → &[String]` slice-return accessors on
// [`Placement::clusters`] and [`Entrada::paths`]. Each
// destructures the typed slot's `Vec<String>` storage through
// the `pub const fn` [`Vec::as_slice`] (const-stable since Rust
// 1.66, well within the workspace MSRV) — any future accidental
// downgrade to non-`const` fails the corresponding
// `<name>_via_const_fn` wrapper at caixa-core build time with
// E0015 (`cannot call non-const method`), strictly stronger
// than a runtime `assert!`. Sibling of the peer
// [`m3_aplicacao_spec_reference_return_accessor_family_is_const_fn`]
// pin on the outer-`AplicacaoSpec` reference-return family
// (`:membros` / `:contratos` slice-return + `:politicas` /
// `:placement` / `:entrada` composite-reference), and of the
// peer M2 slice-return axis pins
// [`crate::supervisor::tests::supervisor_children_slice_return_accessor_is_const_fn`]
// (on `SupervisorSpec::children`) and
// [`crate::upgrade::tests::upgrade_from_entry_instructions_slice_return_accessor_is_const_fn`]
// (on `UpgradeFromEntry::instructions`). Together the four
// pins close the last unlifted reference-return accessor
// family across the substrate primitive.
const fn placement_clusters_via_const_fn(p: &Placement) -> &[String] {
p.clusters()
}
const fn entrada_paths_via_const_fn(e: &Entrada) -> &[String] {
e.paths()
}
// Sweep both the empty-Vec (no author-declared entries) and
// the populated-Vec arms on every slice-return accessor so
// each carries a const-dispatch pin on both arms.
let p_empty = Placement {
estrategia: PlacementStrategy::default(),
clusters: vec![],
affinity: None,
shard_key: None,
};
let p_full = Placement {
estrategia: PlacementStrategy::default(),
clusters: vec!["prod-a".into(), "prod-b".into()],
affinity: None,
shard_key: None,
};
assert_eq!(
placement_clusters_via_const_fn(&p_empty),
p_empty.clusters()
);
assert_eq!(placement_clusters_via_const_fn(&p_full), p_full.clusters());
assert!(p_empty.clusters().is_empty());
assert_eq!(p_full.clusters(), &["prod-a", "prod-b"]);
let e_empty = Entrada {
host: "web.example.com".into(),
para: "web".into(),
paths: vec![],
port: DEFAULT_SERVICO_PORT,
};
let e_full = Entrada {
host: "web.example.com".into(),
para: "web".into(),
paths: vec!["/api".into(), "/health".into()],
port: DEFAULT_SERVICO_PORT,
};
assert_eq!(entrada_paths_via_const_fn(&e_empty), e_empty.paths());
assert_eq!(entrada_paths_via_const_fn(&e_full), e_full.paths());
assert!(e_empty.paths().is_empty());
assert_eq!(e_full.paths(), &["/api", "/health"]);
}
#[test]
fn m3_aplicacao_spec_reference_return_accessor_family_is_const_fn() {
// Fail-before-pass-after pin on the five outer-`AplicacaoSpec`
// reference-return accessors — the two `Vec → &[T]` slice-
// return accessors on [`AplicacaoSpec::membros`] and
// [`AplicacaoSpec::contratos`] (each routes through the
// `pub const fn` [`Vec::as_slice`], const-stable since Rust
// 1.66), the two `&Composite` composite-reference accessors
// on [`AplicacaoSpec::politicas`] and
// [`AplicacaoSpec::placement`] (each routes through a raw
// `&self.<field>` borrow, trivially const), and the one
// `Option<&Composite>` optional-composite-reference accessor
// on [`AplicacaoSpec::entrada`] (routes through the
// `pub const fn` [`Option::as_ref`], const-stable since Rust
// 1.83). Any future accidental downgrade to non-`const` fails
// the corresponding `<name>_via_const_fn` wrapper at caixa-
// core build time with E0015 (`cannot call non-const
// method`), strictly stronger than a runtime `assert!`.
// Sibling of the peer inner-composite pin
// [`m3_placement_entrada_slice_return_accessor_pair_is_const_fn`]
// on the `Placement::clusters` + `Entrada::paths` slice-
// return pair, and of the peer M2 axis pins on
// [`crate::supervisor::SupervisorSpec::children`] and
// [`crate::upgrade::UpgradeFromEntry::instructions`].
const fn aplicacao_membros_via_const_fn(s: &AplicacaoSpec) -> &[Membro] {
s.membros()
}
const fn aplicacao_contratos_via_const_fn(s: &AplicacaoSpec) -> &[WitContract] {
s.contratos()
}
const fn aplicacao_politicas_via_const_fn(s: &AplicacaoSpec) -> &MeshPolicy {
s.politicas()
}
const fn aplicacao_placement_via_const_fn(s: &AplicacaoSpec) -> &Placement {
s.placement()
}
const fn aplicacao_entrada_via_const_fn(s: &AplicacaoSpec) -> Option<&Entrada> {
s.entrada()
}
// Construct both a minimal "no :entrada" (internal-only
// mesh) and a full "with :entrada" (external-gateway)
// fixture so the family pins both the `None`-arm (author-
// omitted `:entrada`) and the `Some`-arm (author-declared
// `:entrada`) on the optional-composite axis.
let membro = Membro {
caixa: "web".into(),
versao: "^0.1".into(),
};
let entrada_full = Entrada {
host: "web.example.com".into(),
para: "web".into(),
paths: vec!["/api".into()],
port: DEFAULT_SERVICO_PORT,
};
let internal_only = AplicacaoSpec {
membros: vec![membro.clone()],
contratos: vec![],
politicas: MeshPolicy::default(),
placement: Placement::default(),
entrada: None,
};
let with_entrada = AplicacaoSpec {
membros: vec![membro],
contratos: vec![],
politicas: MeshPolicy::default(),
placement: Placement::default(),
entrada: Some(entrada_full),
};
assert_eq!(
aplicacao_membros_via_const_fn(&internal_only),
internal_only.membros()
);
assert_eq!(
aplicacao_membros_via_const_fn(&with_entrada),
with_entrada.membros()
);
assert_eq!(
aplicacao_contratos_via_const_fn(&internal_only),
internal_only.contratos()
);
assert!(std::ptr::eq(
aplicacao_politicas_via_const_fn(&internal_only),
internal_only.politicas(),
));
assert!(std::ptr::eq(
aplicacao_placement_via_const_fn(&internal_only),
internal_only.placement(),
));
assert!(aplicacao_entrada_via_const_fn(&internal_only).is_none());
match (
aplicacao_entrada_via_const_fn(&with_entrada),
with_entrada.entrada(),
) {
(Some(a), Some(b)) => assert!(std::ptr::eq(a, b)),
_ => panic!(
"aplicacao_entrada_via_const_fn must agree with \
AplicacaoSpec::entrada on the Some-arm reference"
),
}
}
#[test]
fn target_projected_returns_byte_equal_typed_view_across_all_four_arms() {
// Load-bearing contract pin: on every canonical
// `(:wit, :endpoint/:subject/:slot)` shape the substrate admits,
// [`WitContract::target_projected`] returns byte-equal to
// [`WitContract::target`]`().unwrap()` — the post-validation
// projection accessor is a thin panicking wrapper over the
// pre-validation validator, no extra work in the projection
// path. Any future divergence (a validator-side normalization
// the projection doesn't route through, an accessor-side
// caching layer the validator doesn't populate) would surface
// here at caixa-core build time rather than a silent per-consumer
// split at renderer emit time. Sweeps the closed 4-arm
// [`WitTarget`] partition ([`WitTarget::Http`] /
// [`WitTarget::PubSub`] / [`WitTarget::Store`] /
// [`WitTarget::Capability`]) so every arm carries a byte-equality
// pin on the two-accessor pair.
for (wit, endpoint, subject, slot) in [
("wasi:http/proxy", Some("/x"), None, None),
("nats:pub-sub", None, Some("events.x"), None),
("wasi:keyvalue/store", None, None, Some("checkout/$orderId")),
("custom:capability-only", None, None, None),
] {
let c = WitContract {
de: "cart".into(),
para: "catalog".into(),
wit: wit.into(),
endpoint: endpoint.map(str::to_string),
subject: subject.map(str::to_string),
slot: slot.map(str::to_string),
};
assert_eq!(
c.target_projected(),
c.target().unwrap(),
"target_projected must return byte-equal to target().unwrap() at wit={wit:?}"
);
}
}
#[test]
#[should_panic(expected = "validated by typed_view")]
fn target_projected_panics_with_canonical_message_on_unvalidated_contract() {
// Panic-path pin: [`WitContract::target_projected`] threads the
// canonical [`WitContract::PROJECTED_INVARIANT_MSG`] byte-string
// through its expect-panic when called on a contract whose
// (`:wit`, payload) shape has not been crossed by
// [`AplicacaoSpec::validate`] — a contract with a structurally-
// invalid `:wit` (hyphen-for-colon typo) that would surface
// [`AplicacaoError::ContratoWitInvalid`] at the validator gate.
// A future rebrand on the panic-message axis would land at one
// caixa-core edit on [`WitContract::PROJECTED_INVARIANT_MSG`]
// and this pin's [`should_panic(expected = …)`] literal would
// migrate alongside — the pin catches drift between the const
// and the accessor's `expect(…)` call by construction.
let c = WitContract {
de: "cart".into(),
para: "catalog".into(),
// Hyphen-for-colon typo: `WitContract::target` returns
// [`AplicacaoError::ContratoWitInvalid`] on this shape,
// driving the [`WitContract::target_projected`] expect-panic.
wit: "wasi-http/proxy".into(),
endpoint: Some("/x".into()),
subject: None,
slot: None,
};
let _ = c.target_projected();
}
#[test]
fn target_projected_invariant_msg_matches_prior_inline_call_site_literal() {
// Byte-equivalence pin: [`WitContract::PROJECTED_INVARIANT_MSG`]
// carries the exact byte-string the two prior open-coded
// `.target().expect("validated by typed_view")` production
// consumers threaded through inline before this lift converged
// them onto [`WitContract::target_projected`] — the caixa-mesh
// per-`(:de, :para)` CNP L7 introspection branch at
// `caixa-mesh/src/lib.rs:2825` and the caixa-feira `feira app
// graph` per-`:contratos` payload-column printer at
// `caixa-feira/src/cmd/app.rs:110`. Locks the panic-message
// byte-string load-bearing so a well-meaning const-side rebrand
// that didn't carry a matched pin migration would surface here
// at caixa-core build time rather than a silent per-consumer
// panic-message drift at cluster-apply time. Peer of the
// sibling [`WitTarget::CAPABILITY_LABEL`] /
// [`WitTarget::CAPABILITY_EXPECTED`] /
// [`WitTarget::CAPABILITY_GRAPH_LABEL`] byte-equivalence pins on
// the paired payload-less-arm scalar-const family.
assert_eq!(
WitContract::PROJECTED_INVARIANT_MSG,
"validated by typed_view"
);
}
#[test]
fn empty_wit_takes_precedence_over_invalid() {
// Ordering pin: `EmptyWit` is the more self-locating
// diagnostic on `""` and must lead — the value-shape gate is
// only reached after the empty-check fires. Mirrors
// `contrato_endpoint_empty_takes_precedence_over_invalid` on
// the peer payload axis.
let mut s = three_member_spec();
s.contratos.push(WitContract {
de: "payment".into(),
para: "catalog".into(),
wit: String::new(),
endpoint: None,
subject: None,
slot: None,
});
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::EmptyWit { .. }),
"got {err:?}"
);
}
#[test]
fn wit_invalid_fires_before_payload_shape_arm() {
// Ordering pin: a malformed `:wit` surfaces *its own*
// diagnostic (which names the offending wit verbatim) before
// any payload-field check — a contrato whose wit is
// structurally invalid AND carries a wrong target field
// returns `ContratoWitInvalid`, not `ContratoWrongTarget`,
// because the dispatch on the wit is what decides which
// payload field is "right" in the first place. Without this
// ordering, the author would see "wrong target field" for a
// wit that hasn't even been parsed, which doesn't name the
// root cause.
let mut s = three_member_spec();
s.contratos.push(WitContract {
de: "payment".into(),
para: "catalog".into(),
// Hyphen-for-colon typo + endpoint set: pre-gate this
// raised `ContratoWrongTarget { expected: "none" }` (the
// Capability arm rejecting the endpoint), masking the
// real authoring mistake (the wit isn't `wasi:http/proxy`).
wit: "wasi-http/proxy".into(),
endpoint: Some("/x".into()),
subject: None,
slot: None,
});
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, .. }
if wit == "wasi-http/proxy"),
"got {err:?}"
);
}
#[test]
fn wit_invalid_diagnostic_carries_offending_wit() {
// Diagnostic-shape pin — the offending `:wit` + `:de` +
// `:para` + a non-empty reason flow through verbatim so the
// author can grep their caixa.lisp for the offending contrato
// block and fix it in one edit. Same shape as
// `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`.
let err = contrato_wit_err("WASI:HTTP/proxy");
match err {
AplicacaoError::ContratoWitInvalid {
de,
para,
wit,
reason,
} => {
assert_eq!(de, "payment");
assert_eq!(para, "catalog");
assert_eq!(wit, "WASI:HTTP/proxy");
assert!(!reason.is_empty(), "reason field must be non-empty");
}
other => panic!("expected ContratoWitInvalid, got {other:?}"),
}
}
// ── :contratos :subject value-shape gate ─────────────────────────────
//
// Mirrors the `:contratos :endpoint` / `:contratos :wit` value-shape
// suites on the peer payload axes. Until this gate landed
// `WitContract::target()` only refused the empty string; a
// structurally invalid subject silently passed validate and the
// failure surfaced at runtime as a NATS server-side `-ERR 'Invalid
// Subject'` on publish / subscribe, or as a silent message drop,
// far from the source caixa.lisp. Every authoring footgun the
// NATS server's subject parser would catch on admission now
// becomes a caixa-build-time `ContratoSubjectInvalid` with the
// offending `:subject` + `:de` + `:para` named verbatim. Same
// diagnostic shape as `ContratoEndpointInvalid` /
// `ContratoWitInvalid` on the peer payload axes; same shared
// predicate (`crate::render::is_nats_subject`) ensures drift
// between any two axes' rule enforcement is a build error at the
// predicate, not piecemeal across renderers.
fn contrato_subject_err(subject: &str) -> AplicacaoError {
// Fresh spec per call so the new contract doesn't collide on
// identity with `three_member_spec`'s pre-existing entries.
// The new edge uses `(payment, catalog)` — a pair the fixture
// doesn't already declare — with `:wit "nats:pub-sub"` and the
// varying `:subject`, so the subject-shape gate fires cleanly
// after the wit-shape gate (which `"nats:pub-sub"` passes).
let mut s = three_member_spec();
s.contratos.push(WitContract {
de: "payment".into(),
para: "catalog".into(),
wit: "nats:pub-sub".into(),
endpoint: None,
subject: Some(subject.into()),
slot: None,
});
s.validate().unwrap_err()
}
#[test]
fn rejects_pubsub_contrato_subject_with_whitespace() {
// Fail-before-pass-after pin — pre-gate `"foo bar"` silently
// landed at the NATS server as a malformed subject the parser
// rejects with `-ERR 'Invalid Subject'`. Now caught at the
// source caixa.lisp.
let err = contrato_subject_err("foo bar");
assert!(
matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
if subject == "foo bar" && reason.contains("whitespace")),
"got {err:?}"
);
}
#[test]
fn rejects_pubsub_contrato_subject_with_control_char() {
let err = contrato_subject_err("foo\x01bar");
assert!(
matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
if subject == "foo\x01bar" && reason.contains("control character")),
"got {err:?}"
);
}
#[test]
fn rejects_pubsub_contrato_subject_with_non_ascii() {
// Un-percent-encoded non-ASCII byte — the canonical "I copied
// the subject from a doc with smart quotes / accented
// characters" footgun.
let err = contrato_subject_err("foo.caf\u{e9}");
assert!(
matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
if subject == "foo.caf\u{e9}" && reason.contains("non-ASCII")),
"got {err:?}"
);
}
#[test]
fn rejects_pubsub_contrato_subject_with_leading_dot() {
// Empty leading token — NATS rejects.
let err = contrato_subject_err(".foo");
assert!(
matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
if subject == ".foo" && reason.contains("must not start with `.`")),
"got {err:?}"
);
}
#[test]
fn rejects_pubsub_contrato_subject_with_trailing_dot() {
// Empty trailing token — NATS rejects. The remediation
// (use `>` instead) is in the reason string.
let err = contrato_subject_err("foo.");
assert!(
matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
if subject == "foo." && reason.contains("must not end with `.`")),
"got {err:?}"
);
}
#[test]
fn rejects_pubsub_contrato_subject_with_consecutive_dots() {
// The canonical "I forgot to fill in the middle segment"
// typo — `"foo..bar"`. NATS rejects empty tokens.
let err = contrato_subject_err("foo..bar");
assert!(
matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
if subject == "foo..bar" && reason.contains("consecutive `.`")),
"got {err:?}"
);
}
#[test]
fn rejects_pubsub_contrato_subject_with_non_trailing_multi_wildcard() {
// `foo.>.bar` — `>` is the multi-token wildcard, only allowed
// as the final segment. Pre-gate this passed as a typed edge
// and surfaced at runtime as a NATS subscribe rejection.
let err = contrato_subject_err("foo.>.bar");
assert!(
matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
if subject == "foo.>.bar" && reason.contains("only allowed as the final segment")),
"got {err:?}"
);
}
#[test]
fn rejects_pubsub_contrato_subject_with_mid_segment_star() {
// `foo*.bar` — NATS wildcards are standalone tokens. The
// remediation is in the reason string.
let err = contrato_subject_err("foo*.bar");
assert!(
matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
if subject == "foo*.bar" && reason.contains("`*` mid-segment")),
"got {err:?}"
);
}
#[test]
fn rejects_pubsub_contrato_subject_with_invalid_char() {
// `foo,bar` — comma is not a valid NATS subject character.
// Pinned separately from the wildcard arms so the invalid-
// character diagnostic is in force.
let err = contrato_subject_err("foo,bar");
assert!(
matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
if subject == "foo,bar" && reason.contains("invalid character")),
"got {err:?}"
);
}
#[test]
fn rejects_pubsub_contrato_subject_too_long() {
// 257-byte subject — one over the NATS_SUBJECT_MAX_LEN cap.
// The legitimate-shape arms all pass (one all-`a` token, no
// `.`, no wildcards); only the cap arm fires. Surfaces the
// paste-from-binary / accidental-multi-line-blob landing
// footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
// on the peer axis.
let big = "a".repeat(257);
assert_eq!(big.len(), 257);
let err = contrato_subject_err(&big);
assert!(
matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
if subject == &big && reason.contains("max length of 256")),
"got {err:?}"
);
}
#[test]
fn pubsub_contrato_subject_max_length_validates() {
// 256-byte subject — exactly the cap. Boundary pin: drift in
// the cap surfaces here and at
// `rejects_pubsub_contrato_subject_too_long` simultaneously,
// mirroring `http_contrato_endpoint_max_length_validates` and
// `wit_max_length_validates` on the peer axes.
let big = "a".repeat(256);
assert_eq!(big.len(), 256);
let mut s = three_member_spec();
s.contratos.push(WitContract {
de: "payment".into(),
para: "catalog".into(),
wit: "nats:pub-sub".into(),
endpoint: None,
subject: Some(big),
slot: None,
});
s.validate().unwrap();
}
#[test]
fn pubsub_contrato_subject_accepts_canonical_forms() {
// Positive-set sweep: every canonical NATS subject shape the
// substrate-side `is_nats_subject` predicate accepts (the
// multi-dot `events.order.charged`, the snake_case / kebab-
// case / mixed-case tokens, the digit-bearing tokens, the
// single-token wildcard `*` at every segment position, and
// the trailing `>` multi-token wildcard) must remain a valid
// contrato subject too. Drift between this list and the
// substrate-side `nats_subject_accepts_canonical_forms` sweep
// surfaces at the shared predicate — one source of truth.
// Uses a fresh `(payment, catalog)` edge so none of the swept
// subjects collide with the pre-existing entries in
// `three_member_spec`.
for subject in [
"checkout.events.charge.failed",
"rio.events.order.charged",
"orders",
"orders.123",
"snake_case.token",
"kebab-case.token",
"MixedCase.Token",
"orders.*.charged",
"*.events.*",
"orders.>",
] {
let mut s = three_member_spec();
s.contratos.push(WitContract {
de: "payment".into(),
para: "catalog".into(),
wit: "nats:pub-sub".into(),
endpoint: None,
subject: Some(subject.into()),
slot: None,
});
s.validate()
.unwrap_or_else(|e| panic!("expected {subject:?} to validate, got {e:?}"));
}
}
#[test]
fn contrato_subject_empty_takes_precedence_over_invalid() {
// Ordering pin: `ContratoSubjectEmpty` is the more self-
// locating diagnostic on `""` and must lead — the value-shape
// gate is only reached after the empty-check fires. Mirrors
// `contrato_endpoint_empty_takes_precedence_over_invalid` on
// the peer payload axis.
let mut s = three_member_spec();
s.contratos.push(WitContract {
de: "payment".into(),
para: "catalog".into(),
wit: "nats:pub-sub".into(),
endpoint: None,
subject: Some(String::new()),
slot: None,
});
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::ContratoSubjectEmpty { .. }),
"got {err:?}"
);
}
#[test]
fn contrato_subject_invalid_diagnostic_carries_offending_subject() {
// Diagnostic-shape pin — the offending `:subject` + `:de` +
// `:para` + a non-empty reason flow through verbatim so the
// author can grep their caixa.lisp for the offending contrato
// block and fix it in one edit. Same shape as
// `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
// and `wit_invalid_diagnostic_carries_offending_wit`.
let err = contrato_subject_err("foo..bar");
match err {
AplicacaoError::ContratoSubjectInvalid {
de,
para,
subject,
reason,
} => {
assert_eq!(de, "payment");
assert_eq!(para, "catalog");
assert_eq!(subject, "foo..bar");
assert!(!reason.is_empty(), "reason field must be non-empty");
}
other => panic!("expected ContratoSubjectInvalid, got {other:?}"),
}
}
#[test]
fn target_view_pubsub_subject_passes_through_to_typed_view() {
// The compounding theorem on the pub-sub axis: every
// `WitTarget::PubSub { subject }` returned by `target()` carries
// a NATS-server-accepted subject. Renderers downstream of
// `typed_view()` (caixa-mesh's CNP L4 emitter, the future
// NATS Stream/Consumer CR emitter, the future `feira app graph`
// view's subject labeller) can rely on this without re-checking
// — the type system carries the proof. Mirrors
// `target_view_payload_is_guaranteed_nonempty_after_target_call`
// on the peer axes.
let nats = WitContract {
de: "a".into(),
para: "b".into(),
wit: "nats:pub-sub".into(),
endpoint: None,
subject: Some("orders.events.*.charged".into()),
slot: None,
};
match nats.target().unwrap() {
WitTarget::PubSub { subject } => {
assert_eq!(subject, "orders.events.*.charged");
}
other => panic!("expected PubSub, got {other:?}"),
}
}
// ── :contratos :slot value-shape gate ────────────────────────────────
//
// Mirrors the `:contratos :endpoint` (4f0390b) + `:contratos :subject`
// (63e18a0) value-shape suites on the peer payload axes. Until this
// gate landed `WitContract::target()` only refused the empty string
// for the Store arm; a structurally invalid slot (raw whitespace,
// control character, non-ASCII byte, paste-from-binary multi-line
// blob) silently passed validate and surfaced at runtime as a
// per-backend kv write rejection or a silent next-read corruption,
// far from the source caixa.lisp with no field naming which
// `:contratos` edge carried the typo. Every authoring footgun the
// kv backend intersection-floor would catch on write now becomes a
// caixa-build-time `ContratoSlotInvalid` with the offending
// `:slot` + `:de` + `:para` named verbatim. Same diagnostic shape
// as `ContratoEndpointInvalid` / `ContratoSubjectInvalid` on the
// peer payload axes; same shared predicate
// (`crate::render::is_wasi_keyvalue_slot`) ensures drift between
// any two axes' rule enforcement is a build error at the
// predicate, not piecemeal across renderers. Closes the typed
// payload-axis value-shape trajectory across all three legs of the
// four `WitTarget` arms (HTTP / PubSub / Store / Capability).
fn contrato_slot_err(slot: &str) -> AplicacaoError {
// Fresh spec per call so the new contract doesn't collide on
// identity with `three_member_spec`'s pre-existing entries
// and doesn't close a synchronous cycle the cycle detector
// would reject before the slot-shape gate fires. The new edge
// uses `(payment, catalog)` — a pair the fixture doesn't
// already declare in either direction (the fixture carries
// `cart -> catalog` and `cart -> payment`, so `payment ->
// catalog` doesn't form a cycle on the sync subgraph) — with
// `:wit "wasi:keyvalue/store"` and the varying `:slot`, so the
// slot-shape gate fires cleanly after the wit-shape gate
// (which `"wasi:keyvalue/store"` passes). Same edge pair the
// peer `contrato_subject_err` helper uses (63e18a0).
let mut s = three_member_spec();
s.contratos.push(WitContract {
de: "payment".into(),
para: "catalog".into(),
wit: "wasi:keyvalue/store".into(),
endpoint: None,
subject: None,
slot: Some(slot.into()),
});
s.validate().unwrap_err()
}
#[test]
fn rejects_store_contrato_slot_with_whitespace() {
// Fail-before-pass-after pin — pre-gate `"check out/$order"`
// silently landed at the kv backend with whitespace whose
// runtime behavior varies unpredictably across backends (etcd
// accepts, Redis accepts then breaks on next CLI op, DynamoDB
// rejects on write). Now caught at the source caixa.lisp.
let err = contrato_slot_err("check out/$order");
assert!(
matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
if slot == "check out/$order" && reason.contains("whitespace")),
"got {err:?}"
);
}
#[test]
fn rejects_store_contrato_slot_with_tab() {
// Tab byte arm-pinned separately from the space arm so a
// future relaxation that admits one but not the other surfaces
// here.
let err = contrato_slot_err("check\tout");
assert!(
matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
if slot == "check\tout" && reason.contains("whitespace")),
"got {err:?}"
);
}
#[test]
fn rejects_store_contrato_slot_with_control_char() {
// SOH (0x01) — distinct from the whitespace arm. Redis admits
// and corrupts on RESP protocol framing; DynamoDB rejects on
// write.
let err = contrato_slot_err("checkout/\x01order");
assert!(
matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
if slot == "checkout/\x01order" && reason.contains("control character")),
"got {err:?}"
);
}
#[test]
fn rejects_store_contrato_slot_with_newline() {
// Embedded newline — the canonical "the paste-from-binary slug
// spans multiple lines" footgun. Distinct from the whitespace
// arm because `\n` is a control character (0x0A).
let err = contrato_slot_err("checkout\norder");
assert!(
matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
if slot == "checkout\norder" && reason.contains("control character")),
"got {err:?}"
);
}
#[test]
fn rejects_store_contrato_slot_with_non_ascii() {
// Un-percent-encoded non-ASCII byte — the canonical "I copied
// the slot from a doc with accented characters" footgun. Each
// kv backend re-encodes non-ASCII differently (etcd preserves
// bytes verbatim; Redis-via-RESP3 may re-encode; DynamoDB
// rejects), so the typed slot's value set is the intersection-
// floor every backend admits identically (printable ASCII).
let err = contrato_slot_err("ch\u{e9}ckout/$order");
assert!(
matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
if slot == "ch\u{e9}ckout/$order" && reason.contains("non-ASCII")),
"got {err:?}"
);
}
#[test]
fn rejects_store_contrato_slot_too_long() {
// 513-byte slot — one over the WASI_KV_SLOT_MAX_LEN cap. The
// legitimate-shape arms all pass (a single all-`a` token, no
// separators); only the cap arm fires. Surfaces the paste-
// from-binary / accidental-multi-line-blob landing footgun.
// Mirrors `rejects_pubsub_contrato_subject_too_long` and
// `rejects_http_contrato_endpoint_too_long` on the peer
// payload axes.
let big = "a".repeat(513);
assert_eq!(big.len(), 513);
let err = contrato_slot_err(&big);
assert!(
matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
if slot == &big && reason.contains("max length of 512")),
"got {err:?}"
);
}
#[test]
fn store_contrato_slot_max_length_validates() {
// 512-byte slot — exactly the cap. Boundary pin: drift in the
// cap surfaces here and at `rejects_store_contrato_slot_too_long`
// simultaneously, mirroring
// `pubsub_contrato_subject_max_length_validates` and
// `http_contrato_endpoint_max_length_validates` on the peer
// payload axes.
let big = "a".repeat(512);
assert_eq!(big.len(), 512);
let mut s = three_member_spec();
s.contratos.push(WitContract {
de: "payment".into(),
para: "catalog".into(),
wit: "wasi:keyvalue/store".into(),
endpoint: None,
subject: None,
slot: Some(big),
});
s.validate().unwrap();
}
#[test]
fn store_contrato_slot_accepts_canonical_forms() {
// Positive-set sweep: every canonical kv slot template the
// substrate-side `is_wasi_keyvalue_slot` predicate accepts
// (single-token identifiers, path-namespaced `$`-templates,
// colon-namespaced `{}`-templates, dot-namespaced `<>`-templates,
// snake_case / kebab-case / MixedCase tokens, digit-bearing
// tokens, percent-encoded fragments) must remain valid
// contrato slots too. Drift between this list and the
// substrate-side `wasi_kv_slot_accepts_canonical_forms` sweep
// surfaces at the shared predicate — one source of truth.
// Uses a fresh `(payment, catalog)` edge so none of the swept
// slots collide with the pre-existing entries in
// `three_member_spec`.
for slot in [
"checkout",
"checkout/$orderId",
"users:{tenant}/{id}",
"session.<sid>",
"session.tokens.<sid>",
"snake_case_key",
"kebab-case-key",
"MixedCase",
"shard0",
"v2/key",
"users/caf%C3%A9",
] {
let mut s = three_member_spec();
s.contratos.push(WitContract {
de: "payment".into(),
para: "catalog".into(),
wit: "wasi:keyvalue/store".into(),
endpoint: None,
subject: None,
slot: Some(slot.into()),
});
s.validate()
.unwrap_or_else(|e| panic!("expected slot {slot:?} to validate, got {e:?}"));
}
}
#[test]
fn contrato_slot_empty_takes_precedence_over_invalid() {
// Ordering pin: `ContratoSlotEmpty` is the more self-locating
// diagnostic on `""` and must lead — the value-shape gate is
// only reached after the empty-check fires. Mirrors
// `contrato_subject_empty_takes_precedence_over_invalid` and
// `contrato_endpoint_empty_takes_precedence_over_invalid` on
// the peer payload axes.
let mut s = three_member_spec();
s.contratos.push(WitContract {
de: "payment".into(),
para: "catalog".into(),
wit: "wasi:keyvalue/store".into(),
endpoint: None,
subject: None,
slot: Some(String::new()),
});
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::ContratoSlotEmpty { .. }),
"got {err:?}"
);
}
#[test]
fn contrato_slot_invalid_diagnostic_carries_offending_slot() {
// Diagnostic-shape pin — the offending `:slot` + `:de` +
// `:para` + a non-empty reason flow through verbatim so the
// author can grep their caixa.lisp for the offending contrato
// block and fix it in one edit. Same shape as
// `contrato_subject_invalid_diagnostic_carries_offending_subject`
// and `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
// on the peer payload axes.
let err = contrato_slot_err("check out/$order");
match err {
AplicacaoError::ContratoSlotInvalid {
de,
para,
slot,
reason,
} => {
assert_eq!(de, "payment");
assert_eq!(para, "catalog");
assert_eq!(slot, "check out/$order");
assert!(!reason.is_empty(), "reason field must be non-empty");
}
other => panic!("expected ContratoSlotInvalid, got {other:?}"),
}
}
#[test]
fn target_view_store_slot_passes_through_to_typed_view() {
// The compounding theorem on the store axis: every
// `WitTarget::Store { slot }` returned by `target()` carries a
// kv-backend-accepted slot template. Renderers downstream of
// `typed_view()` (the future per-Servico `:capabilities
// wasi:keyvalue/store` axis emitter, the future `feira app
// graph` view's slot labeller, the future kv-provider CR
// materializer) can rely on this without re-checking — the
// type system carries the proof. Mirrors
// `target_view_pubsub_subject_passes_through_to_typed_view` on
// the peer payload axis.
let store = WitContract {
de: "a".into(),
para: "b".into(),
wit: "wasi:keyvalue/store".into(),
endpoint: None,
subject: None,
slot: Some("checkout/$orderId".into()),
};
match store.target().unwrap() {
WitTarget::Store { slot } => {
assert_eq!(slot, "checkout/$orderId");
}
other => panic!("expected Store, got {other:?}"),
}
}
#[test]
fn rejects_self_loop_in_synchronous_contratos() {
// A synchronous self-edge (`cart → cart` over HTTP) is now
// rejected by the dedicated `ContratoSelfLoop` gate — a precise
// "this edge is degenerate" diagnostic — rather than incidentally
// by the cycle detector framing it as a `["cart", "cart"]`
// multi-node deadlock.
let mut s = three_member_spec();
s.contratos.push(contract_http("cart", "cart", "/loop"));
let err = s.validate().unwrap_err();
match err {
AplicacaoError::ContratoSelfLoop { caixa, wit } => {
assert_eq!(caixa, "cart");
assert_eq!(wit, "wasi:http/proxy");
}
other => panic!("expected ContratoSelfLoop, got {other:?}"),
}
}
#[test]
fn rejects_self_loop_in_pubsub_contratos() {
// The cycle detector excludes pub-sub edges (acyclic by
// construction), so before the explicit gate a `nats:pub-sub`
// self-edge silently validated and rendered a self-allow CNP.
// The shape-agnostic `ContratoSelfLoop` gate closes that hole.
let mut s = three_member_spec();
s.contratos.push(WitContract {
de: "payment".into(),
para: "payment".into(),
wit: "nats:pub-sub".into(),
endpoint: None,
subject: Some("rio.events.payment".into()),
slot: None,
});
let err = s.validate().unwrap_err();
match err {
AplicacaoError::ContratoSelfLoop { caixa, wit } => {
assert_eq!(caixa, "payment");
assert_eq!(wit, "nats:pub-sub");
}
other => panic!("expected ContratoSelfLoop, got {other:?}"),
}
}
#[test]
fn self_loop_fires_before_payload_shape_check() {
// The structural "this edge can't exist" error precedes the
// narrower payload-shape diagnostics: a self-edge carrying an
// otherwise-malformed endpoint still reports ContratoSelfLoop,
// not ContratoEndpointInvalid.
let mut s = three_member_spec();
s.contratos.push(WitContract {
de: "cart".into(),
para: "cart".into(),
wit: "wasi:http/proxy".into(),
endpoint: Some("not-absolute".into()),
subject: None,
slot: None,
});
match s.validate().unwrap_err() {
AplicacaoError::ContratoSelfLoop { caixa, .. } => assert_eq!(caixa, "cart"),
other => panic!("expected ContratoSelfLoop, got {other:?}"),
}
}
#[test]
fn self_loop_fires_before_membership_is_satisfied_but_after_missing_member() {
// A self-edge naming a non-member reports the more fundamental
// ContratoMemberMissing first (the member doesn't exist), so the
// self-loop gate is reached only once both endpoints resolve.
let mut s = three_member_spec();
s.contratos.push(contract_http("ghost", "ghost", "/loop"));
match s.validate().unwrap_err() {
AplicacaoError::ContratoMemberMissing { caixa } => assert_eq!(caixa, "ghost"),
other => panic!("expected ContratoMemberMissing, got {other:?}"),
}
}
#[test]
fn rejects_two_node_synchronous_cycle() {
let mut s = three_member_spec();
// existing edges: cart → catalog, cart → payment
// adding catalog → cart closes a 2-cycle on the HTTP subgraph
s.contratos
.push(contract_http("catalog", "cart", "/refresh"));
let err = s.validate().unwrap_err();
match err {
AplicacaoError::ContratoCycle { cycle } => {
// Cycle traversal should mention both endpoints, with
// the back-edge target appearing as both first and last
// element to close the loop.
assert!(cycle.len() >= 3);
assert_eq!(cycle.first(), cycle.last());
let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
assert!(body.contains("cart"));
assert!(body.contains("catalog"));
}
other => panic!("expected ContratoCycle, got {other:?}"),
}
}
#[test]
fn rejects_three_node_synchronous_cycle() {
let mut s = three_member_spec();
// Reset to a clean 3-cycle: catalog → cart → payment → catalog
s.contratos = vec![
contract_http("catalog", "cart", "/x"),
contract_http("cart", "payment", "/y"),
contract_http("payment", "catalog", "/z"),
];
let err = s.validate().unwrap_err();
match err {
AplicacaoError::ContratoCycle { cycle } => {
assert_eq!(cycle.first(), cycle.last());
let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
assert_eq!(body.len(), 3);
assert!(body.contains("cart"));
assert!(body.contains("catalog"));
assert!(body.contains("payment"));
}
other => panic!("expected ContratoCycle, got {other:?}"),
}
}
#[test]
fn pubsub_edge_breaks_cycle_per_mesh_composition_iii_3() {
// MESH-COMPOSITION §III.3 explicitly says NATS pub-sub is
// "acyclic by construction" — so a cycle whose closing edge
// is pub-sub should NOT raise ContratoCycle.
let mut s = three_member_spec();
s.contratos = vec![
contract_http("catalog", "cart", "/x"),
contract_http("cart", "payment", "/y"),
// Closing edge is pub-sub — async; not a sync deadlock.
WitContract {
de: "payment".into(),
para: "catalog".into(),
wit: "nats:pub-sub".into(),
endpoint: None,
subject: Some("checkout.events.charge.completed".into()),
slot: None,
},
];
s.validate().expect("pub-sub edge breaks the sync cycle");
}
#[test]
fn store_edge_counts_as_synchronous_for_cycle_detection() {
// wasi:keyvalue/store is request/response; a cycle through one
// *is* a sync deadlock, just like HTTP.
let mut s = three_member_spec();
s.contratos = vec![
contract_http("catalog", "cart", "/x"),
WitContract {
de: "cart".into(),
para: "catalog".into(),
wit: "wasi:keyvalue/store".into(),
endpoint: None,
subject: None,
slot: Some("session/$id".into()),
},
];
let err = s.validate().unwrap_err();
assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
}
#[test]
fn capability_edge_counts_as_synchronous_for_cycle_detection() {
// Capability-only edges (unknown WIT shape, no payload) default
// to synchronous — safer; authors with truly async capability
// semantics can model them as pub-sub explicitly.
let mut s = three_member_spec();
s.contratos = vec![
contract_http("catalog", "cart", "/x"),
WitContract {
de: "cart".into(),
para: "catalog".into(),
wit: "custom:exchange".into(),
endpoint: None,
subject: None,
slot: None,
},
];
let err = s.validate().unwrap_err();
assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
}
#[test]
fn long_acyclic_chain_validates() {
// A long sync chain (no back-edges) must validate even when
// every node is reachable from the first.
let mut s = three_member_spec();
s.membros = vec![
membro("a", "^0.1"),
membro("b", "^0.1"),
membro("c", "^0.1"),
membro("d", "^0.1"),
membro("e", "^0.1"),
];
s.contratos = vec![
contract_http("a", "b", "/1"),
contract_http("b", "c", "/2"),
contract_http("c", "d", "/3"),
contract_http("d", "e", "/4"),
];
s.entrada.as_mut().unwrap().para = "a".into();
s.validate().unwrap();
}
#[test]
fn diamond_acyclic_validates() {
// a → b, a → c, b → d, c → d. Two paths to d, no cycle.
let mut s = three_member_spec();
s.membros = vec![
membro("a", "^0.1"),
membro("b", "^0.1"),
membro("c", "^0.1"),
membro("d", "^0.1"),
];
s.contratos = vec![
contract_http("a", "b", "/1"),
contract_http("a", "c", "/2"),
contract_http("b", "d", "/3"),
contract_http("c", "d", "/4"),
];
s.entrada.as_mut().unwrap().para = "a".into();
s.validate().unwrap();
}
// ── duplicate-`:contratos` build-error gate ──────────────────────────
#[test]
fn rejects_duplicate_http_contrato() {
// Fail-before-pass-after pin: the fixture's `cart → catalog`
// HTTP edge appears once. Push an identical entry — same
// (de, para, wit, endpoint) — and validate() must reject it.
// Until this gate landed the typed surface accepted the
// duplicate silently and caixa-mesh's `cilium_network_policies`
// emitted two ``CiliumNetworkPolicy`` objects with identical
// `metadata.name` (`<aplicacao>-<de>-to-<para>`), which K8s
// admission rejects on `kubectl apply` far from the source.
let mut s = three_member_spec();
s.contratos
.push(contract_http("cart", "catalog", "/products/:id"));
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
if de == "cart" && para == "catalog" && wit == "wasi:http/proxy"
),
"got {err:?}"
);
}
#[test]
fn rejects_duplicate_pubsub_contrato() {
// Same gate on the pub-sub edge axis. Two `nats:pub-sub`
// edges with identical (de, para, subject) are degenerate;
// pin that the typed surface refuses both at validate time.
let mut s = three_member_spec();
let pubsub = WitContract {
de: "payment".into(),
para: "cart".into(),
wit: "nats:pub-sub".into(),
endpoint: None,
subject: Some("checkout.events.charge.failed".into()),
slot: None,
};
s.contratos.push(pubsub.clone());
s.contratos.push(pubsub);
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
if de == "payment" && para == "cart" && wit == "nats:pub-sub"
),
"got {err:?}"
);
}
#[test]
fn rejects_duplicate_store_contrato() {
// Same gate on the key-value edge axis. Two `wasi:keyvalue/store`
// edges with identical (de, para, slot) collapse to one mesh-
// policy edge; pin the build error.
let mut s = three_member_spec();
let store = WitContract {
de: "cart".into(),
para: "payment".into(),
wit: "wasi:keyvalue/store".into(),
endpoint: None,
subject: None,
slot: Some("checkout/$orderId".into()),
};
// Drop the conflicting HTTP `cart → payment` edge from the
// fixture so the duplicate-store pair is the only one
// distinguishable on this pair.
s.contratos
.retain(|c| !(c.de == "cart" && c.para == "payment"));
s.contratos.push(store.clone());
s.contratos.push(store);
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
if de == "cart" && para == "payment" && wit == "wasi:keyvalue/store"
),
"got {err:?}"
);
}
#[test]
fn rejects_duplicate_capability_contrato() {
// Same gate on the pure-capability axis (no payload selector).
// Two contracts with identical (de, para, wit) and no
// endpoint/subject/slot are duplicate edges; pin so a future
// `target_label` change can't accidentally collapse the
// capability arm into a None-shaped key that compares equal
// to a populated one.
let mut s = three_member_spec();
let capability = WitContract {
de: "cart".into(),
para: "catalog".into(),
wit: "pleme:cap/audit".into(),
endpoint: None,
subject: None,
slot: None,
};
s.contratos.push(capability.clone());
s.contratos.push(capability);
let err = s.validate().unwrap_err();
match err {
AplicacaoError::ContratoDuplicate {
de,
para,
wit,
target,
} => {
assert_eq!(de, "cart");
assert_eq!(para, "catalog");
assert_eq!(wit, "pleme:cap/audit");
assert!(
target.contains("capability"),
"capability-edge duplicate diagnostic must surface the \
no-payload shape (got target = {target:?})"
);
}
other => panic!("expected ContratoDuplicate, got {other:?}"),
}
}
#[test]
fn accepts_distinct_http_paths_between_same_pair() {
// Negative pin: two HTTP contracts cart → catalog at distinct
// endpoints (`/products/:id` and `/search`) are *not*
// duplicates — they're distinct typed edges differing on the
// payload axis. The duplicate-gate must not over-match here,
// since the cart-calls-catalog-on-multiple-paths shape is the
// canonical multi-endpoint pattern (MESH-COMPOSITION §III.1
// example: cart calls catalog at /products/:id, payment at
// /charge — same shape extends to two paths on one para).
let mut s = three_member_spec();
s.contratos
.push(contract_http("cart", "catalog", "/search"));
s.validate()
.expect("distinct endpoints between same (de, para) must validate");
}
#[test]
fn accepts_same_endpoint_on_different_pairs() {
// Negative pin: the same `/charge` endpoint reused on two
// different (de, para) pairs is two distinct edges, not a
// duplicate. Pinning this shape so the gate's identity key
// includes both `de` and `para` (not just `(wit, endpoint)`).
let mut s = three_member_spec();
s.contratos
.push(contract_http("payment", "catalog", "/charge"));
s.validate()
.expect("same endpoint reused on distinct (de, para) must validate");
}
#[test]
fn rejects_duplicate_contrato_diagnostic_names_offending_target() {
// Pin the diagnostic shape: the duplicate-edge error names
// *which* target field carried the conflict, so the author
// doesn't have to re-grep the source caixa.lisp to find it.
// Same self-locating diagnostic discipline as
// ContratoEndpointEmpty / ContratoSubjectEmpty / etc.
let mut s = three_member_spec();
s.contratos
.push(contract_http("cart", "catalog", "/products/:id"));
let err = s.validate().unwrap_err();
let msg = format!("{err}");
assert!(
msg.contains("\"/products/:id\""),
"duplicate-contrato diagnostic must name the offending \
:endpoint payload (got: {msg:?})"
);
assert!(
msg.contains("cart") && msg.contains("catalog"),
"diagnostic must name both endpoints of the duplicate edge \
(got: {msg:?})"
);
}
#[test]
fn duplicate_contrato_gate_runs_after_membership_check() {
// Order pin: a duplicate contract whose `:de` is *also* not in
// `:membros` surfaces the membership error first — the
// missing-member diagnostic is more locating than the
// duplicate-edge one (the author has to fix the membership
// before the duplicate is meaningful). Same ordering
// discipline as `membros_validation_runs_before_contratos_membership_check`.
let mut s = three_member_spec();
s.contratos.push(contract_http("phantom", "catalog", "/x"));
s.contratos.push(contract_http("phantom", "catalog", "/x"));
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::ContratoMemberMissing { ref caixa } if caixa == "phantom"),
"membership-missing must fire before duplicate-edge (got {err:?})"
);
}
#[test]
fn duplicate_contrato_gate_runs_after_target_shape_check() {
// Order pin: a contract with a malformed target (e.g. an HTTP
// wit world with an empty :endpoint) surfaces the target-shape
// error first, not the duplicate one. Even when two such
// malformed entries are identical, the per-contract `target()`
// check fires inside the loop *before* the duplicate-key
// insert, so the diagnostic remains the most-locating one.
let mut s = three_member_spec();
let malformed = WitContract {
de: "cart".into(),
para: "catalog".into(),
wit: "wasi:http/proxy".into(),
endpoint: Some(String::new()),
subject: None,
slot: None,
};
s.contratos.push(malformed.clone());
s.contratos.push(malformed);
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
"endpoint-empty must fire before duplicate-edge (got {err:?})"
);
}
#[test]
fn wit_target_label_pins_per_variant_format() {
// Label format is the single source of truth every duplicate-
// `:contratos` diagnostic + every future `feira app graph`
// consumer routes through. Pin the shape per variant so a
// future edit to `WitTarget::label` (e.g. a JSON emitter that
// strips the leading `:`, or a rename from `endpoint` →
// `path`) surfaces as a red-red test rather than as a silent
// downstream diagnostic drift. Together with the exhaustive
// `match` on `WitTarget` inside `label()`, adding a future
// variant (M4 `Rest` / `Grpc` split, `Queue`-shaped `Store`
// peer, per-edge WIT registry variants) is a compile error at
// the label site — not a fall-through into the `Capability`
// "no payload" default the prior raw-field-probe helper
// silently landed on.
assert_eq!(
WitTarget::Http {
endpoint: "/charge",
}
.label(),
"\
:endpoint \"/charge\""
);
assert_eq!(
WitTarget::PubSub {
subject: "events.checkout.paid",
}
.label(),
"\
:subject \"events.checkout.paid\""
);
assert_eq!(
WitTarget::Store {
slot: "checkout/$order",
}
.label(),
"\
:slot \"checkout/$order\""
);
assert_eq!(WitTarget::Capability.label(), "(capability — no payload)");
// Capability-arm label routes through the lifted
// [`WitTarget::CAPABILITY_LABEL`] const so the "one canonical
// declaration per arm, next to the variant" discipline the
// peer payload-arm [`WitTarget::HTTP_FIELD_NAME`] /
// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
// consts already carry extends to the payload-less arm; the
// byte-string equality pin below plus this label-routes-
// through-the-const pin make a future rebrand on either the
// const declaration or the `label()` template a build error
// here rather than a downstream consumer surprise.
assert_eq!(WitTarget::Capability.label(), WitTarget::CAPABILITY_LABEL,);
assert_eq!(WitTarget::CAPABILITY_LABEL, "(capability — no payload)");
}
#[test]
fn wit_target_display_routes_through_label_helper() {
// Fail-before-pass-after pin on the fourth (and only remaining)
// typed-shape-discriminator axis to converge onto the
// three-path-convergence discipline the sibling M3
// [`PlacementStrategy`] (0a2f653) and M2
// [`crate::supervisor::RestartStrategy`] /
// [`crate::supervisor::RestartPolicy`] OTP-shape typed enums
// already carry: [`std::fmt::Display`] on [`WitTarget`] routes
// through [`WitTarget::label`], so every consumer reaching for
// `format!("{v}")` on a typed payload target lands on the same
// stable author-facing byte-string [`WitTarget::label`] returns
// — the byte-string the [`AplicacaoError::ContratoDuplicate`]
// `target:` carry the [`AplicacaoSpec::validate`] duplicate-
// `:contratos` gate seeds via [`WitTarget::label`] at
// aplicacao.rs:5491 already threads through.
//
// Pre-lift `format!("{v}")` on [`WitTarget`] would have fallen
// through to the `Debug` derive's structural output
// (`Http { endpoint: "/charge" }` — Rust struct-literal syntax)
// rather than the [`WitTarget::label`] helper's stable byte-
// string (`:endpoint "/charge"` — the author-facing `:contratos`
// keyword form). Every future consumer that reaches for
// `format!("{target}")` — the canonical shape every user-facing
// pretty-print site on the sibling typed-enum axes
// ([`PlacementStrategy`], [`crate::supervisor::RestartStrategy`],
// [`crate::supervisor::RestartPolicy`]) already uses — would
// silently land under a different byte-string than the
// [`WitTarget::label`] callers that the duplicate-`:contratos`
// diagnostic already threads through, with the mismatch
// surfacing as a downstream diagnostic / graph / audit line
// reading one spelling while the substrate's own gate emitted
// another.
//
// Pin the routing here so a future
// `impl std::fmt::Display for WitTarget<'_>` reimplementation
// that hand-rolls the per-arm formatting instead of delegating
// to [`WitTarget::label`] fails at caixa-core build time.
for variant in [
WitTarget::Http {
endpoint: "/charge",
},
WitTarget::PubSub {
subject: "events.checkout.paid",
},
WitTarget::Store {
slot: "checkout/$order",
},
WitTarget::Capability,
] {
assert_eq!(
variant.to_string(),
variant.label(),
"WitTarget::{variant:?} Display must route through \
WitTarget::label (single source of truth: the lifted \
payload_pair 4-arm dispatch the label helper already \
threads through)"
);
}
}
#[test]
fn wit_target_display_matches_duplicate_contratos_diagnostic_carrier() {
// Consumer-side pin on the three-path convergence:
// [`std::fmt::Display`] agrees byte-for-byte with the
// [`AplicacaoError::ContratoDuplicate`] `target:` carrier the
// [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds
// via [`WitTarget::label`] at aplicacao.rs:5491 on every arm.
// Pre-lift the two paths were structurally independent — the
// substrate-side gate reached for `target_view.label()` while a
// future downstream diagnostic / graph / audit line reaching
// for `format!("{target}")` would silently land on the `Debug`
// derive's structural output. Pin the two paths byte-for-byte
// here so any future variant addition (M4 `Rest`/`Grpc` split
// of [`WitTarget::Http`], `Queue`-shaped peer of
// [`WitTarget::Store`]) is a caixa-core-build-time exhaustive-
// match error at [`WitTarget::payload_pair`] rather than a
// silent per-consumer dispatch miss.
for variant in [
WitTarget::Http {
endpoint: "/charge",
},
WitTarget::PubSub {
subject: "events.checkout.paid",
},
WitTarget::Store {
slot: "checkout/$order",
},
WitTarget::Capability,
] {
assert_eq!(
format!("{variant}"),
variant.label(),
"WitTarget::{variant:?} Display byte-string must match \
the AplicacaoError::ContratoDuplicate `target:` carrier \
the AplicacaoSpec::validate duplicate-`:contratos` gate \
seeds via WitTarget::label — three-path convergence: \
Display + label + payload_pair all resolve to the same \
per-arm byte-string"
);
}
}
#[test]
fn wit_target_payload_pair_pins_per_variant() {
// Pin the per-arm `(field-name, payload)` pair single-sourced
// onto [`WitTarget::payload_pair`] — the single 4-arm dispatch
// both [`WitTarget::label`] (formats `":{field} {payload:?}"`
// on `Some`, falls to [`WitTarget::CAPABILITY_LABEL`] on `None`)
// and [`WitTarget::field_name`] (returns the first component)
// route through. Until this lift landed [`WitTarget::label`]
// dispatched on the same three arms with a per-arm
// `format!(":{} {…:?}", …)` invocation each, hand-quoting the
// paired [`WitTarget::HTTP_FIELD_NAME`] /
// [`WitTarget::PUBSUB_FIELD_NAME`] /
// [`WitTarget::STORE_FIELD_NAME`] const at every site — the
// canonical "same shape, written N times" duplication
// THEORY.md §I.3.5 promotes to a build-time concern. A future
// [`WitTarget`] variant addition (`Rest`/`Grpc` split of
// [`WitTarget::Http`], `Queue`-shaped peer of
// [`WitTarget::Store`]) is one match-arm edit at
// [`WitTarget::payload_pair`], visible here as a compile-time
// exhaustiveness error on both this pin and the label-format
// pin above.
assert_eq!(
WitTarget::Http {
endpoint: "/charge"
}
.payload_pair(),
Some((WitTarget::HTTP_FIELD_NAME, "/charge")),
);
assert_eq!(
WitTarget::PubSub {
subject: "events.x",
}
.payload_pair(),
Some((WitTarget::PUBSUB_FIELD_NAME, "events.x")),
);
assert_eq!(
WitTarget::Store {
slot: "checkout/$order",
}
.payload_pair(),
Some((WitTarget::STORE_FIELD_NAME, "checkout/$order")),
);
assert_eq!(WitTarget::Capability.payload_pair(), None);
}
#[test]
fn wit_target_field_name_pins_per_variant() {
// Pin the per-arm author-facing `:contratos` payload field
// name single-sourced onto [`WitTarget::HTTP_FIELD_NAME`] /
// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
// + returned by [`WitTarget::field_name`]. Every downstream
// consumer (the [`WitContract::target`] gate's `expected:`
// scalar, the [`WitTarget::label`] template's keyword prefix,
// the `feira app graph` verb's `endpoint=…` prefix) routes
// through the same three peer consts, so a rename on the
// author-surface `(defcaixa … :contratos ((:de … :para …
// :wit … :endpoint …)))` field lands in exactly one place.
assert_eq!(
WitTarget::Http {
endpoint: "/charge"
}
.field_name(),
Some(WitTarget::HTTP_FIELD_NAME),
);
assert_eq!(
WitTarget::PubSub {
subject: "events.x",
}
.field_name(),
Some(WitTarget::PUBSUB_FIELD_NAME),
);
assert_eq!(
WitTarget::Store {
slot: "checkout/$order",
}
.field_name(),
Some(WitTarget::STORE_FIELD_NAME),
);
// Capability arm carries no payload field — the diagnostic
// never reports `expected: "capability"` because the gate's
// Capability arm accepts no payload at all (it fires the
// "expected: none" WrongTarget error instead), so the field-
// name method returns None here rather than a placeholder.
assert_eq!(WitTarget::Capability.field_name(), None);
// Peer const scalar values pinned so a rename on either side
// (author-surface field name in the `(defcaixa …)` DSL, or
// the diagnostic's `expected:` scalar) can't drift without
// failing here first.
assert_eq!(WitTarget::HTTP_FIELD_NAME, "endpoint");
assert_eq!(WitTarget::PUBSUB_FIELD_NAME, "subject");
assert_eq!(WitTarget::STORE_FIELD_NAME, "slot");
}
#[test]
fn wit_target_payload_pins_per_variant() {
// Pin the per-arm payload scalar single-sourced onto the
// [`WitTarget::payload_pair`] 4-arm dispatch and surfaced through
// [`WitTarget::payload`] — the peer per-half projection to
// [`WitTarget::field_name`] on the paired sub-selector axis. The
// three payload-carrying arms round-trip their author-declared
// scalar verbatim (`Http` → `Some("/charge")`, `PubSub` →
// `Some("events.x")`, `Store` → `Some("checkout/$order")`) and
// the payload-less [`WitTarget::Capability`] arm returns `None`.
// Same shape as the sibling `wit_target_field_name_pins_per_variant`
// (c6ec2af) pin on the Component-0 projection axis, extended
// onto the Component-1 projection axis so both per-half readers
// on the paired dispatch carry their own byte-shape pin.
assert_eq!(
WitTarget::Http {
endpoint: "/charge",
}
.payload(),
Some("/charge"),
);
assert_eq!(
WitTarget::PubSub {
subject: "events.x",
}
.payload(),
Some("events.x"),
);
assert_eq!(
WitTarget::Store {
slot: "checkout/$order",
}
.payload(),
Some("checkout/$order"),
);
assert_eq!(WitTarget::Capability.payload(), None);
}
#[test]
fn wit_target_payload_matches_payload_pair_second_component_per_variant() {
// Per-variant equivalence pin: for every arm of [`WitTarget`],
// `.payload()` equals `.payload_pair().map(|(_, p)| p)`
// byte-for-byte. Guards the drift surface where a future refactor
// that split one accessor off the shared match onto its own
// dispatch — a well-meaning "inline the pair back into per-half
// fields for one crate-internal caller who only wanted one half"
// or a scratch `impl` shadowing the derived projection — would
// silently desynchronize [`WitTarget::payload`] from the
// authoritative [`WitTarget::payload_pair`] dispatch, and every
// downstream consumer that thinks "the payload half of the pair"
// would drift from the diagnostic / graph consumers reading the
// same match through [`WitTarget::label`] / [`WitTarget::graph_label`].
// Sibling to the peer [`caixa_flux::GitRefSpec`] `ref_value`
// per-half projection pin (`gitrefspec_ref_pair_projects_
// ref_field_name_and_ref_value_per_variant`, 655a1c0) on the
// FluxCD source-controller `spec.ref.<field>` axis — same "one
// paired dispatch, both per-half projections agree byte-for-
// byte" discipline extended onto the M3 `:contratos` payload-
// arm surface.
for variant in [
WitTarget::Http {
endpoint: "/charge",
},
WitTarget::PubSub {
subject: "events.checkout.paid",
},
WitTarget::Store {
slot: "checkout/$order",
},
WitTarget::Capability,
] {
let via_projection = variant.payload();
let via_pair = variant.payload_pair().map(|(_, p)| p);
assert_eq!(
via_projection, via_pair,
"WitTarget::{variant:?} payload() must equal \
payload_pair().map(|(_, p)| p) byte-for-byte — a \
regression that splits the two per-half projections off \
their shared match would silently desynchronize the \
payload accessor from the paired dispatch every \
diagnostic / graph consumer reads through",
);
}
}
#[test]
fn wit_target_http_endpoint_pins_per_variant() {
// Pin the per-arm HTTP-endpoint scalar single-sourced onto the
// [`WitTarget::http_endpoint`] 2-arm dispatch — the
// substrate-primitive per-arm post-projection accessor every
// L7-HTTP-facing consumer routes through, sibling to the peer
// WitContract pre-projection [`WitContract::endpoint`] (7020470)
// scalar accessor on the raw-field axis. The [`WitTarget::Http`]
// arm round-trips its author-declared endpoint verbatim as
// `Some("/charge")`; the three sibling arms
// ([`WitTarget::PubSub`] / [`WitTarget::Store`] /
// [`WitTarget::Capability`]) each return `None` because they
// carry no HTTP endpoint by definition. Same fail-before-pass-
// after per-variant discipline as the sibling
// `wit_target_payload_pins_per_variant` (5d6dc92) /
// `wit_target_field_name_pins_per_variant` (c6ec2af) /
// `wit_target_payload_pair_pins_per_variant` (6788ed6) pins on
// the peer pan-arm / per-half projection axes — extended onto
// the per-arm HTTP-shape post-projection axis so a future
// [`WitTarget`] variant addition (a `Rest`/`Grpc` split of
// [`WitTarget::Http`], a `Queue`-shaped peer of
// [`WitTarget::Store`]) trips a compile-time exhaustiveness
// error on the sibling [`WitTarget::http_endpoint`] match arms
// whose payload the L7-HTTP-shape accept-set is meant to bound.
assert_eq!(
WitTarget::Http {
endpoint: "/charge",
}
.http_endpoint(),
Some("/charge"),
);
assert_eq!(
WitTarget::PubSub {
subject: "events.checkout.paid",
}
.http_endpoint(),
None,
);
assert_eq!(
WitTarget::Store {
slot: "checkout/$order",
}
.http_endpoint(),
None,
);
assert_eq!(WitTarget::Capability.http_endpoint(), None);
}
#[test]
fn wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere() {
// Per-variant coherence pin: for every arm of [`WitTarget`],
// `.http_endpoint()` equals `.payload()` on the [`WitTarget::Http`]
// arm (both project the same author-declared request-path
// scalar), and returns `None` on every sibling arm regardless of
// whether [`WitTarget::payload`] itself returns `Some` (PubSub /
// Store carry their own payload the pan-arm accessor surfaces,
// but that payload is not an HTTP endpoint — the per-arm
// accessor must not leak it through the HTTP-shape channel).
// Guards the drift surface where a future refactor that
// conflated the per-arm HTTP projection with the pan-arm
// [`WitTarget::payload`] projection — a well-meaning "one
// accessor for the L7 branch, one for the graph" collapse that
// routes both through the same 4-arm dispatch — would silently
// widen the L7-HTTP-shape accept-set onto pub-sub / store
// payloads at the caixa-mesh L7 emit branch, admitting a
// `nats:pub-sub` edge's `:subject` as a Cilium L7 HTTP `path:`
// rule with the operator-side apply-time symptom (Cilium's
// eBPF data-plane rejects every ingress edge whose L7 filter
// doesn't match the wire-format HTTP request line) far from
// the source refactor. Sibling to the peer
// `wit_target_payload_matches_payload_pair_second_component_
// per_variant` (5d6dc92) coherence pin on the pan-arm axis —
// extended onto the per-arm HTTP specialization axis so both
// the pan-arm and the per-arm projections carry their own
// byte-shape coherence witness against the substrate's typed
// arm-family accept-set.
for variant in [
WitTarget::Http {
endpoint: "/charge",
},
WitTarget::PubSub {
subject: "events.checkout.paid",
},
WitTarget::Store {
slot: "checkout/$order",
},
WitTarget::Capability,
] {
let per_arm = variant.http_endpoint();
let pan_arm = variant.payload();
if variant.is_http() {
assert_eq!(
per_arm, pan_arm,
"WitTarget::{variant:?} http_endpoint() must equal \
payload() on the Http arm — a per-arm-vs-pan-arm \
split would silently drift the L7 emit branch's \
path-scalar source from the graph verb's payload \
scalar source",
);
} else {
assert_eq!(
per_arm, None,
"WitTarget::{variant:?} http_endpoint() must return \
None on non-Http arms — a leak that surfaced a \
pub-sub :subject or a key/value :slot through the \
HTTP-endpoint accessor would silently widen the \
Cilium L7 HTTP `path:` rule accept-set onto \
protocol shapes Cilium's eBPF data-plane can't \
introspect",
);
}
}
}
#[test]
fn wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant() {
// Per-variant coherence pin: for every arm of [`WitTarget`],
// `.http_endpoint().is_some()` iff `.is_http()`. Guards the
// drift surface where a future extension of the
// [`WitTarget::http_endpoint`] accessor's accept-set (e.g. a
// `Rest`/`Grpc` split of [`WitTarget::Http`] that widened the
// accessor to cover both peers) landed without a paired
// extension of the [`gen_platform::IsVariant`]-derived
// `is_http()` predicate's accept-set, or vice versa — a
// regression that split the "which arms count as HTTP-shaped
// for L7-path emission?" answer between two dispatch surfaces
// the substrate ships. Sibling to the peer
// `wit_target_field_name_pins_per_variant` (c6ec2af) discipline
// on the paired dispatch axis — extended onto the per-arm
// predicate-vs-accessor coherence axis so the gen-platform
// IsVariant predicate and the substrate-lifted per-arm
// accessor carry one shared answer to "is this the HTTP arm?".
for variant in [
WitTarget::Http {
endpoint: "/charge",
},
WitTarget::PubSub {
subject: "events.checkout.paid",
},
WitTarget::Store {
slot: "checkout/$order",
},
WitTarget::Capability,
] {
assert_eq!(
variant.http_endpoint().is_some(),
variant.is_http(),
"WitTarget::{variant:?} http_endpoint().is_some() must \
equal is_http() — a drift would split the L7 emit \
branch's arm-set gate from the substrate-derived \
shape-discrimination predicate on the same axis",
);
}
}
#[test]
fn wit_target_pubsub_subject_pins_per_variant() {
// Fail-before-pass-after pin: the substrate-canonical per-arm
// pub-sub-subject scalar accessor [`WitTarget::pubsub_subject`]
// is the single dispatch every future pub-sub-facing consumer
// routes through, sibling to the peer [`WitContract::subject`]
// (63e18a0) pre-projection scalar accessor on the raw-field
// axis and to the peer [`WitTarget::http_endpoint`] (5d6dc92)
// post-projection per-arm accessor on the sibling HTTP-shape
// axis. The [`WitTarget::PubSub`] arm round-trips its
// author-declared subject verbatim as
// `Some("events.checkout.paid")`; the three sibling arms each
// return `None` because they carry no NATS-shaped subject by
// definition. Same fail-before-pass-after per-variant discipline
// as the sibling `wit_target_http_endpoint_pins_per_variant`
// pin on the peer per-arm axis — extended onto the per-arm
// pub-sub-shape post-projection axis so a future [`WitTarget`]
// variant addition (a `Rest`/`Grpc` split of [`WitTarget::Http`],
// a `Queue`-shaped peer of [`WitTarget::Store`]) trips a
// compile-time exhaustiveness error on the sibling
// [`WitTarget::pubsub_subject`] match arms whose payload the
// pub-sub-shape accept-set is meant to bound.
assert_eq!(
WitTarget::PubSub {
subject: "events.checkout.paid",
}
.pubsub_subject(),
Some("events.checkout.paid"),
);
assert_eq!(
WitTarget::Http {
endpoint: "/charge",
}
.pubsub_subject(),
None,
);
assert_eq!(
WitTarget::Store {
slot: "checkout/$order",
}
.pubsub_subject(),
None,
);
assert_eq!(WitTarget::Capability.pubsub_subject(), None);
}
#[test]
fn wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere() {
// Per-variant coherence pin: for every arm of [`WitTarget`],
// `.pubsub_subject()` equals `.payload()` on the
// [`WitTarget::PubSub`] arm (both project the same
// author-declared subject scalar), and returns `None` on every
// sibling arm regardless of whether [`WitTarget::payload`]
// itself returns `Some` (Http / Store carry their own payload
// the pan-arm accessor surfaces, but that payload is not a
// pub-sub subject — the per-arm accessor must not leak it
// through the pub-sub-shape channel). Sibling to the peer
// `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
// coherence pin on the per-arm HTTP-shape axis — extended onto
// the per-arm pub-sub specialization axis so both per-arm
// projections carry their own byte-shape coherence witness
// against the substrate's typed arm-family accept-set.
for variant in [
WitTarget::Http {
endpoint: "/charge",
},
WitTarget::PubSub {
subject: "events.checkout.paid",
},
WitTarget::Store {
slot: "checkout/$order",
},
WitTarget::Capability,
] {
let per_arm = variant.pubsub_subject();
let pan_arm = variant.payload();
if variant.is_pubsub() {
assert_eq!(
per_arm, pan_arm,
"WitTarget::{variant:?} pubsub_subject() must equal \
payload() on the PubSub arm — a per-arm-vs-pan-arm \
split would silently drift the pub-sub-shape emit \
branch's subject-scalar source from the graph verb's \
payload scalar source",
);
} else {
assert_eq!(
per_arm, None,
"WitTarget::{variant:?} pubsub_subject() must return \
None on non-PubSub arms — a leak that surfaced an \
HTTP :endpoint or a key/value :slot through the \
pub-sub-subject accessor would silently widen the \
downstream NATS-shape accept-set onto protocol \
shapes NATS servers can't route",
);
}
}
}
#[test]
fn wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant() {
// Per-variant coherence pin: for every arm of [`WitTarget`],
// `.pubsub_subject().is_some()` iff `.is_pubsub()`. Guards the
// drift surface where a future extension of the
// [`WitTarget::pubsub_subject`] accessor's accept-set landed
// without a paired extension of the [`gen_platform::IsVariant`]-
// derived `is_pubsub()` predicate's accept-set, or vice versa
// — a regression that split the "which arms count as pub-sub-
// shaped for subject emission?" answer between two dispatch
// surfaces the substrate ships. Sibling to the peer
// `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
// pin on the per-arm HTTP-shape axis — extended onto the
// per-arm pub-sub predicate-vs-accessor coherence axis so the
// gen-platform IsVariant predicate and the substrate-lifted
// per-arm accessor carry one shared answer to "is this the
// PubSub arm?".
for variant in [
WitTarget::Http {
endpoint: "/charge",
},
WitTarget::PubSub {
subject: "events.checkout.paid",
},
WitTarget::Store {
slot: "checkout/$order",
},
WitTarget::Capability,
] {
assert_eq!(
variant.pubsub_subject().is_some(),
variant.is_pubsub(),
"WitTarget::{variant:?} pubsub_subject().is_some() must \
equal is_pubsub() — a drift would split the pub-sub \
emit branch's arm-set gate from the substrate-derived \
shape-discrimination predicate on the same axis",
);
}
}
#[test]
fn wit_target_store_slot_pins_per_variant() {
// Fail-before-pass-after pin: the substrate-canonical per-arm
// key/value-store-slot scalar accessor [`WitTarget::store_slot`]
// is the single dispatch every future store-facing consumer
// routes through, sibling to the peer [`WitContract::slot`]
// pre-projection scalar accessor on the raw-field axis and to
// the peer [`WitTarget::http_endpoint`] (5d6dc92) +
// [`WitTarget::pubsub_subject`] post-projection per-arm
// accessors on the sibling per-payload-arm axes. The
// [`WitTarget::Store`] arm round-trips its author-declared
// slot verbatim as `Some("checkout/$order")`; the three
// sibling arms each return `None` because they carry no
// WASI-key/value slot by definition. Same fail-before-pass-
// after per-variant discipline as the sibling
// `wit_target_http_endpoint_pins_per_variant` +
// `wit_target_pubsub_subject_pins_per_variant` pins on the
// peer per-arm axes — extended onto the per-arm store-shape
// post-projection axis so a future [`WitTarget`] variant
// addition trips a compile-time exhaustiveness error on the
// sibling [`WitTarget::store_slot`] match arms whose payload
// the store-shape accept-set is meant to bound.
assert_eq!(
WitTarget::Store {
slot: "checkout/$order",
}
.store_slot(),
Some("checkout/$order"),
);
assert_eq!(
WitTarget::Http {
endpoint: "/charge",
}
.store_slot(),
None,
);
assert_eq!(
WitTarget::PubSub {
subject: "events.checkout.paid",
}
.store_slot(),
None,
);
assert_eq!(WitTarget::Capability.store_slot(), None);
}
#[test]
fn wit_target_store_slot_matches_payload_on_store_arm_and_is_none_elsewhere() {
// Per-variant coherence pin: for every arm of [`WitTarget`],
// `.store_slot()` equals `.payload()` on the
// [`WitTarget::Store`] arm (both project the same
// author-declared slot scalar), and returns `None` on every
// sibling arm regardless of whether [`WitTarget::payload`]
// itself returns `Some`. Sibling to the peer
// `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
// and `wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere`
// pins on the per-arm HTTP and PubSub axes — closes the
// per-arm-vs-pan-arm byte-shape coherence trio across all
// three payload arms.
for variant in [
WitTarget::Http {
endpoint: "/charge",
},
WitTarget::PubSub {
subject: "events.checkout.paid",
},
WitTarget::Store {
slot: "checkout/$order",
},
WitTarget::Capability,
] {
let per_arm = variant.store_slot();
let pan_arm = variant.payload();
if variant.is_store() {
assert_eq!(
per_arm, pan_arm,
"WitTarget::{variant:?} store_slot() must equal \
payload() on the Store arm — a per-arm-vs-pan-arm \
split would silently drift the store-shape emit \
branch's slot-scalar source from the graph verb's \
payload scalar source",
);
} else {
assert_eq!(
per_arm, None,
"WitTarget::{variant:?} store_slot() must return \
None on non-Store arms — a leak that surfaced an \
HTTP :endpoint or a NATS :subject through the \
key/value-slot accessor would silently widen the \
downstream WASI-key/value slot accept-set onto \
protocol shapes the kv backends can't route",
);
}
}
}
#[test]
fn wit_target_store_slot_agrees_with_is_store_predicate_per_variant() {
// Per-variant coherence pin: for every arm of [`WitTarget`],
// `.store_slot().is_some()` iff `.is_store()`. Guards the
// drift surface where a future extension of the
// [`WitTarget::store_slot`] accessor's accept-set landed
// without a paired extension of the [`gen_platform::IsVariant`]-
// derived `is_store()` predicate's accept-set. Sibling to the
// peer `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
// and `wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant`
// pins — closes the per-arm predicate-vs-accessor coherence
// trio across all three payload arms so the gen-platform
// IsVariant predicate and the substrate-lifted per-arm
// accessor carry one shared answer to "is this the Store arm?".
for variant in [
WitTarget::Http {
endpoint: "/charge",
},
WitTarget::PubSub {
subject: "events.checkout.paid",
},
WitTarget::Store {
slot: "checkout/$order",
},
WitTarget::Capability,
] {
assert_eq!(
variant.store_slot().is_some(),
variant.is_store(),
"WitTarget::{variant:?} store_slot().is_some() must \
equal is_store() — a drift would split the store-shape \
emit branch's arm-set gate from the substrate-derived \
shape-discrimination predicate on the same axis",
);
}
}
#[test]
fn wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set() {
// Fail-before-pass-after cross-axis pin on the trio
// (`http_endpoint`, `pubsub_subject`, `store_slot`): on every
// payload-carrying arm of [`WitTarget`], exactly one per-arm
// accessor returns `Some(payload)` and the two peers return
// `None`; and on the payload-less [`WitTarget::Capability`]
// arm, all three return `None`. Guards the drift surface where
// a future extension of one per-arm accessor's accept-set (e.g.
// a hypothetical `Rest`/`Grpc` split of [`WitTarget::Http`]
// that widened `http_endpoint` to cover both peers without
// narrowing the peer `pubsub_subject` / `store_slot` accept-
// sets to keep the partition mutually exclusive) landed without
// threading through the peer per-arm accessors — the resulting
// silent overlap would land the same edge's payload on two
// downstream per-shape emit branches at once, or leak a
// pub-sub subject through the store-slot channel, at renderer
// emit time far from the substrate primitive's arm-widening
// commit. Peer of the sibling `wit_target_field_names_are_pairwise_distinct`
// 3-way pin on the payload-field-name axis — extended onto the
// per-arm-accessor payload-projection axis so the substrate-
// owned partition invariant is load-bearing at every per-arm
// consumer's read site.
let payload_variants = [
(
WitTarget::Http {
endpoint: "/charge",
},
"http",
),
(
WitTarget::PubSub {
subject: "events.checkout.paid",
},
"pubsub",
),
(
WitTarget::Store {
slot: "checkout/$order",
},
"store",
),
];
for (variant, own_arm_label) in payload_variants {
let own_arm_hit = match own_arm_label {
"http" => variant.is_http(),
"pubsub" => variant.is_pubsub(),
"store" => variant.is_store(),
other => panic!("unknown own-arm label {other:?}"),
};
let per_arm_results = [
("http_endpoint", variant.http_endpoint()),
("pubsub_subject", variant.pubsub_subject()),
("store_slot", variant.store_slot()),
];
let some_count = per_arm_results.iter().filter(|(_, v)| v.is_some()).count();
assert_eq!(
some_count, 1,
"WitTarget::{variant:?} must land exactly one per-arm \
post-projection accessor's Some result — the trio \
(http_endpoint, pubsub_subject, store_slot) must \
partition the payload arm-set; got {per_arm_results:?}",
);
assert!(
own_arm_hit,
"WitTarget::{variant:?} own-arm gen-platform predicate \
must return true on its own arm — a partition failure \
upstream of this pin",
);
assert!(
variant.payload().is_some(),
"WitTarget::{variant:?} pan-arm payload() must return \
Some on every payload-carrying arm the trio partitions",
);
}
// The payload-less Capability arm must return None on every
// per-arm accessor — the partition's terminal-fallback shape.
let cap = WitTarget::Capability;
assert_eq!(cap.http_endpoint(), None);
assert_eq!(cap.pubsub_subject(), None);
assert_eq!(cap.store_slot(), None);
assert_eq!(
cap.payload(),
None,
"WitTarget::Capability pan-arm payload() must return None — \
the trio's payload-less-arm coherence witness",
);
}
#[test]
fn wit_target_field_names_are_pairwise_distinct() {
// Distinctness pin: if any two of the three payload-field-name
// scalars ever collapse (e.g. an accidental `endpoint` copy-
// paste over the `subject` const), the [`WitContract::target`]
// gate's diagnostic would point authors at the wrong field —
// an "expected `:endpoint`" error on a pub-sub edge would
// silently misroute the fix. Same cross-axis-distinctness
// discipline as the peer M3 `:placement :estrategia` variant-
// discriminator scalar-value pins (cc8f749) applied to the
// payload-field-name axis.
assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::PUBSUB_FIELD_NAME);
assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
assert_ne!(WitTarget::PUBSUB_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
}
#[test]
fn wit_target_graph_label_routes_through_payload_pair_on_payload_arms() {
// Fail-before-pass-after pin: the graph-verb payload column's
// per-arm `{field}={payload}` byte-string is derived through the
// single [`WitTarget::payload_pair`] 4-arm dispatch on the three
// payload-carrying arms, not through a hand-rolled per-arm match
// that re-projects [`WitTarget::HTTP_FIELD_NAME`] /
// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
// inline. A future variant addition — the M4-and-later per-edge
// WIT registry may split [`WitTarget::Http`] into `Rest` / `Grpc`
// peers, or extend [`WitTarget::Store`] with a `Queue`-shaped
// peer — becomes one match-arm edit at [`WitTarget::payload_pair`],
// and both [`WitTarget::label`] (duplicate-`:contratos`
// diagnostic) and [`WitTarget::graph_label`] (`feira app graph`
// payload column) pick up the new arm from the same dispatch.
// Prior to this lift the graph verb open-coded the 4-arm match
// in caixa-feira, so a variant addition would have to be threaded
// through both projections in lockstep or the graph verb would
// silently drop the new arm to `(capability-only)`.
for variant in [
WitTarget::Http {
endpoint: "/charge",
},
WitTarget::PubSub {
subject: "events.checkout.paid",
},
WitTarget::Store {
slot: "checkout/$order",
},
] {
let (field, payload) = variant
.payload_pair()
.expect("payload arm must expose (field, payload)");
assert_eq!(
variant.graph_label(),
format!("{field}={payload}"),
"WitTarget::{variant:?} graph_label must route the \
`{{field}}={{payload}}` template through payload_pair — \
a regression to a hand-rolled per-arm match at the graph \
verb would silently disagree with a future variant \
addition landed only at payload_pair"
);
}
}
#[test]
fn wit_target_graph_label_returns_capability_graph_label_const_on_capability_arm() {
// Fail-before-pass-after pin on the payload-less arm: the graph
// verb's `(capability-only)` byte-string routes through the
// lifted [`WitTarget::CAPABILITY_GRAPH_LABEL`] const on the
// [`WitTarget::Capability`] arm, not through an inline
// `.to_string()` literal at the caixa-feira `cmd::app::GraphArgs::run`
// per-`:contratos` payload column. Peer of the sibling
// [`wit_target_label_pins_per_variant_format`] Capability-arm
// assertion on the [`WitTarget::CAPABILITY_LABEL`] const —
// extended here onto the third payload-less-arm consumer axis
// (graph verb, sibling to the duplicate-`:contratos` diagnostic
// axis and the wrong-target diagnostic axis).
assert_eq!(
WitTarget::Capability.graph_label(),
WitTarget::CAPABILITY_GRAPH_LABEL,
);
assert_eq!(WitTarget::CAPABILITY_GRAPH_LABEL, "(capability-only)");
}
#[test]
fn wit_target_capability_graph_label_distinct_from_capability_label() {
// Cross-consumer-axis distinctness pin: the graph-verb
// payload-column const [`WitTarget::CAPABILITY_GRAPH_LABEL`]
// (`(capability-only)`) and the duplicate-`:contratos` diagnostic
// label const [`WitTarget::CAPABILITY_LABEL`] (`(capability — no
// payload)`) surface the payload-less arm on two distinct
// consumer axes; a collapse (an accidental rebrand that lands
// one spelling on both consts, a copy-paste that unifies them
// "for consistency") would silently merge the two byte-strings
// and lose the vocabulary distinction the graph verb's
// compact-column form and the diagnostic's descriptive-clause
// form each carry on purpose. Peer of the sibling 4-way
// [`wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`]
// pin on the `ContratoWrongTarget::expected` scalar-value axis —
// extended here onto the cross-consumer-axis distinctness of the
// two payload-less-arm consts.
assert_ne!(
WitTarget::CAPABILITY_GRAPH_LABEL,
WitTarget::CAPABILITY_LABEL,
"WitTarget::CAPABILITY_GRAPH_LABEL (graph-verb payload column) \
and WitTarget::CAPABILITY_LABEL (duplicate-`:contratos` \
diagnostic) must remain distinct — a collapse would silently \
merge two consumer axes onto one spelling"
);
}
#[test]
fn wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms() {
// 4-way distinctness pin extending the sibling
// [`wit_target_field_names_are_pairwise_distinct`] 3-way pin
// (which covers only the HTTP / PubSub / Store payload arms)
// onto the fourth scalar the shared
// [`AplicacaoError::ContratoWrongTarget`] `expected: &'static
// str` axis threads through — [`WitTarget::CAPABILITY_EXPECTED`]
// (`"none"`), the payload-less Capability-arm rejection scalar.
//
// All four [`WitTarget::HTTP_FIELD_NAME`] /
// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
// / [`WitTarget::CAPABILITY_EXPECTED`] consts are the closed-set
// dispatch surface [`WitContract::target`] writes onto the
// `ContratoWrongTarget::expected` field — the same `&'static
// str` axis authors read as "this WIT world's shape admits
// (only|not) `:<field>`". Pairwise-distinctness is the invariant
// downstream consumers rely on: an `expected: "endpoint"`
// diagnostic on a Capability-shaped edge tells the author to
// add a `:endpoint "…"` slot to a WIT world that admits none,
// silently misrouting the fix. Until this pin landed the three
// payload-arm consts were distinctness-guarded by the sibling
// 3-way pin (a4a5d09 / 4a1e490) while the fourth Capability-arm
// scalar (d4f54f2) sat unguarded — a rebrand collision (the
// author-facing vocabulary shift from `"none"` to `"endpoint"`
// / `"subject"` / `"slot"` as M4 splits [`WitTarget::Capability`]
// into per-shape peers) would have silently landed one
// Capability-arm rejection on a payload-arm's `expected:` byte-
// string and desynchronized the diagnostic from the author's
// typed shape.
//
// Same 4-way pairwise-distinctness pin discipline as the peer
// [`m3_placement_estrategia_consts_are_pairwise_distinct`]
// (cc8f749) applies on the sibling M3 closed-set typed-enum
// scalar-value dispatch axis; extends the pin trajectory the
// sibling `wit_target_field_names_are_pairwise_distinct`
// 3-way pin opened to cover the last unguarded corner on the
// `ContratoWrongTarget::expected` scalar-value axis.
//
// Fail-before-pass-after locally verified by mutating
// [`WitTarget::CAPABILITY_EXPECTED`] to also read `"endpoint"`
// — this pin fires as expected; restoring passes.
let all = [
WitTarget::HTTP_FIELD_NAME,
WitTarget::PUBSUB_FIELD_NAME,
WitTarget::STORE_FIELD_NAME,
WitTarget::CAPABILITY_EXPECTED,
];
for (i, a) in all.iter().enumerate() {
for (j, b) in all.iter().enumerate() {
if i != j {
assert_ne!(
a, b,
"WitTarget::{{HTTP_FIELD_NAME, PUBSUB_FIELD_NAME, \
STORE_FIELD_NAME, CAPABILITY_EXPECTED}} consts must be \
pairwise distinct — got duplicate {a:?} at indices \
{i} and {j}; all four scalars thread through the \
shared `AplicacaoError::ContratoWrongTarget::expected` \
&'static str axis, so a collapse silently misdirects \
the diagnostic on which typed shape the WIT world admits",
);
}
}
}
}
#[test]
fn wit_target_is_variant_predicates_partition_the_arm_set() {
// Fail-before-pass-after pin on the
// [`gen_platform::IsVariant`] derive on [`WitTarget`]: for
// each of the four variants exactly one of the generated
// `is_http` / `is_pubsub` / `is_store` / `is_capability`
// predicates returns `true` and the other three return
// `false`. Prior to this derive the only production
// arm-discriminator on [`WitTarget`] — the sync-cycle
// exclusion in [`AplicacaoSpec::detect_sync_cycles`] — was a
// raw `matches!(c.target()?, WitTarget::PubSub { .. })` on
// the variant that expressed no compile-time link back to
// the closed-set typed dispatch a future fifth
// `:contratos :wit`-shape arm (an M4 per-edge WIT registry
// split of [`WitTarget::PubSub`] into shape-specific peers,
// an M4-and-later `Rest` / `Grpc` split of [`WitTarget::Http`],
// a `Queue`-shaped peer of [`WitTarget::Store`]) would have
// to thread through in lockstep or the DFS exclusion would
// silently disagree with the peer diagnostic templates on
// which arms carry sync-versus-async semantics. Peer of the
// sibling [`crate::CaixaKind`] (f5bba80),
// [`PlacementStrategy`] (766ec63),
// [`crate::supervisor::RestartStrategy`],
// [`crate::supervisor::RestartPolicy`], and
// [`crate::upgrade::UpgradeInstruction`] (915a934)
// `IsVariant` derives on the sibling closed-set typed-enum
// discriminator axes — extends the same one-typed-dispatch-
// per-variant discipline onto the last unlifted closed-set
// typed-enum discriminator on the caixa surface (the M3
// mesh-slot per-`:contratos` target-arm axis), closing the
// arm-discriminator convergence trajectory across every
// closed-set typed enum in caixa-core.
let rows: [(WitTarget<'static>, [bool; 4]); 4] = [
(
WitTarget::Http { endpoint: "/x" },
[true, false, false, false],
),
(
WitTarget::PubSub {
subject: "events.x",
},
[false, true, false, false],
),
(
WitTarget::Store { slot: "kv/x" },
[false, false, true, false],
),
(WitTarget::Capability, [false, false, false, true]),
];
for (variant, expected) in rows {
let observed = [
variant.is_http(),
variant.is_pubsub(),
variant.is_store(),
variant.is_capability(),
];
assert_eq!(
observed, expected,
"WitTarget::{variant:?} is_* predicates must partition \
the arm set (http, pubsub, store, capability); got {observed:?}"
);
}
}
#[test]
fn wit_target_is_variant_predicates_are_const_fn() {
// The [`gen_platform::IsVariant`] derive emits `const fn`
// predicates on the peer [`crate::CaixaKind`] +
// [`crate::upgrade::UpgradeInstruction`] +
// [`crate::supervisor::RestartStrategy`] +
// [`crate::supervisor::RestartPolicy`] +
// [`PlacementStrategy`] closed-set typed enums — pin the
// same posture on [`WitTarget`] so a future accidental
// downgrade to non-`const` (an added runtime helper reachable
// only from a non-`const` context, a manual hand-rolled
// `impl` that shadows the derive-generated method) trips at
// caixa-core build time rather than surfacing as a downstream
// `const`-context regression far from the derive declaration.
//
// Unlike the peer unit-variant enums (`CaixaKind` /
// `PlacementStrategy` / `RestartStrategy` / `RestartPolicy`)
// whose `const` constructors need no arguments, the three
// payload-carrying [`WitTarget`] arms are const-constructed
// through `&'static str` payloads — the same `'static`
// lifetime the closed-set typed enum's four-arm partition
// pin above already threads through.
//
// The pin lives inside a `const { assert!(..) }` block so the
// compiler enforces both halves (arm predicate is `const`-
// callable AND returns `true` for the matching arm) at
// caixa-core compile time — peer to the sibling
// [`crate::CaixaKind::is_*`] const-block pin on the closed-set
// typed enum arm-predicate const-callability axis.
const {
assert!(WitTarget::Http { endpoint: "/x" }.is_http());
assert!(WitTarget::PubSub { subject: "e" }.is_pubsub());
assert!(WitTarget::Store { slot: "kv/x" }.is_store());
assert!(WitTarget::Capability.is_capability());
}
}
#[test]
fn detect_sync_cycles_skips_pubsub_edges_through_is_pubsub_predicate() {
// Consumer-side pin on the sole production converge site:
// [`AplicacaoSpec::detect_sync_cycles`] excludes pub-sub
// edges from the synchronous-subgraph DFS via the lifted
// [`WitTarget::is_pubsub`] `IsVariant`-derived arm-discriminator
// predicate (rebound from the prior raw
// `matches!(c.target()?, WitTarget::PubSub { .. })` on the
// variant). Byte-equivalent today (`is_pubsub` is the
// derive-generated `matches!(self, Self::PubSub { .. })` by
// construction, the `#[is_variant(name = "pubsub")]` override
// aliasing the auto-derived `is_pub_sub` back to the sibling
// [`WitContract::is_pubsub`] name); pin the behavior so a
// future accidental drift (a rebind onto a peer arm
// predicate, a manual hand-rolled `impl` that shadows the
// derive-generated method with different semantics, a peer
// arm rename that shifts which variant carries sync-versus-
// async semantics) trips at caixa-core test time rather than
// at some downstream operator's runtime dispatch far from the
// rebind commit.
//
// The fixture constructs a two-Servico Aplicacao with one
// pub-sub edge that would close a sync-cycle if the DFS did
// not exclude it: `a → b` (pub-sub) + `b → a` (http). The
// pub-sub exclusion means the DFS sees only the `b → a` HTTP
// edge, which is not a cycle. A regression in the converge
// (a rebind that reads the pub-sub arm as sync) would report
// `AplicacaoError::ContratoCycle`.
let s = AplicacaoSpec {
membros: vec![membro("a", "^0.1"), membro("b", "^0.1")],
contratos: vec![
// Pub-sub edge: DFS must skip via is_pubsub().
WitContract {
de: "a".into(),
para: "b".into(),
wit: "nats:pub-sub".into(),
endpoint: None,
subject: Some("events.x".into()),
slot: None,
},
// HTTP edge: DFS must include.
WitContract {
de: "b".into(),
para: "a".into(),
wit: "wasi:http/proxy".into(),
endpoint: Some("/x".into()),
subject: None,
slot: None,
},
],
politicas: MeshPolicy::default(),
placement: Placement {
estrategia: PlacementStrategy::Replicated,
clusters: vec!["rio".into()],
affinity: None,
shard_key: None,
},
entrada: None,
};
s.validate()
.expect("pub-sub edge must be excluded from sync-cycle DFS");
}
#[test]
fn wit_target_field_name_routes_through_label_and_expected_diagnostic() {
// Consumer-side pin: the same three peer consts thread through
// both the [`WitTarget::label`] template (leading-`:` keyword
// prefix in the duplicate-`:contratos` diagnostic) and the
// [`WitContract::target`] gate's [`AplicacaoError::
// ContratoMissingTarget`] `expected:` scalar (the field the
// author needs to add). Pin both routes at once so a future
// refactor can't accidentally split them onto separate string
// literals — the "one place, everywhere reaches for it"
// invariant the peer const set carries.
let http_label = WitTarget::Http { endpoint: "/x" }.label();
assert!(
http_label.starts_with(&format!(":{} ", WitTarget::HTTP_FIELD_NAME)),
"label must lead with :{} keyword (got {http_label:?})",
WitTarget::HTTP_FIELD_NAME,
);
let mut s = three_member_spec();
s.contratos.push(WitContract {
de: "cart".into(),
para: "catalog".into(),
wit: "kafka:topic".into(),
endpoint: None,
subject: None,
slot: None,
});
match s.validate().unwrap_err() {
AplicacaoError::ContratoMissingTarget { expected, .. } => {
assert_eq!(expected, WitTarget::PUBSUB_FIELD_NAME);
}
other => panic!("expected ContratoMissingTarget, got {other:?}"),
}
}
#[test]
fn duplicate_pubsub_diagnostic_names_offending_subject() {
// Peer of `rejects_duplicate_contrato_diagnostic_names_offending_target`
// on the pub-sub target axis: the duplicate-edge diagnostic
// must name the `:subject` payload verbatim (not just the
// `(de, para, wit)` triple). Prior to lifting the label onto
// [`WitTarget::label`] the diagnostic derived the label from
// raw [`WitContract`] `Option<String>` probes — a future
// `WitTarget` variant addition (M4 per-edge WIT registry)
// would silently fall through to the `Capability` "no
// payload" default without a compiler warning. Pinning the
// pub-sub arm's format closes the second of three
// payload-carrying `WitTarget` arms this diagnostic threads
// through.
let mut s = three_member_spec();
let pubsub = WitContract {
de: "payment".into(),
para: "cart".into(),
wit: "nats:pub-sub".into(),
endpoint: None,
subject: Some("events.checkout.paid".into()),
slot: None,
};
s.contratos.push(pubsub.clone());
s.contratos.push(pubsub);
let err = s.validate().unwrap_err();
let msg = format!("{err}");
assert!(
msg.contains(":subject \"events.checkout.paid\""),
"duplicate-pubsub diagnostic must name the offending \
:subject payload (got: {msg:?})"
);
}
#[test]
fn duplicate_store_diagnostic_names_offending_slot() {
// Peer of the HTTP + pub-sub duplicate-diagnostic pins on the
// key-value target axis: the diagnostic must name the `:slot`
// payload verbatim. Third of three payload-carrying
// `WitTarget` arms this diagnostic threads through, closing
// the per-arm label pin trilogy (`Http` — 6841,
// `PubSub` + `Store` — this test + peer above).
let mut s = three_member_spec();
let store = WitContract {
de: "cart".into(),
para: "payment".into(),
wit: "wasi:keyvalue/store".into(),
endpoint: None,
subject: None,
slot: Some("checkout/$orderId".into()),
};
s.contratos
.retain(|c| !(c.de == "cart" && c.para == "payment"));
s.contratos.push(store.clone());
s.contratos.push(store);
let err = s.validate().unwrap_err();
let msg = format!("{err}");
assert!(
msg.contains(":slot \"checkout/$orderId\""),
"duplicate-store diagnostic must name the offending :slot \
payload (got: {msg:?})"
);
}
#[test]
fn rejects_entrada_path_without_leading_slash() {
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "api/products".into()];
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "api/products"),
"got {err:?}"
);
}
#[test]
fn rejects_empty_entrada_path() {
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), String::new()];
assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
}
#[test]
fn rejects_duplicate_entrada_paths() {
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().paths = vec![
"/api/cart".into(),
"/api/products".into(),
"/api/cart".into(),
];
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::EntradaPathDuplicate { ref path } if path == "/api/cart"),
"got {err:?}"
);
}
#[test]
fn rejects_zero_entrada_port() {
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().port = 0;
assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
}
// ── :entrada :paths value-shape gate ─────────────────────────────
//
// Mirrors the `:entrada :host` value-shape suite (c7d05ec) on the
// sibling `:paths` axis. Every authoring footgun the K8s Gateway
// API v1 apiserver / webhook would catch on `HTTPRoute.spec.rules[]
// .matches[].path.value` (caixa-mesh/src/lib.rs:498) at admission
// time now becomes a caixa-build-time `EntradaPathInvalid` with
// the offending `:paths` entry named verbatim.
#[test]
fn rejects_entrada_path_with_query() {
// Fail-before-pass-after pin — pre-gate the `?q=1` suffix
// silently passed validate and the Gateway API webhook
// rejected it at apply time with no source citation.
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().paths = vec!["/api/cart?q=1".into()];
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
if path == "/api/cart?q=1" && reason.contains("must not contain `?`")),
"got {err:?}"
);
}
#[test]
fn rejects_entrada_path_with_fragment() {
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().paths = vec!["/api/cart#frag".into()];
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
if path == "/api/cart#frag" && reason.contains("must not contain `#`")),
"got {err:?}"
);
}
#[test]
fn rejects_entrada_path_with_space() {
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().paths = vec!["/api/my cart".into()];
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
if path == "/api/my cart" && reason.contains("whitespace")),
"got {err:?}"
);
}
#[test]
fn rejects_entrada_path_with_tab() {
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().paths = vec!["/api/\tcart".into()];
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
if path == "/api/\tcart" && reason.contains("whitespace")),
"got {err:?}"
);
}
#[test]
fn rejects_entrada_path_with_control_char() {
// 0x01 (SOH) — a non-whitespace control char surfaces the
// distinct "control character" reason arm, separate from
// the whitespace arm. Pinned so a future refactor that
// collapses the two arms can't accidentally drop the more
// self-locating diagnostic.
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().paths = vec!["/api/\x01cart".into()];
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
if path == "/api/\x01cart" && reason.contains("control character")),
"got {err:?}"
);
}
#[test]
fn rejects_entrada_path_with_non_ascii() {
// `café` — the un-percent-encoded UTF-8 footgun the RFC 3986
// unreserved-set rule rejects. The Gateway API webhook
// rejects literal non-ASCII bytes; percent-encoding is the
// only way to author non-ASCII in a path.
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().paths = vec!["/api/café".into()];
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
if path == "/api/café" && reason.contains("non-ASCII")),
"got {err:?}"
);
}
#[test]
fn rejects_entrada_path_with_consecutive_slashes() {
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().paths = vec!["/api//cart".into()];
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
if path == "/api//cart" && reason.contains("consecutive `/`")),
"got {err:?}"
);
}
#[test]
fn rejects_entrada_path_with_dot_segment() {
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().paths = vec!["/api/./cart".into()];
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
if path == "/api/./cart" && reason.contains("`.` segment")),
"got {err:?}"
);
}
#[test]
fn rejects_entrada_path_with_trailing_dot_segment() {
// The bare `/.` and the trailing `/foo/.` are both rejected
// by the Gateway API webhook; pinned separately so a future
// narrowing that catches only the inner form surfaces here.
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().paths = vec!["/api/.".into()];
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
if path == "/api/." && reason.contains("`.` segment")),
"got {err:?}"
);
}
#[test]
fn rejects_entrada_path_with_parent_segment() {
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().paths = vec!["/api/../etc".into()];
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
if path == "/api/../etc" && reason.contains("`..` parent-segment")),
"got {err:?}"
);
}
#[test]
fn rejects_entrada_path_with_trailing_parent_segment() {
// Trailing `/..` — symmetric arm of the parent-segment rule,
// pinned separately so a future relaxation that only checks
// the inner form (`/../`) surfaces here.
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().paths = vec!["/api/..".into()];
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
if path == "/api/.." && reason.contains("`..` parent-segment")),
"got {err:?}"
);
}
#[test]
fn rejects_entrada_path_too_long() {
// 1025-byte path — one over the Gateway API HTTPPathMatch.value
// maxLength cap of 1024. Use a `/api/` prefix + a 1020-byte
// ASCII-alphanumeric body so only the length rule fires.
let mut s = three_member_spec();
let big = format!("/api/{}", "a".repeat(1020));
assert_eq!(big.len(), 1025);
s.entrada.as_mut().unwrap().paths = vec![big.clone()];
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
if path == &big && reason.contains("max length of 1024")),
"got {err:?}"
);
}
#[test]
fn entrada_path_max_length_validates() {
// 1024-byte path — exactly the Gateway API HTTPPathMatch.value
// maxLength cap. Boundary pin: drift in the cap surfaces here
// and at `rejects_entrada_path_too_long` simultaneously.
let mut s = three_member_spec();
let big = format!("/api/{}", "a".repeat(1019));
assert_eq!(big.len(), 1024);
s.entrada.as_mut().unwrap().paths = vec![big];
s.validate().unwrap();
}
#[test]
fn entrada_accepts_canonical_paths() {
// Positive-control sweep — every form the Gateway API
// apiserver accepts must round-trip through validate. Covers
// the root catch-all, plain paths, dot-prefixed segments
// (hidden-file-style, distinct from `.` and `..` segments
// which are rejected), digit-bearing segments, the canonical
// route-template `:param` form (`:` is RFC 3986 reserved-set
// valid in paths), trailing-slash form, percent-encoded
// segments, and an interior `..` *substring* (`/foo..bar` is
// not the `..` segment and is allowed).
for path in [
"/",
"/api/cart",
"/healthz",
"/api/.config",
"/v1/products",
"/products/:id",
"/api/cart/",
"/api/caf%C3%A9",
"/foo..bar",
"/...",
] {
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().paths = vec![path.into()];
s.validate()
.unwrap_or_else(|e| panic!("expected {path:?} to validate, got {e:?}"));
}
}
#[test]
fn entrada_path_empty_takes_precedence_over_invalid() {
// Ordering pin: `EntradaPathEmpty` is the more self-locating
// diagnostic on `""` and must lead — `validate_entrada_path`
// is only reached after the empty-check fires at the call
// site. (The predicate itself defends against direct
// invocation by returning the same error on `""`.)
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().paths = vec![String::new()];
assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
}
#[test]
fn entrada_path_not_absolute_takes_precedence_over_invalid() {
// Ordering pin: a path without a leading `/` surfaces the
// narrower `EntradaPathNotAbsolute` diagnostic first; the
// value-shape gate is only consulted on paths that already
// satisfy the absolute-prefix invariant.
let mut s = three_member_spec();
// `bad path` would fire the whitespace rule under the
// value-shape gate, but missing-leading-`/` is the more
// self-locating diagnostic.
s.entrada.as_mut().unwrap().paths = vec!["bad path".into()];
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "bad path"),
"got {err:?}"
);
}
#[test]
fn entrada_path_invalid_fires_before_duplicate_check() {
// Ordering pin: a malformed path on the *first* entry of a
// would-be duplicate pair fires the value-shape gate before
// the duplicate gate, mirroring the
// `placement_cluster_invalid_fires_before_duplicate_check`
// (6cbb900) pattern on the peer axis.
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().paths = vec!["/api?q".into(), "/api?q".into()];
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::EntradaPathInvalid { ref path, .. } if path == "/api?q"),
"got {err:?}"
);
}
#[test]
fn entrada_path_diagnostic_carries_offending_path() {
// Diagnostic-shape pin — the offending path + a non-empty
// reason flow through verbatim so the author can grep their
// caixa.lisp for `:paths` and fix it in one edit. Same shape
// as `entrada_host_diagnostic_carries_offending_host` (c7d05ec).
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().paths = vec!["/api?q=1".into()];
let err = s.validate().unwrap_err();
match err {
AplicacaoError::EntradaPathInvalid { path, reason } => {
assert_eq!(path, "/api?q=1");
assert!(!reason.is_empty(), "reason field must be non-empty");
}
other => panic!("expected EntradaPathInvalid, got {other:?}"),
}
}
#[test]
fn rejects_entrada_path_with_curly_brace_template_form() {
// Per-axis pin on the shared `is_gateway_api_http_path`
// reserved-byte arm: the canonical "I wrote an OpenAPI
// path-template `{id}` instead of the Gateway API `:id` form"
// footgun the K8s apiserver would otherwise catch at admission
// time on every `HTTPRoute.spec.rules[].matches[].path.value`
// landing site, far from the caixa.lisp. Surfaces as
// `EntradaPathInvalid` carrying the offending path verbatim
// plus the canonical `%7B`/`%7D` percent-encoding remediation
// — the substrate-side `gateway_api_http_path_rejects_every_
// reserved_printable_ascii_byte` predicate-level sweep pins the
// full eleven-byte set; this per-axis pin confirms the
// diagnostic flows through to the `EntradaPathInvalid` variant.
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().paths = vec!["/api/cart/{id}".into()];
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
if path == "/api/cart/{id}"
&& reason.contains("reserved character")
&& reason.contains("'{'")
&& reason.contains("%7B")),
"got {err:?}"
);
}
#[test]
fn rejects_http_contrato_endpoint_with_curly_brace_template_form() {
// Per-axis peer of `rejects_entrada_path_with_curly_brace_
// template_form` on the sibling `:contratos :endpoint` axis.
// Same shared `is_gateway_api_http_path` reserved-byte arm
// fires through `ContratoEndpointInvalid`, with the offending
// endpoint + `:de` + `:para` + reason flowing through verbatim.
// Pins that the lifted predicate's tightening lands on both
// caller axes simultaneously — one source of truth for the
// Gateway API HTTPPathMatch.value accepted set.
let err = contrato_endpoint_err("/api/cart/{id}");
assert!(
matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
if endpoint == "/api/cart/{id}"
&& reason.contains("reserved character")
&& reason.contains("'{'")
&& reason.contains("%7B")),
"got {err:?}"
);
}
// ── :entrada :host value-shape gate ──────────────────────────────
//
// Mirrors the `:entrada :paths` value-shape suite (eb3456d) on
// the sibling `:host` axis. Every authoring footgun the K8s
// Gateway API v1 apiserver would catch at admission time becomes
// a caixa-build-time `EntradaHostInvalid` with the offending
// `:host` named verbatim. Same diagnostic shape as
// `MembroVersaoInvalid` (9888b13).
#[test]
fn rejects_entrada_host_with_scheme() {
// Fail-before-pass-after pin — pre-gate codebases silently
// accepted `https://…` and the apiserver rejected it at apply
// time with no source citation.
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().host = "https://checkout.quero.cloud".into();
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
if host == "https://checkout.quero.cloud"),
"got {err:?}"
);
}
#[test]
fn rejects_entrada_host_with_port() {
// The `:8080` port suffix is the canonical "I forgot the port
// belongs in `:entrada :port`" footgun. The top-level `:` arm
// (introduced after the per-label loop-only impl silently
// surfaced a deep "label \"cloud:8080\" contains invalid
// character ':'" leak) names the canonical fix verbatim — the
// `:entrada :port` slot.
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
if host == "checkout.quero.cloud:8080"
&& reason.contains(":entrada :port")),
"got {err:?}"
);
}
#[test]
fn rejects_entrada_host_with_trailing_colon() {
// Trailing `:` (e.g. an in-progress `:host "example.com:"`
// edit) — the per-label loop would land it as a deep
// "label \"com:\" must start and end with an alphanumeric"
// / "contains invalid character ':'" leak. The top-level
// `:` arm pre-empts with the canonical `:port` slot
// diagnostic.
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:".into();
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
if host == "checkout.quero.cloud:"
&& reason.contains(":entrada :port")),
"got {err:?}"
);
}
#[test]
fn rejects_entrada_host_unbracketed_ipv6_literal() {
// Unbracketed IPv6 literal — Gateway API v1 Hostname forbids IP
// literals across the board (peer with `rejects_entrada_host_
// ipv4_literal` above for the four-label-all-digit IPv4 arm).
// Before this top-level `:` arm landed the per-label loop
// surfaced a single-label byte-class diagnostic that named the
// `:` byte but not the IP-literal prohibition. The top-level
// `:` arm names both the `:port` slot and the IP-literal
// prohibition verbatim, so an author whose `:host "2001:..."`
// value lands here gets a self-locating fix either way.
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().host = "2001:db8::1".into();
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
if host == "2001:db8::1"
&& reason.contains("IPv6")),
"got {err:?}"
);
}
#[test]
fn rejects_entrada_host_wildcard_with_port() {
// Wildcard host with port suffix — the `*.` strip and the
// per-label loop on `["foo", "quero", "cloud:8080"]` would
// surface the deep byte-class leak. The top-level `:` arm sits
// upstream of the `*.` strip, so it names the canonical `:port`
// fix verbatim regardless of whether the host is wildcard-led.
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().host = "*.quero.cloud:8080".into();
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
if host == "*.quero.cloud:8080"
&& reason.contains(":entrada :port")),
"got {err:?}"
);
}
#[test]
fn rejects_entrada_host_with_path() {
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().host = "checkout.quero.cloud/api".into();
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
if host == "checkout.quero.cloud/api"),
"got {err:?}"
);
}
#[test]
fn rejects_entrada_host_with_uppercase() {
// Gateway API regex is `[a-z0-9]…` strictly — uppercase is
// rejected, not silently lower-cased.
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().host = "Checkout.quero.cloud".into();
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
if reason.contains("uppercase")),
"got {err:?}"
);
}
#[test]
fn rejects_entrada_host_with_underscore() {
// RFC 1123 allows `[a-z0-9-]` only; underscore is the
// canonical "I'm thinking of HTTP cookies / SRV records" leak.
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().host = "checkout_app.quero.cloud".into();
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
if reason.contains('_')),
"got {err:?}"
);
}
#[test]
fn rejects_entrada_host_ipv4_literal() {
// Gateway API v1 explicitly forbids IP literals as Hostnames.
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().host = "10.0.0.1".into();
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
if reason.contains("IPv4")),
"got {err:?}"
);
}
#[test]
fn rejects_entrada_host_with_trailing_dot() {
// The Gateway API regex anchors at end-of-string with no
// trailing `.` allowance — the FQDN root-dot form is rejected.
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().host = "checkout.quero.cloud.".into();
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
if host == "checkout.quero.cloud."),
"got {err:?}"
);
}
#[test]
fn rejects_entrada_host_with_leading_dot() {
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().host = ".checkout.quero.cloud".into();
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
if reason.contains("empty label")),
"got {err:?}"
);
}
#[test]
fn rejects_entrada_host_with_consecutive_dots() {
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().host = "checkout..quero.cloud".into();
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
if reason.contains("empty label")),
"got {err:?}"
);
}
#[test]
fn rejects_entrada_host_with_leading_hyphen_label() {
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().host = "-checkout.quero.cloud".into();
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
if reason.contains("alphanumeric")),
"got {err:?}"
);
}
#[test]
fn rejects_entrada_host_with_trailing_hyphen_label() {
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().host = "checkout-.quero.cloud".into();
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
if reason.contains("alphanumeric")),
"got {err:?}"
);
}
#[test]
fn rejects_entrada_host_with_inner_wildcard() {
// Gateway API allows `*` only as the first label (`*.foo`);
// any inner or trailing `*` is rejected.
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().host = "checkout.*.quero.cloud".into();
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
if reason.contains("wildcard")),
"got {err:?}"
);
}
#[test]
fn rejects_entrada_host_bare_wildcard() {
// `*.` with no domain is meaningless; Gateway API rejects it.
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().host = "*.".into();
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
if reason.contains("wildcard")),
"got {err:?}"
);
}
#[test]
fn rejects_entrada_host_with_whitespace() {
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
if reason.contains("whitespace")),
"got {err:?}"
);
}
#[test]
fn rejects_entrada_host_space_names_offending_byte() {
// Embedded space in the `:entrada :host` axis surfaces the
// byte-naming diagnostic through the lifted
// `find_ascii_whitespace_byte` predicate. Peer with the
// sibling `parse_rejects_leading_whitespace` pins on
// `supervisor::duration_codec` (a7ae622) — same "the
// diagnostic carries the offending byte's `0x{b:02x}` shape"
// discipline extended from the shared duration codec to the
// Gateway API v1 Hostname axis.
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
let err = s.validate().unwrap_err();
let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
panic!("expected EntradaHostInvalid, got {err:?}");
};
assert!(
reason.contains("ASCII whitespace byte"),
"expected byte-naming diagnostic, got {reason:?}"
);
assert!(
reason.contains("0x20"),
"expected offending space byte 0x20, got {reason:?}"
);
}
#[test]
fn rejects_entrada_host_tab_names_offending_byte() {
// Embedded tab byte in the `:entrada :host` axis — the
// canonical paste-from-YAML-block-scalar / paste-from-
// indented-doc footgun. Pins that the lifted predicate covers
// the full ASCII-whitespace set (`u8::is_ascii_whitespace` —
// space `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d`),
// not just the leading-space case the pre-lift `.bytes().any`
// arm's opaque "must not contain whitespace" reason already
// covered. Peer with `parse_rejects_tab_byte` on
// `supervisor::duration_codec` (a7ae622).
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().host = "checkout.\tquero.cloud".into();
let err = s.validate().unwrap_err();
let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
panic!("expected EntradaHostInvalid, got {err:?}");
};
assert!(
reason.contains("ASCII whitespace byte"),
"expected byte-naming diagnostic, got {reason:?}"
);
assert!(
reason.contains("0x09"),
"expected offending tab byte 0x09, got {reason:?}"
);
}
#[test]
fn rejects_entrada_host_lf_names_offending_byte() {
// Embedded LF byte in the `:entrada :host` axis — the
// canonical paste-from-shell-heredoc / paste-from-multiline-
// doc footgun the caixa-mesh YAML emitter would silently
// reinterpret at the Gateway API v1 HTTPRoute admission
// layer (an embedded LF byte in a YAML plain scalar either
// truncates the value at the emitter or crashes the parser
// on the k8s-apiserver side). Pins the third representative
// of the full ASCII-whitespace set through the shared
// predicate.
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().host = "checkout\n.quero.cloud".into();
let err = s.validate().unwrap_err();
let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
panic!("expected EntradaHostInvalid, got {err:?}");
};
assert!(
reason.contains("ASCII whitespace byte"),
"expected byte-naming diagnostic, got {reason:?}"
);
assert!(
reason.contains("0x0a"),
"expected offending LF byte 0x0a, got {reason:?}"
);
}
#[test]
fn rejects_entrada_host_nbsp_names_offending_codepoint() {
// Leading NBSP (`U+00A0`, `\u{00A0}`) in the `:entrada :host`
// axis — the canonical paste-from-typography /
// paste-from-word-processor footgun. Before the non-ASCII
// Unicode `White_Space` scan lifted through the shared
// `find_non_ascii_whitespace_char` predicate, the UTF-8 bytes
// of NBSP (`0xC2 0xA0`) survived the ASCII byte-scan (neither
// `0xC2` nor `0xA0` is `u8::is_ascii_whitespace`) and landed
// on the per-label `bytes[0].is_ascii_alphanumeric()` arm
// with the far-from-source `label "…" must start and end
// with an alphanumeric` diagnostic — burying the
// paste-from-typography origin under a label-shape leak.
// Peer with the sibling non-ASCII-whitespace pins at
// `limits::parse_byte_size` (`parse_byte_size_rejects_leading_nbsp`
// — 1b75b38), `limits::parse_duration`,
// `limits::parse_millicores`, and the shared duration codec
// — same "the diagnostic carries the offending Unicode
// codepoint's `U+XXXX` shape" discipline extended from every
// typed-magnitude codec to the Gateway API v1 Hostname axis.
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().host = "\u{00A0}checkout.quero.cloud".into();
let err = s.validate().unwrap_err();
let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
panic!("expected EntradaHostInvalid, got {err:?}");
};
assert!(
reason.contains("non-ASCII Unicode whitespace character"),
"expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
);
assert!(
reason.contains("U+00A0"),
"expected offending NBSP codepoint U+00A0, got {reason:?}"
);
}
#[test]
fn rejects_entrada_host_line_separator_names_offending_codepoint() {
// Trailing LINE SEPARATOR (`U+2028`, `\u{2028}`) in the
// `:entrada :host` axis — the canonical paste-from-web-doc /
// paste-from-published-HTML footgun. `char::is_whitespace`
// returns true for `U+2028` per the Unicode `White_Space`
// property, so `str::trim` at any downstream site would
// silently strip it — same drift class as NBSP but on a
// different codepoint region. Pins the second representative
// (non-Latin-1 `char::is_whitespace` member) through the
// shared predicate. Peer with
// `parse_byte_size_rejects_internal_line_separator` on
// `limits::parse_byte_size` (1b75b38).
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().host = "checkout.quero.cloud\u{2028}".into();
let err = s.validate().unwrap_err();
let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
panic!("expected EntradaHostInvalid, got {err:?}");
};
assert!(
reason.contains("non-ASCII Unicode whitespace character"),
"expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
);
assert!(
reason.contains("U+2028"),
"expected offending LINE SEPARATOR codepoint U+2028, got {reason:?}"
);
}
#[test]
fn rejects_entrada_host_ideographic_space_names_offending_codepoint() {
// Embedded IDEOGRAPHIC SPACE (`U+3000`, `\u{3000}`) between
// labels in the `:entrada :host` axis — the canonical
// paste-from-CJK-typography footgun (CJK IMEs default to
// full-width whitespace when the space bar is pressed in
// Japanese / Chinese input modes). Pins the third
// representative of the non-ASCII Unicode `White_Space` set
// through the shared predicate: the CJK block, distinct from
// the Latin-1 NBSP `U+00A0` and the punctuation-region LINE
// SEPARATOR `U+2028` — covering the same axis breadth the
// sibling `parse_byte_size_rejects_trailing_ideographic_space`
// (1b75b38) pins on `limits::parse_byte_size`.
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().host = "checkout\u{3000}.quero.cloud".into();
let err = s.validate().unwrap_err();
let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
panic!("expected EntradaHostInvalid, got {err:?}");
};
assert!(
reason.contains("non-ASCII Unicode whitespace character"),
"expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
);
assert!(
reason.contains("U+3000"),
"expected offending IDEOGRAPHIC SPACE codepoint U+3000, got {reason:?}"
);
}
#[test]
fn rejects_entrada_host_too_long() {
// Total length cap = 253; build a 254-byte host out of two
// 63-byte labels + one 62-byte label + dots.
let mut s = three_member_spec();
let big = format!(
"{}.{}.{}.{}",
"a".repeat(63),
"b".repeat(63),
"c".repeat(63),
"d".repeat(254 - 63 * 3 - 3)
);
assert_eq!(big.len(), 254);
s.entrada.as_mut().unwrap().host = big;
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
if reason.contains("max length of 253")),
"got {err:?}"
);
}
#[test]
fn rejects_entrada_host_label_too_long() {
let mut s = three_member_spec();
// 64-byte label — one over the per-label cap.
s.entrada.as_mut().unwrap().host = format!("{}.quero.cloud", "x".repeat(64));
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
if reason.contains("label max length of 63")),
"got {err:?}"
);
}
#[test]
fn entrada_host_diagnostic_carries_offending_host() {
// Diagnostic-shape pin — the offending host + a non-empty
// reason flow through verbatim so the author can grep their
// caixa.lisp for `:host "<host>"` and fix it in one edit.
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
let err = s.validate().unwrap_err();
match err {
AplicacaoError::EntradaHostInvalid { host, reason } => {
assert_eq!(host, "checkout.quero.cloud:8080");
assert!(!reason.is_empty(), "reason field must be non-empty");
}
other => panic!("expected EntradaHostInvalid, got {other:?}"),
}
}
// Equivalence pin for the [`AplicacaoError::entrada_host_invalid`]
// substrate primitive that folds the fourteen
// `AplicacaoError::EntradaHostInvalid { host: host.to_string(),
// reason: <expr> }` wire-up sites at [`validate_entrada_host`] onto
// one dispatch — peer with the sixteen equivalence pins the
// [`crate::LayoutError`] `_violation` constructor family carries in
// `layout::tests::*_ctor_matches_struct_literal_wrap` (131ca0d). The
// fixture host + reason are fixed `&'static str`s so both fields of
// both constructed variants pin verbatim: the `host` axis is pinned
// through the shared `host.to_string()` wrap (the ctor's uniform
// one-slot construction) and the `reason` axis is pinned through
// the shared `reason.into()` wrap (the ctor's `impl Into<String>`
// routing). Any future regression on the lift (an extra field
// introduced without updating the ctor, a diverging string
// conversion at either arm) surfaces at this pin's diagnostic
// rather than at a per-wire-up struct-literal reintroduction.
#[test]
fn entrada_host_invalid_ctor_matches_struct_literal_wrap() {
let host = "checkout.quero.cloud:8080";
let reason = "sample reason text";
assert_eq!(
AplicacaoError::entrada_host_invalid(host, reason),
AplicacaoError::EntradaHostInvalid {
host: host.to_string(),
reason: reason.to_string(),
},
"generated constructor must produce byte-equal AplicacaoError to open-coded struct-literal wrap",
);
}
// Routing pin — the ctor's `host: &str` argument threads through
// `.to_string()` verbatim on the `host` field, so the constructed
// variant carries the offending host bytes without any wrapper-
// side transformation (no `.to_ascii_lowercase()` normalization,
// no `.trim()` strip, no truncation) — the same "diagnostic carries
// the offending value verbatim so the author can grep their
// caixa.lisp" discipline every peer typed-slot ctor at this
// altitude carries.
#[test]
fn entrada_host_invalid_ctor_routes_host_through_to_string() {
// Uppercase + trailing whitespace + port suffix — three
// wrapper-side transformations the ctor must *not* apply.
let host = " Checkout.quero.CLOUD:8080 ";
let err = AplicacaoError::entrada_host_invalid(host, "sample");
match err {
AplicacaoError::EntradaHostInvalid { host: h, .. } => {
assert_eq!(h, host, "host must thread through `.to_string()` verbatim");
}
other => panic!("expected EntradaHostInvalid, got {other:?}"),
}
}
// Routing pin — the ctor's `reason: impl Into<String>` accepts both
// `&str` literals and `format!(…)` outputs identically and both
// route through `Into::into` verbatim onto the `reason` field.
// Pins both codepaths against the same host to prove the two
// shapes the fourteen wire-up sites use at their per-arm diagnostic
// (ten `&str` literals — some with `.to_string()` at the caller,
// some without — plus four `format!(…)` outputs) each produce
// byte-equal `reason` fields against the same offending host.
#[test]
fn entrada_host_invalid_ctor_routes_reason_through_into() {
let host = "checkout.quero.cloud";
// `&str` literal — the ctor's `impl Into<String>` accepts it
// without a caller-side `.to_string()`.
let from_literal = AplicacaoError::entrada_host_invalid(host, "literal reason text");
// Owned `String` from `format!` — the peer `format!(…)`-shaped
// wire-up arm.
let from_format =
AplicacaoError::entrada_host_invalid(host, format!("{} reason text", "literal"));
// `String` from `.to_string()` on a literal — the peer
// `"literal".to_string()`-shaped wire-up arm the pre-lift
// sites carried.
let from_to_string =
AplicacaoError::entrada_host_invalid(host, "literal reason text".to_string());
match (&from_literal, &from_format, &from_to_string) {
(
AplicacaoError::EntradaHostInvalid {
reason: r_lit,
host: h_lit,
},
AplicacaoError::EntradaHostInvalid {
reason: r_fmt,
host: h_fmt,
},
AplicacaoError::EntradaHostInvalid {
reason: r_ts,
host: h_ts,
},
) => {
assert_eq!(r_lit, "literal reason text");
assert_eq!(r_fmt, "literal reason text");
assert_eq!(r_ts, "literal reason text");
assert_eq!(h_lit, host);
assert_eq!(h_fmt, host);
assert_eq!(h_ts, host);
}
_ => panic!("expected three EntradaHostInvalid variants"),
}
// Cross-arm equivalence — the three shapes must produce
// byte-equal `AplicacaoError` values, so the fourteen wire-up
// sites' mixed per-arm shapes fold onto one canonical form.
assert_eq!(from_literal, from_format);
assert_eq!(from_literal, from_to_string);
}
// Equivalence pins for the six sibling
// [`aplicacao_field_reason_ctors!`]-generated constructors that
// fold the peer `{ <field>: String, reason: String }` variants
// onto the same substrate-primitive family
// `entrada_host_invalid` (17dd504) already carries pins for.
// Each ctor's fixture pair (a fixed `&'static str` value and a
// fixed `&'static str` reason) pins both fields verbatim so any
// future regression on the macro (an extra field introduced
// without updating the macro, a diverging string conversion at
// either arm, a field-name typo on one variant that dropped it
// off the shared shape) surfaces at the affected variant's pin
// rather than at a per-wire-up struct-literal reintroduction. Peer
// discipline of the sixteen `LayoutError` _violation ctor pins in
// `layout::tests::*_ctor_matches_struct_literal_wrap` (131ca0d)
// and the paired
// `contrato_wrong_target_ctor_matches_struct_literal_wrap` /
// `contrato_missing_target_ctor_matches_struct_literal_wrap`
// (14b81d5) / `contrato_endpoint_empty_ctor_matches_struct_literal_wrap`
// (8580068) equivalence pins on the sibling `AplicacaoError`
// ctor macros.
#[test]
fn membro_caixa_invalid_ctor_matches_struct_literal_wrap() {
let caixa = "cart-svc";
let reason = "sample reason text";
assert_eq!(
AplicacaoError::membro_caixa_invalid(caixa, reason),
AplicacaoError::MembroCaixaInvalid {
caixa: caixa.to_string(),
reason: reason.to_string(),
},
);
}
#[test]
fn entrada_para_invalid_ctor_matches_struct_literal_wrap() {
let para = "checkout";
let reason = "sample reason text";
assert_eq!(
AplicacaoError::entrada_para_invalid(para, reason),
AplicacaoError::EntradaParaInvalid {
para: para.to_string(),
reason: reason.to_string(),
},
);
}
#[test]
fn entrada_path_invalid_ctor_matches_struct_literal_wrap() {
let path = "/api/cart";
let reason = "sample reason text";
assert_eq!(
AplicacaoError::entrada_path_invalid(path, reason),
AplicacaoError::EntradaPathInvalid {
path: path.to_string(),
reason: reason.to_string(),
},
);
}
#[test]
fn placement_cluster_invalid_ctor_matches_struct_literal_wrap() {
let cluster = "rio";
let reason = "sample reason text";
assert_eq!(
AplicacaoError::placement_cluster_invalid(cluster, reason),
AplicacaoError::PlacementClusterInvalid {
cluster: cluster.to_string(),
reason: reason.to_string(),
},
);
}
#[test]
fn placement_affinity_invalid_ctor_matches_struct_literal_wrap() {
let affinity = "data-locality";
let reason = "sample reason text";
assert_eq!(
AplicacaoError::placement_affinity_invalid(affinity, reason),
AplicacaoError::PlacementAffinityInvalid {
affinity: affinity.to_string(),
reason: reason.to_string(),
},
);
}
#[test]
fn shard_key_invalid_ctor_matches_struct_literal_wrap() {
let shard_key = "tenantId";
let reason = "sample reason text";
assert_eq!(
AplicacaoError::shard_key_invalid(shard_key, reason),
AplicacaoError::ShardKeyInvalid {
shard_key: shard_key.to_string(),
reason: reason.to_string(),
},
);
}
// Pin the three-slot per-`:contratos <slot>` sibling of the
// two-slot `aplicacao_field_reason_ctors!` family — the sole
// per-axis ctor carrying the extra `slot: &'static str` axis-tag
// distinguishing the two-arm `:de` / `:para` cascade. Sweeps both
// canonical author-side slot tags through the ctor and asserts
// byte-equality against the pre-lift struct-literal shape so no
// per-arm wrapper transformation drifts in against the sole
// in-crate wire-up.
#[test]
fn contrato_caixa_invalid_ctor_matches_struct_literal_wrap() {
let caixa = "cart-svc";
let reason = "sample reason text";
for slot in [
crate::render::CONTRATO_AUTHOR_KEY_DE,
crate::render::CONTRATO_AUTHOR_KEY_PARA,
] {
assert_eq!(
AplicacaoError::contrato_caixa_invalid(slot, caixa, reason),
AplicacaoError::ContratoCaixaInvalid {
slot,
caixa: caixa.to_string(),
reason: reason.to_string(),
},
);
}
}
// The `reason: impl Into<String>` bound accepts both a `&str`
// literal and a `format!(…)` owned-`String` output verbatim,
// matching the peer `aplicacao_field_reason_ctors!` family's
// reason-axis invariance so the sole in-crate wire-up's
// `require_valid_dns_1123_label`-delivered owned-`String` return
// and any future `&str` literal caller land on the same variant.
#[test]
fn contrato_caixa_invalid_ctor_routes_reason_through_into_uniformly() {
let via_literal = "literal reason text";
let via_format = format!("{} reason text", "literal");
for slot in [
crate::render::CONTRATO_AUTHOR_KEY_DE,
crate::render::CONTRATO_AUTHOR_KEY_PARA,
] {
assert_eq!(
AplicacaoError::contrato_caixa_invalid(slot, "c", via_literal),
AplicacaoError::contrato_caixa_invalid(slot, "c", via_format.clone()),
);
}
}
// Pin the paired one-slot empty-arm sibling of the three-slot
// `contrato_caixa_invalid` per-`:contratos <slot>` ctor — the sole
// closure-form empty-arm on the shared
// [`crate::render::require_valid_dns_1123_label`] two-closure
// cascade at [`validate_contrato_caixa`], carrying the same
// `slot: &'static str` axis-tag that distinguishes the two-arm
// `:de` / `:para` cascade. Sweeps both canonical author-side slot
// tags through the ctor and asserts byte-equality against the
// pre-lift struct-literal shape so no per-arm wrapper transformation
// drifts in against the sole in-crate wire-up. Peer of the sibling
// [`crate::behavior::BehaviorError::empty_path`] one-slot
// `{ slot: &'static str }` equivalence pin on the paired
// `BehaviorError` envelope's four-arm sandboxed-lisp-path cascade
// ([`crate::render::require_sandboxed_lisp_path`]) — extended here
// onto the sibling `AplicacaoError` envelope's two-arm
// DNS-1123-label cascade so both empty-arm axes carry a
// substrate-primitive equivalence pin rather than the pre-lift
// hand-open struct-literal.
#[test]
fn contrato_caixa_empty_ctor_matches_struct_literal_wrap() {
for slot in [
crate::render::CONTRATO_AUTHOR_KEY_DE,
crate::render::CONTRATO_AUTHOR_KEY_PARA,
] {
assert_eq!(
AplicacaoError::contrato_caixa_empty(slot),
AplicacaoError::ContratoCaixaEmpty { slot },
"generated contrato_caixa_empty ctor must produce \
byte-equal AplicacaoError to the open-coded \
struct-literal wrap on the same &'static str fixture \
(slot = {slot:?})",
);
}
}
// Cross-axis pin: sweep the constructor's single input axis (`slot:
// &'static str`) through every canonical
// [`crate::render::CONTRATO_AUTHOR_KEY_*`] tag *plus* a non-canonical
// `&'static str` value (`":phantom"`), so any wrapper-side lowercase
// / trim / truncate / re-order / fixed-slot substitution on the
// one-field construction surfaces here rather than at a downstream
// diagnostic-shape mismatch. The non-canonical arm proves the
// constructor does not silently clamp `slot` to the `:de` /
// `:para` roster (a future third `:contratos <slot>` axis lands on
// this ctor without a per-arm rewrite), matching the discipline the
// sibling [`Self::contrato_caixa_invalid`] ctor's tri-slot sweep
// establishes at
// `contrato_caixa_invalid_ctor_matches_struct_literal_wrap`
// (18114) on the paired three-slot invalid-arm envelope.
#[test]
fn contrato_caixa_empty_ctor_routes_slot_verbatim_across_both_axes() {
for slot in [
crate::render::CONTRATO_AUTHOR_KEY_DE,
crate::render::CONTRATO_AUTHOR_KEY_PARA,
":phantom",
] {
assert_eq!(
AplicacaoError::contrato_caixa_empty(slot),
AplicacaoError::ContratoCaixaEmpty { slot },
);
}
}
// End-to-end wire-up pin: `AplicacaoSpec::validate` on an empty
// `:contratos :de` value must surface a diagnostic byte-equal to
// the substrate primitive `AplicacaoError::contrato_caixa_empty`'s
// output on the same slot fixture. Proves the sole in-crate
// closure-form wire-up inside [`validate_contrato_caixa`]'s
// [`crate::render::require_valid_dns_1123_label`] empty-arm routes
// through the ctor rather than the pre-lift open-coded
// struct-literal block, matching the sibling per-arm
// `end_to_end_wire_up_routes_through_ctor` discipline the peer
// per-envelope ctor pins the recent
// [`Self::policy_rate_limit_cannot_admit_retry_burst`] (9703bd6),
// [`Self::policy_breaker_trips_before_retries_exhausted`] (f54c539),
// [`Self::policy_breaker_cannot_trip_under_rate_limit`] (6bb4e46),
// and [`Self::policy_breaker_window_below_timeout`] (9b30c07)
// cross-axis Policy* variants carry. Complements the two axis-tag
// arms already pinned above the `:contratos` value-shape gate
// block (`rejects_contrato_de_empty`, `rejects_contrato_para_empty`)
// which anchor via the shape; this pin additionally verifies the
// ctor is the exclusive construction path.
#[test]
fn contrato_caixa_empty_end_to_end_wire_up_routes_through_ctor() {
// Empty `:de` — the sole in-crate wire-up hits the empty-arm
// closure at the first `:contratos` value-shape gate, threading
// the `CONTRATO_AUTHOR_KEY_DE` label through the ctor.
let mut s_de = three_member_spec();
s_de.contratos.push(contract_http("", "catalog", "/x"));
assert_eq!(
s_de.validate().unwrap_err(),
AplicacaoError::contrato_caixa_empty(crate::render::CONTRATO_AUTHOR_KEY_DE),
);
// Symmetric arm: an empty `:para` on a valid `:de` fires the
// same closure with the `CONTRATO_AUTHOR_KEY_PARA` label.
let mut s_para = three_member_spec();
s_para.contratos.push(contract_http("cart", "", "/x"));
assert_eq!(
s_para.validate().unwrap_err(),
AplicacaoError::contrato_caixa_empty(crate::render::CONTRATO_AUTHOR_KEY_PARA),
);
}
// Cross-family invariance pin — the six sibling ctors and
// `entrada_host_invalid` all route `reason: impl Into<String>` +
// `<field>: &str` verbatim onto their respective typed variants
// through the shared [`aplicacao_field_reason_ctors!`] macro.
// Sweeps a fixture pair (`&str` literal, `format!` output) against
// every ctor to pin that no per-arm wrapper transformation drifted
// in against the uniform macro-generated body.
#[test]
fn aplicacao_field_reason_ctors_route_reason_through_into_uniformly() {
let via_literal = "literal reason text";
let via_format = format!("{} reason text", "literal");
assert_eq!(
AplicacaoError::membro_caixa_invalid("m", via_literal),
AplicacaoError::membro_caixa_invalid("m", via_format.clone()),
);
assert_eq!(
AplicacaoError::entrada_para_invalid("p", via_literal),
AplicacaoError::entrada_para_invalid("p", via_format.clone()),
);
assert_eq!(
AplicacaoError::entrada_path_invalid("/a", via_literal),
AplicacaoError::entrada_path_invalid("/a", via_format.clone()),
);
assert_eq!(
AplicacaoError::placement_cluster_invalid("c", via_literal),
AplicacaoError::placement_cluster_invalid("c", via_format.clone()),
);
assert_eq!(
AplicacaoError::placement_affinity_invalid("a", via_literal),
AplicacaoError::placement_affinity_invalid("a", via_format.clone()),
);
assert_eq!(
AplicacaoError::shard_key_invalid("k", via_literal),
AplicacaoError::shard_key_invalid("k", via_format.clone()),
);
assert_eq!(
AplicacaoError::entrada_host_invalid("h", via_literal),
AplicacaoError::entrada_host_invalid("h", via_format),
);
}
#[test]
fn entrada_host_empty_takes_precedence_over_invalid() {
// Ordering pin: `EmptyEntradaHost` is the more self-locating
// diagnostic on `""` and must lead — `validate_entrada_host`
// is only reached after the empty-check fires at the call
// site. (The predicate itself defends against direct
// invocation by returning the same error on `""`.)
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().host = String::new();
assert_eq!(s.validate().unwrap_err(), AplicacaoError::EmptyEntradaHost);
}
#[test]
fn entrada_host_member_missing_takes_precedence_over_host_invalid() {
// Ordering pin: a missing :para member is the more
// self-locating diagnostic and fires before the host gate.
let mut s = three_member_spec();
let e = s.entrada.as_mut().unwrap();
e.para = "ghost".into();
e.host = "BAD HOST".into();
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::EntradaMemberMissing { ref para } if para == "ghost"),
"got {err:?}"
);
}
#[test]
fn entrada_host_invalid_fires_before_port_zero() {
// Ordering pin: the host gate fires before the port gate so
// a malformed host is named even when the port is also wrong.
let mut s = three_member_spec();
let e = s.entrada.as_mut().unwrap();
e.host = "Checkout.quero.cloud".into();
e.port = 0;
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
if host == "Checkout.quero.cloud"),
"got {err:?}"
);
}
#[test]
fn entrada_accepts_canonical_hosts() {
// Positive-control sweep — every form the Gateway API
// apiserver accepts must round-trip through validate. Covers
// a plain DNS subdomain, a leading wildcard, a single-label
// host (cluster-internal), a max-length-edge label, a
// hyphen-bearing label, and a Punycode IDN label.
for host in [
"checkout.quero.cloud",
"*.quero.cloud",
"checkout",
// 63-byte label — exactly the per-label cap.
"abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0.quero.cloud",
"foo-bar.quero.cloud",
// Punycode IDN — valid because the author pre-encoded.
"xn--bcher-kva.example.com",
] {
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().host = host.into();
s.validate()
.unwrap_or_else(|e| panic!("expected {host:?} to validate, got {e:?}"));
}
}
#[test]
fn entrada_host_max_length_validates() {
// 253-byte host is the cap exactly — must validate. Build a
// 253-byte host out of three 63-byte labels + one 61-byte
// label + 3 dots = 252 bytes, then pad one byte to 253.
let mut s = three_member_spec();
let host = format!(
"{}.{}.{}.{}",
"a".repeat(63),
"b".repeat(63),
"c".repeat(63),
"d".repeat(253 - 63 * 3 - 3)
);
assert_eq!(host.len(), 253);
s.entrada.as_mut().unwrap().host = host;
s.validate().unwrap();
}
#[test]
fn entrada_host_total_length_cap_threads_lifted_render_const() {
// Cross-crate-side pin: the aplicacao-side `:entrada :host`
// total-length gate now reads the K8s Gateway API v1 Hostname
// `maxLength: 253` cap from the lifted
// [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] canonical source
// of truth — the same constant every future Gateway-API-Hostname
// landing site (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
// materializer's per-host validator, the future per-`Certificate`
// SAN emitter for cert-manager, the multi-`:entrada`
// host-collision gate when M4 lands `:entrada` as a `Vec`) reads
// from. Before the lift, the aplicacao-side reader consumed a
// private const alias `ENTRADA_HOST_MAX_LEN` sitting at the same
// 253-byte value as the peer render-side canonical bounds
// ([`GATEWAY_API_HTTP_PATH_MAX_LEN`], [`DNS_1123_LABEL_MAX_LEN`],
// [`NATS_SUBJECT_MAX_LEN`], [`WASI_KV_SLOT_MAX_LEN`],
// [`WIT_IDENT_MAX_LEN`]) but structurally split from them at the
// module boundary — a future 253-byte drift on either side would
// silently split into two axes' worth of admission-schema mismatch
// without a build-time signal. Pin the cap through a fresh 254-
// byte host that hits the total-length arm, then read the reason
// for the exact byte count the shared constant carries: any future
// regression on the lift (a private alias reintroduced, a hard-
// coded literal at the arm, a mismatch between the aplicacao-side
// and render-side canonicals) surfaces as this pin's diagnostic
// failing to match, not as a per-cluster admission rejection far
// from the caixa.lisp source line.
let mut s = three_member_spec();
let over_cap = format!(
"{}.{}.{}.{}",
"a".repeat(63),
"b".repeat(63),
"c".repeat(63),
"d".repeat(crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1 - 63 * 3 - 3)
);
assert_eq!(
over_cap.len(),
crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1
);
s.entrada.as_mut().unwrap().host = over_cap;
let err = s.validate().unwrap_err();
match err {
AplicacaoError::EntradaHostInvalid { reason, .. } => {
let needle = format!(
"max length of {} bytes",
crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
);
assert!(
reason.contains(&needle),
"diagnostic must name the lifted \
GATEWAY_API_HOSTNAME_MAX_LEN cap verbatim, got: {reason:?}",
);
}
other => panic!("expected EntradaHostInvalid, got {other:?}"),
}
}
#[test]
fn entrada_host_per_label_cap_threads_lifted_dns_1123_const() {
// Peer of [`entrada_host_total_length_cap_threads_lifted_render_const`]
// on the per-label-cap axis. Before the lift, the aplicacao-side
// per-label arm consumed a private const alias
// `ENTRADA_HOST_LABEL_MAX_LEN` sitting at the same 63-byte value
// as [`crate::render::DNS_1123_LABEL_MAX_LEN`] but structurally
// split from it at the module boundary — every `.`-separated
// label in a Gateway API v1 Hostname is a DNS-1123 label under
// the apiserver's OpenAPI regex `[a-z0-9]([-a-z0-9]*[a-z0-9])?`,
// so the private alias's 63 and the canonical const's 63 were
// pinning the same underlying rule twice. Pin the cap through a
// 64-byte label that hits the per-label arm, then read the reason
// for the exact byte count the shared constant carries: any
// future drift on either side (a private alias reintroduced, a
// hard-coded literal at the arm, a mismatch between the two
// 63-byte pins) surfaces at this pin's diagnostic rather than at
// a per-cluster admission rejection whose "field is invalid"
// opacity misframes the root cause.
let mut s = three_member_spec();
let over_cap_label = format!(
"{}.quero.cloud",
"x".repeat(crate::render::DNS_1123_LABEL_MAX_LEN + 1),
);
s.entrada.as_mut().unwrap().host = over_cap_label;
let err = s.validate().unwrap_err();
match err {
AplicacaoError::EntradaHostInvalid { reason, .. } => {
let needle = format!(
"label max length of {} bytes",
crate::render::DNS_1123_LABEL_MAX_LEN,
);
assert!(
reason.contains(&needle),
"diagnostic must name the lifted DNS_1123_LABEL_MAX_LEN \
cap verbatim on the per-label arm, got: {reason:?}",
);
}
other => panic!("expected EntradaHostInvalid, got {other:?}"),
}
}
#[test]
fn entrada_with_empty_paths_validates() {
// Empty `:paths` is the documented "match every path" form;
// caixa-mesh's gateway_routes synthesizes a `/` catch-all.
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().paths = vec![];
s.validate().unwrap();
}
#[test]
fn entrada_root_path_validates() {
// The author-supplied bare-root `:entrada :paths` entry is the
// same byte-shape the peer emit-side catch-all constant
// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] renders when
// the author's `:paths` list is empty — sweeping the test-side
// probe literal onto the lifted const closes the two-axis pin
// (author-side admit + emit-side canonical fallback) around
// one `&'static str`, so a future rebrand of the catch-all
// reaches both consumers by construction. Peer to
// [`crate::tests::gateway_api_default_http_route_path_pins_canonical_root_literal`]
// on the canonical-literal pin surface.
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().paths = vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH.into()];
s.validate().unwrap();
}
#[test]
fn placement_strategy_variants_round_trip() {
for s in [
PlacementStrategy::SingleNode,
PlacementStrategy::Replicated,
PlacementStrategy::Sharded,
] {
let p = Placement {
estrategia: s,
clusters: vec!["rio".into()],
affinity: None,
// Route the paired `:shard-key` fixture-builder through the
// typed cross-slot invariant predicate
// [`PlacementStrategy::requires_shard_key`] rather than the
// [`gen_platform::IsVariant`]-derived [`Self::is_sharded`]
// arm-identity predicate — the two answer the same
// question under today's closed accept-set but a future
// arm addition that consumed `:shard-key` under a
// non-`Sharded` name would silently mis-attach the
// fixture's `:shard-key` if the builder read through the
// arm-identity predicate. The cross-slot-invariant
// predicate migrates through one caixa-core edit on any
// future arm addition; the fixture keeps producing a
// `validate()`-passing round-trip by construction.
shard_key: if s.requires_shard_key() {
Some("$key".into())
} else {
None
},
};
let json = serde_json::to_string(&p).unwrap();
let back: Placement = serde_json::from_str(&json).unwrap();
assert_eq!(back, p);
}
}
#[test]
fn placement_strategy_variants_serialize_to_lifted_scalar_values() {
// The fail-before-pass-after pin: pre-lift there was no
// single-source binding between the [`PlacementStrategy`]
// variant name the `Serialize` derive emits and the byte-
// string every downstream cluster-side dispatcher (the
// `lareira-fleet-programs` aggregator's per-entry strategy
// branch, the future `app-operator` reconciler, the M3
// Adaptive compression pass's per-strategy weighting) probes
// verbatim under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. A
// future `#[serde(rename_all = "kebab-case")]` attribute on
// the enum — or a variant rename in the source — would
// silently rebrand the emitted scalar under one spelling
// while every downstream dispatcher still probed the other,
// with the failure surfacing at the aggregator's dispatch
// step or the operator's reconcile posture (workloads coming
// up under the `default()` `Replicated` arm rather than the
// typed slot's declared strategy) far from the source
// rebrand commit and with no field naming the drift. Pinning
// the two paths (the `Serialize` derive's serialized string
// AND the [`PlacementStrategy::as_str`] helper) to the same
// three lifted [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
// / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] byte-strings
// makes any future drift on either endpoint fail here at
// caixa-core build time.
for (variant, expected) in [
(
PlacementStrategy::SingleNode,
crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
),
(
PlacementStrategy::Replicated,
crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
),
(
PlacementStrategy::Sharded,
crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
),
] {
let json = serde_json::to_string(&variant).unwrap();
assert_eq!(
json,
format!("\"{expected}\""),
"PlacementStrategy::{variant:?} must serialize to {expected:?}"
);
assert_eq!(
variant.as_str(),
expected,
"PlacementStrategy::{variant:?}.as_str() must return the lifted \
M3_PLACEMENT_ESTRATEGIA_* constant"
);
}
}
#[test]
fn m3_placement_estrategia_consts_are_pairwise_distinct() {
// Cross-arm drift-detection pin on the M3
// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
// [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] closed-set
// scalar-value pentad: a future collapse of two canonical
// variant byte-strings onto the same value (an accidental
// copy-paste flip of
// [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to also
// read `"SingleNode"`, a per-arm rebrand that lands one const
// without touching its paired peer) would silently reroute
// every downstream operator's per-strategy dispatch onto the
// sibling arm's reconcile branch and pass every
// propagation-probe test that expected only the stale arm's
// value — a `Replicated`-declared Aplicacao would come up
// under the `SingleNode` primary-and-standby reconcile
// posture, so every-cluster active-active workload would
// silently collapse onto one-cluster-runs-at-a-time takeover
// semantics against its declared strategy, with no field
// naming the strategy-value drift root cause. Peer of the
// sibling
// [`crate::supervisor::tests::supervisor_estrategia_consts_are_pairwise_distinct`]
// (09ffb2d) /
// [`crate::supervisor::tests::supervisor_child_restart_consts_are_pairwise_distinct`]
// (ccdf955) /
// [`crate::kind::tests::caixa_kind_label_consts_are_pairwise_distinct`]
// (d739850) distinctness pins on the sibling OTP-shape /
// caixa-kind closed-set typed-enum discriminator axes — the
// fourth (and structurally the M3 mesh-primitive-defining)
// closed-set typed-enum axis to converge on the same
// "pairwise-distinct-by-construction" discipline.
//
// Fail-before-pass-after locally verified by mutating
// [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to
// also read `"SingleNode"` — this pin fires as expected;
// restoring passes.
let all = [
crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
];
for (i, a) in all.iter().enumerate() {
for (j, b) in all.iter().enumerate() {
if i != j {
assert_ne!(
a, b,
"M3_PLACEMENT_ESTRATEGIA_* consts must be pairwise \
distinct — got duplicate {a:?} at indices {i} and {j}",
);
}
}
}
}
#[test]
fn placement_strategy_display_routes_through_as_str_helper() {
// The fail-before-pass-after pin: pre-lift the sibling
// OTP-shape typed enums [`crate::supervisor::RestartStrategy`]
// / [`crate::supervisor::RestartPolicy`] both carried a stable
// [`std::fmt::Display`] surface via their
// `#[discriminant(also_display)]` gen-platform derive, but
// [`PlacementStrategy`] did not — every consumer reaching for
// a strategy byte-string past the wire format had to pick
// between three paths ([`PlacementStrategy::as_str`], the
// `Serialize` derive's serialized string, or `format!("{v:?}")`
// on the `Debug` derive), any two of which a future variant
// rename or `#[serde(rename_all = "kebab-case")]` attribute
// would silently desynchronize. Wiring [`std::fmt::Display`]
// through [`PlacementStrategy::as_str`] closes the third path:
// every `format!("{v}")` call reaches the same lifted
// [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
// and the [`PlacementStrategy::as_str`] helper already route
// through, so a future variant rename lands at exactly one
// place. Pin the routing here so a future
// `impl std::fmt::Display for PlacementStrategy` reimplementation
// that hand-rolls the arms instead of delegating to
// [`PlacementStrategy::as_str`] fails at caixa-core build time.
for variant in [
PlacementStrategy::SingleNode,
PlacementStrategy::Replicated,
PlacementStrategy::Sharded,
] {
assert_eq!(
variant.to_string(),
variant.as_str(),
"PlacementStrategy::{variant:?} Display must route through \
PlacementStrategy::as_str (single source of truth: the lifted \
M3_PLACEMENT_ESTRATEGIA_* const the wire format also emits)"
);
}
}
#[test]
fn placement_strategy_display_matches_serialized_wire_byte_string() {
// The fail-before-pass-after pin on the second half of the
// three-path convergence: `Display` (user-facing text) agrees
// byte-for-byte with the `Serialize` derive's wire format
// (canonical camelCase-schema `M3_PLACEMENT_KEY_ESTRATEGIA`
// scalar) on every variant. Pre-lift the two paths were
// structurally independent — a future
// `#[serde(rename_all = "kebab-case")]` attribute on the enum
// would silently rebrand the emitted wire scalar
// (`single-node`, `replicated`, `sharded`) while every consumer
// that pretty-prints the strategy (the M3 diagnostic templates,
// the future `feira app graph` per-Aplicacao strategy line,
// the future M4 CR materializer's admission-webhook rejection
// body) would still emit the TitleCase form the `as_str` /
// `Display` route returns, with the mismatch surfacing at
// consumer parse time / operator dispatch time far from the
// source rebrand commit. Pin the two paths byte-for-byte here
// so any future serde-attribute or variant-rename drift is a
// caixa-core-build-time test failure at this call, not a
// silent per-consumer dispatch miss.
for variant in [
PlacementStrategy::SingleNode,
PlacementStrategy::Replicated,
PlacementStrategy::Sharded,
] {
let wire = serde_json::to_string(&variant).unwrap();
// Strip the outer `"…"` the JSON string form carries — the
// wire scalar the K8s / YAML apiserver consumes is the
// enclosed byte-string, not the quote wrapper.
let unquoted = wire
.strip_prefix('"')
.and_then(|s| s.strip_suffix('"'))
.expect("serialized PlacementStrategy is a JSON string");
assert_eq!(
variant.to_string(),
unquoted,
"PlacementStrategy::{variant:?} Display byte-string must match the \
Serialize derive's wire byte-string (three-path convergence: \
Display + as_str + Serialize all resolve to the same \
M3_PLACEMENT_ESTRATEGIA_* const)"
);
}
}
#[test]
fn placement_strategy_as_ref_str_routes_through_as_str_accessor() {
// Fail-before-pass-after byte-parity pin on the lifted
// `impl AsRef<str> for PlacementStrategy` — asserts the
// standard-library trait impl and the substrate-primitive
// [`PlacementStrategy::as_str`] `pub const fn` accessor resolve
// to the same `&str` per instance across the three-arm closed
// set, so any future silent detour that routes the impl through
// a divergent projection (a per-arm inline
// `match self { PlacementStrategy::Sharded => "Sharded", … }`
// re-inlining that opens a compile-time link to the un-lifted
// arm-literal, a swap onto the kebab-case
// [`gen_platform::Discriminant`] catalog identity that would
// collide the wire axis with the dispatcher-catalog axis) trips
// at caixa-core test time under `PartialEq` rather than at a
// downstream `impl AsRef<str>`-bound consumer's silent split.
// Sweeps every one of the three arms [`PlacementStrategy::ALL`]
// carries so no arm's projection is covered only by the sibling
// wire-format `Serialize` derive path. Peer of the sibling
// [`crate::supervisor::tests::restart_policy_as_ref_str_routes_through_as_str_accessor`]
// (419ea81) / `restart_strategy_as_ref_str_routes_through_as_str_accessor`
// (63eb1a4) on the paired M2 per-supervisor closed-set typed
// enums, and the [`crate::version::tests::caixa_version_as_ref_str_routes_through_as_str_accessor`]
// (16d5c7e) pin on the paired top-level `:versao` typed newtype
// — the four pins together close the substrate primitive's
// `AsRef<str>` projection axis on every closed-set typed enum
// /newtype on the M2/M3 mesh + supervision + version surface.
for &variant in PlacementStrategy::ALL {
assert_eq!(
<PlacementStrategy as AsRef<str>>::as_ref(&variant),
variant.as_str(),
"AsRef<str> impl on PlacementStrategy::{variant:?} must \
byte-equal PlacementStrategy::as_str on the same instance \
— divergence signals a silent detour off the substrate-\
primitive accessor"
);
}
}
#[test]
fn placement_strategy_as_ref_str_routes_through_display_via_shared_accessor() {
// Fail-before-pass-after byte-parity pin on the three-path
// convergence discipline the M3 per-Aplicacao distribution-
// strategy primitive now carries on the `&str`-projection axis:
// `<PlacementStrategy as AsRef<str>>::as_ref(&v)` (the newly
// lifted impl), `format!("{v}")` (the pre-existing
// [`fmt::Display`] impl), and `v.as_str()` (the substrate-
// primitive `pub const fn` accessor both trait impls delegate
// through) must resolve to the same byte-string on every
// instance across the three-arm closed set. Refuses any future
// divergence between the two trait impls (a stray
// [`fmt::Display::fmt`] rewrite that hand-rolls the arms rather
// than delegating through the shared accessor; a hypothetical
// `AsRef<str>` rewrite that inlines a per-arm literal cascade)
// that would silently split the two projection paths of the
// same closed-set typed enum. Mirrors the sibling three-path-
// convergence discipline the peer
// [`crate::supervisor::RestartPolicy`] typed enum carries on its
// `AsRef<str>` / `Display` / `as_str` triple (supervisor.rs pin
// `restart_policy_as_ref_str_routes_through_display_via_shared_accessor`,
// 419ea81), the peer [`crate::supervisor::RestartStrategy`]
// triple (supervisor.rs pin
// `restart_strategy_as_ref_str_routes_through_display_via_shared_accessor`,
// 63eb1a4), and the [`crate::CaixaVersion`] typed newtype
// triple (version.rs pin
// `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
// 16d5c7e).
for &variant in PlacementStrategy::ALL {
let via_as_ref: &str = <PlacementStrategy as AsRef<str>>::as_ref(&variant);
let via_display: String = format!("{variant}");
let via_accessor: &str = variant.as_str();
assert_eq!(via_as_ref, via_accessor);
assert_eq!(via_display, via_accessor);
assert_eq!(via_as_ref, via_display.as_str());
}
}
#[test]
fn placement_strategy_is_variant_predicates_partition_the_arm_set() {
// Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
// derive on [`PlacementStrategy`]: for each of the three variants
// exactly one of the generated `is_single_node` / `is_replicated`
// / `is_sharded` predicates returns `true` and the other two
// return `false`. Prior to this derive the three per-arm
// `matches!(s, PlacementStrategy::Sharded)` sites in this crate
// (the `placement_strategy_variants_round_trip` fixture, the
// `estrategia_returns_placement_estrategia_verbatim_across_permutations`
// fixture, and the
// `validate_placement_reads_through_lifted_estrategia_accessor`
// fixture) each open-coded a per-arm PartialEq compare against
// the enum variant — three sites that expressed no compile-time
// link back to the closed-set typed dispatch a future fourth
// `:placement :estrategia` (e.g. an `Anycast` mesh-anycast arm
// for the future MESH-COMPOSITION §II.5 hint the roadmap names)
// would have to thread through in lockstep or one fixture would
// silently disagree with the others on which arms consume the
// `:shard-key` axis. Peer of the sibling
// [`crate::CaixaKind`] / [`crate::supervisor::RestartStrategy`]
// / [`crate::supervisor::RestartPolicy`] /
// [`crate::upgrade::UpgradeInstruction`] `IsVariant` derives on
// the sibling closed-set typed-enum discriminator axes — extends
// the same one-typed-dispatch-per-variant discipline onto the
// fifth (and only remaining) closed-set typed-enum discriminator
// on the caixa surface, closing the axis on the M3 mesh-slot
// family.
let rows: [(PlacementStrategy, [bool; 3]); 3] = [
(PlacementStrategy::SingleNode, [true, false, false]),
(PlacementStrategy::Replicated, [false, true, false]),
(PlacementStrategy::Sharded, [false, false, true]),
];
for (variant, expected) in rows {
let observed = [
variant.is_single_node(),
variant.is_replicated(),
variant.is_sharded(),
];
assert_eq!(
observed, expected,
"PlacementStrategy::{variant:?} is_* predicates must partition \
the arm set (single_node, replicated, sharded); got {observed:?}"
);
}
}
#[test]
fn placement_strategy_is_variant_predicates_are_const_fn() {
// The [`gen_platform::IsVariant`] derive emits `const fn`
// predicates on the peer [`crate::CaixaKind`] +
// [`crate::upgrade::UpgradeInstruction`] +
// [`crate::supervisor::RestartStrategy`] +
// [`crate::supervisor::RestartPolicy`] closed-set typed enums —
// pin the same posture on [`PlacementStrategy`] so a future
// accidental downgrade to non-`const` (an added runtime helper
// reachable only from a non-`const` context, a manual hand-rolled
// `impl` that shadows the derive-generated method) trips at
// caixa-core build time rather than surfacing as a downstream
// `const`-context regression far from the derive declaration.
//
// The pin lives inside a `const { assert!(..) }` block so the
// compiler enforces both halves (arm predicate is `const`-
// callable AND returns `true` for the matching arm) at
// caixa-core compile time — peer to the sibling
// [`crate::CaixaKind::is_*`] + [`WitTarget::is_*`] const-block
// pins on the closed-set typed enum arm-predicate const-
// callability axis.
const {
assert!(PlacementStrategy::SingleNode.is_single_node());
assert!(PlacementStrategy::Replicated.is_replicated());
assert!(PlacementStrategy::Sharded.is_sharded());
}
}
#[test]
fn placement_strategy_requires_shard_key_partitions_the_arm_set() {
// Fail-before-pass-after pin on the substrate-lifted
// [`PlacementStrategy::requires_shard_key`] cross-slot-invariant
// per-arm predicate: for each variant in the closed accept-set the
// predicate returns `true` iff the variant consumes the paired
// [`Placement::shard_key`] axis under
// [`AplicacaoSpec::validate_placement`]'s `Sharded` ↔ non-`Sharded`
// partition. Today the accept-set is the singleton `{Sharded}` —
// `Sharded` is the Akka-style hash-keyed distribution arm
// (MESH-COMPOSITION §II.4), `SingleNode` (Erlang/OTP takeover —
// §II.1) and `Replicated` (active-active) refuse the axis through
// [`AplicacaoError::ShardKeyOnNonSharded`].
//
// Pins the per-arm truth-table so a future arm addition (an
// `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint the
// roadmap names, a `WeightedShard` promotion the future M5
// adaptive-placement engine acknowledges) that landed a variant
// without extending this predicate's arm-set would surface as a
// caixa-core build-time exhaustiveness error at the
// `match self { … }` arm-fan below rather than a silent per-consumer
// mis-classification at renderer emit time. The paired
// [`Self::is_sharded`] `gen_platform::IsVariant`-derived arm-identity
// predicate stays a distinct question — arm-identity (which the
// sibling
// [`placement_strategy_is_variant_predicates_partition_the_arm_set`]
// pin already locks) is not cross-slot-invariant consumption; today
// they trip on the same singleton but the pair migrates through
// one caixa-core edit on any future arm addition.
//
// Peer of the sibling per-arm classifier pins
// [`wit_contract_is_capability_partitions_the_wit_shape_space`]
// (7b97d26) on the [`WitContract`] pre-projection WIT-shape axis
// and the [`WitTarget::is_capability`] `gen_platform::IsVariant`-
// derived paired predicate on the post-projection typed-view axis
// — same "per-arm semantic-classification predicate paired with
// the arm-identity predicate the derive already emits" discipline
// extended onto the M3 mesh-slot `:placement :estrategia` ↔
// `:placement :shard-key` cross-slot-invariant axis.
let rows: [(PlacementStrategy, bool); 3] = [
(PlacementStrategy::SingleNode, false),
(PlacementStrategy::Replicated, false),
(PlacementStrategy::Sharded, true),
];
for (variant, expected) in rows {
assert_eq!(
variant.requires_shard_key(),
expected,
"PlacementStrategy::{variant:?}.requires_shard_key() must \
be {expected} (the substrate-canonical cross-slot invariant \
on the :placement :shard-key axis; today `Sharded` is the \
singleton consuming arm — MESH-COMPOSITION §II.4)",
);
}
}
#[test]
fn placement_strategy_requires_shard_key_is_const_fn() {
// The [`PlacementStrategy::requires_shard_key`] cross-slot-
// invariant per-arm predicate is declared `#[must_use] pub const
// fn` — pin the `const`-eval posture here so a future accidental
// downgrade to non-`const` (an added runtime helper reachable
// only from a non-`const` context, a manual hand-rolled `impl`
// that shadows the current three-arm `match self { … }` dispatch)
// trips at caixa-core build time rather than surfacing as a
// downstream `const`-context regression far from the declaration.
// Same shape as the sibling
// [`placement_strategy_is_variant_predicates_are_const_fn`] pin on
// the peer [`gen_platform::IsVariant`]-derived arm-identity
// predicate axis, but here the load-bearing assertions live in
// module-scope `const _: () = assert!(…)` items so a violation
// fails at compile time (const-eval trip) rather than test time —
// strictly stronger than the runtime `assert!(CONST)` pattern the
// sibling pin uses, and side-steps the
// `clippy::assertions_on_constants` lint the runtime pattern
// otherwise accumulates on the module baseline.
//
// The test body simply witnesses that the module-scope items
// compiled and the runtime dispatch agrees with the const-eval
// dispatch on every arm — the runtime read gives the test a
// failure surface (rather than an empty test body clippy would
// flag as a no-op).
const REQUIRES_SINGLE_NODE: bool = PlacementStrategy::SingleNode.requires_shard_key();
const REQUIRES_REPLICATED: bool = PlacementStrategy::Replicated.requires_shard_key();
const REQUIRES_SHARDED: bool = PlacementStrategy::Sharded.requires_shard_key();
assert_eq!(
[REQUIRES_SINGLE_NODE, REQUIRES_REPLICATED, REQUIRES_SHARDED,],
[
PlacementStrategy::SingleNode.requires_shard_key(),
PlacementStrategy::Replicated.requires_shard_key(),
PlacementStrategy::Sharded.requires_shard_key(),
],
"runtime and const-eval dispatch on \
PlacementStrategy::requires_shard_key must agree on every arm",
);
}
#[test]
fn placement_estrategia_accessor_is_const_fn() {
// The [`Placement::estrategia`] per-`:placement` distribution-
// strategy `Copy`-return scalar accessor is declared
// `#[must_use] pub const fn` — matching the peer M3 mesh-slot
// `Copy`-return accessor family ([`MeshPolicy::timeout`] /
// [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
// [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`]
// on the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`]
// / [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
// [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
// [`RateLimit`], every one a `pub const fn`). Pin the
// `const`-eval posture here so a future accidental downgrade to
// non-`const` (an added runtime helper reachable only from a
// non-`const` context, a slot promotion to a non-`Copy` return
// that would silently drop the `const` qualifier, a manual
// hand-rolled shadow) trips at caixa-core build time rather
// than surfacing as a downstream `const`-context regression far
// from the declaration.
//
// Same shape as the sibling
// [`placement_strategy_requires_shard_key_is_const_fn`] pin on
// the peer [`PlacementStrategy::requires_shard_key`] `const fn`
// predicate axis — the load-bearing witness lives in the
// module-scope `const fn` wrapper `estrategia_via_const_fn`
// below: a body that calls [`Placement::estrategia`] under a
// `const fn` signature is well-formed only when the callee is
// itself `const fn`, so any future accidental downgrade of
// [`Placement::estrategia`] to non-`const` fails at caixa-core
// build time (const-eval E0015 / E0658 depending on the arm),
// strictly stronger than a runtime `assert!(CONST)` and
// side-stepping the destructor-in-const restriction that
// blocks direct `const _: PlacementStrategy = FIXTURE.estrategia()`
// items on `Placement`'s `Vec<String>` / `Option<String>`
// carriers.
//
// The runtime body witnesses that the const-eval-shaped
// wrapper agrees with a direct call on every closed-set arm.
const fn estrategia_via_const_fn(p: &Placement) -> PlacementStrategy {
p.estrategia()
}
for estrategia in [
PlacementStrategy::SingleNode,
PlacementStrategy::Replicated,
PlacementStrategy::Sharded,
] {
let placement = Placement {
estrategia,
clusters: Vec::new(),
affinity: None,
shard_key: None,
};
assert_eq!(
estrategia_via_const_fn(&placement),
placement.estrategia(),
"const-fn-wrapped and direct dispatch on \
Placement::estrategia must agree for {estrategia:?}",
);
}
}
#[test]
fn entrada_port_accessor_is_const_fn() {
// The [`Entrada::port`] per-`:entrada` L4-port `Copy`-return
// scalar accessor is declared `#[must_use] pub const fn` —
// matching the peer M3 mesh-slot `Copy`-return accessor family
// ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`] /
// [`MeshPolicy::mtls_required`] / [`MeshPolicy::rate_limit`] /
// [`MeshPolicy::circuit_breaker`] on the parent [`MeshPolicy`],
// [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
// on the sibling [`CircuitBreaker`], [`RateLimit::rate`] /
// [`RateLimit::window`] on the sibling [`RateLimit`], the
// sibling per-`:placement` [`Placement::estrategia`] pinned by
// [`placement_estrategia_accessor_is_const_fn`] above — every
// one a `pub const fn`). Pin the `const`-eval posture here so
// a future accidental downgrade to non-`const` (an added
// runtime helper reachable only from a non-`const` context, an
// `Option<u16>`-shape migration once the substrate grows
// per-`:membros` heterogeneous listener ports that would
// silently drop the `const` qualifier, a manual hand-rolled
// shadow) trips at caixa-core build time rather than surfacing
// as a downstream `const`-context regression far from the
// declaration.
//
// Same shape as the sibling
// [`placement_estrategia_accessor_is_const_fn`] pin above — the
// load-bearing witness lives in the module-scope `const fn`
// wrapper `port_via_const_fn`: a body that calls
// [`Entrada::port`] under a `const fn` signature is well-formed
// only when the callee is itself `const fn`, side-stepping the
// destructor-in-const restriction that would otherwise block a
// direct `const _: u16 = FIXTURE.port()` item on `Entrada`'s
// `String` / `Vec<String>` carriers.
//
// The runtime body sweeps a representative port set spanning
// the [`SERVICO_PORT_MIN`] floor, the substrate-canonical
// [`DEFAULT_SERVICO_PORT`] default, and the top-edge `u16::MAX`
// ceiling — the const-fn-wrapped call must agree with a direct
// call on every fixture (a violation trips the test) and every
// returned scalar must byte-equal the input `port` (a violation
// means the accessor stopped being a raw field-return copy).
const fn port_via_const_fn(e: &Entrada) -> u16 {
e.port()
}
for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, u16::MAX] {
let entrada = Entrada {
host: String::new(),
para: String::new(),
port,
paths: Vec::new(),
};
assert_eq!(
port_via_const_fn(&entrada),
entrada.port(),
"const-fn-wrapped and direct dispatch on Entrada::port \
must agree for port={port}",
);
assert_eq!(
entrada.port(),
port,
"Entrada::port must return the storage-side u16 verbatim \
for port={port}",
);
}
}
#[test]
fn validate_placement_admits_paired_shape_iff_strategy_requires_shard_key() {
// Load-bearing cross-slot-partition pin closing the loop between
// the substrate-lifted
// [`PlacementStrategy::requires_shard_key`] per-arm predicate on
// the closed-set typed enum and the actual
// [`AplicacaoSpec::validate_placement`] runtime behavior across
// the paired `:placement :shard-key` axis: every validated
// [`Placement`] past [`AplicacaoSpec::validate_placement`]
// satisfies `placement.shard_key().is_some() ==
// placement.estrategia().requires_shard_key()`. The four-cell
// shape witness sweeps every combination of (variant in the
// closed accept-set, `:shard-key` Some/None) and pins:
//
// * variant.requires_shard_key() && shard_key.is_some() →
// validate() passes; the paired shape is the sole
// `requires_shard_key` arm-family accepted shape.
// * variant.requires_shard_key() && shard_key.is_none() →
// validate() fails with [`AplicacaoError::ShardedWithoutKey`];
// the paired shape is the refused missing-key shape on
// Sharded-family arms.
// * !variant.requires_shard_key() && shard_key.is_some() →
// validate() fails with
// [`AplicacaoError::ShardKeyOnNonSharded`]; the paired shape
// is the refused declared-but-inert shape on non-Sharded-
// family arms.
// * !variant.requires_shard_key() && shard_key.is_none() →
// validate() passes; the paired shape is the sole
// non-`requires_shard_key` arm-family accepted shape.
//
// The compile-time-exhaustive `match p.estrategia()` dispatch at
// [`AplicacaoSpec::validate_placement`] preserves its structural
// arm-fan (a future arm addition still surfaces a build-time
// exhaustiveness error there); this pin closes the semantic loop
// between the arm-fan's shape-gate cascades and the substrate-
// canonical predicate every downstream consumer of the paired
// shape reads through. Fail-before-pass-after locally verified by
// mutating the predicate's `Sharded => true` arm to `false` — the
// truthy `expects_ok` cell for `Sharded` + `Some` trips the
// `validate() must pass` assertion; restoring passes. Same "close
// the loop between the typed predicate and the runtime behavior"
// discipline as the sibling
// [`wit_contract_is_capability_agrees_with_projected_wit_target_capability_variant`]
// (7b97d26) cross-projection pin on the peer [`WitTarget`]
// per-arm classifier axis.
for variant in [
PlacementStrategy::SingleNode,
PlacementStrategy::Replicated,
PlacementStrategy::Sharded,
] {
for present in [false, true] {
let mut spec = three_member_spec();
spec.placement.estrategia = variant;
spec.placement.shard_key = present.then(|| "tenantId".into());
let expects_ok = variant.requires_shard_key() == present;
let result = spec.validate();
match (expects_ok, &result) {
(true, Ok(())) => {}
(false, Err(err)) => {
// Cross-check the refusal diagnostic names the
// right cell of the four-cell shape witness — the
// `requires_shard_key && !present` cell must trip
// [`AplicacaoError::ShardedWithoutKey`]; the
// `!requires_shard_key && present` cell must trip
// [`AplicacaoError::ShardKeyOnNonSharded`].
match (variant.requires_shard_key(), present, err) {
(true, false, AplicacaoError::ShardedWithoutKey) => {}
(
false,
true,
AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. },
) => {
assert_eq!(
*e, variant,
"ShardKeyOnNonSharded.estrategia must byte-equal \
the paired PlacementStrategy",
);
}
_ => panic!(
"unexpected refusal for estrategia={variant:?} \
present={present}: {err:?}"
),
}
}
(true, Err(err)) => panic!(
"validate() must pass for estrategia={variant:?} \
present={present} (requires_shard_key={} == present={present}), \
got {err:?}",
variant.requires_shard_key(),
),
(false, Ok(())) => panic!(
"validate() must fail for estrategia={variant:?} \
present={present} (requires_shard_key={} != present={present})",
variant.requires_shard_key(),
),
}
}
}
}
#[test]
fn placement_without_clusters_diagnostic_carries_strategy_display_byte_string() {
// Pin the M3 diagnostic template routes through the typed
// [`PlacementStrategy`] Display byte-string (rebound from the
// prior `{estrategia:?}` `Debug` route). Pre-lift the two
// routes emitted identical bytes (the `Debug` derive on a
// unit variant emits the variant name verbatim, exactly what
// `as_str` returns), but the two paths were structurally
// independent — a future `#[serde(rename_all = "…")]`
// attribute or variant rename would coordinate the wire /
// `Display` / `as_str` triple through the lifted const but
// leave the `Debug` route on the compiler-derived variant name,
// silently desynchronizing the diagnostic byte-string from the
// wire byte-string. Rebinding the template onto `Display`
// ties the diagnostic to the same lifted
// [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
// emits — drift becomes structurally impossible. Pin the
// byte-string here so a future edit that reverts the template
// to `{estrategia:?}` is caught at caixa-core test time, not
// at consumer dispatch time.
for (variant, expected_scalar) in [
(
PlacementStrategy::SingleNode,
crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
),
(
PlacementStrategy::Replicated,
crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
),
(
PlacementStrategy::Sharded,
crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
),
] {
let err = AplicacaoError::PlacementWithoutClusters {
estrategia: variant,
};
let msg = err.to_string();
assert!(
msg.starts_with(&format!(":placement {expected_scalar} requires")),
"PlacementWithoutClusters diagnostic for {variant:?} must open \
with the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
);
}
}
#[test]
fn shard_key_on_non_sharded_diagnostic_carries_strategy_display_byte_string() {
// Peer of
// [`placement_without_clusters_diagnostic_carries_strategy_display_byte_string`]
// on the second M3 diagnostic that carries the typed
// [`PlacementStrategy`] in its `#[error(…)]` template. Both
// diagnostics now route the strategy scalar through the same
// [`std::fmt::Display`] surface, tying the diagnostic
// byte-string to the lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`]
// const set the wire format also emits. The two non-Sharded
// arms are exercised here (the diagnostic exists to flag a
// `:shard-key` slot the current strategy will never consume);
// the peer `Sharded` arm never reaches this diagnostic (the
// `Sharded` strategy consumes `:shard-key` — the
// [`AplicacaoError::ShardedWithoutKey`] arm reports the missing
// slot instead).
for (variant, expected_scalar) in [
(
PlacementStrategy::SingleNode,
crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
),
(
PlacementStrategy::Replicated,
crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
),
] {
let err = AplicacaoError::ShardKeyOnNonSharded {
estrategia: variant,
shard_key: "$tenantId".into(),
};
let msg = err.to_string();
assert!(
msg.starts_with(&format!(":placement {expected_scalar} carries")),
"ShardKeyOnNonSharded diagnostic for {variant:?} must open with \
the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
);
}
}
#[test]
fn placement_strategy_all_enumerates_every_variant_once() {
// Fail-before-pass-after pin on the [`PlacementStrategy::ALL`]
// exhaustive-iteration surface: every variant appears exactly
// once, and the slice length matches the arm count of the
// closed set. Every consumer that walks the accepted-strategy
// set (a future `feira app placement --list` CLI-side surfacing,
// a future M4 admission-webhook's rejection body naming the
// accepted-strategy list, the [`PlacementStrategy::from_wire`]
// reverse-projection consumers that iterate the accept-set for
// a "did you mean" hint) reads through this slice, so a future
// variant addition (an `Anycast` mesh-anycast arm the
// MESH-COMPOSITION §II.5 hint names as a trajectory item) that
// grows the enum but forgets to grow [`Self::ALL`] silently
// truncates every downstream consumer's accept-set at the same
// pre-addition boundary — this pin fails at caixa-core build
// time on the pairwise-distinct + arm-count invariants.
//
// Peer of the sibling [`RateLimitUnit::ALL`] (6bce03d) /
// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
// pins on the peer closed-set typed-enum axes.
let all: &[PlacementStrategy] = PlacementStrategy::ALL;
assert_eq!(
all.len(),
3,
"PlacementStrategy::ALL must enumerate every variant of the \
three-arm closed set (SingleNode, Replicated, Sharded); got {all:?}"
);
for (i, a) in all.iter().enumerate() {
for (j, b) in all.iter().enumerate() {
if i != j {
assert_ne!(
a, b,
"PlacementStrategy::ALL must carry every variant exactly \
once — got duplicate {a:?} at indices {i} and {j}"
);
}
}
}
for variant in [
PlacementStrategy::SingleNode,
PlacementStrategy::Replicated,
PlacementStrategy::Sharded,
] {
assert!(
all.contains(&variant),
"PlacementStrategy::ALL must contain {variant:?} — a future variant \
addition that grows the enum but forgets to grow the ALL slice \
silently truncates every downstream consumer's accept-set at the \
pre-addition boundary"
);
}
}
#[test]
fn placement_strategy_from_wire_accepts_every_lifted_constant() {
// Fail-before-pass-after pin on the forward accept-set of the
// [`PlacementStrategy::from_wire`] reverse projection: every
// canonical [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`]
// constant the [`PlacementStrategy::as_str`] emitter walks
// parses back to its paired variant. Any future arm addition
// that grows the emitter's `as_str` match but forgets to grow
// the parser's `from_str` match silently splits the two halves
// of the round-trip — the wire byte-string one non-serde
// consumer parses from the one the emitter wrote — with the
// failure surfacing at parse time far from the rebrand commit.
// Pinning the three-arm accept-set here catches the drift at
// caixa-core build time.
//
// Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
// + [`RateLimitUnit::from_suffix`] accept-set pins on the peer
// closed-set typed-enum `str → Self` axes.
for (wire, expected) in [
(
crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
PlacementStrategy::SingleNode,
),
(
crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
PlacementStrategy::Replicated,
),
(
crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
PlacementStrategy::Sharded,
),
] {
let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
panic!(
"PlacementStrategy::from_wire({wire:?}) must accept every \
M3_PLACEMENT_ESTRATEGIA_* constant — got None for the \
lifted canonical byte-string that PlacementStrategy::{expected:?} \
serializes as under M3_PLACEMENT_KEY_ESTRATEGIA"
)
});
assert_eq!(
parsed, expected,
"PlacementStrategy::from_wire({wire:?}) must return \
PlacementStrategy::{expected:?}; got PlacementStrategy::{parsed:?}"
);
}
}
#[test]
fn placement_strategy_from_wire_round_trips_through_as_str() {
// Fail-before-pass-after pin on the closed round-trip between
// the forward [`PlacementStrategy::as_str`] emitter and the
// reverse [`PlacementStrategy::from_wire`] parser: for every
// variant in [`PlacementStrategy::ALL`], parsing the emitter's
// output must return exactly the same variant. Any per-arm
// divergence — a future arm added to `as_str` but not
// `from_str`, an accidental copy-paste flip in one but not the
// other — silently splits the emit and parse halves and the
// failure surfaces at consumer parse time far from the drift
// site. The `ALL`-iterating shape means a future variant
// addition picks up the coverage by construction.
//
// Peer of the sibling [`crate::kind::tests`] round-trip pin on
// [`crate::CaixaKind::from_wire`] and the
// [`super::tests::rate_limit_unit_from_suffix_round_trips_through_as_suffix`]
// sibling round-trip pin on [`RateLimitUnit`].
for &variant in PlacementStrategy::ALL {
let wire = variant.as_str();
let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
panic!(
"PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
must be Some({variant:?}) — the two halves of the round-trip \
dispatch on the same lifted M3_PLACEMENT_ESTRATEGIA_* consts; \
got None on wire byte-string {wire:?}"
)
});
assert_eq!(
parsed, variant,
"PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
must round-trip to the same variant; got {parsed:?}"
);
}
}
#[test]
fn placement_strategy_from_wire_rejects_unknown_byte_strings() {
// Fail-before-pass-after pin on the closed-set refusal
// discipline of [`PlacementStrategy::from_wire`]: every
// byte-string outside the three-arm accept-set returns `None`
// rather than silently collapsing onto the [`Default`]
// (`Replicated`) arm or an arbitrary neighbor. The refusal set
// exercised here sweeps the load-bearing drift shapes: the
// empty string (a stripped serde-attribute drift), an all-
// whitespace string (the canonical text-editor accidental
// padding shape), the lowercased kebab-case forms a future
// `#[serde(rename_all = "kebab-case")]` attribute would emit
// (`"single-node"`, `"replicated"`, `"sharded"` — the last two
// coincidentally match the accepted canonical scalars, so only
// `"single-node"` fires as a refusal, but pinning the case-
// sensitivity of the accepted arms via the peer [`SingleNode`]
// assertion in the round-trip pin makes the discipline
// structurally clear), the lowercased single-word forms
// (`"singlenode"`), the padded canonical scalar
// (`" Sharded "`), the trailing-comma / trailing-newline shapes
// (`"Sharded\n"`), and a pointer-different `&'static str` that
// happens to alias a canonical byte-string by content but not
// by identity (validated implicitly by the emitter's routing
// through `crate::render::M3_PLACEMENT_ESTRATEGIA_*`, whose
// identity a paired [`crate::assert_str_reexport_identity`] pin
// in caixa-core's per-const declaration surface would catch).
//
// Peer of the sibling
// [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
// (2aa6d23) refusal pin on [`crate::CaixaKind::from_wire`].
for bad in [
"",
" ",
"\n",
"\t",
"single-node",
"singlenode",
"SingleNodes",
"single_node",
"single node",
"SINGLENODE",
"SingleNode ",
" SingleNode",
" Sharded ",
"Sharded\n",
"replicated ",
"sharded",
"REPLICATED",
"Anycast",
"Global",
"?",
] {
assert!(
PlacementStrategy::from_wire(bad).is_none(),
"PlacementStrategy::from_wire({bad:?}) must return None — the \
parser's accept-set is exactly the three PlacementStrategy::as_str \
outputs (SingleNode, Replicated, Sharded), and this byte-string \
is outside that closed set"
);
}
}
#[test]
fn placement_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
// Fail-before-pass-after pin on the third path of the four-path
// convergence: `from_str` (the reverse projection) inverts the
// `Serialize` derive's wire byte-string on every variant.
// Together with the pre-existing three-path convergence
// (`Display` + `as_str` + `Serialize` all resolve to the same
// lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const, pinned by
// the peer
// [`placement_strategy_display_matches_serialized_wire_byte_string`])
// this closes the round-trip: the wire byte-string the
// `Serialize` derive emits parses back to the same variant
// through `from_str`, so any future serde-attribute or variant-
// rename drift on the emit half now surfaces as a matched drift
// on the parse half at caixa-core build time — the two halves
// migrate as a unit through the lifted consts on any future
// rename, and the round-trip cannot silently split.
//
// Peer of the sibling
// [`placement_strategy_display_matches_serialized_wire_byte_string`]
// wire-format pin — extends the three-path convergence
// (`Display` + `as_str` + `Serialize`) onto the fourth path
// (`from_str`), closing the `str ↔ Self` round-trip on the
// M3 `:placement :estrategia` closed-set axis.
for &variant in PlacementStrategy::ALL {
let wire = serde_json::to_string(&variant).unwrap();
let unquoted = wire
.strip_prefix('"')
.and_then(|s| s.strip_suffix('"'))
.expect("serialized PlacementStrategy is a JSON string");
let parsed = PlacementStrategy::from_wire(unquoted).unwrap_or_else(|| {
panic!(
"PlacementStrategy::from_wire({unquoted:?}) must accept the \
Serialize derive's wire byte-string for \
PlacementStrategy::{variant:?} — the four-path convergence \
(Display + as_str + Serialize + from_str) resolves through \
the same lifted M3_PLACEMENT_ESTRATEGIA_* const; got None"
)
});
assert_eq!(
parsed, variant,
"PlacementStrategy::from_wire of the Serialize derive's wire \
byte-string for PlacementStrategy::{variant:?} must round-trip \
to the same variant; got {parsed:?}"
);
}
}
#[test]
fn placement_strategy_try_from_str_routes_through_from_wire_accessor() {
// Fail-before-pass-after byte-parity pin on the newly lifted
// `impl TryFrom<&str> for PlacementStrategy` — asserts the
// standard-library trait impl and the substrate-primitive
// [`PlacementStrategy::from_wire`] `Option<Self>` accessor
// resolve to the same three-arm accept-set across every arm the
// exhaustive [`PlacementStrategy::ALL`] slice enumerates. Any
// future silent detour that routes the trait impl through a
// divergent projection (a per-arm inline `match s { "SingleNode"
// => Ok(Self::SingleNode), … }` re-inlining that opens a
// compile-time link to the un-lifted arm-literal, a stray
// `#[serde(rename_all = "…")]` attribute drift that silently
// splits the wire byte-string from every consumer that reaches
// for this typed dispatch) trips at caixa-core test time under
// `assert_eq!` rather than at a downstream `impl TryFrom<&str>`-
// bound consumer's silent split. Sweeps every one of the three
// arms [`PlacementStrategy::ALL`] carries so no arm's projection
// is covered only by the sibling method-named `from_wire` path.
// Peer of the sibling
// [`crate::kind::tests::caixa_kind_try_from_str_routes_through_from_wire_accessor`]
// (3c83606) and
// [`crate::dialeto::tests::caixa_dialeto_try_from_str_routes_through_from_wire_accessor`]
// (bf33136) — extends the trait-idiomatic reverse-projection
// axis onto the first M3-mesh-primitive-defining slot enum on
// the caixa surface.
for &variant in PlacementStrategy::ALL {
let wire = variant.as_str();
assert_eq!(
<PlacementStrategy as TryFrom<&str>>::try_from(wire),
Ok(variant),
"TryFrom<&str> impl on PlacementStrategy must round-trip \
PlacementStrategy::{variant:?}.as_str() = {wire:?} back to \
Ok(PlacementStrategy::{variant:?}) — divergence from \
PlacementStrategy::from_wire signals a silent detour off \
the substrate-primitive accessor"
);
assert_eq!(
<PlacementStrategy as TryFrom<&str>>::try_from(wire).ok(),
PlacementStrategy::from_wire(wire),
"TryFrom<&str> ok()-projection on {wire:?} must byte-equal \
PlacementStrategy::from_wire on the same input"
);
}
}
#[test]
fn placement_strategy_try_from_str_rejects_unknown_byte_strings() {
// Rejection witness on the `impl TryFrom<&str> for
// PlacementStrategy` — sweeps a candidate set of byte-strings
// outside the three-arm camelCase-schema wire accept-set the
// sibling [`PlacementStrategy::as_str`] emits and asserts every
// one lands on `Err(())`, so a future accidental widening of the
// trait impl's accept-set (a stray additional
// `_ if s.eq_ignore_ascii_case("SingleNode") => Ok(…)` case-
// fold path, a silent inclusion of a kebab-case rebrand of the
// wire byte-string that would collide the two-axis split the
// sibling `placement_strategy_from_wire_rejects_unknown_byte_strings`
// pin makes load-bearing) trips at caixa-core test time. The
// candidate set includes the empty string, whitespace-only
// padding, kebab-case rebrand candidates (`"single-node"`),
// snake_case rebrand candidates (`"single_node"`), uppercase
// rebrand candidates, trailing/leading-whitespace-padded
// canonical scalars, the trailing-newline shape, English-rebrand
// candidates (`"Anycast"`, `"Global"`), and the residual `"?"`
// to trip on any future accidental widening onto the sentinel
// shape sibling enums use for unknown-arm diagnostics.
// Peer of the sibling
// [`crate::kind::tests::caixa_kind_try_from_str_rejects_unknown_byte_strings`]
// (3c83606) rejection witness.
let rejected: &[&str] = &[
"",
" ",
"\n",
"\t",
"single-node",
"singlenode",
"SingleNodes",
"single_node",
"single node",
"SINGLENODE",
"SingleNode ",
" SingleNode",
" Sharded ",
"Sharded\n",
"replicated ",
"sharded",
"REPLICATED",
"Anycast",
"Global",
"?",
"\"Sharded\"",
];
for &input in rejected {
assert_eq!(
<PlacementStrategy as TryFrom<&str>>::try_from(input),
Err(()),
"TryFrom<&str> impl on PlacementStrategy must reject the \
non-wire byte-string {input:?} — silent acceptance signals \
an accept-set widening off the paired \
PlacementStrategy::from_wire resolver"
);
}
}
#[test]
fn placement_strategy_from_into_static_str_routes_through_as_str_accessor() {
// Fail-before-pass-after byte-parity pin on the newly lifted
// `impl From<PlacementStrategy> for &'static str` — asserts the
// standard-library trait impl and the substrate-primitive
// [`PlacementStrategy::as_str`] `pub const fn` accessor resolve
// to the same three-arm emit-set across every arm the exhaustive
// [`PlacementStrategy::ALL`] slice enumerates. Any future silent
// detour that routes the trait impl through a divergent
// projection (a per-arm inline `match strategy { SingleNode =>
// "SingleNode", … }` re-inlining that opens a compile-time link
// to the un-lifted arm-literal outside the paired
// [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`] lifted constants,
// an accidental swap onto the sibling kebab-case
// [`gen_platform::Discriminant`] catalog identity that would
// collide the wire axis with the dispatcher-catalog axis the
// sibling [`PlacementStrategy::as_str`] doc block makes load-
// bearing) trips at caixa-core test time under `assert_eq!`
// rather than at a downstream `impl Into<&'static str>`-bound
// consumer's silent split. Sweeps every one of the three arms
// [`PlacementStrategy::ALL`] carries so no arm's projection is
// covered only by the sibling method-named `as_str` /
// [`std::fmt::Display`] / [`AsRef<str>`] paths. Materializes the
// `<&'static str as From<PlacementStrategy>>::from` output in
// three `const`-shape bindings to make the `'static` lifetime
// promise a build-time invariant — a future accidental downgrade
// of any of the three arms'
// [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`] constants to a
// non-`&'static str` (a `String::leak()`-produced return, a
// `Box::leak`-cast, an intermediate lifetime-erasing helper)
// trips at caixa-core build time rather than at a downstream
// `'static`-bound consumer. Peer of the sibling
// [`crate::supervisor::tests::restart_strategy_from_into_static_str_routes_through_as_str_accessor`]
// (523157d) /
// [`crate::supervisor::tests::restart_policy_from_into_static_str_routes_through_as_str_accessor`]
// (9fb37d0) /
// [`crate::kind::tests::caixa_kind_from_into_static_str_routes_through_as_str_accessor`]
// (edb827b) /
// [`crate::dialeto::tests::caixa_dialeto_from_into_static_str_routes_through_as_str_accessor`]
// (c189a6f) pins on the sibling closed-set typed-enum forward-
// projection axes — extends the trait-idiomatic forward-
// projection axis onto the fifth closed-set fieldless typed
// enum on the caixa surface (the M3-mesh-primitive-defining
// `:placement :estrategia` axis, first-of-many on the M3 mesh
// slot family the caixa-mesh renderer keys off end-to-end).
const SINGLE_NODE: &str = PlacementStrategy::SingleNode.as_str();
const REPLICATED: &str = PlacementStrategy::Replicated.as_str();
const SHARDED: &str = PlacementStrategy::Sharded.as_str();
for &variant in PlacementStrategy::ALL {
let via_trait: &'static str = <&'static str as From<PlacementStrategy>>::from(variant);
let via_method: &'static str = variant.as_str();
assert_eq!(
via_trait, via_method,
"From<PlacementStrategy> for &'static str impl must \
round-trip PlacementStrategy::{variant:?} to the same \
lifted M3_PLACEMENT_ESTRATEGIA_* const \
PlacementStrategy::as_str returns — divergence signals \
a silent detour off the substrate-primitive accessor"
);
let via_into: &'static str = variant.into();
assert_eq!(
via_into, via_method,
"Into<&'static str>::into on PlacementStrategy::{variant:?} \
must byte-equal PlacementStrategy::as_str on the same \
input — the blanket-derived Into shape must resolve to \
the same as_str dispatch as the explicit From impl"
);
}
assert_eq!(
[SINGLE_NODE, REPLICATED, SHARDED],
[
crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
],
"const-context PlacementStrategy::as_str must resolve to the \
three lifted M3_PLACEMENT_ESTRATEGIA_* consts — a future \
accidental downgrade of any arm to a non-const or non-static \
byte-string breaks the `&'static str`-lifetime promise the \
paired From<PlacementStrategy> for &'static str impl carries \
by construction"
);
}
#[test]
fn placement_strategy_from_into_static_str_and_as_str_partition_the_emit_set() {
// Cross-axis partition pin: the paired trait-idiomatic
// `From<PlacementStrategy> for &'static str` forward projection
// and the method-named [`PlacementStrategy::as_str`] forward
// projection must resolve identically on *every* arm, not just
// the ones named in the primary byte-parity pin above. Sweeps
// every [`PlacementStrategy::ALL`] arm and asserts the trait's
// `From::from` output byte-equals the method-named accessor's
// return-value on each, locking the two forward-projection paths
// together by construction so any future detour (a stray `From`
// special-case that lands on a divergent per-arm literal outside
// the paired `as_str` dispatch, a hypothetical rebrand touching
// one axis without the other) trips at caixa-core test time.
// Peer of the sibling forward-projection partition pins
// [`crate::supervisor::tests::restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
// (523157d) /
// [`crate::supervisor::tests::restart_policy_from_into_static_str_and_as_str_partition_the_emit_set`]
// (9fb37d0) /
// [`crate::kind::tests::caixa_kind_from_into_static_str_and_as_str_partition_the_emit_set`]
// (edb827b) /
// [`crate::dialeto::tests::caixa_dialeto_from_into_static_str_and_as_str_partition_the_emit_set`]
// (c189a6f) — extends the round-trip discipline onto the fifth
// closed-set typed enum on the caixa surface, closing the two-way
// `Self ↔ &'static str` round-trip on the trait-idiomatic pair
// (`From<Self> for &'static str` + `TryFrom<&str> for Self`) as
// well as the pre-existing method-named pair (`as_str` +
// `from_wire`).
for &variant in PlacementStrategy::ALL {
let via_trait: &'static str = <&'static str as From<PlacementStrategy>>::from(variant);
let via_method: &'static str = variant.as_str();
assert_eq!(
via_trait, via_method,
"From<PlacementStrategy> for &'static str and \
PlacementStrategy::as_str must resolve identically on \
PlacementStrategy::{variant:?} — divergence signals the \
two forward-projection paths have drifted onto different \
emit-sets"
);
}
// Round-trip witness: every arm's forward `From` output re-parses
// through the paired trait-idiomatic reverse `TryFrom<&str>` back
// to the original variant. Closes the two-way `PlacementStrategy
// ↔ &'static str` round-trip on the trait-idiomatic axis pair
// directly (no wire-vocab intermediate the peer [`CaixaKind`]
// axis pair requires — the emit-side
// [`PlacementStrategy::as_str`] and the parse-side
// [`PlacementStrategy::from_wire`] dispatch on the same three
// lifted [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`] constants
// by construction), mirroring the pre-existing method-named
// `as_str` + `from_wire` round-trip on the substrate-primitive
// axis pair.
for &variant in PlacementStrategy::ALL {
let emitted: &'static str = variant.into();
let re_parsed: Result<PlacementStrategy, ()> =
<PlacementStrategy as TryFrom<&str>>::try_from(emitted);
assert_eq!(
re_parsed,
Ok(variant),
"trait-idiomatic axis pair must round-trip \
PlacementStrategy::{variant:?} through `.into::<&'static \
str>()` and back through `TryFrom<&str>` — a break \
signals the forward-emit and reverse-parse axes have \
drifted onto different vocabularies"
);
}
}
#[test]
fn placement_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
// Fail-before-pass-after byte-parity pin on the newly lifted
// `impl From<&PlacementStrategy> for &'static str` — asserts
// the borrowed-input standard-library trait impl and the
// substrate-primitive [`PlacementStrategy::as_str`] `pub const
// fn` accessor resolve to the same three-arm emit-set across
// every arm the exhaustive [`PlacementStrategy::ALL`] slice
// enumerates. Rust's `From` trait does not auto-derive the
// borrowed-input sibling from a paired owned-input impl (no
// `impl<T, U> From<&T> for U where T: Copy, U: From<T>`
// blanket in `core`), so the borrowed-input axis is a distinct
// trait-idiomatic surface that a `.iter().map(Into::into)`
// shape over [`PlacementStrategy::ALL`] (whose iterator yields
// `&PlacementStrategy`, not `PlacementStrategy`) reaches
// through this impl and no other — the paired owned-input
// [`From<PlacementStrategy>`] impl requires an explicit
// `.copied()` / dereference before the trait fires.
// Materializes the `<&'static str as
// From<&PlacementStrategy>>::from` output in a `const`-shape
// binding to make the `'static` lifetime promise a build-time
// invariant. Peer of the sibling
// [`crate::dep::tests::dep_list_from_borrowed_into_static_str_routes_through_as_str_accessor`]
// (64aa742) /
// [`crate::kind::tests::caixa_kind_from_borrowed_into_static_str_routes_through_as_str_accessor`]
// (5ab993a) /
// [`crate::dialeto::tests::caixa_dialeto_from_borrowed_into_static_str_routes_through_as_str_accessor`]
// (807b0b5) /
// [`crate::supervisor::tests::restart_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
// (e941836) /
// [`crate::supervisor::tests::restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
// (842c7f3) pins on the sibling closed-set typed-enum
// borrowed-input forward-projection axes — extends the
// borrowed-input axis onto the first M3-mesh-primitive-defining
// closed-set typed enum on the caixa surface.
const SINGLE_NODE: &str = PlacementStrategy::SingleNode.as_str();
const REPLICATED: &str = PlacementStrategy::Replicated.as_str();
const SHARDED: &str = PlacementStrategy::Sharded.as_str();
for variant in PlacementStrategy::ALL {
let via_trait: &'static str = <&'static str as From<&PlacementStrategy>>::from(variant);
let via_method: &'static str = variant.as_str();
assert_eq!(
via_trait, via_method,
"From<&PlacementStrategy> for &'static str impl must \
round-trip &PlacementStrategy::{variant:?} to the same \
lifted M3_PLACEMENT_ESTRATEGIA_* const \
PlacementStrategy::as_str returns — divergence signals \
a silent detour off the substrate-primitive accessor"
);
let via_into: &'static str = variant.into();
assert_eq!(
via_into, via_method,
"Into<&'static str>::into on &PlacementStrategy::{variant:?} \
must byte-equal PlacementStrategy::as_str on the same \
input — the blanket-derived Into shape must resolve to \
the same as_str dispatch as the explicit From impl"
);
}
assert_eq!(
[SINGLE_NODE, REPLICATED, SHARDED],
[
crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
],
"const-context PlacementStrategy::as_str must resolve to the \
three lifted M3_PLACEMENT_ESTRATEGIA_* consts — the \
borrowed-input From<&PlacementStrategy> for &'static str \
impl inherits its `'static` lifetime promise from the same \
accessor the owned-input sibling routes through"
);
}
#[test]
fn placement_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
// Cross-axis partition pin: the paired trait-idiomatic
// owned-input `From<PlacementStrategy> for &'static str`
// (afa3562 campaign-shape) and borrowed-input
// `From<&PlacementStrategy> for &'static str` (this lift)
// forward projections must resolve identically on every arm,
// locking the two input-shape paths together so any future
// detour trips at caixa-core test time. Then a witness that a
// `.iter().map(Into::into)` pipe over
// [`PlacementStrategy::ALL`] (whose iterator yields
// `&PlacementStrategy`) materializes the three-arm accept-set
// through the borrowed-input axis alone — the exact shape a
// future M4 admission-webhook rejection body's accepted-set
// enumeration, a future substrate-wide per-arm diagnostic
// column, or a
// `HashMap::<&'static str, PlacementStrategy>::from_iter(
// PlacementStrategy::ALL.iter().map(|s| (s.into(), *s)))`-
// style per-strategy lookup reaches through — closing the
// two-way owned/borrowed input-shape symmetry on the M3 slot
// enum's forward-projection trait-idiomatic axis. Peer of the
// sibling
// [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
// (64aa742) /
// [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
// (5ab993a) /
// [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
// (807b0b5) /
// [`crate::supervisor::tests::restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
// (e941836) /
// [`crate::supervisor::tests::restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
// (842c7f3) partition pins on the sibling closed-set typed-enum
// discriminator axes — extends the borrowed-input axis
// discipline onto the first M3-mesh-primitive-defining closed-
// set typed enum on the caixa surface (the `:placement
// :estrategia` axis). Also closes the direct two-way `&Self →
// &'static str → Self` round-trip via the paired
// [`TryFrom<&str>`] axis — unlike the peer [`crate::CaixaKind`]
// axis pair (whose forward `From` emits lowercase Portuguese
// diagnostic bytes while the reverse `TryFrom` parses
// `PascalCase` wire bytes, forcing the round-trip through an
// intermediate wire-vocab hop), the
// [`PlacementStrategy::as_str`] emit and
// [`PlacementStrategy::from_wire`] parse share the same
// `PascalCase` vocabulary by construction, so the borrowed-
// input forward axis and the reverse axis compose directly.
for &variant in PlacementStrategy::ALL {
let owned: &'static str = <&'static str as From<PlacementStrategy>>::from(variant);
let borrowed: &'static str = <&'static str as From<&PlacementStrategy>>::from(&variant);
assert_eq!(
owned, borrowed,
"From<PlacementStrategy> and From<&PlacementStrategy> \
for &'static str must resolve identically on \
PlacementStrategy::{variant:?} — divergence signals \
the owned-input and borrowed-input forward-projection \
paths have drifted onto different emit-sets"
);
}
let via_iter: Vec<&'static str> = PlacementStrategy::ALL.iter().map(Into::into).collect();
let via_method: Vec<&'static str> =
PlacementStrategy::ALL.iter().map(|s| s.as_str()).collect();
assert_eq!(
via_iter, via_method,
"`.iter().map(Into::into)` over PlacementStrategy::ALL must \
byte-equal `.iter().map(|s| s.as_str())` on every arm — \
the borrowed-input `From<&PlacementStrategy> for &'static \
str` axis is what makes the `.iter().map(Into::into)` \
shape route through the substrate-primitive \
`PlacementStrategy::as_str` accessor rather than through a \
per-call-site `.copied()` / dereference detour"
);
for variant in PlacementStrategy::ALL {
let emitted: &'static str = variant.into();
let re_parsed: Result<PlacementStrategy, ()> =
<PlacementStrategy as TryFrom<&str>>::try_from(emitted);
assert_eq!(
re_parsed,
Ok(*variant),
"trait-idiomatic borrowed-input forward-projection + \
reverse-projection axis pair must round-trip \
&PlacementStrategy::{variant:?} through `.into::<&'static \
str>()` (via the borrowed-input axis) and back through \
`TryFrom<&str>` — a break signals the borrowed-input \
forward-emit and reverse-parse axes have drifted onto \
different vocabularies"
);
}
}
#[test]
fn placement_strategy_from_into_owned_string_routes_through_as_str_accessor() {
// Fail-before-pass-after byte-parity pin on the newly lifted
// `impl From<PlacementStrategy> for String` — asserts the
// owned-`String`-returning standard-library trait impl and the
// substrate-primitive [`PlacementStrategy::as_str`] `pub const
// fn` accessor resolve to the same three-arm emit-set across
// every arm the exhaustive [`PlacementStrategy::ALL`] slice
// enumerates. Rust's standard library does not carry a blanket
// `impl<T: AsRef<str>> From<T> for String` (nor an
// `impl<T: fmt::Display> From<T> for String`), so the
// owned-`String` forward-projection axis is a distinct trait-
// idiomatic surface that a `let key: String = strategy.into();`-
// shaped call site reaches through this impl and no other — the
// paired sibling `From<PlacementStrategy> for &'static str` impl
// forces every owned-`String` call site through an explicit
// `.to_owned()` / `String::from` restatement. Peer of the
// first-mover
// [`crate::supervisor::tests::restart_strategy_from_into_owned_string_routes_through_as_str_accessor`]
// (7baa18a), the second-peer
// [`crate::supervisor::tests::restart_policy_from_into_owned_string_routes_through_as_str_accessor`]
// (7851725), the third-peer
// [`crate::kind::tests::caixa_kind_from_into_owned_string_routes_through_as_str_accessor`]
// (231a18c), the fourth-peer
// [`crate::dialeto::tests::caixa_dialeto_from_into_owned_string_routes_through_as_str_accessor`]
// (88942cd), and the fifth-peer
// [`crate::dep::tests::dep_list_from_into_owned_string_routes_through_as_str_accessor`]
// (32b0ee8) — extends the trait-idiomatic owned-`String`
// forward-projection axis onto the sixth closed-set fieldless
// typed enum on the caixa surface (the first
// M3-mesh-primitive-defining `:placement :estrategia`
// distribution-strategy axis).
for &variant in PlacementStrategy::ALL {
let via_trait: String = <String as From<PlacementStrategy>>::from(variant);
let via_method: &'static str = variant.as_str();
assert_eq!(
via_trait.as_str(),
via_method,
"From<PlacementStrategy> for String impl must round-trip \
PlacementStrategy::{variant:?} to the same lifted \
M3_PLACEMENT_ESTRATEGIA_* const PlacementStrategy::as_str \
returns — divergence signals a silent detour off the \
substrate-primitive accessor"
);
let via_into: String = variant.into();
assert_eq!(
via_into.as_str(),
via_method,
"Into<String>::into on PlacementStrategy::{variant:?} must \
byte-equal PlacementStrategy::as_str on the same input — \
the blanket-derived Into shape must resolve to the same \
as_str dispatch as the explicit From impl"
);
}
}
#[test]
fn placement_strategy_from_into_owned_string_and_static_str_agree_on_every_arm() {
// Cross-axis partition pin: the paired trait-idiomatic
// owned-`String` `From<PlacementStrategy> for String` (this
// lift) and owned-`&'static str` `From<PlacementStrategy> for
// &'static str` (afa3562) forward projections must resolve
// identically on every arm, locking the two return-type-shape
// paths together so any future detour trips at caixa-core test
// time. Also byte-parity witness against the sibling
// [`ToString::to_string`] surface routed through
// [`std::fmt::Display`] — the three owned-heap-string paths
// (`.into::<String>()`, `String::from`, `.to_string()`) must
// resolve identically on every arm so a future consumer that
// picks any of the three lands on the same three-arm lifted
// [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`] accept-set. Then
// a `.iter().copied().map(String::from)` pipe witness over
// [`PlacementStrategy::ALL`] that materializes the three-arm
// accept-set through the owned-`String` axis alone — the exact
// shape a future M4 admission-webhook rejection body composer
// or a `HashMap::<String,
// PlacementStrategy>::from_iter(PlacementStrategy::ALL.iter()
// .copied().map(|s| (s.into(), s)))`-style owned-key
// per-strategy lookup reaches through — closing the
// owned-`String` forward-projection axis's iterator-pipe shape.
// Then a direct round-trip witness through the paired trait-
// idiomatic reverse [`TryFrom<&str>`] axis on the
// owned-`String`'s [`String::as_str`] borrow that closes the
// two-way `Self → String → Self` round-trip on the trait-
// idiomatic owned-`String` forward + reverse axis pair.
//
// Unlike the peer [`crate::CaixaKind`] axis pair (whose forward
// `From` emit lands on the lowercase Portuguese `as_str`
// diagnostic vocabulary while the reverse `TryFrom<&str>`
// parses the `PascalCase` `wire_name` author-surface
// vocabulary, forcing the round-trip through an intermediate
// [`crate::CaixaKind::wire_name`] hop), [`PlacementStrategy`]'s
// [`PlacementStrategy::as_str`] emit and
// [`PlacementStrategy::from_wire`] parse resolve through the
// same three lifted
// [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`] consts by
// construction (there is no wire/diagnostic axis split on this
// enum), so the owned-`String` forward axis and the reverse
// axis compose directly — matching the peer
// [`crate::supervisor::RestartStrategy`] /
// [`crate::supervisor::RestartPolicy`] /
// [`crate::CaixaDialeto`] / [`crate::dep::DepList`]
// owned-`String` axis pairs.
for &variant in PlacementStrategy::ALL {
let owned_string: String = <String as From<PlacementStrategy>>::from(variant);
let owned_static: &'static str =
<&'static str as From<PlacementStrategy>>::from(variant);
assert_eq!(
owned_string.as_str(),
owned_static,
"From<PlacementStrategy> for String and \
From<PlacementStrategy> for &'static str must resolve \
identically on PlacementStrategy::{variant:?} — \
divergence signals the owned-`String` and \
owned-`&'static str` forward-projection return-type-\
shape paths have drifted onto different emit-sets"
);
let via_to_string: String = variant.to_string();
assert_eq!(
owned_string, via_to_string,
"From<PlacementStrategy> for String must byte-equal \
PlacementStrategy::to_string on \
PlacementStrategy::{variant:?} — divergence signals the \
trait-idiomatic owned-`String` forward-projection axis \
and the ToString-through-Display axis have drifted onto \
different emit-sets"
);
}
let via_iter: Vec<String> = PlacementStrategy::ALL
.iter()
.copied()
.map(String::from)
.collect();
let via_method: Vec<String> = PlacementStrategy::ALL
.iter()
.map(|s| s.as_str().to_owned())
.collect();
assert_eq!(
via_iter, via_method,
"`.iter().copied().map(String::from)` over \
PlacementStrategy::ALL must byte-equal `.iter().map(|s| \
s.as_str().to_owned())` on every arm — the owned-`String` \
`From<PlacementStrategy> for String` axis is what makes the \
`String::from` composition route through the substrate-\
primitive `PlacementStrategy::as_str` accessor rather than \
through a per-call-site `.to_owned()` / \
`String::from(strategy.as_str())` detour"
);
for &variant in PlacementStrategy::ALL {
let emitted: String = variant.into();
let re_parsed: Result<PlacementStrategy, ()> =
<PlacementStrategy as TryFrom<&str>>::try_from(emitted.as_str());
assert_eq!(
re_parsed,
Ok(variant),
"trait-idiomatic owned-`String` forward-projection + \
reverse-projection axis pair must round-trip \
PlacementStrategy::{variant:?} through `.into::<String>()` \
and back through `TryFrom<&str>` on the owned-`String`'s \
String::as_str borrow — a break signals the owned-\
`String` forward-emit and reverse-parse axes have \
drifted onto different vocabularies (unlike the peer \
CaixaKind axis pair, PlacementStrategy's forward emit \
and reverse parse share the same lifted \
M3_PLACEMENT_ESTRATEGIA_* consts by construction, so \
the round-trip composes directly)"
);
}
}
#[test]
fn placement_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor() {
// Fail-before-pass-after byte-parity pin on the newly lifted
// `impl From<&PlacementStrategy> for String` — asserts the
// borrowed-input owned-`String`-returning standard-library trait
// impl and the substrate-primitive [`PlacementStrategy::as_str`]
// `pub const fn` accessor resolve to the same three-arm emit-set
// across every arm the exhaustive [`PlacementStrategy::ALL`]
// slice enumerates. Rust's standard library does not carry a
// blanket `impl<T: AsRef<str>> From<&T> for String` (nor an
// `impl<T: fmt::Display> From<&T> for String`), so the
// borrowed-input owned-`String` forward-projection axis is a
// distinct trait-idiomatic surface that a
// `let key: String = (&strategy).into();`-shaped call site
// reaches through this impl and no other — the paired sibling
// `From<PlacementStrategy> for String` impl forces every
// borrowed-input call site through an explicit `Copy` deref
// (`String::from(*strategy)`) or an `.as_str().to_owned()` /
// `.to_string()` detour. Peer of the first-mover
// [`crate::supervisor::tests::restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
// (579385f), the second-peer
// [`crate::supervisor::tests::restart_policy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
// (8465740), the third-peer
// [`crate::dep::tests::dep_list_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
// (e0cb617), the fourth-peer
// [`crate::kind::tests::caixa_kind_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
// (e76436d), and the fifth-peer
// [`crate::dialeto::tests::caixa_dialeto_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
// (d3c0d1d) — extends the trait-idiomatic borrowed-input owned-
// `String` forward-projection axis onto the sixth closed-set
// fieldless typed enum on the caixa surface (the first
// M3-mesh-primitive-defining `:placement :estrategia`
// distribution-strategy axis).
for &variant in PlacementStrategy::ALL {
let via_trait: String = <String as From<&PlacementStrategy>>::from(&variant);
let via_method: &'static str = variant.as_str();
assert_eq!(
via_trait.as_str(),
via_method,
"From<&PlacementStrategy> for String impl must round-trip \
&PlacementStrategy::{variant:?} to the same lifted \
M3_PLACEMENT_ESTRATEGIA_* const PlacementStrategy::as_str \
returns — divergence signals a silent detour off the \
substrate-primitive accessor"
);
let via_into: String = (&variant).into();
assert_eq!(
via_into.as_str(),
via_method,
"Into<String>::into on &PlacementStrategy::{variant:?} \
must byte-equal PlacementStrategy::as_str on the same \
input — the blanket-derived Into shape must resolve to \
the same as_str dispatch as the explicit From impl"
);
}
}
#[test]
fn placement_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm() {
// Cross-axis partition pin: the newly lifted trait-idiomatic
// borrowed-input owned-`String`
// `From<&PlacementStrategy> for String` (this lift), the paired
// owned-input owned-`String`
// `From<PlacementStrategy> for String` (1154c2f), the paired
// borrowed-input owned-`&'static str`
// `From<&PlacementStrategy> for &'static str` (4d941d8), and the
// paired owned-input owned-`&'static str`
// `From<PlacementStrategy> for &'static str` (afa3562) — every
// corner of the `{Self, &Self} × {&'static str, String}` 2×2
// trait-idiomatic projection family — must resolve identically
// on every arm, locking the four return-shape × input-shape
// paths together so any future detour trips at caixa-core test
// time. Also byte-parity witness against the sibling
// [`ToString::to_string`] surface routed through
// [`std::fmt::Display`] and a direct round-trip witness through
// the paired trait-idiomatic reverse [`TryFrom<&str>`] axis on
// the owned-`String`'s [`String::as_str`] borrow that closes
// the two-way `&Self → String → Self` round-trip on the trait-
// idiomatic borrowed-input owned-`String` forward + reverse
// axis pair. Peer of the first-mover
// [`crate::supervisor::tests::restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
// (579385f), the second-peer
// [`crate::supervisor::tests::restart_policy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
// (8465740), the third-peer
// [`crate::dep::tests::dep_list_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
// (e0cb617), the fourth-peer
// [`crate::kind::tests::caixa_kind_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
// (e76436d), and the fifth-peer
// [`crate::dialeto::tests::caixa_dialeto_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
// (d3c0d1d) — closes the whole `{Self, &Self} × {&'static str,
// String}` 2×2 projection corner on the sixth substrate-wide
// closed-set fieldless typed enum peer (the first
// M3-mesh-primitive-defining `:placement :estrategia`
// distribution-strategy axis, first M3 slot enum to reach the
// 2×2-completion corner).
//
// Unlike the peer [`crate::CaixaKind`] axis pair (whose forward
// `From` emit lands on the lowercase Portuguese `as_str`
// diagnostic vocabulary while the reverse `TryFrom<&str>`
// parses the `PascalCase` `wire_name` author-surface
// vocabulary, forcing the round-trip through an intermediate
// [`crate::CaixaKind::wire_name`] hop), [`PlacementStrategy`]'s
// [`PlacementStrategy::as_str`] emit and
// [`PlacementStrategy::from_wire`] parse resolve through the
// same three lifted [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`]
// consts by construction (there is no wire/diagnostic axis
// split on this M3 slot enum), so the borrowed-input
// owned-`String` forward axis and the reverse axis compose
// directly — matching the peer
// [`crate::supervisor::RestartStrategy`] /
// [`crate::supervisor::RestartPolicy`] / [`crate::dep::DepList`]
// / [`crate::CaixaDialeto`] borrowed-input owned-`String` axis
// pairs.
for &variant in PlacementStrategy::ALL {
let borrowed_string: String = <String as From<&PlacementStrategy>>::from(&variant);
let owned_string: String = <String as From<PlacementStrategy>>::from(variant);
let borrowed_static: &'static str =
<&'static str as From<&PlacementStrategy>>::from(&variant);
let owned_static: &'static str =
<&'static str as From<PlacementStrategy>>::from(variant);
assert_eq!(
borrowed_string, owned_string,
"From<&PlacementStrategy> for String and \
From<PlacementStrategy> for String must resolve \
identically on PlacementStrategy::{variant:?} — \
divergence signals the borrowed-input and owned-input \
owned-`String` forward-projection input-shape paths \
have drifted onto different emit-sets"
);
assert_eq!(
borrowed_string.as_str(),
borrowed_static,
"From<&PlacementStrategy> for String and \
From<&PlacementStrategy> for &'static str must resolve \
identically on PlacementStrategy::{variant:?} — \
divergence signals the borrowed-input `&'static str` \
and owned-`String` return-shape paths have drifted \
onto different emit-sets"
);
assert_eq!(
borrowed_string.as_str(),
owned_static,
"From<&PlacementStrategy> for String and \
From<PlacementStrategy> for &'static str must resolve \
identically on PlacementStrategy::{variant:?} — \
divergence signals a break in the diagonal corner of \
the {{Self, &Self}} × {{&'static str, String}} 2×2 \
trait-idiomatic projection family"
);
let via_to_string: String = variant.to_string();
assert_eq!(
borrowed_string, via_to_string,
"From<&PlacementStrategy> for String must byte-equal \
PlacementStrategy::to_string on \
PlacementStrategy::{variant:?} — divergence signals \
the trait-idiomatic borrowed-input owned-`String` \
forward-projection axis and the ToString-through-\
Display axis have drifted onto different emit-sets"
);
}
let via_iter: Vec<String> = PlacementStrategy::ALL.iter().map(String::from).collect();
let via_method: Vec<String> = PlacementStrategy::ALL
.iter()
.map(|s| s.as_str().to_owned())
.collect();
assert_eq!(
via_iter, via_method,
"`.iter().map(String::from)` over PlacementStrategy::ALL — \
a call site whose iteration axis holds \
`&PlacementStrategy` by construction — must byte-equal \
`.iter().map(|s| s.as_str().to_owned())` on every arm — \
the borrowed-input owned-`String` \
`From<&PlacementStrategy> for String` axis is what makes \
the `String::from` composition route through the \
substrate-primitive `PlacementStrategy::as_str` accessor \
without a spurious `Copy` deref (which would only be \
reachable through the owned-input \
`From<PlacementStrategy> for String` axis by first \
calling `.copied()` on the iterator)"
);
for &variant in PlacementStrategy::ALL {
let emitted: String = (&variant).into();
let re_parsed: Result<PlacementStrategy, ()> =
<PlacementStrategy as TryFrom<&str>>::try_from(emitted.as_str());
assert_eq!(
re_parsed,
Ok(variant),
"trait-idiomatic borrowed-input owned-`String` \
forward-projection + reverse-projection axis pair \
must round-trip &PlacementStrategy::{variant:?} \
through `.into::<String>()` on the borrowed-input \
surface and back through `TryFrom<&str>` on the \
owned-`String`'s String::as_str borrow — a break \
signals the borrowed-input owned-`String` \
forward-emit and reverse-parse axes have drifted onto \
different vocabularies (unlike the peer CaixaKind \
axis pair, PlacementStrategy's forward emit and \
reverse parse share the same lifted \
M3_PLACEMENT_ESTRATEGIA_* consts by construction, so \
the round-trip composes directly)"
);
}
}
#[test]
fn placement_strategy_from_into_static_cow_str_routes_through_as_str_accessor() {
// Fail-before-pass-after byte-parity pin on the newly lifted
// `impl From<PlacementStrategy> for
// std::borrow::Cow<'static, str>` — asserts the standard-
// library trait impl and the substrate-primitive
// [`super::PlacementStrategy::as_str`] `pub const fn`
// accessor resolve to the same three-arm emit-set across
// every arm the exhaustive [`super::PlacementStrategy::ALL`]
// slice enumerates. Rust's standard library does not carry a
// blanket `impl<T: AsRef<str>> From<T> for Cow<'static, str>`
// (nor an `impl<T: fmt::Display> From<T> for
// Cow<'static, str>`), so the `Cow<'static, str>` forward-
// projection axis is a distinct trait-idiomatic surface that
// a `let key: Cow<'static, str> = strategy.into();`-shaped
// call site reaches through this impl and no other — the
// paired sibling `From<PlacementStrategy> for &'static str`
// and `From<PlacementStrategy> for String` impls force every
// `Cow<'static, str>`-parameterized call site through a
// `Cow::Borrowed(strategy.as_str())` /
// `Cow::Owned(strategy.to_string())` composition whose type
// bounds have no compile-time link back to the substrate
// primitive.
//
// Also asserts the projection lands on the zero-alloc
// [`std::borrow::Cow::Borrowed`] arm (not the
// [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
// [`super::PlacementStrategy::as_str`] accessor's
// `&'static str` return lifetime by construction (each match
// arm resolves to one of the three lifted
// [`super::render::M3_PLACEMENT_ESTRATEGIA_*`] `pub const
// &str` values) makes the borrowed arm the type-correct
// projection with no runtime allocation. Any future silent
// detour that routes the impl through the owned arm trips at
// caixa-core test time under the
// [`std::borrow::Cow::Borrowed`] discriminator witness
// rather than at a downstream `Cow<'static, str>`-bound
// consumer's silent allocation.
//
// Second M3-mesh-primitive-defining peer on the substrate-
// wide trait-idiomatic [`std::borrow::Cow<'static, str>`]
// forward-projection campaign — extends the axis off the
// first M3-mesh-primitive peer (the [`super::WitShape`]
// `:contratos :wit` census-label axis: 8634dec owned-input +
// 25690ef borrowed-input) onto the second M3-slot-enum peer,
// ahead of the sibling [`super::RateLimitUnit`] whose
// Cow<'static, str> axis remains a future target.
for &variant in PlacementStrategy::ALL {
let via_trait: std::borrow::Cow<'static, str> =
<std::borrow::Cow<'static, str> as From<PlacementStrategy>>::from(variant);
let via_method: &'static str = variant.as_str();
assert_eq!(
via_trait.as_ref(),
via_method,
"From<PlacementStrategy> for Cow<'static, str> impl \
must round-trip PlacementStrategy::{variant:?} to \
the same lifted M3_PLACEMENT_ESTRATEGIA_* const \
PlacementStrategy::as_str returns — divergence \
signals a silent detour off the substrate-primitive \
accessor"
);
assert!(
matches!(via_trait, std::borrow::Cow::Borrowed(_)),
"From<PlacementStrategy> for Cow<'static, str> impl \
must land on the zero-alloc Cow::Borrowed arm on \
PlacementStrategy::{variant:?} — a Cow::Owned \
outcome signals the projection has silently \
allocated where the substrate-primitive \
PlacementStrategy::as_str `&'static str` return \
makes the borrowed arm the type-correct projection"
);
let via_into: std::borrow::Cow<'static, str> = variant.into();
assert_eq!(
via_into.as_ref(),
via_method,
"Into<Cow<'static, str>>::into on \
PlacementStrategy::{variant:?} must byte-equal \
PlacementStrategy::as_str on the same input — the \
blanket-derived Into shape must resolve to the same \
as_str dispatch as the explicit From impl"
);
assert!(
matches!(via_into, std::borrow::Cow::Borrowed(_)),
"Into<Cow<'static, str>>::into on \
PlacementStrategy::{variant:?} must land on the \
zero-alloc Cow::Borrowed arm — the blanket-derived \
Into shape must resolve to the same Cow::Borrowed \
dispatch as the explicit From impl"
);
}
}
#[test]
fn placement_strategy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
// Cross-axis partition pin: the newly lifted trait-idiomatic
// `From<PlacementStrategy> for std::borrow::Cow<'static, str>`
// (this lift), the paired owned-input `From<PlacementStrategy>
// for &'static str`, and the paired owned-input
// `From<PlacementStrategy> for String` forward projections
// must resolve identically on every arm, locking the three
// return-shape paths together by construction so any future
// detour trips at caixa-core test time. Also byte-parity
// witness against the sibling [`ToString::to_string`] surface
// routed through [`std::fmt::Display`] — every owned-heap-
// string path (the `Cow::Owned` promotion of this axis's
// `.into_owned()`, `From<PlacementStrategy> for String`, and
// `.to_string()`) resolves to the same three-arm lifted
// M3_PLACEMENT_ESTRATEGIA_* byte-string per arm.
//
// Then a `.iter().copied().map(std::borrow::Cow::from)` pipe
// witness over [`super::PlacementStrategy::ALL`] that
// materializes the three-arm accept-set through the
// [`std::borrow::Cow<'static, str>`] axis alone — the exact
// shape a future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
// admission-webhook rejection body's accepted-`:placement
// :estrategia` enumeration, a future substrate-wide per-arm
// diagnostic surface whose typing rules out the sibling
// [`AsRef<str>`] borrowed return, or a future per-arm
// placement-strategy emitter that binds through a
// [`Cow<'static, str>`] boundary reaches through — closing
// the composable-projection axis on the second
// M3-mesh-primitive-defining closed-set fieldless typed enum
// peer on the caixa surface. The pipe witness also pins the
// zero-alloc discipline: every element in the collected
// vector satisfies the [`std::borrow::Cow::Borrowed`] arm
// predicate, so a future accidental silent-allocation
// regression on the pipe's iteration axis is a caixa-core-
// test-time failure.
for &variant in PlacementStrategy::ALL {
let via_cow: std::borrow::Cow<'static, str> =
<std::borrow::Cow<'static, str> as From<PlacementStrategy>>::from(variant);
let via_static: &'static str = <&'static str as From<PlacementStrategy>>::from(variant);
let via_string: String = <String as From<PlacementStrategy>>::from(variant);
assert_eq!(
via_cow.as_ref(),
via_static,
"From<PlacementStrategy> for Cow<'static, str> and \
From<PlacementStrategy> for &'static str must \
resolve identically on PlacementStrategy::\
{variant:?} — divergence signals the \
Cow<'static, str> and &'static str return-shape \
paths have drifted onto different emit-sets"
);
assert_eq!(
via_cow.as_ref(),
via_string.as_str(),
"From<PlacementStrategy> for Cow<'static, str> and \
From<PlacementStrategy> for String must resolve \
identically on PlacementStrategy::{variant:?} — \
divergence signals the Cow<'static, str> and String \
return-shape paths have drifted onto different \
emit-sets"
);
let via_to_string: String = variant.to_string();
assert_eq!(
via_cow.as_ref(),
via_to_string.as_str(),
"From<PlacementStrategy> for Cow<'static, str> must \
byte-equal PlacementStrategy::to_string on \
PlacementStrategy::{variant:?} — divergence signals \
the trait-idiomatic Cow<'static, str> forward-\
projection axis and the ToString-through-Display \
axis have drifted onto different emit-sets"
);
}
let via_iter: Vec<std::borrow::Cow<'static, str>> = PlacementStrategy::ALL
.iter()
.copied()
.map(std::borrow::Cow::from)
.collect();
let via_method: Vec<std::borrow::Cow<'static, str>> = PlacementStrategy::ALL
.iter()
.map(|s| std::borrow::Cow::Borrowed(s.as_str()))
.collect();
assert_eq!(
via_iter, via_method,
"`.iter().copied().map(Cow::from)` over \
PlacementStrategy::ALL must byte-equal \
`.iter().map(|s| Cow::Borrowed(s.as_str()))` on every \
arm — the trait-idiomatic `From<PlacementStrategy> for \
Cow<'static, str>` axis is what makes the `Cow::from` \
composition route through the substrate-primitive \
`PlacementStrategy::as_str` accessor with the zero-alloc \
Cow::Borrowed arm by construction, rather than a per-\
call-site `Cow::Owned(strategy.to_string())` allocation"
);
for cow in &via_iter {
assert!(
matches!(cow, std::borrow::Cow::Borrowed(_)),
"every element of the .iter().copied().map(Cow::from) \
pipe over PlacementStrategy::ALL must land on the \
zero-alloc Cow::Borrowed arm — a Cow::Owned outcome \
on any arm signals the pipe's iteration axis has \
silently allocated where the substrate-primitive \
PlacementStrategy::as_str `&'static str` return \
makes the borrowed arm the type-correct projection"
);
}
}
#[test]
fn placement_strategy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor() {
// Fail-before-pass-after byte-parity pin on the newly lifted
// `impl From<&PlacementStrategy> for
// std::borrow::Cow<'static, str>` — asserts the borrowed-input
// standard-library trait impl and the substrate-primitive
// [`super::PlacementStrategy::as_str`] `pub const fn`
// accessor resolve to the same three-arm emit-set across
// every arm the exhaustive [`super::PlacementStrategy::ALL`]
// slice enumerates. Rust's standard library does not carry a
// blanket `impl<T: AsRef<str>> From<&T> for Cow<'static, str>`
// (nor a `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for
// U`), so the borrowed-input `Cow<'static, str>` forward-
// projection axis is a distinct trait-idiomatic surface that
// a `let key: Cow<'static, str> = (&strategy).into();`-shaped
// call site or a `PlacementStrategy::ALL.iter().map(Cow::from)`
// -shaped pipe reaches through this impl and no other — the
// paired owned-input `From<PlacementStrategy> for
// Cow<'static, str>` impl (eee504d) forces every borrowed-
// input call site through an explicit `Copy` deref
// (`Cow::from(*strategy)`) or a
// `Cow::Borrowed(strategy.as_str())` open-code whose type
// bounds have no compile-time link back to the substrate
// primitive.
//
// Also asserts the projection lands on the zero-alloc
// [`std::borrow::Cow::Borrowed`] arm (not the
// [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
// [`super::PlacementStrategy::as_str`] accessor's `&'static
// str` return lifetime by construction (each match arm
// resolves to one of the three lifted
// [`super::render::M3_PLACEMENT_ESTRATEGIA_*`] `pub const
// &str` values) makes the borrowed arm the type-correct
// projection with no runtime allocation on the borrowed-input
// surface just as on the paired owned-input surface.
//
// Closes the `{Self, &Self}` input-shape corner on the M3-
// mesh-shape `:placement :estrategia` distribution-strategy
// [`Cow<'static, str>`] axis on the second M3-mesh-primitive-
// defining closed-set fieldless typed enum peer on the caixa
// surface, exactly as 25690ef closed it on the first M3-mesh-
// primitive peer ([`super::WitShape`]) one commit after the
// owning half (8634dec) landed, as d45c409 closed it on the
// top-level [`super::CaixaKind`] one commit after the owning
// half (99c1735) landed, and as 9b3e4b3 / ee577fd closed it
// on the M2 OTP-shape [`crate::supervisor::RestartStrategy`] /
// [`crate::supervisor::RestartPolicy`] sibling peers one
// commit after (7dd28b3 / 0612398) landed.
for &variant in PlacementStrategy::ALL {
let via_trait: std::borrow::Cow<'static, str> =
<std::borrow::Cow<'static, str> as From<&PlacementStrategy>>::from(&variant);
let via_method: &'static str = variant.as_str();
assert_eq!(
via_trait.as_ref(),
via_method,
"From<&PlacementStrategy> for Cow<'static, str> impl \
must round-trip &PlacementStrategy::{variant:?} to \
the same lifted M3_PLACEMENT_ESTRATEGIA_* const \
PlacementStrategy::as_str returns — divergence \
signals a silent detour off the substrate-primitive \
accessor"
);
assert!(
matches!(via_trait, std::borrow::Cow::Borrowed(_)),
"From<&PlacementStrategy> for Cow<'static, str> impl \
must land on the zero-alloc Cow::Borrowed arm on \
&PlacementStrategy::{variant:?} — a Cow::Owned \
outcome signals the projection has silently \
allocated where the substrate-primitive \
PlacementStrategy::as_str `&'static str` return \
makes the borrowed arm the type-correct projection"
);
let via_into: std::borrow::Cow<'static, str> = (&variant).into();
assert_eq!(
via_into.as_ref(),
via_method,
"Into<Cow<'static, str>>::into on \
&PlacementStrategy::{variant:?} must byte-equal \
PlacementStrategy::as_str on the same input — the \
blanket-derived Into shape must resolve to the same \
as_str dispatch as the explicit From impl"
);
assert!(
matches!(via_into, std::borrow::Cow::Borrowed(_)),
"Into<Cow<'static, str>>::into on \
&PlacementStrategy::{variant:?} must land on the \
zero-alloc Cow::Borrowed arm — the blanket-derived \
Into shape must resolve to the same Cow::Borrowed \
dispatch as the explicit From impl"
);
}
}
#[test]
fn placement_strategy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
// Cross-axis partition pin: the newly lifted trait-idiomatic
// borrowed-input `From<&PlacementStrategy> for
// std::borrow::Cow<'static, str>` (this lift), the paired
// owned-input `From<PlacementStrategy> for
// std::borrow::Cow<'static, str>` (eee504d), the paired
// borrowed-input owned-`&'static str` `From<&PlacementStrategy>
// for &'static str`, and the paired borrowed-input owned-
// `String` `From<&PlacementStrategy> for String` must resolve
// identically on every arm, locking the four return-shape ×
// input-shape paths together by construction so any future
// detour trips at caixa-core test time. Also byte-parity
// witness against the sibling [`ToString::to_string`] surface
// routed through [`std::fmt::Display`] — every owned-heap-
// string path (this axis's `.into_owned()` promotion, the
// paired [`From<&PlacementStrategy> for String`], and
// `.to_string()`) resolves to the same three-arm lifted
// M3_PLACEMENT_ESTRATEGIA_* byte-string per arm.
//
// Then a `.iter().map(std::borrow::Cow::from)` pipe witness
// over [`super::PlacementStrategy::ALL`] — whose iterator
// yields `&PlacementStrategy` by construction, so the
// borrowed-input [`Cow<'static, str>`] axis is what routes
// the pipe through the substrate-primitive
// [`super::PlacementStrategy::as_str`] accessor without a
// spurious [`Copy`] deref (which would only be reachable
// through the owned-input [`From<PlacementStrategy> for
// Cow<'static, str>`] axis by first calling `.copied()` on
// the iterator). The pipe witness also pins the zero-alloc
// discipline: every element in the collected vector
// satisfies the [`std::borrow::Cow::Borrowed`] arm predicate,
// so a future accidental silent-allocation regression on the
// pipe's iteration axis is a caixa-core-test-time failure.
// Peer of the sibling
// [`wit_shape_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
// (25690ef) on the M3 mesh-shape `:contratos :wit` axis —
// extends the whole borrowed-input `Cow<'static, str>` +
// paired `{&'static str, String}` cross-axis-parity corner
// onto the second M3-mesh-primitive-defining closed-set
// fieldless typed enum peer on the caixa surface.
for &variant in PlacementStrategy::ALL {
let borrowed_cow: std::borrow::Cow<'static, str> =
<std::borrow::Cow<'static, str> as From<&PlacementStrategy>>::from(&variant);
let owned_cow: std::borrow::Cow<'static, str> =
<std::borrow::Cow<'static, str> as From<PlacementStrategy>>::from(variant);
let borrowed_static: &'static str =
<&'static str as From<&PlacementStrategy>>::from(&variant);
let borrowed_string: String = <String as From<&PlacementStrategy>>::from(&variant);
assert_eq!(
borrowed_cow, owned_cow,
"From<&PlacementStrategy> for Cow<'static, str> and \
From<PlacementStrategy> for Cow<'static, str> must \
resolve identically on PlacementStrategy::\
{variant:?} — divergence signals the borrowed-input \
and owned-input Cow<'static, str> forward-projection \
input-shape paths have drifted onto different \
emit-sets"
);
assert_eq!(
borrowed_cow.as_ref(),
borrowed_static,
"From<&PlacementStrategy> for Cow<'static, str> and \
From<&PlacementStrategy> for &'static str must \
resolve identically on PlacementStrategy::\
{variant:?} — divergence signals the borrowed-input \
Cow<'static, str> and &'static str return-shape paths \
have drifted onto different emit-sets"
);
assert_eq!(
borrowed_cow.as_ref(),
borrowed_string.as_str(),
"From<&PlacementStrategy> for Cow<'static, str> and \
From<&PlacementStrategy> for String must resolve \
identically on PlacementStrategy::{variant:?} — \
divergence signals the borrowed-input \
Cow<'static, str> and owned-`String` return-shape \
paths have drifted onto different emit-sets"
);
let via_to_string: String = variant.to_string();
assert_eq!(
borrowed_cow.as_ref(),
via_to_string.as_str(),
"From<&PlacementStrategy> for Cow<'static, str> must \
byte-equal PlacementStrategy::to_string on \
PlacementStrategy::{variant:?} — divergence signals \
the trait-idiomatic borrowed-input Cow<'static, str> \
forward-projection axis and the ToString-through-\
Display axis have drifted onto different emit-sets"
);
}
let via_iter: Vec<std::borrow::Cow<'static, str>> = PlacementStrategy::ALL
.iter()
.map(std::borrow::Cow::from)
.collect();
let via_method: Vec<std::borrow::Cow<'static, str>> = PlacementStrategy::ALL
.iter()
.map(|s| std::borrow::Cow::Borrowed(s.as_str()))
.collect();
assert_eq!(
via_iter, via_method,
"`.iter().map(Cow::from)` over PlacementStrategy::ALL — a \
call site whose iteration axis holds &PlacementStrategy \
by construction — must byte-equal `.iter().map(|s| \
Cow::Borrowed(s.as_str()))` on every arm — the borrowed-\
input Cow<'static, str> `From<&PlacementStrategy> for \
Cow<'static, str>` axis is what makes the `Cow::from` \
composition route through the substrate-primitive \
`PlacementStrategy::as_str` accessor with the zero-alloc \
Cow::Borrowed arm by construction and without a spurious \
`Copy` deref (which would only be reachable through the \
owned-input `From<PlacementStrategy> for Cow<'static, \
str>` axis by first calling `.copied()` on the iterator)"
);
for cow in &via_iter {
assert!(
matches!(cow, std::borrow::Cow::Borrowed(_)),
"every element of the .iter().map(Cow::from) pipe \
over PlacementStrategy::ALL must land on the zero-\
alloc Cow::Borrowed arm — a Cow::Owned outcome on \
any arm signals the pipe's iteration axis has \
silently allocated where the substrate-primitive \
PlacementStrategy::as_str `&'static str` return \
makes the borrowed arm the type-correct projection"
);
}
}
#[test]
fn rejects_zero_policy_timeout() {
let mut s = three_member_spec();
s.politicas.timeout = Some(Duration::ZERO);
assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
}
#[test]
fn rejects_zero_policy_retries() {
let mut s = three_member_spec();
s.politicas.retries = Some(0);
assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyRetriesZero);
}
#[test]
fn rejects_policy_retries_above_cap() {
// The fail-before-pass-after pin: `Some(11)` is structurally
// one past the [`POLICY_RETRIES_MAX`] ceiling and silently
// passed validate on every pre-gate codebase because the
// typed slot's only check was the zero-floor arm. The
// thundering-herd amplification vector only surfaced at the
// runtime substrate (Envoy / Cilium L7 retry overlay)
// far from the source caixa.lisp with no field naming the
// offending policy.
let mut s = three_member_spec();
s.politicas.retries = Some(POLICY_RETRIES_MAX + 1);
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyRetriesExceedsCap {
retries: POLICY_RETRIES_MAX + 1
}
);
}
#[test]
fn rejects_policy_retries_far_above_cap() {
// The `u32::MAX` worst case — the four-billion-retry policy
// a typo (`(:retries 4294967295)`) or struct-literal
// copy-paste lands in the slot. Pin the cap arm's coverage
// explicitly across the full `u32` overflow so a future
// relaxation that drops the upper bound surfaces here.
let mut s = three_member_spec();
s.politicas.retries = Some(u32::MAX);
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyRetriesExceedsCap { retries: u32::MAX }
);
}
#[test]
fn accepts_policy_retries_at_cap() {
// The boundary value — exactly [`POLICY_RETRIES_MAX`] —
// must validate. The cap is inclusive on the top edge,
// matching the [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
// discipline on the sibling [`crate::LimitsSpec::memory`]
// axis. Pin the boundary explicitly so a future off-by-one
// tightening (`>= POLICY_RETRIES_MAX` instead of `>`)
// surfaces here as a test failure rather than a silent
// contract narrowing.
let mut s = three_member_spec();
s.politicas.retries = Some(POLICY_RETRIES_MAX);
s.validate()
.expect("retries == POLICY_RETRIES_MAX must validate");
}
#[test]
fn accepts_policy_retries_typical_values() {
// The full inclusive `1..=POLICY_RETRIES_MAX` sweep —
// every value in the validated set must pass. The
// Envoy / Istio production-playbook recommendation band
// (`num_retries ≤ 5`) and the AWS App Mesh schema cap
// (`maxRetries ≤ 10`) both lie within this set.
for r in 1..=POLICY_RETRIES_MAX {
let mut s = three_member_spec();
s.politicas.retries = Some(r);
s.validate()
.unwrap_or_else(|e| panic!("retries={r} must validate; got {e:?}"));
}
}
#[test]
fn policy_retries_zero_takes_precedence_over_cap() {
// The cross-arm ordering pin: `Some(0)` is structurally
// outside both `1..` (zero-floor) and `..=POLICY_RETRIES_MAX`
// (cap), but the zero-floor diagnostic is the more
// self-locating one (it directly names the omit-axis
// remediation), so the validate gate must fire on zero
// first. Pin the order so a future refactor that reorders
// the arms surfaces here as a test failure rather than a
// silent diagnostic regression. Same shape every other
// zero-then-shape ordering on this surface uses
// ([`AplicacaoError::PolicyTimeoutZero`] then
// [`AplicacaoError::PolicyTimeoutNotCanonical`];
// [`AplicacaoError::PolicyBreakerZeroWindow`] then
// [`AplicacaoError::PolicyBreakerWindowNotCanonical`]).
let mut s = three_member_spec();
s.politicas.retries = Some(0);
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyRetriesZero,
"Some(0) must surface the zero-floor diagnostic, not the cap diagnostic"
);
}
#[test]
fn policy_retries_cap_diagnostic_carries_offending_value() {
// The diagnostic-shape pin: the offending `u32` is carried
// verbatim into the [`AplicacaoError::PolicyRetriesExceedsCap`]
// variant so the surfaced error message names the value the
// author wrote (`":politicas :retries (47) exceeds the
// mesh-policy ceiling …"`), not just the cap. Same
// self-locating diagnostic shape every other typed-cap arm
// on this surface carries
// ([`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
// offending byte count verbatim).
let mut s = three_member_spec();
s.politicas.retries = Some(47);
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::PolicyRetriesExceedsCap { retries: 47 }),
"got {err:?}"
);
let msg = err.to_string();
assert!(
msg.contains("47"),
":politicas :retries cap diagnostic must carry the offending value verbatim (got: {msg})"
);
}
#[test]
fn policy_retries_cap_is_aws_app_mesh_aligned() {
// The [`POLICY_RETRIES_MAX`] constant pins the value at 10,
// matching AWS App Mesh's `gRPCRouteRetryPolicy.maxRetries`
// schema cap — the only upstream mesh-policy schema that
// documents an explicit hard cap. Pinning the literal value
// here surfaces a future drift (a relaxation to 20, a
// tightening to 5) as a deliberate test edit, not a silent
// contract narrowing.
assert_eq!(POLICY_RETRIES_MAX, 10);
}
#[test]
fn rejects_circuit_breaker_zero_max_failures() {
let mut s = three_member_spec();
s.politicas.circuit_breaker = Some(CircuitBreaker {
max_failures: 0,
window: Duration::from_secs(60),
});
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyBreakerZeroFailures
);
}
#[test]
fn rejects_circuit_breaker_max_failures_above_cap() {
// The fail-before-pass-after pin: `1001` is structurally one
// past the [`POLICY_BREAKER_MAX_FAILURES_MAX`] ceiling and
// silently passed validate on every pre-gate codebase
// because the typed slot's only check was the zero-floor
// arm. The breaker-no-op vector only surfaced at the runtime
// substrate (Envoy / Cilium L7 outlier-detection overlay)
// far from the source caixa.lisp with no field naming the
// offending policy.
let mut s = three_member_spec();
s.politicas.circuit_breaker = Some(CircuitBreaker {
max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
window: Duration::from_secs(60),
});
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
}
);
}
#[test]
fn rejects_circuit_breaker_max_failures_far_above_cap() {
// The `u32::MAX` worst case — the four-billion-failure
// threshold a typo (`(:max-failures 4294967295)`) or a
// struct-literal copy-paste lands in the slot. Pin the cap
// arm's coverage explicitly across the full `u32` overflow
// so a future relaxation that drops the upper bound surfaces
// here.
let mut s = three_member_spec();
s.politicas.circuit_breaker = Some(CircuitBreaker {
max_failures: u32::MAX,
window: Duration::from_secs(60),
});
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
max_failures: u32::MAX,
}
);
}
#[test]
fn accepts_circuit_breaker_max_failures_at_cap() {
// The boundary value — exactly
// [`POLICY_BREAKER_MAX_FAILURES_MAX`] — must validate. The
// cap is inclusive on the top edge, matching the
// [`POLICY_RETRIES_MAX`] / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
// discipline on the sibling capped axes. Pin the boundary
// explicitly so a future off-by-one tightening
// (`>= POLICY_BREAKER_MAX_FAILURES_MAX` instead of `>`)
// surfaces here as a test failure rather than a silent
// contract narrowing.
let mut s = three_member_spec();
s.politicas.circuit_breaker = Some(CircuitBreaker {
max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
window: Duration::from_secs(60),
});
s.validate()
.expect("max_failures == POLICY_BREAKER_MAX_FAILURES_MAX must validate");
}
#[test]
fn accepts_circuit_breaker_max_failures_typical_values() {
// The documented production-playbook band positive-control
// sweep — every value Hystrix / Istio / Envoy / Polly /
// Resilience4j recommend (5..=50) must pass, plus a sweep
// through the hyperscale band (100, 500, 1000) the cap
// accepts. Pin the inclusive validated set explicitly so a
// future tightening of the ceiling surfaces here.
//
// Clears the fixture's `:retries` (which is `Some(3)`) so this
// per-axis sweep is pure: the sibling cross-axis
// [`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
// gate rejects any `max_failures <= retries` pair, so the
// `max_failures = 1` boundary at the head of the sweep would
// otherwise trip on the fixture-inherited retry policy rather
// than the per-axis boundary this test names. Same discipline
// the sibling per-axis `accepts_circuit_breaker_window_*`
// sweeps take against the fixture's `:timeout` for the
// [`AplicacaoError::PolicyBreakerWindowBelowTimeout`]
// cross-axis arm.
for n in [1u32, 5, 10, 20, 50, 100, 500, 1000] {
let mut s = three_member_spec();
s.politicas.retries = None;
s.politicas.circuit_breaker = Some(CircuitBreaker {
max_failures: n,
window: Duration::from_secs(60),
});
s.validate()
.unwrap_or_else(|e| panic!("max_failures={n} must validate; got {e:?}"));
}
}
#[test]
fn circuit_breaker_zero_max_failures_takes_precedence_over_cap() {
// The cross-arm ordering pin: `0` is structurally outside
// both `1..` (zero-floor) and `..=POLICY_BREAKER_MAX_FAILURES_MAX`
// (cap), but the zero-floor diagnostic is the more
// self-locating one (it directly names the omit-axis
// remediation), so the validate gate must fire on zero
// first. Same shape every other zero-then-shape ordering on
// this surface uses
// ([`AplicacaoError::PolicyRetriesZero`] then
// [`AplicacaoError::PolicyRetriesExceedsCap`];
// [`AplicacaoError::PolicyTimeoutZero`] then
// [`AplicacaoError::PolicyTimeoutNotCanonical`]).
let mut s = three_member_spec();
s.politicas.circuit_breaker = Some(CircuitBreaker {
max_failures: 0,
window: Duration::from_secs(60),
});
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyBreakerZeroFailures,
"max_failures == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
);
}
#[test]
fn circuit_breaker_max_failures_cap_takes_precedence_over_window_gates() {
// The cross-arm ordering pin between the cap and the
// sibling `:window` gates (zero-window, canonical-window).
// A breaker carrying both an over-cap `max_failures` AND a
// structurally invalid window (zero, sub-ms) must surface
// the cap diagnostic first — the cap arm is wired
// immediately after the zero-failure arm and strictly
// before the window arms, so the offending value the
// diagnostic names matches the order the author would
// discover the gates by reading top-to-bottom through
// [`AplicacaoSpec::validate_politicas`]. Pin the order so a
// future refactor that reorders the arms surfaces here as a
// test failure rather than a silent diagnostic regression.
let mut s = three_member_spec();
s.politicas.circuit_breaker = Some(CircuitBreaker {
max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
window: Duration::ZERO,
});
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
},
"over-cap max_failures must surface the cap diagnostic before any window-axis diagnostic"
);
}
#[test]
fn policy_breaker_max_failures_cap_diagnostic_carries_offending_value() {
// The diagnostic-shape pin: the offending `u32` is carried
// verbatim into the
// [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]
// variant so the surfaced error message names the value the
// author wrote (`":politicas :circuit-breaker :max-failures
// (50000) exceeds the mesh-policy ceiling …"`), not just
// the cap. Same self-locating diagnostic shape every other
// typed-cap arm on this surface carries
// ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
// offending retry count verbatim,
// [`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
// offending byte count verbatim).
let mut s = three_member_spec();
s.politicas.circuit_breaker = Some(CircuitBreaker {
max_failures: 50_000,
window: Duration::from_secs(60),
});
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
max_failures: 50_000
}
),
"got {err:?}"
);
let msg = err.to_string();
assert!(
msg.contains("50000"),
":politicas :circuit-breaker :max-failures cap diagnostic must carry the offending value verbatim (got: {msg})"
);
}
#[test]
fn policy_breaker_max_failures_cap_pins_canonical_value() {
// The [`POLICY_BREAKER_MAX_FAILURES_MAX`] constant pins the
// value at 1000 — an order of magnitude above every
// documented production-playbook recommendation band
// (Hystrix `requestVolumeThreshold` default 20, Istio
// `outlierDetection.consecutive5xxErrors` default 5, Envoy
// `outlier_detection.consecutive_5xx` default 5, Polly /
// Resilience4j typical 5..=50) and below the
// clearly-pathological "effectively no protection" floor
// (10_000, 100_000, u32::MAX). Pinning the literal value
// here surfaces a future drift (a relaxation to 10_000, a
// tightening to 100) as a deliberate test edit, not a
// silent contract narrowing.
assert_eq!(POLICY_BREAKER_MAX_FAILURES_MAX, 1000);
}
#[test]
fn rejects_circuit_breaker_zero_window() {
let mut s = three_member_spec();
s.politicas.circuit_breaker = Some(CircuitBreaker {
max_failures: 5,
window: Duration::ZERO,
});
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyBreakerZeroWindow
);
}
#[test]
fn rejects_zero_rate_limit() {
let mut s = three_member_spec();
s.politicas.rate_limit = Some(RateLimit {
rate: 0,
window: Duration::from_secs(1),
});
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyRateLimitZero
);
}
#[test]
fn rejects_rate_limit_zero_window() {
// `RateLimit { rate: 100, window: Duration::ZERO }` is
// constructible programmatically (the typed `Duration` field
// imposes no nonzero invariant) but renders through
// `rate_limit_codec::render` as `"100/0s"` — a fragment the
// codec's `parse` rejects as `unknown rate-limit window unit
// "0s"`. Until this validate-time gate landed the typed slot
// accepted the value silently and the round-trip break only
// surfaced at deserialize time (potentially in a downstream
// consumer that never re-validates). Pin the rejection at
// `AplicacaoSpec::validate` so the typed slot's valid set
// matches the codec's round-trippable set structurally.
let mut s = three_member_spec();
s.politicas.rate_limit = Some(RateLimit {
rate: 100,
window: Duration::ZERO,
});
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyRateLimitWindowNotCanonical {
window: Duration::ZERO
}
);
}
#[test]
fn rejects_rate_limit_arbitrary_seconds_window() {
// 45 seconds is a valid `Duration` but not one of the three
// canonical rate-limit windows the codec round-trips
// (1s / 60s / 3600s). Renders as `"100/45s"`, which the parser
// refuses on round-trip — same round-trip-break shape the
// zero-window arm above pins, with a non-zero magnitude to
// guard against a future "reject only zero" half-measure.
let mut s = three_member_spec();
let window = Duration::from_secs(45);
s.politicas.rate_limit = Some(RateLimit { rate: 100, window });
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
);
}
#[test]
fn rejects_rate_limit_two_minute_window() {
// 120 seconds = 2 minutes is a "looks-canonical" but
// not-canonical window: it's a clean integer multiple of the
// minute unit, but the codec only round-trips the
// unit-magnitude-1 forms (`"<n>/m"` ≡ 60s, *not* `"<n>/2m"`).
// A `Duration::from_secs(120)` window renders as `"100/120s"`
// which the parser rejects. Pinning this case rules out a
// future "accept any clean multiple of s/m/h" relaxation
// that would silently break the codec contract.
let mut s = three_member_spec();
let window = Duration::from_secs(120);
s.politicas.rate_limit = Some(RateLimit { rate: 50, window });
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
);
}
#[test]
fn rejects_rate_limit_subsecond_window() {
// A sub-second window (e.g. 500ms) is a valid `Duration` but
// unrepresentable in the codec's `<n>/<s|m|h>` author surface.
// Pin the rejection so a future relaxation can't silently
// admit fractional-second windows that the codec can't
// round-trip.
let mut s = three_member_spec();
let window = Duration::from_millis(500);
s.politicas.rate_limit = Some(RateLimit { rate: 200, window });
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
);
}
#[test]
fn rejects_policy_rate_limit_above_cap() {
// The fail-before-pass-after pin: `rate = POLICY_RATE_LIMIT_MAX + 1`
// is structurally one past the cap and silently passed
// validate on every pre-gate codebase because the typed slot's
// only `rate` check was the zero-floor arm. The no-op-limiter
// shape only surfaced at the runtime substrate (Envoy's
// `local_rate_limit.token_bucket.max_tokens`, the future
// Cilium L7 rate-limit overlay) far from the source caixa.lisp
// with no field naming the offending policy.
let mut s = three_member_spec();
s.politicas.rate_limit = Some(RateLimit {
rate: POLICY_RATE_LIMIT_MAX + 1,
window: Duration::from_secs(1),
});
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyRateLimitExceedsCap {
rate: POLICY_RATE_LIMIT_MAX + 1
}
);
}
#[test]
fn rejects_policy_rate_limit_far_above_cap() {
// The `u32::MAX` worst case — the four-billion-token rate-limit
// a typo (`(:rate-limit "4294967295/s")`) or struct-literal
// copy-paste lands in the slot. Pin the cap arm's coverage
// explicitly across the full `u32` overflow so a future
// relaxation that drops the upper bound surfaces here. Peer to
// `rejects_policy_retries_far_above_cap` on the sibling
// `:retries` axis and `rejects_policy_breaker_max_failures_far_above_cap`
// on the sibling `:max-failures` axis.
let mut s = three_member_spec();
s.politicas.rate_limit = Some(RateLimit {
rate: u32::MAX,
window: Duration::from_secs(1),
});
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyRateLimitExceedsCap { rate: u32::MAX }
);
}
#[test]
fn accepts_policy_rate_limit_at_cap() {
// The boundary value — exactly [`POLICY_RATE_LIMIT_MAX`] —
// must validate. The cap is inclusive on the top edge, matching
// every other typed upper bound in this crate
// ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]). Pin the boundary
// across all three canonical windows so a future off-by-one
// tightening (`>= POLICY_RATE_LIMIT_MAX` instead of `>`) or a
// window-conditional cap surfaces here as a test failure rather
// than a silent contract narrowing.
for secs in [1u64, 60, 3600] {
let mut s = three_member_spec();
s.politicas.rate_limit = Some(RateLimit {
rate: POLICY_RATE_LIMIT_MAX,
window: Duration::from_secs(secs),
});
s.validate().unwrap_or_else(|e| {
panic!("rate == POLICY_RATE_LIMIT_MAX must validate (window={secs}s); got {e:?}",)
});
}
}
#[test]
fn accepts_policy_rate_limit_typical_values() {
// The documented production-playbook recommendation band —
// Envoy / Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare /
// AWS API Gateway 10_000..=100_000 per-minute, Cloudflare
// Enterprise ~1M per-hour. Every value in the validated set
// must pass; pin the band explicitly so a future tightening
// surfaces here.
//
// Clears the fixture's `:retries` (which is `Some(3)`) so this
// per-axis sweep is pure: the sibling cross-axis
// [`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] gate
// rejects any `rate <= retries` pair, so the `rate = 1`
// boundary at the head of the sweep would otherwise trip on the
// fixture-inherited retry policy rather than the per-axis
// boundary this test names. Same discipline the sibling per-axis
// `accepts_circuit_breaker_max_failures_typical_values` sweep
// takes against the fixture's `:retries` for the peer cross-axis
// [`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
// arm.
for rate in [1u32, 10, 100, 1_000, 10_000, 100_000, 1_000_000] {
for secs in [1u64, 60, 3600] {
let mut s = three_member_spec();
s.politicas.retries = None;
s.politicas.rate_limit = Some(RateLimit {
rate,
window: Duration::from_secs(secs),
});
s.validate().unwrap_or_else(|e| {
panic!("rate={rate} window={secs}s must validate; got {e:?}")
});
}
}
}
#[test]
fn policy_rate_limit_zero_takes_precedence_over_cap() {
// The cross-arm ordering pin: `rate == 0` is structurally
// outside both `1..` (zero-floor) and `..=POLICY_RATE_LIMIT_MAX`
// (cap), but the zero-floor diagnostic is the more
// self-locating one (it directly names the omit-axis
// remediation). Pin the order so a future refactor that
// reorders the arms surfaces here as a test failure rather
// than a silent diagnostic regression. Same shape every other
// zero-then-cap ordering on this surface uses
// ([`AplicacaoError::PolicyRetriesZero`] then
// [`AplicacaoError::PolicyRetriesExceedsCap`];
// [`AplicacaoError::PolicyBreakerZeroFailures`] then
// [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
let mut s = three_member_spec();
s.politicas.rate_limit = Some(RateLimit {
rate: 0,
window: Duration::from_secs(1),
});
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyRateLimitZero,
"rate == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
);
}
#[test]
fn policy_rate_limit_cap_takes_precedence_over_non_canonical_window() {
// Two-axis-bad pin: rate above cap *and* window non-canonical.
// The validate gate must fire on the rate cap first — the
// amplification-shape (no-op limiter) diagnostic is the more
// fundamental one; the window-canonical diagnostic is the
// narrower codec-round-trip shape. Pin the ordering so a future
// refactor that reorders the rate-then-window check arms
// surfaces here as a test failure rather than a silent
// diagnostic regression.
let mut s = three_member_spec();
s.politicas.rate_limit = Some(RateLimit {
rate: POLICY_RATE_LIMIT_MAX + 1,
window: Duration::from_secs(45),
});
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyRateLimitExceedsCap {
rate: POLICY_RATE_LIMIT_MAX + 1
},
"above-cap rate must surface the cap diagnostic, not the window diagnostic"
);
}
#[test]
fn policy_rate_limit_cap_diagnostic_carries_offending_value() {
// The diagnostic-shape pin: the offending `u32` is carried
// verbatim into the [`AplicacaoError::PolicyRateLimitExceedsCap`]
// variant so the surfaced error message names the value the
// author wrote (`":politicas :rate-limit rate (5000000) exceeds
// the mesh-policy ceiling …"`), not just the cap. Same
// self-locating diagnostic shape every other typed-cap arm on
// this surface carries ([`AplicacaoError::PolicyRetriesExceedsCap`]
// carries the offending retries count verbatim,
// [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`] carries
// the offending failure count verbatim).
let mut s = three_member_spec();
s.politicas.rate_limit = Some(RateLimit {
rate: 5_000_000,
window: Duration::from_secs(1),
});
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::PolicyRateLimitExceedsCap { rate: 5_000_000 }
),
"got {err:?}"
);
let msg = err.to_string();
assert!(
msg.contains("5000000"),
":politicas :rate-limit cap diagnostic must carry the offending value verbatim (got: {msg})"
);
}
#[test]
fn policy_rate_limit_cap_pins_canonical_value() {
// The [`POLICY_RATE_LIMIT_MAX`] constant pins the value at
// 1_000_000 — two-to-three orders of magnitude above every
// documented production-playbook recommendation band (Envoy /
// Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare / AWS API
// Gateway 10_000..=100_000 per-minute) and below the
// clearly-pathological "paste-from-binary blob" floor
// (100_000_000, u32::MAX). Pinning the literal value here
// surfaces a future drift (a relaxation to 10_000_000, a
// tightening to 100_000) as a deliberate test edit, not a
// silent contract narrowing.
assert_eq!(POLICY_RATE_LIMIT_MAX, 1_000_000);
}
#[test]
fn rate_limit_zero_rate_takes_precedence_over_non_canonical_window() {
// Both axes are invalid here: rate == 0 *and* window is
// non-canonical. The validate gate must fire on rate first
// (matching the existing `rejects_zero_rate_limit` ordering),
// so the existing diagnostic continues to lead with the
// simpler "zero rate" framing. Pinning the order of checks
// so a future refactor that reorders the arms surfaces here
// as a test failure rather than a silent diagnostic
// regression.
let mut s = three_member_spec();
s.politicas.rate_limit = Some(RateLimit {
rate: 0,
window: Duration::from_secs(45),
});
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyRateLimitZero
);
}
#[test]
fn rate_limit_canonical_windows_validate() {
// The three canonical windows the codec round-trips
// losslessly — 1s / 60s / 3600s — must all pass `validate()`
// unchanged. Pin the full canonical set as a positive case
// (the existing `rate_limit_round_trip_seconds` /
// `rate_limit_round_trip_minutes` tests pin the
// serialize-then-deserialize property at the codec layer; this
// test pins the validate-side complement so a future tightening
// of the canonical set — e.g. dropping `:hour` — surfaces here
// as a test failure rather than a silent contract narrowing).
for secs in [1u64, 60, 3600] {
let mut s = three_member_spec();
s.politicas.rate_limit = Some(RateLimit {
rate: 100,
window: Duration::from_secs(secs),
});
s.validate().expect("canonical window must validate");
}
}
#[test]
fn rate_limit_validated_value_round_trips_through_codec() {
// The structural property the validate gate enforces:
// every `RateLimit` past `AplicacaoSpec::validate` round-trips
// losslessly through the `rate_limit_codec` (serialize → string
// → deserialize → equal value). Pin this end-to-end so a future
// change to either side (the validate gate's accepted window
// set, the codec's parse/render unit set) that breaks the
// alignment surfaces here. The previous-state shape (typed
// slot accepts arbitrary `Duration`, codec only round-trips
// 1s/60s/3600s) would fail this test for a `Duration::from_secs(45)`
// window — the validate gate now forecloses that.
for secs in [1u64, 60, 3600] {
let mut s = three_member_spec();
s.politicas.rate_limit = Some(RateLimit {
rate: 250,
window: Duration::from_secs(secs),
});
s.validate().unwrap();
let json = serde_json::to_string(&s.politicas).unwrap();
let back: MeshPolicy = serde_json::from_str(&json).unwrap();
assert_eq!(
back.rate_limit, s.politicas.rate_limit,
"every validated :rate-limit must round-trip losslessly through the codec"
);
}
}
#[test]
fn rate_limit_canonical_per_hour_renders_with_h_suffix() {
// The hour-window canonical form (`"<n>/h"`) was missing from
// the prior `rate_limit_round_trip_seconds` / `_minutes` test
// pair. Now that the validate gate pins 3600s as part of the
// canonical set, pin its serialize-side render shape too so
// the third leg of the s/m/h tripod is explicitly tested.
let policy = MeshPolicy {
rate_limit: Some(RateLimit {
rate: 10000,
window: Duration::from_secs(3600),
}),
..Default::default()
};
let json = serde_json::to_string(&policy).unwrap();
assert!(
json.contains("\"10000/h\""),
"hour-window canonical form must render with `h` suffix (got: {json})"
);
let back: MeshPolicy = serde_json::from_str(&json).unwrap();
assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(3600));
}
#[test]
fn canonical_rate_limit_window_set_tracks_codec_via_canonical_unit() {
// Pin the substrate-primitive [`RateLimit::canonical_unit`]
// typed accessor's accepted-window set against the codec's
// accepted set explicitly. A future addition to the codec
// (e.g. accepting `:day`/`:week` as authoring units) must be
// accompanied by a parallel addition here, and a regression
// that drops one of the three canonical units from either
// side surfaces as a test failure. The accessor is the
// single source of truth for the canonical-window set —
// [`AplicacaoSpec::validate_politicas`]'s canonical-window
// gate and [`rate_limit_codec::render`]'s canonical arm both
// read through it — this test enshrines that its
// `Duration → Option<RateLimitUnit>` projection matches the
// codec's parse / render arms' accepted-window set exactly.
//
// Predecessor: this pin previously read the module-private
// free helper `is_canonical_rate_limit_window` — a delegate
// that composed [`RateLimitUnit::from_window`] with `.is_some()`
// — but the helper had no production consumers left after the
// validate-gate migration onto [`RateLimit::canonical_unit`]
// and was deleted; the closed-set arm-window bijection now
// lives on exactly one typed dispatch on the substrate
// primitive.
let canonical_unit = |window: Duration| -> Option<super::RateLimitUnit> {
RateLimit { rate: 1, window }.canonical_unit()
};
assert!(canonical_unit(Duration::from_secs(1)).is_some());
assert!(canonical_unit(Duration::from_secs(60)).is_some());
assert!(canonical_unit(Duration::from_secs(3600)).is_some());
// Non-canonical windows the accessor rejects.
assert!(canonical_unit(Duration::ZERO).is_none());
assert!(canonical_unit(Duration::from_secs(2)).is_none());
assert!(canonical_unit(Duration::from_secs(30)).is_none());
assert!(canonical_unit(Duration::from_secs(120)).is_none());
assert!(canonical_unit(Duration::from_secs(86400)).is_none());
// Sub-second windows: even `Duration::from_millis(1000)` is
// exactly 1s and accepted; `Duration::from_millis(500)` is
// sub-second and rejected.
assert!(canonical_unit(Duration::from_millis(1000)).is_some());
assert!(canonical_unit(Duration::from_millis(500)).is_none());
assert!(canonical_unit(Duration::from_millis(1500)).is_none());
}
#[test]
fn rate_limit_unit_table_projections_are_mutual_inverses() {
// Bidirection pin against the closed-set typed enum
// [`RateLimitUnit`] arm-table (the canonical
// `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer
// of the rate-limit unit surface reads from). The two
// projection directions [`RateLimitUnit::from_suffix`] /
// [`RateLimitUnit::window`] (str → Duration, exposed as one
// typed dispatch through [`RateLimitUnit::window_from_suffix`])
// and [`RateLimitUnit::from_window`] / [`RateLimitUnit::as_suffix`]
// (Duration → str, exposed as one typed dispatch through
// [`RateLimit::canonical_unit`] composed with
// [`RateLimitUnit::as_suffix`]) are the substrate primitives the
// codec's parse arm ([`rate_limit_codec::parse`] via
// [`RateLimitUnit::window_from_suffix`]), the codec's render arm
// ([`rate_limit_codec::render`] via [`RateLimit::canonical_unit`]),
// and the validate gate ([`AplicacaoSpec::validate_politicas`]
// via [`RateLimit::canonical_unit`]) all key off. A future
// rate-limit-unit addition (a `"d"` day suffix, a `"ms"`
// sub-second window) is one variant + one arm per method on the
// closed-set enum; the compiler-enforced exhaustiveness on
// every consumer's `match self` arms picks it up by
// construction. This pin enshrines that both projection
// directions agree on every canonical arm row and neither
// leaks a spurious entry the other doesn't recognize.
//
// Predecessor: this test previously read the two vestigial
// module-private free helpers `rate_limit_window_unit` and
// `rate_limit_window_from_unit` on the `Duration → &str` and
// `&str → Duration` axes; the former was deleted after its
// sole production consumer ([`rate_limit_codec::render`])
// migrated onto [`RateLimit::canonical_unit`] (61421a6), and
// the latter is folded here into the substrate primitive
// [`RateLimitUnit::window_from_suffix`] so both projection
// directions live on the closed-set enum's arm-table.
for (unit, secs) in [("s", 1u64), ("m", 60), ("h", 3600)] {
let window = super::RateLimitUnit::window_from_suffix(unit)
.unwrap_or_else(|| panic!("canonical unit {unit:?} must resolve to a Duration"));
assert_eq!(
window,
Duration::from_secs(secs),
"unit {unit:?} must resolve to {secs}s"
);
let projected_suffix = RateLimit { rate: 1, window }
.canonical_unit()
.map(super::RateLimitUnit::as_suffix);
assert_eq!(
projected_suffix,
Some(unit),
"Duration({secs}s) must render as {unit:?} \
via RateLimit::canonical_unit + RateLimitUnit::as_suffix"
);
}
// Non-table units yield None on the `unit → Duration`
// projection — a future `"d"` addition to the table would
// flip this arm; today it pins the current three-row table's
// rejection semantics.
assert!(super::RateLimitUnit::window_from_suffix("d").is_none());
assert!(super::RateLimitUnit::window_from_suffix("ms").is_none());
assert!(super::RateLimitUnit::window_from_suffix("").is_none());
// Non-table Durations yield None on the `Duration → unit`
// projection — pins that the two projections agree on the
// "not in the table" semantic too, so a drift where the
// parse-side accepts a value the render-side can't emit is
// a build error at the two-arm pair, not a silent codec
// round-trip break.
let projected_suffix = |window: Duration| -> Option<&'static str> {
RateLimit { rate: 1, window }
.canonical_unit()
.map(super::RateLimitUnit::as_suffix)
};
assert!(projected_suffix(Duration::from_secs(2)).is_none());
assert!(projected_suffix(Duration::from_secs(86_400)).is_none());
assert!(projected_suffix(Duration::from_millis(1500)).is_none());
}
#[test]
fn rate_limit_unit_window_from_suffix_composes_from_suffix_and_window() {
// Byte-parity pin on the [`RateLimitUnit::window_from_suffix`]
// substrate-primitive `&str → Duration` associated method the
// codec's parse arm ([`rate_limit_codec::parse`]) now routes
// through. Every canonical arm (`"s"`, `"m"`, `"h"`) must resolve
// to the same [`Duration`] the two-step composition
// [`RateLimitUnit::from_suffix`] with [`RateLimitUnit::window`]
// returns; every non-arm suffix (`"d"`, `"ms"`, `""`, `"seconds"`,
// `"MIN"`) must project to [`None`] on both paths. A future
// implementation of `window_from_suffix` that took a shortcut
// through a per-suffix `match` table (bypassing the arm-table's
// `Self::from_suffix` scan and the arm-table's `Self::window`
// dispatch) would silently split the accept-set — the parse
// arm would accept a suffix the enum's arm-table doesn't know,
// or reject a suffix the enum's arm-table does; this pin
// surfaces that drift at caixa-core build time rather than at a
// downstream serde round-trip audit on a live `MeshPolicy`.
//
// Same byte-parity discipline the sibling
// [`canonical_rate_limit_window_set_tracks_codec_via_canonical_unit`]
// pin carries on the peer `Duration → RateLimitUnit` axis via
// [`RateLimit::canonical_unit`], and the peer
// [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
// carries on the bidirectional arm-table axis — extended here
// onto the fifth (and last unlifted) projection axis on the
// closed-set enum's arm-table.
let composition = |suffix: &str| -> Option<Duration> {
super::RateLimitUnit::from_suffix(suffix).map(super::RateLimitUnit::window)
};
for suffix in ["s", "m", "h"] {
let via_method = super::RateLimitUnit::window_from_suffix(suffix);
let via_composition = composition(suffix);
assert_eq!(
via_method, via_composition,
"RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
from_suffix({suffix:?}).map(window) — the substrate-primitive \
method must delegate to the arm-table's two typed dispatches, \
not shortcut through a per-suffix match table"
);
assert!(
via_method.is_some(),
"canonical suffix {suffix:?} must resolve to Some(Duration) via \
RateLimitUnit::window_from_suffix"
);
}
for suffix in ["d", "ms", "", "seconds", "MIN", "S", "H", "/"] {
let via_method = super::RateLimitUnit::window_from_suffix(suffix);
let via_composition = composition(suffix);
assert_eq!(
via_method, via_composition,
"RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
from_suffix({suffix:?}).map(window) on the non-arm rejection \
axis too"
);
assert!(
via_method.is_none(),
"non-arm suffix {suffix:?} must project to None via \
RateLimitUnit::window_from_suffix — a future extension that \
accepted this suffix without a corresponding arm on the enum \
would split the codec's parse-accepted set from the enum's \
arm-table"
);
}
// And the codec's parse arm now reads through this method: a
// canonical `"100/<u>"` MeshPolicy JSON payload round-trips to
// the same `Duration` the method returns for its unit, closing
// the two-consumer drift surface (the codec's parse arm and the
// enum's arm-table) with one typed dispatch on the substrate
// primitive.
for suffix in ["s", "m", "h"] {
let wire = format!(r#"{{"rateLimit":"100/{suffix}"}}"#);
let mp: MeshPolicy = serde_json::from_str(&wire)
.unwrap_or_else(|e| panic!("wire {wire:?} must parse: {e}"));
let parsed = mp.rate_limit().expect("rate_limit payload present");
let via_method = super::RateLimitUnit::window_from_suffix(suffix)
.unwrap_or_else(|| panic!("suffix {suffix:?} must resolve via window_from_suffix"));
assert_eq!(
parsed.window(),
via_method,
"codec parse arm on {wire:?} must resolve the window through \
RateLimitUnit::window_from_suffix, not a divergent path"
);
}
}
#[test]
fn rate_limit_unit_all_enumerates_every_arm_once() {
// Fail-before-pass-after pin: [`RateLimitUnit::ALL`] must
// enumerate every arm of the closed-set enum exactly once, in
// the canonical shortest-to-longest window order (Second before
// Minute before Hour) — the same order the sibling
// [`crate::supervisor::RestartStrategy`] /
// [`crate::supervisor::RestartPolicy`] /
// [`crate::PlacementStrategy`] / [`crate::CaixaKind`] closed-set
// typed enums carry (the arm declared first is the arm listed
// first). A future variant addition that extends the enum
// without appending to [`RateLimitUnit::ALL`] leaves the
// exhaustive iteration surface silently short one arm — the
// codec's parse arm would then reject the new suffix even
// though the enum knows it. This pin closes the drift.
assert_eq!(
super::RateLimitUnit::ALL,
&[
super::RateLimitUnit::Second,
super::RateLimitUnit::Minute,
super::RateLimitUnit::Hour,
],
"RateLimitUnit::ALL must enumerate every arm exactly once, \
in canonical shortest-to-longest window order"
);
}
#[test]
fn rate_limit_unit_from_suffix_and_as_suffix_round_trip() {
// Total round-trip pin on the `(from_suffix, as_suffix)` pair:
// every arm's [`RateLimitUnit::as_suffix`] output must parse
// back through [`RateLimitUnit::from_suffix`] to the same
// variant. A future arm addition that lands `as_suffix` but
// forgets `from_suffix` (`from_suffix` iterates
// [`RateLimitUnit::ALL`] so the peer arm's inclusion in `ALL`
// is the load-bearing carrier of the round-trip; the sibling
// `rate_limit_unit_all_enumerates_every_arm_once` pin covers
// the `ALL` half) trips here at caixa-core build time rather
// than surfacing as a codec round-trip miss (a `render` emit
// that lands a suffix the paired `parse` cannot decode).
for unit in super::RateLimitUnit::ALL {
let suffix = unit.as_suffix();
let parsed = super::RateLimitUnit::from_suffix(suffix).unwrap_or_else(|| {
panic!(
"RateLimitUnit::from_suffix({suffix:?}) must accept every \
RateLimitUnit::as_suffix output — got None for {unit:?}"
)
});
assert_eq!(
parsed, *unit,
"RateLimitUnit::from_suffix(RateLimitUnit::{unit:?}.as_suffix()) \
must return RateLimitUnit::{unit:?}"
);
}
}
#[test]
fn rate_limit_unit_from_window_and_window_round_trip() {
// Total round-trip pin on the `(from_window, window)` pair:
// every arm's [`RateLimitUnit::window`] output must parse back
// through [`RateLimitUnit::from_window`] to the same variant.
// Sibling of `rate_limit_unit_from_suffix_and_as_suffix_round_trip`
// on the peer `Duration` axis — the two round-trip pins
// together enshrine that both projections of the typed
// canonical-unit bijection are total on the arm-set.
for unit in super::RateLimitUnit::ALL {
let window = unit.window();
let parsed = super::RateLimitUnit::from_window(window).unwrap_or_else(|| {
panic!(
"RateLimitUnit::from_window({window:?}) must accept every \
RateLimitUnit::window output — got None for {unit:?}"
)
});
assert_eq!(
parsed, *unit,
"RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
must return RateLimitUnit::{unit:?}"
);
}
}
#[test]
fn rate_limit_unit_from_window_accessor_is_const_fn() {
// Fail-before-pass-after pin: witnesses the
// [`RateLimitUnit::from_window`] `const`-eval posture via a
// `const fn` wrapper `from_window_via_const_fn(window: Duration)
// -> Option<RateLimitUnit>` whose body calls
// `RateLimitUnit::from_window(window)`, well-formed only when
// the callee is itself `const fn` (any future downgrade to
// non-`const` fails at caixa-core build time with E0015 `cannot
// call non-const function`, strictly stronger than a runtime
// `assert!`, side-stepping the destructor-in-const restriction
// that blocks direct `const _: Option<RateLimitUnit> =
// RateLimitUnit::from_window(...)` items on `Duration`'s
// carrier). The runtime body sweeps every closed-set
// [`RateLimitUnit::ALL`] arm plus a representative non-canonical
// rejection sample (`Duration::from_millis(500)` sub-second
// residue) and asserts the wrapped and direct dispatches agree
// — a violation means the wrapper stopped compiling under a
// future `const`-posture downgrade, or the reverse resolver's
// arm-set silently split from the peer `Self::window` emitter's
// arm-set. Peer of the sibling
// [`crate::supervisor::tests::child_spec_restart_accessor_is_const_fn`]
// (152c868) /
// [`crate::supervisor::tests::supervisor_spec_estrategia_accessor_is_const_fn`]
// (152c868) /
// [`entrada_port_accessor_is_const_fn`] (bafa004) /
// [`placement_estrategia_accessor_is_const_fn`] (bafa004)
// `const`-eval-surface pins on the peer M2 / M3 substrate-
// primitive `Copy`-return accessor axes, extended onto the
// reverse `Duration → RateLimitUnit` projection axis on the
// M3 mesh-slot rate-limit closed-set typed enum.
const fn from_window_via_const_fn(window: Duration) -> Option<super::RateLimitUnit> {
super::RateLimitUnit::from_window(window)
}
for unit in super::RateLimitUnit::ALL {
let window = unit.window();
let via_wrapper = from_window_via_const_fn(window);
let direct = super::RateLimitUnit::from_window(window);
assert_eq!(
via_wrapper, direct,
"RateLimitUnit::from_window({window:?}) via const fn \
wrapper must agree with direct dispatch for {unit:?}"
);
assert_eq!(
via_wrapper,
Some(*unit),
"RateLimitUnit::from_window({window:?}) via const fn \
wrapper must return Some({unit:?}) for the peer \
window() output"
);
}
assert!(from_window_via_const_fn(Duration::from_millis(500)).is_none());
assert!(from_window_via_const_fn(Duration::from_secs(30)).is_none());
}
#[test]
fn rate_limit_unit_from_window_composes_through_window_accessor() {
// Composition-witness pin on the routing-through-peer discipline:
// [`RateLimitUnit::from_window`]'s per-arm probes each dispatch
// through the peer `pub const fn` [`RateLimitUnit::window`]
// canonical-`Duration` projection rather than a hand-authored
// per-arm second-magnitude literal — a future arm-magnitude edit
// on the sibling `window()` accessor (a `Second → 2s` typo, a
// `Hour → 3599s` off-by-one) must therefore reach this reverse
// resolver by construction. A pin that hard-coded the three
// second-magnitudes here would silently split from the peer
// emitter on any such edit; instead, this pin asserts the
// composition invariant `from_window(u.window()) == Some(u)`
// holds byte-for-byte on every closed-set [`RateLimitUnit::ALL`]
// arm — a violation means either the peer `Self::window`
// accessor drifted (breaking every downstream consumer that
// reads through it), or the reverse resolver stopped routing
// through the peer (introducing a hand-authored literal that
// silently disagrees with the emitter). Either failure is a
// caixa-core-build-time surface, not a downstream renderer
// round-trip regression.
//
// Peer of the sibling
// [`crate::render::assert_str_reexport_identity`] discipline on
// the substrate-primitive `&'static str` re-export axis and the
// [`rate_limit_unit_from_window_and_window_round_trip`]
// round-trip pin on the peer projection direction; extends the
// one-canonical-dispatch-per-projection discipline onto the
// reverse-resolver's per-arm probe axis.
for unit in super::RateLimitUnit::ALL {
let window_via_peer = unit.window();
let resolved = super::RateLimitUnit::from_window(window_via_peer);
assert_eq!(
resolved,
Some(*unit),
"RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
must return Some({unit:?}) — the reverse resolver's per-arm \
probes must route through the peer `Self::window` accessor \
so any future arm-magnitude edit reaches both projection \
directions by construction"
);
}
}
#[test]
fn rate_limit_canonical_unit_accessor_is_const_fn() {
// Fail-before-pass-after pin: witnesses the
// [`RateLimit::canonical_unit`] `const`-eval posture via a
// `const fn` wrapper
// `canonical_unit_via_const_fn(rl: &RateLimit) -> Option<RateLimitUnit>`
// whose body calls `rl.canonical_unit()`, well-formed only when
// the callee is itself `const fn` (any future downgrade to
// non-`const` fails at caixa-core build time with E0015 `cannot
// call non-const method`). The runtime body sweeps every
// closed-set [`RateLimitUnit::ALL`] arm — for each arm,
// constructs a typed [`RateLimit`] with the peer `Self::window`
// canonical `Duration`, then asserts both the wrapper and the
// direct dispatch agree and both return `Some(unit)`. Composes
// with the sibling
// [`rate_limit_unit_from_window_accessor_is_const_fn`] pin: the
// typed [`RateLimit`] projection layer's `const`-posture is
// load-bearing on the reverse resolver's `const`-posture, and
// both must migrate together (a downgrade of either surface
// splits the paired `const`-eval-surface pass on the M3
// mesh-slot rate-limit `Duration ↔ Self` bijection).
const fn canonical_unit_via_const_fn(
rl: &super::RateLimit,
) -> Option<super::RateLimitUnit> {
rl.canonical_unit()
}
for unit in super::RateLimitUnit::ALL {
let rl = super::RateLimit {
rate: 1,
window: unit.window(),
};
let via_wrapper = canonical_unit_via_const_fn(&rl);
let direct = rl.canonical_unit();
assert_eq!(
via_wrapper, direct,
"RateLimit::canonical_unit() via const fn wrapper must \
agree with direct dispatch for {unit:?}"
);
assert_eq!(
via_wrapper,
Some(*unit),
"RateLimit::canonical_unit() via const fn wrapper must \
return Some({unit:?}) for a RateLimit whose window is \
the peer RateLimitUnit::{unit:?}.window() output"
);
}
}
#[test]
fn rate_limit_unit_projections_are_pairwise_distinct() {
// Distinctness pin: [`RateLimitUnit::as_suffix`] and
// [`RateLimitUnit::window`] outputs must be pairwise distinct
// across every arm — an accidental copy-paste flip that
// reroutes one arm's suffix or window to also match another
// silently collapses two arms onto one, so
// [`RateLimitUnit::from_suffix`] / [`RateLimitUnit::from_window`]
// (both using `find` on `Self::ALL`) would return whichever
// arm the linear scan lands on first — a match-arm-ordering-
// dependent outcome the closed-set typed-enum shape is meant
// to rule out structurally. Peer of the sibling
// `caixa_kind_wire_consts_are_pairwise_distinct` /
// `caixa_kind_label_consts_are_pairwise_distinct` pins on the
// other closed-set typed-enum discriminator axes.
let all = super::RateLimitUnit::ALL;
for (i, a) in all.iter().enumerate() {
for (j, b) in all.iter().enumerate() {
if i != j {
assert_ne!(
a.as_suffix(),
b.as_suffix(),
"RateLimitUnit::{a:?}.as_suffix() and {b:?}.as_suffix() \
must be distinct — a collision silently collapses two \
arms onto one under from_suffix's linear scan"
);
assert_ne!(
a.window(),
b.window(),
"RateLimitUnit::{a:?}.window() and {b:?}.window() \
must be distinct — a collision silently collapses two \
arms onto one under from_window's linear scan"
);
}
}
}
}
#[test]
fn rate_limit_unit_display_routes_through_as_suffix() {
// Route pin: [`std::fmt::Display`] must byte-equal
// [`RateLimitUnit::as_suffix`] on every arm — the single
// source of truth for the canonical suffix. A future
// reimplementation that hand-rolls the arms instead of
// delegating to [`RateLimitUnit::as_suffix`] would silently
// desynchronize `format!("{u}")` from the codec's parse arm
// (which uses `as_suffix` to compare suffixes). Peer of the
// sibling `caixa_kind_display_routes_through_as_str_helper` /
// `placement_strategy_display_routes_through_as_str_helper`
// pins on the peer closed-set typed-enum Display axes.
for unit in super::RateLimitUnit::ALL {
assert_eq!(
unit.to_string(),
unit.as_suffix(),
"RateLimitUnit::{unit:?} Display must route through \
as_suffix (single source of truth: the canonical suffix \
the codec parses and renders)"
);
}
}
#[test]
fn rate_limit_unit_as_ref_str_routes_through_as_suffix_accessor() {
// Fail-before-pass-after byte-parity pin on the lifted
// `impl AsRef<str> for RateLimitUnit` — asserts the standard-
// library trait impl and the substrate-primitive
// [`super::RateLimitUnit::as_suffix`] `pub const fn` accessor
// resolve to the same `&str` per instance across the three-arm
// closed set, so any future silent detour that routes the impl
// through a divergent projection (a per-arm inline
// `match self { RateLimitUnit::Second => "s", … }` re-inlining
// that opens a compile-time link to the un-lifted arm-literal,
// a swap onto the second-magnitude
// [`super::RateLimitUnit::window`] axis that would collide the
// canonical-suffix / token-bucket-refill two-axis split) trips
// at caixa-core test time under `PartialEq` rather than at a
// downstream `impl AsRef<str>`-bound consumer's silent split.
// Sweeps every one of the three arms
// [`super::RateLimitUnit::ALL`] carries so no arm's projection
// is covered only by the sibling `Display` path. Peer of the
// sibling
// `placement_strategy_as_ref_str_routes_through_as_str_accessor`
// (d86edd2) on the M3 mesh-placement closed-set typed enum,
// and the peer
// [`crate::kind::tests::caixa_kind_as_ref_str_routes_through_as_str_accessor`]
// (cd2091f) pin on the top-level closed-set typed
// discriminator — the pins together close the substrate
// primitive's `AsRef<str>` projection axis on every closed-set
// typed enum with a `fmt::Display` surface across the M2 / M3
// typed slots plus the top-level `:kind` + `:versao`
// primitives.
for &unit in super::RateLimitUnit::ALL {
assert_eq!(
<super::RateLimitUnit as AsRef<str>>::as_ref(&unit),
unit.as_suffix(),
"AsRef<str> impl on RateLimitUnit::{unit:?} must \
byte-equal RateLimitUnit::as_suffix on the same \
instance — divergence signals a silent detour off the \
substrate-primitive accessor"
);
}
}
#[test]
fn rate_limit_unit_as_ref_str_routes_through_display_via_shared_accessor() {
// Fail-before-pass-after byte-parity pin on the three-path
// convergence discipline the M3 `:politicas :rate-limit`
// canonical-unit primitive now carries on the `&str`-projection
// axis: `<RateLimitUnit as AsRef<str>>::as_ref(&v)` (the newly
// lifted impl), `format!("{v}")` (the pre-existing
// [`fmt::Display`] impl), and `v.as_suffix()` (the substrate-
// primitive `pub const fn` accessor both trait impls delegate
// through) must resolve to the same byte-string on every
// instance across the three-arm closed set. Refuses any future
// divergence between the two trait impls (a stray
// [`fmt::Display::fmt`] rewrite that hand-rolls the arms
// rather than delegating through the shared accessor; a
// hypothetical `AsRef<str>` rewrite that inlines a per-arm
// literal cascade) that would silently split the two
// projection paths of the same closed-set typed enum. Mirrors
// the sibling three-path-convergence discipline the peer
// [`super::PlacementStrategy`] typed enum carries
// (`placement_strategy_as_ref_str_routes_through_display_via_shared_accessor`,
// d86edd2), the peer [`crate::CaixaKind`] triple
// (`caixa_kind_as_ref_str_routes_through_display_via_shared_accessor`,
// cd2091f), and the [`crate::CaixaVersion`] typed newtype
// triple (`caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
// 16d5c7e).
for &unit in super::RateLimitUnit::ALL {
let via_as_ref: &str = <super::RateLimitUnit as AsRef<str>>::as_ref(&unit);
let via_display: String = format!("{unit}");
let via_accessor: &str = unit.as_suffix();
assert_eq!(via_as_ref, via_accessor);
assert_eq!(via_display, via_accessor);
assert_eq!(via_as_ref, via_display.as_str());
}
}
#[test]
fn rate_limit_unit_from_window_rejects_non_canonical() {
// Rejection pin on the parser's accept-set: any Duration
// outside the three-arm [`RateLimitUnit::window`] output set
// (sub-second residue, or a second-magnitude outside `{1, 60,
// 3600}`) must return `None`. A future accidental widening of
// the accept-set (rounding down sub-second residue to the
// nearest arm, admitting `Duration::from_secs(30)` as a
// half-minute unit) would silently drift the parser's accept-
// set from the emitter's — a validated slot with a
// non-canonical window would then round-trip through the
// codec to a canonical form the author never wrote.
assert!(super::RateLimitUnit::from_window(Duration::ZERO).is_none());
assert!(super::RateLimitUnit::from_window(Duration::from_secs(2)).is_none());
assert!(super::RateLimitUnit::from_window(Duration::from_secs(30)).is_none());
assert!(super::RateLimitUnit::from_window(Duration::from_secs(120)).is_none());
assert!(super::RateLimitUnit::from_window(Duration::from_secs(86_400)).is_none());
assert!(super::RateLimitUnit::from_window(Duration::from_millis(500)).is_none());
assert!(super::RateLimitUnit::from_window(Duration::from_millis(1500)).is_none());
}
#[test]
fn rate_limit_unit_from_suffix_rejects_unknown() {
// Rejection pin on the suffix parser's accept-set: any string
// outside the three-arm [`RateLimitUnit::as_suffix`] output
// set must return `None`. Peer of the sibling
// `caixa_kind_from_wire_rejects_unknown_byte_strings` pin on
// the [`crate::CaixaKind`] `from_wire` accept-set.
for bad in [
"", "S", "M", "H", "sec", "min", "hour", "d", "ms", "ns", "us", "week", "1s", "s/",
" s",
] {
assert!(
super::RateLimitUnit::from_suffix(bad).is_none(),
"RateLimitUnit::from_suffix({bad:?}) must return None — the \
parser's accept-set is exactly the three RateLimitUnit::as_suffix \
outputs"
);
}
}
#[test]
fn rate_limit_unit_try_from_str_routes_through_from_suffix_accessor() {
// Fail-before-pass-after byte-parity pin on the newly lifted
// `impl TryFrom<&str> for RateLimitUnit` — asserts the standard-
// library trait impl and the substrate-primitive
// [`super::RateLimitUnit::from_suffix`] `Option<Self>` accessor
// resolve to the same three-arm accept-set across every arm the
// exhaustive [`super::RateLimitUnit::ALL`] slice enumerates. Any
// future silent detour that routes the trait impl through a
// divergent projection (a per-arm inline
// `match s { "s" => Ok(Self::Second), … }` re-inlining that
// opens a compile-time link to the un-lifted arm-literal, a
// silent case-fold that admits `"S"` / `"M"` / `"H"` and would
// collide the canonical-suffix accept-set the codec's parse arm
// dispatches on) trips at caixa-core test time under
// `assert_eq!` rather than at a downstream `impl TryFrom<&str>`-
// bound consumer's silent split. Sweeps every one of the three
// arms [`super::RateLimitUnit::ALL`] carries so no arm's
// projection is covered only by the sibling method-named
// `from_suffix` path. Peer of the sibling
// [`crate::kind::tests::caixa_kind_try_from_str_routes_through_from_wire_accessor`]
// (3c83606),
// [`crate::dialeto::tests::caixa_dialeto_try_from_str_routes_through_from_wire_accessor`]
// (bf33136), and
// `placement_strategy_try_from_str_routes_through_from_wire_accessor`
// (6fd00cd) — extends the trait-idiomatic reverse-projection
// axis onto the third M3-mesh-primitive-defining slot enum on
// the caixa surface (the `:politicas :rate-limit` unit-suffix
// closed set the caixa-mesh renderer keys off end-to-end).
for &unit in super::RateLimitUnit::ALL {
let suffix = unit.as_suffix();
assert_eq!(
<super::RateLimitUnit as TryFrom<&str>>::try_from(suffix),
Ok(unit),
"TryFrom<&str> impl on RateLimitUnit must round-trip \
RateLimitUnit::{unit:?}.as_suffix() = {suffix:?} back to \
Ok(RateLimitUnit::{unit:?}) — divergence from \
RateLimitUnit::from_suffix signals a silent detour off \
the substrate-primitive accessor"
);
assert_eq!(
<super::RateLimitUnit as TryFrom<&str>>::try_from(suffix).ok(),
super::RateLimitUnit::from_suffix(suffix),
"TryFrom<&str> ok()-projection on {suffix:?} must \
byte-equal RateLimitUnit::from_suffix on the same input"
);
}
}
#[test]
fn rate_limit_unit_try_from_str_rejects_unknown_byte_strings() {
// Rejection witness on the `impl TryFrom<&str> for RateLimitUnit`
// — sweeps a candidate set of byte-strings outside the three-arm
// canonical-suffix wire accept-set the sibling
// [`super::RateLimitUnit::as_suffix`] emits and asserts every
// one lands on `Err(())`, so a future accidental widening of the
// trait impl's accept-set (a stray additional
// `_ if s.eq_ignore_ascii_case("s") => Ok(…)` case-fold path, a
// silent inclusion of a long-form English rebrand of the
// canonical suffix like `"second"` / `"minute"` / `"hour"` that
// would collide the one-letter-suffix discipline the sibling
// [`super::RateLimitUnit::from_suffix`] carries, a silent
// acceptance of the `"1s"` / `"1m"` / `"1h"` full-rate-limit
// shape that would collide the codec-composed `<n>/<unit>` axis
// onto the unit-suffix axis) trips at caixa-core test time. The
// candidate set includes the empty string, whitespace-only
// padding, uppercase rebrand candidates, long-form English
// rebrand candidates (`"second"`, `"minute"`, `"hour"`),
// trailing/leading-whitespace-padded canonical suffixes,
// sub-second and multi-day trajectory-item candidates
// (`"ms"`, `"d"`, `"week"`), digits-prefixed shapes that would
// collide with the `<n>/<unit>` parent codec, the quoted-shape
// (`"\"s\""`) that would signal a stray serde-quote survival,
// and the `"?"` sentinel. Peer of the sibling
// [`crate::kind::tests::caixa_kind_try_from_str_rejects_unknown_byte_strings`]
// (3c83606) rejection witness, and
// `placement_strategy_try_from_str_rejects_unknown_byte_strings`
// (6fd00cd).
let rejected: &[&str] = &[
"", " ", "\n", "\t", "S", "M", "H", "s ", " s", "m ", " h", "s\n", "second", "minute",
"hour", "sec", "min", "hr", "d", "ms", "ns", "us", "week", "1s", "1m", "1h", "100/s",
"s/", "?", "\"s\"",
];
for &input in rejected {
assert_eq!(
<super::RateLimitUnit as TryFrom<&str>>::try_from(input),
Err(()),
"TryFrom<&str> impl on RateLimitUnit must reject the \
non-suffix byte-string {input:?} — silent acceptance \
signals an accept-set widening off the paired \
RateLimitUnit::from_suffix resolver"
);
}
}
#[test]
fn rate_limit_unit_try_from_str_and_from_suffix_partition_the_accept_set() {
// Cross-axis partition pin on the two `str → Option<Self>` /
// `str → Result<Self, ()>` projections on
// [`super::RateLimitUnit`]: the trait-idiomatic
// [`TryFrom<&str>`] axis (newly lifted) and the method-named
// [`super::RateLimitUnit::from_suffix`] axis (pre-existing) must
// partition every input into the same accept-set / reject-set
// — a `TryFrom<&str>` `Ok(v)` outcome iff `from_suffix` returns
// `Some(v)`, and a `TryFrom<&str>` `Err(())` outcome iff
// `from_suffix` returns `None`. Sweeps a mixed input set of
// canonical accepts + rejections so any future divergence
// between the two projection paths (a hand-rolled `try_from`
// rewrite that no longer routes through `from_suffix`, a
// hypothetical `from_suffix` widening that admits a byte-string
// the trait impl still rejects) surfaces here at caixa-core
// test time rather than at a downstream consumer's silent
// split. Peer of the sibling
// `wit_shape_try_from_str_and_from_wire_partition_the_accept_set`
// (5472902) cross-axis partition pin on the sibling M3-mesh-
// primitive closed-set typed enum.
let inputs: &[&str] = &[
"s", "m", "h", "", " ", "S", "second", "d", "ms", "1s", "?", "\"s\"", "sec",
];
for &input in inputs {
let via_try_from: Option<super::RateLimitUnit> =
<super::RateLimitUnit as TryFrom<&str>>::try_from(input).ok();
let via_from_suffix: Option<super::RateLimitUnit> =
super::RateLimitUnit::from_suffix(input);
assert_eq!(
via_try_from, via_from_suffix,
"TryFrom<&str> and from_suffix must partition the \
accept-set identically on input {input:?} — got \
TryFrom = {via_try_from:?}, from_suffix = {via_from_suffix:?}"
);
}
}
#[test]
fn rate_limit_unit_from_into_static_str_routes_through_as_suffix_accessor() {
// Fail-before-pass-after byte-parity pin on the newly lifted
// `impl From<RateLimitUnit> for &'static str` — asserts the
// standard-library trait impl and the substrate-primitive
// [`super::RateLimitUnit::as_suffix`] `pub const fn` accessor
// resolve to the same three-arm canonical-suffix emit-set across
// every arm the exhaustive [`super::RateLimitUnit::ALL`] slice
// enumerates. Any future silent detour that routes the trait
// impl through a divergent projection (a per-arm inline
// `match unit { Second => "s", … }` re-inlining that opens a
// compile-time link to the un-lifted arm-literal outside the
// paired [`super::RateLimitUnit::as_suffix`] dispatch, a swap
// onto the second-magnitude [`super::RateLimitUnit::window`]
// axis that would collide the canonical-suffix /
// token-bucket-refill two-axis split) trips at caixa-core test
// time under `assert_eq!` rather than at a downstream
// `impl Into<&'static str>`-bound consumer's silent split.
// Sweeps every one of the three arms
// [`super::RateLimitUnit::ALL`] carries so no arm's projection
// is covered only by the sibling method-named `as_suffix` /
// [`std::fmt::Display`] / [`AsRef<str>`] paths. Materializes the
// `<&'static str as From<RateLimitUnit>>::from` output in three
// `const`-shape bindings against the paired
// [`super::RateLimitUnit::as_suffix`] `pub const fn` accessor to
// make the `'static` lifetime promise a build-time invariant —
// a future accidental downgrade of any of the three arms'
// inline canonical-suffix byte-strings to a non-`&'static str`
// (a `String::leak()`-produced return, a `Box::leak`-cast, an
// intermediate lifetime-erasing helper) trips at caixa-core
// build time rather than at a downstream `'static`-bound
// consumer.
//
// Peer of the sibling
// [`crate::supervisor::tests::restart_strategy_from_into_static_str_routes_through_as_str_accessor`]
// (523157d),
// [`crate::supervisor::tests::restart_policy_from_into_static_str_routes_through_as_str_accessor`]
// (9fb37d0),
// [`crate::kind::tests::caixa_kind_from_into_static_str_routes_through_as_str_accessor`]
// (edb827b),
// [`crate::dialeto::tests::caixa_dialeto_from_into_static_str_routes_through_as_str_accessor`]
// (c189a6f),
// [`tests::placement_strategy_from_into_static_str_routes_through_as_str_accessor`]
// (afa3562), and
// [`tests::wit_shape_from_into_static_str_routes_through_as_str_accessor`]
// (56998ec) pins on the sibling closed-set typed-enum forward-
// projection axes — extends the trait-idiomatic forward-
// projection axis onto the seventh closed-set fieldless typed
// enum on the caixa surface (the third M3-mesh-primitive-
// defining slot enum, the `:politicas :rate-limit`
// canonical-suffix axis the caixa-mesh renderer keys off end-
// to-end for per-Aplicacao Envoy
// `local_rate_limit.token_bucket.fill_interval` overlay
// emission).
const SECOND: &str = super::RateLimitUnit::Second.as_suffix();
const MINUTE: &str = super::RateLimitUnit::Minute.as_suffix();
const HOUR: &str = super::RateLimitUnit::Hour.as_suffix();
for &unit in super::RateLimitUnit::ALL {
let via_trait: &'static str = <&'static str as From<super::RateLimitUnit>>::from(unit);
let via_method: &'static str = unit.as_suffix();
assert_eq!(
via_trait, via_method,
"From<RateLimitUnit> for &'static str impl must \
round-trip RateLimitUnit::{unit:?} to the same \
canonical-suffix byte-string RateLimitUnit::as_suffix \
returns — divergence signals a silent detour off the \
substrate-primitive accessor"
);
let via_into: &'static str = unit.into();
assert_eq!(
via_into, via_method,
"Into<&'static str>::into on RateLimitUnit::{unit:?} \
must byte-equal RateLimitUnit::as_suffix on the same \
input — the blanket-derived Into shape must resolve to \
the same as_suffix dispatch as the explicit From impl"
);
}
assert_eq!(
[SECOND, MINUTE, HOUR],
["s", "m", "h"],
"const-context RateLimitUnit::as_suffix must resolve to the \
three canonical-suffix byte-strings — a future accidental \
downgrade of any arm to a non-const or non-static \
byte-string breaks the `&'static str`-lifetime promise the \
paired From<RateLimitUnit> for &'static str impl carries \
by construction"
);
}
#[test]
fn rate_limit_unit_from_into_static_str_and_as_suffix_partition_the_emit_set() {
// Cross-axis partition pin: the paired trait-idiomatic
// `From<RateLimitUnit> for &'static str` forward projection and
// the method-named [`super::RateLimitUnit::as_suffix`] forward
// projection must resolve identically on *every* arm, not just
// the ones named in the primary byte-parity pin above. Sweeps
// every [`super::RateLimitUnit::ALL`] arm and asserts the
// trait's `From::from` output byte-equals the method-named
// accessor's return-value on each, locking the two forward-
// projection paths together by construction so any future
// detour (a stray `From` special-case that lands on a divergent
// per-arm literal outside the paired `as_suffix` dispatch, a
// hypothetical rebrand touching one axis without the other)
// trips at caixa-core test time.
//
// Peer of the sibling forward-projection partition pins
// [`crate::supervisor::tests::restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
// (523157d),
// [`crate::supervisor::tests::restart_policy_from_into_static_str_and_as_str_partition_the_emit_set`]
// (9fb37d0),
// [`crate::kind::tests::caixa_kind_from_into_static_str_and_as_str_partition_the_emit_set`]
// (edb827b),
// [`crate::dialeto::tests::caixa_dialeto_from_into_static_str_and_as_str_partition_the_emit_set`]
// (c189a6f),
// [`tests::placement_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
// (afa3562), and
// [`tests::wit_shape_from_into_static_str_and_as_str_partition_the_emit_set`]
// (56998ec) — extends the round-trip discipline onto the seventh
// closed-set typed enum on the caixa surface, closing the two-
// way `Self ↔ &'static str` round-trip on the trait-idiomatic
// pair (`From<Self> for &'static str` + `TryFrom<&str> for
// Self`) as well as the pre-existing method-named pair
// (`as_suffix` + `from_suffix`).
for &unit in super::RateLimitUnit::ALL {
let via_trait: &'static str = <&'static str as From<super::RateLimitUnit>>::from(unit);
let via_method: &'static str = unit.as_suffix();
assert_eq!(
via_trait, via_method,
"From<RateLimitUnit> for &'static str and \
RateLimitUnit::as_suffix must resolve identically on \
RateLimitUnit::{unit:?} — divergence signals the two \
forward-projection paths have drifted onto different \
emit-sets"
);
}
// Round-trip witness: every arm's forward `From` output re-parses
// through the paired trait-idiomatic reverse `TryFrom<&str>` back
// to the original variant. Closes the two-way `RateLimitUnit ↔
// &'static str` round-trip on the trait-idiomatic axis pair
// directly (no wire-vocab intermediate the peer [`CaixaKind`]
// axis pair requires — the emit-side
// [`super::RateLimitUnit::as_suffix`] and the parse-side
// [`super::RateLimitUnit::from_suffix`] dispatch on the same
// three inline canonical-suffix byte-strings by construction),
// mirroring the pre-existing method-named `as_suffix` +
// `from_suffix` round-trip on the substrate-primitive axis pair
// and the peer [`super::WitShape`] round-trip (56998ec) on the
// sibling M3-mesh-primitive-defining slot enum.
for &unit in super::RateLimitUnit::ALL {
let emitted: &'static str = unit.into();
let re_parsed: Result<super::RateLimitUnit, ()> =
<super::RateLimitUnit as TryFrom<&str>>::try_from(emitted);
assert_eq!(
re_parsed,
Ok(unit),
"trait-idiomatic axis pair must round-trip \
RateLimitUnit::{unit:?} through `.into::<&'static \
str>()` and back through `TryFrom<&str>` — a break \
signals the forward-emit and reverse-parse axes have \
drifted onto different vocabularies"
);
}
}
#[test]
fn rate_limit_unit_from_borrowed_into_static_str_routes_through_as_suffix_accessor() {
// Fail-before-pass-after byte-parity pin on the newly lifted
// `impl From<&RateLimitUnit> for &'static str` — asserts the
// borrowed-input standard-library trait impl and the substrate-
// primitive [`super::RateLimitUnit::as_suffix`] `pub const fn`
// accessor resolve to the same three-arm canonical-suffix
// emit-set across every arm the exhaustive
// [`super::RateLimitUnit::ALL`] slice enumerates. Rust's `From`
// trait does not auto-derive the borrowed-input sibling from a
// paired owned-input impl (no `impl<T, U> From<&T> for U where
// T: Copy, U: From<T>` blanket in `core`), so the borrowed-input
// axis is a distinct trait-idiomatic surface that a
// `.iter().map(Into::into)` shape over
// [`super::RateLimitUnit::ALL`] (whose iterator yields
// `&RateLimitUnit`, not `RateLimitUnit`) reaches through this
// impl and no other — the paired owned-input
// [`From<RateLimitUnit>`] impl requires an explicit `.copied()`
// / dereference before the trait fires. Materializes the
// `<&'static str as From<&RateLimitUnit>>::from` output in three
// `const`-shape bindings against the paired
// [`super::RateLimitUnit::as_suffix`] `pub const fn` accessor to
// make the `'static` lifetime promise a build-time invariant —
// a future accidental downgrade of any of the three arms'
// inline canonical-suffix byte-strings to a non-`&'static str`
// (a `String::leak()`-produced return, a `Box::leak`-cast, an
// intermediate lifetime-erasing helper) trips at caixa-core
// build time rather than at a downstream `'static`-bound
// consumer.
//
// Peer of the sibling
// [`crate::dep::tests::dep_list_from_borrowed_into_static_str_routes_through_as_str_accessor`]
// (64aa742),
// [`crate::kind::tests::caixa_kind_from_borrowed_into_static_str_routes_through_as_str_accessor`]
// (5ab993a),
// [`crate::dialeto::tests::caixa_dialeto_from_borrowed_into_static_str_routes_through_as_str_accessor`]
// (807b0b5),
// [`crate::supervisor::tests::restart_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
// (e941836),
// [`crate::supervisor::tests::restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
// (842c7f3),
// [`tests::placement_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
// (4d941d8), and
// [`tests::wit_shape_from_borrowed_into_static_str_routes_through_as_str_accessor`]
// (3187bd0) pins on the sibling closed-set typed-enum
// borrowed-input forward-projection axes — extends the
// borrowed-input axis onto the third (and last) M3-mesh-
// primitive-defining closed-set typed enum on the caixa surface
// (the `:politicas :rate-limit` canonical-suffix axis the
// caixa-mesh renderer keys off end-to-end for per-Aplicacao
// Envoy `local_rate_limit.token_bucket.fill_interval` overlay
// emission).
const SECOND: &str = super::RateLimitUnit::Second.as_suffix();
const MINUTE: &str = super::RateLimitUnit::Minute.as_suffix();
const HOUR: &str = super::RateLimitUnit::Hour.as_suffix();
for unit in super::RateLimitUnit::ALL {
let via_trait: &'static str = <&'static str as From<&super::RateLimitUnit>>::from(unit);
let via_method: &'static str = unit.as_suffix();
assert_eq!(
via_trait, via_method,
"From<&RateLimitUnit> for &'static str impl must \
round-trip &RateLimitUnit::{unit:?} to the same \
canonical-suffix byte-string RateLimitUnit::as_suffix \
returns — divergence signals a silent detour off the \
substrate-primitive accessor"
);
let via_into: &'static str = unit.into();
assert_eq!(
via_into, via_method,
"Into<&'static str>::into on &RateLimitUnit::{unit:?} \
must byte-equal RateLimitUnit::as_suffix on the same \
input — the blanket-derived Into shape must resolve to \
the same as_suffix dispatch as the explicit From impl"
);
}
assert_eq!(
[SECOND, MINUTE, HOUR],
["s", "m", "h"],
"const-context RateLimitUnit::as_suffix must resolve to the \
three canonical-suffix byte-strings — the borrowed-input \
From<&RateLimitUnit> for &'static str impl inherits its \
`'static` lifetime promise from the same accessor the \
owned-input sibling routes through"
);
}
#[test]
fn rate_limit_unit_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
// Cross-axis partition pin: the paired trait-idiomatic
// owned-input `From<RateLimitUnit> for &'static str` (7fdfbf4
// campaign-shape) and borrowed-input `From<&RateLimitUnit> for
// &'static str` (this lift) forward projections must resolve
// identically on every arm, locking the two input-shape paths
// together so any future detour trips at caixa-core test time.
// Then a witness that a `.iter().map(Into::into)` pipe over
// [`super::RateLimitUnit::ALL`] (whose iterator yields
// `&RateLimitUnit`) materializes the three-arm accept-set
// through the borrowed-input axis alone — the exact shape a
// future M4 admission-webhook rejection body's accepted-set
// enumeration, a future substrate-wide per-arm diagnostic
// column, or a `HashMap::<&'static str,
// RateLimitUnit>::from_iter(RateLimitUnit::ALL.iter().map(|u|
// (u.into(), *u)))`-style per-unit lookup reaches through —
// closing the two-way owned/borrowed input-shape symmetry on
// the M3 slot enum's forward-projection trait-idiomatic axis.
// Peer of the sibling
// [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
// (64aa742),
// [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
// (5ab993a),
// [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
// (807b0b5),
// [`crate::supervisor::tests::restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
// (e941836),
// [`crate::supervisor::tests::restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
// (842c7f3),
// [`tests::placement_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
// (4d941d8), and
// [`tests::wit_shape_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
// (3187bd0) partition pins on the sibling closed-set typed-enum
// discriminator axes — extends the borrowed-input axis
// discipline onto the third (and last) M3-mesh-primitive-
// defining closed-set typed enum on the caixa surface (the
// `:politicas :rate-limit` canonical-suffix axis). Also closes
// the direct two-way `&Self → &'static str → Self` round-trip
// via the paired [`TryFrom<&str>`] axis — unlike the peer
// [`crate::CaixaKind`] axis pair (whose forward `From` emits
// lowercase Portuguese diagnostic bytes while the reverse
// `TryFrom` parses `PascalCase` wire bytes, forcing the
// round-trip through an intermediate wire-vocab hop), the
// [`super::RateLimitUnit::as_suffix`] emit and
// [`super::RateLimitUnit::from_suffix`] parse share the same
// three inline canonical-suffix byte-strings by construction,
// so the borrowed-input forward axis and the reverse axis
// compose directly.
for &unit in super::RateLimitUnit::ALL {
let owned: &'static str = <&'static str as From<super::RateLimitUnit>>::from(unit);
let borrowed: &'static str = <&'static str as From<&super::RateLimitUnit>>::from(&unit);
assert_eq!(
owned, borrowed,
"From<RateLimitUnit> and From<&RateLimitUnit> for \
&'static str must resolve identically on \
RateLimitUnit::{unit:?} — divergence signals the \
owned-input and borrowed-input forward-projection paths \
have drifted onto different emit-sets"
);
}
let via_iter: Vec<&'static str> =
super::RateLimitUnit::ALL.iter().map(Into::into).collect();
let via_method: Vec<&'static str> = super::RateLimitUnit::ALL
.iter()
.map(|u| u.as_suffix())
.collect();
assert_eq!(
via_iter, via_method,
"`.iter().map(Into::into)` over RateLimitUnit::ALL must \
byte-equal `.iter().map(|u| u.as_suffix())` on every arm — \
the borrowed-input `From<&RateLimitUnit> for &'static str` \
axis is what makes the `.iter().map(Into::into)` shape \
route through the substrate-primitive \
RateLimitUnit::as_suffix accessor rather than through a \
per-call-site `.copied()` / dereference detour"
);
for unit in super::RateLimitUnit::ALL {
let emitted: &'static str = unit.into();
let re_parsed: Result<super::RateLimitUnit, ()> =
<super::RateLimitUnit as TryFrom<&str>>::try_from(emitted);
assert_eq!(
re_parsed,
Ok(*unit),
"trait-idiomatic borrowed-input forward-projection + \
reverse-projection axis pair must round-trip \
&RateLimitUnit::{unit:?} through `.into::<&'static \
str>()` (via the borrowed-input axis) and back through \
`TryFrom<&str>` — a break signals the borrowed-input \
forward-emit and reverse-parse axes have drifted onto \
different vocabularies"
);
}
}
#[test]
fn rate_limit_unit_from_into_owned_string_routes_through_as_suffix_accessor() {
// Fail-before-pass-after byte-parity pin on the newly lifted
// `impl From<RateLimitUnit> for String` — asserts the
// owned-`String`-returning standard-library trait impl and the
// substrate-primitive [`super::RateLimitUnit::as_suffix`]
// `pub const fn` accessor resolve to the same three-arm
// canonical-suffix emit-set across every arm the exhaustive
// [`super::RateLimitUnit::ALL`] slice enumerates. Rust's standard
// library does not carry a blanket
// `impl<T: AsRef<str>> From<T> for String` (nor an
// `impl<T: fmt::Display> From<T> for String`), so the
// owned-`String` forward-projection axis is a distinct trait-
// idiomatic surface that a `let key: String = unit.into();`-
// shaped call site reaches through this impl and no other — the
// paired sibling `From<RateLimitUnit> for &'static str` impl
// forces every owned-`String` call site through an explicit
// `.to_owned()` / `String::from` restatement. Peer of the
// first-mover
// [`crate::supervisor::tests::restart_strategy_from_into_owned_string_routes_through_as_str_accessor`]
// (7baa18a), the second-peer
// [`crate::supervisor::tests::restart_policy_from_into_owned_string_routes_through_as_str_accessor`]
// (7851725), the third-peer
// [`crate::kind::tests::caixa_kind_from_into_owned_string_routes_through_as_str_accessor`]
// (231a18c), the fourth-peer
// [`crate::dialeto::tests::caixa_dialeto_from_into_owned_string_routes_through_as_str_accessor`]
// (88942cd), the fifth-peer
// [`crate::dep::tests::dep_list_from_into_owned_string_routes_through_as_str_accessor`]
// (32b0ee8), the sixth-peer
// [`tests::placement_strategy_from_into_owned_string_routes_through_as_str_accessor`]
// (1154c2f), and the seventh-peer
// [`tests::wit_shape_from_into_owned_string_routes_through_as_str_accessor`]
// (79a8723) — extends the trait-idiomatic owned-`String`
// forward-projection axis onto the eighth closed-set fieldless
// typed enum on the caixa surface (the third — and last —
// M3-mesh-primitive-defining `:politicas :rate-limit`
// canonical-suffix axis).
for &unit in super::RateLimitUnit::ALL {
let via_trait: String = <String as From<super::RateLimitUnit>>::from(unit);
let via_method: &'static str = unit.as_suffix();
assert_eq!(
via_trait.as_str(),
via_method,
"From<RateLimitUnit> for String impl must round-trip \
RateLimitUnit::{unit:?} to the same three-arm \
canonical-suffix byte-string RateLimitUnit::as_suffix \
returns — divergence signals a silent detour off the \
substrate-primitive accessor"
);
let via_into: String = unit.into();
assert_eq!(
via_into.as_str(),
via_method,
"Into<String>::into on RateLimitUnit::{unit:?} must \
byte-equal RateLimitUnit::as_suffix on the same input — \
the blanket-derived Into shape must resolve to the same \
as_suffix dispatch as the explicit From impl"
);
}
}
#[test]
fn rate_limit_unit_from_into_owned_string_and_static_str_agree_on_every_arm() {
// Cross-axis partition pin: the paired trait-idiomatic
// owned-`String` `From<RateLimitUnit> for String` (this lift)
// and owned-`&'static str` `From<RateLimitUnit> for &'static
// str` (7fdfbf4) forward projections must resolve identically
// on every arm, locking the two return-type-shape paths together
// so any future detour trips at caixa-core test time. Also
// byte-parity witness against the sibling [`ToString::to_string`]
// surface routed through [`std::fmt::Display`] — the three
// owned-heap-string paths (`.into::<String>()`, `String::from`,
// `.to_string()`) must resolve identically on every arm so a
// future consumer that picks any of the three lands on the same
// three-arm inline canonical-suffix accept-set. Then a
// `.iter().copied().map(String::from)` pipe witness over
// [`super::RateLimitUnit::ALL`] that materializes the three-arm
// accept-set through the owned-`String` axis alone — the exact
// shape a future M4 admission-webhook rejection body composer
// or a `HashMap::<String, RateLimitUnit>::from_iter(
// RateLimitUnit::ALL.iter().copied().map(|u| (u.into(),
// u)))`-style owned-key per-unit lookup reaches through —
// closing the owned-`String` forward-projection axis's
// iterator-pipe shape. Then a direct round-trip witness through
// the paired trait-idiomatic reverse [`TryFrom<&str>`] axis on
// the owned-`String`'s [`String::as_str`] borrow that closes the
// two-way `Self → String → Self` round-trip on the trait-
// idiomatic owned-`String` forward + reverse axis pair.
//
// Unlike the peer [`crate::CaixaKind`] axis pair (whose forward
// `From` emit lands on the lowercase Portuguese `as_str`
// diagnostic vocabulary while the reverse `TryFrom<&str>`
// parses the `PascalCase` `wire_name` author-surface
// vocabulary, forcing the round-trip through an intermediate
// [`crate::CaixaKind::wire_name`] hop),
// [`super::RateLimitUnit`]'s [`super::RateLimitUnit::as_suffix`]
// emit and [`super::RateLimitUnit::from_suffix`] parse resolve
// through the same three inline canonical-suffix byte-strings
// by construction (there is no wire/diagnostic axis split on
// this enum), so the owned-`String` forward axis and the reverse
// axis compose directly — matching the peer
// [`crate::supervisor::RestartStrategy`] /
// [`crate::supervisor::RestartPolicy`] /
// [`crate::CaixaDialeto`] / [`crate::dep::DepList`] /
// [`super::PlacementStrategy`] / [`super::WitShape`]
// owned-`String` axis pairs.
for &unit in super::RateLimitUnit::ALL {
let owned_string: String = <String as From<super::RateLimitUnit>>::from(unit);
let owned_static: &'static str =
<&'static str as From<super::RateLimitUnit>>::from(unit);
assert_eq!(
owned_string.as_str(),
owned_static,
"From<RateLimitUnit> for String and From<RateLimitUnit> \
for &'static str must resolve identically on \
RateLimitUnit::{unit:?} — divergence signals the \
owned-`String` and owned-`&'static str` forward-\
projection return-type-shape paths have drifted onto \
different emit-sets"
);
let via_to_string: String = unit.to_string();
assert_eq!(
owned_string, via_to_string,
"From<RateLimitUnit> for String must byte-equal \
RateLimitUnit::to_string on RateLimitUnit::{unit:?} — \
divergence signals the trait-idiomatic owned-`String` \
forward-projection axis and the ToString-through-\
Display axis have drifted onto different emit-sets"
);
}
let via_iter: Vec<String> = super::RateLimitUnit::ALL
.iter()
.copied()
.map(String::from)
.collect();
let via_method: Vec<String> = super::RateLimitUnit::ALL
.iter()
.map(|u| u.as_suffix().to_owned())
.collect();
assert_eq!(
via_iter, via_method,
"`.iter().copied().map(String::from)` over RateLimitUnit::ALL \
must byte-equal `.iter().map(|u| u.as_suffix().to_owned())` \
on every arm — the owned-`String` `From<RateLimitUnit> for \
String` axis is what makes the `String::from` composition \
route through the substrate-primitive \
RateLimitUnit::as_suffix accessor rather than through a \
per-call-site `.to_owned()` / `String::from(unit.as_suffix())` \
detour"
);
for &unit in super::RateLimitUnit::ALL {
let emitted: String = unit.into();
let re_parsed: Result<super::RateLimitUnit, ()> =
<super::RateLimitUnit as TryFrom<&str>>::try_from(emitted.as_str());
assert_eq!(
re_parsed,
Ok(unit),
"trait-idiomatic owned-`String` forward-projection + \
reverse-projection axis pair must round-trip \
RateLimitUnit::{unit:?} through `.into::<String>()` and \
back through `TryFrom<&str>` on the owned-`String`'s \
String::as_str borrow — a break signals the \
owned-`String` forward-emit and reverse-parse axes have \
drifted onto different vocabularies (unlike the peer \
CaixaKind axis pair, RateLimitUnit's forward emit and \
reverse parse share the same three inline canonical-\
suffix byte-strings by construction, so the round-trip \
composes directly)"
);
}
}
#[test]
fn rate_limit_unit_from_into_borrowed_owned_string_routes_through_as_suffix_accessor() {
// Fail-before-pass-after byte-parity pin on the newly lifted
// `impl From<&RateLimitUnit> for String` — asserts the
// borrowed-input owned-`String`-returning standard-library
// trait impl and the substrate-primitive
// [`super::RateLimitUnit::as_suffix`] `pub const fn` accessor
// resolve to the same three-arm canonical-suffix emit-set across
// every arm the exhaustive [`super::RateLimitUnit::ALL`] slice
// enumerates. Rust's standard library does not carry a blanket
// `impl<T: AsRef<str>> From<&T> for String` (nor an
// `impl<T: fmt::Display> From<&T> for String`), so the
// borrowed-input owned-`String` forward-projection axis is a
// distinct trait-idiomatic surface that a
// `let key: String = (&unit).into();`-shaped call site reaches
// through this impl and no other — the paired sibling
// `From<RateLimitUnit> for String` impl forces every borrowed-\
// input call site through an explicit `Copy` deref
// (`String::from(*unit)`) or an `.as_suffix().to_owned()` /
// `.to_string()` detour. Peer of the first-mover
// [`crate::supervisor::tests::restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
// (579385f), the second-peer
// [`crate::supervisor::tests::restart_policy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
// (8465740), the third-peer
// [`crate::dep::tests::dep_list_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
// (e0cb617), the fourth-peer
// [`crate::kind::tests::caixa_kind_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
// (e76436d), the fifth-peer
// [`crate::dialeto::tests::caixa_dialeto_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
// (d3c0d1d), the sixth-peer
// [`tests::placement_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
// (d3dc000), and the seventh-peer
// [`tests::wit_shape_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
// (d638fd3) — extends the trait-idiomatic borrowed-input owned-\
// `String` forward-projection axis onto the eighth closed-set
// fieldless typed enum on the caixa surface (the third — and
// last — M3-mesh-primitive-defining `:politicas :rate-limit`
// canonical-suffix axis).
for &unit in super::RateLimitUnit::ALL {
let via_trait: String = <String as From<&super::RateLimitUnit>>::from(&unit);
let via_method: &'static str = unit.as_suffix();
assert_eq!(
via_trait.as_str(),
via_method,
"From<&RateLimitUnit> for String impl must round-trip \
&RateLimitUnit::{unit:?} to the same three-arm \
canonical-suffix byte-string RateLimitUnit::as_suffix \
returns — divergence signals a silent detour off the \
substrate-primitive accessor"
);
let via_into: String = (&unit).into();
assert_eq!(
via_into.as_str(),
via_method,
"Into<String>::into on &RateLimitUnit::{unit:?} must \
byte-equal RateLimitUnit::as_suffix on the same input — \
the blanket-derived Into shape must resolve to the same \
as_suffix dispatch as the explicit From impl"
);
}
}
#[test]
fn rate_limit_unit_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm() {
// Cross-axis partition pin: the newly lifted trait-idiomatic
// borrowed-input owned-`String` `From<&RateLimitUnit> for String`
// (this lift), the paired owned-input owned-`String`
// `From<RateLimitUnit> for String` (c7d687d), the paired
// borrowed-input owned-`&'static str`
// `From<&RateLimitUnit> for &'static str` (f4b9e6b), and the
// paired owned-input owned-`&'static str`
// `From<RateLimitUnit> for &'static str` (7fdfbf4) — every
// corner of the `{Self, &Self} × {&'static str, String}` 2×2
// trait-idiomatic projection family — must resolve identically
// on every arm, locking the four return-shape × input-shape
// paths together so any future detour trips at caixa-core test
// time. Also byte-parity witness against the sibling
// [`ToString::to_string`] surface routed through
// [`std::fmt::Display`] and a direct round-trip witness through
// the paired trait-idiomatic reverse [`TryFrom<&str>`] axis on
// the owned-`String`'s [`String::as_str`] borrow that closes the
// two-way `&Self → String → Self` round-trip on the trait-\
// idiomatic borrowed-input owned-`String` forward + reverse
// axis pair. Peer of the first-mover
// [`crate::supervisor::tests::restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
// (579385f), the second-peer
// [`crate::supervisor::tests::restart_policy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
// (8465740), the third-peer
// [`crate::dep::tests::dep_list_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
// (e0cb617), the fourth-peer
// [`crate::kind::tests::caixa_kind_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
// (e76436d), the fifth-peer
// [`crate::dialeto::tests::caixa_dialeto_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
// (d3c0d1d), the sixth-peer
// [`tests::placement_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
// (d3dc000), and the seventh-peer
// [`tests::wit_shape_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
// (d638fd3) — closes the whole
// `{Self, &Self} × {&'static str, String}` 2×2 projection
// corner across the whole M3 mesh-primitive triple on the
// eighth substrate-wide closed-set fieldless typed enum peer
// (the third — and last — M3-mesh-primitive-defining
// `:politicas :rate-limit` canonical-suffix axis).
//
// Unlike the peer [`crate::CaixaKind`] axis pair (whose forward
// `From` emit lands on the lowercase Portuguese `as_str`
// diagnostic vocabulary while the reverse `TryFrom<&str>`
// parses the `PascalCase` `wire_name` author-surface
// vocabulary, forcing the round-trip through an intermediate
// [`crate::CaixaKind::wire_name`] hop),
// [`super::RateLimitUnit`]'s [`super::RateLimitUnit::as_suffix`]
// emit and [`super::RateLimitUnit::from_suffix`] parse resolve
// through the same three inline canonical-suffix byte-strings
// by construction (there is no wire/diagnostic axis split on
// this M3 slot enum), so the borrowed-input owned-`String`
// forward axis and the reverse axis compose directly — matching
// the peer [`crate::supervisor::RestartStrategy`] /
// [`crate::supervisor::RestartPolicy`] / [`crate::dep::DepList`]
// / [`crate::CaixaDialeto`] / [`super::PlacementStrategy`] /
// [`super::WitShape`] borrowed-input owned-`String` axis pairs.
for &unit in super::RateLimitUnit::ALL {
let borrowed_string: String = <String as From<&super::RateLimitUnit>>::from(&unit);
let owned_string: String = <String as From<super::RateLimitUnit>>::from(unit);
let borrowed_static: &'static str =
<&'static str as From<&super::RateLimitUnit>>::from(&unit);
let owned_static: &'static str =
<&'static str as From<super::RateLimitUnit>>::from(unit);
assert_eq!(
borrowed_string, owned_string,
"From<&RateLimitUnit> for String and From<RateLimitUnit> \
for String must resolve identically on RateLimitUnit::\
{unit:?} — divergence signals the borrowed-input and \
owned-input owned-`String` forward-projection input-\
shape paths have drifted onto different emit-sets"
);
assert_eq!(
borrowed_string.as_str(),
borrowed_static,
"From<&RateLimitUnit> for String and From<&RateLimitUnit> \
for &'static str must resolve identically on \
RateLimitUnit::{unit:?} — divergence signals the \
borrowed-input `&'static str` and owned-`String` \
return-shape paths have drifted onto different \
emit-sets"
);
assert_eq!(
borrowed_string.as_str(),
owned_static,
"From<&RateLimitUnit> for String and From<RateLimitUnit> \
for &'static str must resolve identically on \
RateLimitUnit::{unit:?} — divergence signals a break \
in the diagonal corner of the {{Self, &Self}} × \
{{&'static str, String}} 2×2 trait-idiomatic \
projection family"
);
let via_to_string: String = unit.to_string();
assert_eq!(
borrowed_string, via_to_string,
"From<&RateLimitUnit> for String must byte-equal \
RateLimitUnit::to_string on RateLimitUnit::{unit:?} — \
divergence signals the trait-idiomatic borrowed-input \
owned-`String` forward-projection axis and the \
ToString-through-Display axis have drifted onto \
different emit-sets"
);
}
let via_iter: Vec<String> = super::RateLimitUnit::ALL.iter().map(String::from).collect();
let via_method: Vec<String> = super::RateLimitUnit::ALL
.iter()
.map(|u| u.as_suffix().to_owned())
.collect();
assert_eq!(
via_iter, via_method,
"`.iter().map(String::from)` over RateLimitUnit::ALL — a \
call site whose iteration axis holds `&RateLimitUnit` by \
construction — must byte-equal `.iter().map(|u| \
u.as_suffix().to_owned())` on every arm — the borrowed-\
input owned-`String` `From<&RateLimitUnit> for String` \
axis is what makes the `String::from` composition route \
through the substrate-primitive RateLimitUnit::as_suffix \
accessor without a spurious `Copy` deref (which would \
only be reachable through the owned-input \
`From<RateLimitUnit> for String` axis by first calling \
`.copied()` on the iterator)"
);
for &unit in super::RateLimitUnit::ALL {
let emitted: String = (&unit).into();
let re_parsed: Result<super::RateLimitUnit, ()> =
<super::RateLimitUnit as TryFrom<&str>>::try_from(emitted.as_str());
assert_eq!(
re_parsed,
Ok(unit),
"trait-idiomatic borrowed-input owned-`String` \
forward-projection + reverse-projection axis pair \
must round-trip &RateLimitUnit::{unit:?} through \
`.into::<String>()` on the borrowed-input surface and \
back through `TryFrom<&str>` on the owned-`String`'s \
String::as_str borrow — a break signals the \
borrowed-input owned-`String` forward-emit and \
reverse-parse axes have drifted onto different \
vocabularies (unlike the peer CaixaKind axis pair, \
RateLimitUnit's forward emit and reverse parse share \
the same three inline canonical-suffix byte-strings \
by construction, so the round-trip composes directly)"
);
}
}
#[test]
fn rate_limit_unit_from_into_static_cow_str_routes_through_as_suffix_accessor() {
// Fail-before-pass-after byte-parity pin on the newly lifted
// `impl From<RateLimitUnit> for
// std::borrow::Cow<'static, str>` — asserts the standard-
// library trait impl and the substrate-primitive
// [`super::RateLimitUnit::as_suffix`] `pub const fn`
// accessor resolve to the same three-arm emit-set across
// every arm the exhaustive [`super::RateLimitUnit::ALL`]
// slice enumerates. Rust's standard library does not carry a
// blanket `impl<T: AsRef<str>> From<T> for Cow<'static, str>`
// (nor an `impl<T: fmt::Display> From<T> for
// Cow<'static, str>`), so the `Cow<'static, str>` forward-
// projection axis is a distinct trait-idiomatic surface that
// a `let key: Cow<'static, str> = unit.into();`-shaped call
// site reaches through this impl and no other — the paired
// sibling `From<RateLimitUnit> for &'static str` and
// `From<RateLimitUnit> for String` impls force every
// `Cow<'static, str>`-parameterized call site through a
// `Cow::Borrowed(unit.as_suffix())` /
// `Cow::Owned(unit.to_string())` composition whose type
// bounds have no compile-time link back to the substrate
// primitive.
//
// Also asserts the projection lands on the zero-alloc
// [`std::borrow::Cow::Borrowed`] arm (not the
// [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
// [`super::RateLimitUnit::as_suffix`] accessor's
// `&'static str` return lifetime by construction (each match
// arm resolves to one of the three inline `"s"` / `"m"` /
// `"h"` canonical-suffix `&'static str` values) makes the
// borrowed arm the type-correct projection with no runtime
// allocation. Any future silent detour that routes the impl
// through the owned arm trips at caixa-core test time under
// the [`std::borrow::Cow::Borrowed`] discriminator witness
// rather than at a downstream `Cow<'static, str>`-bound
// consumer's silent allocation.
//
// Third — and last — M3-mesh-primitive-defining peer on the
// substrate-wide trait-idiomatic
// [`std::borrow::Cow<'static, str>`] forward-projection
// campaign — extends the axis off the paired
// [`super::WitShape`] `:contratos :wit` census-label first-
// mover (8634dec + 25690ef) and the paired
// [`super::PlacementStrategy`] `:placement :estrategia`
// distribution-strategy second-peer (eee504d + afdf0f4) onto
// the third — and last — M3-slot-enum peer, closing the M3-
// mesh-shape tier of the campaign's owned-input corner.
for &variant in super::RateLimitUnit::ALL {
let via_trait: std::borrow::Cow<'static, str> =
<std::borrow::Cow<'static, str> as From<super::RateLimitUnit>>::from(variant);
let via_method: &'static str = variant.as_suffix();
assert_eq!(
via_trait.as_ref(),
via_method,
"From<RateLimitUnit> for Cow<'static, str> impl must \
round-trip RateLimitUnit::{variant:?} to the same \
inline canonical-suffix byte-string \
RateLimitUnit::as_suffix returns — divergence \
signals a silent detour off the substrate-primitive \
accessor"
);
assert!(
matches!(via_trait, std::borrow::Cow::Borrowed(_)),
"From<RateLimitUnit> for Cow<'static, str> impl must \
land on the zero-alloc Cow::Borrowed arm on \
RateLimitUnit::{variant:?} — a Cow::Owned outcome \
signals the projection has silently allocated where \
the substrate-primitive RateLimitUnit::as_suffix \
`&'static str` return makes the borrowed arm the \
type-correct projection"
);
let via_into: std::borrow::Cow<'static, str> = variant.into();
assert_eq!(
via_into.as_ref(),
via_method,
"Into<Cow<'static, str>>::into on RateLimitUnit::\
{variant:?} must byte-equal RateLimitUnit::as_suffix \
on the same input — the blanket-derived Into shape \
must resolve to the same as_suffix dispatch as the \
explicit From impl"
);
assert!(
matches!(via_into, std::borrow::Cow::Borrowed(_)),
"Into<Cow<'static, str>>::into on RateLimitUnit::\
{variant:?} must land on the zero-alloc \
Cow::Borrowed arm — the blanket-derived Into shape \
must resolve to the same Cow::Borrowed dispatch as \
the explicit From impl"
);
}
}
#[test]
fn rate_limit_unit_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
// Cross-axis partition pin: the newly lifted trait-idiomatic
// `From<RateLimitUnit> for std::borrow::Cow<'static, str>`
// (this lift), the paired owned-input `From<RateLimitUnit>
// for &'static str` (7fdfbf4), and the paired owned-input
// `From<RateLimitUnit> for String` (c7d687d) forward
// projections must resolve identically on every arm, locking
// the three return-shape paths together by construction so
// any future detour trips at caixa-core test time. Also
// byte-parity witness against the sibling
// [`ToString::to_string`] surface routed through
// [`std::fmt::Display`] — every owned-heap-string path (the
// `Cow::Owned` promotion of this axis's `.into_owned()`,
// `From<RateLimitUnit> for String`, and `.to_string()`)
// resolves to the same three-arm inline canonical-suffix
// byte-string per arm.
//
// Then a `.iter().copied().map(std::borrow::Cow::from)` pipe
// witness over [`super::RateLimitUnit::ALL`] that
// materializes the three-arm accept-set through the
// [`std::borrow::Cow<'static, str>`] axis alone — the exact
// shape a future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
// admission-webhook rejection body's accepted-`:politicas
// :rate-limit` canonical-suffix enumeration, a future
// substrate-wide per-arm diagnostic surface whose typing
// rules out the sibling [`AsRef<str>`] borrowed return, or a
// future per-arm rate-limit-suffix emitter that binds
// through a [`Cow<'static, str>`] boundary reaches through —
// closing the composable-projection axis on the third — and
// last — M3-mesh-primitive-defining closed-set fieldless
// typed enum peer on the caixa surface. The pipe witness
// also pins the zero-alloc discipline: every element in the
// collected vector satisfies the
// [`std::borrow::Cow::Borrowed`] arm predicate, so a future
// accidental silent-allocation regression on the pipe's
// iteration axis is a caixa-core-test-time failure.
for &variant in super::RateLimitUnit::ALL {
let via_cow: std::borrow::Cow<'static, str> =
<std::borrow::Cow<'static, str> as From<super::RateLimitUnit>>::from(variant);
let via_static: &'static str =
<&'static str as From<super::RateLimitUnit>>::from(variant);
let via_string: String = <String as From<super::RateLimitUnit>>::from(variant);
assert_eq!(
via_cow.as_ref(),
via_static,
"From<RateLimitUnit> for Cow<'static, str> and \
From<RateLimitUnit> for &'static str must resolve \
identically on RateLimitUnit::{variant:?} — \
divergence signals the Cow<'static, str> and \
&'static str return-shape paths have drifted onto \
different emit-sets"
);
assert_eq!(
via_cow.as_ref(),
via_string.as_str(),
"From<RateLimitUnit> for Cow<'static, str> and \
From<RateLimitUnit> for String must resolve \
identically on RateLimitUnit::{variant:?} — \
divergence signals the Cow<'static, str> and String \
return-shape paths have drifted onto different \
emit-sets"
);
let via_to_string: String = variant.to_string();
assert_eq!(
via_cow.as_ref(),
via_to_string.as_str(),
"From<RateLimitUnit> for Cow<'static, str> must \
byte-equal RateLimitUnit::to_string on \
RateLimitUnit::{variant:?} — divergence signals the \
trait-idiomatic Cow<'static, str> forward-\
projection axis and the ToString-through-Display \
axis have drifted onto different emit-sets"
);
}
let via_iter: Vec<std::borrow::Cow<'static, str>> = super::RateLimitUnit::ALL
.iter()
.copied()
.map(std::borrow::Cow::from)
.collect();
let via_method: Vec<std::borrow::Cow<'static, str>> = super::RateLimitUnit::ALL
.iter()
.map(|u| std::borrow::Cow::Borrowed(u.as_suffix()))
.collect();
assert_eq!(
via_iter, via_method,
"`.iter().copied().map(Cow::from)` over \
RateLimitUnit::ALL must byte-equal `.iter().map(|u| \
Cow::Borrowed(u.as_suffix()))` on every arm — the \
trait-idiomatic `From<RateLimitUnit> for \
Cow<'static, str>` axis is what makes the `Cow::from` \
composition route through the substrate-primitive \
`RateLimitUnit::as_suffix` accessor with the zero-alloc \
Cow::Borrowed arm by construction, rather than a per-\
call-site `Cow::Owned(unit.to_string())` allocation"
);
for cow in &via_iter {
assert!(
matches!(cow, std::borrow::Cow::Borrowed(_)),
"every element of the .iter().copied().map(Cow::from) \
pipe over RateLimitUnit::ALL must land on the zero-\
alloc Cow::Borrowed arm — a Cow::Owned outcome on \
any arm signals the pipe's iteration axis has \
silently allocated where the substrate-primitive \
RateLimitUnit::as_suffix `&'static str` return makes \
the borrowed arm the type-correct projection"
);
}
}
#[test]
fn rate_limit_unit_from_borrowed_into_static_cow_str_routes_through_as_suffix_accessor() {
// Fail-before-pass-after byte-parity pin on the newly lifted
// `impl From<&RateLimitUnit> for
// std::borrow::Cow<'static, str>` — asserts the borrowed-input
// standard-library trait impl and the substrate-primitive
// [`super::RateLimitUnit::as_suffix`] `pub const fn` accessor
// resolve to the same three-arm emit-set across every arm the
// exhaustive [`super::RateLimitUnit::ALL`] slice enumerates.
// Rust's standard library does not carry a blanket
// `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor a
// `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`), so
// the borrowed-input `Cow<'static, str>` forward-projection axis
// is a distinct trait-idiomatic surface that a
// `let key: Cow<'static, str> = (&unit).into();`-shaped call
// site or a `RateLimitUnit::ALL.iter().map(Cow::from)`-shaped
// pipe reaches through this impl and no other — the paired
// owned-input `From<RateLimitUnit> for Cow<'static, str>` impl
// (1d59925) forces every borrowed-input call site through an
// explicit `Copy` deref (`Cow::from(*unit)`) or a
// `Cow::Borrowed(unit.as_suffix())` open-code whose type bounds
// have no compile-time link back to the substrate primitive.
//
// Also asserts the projection lands on the zero-alloc
// [`std::borrow::Cow::Borrowed`] arm (not the
// [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
// [`super::RateLimitUnit::as_suffix`] accessor's `&'static str`
// return lifetime by construction (each match arm resolves to
// one of the three inline `"s"` / `"m"` / `"h"` byte-strings
// with static lifetime) makes the borrowed arm the type-correct
// projection with no runtime allocation on the borrowed-input
// surface just as on the paired owned-input surface.
//
// Closes the `{Self, &Self}` input-shape corner on the M3-mesh-
// shape `:politicas :rate-limit` canonical-suffix
// [`Cow<'static, str>`] axis on the third-and-last M3-mesh-
// primitive-defining closed-set fieldless typed enum peer on
// the caixa surface, closing the whole M3-mesh-shape tier of
// the substrate-wide [`Cow<'static, str>`] forward-projection
// campaign, exactly as afdf0f4 closed it on the second
// M3-mesh-primitive peer ([`super::PlacementStrategy`]) one
// commit after the owning half (eee504d) landed, as 25690ef
// closed it on the first M3-mesh-primitive peer
// ([`super::WitShape`]) one commit after (8634dec) landed, as
// d45c409 closed it on the top-level [`super::CaixaKind`] one
// commit after (99c1735) landed, and as 9b3e4b3 / ee577fd
// closed it on the M2 OTP-shape
// [`crate::supervisor::RestartStrategy`] /
// [`crate::supervisor::RestartPolicy`] sibling peers one commit
// after (7dd28b3 / 0612398) landed.
for &variant in super::RateLimitUnit::ALL {
let via_trait: std::borrow::Cow<'static, str> =
<std::borrow::Cow<'static, str> as From<&super::RateLimitUnit>>::from(&variant);
let via_method: &'static str = variant.as_suffix();
assert_eq!(
via_trait.as_ref(),
via_method,
"From<&RateLimitUnit> for Cow<'static, str> impl must \
round-trip &RateLimitUnit::{variant:?} to the same \
inline canonical-suffix byte-string \
RateLimitUnit::as_suffix returns — divergence \
signals a silent detour off the substrate-primitive \
accessor"
);
assert!(
matches!(via_trait, std::borrow::Cow::Borrowed(_)),
"From<&RateLimitUnit> for Cow<'static, str> impl must \
land on the zero-alloc Cow::Borrowed arm on \
&RateLimitUnit::{variant:?} — a Cow::Owned outcome \
signals the projection has silently allocated where \
the substrate-primitive RateLimitUnit::as_suffix \
`&'static str` return makes the borrowed arm the \
type-correct projection"
);
let via_into: std::borrow::Cow<'static, str> = (&variant).into();
assert_eq!(
via_into.as_ref(),
via_method,
"Into<Cow<'static, str>>::into on &RateLimitUnit::\
{variant:?} must byte-equal RateLimitUnit::as_suffix \
on the same input — the blanket-derived Into shape \
must resolve to the same as_suffix dispatch as the \
explicit From impl"
);
assert!(
matches!(via_into, std::borrow::Cow::Borrowed(_)),
"Into<Cow<'static, str>>::into on &RateLimitUnit::\
{variant:?} must land on the zero-alloc \
Cow::Borrowed arm — the blanket-derived Into shape \
must resolve to the same Cow::Borrowed dispatch as \
the explicit From impl"
);
}
}
#[test]
fn rate_limit_unit_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
// Cross-axis partition pin: the newly lifted trait-idiomatic
// borrowed-input `From<&RateLimitUnit> for
// std::borrow::Cow<'static, str>` (this lift), the paired
// owned-input `From<RateLimitUnit> for
// std::borrow::Cow<'static, str>` (1d59925), the paired
// borrowed-input owned-`&'static str` `From<&RateLimitUnit>
// for &'static str`, and the paired borrowed-input owned-
// `String` `From<&RateLimitUnit> for String` must resolve
// identically on every arm, locking the four return-shape ×
// input-shape paths together by construction so any future
// detour trips at caixa-core test time. Also byte-parity
// witness against the sibling [`ToString::to_string`] surface
// routed through [`std::fmt::Display`] — every owned-heap-
// string path (this axis's `.into_owned()` promotion, the
// paired [`From<&RateLimitUnit> for String`], and
// `.to_string()`) resolves to the same three-arm inline
// canonical-suffix byte-string per arm.
//
// Then a `.iter().map(std::borrow::Cow::from)` pipe witness
// over [`super::RateLimitUnit::ALL`] — whose iterator yields
// `&RateLimitUnit` by construction, so the borrowed-input
// [`Cow<'static, str>`] axis is what routes the pipe through
// the substrate-primitive [`super::RateLimitUnit::as_suffix`]
// accessor without a spurious [`Copy`] deref (which would only
// be reachable through the owned-input [`From<RateLimitUnit>
// for Cow<'static, str>`] axis by first calling `.copied()`
// on the iterator). The pipe witness also pins the zero-alloc
// discipline: every element in the collected vector satisfies
// the [`std::borrow::Cow::Borrowed`] arm predicate, so a
// future accidental silent-allocation regression on the pipe's
// iteration axis is a caixa-core-test-time failure. Peer of
// the sibling
// [`placement_strategy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
// (afdf0f4) and
// [`wit_shape_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
// (25690ef) on the M3-mesh-shape `:placement :estrategia` and
// `:contratos :wit` axes — closes the whole borrowed-input
// `Cow<'static, str>` + paired `{&'static str, String}` cross-
// axis-parity corner on the third-and-last M3-mesh-primitive-
// defining closed-set fieldless typed enum peer on the caixa
// surface.
for &variant in super::RateLimitUnit::ALL {
let borrowed_cow: std::borrow::Cow<'static, str> =
<std::borrow::Cow<'static, str> as From<&super::RateLimitUnit>>::from(&variant);
let owned_cow: std::borrow::Cow<'static, str> =
<std::borrow::Cow<'static, str> as From<super::RateLimitUnit>>::from(variant);
let borrowed_static: &'static str =
<&'static str as From<&super::RateLimitUnit>>::from(&variant);
let borrowed_string: String = <String as From<&super::RateLimitUnit>>::from(&variant);
assert_eq!(
borrowed_cow, owned_cow,
"From<&RateLimitUnit> for Cow<'static, str> and \
From<RateLimitUnit> for Cow<'static, str> must \
resolve identically on RateLimitUnit::{variant:?} — \
divergence signals the borrowed-input and owned-\
input Cow<'static, str> forward-projection input-\
shape paths have drifted onto different emit-sets"
);
assert_eq!(
borrowed_cow.as_ref(),
borrowed_static,
"From<&RateLimitUnit> for Cow<'static, str> and \
From<&RateLimitUnit> for &'static str must resolve \
identically on RateLimitUnit::{variant:?} — \
divergence signals the borrowed-input Cow<'static, \
str> and &'static str return-shape paths have \
drifted onto different emit-sets"
);
assert_eq!(
borrowed_cow.as_ref(),
borrowed_string.as_str(),
"From<&RateLimitUnit> for Cow<'static, str> and \
From<&RateLimitUnit> for String must resolve \
identically on RateLimitUnit::{variant:?} — \
divergence signals the borrowed-input Cow<'static, \
str> and owned-`String` return-shape paths have \
drifted onto different emit-sets"
);
let via_to_string: String = variant.to_string();
assert_eq!(
borrowed_cow.as_ref(),
via_to_string.as_str(),
"From<&RateLimitUnit> for Cow<'static, str> must \
byte-equal RateLimitUnit::to_string on \
RateLimitUnit::{variant:?} — divergence signals the \
trait-idiomatic borrowed-input Cow<'static, str> \
forward-projection axis and the ToString-through-\
Display axis have drifted onto different emit-sets"
);
}
let via_iter: Vec<std::borrow::Cow<'static, str>> = super::RateLimitUnit::ALL
.iter()
.map(std::borrow::Cow::from)
.collect();
let via_method: Vec<std::borrow::Cow<'static, str>> = super::RateLimitUnit::ALL
.iter()
.map(|u| std::borrow::Cow::Borrowed(u.as_suffix()))
.collect();
assert_eq!(
via_iter, via_method,
"`.iter().map(Cow::from)` over RateLimitUnit::ALL — a \
call site whose iteration axis holds &RateLimitUnit by \
construction — must byte-equal `.iter().map(|u| \
Cow::Borrowed(u.as_suffix()))` on every arm — the \
borrowed-input Cow<'static, str> `From<&RateLimitUnit> \
for Cow<'static, str>` axis is what makes the \
`Cow::from` composition route through the substrate-\
primitive `RateLimitUnit::as_suffix` accessor with the \
zero-alloc Cow::Borrowed arm by construction and \
without a spurious `Copy` deref (which would only be \
reachable through the owned-input `From<RateLimitUnit> \
for Cow<'static, str>` axis by first calling \
`.copied()` on the iterator)"
);
for cow in &via_iter {
assert!(
matches!(cow, std::borrow::Cow::Borrowed(_)),
"every element of the .iter().map(Cow::from) pipe \
over RateLimitUnit::ALL must land on the zero-alloc \
Cow::Borrowed arm — a Cow::Owned outcome on any arm \
signals the pipe's iteration axis has silently \
allocated where the substrate-primitive \
RateLimitUnit::as_suffix `&'static str` return makes \
the borrowed arm the type-correct projection"
);
}
}
#[test]
fn rate_limit_canonical_unit_returns_typed_arm_on_validated_windows() {
// Fail-before-pass-after pin on [`RateLimit::canonical_unit`]:
// every canonical `:window` magnitude the validate gate
// accepts must map to the paired [`RateLimitUnit`] arm through
// this accessor. A future validate-gate rebrand that widened
// the accepted-window set without extending [`RateLimitUnit`]
// would silently split the accessor's `Some`-return set from
// the validate gate's accept-set — a slot that satisfies
// validate would land at the accessor with `None`, so a
// consumer past validate that pattern-matches on the returned
// `Some` would silently miss the newly-accepted magnitude.
for (window_secs, expected) in [
(1u64, super::RateLimitUnit::Second),
(60, super::RateLimitUnit::Minute),
(3600, super::RateLimitUnit::Hour),
] {
let rl = RateLimit {
rate: 100,
window: Duration::from_secs(window_secs),
};
assert_eq!(
rl.canonical_unit(),
Some(expected),
"RateLimit {{ window: {window_secs}s, .. }}.canonical_unit() \
must return Some({expected:?})"
);
}
// Non-canonical windows the validate gate rejects also return
// None here — the accessor is the typed-enum projection of
// the sibling `is_canonical_rate_limit_window` predicate.
let bad = RateLimit {
rate: 100,
window: Duration::from_secs(30),
};
assert!(
bad.canonical_unit().is_none(),
"RateLimit with a non-canonical window must return None from \
canonical_unit — the validate gate rejects the same set"
);
}
#[test]
fn rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix() {
// Fail-before-pass-after byte-parity pin: for every canonical
// window the [`rate_limit_codec::render`] arm's emitted string
// equals `format!("{}/{}", rl.rate(), unit.as_suffix())` where
// `unit = rl.canonical_unit().unwrap()`. Pins the migration from
// the vestigial free helper [`rate_limit_window_unit`] (a
// `find_map`-walked `Duration → &'static str` delegate) onto the
// substrate primitive [`RateLimit::canonical_unit`] typed method
// (a closed-set `match self.window` arm on
// [`RateLimitUnit::from_window`], projected through
// [`RateLimitUnit::as_suffix`] via the enum's
// [`std::fmt::Display`] impl). A future re-routing of the render
// arm through a differently-computed unit projection would break
// this pin at build time rather than as a silent per-consumer
// codec round-trip drift far from the substrate primitive edit.
//
// Sibling to the peer
// [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
// on the free-helper axis: that pin locks the two projections
// (`from_suffix` / `as_suffix` / `from_window` / `window`) agree
// on the closed-set arm table; this pin locks the codec's render
// arm reads through the typed accessor rather than the free
// helper. Two production consumers of the canonical-unit axis
// now key off one typed dispatch on the substrate primitive.
for (window_secs, unit) in [
(1u64, super::RateLimitUnit::Second),
(60, super::RateLimitUnit::Minute),
(3600, super::RateLimitUnit::Hour),
] {
let rl = RateLimit {
rate: 42,
window: Duration::from_secs(window_secs),
};
let policy = MeshPolicy {
rate_limit: Some(rl),
..Default::default()
};
let json = serde_json::to_string(&policy).unwrap();
let expected = format!("\"{}/{}\"", rl.rate(), unit.as_suffix());
assert!(
json.contains(&expected),
"rate_limit_codec::render must emit {expected} (via \
RateLimit::canonical_unit + RateLimitUnit::as_suffix) \
for a {window_secs}s window; serialized MeshPolicy was: {json}"
);
// And the accessor route resolves to the same typed unit
// the render arm's Display formatting is asked to produce —
// so a future edit that split the two paths (one through
// the accessor, one through a re-introduced free helper)
// trips this pin.
assert_eq!(
rl.canonical_unit(),
Some(unit),
"RateLimit::canonical_unit must return Some({unit:?}) for a \
{window_secs}s window; the codec render arm reads the same \
typed unit through this accessor"
);
}
}
#[test]
fn validate_politicas_rate_limit_canonical_window_gate_routes_through_canonical_unit() {
// Fail-before-pass-after byte-parity pin on the validate gate's
// canonical-window shape probe: every non-canonical `:window`
// the free-helper predicate [`is_canonical_rate_limit_window`]
// rejects is also rejected by the substrate primitive
// [`RateLimit::canonical_unit`] `.is_none()` route the validate
// gate now reads through, and vice versa on the accepted set
// (the three canonical windows). Locks the migration from the
// free helper onto the substrate primitive: a future re-routing
// of one of the two paths through a differently-computed unit
// projection would silently split the codec's accepted set from
// the validate gate's accepted set — a two-consumer drift the
// codec-round-trip pin
// [`rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix`]
// above closes on the render arm and this pin closes on the
// validate arm.
for canonical_window_secs in [1u64, 60, 3600] {
let mut s = three_member_spec();
let rl = RateLimit {
rate: 100,
window: Duration::from_secs(canonical_window_secs),
};
s.politicas.rate_limit = Some(rl);
assert!(
s.validate().is_ok(),
"canonical {canonical_window_secs}s window must pass \
validate_politicas — the validate gate now reads \
RateLimit::canonical_unit().is_none() and the accessor \
returns Some on every canonical arm"
);
assert!(
rl.canonical_unit().is_some(),
"canonical {canonical_window_secs}s window must resolve to \
Some on RateLimit::canonical_unit — the validate gate reads \
this accessor directly"
);
}
for non_canonical_window_secs in [2u64, 30, 120, 86_400] {
let mut s = three_member_spec();
let rl = RateLimit {
rate: 100,
window: Duration::from_secs(non_canonical_window_secs),
};
s.politicas.rate_limit = Some(rl);
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyRateLimitWindowNotCanonical {
window: rl.window(),
},
"non-canonical {non_canonical_window_secs}s window must be \
rejected by validate_politicas — the validate gate now \
keys off RateLimit::canonical_unit().is_none()"
);
assert!(
rl.canonical_unit().is_none(),
"non-canonical {non_canonical_window_secs}s window must \
resolve to None on RateLimit::canonical_unit — the two \
paths (the free helper the validate gate previously read \
and the substrate primitive the validate gate now reads) \
must agree on the same rejected set"
);
}
// And the substrate-primitive [`RateLimit::canonical_unit`]
// accessor's accepted-window set matches the codec's parse arm's
// accepted-suffix set on every canonical / non-canonical shape,
// so a future silent drift between the codec's accepted set and
// the validate gate's accepted set is a build error at test time
// (both consumers key off the same closed-set enum's `match self`
// arms). The predecessor free helper `is_canonical_rate_limit_window`
// — a delegate that composed [`RateLimitUnit::from_window`] with
// `.is_some()` — was deleted after this migration; the
// canonical-window set now lives on exactly one typed dispatch
// on the substrate primitive.
for (secs, expected) in [
(1u64, true),
(60, true),
(3600, true),
(2, false),
(30, false),
(86_400, false),
] {
let window = Duration::from_secs(secs);
let rl = RateLimit { rate: 1, window };
assert_eq!(
rl.canonical_unit().is_some(),
expected,
"RateLimit::canonical_unit().is_some() must agree with the \
codec-accepted canonical-window set on {secs}s"
);
let suffix_from_axis = super::RateLimitUnit::window_from_suffix(match secs {
1 => "s",
60 => "m",
3600 => "h",
_ => return,
})
.is_some_and(|d| d == window);
if expected {
assert!(
suffix_from_axis,
"the codec's `&str → Duration` axis \
({secs}s) must round-trip to the same Duration the \
substrate primitive's accessor returns Some on"
);
}
}
}
#[test]
fn rate_limit_unit_is_variant_predicates_partition_the_arm_set() {
// Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
// derive: for each of the three variants, exactly one of the
// generated `is_second` / `is_minute` / `is_hour` predicates
// returns `true` and the other two return `false`. Peer of
// the sibling
// `caixa_kind_is_variant_predicates_partition_the_arm_set` /
// sibling `IsVariant`-derived closed-set typed-enum pins.
let rows: [(super::RateLimitUnit, [bool; 3]); 3] = [
(super::RateLimitUnit::Second, [true, false, false]),
(super::RateLimitUnit::Minute, [false, true, false]),
(super::RateLimitUnit::Hour, [false, false, true]),
];
for (variant, expected) in rows {
let observed = [variant.is_second(), variant.is_minute(), variant.is_hour()];
assert_eq!(
observed, expected,
"RateLimitUnit::{variant:?} is_* predicates must partition \
the arm set (second, minute, hour); got {observed:?}"
);
}
}
#[test]
fn rejects_policy_timeout_sub_millisecond() {
// A purely sub-millisecond `Duration` (`from_micros(500)` =
// 500_000 ns) is not the zero `Duration` — the `is_zero()`
// arm passes — but `as_millis() == 0`, so the shared codec's
// `render` arm returns the literal `"0s"`, which the
// codec's `parse` arm then deserializes as `Duration::ZERO`
// and the `PolicyTimeoutZero` zero-floor gate would reject
// on re-validate. Pin the rejection at the typed slot's
// canonical-floor gate so the round-trip break surfaces at
// validate time, naming the offending `Duration`, rather
// than at the next serialize → deserialize round-trip far
// from the source `caixa.lisp`.
let mut s = three_member_spec();
let timeout = Duration::from_micros(500);
s.politicas.timeout = Some(timeout);
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyTimeoutNotCanonical { timeout }
);
}
#[test]
fn rejects_policy_timeout_non_integer_millisecond() {
// A `Duration` with non-integer-millisecond residue
// (`from_micros(1500)` = 1.5 ms = 1_500_000 ns) renders
// through the shared codec's `render` arm as `"1ms"` (the
// `as_millis()` floor truncates), which the codec's `parse`
// arm then deserializes as `Duration::from_millis(1)` =
// 1_000_000 ns — silently *different* from the original.
// Pin the rejection so this round-trip break surfaces at
// validate time, where the offending `Duration` is named,
// rather than as a silent value-laundered round-trip on the
// next codec round-trip.
let mut s = three_member_spec();
let timeout = Duration::from_micros(1500);
s.politicas.timeout = Some(timeout);
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyTimeoutNotCanonical { timeout }
);
}
#[test]
fn accepts_policy_timeout_integer_millisecond_forms() {
// The codec's accepted set — integer multiples of 1ms — is
// the typed slot's accepted set: `1ms`, `500ms`, `30s`, `2m`,
// `1h` all pass the canonical gate. Pin the canonical-forms
// sweep so a future tightening of the codec's grammar (e.g.
// dropping `:ms`) surfaces here as a test failure rather
// than a silent contract narrowing on the typed slot.
for timeout in [
Duration::from_millis(1),
Duration::from_millis(500),
Duration::from_millis(1500),
Duration::from_secs(30),
Duration::from_secs(120),
Duration::from_secs(3600),
] {
let mut s = three_member_spec();
s.politicas.timeout = Some(timeout);
s.validate()
.expect("integer-millisecond :timeout must validate");
}
}
#[test]
fn policy_timeout_zero_takes_precedence_over_canonical() {
// `Duration::ZERO` carries `subsec_nanos() == 0` and would
// pass the canonical-millisecond gate; the more self-locating
// `PolicyTimeoutZero` arm (which names the omit-axis
// remediation directly) must fire first. Pin the ordering so
// a future refactor that reorders the arms surfaces here as a
// test failure rather than a silent diagnostic regression.
let mut s = three_member_spec();
s.politicas.timeout = Some(Duration::ZERO);
assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
}
#[test]
fn policy_timeout_canonical_diagnostic_carries_offending_duration() {
// The diagnostic envelope carries the offending `Duration`
// verbatim so the author can grep their `caixa.lisp` for
// `:timeout "<value>"` and fix it in one edit. Same
// diagnostic shape every other typed-slot canonical-form
// gate (`PolicyRateLimitWindowNotCanonical`) uses on the
// peer `:rate-limit :window` axis.
let mut s = three_member_spec();
let timeout = Duration::from_nanos(1_000_001);
s.politicas.timeout = Some(timeout);
match s.validate().unwrap_err() {
AplicacaoError::PolicyTimeoutNotCanonical { timeout: t } => {
assert_eq!(t, timeout, "diagnostic must carry the offending Duration");
}
other => panic!("expected PolicyTimeoutNotCanonical, got {other:?}"),
}
}
#[test]
fn rejects_policy_timeout_above_cap() {
// The fail-before-pass-after pin: 3601s = 1h + 1s is
// structurally one canonical-tick past the
// [`POLICY_TIMEOUT_MAX`] ceiling (1h = 3600s) — an
// integer-millisecond magnitude the canonical-form arm above
// accepts cleanly, that the codec round-trips losslessly as
// `"3601s"`, and that silently passed validate on every
// pre-gate codebase because the typed slot's only checks were
// the zero-floor and canonical-form arms. The mesh-level
// deadline degenerates only at the runtime substrate (Envoy
// / Cilium L7 timeout overlay) far from the source
// `caixa.lisp` with no field naming the offending policy.
let mut s = three_member_spec();
let timeout = POLICY_TIMEOUT_MAX + Duration::from_secs(1);
s.politicas.timeout = Some(timeout);
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyTimeoutExceedsCap { timeout }
);
}
#[test]
fn rejects_policy_timeout_one_millisecond_above_cap() {
// Boundary case: exactly 1ms past the cap (the granularity
// the canonical-form gate enforces). Catches a future
// "strictly less than" half-measure and pins the diagnostic
// to name the offending `Duration` verbatim. Peer of
// [`crate::limits`]'s `validate_rejects_memory_one_byte_above_wasm32_cap`
// boundary pin on the sibling `:limits :memory` top edge.
let mut s = three_member_spec();
let timeout = POLICY_TIMEOUT_MAX + Duration::from_millis(1);
s.politicas.timeout = Some(timeout);
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyTimeoutExceedsCap { timeout }
);
}
#[test]
fn rejects_policy_timeout_far_above_cap() {
// The "obvious authoring footgun" case: a `(:timeout "24h")`
// or `(:timeout "86400s")` — values the canonical-form arm
// accepts as integer-millisecond magnitudes, the codec
// round-trips losslessly through serde, but the mesh-level
// policy cannot honor (a 24-hour synchronous-`:contratos`
// deadline is operationally indistinguishable from
// omit-the-axis). Until this gate landed validate accepted
// it. Pin both common above-cap values (24h, 7d) so a future
// relaxation that drops the upper bound surfaces here.
for timeout in [
Duration::from_secs(86_400), // 24h
Duration::from_secs(604_800), // 7d
Duration::from_secs(1_000_000), // ~11.5 days
] {
let mut s = three_member_spec();
s.politicas.timeout = Some(timeout);
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyTimeoutExceedsCap { timeout }
);
}
}
#[test]
fn accepts_policy_timeout_at_cap() {
// The boundary value — exactly [`POLICY_TIMEOUT_MAX`] (1h) —
// must validate. The cap is inclusive on the top edge,
// matching the [`POLICY_RETRIES_MAX`] /
// [`POLICY_BREAKER_MAX_FAILURES_MAX`] /
// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
// sibling capped axes. Pin the boundary explicitly so a
// future off-by-one tightening (`>= POLICY_TIMEOUT_MAX`
// instead of `>`) surfaces here as a test failure rather
// than a silent contract narrowing.
let mut s = three_member_spec();
s.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
s.validate()
.expect("timeout == POLICY_TIMEOUT_MAX must validate");
}
#[test]
fn accepts_policy_timeout_typical_values() {
// The documented production-playbook band positive-control
// sweep — every value Envoy / Istio / Linkerd / AWS App Mesh
// / Kubernetes ingress-nginx recommend (1s..=60s) must pass,
// plus a sweep through the long-running-workflow band
// (5m, 15m, 30m, 1h) the cap accepts. Pin the inclusive
// validated set explicitly so a future tightening of the
// ceiling surfaces here as a deliberate test edit, not a
// silent contract narrowing.
for timeout in [
Duration::from_millis(1),
Duration::from_millis(500),
Duration::from_secs(1),
Duration::from_secs(10),
Duration::from_secs(15), // Envoy default
Duration::from_secs(30),
Duration::from_secs(60), // AWS App Mesh typical
Duration::from_secs(300),
Duration::from_secs(900),
Duration::from_secs(1800),
Duration::from_secs(3600), // exactly 1h, the cap
] {
let mut s = three_member_spec();
s.politicas.timeout = Some(timeout);
s.validate()
.unwrap_or_else(|e| panic!("timeout={timeout:?} must validate; got {e:?}"));
}
}
#[test]
fn policy_timeout_zero_takes_precedence_over_cap() {
// The cross-arm ordering pin: `Duration::ZERO` is
// structurally outside both `>= 1ms` (zero-floor) and
// `<= POLICY_TIMEOUT_MAX` (cap), but the zero-floor
// diagnostic is the more self-locating one (it directly
// names the omit-axis remediation), so the validate gate
// must fire on zero first. Same shape every other
// zero-then-shape ordering on this surface uses
// ([`AplicacaoError::PolicyRetriesZero`] then
// [`AplicacaoError::PolicyRetriesExceedsCap`];
// [`AplicacaoError::PolicyBreakerZeroFailures`] then
// [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
let mut s = three_member_spec();
s.politicas.timeout = Some(Duration::ZERO);
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyTimeoutZero,
"Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
);
}
#[test]
fn policy_timeout_canonical_takes_precedence_over_cap() {
// The cross-arm ordering pin: a `Duration` that is *both*
// sub-millisecond (non-canonical-form) and structurally
// above the cap surfaces the canonical-form diagnostic
// first, because the round-trip-shape break is the more
// fundamental issue (the value can't even round-trip
// through the codec, so the cap diagnostic naming
// `1ms..=1h` would be misleading — there's no integer-ms
// form of the offending value). Pin the order so a future
// refactor that reorders the arms surfaces here as a test
// failure rather than a silent diagnostic regression.
let mut s = three_member_spec();
// A `Duration` with `subsec_nanos() == 1` (sub-ms residue)
// *and* total magnitude above the 1h cap.
let timeout = POLICY_TIMEOUT_MAX + Duration::from_nanos(1);
s.politicas.timeout = Some(timeout);
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyTimeoutNotCanonical { timeout },
"sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
);
}
#[test]
fn policy_timeout_cap_diagnostic_carries_offending_value() {
// The diagnostic-shape pin: the offending `Duration` is
// carried verbatim into the
// [`AplicacaoError::PolicyTimeoutExceedsCap`] variant so the
// surfaced error message names the value the author wrote
// (`":politicas :timeout (Duration { secs: 7200, nanos: 0 })
// exceeds the mesh-policy ceiling …"`), not just the cap.
// Same self-locating diagnostic shape every other typed-cap
// arm on this surface carries
// ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
// offending retry count verbatim).
let mut s = three_member_spec();
let timeout = Duration::from_secs(7200); // 2h
s.politicas.timeout = Some(timeout);
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::PolicyTimeoutExceedsCap { timeout: t } if t == timeout),
"got {err:?}"
);
let msg = err.to_string();
assert!(
msg.contains("7200"),
":politicas :timeout cap diagnostic must carry the offending value verbatim (got: {msg})"
);
}
#[test]
fn policy_timeout_cap_pins_canonical_value() {
// The [`POLICY_TIMEOUT_MAX`] constant pins the value at
// exactly 1 hour (3600s = 3_600_000ms) — the largest unit
// the shared duration codec emits as a clean canonical
// string (`"<n>h"`). Pinning the literal value here surfaces
// a future drift (a relaxation to 24h, a tightening to 5m)
// as a deliberate test edit, not a silent contract
// narrowing. Same shape every other typed-cap value pin on
// this surface uses (`policy_retries_cap_is_aws_app_mesh_aligned`).
assert_eq!(POLICY_TIMEOUT_MAX, Duration::from_secs(3600));
assert_eq!(POLICY_TIMEOUT_MAX.as_millis(), 3_600_000);
}
#[test]
fn policy_timeout_cap_value_round_trips_through_codec() {
// The codec round-trip property the cap arm preserves: the
// [`POLICY_TIMEOUT_MAX`] constant itself round-trips through
// the shared duration codec — every value at the cap renders
// to a clean canonical string (`"1h"`) and parses back to
// the same `Duration`. Pin this so a future drift between
// the cap constant and the codec's largest emitted unit
// surfaces here. Same shape every other typed boundary pin
// on this surface uses
// (`wasm32_memory_cap_matches_parsed_4_gib`).
let policy = MeshPolicy {
timeout: Some(POLICY_TIMEOUT_MAX),
..Default::default()
};
let json = serde_json::to_string(&policy).unwrap();
// The codec emits `"1h"` for the canonical 1-hour magnitude.
assert!(
json.contains("\"1h\""),
"the POLICY_TIMEOUT_MAX value must render to the canonical \"1h\" form (got: {json})"
);
let back: MeshPolicy = serde_json::from_str(&json).unwrap();
assert_eq!(back.timeout, Some(POLICY_TIMEOUT_MAX));
}
#[test]
fn rejects_circuit_breaker_window_sub_millisecond() {
// Peer of the `:timeout` sub-millisecond arm on the second
// typed-`Duration` `:politicas` axis: a purely sub-ms
// `Duration` (`from_micros(500)`) renders through the shared
// codec as `"0s"`, which the codec parses back to
// `Duration::ZERO`, which the `PolicyBreakerZeroWindow`
// zero-floor gate then rejects on re-validate.
let mut s = three_member_spec();
let window = Duration::from_micros(500);
s.politicas.circuit_breaker = Some(CircuitBreaker {
max_failures: 5,
window,
});
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyBreakerWindowNotCanonical { window }
);
}
#[test]
fn rejects_circuit_breaker_window_non_integer_millisecond() {
// Peer of the `:timeout` non-integer-ms arm: a `Duration`
// with non-integer-millisecond residue renders through the
// shared codec as the truncated `"<n>ms"` form, parsing back
// to a *different* `Duration` on the next round-trip.
let mut s = three_member_spec();
let window = Duration::from_micros(1500);
s.politicas.circuit_breaker = Some(CircuitBreaker {
max_failures: 5,
window,
});
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyBreakerWindowNotCanonical { window }
);
}
#[test]
fn accepts_circuit_breaker_window_integer_millisecond_forms() {
// The canonical-forms sweep on the breaker axis: every
// integer-ms multiple the codec round-trips losslessly
// passes the canonical gate.
//
// Clears `:timeout` from the fixture so this per-axis sweep
// covers windows shorter than the fixture's 30s timeout
// (1ms, 500ms, 1500ms) — the sub-timeout arm is a
// structurally-inert breaker
// ([`AplicacaoError::PolicyBreakerWindowBelowTimeout`]) that
// the cross-axis gate at the end of
// [`AplicacaoSpec::validate_politicas`] rejects on the paired
// `(:timeout, :window)` shape, not on the per-axis
// integer-millisecond canonical-form shape this test pins.
// The paired shape is covered by
// `rejects_circuit_breaker_window_below_timeout`.
for window in [
Duration::from_millis(1),
Duration::from_millis(500),
Duration::from_millis(1500),
Duration::from_secs(30),
Duration::from_secs(60),
Duration::from_secs(3600),
] {
let mut s = three_member_spec();
s.politicas.timeout = None;
s.politicas.circuit_breaker = Some(CircuitBreaker {
max_failures: 5,
window,
});
s.validate()
.expect("integer-millisecond :circuit-breaker :window must validate");
}
}
#[test]
fn circuit_breaker_zero_window_takes_precedence_over_canonical() {
// `Duration::ZERO` would pass the canonical-ms gate (the
// sub-ns residue is zero) but must surface the narrower
// `PolicyBreakerZeroWindow` diagnostic with its omit-axis
// remediation.
let mut s = three_member_spec();
s.politicas.circuit_breaker = Some(CircuitBreaker {
max_failures: 5,
window: Duration::ZERO,
});
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyBreakerZeroWindow
);
}
#[test]
fn circuit_breaker_zero_failures_takes_precedence_over_window_canonical() {
// Both axes invalid: max_failures == 0 *and* window is
// sub-ms. The validate gate must fire on max_failures first
// (matching the existing ordering pin
// `rejects_circuit_breaker_zero_max_failures` enshrines), so
// the existing diagnostic continues to lead with the simpler
// "zero threshold" framing.
let mut s = three_member_spec();
s.politicas.circuit_breaker = Some(CircuitBreaker {
max_failures: 0,
window: Duration::from_micros(500),
});
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyBreakerZeroFailures
);
}
#[test]
fn circuit_breaker_window_canonical_diagnostic_carries_offending_duration() {
let mut s = three_member_spec();
let window = Duration::from_nanos(60_000_000_001);
s.politicas.circuit_breaker = Some(CircuitBreaker {
max_failures: 5,
window,
});
match s.validate().unwrap_err() {
AplicacaoError::PolicyBreakerWindowNotCanonical { window: w } => {
assert_eq!(w, window, "diagnostic must carry the offending Duration");
}
other => panic!("expected PolicyBreakerWindowNotCanonical, got {other:?}"),
}
}
#[test]
fn rejects_circuit_breaker_window_above_cap() {
// The fail-before-pass-after pin: 3601s = 1h + 1s is
// structurally one canonical-tick past the
// [`POLICY_BREAKER_WINDOW_MAX`] ceiling (1h = 3600s) — an
// integer-millisecond magnitude the canonical-form arm above
// accepts cleanly, that the codec round-trips losslessly as
// `"3601s"`, and that silently passed validate on every
// pre-gate codebase because the typed slot's only checks were
// the zero-floor and canonical-form arms. The
// rolling-window-to-lifetime-counter degeneration surfaces
// only at the runtime substrate (Envoy's outlier_detection
// interval, the future CiliumClusterwideEnvoyConfig overlay)
// far from the source `caixa.lisp` with no field naming the
// offending policy.
let mut s = three_member_spec();
let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
s.politicas.circuit_breaker = Some(CircuitBreaker {
max_failures: 5,
window,
});
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyBreakerWindowExceedsCap { window }
);
}
#[test]
fn rejects_circuit_breaker_window_one_millisecond_above_cap() {
// Boundary case: exactly 1ms past the cap (the granularity the
// canonical-form gate enforces). Catches a future "strictly
// less than" half-measure and pins the diagnostic to name the
// offending `Duration` verbatim. Peer of
// `rejects_policy_timeout_one_millisecond_above_cap` on the
// sibling duration-typed `:politicas :timeout` top edge.
let mut s = three_member_spec();
let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_millis(1);
s.politicas.circuit_breaker = Some(CircuitBreaker {
max_failures: 5,
window,
});
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyBreakerWindowExceedsCap { window }
);
}
#[test]
fn rejects_circuit_breaker_window_far_above_cap() {
// The "obvious authoring footgun" case: a `(:window "24h")` or
// `(:window "86400s")` — values the canonical-form arm
// accepts as integer-millisecond magnitudes, the codec
// round-trips losslessly through serde, but the
// rolling-window breaker contract cannot honor (a 24-hour
// rolling failure window is operationally a lifetime counter).
// Until this gate landed validate accepted it. Pin both common
// above-cap values (24h, 7d) so a future relaxation that
// drops the upper bound surfaces here.
for window in [
Duration::from_secs(86_400), // 24h
Duration::from_secs(604_800), // 7d
Duration::from_secs(1_000_000), // ~11.5 days
] {
let mut s = three_member_spec();
s.politicas.circuit_breaker = Some(CircuitBreaker {
max_failures: 5,
window,
});
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyBreakerWindowExceedsCap { window }
);
}
}
#[test]
fn accepts_circuit_breaker_window_at_cap() {
// The boundary value — exactly [`POLICY_BREAKER_WINDOW_MAX`]
// (1h) — must validate. The cap is inclusive on the top edge,
// matching the [`POLICY_TIMEOUT_MAX`] /
// [`POLICY_RETRIES_MAX`] / [`POLICY_BREAKER_MAX_FAILURES_MAX`]
// / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
// sibling capped axes. Pin the boundary explicitly so a
// future off-by-one tightening (`>= POLICY_BREAKER_WINDOW_MAX`
// instead of `>`) surfaces here as a test failure rather than
// a silent contract narrowing.
let mut s = three_member_spec();
s.politicas.circuit_breaker = Some(CircuitBreaker {
max_failures: 5,
window: POLICY_BREAKER_WINDOW_MAX,
});
s.validate()
.expect("window == POLICY_BREAKER_WINDOW_MAX must validate");
}
#[test]
fn accepts_circuit_breaker_window_typical_values() {
// The documented production-playbook band positive-control
// sweep — every value Hystrix / resilience4j / Istio / Envoy
// / AWS App Mesh recommend (1s..=300s) must pass, plus a sweep
// through the long-tail failure-detection band (15m, 30m, 1h)
// the cap accepts. Pin the inclusive validated set explicitly
// so a future tightening of the ceiling surfaces here as a
// deliberate test edit, not a silent contract narrowing.
//
// Clears `:timeout` from the fixture so this per-axis sweep
// covers windows shorter than the fixture's 30s timeout
// (Hystrix's 10s default, resilience4j's 30s, and the
// sub-second warm-up band) — every such value is a
// structurally-inert breaker under the cross-axis gate at the
// end of [`AplicacaoSpec::validate_politicas`]
// ([`AplicacaoError::PolicyBreakerWindowBelowTimeout`]), and
// the paired `(:timeout, :window)` shape is covered by
// `rejects_circuit_breaker_window_below_timeout`; this
// per-axis pin ranges only over the per-axis-bracket accept set.
for window in [
Duration::from_millis(1),
Duration::from_millis(500),
Duration::from_secs(1),
Duration::from_secs(10), // Hystrix / Istio / Envoy default
Duration::from_secs(30),
Duration::from_secs(60), // resilience4j typical
Duration::from_secs(300), // AWS App Mesh typical
Duration::from_secs(900),
Duration::from_secs(1800),
Duration::from_secs(3600), // exactly 1h, the cap
] {
let mut s = three_member_spec();
s.politicas.timeout = None;
s.politicas.circuit_breaker = Some(CircuitBreaker {
max_failures: 5,
window,
});
s.validate()
.unwrap_or_else(|e| panic!("window={window:?} must validate; got {e:?}"));
}
}
#[test]
fn circuit_breaker_zero_window_takes_precedence_over_cap() {
// The cross-arm ordering pin: `Duration::ZERO` is structurally
// outside both `>= 1ms` (zero-floor) and
// `<= POLICY_BREAKER_WINDOW_MAX` (cap), but the zero-floor
// diagnostic is the more self-locating one (it directly names
// the omit-axis remediation), so the validate gate must fire
// on zero first. Same shape every other zero-then-cap
// ordering on this surface uses
// ([`AplicacaoError::PolicyTimeoutZero`] then
// [`AplicacaoError::PolicyTimeoutExceedsCap`];
// [`AplicacaoError::PolicyBreakerZeroFailures`] then
// [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
let mut s = three_member_spec();
s.politicas.circuit_breaker = Some(CircuitBreaker {
max_failures: 5,
window: Duration::ZERO,
});
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyBreakerZeroWindow,
"Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
);
}
#[test]
fn circuit_breaker_window_canonical_takes_precedence_over_cap() {
// The cross-arm ordering pin: a `Duration` that is *both*
// sub-millisecond (non-canonical-form) and structurally above
// the cap surfaces the canonical-form diagnostic first,
// because the round-trip-shape break is the more fundamental
// issue (the value can't even round-trip through the codec, so
// the cap diagnostic naming `1ms..=1h` would be misleading —
// there's no integer-ms form of the offending value). Pin the
// order so a future refactor that reorders the arms surfaces
// here as a test failure rather than a silent diagnostic
// regression. Peer of
// `policy_timeout_canonical_takes_precedence_over_cap` on the
// sibling duration-typed `:politicas :timeout` axis.
let mut s = three_member_spec();
let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_nanos(1);
s.politicas.circuit_breaker = Some(CircuitBreaker {
max_failures: 5,
window,
});
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyBreakerWindowNotCanonical { window },
"sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
);
}
#[test]
fn circuit_breaker_max_failures_cap_takes_precedence_over_window_cap() {
// The cross-arm ordering pin between the two breaker axes: a
// `CircuitBreaker` whose *both* `max_failures` is above its
// cap *and* `window` is above its cap surfaces the
// max-failures cap diagnostic first, because the validate
// gate visits the failures arm before the window arm. Pin the
// order so a future refactor that reorders the breaker arms
// surfaces here.
let mut s = three_member_spec();
let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
s.politicas.circuit_breaker = Some(CircuitBreaker {
max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
window,
});
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1
},
"both-axes-above-cap must surface the max-failures cap diagnostic first (arm order)"
);
}
#[test]
fn circuit_breaker_window_cap_diagnostic_carries_offending_value() {
// The diagnostic-shape pin: the offending `Duration` is
// carried verbatim into the
// [`AplicacaoError::PolicyBreakerWindowExceedsCap`] variant so
// the surfaced error message names the value the author wrote
// (`":politicas :circuit-breaker :window (Duration { secs:
// 7200, nanos: 0 }) exceeds the mesh-policy ceiling …"`), not
// just the cap. Same self-locating diagnostic shape every
// other typed-cap arm on this surface carries
// ([`AplicacaoError::PolicyTimeoutExceedsCap`] carries the
// offending `Duration` verbatim).
let mut s = three_member_spec();
let window = Duration::from_secs(7200); // 2h
s.politicas.circuit_breaker = Some(CircuitBreaker {
max_failures: 5,
window,
});
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::PolicyBreakerWindowExceedsCap { window: w } if w == window),
"got {err:?}"
);
let msg = err.to_string();
assert!(
msg.contains("7200"),
":politicas :circuit-breaker :window cap diagnostic must carry the offending value verbatim (got: {msg})"
);
}
#[test]
fn circuit_breaker_window_cap_pins_canonical_value() {
// The [`POLICY_BREAKER_WINDOW_MAX`] constant pins the value at
// exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
// shared duration codec emits as a clean canonical string
// (`"<n>h"`) and the same value [`POLICY_TIMEOUT_MAX`] pins on
// the sibling duration-typed `:politicas :timeout` axis (the
// two duration-typed `:politicas` axes share a uniform top
// edge). Pinning the literal value here surfaces a future
// drift (a relaxation to 24h, a tightening to 5m) as a
// deliberate test edit, not a silent contract narrowing. Same
// shape every other typed-cap value pin on this surface uses
// (`policy_timeout_cap_pins_canonical_value`).
assert_eq!(POLICY_BREAKER_WINDOW_MAX, Duration::from_secs(3600));
assert_eq!(POLICY_BREAKER_WINDOW_MAX.as_millis(), 3_600_000);
assert_eq!(
POLICY_BREAKER_WINDOW_MAX, POLICY_TIMEOUT_MAX,
"the two duration-typed `:politicas` caps share the same top edge"
);
}
#[test]
fn circuit_breaker_window_cap_value_round_trips_through_codec() {
// The codec round-trip property the cap arm preserves: the
// [`POLICY_BREAKER_WINDOW_MAX`] constant itself round-trips
// through the shared duration codec — every value at the cap
// renders to a clean canonical string (`"1h"`) and parses back
// to the same `Duration`. Pin this so a future drift between
// the cap constant and the codec's largest emitted unit
// surfaces here. Same shape every other typed boundary pin on
// this surface uses
// (`policy_timeout_cap_value_round_trips_through_codec`).
let policy = MeshPolicy {
circuit_breaker: Some(CircuitBreaker {
max_failures: 5,
window: POLICY_BREAKER_WINDOW_MAX,
}),
..Default::default()
};
let json = serde_json::to_string(&policy).unwrap();
// The codec emits `"1h"` for the canonical 1-hour magnitude.
assert!(
json.contains("\"1h\""),
"the POLICY_BREAKER_WINDOW_MAX value must render to the canonical \"1h\" form (got: {json})"
);
let back: MeshPolicy = serde_json::from_str(&json).unwrap();
assert_eq!(
back.circuit_breaker.unwrap().window,
POLICY_BREAKER_WINDOW_MAX
);
}
#[test]
fn is_integer_millisecond_duration_predicate_tracks_codec() {
// Pin the predicate's accepted set against the codec's
// accepted set explicitly. The codec parses
// `<integer><unit>` for unit ∈ {`ms`,`s`,`m`,`h`} — every
// accepted value is an integer-millisecond multiple — so the
// predicate must accept exactly that set. Same shape every
// other predicate-on-the-typed-slot helper carries
// (`is_canonical_rate_limit_window_predicate_tracks_codec`).
// Read directly from the codec-owned predicate — the crate's
// single source of truth every typed-`Duration` axis now routes
// through via
// [`crate::render::require_positive_canonical_bounded_duration`].
use super::supervisor::duration_codec::is_integer_millisecond_duration;
assert!(is_integer_millisecond_duration(Duration::ZERO));
assert!(is_integer_millisecond_duration(Duration::from_millis(1)));
assert!(is_integer_millisecond_duration(Duration::from_millis(500)));
assert!(is_integer_millisecond_duration(Duration::from_millis(1500)));
assert!(is_integer_millisecond_duration(Duration::from_secs(30)));
assert!(is_integer_millisecond_duration(Duration::from_secs(3600)));
// Non-integer-millisecond residue: rejected.
assert!(!is_integer_millisecond_duration(Duration::from_micros(1)));
assert!(!is_integer_millisecond_duration(Duration::from_micros(500)));
assert!(!is_integer_millisecond_duration(Duration::from_micros(
1500
)));
assert!(!is_integer_millisecond_duration(Duration::from_nanos(1)));
assert!(!is_integer_millisecond_duration(Duration::from_nanos(
999_999
)));
// The 1-ns-past-1ms boundary: rejected (no longer a clean
// integer-millisecond multiple).
assert!(!is_integer_millisecond_duration(Duration::from_nanos(
1_000_001
)));
}
#[test]
fn policy_timeout_validated_value_round_trips_through_codec() {
// The structural property the canonical-ms gate enforces:
// every `MeshPolicy::timeout` past `AplicacaoSpec::validate`
// round-trips losslessly through the shared `duration_codec`
// (serialize → string → deserialize → equal value). Pin this
// end-to-end so a future change to either side (the validate
// gate's accepted granularity, the codec's parse/render unit
// set) that breaks the alignment surfaces here. The
// previous-state shape (typed slot accepts arbitrary
// `Duration`, codec only round-trips integer-ms) would fail
// this test for any `Duration::from_micros(1500)` timeout —
// the validate gate now forecloses that.
for timeout in [
Duration::from_millis(1),
Duration::from_millis(1500),
Duration::from_secs(30),
Duration::from_secs(3600),
] {
let mut s = three_member_spec();
s.politicas.timeout = Some(timeout);
s.validate().unwrap();
let json = serde_json::to_string(&s.politicas).unwrap();
let back: MeshPolicy = serde_json::from_str(&json).unwrap();
assert_eq!(
back.timeout, s.politicas.timeout,
"every validated :timeout must round-trip losslessly through the codec"
);
}
}
#[test]
fn circuit_breaker_window_validated_value_round_trips_through_codec() {
// Peer of the `:timeout` round-trip property on the breaker
// axis.
//
// Clears `:timeout` from the fixture so the round-trip pin
// ranges over sub-timeout `Duration` values (1ms, 1500ms) the
// cross-axis gate would otherwise reject as structurally-inert
// breakers ([`AplicacaoError::PolicyBreakerWindowBelowTimeout`]);
// the paired `(:timeout, :window)` cross-axis relation is
// pinned separately by
// `rejects_circuit_breaker_window_below_timeout`, and this
// property is a pure serde-codec round-trip on the per-axis
// slot.
for window in [
Duration::from_millis(1),
Duration::from_millis(1500),
Duration::from_secs(30),
Duration::from_secs(3600),
] {
let mut s = three_member_spec();
s.politicas.timeout = None;
s.politicas.circuit_breaker = Some(CircuitBreaker {
max_failures: 5,
window,
});
s.validate().unwrap();
let json = serde_json::to_string(&s.politicas).unwrap();
let back: MeshPolicy = serde_json::from_str(&json).unwrap();
assert_eq!(
back.circuit_breaker.unwrap().window,
window,
"every validated :circuit-breaker :window must round-trip losslessly"
);
}
}
#[test]
fn rejects_circuit_breaker_window_below_timeout() {
// The fail-before-pass-after pin on the cross-axis
// `(:timeout, :circuit-breaker :window)` invariant. Each axis
// is individually well-formed under its own per-axis bracket
// (both integer-millisecond, both above the zero floor, both
// below the cap), but the pair is a structurally-inert
// breaker: a call dispatched at t=0 is declared failed at
// t=30s, by which point the 10s rolling window open at
// dispatch has already rolled twice, so no window can hold
// a timeout-derived failure however high the call volume.
//
// Envoy's `outlier_detection.interval` against the per-route
// request timeout carries the identical relation; Hystrix
// ships the canonical ratio in its defaults (10s window
// against a 1s timeout — a 10× ratio, not a 3× under-ratio).
//
// Pin both the diagnostic arm and the payload values so a
// future re-shape of the arm surfaces here as a deliberate
// test edit.
let mut s = three_member_spec();
s.politicas.timeout = Some(Duration::from_secs(30));
s.politicas.circuit_breaker = Some(CircuitBreaker {
max_failures: 5,
window: Duration::from_secs(10),
});
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyBreakerWindowBelowTimeout {
window: Duration::from_secs(10),
timeout: Duration::from_secs(30),
}
);
}
#[test]
fn accepts_circuit_breaker_window_equal_to_timeout() {
// Boundary pin: `:window == :timeout` is the smallest window
// that structurally admits at least one full timeout-derived
// failure before the rolling interval closes (the invariant
// is `:window >= :timeout`, not strict inequality). Catches
// a future off-by-one tightening that would drift the accept
// set away from the codified [`MeshPolicy::breaker_window_
// observes_timeout`] predicate.
let mut s = three_member_spec();
s.politicas.timeout = Some(Duration::from_secs(30));
s.politicas.circuit_breaker = Some(CircuitBreaker {
max_failures: 5,
window: Duration::from_secs(30),
});
s.validate()
.expect("window == timeout is the boundary accept case");
}
#[test]
fn accepts_circuit_breaker_window_above_timeout() {
// Positive-control sweep across the production-playbook band —
// Hystrix (1s timeout / 10s window, 10× ratio), Istio (5s /
// 30s, 6×), Envoy (10s / 60s, 6×), resilience4j (30s / 300s,
// 10×), AWS App Mesh (60s / 300s, 5×). Every pair a real
// playbook recommends must validate under the cross-axis gate.
for (timeout, window) in [
(Duration::from_secs(1), Duration::from_secs(10)),
(Duration::from_secs(5), Duration::from_secs(30)),
(Duration::from_secs(10), Duration::from_secs(60)),
(Duration::from_secs(30), Duration::from_secs(300)),
(Duration::from_secs(60), Duration::from_secs(300)),
] {
let mut s = three_member_spec();
s.politicas.timeout = Some(timeout);
s.politicas.circuit_breaker = Some(CircuitBreaker {
max_failures: 5,
window,
});
s.validate().unwrap_or_else(|e| {
panic!(
"production-playbook pair timeout={timeout:?}/window={window:?} must \
validate; got {e:?}"
)
});
}
}
#[test]
fn circuit_breaker_window_below_timeout_by_one_millisecond_rejected() {
// Off-by-one boundary pin: a window exactly 1ms shy of the
// timeout is still structurally inert under the invariant
// (the dispatch-to-report lag is `timeout`, so the window
// must span at least one such lag). Catches a future
// strict-inequality relaxation that would silently drift
// the accept boundary.
let timeout = Duration::from_secs(30);
let window = Duration::from_millis(29_999);
let mut s = three_member_spec();
s.politicas.timeout = Some(timeout);
s.politicas.circuit_breaker = Some(CircuitBreaker {
max_failures: 5,
window,
});
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyBreakerWindowBelowTimeout { window, timeout }
);
}
#[test]
fn cross_axis_gate_vacuous_when_timeout_absent() {
// The predicate is vacuously `true` when `:timeout` is None —
// a `:circuit-breaker` alone declares no relation to a
// substrate-imposed deadline (the failure signal reaches the
// breaker from the transport's own error surface, so no
// dispatch-to-report lag is knowable at author time). Pin so
// a future tightening that made the gate opinionated on
// half-declared pairs surfaces here.
let mut s = three_member_spec();
s.politicas.timeout = None;
s.politicas.circuit_breaker = Some(CircuitBreaker {
max_failures: 5,
window: Duration::from_millis(1),
});
s.validate().expect(
"cross-axis gate must be vacuous when :timeout is None, however small :window is",
);
}
#[test]
fn cross_axis_gate_vacuous_when_circuit_breaker_absent() {
// Peer of the sibling `:timeout`-absent case: a `:timeout`
// without a `:circuit-breaker` declares a per-call deadline
// without any rolling-window failure accounting, so the pair
// is undeclared and the cross-axis gate has nothing to check.
let mut s = three_member_spec();
s.politicas.timeout = Some(Duration::from_secs(3600));
s.politicas.circuit_breaker = None;
s.validate().expect(
"cross-axis gate must be vacuous when :circuit-breaker is None, \
however large :timeout is",
);
}
#[test]
fn cross_axis_gate_runs_after_per_axis_brackets() {
// Ordering pin: a pair whose window is *both* zero-floor-
// violating and structurally below the timeout must surface
// the per-axis zero-floor arm first — the zero-floor
// diagnostic is more self-locating (its omit-axis remediation
// is directly named), where the cross-axis arm would send the
// author to reconcile two values one of which is not a
// meaningful window at all. Same ordering discipline every
// per-axis bracket carries internally (zero-floor before
// canonical-form before cap).
let mut s = three_member_spec();
s.politicas.timeout = Some(Duration::from_secs(30));
s.politicas.circuit_breaker = Some(CircuitBreaker {
max_failures: 5,
window: Duration::ZERO,
});
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyBreakerZeroWindow,
"per-axis zero-floor arm must fire before the cross-axis gate"
);
}
#[test]
fn breaker_window_observes_timeout_predicate_matches_gate_semantic() {
// Equivalence pin: the substrate-canonical
// [`MeshPolicy::breaker_window_observes_timeout`] predicate
// and the [`AplicacaoSpec::validate_politicas`] cross-axis
// arm must discriminate the same set on every pair covered
// by their shared invariant. A future refactor of either
// side that breaks the equivalence trips here rather than as
// a divergence between the predicate's Boolean answer and
// the validate gate's Ok/Err arm — the same
// predicate-vs-gate coherence discipline the peer
// [`PlacementStrategy::is_shard_keyed`] predicate carries
// against `AplicacaoSpec::validate_placement`. The sweep
// covers both arms of the invariant (below, equal, above)
// and both vacuous arms (None `:timeout`, None
// `:circuit-breaker`), so the equivalence holds
// exhaustively over the axis-covered accept and reject sets.
let cases: &[(Option<Duration>, Option<Duration>)] = &[
(Some(Duration::from_secs(30)), Some(Duration::from_secs(10))),
(Some(Duration::from_secs(30)), Some(Duration::from_secs(29))),
(Some(Duration::from_secs(30)), Some(Duration::from_secs(30))),
(Some(Duration::from_secs(30)), Some(Duration::from_secs(60))),
(Some(Duration::from_secs(1)), Some(Duration::from_secs(10))),
(None, Some(Duration::from_secs(1))),
(Some(Duration::from_secs(30)), None),
(None, None),
];
for (timeout, window) in cases.iter().copied() {
let politicas = MeshPolicy {
timeout,
circuit_breaker: window.map(|w| CircuitBreaker {
max_failures: 5,
window: w,
}),
..Default::default()
};
let predicate = politicas.breaker_window_observes_timeout();
let mut s = three_member_spec();
s.politicas = politicas.clone();
let gate_ok = !matches!(
s.validate(),
Err(AplicacaoError::PolicyBreakerWindowBelowTimeout { .. })
);
assert_eq!(
predicate, gate_ok,
"predicate must agree with validate arm on pair \
(timeout={timeout:?}, window={window:?})"
);
}
}
#[test]
fn rejects_rate_limit_starves_circuit_breaker() {
// The fail-before-pass-after pin on the cross-axis
// `(:rate-limit, :circuit-breaker)` invariant. Each axis is
// individually well-formed under its own per-axis bracket
// (both above the zero floor, both below the cap, rate-limit
// window canonical), but the pair is a structurally-inert
// breaker: the token bucket admits `1 × 10s / 3600s` ≈ 0
// calls per rolling breaker window, so no window can
// accumulate five failures however catastrophic the upstream
// failure rate.
//
// Envoy's `outlier_detection.consecutive_5xx` paired against
// `local_rate_limit.token_bucket.max_tokens` /
// `fill_interval` carries the identical relation; every
// production playbook that pairs the two axes (Envoy, Istio,
// AWS App Mesh, Kong) sizes the rate at or above the
// breaker's minimum-request-volume threshold for exactly this
// reason.
//
// Pin both the diagnostic arm and the payload values so a
// future re-shape of the arm surfaces here as a deliberate
// test edit. Clears `:timeout` so the sibling
// [`AplicacaoError::PolicyBreakerWindowBelowTimeout`] gate
// does not fire first on the ordering-precedent it holds
// over this arm.
let mut s = three_member_spec();
s.politicas.timeout = None;
s.politicas.circuit_breaker = Some(CircuitBreaker {
max_failures: 5,
window: Duration::from_secs(10),
});
s.politicas.rate_limit = Some(RateLimit {
rate: 1,
window: Duration::from_secs(3600),
});
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
rate: 1,
rl_window: Duration::from_secs(3600),
max_failures: 5,
cb_window: Duration::from_secs(10),
}
);
}
#[test]
fn accepts_rate_limit_can_trip_circuit_breaker() {
// Positive-control sweep across the production-playbook band
// — every pair a real playbook recommends where the rate
// clearly admits enough calls per breaker window to reach
// `:max-failures` must validate. Envoy default 5 failures
// in 10s with 100/s (1000 calls / window, 200× the threshold),
// Istio 5 in 30s with 50/s (1500 calls, 300×), Hystrix 20 in
// 10s with 1000/s (10000 calls, 500×), AWS App Mesh 5 in
// 300s with 10/s (3000 calls, 600×). Clears `:timeout` so
// the sibling cross-axis arm is vacuous on this sweep.
for (rate, rl_window, max_failures, cb_window) in [
(
100u32,
Duration::from_secs(1),
5u32,
Duration::from_secs(10),
),
(50, Duration::from_secs(1), 5, Duration::from_secs(30)),
(1000, Duration::from_secs(1), 20, Duration::from_secs(10)),
(10, Duration::from_secs(1), 5, Duration::from_secs(300)),
(5000, Duration::from_secs(60), 50, Duration::from_secs(60)),
] {
let mut s = three_member_spec();
s.politicas.timeout = None;
s.politicas.circuit_breaker = Some(CircuitBreaker {
max_failures,
window: cb_window,
});
s.politicas.rate_limit = Some(RateLimit {
rate,
window: rl_window,
});
s.validate().unwrap_or_else(|e| {
panic!(
"production-playbook pair rate={rate}/{rl_window:?} \
max_failures={max_failures}/{cb_window:?} must validate; got {e:?}"
)
});
}
}
#[test]
fn accepts_rate_limit_exactly_at_trip_threshold_per_cb_window() {
// Boundary pin: `rate × cb_window == max_failures × rl_window`
// is the smallest bucket capacity that structurally admits
// exactly `max_failures` calls per rolling breaker window
// (the invariant is `≥`, not strict inequality). Catches a
// future off-by-one tightening to strict inequality that
// would drift the accept set away from the codified
// [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicate.
// 5 calls/s over a 1s breaker window == 5 max_failures.
let mut s = three_member_spec();
s.politicas.timeout = None;
s.politicas.circuit_breaker = Some(CircuitBreaker {
max_failures: 5,
window: Duration::from_secs(1),
});
s.politicas.rate_limit = Some(RateLimit {
rate: 5,
window: Duration::from_secs(1),
});
s.validate()
.expect("rate × cb_window == max_failures × rl_window is the boundary accept case");
}
#[test]
fn rejects_rate_limit_one_call_short_per_cb_window() {
// Off-by-one boundary pin: exactly one call short of the trip
// threshold per breaker window is still structurally inert
// (the invariant is `≥`, so `<` refuses even a one-call
// shortfall). 4 calls/s over a 1s window == 4 admissible
// failures, one shy of the 5-`max_failures` threshold.
// Catches a future strict-inequality relaxation that would
// silently drift the accept boundary.
let mut s = three_member_spec();
s.politicas.timeout = None;
s.politicas.circuit_breaker = Some(CircuitBreaker {
max_failures: 5,
window: Duration::from_secs(1),
});
s.politicas.rate_limit = Some(RateLimit {
rate: 4,
window: Duration::from_secs(1),
});
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
rate: 4,
rl_window: Duration::from_secs(1),
max_failures: 5,
cb_window: Duration::from_secs(1),
}
);
}
#[test]
fn cross_axis_starve_gate_vacuous_when_rate_limit_absent() {
// The predicate is vacuously `true` when `:rate-limit` is
// None — a `:circuit-breaker` alone declares no relation to
// a substrate-imposed call rate (the failure signal reaches
// the breaker from the transport's own error surface, at
// whatever rate upstream callers push traffic). Pin so a
// future tightening that made the gate opinionated on
// half-declared pairs surfaces here.
let mut s = three_member_spec();
s.politicas.timeout = None;
s.politicas.circuit_breaker = Some(CircuitBreaker {
max_failures: 1000,
window: Duration::from_millis(1),
});
s.politicas.rate_limit = None;
s.validate().expect(
"cross-axis starve gate must be vacuous when :rate-limit is None, \
however high :max-failures and however small :window are",
);
}
#[test]
fn cross_axis_starve_gate_vacuous_when_circuit_breaker_absent() {
// Peer of the sibling `:rate-limit`-absent case: a
// `:rate-limit` without a `:circuit-breaker` declares a
// per-edge token-bucket rate without any failure counter to
// starve, so the pair is undeclared and the cross-axis gate
// has nothing to check.
//
// Also clears the fixture's `:retries` (which is `Some(3)`) so
// the sibling cross-axis
// [`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] arm
// (which reasons across the paired `(:retries, :rate-limit)`
// pair independent of `:circuit-breaker`) is vacuous on this
// pin — this test names the *starve* arm's vacuity on the
// `:circuit-breaker`-absent case, not the burst arm's.
let mut s = three_member_spec();
s.politicas.timeout = None;
s.politicas.retries = None;
s.politicas.circuit_breaker = None;
s.politicas.rate_limit = Some(RateLimit {
rate: 1,
window: Duration::from_secs(3600),
});
s.validate().expect(
"cross-axis starve gate must be vacuous when :circuit-breaker is None, \
however low :rate is",
);
}
#[test]
fn cross_axis_starve_gate_runs_after_per_axis_brackets() {
// Ordering pin: a pair whose rate is *both* zero-floor-
// violating and structurally below the trip threshold must
// surface the per-axis zero-floor arm first — the zero-floor
// diagnostic is more self-locating (its omit-axis remediation
// is directly named), where the cross-axis arm would send the
// author to reconcile four values one of which is not a
// meaningful rate at all. Same ordering discipline every
// per-axis bracket carries internally (zero-floor before
// canonical-form before cap), and the sibling cross-axis
// `PolicyBreakerZeroWindow`-before-`PolicyBreakerWindowBelowTimeout`
// ordering pins on the `(:timeout, :window)` pair.
let mut s = three_member_spec();
s.politicas.timeout = None;
s.politicas.circuit_breaker = Some(CircuitBreaker {
max_failures: 5,
window: Duration::from_secs(10),
});
s.politicas.rate_limit = Some(RateLimit {
rate: 0,
window: Duration::from_secs(1),
});
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyRateLimitZero,
"per-axis rate zero-floor arm must fire before the cross-axis starve gate"
);
}
#[test]
fn cross_axis_starve_gate_runs_after_sibling_window_below_timeout_gate() {
// Cross-axis ordering pin: a `:politicas` whose axes trip
// BOTH cross-axis arms — `:window < :timeout` (the sibling
// `PolicyBreakerWindowBelowTimeout` invariant) AND
// `:rate-limit` starves the breaker within `:window` (this
// arm) — must surface the timeout-relation diagnostic first.
// The timeout arm is the per-call-deadline invariant every
// synchronous edge carries whether or not `:rate-limit` is
// declared, so its diagnostic is more self-locating; the
// starve arm needs the reader to reason across three axes,
// where the timeout arm names only two.
//
// A `{ timeout: 30s, window: 10s, rate: 1/h, max_failures: 5 }`
// pair trips both: the window is below the timeout, and the
// rate (1 call/hour) admits far fewer than 5 calls per 10s
// breaker window.
let mut s = three_member_spec();
s.politicas.timeout = Some(Duration::from_secs(30));
s.politicas.circuit_breaker = Some(CircuitBreaker {
max_failures: 5,
window: Duration::from_secs(10),
});
s.politicas.rate_limit = Some(RateLimit {
rate: 1,
window: Duration::from_secs(3600),
});
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyBreakerWindowBelowTimeout {
window: Duration::from_secs(10),
timeout: Duration::from_secs(30),
},
"sibling :window<:timeout cross-axis arm must fire before the \
starve arm when both apply"
);
}
#[test]
fn breaker_can_trip_under_rate_limit_predicate_matches_gate_semantic() {
// Equivalence pin: the substrate-canonical
// [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicate
// and the [`AplicacaoSpec::validate_politicas`] cross-axis
// arm must discriminate the same set on every pair covered
// by their shared invariant. A future refactor of either
// side that breaks the equivalence trips here rather than as
// a divergence between the predicate's Boolean answer and
// the validate gate's Ok/Err arm — the same
// predicate-vs-gate coherence discipline the sibling
// [`MeshPolicy::breaker_window_observes_timeout`] predicate
// carries against `AplicacaoSpec::validate_politicas`. The
// sweep covers both arms of the invariant (strictly below,
// exactly at, strictly above) and both vacuous arms (None
// `:rate-limit`, None `:circuit-breaker`), so the
// equivalence holds exhaustively over the axis-covered
// accept and reject sets. Clears `:timeout` throughout so
// the sibling `:window<:timeout` gate is vacuous on every
// input.
let rl = |rate: u32, secs: u64| {
Some(RateLimit {
rate,
window: Duration::from_secs(secs),
})
};
let cb = |max_failures: u32, secs: u64| {
Some(CircuitBreaker {
max_failures,
window: Duration::from_secs(secs),
})
};
let cases: &[(Option<RateLimit>, Option<CircuitBreaker>)] = &[
// starving pairs (predicate = false, gate = Err)
(rl(1, 3600), cb(5, 10)),
(rl(4, 1), cb(5, 1)),
// boundary + coherent pairs (predicate = true, gate = Ok)
(rl(5, 1), cb(5, 1)),
(rl(100, 1), cb(5, 10)),
// vacuous arms
(None, cb(5, 10)),
(rl(1, 3600), None),
(None, None),
];
for (rate_limit, circuit_breaker) in cases.iter().copied() {
let politicas = MeshPolicy {
circuit_breaker,
rate_limit,
..Default::default()
};
let predicate = politicas.breaker_can_trip_under_rate_limit();
let mut s = three_member_spec();
s.politicas = politicas.clone();
s.politicas.timeout = None;
let gate_ok = !matches!(
s.validate(),
Err(AplicacaoError::PolicyBreakerCannotTripUnderRateLimit { .. })
);
assert_eq!(
predicate, gate_ok,
"predicate must agree with validate arm on pair \
(rate_limit={rate_limit:?}, circuit_breaker={circuit_breaker:?})"
);
}
}
#[test]
fn rejects_retries_saturate_breaker_trip_threshold() {
// The fail-before-pass-after pin on the cross-axis
// `(:retries, :circuit-breaker :max-failures)` invariant. Each
// axis is individually well-formed under its own per-axis
// bracket (both above the zero floor, both below the cap), but
// the pair is a structurally-truncated retry policy: one
// client's `retries + 1 = 4` failing attempts hit the trip
// threshold on the third attempt, the breaker opens, and the
// fourth attempt (the last declared retry) is blocked by the
// open breaker — the substrate declared four attempts and
// structurally allows three.
//
// Envoy's `retry_policy.num_retries` paired against
// `outlier_detection.consecutive_5xx` carries the identical
// relation; every production playbook that pairs the two axes
// (Envoy, Istio, resilience4j, Hystrix) sizes the breaker's
// trip threshold strictly above any single client's retry
// budget so the breaker distinguishes one persistently-failing
// client from sustained multi-client failure.
//
// Pin both the diagnostic arm and the payload values so a
// future re-shape of the arm surfaces here as a deliberate
// test edit. Clears `:timeout` and `:rate-limit` so the
// sibling cross-axis
// [`AplicacaoError::PolicyBreakerWindowBelowTimeout`] /
// [`AplicacaoError::PolicyBreakerCannotTripUnderRateLimit`]
// arms do not fire first on the ordering-precedent they hold
// over this arm.
let mut s = three_member_spec();
s.politicas.timeout = None;
s.politicas.retries = Some(3);
s.politicas.circuit_breaker = Some(CircuitBreaker {
max_failures: 3,
window: Duration::from_secs(1),
});
s.politicas.rate_limit = None;
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
retries: 3,
max_failures: 3,
}
);
}
#[test]
fn accepts_retries_below_breaker_trip_threshold() {
// Positive-control sweep across the production-playbook band
// — every pair a real playbook recommends where the breaker's
// trip threshold is strictly above the client's retry budget
// must validate. Envoy default `num_retries: 3` with
// `consecutive_5xx: 5` (breaker admits one client's 4 attempts,
// opens on multi-client failures beyond that); Istio
// `attempts: 3` with `consecutive5xxErrors: 5`; Hystrix
// `execution.isolation.thread.timeoutInMilliseconds` + 3
// retries with `requestVolumeThreshold: 20`; AWS App Mesh
// `maxRetries: 5` with a `maxEjectionPercent`-derived threshold
// of 10; resilience4j 2 retries with `slidingWindowSize: 10`.
// Clears `:timeout` and `:rate-limit` so the sibling cross-axis
// arms are vacuous on this sweep.
for (retries, max_failures) in [(1u32, 5u32), (3, 5), (3, 20), (5, 10), (2, 10), (10, 1000)]
{
let mut s = three_member_spec();
s.politicas.timeout = None;
s.politicas.retries = Some(retries);
s.politicas.circuit_breaker = Some(CircuitBreaker {
max_failures,
window: Duration::from_secs(60),
});
s.politicas.rate_limit = None;
s.validate().unwrap_or_else(|e| {
panic!(
"production-playbook pair retries={retries} \
max_failures={max_failures} must validate; got {e:?}"
)
});
}
}
#[test]
fn accepts_retries_exactly_at_boundary_below_trip_threshold() {
// Boundary pin: `max_failures == retries + 1` is the smallest
// trip threshold that admits one client's exhausted retries
// through completion (the R+1th failure — the last declared
// retry — trips the breaker exactly as it completes, so
// retries fully executed). The invariant is `>`, not `>=`,
// stated in the coherent direction `max_failures > retries`.
// Catches a future off-by-one tightening to
// `max_failures > retries + 1` that would drift the accept set
// away from the codified
// [`MeshPolicy::retries_fit_under_breaker_trip_threshold`]
// predicate.
let mut s = three_member_spec();
s.politicas.timeout = None;
s.politicas.retries = Some(3);
s.politicas.circuit_breaker = Some(CircuitBreaker {
max_failures: 4,
window: Duration::from_secs(60),
});
s.politicas.rate_limit = None;
s.validate()
.expect("max_failures == retries + 1 is the boundary accept case");
}
#[test]
fn rejects_retries_equal_to_breaker_trip_threshold() {
// Off-by-one boundary pin: exactly at the trip threshold is
// still structurally truncating (the invariant is `>`, so `<=`
// refuses even the tight boundary). `retries = 3` with
// `max_failures = 3` means the breaker trips on the third
// failure — the last declared retry attempt is blocked.
// Catches a future relaxation to `>=` that would silently
// drift the accept boundary.
let mut s = three_member_spec();
s.politicas.timeout = None;
s.politicas.retries = Some(3);
s.politicas.circuit_breaker = Some(CircuitBreaker {
max_failures: 3,
window: Duration::from_secs(60),
});
s.politicas.rate_limit = None;
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
retries: 3,
max_failures: 3,
}
);
}
#[test]
fn cross_axis_retries_gate_vacuous_when_retries_absent() {
// The predicate is vacuously `true` when `:retries` is None —
// a `:circuit-breaker` alone declares a failure counter whose
// per-client attempt count is unconstrained by the substrate,
// so no per-client saturation bound on failures-per-client-call
// is knowable at author time. The substrate takes no position
// on whether an omitted `:retries` axis means zero retries or
// "the client picks its own retry policy" — either way, the
// pair is undeclared and the cross-axis gate has nothing to
// check. Pin so a future tightening that made the gate
// opinionated on half-declared pairs surfaces here.
let mut s = three_member_spec();
s.politicas.timeout = None;
s.politicas.retries = None;
s.politicas.circuit_breaker = Some(CircuitBreaker {
max_failures: 1,
window: Duration::from_secs(60),
});
s.politicas.rate_limit = None;
s.validate().expect(
"cross-axis retries gate must be vacuous when :retries is None, \
however low :max-failures is",
);
}
#[test]
fn cross_axis_retries_gate_vacuous_when_circuit_breaker_absent() {
// Peer of the sibling `:retries`-absent case: a `:retries`
// without a `:circuit-breaker` declares a client-retry policy
// with no failure counter to trip, so the pair is undeclared
// and the cross-axis gate has nothing to check.
let mut s = three_member_spec();
s.politicas.timeout = None;
s.politicas.retries = Some(POLICY_RETRIES_MAX);
s.politicas.circuit_breaker = None;
s.politicas.rate_limit = None;
s.validate().expect(
"cross-axis retries gate must be vacuous when :circuit-breaker is None, \
however high :retries is",
);
}
#[test]
fn cross_axis_retries_gate_runs_after_per_axis_brackets() {
// Ordering pin: a pair whose retries is *both* zero-floor-
// violating and structurally at-or-below the trip threshold
// must surface the per-axis zero-floor arm first — the
// zero-floor diagnostic is more self-locating (its omit-axis
// remediation is directly named), where the cross-axis arm
// would send the author to reconcile two values one of which
// is not a meaningful retry count at all. Same ordering
// discipline every per-axis bracket carries internally
// (zero-floor before canonical-form before cap), and the
// sibling cross-axis
// `PolicyRateLimitZero`-before-`PolicyBreakerCannotTripUnderRateLimit`
// ordering pins on the `(:rate-limit, :circuit-breaker)` pair.
let mut s = three_member_spec();
s.politicas.timeout = None;
s.politicas.retries = Some(0);
s.politicas.circuit_breaker = Some(CircuitBreaker {
max_failures: 3,
window: Duration::from_secs(60),
});
s.politicas.rate_limit = None;
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyRetriesZero,
"per-axis retries zero-floor arm must fire before the cross-axis retries gate"
);
}
#[test]
fn cross_axis_retries_gate_runs_after_sibling_starve_gate() {
// Cross-axis ordering pin: a `:politicas` whose axes trip
// BOTH cross-axis arms — `:rate-limit` starves the breaker
// within `:window` (the sibling
// `PolicyBreakerCannotTripUnderRateLimit` invariant) AND
// `:retries + 1` saturates `:max-failures` (this arm) — must
// surface the rate-limit-starve diagnostic first. The
// rate-limit-starve arm reasons across the token-bucket
// admission axis every rate-limited edge carries whether or
// not `:retries` is declared, so its diagnostic is more
// self-locating; the retries-saturate arm reasons across a
// per-client retry-policy budget the starve arm does not
// touch.
//
// A `{ retries: 5, rate: 1/h, max_failures: 5, cb_window: 10s }`
// pair trips both: the rate structurally cannot deliver 5
// failures per 10s breaker window, and simultaneously
// one client's `retries + 1 = 6` attempts alone would
// saturate the 5-`max_failures` threshold.
let mut s = three_member_spec();
s.politicas.timeout = None;
s.politicas.retries = Some(5);
s.politicas.circuit_breaker = Some(CircuitBreaker {
max_failures: 5,
window: Duration::from_secs(10),
});
s.politicas.rate_limit = Some(RateLimit {
rate: 1,
window: Duration::from_secs(3600),
});
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
rate: 1,
rl_window: Duration::from_secs(3600),
max_failures: 5,
cb_window: Duration::from_secs(10),
},
"sibling :rate-limit-starve cross-axis arm must fire before the \
retries-saturate arm when both apply"
);
}
#[test]
fn retries_fit_under_breaker_trip_threshold_predicate_matches_gate_semantic() {
// Equivalence pin: the substrate-canonical
// [`MeshPolicy::retries_fit_under_breaker_trip_threshold`]
// predicate and the [`AplicacaoSpec::validate_politicas`]
// cross-axis arm must discriminate the same set on every pair
// covered by their shared invariant. A future refactor of
// either side that breaks the equivalence trips here rather
// than as a divergence between the predicate's Boolean answer
// and the validate gate's Ok/Err arm — the same
// predicate-vs-gate coherence discipline the sibling
// [`MeshPolicy::breaker_window_observes_timeout`] and
// [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicates
// carry against `AplicacaoSpec::validate_politicas`. The
// sweep covers both arms of the invariant (strictly below,
// exactly at the boundary, strictly above) and both vacuous
// arms (None `:retries`, None `:circuit-breaker`), so the
// equivalence holds exhaustively over the axis-covered accept
// and reject sets. Clears `:timeout` and `:rate-limit`
// throughout so the sibling cross-axis arms are vacuous on
// every input.
let cb = |max_failures: u32| {
Some(CircuitBreaker {
max_failures,
window: Duration::from_secs(60),
})
};
let cases: &[(Option<u32>, Option<CircuitBreaker>)] = &[
// saturating pairs (predicate = false, gate = Err)
(Some(3), cb(3)),
(Some(3), cb(1)),
(Some(10), cb(5)),
// boundary + coherent pairs (predicate = true, gate = Ok)
(Some(3), cb(4)),
(Some(1), cb(5)),
(Some(3), cb(20)),
// vacuous arms
(None, cb(1)),
(Some(10), None),
(None, None),
];
for (retries, circuit_breaker) in cases.iter().copied() {
let politicas = MeshPolicy {
retries,
circuit_breaker,
..Default::default()
};
let predicate = politicas.retries_fit_under_breaker_trip_threshold();
let mut s = three_member_spec();
s.politicas = politicas.clone();
let gate_ok = !matches!(
s.validate(),
Err(AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted { .. })
);
assert_eq!(
predicate, gate_ok,
"predicate must agree with validate arm on pair \
(retries={retries:?}, circuit_breaker={circuit_breaker:?})"
);
}
}
#[test]
fn rejects_rate_limit_cannot_admit_retry_burst() {
// The fail-before-pass-after pin on the cross-axis
// `(:retries, :rate-limit)` invariant. Each axis is
// individually well-formed under its own per-axis bracket (both
// above the zero floor, both below the cap), but the pair is a
// structurally-truncated retry policy: one client's
// `retries + 1 = 6` failing attempts consume 6 tokens from a
// bucket that admits at most 3 per refill window, so the fourth
// attempt onward is 429ed by the local rate limiter and the
// declared retry policy is silently truncated by the same rate
// limiter it feeds through — the substrate declared six
// attempts and structurally allows three.
//
// Envoy's `local_rate_limit.token_bucket.max_tokens` paired
// against `retry_policy.num_retries` carries the identical
// relation; every production playbook that pairs the two axes
// (Envoy, Istio, resilience4j, AWS App Mesh) sizes the bucket
// capacity strictly above any single client's retry budget so
// the limiter distinguishes one client's declared retries from
// sustained multi-client load.
//
// Pin both the diagnostic arm and the payload values so a
// future re-shape of the arm surfaces here as a deliberate
// test edit. Clears `:timeout` and `:circuit-breaker` so the
// sibling cross-axis
// [`AplicacaoError::PolicyBreakerWindowBelowTimeout`] /
// [`AplicacaoError::PolicyBreakerCannotTripUnderRateLimit`] /
// [`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
// arms do not fire first on the ordering-precedent they hold
// over this arm.
let mut s = three_member_spec();
s.politicas.timeout = None;
s.politicas.retries = Some(5);
s.politicas.circuit_breaker = None;
s.politicas.rate_limit = Some(RateLimit {
rate: 3,
window: Duration::from_secs(1),
});
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
retries: 5,
rate: 3,
}
);
}
#[test]
fn accepts_rate_limit_admits_retry_burst() {
// Positive-control sweep across the production-playbook band
// — every pair a real playbook recommends where the bucket
// capacity is strictly above the client's retry budget must
// validate. Envoy default `num_retries: 3` with 100/s (100
// tokens per window admits 4 attempts per client with 96 to
// spare); Istio `attempts: 3` with 50/s (50 admits 4);
// resilience4j 2 retries with 10/s (10 admits 3); AWS App
// Mesh `maxRetries: 5` with 1000/s (1000 admits 6); Cloudflare
// Enterprise 3 retries with 1_000_000/h (1M admits 4). Clears
// `:timeout` and `:circuit-breaker` so the sibling cross-axis
// arms are vacuous on this sweep.
for (retries, rate, secs) in [
(3u32, 100u32, 1u64),
(3, 50, 1),
(2, 10, 1),
(5, 1000, 1),
(3, 1_000_000, 3600),
(10, POLICY_RATE_LIMIT_MAX, 1),
] {
let mut s = three_member_spec();
s.politicas.timeout = None;
s.politicas.retries = Some(retries);
s.politicas.circuit_breaker = None;
s.politicas.rate_limit = Some(RateLimit {
rate,
window: Duration::from_secs(secs),
});
s.validate().unwrap_or_else(|e| {
panic!(
"production-playbook pair retries={retries} rate={rate}/{secs}s \
must validate; got {e:?}"
)
});
}
}
#[test]
fn accepts_rate_exactly_at_boundary_admits_retry_burst() {
// Boundary pin: `rate == retries + 1` is the smallest bucket
// capacity that structurally admits one client's exhausted
// retries through completion (each attempt draws exactly one
// token; `retries + 1` tokens available admits `retries + 1`
// attempts, retries fully executed). The invariant is `>=`,
// stated in the coherent direction `rate >= retries + 1`.
// Catches a future off-by-one tightening to `rate > retries + 1`
// that would drift the accept set away from the codified
// [`MeshPolicy::rate_limit_admits_retry_burst`] predicate.
let mut s = three_member_spec();
s.politicas.timeout = None;
s.politicas.retries = Some(3);
s.politicas.circuit_breaker = None;
s.politicas.rate_limit = Some(RateLimit {
rate: 4,
window: Duration::from_secs(1),
});
s.validate()
.expect("rate == retries + 1 is the boundary accept case");
}
#[test]
fn rejects_rate_one_below_retry_burst() {
// Off-by-one boundary pin: exactly one token short of the
// retry burst is still structurally truncating (the invariant
// is `>=`, so `<` refuses even a one-token shortfall).
// `retries = 3` with `rate = 3` means one client's four
// attempts consume four tokens from a three-token bucket —
// the fourth attempt is 429ed. Catches a future relaxation to
// `>` on the wrong side (`rate > retries`, accepting equal)
// that would silently drift the accept boundary and admit a
// structurally-truncated retry policy at the emit boundary.
let mut s = three_member_spec();
s.politicas.timeout = None;
s.politicas.retries = Some(3);
s.politicas.circuit_breaker = None;
s.politicas.rate_limit = Some(RateLimit {
rate: 3,
window: Duration::from_secs(1),
});
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
retries: 3,
rate: 3,
}
);
}
#[test]
fn cross_axis_burst_gate_vacuous_when_retries_absent() {
// The predicate is vacuously `true` when `:retries` is None —
// a `:rate-limit` alone declares a token-bucket rate whose
// per-client attempt count is unconstrained by the substrate,
// so no per-client saturation bound on tokens-per-client-call
// is knowable at author time. The substrate takes no position
// on whether an omitted `:retries` axis means zero retries or
// "the client picks its own retry policy" — either way, the
// pair is undeclared and the cross-axis gate has nothing to
// check. Pin so a future tightening that made the gate
// opinionated on half-declared pairs surfaces here.
let mut s = three_member_spec();
s.politicas.timeout = None;
s.politicas.retries = None;
s.politicas.circuit_breaker = None;
s.politicas.rate_limit = Some(RateLimit {
rate: 1,
window: Duration::from_secs(1),
});
s.validate().expect(
"cross-axis burst gate must be vacuous when :retries is None, \
however low :rate is",
);
}
#[test]
fn cross_axis_burst_gate_vacuous_when_rate_limit_absent() {
// Peer of the sibling `:retries`-absent case: a `:retries`
// without a `:rate-limit` declares a client-retry policy with
// no rate limiter to saturate, so the pair is undeclared and
// the cross-axis gate has nothing to check. Uses
// [`POLICY_RETRIES_MAX`] to pin the vacuity across the widest
// authored retry budget the per-axis cap admits — a `:retries
// POLICY_RETRIES_MAX` alone must remain a clean pass whether
// or not `:rate-limit` is declared.
let mut s = three_member_spec();
s.politicas.timeout = None;
s.politicas.retries = Some(POLICY_RETRIES_MAX);
s.politicas.circuit_breaker = None;
s.politicas.rate_limit = None;
s.validate().expect(
"cross-axis burst gate must be vacuous when :rate-limit is None, \
however high :retries is",
);
}
#[test]
fn cross_axis_burst_gate_runs_after_per_axis_brackets() {
// Ordering pin: a pair whose retries is *both* zero-floor-
// violating and structurally below the retry-burst threshold
// must surface the per-axis zero-floor arm first — the
// zero-floor diagnostic is more self-locating (its omit-axis
// remediation is directly named), where the cross-axis arm
// would send the author to reconcile two values one of which
// is not a meaningful retry count at all. Same ordering
// discipline every per-axis bracket carries internally
// (zero-floor before canonical-form before cap), and the
// sibling cross-axis
// `PolicyRetriesZero`-before-`PolicyBreakerTripsBeforeRetriesExhausted`
// ordering pin on the `(:retries, :max-failures)` pair.
let mut s = three_member_spec();
s.politicas.timeout = None;
s.politicas.retries = Some(0);
s.politicas.circuit_breaker = None;
s.politicas.rate_limit = Some(RateLimit {
rate: 1,
window: Duration::from_secs(1),
});
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyRetriesZero,
"per-axis retries zero-floor arm must fire before the cross-axis burst gate"
);
}
#[test]
fn cross_axis_burst_gate_runs_after_sibling_starve_gate() {
// Cross-axis ordering pin: a `:politicas` whose axes trip
// BOTH cross-axis arms — `:rate-limit` starves the breaker
// within `:window` (the sibling
// `PolicyBreakerCannotTripUnderRateLimit` invariant) AND
// `:retries + 1` exceeds the bucket capacity (this arm) —
// must surface the rate-limit-starve diagnostic first. The
// starve arm is the token-bucket admission invariant every
// rate-limited edge carries against the breaker whether or
// not `:retries` is declared, so its diagnostic is more
// self-locating; the burst arm reasons across a per-client
// retry-policy budget the starve arm does not touch. Same
// "more foundational cross-axis first" ordering discipline the
// sibling
// `PolicyBreakerCannotTripUnderRateLimit`-before-`PolicyBreakerTripsBeforeRetriesExhausted`
// pin on the peer pair carries.
//
// A `{ retries: 5, rate: 1/h, max_failures: 5, cb_window: 10s }`
// pair trips both: the rate structurally cannot deliver 5
// failures per 10s breaker window (starve arm), and
// simultaneously one client's `retries + 1 = 6` attempts alone
// would exhaust the 1-token bucket (burst arm).
let mut s = three_member_spec();
s.politicas.timeout = None;
s.politicas.retries = Some(5);
s.politicas.circuit_breaker = Some(CircuitBreaker {
max_failures: 5,
window: Duration::from_secs(10),
});
s.politicas.rate_limit = Some(RateLimit {
rate: 1,
window: Duration::from_secs(3600),
});
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
rate: 1,
rl_window: Duration::from_secs(3600),
max_failures: 5,
cb_window: Duration::from_secs(10),
},
"sibling :rate-limit-starve cross-axis arm must fire before the \
burst arm when both apply"
);
}
#[test]
fn cross_axis_burst_gate_runs_after_sibling_retries_saturate_gate() {
// Cross-axis ordering pin: a `:politicas` whose axes trip
// BOTH the retries-saturate arm and this burst arm — one
// client's `retries + 1` failures saturate the breaker's trip
// threshold (the sibling
// `PolicyBreakerTripsBeforeRetriesExhausted` invariant) AND
// `retries + 1` exceeds the bucket capacity (this arm) —
// must surface the retries-saturate diagnostic first. The
// saturate arm is the per-client-vs-breaker relation every
// retry-with-breaker pair carries whether or not `:rate-limit`
// is declared, so its diagnostic is more self-locating; the
// burst arm reasons across the rate-limit token-bucket
// admission axis the saturate arm does not touch. Same
// "more foundational cross-axis first" ordering discipline
// carries here.
//
// A `{ retries: 5, max_failures: 3, cb_window: 60s,
// rate: 3/s }` pair trips both: the breaker's `max_failures
// = 3` is `<= retries = 5` (saturate arm), and simultaneously
// one client's `retries + 1 = 6` attempts alone would exhaust
// the 3-token bucket (burst arm). Clears `:timeout` so the
// sibling `:window<:timeout` gate is vacuous, and the
// `(rate=3/s, max_failures=3, cb_window=60s)` triple keeps
// the starve arm coherent (`3 × 60s >= 3 × 1s`) so it is not
// the arm that fires first.
let mut s = three_member_spec();
s.politicas.timeout = None;
s.politicas.retries = Some(5);
s.politicas.circuit_breaker = Some(CircuitBreaker {
max_failures: 3,
window: Duration::from_secs(60),
});
s.politicas.rate_limit = Some(RateLimit {
rate: 3,
window: Duration::from_secs(1),
});
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
retries: 5,
max_failures: 3,
},
"sibling :retries-saturate cross-axis arm must fire before the \
burst arm when both apply"
);
}
#[test]
fn rate_limit_admits_retry_burst_predicate_matches_gate_semantic() {
// Equivalence pin: the substrate-canonical
// [`MeshPolicy::rate_limit_admits_retry_burst`] predicate and
// the [`AplicacaoSpec::validate_politicas`] cross-axis arm
// must discriminate the same set on every pair covered by
// their shared invariant. A future refactor of either side
// that breaks the equivalence trips here rather than as a
// divergence between the predicate's Boolean answer and the
// validate gate's Ok/Err arm — the same predicate-vs-gate
// coherence discipline the three sibling cross-axis
// predicates ([`MeshPolicy::breaker_window_observes_timeout`],
// [`MeshPolicy::breaker_can_trip_under_rate_limit`],
// [`MeshPolicy::retries_fit_under_breaker_trip_threshold`])
// carry against `AplicacaoSpec::validate_politicas`. The sweep
// covers both arms of the invariant (strictly below, exactly
// at the boundary, strictly above) and both vacuous arms
// (None `:retries`, None `:rate-limit`), so the equivalence
// holds exhaustively over the axis-covered accept and reject
// sets. Clears `:timeout` and `:circuit-breaker` throughout
// so the three sibling cross-axis arms are vacuous on every
// input.
let rl = |rate: u32, secs: u64| {
Some(RateLimit {
rate,
window: Duration::from_secs(secs),
})
};
let cases: &[(Option<u32>, Option<RateLimit>)] = &[
// burst-exceeding pairs (predicate = false, gate = Err)
(Some(3), rl(3, 1)),
(Some(5), rl(1, 1)),
(Some(10), rl(5, 1)),
// boundary + coherent pairs (predicate = true, gate = Ok)
(Some(3), rl(4, 1)),
(Some(1), rl(5, 1)),
(Some(3), rl(1_000_000, 3600)),
// vacuous arms
(None, rl(1, 1)),
(Some(10), None),
(None, None),
];
for (retries, rate_limit) in cases.iter().copied() {
let politicas = MeshPolicy {
retries,
rate_limit,
..Default::default()
};
let predicate = politicas.rate_limit_admits_retry_burst();
let mut s = three_member_spec();
s.politicas = politicas.clone();
let gate_ok = !matches!(
s.validate(),
Err(AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst { .. })
);
assert_eq!(
predicate, gate_ok,
"predicate must agree with validate arm on pair \
(retries={retries:?}, rate_limit={rate_limit:?})"
);
}
}
/// Sweep body shared by every `first_cross_axis_violation` ≡ gate
/// equivalence pin — assert that on each `(label, politicas,
/// expected)` case the substrate-canonical fold and the validate
/// cascade agree byte-for-byte. Extracted so each pin's own body
/// stays under `clippy::too_many_lines`.
fn assert_first_cross_axis_violation_agrees_with_gate(
cases: &[(&str, MeshPolicy, Option<AplicacaoError>)],
) {
for (label, politicas, expected) in cases {
let fold = politicas.first_cross_axis_violation();
assert_eq!(
fold.as_ref(),
expected.as_ref(),
"fold must return {expected:?} on `{label}`; got {fold:?}"
);
let mut s = three_member_spec();
s.politicas = politicas.clone();
let gate = s.validate();
match expected {
None => {
// No cross-axis violation: validate must pass (the
// per-axis brackets pass by construction on every
// fixture above; every fixture's non-`:politicas`
// slots come from `three_member_spec`).
gate.as_ref()
.unwrap_or_else(|e| panic!("`{label}` must validate cleanly; got {e:?}"));
}
Some(want) => {
let got =
gate.expect_err(&format!("`{label}` must surface a cross-axis violation"));
assert_eq!(
&got, want,
"validate cross-axis cascade must return {want:?} on `{label}`; got {got:?}"
);
}
}
}
}
#[test]
fn first_cross_axis_violation_matches_gate_on_single_arm_and_vacuous_shapes() {
// Equivalence pin on the compound cross-axis fold: the
// substrate-canonical [`MeshPolicy::first_cross_axis_violation`]
// and the [`AplicacaoSpec::validate_politicas`] cross-axis
// cascade must return identical `AplicacaoError` variants on
// every axis-covered input — the "compound-fold ≡ gate"
// contract that generalizes the four sibling per-arm pins
// onto the compound primitive that folds all four. A future
// refactor of either side that breaks the equivalence trips
// here rather than as a divergence between what the substrate
// primitive answers and what `feira build` accepts.
//
// Half-A of the sweep: every single-arm violation (one arm
// fires with the three sibling arms vacuous), the vacuous
// shape (empty policy — no arm fires), and the fully-coherent
// shape (every axis declared inside the coherence surface —
// no arm fires). Half-B (pairwise-ordering coverage — the
// "which arm wins when two apply" contract) lives in the
// sibling `first_cross_axis_violation_matches_gate_on_pairwise_orderings`
// pin; splitting keeps each pin's body under
// `clippy::too_many_lines`.
let cb = |max_failures: u32, secs: u64| CircuitBreaker {
max_failures,
window: Duration::from_secs(secs),
};
let rl = |rate: u32, secs: u64| RateLimit {
rate,
window: Duration::from_secs(secs),
};
let cases: &[(&str, MeshPolicy, Option<AplicacaoError>)] = &[
(
"window-below-timeout only",
MeshPolicy {
timeout: Some(Duration::from_secs(30)),
circuit_breaker: Some(cb(5, 10)),
..Default::default()
},
Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
window: Duration::from_secs(10),
timeout: Duration::from_secs(30),
}),
),
(
"starve only",
MeshPolicy {
rate_limit: Some(rl(1, 3600)),
circuit_breaker: Some(cb(5, 10)),
..Default::default()
},
Some(AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
rate: 1,
rl_window: Duration::from_secs(3600),
max_failures: 5,
cb_window: Duration::from_secs(10),
}),
),
(
"retries-saturate only",
MeshPolicy {
retries: Some(3),
circuit_breaker: Some(cb(3, 60)),
..Default::default()
},
Some(AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
retries: 3,
max_failures: 3,
}),
),
(
"retries-burst only",
MeshPolicy {
retries: Some(5),
rate_limit: Some(rl(3, 1)),
..Default::default()
},
Some(AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
retries: 5,
rate: 3,
}),
),
("empty policy", MeshPolicy::default(), None),
(
"fully-coherent policy",
MeshPolicy {
timeout: Some(Duration::from_secs(30)),
retries: Some(3),
circuit_breaker: Some(cb(5, 60)),
mtls_required: Some(true),
rate_limit: Some(rl(100, 1)),
},
None,
),
];
assert_first_cross_axis_violation_agrees_with_gate(cases);
}
#[test]
fn first_cross_axis_violation_matches_gate_on_pairwise_orderings() {
// Half-B of the compound-fold ≡ gate equivalence pin: the
// load-bearing pairwise-ordering coverage. Every ordered pair
// of the four cross-axis arms — six combinations — where two
// arms are simultaneously eligible must surface the
// more-foundational arm's diagnostic verbatim. Pins the fold's
// arm-ordering byte-for-byte against the validate cascade's
// arm-ordering, so a future reshuffle of either side that
// silently drifts the ordering trips here rather than as a
// per-arm miss the sibling per-arm `_predicate_matches_gate_semantic`
// pins cannot catch (they clear every sibling arm, so their
// sweeps are pairwise-ordering-agnostic by construction).
//
// The six pairs the four-arm cascade admits:
// window-before-starve, window-before-saturate,
// window-before-burst, starve-before-saturate,
// starve-before-burst, saturate-before-burst.
let cb = |max_failures: u32, secs: u64| CircuitBreaker {
max_failures,
window: Duration::from_secs(secs),
};
let rl = |rate: u32, secs: u64| RateLimit {
rate,
window: Duration::from_secs(secs),
};
let cases: &[(&str, MeshPolicy, Option<AplicacaoError>)] = &[
(
"window+starve → window wins",
MeshPolicy {
timeout: Some(Duration::from_secs(30)),
rate_limit: Some(rl(1, 3600)),
circuit_breaker: Some(cb(5, 10)),
..Default::default()
},
Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
window: Duration::from_secs(10),
timeout: Duration::from_secs(30),
}),
),
(
"window+retries-saturate → window wins",
MeshPolicy {
timeout: Some(Duration::from_secs(30)),
retries: Some(5),
circuit_breaker: Some(cb(3, 10)),
..Default::default()
},
Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
window: Duration::from_secs(10),
timeout: Duration::from_secs(30),
}),
),
(
"window+retries-burst → window wins",
MeshPolicy {
timeout: Some(Duration::from_secs(30)),
retries: Some(5),
rate_limit: Some(rl(3, 1)),
circuit_breaker: Some(cb(5, 10)),
..Default::default()
},
Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
window: Duration::from_secs(10),
timeout: Duration::from_secs(30),
}),
),
(
"starve+retries-saturate → starve wins",
MeshPolicy {
retries: Some(5),
rate_limit: Some(rl(1, 3600)),
circuit_breaker: Some(cb(5, 10)),
..Default::default()
},
Some(AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
rate: 1,
rl_window: Duration::from_secs(3600),
max_failures: 5,
cb_window: Duration::from_secs(10),
}),
),
(
"starve+retries-burst → starve wins",
MeshPolicy {
retries: Some(5),
rate_limit: Some(rl(1, 3600)),
circuit_breaker: Some(cb(10, 10)),
..Default::default()
},
Some(AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
rate: 1,
rl_window: Duration::from_secs(3600),
max_failures: 10,
cb_window: Duration::from_secs(10),
}),
),
(
"retries-saturate+retries-burst → saturate wins",
MeshPolicy {
retries: Some(5),
rate_limit: Some(rl(3, 1)),
circuit_breaker: Some(cb(3, 60)),
..Default::default()
},
Some(AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
retries: 5,
max_failures: 3,
}),
),
];
assert_first_cross_axis_violation_agrees_with_gate(cases);
}
/// Sweep body shared by every `MeshPolicy::validate` ≡ gate
/// equivalence pin — assert that on each `(label, politicas,
/// expected)` case both the substrate primitive
/// [`MeshPolicy::validate`] and the [`AplicacaoSpec::validate_politicas`]
/// cascade (reached through `AplicacaoSpec::validate`, keying off the
/// same `three_member_spec` fixture whose non-`:politicas` slots
/// always validate cleanly) return identical `AplicacaoError` variants.
/// Peer of [`assert_first_cross_axis_violation_agrees_with_gate`] on
/// the sibling cross-axis-only surface — extended here onto the
/// compound per-axis + cross-axis entry gate. Extracted so each pin's
/// own body stays under `clippy::too_many_lines`.
fn assert_validate_matches_gate(cases: &[(&str, MeshPolicy, Option<AplicacaoError>)]) {
for (label, politicas, expected) in cases {
let direct = politicas.validate();
match (expected, &direct) {
(None, Ok(())) => {}
(None, Err(got)) => {
panic!("`{label}`: MeshPolicy::validate must pass; got {got:?}")
}
(Some(want), Ok(())) => {
panic!("`{label}`: MeshPolicy::validate must return {want:?}; got Ok")
}
(Some(want), Err(got)) => assert_eq!(
got, want,
"`{label}`: MeshPolicy::validate must return {want:?}; got {got:?}"
),
}
let mut s = three_member_spec();
s.politicas = politicas.clone();
let gate = s.validate();
match (expected, &gate) {
(None, Ok(())) => {}
(None, Err(got)) => {
panic!("`{label}`: validate_politicas gate must pass; got {got:?}")
}
(Some(want), Ok(())) => {
panic!("`{label}`: validate_politicas gate must return {want:?}; got Ok")
}
(Some(want), Err(got)) => assert_eq!(
got, want,
"`{label}`: validate_politicas gate must return {want:?}; got {got:?}"
),
}
}
}
#[test]
fn validate_matches_gate_on_per_axis_and_phase_boundary_shapes() {
// Half-A of the compound-per-axis-+-cross-axis-fold ≡ gate
// equivalence pin on [`MeshPolicy::validate`]: the four per-axis
// zero-floor arms (`:timeout`, `:retries`, `:circuit-breaker
// :max-failures`, `:rate-limit` rate) that discriminate the
// "per-axis phase fires" arm of the compound gate, plus one
// per-axis-before-cross-axis case (`{ timeout: 30s, cb.window:
// ZERO }`) that pins the phase-boundary ordering — the per-axis
// `PolicyBreakerZeroWindow` arm strictly precedes the cross-axis
// `PolicyBreakerWindowBelowTimeout` arm, so the zero-window
// diagnostic wins over the window-below-timeout diagnostic. Peer
// of the sibling
// `first_cross_axis_violation_matches_gate_on_single_arm_and_vacuous_shapes`
// + `_on_pairwise_orderings` pins on the compound cross-axis
// fold, extended here onto the outer compound entry gate that
// folds per-axis + cross-axis surfaces. Half-B (cross-axis and
// clean-pass surfaces) lives in the sibling
// `validate_matches_gate_on_cross_axis_and_clean_pass_shapes`
// pin; splitting keeps each pin's body under
// `clippy::too_many_lines`.
let cases: &[(&str, MeshPolicy, Option<AplicacaoError>)] = &[
(
"per-axis: timeout zero",
MeshPolicy {
timeout: Some(Duration::ZERO),
..Default::default()
},
Some(AplicacaoError::PolicyTimeoutZero),
),
(
"per-axis: retries zero",
MeshPolicy {
retries: Some(0),
..Default::default()
},
Some(AplicacaoError::PolicyRetriesZero),
),
(
"per-axis: breaker max-failures zero",
MeshPolicy {
circuit_breaker: Some(CircuitBreaker {
max_failures: 0,
window: Duration::from_secs(60),
}),
..Default::default()
},
Some(AplicacaoError::PolicyBreakerZeroFailures),
),
(
"per-axis: rate-limit rate zero",
MeshPolicy {
rate_limit: Some(RateLimit {
rate: 0,
window: Duration::from_secs(1),
}),
..Default::default()
},
Some(AplicacaoError::PolicyRateLimitZero),
),
(
"per-axis before cross-axis: zero-window wins over window-below-timeout",
MeshPolicy {
timeout: Some(Duration::from_secs(30)),
circuit_breaker: Some(CircuitBreaker {
max_failures: 5,
window: Duration::ZERO,
}),
..Default::default()
},
Some(AplicacaoError::PolicyBreakerZeroWindow),
),
];
assert_validate_matches_gate(cases);
}
#[test]
fn validate_matches_gate_on_cross_axis_and_clean_pass_shapes() {
// Half-B of the compound-per-axis-+-cross-axis-fold ≡ gate
// equivalence pin on [`MeshPolicy::validate`]: the cross-axis
// arm that discriminates the "cross-axis phase fires" arm of
// the compound gate (window-below-timeout — sibling per-arm
// coverage lives in the two
// `first_cross_axis_violation_matches_gate_on_*` pins above),
// plus the two clean-pass shapes (empty policy — every axis
// absent — and fully-coherent — every axis inside the coherence
// surface) that pin the compound gate's `Ok(())` arm. Half-A
// (per-axis + phase-boundary surfaces) lives in the sibling
// `validate_matches_gate_on_per_axis_and_phase_boundary_shapes`
// pin; splitting keeps each pin's body under
// `clippy::too_many_lines`.
let cases: &[(&str, MeshPolicy, Option<AplicacaoError>)] = &[
(
"cross-axis: window-below-timeout",
MeshPolicy {
timeout: Some(Duration::from_secs(30)),
circuit_breaker: Some(CircuitBreaker {
max_failures: 5,
window: Duration::from_secs(10),
}),
..Default::default()
},
Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
window: Duration::from_secs(10),
timeout: Duration::from_secs(30),
}),
),
("clean pass: empty policy", MeshPolicy::default(), None),
(
"clean pass: every axis coherent",
MeshPolicy {
timeout: Some(Duration::from_secs(30)),
retries: Some(3),
circuit_breaker: Some(CircuitBreaker {
max_failures: 5,
window: Duration::from_secs(60),
}),
mtls_required: Some(true),
rate_limit: Some(RateLimit {
rate: 100,
window: Duration::from_secs(1),
}),
},
None,
),
];
assert_validate_matches_gate(cases);
}
#[test]
fn empty_politicas_validates() {
// Omitting every policy axis is fine — defaults express "no
// policy on this axis", not "policy = 0". The fixture's typical
// values continue to validate; this test pins that
// MeshPolicy::default() is a clean pass through validate().
let mut s = three_member_spec();
s.politicas = MeshPolicy::default();
s.validate().unwrap();
}
#[test]
fn typical_politicas_validates_with_every_axis_set() {
// The full §III.1 example block (timeout + retries + breaker +
// mtls + rate-limit) — every axis nonzero — must remain a
// clean pass.
let mut s = three_member_spec();
s.politicas = MeshPolicy {
timeout: Some(Duration::from_secs(30)),
retries: Some(3),
circuit_breaker: Some(CircuitBreaker {
max_failures: 5,
window: Duration::from_secs(60),
}),
mtls_required: Some(true),
rate_limit: Some(RateLimit {
rate: 100,
window: Duration::from_secs(1),
}),
};
s.validate().unwrap();
}
#[test]
fn rejects_empty_cluster_name() {
let mut s = three_member_spec();
s.placement.clusters = vec!["rio".into(), String::new()];
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PlacementClusterEmpty
);
}
#[test]
fn rejects_duplicate_cluster_names() {
let mut s = three_member_spec();
s.placement.clusters = vec!["rio".into(), "mar".into(), "rio".into()];
let err = s.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::PlacementClusterDuplicate { ref cluster } if cluster == "rio"),
"got {err:?}"
);
}
#[test]
fn rejects_placement_cluster_with_uppercase() {
// The canonical "I copied the cluster's display name verbatim"
// typo — K8s context names are lowercase per DNS-1123 label
// rule, but org docs often round-trip a TitleCase identifier
// (`Rio`, `Mar-East`) from an ADR. Mirrors the
// `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0)
// on the peer name axis.
let mut s = three_member_spec();
s.placement.clusters = vec!["Rio".into(), "mar".into()];
let err = s.validate().unwrap_err();
let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
panic!("expected PlacementClusterInvalid, got other variant");
};
assert_eq!(cluster, "Rio");
assert!(
reason.contains("uppercase"),
"diagnostic must name the violation as `uppercase` (got: {reason:?})"
);
assert!(
reason.contains("\"rio\""),
"diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
);
}
#[test]
fn rejects_placement_cluster_with_underscore() {
// The canonical "I'm thinking of an env var / hostname slug"
// leak — `_` is forbidden by every DNS-1123 / DNS-1035 label
// schema. K8s context filtering on `my_cluster` silently misses
// the cluster the author intended; the gate moves it to caixa-
// build time. Same shape as `rejects_membro_caixa_with_underscore`
// (3f9d7a0).
let mut s = three_member_spec();
s.placement.clusters = vec!["my_cluster".into()];
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
if cluster == "my_cluster" && reason.contains('_')
),
"got {err:?}"
);
}
#[test]
fn rejects_placement_cluster_with_dot() {
// A `:placement :clusters` entry is a single DNS-1123 *label*,
// not a subdomain — even though K8s context names sometimes
// carry a dotted form via kubeconfig conventions, the strictest
// floor among the use sites (DNS-1035 cluster.x-k8s.io
// `metadata.name`, Cilium identity label values) wins. The "I
// want to namespace my cluster names with `.`" intent is
// expressed via `-` (`mar-east`).
let mut s = three_member_spec();
s.placement.clusters = vec!["team.rio".into()];
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
if cluster == "team.rio" && reason.contains('.')
),
"got {err:?}"
);
}
#[test]
fn rejects_placement_cluster_with_leading_hyphen() {
// DNS-1123 / DNS-1035 boundary rule: labels must start and end
// with an alphanumeric. The K8s apiserver rejects `-rio`
// outright; the rendered fan-out would emit a `metadata.name:
// "-rio"` that fails admission far from the source caixa.lisp.
let mut s = three_member_spec();
s.placement.clusters = vec!["-rio".into()];
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
if cluster == "-rio" && reason.contains("start and end")
),
"got {err:?}"
);
}
#[test]
fn rejects_placement_cluster_with_trailing_hyphen() {
// The symmetric arm of the boundary rule. Pin separately so
// both ends are covered against a future relaxation that only
// checks one boundary (parallel to
// `rejects_membro_caixa_with_trailing_hyphen`, 3f9d7a0).
let mut s = three_member_spec();
s.placement.clusters = vec!["rio-".into()];
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
if cluster == "rio-"
),
"got {err:?}"
);
}
#[test]
fn rejects_placement_cluster_with_unicode() {
// DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
// before it reaches K8s. The byte-by-byte ASCII validity check
// rejects multi-byte UTF-8 sequences by the first byte that
// fails `[a-z0-9-]`.
let mut s = three_member_spec();
s.placement.clusters = vec!["rió".into()];
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
if cluster == "rió"
),
"got {err:?}"
);
}
#[test]
fn rejects_placement_cluster_with_whitespace() {
// Whitespace is the canonical "I pasted from a sketch / doc"
// footgun. The apiserver rejects every cluster `metadata.name`
// value carrying whitespace.
let mut s = three_member_spec();
s.placement.clusters = vec!["rio cluster".into()];
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
if cluster == "rio cluster"
),
"got {err:?}"
);
}
#[test]
fn rejects_placement_cluster_too_long() {
// 64 bytes exceeds the DNS-1123 label cap by one — the boundary
// pin. The diagnostic names both the cap (63) and the actual
// length so the author can shorten in one edit. Mirrors
// `rejects_membro_caixa_too_long` (3f9d7a0).
let mut s = three_member_spec();
let too_long = "a".repeat(64);
s.placement.clusters = vec![too_long.clone()];
let err = s.validate().unwrap_err();
let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
panic!("expected PlacementClusterInvalid");
};
assert_eq!(cluster, too_long);
assert!(
reason.contains("63") && reason.contains("64"),
"diagnostic must name the cap (63) and the actual length (64): {reason:?}"
);
}
#[test]
fn placement_cluster_max_length_validates() {
// 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
// future tightening (e.g. dropping to 62) surfaces here as a
// regression, mirroring `membro_caixa_max_length_validates`
// (3f9d7a0).
let mut s = three_member_spec();
s.placement.clusters = vec!["a".repeat(63)];
s.validate().unwrap();
}
#[test]
fn accepts_canonical_placement_cluster_forms() {
// The DNS-1123 label shapes a caixa author is realistically
// going to write for cluster names: single-word lowercase
// (`rio`), regional hyphen-joined (`mar-east`), single
// character (`a` — boundary), digit-start (`3-prod` — DNS-1123
// allows this, unlike DNS-1035), version-suffixed (`prod-v2`).
// Pin every leg so a future tightening that bans (e.g.) digit-
// start identifiers surfaces here.
for form in ["rio", "mar", "mar-east", "a", "p1", "3-prod", "prod-v2"] {
let mut s = three_member_spec();
s.placement.clusters = vec![form.into()];
s.validate().unwrap_or_else(|e| {
panic!("canonical cluster form {form:?} must validate, got {e:?}")
});
}
}
#[test]
fn placement_cluster_empty_takes_precedence_over_invalid() {
// Order pin: the existing `PlacementClusterEmpty` diagnostic
// (which doesn't try to parse) fires before the new
// `PlacementClusterInvalid` parse-side diagnostic, so an empty
// `:clusters` entry keeps its narrower error message — the new
// gate would also reject `""`, but the empty-string arm is the
// more self-locating diagnostic. Mirrors the
// `membro_caixa_empty_takes_precedence_over_invalid` pin
// (3f9d7a0).
let mut s = three_member_spec();
s.placement.clusters = vec!["rio".into(), String::new()];
let err = s.validate().unwrap_err();
assert_eq!(err, AplicacaoError::PlacementClusterEmpty);
}
#[test]
fn placement_cluster_invalid_fires_before_duplicate_check() {
// Order pin: a malformed-shape `:clusters` entry surfaces *its
// own* diagnostic, even when a later entry would otherwise
// collapse onto a duplicate name. The per-entry shape gate runs
// inline before the duplicate-key insert, parallel to
// `membro_caixa_invalid_fires_before_duplicate_check` (3f9d7a0).
let mut s = three_member_spec();
s.placement.clusters = vec!["Rio".into(), "rio".into()];
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::PlacementClusterInvalid { ref cluster, .. } if cluster == "Rio"
),
"got {err:?}"
);
}
#[test]
fn placement_cluster_invalid_diagnostic_carries_offending_cluster() {
// The diagnostic-shape pin: the error names the offending
// `:clusters` value verbatim so the author can grep their
// caixa.lisp without re-running the build, and carries a
// non-empty `reason` naming the specific violation. Same shape
// every typed-shape gate enshrines
// (3f9d7a0's `membro_caixa_invalid_diagnostic_carries_offending_caixa`,
// c7d05ec's `entrada_host_diagnostic_carries_offending_host`).
let mut s = three_member_spec();
s.placement.clusters = vec!["BAD_CLUSTER".into()];
let err = s.validate().unwrap_err();
let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
panic!("expected PlacementClusterInvalid");
};
assert_eq!(cluster, "BAD_CLUSTER");
assert!(
!reason.is_empty(),
"PlacementClusterInvalid `reason` must carry a parser-shaped wording"
);
}
#[test]
fn rejects_sharded_with_empty_clusters() {
// §III.1: Sharded uses :clusters as the shard pool. An empty
// pool means "shard across no clusters" — meaningless, same as
// Replicated with no hosts.
let mut s = three_member_spec();
s.placement.estrategia = PlacementStrategy::Sharded;
s.placement.shard_key = Some("$tenantId".into());
s.placement.clusters = vec![];
assert!(matches!(
s.validate().unwrap_err(),
AplicacaoError::PlacementWithoutClusters {
estrategia: PlacementStrategy::Sharded
}
));
}
#[test]
fn rejects_sharded_with_empty_shard_key() {
let mut s = three_member_spec();
s.placement.estrategia = PlacementStrategy::Sharded;
s.placement.shard_key = Some(String::new());
assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedKeyEmpty);
}
#[test]
fn rejects_shard_key_under_replicated_strategy() {
// The fail-before-pass-after pin: a `:placement (:estrategia
// Replicated :shard-key "tenantId")` manifest carries the
// hash-keyed-distribution slot on a strategy that never consumes
// it. Before the gate the typed slot's value silently vanished
// at the renderer layer (caixa-mesh emits `placement.shardKey`
// verbatim regardless of strategy; the Akka-style cluster-
// sharding reconciler keys off `estrategia == Sharded` and
// ignores the slot otherwise), with no diagnostic. Lifting the
// rejection to a build-time gate makes the
// `shard_key.is_some() == matches!(estrategia, Sharded)`
// partition a structural property of every validated
// [`Placement`].
let mut s = three_member_spec();
// The fixture already uses Replicated; just add a shard-key.
s.placement.shard_key = Some("$tenantId".into());
let err = s.validate().unwrap_err();
let AplicacaoError::ShardKeyOnNonSharded {
estrategia,
shard_key,
} = err
else {
panic!("expected ShardKeyOnNonSharded, got {err:?}");
};
assert_eq!(estrategia, PlacementStrategy::Replicated);
assert_eq!(shard_key, "$tenantId");
}
#[test]
fn rejects_shard_key_under_singlenode_strategy() {
// Peer of the Replicated case above on the SingleNode arm: OTP
// distributed-app takeover (one cluster runs at a time) has no
// hash-keyed routing axis to consume `:shard-key` either, so
// the rejection fires on both non-Sharded arms uniformly.
let mut s = three_member_spec();
s.placement.estrategia = PlacementStrategy::SingleNode;
s.placement.shard_key = Some("$tenantId".into());
let err = s.validate().unwrap_err();
let AplicacaoError::ShardKeyOnNonSharded {
estrategia,
shard_key,
} = err
else {
panic!("expected ShardKeyOnNonSharded, got {err:?}");
};
assert_eq!(estrategia, PlacementStrategy::SingleNode);
assert_eq!(shard_key, "$tenantId");
}
#[test]
fn rejects_empty_shard_key_under_replicated_strategy() {
// The `Some("")` case under non-Sharded is rejected by
// [`AplicacaoError::ShardKeyOnNonSharded`] (the strategy gate
// fires before the empty-value gate), not
// [`AplicacaoError::ShardedKeyEmpty`] (which is reserved for
// the `Sharded` arm). Pin the partition so a future reorder of
// the validate_placement match arms doesn't silently swap which
// diagnostic the author sees — both are author errors, but
// ShardKeyOnNonSharded names which strategy is the actual fix
// (drop the slot, or switch to Sharded), while ShardedKeyEmpty
// only says "pick a non-empty key".
let mut s = three_member_spec();
s.placement.shard_key = Some(String::new());
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::ShardKeyOnNonSharded {
estrategia: PlacementStrategy::Replicated,
ref shard_key,
} if shard_key.is_empty()
),
"got {err:?}"
);
}
#[test]
fn replicated_without_shard_key_validates() {
// The complement of the rejection: `:placement :estrategia
// Replicated` with `:shard-key None` is the canonical happy
// path on every existing fixture. Pin the no-shard-key case so
// the new gate doesn't accidentally fire on `None`.
let mut s = three_member_spec();
assert!(matches!(
s.placement.estrategia,
PlacementStrategy::Replicated
));
s.placement.shard_key = None;
s.validate().unwrap();
}
#[test]
fn singlenode_without_shard_key_validates() {
// Peer of the Replicated no-shard-key case on the SingleNode
// arm — both non-Sharded strategies must validate cleanly when
// the slot is omitted.
let mut s = three_member_spec();
s.placement.estrategia = PlacementStrategy::SingleNode;
s.placement.shard_key = None;
s.validate().unwrap();
}
#[test]
fn shard_key_on_non_sharded_ctor_matches_struct_literal_wrap() {
// Fail-before-pass-after pin on
// [`AplicacaoError::shard_key_on_non_sharded`]'s
// substrate-primitive posture: byte-identity + `Display`
// byte-string parity against the open-coded struct-literal
// for every non-`Sharded` [`PlacementStrategy`] arm across a
// representative `:shard-key` value the sole in-crate wire-up
// site (`AplicacaoSpec::validate_placement`'s
// `PlacementStrategy::Replicated | PlacementStrategy::SingleNode`
// arm) emits. Any wrapper-side silent normalization, `.into()`
// divergence, or accidental field rebrand on the ctor body
// surfaces at assert time rather than at a downstream consumer
// that reads `err.estrategia` / `err.shard_key` back and gets a
// different value than the one it stored.
for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
let placement = Placement {
estrategia,
clusters: vec!["cluster-a".to_string()],
shard_key: Some("$tenantId".to_string()),
affinity: None,
};
let via_ctor = AplicacaoError::shard_key_on_non_sharded(&placement, "$tenantId");
let via_literal = AplicacaoError::ShardKeyOnNonSharded {
estrategia,
shard_key: "$tenantId".to_string(),
};
assert_eq!(
via_ctor, via_literal,
"shard_key_on_non_sharded(&placement, k) must byte-equal the \
open-coded ShardKeyOnNonSharded struct-literal for {estrategia:?}"
);
assert_eq!(
via_ctor.to_string(),
via_literal.to_string(),
"Display byte-string must byte-equal the open-coded struct-literal \
for {estrategia:?}"
);
}
}
#[test]
fn shard_key_on_non_sharded_routes_estrategia_through_placement_accessor() {
// Boundary-sweep pin on the ctor's substrate-primitive
// projection: the `estrategia` slot is stored verbatim from
// [`Placement::estrategia`] on every arm the accessor can
// return, and the `shard_key` slot preserves the caller-side
// `&str` byte-for-byte. Sweeping every arm of
// [`PlacementStrategy::ALL`] (including the `Sharded` arm the
// current caller never reaches, since the ctor is a substrate
// primitive independent of any single caller's dispatch gate)
// catches a future silent field-rebrand or per-arm ctor
// divergence at caixa-core build time rather than at a
// downstream consumer far from the wire-up commit.
for &estrategia in PlacementStrategy::ALL {
let placement = Placement {
estrategia,
clusters: vec!["cluster-a".to_string()],
shard_key: Some("$tenantId".to_string()),
affinity: None,
};
let err = AplicacaoError::shard_key_on_non_sharded(&placement, "$tenantId");
let AplicacaoError::ShardKeyOnNonSharded {
estrategia: stored_estrategia,
shard_key: stored_shard_key,
} = err
else {
panic!(
"shard_key_on_non_sharded must construct ShardKeyOnNonSharded for {estrategia:?}"
);
};
assert_eq!(
stored_estrategia, estrategia,
"estrategia slot must round-trip verbatim through Placement::estrategia \
for {estrategia:?}"
);
assert_eq!(
stored_shard_key, "$tenantId",
"shard_key slot must preserve the caller-side &str byte-for-byte \
for {estrategia:?}"
);
}
}
#[test]
fn validate_placement_non_sharded_arm_routes_through_shard_key_on_non_sharded_ctor() {
// End-to-end pin: the sole in-crate wire-up site
// (`AplicacaoSpec::validate_placement`'s non-`Sharded`-arm
// refusal) routes through
// [`AplicacaoError::shard_key_on_non_sharded`] and the observed
// `Err` byte-equals the ctor's output on the same non-`Sharded`
// fixture. A future silent de-lift of the wire-up back to the
// open-coded struct-literal trips this test at caixa-core build
// time rather than at a downstream diagnostic consumer far from
// the wire-up commit.
for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
let mut s = three_member_spec();
s.placement.estrategia = estrategia;
s.placement.shard_key = Some("$tenantId".to_string());
let observed = s.validate().unwrap_err();
let expected = AplicacaoError::shard_key_on_non_sharded(&s.placement, "$tenantId");
assert_eq!(
observed, expected,
"validate_placement's non-Sharded-arm Err must byte-equal \
shard_key_on_non_sharded(&placement, k) for {estrategia:?}"
);
assert_eq!(
observed.to_string(),
expected.to_string(),
"Display byte-string parity for {estrategia:?}"
);
}
}
fn sharded_spec_with_key(key: &str) -> AplicacaoSpec {
// Fixture builder for the `:placement :shard-key` shape gate
// tests: a three-member Aplicacao on the `Sharded` strategy
// with the supplied `:shard-key` slot. Co-locates the
// arm-construction so every test below carries one line of
// setup (the offending `:shard-key` value) and the assertion.
let mut s = three_member_spec();
s.placement.estrategia = PlacementStrategy::Sharded;
s.placement.shard_key = Some(key.into());
s
}
#[test]
fn rejects_shard_key_with_embedded_space() {
// The canonical paste-from-aligned-doc footgun:
// `:shard-key "$tenant Id"` — the Akka-style entity-id
// extractor reads the slot as a single-token reference, and an
// embedded space breaks the token boundary at the runtime
// hash-extractor pass with no diagnostic naming the offending
// entry.
let s = sharded_spec_with_key("$tenant Id");
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
if shard_key == "$tenant Id" && reason.contains("space")
),
"got {err:?}"
);
}
#[test]
fn rejects_shard_key_with_leading_space() {
// Leading-space arm of the embedded-whitespace footgun — the
// paste-from-aligned-doc / paste-from-CSV-cell variant where
// the leading column-padding leaked into the slot.
let s = sharded_spec_with_key(" $tenantId");
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::ShardKeyInvalid { ref shard_key, .. }
if shard_key == " $tenantId"
),
"got {err:?}"
);
}
#[test]
fn rejects_shard_key_with_trailing_newline() {
// The canonical paste-from-shell-heredoc footgun — every
// `<<EOF` heredoc terminator paste leaves a trailing newline
// the YAML emitter then folds away inconsistently across
// emitter implementations.
let s = sharded_spec_with_key("$tenantId\n");
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
if shard_key == "$tenantId\n" && reason.contains("0x0a")
),
"got {err:?}"
);
}
#[test]
fn rejects_shard_key_with_embedded_tab() {
// The paste-from-aligned-doc tab-stop variant — tabs land
// alongside spaces in copy-paste from formatted columns.
let s = sharded_spec_with_key("$tenant\tId");
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
if shard_key == "$tenant\tId" && reason.contains("tab")
),
"got {err:?}"
);
}
#[test]
fn rejects_shard_key_with_control_character() {
// The paste-from-binary / paste-from-screen-cleared-terminal
// footgun — an embedded `\x01` (SOH) byte that some YAML
// emitters silently strip and others escape as ``,
// breaking round-trip across emitter implementations.
let s = sharded_spec_with_key("$tenant\u{0001}Id");
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
if shard_key == "$tenant\u{0001}Id" && reason.contains("control")
),
"got {err:?}"
);
}
#[test]
fn rejects_shard_key_with_non_ascii() {
// The canonical un-Punycode-encoded IDN / paste-from-Unicode-doc
// footgun — non-ASCII bytes normalize differently between the
// caixa-mesh-side YAML emitter and the in-cluster reconciler's
// YAML parser, the same entity ID can silently map to two
// distinct shards on a re-render.
let s = sharded_spec_with_key("$tenàntId");
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
if shard_key == "$tenàntId" && reason.contains("non-ASCII")
),
"got {err:?}"
);
}
#[test]
fn rejects_shard_key_too_long() {
// Length cap pin: 64 bytes — one byte over the
// PLACEMENT_SHARD_KEY_MAX_LEN (63) cap. The realistic shape
// here is a paste-from-doc multi-line blob landing in
// `:shard-key` instead of a single-token extractor expression.
let too_long = "a".repeat(64);
let s = sharded_spec_with_key(&too_long);
let err = s.validate().unwrap_err();
let AplicacaoError::ShardKeyInvalid {
ref shard_key,
ref reason,
} = err
else {
panic!("expected ShardKeyInvalid, got {err:?}");
};
assert_eq!(shard_key, &too_long);
assert!(
reason.contains("63") && reason.contains("64"),
"diagnostic must name the cap (63) and the actual length (64): {reason:?}"
);
}
#[test]
fn shard_key_max_length_validates() {
// Boundary pin: 63 bytes exactly — the
// `PLACEMENT_SHARD_KEY_MAX_LEN` cap. A future tightening (e.g.
// dropping to 62) surfaces here as a regression, mirroring
// `placement_cluster_max_length_validates` /
// `placement_affinity_max_length_validates` on the peer
// identifier-shaped slots.
let s = sharded_spec_with_key(&"a".repeat(63));
s.validate().unwrap();
}
#[test]
fn accepts_canonical_shard_key_forms() {
// The Akka-style entity-id extractor shapes a caixa author is
// realistically going to write — pin every leg so a future
// tightening that bans (e.g.) the `${...}` interpolation
// variant or the `metadata.<field>` JSONPath form surfaces
// here as a regression. The canonical forms span:
//
// - bare property name (`tenantId`, `customerId`)
// - Akka `ExtractEntityId` placeholder (`$tenantId`)
// - JSONPath-style nested reference (`metadata.tenantId`,
// `$.user.id`)
// - interpolation-style template (`${tenant}`)
// - snake_case property name (`customer_id`)
// - kebab-case property name (`customer-id` — accepted
// because the slot is a printable-ASCII single-token
// reference, not a DNS-1123 label like
// `:placement :affinity` / `:clusters`)
// - single character (`a`, `$` — boundary)
for form in [
"tenantId",
"customerId",
"$tenantId",
"metadata.tenantId",
"$.user.id",
"${tenant}",
"customer_id",
"customer-id",
"a",
"$",
] {
let s = sharded_spec_with_key(form);
s.validate().unwrap_or_else(|e| {
panic!("canonical shard-key form {form:?} must validate, got {e:?}")
});
}
}
#[test]
fn shard_key_empty_takes_precedence_over_invalid() {
// Order pin: the existing `ShardedKeyEmpty` diagnostic
// (reserved for the `Sharded` `Some("")` arm) fires before the
// new `ShardKeyInvalid` parse-side diagnostic, so an empty
// `:shard-key` keeps its narrower error message — the new gate
// would also reject `""` defensively, but the empty-string arm
// is the more self-locating diagnostic. Mirrors the
// `placement_cluster_empty_takes_precedence_over_invalid` pin
// on the peer identifier-shaped slot.
let s = sharded_spec_with_key("");
let err = s.validate().unwrap_err();
assert_eq!(err, AplicacaoError::ShardedKeyEmpty);
}
#[test]
fn shard_key_invalid_diagnostic_carries_offending_value() {
// The diagnostic-shape pin: the error names the offending
// `:shard-key` value verbatim so the author can grep their
// caixa.lisp without re-running the build, and carries a
// parser-shaped `reason:` naming the specific violation —
// mirrors `placement_cluster_invalid_diagnostic_carries_offending_cluster`
// on the peer identifier-shaped slot.
let s = sharded_spec_with_key("$tenant Id");
let err = s.validate().unwrap_err();
let AplicacaoError::ShardKeyInvalid {
ref shard_key,
ref reason,
} = err
else {
panic!("expected ShardKeyInvalid, got {err:?}");
};
assert_eq!(shard_key, "$tenant Id");
assert!(
!reason.is_empty(),
"reason must name the specific violation, got empty string"
);
}
#[test]
fn shard_key_shape_fires_after_non_sharded_strategy_gate() {
// Order pin: the `ShardKeyOnNonSharded` arm (which rejects
// `:shard-key` carried on non-Sharded strategies) fires before
// the shape gate, so a malformed `:shard-key` carried on (e.g.)
// a `Replicated` strategy surfaces the more self-locating
// strategy-mismatch diagnostic (naming the actual fix — drop
// the slot, or switch to Sharded) rather than the shape
// diagnostic. The strategy-mismatch arm is the more actionable
// diagnostic: a malformed shard-key on Replicated is "you
// shouldn't have a :shard-key here at all", not "your
// :shard-key value is malformed".
let mut s = three_member_spec();
// Replicated is the default fixture strategy.
s.placement.shard_key = Some("$tenant Id".into());
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::ShardKeyOnNonSharded {
estrategia: PlacementStrategy::Replicated,
..
}
),
"got {err:?}"
);
}
#[test]
fn rejects_empty_affinity_hint() {
let mut s = three_member_spec();
s.placement.affinity = Some(String::new());
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::PlacementAffinityEmpty
);
}
#[test]
fn placement_without_affinity_validates() {
// Omitting :affinity is fine — the placement engine falls back
// to the default heuristic. Pin the no-hint case so the
// affinity-empty rejection doesn't accidentally fire on `None`.
let mut s = three_member_spec();
s.placement.affinity = None;
s.validate().unwrap();
}
#[test]
fn rejects_placement_affinity_with_uppercase() {
// The canonical "I copied the ADR's display name verbatim" typo
// — placement hints land verbatim in K8s label-selector
// territory, where the apiserver enforces the DNS-1123 label
// rule (lowercase-only) on every identity-keyed admission axis.
// Mirrors `rejects_placement_cluster_with_uppercase` on the
// sibling slot.
let mut s = three_member_spec();
s.placement.affinity = Some("DataLocality".into());
let err = s.validate().unwrap_err();
let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
panic!("expected PlacementAffinityInvalid, got other variant");
};
assert_eq!(affinity, "DataLocality");
assert!(
reason.contains("uppercase"),
"diagnostic must name the violation as `uppercase` (got: {reason:?})"
);
assert!(
reason.contains("\"datalocality\""),
"diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
);
}
#[test]
fn rejects_placement_affinity_with_underscore() {
// The canonical "I'm thinking of an env var / Python identifier"
// leak — `_` is forbidden by every DNS-1123 label schema. Same
// shape as `rejects_placement_cluster_with_underscore` on the
// sibling slot.
let mut s = three_member_spec();
s.placement.affinity = Some("data_locality".into());
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
if affinity == "data_locality" && reason.contains('_')
),
"got {err:?}"
);
}
#[test]
fn rejects_placement_affinity_with_dot() {
// A `:placement :affinity` value is a single DNS-1123 *label*
// (it lands as a K8s label value selector key), not a subdomain.
// The "I want to namespace my hint with `.`" intent is expressed
// via `-` (`data-locality-east`).
let mut s = three_member_spec();
s.placement.affinity = Some("data.locality".into());
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
if affinity == "data.locality" && reason.contains('.')
),
"got {err:?}"
);
}
#[test]
fn rejects_placement_affinity_with_unicode() {
// DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
// before it reaches K8s. The byte-by-byte ASCII validity check
// rejects multi-byte UTF-8 sequences by the first byte that
// fails `[a-z0-9-]`.
let mut s = three_member_spec();
s.placement.affinity = Some("data-localité".into());
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
if affinity == "data-localité"
),
"got {err:?}"
);
}
#[test]
fn rejects_placement_affinity_with_leading_hyphen() {
// DNS-1123 boundary rule: labels must start with an
// alphanumeric. Pin separately from the trailing-hyphen arm so
// a future relaxation that only checks one boundary surfaces
// here as a regression (parallel to
// `rejects_placement_cluster_with_leading_hyphen`).
let mut s = three_member_spec();
s.placement.affinity = Some("-data-locality".into());
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
if affinity == "-data-locality" && reason.contains("start and end")
),
"got {err:?}"
);
}
#[test]
fn rejects_placement_affinity_with_trailing_hyphen() {
// Symmetric arm of the DNS-1123 boundary rule. Pinned so both
// ends are covered against a future relaxation.
let mut s = three_member_spec();
s.placement.affinity = Some("data-locality-".into());
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
if affinity == "data-locality-"
),
"got {err:?}"
);
}
#[test]
fn rejects_placement_affinity_with_whitespace() {
// Whitespace is the canonical "I pasted from a sketch / doc"
// footgun. The apiserver rejects every label-selector value
// carrying whitespace.
let mut s = three_member_spec();
s.placement.affinity = Some("data locality".into());
let err = s.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
if affinity == "data locality"
),
"got {err:?}"
);
}
#[test]
fn rejects_placement_affinity_too_long() {
// 64 bytes exceeds the DNS-1123 label cap by one — the boundary
// pin. The diagnostic names both the cap (63) and the actual
// length so the author can shorten in one edit. Mirrors
// `rejects_placement_cluster_too_long`.
let mut s = three_member_spec();
let too_long = "a".repeat(64);
s.placement.affinity = Some(too_long.clone());
let err = s.validate().unwrap_err();
let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
panic!("expected PlacementAffinityInvalid");
};
assert_eq!(affinity, too_long);
assert!(
reason.contains("63") && reason.contains("64"),
"diagnostic must name the cap (63) and the actual length (64): {reason:?}"
);
}
#[test]
fn placement_affinity_max_length_validates() {
// 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
// future tightening (e.g. dropping to 62) surfaces here as a
// regression, mirroring `placement_cluster_max_length_validates`.
let mut s = three_member_spec();
s.placement.affinity = Some("a".repeat(63));
s.validate().unwrap();
}
#[test]
fn accepts_canonical_placement_affinity_forms() {
// The DNS-1123 label shapes a caixa author is realistically
// going to write for placement hints: the M3 canonical examples
// (`data-locality`, `low-latency`, `anti-affinity`), the
// single-token form (`affinity`), the single-character boundary
// (`a`), the digit-start (DNS-1123 allows this, unlike
// DNS-1035), and a regional-suffixed form. Pin every leg so a
// future tightening that bans (e.g.) digit-start identifiers
// surfaces here.
for form in [
"data-locality",
"low-latency",
"anti-affinity",
"affinity",
"a",
"3-tier",
"locality-east",
] {
let mut s = three_member_spec();
s.placement.affinity = Some(form.into());
s.validate().unwrap_or_else(|e| {
panic!("canonical affinity form {form:?} must validate, got {e:?}")
});
}
}
#[test]
fn placement_affinity_empty_takes_precedence_over_invalid() {
// Order pin: the existing `PlacementAffinityEmpty` diagnostic
// (which doesn't try to parse) fires before the new
// `PlacementAffinityInvalid` parse-side diagnostic, so an empty
// `:affinity` keeps its narrower error message — the new gate
// would also reject `""`, but the empty-string arm is the more
// self-locating diagnostic. Mirrors the
// `placement_cluster_empty_takes_precedence_over_invalid` pin.
let mut s = three_member_spec();
s.placement.affinity = Some(String::new());
let err = s.validate().unwrap_err();
assert_eq!(err, AplicacaoError::PlacementAffinityEmpty);
}
#[test]
fn placement_affinity_invalid_diagnostic_carries_offending_value() {
// The diagnostic shape pin: every rejection carries the offending
// `affinity:` verbatim plus a parser-shaped `reason:` so the
// author can grep their caixa.lisp for `:affinity "<hint>"` and
// fix it in one edit. Mirrors the
// `placement_cluster_invalid_diagnostic_carries_offending_cluster`
// pin on the sibling slot.
let mut s = three_member_spec();
s.placement.affinity = Some("Data_Locality".into());
let err = s.validate().unwrap_err();
let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
panic!("expected PlacementAffinityInvalid");
};
assert_eq!(affinity, "Data_Locality");
assert!(
!reason.is_empty(),
"diagnostic reason must not be empty (got: {reason:?})"
);
}
#[test]
fn singlenode_with_takeover_candidates_validates() {
// OTP distributed-application convention (MESH-COMPOSITION
// §II.1): SingleNode runs on one cluster at a time but the
// :clusters list enumerates the takeover candidates. Multiple
// entries are not a contradiction — they are the failover pool.
let mut s = three_member_spec();
s.placement.estrategia = PlacementStrategy::SingleNode;
s.placement.clusters = vec!["rio".into(), "mar".into(), "plo".into()];
s.validate().unwrap();
}
// ── MeshPolicy::is_empty() — typed emptiness predicate ────────────────
#[test]
fn mesh_policy_default_is_empty() {
// The Default impl carries None on every axis — the typed
// analog of an unset `:politicas (())` slot. Renderers that
// overlay the policy onto a cluster artifact key off this
// predicate to skip the slot entirely; pinning so a future
// axis added to MeshPolicy can't silently break the contract
// (a new field whose Default is non-None would flip is_empty
// to false on every existing caixa, surfacing here).
assert!(MeshPolicy::default().is_empty());
}
#[test]
fn mesh_policy_with_only_timeout_is_not_empty() {
let p = MeshPolicy {
timeout: Some(Duration::from_secs(30)),
..Default::default()
};
assert!(!p.is_empty());
}
#[test]
fn mesh_policy_with_only_retries_is_not_empty() {
let p = MeshPolicy {
retries: Some(3),
..Default::default()
};
assert!(!p.is_empty());
}
#[test]
fn mesh_policy_with_only_circuit_breaker_is_not_empty() {
let p = MeshPolicy {
circuit_breaker: Some(CircuitBreaker {
max_failures: 5,
window: Duration::from_secs(60),
}),
..Default::default()
};
assert!(!p.is_empty());
}
#[test]
fn mesh_policy_with_only_mtls_required_is_not_empty() {
// Even `mtls_required: Some(false)` (an explicit opt-out) is
// not empty — the author *named* the axis, the renderer needs
// to honor that vs. fall back to the cluster default.
let p = MeshPolicy {
mtls_required: Some(false),
..Default::default()
};
assert!(!p.is_empty());
}
#[test]
fn mesh_policy_with_only_rate_limit_is_not_empty() {
let p = MeshPolicy {
rate_limit: Some(RateLimit {
rate: 100,
window: Duration::from_secs(1),
}),
..Default::default()
};
assert!(!p.is_empty());
}
#[test]
fn mesh_policy_is_empty_round_trips_through_three_member_fixture() {
// The three-member happy-path fixture sets timeout + retries +
// mtls_required — every populated axis must read non-empty.
// Pin the round-trip so the M3.x per-:politicas emitter (the
// M3.x roadmap CiliumClusterwideEnvoyConfig artifact) can rely
// on is_empty() to decide whether to emit at all without
// re-deriving the contract from inline field probes.
assert!(!three_member_spec().politicas.is_empty());
}
#[test]
fn mesh_policy_empty_is_the_all_none_arm_and_is_empty() {
// Fail-before-pass-after round-trip pin on the paired
// ([`MeshPolicy::empty`], [`MeshPolicy::is_empty`]) constructor /
// predicate on the [`MeshPolicy`] typed slot: the lifted
// constructor must materialize a value whose every one of the
// five `Option<_>`-carrying per-axis fields is `None`, so the
// paired [`MeshPolicy::is_empty`] predicate returns `true` on
// the constructor's output by construction. A future silent
// regression that omits a `None` arm from the constructor's
// struct-literal (a sixth axis added to the type whose
// constructor arm is forgotten, an accidental `Some(0)` on the
// `retries` arm that would silently violate the
// [`AplicacaoError::PolicyRetriesZero`] admission floor) trips
// here at caixa-core test time rather than surfacing as a
// downstream consumer's per-`:politicas` overlay-emit path
// reading a `MeshPolicy::empty()` output that fails the
// emptiness predicate and lands an unexpected `spec.policies.
// <axis>` field in the emitted Cilium/Envoy overlay. Peer of
// the sibling
// [`crate::limits::tests::limits_spec_empty_is_the_all_none_arm_and_is_empty`]
// pin on the M2 `:limits` typed slot — extends the same
// "the canonical unset baseline satisfies the paired
// emptiness predicate" round-trip discipline onto the M3
// `:politicas` slot.
let empty = MeshPolicy::empty();
assert!(
empty.is_empty(),
"MeshPolicy::empty() must return a value whose is_empty() \
predicate is true — got {empty:?}",
);
assert_eq!(empty.timeout(), None);
assert_eq!(empty.retries(), None);
assert_eq!(empty.circuit_breaker(), None);
assert_eq!(empty.mtls_required(), None);
assert_eq!(empty.rate_limit(), None);
}
#[test]
fn mesh_policy_empty_byte_equals_default() {
// Fail-before-pass-after byte-parity pin on the two-path
// convergence: the lifted `pub const fn` [`MeshPolicy::empty`]
// constructor must byte-equal the derived (non-`const`)
// [`Default::default`] on every one of the five
// `Option<_>`-carrying per-axis fields under `PartialEq`. The
// two paths are semantically identical (both name the
// "canonical unset [`MeshPolicy`]" shape) but structurally
// distinct (the derived [`Default::default`] threads through
// the derive-generated per-field `<Option<_> as Default>::default`
// cascade, resolving to `None` on each; the lifted
// constructor's struct-literal names each `None` arm
// verbatim). A future regression on either path — an
// accidental `Some(0)` on the constructor's `retries` arm
// that would silently drift the constructor's output from the
// derived default (surfacing here as the pin's first-arm
// inequality), a future substrate-wide field-default rebrand
// that lands on the derived path's per-field
// `<Option<_> as Default>::default` but forgets to extend the
// constructor's struct-literal (surfacing here as the pin's
// per-arm inequality on the newly rebranded axis) — trips
// here at caixa-core test time. The `const` binding on the
// LHS forces the lifted constructor through the `const`-eval
// surface at compile time, so any future accidental downgrade
// to `pub fn` fires E0015 at the binding rather than at a
// downstream `const`-context consumer's dispatch site. Peer
// of the sibling
// [`crate::limits::tests::limits_spec_empty_byte_equals_default`]
// pin on the M2 `:limits` typed slot.
const EMPTY: MeshPolicy = MeshPolicy::empty();
assert_eq!(
EMPTY,
MeshPolicy::default(),
"MeshPolicy::empty() must byte-equal MeshPolicy::default() on \
every per-axis field — the two paths name the same canonical \
unset baseline; a mismatch means one path drifted from the \
other on some per-axis default",
);
}
#[test]
fn mesh_policy_empty_ctor_is_const_fn() {
// Const-eval-surface pin on the lifted [`MeshPolicy::empty`]
// constructor: the constructor must remain `pub const fn` so
// downstream consumers can materialize a canonical unset
// baseline in `const` context (a `const EMPTY: MeshPolicy =
// MeshPolicy::empty();` module-scope binding for a
// fixture-builder table, a `const`-context per-arm predicate
// that folds emptiness over the constructor's output at
// compile time, a compile-time lookup table the LSP hover
// renderer materializes per typed-slot fixture). A future
// accidental downgrade to non-`const` (an added runtime
// helper reachable only from a non-`const` context in the
// body, a manual hand-rolled `impl` that shadows this method)
// trips at caixa-core build time — E0015 at the `const EMPTY`
// binding below — rather than surfacing as a downstream
// `const`-context regression far from the constructor's
// declaration. The paired [`Self::is_empty`] predicate call
// inside the `const { assert!(..) }` block enforces both
// halves of the round-trip (constructor is `const`-callable
// AND its output satisfies the paired emptiness predicate at
// `const`-eval time) at caixa-core compile time. Peer of the
// sibling
// [`crate::limits::tests::limits_spec_empty_ctor_is_const_fn`]
// pin on the M2 `:limits` typed slot.
const EMPTY: MeshPolicy = MeshPolicy::empty();
const {
assert!(EMPTY.is_empty());
}
}
#[test]
fn mesh_policy_default_routes_through_empty_ctor() {
// Fail-before-pass-after byte-parity pin on the two-path
// convergence discipline lifted onto the [`Default`] impl:
// pre-fold the derive-generated [`Default::default`] and the
// `pub const fn` [`MeshPolicy::empty`] constructor were
// byte-equal by *coincidence* (each hand-authored or derive-
// authored `None` per axis, pinned load-bearing by the
// pre-existing [`mesh_policy_empty_byte_equals_default`]
// sibling pin), while the folded impl now routes
// [`Default::default`] through the substrate-canonical
// [`Self::empty`] constructor — the two paths are byte-equal
// by *construction*, one delegates to the other. This pin
// sharpens the pre-existing byte-parity invariant into a
// structural-delegation invariant: any future silent regression
// that re-derives [`Default`] on the type (a `#[derive(Default)]`
// re-addition that shadows the manual impl, a swap of the
// manual impl's body onto a divergent struct-literal that
// diverges from [`Self::empty`]'s output on a new field's
// non-`None` canonical baseline) trips here at caixa-core test
// time under `PartialEq` rather than at a downstream consumer
// of the derived-until-now [`Default::default`] surface (the
// five per-axis-only `..Default::default()` fixtures at
// [`mesh_policy_with_only_timeout_is_not_empty`] /
// [`mesh_policy_with_only_retries_is_not_empty`] /
// [`mesh_policy_with_only_circuit_breaker_is_not_empty`] /
// [`mesh_policy_with_only_mtls_required_is_not_empty`] /
// [`mesh_policy_with_only_rate_limit_is_not_empty`], the
// `MeshPolicy::default().is_empty()` round-trip at
// [`mesh_policy_default_is_empty`], every future consumer of
// a hypothetical `..MeshPolicy::default()` overlay-elision
// arm). Peer of the sibling
// [`crate::limits::tests::limits_spec_default_routes_through_empty_ctor`]
// pin on the M2 `:limits` typed slot (abd52c2).
assert_eq!(
MeshPolicy::default(),
MeshPolicy::empty(),
"MeshPolicy::default() must delegate through MeshPolicy::empty() \
on every per-axis field — a mismatch means the manual Default \
impl drifted off the substrate-canonical empty() constructor \
(or the constructor drifted off the impl's expected shape)",
);
}
#[test]
fn mesh_policy_empty_validates_ok() {
// Fail-before-pass-after invariant pin on the empty-baseline
// validate composition: the canonical unset [`MeshPolicy`]
// (every one of the five `Option<_>`-carrying per-axis fields
// set to `None`) must pass every gate on
// [`MeshPolicy::validate`]. The invariant is structurally
// guaranteed today — every per-axis value-shape gate on the
// validate dispatch is `if let Some(_) = self.<axis>()` guarded
// and every cross-axis arm on
// [`MeshPolicy::first_cross_axis_violation`] is a
// `let (Some(_), Some(_))` pattern, so an all-`None` input
// short-circuits every arm before any zero-floor / canonical-
// form / cap / pairwise-ordering check fires. Pinning the
// composition here makes the invariant load-bearing so a
// future extension of the validate surface that adds a
// non-`Option`-guarded gate (a hypothetical cross-slot
// coherence gate a future per-axis / per-slot fold on the M3
// `:politicas` slot establishes on top of the current
// pairwise-cross-axis composition per
// `theory/MESH-COMPOSITION.md` §III.2, a per-arm
// `mtls_required`-defaults-to-`true` admission overlay a
// future admission webhook lands) that fires on the all-`None`
// input trips here at caixa-core test time rather than at a
// downstream consumer that composed [`MeshPolicy::default`]
// (which now routes through [`MeshPolicy::empty`]) with
// [`MeshPolicy::validate`] as its "no-op axis short-circuit"
// and observed a spurious rejection on the canonical unset
// baseline. Peer of the sibling
// [`crate::limits::tests::limits_spec_empty_validates_ok`] pin
// on the M2 `:limits` typed slot (abd52c2) — that one anchors
// the invariant on the folded [`Default`] impl the
// [`crate::LimitsSpec::empty`] constructor now backs; this one
// extends it onto the M3 `:politicas` slot's folded impl.
MeshPolicy::empty().validate().expect(
"MeshPolicy::empty() must satisfy MeshPolicy::validate — \
every per-axis value-shape gate is `if let Some(_)` guarded \
and every cross-axis arm is a `let (Some(_), Some(_))` pattern, \
so an all-`None` input short-circuits every arm; a spurious \
rejection on the canonical unset baseline means a future \
validate-side extension added a non-`Option`-guarded gate that \
fires on empty input",
);
}
// ── shared duration codec: cross-slot integer-magnitude gate ──
//
// The integer-magnitude discipline applied to
// `supervisor::duration_codec::parse` lifts onto every typed slot
// that routes through the shared codec — `MeshPolicy::timeout`
// (`:politicas :timeout`) and `CircuitBreaker::window`
// (`:politicas :circuit-breaker :window`) on the Aplicacao side.
// These cross-slot tests pin that the gate fires at the serde
// layer for both typed slots, not just for the supervisor side.
#[test]
fn policy_timeout_serde_rejects_fractional_seconds() {
// `MeshPolicy::timeout` uses `with = "supervisor::duration_codec"`,
// so the shared codec's integer-magnitude gate applies on
// deserialize. `"1.5s"` previously parsed to 1500ms and round-
// tripped to `"1500ms"` on next emit — DRIFT. Now refused at
// deserialize with the canonical-form diagnostic naming the
// offending `"1.5"` and the remediation `"1500ms"`.
let payload = r#"{"timeout":"1.5s"}"#;
let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
let msg = err.to_string();
assert!(
msg.contains("not a non-negative integer"),
"expected integer-magnitude diagnostic in {msg:?}"
);
assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
assert!(
msg.contains("\"1500ms\""),
"missing canonical-form remediation in {msg:?}"
);
}
#[test]
fn policy_timeout_serde_rejects_leading_plus_sign() {
// Pin the leading-`+` arm cross-slot — the prior f64 parser
// accepted `"+30s"` silently and round-tripped to `"30s"`.
let payload = r#"{"timeout":"+30s"}"#;
let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
let msg = err.to_string();
assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
}
#[test]
fn circuit_breaker_window_serde_rejects_fractional_minutes() {
// `CircuitBreaker::window` uses `with =
// "supervisor::duration_codec_required"` (the required-Duration
// variant that delegates to the same shared parser). `"0.5m"`
// parsed to 30s and round-tripped to `"30s"` on next emit —
// DRIFT closed.
let payload = format!(
r#"{{"{max_failures}":5,"{window}":"0.5m"}}"#,
max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
);
let err = serde_json::from_str::<CircuitBreaker>(&payload).unwrap_err();
let msg = err.to_string();
assert!(
msg.contains("not a non-negative integer"),
"expected integer-magnitude diagnostic in {msg:?}"
);
assert!(msg.contains("\"0.5\""), "missing magnitude in {msg:?}");
assert!(
msg.contains("\"30s\""),
"missing canonical-form remediation in {msg:?}"
);
}
#[test]
fn circuit_breaker_window_serde_accepts_integer_canonical_form() {
// Pin the happy-path on the cross-slot side: every canonical
// author shape `render` ever emits parses cleanly through the
// shared codec on the `CircuitBreaker` slot. The
// codec's accepted set (post-gate) is exactly its emitted set
// for the integer-magnitude class.
for window_lit in ["30s", "500ms", "2m", "1h"] {
let payload = format!(
r#"{{"{max_failures}":5,"{window}":"{window_lit}"}}"#,
max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
);
let cb: CircuitBreaker = serde_json::from_str(&payload).unwrap_or_else(|e| {
panic!("expected {window_lit:?} to parse cleanly through shared codec: {e}")
});
assert_eq!(cb.max_failures, 5);
}
}
// ── rate_limit_codec: integer-magnitude gate ──
//
// The integer-magnitude discipline the 1c55a2a / 818dd38 / d1fd67b
// / 737a676 / d53c922 trajectory landed on every typed-duration /
// typed-byte-size codec in caixa-core lifts onto the fifth typed
// codec — `rate_limit_codec` — through the digit-only magnitude
// gate on the `<rate>` half of the `<rate>/<unit>` author surface.
// These tests pin the gate at the serde layer for `:politicas
// :rate-limit` (the only typed slot the codec backs), and at the
// codec-internal `parse` layer for the canonical positive cases.
#[test]
fn rate_limit_serde_rejects_fractional_rate() {
// `"1.5/s"` previously hit `u32::from_str`'s rejection arm with
// the value-laundered `"rate-limit rate \"1.5\" not a u32"`
// wording, which didn't name the canonical-form remediation or
// the round-trip drift the next emit would produce. Now refused
// at deserialize with the canonical-form diagnostic naming the
// offending `"1.5"` magnitude and the round-trip drift wording.
let payload = r#"{"rateLimit":"1.5/s"}"#;
let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
let msg = err.to_string();
assert!(
msg.contains("not a non-negative integer"),
"expected integer-magnitude diagnostic in {msg:?}"
);
assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
assert!(
msg.contains("THEORY.md"),
"missing render-determinism contract citation in {msg:?}"
);
}
#[test]
fn rate_limit_serde_rejects_leading_plus_sign() {
// `u32::from_str("+100")` returns `Ok(100)` (Rust's
// permissive-`+` parse), so `"+100/s"` silently parsed to
// `RateLimit { 100, 1s }` and round-tripped through `render` to
// `"100/s"` — a *different* canonical string on the next emit,
// breaking the THEORY.md Part V render-determinism contract
// exactly the way the peer duration codecs' `"+30s"` case did.
// This is the load-bearing class the digit-only gate closes
// beyond what `u32::from_str`'s strictness covers on its own.
let payload = r#"{"rateLimit":"+100/s"}"#;
let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
let msg = err.to_string();
assert!(
msg.contains("not a non-negative integer"),
"expected integer-magnitude diagnostic in {msg:?}"
);
assert!(msg.contains("\"+100\""), "missing magnitude in {msg:?}");
}
#[test]
fn rate_limit_serde_rejects_leading_minus_sign() {
// The signed-negative arm: `"-1/s"` lands on the
// non-canonical-but-numeric branch via the `i64` fallback (the
// `f64` parse also succeeds), surfacing the canonical-form
// diagnostic. Replaces the prior value-laundered "not a u32"
// wording with the unified diagnostic across signs.
let payload = r#"{"rateLimit":"-1/s"}"#;
let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
let msg = err.to_string();
assert!(
msg.contains("not a non-negative integer"),
"expected integer-magnitude diagnostic in {msg:?}"
);
assert!(msg.contains("\"-1\""), "missing magnitude in {msg:?}");
}
#[test]
fn rate_limit_serde_rejects_decimal_shaped_integer() {
// `"100.0/s"` is integer-valued numerically but not in the
// codec's accepted set — `render` emits `"100/s"`, so the
// round-trip would drift. Lifted to the canonical-form
// diagnostic peer with the duration codec's `"1.0s"` case
// (1c55a2a).
let payload = r#"{"rateLimit":"100.0/s"}"#;
let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
let msg = err.to_string();
assert!(
msg.contains("not a non-negative integer"),
"expected integer-magnitude diagnostic in {msg:?}"
);
assert!(msg.contains("\"100.0\""), "missing magnitude in {msg:?}");
}
#[test]
fn rate_limit_serde_garbage_still_falls_through_to_not_a_u32() {
// Non-numeric, non-digit-only input lands on the existing
// narrower `"not a u32"` arm (preserved for diagnostic-shape
// stability on the parser-shape footgun case). Pin this so a
// future relaxation of the numeric-fallback predicate doesn't
// silently collapse garbage onto the canonical-form arm — same
// partition the peer duration codecs draw between
// `NonIntegerDurationMagnitude` and `BadDurationMagnitude`.
let payload = r#"{"rateLimit":"abc/s"}"#;
let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
let msg = err.to_string();
assert!(
msg.contains("not a u32"),
"garbage magnitude must surface the narrower `not a u32` wording, got: {msg:?}"
);
assert!(
!msg.contains("not a non-negative integer"),
"garbage magnitude must NOT surface the canonical-form arm, got: {msg:?}"
);
}
#[test]
fn rate_limit_serde_u32_overflow_surfaces_as_overflow() {
// `u32::MAX + 1` (= 4_294_967_296) is digit-only but exceeds
// u32's range. The digit-only gate passes; `u32::from_str`
// fails on overflow. Surface that with the overflow-shaped
// diagnostic naming the offending magnitude verbatim, peer
// with `supervisor::duration_codec`'s overflow arm. Pinning
// the wording so a future refactor doesn't silently collapse
// overflow onto the canonical-form arm.
let payload = r#"{"rateLimit":"4294967296/s"}"#;
let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
let msg = err.to_string();
assert!(
msg.contains("overflows u32"),
"expected overflow diagnostic in {msg:?}"
);
assert!(
msg.contains("\"4294967296\""),
"missing offending magnitude in {msg:?}"
);
}
#[test]
fn rate_limit_serde_rejects_leading_zero_magnitude() {
// `"0100/s"` is digit-only, so the existing
// non-digit-only / sign / fractional arm doesn't catch it —
// `u32::from_str("0100")` returns `Ok(100)`, so before this
// gate `"0100/s"` parsed to `RateLimit { 100, 1s }` and
// round-tripped through `render` to `"100/s"` — a *different*
// canonical string on the next emit, breaking the THEORY.md
// Part V render-determinism contract exactly the way the
// peer `"+100/s"` case did before the leading-`+` arm landed.
// This is the load-bearing class the leading-zero gate closes
// beyond what the existing digit-only / sign / fractional
// gates cover, and the peer arm to the leading-`+` test
// (`rate_limit_serde_rejects_leading_plus_sign`) on the same
// canonical-form-drift axis.
let payload = r#"{"rateLimit":"0100/s"}"#;
let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
let msg = err.to_string();
assert!(
msg.contains("non-canonical leading zero"),
"expected leading-zero diagnostic in {msg:?}"
);
assert!(msg.contains("\"0100\""), "missing magnitude in {msg:?}");
assert!(
msg.contains("THEORY.md"),
"missing render-determinism contract citation in {msg:?}"
);
}
#[test]
fn rate_limit_serde_rejects_multi_digit_zero_magnitude() {
// `"00/s"` is the degenerate leading-zero case — every byte
// is `0`, the magnitude parses to `u32` = 0, and `render(0)`
// emits `"0/s"`. Round-trip drift: `"00/s"` → 0 → `"0/s"`,
// a *different* canonical string, same render-determinism
// violation. The single-byte `"0/s"` itself is in the
// accepted set (round-trips losslessly through `render`,
// refused downstream by `PolicyRateLimitZero`); the
// multi-byte `"00/s"` is not. Pins the boundary between the
// accepted single-`0` and the rejected leading-zero class.
let payload = r#"{"rateLimit":"00/s"}"#;
let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
let msg = err.to_string();
assert!(
msg.contains("non-canonical leading zero"),
"expected leading-zero diagnostic in {msg:?}"
);
assert!(msg.contains("\"00\""), "missing magnitude in {msg:?}");
}
#[test]
fn rate_limit_serde_rejects_leading_zero_per_hour_window() {
// Cross-window pin — the gate is window-agnostic; the
// leading-zero class is a property of the magnitude, not the
// unit. `"007/h"` → 7 → `"7/h"`, same drift. Mirrors the
// peer `rate_limit_serde_rejects_leading_plus_sign` arm's
// single-window coverage extended across the three canonical
// windows the codec accepts.
let payload = r#"{"rateLimit":"007/h"}"#;
let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
let msg = err.to_string();
assert!(
msg.contains("non-canonical leading zero"),
"expected leading-zero diagnostic in {msg:?}"
);
assert!(msg.contains("\"007\""), "missing magnitude in {msg:?}");
}
#[test]
fn rate_limit_serde_rejects_leading_whitespace() {
// `" 100/s"` — the canonical paste-from-aligned-doc /
// paste-from-YAML-quoted-plain-scalar footgun. Before this gate
// the top-level `s.trim()` silently ate the leading space and
// parsed the value to `RateLimit { 100, 1s }`, which then
// round-tripped through `render` to `"100/s"` (a *different*
// canonical string on the next emit) — the exact
// canonical-form-drift class the leading-`+` / leading-zero
// arms already close, extended to the whitespace byte class.
let payload = r#"{"rateLimit":" 100/s"}"#;
let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
let msg = err.to_string();
assert!(
msg.contains("contains whitespace byte"),
"expected whitespace diagnostic in {msg:?}"
);
assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
assert!(
msg.contains("THEORY.md"),
"missing render-determinism contract citation in {msg:?}"
);
}
#[test]
fn rate_limit_serde_rejects_trailing_whitespace() {
// `"100/s "` — the canonical shell-history / trailing-space
// paste footgun. Before this gate the top-level `s.trim()`
// silently ate the trailing space and parsed to
// `RateLimit { 100, 1s }`, round-tripping to `"100/s"` on the
// next emit — same canonical-form drift as the leading-space
// sibling, closed on the same whitespace-byte arm.
let payload = r#"{"rateLimit":"100/s "}"#;
let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
let msg = err.to_string();
assert!(
msg.contains("contains whitespace byte"),
"expected whitespace diagnostic in {msg:?}"
);
assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
}
#[test]
fn rate_limit_serde_rejects_internal_whitespace_around_separator() {
// `"100 / s"` — the canonical typographically-spaced author
// shape (the same idiom every prose reference to a rate limit
// renders as, mistakenly retained when the value is pasted
// into a codec-shaped slot). Before this gate the per-part
// `rate_str.trim()` / `unit.trim()` calls silently ate both
// spaces on either side of `/` and parsed to
// `RateLimit { 100, 1s }`, round-tripping to `"100/s"` — the
// codec's *internal* whitespace-tolerance vector, orthogonal
// to the leading / trailing surface but the same canonical-
// form-drift class. Pins the arm as strictly stronger than the
// pre-existing top-level `s.trim()` behavior: it fires on
// whitespace anywhere in the value, not just at the string
// boundary.
let payload = r#"{"rateLimit":"100 / s"}"#;
let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
let msg = err.to_string();
assert!(
msg.contains("contains whitespace byte"),
"expected whitespace diagnostic in {msg:?}"
);
assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
}
#[test]
fn rate_limit_serde_rejects_tab_byte() {
// `"\t100/s"` — the canonical paste-from-indented-doc /
// paste-from-YAML-block-scalar footgun where a tab byte leads
// the magnitude. Pins that the gate covers tab (`0x09`) as
// well as space (`0x20`) — both are `u8::is_ascii_whitespace`
// members and both would be silently swallowed by `s.trim()`
// pre-gate. The `is_ascii_whitespace` coverage extends beyond
// space alone to the full ASCII-whitespace set (space `0x20`,
// tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
// the tab arm as a representative of the non-space members.
let payload = r#"{"rateLimit":"\t100/s"}"#;
let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
let msg = err.to_string();
assert!(
msg.contains("contains whitespace byte"),
"expected whitespace diagnostic in {msg:?}"
);
assert!(
msg.contains("0x09"),
"missing offending tab byte in {msg:?}"
);
}
// ── canonical-form: non-ASCII Unicode `White_Space` rate-limit gate ───
//
// Successor to the ASCII-whitespace arm (1ad7755) on
// `rate_limit_codec` — closes the strictly-complementary class the
// byte-scan cannot see, through the lifted
// [`crate::render::find_non_ascii_whitespace_char`] predicate.
#[test]
fn rate_limit_serde_rejects_leading_nbsp() {
// NBSP prefix — paste-from-typography footgun. Byte-scan
// misses, `str::trim` silently strips it, value drifts to
// `"100/s"` on next serialize.
let payload = "{\"rateLimit\":\"\u{00A0}100/s\"}";
let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
let msg = err.to_string();
assert!(
msg.contains("non-ASCII Unicode whitespace character"),
"expected non-ASCII whitespace diagnostic in {msg:?}"
);
assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
}
#[test]
fn rate_limit_serde_rejects_internal_em_space() {
// EM-SPACE (`\u{2003}`) between magnitude and unit — canonical
// paste-from-typography footgun on the `<integer>/<unit>`
// shape.
let payload = "{\"rateLimit\":\"100\u{2003}/s\"}";
let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
let msg = err.to_string();
assert!(
msg.contains("non-ASCII Unicode whitespace character"),
"expected non-ASCII whitespace diagnostic in {msg:?}"
);
assert!(msg.contains("U+2003"), "missing codepoint in {msg:?}");
}
#[test]
fn rate_limit_serde_accepts_ascii_only_canonical_forms_after_unicode_arm() {
// Positive-control pin: every ASCII-only canonical form the
// renderer emits stays accepted through the new arm.
for lit in [r#""100/s""#, r#""5000/m""#, r#""10000/h""#] {
let payload = format!(r#"{{"rateLimit":{lit}}}"#);
let p: MeshPolicy = serde_json::from_str(&payload)
.unwrap_or_else(|e| panic!("expected {lit} to parse; got {e}"));
assert!(p.rate_limit.is_some());
}
}
#[test]
fn rate_limit_serde_accepts_single_zero_magnitude_at_codec_layer() {
// The boundary case — `"0/s"` is the canonical form
// `render(RateLimit { 0, 1s })` emits, so the codec accepts
// it at the parse layer; the downstream
// [`AplicacaoError::PolicyRateLimitZero`] gate refuses
// `rate == 0` at the typed-validate layer above. Pins the
// partition: the leading-zero gate at the codec layer does
// not poach the rate-zero semantic-validation arm at the
// typed-validate layer above (a future stricter codec must
// not reject `"0/s"` here, or it'd collapse the diagnostic
// partitioning that lets `PolicyRateLimitZero` name the
// offending typed slot).
let payload = r#"{"rateLimit":"0/s"}"#;
let policy: MeshPolicy = serde_json::from_str(payload).unwrap_or_else(|e| {
panic!("`\"0/s\"` must parse cleanly through rate_limit_codec: {e}")
});
let rl = policy.rate_limit.expect("rate_limit must be Some");
assert_eq!(rl.rate, 0, "single-`0` magnitude must parse to rate=0");
assert_eq!(
rl.window,
Duration::from_secs(1),
"single-`0` magnitude with `s` unit must parse to window=1s"
);
}
#[test]
fn rate_limit_serde_accepts_canonical_magnitude_with_leading_one() {
// The complementary boundary pin — every magnitude
// `render` emits starts with `[1-9]` (or is the single byte
// `"0"`), so the canonical-form predicate is `(len == 1) ||
// (first byte != '0')`. Pinning the `len > 1 && first byte ==
// '1'` case explicitly so a future tightening of the gate
// (e.g. an over-eager "no leading digit < 5" rule, or a
// mistakenly anchored start-of-magnitude byte check) lands
// here before the canonical-forms-iterating test would catch
// it.
let payload = r#"{"rateLimit":"100/s"}"#;
let policy: MeshPolicy = serde_json::from_str(payload)
.unwrap_or_else(|e| panic!("canonical `\"100/s\"` must parse cleanly: {e}"));
let rl = policy.rate_limit.expect("rate_limit must be Some");
assert_eq!(
rl.rate, 100,
"canonical-100 magnitude must parse to rate=100"
);
}
#[test]
fn rate_limit_serde_accepts_integer_canonical_forms() {
// Pin the happy-path: every canonical author shape `render`
// ever emits parses cleanly through the codec post-gate. The
// codec's accepted set (post-gate) is exactly its emitted set
// for the integer-magnitude class — same property
// `parse_byte_size`'s and `parse_duration`'s integer-magnitude
// gates guarantee on the peer codecs. Iterating across rate
// magnitudes (including `"0"`, which the codec accepts even
// though `validate_politicas` rejects `rate == 0` at the typed
// layer above) closes the codec contract at the parse layer
// independently of the validate layer.
for rate_lit in ["0", "1", "100", "5000", "1000000", "4294967295"] {
for unit_lit in ["s", "m", "h"] {
let lit = format!("{rate_lit}/{unit_lit}");
let payload = format!(r#"{{"rateLimit":{lit:?}}}"#);
let policy: MeshPolicy = serde_json::from_str(&payload).unwrap_or_else(|e| {
panic!("expected {lit:?} to parse cleanly through rate_limit_codec: {e}")
});
let rl = policy.rate_limit.expect("rate_limit must be Some");
assert_eq!(
rl.rate,
rate_lit.parse::<u32>().unwrap(),
"rate mismatch for {lit:?}"
);
}
}
}
#[test]
fn rate_limit_serde_round_trip_holds_for_every_canonical_form() {
// The structural property the gate enforces: serialize ∘
// deserialize is the identity on every canonical author shape.
// Peer of `parse_byte_size`'s and `parse_duration`'s
// `_round_trips_through_render_for_every_canonical_form` tests
// on the rate-limit axis. Before the gate, `"+100/s"` violated
// this (`parse` → `RateLimit { 100, 1s }` → `render` →
// `"100/s"` ≠ `"+100/s"`); the gate forecloses that class.
for rate in [1u32, 100, 5000, 1_000_000] {
for (window, unit) in [
(Duration::from_secs(1), "s"),
(Duration::from_secs(60), "m"),
(Duration::from_secs(3600), "h"),
] {
let policy = MeshPolicy {
rate_limit: Some(RateLimit { rate, window }),
..Default::default()
};
let json = serde_json::to_string(&policy).unwrap();
let expected = format!("\"{rate}/{unit}\"");
assert!(
json.contains(&expected),
"expected {expected:?} in {json:?}"
);
let back: MeshPolicy = serde_json::from_str(&json).unwrap();
assert_eq!(
back.rate_limit, policy.rate_limit,
"round-trip for {json:?}"
);
}
}
}
// ── self-membership cross-slot gate ──────────────────────────────
#[test]
fn validate_no_self_membership_rejects_self_named_membro() {
// An Aplicacao whose `:membros` lists its own `:nome` is a
// one-node lacre-closure recursion — rejected, naming the parent.
let membros = vec![
membro("catalog", "^0.1"),
membro("checkout", "^0.1"),
membro("cart", "^0.1"),
];
let err = validate_no_self_membership(&membros, "checkout").unwrap_err();
assert!(
matches!(err, AplicacaoError::MembroIsSelfAplicacao { ref caixa } if caixa == "checkout"),
"got {err:?}"
);
}
#[test]
fn validate_no_self_membership_accepts_distinct_membros() {
// Positive control: distinct member names (including a member
// that is itself an Aplicacao — recursive composition is valid,
// MESH-COMPOSITION §V) pass the gate.
let membros = vec![membro("catalog", "^0.1"), membro("sub-aplicacao", "^0.1")];
validate_no_self_membership(&membros, "checkout").unwrap();
}
#[test]
fn validate_no_self_membership_empty_membros_is_vacuously_ok() {
// An empty `:membros` is rejected by `AplicacaoSpec::validate`'s
// `NoMembros` arm (the more-fundamental "graph must have nodes"
// gate), not by this cross-slot self-edge gate. Keeping the
// self-membership predicate vacuously-ok on the empty input
// matches its supervisor-axis peer
// (`validate_no_self_supervision_empty_children_is_ok`) and
// makes the gate composable from any future call site (an M4
// CR materializer's per-membros validator) without re-checking
// emptiness.
validate_no_self_membership(&[], "checkout").unwrap();
}
#[test]
fn validate_no_self_membership_diagnostic_names_offending_caixa() {
// Pinning the Display: the self-membership diagnostic must name
// the offending caixa verbatim + the "lists itself" framing the
// author can grep for, so the cluster-far failure surfaces at
// build time with one-line remediation. Same diagnostic shape
// as the supervisor-axis `ChildSupervisesSelf` peer.
let membros = vec![membro("orquestra", "^0.1")];
let err = validate_no_self_membership(&membros, "orquestra").unwrap_err();
let msg = err.to_string();
assert!(
msg.contains("orquestra"),
"diagnostic must name the offending caixa nome (got: {msg:?})"
);
assert!(
msg.contains("lists itself"),
"diagnostic must use the canonical `lists itself` framing (got: {msg:?})"
);
}
#[test]
fn default_servico_port_constant_pins_canonical_8080_literal() {
// The canonical-constant arm — pins [`DEFAULT_SERVICO_PORT`]
// at the verbatim `8080` literal both consumers (the
// `Entrada::port` serde default via [`default_port`] and the
// `caixa-mesh` `CiliumNetworkPolicy` L4-fallback at
// `caixa-mesh/src/lib.rs:344`) read from. Peer with the
// [`crate::DEFAULT_NAMESPACE`]-pins-`"tatara-system"`
// discipline (a085b26) on the per-renderer canonical-K8s-axis
// string-constant axis: a future refactor that drifts the
// constant out from under either consumer surfaces here ahead
// of every per-renderer's first emission. The literal value
// matches the well-known HTTP-alt port the `pleme-computeunit`
// library chart already emits as its `trigger.service.port`
// default — by construction the same value the substrate
// assumes about every Servico's in-cluster L4 listener.
assert_eq!(
DEFAULT_SERVICO_PORT, 8080,
"canonical Servico port literal must remain `8080` verbatim — \
this is the value both the `Entrada::port` serde default and the \
caixa-mesh `CiliumNetworkPolicy` L4-fallback read from"
);
}
#[test]
fn default_port_helper_returns_canonical_servico_port_constant() {
// The bridge-arm — pins that the [`default_port`] helper
// [`Entrada::port`]'s `#[serde(default = "default_port")]`
// attribute hooks routes through the lifted
// [`DEFAULT_SERVICO_PORT`] constant, not an open-coded
// literal. A future refactor that re-introduces the `8080`
// literal at the helper's return site (silently re-opening
// the drift footgun this lift closed) surfaces here ahead of
// every author-side `(:entrada (:host … :para …))` slot
// without an explicit `:port`. Peer with the
// `default_namespace_re_export_points_at_caixa_core_canonical`
// pin on the caixa-mesh-side re-export axis.
assert_eq!(
default_port(),
DEFAULT_SERVICO_PORT,
"the serde-default helper must route through the lifted constant"
);
}
#[test]
fn entrada_serde_default_port_inherits_canonical_servico_port_constant() {
// The end-to-end pin — an author-surface `(:entrada (:host …
// :para …))` without an explicit `:port` slot deserializes to
// a typed [`Entrada`] carrying [`DEFAULT_SERVICO_PORT`]
// verbatim. Routes the canonical lifted constant through both
// the serde-default machinery (the `#[serde(default =
// "default_port")]` attribute) and the typed-value-shape
// contract (the resulting [`Entrada::port`] value). A future
// refactor that drifts either axis — replacing the serde
// hook's helper, changing the typed slot's wire shape — would
// surface here before any per-renderer's CNP / Gateway /
// HTTPRoute emission consumed the drifted default.
let entrada: Entrada =
serde_yaml::from_str("host: checkout.quero.cloud\npara: cart\n").expect("yaml parses");
assert_eq!(
entrada.port, DEFAULT_SERVICO_PORT,
"the serde default must materialize as the lifted canonical Servico port"
);
}
#[test]
fn servico_port_min_pins_canonical_accept_set_floor() {
// The canonical-constant arm — pins [`SERVICO_PORT_MIN`] at the
// verbatim `1` literal every typed `:entrada :port` acceptance
// gate keys off. Peer with the
// [`default_servico_port_constant_pins_canonical_8080_literal`]
// discipline on the canonical-Servico-port-constant axis: a
// future refactor that drifts the accept-set floor out from
// under the sole consumer at [`AplicacaoSpec::validate`]'s
// `if e.port < SERVICO_PORT_MIN` gate surfaces here ahead of
// every per-`:entrada` `EntradaPortZero` diagnostic. The
// literal value matches the IANA-registered TCP/UDP port
// space floor (`1..=65535` — port `0` is the "any ephemeral"
// sentinel, not a well-defined destination the substrate's
// per-`Entrada` Gateway API v1 `HTTPRoute.backendRefs[].port`
// axis can honor).
assert_eq!(
SERVICO_PORT_MIN, 1,
"canonical Servico port accept-set floor must remain `1` verbatim — \
this is the value the `AplicacaoSpec::validate` gate at \
`if e.port < SERVICO_PORT_MIN` rejects `port: 0` against"
);
}
#[test]
fn default_servico_port_satisfies_lifted_servico_port_min_floor() {
// The cross-const invariant pin — the substrate's canonical
// default port must satisfy its own accept-set floor by
// construction: `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT`.
// A future rebrand that moved [`DEFAULT_SERVICO_PORT`] below
// [`SERVICO_PORT_MIN`] — a hypothetical `0` typo, a per-cluster
// override the operator pins through a future
// `:placement :default-port` slot that lands out-of-range, a
// per-edition Servico-port migration that lifted the floor
// above the previous default without coordinating the pair —
// would silently invalidate the serde-default emission at
// every author-side `(:entrada (:host … :para …))` slot
// without an explicit `:port`: the default port would fall
// below the accept-set floor, the `AplicacaoSpec::validate`
// gate would reject every default-carrying Aplicacao as
// `EntradaPortZero`, and the substrate's typed
// `(defcaixa … :kind Aplicacao)` surface would fail validate
// on every Aplicacao whose author omitted `:entrada :port`
// for the substrate's chosen default — a class of authoring-
// surface footguns the compile-time pin structurally closes.
// Peer with the
// [`standalone_and_cluster_bundle_lareira_enabled_defaults_are_inverse_by_construction`]
// (27f9b34) cross-const invariant pin discipline on the peer
// canonical-Helm-per-values-block child-chart-enablement-toggle
// axis pair.
const {
assert!(
SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT,
"the substrate's canonical default port DEFAULT_SERVICO_PORT \
must satisfy its own accept-set floor SERVICO_PORT_MIN — \
every default-carrying `(:entrada (:host … :para …))` slot \
without an explicit `:port` inherits `DEFAULT_SERVICO_PORT` \
through the serde default hook and must pass the \
`AplicacaoSpec::validate` floor gate by construction",
);
}
}
#[test]
fn entrada_port_zero_gate_routes_through_lifted_servico_port_min_floor() {
// The gate-site pin — asserts the `AplicacaoSpec::validate`
// floor gate at `if e.port < SERVICO_PORT_MIN` fires the
// `EntradaPortZero` diagnostic on the below-floor input
// `port: 0` (the only below-floor value the `u16` field can
// carry — `SERVICO_PORT_MIN` is `1`, so the below-floor set
// is the singleton `{0}`). A future refactor that drifts the
// gate off the lifted const (silently re-introducing an
// inline `if e.port == 0` byte-check) surfaces here — the
// pin cannot distinguish `< 1` from `== 0` on the current
// floor, but it *does* pin that the diagnostic fires on `0`
// through whichever gate is wired, so any future accept-set
// floor migration (a hypothetical unprivileged-only
// migration lifting `SERVICO_PORT_MIN` to `1024`) must
// update this test alongside the const declaration —
// structurally guaranteeing the gate + accept-set + pin
// trio move together. Peer with the
// [`rejects_zero_entrada_port`] behavioral pin on the same
// per-`:entrada :port` axis — that pin asserts the pre-lift
// behavioral contract (`port: 0` → `EntradaPortZero`); this
// pin adds the structural link to the lifted floor const.
assert_eq!(SERVICO_PORT_MIN, 1, "current floor pinned above");
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().port = 0;
assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
}
// ── drift-detection: serde-derive-to-MEMBRO_KEY_* identity ────────────
#[test]
fn membro_serde_keys_match_lifted_membro_key_consts() {
// Load-bearing invariant: the two `MEMBRO_KEY_*` consts
// ([`crate::MEMBRO_KEY_CAIXA`] / [`crate::MEMBRO_KEY_VERSAO`])
// name the exact camelCase JSON keys the
// `#[serde(rename_all = "camelCase")]` attribute on
// [`Membro`] emits. Serialize a fully-populated `Membro` and pin
// that each canonical byte-sequence appears verbatim in the
// JSON — a future accidental `rename_all = "snake_case"` /
// `"kebab-case"` / verbatim-field-name flip at the derive
// attribute (any of which would silently break every downstream
// JSON consumer that reaches for one of the two consts via
// `Value::get(...)`) surfaces here as a build-time test failure
// at `aplicacao.rs`, not as an apply-time
// `.get(<stale-canonical-const>)` returning `None` far from the
// derive-attr drift's commit. Peer with the sibling
// `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
// (40cc4e5) pin on the M2 supervision-tree top-level axis —
// same discipline the SupervisorSpec top-level lift established,
// extended here to the M3 [`Membro`] per-`:membros` axis.
let m = Membro {
caixa: "catalog".into(),
versao: "^0.1".into(),
};
let json = serde_json::to_string(&m).unwrap();
for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
let quoted = format!("\"{key}\"");
assert!(
json.contains("ed),
"serialized Membro must carry the lifted MEMBRO_KEY_* \
byte-sequence {quoted} verbatim in the JSON emission \
(got: {json})",
);
}
}
#[test]
fn membro_key_consts_are_pairwise_distinct() {
// Cross-axis drift-detection pin: a future collapse of the two
// canonical [`Membro`] per-entry byte-strings onto the same
// value (e.g. an accidental copy-paste flip of
// [`crate::MEMBRO_KEY_VERSAO`] to also read `"caixa"`) would
// silently reroute every downstream probe on one axis onto the
// sibling axis's overlay entry and pass every propagation-probe
// test that expected only the stale axis's value. Peer of the
// sibling four-way distinct pin on the `SUPERVISOR_KEY_*` tetrad
// (40cc4e5).
let all = [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO];
for (i, a) in all.iter().enumerate() {
for b in all.iter().skip(i + 1) {
assert_ne!(
a, b,
"MEMBRO_KEY_* consts must be pairwise-distinct \
canonical byte-sequences — got `{a}` == `{b}`",
);
}
}
}
// ── Entrada::resolved_paths — the substrate-canonical per-`:entrada`
// URL-path fallback resolver every HTTPRoute-aware renderer
// reaching for a per-rule path-list resolution routes through.
// The four pin tests below fix the four-way accept-set the
// resolver must always honor: (:paths-non-empty-verbatim,
// :paths-empty-falls-back-to-catchall, :paths-single-entry-verbatim,
// :paths-preserves-order-across-multiple-entries) — drift on any
// arm surfaces at caixa-core build time rather than at cluster-
// apply time. Peer discipline with `MeshPolicy::is_empty` on the
// sibling `:politicas` typed-primitive dispatch axis.
fn entrada_with_paths(paths: Vec<&str>) -> Entrada {
Entrada {
host: "example.com".into(),
para: "cart".into(),
paths: paths.into_iter().map(String::from).collect(),
port: DEFAULT_SERVICO_PORT,
}
}
#[test]
fn resolved_paths_returns_declared_paths_verbatim_when_non_empty() {
// The typed `:entrada :paths` slot carries an author-declared
// list — the resolver returns each entry verbatim, no
// catch-all substitution. The canonical "author declared
// paths, honor them verbatim" arm of the path-list dispatch.
let e = entrada_with_paths(vec!["/api/cart", "/api/products"]);
assert_eq!(
e.resolved_paths(),
vec!["/api/cart", "/api/products"],
"resolved_paths must return each `:entrada :paths` entry \
verbatim when the typed slot is non-empty (got {:?})",
e.resolved_paths(),
);
}
#[test]
fn resolved_paths_falls_back_to_gateway_api_default_http_route_path_when_paths_empty() {
// Empty `:entrada :paths` slot — the resolver substitutes the
// singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
// catch-all fallback verbatim. Pins the empty-arm of the
// resolver's four-way accept-set against a future silent
// detour that returned an empty Vec (which would emit an
// HTTPRoute with zero rules — silently dropping every
// external `:entrada` flow at admission time), routed to a
// different fallback shape, or dropped the catch-all
// altogether.
let e = entrada_with_paths(vec![]);
assert_eq!(
e.resolved_paths(),
vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
"resolved_paths on empty `:entrada :paths` must fall back \
to the lifted GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH catch-\
all — got {:?}",
e.resolved_paths(),
);
}
#[test]
fn resolved_paths_returns_single_declared_path_verbatim_when_len_one() {
// Single-entry `:entrada :paths` — the resolver returns the
// single declared path verbatim, NOT the catch-all fallback
// (author declared a path, honor it — the empty-arm and the
// len-1 arm are semantically distinct axes of the resolver's
// accept-set). Pins that the resolver treats "author declared
// one path" as authored input, not as the empty case.
let e = entrada_with_paths(vec!["/api/only"]);
assert_eq!(
e.resolved_paths(),
vec!["/api/only"],
"resolved_paths on single-entry `:entrada :paths` must \
return the declared path verbatim, NOT the catch-all \
fallback (got {:?})",
e.resolved_paths(),
);
}
#[test]
fn resolved_paths_preserves_author_declared_order() {
// The `:entrada :paths` list is author-ordered — the resolver
// preserves the author's declaration order verbatim, since
// per-rule dispatch order at the K8s Gateway API HTTPRoute
// consumer is significant (first-match-wins under the
// path-prefix matcher). Pins against a future silent
// re-sort / dedup / normalize detour that reordered author
// input.
let e = entrada_with_paths(vec!["/z/last", "/a/first", "/m/mid"]);
assert_eq!(
e.resolved_paths(),
vec!["/z/last", "/a/first", "/m/mid"],
"resolved_paths must preserve author-declared `:entrada \
:paths` order verbatim — got {:?}",
e.resolved_paths(),
);
}
// ── Entrada::paths — the substrate-canonical per-`:entrada` raw-
// slot `&[String]` slice accessor every per-`:entrada` consumer
// that must see the author's declaration verbatim (not the
// fallback-applied projection the sibling `resolved_paths`
// returns) routes through. The three pin tests below fix the
// accept-set the accessor must honor: (:non-empty-byte-equal,
// :empty-projects-empty-slice, :preserves-author-declared-order)
// — drift on any arm surfaces at caixa-core build time rather
// than at cluster-apply time. Peer discipline with the sibling
// [`Placement::clusters`] (a6e18d7) `&[String]` accessor on the
// peer M3 mesh-slot `Vec<String>`-carry axis.
#[test]
fn paths_returns_entrada_paths_slice_byte_equal_across_permutations() {
// Byte-equal pin: [`Entrada::paths`] must project the raw
// `:entrada :paths` `Vec<String>` verbatim as a `&[String]`
// slice borrowed from the typed slot's own [`Vec<String>`]
// storage — no re-ordering, no dedup, no per-entry normalization,
// no fallback substitution (the fallback-applying projection is
// the sibling [`Entrada::resolved_paths`] resolver). Pins against
// a future silent detour that re-normalized the list, dropped
// duplicates the [`AplicacaoSpec::validate`]
// `EntradaPathDuplicate` refusal already rejects at build time,
// or (most severe) accidentally routed through the fallback-
// applying sibling and returned the substrate catch-all when
// the author declared an empty list — collapsing the raw-slot
// and fallback-applied axes into one and breaking the
// [`AplicacaoSpec::validate`] "empty `:paths` is `Ok(())`" contract.
//
// Peer of the sibling
// [`Placement::clusters`]-shape byte-equal pin
// `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
// (a6e18d7) on the peer M3 mesh-slot `Vec<String>`-carry axis.
let fixtures: Vec<Vec<String>> = vec![
Vec::new(),
vec!["/api/cart".into()],
vec!["/api/cart".into(), "/api/products".into()],
vec!["/z/last".into(), "/a/first".into(), "/m/mid".into()],
];
for paths in fixtures {
let e = Entrada {
host: "example.com".into(),
para: "cart".into(),
paths: paths.clone(),
port: DEFAULT_SERVICO_PORT,
};
assert_eq!(
e.paths(),
paths.as_slice(),
"Entrada::paths must return :entrada :paths verbatim \
(got {:?}, expected {:?})",
e.paths(),
paths.as_slice(),
);
assert_eq!(
e.paths(),
e.paths.as_slice(),
"Entrada::paths accessor and .paths.as_slice() field \
access must byte-equal — the accessor is the substrate-\
primitive typed dispatch every downstream per-`:entrada` \
raw-slot path-list consumer must route through",
);
assert_eq!(
e.paths().len(),
e.paths.len(),
"Entrada::paths().len() must byte-equal self.paths.len() \
— a length drift would silently split the paired \
pre-flight cascade-head `.is_empty()` probe input in \
the sibling [`Entrada::resolved_paths`] resolver from \
the per-entry validate loop's traversal input in \
[`AplicacaoSpec::validate`]",
);
}
}
#[test]
fn resolved_paths_reads_through_lifted_paths_accessor() {
// Two-consumer coherence pin: the [`Entrada::resolved_paths`]
// pre-flight `.paths().is_empty()` cascade-head probe (which
// must trip the [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
// catch-all fallback arm when the accessor projects the empty
// slice) and the per-entry `.paths().iter().map(String::as_str)`
// projection (which must reach every entry in the same order
// the accessor projects, so the sibling
// [`AplicacaoSpec::validate`] per-entry gate and the resolver's
// per-entry projection stay in lockstep by construction) must
// both key off the lifted accessor. Pins the two-site coherence
// by exercising each production consumer end-to-end: (1) the
// catch-all-fallback arm under the empty slice, (2) the
// author-declared-verbatim arm under a two-entry cohort whose
// per-entry projection must byte-equal the input's per-entry
// author-declared paths in the author's declared order.
//
// Peer of the sibling M3
// [`AplicacaoSpec::validate_placement`]-shape two-consumer pin
// `validate_placement_reads_through_lifted_clusters_accessor`
// on the sibling `Placement::clusters` reader-site convergence.
let empty = entrada_with_paths(vec![]);
assert_eq!(
empty.resolved_paths(),
vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
"resolved_paths on empty :entrada :paths must trip the \
lifted [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] \
catch-all fallback — routing through the lifted paths() \
accessor must not silently drop the fallback arm",
);
let declared = entrada_with_paths(vec!["/api/cart", "/api/products"]);
assert_eq!(
declared.resolved_paths(),
vec!["/api/cart", "/api/products"],
"resolved_paths on non-empty :entrada :paths must return each \
entry verbatim in the author's declared order — routing \
through the lifted paths() accessor must not silently \
reorder or drop entries",
);
// Byte-equal pin against the raw-slot accessor to keep the
// fallback-applying resolver's per-entry projection input in
// lockstep with the raw-slot accessor's projection.
let raw_projected: Vec<&str> = declared.paths().iter().map(String::as_str).collect();
assert_eq!(
declared.resolved_paths(),
raw_projected,
"resolved_paths non-empty projection must byte-equal the \
lifted paths() accessor's per-entry String::as_str projection \
— the two projections share the same input slice by \
construction, so any drift here would surface a silent \
re-ordering / dedup / normalization detour in the resolver",
);
}
#[test]
fn validate_reads_through_lifted_entrada_paths_accessor() {
// Two-consumer coherence pin: the [`AplicacaoSpec::validate`]
// per-entry value-shape gate's `for p in e.paths()` traversal
// (which must reach every entry in the same order the accessor
// projects, so both the per-entry `EntradaPathEmpty` /
// `EntradaPathNotAbsolute` / `EntradaPathInvalid` gates and
// the duplicate-detection HashSet insert that trips
// [`AplicacaoError::EntradaPathDuplicate`] key off the accessor's
// projection) must route through the lifted accessor. Pins the
// coherence by exercising each production consumer end-to-end:
// (1) the `EntradaPathEmpty` refusal fires on the second entry
// of a two-entry cohort whose head is valid but tail is empty
// (which requires the loop to reach the second entry through
// the accessor), and (2) the `EntradaPathDuplicate` refusal
// fires on the second entry of a two-entry cohort that shares
// a path (which requires the loop to reach both entries — a
// first-entry-only projection would silently pass since the
// dedup HashSet has room for the first insert).
//
// Peer of the sibling
// `validate_placement_reads_through_lifted_clusters_accessor`
// on the sibling `Placement::clusters` reader-site convergence.
let base = crate::AplicacaoSpec {
membros: vec![crate::Membro {
caixa: "cart".into(),
versao: "^0.1".into(),
}],
contratos: Vec::new(),
politicas: crate::MeshPolicy::default(),
placement: crate::Placement {
estrategia: crate::PlacementStrategy::SingleNode,
clusters: vec!["rio".into()],
shard_key: None,
affinity: None,
},
entrada: Some(Entrada {
host: "example.com".into(),
para: "cart".into(),
paths: vec!["/api/cart".into(), String::new()],
port: DEFAULT_SERVICO_PORT,
}),
};
assert_eq!(
base.validate(),
Err(crate::AplicacaoError::EntradaPathEmpty),
"validate must trip EntradaPathEmpty on the second entry of \
a two-entry cohort — routing through the lifted paths() \
accessor must not silently short-circuit the loop at the \
valid head entry",
);
let mut dup = base;
dup.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "/api/cart".into()];
assert_eq!(
dup.validate(),
Err(crate::AplicacaoError::EntradaPathDuplicate {
path: "/api/cart".into(),
}),
"validate must trip EntradaPathDuplicate on the second entry \
of a two-entry cohort that shares a path — routing through \
the lifted paths() accessor must not silently short-circuit \
the dedup HashSet insert at the first entry",
);
}
// ── Entrada::hostname / Entrada::hostnames — the substrate-
// canonical per-`:entrada` DNS-hostname resolver pair every
// Gateway-API-aware renderer reaching for a per-listener
// singular `hostname:` filter (Gateway) or a per-route plural
// `spec.hostnames[]` filter list (HTTPRoute) routes through.
// The three pin tests below fix the two-way accept-set the pair
// must always honor: (:singular-byte-equal-to-host,
// :plural-is-singleton-of-singular, :plural-len-is-one) — drift
// on any arm surfaces at caixa-core build time rather than at
// cluster-apply time when the API server refuses the HTTPRoute
// for non-intersecting hostname filters. Peer discipline with
// the sibling `resolved_paths` accept-set pin block above on the
// per-`:entrada` path-list resolver axis.
fn entrada_with_host(host: &str) -> Entrada {
Entrada {
host: host.into(),
para: "cart".into(),
paths: Vec::new(),
port: DEFAULT_SERVICO_PORT,
}
}
#[test]
fn hostname_returns_entrada_host_byte_equal() {
// The canonical singular-axis pin: [`Entrada::hostname`] must
// return the `:entrada :host` field byte-for-byte, borrowed
// from the typed slot's own [`String`] storage. Pins against a
// future silent detour that re-normalized the host (an
// accidental `.to_lowercase()` — validate_entrada_host already
// enforces lowercase, so any re-normalization is redundant + a
// drift surface between the validator and the accessor), a
// trailing-`.` fully-qualified DNS shape substitution, or a
// Punycode round-trip that lowered a Unicode host through IDNA.
let e = entrada_with_host("checkout.quero.cloud");
assert_eq!(
e.hostname(),
"checkout.quero.cloud",
"Entrada::hostname must return :entrada :host verbatim \
(got {:?})",
e.hostname(),
);
assert_eq!(
e.hostname(),
e.host.as_str(),
"Entrada::hostname must byte-equal the .host field access",
);
}
#[test]
fn hostnames_returns_singleton_of_hostname_accessor() {
// The pair-invariant pin: [`Entrada::hostnames`] must always
// return exactly `vec![hostname()]` — the singleton list whose
// sole entry is the substrate's canonical per-`:entrada`
// singular hostname. Pins the two-consumer coherence axis: the
// Gateway listener's singular `hostname:` filter and the
// HTTPRoute's plural `spec.hostnames[]` filter list must
// agree, else the Gateway API v1.x conformance layer rejects
// the HTTPRoute at attach time with
// `Accepted:False/NoMatchingParent` (the parent Gateway's
// listener hostname doesn't intersect the route's hostname
// filter list) — a divergence whose apply-time symptom is far
// from any single-site commit and never surfaces in the
// emitted YAML. Pinning the pair-invariant here makes any
// future accidental split (an accidental `.to_string() + "."`
// trailing-`.` on the plural side that didn't land on the
// singular side, an accidental prefix stripping on one axis,
// an accidental wildcard prepend the SNI fan-out overlay
// authors on the plural side without a paired singular
// migration) trip at caixa-core build time.
let e = entrada_with_host("checkout.quero.cloud");
assert_eq!(
e.hostnames(),
vec![e.hostname()],
"Entrada::hostnames must return `vec![hostname()]` under \
the pair-invariant — got {:?} vs. singleton {:?}",
e.hostnames(),
vec![e.hostname()],
);
}
#[test]
fn hostnames_is_singleton_under_single_host_author_surface() {
// The singleton-shape pin: under today's single-hostname-per-
// `:entrada` author surface (the `:host` slot is a single
// [`String`], not a `Vec<String>`), [`Entrada::hostnames`]
// must always return a list of length exactly one. Pins
// against a future silent detour that returned an empty list
// (which would emit an HTTPRoute with `spec.hostnames: []` —
// matching every incoming Host header regardless of the
// Aplicacao's declared ingress apex, silently over-matching
// every foreign VirtualHost the parent Gateway also fronts) or
// a duplicated entry (which the Gateway API v1.x parser
// accepts as a `[]-length-2 list of equal hostnames]` but
// whose semantics differ from the intended singleton). The
// author-surface extension point ("a future `:entrada
// :alt-hosts` list overlay" the docstring names) is the sole
// future axis that flips this pin — that migration will re-
// author this test to pin the new plural cardinality.
let e = entrada_with_host("checkout.quero.cloud");
assert_eq!(
e.hostnames().len(),
1,
"Entrada::hostnames must be a singleton under today's \
single-hostname-per-`:entrada` author surface — got \
length {}: {:?}",
e.hostnames().len(),
e.hostnames(),
);
}
// ── Entrada::destination — the substrate-canonical per-`:entrada`
// destination-Servico scalar accessor every Gateway-API
// HTTPRoute-aware renderer reaching for a per-CR `metadata.name`
// discriminator arg (HTTPRoute name composer) or a per-rule
// `backendRefs[0].name` axis routes through. The two pin tests
// below fix (:byte-equal-to-para, :borrow-not-copy) — drift on
// either arm surfaces at caixa-core build time rather than at
// cluster-apply time when an HTTPRoute's `metadata.name` and
// `backendRefs[]` silently disagree on which destination Servico
// the ingress fronts. Peer discipline with the sibling
// `resolved_paths` + `hostname` + `hostnames` accept-set pin
// blocks above on the per-`:entrada` path-list / DNS-hostname
// resolver axes.
#[test]
fn destination_returns_entrada_para_byte_equal() {
// The canonical destination-scalar pin: [`Entrada::destination`]
// must return the `:entrada :para` field byte-for-byte, borrowed
// from the typed slot's own [`String`] storage. Pins against a
// future silent detour that re-normalized the destination (an
// accidental `.to_lowercase()` — the destination Servico is
// already validated as a DNS-1123 label upstream, so any
// re-normalization is redundant + a drift surface between the
// validator and the accessor), a namespace-prefix rewrite (an
// accidental `format!("{namespace}/{para}")` per-CR fully-
// qualified rewrite that didn't land on the peer axis), or a
// per-cluster suffix stamp the operator authors on one
// consumer without the other.
for para in ["cart", "checkout", "catalog", "orders-v2"] {
let e = Entrada {
host: "checkout.quero.cloud".into(),
para: para.into(),
paths: Vec::new(),
port: DEFAULT_SERVICO_PORT,
};
assert_eq!(
e.destination(),
para,
"Entrada::destination must return :entrada :para verbatim \
(got {:?}, expected {para:?})",
e.destination(),
);
assert_eq!(
e.destination(),
e.para.as_str(),
"Entrada::destination must byte-equal the .para field access",
);
}
}
#[test]
fn destination_borrows_from_entrada_para_storage() {
// The borrow-not-copy pin: [`Entrada::destination`] must
// return a `&str` slice that borrows from the typed slot's
// own [`String`] storage — same-address invariant with
// `entrada.para.as_str()`. Pins against a future silent detour
// that allocated a fresh `String` (`self.para.clone()` in the
// body would type-check but silently drop the borrow, and
// every downstream consumer that assumed the returned slice
// outlives `&self` would break on a stale-reference use-after-
// free). Peer with the sibling `hostname_returns_entrada_
// host_byte_equal` on the singular-DNS-hostname axis.
let e = entrada_with_host("checkout.quero.cloud");
let dest = e.destination();
let para_slice = e.para.as_str();
assert_eq!(
dest.as_ptr(),
para_slice.as_ptr(),
"Entrada::destination must borrow from the .para String's \
backing storage — a fresh allocation here means the \
accessor no longer names the substrate-primitive typed \
dispatch and every downstream consumer would silently \
carry a detached copy",
);
assert_eq!(
dest.len(),
para_slice.len(),
"Entrada::destination and .para.as_str() must byte-equal in \
length as well as in address",
);
}
#[test]
fn port_returns_entrada_port_verbatim_across_permutations() {
// The canonical L4-port-scalar pin: [`Entrada::port`] must
// return the `:entrada :port` field verbatim as a `u16` across
// every author-declared value in the validated accept-set
// ([`SERVICO_PORT_MIN`]`..=u16::MAX`). Pins against a future
// silent detour that clamped the port (an accidental
// `.min(HTTPS_STANDARD_PORT)` per-cluster ceiling that didn't
// land on the peer [`AplicacaoSpec::port_for_destination`]
// resolver), rewrote it through a per-cluster port-remap table
// the operator authors on one consumer without the other, or
// substituted [`DEFAULT_SERVICO_PORT`] when the field held its
// serde-default value (which would silently collapse the
// distinction between "author explicitly declared `:port 8080`"
// and "author omitted the slot and inherited the default" the
// future per-cluster override slot depends on). Peer with the
// sibling `destination_returns_entrada_para_byte_equal` +
// `hostname_returns_entrada_host_byte_equal` pins on the
// per-`:entrada` `&str` scalar axes.
for port in [
SERVICO_PORT_MIN,
DEFAULT_SERVICO_PORT,
8443u16,
9090u16,
u16::MAX,
] {
let e = Entrada {
host: "checkout.quero.cloud".into(),
para: "cart".into(),
paths: Vec::new(),
port,
};
assert_eq!(
e.port(),
port,
"Entrada::port must return :entrada :port verbatim \
(got {}, expected {port})",
e.port(),
);
assert_eq!(
e.port(),
e.port,
"Entrada::port accessor and .port field access must \
byte-equal — the accessor is the substrate-primitive \
typed dispatch every downstream L4-port consumer must \
route through",
);
}
}
#[test]
fn validate_entrada_port_floor_gate_reads_through_lifted_port_accessor() {
// Two-consumer coherence pin: the
// [`AplicacaoSpec::validate`] entrada-block structural-floor gate
// (which reads through [`Entrada::port`] to compare against
// [`SERVICO_PORT_MIN`]) and the
// [`AplicacaoSpec::port_for_destination`] resolver (which reads
// through [`Entrada::port`] to emit the per-destination
// `HTTPRoute.backendRefs[0].port` scalar) must both key off the
// lifted accessor, so any future rebrand on the typed slot's
// reader shape lands at exactly one place. Pins the two-site
// coherence by exercising a below-floor port through validate
// (which must reject) and a validated in-accept-set port through
// port_for_destination (which must emit the same value the
// accessor returns).
let mut spec = three_member_spec();
if let Some(e) = spec.entrada.as_mut() {
e.port = 0;
}
assert_eq!(
spec.validate().unwrap_err(),
AplicacaoError::EntradaPortZero,
"validate must reject `:entrada :port 0` through the lifted \
Entrada::port accessor — port zero lies below \
SERVICO_PORT_MIN and the validator routes through port() \
to name the floor",
);
for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, 8443u16] {
let mut spec = three_member_spec();
if let Some(e) = spec.entrada.as_mut() {
e.port = port;
}
spec.validate().expect(
"entrada with in-accept-set :port must validate — the \
structural-floor gate reads through Entrada::port",
);
let entrada_ref = spec.entrada().expect(":entrada present");
assert_eq!(
spec.port_for_destination(entrada_ref.destination()),
entrada_ref.port(),
"port_for_destination(entrada.destination()) must equal \
entrada.port() — the two consumers of the per-:entrada \
L4-port axis (validator, per-destination resolver) both \
route through Entrada::port",
);
}
}
#[test]
fn wit_contract_source_returns_de_byte_equal_across_permutations() {
// The canonical caller-Servico-scalar pin: [`WitContract::source`]
// must return the `:contratos :de` field byte-for-byte, borrowed
// from the typed slot's own [`String`] storage. Peer of the
// sibling `destination_returns_entrada_para_byte_equal` pin on
// the per-`:entrada` axis — same "the substrate-primitive
// accessor must byte-equal the raw field access verbatim across
// every author-declared value" discipline extended to the
// per-`:contratos` caller arm. Pins against a future silent
// detour that re-normalized the caller (an accidental
// `.to_lowercase()` — every `:contratos :de` is validated as a
// DNS-1123 label upstream via `validate_contrato_caixa`, so any
// re-normalization is redundant + a drift surface between the
// validator and the accessor), a namespace-prefix rewrite (an
// accidental `format!("{namespace}/{de}")` per-CR fully-qualified
// rewrite that didn't land on the peer axis), or a per-cluster
// suffix stamp the operator authors on one consumer without the
// other.
for de in ["cart", "checkout", "catalog", "orders-v2"] {
let c = WitContract {
de: de.into(),
para: "downstream".into(),
wit: "wasi:http/proxy".into(),
endpoint: Some("/lookup".into()),
subject: None,
slot: None,
};
assert_eq!(
c.source(),
de,
"WitContract::source must return :contratos :de verbatim \
(got {:?}, expected {de:?})",
c.source(),
);
assert_eq!(
c.source(),
c.de.as_str(),
"WitContract::source must byte-equal the .de field access",
);
}
}
#[test]
fn wit_contract_source_borrows_from_de_storage() {
// The borrow-not-copy pin: [`WitContract::source`] must return a
// `&str` slice that borrows from the typed slot's own [`String`]
// storage — same-address invariant with `c.de.as_str()`. Pins
// against a future silent detour that allocated a fresh `String`
// (`self.de.clone()` in the body would type-check but silently
// drop the borrow, and every downstream consumer that assumed
// the returned slice outlives `&self` would break on a stale-
// reference use-after-free). Peer of the sibling
// `destination_borrows_from_entrada_para_storage` on the
// per-`:entrada` axis.
let c = WitContract {
de: "cart".into(),
para: "catalog".into(),
wit: "wasi:http/proxy".into(),
endpoint: Some("/lookup".into()),
subject: None,
slot: None,
};
let src = c.source();
let de_slice = c.de.as_str();
assert_eq!(
src.as_ptr(),
de_slice.as_ptr(),
"WitContract::source must borrow from the .de String's \
backing storage — a fresh allocation here means the \
accessor no longer names the substrate-primitive typed \
dispatch and every downstream consumer would silently \
carry a detached copy",
);
assert_eq!(
src.len(),
de_slice.len(),
"WitContract::source and .de.as_str() must byte-equal in \
length as well as in address",
);
}
#[test]
fn wit_contract_destination_returns_para_byte_equal_across_permutations() {
// The canonical callee-Servico-scalar pin: [`WitContract::destination`]
// must return the `:contratos :para` field byte-for-byte,
// borrowed from the typed slot's own [`String`] storage. Peer of
// the sibling `destination_returns_entrada_para_byte_equal` on
// the per-`:entrada` axis — both accessors name "the destination-
// Servico byte-string" concept on their respective mesh-slot
// atoms (per-ingress apex vs. per-typed-edge callee) and both
// must project the underlying `.para` field verbatim so every
// downstream renderer that composes them with peer accessors
// (e.g. `spec.port_for_destination(c.destination())` at the CNP
// per-edge L4 port emit site) reads the same byte-string the
// author declared.
for para in ["catalog", "payment", "orders", "inventory-v3"] {
let c = WitContract {
de: "cart".into(),
para: para.into(),
wit: "wasi:http/proxy".into(),
endpoint: Some("/lookup".into()),
subject: None,
slot: None,
};
assert_eq!(
c.destination(),
para,
"WitContract::destination must return :contratos :para \
verbatim (got {:?}, expected {para:?})",
c.destination(),
);
assert_eq!(
c.destination(),
c.para.as_str(),
"WitContract::destination must byte-equal the .para \
field access",
);
}
}
#[test]
fn wit_contract_destination_borrows_from_para_storage() {
// The borrow-not-copy pin: [`WitContract::destination`] must
// return a `&str` slice that borrows from the typed slot's own
// [`String`] storage — same-address invariant with
// `c.para.as_str()`. Peer of the sibling
// `destination_borrows_from_entrada_para_storage` on the
// per-`:entrada` axis.
let c = WitContract {
de: "cart".into(),
para: "catalog".into(),
wit: "wasi:http/proxy".into(),
endpoint: Some("/lookup".into()),
subject: None,
slot: None,
};
let dest = c.destination();
let para_slice = c.para.as_str();
assert_eq!(
dest.as_ptr(),
para_slice.as_ptr(),
"WitContract::destination must borrow from the .para \
String's backing storage — a fresh allocation here means \
the accessor no longer names the substrate-primitive typed \
dispatch and every downstream consumer would silently \
carry a detached copy",
);
assert_eq!(
dest.len(),
para_slice.len(),
"WitContract::destination and .para.as_str() must byte-equal \
in length as well as in address",
);
}
#[test]
fn wit_contract_world_ref_returns_wit_byte_equal_across_permutations() {
// The canonical per-`:contratos` WIT-world-reference scalar pin:
// [`WitContract::world_ref`] must return the `:contratos :wit`
// field byte-for-byte, borrowed from the typed slot's own
// [`String`] storage. Sibling of the peer per-`:contratos`
// [`WitContract::source`] / [`WitContract::destination`]
// (7f0fd43), per-`:entrada` [`Entrada::hostname`] /
// [`Entrada::destination`] (11f3dfe / 6db982c), per-`:membros`
// [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf /
// a40b0e3) pins on the mesh-slot-atom scalar-value axes — same
// "the substrate-primitive accessor must byte-equal the raw
// field access verbatim across every author-declared value"
// discipline extended to the per-`:contratos` WIT-world arm.
// Pins against a future silent detour that re-canonicalized the
// WIT world reference (an accidental `.to_lowercase()` pass that
// collapsed `WASI:HTTP/proxy` — every `:contratos :wit` past
// [`WitContract::target`]'s [`crate::render::is_wit_world_ref`]
// gate is already lowercase-prefixed so any re-normalization is
// redundant + a drift surface between the validator and the
// accessor), an M4-promotion-shape rewrite that formatted a
// typed WIT-world enum through [`Display`] and silently drifted
// the printer output from the source `caixa.lisp`, or a per-
// cluster WIT-alias rewrite that didn't land on the peer field-
// access sites. Five values sweep the shape-dispatch accept-set
// the peer [`wit_shape_matches`] combinator admits (HTTP `wasi:`
// / HTTP `http:` / PubSub `nats:` / PubSub `kafka:` / Store
// `wasi:keyvalue/`).
for (wit, endpoint, subject, slot) in [
("wasi:http/proxy", Some("/lookup"), None, None),
("http:proxy", Some("/health"), None, None),
("nats:pub-sub", None, Some("orders.paid"), None),
("kafka:events", None, Some("checkout-events"), None),
("wasi:keyvalue/store", None, None, Some("carts/{cart_id}")),
] {
let c = WitContract {
de: "cart".into(),
para: "downstream".into(),
wit: wit.into(),
endpoint: endpoint.map(str::to_string),
subject: subject.map(str::to_string),
slot: slot.map(str::to_string),
};
assert_eq!(
c.world_ref(),
wit,
"WitContract::world_ref must return :contratos :wit \
verbatim (got {:?}, expected {wit:?})",
c.world_ref(),
);
assert_eq!(
c.world_ref(),
c.wit.as_str(),
"WitContract::world_ref must byte-equal the .wit field \
access",
);
}
}
#[test]
fn wit_contract_world_ref_borrows_from_wit_storage() {
// The borrow-not-copy pin: [`WitContract::world_ref`] must
// return a `&str` slice that borrows from the typed slot's own
// [`String`] storage — same-address invariant with
// `c.wit.as_str()`. Pins against a future silent detour that
// allocated a fresh `String` (`self.wit.clone()` in the body
// would type-check but silently drop the borrow, and every
// downstream consumer that assumed the returned slice outlives
// `&self` would break on a stale-reference use-after-free — the
// dedup-key `&str`-tuple at [`AplicacaoSpec::validate`]'s
// duplicate-`:contratos` gate, the per-shape `wit_shape_is_*`
// predicates' `&str` arg the peer [`is_http`][WitContract::is_http]
// / [`is_pubsub`][WitContract::is_pubsub] /
// [`is_store`][WitContract::is_store] methods route through —
// each borrow from the WitContract's own storage and each would
// silently misbehave if this accessor produced a detached copy).
// Peer of the sibling per-`:contratos` [`WitContract::source`] /
// [`WitContract::destination`] and per-`:entrada`
// [`Entrada::destination`] / [`Entrada::hostname`] and
// per-`:membros` [`Membro::nome`] / [`Membro::versao_requirement`]
// borrow-invariant pins on the mesh-slot-atom scalar-value axes.
let c = WitContract {
de: "cart".into(),
para: "catalog".into(),
wit: "wasi:http/proxy".into(),
endpoint: Some("/lookup".into()),
subject: None,
slot: None,
};
let world = c.world_ref();
let wit_slice = c.wit.as_str();
assert_eq!(
world.as_ptr(),
wit_slice.as_ptr(),
"WitContract::world_ref must borrow from the .wit String's \
backing storage — a fresh allocation here means the \
accessor no longer names the substrate-primitive typed \
dispatch and every downstream consumer would silently carry \
a detached copy",
);
assert_eq!(
world.len(),
wit_slice.len(),
"WitContract::world_ref and .wit.as_str() must byte-equal in \
length as well as in address",
);
}
#[test]
fn wit_contract_source_destination_world_ref_project_de_para_wit_triple() {
// Sibling-triple invariant pin composing all three per-`:contratos`
// substrate-primitive typed dispatches — [`WitContract::source`]
// (7f0fd43), [`WitContract::destination`] (7f0fd43), and
// [`WitContract::world_ref`] — at the joint
// `(source(), destination(), world_ref())` call shape every
// renderer that fans on per-edge caller-callee-shape identity
// keys off. The invariant, evaluated per-contract:
//
// (c.source(), c.destination(), c.world_ref())
// == (c.de.as_str(), c.para.as_str(), c.wit.as_str())
//
// Closes the last unlifted per-`:contratos` scalar axis — every
// downstream consumer that reads the triple now routes through
// exactly three typed dispatches on the substrate primitive,
// not two typed + one open-coded field access. A future refactor
// that silently split any one accessor's projection (an
// accidental `world_ref()` M4-typed-WIT-enum `Display` re-
// canonicalization that didn't reach the peer `source`/
// `destination` arms, an accidental `source()` per-cluster
// caller-alias rewrite that didn't land on the `world_ref` peer)
// surfaces at caixa-core build time. Peer of the sibling per-
// `:membros` `(nome(), versao_requirement())` (a40b0e3) and
// per-`:entrada` `(hostname(), destination())` (6db982c /
// 11f3dfe) pair invariants on the mesh-slot-atom scalar-value
// axes, extended to the per-`:contratos` triple.
for (de, para, wit, endpoint, subject, slot) in [
(
"cart",
"catalog",
"wasi:http/proxy",
Some("/lookup"),
None,
None,
),
(
"checkout",
"orders",
"nats:pub-sub",
None,
Some("orders.paid"),
None,
),
(
"cart",
"kv",
"wasi:keyvalue/store",
None,
None,
Some("carts/{cart_id}"),
),
(
"orders-v2",
"inventory-v3",
"http:proxy",
Some("/reserve"),
None,
None,
),
] {
let c = WitContract {
de: de.into(),
para: para.into(),
wit: wit.into(),
endpoint: endpoint.map(str::to_string),
subject: subject.map(str::to_string),
slot: slot.map(str::to_string),
};
assert_eq!(
(c.source(), c.destination(), c.world_ref()),
(c.de.as_str(), c.para.as_str(), c.wit.as_str()),
"(WitContract::source, ::destination, ::world_ref) must \
project (.de, .para, .wit) verbatim across every author-\
declared triple (got ({:?}, {:?}, {:?}), expected \
({de:?}, {para:?}, {wit:?}))",
c.source(),
c.destination(),
c.world_ref(),
);
}
}
#[test]
fn wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations() {
// The canonical per-`:contratos` owned-form caller-callee-pair
// pin: [`WitContract::edge_pair`] must return the
// `(source(), destination())` tuple in owned form byte-for-byte,
// projected through the lifted [`WitContract::source`] /
// [`WitContract::destination`] scalar accessors. Pins the
// composite-projection invariant on the per-`:contratos`
// mesh-slot atom — every author-declared `(de, para)` pair must
// round-trip verbatim through the substrate primitive's typed
// dispatch, so the nine [`AplicacaoError`] diagnostic-
// construction sites the accessor now feeds
// ([`AplicacaoError::EmptyWit`],
// [`AplicacaoError::ContratoEndpointEmpty`],
// [`AplicacaoError::ContratoEndpointNotAbsolute`],
// [`AplicacaoError::ContratoEndpointInvalid`],
// [`AplicacaoError::ContratoSubjectEmpty`],
// [`AplicacaoError::ContratoSubjectInvalid`],
// [`AplicacaoError::ContratoSlotEmpty`],
// [`AplicacaoError::ContratoSlotInvalid`],
// [`AplicacaoError::ContratoDuplicate`]) all read the same
// `(de, para)` label pair every author sees at the source
// `caixa.lisp`. Pins against a future silent detour that swapped
// the `.0` / `.1` arms (an accidental `(destination(),
// source())` re-order in the body would silently invert every
// downstream diagnostic's `de:` / `para:` label pair, silently
// reversing the direction of every operator-facing typed error
// arrow), a fresh-allocation shape drift (an accidental
// `.to_string()` on one arm but not the other would leave the
// owned/borrowed pair mismatched vs. the sibling `source()` /
// `destination()` returns), or an M4 per-cluster caller/callee-
// alias rewrite that landed on `source()` without reaching
// `destination()` (or vice versa). Peer of the sibling per-
// `:contratos` `(source, destination, world_ref)` triple
// pin above on the mesh-slot-atom scalar-value axes, extended
// to the owned-form pair-projection axis.
for (de, para, wit, endpoint, subject, slot) in [
(
"cart",
"catalog",
"wasi:http/proxy",
Some("/lookup"),
None,
None,
),
(
"checkout",
"orders",
"nats:pub-sub",
None,
Some("orders.paid"),
None,
),
(
"cart",
"kv",
"wasi:keyvalue/store",
None,
None,
Some("carts/{cart_id}"),
),
(
"orders-v2",
"inventory-v3",
"http:proxy",
Some("/reserve"),
None,
None,
),
] {
let c = WitContract {
de: de.into(),
para: para.into(),
wit: wit.into(),
endpoint: endpoint.map(str::to_string),
subject: subject.map(str::to_string),
slot: slot.map(str::to_string),
};
assert_eq!(
c.edge_pair(),
(de.to_string(), para.to_string()),
"WitContract::edge_pair must return (:contratos :de, \
:contratos :para) as an owned tuple verbatim (got {:?}, \
expected ({de:?}, {para:?}))",
c.edge_pair(),
);
}
}
#[test]
fn wit_contract_edge_pair_routes_through_source_destination_accessors() {
// The composition pin: [`WitContract::edge_pair`] must return
// exactly `(source().to_string(), destination().to_string())` —
// the owned form of the sibling accessor pair — so any future
// refactor that silently re-authored the caller-arm / callee-arm
// projection to bypass the lifted scalar accessors (an accidental
// `(self.de.clone(), self.para.clone())` regression back to the
// raw field-access shape, an M4-typed-caller-enum `Display`
// re-canonicalization on `source()` that didn't reach
// `edge_pair()`, a per-cluster alias rewrite the operator lands
// on `destination()` without reaching this composite projection)
// trips at caixa-core build time. Pins the "typed dispatch
// composes with typed dispatch, not with raw field access"
// discipline every downstream diagnostic-construction site now
// routes through — a `de:` / `para:` label pair whose
// projection silently drifted off the substrate primitive's
// scalar accessors would silently split the diagnostic's self-
// locating signal from the source `caixa.lisp` author's view.
// Peer of the sibling per-`:politicas` `is_empty` /
// `validate_politicas` accessor-routing-pin family on the M3
// mesh-slot family (18575, 18739, 18918, 19140, 19371).
let c = WitContract {
de: "cart".into(),
para: "catalog".into(),
wit: "wasi:http/proxy".into(),
endpoint: Some("/lookup".into()),
subject: None,
slot: None,
};
assert_eq!(
c.edge_pair(),
(c.source().to_string(), c.destination().to_string()),
"WitContract::edge_pair must compose exactly \
(source().to_string(), destination().to_string()) — a \
bypass of either sibling accessor here would silently \
decouple the composite-projection axis from the \
substrate-primitive scalar accessors every downstream \
consumer routes through",
);
}
#[test]
fn wit_contract_edge_triple_returns_source_destination_world_ref_owned_triple_across_permutations()
{
// The canonical per-`:contratos` owned-form
// caller-callee-world-ref-triple pin:
// [`WitContract::edge_triple`] must return the
// `(source(), destination(), world_ref())` tuple in owned form
// byte-for-byte, projected through the lifted
// [`WitContract::source`] / [`WitContract::destination`] /
// [`WitContract::world_ref`] scalar accessors. Pins the
// composite-projection invariant on the per-`:contratos`
// mesh-slot atom — every author-declared `(de, para, wit)`
// triple must round-trip verbatim through the substrate
// primitive's typed dispatch, so the nine
// [`AplicacaoError`] diagnostic-construction sites the
// accessor now feeds (the [`WitTarget`]-dispatch's eight
// wrong-target / missing-target / invalid-wit / capability-
// with-payload arms in [`WitContract::target`], plus the
// paired duplicate-gate [`AplicacaoError::ContratoDuplicate`]
// diagnostic constructor in [`AplicacaoSpec::validate`]) all
// read the same `(de, para, wit)` triple every author sees at
// the source `caixa.lisp`. Pins against a future silent
// detour that swapped any two arms (an accidental `(destination(),
// source(), world_ref())` re-order in the body would silently
// invert every downstream diagnostic's `de:` / `para:` label
// pair, silently reversing the direction of every operator-
// facing typed error arrow), a fresh-allocation shape drift
// (an accidental `.to_string()` skipped on one arm would leave
// the owned/borrowed triple mismatched vs. the sibling
// `source()` / `destination()` / `world_ref()` returns), or an
// M4 per-cluster caller/callee-alias rewrite / per-CR world-ref
// canonicalization pass that landed on one accessor without
// reaching the peers. Peer of the sibling per-`:contratos`
// caller-callee-pair
// [`tests::wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations`]
// pin on the mesh-slot-atom composite-projection axis,
// extended to the triple-projection axis.
for (de, para, wit, endpoint, subject, slot) in [
(
"cart",
"catalog",
"wasi:http/proxy",
Some("/lookup"),
None,
None,
),
(
"checkout",
"orders",
"nats:pub-sub",
None,
Some("orders.paid"),
None,
),
(
"cart",
"kv",
"wasi:keyvalue/store",
None,
None,
Some("carts/{cart_id}"),
),
(
"orders-v2",
"inventory-v3",
"http:proxy",
Some("/reserve"),
None,
None,
),
] {
let c = WitContract {
de: de.into(),
para: para.into(),
wit: wit.into(),
endpoint: endpoint.map(str::to_string),
subject: subject.map(str::to_string),
slot: slot.map(str::to_string),
};
assert_eq!(
c.edge_triple(),
(de.to_string(), para.to_string(), wit.to_string()),
"WitContract::edge_triple must return (:contratos :de, \
:contratos :para, :contratos :wit) as an owned triple \
verbatim (got {:?}, expected ({de:?}, {para:?}, {wit:?}))",
c.edge_triple(),
);
}
}
#[test]
fn wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors() {
// The composition pin: [`WitContract::edge_triple`] must return
// exactly `(source().to_string(), destination().to_string(),
// world_ref().to_string())` — the owned form of the sibling
// scalar-accessor triple — so any future refactor that silently
// re-authored one arm's projection to bypass the lifted scalar
// accessors (an accidental `(self.de.clone(), self.para.clone(),
// self.wit.clone())` regression back to the raw field-access
// shape the internal `edge` closure and the ContratoDuplicate
// diagnostic both carried before this lift landed, an
// M4-typed-caller-enum `Display` re-canonicalization on
// `source()` that didn't reach `edge_triple()`, a per-cluster
// alias rewrite the operator lands on `destination()` /
// `world_ref()` without reaching this composite projection)
// trips at caixa-core build time. Pins the "typed dispatch
// composes with typed dispatch, not with raw field access"
// discipline every downstream diagnostic-construction site now
// routes through — a `de:` / `para:` / `wit:` triple whose
// projection silently drifted off the substrate primitive's
// scalar accessors would silently split the diagnostic's self-
// locating signal from the source `caixa.lisp` author's view.
// Peer of the sibling per-`:contratos` edge_pair composition-
// pin above on the mesh-slot-atom composite-projection axis.
let c = WitContract {
de: "cart".into(),
para: "catalog".into(),
wit: "wasi:http/proxy".into(),
endpoint: Some("/lookup".into()),
subject: None,
slot: None,
};
assert_eq!(
c.edge_triple(),
(
c.source().to_string(),
c.destination().to_string(),
c.world_ref().to_string(),
),
"WitContract::edge_triple must compose exactly \
(source().to_string(), destination().to_string(), \
world_ref().to_string()) — a bypass of any sibling accessor \
here would silently decouple the composite-projection axis \
from the substrate-primitive scalar accessors every \
downstream consumer routes through",
);
}
#[test]
fn wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple() {
// The canonical semantics-pin: [`WitContract::edge_triple`] must
// project the full `(de, para, wit)` identity of a `:contratos`
// edge — the sub-triple every triple-carrying
// [`AplicacaoError::Contrato*`] diagnostic weaves into its
// author-facing `de:` / `para:` / `wit:` fields (wrong-target,
// missing-target, capability-with-payload, invalid-wit, and the
// duplicate-gate). Rejects a drift in shape (an accidental
// silent detour that returned a `(de, para)` pair or added an
// extra field to the tuple, e.g. `(de, para, wit, endpoint)`,
// would trip here because the return type would no longer
// pattern-match the eight `let (de, para, wit) = edge();`
// destructures the [`WitContract::target`] dispatch feeds off
// + the paired duplicate-gate `let (de, para, wit) =
// c.edge_triple();` destructure in
// [`AplicacaoSpec::validate`]). Peer of the sibling per-
// `:contratos` caller-callee-pair pin above extended to the
// triple projection surface: closes the "one composite
// accessor per typed diagnostic-construction sub-tuple"
// discipline on the per-`:contratos` mesh-slot-atom axis.
let c = WitContract {
de: "checkout".into(),
para: "orders".into(),
wit: "nats:pub-sub".into(),
endpoint: None,
subject: Some("orders.paid".into()),
slot: None,
};
let (de, para, wit) = c.edge_triple();
assert_eq!(de, "checkout");
assert_eq!(para, "orders");
assert_eq!(wit, "nats:pub-sub");
}
#[test]
fn wit_contract_identity_routes_through_source_destination_world_ref_endpoint_subject_slot_accessors()
{
// The composition pin: [`WitContract::identity`] must return
// exactly `(source(), destination(), world_ref(), endpoint(),
// subject(), slot())` — the borrowed form of the six-scalar-
// accessor identity axis. Any future refactor that silently
// re-authored one arm's projection to bypass a scalar accessor
// (a `self.de.as_str()` regression back to raw field access on
// any of the three required arms, a `self.endpoint.as_deref()`
// regression on any of the three optional arms, an M4 per-
// cluster caller/callee-alias rewrite the operator lands on
// `source()` / `destination()` without reaching this composite
// projection) trips at caixa-core build time. Sweeps four
// permutations of the WIT-shape × payload lattice — HTTP with
// endpoint, pub-sub with subject, store with slot, payload-less
// capability — so every payload arm is exercised. Peer of the
// sibling per-`:contratos`
// `wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`
// composition pin on the mesh-slot-atom composite-projection
// axis; extends the discipline from the (de, para, wit) prefix
// onto the full-identity axis carrying the three payload arms.
for (de, para, wit, endpoint, subject, slot) in [
(
"cart",
"catalog",
"wasi:http/proxy",
Some("/lookup"),
None,
None,
),
(
"checkout",
"orders",
"nats:pub-sub",
None,
Some("orders.paid"),
None,
),
(
"cart",
"kv",
"wasi:keyvalue/store",
None,
None,
Some("carts/{cart_id}"),
),
("audit", "sink", "wasi:logging", None, None, None),
] {
let c = WitContract {
de: de.into(),
para: para.into(),
wit: wit.into(),
endpoint: endpoint.map(str::to_owned),
subject: subject.map(str::to_owned),
slot: slot.map(str::to_owned),
};
assert_eq!(
c.identity(),
(
c.source(),
c.destination(),
c.world_ref(),
c.endpoint(),
c.subject(),
c.slot(),
),
"WitContract::identity must compose exactly \
(source(), destination(), world_ref(), endpoint(), \
subject(), slot()) — a bypass of any sibling accessor \
here would silently decouple the identity-projection \
axis from the substrate-primitive scalar accessors \
every dedup-key consumer routes through",
);
}
}
#[test]
fn wit_contract_identity_projects_full_typed_edge_dedup_key_across_payload_shapes() {
// The canonical semantics-pin: [`WitContract::identity`] must
// project the six-axis (de, para, wit, endpoint, subject, slot)
// dedup key the [`AplicacaoSpec::validate`] duplicate-`:contratos`
// gate keys off — two `WitContract`s that agree on all six axes
// are the same typed edge declared twice, the graph-edge
// analogue of duplicate `:membros` / `:placement :clusters` /
// `:entrada :paths` entries. Rejects a shape drift (an
// accidental silent detour that returned a prefix tuple or
// added an extra field) by pattern-matching the six-arm shape.
// Peer of the sibling per-`:contratos`
// `wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple`
// pin extended from the (de, para, wit) prefix onto the full
// six-axis identity that the dedup key rides.
let c = WitContract {
de: "cart".into(),
para: "catalog".into(),
wit: "wasi:http/proxy".into(),
endpoint: Some("/products/:id".into()),
subject: None,
slot: None,
};
let (de, para, wit, endpoint, subject, slot) = c.identity();
assert_eq!(de, "cart");
assert_eq!(para, "catalog");
assert_eq!(wit, "wasi:http/proxy");
assert_eq!(endpoint, Some("/products/:id"));
assert_eq!(subject, None);
assert_eq!(slot, None);
// Two byte-identical contracts must produce equal identities —
// the dedup key's foundational invariant.
let c2 = c.clone();
assert_eq!(c.identity(), c2.identity());
// Any change on any of the six axes must break the identity —
// sweeps by mutating one axis at a time.
let mut mutated = c.clone();
mutated.de = "search".into();
assert_ne!(c.identity(), mutated.identity(), "de axis must partition");
let mut mutated = c.clone();
mutated.para = "warehouse".into();
assert_ne!(c.identity(), mutated.identity(), "para axis must partition");
let mut mutated = c.clone();
mutated.wit = "http:legacy".into();
assert_ne!(c.identity(), mutated.identity(), "wit axis must partition");
let mut mutated = c.clone();
mutated.endpoint = Some("/search".into());
assert_ne!(
c.identity(),
mutated.identity(),
"endpoint axis must partition"
);
let mut mutated = c.clone();
mutated.subject = Some("orders.paid".into());
assert_ne!(
c.identity(),
mutated.identity(),
"subject axis must partition"
);
let mut mutated = c;
mutated.slot = Some("carts/{id}".into());
assert_ne!(mutated.identity().5, None, "slot axis must partition");
}
#[test]
fn wit_contract_is_self_loop_returns_true_on_matching_endpoints_across_permutations() {
// The canonical per-`:contratos` structural-self-edge pin:
// [`WitContract::is_self_loop`] must return `true` when the
// `:de` and `:para` fields agree byte-for-byte, across every
// WIT-shape variant the per-edge shape family carries. Pins
// the shape-agnostic identity-space partition the
// [`AplicacaoSpec::validate`] self-edge gate at
// caixa-core/src/aplicacao.rs:5559 fires against — all four
// [`WitTarget`] arms (HTTP / PubSub / Store / Capability) fall
// under the same one predicate. Four permutations sweep the
// accept-set: HTTP with endpoint, pub-sub with subject, KV
// store with slot, and payload-less capability.
for (nome, wit, endpoint, subject, slot) in [
("cart", "wasi:http/proxy", Some("/lookup"), None, None),
("checkout", "nats:pub-sub", None, Some("orders.paid"), None),
(
"kv",
"wasi:keyvalue/store",
None,
None,
Some("carts/{cart_id}"),
),
("audit", "wasi:logging", None, None, None),
] {
let c = WitContract {
de: nome.into(),
para: nome.into(),
wit: wit.into(),
endpoint: endpoint.map(str::to_string),
subject: subject.map(str::to_string),
slot: slot.map(str::to_string),
};
assert!(
c.is_self_loop(),
"WitContract::is_self_loop must return true when \
:contratos :de == :contratos :para (got false on \
{nome:?} under {wit:?})",
);
}
}
#[test]
fn wit_contract_is_self_loop_returns_false_on_distinct_endpoints_across_permutations() {
// The complement pin: [`WitContract::is_self_loop`] must return
// `false` on every well-shaped inter-Servico contract (the
// author-intended `:contratos` shape MESH-COMPOSITION §III.1
// names — "Servico A calls Servico B" between two distinct
// graph nodes). Pins against a future silent detour that
// inverted the predicate (an accidental `!= ` swap for `==`
// would silently reject every legitimate inter-Servico edge
// and admit every self-edge — the exact inversion of the
// author-intended shape). Four permutations sweep the same
// WIT-shape accept-set the sibling positive-arm test carries.
for (de, para, wit, endpoint, subject, slot) in [
(
"cart",
"catalog",
"wasi:http/proxy",
Some("/lookup"),
None,
None,
),
(
"checkout",
"orders",
"nats:pub-sub",
None,
Some("orders.paid"),
None,
),
(
"cart",
"kv",
"wasi:keyvalue/store",
None,
None,
Some("carts/{cart_id}"),
),
("audit", "sink", "wasi:logging", None, None, None),
] {
let c = WitContract {
de: de.into(),
para: para.into(),
wit: wit.into(),
endpoint: endpoint.map(str::to_string),
subject: subject.map(str::to_string),
slot: slot.map(str::to_string),
};
assert!(
!c.is_self_loop(),
"WitContract::is_self_loop must return false when \
:contratos :de differs from :contratos :para (got true \
on {de:?} → {para:?} under {wit:?})",
);
}
}
#[test]
fn wit_contract_is_self_loop_routes_through_source_destination_accessors() {
// The composition pin: [`WitContract::is_self_loop`] must
// resolve to exactly `self.source() == self.destination()` —
// the equality probe of the sibling scalar-accessor pair — so
// any future refactor that silently re-authored the predicate
// to bypass the lifted scalar accessors (an accidental
// `self.de == self.para` regression back to the raw field-
// access shape, an M4-typed-caller-enum identity-comparison
// rule that landed on `source()` without reaching
// `destination()`, a per-cluster alias rewrite the operator
// pins on `destination()` without reaching this predicate)
// trips at caixa-core build time. Pins the "typed dispatch
// composes with typed dispatch, not with raw field access"
// discipline the sibling [`WitContract::edge_pair`] /
// [`WitContract::edge_triple`] composite-projection accessors
// already carry, extended onto the per-edge endpoint-equality
// predicate axis. Positive and complement arms both fire.
let self_edge = WitContract {
de: "cart".into(),
para: "cart".into(),
wit: "wasi:http/proxy".into(),
endpoint: Some("/lookup".into()),
subject: None,
slot: None,
};
assert_eq!(
self_edge.is_self_loop(),
self_edge.source() == self_edge.destination(),
"WitContract::is_self_loop must compose exactly \
`source() == destination()` — a bypass of either sibling \
accessor here would silently decouple the endpoint-\
equality predicate from the substrate-primitive scalar \
accessors every downstream consumer routes through",
);
let inter_edge = WitContract {
de: "cart".into(),
para: "catalog".into(),
wit: "wasi:http/proxy".into(),
endpoint: Some("/lookup".into()),
subject: None,
slot: None,
};
assert_eq!(
inter_edge.is_self_loop(),
inter_edge.source() == inter_edge.destination(),
"WitContract::is_self_loop must compose exactly \
`source() == destination()` on the complement arm too",
);
}
#[test]
fn wit_contract_target_wit_shape_gate_routes_through_world_ref_accessor() {
// The composition pin: [`WitContract::target`]'s invalid-wit
// value-shape gate must feed the reason string through the
// lifted [`WitContract::world_ref`] scalar accessor — the same
// typed dispatch on the substrate primitive every peer
// per-`:contratos` payload-carrier extraction in the same
// method body already routes through
// ([`WitContract::endpoint`] on the HTTP-arm target extraction,
// [`WitContract::subject`] on the pub-sub-arm target extraction,
// [`WitContract::slot`] on the store-arm target extraction) and
// every peer composite-projection accessor
// ([`WitContract::edge_pair`], [`WitContract::edge_triple`],
// [`WitContract::identity`]) already composes from. Any future
// refactor that silently re-authored the gate to bypass the
// lifted accessor (an accidental `&self.wit` regression back to
// the raw field-access shape, an M4-typed-`WitWorld` `Display`
// re-canonicalization on `world_ref()` that didn't reach this
// gate, a per-CR lowercasing canonicalization pass the M4
// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
// per-tenant that lands on `world_ref()` without reaching this
// gate) would silently split the invalid-wit diagnostic reason
// from the substrate-primitive projection every downstream
// consumer routes through. Same "typed dispatch composes with
// typed dispatch, not with raw field access" discipline the
// sibling
// [`wit_contract_is_self_loop_routes_through_source_destination_accessors`]
// pin already carries on the endpoint-equality predicate axis,
// extended onto the invalid-wit value-shape gate axis inside
// the same [`WitContract::target`] body. Closes the last
// unlifted raw-field-access site inside `impl WitContract`.
//
// The fixture carries `:wit "WASI:HTTP/proxy"` — the canonical
// uppercase-typo footgun the pre-c4213a4 shape silently demoted
// to a capability-only edge; the value-shape gate rejects it
// through [`crate::render::is_wit_world_ref`] on the substrate
// primitive's ASCII-lowercase-only accept-set, with a
// parser-shaped reason string the test asserts round-trips
// byte-for-byte between the direct-dispatch call (through the
// predicate on the accessor's projection) and the
// [`WitContract::target`] gate's produced reason field.
let c = WitContract {
de: "cart".into(),
para: "catalog".into(),
wit: "WASI:HTTP/proxy".into(),
endpoint: Some("/lookup".into()),
subject: None,
slot: None,
};
let err = c.target().unwrap_err();
let AplicacaoError::ContratoWitInvalid {
ref de,
ref para,
ref wit,
ref reason,
} = err
else {
panic!("expected ContratoWitInvalid, got {err:?}");
};
assert_eq!(de, "cart");
assert_eq!(para, "catalog");
assert_eq!(wit, "WASI:HTTP/proxy");
let expected_reason = crate::render::is_wit_world_ref(c.world_ref()).unwrap_err();
assert_eq!(
*reason, expected_reason,
"WitContract::target's invalid-wit value-shape gate reason \
must compose exactly is_wit_world_ref(self.world_ref()) — \
a bypass here (e.g. a raw `&self.wit` field-access \
regression, or a divergent predicate on a different \
projection) would silently decouple the invalid-wit \
diagnostic's reason field from the substrate-primitive \
scalar accessor every peer per-`:contratos` extraction in \
the same method body already routes through",
);
}
#[test]
fn wit_contract_is_self_loop_predicate_is_const_fn() {
// Fail-before-pass-after pin on the [`WitContract::is_self_loop`]
// caller-callee identity-space predicate's `const`-eval-surface
// posture. The wrapper below dispatches through
// [`WitContract::is_self_loop`] and is well-formed only when the
// callee is itself `pub const fn` — any future accidental
// downgrade to non-`const` fails the wrapper at caixa-core build
// time with E0015 (`cannot call non-const method`), strictly
// stronger than a runtime `assert!` and strictly stronger than a
// module-scope `const _: () = assert!(…)` pin (the type's
// `String` / `Option<String>` carriers rule out `const`-context
// value construction; the `const fn` wrapper is the load-bearing
// shape that side-steps the destructor-in-const restriction on
// the value axis while still pinning the `const`-fn posture on
// the callee — mirror of the sibling
// [`wit_contract_pre_projection_accessor_family_is_const_fn`]
// (279823b) and
// [`wit_contract_identity_projection_accessor_is_const_fn`]
// (1ab648c) pins' discipline verbatim on the peer scalar-
// accessor and composite-projection surfaces). Closes the last
// unlifted per-`:contratos` shape/identity predicate on the
// const-eval surface — the peer WIT-shape-partition family
// [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
// [`WitContract::is_store`] / [`WitContract::is_capability`]
// already carried the `pub const fn` posture on the peer
// WIT-world-ref classifier axis (d46420c / 84c2325 / 279823b);
// this pin extends the same posture onto the caller-callee
// identity-space partition. Sweeps every WIT-shape arm on both
// the equal-endpoints (self-edge) and distinct-endpoints
// (inter-edge) arms of the identity-space partition, plus one
// same-length distinct-byte pair to pin the mid-loop `!=` arm
// past the leading length-mismatch shortcut.
const fn is_self_loop_via_const_fn(c: &WitContract) -> bool {
c.is_self_loop()
}
let mk = |de: &str, para: &str, wit: &str| WitContract {
de: de.into(),
para: para.into(),
wit: wit.into(),
endpoint: None,
subject: None,
slot: None,
};
for (nome, wit) in [
("cart", "wasi:http/proxy"),
("checkout", "nats:pub-sub"),
("kv", "wasi:keyvalue/store"),
("audit", "wasi:logging"),
] {
let self_edge = mk(nome, nome, wit);
assert!(
is_self_loop_via_const_fn(&self_edge),
"self-edge {nome:?} under {wit:?}"
);
assert_eq!(
is_self_loop_via_const_fn(&self_edge),
self_edge.is_self_loop()
);
}
for (de, para, wit) in [
("cart", "catalog", "wasi:http/proxy"),
("checkout", "orders", "nats:pub-sub"),
("cart", "kv", "wasi:keyvalue/store"),
("audit", "sink", "wasi:logging"),
] {
let inter_edge = mk(de, para, wit);
assert!(
!is_self_loop_via_const_fn(&inter_edge),
"inter-edge {de:?}→{para:?} under {wit:?}",
);
assert_eq!(
is_self_loop_via_const_fn(&inter_edge),
inter_edge.is_self_loop()
);
}
// Same-length distinct-byte pair — pins the mid-loop `!=` arm
// past the leading `a.len() != b.len()` shortcut so the const-fn
// wrapper exercises every arm of the byte-slice equality loop.
let same_len_pair = mk("cart", "kart", "wasi:http/proxy");
assert!(
!is_self_loop_via_const_fn(&same_len_pair),
"same-length distinct-byte"
);
assert_eq!(
is_self_loop_via_const_fn(&same_len_pair),
same_len_pair.is_self_loop()
);
}
#[test]
fn wit_contract_endpoint_returns_endpoint_option_byte_equal_across_permutations() {
// The canonical per-`:contratos` HTTP-shaped `:endpoint`-scalar
// pin: [`WitContract::endpoint`] must return the `:contratos
// :endpoint` field byte-for-byte, borrowed from the typed slot's
// own `Option<String>` storage. Peer of the sibling
// per-`:placement` [`Placement::shard_key`] (7cd2a28) /
// [`Placement::affinity`] (74ec2d3) accessor pins on the M3
// mesh-slot `Option<String>` optional-scalar axes — same "the
// substrate-primitive accessor must byte-equal the raw field
// access verbatim across every author-declared value" discipline
// extended to the per-`:contratos` HTTP-payload-carrier arm.
// Pins against a future silent detour that re-canonicalized the
// endpoint (an accidental percent-encoding pass that didn't
// reach the peer field-access site at the dedup key, a per-CR
// fully-qualified prefix rewrite the operator authors on one
// consumer without the other, or an M4 typed-path-template
// `Display` re-canonicalization that silently drifted the
// printer output from the source `caixa.lisp`). Four values
// sweep the accept-set the [`crate::render::is_gateway_api_http_path`]
// gate upstream admits (short root-path, dashed, param-shaped,
// deep-hierarchy).
for endpoint in ["/lookup", "/api/v1/orders", "/products/:id", "/health/live"] {
let c = WitContract {
de: "cart".into(),
para: "catalog".into(),
wit: "wasi:http/proxy".into(),
endpoint: Some(endpoint.into()),
subject: None,
slot: None,
};
assert_eq!(
c.endpoint(),
Some(endpoint),
"WitContract::endpoint must return :contratos :endpoint \
verbatim (got {:?}, expected Some({endpoint:?}))",
c.endpoint(),
);
assert_eq!(
c.endpoint(),
c.endpoint.as_deref(),
"WitContract::endpoint must byte-equal the .endpoint \
field's `.as_deref()` projection",
);
}
}
#[test]
fn wit_contract_endpoint_none_when_field_is_none() {
// The absent-`:endpoint` arm of the per-`:contratos` HTTP-shaped
// payload-carrier accessor pin: when the typed slot is absent —
// the canonical shape under a non-HTTP `:wit` world per the
// [`WitContract::target`]-enforced shape ↔ target partition
// ([`WitTarget::PubSub`] carries `:subject`, [`WitTarget::Store`]
// carries `:slot`, [`WitTarget::Capability`] carries none) —
// [`WitContract::endpoint`] must return `None`. Pins against a
// future silent detour that projected the absent slot to a
// `Some("")` empty-string default (the canonical `Option<String>`
// → `String` collapse footgun the sibling M2
// [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
// emptiness predicates already guard on the peer M2 typed-slot
// surfaces), a `Some("None")` stringified-None round-trip, or a
// `Some` arm whose contents were derived from a sibling slot (an
// accidental fallback to the `:subject` / `:slot` payload that
// read the pub-sub / store payload into the endpoint axis).
// Three contracts sweep the accept-set every non-HTTP `:wit`
// world lands on — pub-sub NATS, key/value, and payload-less
// capability.
for (wit, subject, slot) in [
("nats:pub-sub", Some("orders.paid"), None),
("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
("wasi:cli/environment", None, None),
] {
let c = WitContract {
de: "cart".into(),
para: "downstream".into(),
wit: wit.into(),
endpoint: None,
subject: subject.map(str::to_string),
slot: slot.map(str::to_string),
};
assert!(
c.endpoint().is_none(),
"WitContract::endpoint must return None when the typed \
slot is absent under :wit {wit:?} (got {:?})",
c.endpoint(),
);
assert_eq!(
c.endpoint(),
c.endpoint.as_deref(),
"WitContract::endpoint must byte-equal the .endpoint \
field's `.as_deref()` projection in the absent arm",
);
}
}
#[test]
fn wit_contract_endpoint_borrows_from_endpoint_storage() {
// The borrow-not-copy pin: [`WitContract::endpoint`] must return
// an `Option<&str>` whose `Some` arm borrows from the typed
// slot's own [`String`] storage — same-address invariant with
// `c.endpoint.as_deref().unwrap()`. Pins against a future silent
// detour that allocated a fresh `String`
// (`self.endpoint.clone().map(...)` in the body would type-check
// but silently drop the borrow, and every downstream consumer
// that assumed the returned slice outlives `&self` would break
// on a stale-reference use-after-free — the [`WitContract::target`]
// Http-arm payload extraction rebinds the returned `Option<&str>`
// through `.ok_or_else(...)` and threads the `&str` payload into
// [`WitTarget::Http { endpoint: &'a str }`], the
// [`AplicacaoSpec::validate`] duplicate-`:contratos`
// [`ContratoIdentity`] dedup key threads the returned
// `Option<&str>` into the six-tuple's HTTP arm — each borrow
// from the WitContract's own storage and each would silently
// misbehave if this accessor produced a detached copy). Peer of
// the sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
// borrow-invariant pin on the M3 mesh-slot `Option<String>`-
// shaped optional-scalar axes — first extension of the
// `Option<&str>` borrow-not-copy discipline onto the
// per-`:contratos` HTTP-shaped payload-carrier axis.
let c = WitContract {
de: "cart".into(),
para: "catalog".into(),
wit: "wasi:http/proxy".into(),
endpoint: Some("/lookup".into()),
subject: None,
slot: None,
};
let ep = c.endpoint().expect("Some arm");
let storage_slice = c.endpoint.as_deref().expect("Some arm — storage side");
assert_eq!(
ep.as_ptr(),
storage_slice.as_ptr(),
"WitContract::endpoint must borrow from the .endpoint \
String's backing storage — a fresh allocation here means \
the accessor no longer names the substrate-primitive typed \
dispatch and every downstream consumer would silently \
carry a detached copy",
);
assert_eq!(
ep.len(),
storage_slice.len(),
"WitContract::endpoint and .endpoint.as_deref() must byte-\
equal in length as well as in address",
);
}
#[test]
fn wit_contract_subject_returns_subject_option_byte_equal_across_permutations() {
// The canonical per-`:contratos` pub-sub-shaped `:subject`-scalar
// pin: [`WitContract::subject`] must return the `:contratos
// :subject` field byte-for-byte, borrowed from the typed slot's
// own `Option<String>` storage. Peer of the sibling per-`:contratos`
// [`WitContract::endpoint`] (7020470) accessor pin on the M3
// mesh-slot per-`:contratos` payload-carrier `Option<String>`
// optional-scalar axis — same "the substrate-primitive accessor
// must byte-equal the raw field access verbatim across every
// author-declared value" discipline extended to the pub-sub arm.
// Pins against a future silent detour that re-canonicalized the
// subject (an accidental `.to_lowercase()` normalization that
// didn't reach the peer field-access site at the dedup key, a
// per-CR fully-qualified prefix rewrite the operator authors on
// one consumer without the other, or an M4 typed-subject-template
// `Display` re-canonicalization that silently drifted the printer
// output from the source `caixa.lisp`). Four values sweep the
// NATS accept-set every pub-sub author-declared subject lands on
// (flat token, dotted hierarchy, per-tenant prefix, wildcard).
for subject in ["events", "orders.paid", "tenant-a.orders", "orders.>"] {
let c = WitContract {
de: "cart".into(),
para: "notifier".into(),
wit: "nats:pub-sub".into(),
endpoint: None,
subject: Some(subject.into()),
slot: None,
};
assert_eq!(
c.subject(),
Some(subject),
"WitContract::subject must return :contratos :subject \
verbatim (got {:?}, expected Some({subject:?}))",
c.subject(),
);
assert_eq!(
c.subject(),
c.subject.as_deref(),
"WitContract::subject must byte-equal the .subject \
field's `.as_deref()` projection",
);
}
}
#[test]
fn wit_contract_subject_none_when_field_is_none() {
// The absent-`:subject` arm of the per-`:contratos` pub-sub-
// shaped payload-carrier accessor pin: when the typed slot is
// absent — the canonical shape under a non-pub-sub `:wit` world
// per the [`WitContract::target`]-enforced shape ↔ target
// partition ([`WitTarget::Http`] carries `:endpoint`,
// [`WitTarget::Store`] carries `:slot`, [`WitTarget::Capability`]
// carries none) — [`WitContract::subject`] must return `None`.
// Pins against a future silent detour that projected the absent
// slot to a `Some("")` empty-string default (the canonical
// `Option<String>` → `String` collapse footgun the sibling M2
// [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
// emptiness predicates already guard on the peer M2 typed-slot
// surfaces), a `Some("None")` stringified-None round-trip, or a
// `Some` arm whose contents were derived from a sibling slot (an
// accidental fallback to the `:endpoint` / `:slot` payload that
// read the HTTP / store payload into the subject axis). Three
// contracts sweep the accept-set every non-pub-sub `:wit` world
// lands on — HTTP proxy, key/value store, and payload-less
// capability.
for (wit, endpoint, slot) in [
("wasi:http/proxy", Some("/lookup"), None),
("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
("wasi:cli/environment", None, None),
] {
let c = WitContract {
de: "cart".into(),
para: "downstream".into(),
wit: wit.into(),
endpoint: endpoint.map(str::to_string),
subject: None,
slot: slot.map(str::to_string),
};
assert!(
c.subject().is_none(),
"WitContract::subject must return None when the typed \
slot is absent under :wit {wit:?} (got {:?})",
c.subject(),
);
assert_eq!(
c.subject(),
c.subject.as_deref(),
"WitContract::subject must byte-equal the .subject \
field's `.as_deref()` projection in the absent arm",
);
}
}
#[test]
fn wit_contract_subject_borrows_from_subject_storage() {
// The borrow-not-copy pin: [`WitContract::subject`] must return
// an `Option<&str>` whose `Some` arm borrows from the typed
// slot's own [`String`] storage — same-address invariant with
// `c.subject.as_deref().unwrap()`. Pins against a future silent
// detour that allocated a fresh `String`
// (`self.subject.clone().map(...)` in the body would type-check
// but silently drop the borrow, and every downstream consumer
// that assumed the returned slice outlives `&self` would break
// on a stale-reference use-after-free — the [`WitContract::target`]
// PubSub-arm payload extraction rebinds the returned
// `Option<&str>` through `.ok_or_else(...)` and threads the
// `&str` payload into [`WitTarget::PubSub { subject: &'a str }`],
// the [`AplicacaoSpec::validate`] duplicate-`:contratos`
// [`ContratoIdentity`] dedup key threads the returned
// `Option<&str>` into the six-tuple's pub-sub arm — each borrow
// from the WitContract's own storage and each would silently
// misbehave if this accessor produced a detached copy). Peer of
// the sibling per-`:contratos` [`WitContract::endpoint`] (7020470)
// borrow-invariant pin on the M3 mesh-slot `Option<String>`-
// shaped optional-scalar axis — second extension of the
// `Option<&str>` borrow-not-copy discipline onto the
// per-`:contratos` payload-carrier family, this time on the
// pub-sub arm.
let c = WitContract {
de: "cart".into(),
para: "notifier".into(),
wit: "nats:pub-sub".into(),
endpoint: None,
subject: Some("orders.paid".into()),
slot: None,
};
let sub = c.subject().expect("Some arm");
let storage_slice = c.subject.as_deref().expect("Some arm — storage side");
assert_eq!(
sub.as_ptr(),
storage_slice.as_ptr(),
"WitContract::subject must borrow from the .subject \
String's backing storage — a fresh allocation here means \
the accessor no longer names the substrate-primitive typed \
dispatch and every downstream consumer would silently \
carry a detached copy",
);
assert_eq!(
sub.len(),
storage_slice.len(),
"WitContract::subject and .subject.as_deref() must byte-\
equal in length as well as in address",
);
}
#[test]
fn wit_contract_slot_returns_slot_option_byte_equal_across_permutations() {
// The canonical per-`:contratos` key/value-store-shaped
// `:slot`-scalar pin: [`WitContract::slot`] must return the
// `:contratos :slot` field byte-for-byte, borrowed from the
// typed slot's own `Option<String>` storage. Peer of the
// sibling per-`:contratos` [`WitContract::endpoint`] (7020470) /
// [`WitContract::subject`] (90de675) accessor pins on the M3
// mesh-slot per-`:contratos` payload-carrier `Option<String>`
// optional-scalar axis — same "the substrate-primitive
// accessor must byte-equal the raw field access verbatim
// across every author-declared value" discipline extended to
// the store arm. Pins against a future silent detour that
// re-canonicalized the slot template (an accidental
// `.to_lowercase()` bucket-prefix normalization that didn't
// reach the peer field-access site at the dedup key, a per-CR
// fully-qualified prefix rewrite the operator authors on one
// consumer without the other, or an M4 typed-key-template
// `Display` re-canonicalization that silently drifted the
// printer output from the source `caixa.lisp`). Four values
// sweep the wasi:keyvalue accept-set every store-shaped
// author-declared slot lands on (flat bucket, single-param
// template, multi-param template, nested-hierarchy template).
for slot in [
"sessions",
"carts/{cart_id}",
"orders/{tenant}/{order_id}",
"cache/tenant-a/orders/{id}",
] {
let c = WitContract {
de: "cart".into(),
para: "kv".into(),
wit: "wasi:keyvalue/store".into(),
endpoint: None,
subject: None,
slot: Some(slot.into()),
};
assert_eq!(
c.slot(),
Some(slot),
"WitContract::slot must return :contratos :slot \
verbatim (got {:?}, expected Some({slot:?}))",
c.slot(),
);
assert_eq!(
c.slot(),
c.slot.as_deref(),
"WitContract::slot must byte-equal the .slot field's \
`.as_deref()` projection",
);
}
}
#[test]
fn wit_contract_slot_none_when_field_is_none() {
// The absent-`:slot` arm of the per-`:contratos` store-shaped
// payload-carrier accessor pin: when the typed slot is absent —
// the canonical shape under a non-store `:wit` world per the
// [`WitContract::target`]-enforced shape ↔ target partition
// ([`WitTarget::Http`] carries `:endpoint`, [`WitTarget::PubSub`]
// carries `:subject`, [`WitTarget::Capability`] carries none) —
// [`WitContract::slot`] must return `None`. Pins against a
// future silent detour that projected the absent slot to a
// `Some("")` empty-string default (the canonical
// `Option<String>` → `String` collapse footgun the sibling M2
// [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
// emptiness predicates already guard on the peer M2 typed-slot
// surfaces), a `Some("None")` stringified-None round-trip, or
// a `Some` arm whose contents were derived from a sibling
// slot (an accidental fallback to the `:endpoint` / `:subject`
// payload that read the HTTP / pub-sub payload into the store
// axis). Three contracts sweep the accept-set every non-store
// `:wit` world lands on — HTTP proxy, pub-sub NATS, and
// payload-less capability.
for (wit, endpoint, subject) in [
("wasi:http/proxy", Some("/lookup"), None),
("nats:pub-sub", None, Some("orders.paid")),
("wasi:cli/environment", None, None),
] {
let c = WitContract {
de: "cart".into(),
para: "downstream".into(),
wit: wit.into(),
endpoint: endpoint.map(str::to_string),
subject: subject.map(str::to_string),
slot: None,
};
assert!(
c.slot().is_none(),
"WitContract::slot must return None when the typed \
slot is absent under :wit {wit:?} (got {:?})",
c.slot(),
);
assert_eq!(
c.slot(),
c.slot.as_deref(),
"WitContract::slot must byte-equal the .slot field's \
`.as_deref()` projection in the absent arm",
);
}
}
#[test]
fn wit_contract_slot_borrows_from_slot_storage() {
// The borrow-not-copy pin: [`WitContract::slot`] must return
// an `Option<&str>` whose `Some` arm borrows from the typed
// slot's own [`String`] storage — same-address invariant with
// `c.slot.as_deref().unwrap()`. Pins against a future silent
// detour that allocated a fresh `String`
// (`self.slot.clone().map(...)` in the body would type-check
// but silently drop the borrow, and every downstream consumer
// that assumed the returned slice outlives `&self` would
// break on a stale-reference use-after-free — the
// [`WitContract::target`] Store-arm payload extraction rebinds
// the returned `Option<&str>` through `.ok_or_else(...)` and
// threads the `&str` payload into [`WitTarget::Store { slot: &'a str }`],
// the [`AplicacaoSpec::validate`] duplicate-`:contratos`
// [`ContratoIdentity`] dedup key threads the returned
// `Option<&str>` into the six-tuple's store arm — each borrow
// from the WitContract's own storage and each would silently
// misbehave if this accessor produced a detached copy). Peer
// of the sibling per-`:contratos` [`WitContract::endpoint`]
// (7020470) / [`WitContract::subject`] (90de675)
// borrow-invariant pins on the M3 mesh-slot `Option<String>`-
// shaped optional-scalar axis — third and final extension of
// the `Option<&str>` borrow-not-copy discipline onto the
// per-`:contratos` payload-carrier family, this time on the
// store arm.
let c = WitContract {
de: "cart".into(),
para: "kv".into(),
wit: "wasi:keyvalue/store".into(),
endpoint: None,
subject: None,
slot: Some("carts/{cart_id}".into()),
};
let slot = c.slot().expect("Some arm");
let storage_slice = c.slot.as_deref().expect("Some arm — storage side");
assert_eq!(
slot.as_ptr(),
storage_slice.as_ptr(),
"WitContract::slot must borrow from the .slot String's \
backing storage — a fresh allocation here means the \
accessor no longer names the substrate-primitive typed \
dispatch and every downstream consumer would silently \
carry a detached copy",
);
assert_eq!(
slot.len(),
storage_slice.len(),
"WitContract::slot and .slot.as_deref() must byte-equal \
in length as well as in address",
);
}
#[test]
fn membro_nome_returns_caixa_byte_equal_across_permutations() {
// The canonical per-`:membros` member-caixa `:nome`-scalar pin:
// [`Membro::nome`] must return the `:membros :caixa` field
// byte-for-byte, borrowed from the typed slot's own [`String`]
// storage. Peer of the sibling per-`:contratos` [`WitContract::source`]
// / [`WitContract::destination`] (7f0fd43) and per-`:entrada`
// [`Entrada::destination`] (6db982c) accessor pins on the mesh-
// slot-atom scalar-value axes — same "the substrate-primitive
// accessor must byte-equal the raw field access verbatim across
// every author-declared value" discipline extended to the
// per-`:membros` member-identity arm. Pins against a future
// silent detour that re-normalized the member identity (an
// accidental `.to_lowercase()` — every `:membros :caixa` is
// validated as a DNS-1123 label upstream via
// [`validate_membro_caixa`], so any re-normalization is
// redundant + a drift surface between the validator and the
// accessor), a namespace-prefix rewrite (an accidental
// `format!("{namespace}/{caixa}")` per-CR fully-qualified
// rewrite that didn't land on the peer axes), or a per-cluster
// alias stamp the operator authors on one consumer without the
// other. Four values sweep the accept-set the DNS-1123 gate
// upstream admits (short single-word / dashed / v-suffixed
// member names).
for name in ["cart", "checkout", "catalog", "orders-v2"] {
let m = Membro {
caixa: name.into(),
versao: "^0.1".into(),
};
assert_eq!(
m.nome(),
name,
"Membro::nome must return :membros :caixa verbatim \
(got {:?}, expected {name:?})",
m.nome(),
);
assert_eq!(
m.nome(),
m.caixa.as_str(),
"Membro::nome must byte-equal the .caixa field access",
);
}
}
#[test]
fn membro_nome_borrows_from_caixa_storage() {
// The borrow-not-copy pin: [`Membro::nome`] must return a `&str`
// slice that borrows from the typed slot's own [`String`]
// storage — same-address invariant with `m.caixa.as_str()`. Pins
// against a future silent detour that allocated a fresh `String`
// (`self.caixa.clone()` in the body would type-check but
// silently drop the borrow, and every downstream consumer that
// assumed the returned slice outlives `&self` would break on a
// stale-reference use-after-free — the `HashSet<&str>` collector
// at [`AplicacaoSpec::validate`]'s `names` seed, the
// `BTreeMap<&str, BTreeSet<&str>>` adjacency map at
// [`AplicacaoSpec::detect_sync_cycles`], the
// [`crate::render::insert_first_seen`] dedup key at
// [`AplicacaoSpec::validate_membros`] — each borrow from the
// Membro's own storage and each would silently misbehave if
// this accessor produced a detached copy). Peer of the sibling
// per-`:contratos` [`WitContract::source`] /
// [`WitContract::destination`] and per-`:entrada`
// [`Entrada::destination`] borrow-invariant pins on the mesh-
// slot-atom scalar-value axes.
let m = Membro {
caixa: "checkout".into(),
versao: "^0.1".into(),
};
let name = m.nome();
let caixa_slice = m.caixa.as_str();
assert_eq!(
name.as_ptr(),
caixa_slice.as_ptr(),
"Membro::nome must borrow from the .caixa String's backing \
storage — a fresh allocation here means the accessor no \
longer names the substrate-primitive typed dispatch and \
every downstream consumer would silently carry a detached \
copy",
);
assert_eq!(
name.len(),
caixa_slice.len(),
"Membro::nome and .caixa.as_str() must byte-equal in length \
as well as in address",
);
}
#[test]
fn membro_versao_requirement_returns_versao_byte_equal_across_permutations() {
// The canonical per-`:membros` member-`:versao`-scalar pin:
// [`Membro::versao_requirement`] must return the
// `:membros :versao` field byte-for-byte, borrowed from the typed
// slot's own [`String`] storage. Sibling of the peer
// `membro_nome_returns_caixa_byte_equal_across_permutations`
// (4a32abf) pin on the per-`:membros` member-caixa `:nome` scalar
// — same "the substrate-primitive accessor must byte-equal the
// raw field access verbatim across every author-declared value"
// discipline extended to the per-`:membros` member-`:versao`
// requirement-string arm. Pins against a future silent detour
// that re-canonicalized the requirement (an accidental
// `.to_string()` via [`parse_requirement`] → [`Display`] round-
// trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and silently
// drifted the printer output away from the source `caixa.lisp`,
// an accidental whitespace trim on `"^ 0.1"` that no consumer
// ever produced from the field-access side, an accidental
// per-cluster lacre-projected concrete-version rewrite that
// didn't land on the peer field-access sites). Five values sweep
// the accept-set the shared
// [`crate::render::require_valid_versao_requirement`] gate
// admits (caret / tilde / exact / wildcard / bare-major).
for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
let m = Membro {
caixa: "cart".into(),
versao: req.into(),
};
assert_eq!(
m.versao_requirement(),
req,
"Membro::versao_requirement must return :membros :versao \
verbatim (got {:?}, expected {req:?})",
m.versao_requirement(),
);
assert_eq!(
m.versao_requirement(),
m.versao.as_str(),
"Membro::versao_requirement must byte-equal the .versao \
field access",
);
}
}
#[test]
fn membro_versao_requirement_borrows_from_versao_storage() {
// The borrow-not-copy pin: [`Membro::versao_requirement`] must
// return a `&str` slice that borrows from the typed slot's own
// [`String`] storage — same-address invariant with
// `m.versao.as_str()`. Pins against a future silent detour that
// allocated a fresh `String` (`self.versao.clone()` in the body
// would type-check but silently drop the borrow, and every
// downstream consumer that assumed the returned slice outlives
// `&self` would break on a stale-reference use-after-free). Peer
// of the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
// per-`:contratos` [`WitContract::source`] /
// [`WitContract::destination`] (7f0fd43) and per-`:entrada`
// [`Entrada::destination`] (6db982c) borrow-invariant pins on
// the mesh-slot-atom scalar-value axes.
let m = Membro {
caixa: "checkout".into(),
versao: "^0.1".into(),
};
let req = m.versao_requirement();
let versao_slice = m.versao.as_str();
assert_eq!(
req.as_ptr(),
versao_slice.as_ptr(),
"Membro::versao_requirement must borrow from the .versao \
String's backing storage — a fresh allocation here means \
the accessor no longer names the substrate-primitive typed \
dispatch and every downstream consumer would silently carry \
a detached copy",
);
assert_eq!(
req.len(),
versao_slice.len(),
"Membro::versao_requirement and .versao.as_str() must byte-\
equal in length as well as in address",
);
}
#[test]
fn membro_nome_and_versao_requirement_project_caixa_and_versao_pair() {
// Sibling-pair invariant pin composing both per-`:membros`
// substrate-primitive typed dispatches — [`Membro::nome`]
// (4a32abf) and [`Membro::versao_requirement`] — at the joint
// `(nome(), versao_requirement())` call shape every renderer
// that fans on per-member identity + version pin keys off. The
// invariant, evaluated per-member:
//
// (m.nome(), m.versao_requirement()) == (m.caixa.as_str(), m.versao.as_str())
//
// Closes the last unlifted per-`:membros` scalar axis — every
// downstream consumer that reads the pair now routes through
// exactly two typed dispatches on the substrate primitive, not
// one typed + one open-coded field access. A future refactor
// that silently split either accessor's projection (an
// accidental `nome()` namespace-prefix rewrite that didn't
// reach the peer, an accidental `versao_requirement()` lacre-
// projected concrete-version rewrite that didn't land on the
// `nome()` peer) surfaces at caixa-core build time. Peer of the
// sibling per-`:entrada` `(hostname(), destination())` and
// per-`:contratos` `(source(), destination())` pair invariants
// on the mesh-slot-atom scalar-value axes.
for (caixa, versao) in [
("cart", "^0.1"),
("checkout", "~0.1.2"),
("catalog", "0.1.0"),
("orders-v2", "*"),
] {
let m = Membro {
caixa: caixa.into(),
versao: versao.into(),
};
assert_eq!(
(m.nome(), m.versao_requirement()),
(m.caixa.as_str(), m.versao.as_str()),
"(Membro::nome, Membro::versao_requirement) must project \
(.caixa, .versao) verbatim across every author-declared \
pair (got ({:?}, {:?}), expected ({caixa:?}, {versao:?}))",
m.nome(),
m.versao_requirement(),
);
}
}
#[test]
fn validate_membros_empty_gate_routes_through_nome_accessor() {
// Composition pin: [`AplicacaoSpec::validate_membros`]'s
// `MembroCaixaEmpty` refusal-arm must key off [`Membro::nome`],
// not the raw `.caixa` field access. Structurally: setting
// ONLY the `.caixa` field to `""` on an otherwise-well-formed
// `:membros` entry must (1) trip the `MembroCaixaEmpty` gate
// and (2) produce a `m.nome()` byte-equal to `m.caixa.as_str()`
// (i.e. the empty string) — so the emptiness predicate the
// refusal arm reaches under is the accessor-projected value,
// not a peer field that would silently drift under a future
// accessor-side rewrite.
//
// Pins against a future silent detour that (a) re-derived the
// emptiness gate off `self.caixa.is_empty()` in `validate_membros`
// instead of `self.nome().is_empty()`, silently disagreeing with
// every peer consumer (the `validate_membro_caixa(m.nome())`
// per-slot helper — which now owns the emptiness arm outright —
// the dedup-key `insert_first_seen(&mut seen, m.nome(), …)`
// below, and the emit-side per-`programs[]` entry-`name:` at
// caixa-mesh/src/lib.rs:133), (b) accessor-side introduced a
// per-tenant alias arm the caller was unaware of, silently
// rewriting an author-declared `:caixa "checkout"` to `""` —
// the raw-field-access gate would fail-open while the
// accessor-routed peer consumers would fail-closed, splitting
// the diagnostic from the actual failure surface.
//
// Peer of the sibling
// [`mesh_policy_is_empty_mtls_required_arm_routes_through_accessor`]
// (c0110f1) composition pin — same "the shape-gate predicate
// must route through the substrate-primitive typed dispatch"
// discipline extended onto the per-`:membros` empty-`:caixa`
// refusal-arm axis. Closes the last unlifted `.caixa` production-
// code read site on `Membro` — after this converge every
// caixa-core `.caixa` field access outside the accessor's own
// body is either a test-side field-setter (in-module tests
// constructing invalid-shape inputs) or a doc-comment reference.
let mut s = three_member_spec();
s.membros[1].caixa = String::new();
assert!(
s.membros[1].nome().is_empty(),
"Membro::nome must byte-equal the .caixa field access — an \
accessor-side detour that no longer projects the raw field \
would silently split this drift-detection test from the \
validate() refusal arm",
);
assert_eq!(
s.membros[1].nome(),
s.membros[1].caixa.as_str(),
"Membro::nome and .caixa.as_str() must byte-equal on an \
empty-`:caixa` entry — the emptiness gate keys off the \
accessor by construction",
);
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::MembroCaixaEmpty,
"validate_membros' emptiness gate must fire MembroCaixaEmpty \
on an entry whose accessor-projected `nome()` is empty",
);
}
#[test]
fn validate_membros_empty_arm_is_owned_by_validate_membro_caixa_alone() {
// Convergence pin, paired with the deletion of the redundant
// outer `if m.nome().is_empty() { return Err(MembroCaixaEmpty); }`
// guard formerly inline in [`AplicacaoSpec::validate_membros`]:
// after the collapse, the `MembroCaixaEmpty` refusal on every
// empty-`:caixa` per-member input is owned solely by the shared
// [`validate_membro_caixa`] helper — the same per-slot substrate
// primitive routing empty + shape arms uniformly onto
// [`crate::render::require_valid_dns_1123_label`] that every
// peer M3 mesh-slot per-slot gate ([`validate_placement_cluster`]
// on `:placement :clusters`, [`validate_entrada_para`] on
// `:entrada :para`, [`validate_contrato_caixa`] on `:contratos
// :de`/`:para`) already funnels its own empty arm through.
//
// Two arms pin the collapse:
//
// (1) The per-slot helper called with the empty string returns
// byte-equal to the previous inline arm's diagnostic — so
// a future rebrand of [`validate_membro_caixa`] that
// (accidentally) stopped returning [`MembroCaixaEmpty`] on
// empty input (an inadvertent switch to
// [`AplicacaoError::MembroCaixaInvalid`] via the parse-side
// `on_invalid` arm, an accidental re-routing to a shared
// `MembroError::Empty` under a future error-hierarchy
// flattening) would silently split the drift from the
// [`validate_membros`] caller and surface the wrong
// diagnostic on the author-facing empty-`:caixa` footgun.
//
// (2) The whole-spec equivalence: an empty-`:caixa` entry
// anywhere in the `:membros` fan-out still trips
// [`MembroCaixaEmpty`] end-to-end via [`validate`], with
// no outer inline guard needed. Same shape as the
// whole-spec arm on [`validate_placement_cluster`] /
// [`validate_entrada_para`] / [`validate_contrato_caixa`]:
// one substrate primitive per axis, folding empty + shape.
//
// Same PRIME DIRECTIVE convergence the peer per-slot gate lifts
// (906a5c6 validate_contratos, 20cd523 validate_entrada, f03a154
// MeshPolicy::validate) already extend across the M3 mesh-slot
// family — closes the last per-slot gate on the family carrying
// an inline empty guard duplicating its own helper.
assert_eq!(
validate_membro_caixa(""),
Err(AplicacaoError::MembroCaixaEmpty),
"validate_membro_caixa must own the empty arm outright — a \
regression here would silently split MembroCaixaEmpty from \
validate_membros' end-to-end refusal shape after the outer \
inline `if m.nome().is_empty()` guard collapse",
);
let mut s = three_member_spec();
s.membros[0].caixa = String::new();
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::MembroCaixaEmpty,
"an empty-`:caixa` :membros head entry must trip \
MembroCaixaEmpty end-to-end via validate() with the outer \
inline guard removed — the per-slot helper alone is now \
load-bearing",
);
let mut s = three_member_spec();
s.membros[2].caixa = String::new();
assert_eq!(
s.validate().unwrap_err(),
AplicacaoError::MembroCaixaEmpty,
"an empty-`:caixa` :membros tail entry must trip \
MembroCaixaEmpty end-to-end via validate() with the outer \
inline guard removed — the per-slot helper alone reaches \
every fan-out position",
);
}
#[test]
fn placement_shard_key_returns_shard_key_option_byte_equal_across_permutations() {
// The canonical per-`:placement` Akka-cluster-sharding
// `:shard-key`-scalar pin: [`Placement::shard_key`] must return
// the `:placement :shard-key` field byte-for-byte, borrowed
// from the typed slot's own `Option<String>` storage. Peer of
// the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
// per-`:contratos` [`WitContract::source`] /
// [`WitContract::destination`] (7f0fd43) and per-`:entrada`
// [`Entrada::destination`] (6db982c) accessor pins on the mesh-
// slot-atom scalar-value axes — same "the substrate-primitive
// accessor must byte-equal the raw field access verbatim across
// every author-declared value" discipline extended to the
// per-`:placement` Akka-cluster-sharding key extractor arm.
// Pins against a future silent detour that re-normalized the
// key (an accidental `.to_lowercase()` — every non-empty
// `:shard-key` is validated as a printable-ASCII single-token
// reference upstream via [`validate_placement_shard_key`], so
// any re-normalization is redundant + a drift surface between
// the validator and the accessor), a per-cluster alias rewrite
// the operator authors on one consumer without the other, or an
// accidental variable-prefix strip (`$tenantId` → `tenantId`)
// that didn't land on the peer field-access sites. Four values
// sweep the accept-set the shape gate admits — bare identifier,
// `$`-prefixed variable, dotted path, `${}`-quoted variable —
// the four canonical Akka-style entity-id extractor shapes the
// future M4 cluster-sharding reconciler hashes.
for key in ["tenantId", "$tenantId", "metadata.tenantId", "${tenant}"] {
let p = Placement {
estrategia: PlacementStrategy::Sharded,
clusters: vec!["rio".into()],
affinity: None,
shard_key: Some(key.into()),
};
assert_eq!(
p.shard_key(),
Some(key),
"Placement::shard_key must return :placement :shard-key \
verbatim (got {:?}, expected Some({key:?}))",
p.shard_key(),
);
assert_eq!(
p.shard_key(),
p.shard_key.as_deref(),
"Placement::shard_key must byte-equal the .shard_key \
field's `.as_deref()` projection",
);
}
}
#[test]
fn placement_shard_key_none_when_field_is_none() {
// The absent-`:shard-key` arm of the per-`:placement`
// Akka-cluster-sharding accessor pin: when the typed slot is
// absent — the canonical shape under `:estrategia Replicated` /
// `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
// enforced `shard_key.is_some() == matches!(estrategia,
// Sharded)` partition — [`Placement::shard_key`] must return
// `None`. Pins against a future silent detour that projected
// the absent slot to a `Some("")` empty-string default (the
// canonical `Option<String>` → `String` collapse footgun the
// sibling M2 [`crate::LimitsSpec::is_empty`] /
// [`crate::BehaviorSpec::is_empty`] emptiness predicates
// already guard on the peer M2 typed-slot surfaces), a
// `Some("None")` stringified-None round-trip, or a `Some` arm
// whose contents were derived from a sibling slot (an
// accidental fallback to `estrategia.as_str()` that read the
// strategy discriminator into the key axis). Two placements
// sweep the accept-set every `validate`-passing non-`Sharded`
// shape lands on — `Replicated` (Erlang/OTP distributed-app
// takeover) and `SingleNode` (single-node hosting).
for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
let p = Placement {
estrategia,
clusters: vec!["rio".into()],
affinity: None,
shard_key: None,
};
assert!(
p.shard_key().is_none(),
"Placement::shard_key must return None when the typed \
slot is absent under :estrategia {estrategia:?} (got {:?})",
p.shard_key(),
);
assert_eq!(
p.shard_key(),
p.shard_key.as_deref(),
"Placement::shard_key must byte-equal the .shard_key \
field's `.as_deref()` projection in the absent arm",
);
}
}
#[test]
fn placement_shard_key_borrows_from_shard_key_storage() {
// The borrow-not-copy pin: [`Placement::shard_key`] must return
// an `Option<&str>` whose `Some` arm borrows from the typed
// slot's own [`String`] storage — same-address invariant with
// `p.shard_key.as_deref().unwrap()`. Pins against a future
// silent detour that allocated a fresh `String`
// (`self.shard_key.clone().map(...)` in the body would type-
// check but silently drop the borrow, and every downstream
// consumer that assumed the returned slice outlives `&self`
// would break on a stale-reference use-after-free — the
// [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape
// gate's `Some(k)`-bound match arm reads `k: &str` under the
// accessor's return type and would silently misbehave if this
// accessor produced a detached copy). Peer of the sibling
// per-`:membros` [`Membro::nome`] (4a32abf), per-`:contratos`
// [`WitContract::source`] / [`WitContract::destination`]
// (7f0fd43), and per-`:entrada` [`Entrada::destination`]
// (6db982c) borrow-invariant pins on the mesh-slot-atom
// scalar-value axes — first extension of the discipline onto
// an `Option<String>`-shaped optional-scalar axis.
let p = Placement {
estrategia: PlacementStrategy::Sharded,
clusters: vec!["rio".into()],
affinity: None,
shard_key: Some("tenantId".into()),
};
let key = p.shard_key().expect("Some arm");
let storage_slice = p.shard_key.as_deref().expect("Some arm — storage side");
assert_eq!(
key.as_ptr(),
storage_slice.as_ptr(),
"Placement::shard_key must borrow from the .shard_key \
String's backing storage — a fresh allocation here means \
the accessor no longer names the substrate-primitive typed \
dispatch and every downstream consumer would silently \
carry a detached copy",
);
assert_eq!(
key.len(),
storage_slice.len(),
"Placement::shard_key and .shard_key.as_deref() must byte-\
equal in length as well as in address",
);
}
#[test]
fn placement_affinity_returns_affinity_option_byte_equal_across_permutations() {
// The canonical per-`:placement` M3-Adaptive-compression-hint
// scalar pin: [`Placement::affinity`] must return the
// `:placement :affinity` field byte-for-byte, borrowed from the
// typed slot's own `Option<String>` storage. Peer of the sibling
// per-`:placement` [`Placement::shard_key`] (7cd2a28) accessor
// pin on the sibling `Option<&str>` optional-scalar axis — same
// "the substrate-primitive accessor must byte-equal the raw
// field access verbatim across every author-declared value"
// discipline extended to the peer per-`:placement` M3-Adaptive-
// compression-hint arm. Pins against a future silent detour
// that re-normalized the hint (an accidental `.to_lowercase()`
// — every `:affinity` is already validated as a DNS-1123 label
// upstream via [`validate_placement_affinity`], so any re-
// normalization is redundant + a drift surface between the
// validator and the accessor), a per-cluster alias rewrite the
// operator authors on one consumer without the other, or an
// accidental hint-family collapse (`low-latency` → `latency`
// that dropped the qualifier prefix). Four values sweep the
// MESH-COMPOSITION §II.4 vocabulary the accept-set names — the
// canonical adaptive-compression-weight biases the future M4
// placement engine reads.
for hint in [
"data-locality",
"low-latency",
"high-throughput",
"cost-optimized",
] {
let p = Placement {
estrategia: PlacementStrategy::Replicated,
clusters: vec!["rio".into()],
affinity: Some(hint.into()),
shard_key: None,
};
assert_eq!(
p.affinity(),
Some(hint),
"Placement::affinity must return :placement :affinity \
verbatim (got {:?}, expected Some({hint:?}))",
p.affinity(),
);
assert_eq!(
p.affinity(),
p.affinity.as_deref(),
"Placement::affinity must byte-equal the .affinity \
field's `.as_deref()` projection",
);
}
}
#[test]
fn placement_affinity_none_when_field_is_none() {
// The absent-`:affinity` arm of the per-`:placement`
// M3-Adaptive-compression-hint accessor pin: when the typed
// slot is absent — the canonical shape of an Aplicacao that
// leaves the compression weighting up to the placement engine's
// cluster-default arm — [`Placement::affinity`] must return
// `None`. Pins against a future silent detour that projected
// the absent slot to a `Some("")` empty-string default (the
// canonical `Option<String>` → `String` collapse footgun the
// sibling M2 [`crate::LimitsSpec::is_empty`] /
// [`crate::BehaviorSpec::is_empty`] emptiness predicates
// already guard on the peer M2 typed-slot surfaces), a
// `Some("None")` stringified-None round-trip, a `Some` arm
// whose contents were derived from a sibling slot (an
// accidental fallback to `estrategia.as_str()` that read the
// strategy discriminator into the hint axis), or a
// `Some("default")` implicit-default that would silently biases
// the routing without the author having written one. Three
// placements sweep the accept-set every `validate`-passing
// `:affinity None` shape lands on — one per PlacementStrategy
// discriminator arm (`SingleNode`, `Replicated`, `Sharded`
// with a shard-key), since `:affinity` is orthogonal to
// `:estrategia` in the typed grammar.
for (estrategia, shard_key) in [
(PlacementStrategy::SingleNode, None),
(PlacementStrategy::Replicated, None),
(PlacementStrategy::Sharded, Some("tenantId".to_string())),
] {
let p = Placement {
estrategia,
clusters: vec!["rio".into()],
affinity: None,
shard_key,
};
assert!(
p.affinity().is_none(),
"Placement::affinity must return None when the typed \
slot is absent under :estrategia {estrategia:?} (got {:?})",
p.affinity(),
);
assert_eq!(
p.affinity(),
p.affinity.as_deref(),
"Placement::affinity must byte-equal the .affinity \
field's `.as_deref()` projection in the absent arm",
);
}
}
#[test]
fn placement_affinity_borrows_from_affinity_storage() {
// The borrow-not-copy pin: [`Placement::affinity`] must return
// an `Option<&str>` whose `Some` arm borrows from the typed
// slot's own [`String`] storage — same-address invariant with
// `p.affinity.as_deref().unwrap()`. Pins against a future
// silent detour that allocated a fresh `String`
// (`self.affinity.clone().map(...)` in the body would type-
// check but silently drop the borrow, and every downstream
// consumer that assumed the returned slice outlives `&self`
// would break on a stale-reference use-after-free — the
// [`AplicacaoSpec::validate_placement`] per-hint value-shape
// gate reads the accessor's `&str` return through the
// [`validate_placement_affinity`] `&str` parameter and would
// silently misbehave if this accessor produced a detached
// copy). Peer of the sibling per-`:placement`
// [`Placement::shard_key`] (7cd2a28) borrow-invariant pin on
// the M3 mesh-slot-atom `Option<String>` optional-scalar axis —
// extends the discipline onto the sibling per-`:placement`
// M3-Adaptive-compression-hint arm.
let p = Placement {
estrategia: PlacementStrategy::Replicated,
clusters: vec!["rio".into()],
affinity: Some("data-locality".into()),
shard_key: None,
};
let hint = p.affinity().expect("Some arm");
let storage_slice = p.affinity.as_deref().expect("Some arm — storage side");
assert_eq!(
hint.as_ptr(),
storage_slice.as_ptr(),
"Placement::affinity must borrow from the .affinity \
String's backing storage — a fresh allocation here means \
the accessor no longer names the substrate-primitive typed \
dispatch and every downstream consumer would silently \
carry a detached copy",
);
assert_eq!(
hint.len(),
storage_slice.len(),
"Placement::affinity and .affinity.as_deref() must byte-\
equal in length as well as in address",
);
}
#[test]
fn placement_estrategia_returns_estrategia_verbatim_across_permutations() {
// The canonical per-`:placement` distribution-strategy-scalar
// pin: [`Placement::estrategia`] must return the `:placement
// :estrategia` field verbatim as a [`PlacementStrategy`],
// `Copy`-projected from the typed slot's own `PlacementStrategy`
// storage across every variant in the closed accept-set
// (`SingleNode` — Erlang/OTP distributed-app takeover;
// `Replicated` — active-active across every named cluster;
// `Sharded` — Akka-style hash-keyed entity distribution). Pins
// against a future silent detour that re-derived the strategy
// from a peer axis (an accidental fallback to
// `if shard_key.is_some() { Sharded } else { Replicated }`
// collapse that read the shard-key axis into the strategy
// discriminator), a variant remap the operator authors on one
// consumer without the other, or a stale-derive detour that
// substituted [`PlacementStrategy::default`] when the field
// held any explicit variant (which would silently collapse the
// distinction between "author explicitly declared `:estrategia
// Replicated`" and "author omitted the slot and inherited the
// default" the future per-cluster override slot depends on).
// Peer of the sibling per-`:entrada` `port_returns_entrada_port_verbatim_across_permutations`
// pin on the `Copy`-return `u16` scalar axis — same "the
// substrate-primitive accessor must byte-equal the raw field
// access verbatim across every author-declared value" discipline
// extended onto the per-`:placement` distribution-strategy
// `Copy`-composite-enum scalar axis.
for estrategia in [
PlacementStrategy::SingleNode,
PlacementStrategy::Replicated,
PlacementStrategy::Sharded,
] {
// Route the paired `:shard-key` fixture-builder through the
// typed cross-slot invariant predicate
// [`PlacementStrategy::requires_shard_key`] rather than the
// [`gen_platform::IsVariant`]-derived [`PlacementStrategy::is_sharded`]
// arm-identity predicate — same discipline the sibling
// `placement_strategy_variants_round_trip` fixture builder now
// reads through.
let shard_key = estrategia
.requires_shard_key()
.then(|| "tenantId".to_string());
let p = Placement {
estrategia,
clusters: vec!["rio".into()],
affinity: None,
shard_key,
};
assert_eq!(
p.estrategia(),
estrategia,
"Placement::estrategia must return :placement :estrategia \
verbatim (got {:?}, expected {estrategia:?})",
p.estrategia(),
);
assert_eq!(
p.estrategia(),
p.estrategia,
"Placement::estrategia accessor and .estrategia field \
access must byte-equal — the accessor is the substrate-\
primitive typed dispatch every downstream distribution-\
strategy consumer must route through",
);
}
}
#[test]
fn validate_placement_reads_through_lifted_estrategia_accessor() {
// Three-consumer coherence pin: the
// [`AplicacaoSpec::validate_placement`]
// [`AplicacaoError::PlacementWithoutClusters`] error carrier's
// `estrategia:` field (which reads through
// [`Placement::estrategia`] to name the strategy the empty
// `:clusters` list was declared against), the same method's
// `Sharded ↔ non-Sharded` `match` partition dispatch (which
// reads through [`Placement::estrategia`] to fan across the
// shape-gate cascades), and the non-`Sharded`-arm
// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
// `estrategia:` field (which reads through
// [`Placement::estrategia`] to name the strategy the declared-
// but-inert `:shard-key` was authored under) must all key off
// the lifted accessor, so any future rebrand on the typed
// slot's reader shape lands at exactly one place. Pins the
// three-site coherence by exercising each error surface end-
// to-end and asserting the surfaced `estrategia:` field byte-
// equals the accessor's return. Peer of the sibling per-
// `:entrada` `validate_entrada_port_floor_gate_reads_through_lifted_port_accessor`
// pin on the M3 mesh-slot `Copy`-return scalar axis.
// Arm 1: empty `:clusters` list surfaces `PlacementWithoutClusters`,
// whose `estrategia:` field must byte-equal the accessor's return
// for every variant in the closed accept-set.
for estrategia in [
PlacementStrategy::SingleNode,
PlacementStrategy::Replicated,
PlacementStrategy::Sharded,
] {
let mut spec = three_member_spec();
spec.placement.estrategia = estrategia;
spec.placement.clusters = Vec::new();
// Route the paired `:shard-key` spec-mutator through the typed
// cross-slot invariant predicate
// [`PlacementStrategy::requires_shard_key`] rather than the
// [`gen_platform::IsVariant`]-derived
// [`PlacementStrategy::is_sharded`] arm-identity predicate —
// same discipline the sibling
// `placement_strategy_variants_round_trip` and
// `estrategia_returns_placement_estrategia_verbatim_across_permutations`
// fixture builders now read through.
spec.placement.shard_key = estrategia
.requires_shard_key()
.then(|| "tenantId".to_string());
let err = spec.validate().unwrap_err();
match err {
AplicacaoError::PlacementWithoutClusters { estrategia: e } => {
assert_eq!(
e,
spec.placement.estrategia(),
"PlacementWithoutClusters.estrategia must byte-equal \
Placement::estrategia() — the error carrier reads \
through the lifted accessor",
);
}
other => panic!(
"expected PlacementWithoutClusters, got {other:?} for \
estrategia={estrategia:?}"
),
}
}
// Arm 2: `:shard-key` authored on a non-`Sharded` strategy
// surfaces `ShardKeyOnNonSharded`, whose `estrategia:` field
// must byte-equal the accessor's return for both non-`Sharded`
// strategies.
for estrategia in [PlacementStrategy::SingleNode, PlacementStrategy::Replicated] {
let mut spec = three_member_spec();
spec.placement.estrategia = estrategia;
spec.placement.shard_key = Some("tenantId".into());
let err = spec.validate().unwrap_err();
match err {
AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. } => {
assert_eq!(
e,
spec.placement.estrategia(),
"ShardKeyOnNonSharded.estrategia must byte-equal \
Placement::estrategia() — the non-Sharded-arm \
refusal reads through the lifted accessor",
);
}
other => panic!(
"expected ShardKeyOnNonSharded, got {other:?} for \
estrategia={estrategia:?}"
),
}
}
}
// ── per-`:placement` `:clusters` typed-accessor coherence pins ──────────
//
// The [`Placement::clusters`] accessor lift is the second slice-return
// (`&[T]`) accessor on any typed slot — sibling to the seed M2
// [`crate::SupervisorSpec::children`] (bc92bce) accessor on the peer
// per-`:supervisor` static-child-list `Vec`-carry axis. The two pins
// below cover (1) the accessor's byte-equal projection against the raw
// field access across the empty / singleton / cohort fixtures the
// [`AplicacaoSpec::validate_placement`] pre-flight `.is_empty()` probe
// and the per-cluster validate loop fan between, and (2) the two-
// consumer coherence of the paired pre-flight refusal probe and the
// per-cluster validate loop routing through the accessor on both arms.
#[test]
fn placement_clusters_returns_clusters_slice_byte_equal_across_permutations() {
// The canonical per-`:placement` cluster-pool-scalar-shape pin:
// [`Placement::clusters`] must return the `:placement :clusters`
// typed `Vec<String>` verbatim as a `&[String]` slice-view over
// the same backing buffer the raw `self.clusters.as_slice()`
// field access borrows from, byte-equal across every
// representative fixture in the accept-set — the empty slice
// (the pre-validation sentinel every
// [`AplicacaoError::PlacementWithoutClusters`] refusal keys off),
// the singleton slice (the minimal `SingleNode`-shape cohort),
// and multi-entry cohorts (the peer `Replicated` / `Sharded`
// multi-cluster shapes MESH-COMPOSITION §II.1 / §II.4 declare).
//
// Pins against a future silent detour that returned
// `&Vec<String>` (which would type-check but leak the storage-
// side `Vec`'s grow/push/reserve surface no consumer of the
// typed view reaches for), a fresh-allocated `Vec<String>` copy
// (which would type-check via a coercion but silently break
// every downstream caller that relied on the slice sharing the
// backing buffer's identity), or an out-of-order or length-
// drifted projection (which would silently split the paired
// pre-flight `.is_empty()` refusal probe's input from the per-
// cluster validate loop's traversal input).
//
// Peer of the sibling M2
// `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
// (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
// `:supervisor` static-child-list axis, extended onto the M3
// per-`:placement` distribution-target-list `Vec`-carry axis.
let fixtures: Vec<Vec<String>> = vec![
Vec::new(),
vec!["rio".into()],
vec!["rio".into(), "mar".into()],
vec!["rio".into(), "mar".into(), "plo".into()],
];
for clusters in fixtures {
let p = Placement {
clusters: clusters.clone(),
..Placement::default()
};
assert_eq!(
p.clusters(),
clusters.as_slice(),
"Placement::clusters must return :placement :clusters \
verbatim (got {:?}, expected {:?})",
p.clusters(),
clusters.as_slice(),
);
assert_eq!(
p.clusters(),
p.clusters.as_slice(),
"Placement::clusters accessor and .clusters.as_slice() \
field access must byte-equal — the accessor is the \
substrate-primitive typed dispatch every downstream \
cluster-pool consumer must route through",
);
assert_eq!(
p.clusters().len(),
p.clusters.len(),
"Placement::clusters().len() must byte-equal \
self.clusters.len() — a length-drift would silently \
split the paired pre-flight `.is_empty()` refusal \
probe input from the per-cluster validate loop's \
traversal input",
);
}
}
#[test]
fn validate_placement_reads_through_lifted_clusters_accessor() {
// Two-consumer coherence pin: the
// [`AplicacaoSpec::validate_placement`] pre-flight
// `self.placement.clusters().is_empty()` refusal probe (which
// must trip [`AplicacaoError::PlacementWithoutClusters`] when
// the accessor projects the empty slice) and the per-cluster
// validate loop's `for c in self.placement.clusters()`
// traversal (which must reach every entry in the same order
// the accessor projects, so both the per-entry value-shape
// gate that trips [`AplicacaoError::PlacementClusterInvalid`]
// and the duplicate-detection HashSet insert that trips
// [`AplicacaoError::PlacementClusterDuplicate`] key off the
// accessor's projection) must both key off the lifted
// accessor, so any future rebrand on the typed slot's reader
// shape lands at exactly one place. Pins the two-site
// coherence by exercising each production consumer end-to-end:
// (1) the `PlacementWithoutClusters` refusal under the empty
// slice, (2) the `PlacementClusterInvalid` refusal fires on
// the second entry of a two-cluster cohort whose head is
// valid but tail is not (which requires the loop to reach the
// second entry through the accessor), and (3) the
// `PlacementClusterDuplicate` refusal fires on the second
// entry of a two-cluster cohort that shares a name (which
// requires the loop to reach both entries — a first-entry-only
// projection would silently pass since the dedup HashSet has
// room for the first insert).
//
// Peer of the sibling M2
// [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
// (bc92bce) coherence pin on the per-`:supervisor` static-
// child-list axis, extended onto the M3 per-`:placement`
// distribution-target-list `Vec`-carry axis.
// (1) Pre-flight `.is_empty()` probe: the empty slice must
// trip `PlacementWithoutClusters`.
let mut spec = three_member_spec();
spec.placement.clusters = Vec::new();
match spec.validate().unwrap_err() {
AplicacaoError::PlacementWithoutClusters { .. } => {}
other => panic!("expected PlacementWithoutClusters, got {other:?}"),
}
assert!(
spec.placement.clusters().is_empty(),
"the pre-flight refusal input must be the empty slice per \
the accessor's projection",
);
// (2) Per-cluster validate loop: a two-cluster cohort with an
// invalid tail entry must trip `PlacementClusterInvalid` on
// the tail — the loop must reach the second entry through
// the accessor.
let mut spec = three_member_spec();
spec.placement.clusters = vec!["rio".into(), "BAD_CLUSTER".into()];
match spec.validate().unwrap_err() {
AplicacaoError::PlacementClusterInvalid { cluster, .. } => {
assert_eq!(
cluster, "BAD_CLUSTER",
"PlacementClusterInvalid.cluster must carry the \
tail entry the loop reached through the accessor",
);
}
other => panic!("expected PlacementClusterInvalid, got {other:?}"),
}
assert_eq!(
spec.placement.clusters().len(),
2,
"the per-cluster validate loop's traversal input must be \
a two-element slice per the accessor's projection",
);
// (3) Per-cluster validate loop: a two-cluster cohort that
// shares a name must trip `PlacementClusterDuplicate` on the
// second entry — the loop must reach both entries through the
// accessor for the dedup HashSet's second insert to collide.
let mut spec = three_member_spec();
spec.placement.clusters = vec!["rio".into(), "rio".into()];
match spec.validate().unwrap_err() {
AplicacaoError::PlacementClusterDuplicate { cluster } => {
assert_eq!(
cluster, "rio",
"PlacementClusterDuplicate.cluster must carry the \
shared cluster name verbatim",
);
}
other => panic!("expected PlacementClusterDuplicate, got {other:?}"),
}
assert_eq!(
spec.placement.clusters().len(),
2,
"the per-cluster validate loop's traversal input must be \
a two-element slice per the accessor's projection",
);
}
#[test]
fn aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations() {
// The canonical per-`:membros` member-list-slice-shape pin:
// [`AplicacaoSpec::membros`] must return the `:membros` typed
// `Vec<Membro>` verbatim as a `&[Membro]` slice-view over the
// same backing buffer the raw `self.membros.as_slice()` field
// access borrows from, byte-equal across every representative
// fixture in the accept-set — the empty slice (the pre-
// validation sentinel every [`AplicacaoError::NoMembros`]
// refusal keys off), the singleton slice (the minimal one-
// Servico Aplicacao shape), and multi-entry cohorts (the peer
// multi-Servico shapes MESH-COMPOSITION §III.1 declares as the
// load-bearing identity of the application graph).
//
// Pins against a future silent detour that returned
// `&Vec<Membro>` (which would type-check but leak the storage-
// side `Vec`'s grow/push/reserve surface no consumer of the
// typed view reaches for), a fresh-allocated `Vec<Membro>` copy
// (which would type-check via a coercion but silently break
// every downstream caller that relied on the slice sharing the
// backing buffer's identity), or an out-of-order or length-
// drifted projection (which would silently split the paired
// `HashSet<&str>` name-set seed's collect input from the
// pre-flight `.is_empty()` refusal probe's input from the per-
// member validate loop's traversal input from the
// programs.yaml emitter's per-entry fan-out loop's input from
// the `feira app graph` per-member print traversal's input).
//
// Peer of the sibling M2
// `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
// (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
// `:supervisor` static-child-list axis and the sibling M3
// `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
// (a6e18d7) `&[String]` byte-equal pin on the per-
// `:placement` distribution-target-list axis — extends the
// slice-return-accessor byte-equal-projection discipline onto
// the outermost M3 mesh-slot type's per-Aplicacao member-list
// `Vec`-carry axis.
let fixtures: Vec<Vec<Membro>> = vec![
Vec::new(),
vec![membro("catalog", "^0.1")],
vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
vec![
membro("catalog", "^0.1"),
membro("cart", "^0.1"),
membro("payment", "^0.2"),
],
];
for membros in fixtures {
let s = AplicacaoSpec {
membros: membros.clone(),
contratos: Vec::new(),
politicas: MeshPolicy::default(),
placement: Placement::default(),
entrada: None,
};
assert_eq!(
s.membros(),
membros.as_slice(),
"AplicacaoSpec::membros must return :membros verbatim \
(got {:?}, expected {:?})",
s.membros(),
membros.as_slice(),
);
assert_eq!(
s.membros(),
s.membros.as_slice(),
"AplicacaoSpec::membros accessor and .membros.as_slice() \
field access must byte-equal — the accessor is the \
substrate-primitive typed dispatch every downstream \
member-list consumer must route through",
);
assert_eq!(
s.membros().len(),
s.membros.len(),
"AplicacaoSpec::membros().len() must byte-equal \
self.membros.len() — a length-drift would silently \
split the paired `HashSet<&str>` name-set seed's \
collect input from the pre-flight `.is_empty()` \
refusal probe input from the per-member validate \
loop's traversal input",
);
}
}
#[test]
fn validate_reads_through_lifted_membros_accessor() {
// Three-consumer coherence pin: the
// [`AplicacaoSpec::validate_membros`] pre-flight
// `self.membros().is_empty()` refusal probe (which must trip
// [`AplicacaoError::NoMembros`] when the accessor projects the
// empty slice), the same method's per-member validate loop's
// `for m in self.membros()` traversal (which must reach every
// entry in the same order the accessor projects, so both the
// per-entry empty-`:caixa` gate that trips
// [`AplicacaoError::MembroCaixaEmpty`] and the duplicate-
// detection `insert_first_seen` that trips
// [`AplicacaoError::MembroDuplicate`] key off the accessor's
// projection), and the peer [`AplicacaoSpec::validate`]'s
// `HashSet<&str>` name-set seed's
// `self.membros().iter().map(Membro::nome).collect()` collect
// input (which every `:contratos` `:de` / `:para` membership
// lookup rejects an unknown name against) must all three key
// off the lifted accessor, so any future rebrand on the typed
// slot's reader shape lands at exactly one place. Pins the
// three-site coherence by exercising each production consumer
// end-to-end: (1) the `NoMembros` refusal under the empty
// slice, (2) the `MembroCaixaEmpty` refusal fires on the
// second entry of a two-member cohort whose head is valid but
// tail has an empty `:caixa` (which requires the loop to
// reach the second entry through the accessor), and (3) the
// `MembroDuplicate` refusal fires on the second entry of a
// two-member cohort that shares a `:caixa` name (which
// requires the loop to reach both entries through the
// accessor for the dedup HashSet's second insert to collide).
//
// Peer of the sibling M2
// [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
// (bc92bce) coherence pin on the per-`:supervisor` static-
// child-list axis and the sibling M3
// `validate_placement_reads_through_lifted_clusters_accessor`
// (a6e18d7) coherence pin on the per-`:placement` distribution-
// target-list axis — extends the slice-return-accessor
// multi-consumer coherence discipline onto the outermost M3
// mesh-slot type's per-Aplicacao member-list `Vec`-carry axis.
// (1) Pre-flight `.is_empty()` probe: the empty slice must
// trip `NoMembros`.
let mut spec = three_member_spec();
spec.membros = Vec::new();
assert_eq!(spec.validate().unwrap_err(), AplicacaoError::NoMembros);
assert!(
spec.membros().is_empty(),
"the pre-flight refusal input must be the empty slice per \
the accessor's projection",
);
// (2) Per-member validate loop: a two-member cohort with an
// empty-`:caixa` tail entry must trip `MembroCaixaEmpty` on
// the tail — the loop must reach the second entry through
// the accessor.
let mut spec = three_member_spec();
spec.membros = vec![membro("catalog", "^0.1"), membro("", "^0.1")];
assert_eq!(
spec.validate().unwrap_err(),
AplicacaoError::MembroCaixaEmpty,
);
assert_eq!(
spec.membros().len(),
2,
"the per-member validate loop's traversal input must be \
a two-element slice per the accessor's projection",
);
// (3) Per-member validate loop: a two-member cohort that
// shares a `:caixa` name must trip `MembroDuplicate` on the
// second entry — the loop must reach both entries through the
// accessor for the dedup HashSet's second insert to collide.
let mut spec = three_member_spec();
spec.membros = vec![membro("catalog", "^0.1"), membro("catalog", "^0.2")];
match spec.validate().unwrap_err() {
AplicacaoError::MembroDuplicate { caixa } => {
assert_eq!(
caixa, "catalog",
"MembroDuplicate.caixa must carry the shared \
member name verbatim",
);
}
other => panic!("expected MembroDuplicate, got {other:?}"),
}
assert_eq!(
spec.membros().len(),
2,
"the per-member validate loop's traversal input must be \
a two-element slice per the accessor's projection",
);
}
#[test]
fn aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations() {
// The canonical per-`:contratos` contract-list-slice-shape pin:
// [`AplicacaoSpec::contratos`] must return the `:contratos`
// typed `Vec<WitContract>` verbatim as a `&[WitContract]`
// slice-view over the same backing buffer the raw
// `self.contratos.as_slice()` field access borrows from, byte-
// equal across every representative fixture in the accept-set —
// the empty slice (the pre-validation "internal-only mesh" shape
// an Aplicacao whose members exchange no typed edges renders
// through), the singleton slice (the minimal one-edge Aplicacao
// shape), and multi-entry cohorts (the peer multi-edge shapes
// MESH-COMPOSITION §III.1 declares as the load-bearing edge-set
// of the application graph).
//
// Pins against a future silent detour that returned
// `&Vec<WitContract>` (which would type-check but leak the
// storage-side `Vec`'s grow/push/reserve surface no consumer of
// the typed view reaches for), a fresh-allocated
// `Vec<WitContract>` copy (which would type-check via a coercion
// but silently break every downstream caller that relied on the
// slice sharing the backing buffer's identity), or an out-of-
// order or length-drifted projection (which would silently split
// the paired `AplicacaoSpec::validate` per-edge dedup HashSet
// seed's traversal input from the `detect_sync_cycles` per-edge
// adjacency-list seed's traversal input from the
// `caixa_mesh::cilium_network_policies` per-`(:de, :para)`
// BTreeMap grouping loop's traversal input from the
// `feira app graph` per-contract print traversal's input).
//
// Peer of the immediately-adjacent sibling M3
// `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
// (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
// node-list axis, the sibling M3
// `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
// (a6e18d7) `&[String]` byte-equal pin on the per-`:placement`
// distribution-target-list axis, and the sibling M2
// `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
// (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
// `:supervisor` static-child-list axis — extends the slice-
// return-accessor byte-equal-projection discipline onto the
// outermost M3 mesh-slot type's per-Aplicacao contract-list
// `Vec`-carry axis, closing the last unlifted per-
// `AplicacaoSpec` `Vec`-carry axis.
let fixtures: Vec<Vec<WitContract>> = vec![
Vec::new(),
vec![contract_http("cart", "catalog", "/products/:id")],
vec![
contract_http("cart", "catalog", "/products/:id"),
contract_http("cart", "payment", "/charge"),
],
vec![
contract_http("cart", "catalog", "/products/:id"),
contract_http("cart", "payment", "/charge"),
contract_http("payment", "catalog", "/audit"),
],
];
for contratos in fixtures {
let s = AplicacaoSpec {
membros: vec![
membro("catalog", "^0.1"),
membro("cart", "^0.1"),
membro("payment", "^0.2"),
],
contratos: contratos.clone(),
politicas: MeshPolicy::default(),
placement: Placement::default(),
entrada: None,
};
assert_eq!(
s.contratos(),
contratos.as_slice(),
"AplicacaoSpec::contratos must return :contratos verbatim \
(got {:?}, expected {:?})",
s.contratos(),
contratos.as_slice(),
);
assert_eq!(
s.contratos(),
s.contratos.as_slice(),
"AplicacaoSpec::contratos accessor and \
.contratos.as_slice() field access must byte-equal — \
the accessor is the substrate-primitive typed dispatch \
every downstream contract-list consumer must route \
through",
);
assert_eq!(
s.contratos().len(),
s.contratos.len(),
"AplicacaoSpec::contratos().len() must byte-equal \
self.contratos.len() — a length-drift would silently \
split the paired per-edge validate-loop's traversal \
input from the sync-cycle adjacency-list seed's \
traversal input from the cilium_network_policies \
per-`(:de, :para)` BTreeMap grouping loop's traversal \
input from the `feira app graph` per-contract print \
traversal's input",
);
}
}
#[test]
fn validate_reads_through_lifted_contratos_accessor() {
// Three-consumer coherence pin: the [`AplicacaoSpec::validate`]
// per-`:contratos` validate-loop's `for c in self.contratos()`
// traversal (which must reach every entry in the same order the
// accessor projects, so both the per-entry
// [`AplicacaoError::ContratoMemberMissing`] membership-lookup
// gate and the per-entry [`AplicacaoError::ContratoDuplicate`]
// dedup `HashSet` insert key off the accessor's projection),
// the peer [`AplicacaoSpec::detect_sync_cycles`]'s
// `for c in self.contratos()` adjacency-list seed (which drives
// the sync-subgraph deadlock-detection gate via
// [`AplicacaoError::SyncCycle`]), and the peer
// [`caixa_mesh::cilium_network_policies`]'s
// `for c in spec.contratos()` per-`(:de, :para)` BTreeMap
// grouping loop (which drives the per-CNP fan-out) must all
// three key off the lifted accessor, so any future rebrand on
// the typed slot's reader shape lands at exactly one place. Pins
// the three-site coherence by exercising the two caixa-core
// production consumers end-to-end: (1) the empty-`:contratos`
// slice must validate without a per-edge diagnostic (the
// per-edge loop is a no-op under the empty projection), (2) the
// `ContratoMemberMissing` refusal fires on the second entry of a
// two-edge cohort whose head references a valid member but tail
// references a phantom name (which requires the loop to reach
// the second entry through the accessor), and (3) the
// `SyncCycle` refusal fires on a self-referential two-edge
// cohort through the sync-cycle detector's peer projection
// (which requires the detector to iterate the accessor's
// projection to add the back-edge to its adjacency list).
//
// Peer of the sibling M3
// [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
// three-consumer coherence pin on the per-`:membros` node-list
// axis and the sibling M3
// `validate_placement_reads_through_lifted_clusters_accessor`
// (a6e18d7) coherence pin on the per-`:placement` distribution-
// target-list axis — extends the slice-return-accessor multi-
// consumer coherence discipline onto the outermost M3 mesh-slot
// type's per-Aplicacao contract-list `Vec`-carry axis.
// (1) Empty-`:contratos` slice: the per-edge loop is a no-op
// and no per-edge diagnostic surfaces. Validate succeeds on
// the well-formed `:membros` head.
let mut spec = three_member_spec();
spec.contratos = Vec::new();
assert!(
spec.validate().is_ok(),
"empty :contratos must validate — the per-edge loop is a \
no-op under the accessor's empty projection",
);
assert!(
spec.contratos().is_empty(),
"the per-edge validate loop's traversal input must be the \
empty slice per the accessor's projection",
);
// (2) Per-edge validate loop: a two-edge cohort whose tail
// references a phantom `:para` member must trip
// `ContratoMemberMissing` on the tail — the loop must reach
// the second entry through the accessor for the membership
// lookup to fail on the phantom name.
let mut spec = three_member_spec();
spec.contratos = vec![
contract_http("cart", "catalog", "/products/:id"),
contract_http("cart", "phantom", "/x"),
];
let err = spec.validate().unwrap_err();
assert!(
matches!(
err,
AplicacaoError::ContratoMemberMissing { ref caixa }
if caixa == "phantom"
),
"expected ContratoMemberMissing{{caixa:\"phantom\"}}, got {err:?}",
);
assert_eq!(
spec.contratos().len(),
2,
"the per-edge validate loop's traversal input must be \
a two-element slice per the accessor's projection",
);
// (3) Sync-cycle detector: a two-edge synchronous cohort
// whose second edge closes the sync-subgraph back onto the
// first must trip [`AplicacaoError::ContratoCycle`] — the
// detector must iterate the accessor's projection to add
// both edges to its adjacency list, so a length-drift on
// the accessor's projection would silently disagree with
// the sync-cycle detector on which edge closes the loop.
// Peer projection to the `validate` per-edge loop above:
// the sync-cycle detector routes through the same lifted
// accessor, so a rebrand of the reader shape lands at one
// place. Uses a two-edge cohort (cart → catalog → cart)
// because the per-edge `ContratoSelfLoop` gate fires before
// the sync-cycle detector on a single self-referential edge
// (`cart → cart`) — the cycle-detector's input must be a
// multi-edge cohort for its per-edge traversal input to be
// observably wider than the per-edge validate loop's input.
let mut spec = three_member_spec();
spec.contratos = vec![
contract_http("cart", "catalog", "/products/:id"),
contract_http("catalog", "cart", "/callback"),
];
let err = spec.validate().unwrap_err();
assert!(
matches!(err, AplicacaoError::ContratoCycle { .. }),
"expected ContratoCycle from the sync-cycle detector on a \
two-edge back-edge cohort, got {err:?}",
);
assert_eq!(
spec.contratos().len(),
2,
"the sync-cycle detector's traversal input must be a \
two-element slice per the accessor's projection",
);
}
#[test]
fn aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations() {
// The canonical per-`:politicas` outer-composite-reference-shape
// pin: [`AplicacaoSpec::politicas`] must return the `:politicas`
// typed `MeshPolicy` verbatim as a `&MeshPolicy` reference over
// the same backing storage the raw `&self.politicas` field
// access borrows from, byte-equal across every representative
// fixture in the accept-set — the default `MeshPolicy` (the
// author-empty "no policy on any axis" shape whose
// [`MeshPolicy::is_empty`] evaluates `true`), the singleton
// shapes carrying one axis at a time
// (`{mtls_required, timeout, retries, circuit_breaker,
// rate_limit}` — the minimal five-axis fan-out over the
// per-axis lifted accessor family every downstream mesh-artifact
// emitter dispatches on), and the multi-axis composite (the
// canonical `three_member_spec` fixture's `{timeout, retries,
// mtls_required}` triple — the load-bearing shape every
// Aplicacao-scoped fixture in this suite constructs).
//
// Pins against a future silent detour that returned a fresh-
// cloned `MeshPolicy` copy (which would type-check via a `Clone`
// impl but silently break every downstream caller that relied
// on the reference sharing the composite's backing identity), a
// reference to an operator-resolved overlay (the future
// per-cluster `:politicas-overrides` slot MESH-COMPOSITION §V
// acknowledges — its resolution must land at exactly this
// accessor body, not silently divert the raw slot away from a
// second consumer), or an axis-shuffled projection (a future
// detour that swapped `timeout` and `retries` through the
// accessor would silently split the paired `validate_politicas`
// per-axis bracket-dispatch's traversal input from the peer
// `caixa_mesh::gateway_routes` HTTPRoute timeout+retry overlay
// emitter's fan-out input from the peer
// `caixa_mesh::cilium_network_policies` per-CNP mTLS-mode
// overlay emitter's fan-out input).
//
// Peer of the sibling M3
// `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
// (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
// node-list `Vec`-carry axis and the sibling M3
// `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations`
// (0dcc926) `&[WitContract]` byte-equal pin on the per-
// `:contratos` edge-list `Vec`-carry axis — extends the outer-
// accessor byte-equal-projection discipline onto the outermost
// M3 mesh-slot type's per-Aplicacao mesh-policy composite-
// reference axis, the first `&Composite`-return accessor on the
// outer [`AplicacaoSpec`] type.
let fixtures: Vec<MeshPolicy> = vec![
MeshPolicy::default(),
MeshPolicy {
mtls_required: Some(true),
..MeshPolicy::default()
},
MeshPolicy {
mtls_required: Some(false),
..MeshPolicy::default()
},
MeshPolicy {
timeout: Some(Duration::from_secs(30)),
..MeshPolicy::default()
},
MeshPolicy {
retries: Some(3),
..MeshPolicy::default()
},
MeshPolicy {
circuit_breaker: Some(CircuitBreaker {
max_failures: 5,
window: Duration::from_secs(30),
}),
..MeshPolicy::default()
},
MeshPolicy {
rate_limit: Some(RateLimit {
rate: 100,
window: Duration::from_secs(1),
}),
..MeshPolicy::default()
},
MeshPolicy {
timeout: Some(Duration::from_secs(30)),
retries: Some(3),
mtls_required: Some(true),
..MeshPolicy::default()
},
];
for politicas in fixtures {
let s = AplicacaoSpec {
membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
contratos: Vec::new(),
politicas: politicas.clone(),
placement: Placement::default(),
entrada: None,
};
assert_eq!(
*s.politicas(),
politicas,
"AplicacaoSpec::politicas must return :politicas verbatim \
(got {:?}, expected {:?})",
s.politicas(),
politicas,
);
assert!(
std::ptr::eq(s.politicas(), &s.politicas),
"AplicacaoSpec::politicas accessor and &self.politicas \
field access must borrow the same backing storage — \
the accessor is the substrate-primitive typed dispatch \
every downstream mesh-policy composite consumer must \
route through, and a reference-identity split would \
silently break every consumer that relied on the \
borrow sharing the composite's storage",
);
assert_eq!(
s.politicas().is_empty(),
s.politicas.is_empty(),
"AplicacaoSpec::politicas().is_empty() must byte-equal \
self.politicas.is_empty() — an emptiness-drift would \
silently split the paired `validate_politicas` \
per-axis bracket-dispatch's seed from the peer \
caixa-mesh CNP mTLS-overlay emitter's key from the \
peer caixa-mesh HTTPRoute timeout+retry overlay \
emitter's key",
);
}
}
#[test]
fn validate_politicas_reads_through_lifted_politicas_accessor() {
// Multi-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
// per-axis bracket-dispatch seed (`let p = self.politicas();`,
// followed by the per-axis fan-out `p.timeout()` /
// `p.retries()` / `p.circuit_breaker()` / `p.rate_limit()` on
// the lifted axis-level accessor family) must key off the
// lifted outer accessor, so any future rebrand on the typed
// slot's outer-composite reader shape lands at exactly one
// place. Pins the multi-axis coherence by exercising each
// per-axis refusal end-to-end: (1) `PolicyTimeoutZero` fires on
// a `Some(Duration::ZERO)` timeout under the outer accessor's
// reference projection, (2) `PolicyRetriesZero` fires on a
// `Some(0)` retries under the same projection, and (3) an
// empty [`MeshPolicy::default`] passes `validate_politicas` —
// the outer accessor's reference-projection reaches every
// per-axis branch without silently short-circuiting any.
//
// Peer of the sibling M3
// [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
// three-consumer coherence pin on the per-`:membros` node-list
// axis and the sibling M3
// [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
// three-consumer coherence pin on the per-`:contratos`
// edge-list axis — extends the multi-consumer coherence
// discipline onto the outermost M3 mesh-slot type's per-
// Aplicacao mesh-policy composite-reference axis, the first
// `&Composite`-return accessor on the outer [`AplicacaoSpec`]
// type.
// (1) `PolicyTimeoutZero` refusal under the outer accessor's
// reference projection: a `Some(Duration::ZERO)` timeout must
// trip the zero-floor gate. The bracket-dispatch's first arm
// reads `p.timeout()` on the reference returned by the outer
// accessor.
let mut spec = three_member_spec();
spec.politicas.timeout = Some(Duration::ZERO);
spec.politicas.retries = None;
spec.politicas.circuit_breaker = None;
spec.politicas.rate_limit = None;
assert_eq!(
spec.validate().unwrap_err(),
AplicacaoError::PolicyTimeoutZero,
);
assert!(
std::ptr::eq(spec.politicas(), &spec.politicas),
"the `validate_politicas` per-axis bracket-dispatch's \
traversal input must be the same backing composite the \
accessor's reference projection borrows from",
);
// (2) `PolicyRetriesZero` refusal under the outer accessor's
// reference projection: a `Some(0)` retries must trip the
// zero-floor gate. The bracket-dispatch's second arm reads
// `p.retries()` on the reference returned by the outer accessor.
let mut spec = three_member_spec();
spec.politicas.timeout = None;
spec.politicas.retries = Some(0);
spec.politicas.circuit_breaker = None;
spec.politicas.rate_limit = None;
assert_eq!(
spec.validate().unwrap_err(),
AplicacaoError::PolicyRetriesZero,
);
// (3) Empty `MeshPolicy::default()` passes `validate_politicas`
// — every per-axis arm short-circuits on `None`, so the outer
// accessor's reference projection reaches the fall-through
// `Ok(())` without any per-axis refusal firing.
let mut spec = three_member_spec();
spec.politicas = MeshPolicy::default();
assert!(
spec.validate().is_ok(),
"an empty `MeshPolicy` must pass `validate_politicas` — \
every per-axis arm short-circuits on `None` under the \
outer accessor's reference projection",
);
assert!(
spec.politicas().is_empty(),
"the outer accessor's reference projection must be the \
empty composite per the `MeshPolicy::default()` fixture",
);
}
#[test]
#[allow(clippy::too_many_lines)]
fn validate_politicas_timeout_and_retries_arms_route_through_lifted_axis_accessors() {
// Per-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
// per-axis bracket-dispatch's `:timeout` and `:retries` arms
// must both key off the lifted axis-level accessors
// ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`]), matching
// the peer `:circuit-breaker` / `:rate-limit` arms already
// routing through [`MeshPolicy::circuit_breaker`] /
// [`MeshPolicy::rate_limit`] — a uniform "one typed dispatch
// per axis on the substrate primitive" shape at the fan-out
// (four axes, four accessors, no raw-field-access site
// anywhere on the bracket-dispatch). Pins the per-axis
// coherence at the accept-set boundaries the bracket carves:
// 1. accessor byte-equal to raw field on every representative
// accept-set value (`None`, sub-cap, at-cap, past-cap
// sentinel) — a future accessor drift that no longer
// shipped the raw slot verbatim would surface here,
// 2. `PolicyTimeoutZero` refusal fires on `Some(Duration::ZERO)`
// routed through the accessor's projection, proving the
// first arm reads through the accessor rather than a
// silent-detour peer-axis field access,
// 3. `PolicyRetriesZero` refusal fires on `Some(0)` routed
// through the accessor's projection, proving the second
// arm reads through the accessor,
// 4. an at-cap `Some(POLICY_RETRIES_MAX)` retries value
// passes validate under the accessor projection (paired
// with a `Some(POLICY_TIMEOUT_MAX)` at-cap timeout on the
// sibling axis), pinning the upper-boundary accept-arm
// also routes through the accessor.
//
// Peer of the sibling M3
// [`validate_politicas_reads_through_lifted_politicas_accessor`]
// outer-composite-reference coherence pin (which asserts the
// `let p = self.politicas()` seed); extends the discipline onto
// the per-axis fan-out layer that consumes the seed's
// reference. Same shape as
// [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
// and [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
// apply on the per-`AplicacaoSpec` `Vec`-carry axes, extended
// onto the per-`MeshPolicy` `Option<Copy-T>`-carry axes.
// (1) Accessor byte-equal to raw field on the `:timeout` axis
// across the accept-set boundaries the bracket dispatch's
// three-arm gate carves out
// ([`crate::render::require_positive_canonical_bounded_duration`]
// — zero-floor + canonical-form + upper-cap).
for timeout in [
None,
Some(Duration::ZERO),
Some(Duration::from_millis(1)),
Some(POLICY_TIMEOUT_MAX),
] {
let p = MeshPolicy {
timeout,
..MeshPolicy::default()
};
assert_eq!(
p.timeout(),
p.timeout,
"MeshPolicy::timeout accessor must byte-equal the raw \
.timeout field across every accept-set boundary the \
validate_politicas :timeout arm carves out — a drift \
here would silently split the validate bracket's arm \
from the peer caixa-mesh HTTPRoute timeout-overlay \
emitter's read",
);
}
// (2) Accessor byte-equal to raw field on the `:retries` axis
// across the accept-set boundaries the bracket dispatch's
// two-arm gate carves out
// ([`crate::render::require_positive_bounded_u32`] — zero-floor
// + upper-cap).
for retries in [
None,
Some(0u32),
Some(1u32),
Some(POLICY_RETRIES_MAX),
Some(POLICY_RETRIES_MAX + 1),
Some(u32::MAX),
] {
let p = MeshPolicy {
retries,
..MeshPolicy::default()
};
assert_eq!(
p.retries(),
p.retries,
"MeshPolicy::retries accessor must byte-equal the raw \
.retries field across every accept-set boundary the \
validate_politicas :retries arm carves out — a drift \
here would silently split the validate bracket's arm \
from the peer caixa-mesh HTTPRoute retry-overlay \
emitter's read",
);
}
// (3) `PolicyTimeoutZero` fires on the accessor-projected
// zero-floor boundary. A silent detour that no longer read
// through `p.timeout()` (a peer-axis field read, an accidental
// Option::and-then chain that collapsed the None arm to Some,
// an accessor rebrand that clamped the return through the
// upper cap) would fail to refuse here.
let mut spec = three_member_spec();
spec.politicas.timeout = Some(Duration::ZERO);
spec.politicas.retries = None;
spec.politicas.circuit_breaker = None;
spec.politicas.rate_limit = None;
assert_eq!(
spec.politicas().timeout(),
Some(Duration::ZERO),
"the accessor projection must reflect the fixture's \
`Some(Duration::ZERO)` :timeout verbatim",
);
assert_eq!(
spec.validate().unwrap_err(),
AplicacaoError::PolicyTimeoutZero,
"the validate_politicas :timeout zero-floor arm must fire \
through the lifted accessor's projection — a silent \
detour to a peer-axis field would fail to refuse",
);
// (4) `PolicyRetriesZero` fires on the accessor-projected
// zero-floor boundary on the sibling `:retries` axis.
let mut spec = three_member_spec();
spec.politicas.timeout = None;
spec.politicas.retries = Some(0);
spec.politicas.circuit_breaker = None;
spec.politicas.rate_limit = None;
assert_eq!(
spec.politicas().retries(),
Some(0),
"the accessor projection must reflect the fixture's \
`Some(0)` :retries verbatim",
);
assert_eq!(
spec.validate().unwrap_err(),
AplicacaoError::PolicyRetriesZero,
"the validate_politicas :retries zero-floor arm must fire \
through the lifted accessor's projection — a silent \
detour to a peer-axis field would fail to refuse",
);
// (5) At-cap accept-arm on both axes: a `Some(POLICY_TIMEOUT_MAX)`
// timeout paired with a `Some(POLICY_RETRIES_MAX)` retries
// must pass validate under the accessor projection — pins the
// upper-boundary accept-arm also routes through the lifted
// accessor (a drift that clamped or short-circuited at the
// upper boundary would fail the whole-spec validate here).
let mut spec = three_member_spec();
spec.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
spec.politicas.retries = Some(POLICY_RETRIES_MAX);
spec.politicas.circuit_breaker = None;
spec.politicas.rate_limit = None;
assert_eq!(
spec.politicas().timeout(),
Some(POLICY_TIMEOUT_MAX),
"the accessor projection must reflect the fixture's \
at-cap :timeout verbatim",
);
assert_eq!(
spec.politicas().retries(),
Some(POLICY_RETRIES_MAX),
"the accessor projection must reflect the fixture's \
at-cap :retries verbatim",
);
assert!(
spec.validate().is_ok(),
"at-cap :timeout + :retries must pass validate under the \
accessor projection — the upper-boundary accept-arm on \
both axes routes through the lifted accessor",
);
}
#[test]
fn aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations() {
// The canonical per-`:placement` outer-composite-reference-shape
// pin: [`AplicacaoSpec::placement`] must return the `:placement`
// typed `Placement` verbatim as a `&Placement` reference over the
// same backing storage the raw `&self.placement` field access
// borrows from, byte-equal across every representative fixture in
// the accept-set — the default `Placement` (the substrate seed
// shape whose [`PlacementStrategy::default`] evaluates to
// `SingleNode` with an empty `:clusters` pool and both
// optional-scalar axes `None`), and every canonical strategy /
// cluster-pool / optional-scalar combination the
// [`AplicacaoSpec::validate_placement`] gate accepts (each of the
// three [`PlacementStrategy`] variants — `SingleNode`,
// `Replicated`, `Sharded` — cross-projected with a non-empty
// `:clusters` pool and, on the `Sharded` arm, a non-empty
// `:shard-key`; a `:affinity`-carrying `Replicated` fixture; the
// canonical `three_member_spec` `Replicated` fixture's
// `{Replicated, ["rio", "mar"], "data-locality", None}` composite).
//
// Pins against a future silent detour that returned a fresh-
// cloned `Placement` copy (which would type-check via a `Clone`
// impl but silently break every downstream caller that relied on
// the reference sharing the composite's backing identity), a
// reference to an operator-resolved overlay (the future per-
// cluster `:placement-overrides` slot MESH-COMPOSITION §V
// acknowledges — its resolution must land at exactly this
// accessor body, not silently divert the raw slot away from a
// second consumer), or an axis-shuffled projection (a future
// detour that swapped `clusters` and `affinity` through the
// accessor would silently split the paired `validate_placement`
// per-axis bracket-dispatch's traversal input from the peer
// `caixa_mesh::programs_for_aplicacao` per-Aplicacao
// programs.yaml distribution-annotation emitter's fan-out input
// from the peer `feira app graph` per-Aplicacao print line's
// input).
//
// Peer of the sibling M3
// `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
// (534dc21) `&MeshPolicy` byte-equal pin on the per-`:politicas`
// outer mesh-policy composite-reference axis, and of the sibling
// slice-return `aplicacao_spec_membros_returns_membros_slice_
// byte_equal_across_permutations` (6c77e36) `&[Membro]` +
// `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_
// across_permutations` (0dcc926) `&[WitContract]` pins — extends
// the outer-accessor byte-equal-projection discipline onto the
// outermost M3 mesh-slot type's per-Aplicacao distribution
// composite-reference axis, the second `&Composite`-return
// accessor on the outer [`AplicacaoSpec`] type.
let fixtures: Vec<Placement> = vec![
Placement::default(),
Placement {
estrategia: PlacementStrategy::SingleNode,
clusters: vec!["rio".into()],
affinity: None,
shard_key: None,
},
Placement {
estrategia: PlacementStrategy::Replicated,
clusters: vec!["rio".into(), "mar".into()],
affinity: None,
shard_key: None,
},
Placement {
estrategia: PlacementStrategy::Replicated,
clusters: vec!["rio".into(), "mar".into()],
affinity: Some("data-locality".into()),
shard_key: None,
},
Placement {
estrategia: PlacementStrategy::Sharded,
clusters: vec!["rio".into(), "mar".into()],
affinity: None,
shard_key: Some("tenantId".into()),
},
Placement {
estrategia: PlacementStrategy::Sharded,
clusters: vec!["rio".into(), "mar".into(), "sol".into()],
affinity: Some("low-latency".into()),
shard_key: Some("metadata.tenantId".into()),
},
];
for placement in fixtures {
let s = AplicacaoSpec {
membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
contratos: Vec::new(),
politicas: MeshPolicy::default(),
placement: placement.clone(),
entrada: None,
};
assert_eq!(
*s.placement(),
placement,
"AplicacaoSpec::placement must return :placement verbatim \
(got {:?}, expected {:?})",
s.placement(),
placement,
);
assert!(
std::ptr::eq(s.placement(), &s.placement),
"AplicacaoSpec::placement accessor and &self.placement \
field access must borrow the same backing storage — the \
accessor is the substrate-primitive typed dispatch every \
downstream distribution-composite consumer must route \
through, and a reference-identity split would silently \
break every consumer that relied on the borrow sharing \
the composite's storage",
);
assert_eq!(
s.placement().estrategia(),
s.placement.estrategia,
"AplicacaoSpec::placement().estrategia() must byte-equal \
self.placement.estrategia — a strategy-drift would \
silently split the paired `validate_placement` \
`Sharded` ↔ non-`Sharded` partition scrutinee from the \
peer caixa-mesh programs.yaml `placement.estrategia` \
emitter's key from the peer `feira app graph` printer's \
strategy label",
);
assert_eq!(
s.placement().clusters(),
s.placement.clusters.as_slice(),
"AplicacaoSpec::placement().clusters() must byte-equal \
self.placement.clusters — a cluster-pool drift would \
silently split the paired `validate_placement` \
pre-flight `.is_empty()` refusal probe's traversal from \
the peer caixa-mesh programs.yaml `placement.clusters` \
emitter's fan-out from the peer `feira app graph` \
printer's cluster list",
);
}
}
#[test]
fn validate_placement_reads_through_lifted_placement_accessor() {
// Multi-axis coherence pin: the [`AplicacaoSpec::validate_placement`]
// per-axis bracket-dispatch seed (`let p = self.placement();`,
// followed by the per-axis fan-out `p.clusters()` /
// `p.estrategia()` / `p.affinity()` / `p.shard_key()` on the
// lifted axis-level accessor family) must key off the lifted
// outer accessor, so any future rebrand on the typed slot's
// outer-composite reader shape lands at exactly one place. Pins
// the multi-axis coherence by exercising each per-axis refusal
// end-to-end: (1) `PlacementWithoutClusters` fires on an empty
// `:clusters` pool under the outer accessor's reference
// projection, (2) `ShardedWithoutKey` fires on a `Sharded`
// strategy with a `None` `:shard-key` under the same projection,
// (3) `ShardKeyOnNonSharded` fires on a non-`Sharded` strategy
// with a `Some` `:shard-key` under the same projection, and
// (4) the canonical `three_member_spec` `Replicated` fixture
// passes `validate_placement` under the outer accessor's
// reference projection — the accessor's reference-projection
// reaches every per-axis branch (cluster-pool refusal, `Sharded`
// ↔ non-`Sharded` partition scrutinee, `:shard-key` shape gate)
// without silently short-circuiting any.
//
// Peer of the sibling M3
// [`validate_politicas_reads_through_lifted_politicas_accessor`]
// (534dc21) multi-axis coherence pin on the per-`:politicas`
// outer mesh-policy composite-reference axis — extends the
// multi-consumer coherence discipline onto the outermost M3
// mesh-slot type's per-Aplicacao distribution composite-
// reference axis, the second `&Composite`-return accessor on
// the outer [`AplicacaoSpec`] type.
// (1) `PlacementWithoutClusters` refusal under the outer
// accessor's reference projection: an empty `:clusters` pool
// must trip the pre-flight refusal probe. The bracket-dispatch's
// first arm reads `p.clusters()` on the reference returned by
// the outer accessor.
let mut spec = three_member_spec();
spec.placement.clusters = Vec::new();
assert_eq!(
spec.validate().unwrap_err(),
AplicacaoError::PlacementWithoutClusters {
estrategia: PlacementStrategy::Replicated,
},
);
assert!(
std::ptr::eq(spec.placement(), &spec.placement),
"the `validate_placement` per-axis bracket-dispatch's \
traversal input must be the same backing composite the \
accessor's reference projection borrows from",
);
// (2) `ShardedWithoutKey` refusal under the outer accessor's
// reference projection: a `Sharded` strategy with a `None`
// `:shard-key` must trip the `Sharded`-arm shape-gate cascade.
// The bracket-dispatch's third arm reads `p.estrategia()` for
// the match scrutinee then `p.shard_key()` for the cascade
// scrutinee, both on the reference returned by the outer
// accessor.
let mut spec = three_member_spec();
spec.placement.estrategia = PlacementStrategy::Sharded;
spec.placement.shard_key = None;
assert_eq!(
spec.validate().unwrap_err(),
AplicacaoError::ShardedWithoutKey,
);
// (3) `ShardKeyOnNonSharded` refusal under the outer accessor's
// reference projection: a non-`Sharded` strategy with a `Some`
// `:shard-key` must trip the declared-but-inert refusal. The
// bracket-dispatch's non-`Sharded` arm reads `p.shard_key()`
// + `p.estrategia()` for the diagnostic on the reference
// returned by the outer accessor.
let mut spec = three_member_spec();
spec.placement.estrategia = PlacementStrategy::Replicated;
spec.placement.shard_key = Some("tenantId".into());
assert_eq!(
spec.validate().unwrap_err(),
AplicacaoError::ShardKeyOnNonSharded {
estrategia: PlacementStrategy::Replicated,
shard_key: "tenantId".into(),
},
);
// (4) Canonical `three_member_spec` `Replicated` fixture passes
// `validate_placement` — every per-axis arm reaches the fall-
// through `Ok(())` without any per-axis refusal firing under the
// outer accessor's reference projection.
let spec = three_member_spec();
assert!(
spec.validate().is_ok(),
"the canonical Replicated placement fixture must pass \
`validate_placement` — every per-axis arm short-circuits on \
valid input under the outer accessor's reference projection",
);
assert_eq!(
spec.placement().estrategia(),
PlacementStrategy::Replicated,
"the outer accessor's reference projection must be the \
canonical Replicated fixture's strategy",
);
assert_eq!(
spec.placement().clusters(),
&["rio", "mar"],
"the outer accessor's reference projection must be the \
canonical Replicated fixture's cluster pool",
);
}
#[test]
fn aplicacao_spec_entrada_returns_entrada_option_ref_byte_equal_across_permutations() {
// The canonical per-`:entrada` outer-composite-optional-
// reference-shape pin: [`AplicacaoSpec::entrada`] must return
// the `:entrada` typed `Option<Entrada>` verbatim as an
// `Option<&Entrada>` reference over the same backing storage
// the raw `self.entrada.as_ref()` field access borrows from,
// byte-equal across every representative fixture in the
// accept-set — the author-omitted `None` shape (the
// "internal-only mesh" partition every downstream external-
// gateway emitter treats as "emit nothing"), the minimal
// singleton `:entrada` composite (host + destination + empty
// paths + default port), the paths-carrying composite (the
// canonical `three_member_spec` fixture's ["/api" "/health"]
// path-list shape every HTTPRoute per-rule fan-out emitter
// reads), and the non-default port composite (the canonical
// custom-port shape the port-fallback resolver reads).
//
// Pins against a future silent detour that returned a fresh-
// cloned `Entrada` copy (which would type-check via a `Clone`
// impl but silently break every downstream caller that
// relied on the reference sharing the composite's backing
// identity), a reference to an operator-resolved overlay
// (the future per-cluster `:entrada-overrides` slot the
// MESH-COMPOSITION §V federation roadmap acknowledges — its
// resolution must land at exactly this accessor body, not
// silently divert the raw slot away from a second consumer),
// a `None` → `Some(Entrada::default)` cluster-default
// projection (which would collapse the load-bearing
// "author-omitted `:entrada` ⇒ internal-only mesh" partition
// the peer `gateway_routes` early-return + `feira app graph`
// internal-only-mesh partition both read), or an axis-
// shuffled projection (a future detour that swapped
// `host` and `para` through the accessor would silently
// split the paired `validate` per-`:entrada` shape-and-
// membership gate's traversal input from the peer
// `caixa_mesh::gateway_routes` Gateway + HTTPRoute emitter's
// fan-out input from the peer `feira app graph` external-
// gateway summary line).
//
// Peer of the sibling M3
// `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
// (534dc21) `&MeshPolicy` byte-equal pin on the per-
// `:politicas` outer mesh-policy composite-reference axis
// and of the sibling M3
// `aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations`
// (9abb8f0) `&Placement` byte-equal pin on the per-
// `:placement` outer distribution-composite composite-
// reference axis — extends the outer-accessor byte-equal-
// projection discipline onto the last unlifted outermost M3
// mesh-slot type's per-Aplicacao external-gateway composite-
// reference axis, the third and final `&Composite`-return
// accessor on the outer [`AplicacaoSpec`] type.
let fixtures: Vec<Option<Entrada>> = vec![
None,
Some(Entrada {
host: "checkout.quero.cloud".into(),
para: "cart".into(),
paths: Vec::new(),
port: DEFAULT_SERVICO_PORT,
}),
Some(Entrada {
host: "checkout.quero.cloud".into(),
para: "cart".into(),
paths: vec!["/api".into(), "/health".into()],
port: DEFAULT_SERVICO_PORT,
}),
Some(Entrada {
host: "checkout.quero.cloud".into(),
para: "cart".into(),
paths: vec!["/api".into()],
port: 9443,
}),
];
for entrada in fixtures {
let s = AplicacaoSpec {
membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
contratos: Vec::new(),
politicas: MeshPolicy::default(),
placement: Placement::default(),
entrada: entrada.clone(),
};
assert_eq!(
s.entrada(),
entrada.as_ref(),
"AplicacaoSpec::entrada must return :entrada verbatim \
(got {:?}, expected {:?})",
s.entrada(),
entrada.as_ref(),
);
match (s.entrada(), s.entrada.as_ref()) {
(Some(a), Some(b)) => assert!(
std::ptr::eq(a, b),
"AplicacaoSpec::entrada accessor and \
self.entrada.as_ref() field access must borrow \
the same backing storage — the accessor is the \
substrate-primitive typed dispatch every \
downstream external-gateway composite consumer \
must route through, and a reference-identity \
split would silently break every consumer that \
relied on the borrow sharing the composite's \
storage",
),
(None, None) => {}
_ => panic!(
"AplicacaoSpec::entrada presence bit must byte-\
equal self.entrada.is_some() — a presence-bit \
drift would silently split the paired `validate` \
per-`:entrada` shape-and-membership gate's \
traversal head from the peer \
caixa-mesh gateway_routes early-return partition \
from the peer `feira app graph` internal-only-\
mesh partition",
),
}
assert_eq!(
s.entrada().is_some(),
s.entrada.is_some(),
"AplicacaoSpec::entrada().is_some() must byte-equal \
self.entrada.is_some() — a presence-bit drift would \
silently split every downstream `Option<&Entrada>` \
consumer's partition on the internal-only-mesh arm",
);
}
}
#[test]
fn validate_reads_through_lifted_entrada_accessor() {
// Multi-consumer coherence pin: the [`AplicacaoSpec::validate`]
// per-`:entrada` shape-and-membership gate (`if let Some(e) =
// self.entrada() { … }`, followed by the per-axis fan-out
// `validate_entrada_para(&e.para)` /
// `EntradaMemberMissing` membership lookup /
// `EmptyEntradaHost` / `validate_entrada_host(&e.host)` /
// per-`e.paths` `validate_entrada_path` traversal) must key
// off the lifted outer accessor, so any future rebrand on
// the typed slot's outer-composite reader shape lands at
// exactly one place. Pins the multi-axis coherence by
// exercising each per-axis refusal end-to-end: (1) the
// author-omitted `None` shape short-circuits past every
// per-`:entrada` refusal (the internal-only mesh partition
// the accessor's `None` arm names), (2) `EntradaMemberMissing`
// fires on a well-shaped but phantom `:para` under the outer
// accessor's reference projection, and (3) the canonical
// `three_member_spec` `:entrada` fixture passes `validate`
// under the outer accessor's reference projection.
//
// Peer of the sibling M3
// [`validate_politicas_reads_through_lifted_politicas_accessor`]
// (534dc21) multi-axis coherence pin on the per-`:politicas`
// outer mesh-policy composite-reference axis and the sibling
// M3
// [`validate_placement_reads_through_lifted_placement_accessor`]
// (9abb8f0) multi-axis coherence pin on the per-`:placement`
// outer distribution-composite composite-reference axis —
// extends the multi-consumer coherence discipline onto the
// last unlifted outermost M3 mesh-slot type's per-Aplicacao
// external-gateway composite-reference axis, the third and
// final `&Composite`-return accessor on the outer
// [`AplicacaoSpec`] type.
// (1) `None` :entrada — the internal-only-mesh partition
// short-circuits past every per-`:entrada` refusal. The outer
// accessor's reference projection reaches the fall-through
// `Ok(())` on the `None` arm without any per-axis refusal
// firing.
let mut spec = three_member_spec();
spec.entrada = None;
assert!(
spec.validate().is_ok(),
"an author-omitted `:entrada` must pass `validate` — the \
internal-only-mesh partition short-circuits past every \
per-`:entrada` refusal under the outer accessor's \
reference projection",
);
assert!(
spec.entrada().is_none(),
"the outer accessor's reference projection must name the \
internal-only-mesh partition per the `None` fixture",
);
// (2) `EntradaMemberMissing` refusal under the outer accessor's
// reference projection: a well-shaped but phantom `:para` must
// trip the membership-lookup refusal. The gate's second arm
// reads `e.para` on the reference returned by the outer
// accessor.
let mut spec = three_member_spec();
if let Some(e) = spec.entrada.as_mut() {
e.para = "phantom".into();
}
assert_eq!(
spec.validate().unwrap_err(),
AplicacaoError::EntradaMemberMissing {
para: "phantom".into(),
},
);
match (spec.entrada(), spec.entrada.as_ref()) {
(Some(a), Some(b)) => assert!(
std::ptr::eq(a, b),
"the `validate` per-`:entrada` gate's traversal head \
must be the same backing composite the accessor's \
reference projection borrows from",
),
_ => panic!("fixture must carry Some(:entrada)"),
}
// (3) Canonical `three_member_spec` `:entrada` fixture passes
// `validate` — every per-axis arm reaches the fall-through
// `Ok(())` without any per-axis refusal firing under the
// outer accessor's reference projection.
let spec = three_member_spec();
assert!(
spec.validate().is_ok(),
"the canonical `:entrada` fixture must pass `validate` — \
every per-axis arm short-circuits on valid input under \
the outer accessor's reference projection",
);
assert!(
spec.entrada().is_some(),
"the outer accessor's reference projection must be the \
canonical `:entrada` fixture's composite",
);
}
#[test]
fn membro_names_matches_inline_membros_projection() {
// Substrate-primitive ≡ inline-projection pin on
// [`AplicacaoSpec::membro_names`]: the lifted membership oracle
// must be byte-for-byte the set the pre-lift inline
// `self.membros().iter().map(Membro::nome).collect()` builder
// produced, on every membership shape the three
// Servico-name-*reference* axes (`:contratos :de`, `:contratos
// :para`, `:entrada :para`) resolve against. Pins the
// projection so a future rebrand of the node-identity axis
// lands at the primitive rather than diverging between the
// per-`:contratos` membership arms still inline at `validate`
// and the lifted `validate_entrada` gate.
for membros in [
vec![],
vec![membro("cart", "^0.1")],
vec![
membro("catalog", "^0.1"),
membro("cart", "^0.1"),
membro("payment", "^0.2"),
],
] {
let mut spec = three_member_spec();
spec.membros = membros;
let inline: std::collections::HashSet<&str> =
spec.membros().iter().map(Membro::nome).collect();
assert_eq!(
spec.membro_names(),
inline,
"the lifted membership oracle must discriminate the \
same node set as the pre-lift inline projection",
);
}
}
#[test]
fn validate_entrada_matches_gate_on_every_per_axis_shape() {
// Per-slot-gate ≡ validate equivalence pin on the lifted
// [`AplicacaoSpec::validate_entrada`]: the named per-slot gate
// must discriminate the same set as [`AplicacaoSpec::validate`]
// on every `:entrada`-covered input, so a future consumer that
// re-validates the one slot (the M4 admission webhook
// re-checking `:entrada` after a gateway-host patch) accepts
// exactly what `feira build` accepts and surfaces the same
// diagnostic on the same input. Covers each of the five gated
// axes plus the two clean-pass shapes (`None` — the
// internal-only-mesh partition — and the canonical fixture).
//
// Peer of the sibling per-slot equivalence pins
// `validate_matches_gate_on_per_axis_and_phase_boundary_shapes`
// / `_on_cross_axis_and_clean_pass_shapes` (f03a154) on the
// `:politicas` slot's compound entry gate, extended here onto
// the `:entrada` slot's newly-named per-slot gate.
/// One `:entrada` equivalence case: a label, the per-axis
/// mutation applied to the canonical fixture's composite, and
/// the diagnostic both the per-slot gate and `validate` must
/// surface on it (`None` = clean pass).
type EntradaCase = (&'static str, fn(&mut Entrada), Option<AplicacaoError>);
let cases: &[EntradaCase] = &[
(
":para shape — empty",
|e| e.para = String::new(),
Some(AplicacaoError::EntradaParaEmpty),
),
(
":para membership — well-shaped phantom",
|e| e.para = "phantom".into(),
Some(AplicacaoError::EntradaMemberMissing {
para: "phantom".into(),
}),
),
(
":host emptiness",
|e| e.host = String::new(),
Some(AplicacaoError::EmptyEntradaHost),
),
(
":port structural floor",
|e| e.port = 0,
Some(AplicacaoError::EntradaPortZero),
),
(
":paths per-entry emptiness",
|e| e.paths = vec![String::new()],
Some(AplicacaoError::EntradaPathEmpty),
),
(
":paths leading-slash grammar",
|e| e.paths = vec!["api/cart".into()],
Some(AplicacaoError::EntradaPathNotAbsolute {
path: "api/cart".into(),
}),
),
(
":paths set-not-multiset",
|e| e.paths = vec!["/api/cart".into(), "/api/cart".into()],
Some(AplicacaoError::EntradaPathDuplicate {
path: "/api/cart".into(),
}),
),
("clean pass — canonical fixture", |_| {}, None),
];
for (label, mutate, expected) in cases {
let mut spec = three_member_spec();
mutate(spec.entrada.as_mut().expect("fixture carries :entrada"));
assert_eq!(
spec.validate_entrada().err(),
*expected,
"per-slot gate disagreed with the expected diagnostic on {label}",
);
assert_eq!(
spec.validate().err(),
*expected,
"`validate` disagreed with the per-slot gate on {label}",
);
}
// The `None` arm is the internal-only-mesh partition: a clean
// pass through both the per-slot gate and `validate`, not a
// refusal.
let mut spec = three_member_spec();
spec.entrada = None;
assert_eq!(spec.validate_entrada().err(), None);
assert_eq!(spec.validate().err(), None);
}
#[test]
fn validate_entrada_resolves_membership_through_own_oracle() {
// Self-containment pin on the lifted per-slot gate:
// [`AplicacaoSpec::validate_entrada`] resolves `:entrada :para`
// against the oracle *it* builds through
// [`AplicacaoSpec::membro_names`], not one threaded down from
// [`AplicacaoSpec::validate`]. A spec whose `:membros` no
// longer contains the `:entrada :para` target must trip
// `EntradaMemberMissing` when the per-slot gate is called
// directly — the shape a future single-slot re-validator
// (the M4 admission webhook) reaches the axis through, without
// re-walking `:membros` / `:contratos` / the sync-cycle
// detector first. Same self-contained posture
// [`AplicacaoSpec::detect_sync_cycles`] already carries for
// the M4 per-edge policy resolver.
let mut spec = three_member_spec();
spec.membros.retain(|m| m.nome() != "cart");
assert_eq!(
spec.validate_entrada().unwrap_err(),
AplicacaoError::EntradaMemberMissing {
para: "cart".into(),
},
"the per-slot gate must resolve `:para` against the oracle \
it builds itself, with no membership set threaded in",
);
assert!(
!spec.membro_names().contains("cart"),
"fixture must have dropped the `:entrada :para` target \
from the graph's node set",
);
}
#[test]
fn validate_contratos_matches_gate_on_every_per_axis_shape() {
// Per-slot-gate ≡ validate equivalence pin on the lifted
// [`AplicacaoSpec::validate_contratos`]: the named per-slot
// gate must discriminate the same set as
// [`AplicacaoSpec::validate`] on every `:contratos`-covered
// input, so a future consumer that re-validates the one slot
// (the M4 admission webhook re-checking `:contratos` after a
// per-`(:de, :para)` edge patch, the per-`:contratos`-edge
// `:politicas` override MESH-COMPOSITION §III.2 #3
// acknowledges — which resolves an effective per-edge
// [`MeshPolicy`] and must re-check the edge's identity closure
// before it can key a per-edge override off the endpoint
// tuple) accepts exactly what `feira build` accepts and
// surfaces the same diagnostic on the same input. Covers each
// of the six gated axes (`:de`/`:para` per-arm shape,
// per-arm graph-membership, structural self-loop, `:wit`
// emptiness) plus the clean-pass canonical fixture; the
// reason-carrying arms (`ContratoCaixaInvalid` on `:de`/`:para`
// shape, `ContratoWitInvalid` on WIT-shape ↔ target dispatch,
// `ContratoDuplicate` on whole-edge dedup) whose `reason:` /
// `target:` carriers depend on library implementation
// details are pinned separately below with a `matches!`
// predicate on the arm identity plus the mirror equivalence
// between the two entry points.
//
// Peer of the sibling per-slot equivalence pins
// `validate_matches_gate_on_per_axis_and_phase_boundary_shapes`
// / `_on_cross_axis_and_clean_pass_shapes` (f03a154) on the
// `:politicas` slot's compound entry gate, and
// `validate_entrada_matches_gate_on_every_per_axis_shape`
// (20cd523) on the `:entrada` slot's per-slot gate — extended
// here onto the `:contratos` slot's newly-named per-slot gate,
// closing the last unlifted per-slot gate on the M3 mesh-slot
// family.
/// One `:contratos` equivalence case: a label, the per-axis
/// mutation applied to the canonical fixture's spec, and the
/// diagnostic both the per-slot gate and `validate` must
/// surface on it (`None` = clean pass).
type ContratoCase = (&'static str, fn(&mut AplicacaoSpec), Option<AplicacaoError>);
let cases: &[ContratoCase] = &[
(
":de shape — empty",
|s| s.contratos[0].de = String::new(),
Some(AplicacaoError::ContratoCaixaEmpty {
slot: crate::render::CONTRATO_AUTHOR_KEY_DE,
}),
),
(
":para shape — empty",
|s| s.contratos[0].para = String::new(),
Some(AplicacaoError::ContratoCaixaEmpty {
slot: crate::render::CONTRATO_AUTHOR_KEY_PARA,
}),
),
(
":de membership — well-shaped phantom",
|s| s.contratos[0].de = "phantom".into(),
Some(AplicacaoError::ContratoMemberMissing {
caixa: "phantom".into(),
}),
),
(
":para membership — well-shaped phantom",
|s| s.contratos[0].para = "phantom".into(),
Some(AplicacaoError::ContratoMemberMissing {
caixa: "phantom".into(),
}),
),
(
"structural self-loop",
|s| s.contratos[0].para = "cart".into(),
Some(AplicacaoError::ContratoSelfLoop {
caixa: "cart".into(),
wit: "wasi:http/proxy".into(),
}),
),
(
":wit emptiness",
|s| s.contratos[0].wit = String::new(),
Some(AplicacaoError::EmptyWit {
de: "cart".into(),
para: "catalog".into(),
}),
),
("clean pass — canonical fixture", |_| {}, None),
];
for (label, mutate, expected) in cases {
let mut spec = three_member_spec();
mutate(&mut spec);
assert_eq!(
spec.validate_contratos().err(),
*expected,
"per-slot gate disagreed with the expected diagnostic on {label}",
);
assert_eq!(
spec.validate().err(),
*expected,
"`validate` disagreed with the per-slot gate on {label}",
);
}
}
#[test]
fn validate_contratos_matches_gate_on_reason_carrying_arms() {
// Companion pin to
// [`validate_contratos_matches_gate_on_every_per_axis_shape`]:
// the per-slot gate ≡ `validate` equivalence on the three
// `:contratos` refusal arms whose diagnostic carries a
// library-owned string ([`AplicacaoError::ContratoCaixaInvalid`]
// and [`AplicacaoError::ContratoWrongTarget`] via the paired
// `is_dns_1123_label` / `WitContract::target` shape helpers,
// and [`AplicacaoError::ContratoDuplicate`] via [`WitTarget::label`]'s
// library-formatted `target:` scalar). Value equality between
// the per-slot gate and `validate` outputs pins the full
// `Option<AplicacaoError>` (including reason-strings), and the
// per-arm `matches!` predicate pins the arm-discriminator
// identity on the specific `Contrato*` variant. Split from
// the primary equivalence pin so each pin body stays under
// [`clippy::too_many_lines`], the same shape the peer
// `validate_matches_gate_on_per_axis_and_phase_boundary_shapes`
// / `_on_cross_axis_and_clean_pass_shapes` split (f03a154)
// carries on the `:politicas` slot's compound entry gate.
type ContratoReasonCase = (
&'static str,
fn(&mut AplicacaoSpec),
fn(&AplicacaoError) -> bool,
);
let cases: &[ContratoReasonCase] = &[
(
":de shape — DNS-1123 invalid",
|s| s.contratos[0].de = "Cart".into(),
|err| {
matches!(
err,
AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. }
if *slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
)
},
),
(
":wit target-shape mismatch — payload on capability arm",
|s| s.contratos[0].wit = "wasi:junk/nope".into(),
|err| {
matches!(
err,
AplicacaoError::ContratoWrongTarget { de, para, wit, .. }
if de == "cart" && para == "catalog" && wit == "wasi:junk/nope"
)
},
),
(
"whole-edge dedup — six-axis identity collision",
|s| {
let dup = s.contratos[0].clone();
s.contratos.push(dup);
},
|err| {
matches!(
err,
AplicacaoError::ContratoDuplicate { de, para, wit, .. }
if de == "cart" && para == "catalog" && wit == "wasi:http/proxy"
)
},
),
];
for (label, mutate, arm_matches) in cases {
let mut spec = three_member_spec();
mutate(&mut spec);
let per_slot = spec.validate_contratos().err();
let gate = spec.validate().err();
assert_eq!(
per_slot, gate,
"per-slot gate and `validate` must return byte-equal \
`Option<AplicacaoError>` on {label} (including \
library-owned reason strings)",
);
let err = per_slot
.as_ref()
.unwrap_or_else(|| panic!("expected refusal on {label}, got clean pass"));
assert!(
arm_matches(err),
"per-slot gate surfaced the wrong arm on {label}: got {err:?}",
);
}
}
#[test]
fn validate_contratos_resolves_membership_through_own_oracle() {
// Self-containment pin on the lifted per-slot gate:
// [`AplicacaoSpec::validate_contratos`] resolves each edge's
// `:de` / `:para` against the oracle *it* builds through
// [`AplicacaoSpec::membro_names`], not one threaded down from
// [`AplicacaoSpec::validate`]. A spec whose `:membros` no
// longer contains a `:contratos` edge's endpoint must trip
// `ContratoMemberMissing` when the per-slot gate is called
// directly — the shape a future single-slot re-validator
// (the M4 admission webhook re-checking `:contratos` after a
// per-`(:de, :para)` edge patch, the M4 per-edge policy
// resolver on the `:politicas` override axis) reaches the
// axis through, without re-walking `:membros` / `:entrada` /
// `:placement` / `:politicas` first. Same self-contained
// posture the peer per-slot gates
// [`AplicacaoSpec::detect_sync_cycles`] and
// [`AplicacaoSpec::validate_entrada`] already carry for the
// same M4 consumers.
let mut spec = three_member_spec();
spec.membros.retain(|m| m.nome() != "catalog");
assert_eq!(
spec.validate_contratos().unwrap_err(),
AplicacaoError::ContratoMemberMissing {
caixa: "catalog".into(),
},
"the per-slot gate must resolve `:de` / `:para` against \
the oracle it builds itself, with no membership set \
threaded in",
);
assert!(
!spec.membro_names().contains("catalog"),
"fixture must have dropped the `:contratos` edge's \
`:para` target from the graph's node set",
);
}
#[test]
fn validate_contratos_folds_cycle_axis_matches_gate() {
// Fold-into-per-slot-gate equivalence pin on the
// cross-edge cycle axis: an [`AplicacaoError::ContratoCycle`]
// surfaces byte-equal through both
// [`AplicacaoSpec::validate_contratos`] and
// [`AplicacaoSpec::validate`] on a fixture whose only defect is
// a synchronous-edge cycle in `:contratos`. Pins the fold that
// moved the cross-edge cycle axis onto the per-slot gate — a
// future silent regression that de-folded the axis back to the
// outer [`AplicacaoSpec::validate`] dispatch (a rebase artifact,
// a peer per-slot gate lift that skipped the cross-axis half of
// the [`MeshPolicy::validate`]-analogous discipline) would
// surface here as `Some(ContratoCycle)` from `validate` and
// `None` from `validate_contratos`.
//
// Cycle fixture is the same shape as the peer
// [`rejects_three_node_synchronous_cycle`] test carries: a
// clean 3-cycle over the HTTP subgraph (catalog → cart →
// payment → catalog), so the per-entry cascade (shape +
// membership + self-loop + `:wit` emptiness + WIT-target +
// whole-edge dedup) passes cleanly and the sole surviving
// refusal shape is the cross-edge cycle axis. The `cycle`
// vector is normalized to a sorted body set for the equality
// compare (the traversal path's starting node depends on
// BTreeMap iteration order, which is deterministic but is not
// the load-bearing property this pin covers).
//
// Peer of the sibling per-slot ≡ `validate` equivalence pins
// [`validate_contratos_matches_gate_on_every_per_axis_shape`]
// (per-entry axes) and
// [`validate_contratos_matches_gate_on_reason_carrying_arms`]
// (parser-owned reason arms) already carry on the six
// per-entry axes — this extends the discipline onto the
// cross-edge cycle axis newly folded into the per-slot gate,
// matching the peer per-slot compound gate
// [`AplicacaoSpec::validate_politicas`] (f03a154) which folded
// both per-axis and cross-axis surfaces on `:politicas`.
let mut spec = three_member_spec();
spec.contratos = vec![
contract_http("catalog", "cart", "/x"),
contract_http("cart", "payment", "/y"),
contract_http("payment", "catalog", "/z"),
];
let per_slot_err = spec.validate_contratos().unwrap_err();
let gate_err = spec.validate().unwrap_err();
assert_eq!(
per_slot_err, gate_err,
"the per-slot gate and `validate` must return byte-equal \
`AplicacaoError::ContratoCycle` on a cycle-only fixture \
— the fold pins the cross-edge axis onto the per-slot \
gate the same way the peer `validate_politicas` fold \
pinned the `:politicas` cross-axis surface",
);
match per_slot_err {
AplicacaoError::ContratoCycle { ref cycle } => {
assert_eq!(
cycle.first(),
cycle.last(),
"cycle traversal must close on the back-edge \
target — the diagnostic shape the peer \
`rejects_three_node_synchronous_cycle` pins",
);
let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
assert_eq!(body.len(), 3, "3-cycle must visit 3 distinct nodes");
assert!(body.contains("cart"));
assert!(body.contains("catalog"));
assert!(body.contains("payment"));
}
other => panic!("expected ContratoCycle, got {other:?}"),
}
}
#[test]
fn validate_contratos_per_entry_arm_fires_before_cycle_arm() {
// Diagnostic-ordering pin on the fold: a `:contratos` fixture
// carrying *both* a per-entry defect (a self-loop, the
// structural-self-edge arm on the per-entry cascade — chosen
// because it never masks or is masked by the cycle diagnostic
// on the peer arms) *and* a would-be synchronous-edge cycle in
// the remaining edges must surface the per-entry diagnostic
// first through both [`AplicacaoSpec::validate_contratos`] and
// [`AplicacaoSpec::validate`] — pinning the fold's canonical
// per-entry-before-cross-edge dispatch ordering, byte-equal to
// the pre-fold `validate`-side sequence
// (`validate_contratos()? → detect_sync_cycles()?`) the
// dispatch encoded verbatim. A silent regression that reversed
// the ordering inside the fold would surface here as a cycle
// diagnostic on a fixture carrying an earlier per-entry defect
// — masking the narrower "this edge is degenerate" arm behind
// the coarser "this graph deadlocks" arm.
//
// Peer of the diagnostic-ordering property the pre-fold
// dispatch encoded at the [`AplicacaoSpec::validate`]
// altitude (`validate_contratos()? → detect_sync_cycles()?`),
// now enforced inside the per-slot gate's own body, so a future
// consumer that reaches only the per-slot gate (the M4
// admission webhook re-checking `:contratos` after a per-edge
// patch) inherits the ordering property by construction.
let mut spec = three_member_spec();
// The three-member fixture already has cart → catalog and
// cart → payment; adding catalog → cart closes a 2-cycle on
// the HTTP subgraph.
spec.contratos
.push(contract_http("catalog", "cart", "/refresh"));
// Add a self-loop on `payment` — the per-entry structural-
// self-edge arm — which must surface first.
spec.contratos
.push(contract_http("payment", "payment", "/loop"));
let per_slot_err = spec.validate_contratos().unwrap_err();
let gate_err = spec.validate().unwrap_err();
assert_eq!(
per_slot_err, gate_err,
"per-slot gate and `validate` must agree on the ordering \
fixture's surfaced diagnostic — a divergence here means \
the fold reshaped one dispatch's ordering without the \
other",
);
assert!(
matches!(
per_slot_err,
AplicacaoError::ContratoSelfLoop { ref caixa, .. }
if caixa == "payment"
),
"the per-entry structural-self-edge arm must fire before \
the cross-edge cycle arm — pinning the fold's per-entry-\
before-cross-edge dispatch ordering byte-equal to the \
pre-fold `validate_contratos()? → detect_sync_cycles()?` \
sequence; got {per_slot_err:?}",
);
}
#[test]
fn validate_contratos_cycle_axis_is_self_contained_on_slot() {
// Self-containment pin on the folded cross-edge cycle axis:
// [`AplicacaoSpec::validate_contratos`] surfaces
// [`AplicacaoError::ContratoCycle`] directly against `&self`
// without depending on the peer per-slot gates
// ([`AplicacaoSpec::validate_membros`],
// [`AplicacaoSpec::validate_entrada`],
// [`AplicacaoSpec::validate_placement`],
// [`AplicacaoSpec::validate_politicas`]) running first — the
// shape a future single-slot re-validator (the M4 admission
// webhook re-checking `:contratos` after a per-`(:de, :para)`
// edge patch, the per-edge policy resolver MESH-COMPOSITION
// §III.2 #3 acknowledges) reaches *both* structural axes on
// the slot through one call. A spec with a per-`:politicas`
// refusal shape (zero `:timeout`, the first per-axis arm the
// peer [`MeshPolicy::validate`] gate covers) AND a
// synchronous-edge cycle in `:contratos` must:
//
// - surface [`AplicacaoError::ContratoCycle`] through the
// per-slot gate `validate_contratos` directly (proves the
// cycle axis reaches the per-slot altitude without the
// peer `:politicas` gate running first);
// - surface [`AplicacaoError::ContratoCycle`] through
// `validate` (which reaches `validate_contratos` before
// `validate_politicas` per the fixed dispatch order), so
// the fold's cross-slot ordering (`:membros` →
// `:contratos` → `:entrada` → `:placement` → `:politicas`)
// is byte-equal to the pre-fold dispatch's ordering.
//
// Same self-contained-on-`&self` posture the peer per-slot
// gates [`AplicacaoSpec::validate_entrada`] (20cd523),
// [`AplicacaoSpec::validate_contratos`] per-entry axis
// (906a5c6), and [`AplicacaoSpec::validate_politicas`]
// (f03a154) already carry — extended here onto the newly-
// folded cross-edge cycle axis. Peer of the sibling per-slot
// self-containment pins
// `validate_entrada_resolves_membership_through_own_oracle`
// and `validate_contratos_resolves_membership_through_own_oracle`
// on the per-entry membership axis — extends the discipline
// onto the cross-edge cycle axis of the same per-slot gate.
let mut spec = three_member_spec();
// Poison `:politicas` — zero-`:timeout` trips the first per-
// axis arm the [`MeshPolicy::validate`] gate covers, so any
// dispatch that reached `:politicas` would surface a
// `:politicas` diagnostic instead of `ContratoCycle`.
spec.politicas.timeout = Some(Duration::from_secs(0));
// Close a synchronous-edge cycle on the HTTP subgraph.
spec.contratos
.push(contract_http("catalog", "cart", "/refresh"));
let per_slot_err = spec.validate_contratos().unwrap_err();
assert!(
matches!(per_slot_err, AplicacaoError::ContratoCycle { .. }),
"the per-slot gate must surface `ContratoCycle` directly \
against `&self` — a peer per-slot gate's regression \
would surface a non-`ContratoCycle` diagnostic here; \
got {per_slot_err:?}",
);
let gate_err = spec.validate().unwrap_err();
assert!(
matches!(gate_err, AplicacaoError::ContratoCycle { .. }),
"`validate`'s five-slot dispatch must reach the fold's \
cross-edge cycle axis on `:contratos` before the peer \
`:politicas` gate — a dispatch-order regression would \
surface a `:politicas` diagnostic here; got {gate_err:?}",
);
// Sanity: the poisoned `:politicas` alone would trip
// [`MeshPolicy::validate`] under the peer per-slot gate, so
// the cycle-first surfacing above is a real ordering property,
// not a case where the `:politicas` axis silently accepts the
// fixture.
let mut politicas_only = three_member_spec();
politicas_only.politicas.timeout = Some(Duration::from_secs(0));
assert!(
politicas_only.validate_politicas().is_err(),
"the poisoned `:politicas` fixture must trip the peer \
per-slot gate on its own — otherwise the self-contained \
cycle-first surfacing above would not be an ordering \
property",
);
}
#[test]
fn wit_contract_require_endpoints_in_folds_per_arm_membership_cascade() {
// Fail-before-pass-after equivalence pin on the lifted
// per-edge substrate primitive [`WitContract::require_endpoints_in`]:
// both arms (`:de` phantom and `:para` phantom) must fire the
// `AplicacaoError::ContratoMemberMissing` diagnostic with a
// `caixa` carrier byte-equal to the offending accessor's
// projection, and `:de` must fire before `:para` when both
// arms would trip on the same call — preserving the canonical
// edge-direction order the peer per-arm shape gate
// [`validate_contrato_caixa`], the [`WitContract::is_self_loop`]
// diagnostic, and every peer per-arm ordering in
// [`AplicacaoSpec::validate_contratos`] already carry.
//
// Two-endpoint oracle covers exactly enough graph nodes to
// exercise each arm in isolation: the `:de` arm fires when
// the source is off-oracle and the destination is on-oracle,
// the `:para` arm fires when the source is on-oracle and the
// destination is off-oracle, and the `:de`-before-`:para`
// ordering falls out from a probe where *both* endpoints are
// off-oracle — the diagnostic's `caixa` field must byte-equal
// the source, not the destination, pinning the primitive's
// arm ordering as `:de` first.
let mut names: std::collections::HashSet<&str> = std::collections::HashSet::new();
names.insert("cart");
names.insert("catalog");
// `:de` phantom, `:para` on-oracle
let de_phantom = contract_http("phantom-de", "catalog", "/x");
let err = de_phantom.require_endpoints_in(&names).unwrap_err();
assert_eq!(
err,
AplicacaoError::ContratoMemberMissing {
caixa: de_phantom.source().to_string(),
},
"the `:de` phantom arm must fire ContratoMemberMissing \
with `caixa` byte-equal to `WitContract::source` — a \
bypass here (a raw `.de.clone()` regression, a divergent \
accessor on a per-CR alias table) would silently split \
the primitive's diagnostic from the substrate-primitive \
scalar accessor every downstream consumer routes through",
);
// `:de` on-oracle, `:para` phantom
let para_phantom = contract_http("cart", "phantom-para", "/x");
let err = para_phantom.require_endpoints_in(&names).unwrap_err();
assert_eq!(
err,
AplicacaoError::ContratoMemberMissing {
caixa: para_phantom.destination().to_string(),
},
"the `:para` phantom arm must fire ContratoMemberMissing \
with `caixa` byte-equal to `WitContract::destination` — \
symmetric callee-side pin to the `:de` arm above",
);
// Both endpoints off-oracle: the `:de` arm must fire first,
// pinning the primitive's canonical edge-direction order.
let both_phantom = contract_http("phantom-de", "phantom-para", "/x");
let err = both_phantom.require_endpoints_in(&names).unwrap_err();
assert_eq!(
err,
AplicacaoError::ContratoMemberMissing {
caixa: both_phantom.source().to_string(),
},
"when both endpoints are off-oracle, the `:de` arm must \
fire before the `:para` arm — preserving byte-equal \
ordering with the pre-lift inline cascade in \
`validate_contratos` and with every peer per-arm \
ordering the sibling per-edge substrate primitives \
already carry",
);
// Both endpoints on-oracle: clean pass.
let clean = contract_http("cart", "catalog", "/x");
clean.require_endpoints_in(&names).unwrap();
}
#[test]
fn validate_contratos_membership_gate_routes_through_require_endpoints_in() {
// Convergence pin: the whole-spec end-to-end route through
// [`AplicacaoSpec::validate_contratos`] must reach the
// per-edge substrate primitive
// [`WitContract::require_endpoints_in`] on every membership
// arm — the diagnostic fired at the per-slot altitude must
// byte-equal the diagnostic the primitive fires when called
// directly on the same edge and the same oracle. Pins the
// primitive as the sole load-bearing gate on the membership
// axis, so any future silent detour that re-inlined the twin
// `if !names.contains(...)` cascade back into the per-slot
// gate (a rebase-artifact regression, an M4 admission-webhook
// consumer that bypassed the primitive) would surface here as
// a byte-equal miss between the two dispatches.
//
// Same equivalence-pin discipline the peer
// [`validate_contratos_matches_gate_on_every_per_axis_shape`]
// pin already carries on the per-slot gate ≡ `validate` axis,
// extended here onto the per-slot gate ≡ per-edge primitive
// axis at one altitude deeper.
for phantom_edge in [
contract_http("phantom-de", "catalog", "/x"),
contract_http("cart", "phantom-para", "/x"),
] {
let mut spec = three_member_spec();
spec.contratos.push(phantom_edge.clone());
let per_slot_err = spec.validate_contratos().unwrap_err();
let primitive_err = phantom_edge
.require_endpoints_in(&spec.membro_names())
.unwrap_err();
assert_eq!(
per_slot_err, primitive_err,
"the per-slot gate must reach the per-edge substrate \
primitive on every membership arm — a bypass here \
would silently split the two dispatches on the \
same edge + same oracle input",
);
// And the diagnostic's `caixa` carrier must byte-equal
// the offending accessor's projection at both altitudes,
// pinning the accessor routing across the whole-spec
// path.
let AplicacaoError::ContratoMemberMissing { ref caixa } = per_slot_err else {
panic!("expected ContratoMemberMissing, got {per_slot_err:?}");
};
let expected = if spec.membro_names().contains(phantom_edge.source()) {
phantom_edge.destination()
} else {
phantom_edge.source()
};
assert_eq!(
caixa, expected,
"the whole-spec ContratoMemberMissing.caixa carrier \
must byte-equal the offending edge's accessor \
projection — a bypass here would silently split \
the wrap envelope's `caixa` field from the \
substrate-primitive scalar accessor every \
downstream consumer routes through",
);
}
}
#[test]
fn port_for_destination_reads_through_lifted_entrada_accessor() {
// Peer coherence pin: the
// [`AplicacaoSpec::port_for_destination`] per-destination
// L4-port fallback resolver's composite-projection seed
// (`self.entrada().filter(…).map_or(…)`) must key off the
// lifted outer accessor. Pins the coherence by exercising
// the resolver end-to-end: (1) the `None` `:entrada` shape
// falls through to `DEFAULT_SERVICO_PORT` under the outer
// accessor's reference projection, (2) a non-matching
// destination falls through to `DEFAULT_SERVICO_PORT` under
// the outer accessor's reference projection, and (3) the
// matching destination resolves to the `:entrada :port`
// value under the outer accessor's reference projection.
//
// Peer of the sibling
// [`validate_reads_through_lifted_entrada_accessor`] multi-
// consumer coherence pin on the same per-`:entrada` outer-
// composite axis — extends the multi-consumer coherence
// discipline onto the second per-`:entrada` production
// consumer, the L4-port fallback resolver.
// (1) `None` :entrada — the resolver's `filter(…).map_or(…)`
// seed falls through to `DEFAULT_SERVICO_PORT` on the `None`
// arm under the outer accessor's reference projection.
let mut spec = three_member_spec();
spec.entrada = None;
assert_eq!(
spec.port_for_destination("cart"),
DEFAULT_SERVICO_PORT,
"the port-fallback resolver must fall through to \
DEFAULT_SERVICO_PORT on an author-omitted `:entrada` \
under the outer accessor's reference projection",
);
// (2) Non-matching destination — the resolver's `filter(…)`
// arm rejects a mismatched destination and falls through
// to `DEFAULT_SERVICO_PORT` under the outer accessor's
// reference projection.
let mut spec = three_member_spec();
if let Some(e) = spec.entrada.as_mut() {
e.para = "cart".into();
e.port = 9443;
}
assert_eq!(
spec.port_for_destination("catalog"),
DEFAULT_SERVICO_PORT,
"the port-fallback resolver must fall through to \
DEFAULT_SERVICO_PORT on a non-matching destination \
under the outer accessor's reference projection",
);
// (3) Matching destination — the resolver's `map_or(…)` arm
// returns the `:entrada :port` value under the outer
// accessor's reference projection.
let mut spec = three_member_spec();
if let Some(e) = spec.entrada.as_mut() {
e.para = "cart".into();
e.port = 9443;
}
assert_eq!(
spec.port_for_destination("cart"),
9443,
"the port-fallback resolver must return the \
`:entrada :port` value on a matching destination \
under the outer accessor's reference projection",
);
}
#[test]
fn mesh_policy_mtls_required_returns_mtls_required_option_byte_equal_across_permutations() {
// The canonical per-`:politicas` `:mtls-required` mTLS-
// enforcement-toggle scalar pin: [`MeshPolicy::mtls_required`]
// must return the `:politicas :mtls-required` typed bool
// verbatim as an `Option<bool>`, byte-equal to the raw field
// access across every value in the three-way accept-set —
// `None` (cluster default applies), `Some(true)` (mTLS
// handshake enforced — the sandboxing-by-default arm the
// MeshPolicy's docstring names), `Some(false)` (handshake
// skipped — the explicit debug-edge opt-out).
//
// Peer of the sibling per-`:placement` [`Placement::shard_key`]
// (7cd2a28) accessor pin on the `Option<&str>` optional-scalar
// axis, extended to the peer per-`:politicas` `Option<Copy-T>`
// shape — first `Option<Copy-T>`-return accessor on the M3
// mesh-slot family. Pins against a future silent detour that
// re-derived the toggle from a peer axis (an accidental
// `.circuit_breaker.is_some()` collapse that assumed mTLS on
// whenever a breaker is set), a `None` → `Some(false)` cluster-
// default projection (the canonical `Option<bool>` → `bool`
// collapse footgun the surrounding `is_empty()` predicate
// guards on the peer emptiness axis), or a `Some(true)` /
// `Some(false)` variant swap that landed on one consumer
// without the other.
for required in [None, Some(true), Some(false)] {
let p = MeshPolicy {
mtls_required: required,
..MeshPolicy::default()
};
assert_eq!(
p.mtls_required(),
required,
"MeshPolicy::mtls_required must return :politicas \
:mtls-required verbatim (got {:?}, expected {required:?})",
p.mtls_required(),
);
assert_eq!(
p.mtls_required(),
p.mtls_required,
"MeshPolicy::mtls_required must byte-equal the raw \
.mtls_required field access across every value in the \
three-way accept-set",
);
}
}
#[test]
fn mesh_policy_is_empty_mtls_required_arm_routes_through_accessor() {
// Composition pin: [`MeshPolicy::is_empty`]'s `mtls_required`
// arm must key off [`MeshPolicy::mtls_required`], not the raw
// `.mtls_required` field access. Structurally: toggling ONLY
// the `mtls_required` slot on an otherwise-default MeshPolicy
// must flip `is_empty()` from `true` (all-`None`) to `false`
// (one axis carries a value); the flip must be observed for
// both `Some(true)` and `Some(false)` since the emptiness
// semantic reads "any axis carries a value" — not "any axis
// carries a truthy value" — the same non-collapsing shape the
// sibling M2 [`crate::LimitsSpec::is_empty`] /
// [`crate::BehaviorSpec::is_empty`] predicates carry on their
// peer `Option<T>`-typed slot surfaces.
//
// Pins against a future silent detour that re-derived the
// emptiness predicate off a peer axis (an accidental
// `.rate_limit.is_none()`-only chain that dropped the
// `mtls_required` arm entirely), a `mtls_required == Some(_)`
// collapse to a truthy-only check (which would silently
// classify `Some(false)` as empty), or an accessor-side
// detour that no longer names the substrate-primitive typed
// dispatch (an accidental `self.mtls_required.unwrap_or(false)
// == false` fallback in the accessor that would silently
// classify both `None` and `Some(false)` as the same value).
//
// Peer of the sibling per-`:placement` [`Placement::shard_key`]
// (7cd2a28) accessor-composition pin on the sibling optional-
// scalar axis — same "the emptiness / shape-gate predicate
// must route through the substrate-primitive typed dispatch"
// discipline extended onto the peer per-`:politicas` emptiness
// predicate.
let empty = MeshPolicy::default();
assert!(
empty.is_empty(),
"MeshPolicy::default() must be is_empty() — every axis \
defaults to None",
);
for required in [Some(true), Some(false)] {
let p = MeshPolicy {
mtls_required: required,
..MeshPolicy::default()
};
assert!(
!p.is_empty(),
"MeshPolicy::is_empty must return false when \
:mtls-required is {required:?} — the emptiness \
predicate reads \"any axis carries a value\", not \
\"any axis carries a truthy value\"",
);
assert_eq!(
p.mtls_required().is_none(),
p.is_empty(),
"when :mtls-required is the only set axis, \
is_empty() must equal mtls_required().is_none() — \
the accessor and the emptiness predicate must \
route through the same substrate-primitive typed \
dispatch on the :mtls-required arm",
);
}
}
#[test]
fn mesh_policy_mtls_required_projects_option_bool_by_copy() {
// The by-copy pin: [`MeshPolicy::mtls_required`] returns
// `Option<bool>` by copy — `Option<bool>` is `Copy` and the
// accessor must return by value, not by reference. Peer of the
// sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
// borrow-invariant pin on the sibling `Option<String>` slot,
// but extended onto the peer `Option<bool>` copy-invariant
// shape — the accessor's returned `Option<bool>` must outlive
// `&self` (multiple calls must return equal values from a
// dropped-`&self` copy, since the returned Option carries no
// borrow), and calling the accessor twice on the same
// MeshPolicy must yield the same `Option<bool>` verbatim
// (idempotent, no side effects on `&self`).
//
// Pins against a future silent detour that returned
// `Option<&bool>` (which would type-check but silently break
// every downstream caller — [`single_field_overlay`]'s first
// parameter is `Option<T: Clone>`, and `&bool` would fold to a
// detached copy at the call site), an accidental
// `Option::as_ref()` projection (`self.mtls_required.as_ref()`
// would also type-check but return `Option<&bool>`), or a
// one-arm-only accessor that reads `Some(*b)` in the Some arm
// but reads a fresh Default::default() in the None arm.
for required in [None, Some(true), Some(false)] {
let p = MeshPolicy {
mtls_required: required,
..MeshPolicy::default()
};
let first = p.mtls_required();
let second = p.mtls_required();
assert_eq!(
first, second,
"MeshPolicy::mtls_required must be idempotent — two \
successive calls on the same &self must return the \
same Option<bool>",
);
assert_eq!(
first, required,
"MeshPolicy::mtls_required must return :politicas \
:mtls-required verbatim by copy — got {first:?}, \
expected {required:?}",
);
}
}
#[test]
fn mesh_policy_retries_returns_retries_option_byte_equal_across_permutations() {
// The canonical per-`:politicas` `:retries` transient-failure-
// retry-budget scalar pin: [`MeshPolicy::retries`] must return
// the `:politicas :retries` typed `u32` verbatim as an
// `Option<u32>`, byte-equal to the raw field access across every
// representative value in the accept-set — `None` (cluster
// default applies — typically "no retries beyond a single
// dispatch attempt" the caixa-mesh `retry_overlay` builder
// documents), `Some(1)` (the lower boundary of the
// `1..=POLICY_RETRIES_MAX` accept-set the surrounding
// `AplicacaoSpec::validate_politicas` gate carves out on the
// sibling `PolicyRetriesZero` refusal), `Some(POLICY_RETRIES_MAX)`
// (the upper boundary the same gate carves out on the sibling
// `PolicyRetriesOverMax` refusal), and `Some(u32::MAX)` (a
// past-the-guard sentinel that pins the accessor doesn't perform
// a silent bounds-collapse at the return path).
//
// Sibling of the peer per-`:politicas`
// [`MeshPolicy::mtls_required`] (c0110f1) accessor pin on the
// sibling `Option<Copy-T>` optional-scalar axis, extended to the
// peer per-`:politicas` `Option<u32>` shape — second
// `Option<Copy-T>`-return accessor on the M3 mesh-slot family.
// Pins against a future silent detour that re-derived the retry
// cap from a peer axis (an accidental `.circuit_breaker
// .as_ref().map(|b| b.max_failures)` collapse that read the
// breaker's max-failure count as a retry budget), a
// `None → Some(0)` cluster-default projection (which would
// silently re-introduce the `PolicyRetriesZero` refusal case at
// the emit boundary), or a bounds-collapsing accessor that
// clamped the return through `POLICY_RETRIES_MAX` (the
// `AplicacaoSpec::validate` gate owns the bounds; the accessor
// must ship the raw slot verbatim so a validate-time gate
// regression surfaces at the emit boundary rather than being
// silently absorbed).
for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
let p = MeshPolicy {
retries,
..MeshPolicy::default()
};
assert_eq!(
p.retries(),
retries,
"MeshPolicy::retries must return :politicas :retries \
verbatim (got {:?}, expected {retries:?})",
p.retries(),
);
assert_eq!(
p.retries(),
p.retries,
"MeshPolicy::retries must byte-equal the raw .retries \
field access across every value in the accept-set",
);
}
}
#[test]
fn mesh_policy_is_empty_retries_arm_routes_through_accessor() {
// Composition pin: [`MeshPolicy::is_empty`]'s `retries` arm
// must key off [`MeshPolicy::retries`], not the raw `.retries`
// field access. Structurally: toggling ONLY the `retries` slot
// on an otherwise-default MeshPolicy must flip `is_empty()`
// from `true` (all-`None`) to `false` (one axis carries a
// value); the flip must be observed for every value in the
// accept-set the surrounding `AplicacaoSpec::validate_politicas`
// gate accepts (`Some(1)`, `Some(POLICY_RETRIES_MAX)`), since
// the emptiness semantic reads "any axis carries a value" —
// not "any axis carries a value the validate gate accepts" —
// the same non-collapsing shape the peer M2
// [`crate::LimitsSpec::is_empty`] /
// [`crate::BehaviorSpec::is_empty`] predicates carry.
//
// Pins against a future silent detour that re-derived the
// emptiness predicate off a peer axis (an accidental
// `.rate_limit.is_none()`-only chain that dropped the
// `retries` arm entirely), a `retries == Some(_)` collapse
// that key-off a validate-gate-clamped bounds check (which
// would silently classify a past-the-guard `Some(u32::MAX)`
// as empty because it fails the `1..=POLICY_RETRIES_MAX`
// check), or an accessor-side detour that no longer names the
// substrate-primitive typed dispatch.
//
// Sibling of the peer per-`:politicas`
// [`MeshPolicy::mtls_required`] (c0110f1) accessor-composition
// pin on the sibling `Option<Copy-T>` optional-scalar axis —
// same "the emptiness predicate must route through the
// substrate-primitive typed dispatch" discipline extended onto
// the peer per-`:politicas` `Option<u32>` axis.
let empty = MeshPolicy::default();
assert!(
empty.is_empty(),
"MeshPolicy::default() must be is_empty() — every axis \
defaults to None",
);
for retries in [Some(1u32), Some(POLICY_RETRIES_MAX)] {
let p = MeshPolicy {
retries,
..MeshPolicy::default()
};
assert!(
!p.is_empty(),
"MeshPolicy::is_empty must return false when \
:retries is {retries:?} — the emptiness \
predicate reads \"any axis carries a value\", not \
\"any axis carries a value the validate gate \
accepts\"",
);
assert_eq!(
p.retries().is_none(),
p.is_empty(),
"when :retries is the only set axis, is_empty() \
must equal retries().is_none() — the accessor and \
the emptiness predicate must route through the same \
substrate-primitive typed dispatch on the :retries \
arm",
);
}
}
#[test]
fn mesh_policy_retries_projects_option_u32_by_copy() {
// The by-copy pin: [`MeshPolicy::retries`] returns
// `Option<u32>` by copy — `Option<u32>` is `Copy` and the
// accessor must return by value, not by reference. Sibling of
// the peer per-`:politicas` [`MeshPolicy::mtls_required`]
// (c0110f1) by-copy pin on the peer `Option<bool>` slot,
// extended onto the sibling `Option<u32>` copy-invariant
// shape — the accessor's returned `Option<u32>` must outlive
// `&self` (multiple calls must return equal values from a
// dropped-`&self` copy, since the returned Option carries no
// borrow), and calling the accessor twice on the same
// MeshPolicy must yield the same `Option<u32>` verbatim
// (idempotent, no side effects on `&self`).
//
// Pins against a future silent detour that returned
// `Option<&u32>` (which would type-check but silently break
// every downstream caller — [`crate::render::single_field_overlay`]'s
// first parameter is `Option<T: Clone>`, and `&u32` would
// fold to a detached copy at the call site), an accidental
// `Option::as_ref()` projection (`self.retries.as_ref()` would
// also type-check but return `Option<&u32>`), or a one-arm-
// only accessor that reads `Some(*n)` in the Some arm but
// reads a fresh `Default::default()` (`0_u32`) in the None
// arm.
for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
let p = MeshPolicy {
retries,
..MeshPolicy::default()
};
let first = p.retries();
let second = p.retries();
assert_eq!(
first, second,
"MeshPolicy::retries must be idempotent — two \
successive calls on the same &self must return the \
same Option<u32>",
);
assert_eq!(
first, retries,
"MeshPolicy::retries must return :politicas :retries \
verbatim by copy — got {first:?}, expected {retries:?}",
);
}
}
#[test]
fn mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations() {
// The canonical per-`:politicas` `:timeout` Gateway-API-mesh
// per-call-deadline scalar pin: [`MeshPolicy::timeout`] must
// return the `:politicas :timeout` typed [`Duration`] verbatim
// as an `Option<Duration>`, byte-equal to the raw field access
// across every representative value in the accept-set — `None`
// (cluster default applies — typically the gateway class's
// implementation-side per-request wall-clock cap the caixa-mesh
// `timeout_overlay` builder documents), `Some(Duration::from_millis(1))`
// (the lower boundary of the `1ms..=POLICY_TIMEOUT_MAX` accept-
// set the surrounding `AplicacaoSpec::validate_politicas` gate
// carves out on the sibling `PolicyTimeoutZero` /
// `PolicyTimeoutNotCanonical` refusals), `Some(POLICY_TIMEOUT_MAX)`
// (the upper boundary the same gate carves out on the sibling
// `PolicyTimeoutExceedsCap` refusal), `Some(Duration::ZERO)`
// (a past-the-guard sentinel that pins the accessor doesn't
// perform a silent bounds-collapse into `None` on the zero-
// Duration arm — validate rejects zero but the accessor must
// ship the raw slot verbatim), and `Some(Duration::MAX)` (a
// past-the-guard sentinel that pins the accessor doesn't
// perform a silent bounds-collapse at the return path).
//
// Sibling of the peer per-`:politicas`
// [`MeshPolicy::retries`] (bdfb399) accessor pin on the sibling
// `Option<u32>` optional-scalar axis and the peer per-
// `:politicas` [`MeshPolicy::mtls_required`] (c0110f1) accessor
// pin on the sibling `Option<bool>` optional-scalar axis,
// extended onto the peer per-`:politicas` `Option<Duration>`
// shape — third `Option<Copy-T>`-return accessor on the M3
// mesh-slot family. Pins against a future silent detour that
// re-derived the per-call cap from a peer axis (an accidental
// `.circuit_breaker.as_ref().map(|b| b.window)` collapse that
// read the breaker's rolling-window duration as a per-call
// deadline), a `None → Some(Duration::MAX)` cluster-default
// projection (which would silently re-introduce the
// MESH-COMPOSITION §V CSE-invariant-violating "no infinite
// blocking" arm at the emit boundary), or a bounds-collapsing
// accessor that clamped the return through `POLICY_TIMEOUT_MAX`
// (the `AplicacaoSpec::validate` gate owns the bounds; the
// accessor must ship the raw slot verbatim so a validate-time
// gate regression surfaces at the emit boundary rather than
// being silently absorbed).
for timeout in [
None,
Some(Duration::from_millis(1)),
Some(POLICY_TIMEOUT_MAX),
Some(Duration::ZERO),
Some(Duration::MAX),
] {
let p = MeshPolicy {
timeout,
..MeshPolicy::default()
};
assert_eq!(
p.timeout(),
timeout,
"MeshPolicy::timeout must return :politicas :timeout \
verbatim (got {:?}, expected {timeout:?})",
p.timeout(),
);
assert_eq!(
p.timeout(),
p.timeout,
"MeshPolicy::timeout must byte-equal the raw .timeout \
field access across every value in the accept-set",
);
}
}
#[test]
fn mesh_policy_is_empty_timeout_arm_routes_through_accessor() {
// Composition pin: [`MeshPolicy::is_empty`]'s `timeout` arm
// must key off [`MeshPolicy::timeout`], not the raw `.timeout`
// field access. Structurally: toggling ONLY the `timeout` slot
// on an otherwise-default MeshPolicy must flip `is_empty()`
// from `true` (all-`None`) to `false` (one axis carries a
// value); the flip must be observed for every value in the
// accept-set the surrounding `AplicacaoSpec::validate_politicas`
// gate accepts (`Some(Duration::from_millis(1))`,
// `Some(POLICY_TIMEOUT_MAX)`), since the emptiness semantic
// reads "any axis carries a value" — not "any axis carries a
// value the validate gate accepts" — the same non-collapsing
// shape the peer M2 [`crate::LimitsSpec::is_empty`] /
// [`crate::BehaviorSpec::is_empty`] predicates carry.
//
// Pins against a future silent detour that re-derived the
// emptiness predicate off a peer axis (an accidental
// `.rate_limit.is_none()`-only chain that dropped the
// `timeout` arm entirely), a `timeout == Some(_)` collapse
// that key-off a validate-gate-clamped bounds check (which
// would silently classify a past-the-guard `Some(Duration::MAX)`
// as empty because it fails the `1ms..=POLICY_TIMEOUT_MAX`
// check), or an accessor-side detour that no longer names the
// substrate-primitive typed dispatch.
//
// Sibling of the peer per-`:politicas`
// [`MeshPolicy::retries`] (bdfb399) accessor-composition pin on
// the sibling `Option<u32>` optional-scalar axis and the peer
// per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
// accessor-composition pin on the sibling `Option<bool>`
// optional-scalar axis — same "the emptiness predicate must
// route through the substrate-primitive typed dispatch"
// discipline extended onto the peer per-`:politicas`
// `Option<Duration>` axis.
let empty = MeshPolicy::default();
assert!(
empty.is_empty(),
"MeshPolicy::default() must be is_empty() — every axis \
defaults to None",
);
for timeout in [Some(Duration::from_millis(1)), Some(POLICY_TIMEOUT_MAX)] {
let p = MeshPolicy {
timeout,
..MeshPolicy::default()
};
assert!(
!p.is_empty(),
"MeshPolicy::is_empty must return false when \
:timeout is {timeout:?} — the emptiness \
predicate reads \"any axis carries a value\", not \
\"any axis carries a value the validate gate \
accepts\"",
);
assert_eq!(
p.timeout().is_none(),
p.is_empty(),
"when :timeout is the only set axis, is_empty() \
must equal timeout().is_none() — the accessor and \
the emptiness predicate must route through the same \
substrate-primitive typed dispatch on the :timeout \
arm",
);
}
}
#[test]
fn mesh_policy_timeout_projects_option_duration_by_copy() {
// The by-copy pin: [`MeshPolicy::timeout`] returns
// `Option<Duration>` by copy — `Option<Duration>` is `Copy`
// and the accessor must return by value, not by reference.
// Sibling of the peer per-`:politicas`
// [`MeshPolicy::retries`] (bdfb399) by-copy pin on the
// sibling `Option<u32>` optional-scalar axis and the peer
// per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
// by-copy pin on the sibling `Option<bool>` optional-scalar
// axis, extended onto the peer per-`:politicas`
// `Option<Duration>` copy-invariant shape — the accessor's
// returned `Option<Duration>` must outlive `&self` (multiple
// calls must return equal values from a dropped-`&self`
// copy, since the returned Option carries no borrow), and
// calling the accessor twice on the same MeshPolicy must
// yield the same `Option<Duration>` verbatim (idempotent, no
// side effects on `&self`).
//
// Pins against a future silent detour that returned
// `Option<&Duration>` (which would type-check but silently
// break every downstream caller — [`crate::render::single_field_overlay`]'s
// first parameter is `Option<T: Clone>`, and `&Duration`
// would fold to a detached copy at the call site), an
// accidental `Option::as_ref()` projection
// (`self.timeout.as_ref()` would also type-check but return
// `Option<&Duration>`), or a one-arm-only accessor that
// reads `Some(*d)` in the Some arm but reads a fresh
// `Default::default()` (`Duration::ZERO`) in the None arm
// (which would silently re-classify every unset `:timeout`
// as the `PolicyTimeoutZero`-refused zero-Duration value at
// the accessor boundary).
for timeout in [
None,
Some(Duration::from_millis(1)),
Some(POLICY_TIMEOUT_MAX),
Some(Duration::ZERO),
Some(Duration::MAX),
] {
let p = MeshPolicy {
timeout,
..MeshPolicy::default()
};
let first = p.timeout();
let second = p.timeout();
assert_eq!(
first, second,
"MeshPolicy::timeout must be idempotent — two \
successive calls on the same &self must return the \
same Option<Duration>",
);
assert_eq!(
first, timeout,
"MeshPolicy::timeout must return :politicas :timeout \
verbatim by copy — got {first:?}, expected {timeout:?}",
);
}
}
#[test]
fn mesh_policy_rate_limit_returns_rate_limit_option_byte_equal_across_permutations() {
// The canonical per-`:politicas` `:rate-limit` Envoy-
// `local_rate_limit`-mesh token-bucket-declaration scalar pin:
// [`MeshPolicy::rate_limit`] must return the `:politicas
// :rate-limit` typed [`RateLimit`] verbatim as an
// `Option<RateLimit>`, byte-equal to the raw field access
// across every representative value in the accept-set — `None`
// (cluster default applies — no per-Aplicacao rate declaration,
// the gateway-class per-listener default arm the future caixa-
// mesh `local_rate_limit_overlay` emitter documents),
// `Some(RateLimit { rate: 1, window: Duration::from_secs(1) })`
// (the lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` rate
// accept-set the surrounding
// [`AplicacaoSpec::validate_politicas`] gate carves out on the
// sibling `PolicyRateLimitZero` refusal, paired with the
// canonical-window "1 second" arm of the three-unit
// `{"s", "m", "h"}` [`is_canonical_rate_limit_window`] bijection),
// `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: Duration::from_secs(3600) })`
// (the upper boundary the same gate carves out on the sibling
// `PolicyRateLimitExceedsCap` refusal, paired with the
// canonical-window "1 hour" arm), `Some(RateLimit { rate: 0, window: Duration::ZERO })`
// (a past-the-guard sentinel that pins the accessor doesn't
// perform a silent bounds-collapse into `None` on the
// zero-rate/zero-window arm — validate rejects zero but the
// accessor must ship the raw slot verbatim so a validate-time
// gate regression surfaces at the emit boundary rather than
// being silently absorbed), and
// `Some(RateLimit { rate: u32::MAX, window: Duration::MAX })`
// (a past-the-guard sentinel that pins the accessor doesn't
// perform a silent bounds-collapse at the return path).
//
// First `Option<Copy-composite-T>`-return accessor pin on the
// M3 mesh-slot family (peer of the sibling per-`:politicas`
// [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` /
// [`MeshPolicy::retries`] bdfb399 `Option<u32>` /
// [`MeshPolicy::timeout`] 7073d0f `Option<Duration>` primitive-
// Copy accessor pins, extended onto the peer per-`:politicas`
// composite-`Copy` shape — [`RateLimit`] is `#[derive(Copy)]`
// and the accessor returns by value). Pins against a future
// silent detour that re-derived the rate declaration from a
// peer axis (an accidental
// `.circuit_breaker.as_ref().map(|b| RateLimit { rate: b.max_failures, window: b.window })`
// collapse that read the breaker's trip threshold + rolling
// window as a rate declaration), a `None → Some(default())`
// cluster-default projection (which would silently re-
// introduce a "cluster default is 0/s" arm the emit boundary
// would take as "declared but inert" — the canonical
// declared-but-inert footgun the sibling
// [`POLICY_RATE_LIMIT_MAX`] cap arm closes on the peer
// amplification-shape axis), a bounds-collapsing accessor
// that clamped `rl.rate` through [`POLICY_RATE_LIMIT_MAX`] or
// clamped `rl.window` through [`is_canonical_rate_limit_window`]
// (the [`AplicacaoSpec::validate`] gate owns the bounds; the
// accessor must ship the raw slot verbatim), or a
// by-reference detour (`Option<&RateLimit>`) that broke every
// downstream consumer keying off `Option<RateLimit>` by-copy.
for rl in [
None,
Some(RateLimit {
rate: 1,
window: Duration::from_secs(1),
}),
Some(RateLimit {
rate: POLICY_RATE_LIMIT_MAX,
window: Duration::from_secs(3600),
}),
Some(RateLimit {
rate: 0,
window: Duration::ZERO,
}),
Some(RateLimit {
rate: u32::MAX,
window: Duration::MAX,
}),
] {
let p = MeshPolicy {
rate_limit: rl,
..MeshPolicy::default()
};
assert_eq!(
p.rate_limit(),
rl,
"MeshPolicy::rate_limit must return :politicas :rate-limit \
verbatim (got {:?}, expected {rl:?})",
p.rate_limit(),
);
assert_eq!(
p.rate_limit(),
p.rate_limit,
"MeshPolicy::rate_limit must byte-equal the raw \
.rate_limit field access across every value in the \
accept-set",
);
}
}
#[test]
fn mesh_policy_is_empty_rate_limit_arm_routes_through_accessor() {
// Composition pin: [`MeshPolicy::is_empty`]'s `rate_limit` arm
// must key off [`MeshPolicy::rate_limit`], not the raw
// `.rate_limit` field access. Structurally: toggling ONLY the
// `rate_limit` slot on an otherwise-default MeshPolicy must
// flip `is_empty()` from `true` (all-`None`) to `false` (one
// axis carries a value); the flip must be observed for every
// representative value in the accept-set the surrounding
// [`AplicacaoSpec::validate_politicas`] gate accepts
// (`Some(RateLimit { rate: 1, window: 1s })`,
// `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: 1h })`),
// since the emptiness semantic reads "any axis carries a
// value" — not "any axis carries a value the validate gate
// accepts" — the same non-collapsing shape the peer M2
// [`crate::LimitsSpec::is_empty`] /
// [`crate::BehaviorSpec::is_empty`] predicates carry.
//
// Pins against a future silent detour that re-derived the
// emptiness predicate off a peer axis (an accidental
// `.timeout.is_none()`-only chain that dropped the
// `rate_limit` arm entirely — the last unlifted inline field
// access on `is_empty` before this lift), a `rate_limit ==
// Some(_)` collapse that key-off a validate-gate-clamped
// bounds check (which would silently classify a past-the-
// guard `Some(RateLimit { rate: 0, window: 0s })` as empty
// because it fails the value-shape gate), or an accessor-
// side detour that no longer names the substrate-primitive
// typed dispatch.
//
// Fourth "the emptiness predicate must route through the
// substrate-primitive typed dispatch" composition pin on the
// M3 mesh-slot family — closes the last unlifted composition
// arm on [`MeshPolicy::is_empty`] (peer of the sibling
// per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
// [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
// 7073d0f is_empty-composition pins on the sibling primitive-
// Copy axes, extended onto the peer per-`:politicas`
// composite-Copy `Option<RateLimit>` axis).
let empty = MeshPolicy::default();
assert!(
empty.is_empty(),
"MeshPolicy::default() must be is_empty() — every axis \
defaults to None",
);
for rl in [
RateLimit {
rate: 1,
window: Duration::from_secs(1),
},
RateLimit {
rate: POLICY_RATE_LIMIT_MAX,
window: Duration::from_secs(3600),
},
] {
let p = MeshPolicy {
rate_limit: Some(rl),
..MeshPolicy::default()
};
assert!(
!p.is_empty(),
"MeshPolicy::is_empty must return false when \
:rate-limit is {rl:?} — the emptiness predicate \
reads \"any axis carries a value\", not \"any axis \
carries a value the validate gate accepts\"",
);
assert_eq!(
p.rate_limit().is_none(),
p.is_empty(),
"when :rate-limit is the only set axis, is_empty() \
must equal rate_limit().is_none() — the accessor \
and the emptiness predicate must route through the \
same substrate-primitive typed dispatch on the \
:rate-limit arm",
);
}
}
#[test]
fn validate_politicas_rate_limit_zero_rate_arm_routes_through_accessor() {
// Composition pin: [`AplicacaoSpec::validate_politicas`]'s
// `:rate-limit` value-shape gate must key off
// [`MeshPolicy::rate_limit`], not the raw `&p.rate_limit`
// field bind. Structurally: a `MeshPolicy` whose only set
// axis is a `Some(RateLimit { rate: 0, .. })` must surface
// the `PolicyRateLimitZero` refusal exactly, and the same
// MeshPolicy with the rate at the canonical lower boundary
// `Some(RateLimit { rate: 1, window: 1s })` must pass validate.
// The pair jointly pins the accessor + validate-gate
// composition: any future silent detour that had the accessor
// omit the `Some(RateLimit { rate: 0, .. })` arm (a
// `.rate_limit().filter(|rl| rl.rate > 0)` collapse) would
// silently absorb the `PolicyRateLimitZero` refusal at the
// accessor boundary — the composition pin catches that at
// caixa-core build time.
//
// Sibling of the peer [`validate_politicas`]
// `:mtls-required` / `:retries` / `:timeout` composition pins
// on the sibling primitive-Copy optional-scalar axes — same
// "the validate / shape-gate predicate must route through the
// substrate-primitive typed dispatch" discipline extended
// onto the peer per-`:politicas` composite-Copy
// `Option<RateLimit>` axis. Second composition-with-accessor
// pin on the M3 mesh-slot `Option<RateLimit>` arm alongside
// the [`MeshPolicy::is_empty`] rate-limit-arm pin above.
let mut spec = three_member_spec();
spec.politicas = MeshPolicy {
rate_limit: Some(RateLimit {
rate: 0,
window: Duration::from_secs(1),
}),
..MeshPolicy::default()
};
assert!(
matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
"validate_politicas must reject rate == 0 with \
PolicyRateLimitZero — the accessor and the validate gate \
must route through the same substrate-primitive typed \
dispatch on the :rate-limit zero-floor arm",
);
spec.politicas = MeshPolicy {
rate_limit: Some(RateLimit {
rate: 1,
window: Duration::from_secs(1),
}),
..MeshPolicy::default()
};
assert!(
spec.validate().is_ok(),
"validate_politicas must accept rate == 1 (the canonical \
lower boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-\
set) with a canonical 1s window",
);
}
#[test]
fn mesh_policy_circuit_breaker_returns_circuit_breaker_option_byte_equal_across_permutations() {
// The canonical per-`:politicas` `:circuit-breaker` Envoy-
// `outlier_detection`-mesh consecutive-failure-ejection scalar
// pin: [`MeshPolicy::circuit_breaker`] must return the
// `:politicas :circuit-breaker` typed [`CircuitBreaker`]
// verbatim as an `Option<CircuitBreaker>`, byte-equal to the
// raw field access across every representative value in the
// accept-set — `None` (cluster default applies — no
// per-Aplicacao breaker declaration, the gateway-class per-
// listener default arm the future caixa-mesh
// `outlier_detection_overlay` emitter documents),
// `Some(CircuitBreaker { max_failures: 1, window: Duration::from_millis(1) })`
// (the lower boundary of the accept-set the surrounding
// [`AplicacaoSpec::validate_politicas`] gate carves out on the
// sibling `PolicyBreakerZeroFailures` / `PolicyBreakerZeroWindow`
// refusals),
// `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`
// (the upper boundary the same gate carves out on the sibling
// `PolicyBreakerMaxFailuresExceedsCap` /
// `PolicyBreakerWindowExceedsCap` refusals),
// `Some(CircuitBreaker { max_failures: 0, window: Duration::ZERO })`
// (a past-the-guard sentinel that pins the accessor doesn't
// perform a silent bounds-collapse into `None` on the
// zero-failures/zero-window arm — validate rejects zero but
// the accessor must ship the raw slot verbatim so a validate-
// time gate regression surfaces at the emit boundary rather
// than being silently absorbed), and
// `Some(CircuitBreaker { max_failures: u32::MAX, window: Duration::MAX })`
// (a past-the-guard sentinel that pins the accessor doesn't
// perform a silent bounds-collapse at the return path).
//
// Second `Option<Copy-composite-T>`-return accessor pin on the
// M3 mesh-slot family (peer of the sibling per-`:politicas`
// [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>`
// composite-Copy accessor pin, and of the sibling per-
// `:politicas` [`MeshPolicy::timeout`] 7073d0f /
// [`MeshPolicy::retries`] bdfb399 /
// [`MeshPolicy::mtls_required`] c0110f1 primitive-Copy
// accessor pins). Pins against a future silent detour that
// re-derived the breaker declaration from a peer axis (an
// accidental `.rate_limit.map(|rl| CircuitBreaker { max_failures: rl.rate, window: rl.window })`
// collapse that read the rate-limit's bucket capacity + refill
// period as a breaker declaration), a `None → Some(default())`
// cluster-default projection (which would silently re-
// introduce the `PolicyBreakerZeroFailures` /
// `PolicyBreakerZeroWindow` refusal cases at the emit
// boundary), a bounds-collapsing accessor that clamped
// `cb.max_failures` through
// [`POLICY_BREAKER_MAX_FAILURES_MAX`] or clamped `cb.window`
// through [`POLICY_BREAKER_WINDOW_MAX`] (the
// [`AplicacaoSpec::validate`] gate owns the bounds; the
// accessor must ship the raw slot verbatim), or a
// by-reference detour (`Option<&CircuitBreaker>`) that broke
// every downstream consumer keying off `Option<CircuitBreaker>`
// by-copy.
for cb in [
None,
Some(CircuitBreaker {
max_failures: 1,
window: Duration::from_millis(1),
}),
Some(CircuitBreaker {
max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
window: POLICY_BREAKER_WINDOW_MAX,
}),
Some(CircuitBreaker {
max_failures: 0,
window: Duration::ZERO,
}),
Some(CircuitBreaker {
max_failures: u32::MAX,
window: Duration::MAX,
}),
] {
let p = MeshPolicy {
circuit_breaker: cb,
..MeshPolicy::default()
};
assert_eq!(
p.circuit_breaker(),
cb,
"MeshPolicy::circuit_breaker must return :politicas \
:circuit-breaker verbatim (got {:?}, expected {cb:?})",
p.circuit_breaker(),
);
assert_eq!(
p.circuit_breaker(),
p.circuit_breaker,
"MeshPolicy::circuit_breaker must byte-equal the raw \
.circuit_breaker field access across every value in \
the accept-set",
);
}
}
#[test]
fn mesh_policy_is_empty_circuit_breaker_arm_routes_through_accessor() {
// Composition pin: [`MeshPolicy::is_empty`]'s `circuit_breaker`
// arm must key off [`MeshPolicy::circuit_breaker`], not the raw
// `.circuit_breaker` field access. Structurally: toggling ONLY
// the `circuit_breaker` slot on an otherwise-default MeshPolicy
// must flip `is_empty()` from `true` (all-`None`) to `false`
// (one axis carries a value); the flip must be observed for
// every representative value in the accept-set the surrounding
// [`AplicacaoSpec::validate_politicas`] gate accepts
// (`Some(CircuitBreaker { max_failures: 1, window: 1ms })`,
// `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`),
// since the emptiness semantic reads "any axis carries a
// value" — not "any axis carries a value the validate gate
// accepts" — the same non-collapsing shape the peer M2
// [`crate::LimitsSpec::is_empty`] /
// [`crate::BehaviorSpec::is_empty`] predicates carry.
//
// Pins against a future silent detour that re-derived the
// emptiness predicate off a peer axis (an accidental
// `.rate_limit.is_none()`-only chain that dropped the
// `circuit_breaker` arm entirely — the last unlifted inline
// field access on `is_empty` before this lift), a
// `circuit_breaker == Some(_)` collapse that key-off a
// validate-gate-clamped bounds check (which would silently
// classify a past-the-guard `Some(CircuitBreaker { max_failures:
// 0, window: 0s })` as empty because it fails the value-shape
// gate), or an accessor-side detour that no longer names the
// substrate-primitive typed dispatch.
//
// Fifth "the emptiness predicate must route through the
// substrate-primitive typed dispatch" composition pin on the
// M3 mesh-slot family — closes the last unlifted composition
// arm on [`MeshPolicy::is_empty`] (peer of the sibling
// per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
// [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
// 7073d0f / [`MeshPolicy::rate_limit`] 21a6c3b is_empty-
// composition pins on the sibling primitive-Copy + composite-
// Copy axes, extended onto the peer per-`:politicas`
// composite-Copy `Option<CircuitBreaker>` axis).
let empty = MeshPolicy::default();
assert!(
empty.is_empty(),
"MeshPolicy::default() must be is_empty() — every axis \
defaults to None",
);
for cb in [
CircuitBreaker {
max_failures: 1,
window: Duration::from_millis(1),
},
CircuitBreaker {
max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
window: POLICY_BREAKER_WINDOW_MAX,
},
] {
let p = MeshPolicy {
circuit_breaker: Some(cb),
..MeshPolicy::default()
};
assert!(
!p.is_empty(),
"MeshPolicy::is_empty must return false when \
:circuit-breaker is {cb:?} — the emptiness predicate \
reads \"any axis carries a value\", not \"any axis \
carries a value the validate gate accepts\"",
);
assert_eq!(
p.circuit_breaker().is_none(),
p.is_empty(),
"when :circuit-breaker is the only set axis, \
is_empty() must equal circuit_breaker().is_none() — \
the accessor and the emptiness predicate must route \
through the same substrate-primitive typed dispatch \
on the :circuit-breaker arm",
);
}
}
#[test]
fn validate_politicas_circuit_breaker_arm_routes_through_accessor() {
// Composition pin: [`AplicacaoSpec::validate_politicas`]'s
// `:circuit-breaker` value-shape gate must key off
// [`MeshPolicy::circuit_breaker`], not the raw
// `&p.circuit_breaker` field bind. Structurally: a `MeshPolicy`
// whose only set axis is a `Some(CircuitBreaker { max_failures:
// 0, .. })` must surface the `PolicyBreakerZeroFailures`
// refusal exactly, and the same MeshPolicy with the breaker at
// the canonical lower boundary
// `Some(CircuitBreaker { max_failures: 1, window: 1ms })` must
// pass validate. The pair jointly pins the accessor +
// validate-gate composition: any future silent detour that had
// the accessor omit the `Some(CircuitBreaker { max_failures:
// 0, .. })` arm (a
// `.circuit_breaker().filter(|cb| cb.max_failures > 0)`
// collapse) would silently absorb the
// `PolicyBreakerZeroFailures` refusal at the accessor
// boundary — the composition pin catches that at caixa-core
// build time.
//
// Sibling of the peer [`validate_politicas`]
// `:mtls-required` / `:retries` / `:timeout` / `:rate-limit`
// composition pins on the sibling primitive-Copy + composite-
// Copy optional-scalar axes — same "the validate / shape-gate
// predicate must route through the substrate-primitive typed
// dispatch" discipline extended onto the peer per-`:politicas`
// composite-Copy `Option<CircuitBreaker>` axis. Second
// composition-with-accessor pin on the M3 mesh-slot
// `Option<CircuitBreaker>` arm alongside the
// [`MeshPolicy::is_empty`] circuit-breaker-arm pin above.
let mut spec = three_member_spec();
spec.politicas = MeshPolicy {
circuit_breaker: Some(CircuitBreaker {
max_failures: 0,
window: Duration::from_millis(1),
}),
..MeshPolicy::default()
};
assert!(
matches!(
spec.validate(),
Err(AplicacaoError::PolicyBreakerZeroFailures)
),
"validate_politicas must reject max_failures == 0 with \
PolicyBreakerZeroFailures — the accessor and the validate \
gate must route through the same substrate-primitive \
typed dispatch on the :circuit-breaker zero-floor arm",
);
spec.politicas = MeshPolicy {
circuit_breaker: Some(CircuitBreaker {
max_failures: 1,
window: Duration::from_millis(1),
}),
..MeshPolicy::default()
};
assert!(
spec.validate().is_ok(),
"validate_politicas must accept a CircuitBreaker at the \
canonical lower boundary (max_failures = 1, window = \
1ms) — the accessor and the validate gate must route \
through the same substrate-primitive typed dispatch on \
the :circuit-breaker arm",
);
}
#[test]
fn circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations() {
// The canonical per-`:politicas :circuit-breaker` `:max-failures`
// Envoy-outlier-detection trip-threshold scalar pin:
// [`CircuitBreaker::max_failures`] must return the
// `:politicas :circuit-breaker :max-failures` typed `u32`
// verbatim, byte-equal to the raw field access across every
// representative value in the accept-set — `1` (the lower
// boundary of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-
// set the surrounding [`AplicacaoSpec::validate_politicas`] gate
// carves out on the sibling `PolicyBreakerZeroFailures` refusal),
// `POLICY_BREAKER_MAX_FAILURES_MAX` (the upper boundary the same
// gate carves out on the sibling `PolicyBreakerMaxFailuresExceedsCap`
// refusal), `0` (a past-the-guard sentinel that pins the accessor
// doesn't perform a silent bounds-collapse into `1` on the zero
// arm — validate rejects zero but the accessor must ship the
// raw slot verbatim so a validate-time gate regression surfaces
// at the emit boundary rather than being silently absorbed),
// `u32::MAX` (a past-the-guard sentinel that pins the accessor
// doesn't perform a silent bounds-collapse through
// `POLICY_BREAKER_MAX_FAILURES_MAX` at the return path).
//
// First sub-struct required-scalar accessor pin on the M3
// mesh-slot family — sibling in shape to the peer per-`:membros`
// [`Membro::nome`] (4a32abf) / [`Membro::versao_requirement`]
// (a40b0e3) required-`String`-carry accessor pins and the peer
// per-`:contratos` [`WitContract::source`] /
// [`WitContract::destination`] (7f0fd43) required-`String`-carry
// accessor pins, extended onto the peer per-`CircuitBreaker`
// required-`u32` scalar-value axis. Pins against a future silent
// detour that re-derived the trip threshold from a peer axis (an
// accidental `self.window.as_secs() as u32` collapse that read
// the breaker's rolling-window duration as a failure count), a
// `0 → 1` cluster-default projection (which would silently absorb
// the `PolicyBreakerZeroFailures` refusal case at the accessor
// boundary), or a bounds-collapsing accessor that clamped the
// return through `POLICY_BREAKER_MAX_FAILURES_MAX` (the
// `AplicacaoSpec::validate` gate owns the bounds; the accessor
// must ship the raw slot verbatim).
for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
let cb = CircuitBreaker {
max_failures,
window: Duration::from_secs(60),
};
assert_eq!(
cb.max_failures(),
max_failures,
"CircuitBreaker::max_failures must return :politicas \
:circuit-breaker :max-failures verbatim (got {}, \
expected {max_failures})",
cb.max_failures(),
);
assert_eq!(
cb.max_failures(),
cb.max_failures,
"CircuitBreaker::max_failures must byte-equal the raw \
.max_failures field access across every value in the \
u32 accept-set",
);
}
}
#[test]
fn validate_politicas_max_failures_zero_floor_arm_routes_through_accessor() {
// Composition pin: [`AplicacaoSpec::validate_politicas`]'s
// `:circuit-breaker :max-failures` zero-floor arm must key off
// [`CircuitBreaker::max_failures`], not the raw `.max_failures`
// field access. Structurally: a `CircuitBreaker { max_failures:
// 0, .. }` embedded in a `:politicas :circuit-breaker` slot must
// surface the `PolicyBreakerZeroFailures` refusal exactly, and a
// `CircuitBreaker { max_failures: 1, .. }` (the lower boundary
// of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-set) must
// pass validate. The pair jointly pins the accessor +
// validate-gate composition: any future silent detour that had
// the accessor return a fresh `1` on the zero arm (a
// `.max_failures().max(1)` collapse) would silently absorb the
// `PolicyBreakerZeroFailures` refusal at the accessor boundary
// and the validate gate would accept a struct-literal
// `CircuitBreaker { max_failures: 0, .. }` — the composition pin
// catches that at caixa-core build time.
//
// Peer of the sibling per-`:politicas`
// [`MeshPolicy::mtls_required`] (c0110f1) /
// [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
// (7073d0f) accessor-composition pins on the sibling optional-
// scalar axes — same "the validate / shape-gate predicate must
// route through the substrate-primitive typed dispatch"
// discipline extended onto the peer per-`CircuitBreaker`
// required-scalar composition axis.
let mut spec = three_member_spec();
spec.politicas = MeshPolicy {
circuit_breaker: Some(CircuitBreaker {
max_failures: 0,
window: Duration::from_secs(60),
}),
..MeshPolicy::default()
};
assert!(
matches!(
spec.validate(),
Err(AplicacaoError::PolicyBreakerZeroFailures)
),
"validate_politicas must reject max_failures == 0 with \
PolicyBreakerZeroFailures — the accessor and the validate \
gate must route through the same substrate-primitive typed \
dispatch on the :max-failures zero-floor arm",
);
spec.politicas = MeshPolicy {
circuit_breaker: Some(CircuitBreaker {
max_failures: 1,
window: Duration::from_secs(60),
}),
..MeshPolicy::default()
};
assert!(
spec.validate().is_ok(),
"validate_politicas must accept max_failures == 1 (the \
lower boundary of the 1..=POLICY_BREAKER_MAX_FAILURES_MAX \
accept-set)",
);
}
#[test]
fn circuit_breaker_max_failures_projects_u32_by_copy() {
// The by-copy pin: [`CircuitBreaker::max_failures`] returns
// `u32` by copy — `u32` is `Copy` and the accessor must return
// by value, not by reference. Peer of the sibling
// per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1) /
// [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
// (7073d0f) by-copy pins on the sibling `Option<Copy-T>`
// optional-scalar axes, extended onto the peer
// per-`CircuitBreaker` required-`u32` copy-invariant shape —
// the accessor's returned `u32` must outlive `&self` (multiple
// calls must return equal values from a dropped-`&self` copy,
// since the returned scalar carries no borrow), and calling
// the accessor twice on the same CircuitBreaker must yield the
// same `u32` verbatim (idempotent, no side effects on `&self`).
//
// Pins against a future silent detour that returned `&u32`
// (which would type-check but silently break every downstream
// arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
// first parameter is `u32`, and `&u32` would fold to a detached
// copy at the call site with a `*` deref the sibling accessors
// don't need), an accidental `.max_failures.wrapping_add(0)`
// detour that returned a fresh copy through an arithmetic
// no-op (breaking a future `const fn` regression), or a
// one-arm-only accessor that returned a saturating value on
// some sentinel input (breaking the pass-through invariant the
// sibling required-scalar accessors carry).
for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
let cb = CircuitBreaker {
max_failures,
window: Duration::from_secs(60),
};
let first = cb.max_failures();
let second = cb.max_failures();
assert_eq!(
first, second,
"CircuitBreaker::max_failures must be idempotent — two \
successive calls on the same &self must return the \
same u32",
);
assert_eq!(
first, max_failures,
"CircuitBreaker::max_failures must return :politicas \
:circuit-breaker :max-failures verbatim by copy — \
got {first}, expected {max_failures}",
);
}
}
#[test]
fn circuit_breaker_window_returns_window_duration_byte_equal_across_permutations() {
// The canonical per-`:politicas :circuit-breaker` `:window`
// Envoy-outlier-detection rolling-observation-interval scalar
// pin: [`CircuitBreaker::window`] must return the
// `:politicas :circuit-breaker :window` typed `Duration`
// verbatim, byte-equal to the raw field access across every
// representative value in the accept-set — `Duration::from_millis(1)`
// (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
// accept-set the surrounding [`AplicacaoSpec::validate_politicas`]
// gate carves out on the sibling `PolicyBreakerZeroWindow`
// refusal), `POLICY_BREAKER_WINDOW_MAX` (the upper boundary the
// same gate carves out on the sibling
// `PolicyBreakerWindowExceedsCap` refusal),
// `Duration::ZERO` (a past-the-guard sentinel that pins the
// accessor doesn't perform a silent bounds-collapse into
// `Duration::from_millis(1)` on the zero arm — validate rejects
// zero but the accessor must ship the raw slot verbatim so a
// validate-time gate regression surfaces at the emit boundary
// rather than being silently absorbed),
// `Duration::from_secs(86_400)` (a past-the-guard sentinel — 24h,
// far above the 1h cap — that pins the accessor doesn't perform
// a silent bounds-collapse through `POLICY_BREAKER_WINDOW_MAX`
// at the return path).
//
// Second sub-struct required-scalar accessor pin on the M3
// mesh-slot family — sibling in shape to the just-landed
// per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
// (3a74062) required-`u32` accessor pin on the peer
// per-`CircuitBreaker` required-axis, extended onto the
// per-sub-struct required-`Duration` axis. Pins against a
// future silent detour that re-derived the observation window
// from a peer axis (an accidental
// `Duration::from_secs(self.max_failures as u64)` collapse that
// read the breaker's trip count as an observation-interval
// duration), a `Duration::ZERO → Duration::from_millis(1)`
// cluster-default projection (which would silently absorb the
// `PolicyBreakerZeroWindow` refusal case at the accessor
// boundary), or a bounds-collapsing accessor that clamped the
// return through `POLICY_BREAKER_WINDOW_MAX` (the
// `AplicacaoSpec::validate` gate owns the bounds; the accessor
// must ship the raw slot verbatim).
for window in [
Duration::from_millis(1),
POLICY_BREAKER_WINDOW_MAX,
Duration::ZERO,
Duration::from_secs(86_400),
] {
let cb = CircuitBreaker {
max_failures: 5,
window,
};
assert_eq!(
cb.window(),
window,
"CircuitBreaker::window must return :politicas \
:circuit-breaker :window verbatim (got {:?}, \
expected {window:?})",
cb.window(),
);
assert_eq!(
cb.window(),
cb.window,
"CircuitBreaker::window must byte-equal the raw \
.window field access across every value in the \
Duration accept-set",
);
}
}
#[test]
fn validate_politicas_window_zero_floor_arm_routes_through_accessor() {
// Composition pin: [`AplicacaoSpec::validate_politicas`]'s
// `:circuit-breaker :window` zero-floor arm must key off
// [`CircuitBreaker::window`], not the raw `.window` field
// access. Structurally: a `CircuitBreaker { window:
// Duration::ZERO, .. }` embedded in a
// `:politicas :circuit-breaker` slot must surface the
// `PolicyBreakerZeroWindow` refusal exactly, and a
// `CircuitBreaker { window: Duration::from_millis(1), .. }`
// (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
// accept-set) must pass validate. The pair jointly pins the
// accessor + validate-gate composition: any future silent
// detour that had the accessor return a fresh
// `Duration::from_millis(1)` on the zero arm (a
// `.window().max(Duration::from_millis(1))` collapse) would
// silently absorb the `PolicyBreakerZeroWindow` refusal at the
// accessor boundary and the validate gate would accept a
// struct-literal `CircuitBreaker { window: Duration::ZERO, .. }`
// — the composition pin catches that at caixa-core build time.
//
// Peer of the sibling per-`CircuitBreaker`
// [`CircuitBreaker::max_failures`] (3a74062) accessor-composition
// pin on the peer required-scalar `:max-failures` axis — same
// "the validate / shape-gate predicate must route through the
// substrate-primitive typed dispatch" discipline extended onto
// the peer per-`CircuitBreaker` required-`Duration` composition
// axis.
let mut spec = three_member_spec();
spec.politicas = MeshPolicy {
circuit_breaker: Some(CircuitBreaker {
max_failures: 5,
window: Duration::ZERO,
}),
..MeshPolicy::default()
};
assert!(
matches!(
spec.validate(),
Err(AplicacaoError::PolicyBreakerZeroWindow)
),
"validate_politicas must reject window == Duration::ZERO \
with PolicyBreakerZeroWindow — the accessor and the \
validate gate must route through the same substrate-\
primitive typed dispatch on the :window zero-floor arm",
);
spec.politicas = MeshPolicy {
circuit_breaker: Some(CircuitBreaker {
max_failures: 5,
window: Duration::from_millis(1),
}),
..MeshPolicy::default()
};
assert!(
spec.validate().is_ok(),
"validate_politicas must accept window == \
Duration::from_millis(1) (the lower boundary of the \
1ms..=POLICY_BREAKER_WINDOW_MAX accept-set)",
);
}
#[test]
fn circuit_breaker_window_projects_duration_by_copy() {
// The by-copy pin: [`CircuitBreaker::window`] returns
// `Duration` by copy — `Duration` is `Copy` and the accessor
// must return by value, not by reference. Peer of the sibling
// per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
// (3a74062) by-copy pin on the peer required-scalar
// `:max-failures` axis, extended onto the peer
// per-`CircuitBreaker` required-`Duration` copy-invariant shape
// — the accessor's returned `Duration` must outlive `&self`
// (multiple calls must return equal values from a
// dropped-`&self` copy, since the returned scalar carries no
// borrow), and calling the accessor twice on the same
// CircuitBreaker must yield the same `Duration` verbatim
// (idempotent, no side effects on `&self`).
//
// Pins against a future silent detour that returned
// `&Duration` (which would type-check but silently break every
// downstream `Duration`-by-value consumer —
// [`crate::render::require_positive_canonical_bounded_duration`]'s
// first parameter is `Duration`, and `&Duration` would fold to
// a detached copy at the call site with a `*` deref the sibling
// accessors don't need), an accidental `.window + Duration::ZERO`
// detour that returned a fresh copy through an arithmetic
// no-op (breaking a future `const fn` regression), or a
// one-arm-only accessor that returned a saturating value on
// some sentinel input (breaking the pass-through invariant the
// sibling required-scalar accessors carry).
for window in [
Duration::from_millis(1),
POLICY_BREAKER_WINDOW_MAX,
Duration::ZERO,
Duration::from_secs(86_400),
] {
let cb = CircuitBreaker {
max_failures: 5,
window,
};
let first = cb.window();
let second = cb.window();
assert_eq!(
first, second,
"CircuitBreaker::window must be idempotent — two \
successive calls on the same &self must return the \
same Duration",
);
assert_eq!(
first, window,
"CircuitBreaker::window must return :politicas \
:circuit-breaker :window verbatim by copy — \
got {first:?}, expected {window:?}",
);
}
}
#[test]
fn port_for_destination_at_contract_destination_returns_entrada_port_when_para_matches() {
// Apex-identity pair-invariant pin composing both substrate-
// primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
// and [`WitContract::destination`] — at the emit-side call shape
// every per-`(:de, :para)` CNP L4 port reader now takes. The
// invariant, evaluated per-edge:
//
// spec.port_for_destination(c.destination()) == expected_port
//
// where `expected_port` is `entrada.port` when
// `c.destination() == entrada.destination()` and
// `DEFAULT_SERVICO_PORT` otherwise. Peer of the sibling
// `port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`
// pin on the per-`:entrada` axis — that pin encodes the apex
// ingress L4 identity via `entrada.destination()`; this pin
// encodes the per-edge L4 identity via `c.destination()`, and
// both compose on the same substrate-primitive resolver so a
// future refactor that silently split either accessor's apex
// behavior surfaces at caixa-core build time.
let mut spec = three_member_spec();
if let Some(e) = spec.entrada.as_mut() {
e.para = "cart".into();
e.port = 8443;
}
let apex_contract = WitContract {
de: "checkout".into(),
para: "cart".into(),
wit: "wasi:http/proxy".into(),
endpoint: Some("/hello".into()),
subject: None,
slot: None,
};
assert_eq!(
spec.port_for_destination(apex_contract.destination()),
8443,
"`spec.port_for_destination(c.destination())` must equal \
`entrada.port` when the contract callee names the ingress \
apex — the CNP per-edge L4 port and the HTTPRoute apex \
backendRef port share this substrate-primitive resolver.",
);
let non_apex_contract = WitContract {
de: "cart".into(),
para: "payment".into(),
wit: "wasi:http/proxy".into(),
endpoint: Some("/charge".into()),
subject: None,
slot: None,
};
assert_eq!(
spec.port_for_destination(non_apex_contract.destination()),
DEFAULT_SERVICO_PORT,
"`spec.port_for_destination(c.destination())` must fall back \
to the substrate-canonical port floor when the contract \
callee is not the ingress apex — the resolver's non-apex \
arm reaches for [`DEFAULT_SERVICO_PORT`] by construction.",
);
}
#[test]
fn membro_key_consts_are_lower_camel_case_shape() {
// Shape-pin: every `MEMBRO_KEY_*` const must be a
// lowerCamelCase byte-sequence (no `snake_case` underscores, no
// `kebab-case` hyphens, no leading colon, no `PascalCase`
// leading capital, no whitespace / dots) — the canonical shape
// the `#[serde(rename_all = "camelCase")]` derive produces on
// [`Membro`]. A future flip to a non-camelCase attribute at
// the derive surfaces both here (this test fails on the
// stale-constant shape) and at
// `membro_serde_keys_match_lifted_membro_key_consts` (that test
// fails on the mismatch between const and derive). Peer with
// `supervisor_key_consts_are_lower_camel_case_shape` (40cc4e5)
// on the sibling `SupervisorSpec` top-level axis.
for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
assert!(
!key.is_empty(),
"MEMBRO_KEY_* must be non-empty (got {key:?})"
);
let first = key.chars().next().unwrap();
assert!(
first.is_ascii_lowercase(),
"MEMBRO_KEY_* must lead with an ASCII-lowercase byte \
(got {key:?}, leads with {first:?})",
);
assert!(
key.chars().all(|c| c.is_ascii_alphanumeric()),
"MEMBRO_KEY_* must be ASCII-alphanumeric only \
— no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
);
}
}
// ── drift-detection: serde-derive-to-CONTRATO_KEY_* identity ─────────
#[test]
fn wit_contract_serde_keys_match_lifted_contrato_key_consts() {
// Load-bearing invariant: the three `CONTRATO_KEY_*` consts
// ([`crate::CONTRATO_KEY_DE`] / [`crate::CONTRATO_KEY_PARA`] /
// [`crate::CONTRATO_KEY_WIT`]) name the exact camelCase JSON
// keys the `#[serde(rename_all = "camelCase")]` attribute on
// [`WitContract`] emits for the required-triad. The three
// sibling payload-arm keys already pin under
// [`WitTarget::HTTP_FIELD_NAME`] / `PUBSUB_FIELD_NAME` /
// `STORE_FIELD_NAME` — pin all six alongside so a future
// accidental `rename_all = "snake_case"` / `"kebab-case"` /
// verbatim-field-name flip at the derive attribute (any of which
// would silently break every downstream JSON consumer that
// reaches for one of the six via `Value::get(...)`) surfaces
// here as a build-time test failure at `aplicacao.rs`, not as an
// apply-time `.get(<stale-canonical-const>)` returning `None`
// far from the derive-attr drift's commit. Peer with the sibling
// `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
// pin on the M3 `:membros` per-entry axis — same discipline the
// `Membro` per-entry lift established, extended here to the
// sibling M3 `WitContract` per-`:contratos` entry axis, the last
// M3 mesh-slot atom top-level `#[serde(rename_all = "camelCase")]`
// axis on the Aplicacao surface without a lifted serde-key peer.
let c = WitContract {
de: "cart".into(),
para: "catalog".into(),
wit: "wasi:http/proxy".into(),
endpoint: Some("/lookup".into()),
subject: None,
slot: None,
};
let json = serde_json::to_string(&c).unwrap();
for key in [
crate::CONTRATO_KEY_DE,
crate::CONTRATO_KEY_PARA,
crate::CONTRATO_KEY_WIT,
WitTarget::HTTP_FIELD_NAME,
] {
let quoted = format!("\"{key}\"");
assert!(
json.contains("ed),
"serialized WitContract must carry the lifted \
CONTRATO_KEY_* / WitTarget::*_FIELD_NAME byte-sequence \
{quoted} verbatim in the JSON emission (got: {json})",
);
}
// Pin the two remaining payload-arm keys by round-tripping a
// `WitContract` under each payload-shape (pub-sub, store) — the
// required-triad appears on every emission but the payload arms
// only surface when their `Option<String>` field is `Some`.
let pubsub = WitContract {
de: "cart".into(),
para: "events".into(),
wit: "nats:pub-sub".into(),
endpoint: None,
subject: Some("orders.placed".into()),
slot: None,
};
let pubsub_json = serde_json::to_string(&pubsub).unwrap();
let pubsub_quoted = format!("\"{}\"", WitTarget::PUBSUB_FIELD_NAME);
assert!(
pubsub_json.contains(&pubsub_quoted),
"serialized pub-sub WitContract must carry the lifted \
WitTarget::PUBSUB_FIELD_NAME byte-sequence {pubsub_quoted} \
verbatim in the JSON emission (got: {pubsub_json})",
);
let store = WitContract {
de: "cart".into(),
para: "sessions".into(),
wit: "wasi:keyvalue/store".into(),
endpoint: None,
subject: None,
slot: Some("cart/$id".into()),
};
let store_json = serde_json::to_string(&store).unwrap();
let store_quoted = format!("\"{}\"", WitTarget::STORE_FIELD_NAME);
assert!(
store_json.contains(&store_quoted),
"serialized store WitContract must carry the lifted \
WitTarget::STORE_FIELD_NAME byte-sequence {store_quoted} \
verbatim in the JSON emission (got: {store_json})",
);
}
#[test]
fn contrato_key_consts_are_pairwise_distinct() {
// Cross-axis drift-detection pin: a future collapse of the six
// canonical [`WitContract`] per-entry byte-strings onto the same
// value (e.g. an accidental copy-paste flip of
// [`crate::CONTRATO_KEY_WIT`] to also read `"de"`, or a
// rebrand of [`WitTarget::STORE_FIELD_NAME`] to match the
// sibling [`WitTarget::HTTP_FIELD_NAME`]) would silently reroute
// every downstream probe on one axis onto the sibling axis's
// overlay entry and pass every propagation-probe test that
// expected only the stale axis's value. Peer of the sibling
// two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0) —
// widened here to the six-way axis the `WitContract`
// required-triad + `WitTarget` payload-triad jointly cover.
let all = [
crate::CONTRATO_KEY_DE,
crate::CONTRATO_KEY_PARA,
crate::CONTRATO_KEY_WIT,
WitTarget::HTTP_FIELD_NAME,
WitTarget::PUBSUB_FIELD_NAME,
WitTarget::STORE_FIELD_NAME,
];
for (i, a) in all.iter().enumerate() {
for b in all.iter().skip(i + 1) {
assert_ne!(
a, b,
"CONTRATO_KEY_* / WitTarget::*_FIELD_NAME consts \
must be pairwise-distinct canonical byte-sequences \
— got `{a}` == `{b}`",
);
}
}
}
#[test]
fn contrato_key_consts_are_lower_camel_case_shape() {
// Shape-pin: every `CONTRATO_KEY_*` (and every peer
// `WitTarget::*_FIELD_NAME`) const must be a lowerCamelCase
// byte-sequence (no `snake_case` underscores, no `kebab-case`
// hyphens, no leading colon, no `PascalCase` leading capital, no
// whitespace / dots) — the canonical shape the
// `#[serde(rename_all = "camelCase")]` derive produces on
// [`WitContract`]. A future flip to a non-camelCase attribute at
// the derive surfaces both here (this test fails on the
// stale-constant shape) and at
// `wit_contract_serde_keys_match_lifted_contrato_key_consts`
// (that test fails on the mismatch between const and derive).
// Peer with `membro_key_consts_are_lower_camel_case_shape`
// (ce80ca0) on the sibling `Membro` per-entry axis.
for key in [
crate::CONTRATO_KEY_DE,
crate::CONTRATO_KEY_PARA,
crate::CONTRATO_KEY_WIT,
WitTarget::HTTP_FIELD_NAME,
WitTarget::PUBSUB_FIELD_NAME,
WitTarget::STORE_FIELD_NAME,
] {
assert!(
!key.is_empty(),
"CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
non-empty (got {key:?})"
);
let first = key.chars().next().unwrap();
assert!(
first.is_ascii_lowercase(),
"CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must lead \
with an ASCII-lowercase byte (got {key:?}, leads with \
{first:?})",
);
assert!(
key.chars().all(|c| c.is_ascii_alphanumeric()),
"CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
ASCII-alphanumeric only — no `_` / `-` / `:` / `.` / \
whitespace (got {key:?})",
);
}
}
// ── drift-detection: serde-derive-to-ENTRADA_KEY_* identity ──────────
#[test]
fn entrada_serde_keys_match_lifted_entrada_key_consts() {
// Load-bearing invariant: the four `ENTRADA_KEY_*` consts
// ([`crate::ENTRADA_KEY_HOST`] / [`crate::ENTRADA_KEY_PARA`] /
// [`crate::ENTRADA_KEY_PATHS`] / [`crate::ENTRADA_KEY_PORT`])
// name the exact camelCase JSON keys the
// `#[serde(rename_all = "camelCase")]` attribute on
// [`Entrada`] emits. Serialize a fully-populated `Entrada` and
// pin that each canonical byte-sequence appears verbatim in the
// JSON — a future accidental `rename_all = "snake_case"` /
// `"kebab-case"` / verbatim-field-name flip at the derive
// attribute (any of which would silently break every downstream
// JSON consumer that reaches for one of the four consts via
// `Value::get(...)` — the [`caixa_mesh`] Gateway/HTTPRoute
// emitter's per-Aplicacao hostname/paths/port projection, the
// future `app-operator` reconciler's per-Aplicacao ingress
// bind, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
// materializer's admission-time cross-check) surfaces here as
// a build-time test failure at `aplicacao.rs`, not as an
// apply-time `.get(<stale-canonical-const>)` returning `None`
// far from the derive-attr drift's commit. Peer with the
// sibling
// `wit_contract_serde_keys_match_lifted_contrato_key_consts`
// (ca463a4) and
// `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
// pins on the M3 collection-slot atom axes — same discipline
// both collection-slot lifts established, extended here to the
// singleton `:entrada` mesh-slot atom axis, the last M3
// typed-struct top-level `#[serde(rename_all = "camelCase")]`
// axis on the Aplicacao surface without a lifted serde-key
// peer.
let e = Entrada {
host: "checkout.quero.cloud".into(),
para: "cart".into(),
paths: vec!["/cart".into()],
port: 8080,
};
let json = serde_json::to_string(&e).unwrap();
for key in [
crate::ENTRADA_KEY_HOST,
crate::ENTRADA_KEY_PARA,
crate::ENTRADA_KEY_PATHS,
crate::ENTRADA_KEY_PORT,
] {
let quoted = format!("\"{key}\"");
assert!(
json.contains("ed),
"serialized Entrada must carry the lifted ENTRADA_KEY_* \
byte-sequence {quoted} verbatim in the JSON emission \
(got: {json})",
);
}
}
#[test]
fn entrada_key_consts_are_pairwise_distinct() {
// Cross-axis drift-detection pin: a future collapse of the four
// canonical [`Entrada`] singleton byte-strings onto the same
// value (e.g. an accidental copy-paste flip of
// [`crate::ENTRADA_KEY_PARA`] to also read `"host"`) would
// silently reroute every downstream probe on one axis onto the
// sibling axis's overlay entry and pass every propagation-probe
// test that expected only the stale axis's value — the
// Gateway/HTTPRoute emitter would read the hostname string
// where the destination-Servico name was expected (or vice
// versa), the admission-webhook cross-check would compare the
// wrong pair of values, and the resulting Gateway resource
// would either be admitted with garbage or rejected at the
// controller far from the rebrand commit's source. Peer of the
// sibling four-way distinct pin on the `SUPERVISOR_KEY_*`
// tetrad (40cc4e5), the two-way distinct pin on the
// `MEMBRO_KEY_*` pair (ce80ca0), and the six-way distinct pin
// on the `CONTRATO_KEY_*` triad + `WitTarget::*_FIELD_NAME`
// triad (ca463a4).
let all = [
crate::ENTRADA_KEY_HOST,
crate::ENTRADA_KEY_PARA,
crate::ENTRADA_KEY_PATHS,
crate::ENTRADA_KEY_PORT,
];
for (i, a) in all.iter().enumerate() {
for b in all.iter().skip(i + 1) {
assert_ne!(
a, b,
"ENTRADA_KEY_* consts must be pairwise-distinct \
canonical byte-sequences — got `{a}` == `{b}`",
);
}
}
}
#[test]
fn entrada_key_consts_are_lower_camel_case_shape() {
// Shape-pin: every `ENTRADA_KEY_*` const must be a
// lowerCamelCase byte-sequence (no `snake_case` underscores, no
// `kebab-case` hyphens, no leading colon, no `PascalCase`
// leading capital, no whitespace / dots) — the canonical shape
// the `#[serde(rename_all = "camelCase")]` derive produces on
// [`Entrada`]. A future flip to a non-camelCase attribute at
// the derive surfaces both here (this test fails on the
// stale-constant shape) and at
// `entrada_serde_keys_match_lifted_entrada_key_consts` (that
// test fails on the mismatch between const and derive). Peer
// with `membro_key_consts_are_lower_camel_case_shape` (ce80ca0)
// and `contrato_key_consts_are_lower_camel_case_shape`
// (ca463a4) on the sibling M3 per-`:membros` and per-`:contratos`
// entry axes.
for key in [
crate::ENTRADA_KEY_HOST,
crate::ENTRADA_KEY_PARA,
crate::ENTRADA_KEY_PATHS,
crate::ENTRADA_KEY_PORT,
] {
assert!(
!key.is_empty(),
"ENTRADA_KEY_* must be non-empty (got {key:?})"
);
let first = key.chars().next().unwrap();
assert!(
first.is_ascii_lowercase(),
"ENTRADA_KEY_* must lead with an ASCII-lowercase byte \
(got {key:?}, leads with {first:?})",
);
assert!(
key.chars().all(|c| c.is_ascii_alphanumeric()),
"ENTRADA_KEY_* must be ASCII-alphanumeric only \
— no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
);
}
}
// ── drift-detection: serde-derive-to-POLITICAS_KEY_* identity ────────
#[test]
fn mesh_policy_serde_keys_match_lifted_politicas_key_consts() {
// Load-bearing invariant: the five `POLITICAS_KEY_*` consts
// ([`crate::POLITICAS_KEY_TIMEOUT`] /
// [`crate::POLITICAS_KEY_RETRIES`] /
// [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] /
// [`crate::POLITICAS_KEY_MTLS_REQUIRED`] /
// [`crate::POLITICAS_KEY_RATE_LIMIT`]) name the exact camelCase
// JSON keys the `#[serde(rename_all = "camelCase")]` attribute
// on [`MeshPolicy`] emits. Three of the five axes
// (`circuit_breaker` → `circuitBreaker`, `mtls_required` →
// `mtlsRequired`, `rate_limit` → `rateLimit`) are non-trivial
// camelCase transforms — the derive-attribute is load-bearing
// on those, unlike the sibling `Entrada` / `Membro` /
// `WitContract` structs whose fields are all lowercase-single-
// word and where the derive is a no-op on every axis.
// Serialize a fully-populated [`MeshPolicy`] (every axis
// `Some(…)` so `skip_serializing_if = "Option::is_none"` fires
// on none of the five slots) and pin that each canonical
// byte-sequence appears verbatim in the JSON — a future
// accidental `rename_all = "snake_case"` / `"kebab-case"` /
// verbatim-field-name flip at the derive attribute (any of
// which would silently break every downstream JSON consumer
// that reaches for one of the five consts via
// `Value::get(...)` — the future M4 per-edge `:politicas`
// overlay projection onto Cilium `L7Rules` and Gateway API
// `HTTPRoute` backend timeouts, the future
// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
// admission-time mesh-policy cross-check, the future
// `feira lint` per-`:politicas` bound-check gate) surfaces here
// as a build-time test failure at `aplicacao.rs`, not as an
// apply-time `.get(<stale-canonical-const>)` returning `None`
// far from the derive-attr drift's commit. Peer with the
// sibling `entrada_serde_keys_match_lifted_entrada_key_consts`
// (a3d6162), `wit_contract_serde_keys_match_lifted_contrato_key_consts`
// (ca463a4), and `membro_serde_keys_match_lifted_membro_key_consts`
// (ce80ca0) pins on the M3 collection-slot / singleton-slot
// atom axes — same discipline every M3 sibling lift
// established, extended here to the singleton `:politicas`
// mesh-slot atom axis, closing the last M3 typed-struct
// top-level `#[serde(rename_all = "camelCase")]` axis on the
// Aplicacao surface without a lifted serde-key peer.
let p = MeshPolicy {
timeout: Some(Duration::from_secs(30)),
retries: Some(3),
circuit_breaker: Some(CircuitBreaker {
max_failures: 5,
window: Duration::from_secs(60),
}),
mtls_required: Some(true),
rate_limit: Some(RateLimit {
rate: 100,
window: Duration::from_secs(1),
}),
};
let json = serde_json::to_string(&p).unwrap();
for key in [
crate::POLITICAS_KEY_TIMEOUT,
crate::POLITICAS_KEY_RETRIES,
crate::POLITICAS_KEY_CIRCUIT_BREAKER,
crate::POLITICAS_KEY_MTLS_REQUIRED,
crate::POLITICAS_KEY_RATE_LIMIT,
] {
let quoted = format!("\"{key}\"");
assert!(
json.contains("ed),
"serialized MeshPolicy must carry the lifted \
POLITICAS_KEY_* byte-sequence {quoted} verbatim in the \
JSON emission (got: {json})",
);
}
}
#[test]
fn politicas_key_consts_are_pairwise_distinct() {
// Cross-axis drift-detection pin: a future collapse of the five
// canonical [`MeshPolicy`] singleton byte-strings onto the same
// value (e.g. an accidental copy-paste flip of
// [`crate::POLITICAS_KEY_RETRIES`] to also read `"timeout"`)
// would silently reroute every downstream probe on one axis
// onto the sibling axis's overlay entry and pass every
// propagation-probe test that expected only the stale axis's
// value — the M4 per-edge `:politicas` overlay projection would
// read the retry-count string where the timeout duration was
// expected (or vice versa), the CR materializer's admission
// cross-check would compare the wrong pair of values, and the
// resulting mesh reconciler would either bind the wrong axis
// or reject the resource at reconcile far from the rebrand
// commit's source. Peer of the sibling four-way distinct pin
// on the `SUPERVISOR_KEY_*` tetrad (40cc4e5), the four-way
// distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
// two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0),
// and the six-way distinct pin on the `CONTRATO_KEY_*` triad +
// `WitTarget::*_FIELD_NAME` triad (ca463a4).
let all = [
crate::POLITICAS_KEY_TIMEOUT,
crate::POLITICAS_KEY_RETRIES,
crate::POLITICAS_KEY_CIRCUIT_BREAKER,
crate::POLITICAS_KEY_MTLS_REQUIRED,
crate::POLITICAS_KEY_RATE_LIMIT,
];
for (i, a) in all.iter().enumerate() {
for b in all.iter().skip(i + 1) {
assert_ne!(
a, b,
"POLITICAS_KEY_* consts must be pairwise-distinct \
canonical byte-sequences — got `{a}` == `{b}`",
);
}
}
}
#[test]
fn politicas_key_consts_are_lower_camel_case_shape() {
// Shape-pin: every `POLITICAS_KEY_*` const must be a
// lowerCamelCase byte-sequence (no `snake_case` underscores, no
// `kebab-case` hyphens, no leading colon, no `PascalCase`
// leading capital, no whitespace / dots) — the canonical shape
// the `#[serde(rename_all = "camelCase")]` derive produces on
// [`MeshPolicy`]. A future flip to a non-camelCase attribute
// at the derive surfaces both here (this test fails on the
// stale-constant shape) and at
// `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
// (that test fails on the mismatch between const and derive).
// Peer with `entrada_key_consts_are_lower_camel_case_shape`
// (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
// (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
// (ca463a4) on the sibling M3 typed-struct axes.
for key in [
crate::POLITICAS_KEY_TIMEOUT,
crate::POLITICAS_KEY_RETRIES,
crate::POLITICAS_KEY_CIRCUIT_BREAKER,
crate::POLITICAS_KEY_MTLS_REQUIRED,
crate::POLITICAS_KEY_RATE_LIMIT,
] {
assert!(
!key.is_empty(),
"POLITICAS_KEY_* must be non-empty (got {key:?})"
);
let first = key.chars().next().unwrap();
assert!(
first.is_ascii_lowercase(),
"POLITICAS_KEY_* must lead with an ASCII-lowercase \
byte (got {key:?}, leads with {first:?})",
);
assert!(
key.chars().all(|c| c.is_ascii_alphanumeric()),
"POLITICAS_KEY_* must be ASCII-alphanumeric only — \
no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
);
}
}
// ── drift-detection: serde-derive-to-CIRCUIT_BREAKER_KEY_* identity ──
#[test]
fn circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts() {
// Load-bearing invariant: the two `CIRCUIT_BREAKER_KEY_*` consts
// ([`crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES`] /
// [`crate::CIRCUIT_BREAKER_KEY_WINDOW`]) name the exact camelCase
// JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
// [`CircuitBreaker`] emits inside the
// [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] sub-block. One of the
// two axes (`max_failures` → `maxFailures`) is a non-trivial
// camelCase transform — the derive-attribute is load-bearing on
// that axis, unlike the sibling `window` field where the derive
// is a no-op. Serialize a fully-populated [`CircuitBreaker`] and
// pin that each canonical byte-sequence appears verbatim in the
// JSON — a future accidental `rename_all = "snake_case"` /
// `"kebab-case"` / verbatim-field-name flip at the derive
// attribute (any of which would silently break every downstream
// JSON consumer that reaches for one of the two consts via
// `Value::get(POLITICAS_KEY_CIRCUIT_BREAKER).and_then(|v|
// v.get(CIRCUIT_BREAKER_KEY_MAX_FAILURES))` — the future M4
// per-edge `:politicas` overlay projection onto the mesh's
// per-backend consecutive-failure-counter tripping threshold, the
// future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
// admission-time breaker cross-check, the future `feira lint`
// per-`:politicas :circuit-breaker` bound-check gate) surfaces
// here as a build-time test failure at `aplicacao.rs`, not as an
// apply-time `.get(<stale-canonical-const>)` returning `None`
// far from the derive-attr drift's commit. Peer with the sibling
// `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
// (b55cca7) parent-axis pin — that test pins the outer
// sub-block key the derive on [`MeshPolicy`] emits, this test
// pins the inner keys the derive on the payload type emits, so
// the two together lock the whole [`MeshPolicy`] breaker-tuning
// shape end-to-end at build time.
let cb = CircuitBreaker {
max_failures: 5,
window: Duration::from_secs(60),
};
let json = serde_json::to_string(&cb).unwrap();
for key in [
crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
crate::CIRCUIT_BREAKER_KEY_WINDOW,
] {
let quoted = format!("\"{key}\"");
assert!(
json.contains("ed),
"serialized CircuitBreaker must carry the lifted \
CIRCUIT_BREAKER_KEY_* byte-sequence {quoted} verbatim \
in the JSON emission (got: {json})",
);
}
}
#[test]
fn circuit_breaker_key_consts_are_pairwise_distinct() {
// Cross-axis drift-detection pin: a future collapse of the two
// canonical [`CircuitBreaker`] sub-block byte-strings onto the
// same value (e.g. an accidental copy-paste flip of
// [`crate::CIRCUIT_BREAKER_KEY_WINDOW`] to also read
// `"maxFailures"`) would silently reroute every downstream
// probe on one axis onto the sibling axis's overlay entry and
// pass every propagation-probe test that expected only the
// stale axis's value — the M4 per-edge `:politicas` overlay
// projection would read the failure-count where the window
// duration was expected (or vice versa), the CR materializer's
// admission cross-check would compare the wrong pair of values,
// and the resulting mesh reconciler would either bind the wrong
// axis or reject the resource at reconcile far from the rebrand
// commit's source. Peer of the sibling five-way distinct pin on
// the `POLITICAS_KEY_*` pentad (b55cca7), the four-way distinct
// pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the two-way
// distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and the
// six-way distinct pin on the `CONTRATO_KEY_*` triad +
// `WitTarget::*_FIELD_NAME` triad (ca463a4).
let all = [
crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
crate::CIRCUIT_BREAKER_KEY_WINDOW,
];
for (i, a) in all.iter().enumerate() {
for b in all.iter().skip(i + 1) {
assert_ne!(
a, b,
"CIRCUIT_BREAKER_KEY_* consts must be pairwise-distinct \
canonical byte-sequences — got `{a}` == `{b}`",
);
}
}
}
#[test]
fn circuit_breaker_key_consts_are_lower_camel_case_shape() {
// Shape-pin: every `CIRCUIT_BREAKER_KEY_*` const must be a
// lowerCamelCase byte-sequence (no `snake_case` underscores, no
// `kebab-case` hyphens, no leading colon, no `PascalCase`
// leading capital, no whitespace / dots) — the canonical shape
// the `#[serde(rename_all = "camelCase")]` derive produces on
// [`CircuitBreaker`]. A future flip to a non-camelCase attribute
// at the derive surfaces both here (this test fails on the
// stale-constant shape) and at
// `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
// (that test fails on the mismatch between const and derive).
// Peer with `politicas_key_consts_are_lower_camel_case_shape`
// (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
// (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
// (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
// (ca463a4) on the sibling M3 typed-struct axes.
for key in [
crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
crate::CIRCUIT_BREAKER_KEY_WINDOW,
] {
assert!(
!key.is_empty(),
"CIRCUIT_BREAKER_KEY_* must be non-empty (got {key:?})"
);
let first = key.chars().next().unwrap();
assert!(
first.is_ascii_lowercase(),
"CIRCUIT_BREAKER_KEY_* must lead with an ASCII-lowercase \
byte (got {key:?}, leads with {first:?})",
);
assert!(
key.chars().all(|c| c.is_ascii_alphanumeric()),
"CIRCUIT_BREAKER_KEY_* must be ASCII-alphanumeric only — \
no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
);
}
}
// ── drift-detection: serde-derive-to-M3_PLACEMENT_KEY_* identity ─────
#[test]
fn placement_serde_keys_match_lifted_m3_placement_key_consts() {
// Load-bearing invariant: the four `M3_PLACEMENT_KEY_*` consts
// ([`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] /
// [`crate::M3_PLACEMENT_KEY_CLUSTERS`] /
// [`crate::M3_PLACEMENT_KEY_AFFINITY`] /
// [`crate::M3_PLACEMENT_KEY_SHARD_KEY`]) name the exact camelCase
// JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
// [`Placement`] emits. One of the four axes (`shard_key` →
// `shardKey`) is a non-trivial camelCase transform — the
// derive-attribute is load-bearing on that axis, unlike the
// sibling `estrategia` / `clusters` / `affinity` axes whose
// source-side field names carry no `_` and where the derive is a
// no-op. Serialize a fully-populated [`Placement`] (both
// `Option`-carrying axes `Some(_)` so
// `skip_serializing_if = "Option::is_none"` fires on neither of
// the two optional slots) and pin that each canonical
// byte-sequence appears verbatim in the JSON — a future
// accidental `rename_all = "snake_case"` / `"kebab-case"` /
// verbatim-field-name flip at the derive attribute (any of which
// would silently break every downstream consumer that reaches
// for one of the four consts via
// `Value::get(M3_KEY_PLACEMENT).and_then(|v|
// v.get(M3_PLACEMENT_KEY_*))` — the `lareira-fleet-programs`
// aggregator's per-cluster fanout filter keying off
// `placement.clusters`, the M3 shard-pool dispatch materializer
// keying off `placement.shardKey`, the M3 Adaptive compression
// pass weighting off `placement.affinity`, every downstream
// dispatcher branching on `placement.estrategia`, the future
// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
// admission-time placement cross-check, the future `feira lint`
// per-`:placement` bound-check gate) surfaces here as a
// build-time test failure at `aplicacao.rs`, not as an
// apply-time `.get(<stale-canonical-const>)` returning `None`
// far from the derive-attr drift's commit. Peer with the sibling
// `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
// (b55cca7),
// `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
// (468e959),
// `entrada_serde_keys_match_lifted_entrada_key_consts` (a3d6162),
// `wit_contract_serde_keys_match_lifted_contrato_key_consts`
// (ca463a4), and
// `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
// pins on the M3 collection-slot / singleton-slot atom axes —
// closes the last M3 typed-struct top-level
// `#[serde(rename_all = "camelCase")]` axis on the Aplicacao
// surface without a drift-detection pin.
let p = Placement {
estrategia: PlacementStrategy::Sharded,
clusters: vec!["rio".into(), "mar".into()],
affinity: Some("data-locality".into()),
shard_key: Some("$tenantId".into()),
};
let json = serde_json::to_string(&p).unwrap();
for key in [
crate::M3_PLACEMENT_KEY_ESTRATEGIA,
crate::M3_PLACEMENT_KEY_CLUSTERS,
crate::M3_PLACEMENT_KEY_AFFINITY,
crate::M3_PLACEMENT_KEY_SHARD_KEY,
] {
let quoted = format!("\"{key}\"");
assert!(
json.contains("ed),
"serialized Placement must carry the lifted \
M3_PLACEMENT_KEY_* byte-sequence {quoted} verbatim in \
the JSON emission (got: {json})",
);
}
}
#[test]
fn m3_placement_key_consts_are_pairwise_distinct() {
// Cross-axis drift-detection pin: a future collapse of the four
// canonical [`Placement`] sub-block byte-strings onto the same
// value (e.g. an accidental copy-paste flip of
// [`crate::M3_PLACEMENT_KEY_SHARD_KEY`] to also read
// `"affinity"`) would silently reroute every downstream probe on
// one axis onto the sibling axis's overlay entry and pass every
// propagation-probe test that expected only the stale axis's
// value — the M3 shard-pool dispatch materializer would read the
// affinity placement-hint where the shard-selection template was
// expected (or vice versa), the M3 Adaptive compression pass's
// cross-check would compare the wrong pair of values, and the
// resulting placement engine would either bind the wrong axis or
// reject the resource at reconcile far from the rebrand commit's
// source. Peer of the sibling two-way distinct pin on the
// `CIRCUIT_BREAKER_KEY_*` pair (468e959), the five-way distinct
// pin on the `POLITICAS_KEY_*` pentad (b55cca7), the four-way
// distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
// two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and
// the six-way distinct pin on the `CONTRATO_KEY_*` triad +
// `WitTarget::*_FIELD_NAME` triad (ca463a4).
let all = [
crate::M3_PLACEMENT_KEY_ESTRATEGIA,
crate::M3_PLACEMENT_KEY_CLUSTERS,
crate::M3_PLACEMENT_KEY_AFFINITY,
crate::M3_PLACEMENT_KEY_SHARD_KEY,
];
for (i, a) in all.iter().enumerate() {
for b in all.iter().skip(i + 1) {
assert_ne!(
a, b,
"M3_PLACEMENT_KEY_* consts must be pairwise-distinct \
canonical byte-sequences — got `{a}` == `{b}`",
);
}
}
}
#[test]
fn m3_placement_key_consts_are_lower_camel_case_shape() {
// Shape-pin: every `M3_PLACEMENT_KEY_*` const must be a
// lowerCamelCase byte-sequence (no `snake_case` underscores, no
// `kebab-case` hyphens, no leading colon, no `PascalCase`
// leading capital, no whitespace / dots) — the canonical shape
// the `#[serde(rename_all = "camelCase")]` derive produces on
// [`Placement`]. A future flip to a non-camelCase attribute at
// the derive surfaces both here (this test fails on the stale-
// constant shape) and at
// `placement_serde_keys_match_lifted_m3_placement_key_consts`
// (that test fails on the mismatch between const and derive).
// Peer with `circuit_breaker_key_consts_are_lower_camel_case_shape`
// (468e959), `politicas_key_consts_are_lower_camel_case_shape`
// (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
// (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
// (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
// (ca463a4) on the sibling M3 typed-struct axes.
for key in [
crate::M3_PLACEMENT_KEY_ESTRATEGIA,
crate::M3_PLACEMENT_KEY_CLUSTERS,
crate::M3_PLACEMENT_KEY_AFFINITY,
crate::M3_PLACEMENT_KEY_SHARD_KEY,
] {
assert!(
!key.is_empty(),
"M3_PLACEMENT_KEY_* must be non-empty (got {key:?})"
);
let first = key.chars().next().unwrap();
assert!(
first.is_ascii_lowercase(),
"M3_PLACEMENT_KEY_* must lead with an ASCII-lowercase \
byte (got {key:?}, leads with {first:?})",
);
assert!(
key.chars().all(|c| c.is_ascii_alphanumeric()),
"M3_PLACEMENT_KEY_* must be ASCII-alphanumeric only — \
no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
);
}
}
// ── AplicacaoSpec::port_for_destination — the substrate-canonical
// destination-facing L4 port resolver every per-Aplicacao renderer
// reaching for a per-destination Servico TCP port axis routes
// through. The four pin tests below fix the four-way accept-set
// the resolver must always honor: (:entrada-para-matches,
// :entrada-para-mismatches, :entrada-none-so-fallback,
// :entrada-port-non-default-honored) — drift on any arm surfaces
// at caixa-core build time rather than at cluster-apply time.
#[test]
fn port_for_destination_returns_entrada_port_when_para_matches_destination() {
// The typed `:entrada` block's `:para "cart"` matches the
// queried destination, so the resolver returns the author-
// declared `:port` scalar verbatim — the canonical "the
// destination Servico IS the ingress apex, honor the typed
// listener port" arm of the port-resolution dispatch.
let mut spec = three_member_spec();
if let Some(e) = spec.entrada.as_mut() {
e.para = "cart".into();
e.port = 9090;
}
assert_eq!(
spec.port_for_destination("cart"),
9090,
"port_for_destination(entrada.para) must return entrada.port \
verbatim, not the DEFAULT_SERVICO_PORT fallback"
);
}
#[test]
fn port_for_destination_falls_back_to_default_servico_port_when_para_mismatches() {
// The typed `:entrada` block names `:para "cart"`, but the
// queried destination is `"payment"` — a Servico that
// participates in the mesh graph but is not the ingress apex.
// The resolver falls back to the lifted DEFAULT_SERVICO_PORT
// canonical port floor, closing the "non-apex destination reads
// the substrate default" arm. Same fixture the peer
// `cnp_l4_fallback_port_routes_through_lifted_default_servico_port`
// pin at caixa-mesh exercises through the CNP emit-side path;
// this pin exercises the shared underlying resolver directly.
let spec = three_member_spec();
assert_eq!(
spec.port_for_destination("payment"),
DEFAULT_SERVICO_PORT,
"port_for_destination(non-apex-destination) must route \
through the lifted DEFAULT_SERVICO_PORT canonical port floor"
);
}
#[test]
fn port_for_destination_falls_back_to_default_servico_port_when_entrada_none() {
// Internal-only Aplicacao — no `:entrada` block declared. Every
// per-destination port query falls back to the lifted
// DEFAULT_SERVICO_PORT canonical floor. The arm exists because
// the Aplicacao surface admits `:entrada None` (internal mesh
// with no external gateway); every downstream renderer's per-
// destination port axis must still resolve to a well-defined
// scalar even without an ingress apex.
let mut spec = three_member_spec();
spec.entrada = None;
assert_eq!(
spec.port_for_destination("cart"),
DEFAULT_SERVICO_PORT,
"port_for_destination on an internal-only Aplicacao must \
fall back to the lifted DEFAULT_SERVICO_PORT floor for \
every destination"
);
assert_eq!(
spec.port_for_destination("payment"),
DEFAULT_SERVICO_PORT,
"port_for_destination on an internal-only Aplicacao must \
fall back uniformly across every destination — the fallback \
is not entrada-shape-conditional"
);
}
#[test]
fn port_for_destination_honors_non_default_entrada_port_verbatim() {
// Structural pin against a hypothetical future refactor that
// reconciled `entrada.port` against `DEFAULT_SERVICO_PORT` at
// the resolver (a "normalize to the default when the author's
// port matches the substrate default" collapse) — that would
// break renderer sites that carry meaning on the emitted port
// value beyond bare equality (a future per-cluster listener-
// audit that keys off the author-declared port, not the
// resolved-with-fallback port). Pin that a non-default
// entrada.port is returned verbatim so drift here surfaces at
// caixa-core build time.
let mut spec = three_member_spec();
if let Some(e) = spec.entrada.as_mut() {
e.para = "cart".into();
e.port = 8443;
}
assert_ne!(
8443, DEFAULT_SERVICO_PORT,
"test fixture must probe a port distinct from \
DEFAULT_SERVICO_PORT to exercise the honor-verbatim arm"
);
assert_eq!(
spec.port_for_destination("cart"),
8443,
"port_for_destination(entrada.para) must return entrada.port \
verbatim, even when the port differs from DEFAULT_SERVICO_PORT"
);
}
#[test]
fn port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations() {
// Apex-identity pair-invariant pin composing both substrate-
// primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
// and [`Entrada::destination`] — at the emit-side call shape
// every per-Aplicacao renderer's ingress-apex L4 port reader
// now takes. The invariant:
//
// spec.port_for_destination(entrada.destination()) == entrada.port
//
// holds by construction under today's single-destination
// `:entrada` slot (`destination()` returns `entrada.para`, and
// the resolver's apex arm matches `para == destination` and
// returns `entrada.port`), and every downstream consumer that
// composes the two accessors at the ingress apex — the
// `caixa_mesh::gateway_routes` HTTPRoute per-rule
// `backendRefs[0].port` emit-site path, the peer future M4 CR
// materializer's admission-webhook that promotes the scalar to
// a per-CR override overlay, every future per-Aplicacao snapshot
// renderer's apex-facing L4 port reader — reaches through the
// same composition. Pin the identity across four permutations
// (`:para` × `:port` including a non-default port to exercise
// the honor-verbatim arm and a non-cart `:para` to exercise
// destination-agnostic identity) so a future refactor that
// silently split either accessor's apex behavior surfaces at
// caixa-core build time — a subtle `destination()` renaming
// that returned `entrada.host.as_str()` instead of
// `entrada.para.as_str()` would blow this pin loudly, closing
// the last quiet failure mode the two lifts admit in composition.
//
// Peer discipline with the sibling caixa-mesh cross-crate pin
// [`caixa_mesh::tests::httproute_backend_ref_port_and_cnp_l4_port_share_port_for_destination_resolver_at_emit_site`]
// on the two-renderer pair-invariant axis; this pin encodes the
// same two-consumer coherence rule at the substrate-primitive
// level so the invariant survives even if every renderer is
// deleted.
for (para, port) in [
("cart", DEFAULT_SERVICO_PORT),
("cart", 8443u16),
("payment", 9090u16),
("catalog", 443u16),
] {
let mut spec = three_member_spec();
if let Some(e) = spec.entrada.as_mut() {
e.para = para.into();
e.port = port;
}
let expected_port = spec
.entrada()
.expect("three_member_spec carries a typed `:entrada` block")
.port();
let composed_port = {
let entrada = spec.entrada().expect("entrada present");
spec.port_for_destination(entrada.destination())
};
assert_eq!(
composed_port, expected_port,
"`spec.port_for_destination(entrada.destination())` must \
equal `entrada.port` under today's single-destination \
`:entrada` slot — this is the apex-identity contract \
every downstream ingress-apex L4 port reader relies on. \
Input :entrada :para: {para:?}, :entrada :port: {port}"
);
}
}
#[test]
fn port_for_destination_apex_arm_routes_through_destination_accessor() {
// Composition pin: [`AplicacaoSpec::port_for_destination`]'s
// per-`:entrada` apex-arm membership probe must key off
// [`Entrada::destination`], not the raw `.para` field access.
// Structurally: setting ONLY the `:entrada :para` field to a
// fresh non-cart destination on an otherwise-well-formed
// Aplicacao must (1) leave `e.destination()` byte-equal to
// `e.para.as_str()` (the accessor is byte-projective by
// definition), and (2) cause the resolver's apex arm to fire
// and return `entrada.port` at exactly that new destination
// while every other destination string falls through to
// [`DEFAULT_SERVICO_PORT`] under the accessor-projected
// membership check. Pins against a future silent detour that
// (a) re-derived the apex-arm membership probe off
// `e.para == destination` in `port_for_destination` instead of
// `e.destination() == destination`, silently disagreeing with
// the two peer `caixa-mesh` per-`(HTTPRoute, CNP)` emit-site
// consumers (`entrada.destination()` at
// caixa-mesh/src/lib.rs:3173, `c.destination()` at
// caixa-mesh/src/lib.rs:2739) that already reach through the
// accessor, (b) accessor-side introduced a per-tenant alias
// arm the caller was unaware of, silently rewriting an
// author-declared `:para "cart"` value to a canary-aliased
// form — the raw-field-access resolver would fall through to
// `DEFAULT_SERVICO_PORT` matching the un-aliased destination
// while the peer emit-site consumers landed on the aliased
// destination, splitting the ingress-apex L4 port at
// cluster-apply time.
//
// Peer of the sibling
// [`validate_membros_empty_gate_routes_through_nome_accessor`]
// (d0de220) composition pin on the per-`:membros` refusal-arm
// axis — same "the shape-gate predicate must route through the
// substrate-primitive typed dispatch" discipline extended onto
// the per-`:entrada` apex-arm membership-probe axis. Closes
// the last unlifted `.para` production-code read site on
// `Entrada` in `caixa-core` — after this converge every
// `caixa-core` `.para` field access outside the accessor's own
// body and outside the `WitContract` per-`:contratos` sibling
// axis is either a test-side field-setter or a doc-comment
// reference.
for (para, port) in [("cart", 8080u16), ("payment", 9090u16), ("catalog", 443u16)] {
let mut spec = three_member_spec();
if let Some(e) = spec.entrada.as_mut() {
e.para = para.into();
e.port = port;
}
let e = spec
.entrada
.as_ref()
.expect("three_member_spec carries a typed `:entrada` block");
assert_eq!(
e.destination(),
e.para.as_str(),
"Entrada::destination must byte-equal the .para field \
access — an accessor-side detour that no longer \
projects the raw field would silently split this \
drift-detection test from the port_for_destination \
apex-arm membership probe",
);
assert_eq!(
spec.port_for_destination(para),
port,
"port_for_destination must key off the accessor-projected \
destination and return `entrada.port` on the apex arm — \
input :entrada :para: {para:?}, :entrada :port: {port}",
);
assert_eq!(
spec.port_for_destination("ghost-destination-never-a-member"),
DEFAULT_SERVICO_PORT,
"port_for_destination must fall through to \
DEFAULT_SERVICO_PORT on a non-matching destination \
under the accessor-projected membership check — input \
:entrada :para: {para:?}, :entrada :port: {port}",
);
}
}
#[test]
fn rate_limit_rate_returns_rate_u32_byte_equal_across_permutations() {
// The canonical per-`:politicas :rate-limit` `:rate`
// Envoy-local-rate-limit-mesh token-bucket-capacity scalar pin:
// [`RateLimit::rate`] must return the `:politicas :rate-limit`
// typed `u32` verbatim, byte-equal to the raw field access
// across every representative value in the accept-set — `1` (the
// lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` accept-set
// the surrounding [`AplicacaoSpec::validate_politicas`] gate
// carves out on the sibling `PolicyRateLimitZero` refusal),
// `POLICY_RATE_LIMIT_MAX` (the upper boundary the same gate
// carves out on the sibling `PolicyRateLimitExceedsCap` refusal),
// `0` (a past-the-guard sentinel that pins the accessor doesn't
// perform a silent bounds-collapse into `1` on the zero arm —
// validate rejects zero but the accessor must ship the raw slot
// verbatim so a validate-time gate regression surfaces at the
// emit boundary rather than being silently absorbed), `u32::MAX`
// (a past-the-guard sentinel that pins the accessor doesn't
// perform a silent bounds-collapse through
// `POLICY_RATE_LIMIT_MAX` at the return path).
//
// First sub-struct required-scalar accessor pin on the
// `RateLimit` axis — sibling in shape to the peer
// per-`CircuitBreaker` [`CircuitBreaker::max_failures`] (3a74062)
// required-`u32` accessor pin on the peer per-sub-struct
// required-axis. Pins against a future silent detour that
// re-derived the token capacity from a peer axis (an accidental
// `self.window.as_secs() as u32` collapse that read the
// rate-limit window duration as a token count), a `0 → 1`
// cluster-default projection (which would silently absorb the
// `PolicyRateLimitZero` refusal case at the accessor boundary),
// or a bounds-collapsing accessor that clamped the return
// through `POLICY_RATE_LIMIT_MAX` (the `AplicacaoSpec::validate`
// gate owns the bounds; the accessor must ship the raw slot
// verbatim).
for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
let rl = RateLimit {
rate,
window: Duration::from_secs(1),
};
assert_eq!(
rl.rate(),
rate,
"RateLimit::rate must return :politicas :rate-limit :rate \
verbatim (got {}, expected {rate})",
rl.rate(),
);
assert_eq!(
rl.rate(),
rl.rate,
"RateLimit::rate must byte-equal the raw .rate field \
access across every value in the u32 accept-set",
);
}
}
#[test]
fn validate_politicas_rate_zero_floor_arm_routes_through_accessor() {
// Composition pin: [`AplicacaoSpec::validate_politicas`]'s
// `:rate-limit :rate` zero-floor arm must key off
// [`RateLimit::rate`], not the raw `.rate` field access.
// Structurally: a `RateLimit { rate: 0, window:
// Duration::from_secs(1) }` embedded in a `:politicas
// :rate-limit` slot must surface the `PolicyRateLimitZero`
// refusal exactly, and a `RateLimit { rate: 1, window:
// Duration::from_secs(1) }` (the lower boundary of the
// `1..=POLICY_RATE_LIMIT_MAX` accept-set) must pass validate.
// The pair jointly pins the accessor + validate-gate composition:
// any future silent detour that had the accessor return a fresh
// `1` on the zero arm (a `.rate().max(1)` collapse) would
// silently absorb the `PolicyRateLimitZero` refusal at the
// accessor boundary and the validate gate would accept a
// struct-literal `RateLimit { rate: 0, .. }` — the composition
// pin catches that at caixa-core build time.
//
// Peer of the sibling per-`CircuitBreaker`
// [`CircuitBreaker::max_failures`] (3a74062) /
// [`CircuitBreaker::window`] (373957f) accessor-composition
// pins on the peer required-scalar axes — same "the validate /
// shape-gate predicate must route through the substrate-primitive
// typed dispatch" discipline extended onto the peer
// per-`RateLimit` required-`u32` composition axis.
let mut spec = three_member_spec();
spec.politicas = MeshPolicy {
rate_limit: Some(RateLimit {
rate: 0,
window: Duration::from_secs(1),
}),
..MeshPolicy::default()
};
assert!(
matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
"validate_politicas must reject rate == 0 with \
PolicyRateLimitZero — the accessor and the validate gate \
must route through the same substrate-primitive typed \
dispatch on the :rate zero-floor arm",
);
spec.politicas = MeshPolicy {
rate_limit: Some(RateLimit {
rate: 1,
window: Duration::from_secs(1),
}),
..MeshPolicy::default()
};
assert!(
spec.validate().is_ok(),
"validate_politicas must accept rate == 1 (the lower \
boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-set)",
);
}
#[test]
fn rate_limit_rate_projects_u32_by_copy() {
// The by-copy pin: [`RateLimit::rate`] returns `u32` by copy —
// `u32` is `Copy` and the accessor must return by value, not by
// reference. Peer of the sibling per-`CircuitBreaker`
// [`CircuitBreaker::max_failures`] (3a74062) by-copy pin on the
// peer required-scalar `:max-failures` axis, extended onto the
// peer per-`RateLimit` required-`u32` copy-invariant shape —
// the accessor's returned `u32` must outlive `&self` (multiple
// calls must return equal values from a dropped-`&self` copy,
// since the returned scalar carries no borrow), and calling the
// accessor twice on the same RateLimit must yield the same
// `u32` verbatim (idempotent, no side effects on `&self`).
//
// Pins against a future silent detour that returned `&u32`
// (which would type-check but silently break every downstream
// arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
// first parameter is `u32`, and `&u32` would fold to a detached
// copy at the call site with a `*` deref the sibling accessors
// don't need), an accidental `.rate.wrapping_add(0)` detour that
// returned a fresh copy through an arithmetic no-op (breaking a
// future `const fn` regression), or a one-arm-only accessor
// that returned a saturating value on some sentinel input
// (breaking the pass-through invariant the sibling required-
// scalar accessors carry).
for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
let rl = RateLimit {
rate,
window: Duration::from_secs(1),
};
let first = rl.rate();
let second = rl.rate();
assert_eq!(
first, second,
"RateLimit::rate must be idempotent — two successive \
calls on the same &self must return the same u32",
);
assert_eq!(
first, rate,
"RateLimit::rate must return :politicas :rate-limit :rate \
verbatim by copy — got {first}, expected {rate}",
);
}
}
#[test]
fn rate_limit_window_returns_window_duration_byte_equal_across_permutations() {
// The canonical per-`:politicas :rate-limit` `:window`
// Envoy-local-rate-limit-mesh token-bucket-refill-period scalar
// pin: [`RateLimit::window`] must return the
// `:politicas :rate-limit :window` typed `Duration` verbatim,
// byte-equal to the raw field access across every
// representative value in the accept-set — `Duration::from_secs(1)`
// (the `"s"` canonical window, the lower row of
// [`RATE_LIMIT_UNIT_TABLE`] the surrounding
// [`AplicacaoSpec::validate_politicas`] gate accepts via
// [`is_canonical_rate_limit_window`]),
// `Duration::from_secs(60)` (the `"m"` canonical window, the
// middle row), `Duration::from_secs(3600)` (the `"h"` canonical
// window, the upper row), `Duration::ZERO` (a past-the-guard
// sentinel that pins the accessor doesn't perform a silent
// bounds-collapse into `Duration::from_secs(1)` on the zero
// arm — validate rejects an off-set window through
// `PolicyRateLimitWindowNotCanonical` but the accessor must
// ship the raw slot verbatim so a validate-time gate
// regression surfaces at the emit boundary rather than being
// silently absorbed), `Duration::from_millis(500)` (a
// sub-canonical past-the-guard sentinel that pins the accessor
// doesn't silently normalize a non-canonical fractional
// magnitude onto the nearest canonical row).
//
// Second sub-struct required-scalar accessor pin on the
// `RateLimit` axis — sibling in shape to the just-landed
// per-`RateLimit` [`RateLimit::rate`] (7f81a60) required-`u32`
// accessor pin on the peer per-sub-struct required-axis,
// extended onto the per-`RateLimit` required-`Duration` axis.
// Pins against a future silent detour that re-derived the
// refill period from a peer axis (an accidental
// `Duration::from_secs(self.rate as u64)` collapse that read
// the rate-limit token capacity as a refill-interval
// duration), a `Duration::ZERO → Duration::from_secs(1)`
// canonical-default projection (which would silently absorb
// the `PolicyRateLimitWindowNotCanonical` refusal case at the
// accessor boundary), or a canonical-set-collapsing accessor
// that clamped the return through [`rate_limit_window_unit`]
// (the `AplicacaoSpec::validate` gate owns the canonical-set
// membership; the accessor must ship the raw slot verbatim).
for window in [
Duration::from_secs(1),
Duration::from_secs(60),
Duration::from_secs(3600),
Duration::ZERO,
Duration::from_millis(500),
] {
let rl = RateLimit { rate: 100, window };
assert_eq!(
rl.window(),
window,
"RateLimit::window must return :politicas :rate-limit :window \
verbatim (got {:?}, expected {window:?})",
rl.window(),
);
assert_eq!(
rl.window(),
rl.window,
"RateLimit::window must byte-equal the raw .window field \
access across every value in the Duration accept-set",
);
}
}
#[test]
fn validate_politicas_rate_limit_window_canonical_arm_routes_through_accessor() {
// Composition pin: [`AplicacaoSpec::validate_politicas`]'s
// `:rate-limit :window` canonical-set arm must key off
// [`RateLimit::window`], not the raw `.window` field access.
// Structurally: a `RateLimit { window: Duration::from_millis(500),
// .. }` embedded in a `:politicas :rate-limit` slot must
// surface the `PolicyRateLimitWindowNotCanonical` refusal
// exactly (with the sub-canonical `Duration::from_millis(500)`
// magnitude carried through verbatim), and a `RateLimit
// { window: Duration::from_secs(1), .. }` (the lower row of
// the `RATE_LIMIT_UNIT_TABLE` accept-set) must pass validate.
// The pair jointly pins the accessor + validate-gate
// composition: any future silent detour that had the accessor
// normalize the off-set window to the nearest canonical row
// (a `.window().max(Duration::from_secs(1))` collapse, or a
// `rate_limit_window_unit(.window()).map_or(Duration::from_secs(1), …)`
// collapse) would silently absorb the
// `PolicyRateLimitWindowNotCanonical` refusal at the accessor
// boundary — including a drift in the error's `window` payload
// (the emit-side diagnostic reader keys off the offending
// magnitude verbatim, so a normalization at the accessor
// boundary would silently pin the wrong magnitude in the
// refusal). The composition pin catches that at caixa-core
// build time.
//
// Peer of the sibling per-`RateLimit` [`RateLimit::rate`]
// (7f81a60) accessor-composition pin on the peer required-
// scalar `:rate` axis — same "the validate / shape-gate
// predicate must route through the substrate-primitive typed
// dispatch, and the error payload must project through the
// same accessor" discipline extended onto the peer
// per-`RateLimit` required-`Duration` composition axis.
let mut spec = three_member_spec();
spec.politicas = MeshPolicy {
rate_limit: Some(RateLimit {
rate: 100,
window: Duration::from_millis(500),
}),
..MeshPolicy::default()
};
match spec.validate() {
Err(AplicacaoError::PolicyRateLimitWindowNotCanonical { window }) => {
assert_eq!(
window,
Duration::from_millis(500),
"PolicyRateLimitWindowNotCanonical must carry the \
offending :window magnitude verbatim through the \
accessor — got {window:?}, expected 500ms",
);
}
other => panic!(
"validate_politicas must reject non-canonical :window \
with PolicyRateLimitWindowNotCanonical — the accessor \
and the validate gate must route through the same \
substrate-primitive typed dispatch on the :window \
canonical-set arm; got {other:?}",
),
}
spec.politicas = MeshPolicy {
rate_limit: Some(RateLimit {
rate: 100,
window: Duration::from_secs(1),
}),
..MeshPolicy::default()
};
assert!(
spec.validate().is_ok(),
"validate_politicas must accept window == Duration::from_secs(1) \
(the lower row of the RATE_LIMIT_UNIT_TABLE accept-set)",
);
}
#[test]
fn rate_limit_window_projects_duration_by_copy() {
// The by-copy pin: [`RateLimit::window`] returns `Duration`
// by copy — `Duration` is `Copy` and the accessor must return
// by value, not by reference. Peer of the sibling per-`RateLimit`
// [`RateLimit::rate`] (7f81a60) by-copy pin on the peer
// required-scalar `:rate` axis, extended onto the peer
// per-`RateLimit` required-`Duration` copy-invariant shape —
// the accessor's returned `Duration` must outlive `&self`
// (multiple calls must return equal values from a
// dropped-`&self` copy, since the returned scalar carries no
// borrow), and calling the accessor twice on the same
// RateLimit must yield the same `Duration` verbatim
// (idempotent, no side effects on `&self`).
//
// Pins against a future silent detour that returned
// `&Duration` (which would type-check but silently break every
// downstream `Duration`-by-value consumer —
// [`is_canonical_rate_limit_window`]'s first parameter is
// `Duration`, and `&Duration` would fold to a detached copy at
// the call site with a `*` deref the sibling accessors don't
// need), an accidental `.window + Duration::ZERO` detour that
// returned a fresh copy through an arithmetic no-op (breaking
// a future `const fn` regression), or a one-arm-only accessor
// that returned a canonical fallback on some sentinel input
// (breaking the pass-through invariant the sibling required-
// scalar accessors carry).
for window in [
Duration::from_secs(1),
Duration::from_secs(60),
Duration::from_secs(3600),
Duration::ZERO,
Duration::from_millis(500),
] {
let rl = RateLimit { rate: 100, window };
let first = rl.window();
let second = rl.window();
assert_eq!(
first, second,
"RateLimit::window must be idempotent — two successive \
calls on the same &self must return the same Duration",
);
assert_eq!(
first, window,
"RateLimit::window must return :politicas :rate-limit :window \
verbatim by copy — got {first:?}, expected {window:?}",
);
}
}
#[test]
fn placement_estrategia_default_pins_m3_canonical_value() {
// Pin [`PLACEMENT_ESTRATEGIA_DEFAULT`] at
// [`PlacementStrategy::Replicated`] — MESH-COMPOSITION §II.2's
// active-active-across-every-named-cluster arm, the closest
// canonical M3 production reference the substrate carries and
// the arm the caixa-mesh `programs.yaml` fan-out already keys off
// for every un-`:placement`-declared Aplicacao. Pinning the arm
// here surfaces a future rebrand of the M3-canonical
// distribution default (a widening to `Sharded` once the
// substrate discovers hash-keyed distribution as the more
// common production shape, a tightening to `SingleNode` for
// stateful Erlang/OTP distributed-app-takeover semantics
// MESH-COMPOSITION §II.1 names, a per-cluster overlay the
// operator pins through a future `:placement-overrides` slot)
// as a deliberate test edit, not a silent contract migration.
// Peer of the sibling M2 per-supervisor value pins
// [`crate::supervisor::tests::supervisor_estrategia_default_pins_otp_canonical_value`]
// /
// [`crate::supervisor::tests::supervisor_child_restart_default_pins_otp_canonical_value`]
// extended onto the M3 mesh-primitive-defining `:placement
// :estrategia` axis.
assert_eq!(PLACEMENT_ESTRATEGIA_DEFAULT, PlacementStrategy::Replicated);
}
#[test]
fn placement_strategy_default_routes_through_lifted_default() {
// Composition pin: the [`Default for PlacementStrategy`] impl's
// return arm must route through the substrate-canonical
// [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
// a raw `Self::Replicated` arm. Prior to the lift the impl
// carried an inline `Self::Replicated` arm with no compile-time
// link back to the shared M3-canonical `Replicated` arm the
// paired [`Default for Placement`] impl's struct-literal
// `estrategia` field, the serde-side `#[serde(default)]` on
// [`Placement::estrategia`] that resolves an author-omitted
// wire-form `:placement :estrategia` scalar through the impl,
// and the [`crate::manifest::Caixa::aplicacao_view`] fold's
// `.unwrap_or_default()` `Option<Placement>` collapse arm (which
// routes through [`Placement::default`] which routes through the
// strategy default) all key off — so a future rebrand of the
// M3-canonical distribution default would have had to be threaded
// through the `Default` impl and the three peer routes in
// lockstep or the four consumers would silently split. Byte-
// parity against the lifted constant closes the split. Peer of
// the sibling
// [`crate::supervisor::tests::restart_strategy_default_routes_through_lifted_default`]
// /
// [`crate::supervisor::tests::restart_policy_default_routes_through_lifted_default`]
// composition pins on the M2 per-supervisor axes.
assert_eq!(PlacementStrategy::default(), PLACEMENT_ESTRATEGIA_DEFAULT);
}
#[test]
fn placement_default_estrategia_routes_through_lifted_default() {
// Composition pin: the [`Default for Placement`] impl's
// struct-literal `estrategia` field must route through the
// substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed
// `pub const` (either directly, or via the [`PlacementStrategy::default`]
// impl that the sibling
// `placement_strategy_default_routes_through_lifted_default` pin
// already routes onto the constant). Structurally: every
// `Placement::default()` call must yield an `estrategia` field
// byte-equal to the lifted constant so the two paired defaults —
// the [`Default for PlacementStrategy`] impl arm and the
// struct-literal default arm here — cannot silently split on any
// future M3-canonical distribution-default rebrand. Peer of the
// sibling M2
// [`crate::supervisor::tests::supervisor_spec_default_estrategia_routes_through_lifted_default`]
// byte-parity pin on the [`Default for SupervisorSpec`]
// struct-literal `estrategia` field extended onto the M3
// mesh-primitive-defining slot family.
assert_eq!(
Placement::default().estrategia,
PLACEMENT_ESTRATEGIA_DEFAULT,
);
}
#[test]
fn placement_serde_default_estrategia_routes_through_lifted_default() {
// Composition pin: the serde-side `#[serde(default)]` on
// [`Placement::estrategia`] — the wire-format author-omitted
// `:placement :estrategia` arm — must resolve onto the substrate-
// canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed `pub const`
// (via the [`Default for PlacementStrategy`] impl the sibling
// `placement_strategy_default_routes_through_lifted_default` pin
// already routes onto the constant). Structurally: a `Placement`
// deserialized from a payload that omits the `estrategia` key
// must yield an `estrategia` field byte-equal to the lifted
// constant, so the wire-format author-omitted arm and the
// [`PlacementStrategy::default`] impl arm cannot silently split
// on any future M3-canonical distribution-default rebrand. Peer
// of the sibling M2
// [`crate::supervisor::tests::child_spec_serde_default_restart_routes_through_lifted_default`]
// byte-parity pin on the wire-format author-omitted `:children
// :restart` scalar extended onto the M3 mesh-primitive-defining
// slot family.
let omitted: Placement = serde_json::from_str("{}")
.expect("Placement must deserialize with the estrategia key omitted");
assert_eq!(
omitted.estrategia, PLACEMENT_ESTRATEGIA_DEFAULT,
"an author-omitted :placement :estrategia slot must degrade onto \
the PLACEMENT_ESTRATEGIA_DEFAULT typed pub const (got \
{:?}, expected {:?})",
omitted.estrategia, PLACEMENT_ESTRATEGIA_DEFAULT,
);
}
// ── contrato_target_ctors! fold pins ────────────────────────────────
//
// Fixture edge triple + payload-field-name label pair for every
// `contrato_target_ctors!`-generated ctor pin below. Kept as
// non-default `("cart", "catalog", "wasi:http/proxy")` +
// `WitTarget::HTTP_FIELD_NAME` so a byte-equality mistake against
// the fixture default doesn't silently pass. Peer of the sibling
// `entrada_host_invalid_ctor_matches_struct_literal_wrap` /
// `<slot>_violation_ctor_matches_struct_literal_wrap` /
// `<slot>_slots_on_non_<owner>_ctor_matches_struct_literal_wrap` /
// `missing_entry_ctor_matches_struct_literal_wrap` /
// `<slot>_ctor_matches_tuple_literal_wrap` equivalence pins on the
// four `LayoutError` constructor families each closed on their
// sibling envelopes.
fn contrato_target_ctor_fixture() -> (String, String, String, &'static str) {
(
"cart".to_string(),
"catalog".to_string(),
"wasi:http/proxy".to_string(),
WitTarget::HTTP_FIELD_NAME,
)
}
#[test]
fn contrato_wrong_target_ctor_matches_struct_literal_wrap() {
// Equivalence pin: the ctor produces byte-equal
// `AplicacaoError::ContratoWrongTarget` to the pre-lift open-
// coded struct-literal on the same edge fixture, so the fold
// cannot silently drift on any future field-addition /
// reordering / string-conversion tweak on the variant. Peer of
// the sibling `entrada_host_invalid_ctor_matches_struct_literal_wrap`
// (17dd504) / the four `LayoutError` family equivalence pins.
let (de, para, wit, expected) = contrato_target_ctor_fixture();
let lifted = AplicacaoError::contrato_wrong_target(
(de.clone(), para.clone(), wit.clone()),
expected,
);
let struct_literal = AplicacaoError::ContratoWrongTarget {
de,
para,
wit,
expected,
};
assert_eq!(lifted, struct_literal);
}
#[test]
fn contrato_missing_target_ctor_matches_struct_literal_wrap() {
// Equivalence pin peer of the sibling
// `contrato_wrong_target_ctor_matches_struct_literal_wrap` above
// on the paired `ContratoMissingTarget` variant of the same
// four-slot envelope shape the `contrato_target_ctors!` macro
// closes.
let (de, para, wit, expected) = contrato_target_ctor_fixture();
let lifted = AplicacaoError::contrato_missing_target(
(de.clone(), para.clone(), wit.clone()),
expected,
);
let struct_literal = AplicacaoError::ContratoMissingTarget {
de,
para,
wit,
expected,
};
assert_eq!(lifted, struct_literal);
}
#[test]
fn contrato_target_ctors_route_edge_triple_through_verbatim() {
// Routing pin: the `(de, para, wit)` triple threads verbatim
// onto same-named fields on both generated ctors, no wrapper-
// side lowercase / trim / re-order. Sweeps a non-default triple
// (`"cart-svc" → "catalog-v2"`, `"nats:pub-sub"`) so any
// wrapper-side transformation surfaces here rather than at a
// downstream diagnostic-shape drift. Sibling of
// `entrada_host_invalid_ctor_routes_host_through_to_string`
// (17dd504) on the paired triple-carrying envelope.
let edge = (
"cart-svc".to_string(),
"catalog-v2".to_string(),
"nats:pub-sub".to_string(),
);
let wrong =
AplicacaoError::contrato_wrong_target(edge.clone(), WitTarget::PUBSUB_FIELD_NAME);
let missing = AplicacaoError::contrato_missing_target(edge, WitTarget::PUBSUB_FIELD_NAME);
let AplicacaoError::ContratoWrongTarget {
de: wde,
para: wpara,
wit: wwit,
..
} = wrong
else {
panic!("contrato_wrong_target must construct the ContratoWrongTarget variant");
};
let AplicacaoError::ContratoMissingTarget {
de: mde,
para: mpara,
wit: mwit,
..
} = missing
else {
panic!("contrato_missing_target must construct the ContratoMissingTarget variant");
};
assert_eq!(wde, "cart-svc");
assert_eq!(wpara, "catalog-v2");
assert_eq!(wwit, "nats:pub-sub");
assert_eq!(mde, "cart-svc");
assert_eq!(mpara, "catalog-v2");
assert_eq!(mwit, "nats:pub-sub");
}
#[test]
fn contrato_target_ctors_route_expected_through_verbatim() {
// Routing pin: the `expected: &'static str` label threads
// verbatim (identity, not copy-and-transform) onto the
// `expected` field of both variants, so the four canonical
// labels [`WitTarget::HTTP_FIELD_NAME`] /
// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
// / [`WitTarget::CAPABILITY_EXPECTED`] survive the fold as
// pointer-equal (not merely value-equal) references — a wrapper-
// side `.to_string()` / `Cow::Owned` promotion would break the
// `&'static str` contract downstream consumers depend on.
for label in [
WitTarget::HTTP_FIELD_NAME,
WitTarget::PUBSUB_FIELD_NAME,
WitTarget::STORE_FIELD_NAME,
WitTarget::CAPABILITY_EXPECTED,
] {
let (de, para, wit, _) = contrato_target_ctor_fixture();
let wrong = AplicacaoError::contrato_wrong_target(
(de.clone(), para.clone(), wit.clone()),
label,
);
let missing = AplicacaoError::contrato_missing_target((de, para, wit), label);
match wrong {
AplicacaoError::ContratoWrongTarget { expected, .. } => {
assert!(
std::ptr::eq(expected.as_ptr(), label.as_ptr())
&& expected.len() == label.len(),
"contrato_wrong_target must thread the &'static str \
label pointer-equal onto the `expected` field \
(label = {label:?})",
);
}
other => panic!("expected ContratoWrongTarget, got {other:?}"),
}
match missing {
AplicacaoError::ContratoMissingTarget { expected, .. } => {
assert!(
std::ptr::eq(expected.as_ptr(), label.as_ptr())
&& expected.len() == label.len(),
"contrato_missing_target must thread the &'static \
str label pointer-equal onto the `expected` field \
(label = {label:?})",
);
}
other => panic!("expected ContratoMissingTarget, got {other:?}"),
}
}
}
// ── contrato_empty_pair_ctors! fold pins ────────────────────────────
//
// Fixture edge pair for every `contrato_empty_pair_ctors!`-generated
// ctor pin below. Kept as non-default `("cart", "catalog")` so a
// byte-equality mistake against the fixture default doesn't silently
// pass. Peer of the sibling `contrato_target_ctor_fixture` (14b81d5,
// triple + expected-label envelope on
// `contrato_target_ctors!`) / `entrada_host_invalid_ctor_matches_
// struct_literal_wrap` (17dd504, host + reason envelope on
// `entrada_host_invalid`) / the four `LayoutError` family
// equivalence pins.
fn contrato_empty_pair_ctor_fixture() -> (String, String) {
("cart".to_string(), "catalog".to_string())
}
#[test]
fn empty_wit_ctor_matches_struct_literal_wrap() {
// Equivalence pin: the ctor produces byte-equal
// `AplicacaoError::EmptyWit` to the pre-lift open-coded
// struct-literal on the same edge pair, so the fold cannot
// silently drift on any future field-addition / reordering /
// string-conversion tweak on the variant. Peer of the sibling
// `contrato_wrong_target_ctor_matches_struct_literal_wrap`
// (14b81d5) / `entrada_host_invalid_ctor_matches_struct_literal_wrap`
// (17dd504) / the four `LayoutError` family equivalence pins.
let (de, para) = contrato_empty_pair_ctor_fixture();
let lifted = AplicacaoError::empty_wit((de.clone(), para.clone()));
let struct_literal = AplicacaoError::EmptyWit { de, para };
assert_eq!(lifted, struct_literal);
}
#[test]
fn contrato_endpoint_empty_ctor_matches_struct_literal_wrap() {
// Equivalence pin peer of the sibling
// `empty_wit_ctor_matches_struct_literal_wrap` above on the
// paired `ContratoEndpointEmpty` variant of the same two-slot
// envelope shape the `contrato_empty_pair_ctors!` macro closes.
let (de, para) = contrato_empty_pair_ctor_fixture();
let lifted = AplicacaoError::contrato_endpoint_empty((de.clone(), para.clone()));
let struct_literal = AplicacaoError::ContratoEndpointEmpty { de, para };
assert_eq!(lifted, struct_literal);
}
#[test]
fn contrato_subject_empty_ctor_matches_struct_literal_wrap() {
// Equivalence pin peer of the sibling
// `contrato_endpoint_empty_ctor_matches_struct_literal_wrap`
// above on the paired `ContratoSubjectEmpty` variant of the
// same two-slot envelope shape.
let (de, para) = contrato_empty_pair_ctor_fixture();
let lifted = AplicacaoError::contrato_subject_empty((de.clone(), para.clone()));
let struct_literal = AplicacaoError::ContratoSubjectEmpty { de, para };
assert_eq!(lifted, struct_literal);
}
#[test]
fn contrato_slot_empty_ctor_matches_struct_literal_wrap() {
// Equivalence pin peer of the sibling
// `contrato_subject_empty_ctor_matches_struct_literal_wrap`
// above on the paired `ContratoSlotEmpty` variant of the same
// two-slot envelope shape.
let (de, para) = contrato_empty_pair_ctor_fixture();
let lifted = AplicacaoError::contrato_slot_empty((de.clone(), para.clone()));
let struct_literal = AplicacaoError::ContratoSlotEmpty { de, para };
assert_eq!(lifted, struct_literal);
}
#[test]
fn contrato_empty_pair_ctors_route_edge_pair_through_verbatim() {
// Routing pin: the `(de, para)` pair threads verbatim onto
// same-named fields on all four generated ctors, no wrapper-
// side lowercase / trim / re-order. Sweeps a non-default pair
// (`"cart-svc" → "catalog-v2"`) so any wrapper-side
// transformation surfaces here rather than at a downstream
// diagnostic-shape drift. Sibling of
// `contrato_target_ctors_route_edge_triple_through_verbatim`
// (14b81d5) on the paired triple-carrying envelope and of
// `entrada_host_invalid_ctor_routes_host_through_to_string`
// (17dd504) on the sibling `{ host, reason }` envelope.
let edge = ("cart-svc".to_string(), "catalog-v2".to_string());
let variants: [(AplicacaoError, &'static str); 4] = [
(AplicacaoError::empty_wit(edge.clone()), "EmptyWit"),
(
AplicacaoError::contrato_endpoint_empty(edge.clone()),
"ContratoEndpointEmpty",
),
(
AplicacaoError::contrato_subject_empty(edge.clone()),
"ContratoSubjectEmpty",
),
(
AplicacaoError::contrato_slot_empty(edge.clone()),
"ContratoSlotEmpty",
),
];
for (built, label) in variants {
let (de, para) = match built {
AplicacaoError::EmptyWit { de, para }
| AplicacaoError::ContratoEndpointEmpty { de, para }
| AplicacaoError::ContratoSubjectEmpty { de, para }
| AplicacaoError::ContratoSlotEmpty { de, para } => (de, para),
other => panic!("expected {label} pair variant, got {other:?}"),
};
assert_eq!(de, "cart-svc", "de field on {label} must thread verbatim");
assert_eq!(
para, "catalog-v2",
"para field on {label} must thread verbatim",
);
}
}
// ── contrato_pair_value_reason_ctors! fold pins ─────────────────────
//
// Fixture edge pair + value + reason for every
// `contrato_pair_value_reason_ctors!`-generated ctor pin below. Kept
// as non-default `("cart", "catalog")` on the `(de, para)` pair and
// fixed per-axis `<val>` / reason so a byte-equality mistake against
// the fixture default doesn't silently pass. Peer of the sibling
// `contrato_empty_pair_ctor_fixture` (8580068, pair-only envelope on
// `contrato_empty_pair_ctors!`) / `contrato_target_ctor_fixture`
// (14b81d5, triple + expected-label envelope on
// `contrato_target_ctors!`) / `entrada_host_invalid_ctor_matches_
// struct_literal_wrap` (17dd504, host + reason envelope on
// `entrada_host_invalid`).
fn contrato_pair_value_reason_ctor_fixture() -> (String, String) {
("cart".to_string(), "catalog".to_string())
}
#[test]
fn contrato_endpoint_invalid_ctor_matches_struct_literal_wrap() {
// Equivalence pin: the ctor produces byte-equal
// `AplicacaoError::ContratoEndpointInvalid` to the pre-lift
// open-coded struct-literal on the same
// `(edge_pair, endpoint, reason)` triple, so the fold cannot
// silently drift on any future field-addition / reordering /
// string-conversion tweak on the variant. Peer of the sibling
// `contrato_endpoint_empty_ctor_matches_struct_literal_wrap`
// (8580068) on the paired two-slot envelope of the same
// `{ de, para, ... }` prefix, and of
// `entrada_host_invalid_ctor_matches_struct_literal_wrap`
// (17dd504) on the sibling `{ <field>: String, reason: String }`
// two-slot envelope.
let (de, para) = contrato_pair_value_reason_ctor_fixture();
let endpoint = "/charge";
let reason = "sample reason text";
let lifted =
AplicacaoError::contrato_endpoint_invalid((de.clone(), para.clone()), endpoint, reason);
let struct_literal = AplicacaoError::ContratoEndpointInvalid {
de,
para,
endpoint: endpoint.to_string(),
reason: reason.to_string(),
};
assert_eq!(lifted, struct_literal);
}
#[test]
fn contrato_subject_invalid_ctor_matches_struct_literal_wrap() {
// Equivalence pin peer of the sibling
// `contrato_endpoint_invalid_ctor_matches_struct_literal_wrap`
// above on the paired `ContratoSubjectInvalid` variant of the
// same four-slot envelope shape the
// `contrato_pair_value_reason_ctors!` macro closes.
let (de, para) = contrato_pair_value_reason_ctor_fixture();
let subject = "checkout.events.charge.failed";
let reason = "sample reason text";
let lifted =
AplicacaoError::contrato_subject_invalid((de.clone(), para.clone()), subject, reason);
let struct_literal = AplicacaoError::ContratoSubjectInvalid {
de,
para,
subject: subject.to_string(),
reason: reason.to_string(),
};
assert_eq!(lifted, struct_literal);
}
#[test]
fn contrato_slot_invalid_ctor_matches_struct_literal_wrap() {
// Equivalence pin peer of the sibling
// `contrato_subject_invalid_ctor_matches_struct_literal_wrap`
// above on the paired `ContratoSlotInvalid` variant of the same
// four-slot envelope shape.
let (de, para) = contrato_pair_value_reason_ctor_fixture();
let slot = "checkout/$orderId";
let reason = "sample reason text";
let lifted =
AplicacaoError::contrato_slot_invalid((de.clone(), para.clone()), slot, reason);
let struct_literal = AplicacaoError::ContratoSlotInvalid {
de,
para,
slot: slot.to_string(),
reason: reason.to_string(),
};
assert_eq!(lifted, struct_literal);
}
#[test]
fn contrato_wit_invalid_ctor_matches_struct_literal_wrap() {
// Equivalence pin peer of the sibling
// `contrato_slot_invalid_ctor_matches_struct_literal_wrap` above
// on the paired `ContratoWitInvalid` variant of the same four-
// slot envelope shape the `contrato_pair_value_reason_ctors!`
// macro closes. Fold pinned this test lands with the last
// `{ de, para, <field>: String, reason: String }` open-coded
// struct-literal inside [`WitContract::target`] rewritten to
// route through the macro-generated
// [`AplicacaoError::contrato_wit_invalid`] ctor — a byte-mismatch
// between the ctor and the pre-lift struct-literal trips this
// pin ahead of any downstream diagnostic-shape drift on the
// `:contratos :wit` axis.
let (de, para) = contrato_pair_value_reason_ctor_fixture();
let wit = "wasi-http/proxy";
let reason = "sample reason text";
let lifted = AplicacaoError::contrato_wit_invalid((de.clone(), para.clone()), wit, reason);
let struct_literal = AplicacaoError::ContratoWitInvalid {
de,
para,
wit: wit.to_string(),
reason: reason.to_string(),
};
assert_eq!(lifted, struct_literal);
}
#[test]
fn contrato_pair_value_reason_ctors_route_edge_pair_through_verbatim() {
// Routing pin: the `(de, para)` pair threads verbatim onto
// same-named fields on all four generated ctors, no wrapper-
// side lowercase / trim / re-order. Sweeps a non-default pair
// (`"cart-svc" → "catalog-v2"`) so any wrapper-side
// transformation surfaces here rather than at a downstream
// diagnostic-shape drift. Sibling of
// `contrato_empty_pair_ctors_route_edge_pair_through_verbatim`
// (8580068) on the paired two-slot envelope and of
// `contrato_target_ctors_route_edge_triple_through_verbatim`
// (14b81d5) on the paired triple-carrying envelope.
let edge = ("cart-svc".to_string(), "catalog-v2".to_string());
let variants: [(AplicacaoError, &'static str); 4] = [
(
AplicacaoError::contrato_endpoint_invalid(edge.clone(), "/x", "r"),
"ContratoEndpointInvalid",
),
(
AplicacaoError::contrato_subject_invalid(edge.clone(), "x.y", "r"),
"ContratoSubjectInvalid",
),
(
AplicacaoError::contrato_slot_invalid(edge.clone(), "x/y", "r"),
"ContratoSlotInvalid",
),
(
AplicacaoError::contrato_wit_invalid(edge.clone(), "wasi:http/proxy", "r"),
"ContratoWitInvalid",
),
];
for (built, label) in variants {
let (de, para) = match built {
AplicacaoError::ContratoEndpointInvalid { de, para, .. }
| AplicacaoError::ContratoSubjectInvalid { de, para, .. }
| AplicacaoError::ContratoSlotInvalid { de, para, .. }
| AplicacaoError::ContratoWitInvalid { de, para, .. } => (de, para),
other => panic!("expected {label} pair variant, got {other:?}"),
};
assert_eq!(de, "cart-svc", "de field on {label} must thread verbatim");
assert_eq!(
para, "catalog-v2",
"para field on {label} must thread verbatim",
);
}
}
#[test]
fn contrato_pair_value_reason_ctors_route_reason_through_into_uniformly() {
// Cross-arm invariance pin — the four ctors all route
// `reason: impl Into<String>` verbatim onto their respective
// typed variants through the shared
// [`contrato_pair_value_reason_ctors!`] macro. Sweeps a fixture
// pair (`&str` literal, `format!` output) against every ctor to
// pin that no per-arm wrapper transformation drifted in against
// the uniform macro-generated body. Peer of
// `aplicacao_field_reason_ctors_route_reason_through_into_uniformly`
// (981060b) on the sibling two-slot envelope's cross-arm sweep.
let edge = || ("cart".to_string(), "catalog".to_string());
let via_literal = "literal reason text";
let via_format = format!("{} reason text", "literal");
assert_eq!(
AplicacaoError::contrato_endpoint_invalid(edge(), "/e", via_literal),
AplicacaoError::contrato_endpoint_invalid(edge(), "/e", via_format.clone()),
);
assert_eq!(
AplicacaoError::contrato_subject_invalid(edge(), "s.t", via_literal),
AplicacaoError::contrato_subject_invalid(edge(), "s.t", via_format.clone()),
);
assert_eq!(
AplicacaoError::contrato_slot_invalid(edge(), "k/v", via_literal),
AplicacaoError::contrato_slot_invalid(edge(), "k/v", via_format.clone()),
);
assert_eq!(
AplicacaoError::contrato_wit_invalid(edge(), "wasi:http/proxy", via_literal),
AplicacaoError::contrato_wit_invalid(edge(), "wasi:http/proxy", via_format),
);
}
// ── contrato_endpoint_not_absolute standalone ctor pins ─────────────
//
// Fail-before-pass-after pins for the standalone
// [`AplicacaoError::contrato_endpoint_not_absolute`] inherent ctor
// (see the paired doc-block above the ctor definition) — the fold of
// the last open-coded three-slot `{ de, para, endpoint: <val>
// .to_string() }` struct-literal inside [`WitContract::target`]'s
// HTTP-arm leading-slash gate onto one substrate primitive on the
// envelope. A byte-mismatched ctor body would trip the equivalence
// pin first, ahead of any downstream diagnostic-shape drift.
//
// Peer of the sibling standalone-ctor equivalence pins on the peer
// one-off variants across caixa-core:
// `contrato_endpoint_empty_ctor_matches_struct_literal_wrap` +
// `contrato_endpoint_invalid_ctor_matches_struct_literal_wrap` above
// on the paired two-slot and four-slot per-`:contratos :endpoint`
// envelopes; `child_caixa_invalid_ctor_matches_struct_literal_wrap`
// and `child_versao_invalid_ctor_matches_struct_literal_wrap`
// (d2ef2ec) on the sibling `SupervisorError` `{ caixa, [versao,]
// reason }` two- and three-slot envelopes; the
// `entrada_host_invalid_ctor_matches_struct_literal_wrap` (17dd504)
// pin on the sibling standalone `{ host, reason }` two-slot ctor.
fn contrato_endpoint_not_absolute_ctor_fixture() -> (String, String) {
("cart".to_string(), "catalog".to_string())
}
#[test]
fn contrato_endpoint_not_absolute_ctor_matches_struct_literal_wrap() {
// Equivalence pin: the ctor produces byte-equal
// `AplicacaoError::ContratoEndpointNotAbsolute` to the pre-lift
// open-coded struct-literal on the same `(edge_pair, endpoint)`
// pair, so the fold cannot silently drift on any future
// field-addition / reordering / string-conversion tweak on the
// variant. Same equivalence-pin shape as the sibling
// `contrato_endpoint_empty_ctor_matches_struct_literal_wrap`
// (8580068) on the paired two-slot envelope and
// `contrato_endpoint_invalid_ctor_matches_struct_literal_wrap`
// (14e13f1) on the paired four-slot envelope of the same
// `{ de, para, ... }`-prefix `:endpoint` axis.
let (de, para) = contrato_endpoint_not_absolute_ctor_fixture();
let endpoint = "charge";
let lifted =
AplicacaoError::contrato_endpoint_not_absolute((de.clone(), para.clone()), endpoint);
let struct_literal = AplicacaoError::ContratoEndpointNotAbsolute {
de,
para,
endpoint: endpoint.to_string(),
};
assert_eq!(lifted, struct_literal);
}
#[test]
fn contrato_endpoint_not_absolute_ctor_routes_edge_pair_through_verbatim() {
// Routing pin on the `(de, para)` axis: sweep a non-default
// pair (`"cart-svc" → "catalog-v2"`) so any wrapper-side
// lowercase / trim / re-order surfaces here rather than at a
// downstream diagnostic-shape drift. Peer of
// `contrato_empty_pair_ctors_route_edge_pair_through_verbatim`
// (8580068) on the paired two-slot envelope and
// `contrato_pair_value_reason_ctors_route_edge_pair_through_verbatim`
// (14e13f1) on the paired four-slot envelope of the same
// `{ de, para, ... }`-prefix `:contratos` axis.
let edge = ("cart-svc".to_string(), "catalog-v2".to_string());
let built = AplicacaoError::contrato_endpoint_not_absolute(edge, "charge");
match built {
AplicacaoError::ContratoEndpointNotAbsolute { de, para, .. } => {
assert_eq!(de, "cart-svc", "de field must thread verbatim");
assert_eq!(para, "catalog-v2", "para field must thread verbatim");
}
other => panic!("expected ContratoEndpointNotAbsolute, got {other:?}"),
}
}
#[test]
fn contrato_endpoint_not_absolute_ctor_routes_endpoint_through_to_string() {
// Routing pin on the `endpoint: &str` axis: sweep a non-default
// value (`"charge"` — no leading `/`, the exact shape the
// [`WitContract::target`] HTTP-arm leading-slash gate rejects)
// through the sole payload-carrier constructor axis so any
// wrapper-side transformation on the `endpoint.to_string()`
// one-field construction surfaces here rather than at a
// downstream diagnostic-shape mismatch. Sibling of
// `contrato_pair_value_reason_ctors_route_reason_through_into_uniformly`
// (14e13f1) on the sibling four-slot envelope's payload-carrier
// routing pin.
let edge = || ("cart".to_string(), "catalog".to_string());
let via_literal = "charge";
let via_string = String::from("charge");
assert_eq!(
AplicacaoError::contrato_endpoint_not_absolute(edge(), via_literal),
AplicacaoError::contrato_endpoint_not_absolute(edge(), via_string.as_str()),
);
}
// ── contrato_self_loop standalone ctor pins ─────────────────────────
//
// Fail-before-pass-after pins for the standalone
// [`AplicacaoError::contrato_self_loop`] inherent ctor (see the paired
// doc-block above the ctor definition) — the fold of the last
// open-coded two-slot `{ caixa: <ct>.source().to_string(), wit:
// <ct>.world_ref().to_string() }` struct-literal inside
// [`AplicacaoSpec::validate_contratos`]'s per-`:contratos` self-edge
// arm onto one substrate primitive on the [`AplicacaoError`]
// envelope, projecting through the paired [`WitContract::source`] /
// [`WitContract::world_ref`] scalar accessors on the substrate
// primitive. A byte-mismatched ctor body would trip the equivalence
// pin first, ahead of any downstream diagnostic-shape drift.
//
// Peer of the sibling standalone-ctor equivalence pins on the peer
// one-off variants across caixa-core:
// `contrato_endpoint_not_absolute_ctor_matches_struct_literal_wrap`
// (cdf1a2c) above on the paired three-slot `{ de, para, endpoint }`
// envelope, the sibling
// `contrato_endpoint_empty_ctor_matches_struct_literal_wrap` +
// `contrato_endpoint_invalid_ctor_matches_struct_literal_wrap` on
// the paired two-slot and four-slot per-`:contratos :endpoint`
// envelopes, and the sibling
// `entrada_host_invalid_ctor_matches_struct_literal_wrap` (17dd504)
// pin on the sibling standalone `{ host, reason }` two-slot ctor.
fn contrato_self_loop_ctor_fixture() -> WitContract {
WitContract {
de: "cart".to_string(),
para: "cart".to_string(),
wit: "wasi:http/proxy".to_string(),
endpoint: Some("/self".to_string()),
subject: None,
slot: None,
}
}
#[test]
fn contrato_self_loop_ctor_matches_struct_literal_wrap() {
// Equivalence pin: the ctor produces byte-equal
// `AplicacaoError::ContratoSelfLoop` to the pre-lift open-coded
// struct-literal that read the same two fields through
// [`WitContract::source`] and [`WitContract::world_ref`]. Guards
// any future field-addition / reordering / string-conversion
// tweak on the variant. Same equivalence-pin shape as the
// sibling `contrato_endpoint_not_absolute_ctor_matches_
// struct_literal_wrap` (cdf1a2c) on the paired three-slot
// per-`:contratos :endpoint` envelope.
let contract = contrato_self_loop_ctor_fixture();
let lifted = AplicacaoError::contrato_self_loop(&contract);
let struct_literal = AplicacaoError::ContratoSelfLoop {
caixa: contract.source().to_string(),
wit: contract.world_ref().to_string(),
};
assert_eq!(lifted, struct_literal);
}
#[test]
fn contrato_self_loop_ctor_routes_source_and_world_ref_through_verbatim() {
// Routing pin sweeping non-default `caixa` and `:wit` values
// (`"catalog-v2"` / `"nats:pub-sub"`) through the paired
// [`WitContract::source`] / [`WitContract::world_ref`] accessor
// axes so any wrapper-side lowercase / trim / re-order surfaces
// here rather than at a downstream diagnostic-shape drift.
// Peer of the sibling
// `contrato_endpoint_not_absolute_ctor_routes_edge_pair_through_verbatim`
// (cdf1a2c) routing pin on the sibling three-slot envelope.
let contract = WitContract {
de: "catalog-v2".to_string(),
para: "catalog-v2".to_string(),
wit: "nats:pub-sub".to_string(),
endpoint: None,
subject: Some("orders.>".to_string()),
slot: None,
};
let built = AplicacaoError::contrato_self_loop(&contract);
match built {
AplicacaoError::ContratoSelfLoop { caixa, wit } => {
assert_eq!(
caixa, "catalog-v2",
"caixa slot must thread WitContract::source() verbatim"
);
assert_eq!(
wit, "nats:pub-sub",
"wit slot must thread WitContract::world_ref() verbatim"
);
}
other => panic!("expected ContratoSelfLoop, got {other:?}"),
}
}
#[test]
fn contrato_self_loop_ctor_projects_source_field_not_destination() {
// Accessor-fidelity pin: the ctor's `caixa` slot keys off the
// [`WitContract::source`] accessor (matching the pre-lift open-
// coded body's field selection), not [`WitContract::destination`].
// Under today's `WitContract::is_self_loop()`-gated call site
// the two are equal by that predicate's own contract, but a
// future consumer that constructs the ctor against a not-yet-
// gated candidate contract — an M4
// `mesh.pleme.io/v1alpha1/Aplicacao` CR admission webhook re-
// checking a per-`(:de, :para)`-patched candidate before the
// self-loop gate re-fires, a per-tenant per-Aplicacao overlay
// resolver rejecting a self-edge introduced by a cluster-local
// `:contratos` override — needs the pre-lift field selection
// pinned so a silent `.destination()` swap at the ctor body
// surfaces here rather than at a downstream diagnostic mis-
// attribution far from the self-loop diagnostic's owner
// (the `caller` side per MESH-COMPOSITION §III.1's typed edge
// direction).
//
// Deliberately constructs a non-self-loop pair (`"cart" →
// "catalog"`) so the two accessors yield distinct bytes on the
// fixture — a `.destination()` swap at the ctor body would land
// `"catalog"` in the `caixa` slot instead of `"cart"` and trip
// the assertion here.
let contract = WitContract {
de: "cart".to_string(),
para: "catalog".to_string(),
wit: "wasi:http/proxy".to_string(),
endpoint: Some("/charge".to_string()),
subject: None,
slot: None,
};
let built = AplicacaoError::contrato_self_loop(&contract);
match built {
AplicacaoError::ContratoSelfLoop { caixa, .. } => {
assert_eq!(
caixa, "cart",
"caixa slot must project WitContract::source() (not destination)"
);
}
other => panic!("expected ContratoSelfLoop, got {other:?}"),
}
}
// Pin the four-slot `{ de, para, wit, target }` per-`:contratos`
// whole-edge-dedup sibling of the two-slot per-`:contratos` envelope
// family — the sole per-axis ctor projecting through both
// [`WitContract::edge_triple`] (on the leading `de` / `para` / `wit`
// triple) and [`WitTarget::label`] (on the trailing `target` slot).
// Equivalence pin locks the ctor body to the pre-lift struct-literal
// shape under `PartialEq`, so any accessor-side field-selection drift
// or per-arm wrapper transformation surfaces here as a build-time
// test failure rather than at a downstream diagnostic-shape mismatch
// far from the substrate primitive. Peer of the sibling
// `contrato_self_loop_ctor_matches_struct_literal_wrap` (b30edfe)
// equivalence pin on the paired two-slot `{ caixa, wit }` per-self-
// edge envelope's `WitContract`-projection ctor.
#[test]
fn contrato_duplicate_ctor_matches_struct_literal_wrap() {
let contract = contrato_self_loop_ctor_fixture();
let target = contract.target_projected();
let lifted = AplicacaoError::contrato_duplicate(&contract, &target);
let (de, para, wit) = contract.edge_triple();
let struct_literal = AplicacaoError::ContratoDuplicate {
de,
para,
wit,
target: target.label(),
};
assert_eq!(lifted, struct_literal);
}
// Routing pin sweeping a non-self-loop pair (`"cart" → "catalog"`) so
// the paired [`WitContract::edge_triple`] projection's three axes
// (`de`, `para`, `wit`) and the [`WitTarget::label`] projection on
// the `target` axis all yield distinct bytes on the fixture — any
// wrapper-side re-order / accessor-swap on the four axes surfaces
// here rather than at a downstream diagnostic-shape drift. Peer of
// the sibling
// `contrato_self_loop_ctor_routes_source_and_world_ref_through_verbatim`
// (b30edfe) routing pin on the paired two-slot envelope.
#[test]
fn contrato_duplicate_ctor_routes_edge_triple_and_target_label_verbatim() {
let contract = WitContract {
de: "cart".to_string(),
para: "catalog".to_string(),
wit: "wasi:http/proxy".to_string(),
endpoint: Some("/charge".to_string()),
subject: None,
slot: None,
};
let target = contract.target_projected();
let built = AplicacaoError::contrato_duplicate(&contract, &target);
match built {
AplicacaoError::ContratoDuplicate {
de,
para,
wit,
target,
} => {
assert_eq!(
de, "cart",
"de slot must thread WitContract::edge_triple().0 verbatim"
);
assert_eq!(
para, "catalog",
"para slot must thread WitContract::edge_triple().1 verbatim"
);
assert_eq!(
wit, "wasi:http/proxy",
"wit slot must thread WitContract::edge_triple().2 verbatim"
);
assert!(
target.contains("/charge"),
"target slot must project through WitTarget::label() \
(got target = {target:?})"
);
}
other => panic!("expected ContratoDuplicate, got {other:?}"),
}
}
// Per-variant equivalence pins for the [`aplicacao_caixa_only_ctors!`]
// macro definition (see the paired doc-block above the macro definition)
// — every generated `<ctor>(caixa: &str) -> Self` constructor folds the
// uniform `Self::<Variant> { caixa: caixa.to_string() }` one-field
// struct-literal onto one substrate primitive. The four per-variant
// equivalence pins below (fail-before-pass-after by construction — a
// byte-mismatched macro arm would trip its equivalence pin first) lock
// each generated constructor to its struct-literal peer under
// `PartialEq`, so every wire-up in [`WitContract::require_endpoints_in`],
// [`AplicacaoSpec::validate_membros`], and
// [`validate_no_self_membership`] on that variant produces a byte-equal
// `AplicacaoError` to the pre-lift open-coded struct-literal. The
// cross-axis pin that follows (non-default caixa name) routes the sole
// constructor input axis through `.to_string()`, so the fold does not
// silently collapse onto a fixed name.
//
// Peer of the sibling per-variant `<ctor>_matches_struct_literal_wrap`
// and cross-axis `<macro>_route_caixa_through_to_string` pins on the
// sibling `SupervisorError` `{ caixa: String }` envelope (db09650,
// `supervisor_caixa_only_ctors!`), sibling of the peer per-variant +
// cross-axis pins on the peer three `AplicacaoError` sub-family folds
// (14b81d5 / 8580068 / 981060b / 14e13f1), sibling of the peer four
// `LayoutError` families (131ca0d / 0419438 / 1b09f9d / 3fe3dd7), sibling
// of the peer M2 `:behavior` envelope fold (67c31ec,
// `behavior_slot_path_ctors!` `{ slot, path }`), sibling of the peer M2
// `:upgrade-from` envelope folds (8e67041 / 7468ca9), and sibling of the
// peer `DepError` envelope folds (792aa92 / f85f145 / 0e35793).
#[test]
fn contrato_member_missing_ctor_matches_struct_literal_wrap() {
assert_eq!(
AplicacaoError::contrato_member_missing("cart"),
AplicacaoError::ContratoMemberMissing {
caixa: "cart".to_string(),
},
"generated contrato_member_missing ctor must produce byte-equal \
AplicacaoError to the open-coded struct-literal wrap on the \
same &str fixture",
);
}
#[test]
fn membro_versao_empty_ctor_matches_struct_literal_wrap() {
assert_eq!(
AplicacaoError::membro_versao_empty("cart"),
AplicacaoError::MembroVersaoEmpty {
caixa: "cart".to_string(),
},
"generated membro_versao_empty ctor must produce byte-equal \
AplicacaoError to the open-coded struct-literal wrap on the \
same &str fixture",
);
}
#[test]
fn membro_duplicate_ctor_matches_struct_literal_wrap() {
assert_eq!(
AplicacaoError::membro_duplicate("cart"),
AplicacaoError::MembroDuplicate {
caixa: "cart".to_string(),
},
"generated membro_duplicate ctor must produce byte-equal \
AplicacaoError to the open-coded struct-literal wrap on the \
same &str fixture",
);
}
#[test]
fn membro_is_self_aplicacao_ctor_matches_struct_literal_wrap() {
assert_eq!(
AplicacaoError::membro_is_self_aplicacao("checkout"),
AplicacaoError::MembroIsSelfAplicacao {
caixa: "checkout".to_string(),
},
"generated membro_is_self_aplicacao ctor must produce byte-equal \
AplicacaoError to the open-coded struct-literal wrap on the \
same &str fixture",
);
}
#[test]
fn aplicacao_caixa_only_ctors_route_caixa_through_to_string() {
// Cross-axis pin: sweep the sole constructor input axis (`caixa:
// &str`) through a non-default fixture name against every generated
// arm in the [`aplicacao_caixa_only_ctors!`] macro, so any
// wrapper-side lowercase / trim / truncate / re-order on the
// `caixa.to_string()` sole-field construction surfaces here rather
// than at a downstream diagnostic-shape mismatch. Peer of the
// sibling `supervisor_caixa_only_ctors_route_caixa_through_to_string`
// cross-axis pin on the sibling `SupervisorError` `{ caixa: String }`
// envelope (db09650), extended here onto the peer `AplicacaoError`
// `{ caixa: String }` envelope so every substrate-primitive ctor
// family in caixa-core carrying a single-slot `{ caixa: String }`
// shape guarantees the sole-field construction routes the caller's
// `&str` through `.to_string()` verbatim.
let name = "cache-v2";
assert_eq!(
AplicacaoError::contrato_member_missing(name),
AplicacaoError::ContratoMemberMissing {
caixa: name.to_string(),
},
);
assert_eq!(
AplicacaoError::membro_versao_empty(name),
AplicacaoError::MembroVersaoEmpty {
caixa: name.to_string(),
},
);
assert_eq!(
AplicacaoError::membro_duplicate(name),
AplicacaoError::MembroDuplicate {
caixa: name.to_string(),
},
);
assert_eq!(
AplicacaoError::membro_is_self_aplicacao(name),
AplicacaoError::MembroIsSelfAplicacao {
caixa: name.to_string(),
},
);
}
#[test]
fn entrada_path_not_absolute_ctor_matches_struct_literal_wrap() {
assert_eq!(
AplicacaoError::entrada_path_not_absolute("api/cart"),
AplicacaoError::EntradaPathNotAbsolute {
path: "api/cart".to_string(),
},
"generated entrada_path_not_absolute ctor must produce byte-equal \
AplicacaoError to the open-coded struct-literal wrap on the \
same &str fixture",
);
}
#[test]
fn entrada_path_duplicate_ctor_matches_struct_literal_wrap() {
assert_eq!(
AplicacaoError::entrada_path_duplicate("/api/cart"),
AplicacaoError::EntradaPathDuplicate {
path: "/api/cart".to_string(),
},
"generated entrada_path_duplicate ctor must produce byte-equal \
AplicacaoError to the open-coded struct-literal wrap on the \
same &str fixture",
);
}
// ── membro_versao_invalid ctor pins ────────────────────────────────
//
// Per-variant byte-equality + cross-axis routing pins guaranteeing the
// lifted [`AplicacaoError::membro_versao_invalid`] inherent constructor
// produces an `AplicacaoError` structurally identical to the pre-lift
// `Self::MembroVersaoInvalid { caixa: caixa.to_string(), versao:
// versao.to_string(), reason: reason.into() }` open-coded three-slot
// struct-literal on the same `(&str, &str, reason)` fixture. Peer of
// the sibling `child_versao_invalid_ctor_matches_struct_literal_wrap` +
// `supervisor_child_reason_ctors_route_reason_through_into_uniformly`
// pins on the peer `SupervisorError` `{ caixa: String, versao: String,
// reason: String }` envelope's per-`:children :versao` axis (d2ef2ec),
// extended here onto the paired per-`:membros :versao` axis on the
// sibling `AplicacaoError` envelope so both three-slot `{ caixa,
// versao, reason }` per-caixa-versao-invalidation ctors on caixa-core's
// typed-error surface guarantee the shared three-field construction
// routes through one substrate primitive per envelope.
#[test]
fn membro_versao_invalid_ctor_matches_struct_literal_wrap() {
let caixa = "cart";
let versao = "not-a-req";
let reason = "sample reason text";
assert_eq!(
AplicacaoError::membro_versao_invalid(caixa, versao, reason),
AplicacaoError::MembroVersaoInvalid {
caixa: caixa.to_string(),
versao: versao.to_string(),
reason: reason.to_string(),
},
"lifted membro_versao_invalid ctor must produce byte-equal \
AplicacaoError to the open-coded struct-literal wrap on the \
same (&str, &str, reason) fixture",
);
}
#[test]
fn membro_versao_invalid_ctor_routes_caixa_and_versao_through_to_string() {
// Cross-axis pin: sweep the two `&str`-shaped constructor input
// axes (`caixa`, `versao`) through non-default fixtures so any
// wrapper-side lowercase / trim / truncate / re-order on either
// `.to_string()` field construction surfaces here rather than at
// a downstream diagnostic-shape mismatch. Peer of the sibling
// `supervisor_child_reason_ctors_route_reason_through_into_uniformly`
// routing pin on the peer `SupervisorError` envelope.
let caixa = "Cart-V2";
let versao = "0.1.0-alpha+build.42";
let reason = "constructed reason";
let err = AplicacaoError::membro_versao_invalid(caixa, versao, reason);
let AplicacaoError::MembroVersaoInvalid {
caixa: got_caixa,
versao: got_versao,
reason: got_reason,
} = err
else {
panic!("membro_versao_invalid must construct MembroVersaoInvalid variant");
};
assert_eq!(got_caixa, caixa.to_string());
assert_eq!(got_versao, versao.to_string());
assert_eq!(got_reason, reason.to_string());
}
#[test]
fn membro_versao_invalid_ctor_routes_reason_through_into() {
// Route pin: the `reason: impl Into<String>` bound accepts both
// `&str` literals and `format!(…)` / `String` outputs verbatim,
// matching the sibling
// `supervisor_child_reason_ctors_route_reason_through_into_uniformly`
// routing pin on the peer `SupervisorError::child_versao_invalid`.
// Pins the sole `AplicacaoSpec::validate_membros` wire-up's
// `require_valid_versao_requirement`-delivered `reason` closure
// parameter (typed `String`) picks the ctor up without a per-arm
// wrapper transformation, and every future consumer that
// constructs the variant from a `format!(…)` reason surfaces
// byte-equal to the `&str`-literal path.
let caixa = "cart";
let versao = "not-a-req";
let from_literal = AplicacaoError::membro_versao_invalid(caixa, versao, "literal reason");
let from_format =
AplicacaoError::membro_versao_invalid(caixa, versao, format!("{} reason", "literal"));
let from_string =
AplicacaoError::membro_versao_invalid(caixa, versao, "literal reason".to_string());
assert_eq!(from_literal, from_format);
assert_eq!(from_literal, from_string);
}
#[test]
fn aplicacao_path_only_ctors_route_path_through_to_string() {
// Cross-axis pin: sweep the sole constructor input axis (`path:
// &str`) through a non-default fixture path against every generated
// arm in the [`aplicacao_path_only_ctors!`] macro, so any
// wrapper-side lowercase / trim / truncate / re-order on the
// `path.to_string()` sole-field construction surfaces here rather
// than at a downstream diagnostic-shape mismatch. Peer of the
// sibling `aplicacao_caixa_only_ctors_route_caixa_through_to_string`
// cross-axis pin on the peer `AplicacaoError` `{ caixa: String }`
// envelope (d9f6867), extended here onto the sibling
// `AplicacaoError` `{ path: String }` envelope so every substrate-
// primitive ctor family in caixa-core carrying a single-slot
// `{ <slot>: String }` shape guarantees the sole-field construction
// routes the caller's `&str` through `.to_string()` verbatim.
let path = "/api/v2/checkout";
assert_eq!(
AplicacaoError::entrada_path_not_absolute(path),
AplicacaoError::EntradaPathNotAbsolute {
path: path.to_string(),
},
);
assert_eq!(
AplicacaoError::entrada_path_duplicate(path),
AplicacaoError::EntradaPathDuplicate {
path: path.to_string(),
},
);
}
// ── aplicacao_policy_scalar_ctors! per-variant + cross-axis pins ────────
//
// Per-variant byte-equality pins guaranteeing every generated ctor arm in
// the [`aplicacao_policy_scalar_ctors!`] macro produces an `AplicacaoError`
// structurally identical to the pre-lift `Self::<variant> { <field>: <val> }`
// one-line struct-literal on the same `Copy`-`Duration | u32` fixture, plus
// one cross-axis sweep that routes each per-variant `<field>: <ty>` scalar
// through the sole `$field:ident: $ty:ty` axis the macro exposes so any
// wrapper-side truncation / re-order / silent `.into()` / silent constant-
// substitution on any one variant surfaces here rather than at a downstream
// per-`:politicas` diagnostic-shape drift. Peer of the sibling per-variant
// pins on `aplicacao_field_reason_ctors!` (981060b),
// `aplicacao_caixa_only_ctors!` (d9f6867), `aplicacao_path_only_ctors!`
// (3ba8de6), `contrato_pair_value_reason_ctors!` (14e13f1),
// `contrato_empty_pair_ctors!` (8580068), `contrato_target_ctors!`
// (14b81d5), plus the sibling `DepError` / `SupervisorError` /
// `LayoutError` / `LimitsError` / `BehaviorError` / `UpgradeError`
// per-envelope ctor-macro pins.
#[test]
fn policy_timeout_not_canonical_ctor_matches_struct_literal_wrap() {
let timeout = Duration::from_micros(1_500);
assert_eq!(
AplicacaoError::policy_timeout_not_canonical(timeout),
AplicacaoError::PolicyTimeoutNotCanonical { timeout },
"generated policy_timeout_not_canonical ctor must produce byte-equal \
`AplicacaoError::PolicyTimeoutNotCanonical` to the pre-lift \
struct-literal wrap on the same `Copy`-`Duration` fixture",
);
}
#[test]
fn policy_timeout_exceeds_cap_ctor_matches_struct_literal_wrap() {
let timeout = Duration::from_secs(3_601);
assert_eq!(
AplicacaoError::policy_timeout_exceeds_cap(timeout),
AplicacaoError::PolicyTimeoutExceedsCap { timeout },
"generated policy_timeout_exceeds_cap ctor must produce byte-equal \
`AplicacaoError::PolicyTimeoutExceedsCap` to the pre-lift \
struct-literal wrap on the same `Copy`-`Duration` fixture",
);
}
#[test]
fn policy_retries_exceeds_cap_ctor_matches_struct_literal_wrap() {
let retries = 47_u32;
assert_eq!(
AplicacaoError::policy_retries_exceeds_cap(retries),
AplicacaoError::PolicyRetriesExceedsCap { retries },
"generated policy_retries_exceeds_cap ctor must produce byte-equal \
`AplicacaoError::PolicyRetriesExceedsCap` to the pre-lift \
struct-literal wrap on the same `Copy`-`u32` fixture",
);
}
#[test]
fn policy_breaker_max_failures_exceeds_cap_ctor_matches_struct_literal_wrap() {
let max_failures = 1_337_u32;
assert_eq!(
AplicacaoError::policy_breaker_max_failures_exceeds_cap(max_failures),
AplicacaoError::PolicyBreakerMaxFailuresExceedsCap { max_failures },
"generated policy_breaker_max_failures_exceeds_cap ctor must produce \
byte-equal `AplicacaoError::PolicyBreakerMaxFailuresExceedsCap` to \
the pre-lift struct-literal wrap on the same `Copy`-`u32` fixture",
);
}
#[test]
fn policy_breaker_window_not_canonical_ctor_matches_struct_literal_wrap() {
let window = Duration::from_micros(500);
assert_eq!(
AplicacaoError::policy_breaker_window_not_canonical(window),
AplicacaoError::PolicyBreakerWindowNotCanonical { window },
"generated policy_breaker_window_not_canonical ctor must produce \
byte-equal `AplicacaoError::PolicyBreakerWindowNotCanonical` to the \
pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
);
}
#[test]
fn policy_breaker_window_exceeds_cap_ctor_matches_struct_literal_wrap() {
let window = Duration::from_secs(3_700);
assert_eq!(
AplicacaoError::policy_breaker_window_exceeds_cap(window),
AplicacaoError::PolicyBreakerWindowExceedsCap { window },
"generated policy_breaker_window_exceeds_cap ctor must produce \
byte-equal `AplicacaoError::PolicyBreakerWindowExceedsCap` to the \
pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
);
}
#[test]
fn policy_rate_limit_exceeds_cap_ctor_matches_struct_literal_wrap() {
let rate = 1_000_001_u32;
assert_eq!(
AplicacaoError::policy_rate_limit_exceeds_cap(rate),
AplicacaoError::PolicyRateLimitExceedsCap { rate },
"generated policy_rate_limit_exceeds_cap ctor must produce byte-equal \
`AplicacaoError::PolicyRateLimitExceedsCap` to the pre-lift \
struct-literal wrap on the same `Copy`-`u32` fixture",
);
}
#[test]
fn policy_rate_limit_window_not_canonical_ctor_matches_struct_literal_wrap() {
let window = Duration::from_secs(15);
assert_eq!(
AplicacaoError::policy_rate_limit_window_not_canonical(window),
AplicacaoError::PolicyRateLimitWindowNotCanonical { window },
"generated policy_rate_limit_window_not_canonical ctor must produce \
byte-equal `AplicacaoError::PolicyRateLimitWindowNotCanonical` to \
the pre-lift struct-literal wrap on the same `Copy`-`Duration` \
fixture",
);
}
#[test]
fn aplicacao_policy_scalar_ctors_route_field_through_copy_uniformly() {
// Cross-axis routing pin: sweep each generated `<field>: <ty>`
// constructor input axis through a non-default `Copy` fixture against
// every arm in the [`aplicacao_policy_scalar_ctors!`] macro, so any
// wrapper-side silent `.into()` / silent constant-substitution / silent
// field re-name away from the canonical `timeout | retries |
// max_failures | window | rate` axes on any one variant, or a
// `Duration | u32` axis silently rerouted through some other `Copy`
// coercion, surfaces here rather than at a downstream per-`:politicas`
// diagnostic-shape drift. Peer of the sibling
// `aplicacao_caixa_only_ctors_route_caixa_through_to_string`
// (d9f6867), `aplicacao_path_only_ctors_route_path_through_to_string`
// (3ba8de6), `dep_nome_list_ctors_route_nome_and_list_through_uniformly`
// (6f5e0cd), and `supervisor_child_reason_ctors_route_reason_through_into_uniformly`
// (d2ef2ec) cross-axis routing pins on the peer per-envelope ctor
// families, extended here onto the last M3 per-`:politicas` per-axis
// `AplicacaoError` variant family folded onto a substrate primitive.
//
// Fixtures picked out of each variant's accept-set boundary rather
// than the default value so a silent constant-substitution to `0` /
// `Duration::ZERO` / any per-variant sentinel surfaces here on the
// structural-equality assertion. The two `Duration` fixtures pick the
// sub-millisecond and above-cap ends respectively; the three `u32`
// fixtures pick above-cap magnitudes for `retries` / `max_failures` /
// `rate` respectively (each variant's cap sits well below the fixture
// so the pre-lift struct-literal wrap the fixture is compared against
// is the same shape the pre-lift wire-up produced).
let sub_ms = Duration::from_micros(1_500);
let above_hour = Duration::from_secs(3_700);
let non_canonical_rl_window = Duration::from_secs(15);
assert_eq!(
AplicacaoError::policy_timeout_not_canonical(sub_ms),
AplicacaoError::PolicyTimeoutNotCanonical { timeout: sub_ms },
);
assert_eq!(
AplicacaoError::policy_timeout_exceeds_cap(above_hour),
AplicacaoError::PolicyTimeoutExceedsCap {
timeout: above_hour,
},
);
assert_eq!(
AplicacaoError::policy_retries_exceeds_cap(47),
AplicacaoError::PolicyRetriesExceedsCap { retries: 47 },
);
assert_eq!(
AplicacaoError::policy_breaker_max_failures_exceeds_cap(1_337),
AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
max_failures: 1_337,
},
);
assert_eq!(
AplicacaoError::policy_breaker_window_not_canonical(sub_ms),
AplicacaoError::PolicyBreakerWindowNotCanonical { window: sub_ms },
);
assert_eq!(
AplicacaoError::policy_breaker_window_exceeds_cap(above_hour),
AplicacaoError::PolicyBreakerWindowExceedsCap { window: above_hour },
);
assert_eq!(
AplicacaoError::policy_rate_limit_exceeds_cap(1_000_001),
AplicacaoError::PolicyRateLimitExceedsCap { rate: 1_000_001 },
);
assert_eq!(
AplicacaoError::policy_rate_limit_window_not_canonical(non_canonical_rl_window),
AplicacaoError::PolicyRateLimitWindowNotCanonical {
window: non_canonical_rl_window,
},
);
}
#[test]
fn aplicacao_policy_scalar_ctors_are_const_zero_runtime_work() {
// Const-eval pin: the [`aplicacao_policy_scalar_ctors!`] macro spells
// every generated ctor `const fn` so a caller can pin an
// `AplicacaoError` at compile time — the same zero-runtime-work
// property the pre-lift `|<slot>| AplicacaoError::<Variant> { <slot> }`
// closure carried on its `Copy`-pass-through construction path (no
// `.to_string()` / `.into()` allocation, no branching). If any future
// edit silently drops the `const` qualifier from the macro body the
// per-arm `const` bindings below fail to compile, which surfaces the
// regression at the substrate-primitive definition rather than at
// some downstream consumer that had come to rely on the `const`-
// constructibility. Peer of the sibling per-variant
// `_ctor_matches_struct_literal_wrap` pins above on the runtime-
// equality axis; this pin closes the compile-time-const axis on the
// same generated family.
const TIMEOUT_NC: AplicacaoError =
AplicacaoError::policy_timeout_not_canonical(Duration::from_micros(1));
const TIMEOUT_CAP: AplicacaoError =
AplicacaoError::policy_timeout_exceeds_cap(Duration::from_secs(3_601));
const RETRIES_CAP: AplicacaoError = AplicacaoError::policy_retries_exceeds_cap(11);
const MAX_FAIL_CAP: AplicacaoError =
AplicacaoError::policy_breaker_max_failures_exceeds_cap(1_001);
const CB_WIN_NC: AplicacaoError =
AplicacaoError::policy_breaker_window_not_canonical(Duration::from_micros(1));
const CB_WIN_CAP: AplicacaoError =
AplicacaoError::policy_breaker_window_exceeds_cap(Duration::from_secs(3_601));
const RATE_CAP: AplicacaoError = AplicacaoError::policy_rate_limit_exceeds_cap(1_000_001);
const RL_WIN_NC: AplicacaoError =
AplicacaoError::policy_rate_limit_window_not_canonical(Duration::from_secs(15));
assert!(matches!(
TIMEOUT_NC,
AplicacaoError::PolicyTimeoutNotCanonical { .. }
));
assert!(matches!(
TIMEOUT_CAP,
AplicacaoError::PolicyTimeoutExceedsCap { .. }
));
assert!(matches!(
RETRIES_CAP,
AplicacaoError::PolicyRetriesExceedsCap { .. }
));
assert!(matches!(
MAX_FAIL_CAP,
AplicacaoError::PolicyBreakerMaxFailuresExceedsCap { .. }
));
assert!(matches!(
CB_WIN_NC,
AplicacaoError::PolicyBreakerWindowNotCanonical { .. }
));
assert!(matches!(
CB_WIN_CAP,
AplicacaoError::PolicyBreakerWindowExceedsCap { .. }
));
assert!(matches!(
RATE_CAP,
AplicacaoError::PolicyRateLimitExceedsCap { .. }
));
assert!(matches!(
RL_WIN_NC,
AplicacaoError::PolicyRateLimitWindowNotCanonical { .. }
));
}
// Per-variant equivalence + routing pins for the
// [`AplicacaoError::placement_cluster_duplicate`] standalone ctor
// (see the paired doc-block above the ctor definition) — the
// generated `pub fn placement_cluster_duplicate(cluster: &str) ->
// Self` inherent constructor folds the uniform
// `Self::PlacementClusterDuplicate { cluster: cluster.to_string() }`
// one-field struct-literal onto one substrate primitive. Same
// shape as the sibling
// `contrato_self_loop_ctor_matches_struct_literal_wrap` (b30edfe) /
// `contrato_endpoint_not_absolute_ctor_matches_struct_literal_wrap`
// (cdf1a2c) equivalence pins on the paired standalone `AplicacaoError`
// ctors — extended here onto the single-slot per-`:placement
// :clusters` dedup-envelope.
#[test]
fn placement_cluster_duplicate_ctor_matches_struct_literal_wrap() {
// Equivalence pin: the ctor produces byte-equal
// `AplicacaoError::PlacementClusterDuplicate` to the pre-lift
// open-coded struct-literal that read the same field through
// `c.clone()` at the caller site inside
// [`AplicacaoSpec::validate_placement_shape`]. Guards any future
// field-addition / reordering / string-conversion tweak on the
// variant.
let cluster = "rio";
let lifted = AplicacaoError::placement_cluster_duplicate(cluster);
let struct_literal = AplicacaoError::PlacementClusterDuplicate {
cluster: cluster.to_string(),
};
assert_eq!(lifted, struct_literal);
}
#[test]
fn placement_cluster_duplicate_ctor_routes_cluster_through_to_string() {
// Routing pin: sweep the sole constructor input axis
// (`cluster: &str`) through a non-default fixture name so any
// wrapper-side lowercase / trim / truncate / re-order on the
// `cluster.to_string()` sole-field construction surfaces here
// rather than at a downstream diagnostic-shape mismatch. Peer of
// the sibling
// `aplicacao_caixa_only_ctors_route_caixa_through_to_string`
// (d9f6867) cross-axis pin on the sibling one-slot
// `{ caixa: String }` envelope — extended here onto the sibling
// `{ cluster: String }` envelope so the sole `String`-slot
// construction routes the caller's `&str` through `.to_string()`
// verbatim.
let cluster = "sao-paulo-2";
let built = AplicacaoError::placement_cluster_duplicate(cluster);
match built {
AplicacaoError::PlacementClusterDuplicate { cluster: c } => {
assert_eq!(
c, cluster,
"cluster slot must thread the caller's `&str` verbatim through .to_string()"
);
}
other => panic!("expected PlacementClusterDuplicate, got {other:?}"),
}
}
// Per-variant equivalence + routing pins for the
// [`AplicacaoError::placement_without_clusters`] standalone ctor
// (see the paired doc-block above the ctor definition) — the
// generated `pub const fn placement_without_clusters(placement:
// &Placement) -> Self` inherent constructor folds the uniform
// `Self::PlacementWithoutClusters { estrategia: placement.estrategia()
// }` one-field `Copy`-pass-through struct-literal onto one substrate
// primitive. Same shape as the sibling
// `placement_cluster_duplicate_ctor_matches_struct_literal_wrap`
// (92b1c92) / `contrato_self_loop_ctor_matches_struct_literal_wrap`
// (b30edfe) equivalence pins on the paired standalone `AplicacaoError`
// ctors — extended here onto the one-slot per-`:placement`
// empty-clusters envelope.
#[test]
fn placement_without_clusters_ctor_matches_struct_literal_wrap() {
// Equivalence pin: the ctor produces byte-equal
// `AplicacaoError::PlacementWithoutClusters` to the pre-lift
// open-coded struct-literal that read the same field through
// `p.estrategia()` at the caller site inside
// [`AplicacaoSpec::validate_placement`]. Guards any future
// field-addition / reordering / accessor-return tweak on the
// variant.
let placement = Placement {
estrategia: PlacementStrategy::Replicated,
clusters: vec![],
affinity: None,
shard_key: None,
};
let lifted = AplicacaoError::placement_without_clusters(&placement);
let struct_literal = AplicacaoError::PlacementWithoutClusters {
estrategia: placement.estrategia(),
};
assert_eq!(lifted, struct_literal);
}
#[test]
fn placement_without_clusters_ctor_routes_estrategia_through_accessor() {
// Routing pin: sweep the sole constructor input axis
// (`placement: &Placement`) through every variant in the closed
// [`PlacementStrategy::ALL`] accept-set so any wrapper-side
// re-derivation / off-by-one arm-swap / stale-field read on the
// `placement.estrategia()` sole-field projection surfaces here
// rather than at a downstream diagnostic-shape mismatch. Peer of
// the sibling
// `validate_placement_reads_through_lifted_estrategia_accessor`
// three-consumer coherence pin — extended here onto the ctor
// itself so the accessor-projection posture is byte-witnessed at
// the substrate primitive rather than only at the caller-site
// fan-out. Sweeps all three [`PlacementStrategy`] variants so any
// future addition to the closed accept-set surfaces as an
// exhaustiveness gap on this iteration list.
for estrategia in [
PlacementStrategy::SingleNode,
PlacementStrategy::Replicated,
PlacementStrategy::Sharded,
] {
let placement = Placement {
estrategia,
clusters: vec![],
affinity: None,
shard_key: None,
};
let built = AplicacaoError::placement_without_clusters(&placement);
match built {
AplicacaoError::PlacementWithoutClusters { estrategia: e } => {
assert_eq!(
e,
placement.estrategia(),
"estrategia slot must thread the caller's `Placement` verbatim \
through Placement::estrategia() — the ctor reads through the \
lifted accessor",
);
assert_eq!(
e, estrategia,
"estrategia slot must byte-equal the fixture-declared variant",
);
}
other => panic!("expected PlacementWithoutClusters, got {other:?}"),
}
}
}
#[test]
fn placement_without_clusters_ctor_is_const_fn() {
// Fail-before-pass-after pin on
// [`AplicacaoError::placement_without_clusters`]'s `const`-eval-
// surface posture. The ctor threads the paired
// [`Placement::estrategia`] `const fn` `Copy`-scalar accessor's
// return through one `const fn` construction — any future
// accidental downgrade to non-`const` (a `.clone()` on the
// `Copy`-scalar `estrategia:` field expression, an owned-`String`
// materialization on the sibling non-`estrategia:` axis) fails
// `placement_without_clusters_via_const_fn` at caixa-core build
// time with E0015 (`cannot call non-const method`), strictly
// stronger than a runtime `assert!`. Sibling of the peer
// [`aplicacao_policy_scalar_ctors!`] (7ef425e) family's `const fn`
// posture on the sibling per-`:politicas` cap-scalar envelopes
// and the peer [`Placement::estrategia`] const-fn accessor pin at
// [`placement_estrategia_accessor_is_const_fn`] on the paired
// substrate primitive.
const fn placement_without_clusters_via_const_fn(p: &Placement) -> AplicacaoError {
AplicacaoError::placement_without_clusters(p)
}
let placement = Placement {
estrategia: PlacementStrategy::Sharded,
clusters: vec![],
affinity: None,
shard_key: Some("tenantId".into()),
};
assert_eq!(
placement_without_clusters_via_const_fn(&placement),
AplicacaoError::placement_without_clusters(&placement),
);
}
#[test]
fn entrada_member_missing_ctor_matches_struct_literal_wrap() {
// Equivalence pin: the ctor produces byte-equal
// `AplicacaoError::EntradaMemberMissing` to the pre-lift
// open-coded struct-literal that read the same `:para` value
// through `e.destination().to_string()` at the caller site
// inside [`AplicacaoSpec::validate_entrada`]. Guards any future
// field-addition / reordering / accessor-return tweak on the
// variant. Sibling of the peer
// `placement_without_clusters_ctor_matches_struct_literal_wrap`
// and `shard_key_on_non_sharded_ctor_matches_struct_literal_wrap`
// pins on the sibling per-`:placement` envelope, and sibling of
// the peer `contrato_member_missing_ctor_matches_struct_literal_wrap`
// pin on the sibling per-`:membros :caixa` envelope.
let entrada = Entrada {
host: "checkout.quero.cloud".into(),
para: "phantom-shim".into(),
paths: vec!["/api".into()],
port: 8080,
};
let via_ctor = AplicacaoError::entrada_member_missing(&entrada);
let via_literal = AplicacaoError::EntradaMemberMissing {
para: entrada.destination().to_string(),
};
assert_eq!(
via_ctor, via_literal,
"entrada_member_missing(&entrada) must byte-equal the open-coded \
EntradaMemberMissing struct-literal on the same &Entrada fixture"
);
assert_eq!(
via_ctor.to_string(),
via_literal.to_string(),
"Display byte-string must byte-equal the open-coded struct-literal"
);
}
#[test]
fn entrada_member_missing_ctor_routes_para_through_entrada_accessor() {
// Boundary-sweep pin on the ctor's substrate-primitive
// projection: the `para` slot is stored verbatim from
// [`Entrada::destination`] across a representative set of
// `:entrada :para` byte-strings, so any wrapper-side silent
// normalization, `.into()` divergence, accidental field
// rebrand, or per-arm ctor divergence on the sole-field
// projection surfaces at caixa-core build time rather than at
// a downstream diagnostic consumer that reads `err.para` back
// and gets a different value than the one it stored. Peer of
// the sibling
// `shard_key_on_non_sharded_routes_estrategia_through_placement_accessor`
// boundary-sweep pin on the sibling per-`:placement :shard-key`
// envelope and the peer `placement_without_clusters_ctor_routes_estrategia_through_accessor`
// sweep on the sibling per-`:placement` empty-clusters envelope
// — extended here onto the [`Entrada`]-borrow-projected sole
// `para` slot on the sibling per-`:entrada :para` envelope. The
// sweep list carries a mixed set (well-shaped phantom, hyphen-
// digit tail, single-character floor, and the digit-start form
// the peer `accepts_canonical_entrada_para_forms` positive-
// control test also sweeps) so a future silent per-input
// normalization surfaces on the arm that diverges.
for para in [
"phantom-shim",
"cart-v2",
"a",
"c0",
"3rd-party-shim",
"x-1-2-3-4",
] {
let entrada = Entrada {
host: "checkout.quero.cloud".into(),
para: para.into(),
paths: vec!["/api".into()],
port: 8080,
};
let err = AplicacaoError::entrada_member_missing(&entrada);
let AplicacaoError::EntradaMemberMissing { para: stored_para } = err else {
panic!("entrada_member_missing must construct EntradaMemberMissing for {para:?}");
};
assert_eq!(
stored_para,
entrada.destination(),
"para slot must round-trip verbatim through Entrada::destination() \
for {para:?}"
);
assert_eq!(
stored_para, para,
"para slot must byte-equal the fixture-declared value for {para:?}"
);
}
}
#[test]
fn validate_entrada_phantom_arm_routes_through_entrada_member_missing_ctor() {
// End-to-end pin: the sole in-crate wire-up site
// (`AplicacaoSpec::validate_entrada`'s membership-lookup arm)
// routes through [`AplicacaoError::entrada_member_missing`] and
// the observed `Err` byte-equals the ctor's output on the same
// well-shaped-phantom `:para` fixture. A future silent de-lift
// of the wire-up back to the open-coded struct-literal trips
// this test at caixa-core build time rather than at a
// downstream diagnostic consumer far from the wire-up commit.
// Sibling of the peer
// `validate_placement_non_sharded_arm_routes_through_shard_key_on_non_sharded_ctor`
// end-to-end pin on the sibling per-`:placement :shard-key`
// envelope, and sibling of the peer
// `entrada_para_well_shaped_phantom_still_raises_member_missing`
// pattern-match pin on the same wire-up — extended here from a
// `matches!` shape check to a byte-identity + Display parity
// route through the ctor.
let mut s = three_member_spec();
s.entrada.as_mut().unwrap().para = "phantom-shim".into();
let observed = s.validate().unwrap_err();
let expected = AplicacaoError::entrada_member_missing(s.entrada.as_ref().unwrap());
assert_eq!(
observed, expected,
"validate_entrada's phantom-reference-arm Err must byte-equal \
entrada_member_missing(&entrada)"
);
assert_eq!(
observed.to_string(),
expected.to_string(),
"Display byte-string parity"
);
}
#[test]
fn contrato_cycle_ctor_matches_struct_literal_wrap() {
// Equivalence pin: the ctor produces byte-equal
// `AplicacaoError::ContratoCycle` to the pre-lift open-coded
// struct-literal that stored the caller-side reconstructed
// cycle path verbatim at the gray-arm cycle-close return inside
// [`AplicacaoSpec::detect_sync_cycles`]. Guards any future
// field-addition / reordering / re-collect divergence on the
// variant. Sibling of the peer
// `entrada_member_missing_ctor_matches_struct_literal_wrap`
// (deeae5c) pin on the sibling per-`:entrada :para`
// phantom-reference envelope, and sibling of the peer
// `placement_without_clusters_ctor_matches_struct_literal_wrap`
// pin on the sibling per-`:placement` empty-clusters envelope.
let cycle = vec![
"cart".to_string(),
"catalog".to_string(),
"cart".to_string(),
];
let via_ctor = AplicacaoError::contrato_cycle(cycle.clone());
let via_literal = AplicacaoError::ContratoCycle {
cycle: cycle.clone(),
};
assert_eq!(
via_ctor, via_literal,
"contrato_cycle(cycle) must byte-equal the open-coded \
ContratoCycle struct-literal on the same Vec<String> fixture"
);
assert_eq!(
via_ctor.to_string(),
via_literal.to_string(),
"Display byte-string must byte-equal the open-coded struct-literal"
);
}
#[test]
fn contrato_cycle_ctor_routes_path_verbatim() {
// Boundary-sweep pin on the ctor's substrate-primitive
// pass-through: the `cycle` slot is stored verbatim across a
// representative set of reconstructed cycle paths (two-node
// closed loop; three-node loop; long chain with repeated
// interior nodes; a fixture whose first/last coincide by the
// gray-arm's own append-target-once-more discipline), so any
// wrapper-side silent normalization, dedup, sort, `.into()`
// divergence, accidental field rebrand, or re-collect on the
// sole-field pass-through surfaces at caixa-core build time
// rather than at a downstream diagnostic consumer that reads
// `err.cycle` back and gets a different value than the one it
// stored. Peer of the sibling
// `entrada_member_missing_ctor_routes_para_through_entrada_accessor`
// (deeae5c) boundary-sweep pin on the sibling per-`:entrada
// :para` envelope — extended here onto the owned-[`Vec<String>`]
// pass-through on the sibling per-`:contratos` cycle envelope.
for cycle in [
vec![
"cart".to_string(),
"catalog".to_string(),
"cart".to_string(),
],
vec![
"cart".to_string(),
"catalog".to_string(),
"payment".to_string(),
"cart".to_string(),
],
vec![
"a".to_string(),
"b".to_string(),
"c".to_string(),
"d".to_string(),
"b".to_string(),
],
vec!["only".to_string(), "only".to_string()],
] {
let err = AplicacaoError::contrato_cycle(cycle.clone());
let AplicacaoError::ContratoCycle { cycle: stored } = err else {
panic!("contrato_cycle must construct ContratoCycle for {cycle:?}");
};
assert_eq!(
stored, cycle,
"cycle slot must round-trip the caller-side Vec<String> verbatim \
for {cycle:?}"
);
}
}
#[test]
fn detect_sync_cycles_arm_routes_through_contrato_cycle_ctor() {
// End-to-end pin: the sole in-crate wire-up site
// (`AplicacaoSpec::detect_sync_cycles`'s gray-arm cycle-close
// return) routes through [`AplicacaoError::contrato_cycle`] and
// the observed `Err` byte-equals the ctor's output on the same
// reconstructed cycle path. A future silent de-lift of the
// wire-up back to the open-coded `AplicacaoError::ContratoCycle
// { cycle }` struct-literal trips this test at caixa-core build
// time rather than at a downstream diagnostic consumer far from
// the wire-up commit. Sibling of the peer
// `validate_entrada_phantom_arm_routes_through_entrada_member_missing_ctor`
// (deeae5c) end-to-end pin on the sibling per-`:entrada :para`
// envelope, and sibling of the peer
// `validate_placement_non_sharded_arm_routes_through_shard_key_on_non_sharded_ctor`
// (14bafca) end-to-end pin on the sibling per-`:placement
// :shard-key` envelope — extended here from a bare
// `matches!(err, AplicacaoError::ContratoCycle { .. })` shape
// check to a byte-identity route through the ctor.
let mut s = three_member_spec();
// Reset to a clean 3-cycle: catalog → cart → payment → catalog
s.contratos = vec![
contract_http("catalog", "cart", "/x"),
contract_http("cart", "payment", "/y"),
contract_http("payment", "catalog", "/z"),
];
let observed = s.validate().unwrap_err();
let AplicacaoError::ContratoCycle { ref cycle } = observed else {
panic!("expected ContratoCycle from the sync-cycle detector, got {observed:?}");
};
let expected = AplicacaoError::contrato_cycle(cycle.clone());
assert_eq!(
observed, expected,
"detect_sync_cycles's gray-arm Err must byte-equal \
contrato_cycle(cycle) on the reconstructed cycle path"
);
assert_eq!(
observed.to_string(),
expected.to_string(),
"Display byte-string parity"
);
}
// ── policy_breaker_window_below_timeout standalone ctor pins ────────
//
// Fail-before-pass-after pins for the standalone
// [`AplicacaoError::policy_breaker_window_below_timeout`] inherent
// ctor (see the paired doc-block above the ctor definition) — the
// fold of the last open-coded two-slot `{ window: cb.window(),
// timeout: t }` struct-literal inside
// [`MeshPolicy::first_cross_axis_violation`]'s window-below-timeout
// arm onto one substrate primitive on the [`AplicacaoError`]
// envelope, projecting through the [`CircuitBreaker::window`] scalar
// accessor on the substrate primitive. A byte-mismatched ctor body
// would trip the equivalence pin first, ahead of any downstream
// diagnostic-shape drift.
//
// Peer of the sibling standalone-ctor equivalence pins on the peer
// per-envelope substrate-primitive-projection ctors across
// caixa-core: `contrato_self_loop_ctor_matches_struct_literal_wrap`
// (b30edfe) on the sibling `{ caixa: String, wit: String }` two-slot
// per-`:contratos` self-edge envelope,
// `entrada_member_missing_ctor_matches_struct_literal_wrap` (deeae5c)
// on the sibling `{ para: String }` one-slot per-`:entrada :para`
// phantom-reference envelope, and
// `shard_key_on_non_sharded_ctor_matches_struct_literal_wrap`
// (14bafca) on the sibling `{ estrategia, shard_key }` two-slot
// per-`:placement :shard-key` envelope.
#[test]
fn policy_breaker_window_below_timeout_ctor_matches_struct_literal_wrap() {
// Equivalence pin: the ctor produces byte-equal
// `AplicacaoError::PolicyBreakerWindowBelowTimeout` to the pre-
// lift open-coded struct-literal that read the same two fields
// through [`CircuitBreaker::window`] and the paired
// `:politicas :timeout` destructure. Guards any future
// field-addition / reordering / accessor-swap tweak on the
// variant. Same equivalence-pin shape as the sibling
// `contrato_self_loop_ctor_matches_struct_literal_wrap`
// (b30edfe) on the sibling per-`:contratos` self-edge envelope.
let cb = CircuitBreaker {
max_failures: 5,
window: Duration::from_secs(10),
};
let timeout = Duration::from_secs(30);
let via_ctor = AplicacaoError::policy_breaker_window_below_timeout(&cb, timeout);
let via_literal = AplicacaoError::PolicyBreakerWindowBelowTimeout {
window: cb.window(),
timeout,
};
assert_eq!(
via_ctor, via_literal,
"policy_breaker_window_below_timeout(&cb, t) must byte-equal \
the open-coded PolicyBreakerWindowBelowTimeout struct-literal \
on the same Copy-Duration fixture"
);
assert_eq!(
via_ctor.to_string(),
via_literal.to_string(),
"Display byte-string must byte-equal the open-coded struct-literal"
);
}
#[test]
fn policy_breaker_window_below_timeout_ctor_routes_cb_window_and_timeout_verbatim() {
// Routing pin sweeping non-default `:circuit-breaker :window`
// and `:timeout` pairs (below-boundary window / above-boundary
// window; sub-second window / multi-minute timeout;
// millisecond-precision fixture) through the paired
// [`CircuitBreaker::window`] accessor and the direct `timeout`
// parameter, so any wrapper-side silent normalization,
// rounding, argument re-order, or accidental slot rebrand on
// the two-slot pass-through surfaces at caixa-core build time
// rather than at a downstream diagnostic consumer that reads
// the two [`Duration`]s back and gets different values than
// the ones it stored.
//
// Deliberately routes through a fixture whose `cb.window` and
// `timeout` are distinct — a silent accessor swap
// (`cb.max_failures` casting to `Duration` would fail to
// compile; a hypothetical field-rename swap swapping the two
// slots at the ctor body would land `timeout` in the `window`
// slot instead of `cb.window()` and vice-versa, tripping the
// per-field assertion here). Peer of the sibling
// `contrato_self_loop_ctor_routes_source_and_world_ref_through_verbatim`
// (b30edfe) routing pin on the sibling two-slot per-`:contratos`
// envelope.
for (max_failures, window, timeout) in [
(5_u32, Duration::from_secs(10), Duration::from_secs(30)),
(
1_u32,
Duration::from_millis(29_999),
Duration::from_secs(30),
),
(42_u32, Duration::from_millis(500), Duration::from_secs(120)),
(7_u32, Duration::from_secs(1), Duration::from_secs(60)),
] {
let cb = CircuitBreaker {
max_failures,
window,
};
let built = AplicacaoError::policy_breaker_window_below_timeout(&cb, timeout);
let AplicacaoError::PolicyBreakerWindowBelowTimeout {
window: stored_window,
timeout: stored_timeout,
} = built
else {
panic!(
"policy_breaker_window_below_timeout must construct \
PolicyBreakerWindowBelowTimeout for cb={cb:?}/timeout={timeout:?}"
);
};
assert_eq!(
stored_window, window,
"window slot must thread CircuitBreaker::window() verbatim \
for cb={cb:?}/timeout={timeout:?}"
);
assert_eq!(
stored_timeout, timeout,
"timeout slot must thread the caller-side :timeout scalar verbatim \
for cb={cb:?}/timeout={timeout:?}"
);
}
}
#[test]
fn first_cross_axis_violation_arm_routes_through_policy_breaker_window_below_timeout_ctor() {
// End-to-end pin: the sole in-crate wire-up site
// ([`MeshPolicy::first_cross_axis_violation`]'s
// window-below-timeout arm) routes through
// [`AplicacaoError::policy_breaker_window_below_timeout`] and
// the observed `Err` byte-equals the ctor's output on the same
// sub-boundary `(:window, :timeout)` fixture. A future silent
// de-lift of the wire-up back to the open-coded
// `AplicacaoError::PolicyBreakerWindowBelowTimeout { window,
// timeout }` struct-literal trips this test at caixa-core build
// time rather than at a downstream diagnostic consumer far from
// the wire-up commit. Sibling of the peer
// `detect_sync_cycles_arm_routes_through_contrato_cycle_ctor`
// (5cfcab8) end-to-end pin on the sibling per-`:contratos`
// cross-edge cycle envelope,
// `validate_entrada_phantom_arm_routes_through_entrada_member_missing_ctor`
// (deeae5c) on the sibling per-`:entrada :para` phantom-
// reference envelope, and
// `validate_placement_non_sharded_arm_routes_through_shard_key_on_non_sharded_ctor`
// (14bafca) on the sibling per-`:placement :shard-key`
// envelope — extended here from a bare `matches!(err,
// AplicacaoError::PolicyBreakerWindowBelowTimeout { .. })`
// shape check to a byte-identity route through the ctor.
let mut s = three_member_spec();
s.politicas.timeout = Some(Duration::from_secs(30));
s.politicas.circuit_breaker = Some(CircuitBreaker {
max_failures: 5,
window: Duration::from_secs(10),
});
let observed = s.validate().unwrap_err();
let cb = s.politicas.circuit_breaker.unwrap();
let timeout = s.politicas.timeout.unwrap();
let expected = AplicacaoError::policy_breaker_window_below_timeout(&cb, timeout);
assert_eq!(
observed, expected,
"MeshPolicy::first_cross_axis_violation's window-below-timeout \
arm's Err must byte-equal policy_breaker_window_below_timeout(&cb, t)"
);
assert_eq!(
observed.to_string(),
expected.to_string(),
"Display byte-string parity"
);
}
#[test]
fn policy_breaker_cannot_trip_under_rate_limit_ctor_matches_struct_literal_wrap() {
// Equivalence pin: the ctor produces byte-equal
// `AplicacaoError::PolicyBreakerCannotTripUnderRateLimit` to the
// pre-lift open-coded struct-literal that read the same four fields
// through [`RateLimit::rate`], [`RateLimit::window`],
// [`CircuitBreaker::max_failures`], and [`CircuitBreaker::window`].
// Guards any future field-addition / reordering / accessor-swap
// tweak on the variant. Same equivalence-pin shape as the sibling
// `policy_breaker_window_below_timeout_ctor_matches_struct_literal_wrap`
// (9b30c07) on the sibling per-`(:timeout, :circuit-breaker)`
// cross-axis envelope.
let rl = RateLimit {
rate: 1,
window: Duration::from_secs(3600),
};
let cb = CircuitBreaker {
max_failures: 5,
window: Duration::from_secs(10),
};
let via_ctor = AplicacaoError::policy_breaker_cannot_trip_under_rate_limit(&rl, &cb);
let via_literal = AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
rate: rl.rate(),
rl_window: rl.window(),
max_failures: cb.max_failures(),
cb_window: cb.window(),
};
assert_eq!(
via_ctor, via_literal,
"policy_breaker_cannot_trip_under_rate_limit(&rl, &cb) must \
byte-equal the open-coded PolicyBreakerCannotTripUnderRateLimit \
struct-literal on the same Copy-(u32|Duration) fixture"
);
assert_eq!(
via_ctor.to_string(),
via_literal.to_string(),
"Display byte-string must byte-equal the open-coded struct-literal"
);
}
#[test]
fn policy_breaker_cannot_trip_under_rate_limit_ctor_routes_rl_and_cb_verbatim() {
// Routing pin sweeping non-default `(:rate, :rate-limit :window,
// :max-failures, :circuit-breaker :window)` tuples across the
// production-playbook starve band — Envoy 5-in-10s vs 1/hour,
// sub-second breaker window, multi-minute rate-limit window,
// multi-tenant per-cluster ratio — through the paired
// [`RateLimit::rate`] / [`RateLimit::window`] /
// [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
// accessors, so any wrapper-side silent normalization, rounding,
// argument re-order, or accidental slot rebrand on the four-slot
// pass-through surfaces at caixa-core build time rather than at a
// downstream diagnostic consumer that reads the four scalars back
// and gets different values than the ones it stored.
//
// Deliberately routes through fixtures whose four scalars are
// pairwise distinct (`rate ≠ max_failures`, `rl_window ≠
// cb_window`) — a hypothetical field-rename swap swapping any
// two adjacent slots at the ctor body would land the value from
// the wrong axis, tripping the per-field assertion here. Peer of
// the sibling
// `policy_breaker_window_below_timeout_ctor_routes_cb_window_and_timeout_verbatim`
// (9b30c07) routing pin on the sibling two-slot per-`(:timeout,
// :circuit-breaker)` cross-axis envelope.
for (rate, rl_window, max_failures, cb_window) in [
(
1_u32,
Duration::from_secs(3600),
5_u32,
Duration::from_secs(10),
),
(4_u32, Duration::from_secs(1), 5_u32, Duration::from_secs(1)),
(
2_u32,
Duration::from_millis(500),
10_u32,
Duration::from_secs(300),
),
(
7_u32,
Duration::from_secs(120),
42_u32,
Duration::from_millis(750),
),
] {
let rl = RateLimit {
rate,
window: rl_window,
};
let cb = CircuitBreaker {
max_failures,
window: cb_window,
};
let built = AplicacaoError::policy_breaker_cannot_trip_under_rate_limit(&rl, &cb);
let AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
rate: stored_rate,
rl_window: stored_rl_window,
max_failures: stored_max_failures,
cb_window: stored_cb_window,
} = built
else {
panic!(
"policy_breaker_cannot_trip_under_rate_limit must \
construct PolicyBreakerCannotTripUnderRateLimit for \
rl={rl:?}/cb={cb:?}"
);
};
assert_eq!(
stored_rate, rate,
"rate slot must thread RateLimit::rate() verbatim for \
rl={rl:?}/cb={cb:?}"
);
assert_eq!(
stored_rl_window, rl_window,
"rl_window slot must thread RateLimit::window() verbatim \
for rl={rl:?}/cb={cb:?}"
);
assert_eq!(
stored_max_failures, max_failures,
"max_failures slot must thread CircuitBreaker::max_failures() \
verbatim for rl={rl:?}/cb={cb:?}"
);
assert_eq!(
stored_cb_window, cb_window,
"cb_window slot must thread CircuitBreaker::window() verbatim \
for rl={rl:?}/cb={cb:?}"
);
}
}
#[test]
fn first_cross_axis_violation_arm_routes_through_policy_breaker_cannot_trip_under_rate_limit_ctor()
{
// End-to-end pin: the sole in-crate wire-up site
// ([`MeshPolicy::first_cross_axis_violation`]'s
// starve-under-rate-limit arm) routes through
// [`AplicacaoError::policy_breaker_cannot_trip_under_rate_limit`]
// and the observed `Err` byte-equals the ctor's output on the same
// token-bucket-starves-breaker fixture. A future silent de-lift of
// the wire-up back to the open-coded
// `AplicacaoError::PolicyBreakerCannotTripUnderRateLimit { rate,
// rl_window, max_failures, cb_window }` struct-literal trips this
// test at caixa-core build time rather than at a downstream
// diagnostic consumer far from the wire-up commit. Sibling of the
// peer
// `first_cross_axis_violation_arm_routes_through_policy_breaker_window_below_timeout_ctor`
// (9b30c07) end-to-end pin on the sibling per-`(:timeout,
// :circuit-breaker)` cross-axis envelope — extended here from a
// bare `matches!(err,
// AplicacaoError::PolicyBreakerCannotTripUnderRateLimit { .. })`
// shape check to a byte-identity route through the ctor. Clears
// `:timeout` so the sibling window-below-timeout arm does not
// fire first on the ordering-precedent it holds over this arm.
let mut s = three_member_spec();
s.politicas.timeout = None;
s.politicas.circuit_breaker = Some(CircuitBreaker {
max_failures: 5,
window: Duration::from_secs(10),
});
s.politicas.rate_limit = Some(RateLimit {
rate: 1,
window: Duration::from_secs(3600),
});
let observed = s.validate().unwrap_err();
let rl = s.politicas.rate_limit.unwrap();
let cb = s.politicas.circuit_breaker.unwrap();
let expected = AplicacaoError::policy_breaker_cannot_trip_under_rate_limit(&rl, &cb);
assert_eq!(
observed, expected,
"MeshPolicy::first_cross_axis_violation's starve-under-rate-limit \
arm's Err must byte-equal \
policy_breaker_cannot_trip_under_rate_limit(&rl, &cb)"
);
assert_eq!(
observed.to_string(),
expected.to_string(),
"Display byte-string parity"
);
}
#[test]
fn policy_breaker_trips_before_retries_exhausted_ctor_matches_struct_literal_wrap() {
// Equivalence pin: the ctor produces byte-equal
// `AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted` to the
// pre-lift open-coded struct-literal that read the same two fields
// through the bare `retries` destructure and
// [`CircuitBreaker::max_failures`]. Guards any future field-addition
// / reordering / accessor-swap tweak on the variant. Same
// equivalence-pin shape as the sibling
// `policy_breaker_cannot_trip_under_rate_limit_ctor_matches_struct_literal_wrap`
// (6bb4e46) on the sibling per-`(:rate-limit, :circuit-breaker)`
// second cross-axis envelope and
// `policy_breaker_window_below_timeout_ctor_matches_struct_literal_wrap`
// (9b30c07) on the sibling per-`(:timeout, :circuit-breaker)` first
// cross-axis envelope.
let retries = 5_u32;
let cb = CircuitBreaker {
max_failures: 3,
window: Duration::from_secs(60),
};
let via_ctor = AplicacaoError::policy_breaker_trips_before_retries_exhausted(retries, &cb);
let via_literal = AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
retries,
max_failures: cb.max_failures(),
};
assert_eq!(
via_ctor, via_literal,
"policy_breaker_trips_before_retries_exhausted(retries, &cb) must \
byte-equal the open-coded PolicyBreakerTripsBeforeRetriesExhausted \
struct-literal on the same Copy-u32 fixture"
);
assert_eq!(
via_ctor.to_string(),
via_literal.to_string(),
"Display byte-string must byte-equal the open-coded struct-literal"
);
}
#[test]
fn policy_breaker_trips_before_retries_exhausted_ctor_routes_retries_and_cb_verbatim() {
// Routing pin sweeping non-default `(retries, max_failures)` tuples
// across the production-playbook retries-saturate band — Envoy 5
// retries vs 3 max-failures, boundary retries==max_failures pair (a
// rejecting arm on the strict-inequality invariant), multi-tenant
// high-retries-vs-low-trip ratio, sub-cap high-max-failures ceiling —
// through the paired bare-`retries` destructure and
// [`CircuitBreaker::max_failures`] accessor, so any wrapper-side
// silent normalization, rounding, argument re-order, or accidental
// slot rebrand on the two-slot pass-through surfaces at caixa-core
// build time rather than at a downstream diagnostic consumer that
// reads the two scalars back and gets different values than the ones
// it stored.
//
// Deliberately routes through fixtures whose two scalars are
// pairwise distinct (`retries ≠ max_failures` on every non-boundary
// arm) — a hypothetical field-rename swap swapping the two slots at
// the ctor body would land the value from the wrong axis, tripping
// the per-field assertion here. Peer of the sibling
// `policy_breaker_cannot_trip_under_rate_limit_ctor_routes_rl_and_cb_verbatim`
// (6bb4e46) routing pin on the sibling four-slot per-`(:rate-limit,
// :circuit-breaker)` second cross-axis envelope.
for (retries, max_failures) in [
(5_u32, 3_u32),
(3_u32, 3_u32),
(100_u32, 1_u32),
(7_u32, 42_u32),
] {
let cb = CircuitBreaker {
max_failures,
window: Duration::from_secs(60),
};
let built = AplicacaoError::policy_breaker_trips_before_retries_exhausted(retries, &cb);
let AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
retries: stored_retries,
max_failures: stored_max_failures,
} = built
else {
panic!(
"policy_breaker_trips_before_retries_exhausted must \
construct PolicyBreakerTripsBeforeRetriesExhausted for \
retries={retries}/cb={cb:?}"
);
};
assert_eq!(
stored_retries, retries,
"retries slot must thread the bare-`retries` destructure \
verbatim for retries={retries}/cb={cb:?}"
);
assert_eq!(
stored_max_failures, max_failures,
"max_failures slot must thread CircuitBreaker::max_failures() \
verbatim for retries={retries}/cb={cb:?}"
);
}
}
#[test]
fn first_cross_axis_violation_arm_routes_through_policy_breaker_trips_before_retries_exhausted_ctor()
{
// End-to-end pin: the sole in-crate wire-up site
// ([`MeshPolicy::first_cross_axis_violation`]'s retries-saturate
// arm) routes through
// [`AplicacaoError::policy_breaker_trips_before_retries_exhausted`]
// and the observed `Err` byte-equals the ctor's output on the same
// retries-saturate fixture. A future silent de-lift of the wire-up
// back to the open-coded
// `AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted { retries,
// max_failures }` struct-literal trips this test at caixa-core build
// time rather than at a downstream diagnostic consumer far from the
// wire-up commit. Sibling of the peer
// `first_cross_axis_violation_arm_routes_through_policy_breaker_cannot_trip_under_rate_limit_ctor`
// (6bb4e46) end-to-end pin on the sibling per-`(:rate-limit,
// :circuit-breaker)` second cross-axis envelope — extended here from
// a bare `matches!(err,
// AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted { .. })`
// shape check to a byte-identity route through the ctor. Clears
// `:timeout` and `:rate-limit` so the sibling window-below-timeout
// and starve-under-rate-limit arms do not fire first on the
// ordering-precedent they hold over this arm.
let mut s = three_member_spec();
s.politicas.timeout = None;
s.politicas.rate_limit = None;
s.politicas.retries = Some(5);
s.politicas.circuit_breaker = Some(CircuitBreaker {
max_failures: 3,
window: Duration::from_secs(60),
});
let observed = s.validate().unwrap_err();
let retries = s.politicas.retries.unwrap();
let cb = s.politicas.circuit_breaker.unwrap();
let expected = AplicacaoError::policy_breaker_trips_before_retries_exhausted(retries, &cb);
assert_eq!(
observed, expected,
"MeshPolicy::first_cross_axis_violation's retries-saturate arm's \
Err must byte-equal \
policy_breaker_trips_before_retries_exhausted(retries, &cb)"
);
assert_eq!(
observed.to_string(),
expected.to_string(),
"Display byte-string parity"
);
}
#[test]
fn policy_rate_limit_cannot_admit_retry_burst_ctor_matches_struct_literal_wrap() {
// Equivalence pin: the ctor produces byte-equal
// `AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst` to the
// pre-lift open-coded struct-literal that read the same two fields
// through the bare `retries` destructure and [`RateLimit::rate`].
// Guards any future field-addition / reordering / accessor-swap
// tweak on the variant. Same equivalence-pin shape as the sibling
// `policy_breaker_trips_before_retries_exhausted_ctor_matches_struct_literal_wrap`
// (f54c539) on the sibling per-`(:retries, :circuit-breaker)`
// third cross-axis envelope,
// `policy_breaker_cannot_trip_under_rate_limit_ctor_matches_struct_literal_wrap`
// (6bb4e46) on the sibling per-`(:rate-limit, :circuit-breaker)`
// second cross-axis envelope, and
// `policy_breaker_window_below_timeout_ctor_matches_struct_literal_wrap`
// (9b30c07) on the sibling per-`(:timeout, :circuit-breaker)`
// first cross-axis envelope.
let retries = 3_u32;
let rl = RateLimit {
rate: 3,
window: Duration::from_secs(1),
};
let via_ctor = AplicacaoError::policy_rate_limit_cannot_admit_retry_burst(retries, &rl);
let via_literal = AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
retries,
rate: rl.rate(),
};
assert_eq!(
via_ctor, via_literal,
"policy_rate_limit_cannot_admit_retry_burst(retries, &rl) must \
byte-equal the open-coded PolicyRateLimitCannotAdmitRetryBurst \
struct-literal on the same Copy-u32 fixture"
);
assert_eq!(
via_ctor.to_string(),
via_literal.to_string(),
"Display byte-string must byte-equal the open-coded struct-literal"
);
}
#[test]
fn policy_rate_limit_cannot_admit_retry_burst_ctor_routes_retries_and_rl_verbatim() {
// Routing pin sweeping non-default `(retries, rate)` tuples across
// the production-playbook rate-limit-starve band — boundary
// `retries==rate` (a rejecting arm on the `>=` invariant stated as
// `rate >= retries + 1`), one-below-boundary pair, multi-tenant
// high-retries-vs-low-rate ratio, and sub-cap high-rate ceiling —
// through the paired bare-`retries` destructure and
// [`RateLimit::rate`] accessor, so any wrapper-side silent
// normalization, rounding, argument re-order, or accidental slot
// rebrand on the two-slot pass-through surfaces at caixa-core
// build time rather than at a downstream diagnostic consumer that
// reads the two scalars back and gets different values than the
// ones it stored.
//
// Deliberately routes through fixtures whose two scalars are
// pairwise distinct on every non-boundary arm — a hypothetical
// field-rename swap swapping the two slots at the ctor body would
// land the value from the wrong axis, tripping the per-field
// assertion here. Peer of the sibling
// `policy_breaker_trips_before_retries_exhausted_ctor_routes_retries_and_cb_verbatim`
// (f54c539) routing pin on the sibling two-slot per-`(:retries,
// :circuit-breaker)` third cross-axis envelope.
for (retries, rate) in [
(3_u32, 3_u32),
(5_u32, 4_u32),
(100_u32, 50_u32),
(2_u32, POLICY_RATE_LIMIT_MAX),
] {
let rl = RateLimit {
rate,
window: Duration::from_secs(1),
};
let built = AplicacaoError::policy_rate_limit_cannot_admit_retry_burst(retries, &rl);
let AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
retries: stored_retries,
rate: stored_rate,
} = built
else {
panic!(
"policy_rate_limit_cannot_admit_retry_burst must \
construct PolicyRateLimitCannotAdmitRetryBurst for \
retries={retries}/rl={rl:?}"
);
};
assert_eq!(
stored_retries, retries,
"retries slot must thread the bare-`retries` destructure \
verbatim for retries={retries}/rl={rl:?}"
);
assert_eq!(
stored_rate, rate,
"rate slot must thread RateLimit::rate() verbatim for \
retries={retries}/rl={rl:?}"
);
}
}
#[test]
fn first_cross_axis_violation_arm_routes_through_policy_rate_limit_cannot_admit_retry_burst_ctor()
{
// End-to-end pin: the sole in-crate wire-up site
// ([`MeshPolicy::first_cross_axis_violation`]'s starve-under-rate-
// limit arm) routes through
// [`AplicacaoError::policy_rate_limit_cannot_admit_retry_burst`]
// and the observed `Err` byte-equals the ctor's output on the same
// rate-limit-starve fixture. A future silent de-lift of the
// wire-up back to the open-coded
// `AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst { retries,
// rate }` struct-literal trips this test at caixa-core build time
// rather than at a downstream diagnostic consumer far from the
// wire-up commit. Sibling of the peer
// `first_cross_axis_violation_arm_routes_through_policy_breaker_trips_before_retries_exhausted_ctor`
// (f54c539) end-to-end pin on the sibling per-`(:retries,
// :circuit-breaker)` third cross-axis envelope. Clears `:timeout`
// and `:circuit-breaker` so the sibling window-below-timeout /
// starve-under-rate-limit / trips-before-retries-exhausted arms
// do not fire first on the ordering-precedent they hold over this
// arm.
let mut s = three_member_spec();
s.politicas.timeout = None;
s.politicas.circuit_breaker = None;
s.politicas.retries = Some(5);
s.politicas.rate_limit = Some(RateLimit {
rate: 3,
window: Duration::from_secs(1),
});
let observed = s.validate().unwrap_err();
let retries = s.politicas.retries.unwrap();
let rl = s.politicas.rate_limit.unwrap();
let expected = AplicacaoError::policy_rate_limit_cannot_admit_retry_burst(retries, &rl);
assert_eq!(
observed, expected,
"MeshPolicy::first_cross_axis_violation's starve-under-rate-limit arm's \
Err must byte-equal \
policy_rate_limit_cannot_admit_retry_burst(retries, &rl)"
);
assert_eq!(
observed.to_string(),
expected.to_string(),
"Display byte-string parity"
);
}
}