tatara_process/tagged_union.rs
1//! `tagged_union::resolve` — the typescape's "exactly-one-Option" pattern,
2//! lifted to one source of truth.
3//!
4//! Several CRD-facing types in this crate ([`crate::intent::Intent`],
5//! [`crate::lifetime::Lifetime`], [`crate::export::ArtifactSource`],
6//! [`crate::export::VectorChannel`], [`crate::encapsulates::EncapsulationKind`])
7//! carry `N` `Option<T>` fields where exactly one is expected to be
8//! populated on the wire. Each previously hand-rolled the same
9//! `count() + if-let-chain + unreachable!()` body — four parallel tables
10//! (the struct fields, an `is_some()` count array, an `if-let-else`
11//! resolution chain, and any sibling projection like `IntentVariant::kind`)
12//! kept coherent only by code review. The `unreachable!()` arm at the
13//! bottom of every chain was a sentinel that fires at runtime if the
14//! parallel tables ever drift.
15//!
16//! This module collapses the resolver to ONE typed sweep over an
17//! `IntoIterator<Item = Option<V>>` of candidate variant projections.
18//! Adding a new tagged-union variant is now ONE additional line at the
19//! callsite — no `unreachable!()` arm to update, no parallel `is_some()`
20//! count array to extend.
21
22/// Outcome of [`resolve`] when the candidate list isn't exactly-one.
23#[derive(Clone, Copy, Debug, PartialEq, Eq)]
24pub enum ResolveError {
25 /// No candidate was populated.
26 None,
27 /// More than one candidate was populated.
28 Many,
29}
30
31/// Resolve at most one populated variant from a candidate list.
32///
33/// Each item in `candidates` is the projected borrowed-variant view for
34/// the corresponding `Option<T>` field — `None` when the field is unset,
35/// `Some(V::Variant(...))` when set.
36///
37/// Returns the single populated variant, [`ResolveError::None`] when
38/// none are populated, or [`ResolveError::Many`] when more than one are.
39///
40/// The body is one short-circuiting sweep — `Many` is returned as soon
41/// as the second populated entry is seen, without scanning the rest.
42pub fn resolve<V>(candidates: impl IntoIterator<Item = Option<V>>) -> Result<V, ResolveError> {
43 let mut found: Option<V> = None;
44 for candidate in candidates {
45 if candidate.is_some() {
46 if found.is_some() {
47 return Err(ResolveError::Many);
48 }
49 found = candidate;
50 }
51 }
52 found.ok_or(ResolveError::None)
53}
54
55/// Sibling error carriers on tagged-union `.variant()` sites all
56/// project the two [`ResolveError`] arms onto the SAME closed-set
57/// diagnostic shape — `Empty(&'static str)` for "no variant set"
58/// (carrying the closed-set kind list so the operator diagnostic
59/// names every candidate) and a payload-free `Ambiguous` for
60/// "multiple variants set". This trait names that shared shape as
61/// ONE typed contract; [`resolve_or_err`] then composes [`resolve`]
62/// with the trait so each per-carrier `.map_err(|e| match e { ... })`
63/// site collapses to a one-line typed dispatch.
64///
65/// Impls live at each error carrier's own module so the (diagnostic
66/// message, closed-set list) pair stays owned by the carrier that
67/// publishes it — the trait is the projection, not the message.
68pub trait TaggedUnionError: Sized {
69 /// Construct the "no variant set" arm with the closed-set kind
70 /// list slash-joined into the diagnostic payload.
71 fn empty(kinds: &'static str) -> Self;
72 /// Construct the "multiple variants set" arm.
73 fn ambiguous() -> Self;
74}
75
76/// Resolve at most one populated variant, mapping the two
77/// [`ResolveError`] arms onto the caller's typed carrier via
78/// [`TaggedUnionError`]. The compound-lift primitive: sweep +
79/// short-circuit + typed-error dispatch as ONE call.
80///
81/// Substrate primitive for the four sibling `Xxx::variant()` sites
82/// on `ProcessSpec` (`Intent::variant`,
83/// `EncapsulationKind::variant`, `ArtifactSource::variant`,
84/// `VectorChannel::variant`) that previously restated the SAME
85/// `.map_err(|e| match e { None => Empty(LIST), Many => Ambiguous })`
86/// two-arm dispatch at each call site — every one of them a
87/// byte-identical restatement of the (empty→list, many→ambiguous)
88/// projection whose payload identity is strictly the carrier's own
89/// diagnostic. A fifth sibling error carrier picks up the projection
90/// through ONE `impl TaggedUnionError` block + ONE `resolve_or_err`
91/// call site.
92///
93/// The [`Lifetime::variant`](crate::lifetime::Lifetime::variant)
94/// site is DELIBERATELY not routed through this primitive — its
95/// `ResolveError::None` arm resolves to a `Permanent` default
96/// variant, not to an `Empty` typed error, so the projection shape
97/// diverges at the None arm.
98pub fn resolve_or_err<V, E: TaggedUnionError>(
99 candidates: impl IntoIterator<Item = Option<V>>,
100 kinds: &'static str,
101) -> Result<V, E> {
102 resolve(candidates).map_err(|e| match e {
103 ResolveError::None => E::empty(kinds),
104 ResolveError::Many => E::ambiguous(),
105 })
106}
107
108/// Declare a sibling error carrier for a tagged-union `.variant()`
109/// site — the enum + [`TaggedUnionError`] impl in ONE authoring
110/// surface.
111///
112/// Every one of the four production `.variant()` sites on
113/// `ProcessSpec` ([`crate::intent::Intent`],
114/// [`crate::encapsulates::EncapsulationKind`],
115/// [`crate::export::ArtifactSource`],
116/// [`crate::export::VectorChannel`]) pre-lift restated the same
117/// four-piece authoring shape by hand:
118///
119/// 1. `#[derive(Clone, Copy, Debug, thiserror::Error, PartialEq,
120/// Eq)]` on the carrier — byte-identical across all four.
121/// 2. A two-variant enum body (`Empty(&'static str)`, `Ambiguous`)
122/// — structurally identical.
123/// 3. Two `#[error(...)]` messages whose only per-carrier knob is a
124/// noun-prefix (`"intent"`, `"encapsulation kind"`, ...) — every
125/// other byte of the (`"has no variant set (one of {0}
126/// required)"`, `"has multiple variants set; exactly one
127/// required"`) tails was verbatim.
128/// 4. A six-line `impl TaggedUnionError` whose two constructor
129/// bodies re-projected `Self::Empty(kinds)` / `Self::Ambiguous`
130/// onto each carrier's own typed variants.
131///
132/// The macro collapses (1) + (2) + (4) onto ONE call and takes the
133/// two per-carrier operator-facing diagnostic literals as named
134/// arguments so (3) stays visible at the callsite without re-authoring
135/// the shared derive set or trait impl. A fifth sibling carrier
136/// lands as ONE `declare_tagged_union_error!` invocation — no
137/// re-authored `#[derive(...)]`, no re-authored two-variant enum
138/// body, no re-authored `impl TaggedUnionError` block.
139///
140/// Emitted derives include `Copy` — the `Empty` arm carries only
141/// a `&'static str` and the `Ambiguous` arm is payload-free, so
142/// the carrier is always `Copy` regardless of caller.
143///
144/// # Example
145///
146/// ```ignore
147/// declare_tagged_union_error! {
148/// pub IntentError,
149/// empty = "intent has no variant set (one of {0} required)",
150/// ambiguous = "intent has multiple variants set; exactly one required",
151/// }
152/// ```
153///
154/// Expands to the enum + [`TaggedUnionError`] impl for
155/// `IntentError`; the `Empty` arm carries the caller's closed-set
156/// kind-list literal.
157#[macro_export]
158macro_rules! declare_tagged_union_error {
159 (
160 $(#[$attr:meta])*
161 $vis:vis $name:ident,
162 empty = $empty:literal,
163 ambiguous = $ambiguous:literal $(,)?
164 ) => {
165 $(#[$attr])*
166 #[derive(
167 ::std::clone::Clone,
168 ::std::marker::Copy,
169 ::std::fmt::Debug,
170 ::thiserror::Error,
171 ::std::cmp::PartialEq,
172 ::std::cmp::Eq,
173 )]
174 $vis enum $name {
175 #[error($empty)]
176 Empty(&'static str),
177 #[error($ambiguous)]
178 Ambiguous,
179 }
180
181 impl $crate::tagged_union::TaggedUnionError for $name {
182 fn empty(kinds: &'static str) -> Self {
183 Self::Empty(kinds)
184 }
185 fn ambiguous() -> Self {
186 Self::Ambiguous
187 }
188 }
189 };
190}
191
192/// Declare the three-block impl stanza a tagged-union parent type
193/// publishes to the substrate — inherent `.variant()` forwarder +
194/// [`VariantSelector<Parent>`] impl on the sibling `Kind` +
195/// [`TaggedUnion`] impl on the parent — in ONE authoring surface.
196///
197/// Every one of the four production `.variant()` sites on
198/// `ProcessSpec` ([`crate::intent::Intent`],
199/// [`crate::encapsulates::EncapsulationKind`],
200/// [`crate::export::ArtifactSource`],
201/// [`crate::export::VectorChannel`]) pre-lift restated the same three
202/// impl blocks by hand:
203///
204/// 1. `impl $parent { pub fn variant(&self) -> Result<$variant<'_>, $err> { ... } }`
205/// — a one-line delegation to the [`TaggedUnion::variant`] default
206/// body, plus 5 lines of rustdoc cross-referencing the other three
207/// sibling `.variant()` sites verbatim.
208/// 2. `impl VariantSelector<$parent> for $kind { type Variant<'a> = $variant<'a>; fn select(...) { <$kind>::select(self, parent) } }`
209/// — 6 lines whose only per-site knobs are (`$parent`, `$kind`,
210/// `$variant`); the trait method body a straight delegation to the
211/// inherent `<$kind>::select`.
212/// 3. `impl TaggedUnion for $parent { type Kind = $kind; type Error = $err; const KIND_LIST = $kind_list; }`
213/// — 3 associated-item assignments whose only per-site knobs are
214/// the (`$kind`, `$err`, `$kind_list`) tuple.
215///
216/// The macro takes the (`$parent`, `$kind`, `$variant`, `$err`,
217/// `$kind_list`) five-tuple as named arguments and emits all three
218/// blocks. A fifth sibling tagged-union parent picks up all three
219/// impls through ONE macro call — no re-authored inherent
220/// `.variant()` forwarder, no re-authored `impl VariantSelector`
221/// block, no re-authored `impl TaggedUnion` block.
222///
223/// The emitted inherent `.variant()`'s rustdoc is canonical (names
224/// the substrate primitive, not the exact set of sibling sites) so
225/// a fifth sibling doesn't drift the cross-ref count against reality
226/// merely by existing.
227///
228/// # Example
229///
230/// ```ignore
231/// declare_tagged_union_impls! {
232/// parent = Intent,
233/// kind = IntentKind,
234/// variant = IntentVariant,
235/// error = IntentError,
236/// kind_list = INTENT_KIND_LIST,
237/// }
238/// ```
239///
240/// Expands to the inherent `Intent::variant`, the
241/// `VariantSelector<Intent>` impl on `IntentKind`, and the
242/// `TaggedUnion` impl on `Intent`.
243#[macro_export]
244macro_rules! declare_tagged_union_impls {
245 (
246 parent = $parent:ty,
247 kind = $kind:ty,
248 variant = $variant:ident,
249 error = $err:ty,
250 kind_list = $kind_list:expr $(,)?
251 ) => {
252 impl $parent {
253 /// Resolve to exactly one variant. Errors on zero or many.
254 ///
255 /// One-line inherent forwarder that delegates the sweep
256 /// body to the substrate primitive
257 /// [`crate::tagged_union::TaggedUnion::variant`] — every
258 /// production `.variant()` site on `ProcessSpec` dispatches
259 /// through this ONE default body so the resolve-sweep
260 /// pattern lives at ONE substrate site. The inherent surface
261 /// stays load-bearing so consumer callsites don't need
262 /// `use TaggedUnion`.
263 pub fn variant(&self) -> ::std::result::Result<$variant<'_>, $err> {
264 <Self as $crate::tagged_union::TaggedUnion>::variant(self)
265 }
266
267 /// Presence probe — does this tagged union carry a
268 /// populated slot addressed by the given closed-set
269 /// discriminator?
270 ///
271 /// One-line inherent forwarder that delegates to the
272 /// substrate primitive
273 /// [`crate::tagged_union::TaggedUnion::has`] — every
274 /// closed-set-driven presence check on `ProcessSpec`
275 /// dispatches through this ONE default body so the
276 /// per-slot `spec.<field>.is_some()` pattern lives at
277 /// ONE substrate site. The inherent surface stays
278 /// load-bearing so consumer callsites don't need
279 /// `use TaggedUnion`.
280 pub fn has(&self, kind: $kind) -> bool {
281 <Self as $crate::tagged_union::TaggedUnion>::has(self, kind)
282 }
283
284 /// Closed-set-complement peer of [`Self::has`] — `true` iff
285 /// the given `kind` is MISSING (its slot on this tagged
286 /// union is empty).
287 ///
288 /// One-line inherent forwarder that delegates to the
289 /// substrate primitive
290 /// [`crate::tagged_union::TaggedUnion::lacks`], whose
291 /// default body is `!self.has(kind)`. Every consumer whose
292 /// semantic reading is "the missing set contains this
293 /// kind" — a "still missing: <kind>" diagnostic, a
294 /// `lacks-<kind>` require-tag classifier arm, a
295 /// dependency-satisfaction check — reads
296 /// `parent.lacks(kind)` through the inherent surface
297 /// rather than negating `parent.has(kind)` at the call
298 /// site. The definitional complement law
299 /// `parent.lacks(kind) == !parent.has(kind)` and the
300 /// kind-scoped implication
301 /// `parent.lacks_only(kind) → parent.lacks(kind)` are
302 /// pinned as first-class typed invariants by the trait's
303 /// own default body and swept substrate-wide by
304 /// [`crate::tagged_union::assert_lacks_matches_has_complement`].
305 pub fn lacks(&self, kind: $kind) -> bool {
306 <Self as $crate::tagged_union::TaggedUnion>::lacks(self, kind)
307 }
308
309 /// Widened peer of [`Self::has`] — returns the borrowed
310 /// variant view addressed by `kind`, or `None` when the
311 /// matching slot is empty.
312 ///
313 /// One-line inherent forwarder that delegates to the
314 /// substrate primitive
315 /// [`crate::tagged_union::TaggedUnion::find`], whose
316 /// default body is `kind.select(self)`. Every
317 /// closed-set-driven `kind.select(&parent)` callsite that
318 /// pre-lift required `use VariantSelector` at the caller
319 /// now reads `parent.find(kind)` through the inherent
320 /// surface, byte-for-byte symmetrical with
321 /// `parent.has(kind)`. The composition law
322 /// `parent.has(kind) == parent.find(kind).is_some()` is
323 /// pinned as a first-class typed invariant by the trait's
324 /// own `has` default body
325 /// (`self.find(kind).is_some()`), swept substrate-wide by
326 /// [`crate::tagged_union::assert_find_agrees_with_has`].
327 pub fn find(&self, kind: $kind) -> ::std::option::Option<$variant<'_>> {
328 <Self as $crate::tagged_union::TaggedUnion>::find(self, kind)
329 }
330
331 /// Closed-set-inversion peer of [`Self::has`] / [`Self::find`]
332 /// — returns the canonical-ordered `Vec` of populated
333 /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL)
334 /// discriminators.
335 ///
336 /// One-line inherent forwarder that delegates to the
337 /// substrate primitive
338 /// [`crate::tagged_union::TaggedUnion::populated_kinds`],
339 /// whose default body is
340 /// `<Kind as ClosedSet>::ALL.iter().copied().filter(|k|
341 /// self.has(*k)).collect()`. Every consumer that needs
342 /// to enumerate which slots on a tagged-union parent are
343 /// populated (an operator-facing "Ambiguous named
344 /// [Nix, Container]" diagnostic composed on the malformed
345 /// arm; a closed-set audit dispatcher; a
346 /// `populated-kind-count-<n>` require-tag classifier
347 /// prefix) reads `parent.populated_kinds()` through the
348 /// inherent surface, byte-for-byte symmetrical with
349 /// `parent.has(kind)` / `parent.find(kind)`. The
350 /// composition law
351 /// `parent.populated_kinds().contains(&k) == parent.has(k)`
352 /// is pinned as a first-class typed invariant by the
353 /// trait's own default body and swept substrate-wide by
354 /// [`crate::tagged_union::assert_populated_kinds_matches_has`].
355 pub fn populated_kinds(&self) -> ::std::vec::Vec<$kind> {
356 <Self as $crate::tagged_union::TaggedUnion>::populated_kinds(self)
357 }
358
359 /// Zero-allocation iterator peer of [`Self::populated_kinds`]
360 /// — walks
361 /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL)
362 /// in canonical order and yields every Kind whose slot on
363 /// `self` is populated, without materializing an
364 /// intermediate `Vec`.
365 ///
366 /// One-line inherent forwarder that delegates to the
367 /// substrate primitive
368 /// [`crate::tagged_union::TaggedUnion::iter_populated_kinds`],
369 /// whose default body is
370 /// `<Kind as ClosedSet>::ALL.iter().copied().filter(|&k| self.has(k))`.
371 /// Consumers reach for the iterator peer when they need
372 /// a short-circuiting fold (`.any(|k| pred(k))`,
373 /// `.find(|&k| pred(k))`, `.take_while(|k| pred(k))`) or
374 /// a projection (`.map(|k| project(k))`) that would
375 /// otherwise pay for the heap allocation the Vec-widened
376 /// [`Self::populated_kinds`] peer materializes. The
377 /// composition law
378 /// `parent.populated_kinds() == parent.iter_populated_kinds().collect::<Vec<_>>()`
379 /// is pinned as a first-class typed invariant by the
380 /// trait's own default body (which IS `iter_populated_kinds().collect()`)
381 /// and swept substrate-wide by
382 /// [`crate::tagged_union::assert_iter_populated_kinds_matches_populated_kinds`].
383 pub fn iter_populated_kinds(&self) -> impl ::std::iter::Iterator<Item = $kind> + '_ {
384 <Self as $crate::tagged_union::TaggedUnion>::iter_populated_kinds(self)
385 }
386
387 /// Scalar cardinality peer of [`Self::populated_kinds`] —
388 /// the number of populated slots on this tagged union.
389 ///
390 /// One-line inherent forwarder that delegates to the
391 /// substrate primitive
392 /// [`crate::tagged_union::TaggedUnion::populated_kind_count`],
393 /// whose default body is
394 /// `<Kind as ClosedSet>::ALL.iter().copied().filter(|k|
395 /// self.has(*k)).count()`. Every consumer that needs the
396 /// cardinality of the populated-slot set as a scalar
397 /// (a `populated-kind-count-<n>` require-tag classifier
398 /// prefix; a fast-path branch on the Ambiguous-arm side
399 /// that discriminates "well-formed" from "malformed with
400 /// N slots"; a coherence check that verifies "every
401 /// well-formed parent has exactly one populated slot")
402 /// reads `parent.populated_kind_count()` through the
403 /// inherent surface, byte-for-byte symmetrical with
404 /// `parent.has(kind)` / `parent.find(kind)` /
405 /// `parent.populated_kinds()`. The composition law
406 /// `parent.populated_kind_count() == parent.populated_kinds().len()`
407 /// is pinned as a first-class typed invariant by the
408 /// trait's own default body and swept substrate-wide by
409 /// [`crate::tagged_union::assert_populated_kind_count_matches_populated_kinds`].
410 pub fn populated_kind_count(&self) -> usize {
411 <Self as $crate::tagged_union::TaggedUnion>::populated_kind_count(self)
412 }
413
414 /// Closed-set-COMPLEMENT peer of [`Self::populated_kinds`]
415 /// — returns the canonical-ordered `Vec` of EMPTY
416 /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL)
417 /// discriminators.
418 ///
419 /// One-line inherent forwarder that delegates to the
420 /// substrate primitive
421 /// [`crate::tagged_union::TaggedUnion::missing_kinds`],
422 /// whose default body is
423 /// `<Kind as ClosedSet>::ALL.iter().copied().filter(|k|
424 /// !self.has(*k)).collect()`. Every consumer that needs to
425 /// enumerate which slots on a tagged-union parent are
426 /// ABSENT (an operator-facing "still missing [Nix, Container]"
427 /// diagnostic on the partially-populated arm; a coherence
428 /// check verifying "every process boundary carries every
429 /// intent slot"; a `missing-<kind>` require-tag classifier
430 /// arm) reads `parent.missing_kinds()` through the
431 /// inherent surface, byte-for-byte symmetrical with
432 /// `parent.populated_kinds()`. The partition law
433 /// `parent.populated_kinds() ∪ parent.missing_kinds() ==
434 /// ClosedSet::ALL` (with the two sets disjoint) is pinned
435 /// as a first-class typed invariant by the trait's own
436 /// default body and swept substrate-wide by
437 /// [`crate::tagged_union::assert_missing_kinds_matches_has`].
438 pub fn missing_kinds(&self) -> ::std::vec::Vec<$kind> {
439 <Self as $crate::tagged_union::TaggedUnion>::missing_kinds(self)
440 }
441
442 /// Zero-allocation iterator peer of [`Self::missing_kinds`]
443 /// — walks
444 /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL)
445 /// in canonical order and yields every Kind whose slot on
446 /// `self` is EMPTY, without materializing an intermediate
447 /// `Vec`.
448 ///
449 /// One-line inherent forwarder that delegates to the
450 /// substrate primitive
451 /// [`crate::tagged_union::TaggedUnion::iter_missing_kinds`],
452 /// whose default body is
453 /// `<Kind as ClosedSet>::ALL.iter().copied().filter(|&k| !self.has(k))`.
454 /// Consumers reach for the iterator peer when they need
455 /// a short-circuiting fold under negation
456 /// (`.any(|k| pred(k))`, `.find(|&k| pred(k))`,
457 /// `.take_while(|k| pred(k))`) or a projection (`.map(|k|
458 /// project(k))`) that would otherwise pay for the heap
459 /// allocation the Vec-widened [`Self::missing_kinds`] peer
460 /// materializes. The composition law
461 /// `parent.missing_kinds() == parent.iter_missing_kinds().collect::<Vec<_>>()`
462 /// is pinned as a first-class typed invariant by the
463 /// trait's own default body (which IS
464 /// `iter_missing_kinds().collect()`) and swept substrate-
465 /// wide by
466 /// [`crate::tagged_union::assert_iter_missing_kinds_matches_missing_kinds`].
467 pub fn iter_missing_kinds(&self) -> impl ::std::iter::Iterator<Item = $kind> + '_ {
468 <Self as $crate::tagged_union::TaggedUnion>::iter_missing_kinds(self)
469 }
470
471 /// Scalar cardinality peer of [`Self::missing_kinds`] —
472 /// the number of EMPTY slots on this tagged union.
473 ///
474 /// One-line inherent forwarder that delegates to the
475 /// substrate primitive
476 /// [`crate::tagged_union::TaggedUnion::missing_kind_count`],
477 /// whose default body is
478 /// `<Kind as ClosedSet>::ALL.iter().copied().filter(|k|
479 /// !self.has(*k)).count()`. Every consumer that needs the
480 /// cardinality of the missing-slot set as a scalar (a
481 /// `missing-kind-count-<n>` require-tag classifier prefix;
482 /// a fast-path branch that discriminates "well-formed"
483 /// from "N missing slots"; a coherence check that verifies
484 /// "every well-formed parent has exactly ALL.len() - 1
485 /// missing slots") reads `parent.missing_kind_count()`
486 /// through the inherent surface, byte-for-byte symmetrical
487 /// with `parent.populated_kind_count()`. The scalar
488 /// partition law `parent.populated_kind_count() +
489 /// parent.missing_kind_count() == <Kind as ClosedSet>::ALL.len()`
490 /// is pinned by the trait's own default body and swept
491 /// substrate-wide by
492 /// [`crate::tagged_union::assert_missing_kind_count_matches_missing_kinds`].
493 pub fn missing_kind_count(&self) -> usize {
494 <Self as $crate::tagged_union::TaggedUnion>::missing_kind_count(self)
495 }
496
497 /// Short-circuiting `Option<$kind>` peer of
498 /// [`Self::populated_kinds`] — the FIRST populated kind on
499 /// this tagged union in canonical
500 /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL)
501 /// order, or `None` when no slot is populated.
502 ///
503 /// One-line inherent forwarder that delegates to the
504 /// substrate primitive
505 /// [`crate::tagged_union::TaggedUnion::first_populated_kind`],
506 /// whose default body is
507 /// `<Kind as ClosedSet>::ALL.iter().copied().find(|k|
508 /// self.has(*k))`. Every consumer that needs the earliest
509 /// populated slot on a tagged-union parent as an
510 /// `Option<Kind>` (an operator-facing "Ambiguous, starting
511 /// at Nix" diagnostic on the malformed arm; a
512 /// `first-populated-<kind>` require-tag classifier arm; a
513 /// fast-path branch that discriminates "empty" from "any
514 /// populated") reads `parent.first_populated_kind()` through
515 /// the inherent surface, byte-for-byte symmetrical with
516 /// `parent.populated_kinds()` / `parent.has(kind)`. The
517 /// composition law `parent.first_populated_kind() ==
518 /// parent.populated_kinds().first().copied()` is pinned as
519 /// a first-class typed invariant by the trait's own default
520 /// body and swept substrate-wide by
521 /// [`crate::tagged_union::assert_first_populated_kind_matches_populated_kinds`].
522 pub fn first_populated_kind(&self) -> ::std::option::Option<$kind> {
523 <Self as $crate::tagged_union::TaggedUnion>::first_populated_kind(self)
524 }
525
526 /// Short-circuiting `Option<$kind>` peer of
527 /// [`Self::missing_kinds`] — the FIRST missing kind on this
528 /// tagged union in canonical
529 /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL)
530 /// order, or `None` when EVERY slot is populated.
531 ///
532 /// One-line inherent forwarder that delegates to the
533 /// substrate primitive
534 /// [`crate::tagged_union::TaggedUnion::first_missing_kind`],
535 /// whose default body is
536 /// `<Kind as ClosedSet>::ALL.iter().copied().find(|k|
537 /// !self.has(*k))`. Byte-for-byte symmetrical with
538 /// `parent.first_populated_kind()` under a negated
539 /// predicate; the two primitives PARTITION
540 /// `ClosedSet::ALL`'s earliest-element projection on the
541 /// (populated, missing) split. The composition law
542 /// `parent.first_missing_kind() ==
543 /// parent.missing_kinds().first().copied()` is pinned as a
544 /// first-class typed invariant by the trait's own default
545 /// body and swept substrate-wide by
546 /// [`crate::tagged_union::assert_first_missing_kind_matches_missing_kinds`].
547 pub fn first_missing_kind(&self) -> ::std::option::Option<$kind> {
548 <Self as $crate::tagged_union::TaggedUnion>::first_missing_kind(self)
549 }
550
551 /// Short-circuiting `Option<$kind>` peer of
552 /// [`Self::populated_kinds`] — the LAST populated kind on
553 /// this tagged union in canonical
554 /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL)
555 /// order, or `None` when no slot is populated.
556 ///
557 /// One-line inherent forwarder that delegates to the
558 /// substrate primitive
559 /// [`crate::tagged_union::TaggedUnion::last_populated_kind`],
560 /// whose default body is
561 /// `<Kind as ClosedSet>::ALL.iter().rev().copied().find(|k|
562 /// self.has(*k))` — a REVERSED closed-set walk composed
563 /// against `self.has` per variant that SHORT-CIRCUITS at
564 /// the latest match. Byte-for-byte time-reversed peer of
565 /// [`Self::first_populated_kind`]. Empty parent returns
566 /// `None`; well-formed parent returns `Some(k)` (the sole
567 /// populated slot); malformed (Ambiguous) parent returns
568 /// `Some(k)` where `k` is the LATEST populated slot in
569 /// canonical `ALL` order — the operator-diagnostic "and
570 /// last at Z" peer of the "Ambiguous, starting at Nix"
571 /// upgrade the first-projection enables. The composition
572 /// law `parent.last_populated_kind() ==
573 /// parent.populated_kinds().last().copied()` is pinned as
574 /// a first-class typed invariant by the trait's own default
575 /// body and swept substrate-wide by
576 /// [`crate::tagged_union::assert_last_populated_kind_matches_populated_kinds`].
577 pub fn last_populated_kind(&self) -> ::std::option::Option<$kind> {
578 <Self as $crate::tagged_union::TaggedUnion>::last_populated_kind(self)
579 }
580
581 /// Short-circuiting `Option<$kind>` peer of
582 /// [`Self::missing_kinds`] — the LAST missing kind on this
583 /// tagged union in canonical
584 /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL)
585 /// order, or `None` when EVERY slot is populated.
586 ///
587 /// One-line inherent forwarder that delegates to the
588 /// substrate primitive
589 /// [`crate::tagged_union::TaggedUnion::last_missing_kind`],
590 /// whose default body is
591 /// `<Kind as ClosedSet>::ALL.iter().rev().copied().find(|k|
592 /// !self.has(*k))`. Byte-for-byte time-reversed peer of
593 /// [`Self::first_missing_kind`] under an identical negated
594 /// predicate. The two primitives PARTITION
595 /// `ClosedSet::ALL`'s endpoint projection on the (populated,
596 /// missing) × (earliest, latest) product together with the
597 /// `first_*` peers — every endpoint-addressable coherence
598 /// check reads ONE of the four at ONE call site without
599 /// allocating a `Vec<$kind>`. The composition law
600 /// `parent.last_missing_kind() ==
601 /// parent.missing_kinds().last().copied()` is pinned as a
602 /// first-class typed invariant by the trait's own default
603 /// body and swept substrate-wide by
604 /// [`crate::tagged_union::assert_last_missing_kind_matches_missing_kinds`].
605 pub fn last_missing_kind(&self) -> ::std::option::Option<$kind> {
606 <Self as $crate::tagged_union::TaggedUnion>::last_missing_kind(self)
607 }
608
609 /// Exactly-one-populated `Option<$kind>` peer of
610 /// [`Self::populated_kinds`] — `Some(k)` iff `k` is the
611 /// SOLE populated kind on this tagged union, else `None`.
612 ///
613 /// One-line inherent forwarder that delegates to the
614 /// substrate primitive
615 /// [`crate::tagged_union::TaggedUnion::unique_populated_kind`],
616 /// whose default body is a two-step-short-circuit walk
617 /// over `<Kind as ClosedSet>::ALL` returning `Some(k)`
618 /// only when EXACTLY ONE `has(k)` is `true`. Every
619 /// consumer that needs the resolved kind identity on the
620 /// well-formed arm (without paying for the borrowed
621 /// variant view [`Self::variant`] returns, and without
622 /// materializing the [`Self::Error`] carrier on the
623 /// empty / malformed arms) reads
624 /// `parent.unique_populated_kind()` through the inherent
625 /// surface — `Some(k)` names well-formed exactly-one,
626 /// `None` collapses BOTH the empty AND the malformed
627 /// (ambiguous) arms.
628 ///
629 /// The composition laws
630 /// `parent.unique_populated_kind().is_some() ==
631 /// (parent.populated_kind_count() == 1)` and (on the
632 /// `Some` arm) `parent.unique_populated_kind() ==
633 /// parent.first_populated_kind() ==
634 /// parent.last_populated_kind()` are pinned as first-
635 /// class typed invariants by the trait's own default body
636 /// and swept substrate-wide by
637 /// [`crate::tagged_union::assert_unique_populated_kind_matches_populated_kinds`].
638 pub fn unique_populated_kind(&self) -> ::std::option::Option<$kind> {
639 <Self as $crate::tagged_union::TaggedUnion>::unique_populated_kind(self)
640 }
641
642 /// Exactly-one-missing `Option<$kind>` peer of
643 /// [`Self::missing_kinds`] — `Some(k)` iff `k` is the
644 /// SOLE missing kind on this tagged union, else `None`.
645 ///
646 /// One-line inherent forwarder that delegates to the
647 /// substrate primitive
648 /// [`crate::tagged_union::TaggedUnion::unique_missing_kind`],
649 /// whose default body is a two-step-short-circuit walk
650 /// over `<Kind as ClosedSet>::ALL` under a NEGATED `has`
651 /// predicate returning `Some(k)` only when EXACTLY ONE
652 /// `!has(k)` is `true`. Byte-for-byte symmetrical with
653 /// `parent.unique_populated_kind()` under complement; on
654 /// tagged unions with `<Kind as ClosedSet>::ALL.len() >
655 /// 2` the primitive returns `Some` only on the near-
656 /// saturation arm (`ALL.len() - 1` populated).
657 ///
658 /// The composition laws
659 /// `parent.unique_missing_kind().is_some() ==
660 /// (parent.missing_kind_count() == 1)` and (on the
661 /// `Some` arm) `parent.unique_missing_kind() ==
662 /// parent.first_missing_kind() ==
663 /// parent.last_missing_kind()` are pinned as first-class
664 /// typed invariants by the trait's own default body and
665 /// swept substrate-wide by
666 /// [`crate::tagged_union::assert_unique_missing_kind_matches_missing_kinds`].
667 pub fn unique_missing_kind(&self) -> ::std::option::Option<$kind> {
668 <Self as $crate::tagged_union::TaggedUnion>::unique_missing_kind(self)
669 }
670
671 /// Boolean cardinality-endpoint peer of [`Self::populated_kinds`]
672 /// — `true` iff NO slot on this tagged union is populated.
673 ///
674 /// One-line inherent forwarder that delegates to the
675 /// substrate primitive
676 /// [`crate::tagged_union::TaggedUnion::is_empty`], whose
677 /// default body is `!<Kind as ClosedSet>::ALL.iter().any(|k|
678 /// self.has(k))` — a short-circuiting closed-set walk that
679 /// returns `true` iff every point-probe returns `false`,
680 /// WITHOUT materializing the `Vec` `populated_kinds` would
681 /// build. Every consumer that needs the zero-arm Boolean
682 /// projection of the populated cardinality (a fast-path
683 /// guard on "any content at all"; an operator-facing
684 /// "carrier missing content" diagnostic on the `Empty` arm;
685 /// an `is-empty` require-tag classifier arm) reads
686 /// `parent.is_empty()` through the inherent surface, byte-
687 /// for-byte symmetrical with `parent.is_saturated()` under
688 /// the (populated, missing) complement axis. The
689 /// composition law
690 /// `parent.is_empty() == (parent.populated_kind_count() == 0)`
691 /// is pinned as a first-class typed invariant by the
692 /// trait's own default body and swept substrate-wide by
693 /// [`crate::tagged_union::assert_is_empty_matches_populated_kind_count`].
694 pub fn is_empty(&self) -> bool {
695 <Self as $crate::tagged_union::TaggedUnion>::is_empty(self)
696 }
697
698 /// Boolean cardinality-endpoint peer of [`Self::missing_kinds`]
699 /// — `true` iff EVERY slot on this tagged union is populated
700 /// (i.e. the missing set is empty).
701 ///
702 /// One-line inherent forwarder that delegates to the
703 /// substrate primitive
704 /// [`crate::tagged_union::TaggedUnion::is_saturated`], whose
705 /// default body is `<Kind as ClosedSet>::ALL.iter().all(|k|
706 /// self.has(k))` — a short-circuiting closed-set walk that
707 /// returns `true` iff every point-probe returns `true`,
708 /// WITHOUT materializing the `Vec` `missing_kinds` would
709 /// build. Every consumer that needs the zero-arm Boolean
710 /// projection of the missing cardinality (a fast-path guard
711 /// discriminating "over-populated" from "well-formed or
712 /// partial"; an operator-facing "over-populated carrier"
713 /// diagnostic; an `is-saturated` require-tag classifier
714 /// arm) reads `parent.is_saturated()` through the inherent
715 /// surface, byte-for-byte symmetrical with
716 /// `parent.is_empty()` under the (populated, missing)
717 /// complement axis. The composition law
718 /// `parent.is_saturated() == (parent.missing_kind_count() == 0)`
719 /// is pinned as a first-class typed invariant by the
720 /// trait's own default body and swept substrate-wide by
721 /// [`crate::tagged_union::assert_is_saturated_matches_missing_kind_count`].
722 pub fn is_saturated(&self) -> bool {
723 <Self as $crate::tagged_union::TaggedUnion>::is_saturated(self)
724 }
725
726 /// Boolean cardinality "at-least-one" peer of
727 /// [`Self::populated_kinds`] — `true` iff AT LEAST ONE slot
728 /// on this tagged union is populated (the populated set is
729 /// NON-empty).
730 ///
731 /// One-line inherent forwarder that delegates to the
732 /// substrate primitive
733 /// [`crate::tagged_union::TaggedUnion::has_any_populated_kind`],
734 /// whose default body is `<Kind as ClosedSet>::ALL.iter().any(|k|
735 /// self.has(k))` — a short-circuiting closed-set walk that
736 /// returns `true` at the FIRST populated slot, WITHOUT
737 /// materializing the `Vec` `populated_kinds` would build.
738 /// Every consumer that needs the ≥ 1 halfspace on the
739 /// populated cardinality (a boundary-progress "any content
740 /// at all" diagnostic; an `is-non-empty` require-tag
741 /// classifier arm; a fast-path branch discriminating "some
742 /// populated" from "all missing") reads
743 /// `parent.has_any_populated_kind()` through the inherent
744 /// surface — byte-for-byte definitional complement of
745 /// `parent.is_empty()`, no readerly inversion at the
746 /// callsite, and byte-for-byte symmetrical with
747 /// `parent.has_any_missing_kind()` under the (populated,
748 /// missing) complement axis. The composition law
749 /// `parent.has_any_populated_kind() == !parent.is_empty()`
750 /// is pinned as a first-class typed invariant by the
751 /// trait's own default body and swept substrate-wide by
752 /// [`crate::tagged_union::assert_has_any_populated_kind_matches_populated_kind_count`].
753 pub fn has_any_populated_kind(&self) -> bool {
754 <Self as $crate::tagged_union::TaggedUnion>::has_any_populated_kind(self)
755 }
756
757 /// Boolean cardinality "at-least-one" peer of
758 /// [`Self::missing_kinds`] — `true` iff AT LEAST ONE slot on
759 /// this tagged union is missing (the missing set is
760 /// NON-empty).
761 ///
762 /// One-line inherent forwarder that delegates to the
763 /// substrate primitive
764 /// [`crate::tagged_union::TaggedUnion::has_any_missing_kind`],
765 /// whose default body is `<Kind as ClosedSet>::ALL.iter().any(|k|
766 /// !self.has(k))` — a short-circuiting closed-set walk under
767 /// a negated `has` predicate that returns `true` at the
768 /// FIRST missing slot, WITHOUT materializing the `Vec`
769 /// `missing_kinds` would build. Every consumer that needs
770 /// the ≥ 1 halfspace on the missing cardinality (an
771 /// operator-facing "not fully populated" diagnostic; a
772 /// `has-any-missing-kind` require-tag classifier arm; a
773 /// fast-path branch discriminating "any slot still absent"
774 /// from "over-populated / saturated") reads
775 /// `parent.has_any_missing_kind()` through the inherent
776 /// surface — byte-for-byte definitional complement of
777 /// `parent.is_saturated()`, no readerly inversion at the
778 /// callsite, and byte-for-byte symmetrical with
779 /// `parent.has_any_populated_kind()` under the (populated,
780 /// missing) complement axis. The composition law
781 /// `parent.has_any_missing_kind() == !parent.is_saturated()`
782 /// is pinned as a first-class typed invariant by the
783 /// trait's own default body and swept substrate-wide by
784 /// [`crate::tagged_union::assert_has_any_missing_kind_matches_missing_kind_count`].
785 pub fn has_any_missing_kind(&self) -> bool {
786 <Self as $crate::tagged_union::TaggedUnion>::has_any_missing_kind(self)
787 }
788
789 /// Boolean cardinality-mid-endpoint peer of
790 /// [`Self::unique_populated_kind`] — `true` iff EXACTLY ONE
791 /// slot on this tagged union is populated.
792 ///
793 /// One-line inherent forwarder that delegates to the
794 /// substrate primitive
795 /// [`crate::tagged_union::TaggedUnion::has_unique_populated_kind`],
796 /// whose default body is `self.unique_populated_kind().is_some()`
797 /// — the Boolean projection of the two-step-short-circuit
798 /// closed-set walk `unique_populated_kind` already performs,
799 /// without paying for a `Vec<$kind>` allocation on any arm.
800 /// Every consumer that needs the exactly-one-populated arm
801 /// as a `bool` (a fast-path branch on the well-formed arm
802 /// that skips the borrowed-view / error-carrier
803 /// materialization [`Self::variant`] would pay for; an
804 /// operator-facing "well-formed" diagnostic on the resolver's
805 /// Ok arm; a `has-unique-populated-kind` require-tag
806 /// classifier arm; a coherence check verifying "every
807 /// production parent from a `single_slot_X` factory is
808 /// well-formed") reads `parent.has_unique_populated_kind()`
809 /// through the inherent surface, byte-for-byte symmetrical
810 /// with `parent.is_empty()` / `parent.is_saturated()` under
811 /// the (zero-, one-arm) × (populated, missing) cardinality
812 /// grid. The composition law
813 /// `parent.has_unique_populated_kind() == (parent.populated_kind_count() == 1)`
814 /// is pinned as a first-class typed invariant by the trait's
815 /// own default body and swept substrate-wide by
816 /// [`crate::tagged_union::assert_has_unique_populated_kind_matches_populated_kind_count`].
817 pub fn has_unique_populated_kind(&self) -> bool {
818 <Self as $crate::tagged_union::TaggedUnion>::has_unique_populated_kind(self)
819 }
820
821 /// Boolean cardinality-mid-endpoint peer of
822 /// [`Self::unique_missing_kind`] — `true` iff EXACTLY ONE
823 /// slot on this tagged union is missing.
824 ///
825 /// One-line inherent forwarder that delegates to the
826 /// substrate primitive
827 /// [`crate::tagged_union::TaggedUnion::has_unique_missing_kind`],
828 /// whose default body is `self.unique_missing_kind().is_some()`
829 /// — the Boolean projection of the two-step-short-circuit
830 /// closed-set walk `unique_missing_kind` already performs.
831 /// Every consumer that needs the exactly-one-missing arm as
832 /// a `bool` (a fast-path branch on the near-saturation arm;
833 /// an operator-facing "one slot away from saturated"
834 /// diagnostic; a `has-unique-missing-kind` require-tag
835 /// classifier arm) reads `parent.has_unique_missing_kind()`
836 /// through the inherent surface, byte-for-byte symmetrical
837 /// with `parent.has_unique_populated_kind()` under the
838 /// (populated, missing) complement axis. The composition law
839 /// `parent.has_unique_missing_kind() == (parent.missing_kind_count() == 1)`
840 /// is pinned as a first-class typed invariant by the trait's
841 /// own default body and swept substrate-wide by
842 /// [`crate::tagged_union::assert_has_unique_missing_kind_matches_missing_kind_count`].
843 pub fn has_unique_missing_kind(&self) -> bool {
844 <Self as $crate::tagged_union::TaggedUnion>::has_unique_missing_kind(self)
845 }
846
847 /// Boolean cardinality many-arm peer of
848 /// [`Self::has_unique_populated_kind`] — `true` iff TWO
849 /// OR MORE slots on this tagged union are populated (i.e.
850 /// the "ambiguous" arm of the resolver contract).
851 ///
852 /// One-line inherent forwarder that delegates to the
853 /// substrate primitive
854 /// [`crate::tagged_union::TaggedUnion::has_multiple_populated_kinds`],
855 /// whose default body is a two-step-short-circuit closed-
856 /// set walk under [`Self::has`] that returns `true` iff
857 /// the filtered iterator yields at least two hits, WITHOUT
858 /// materializing the `Vec` `populated_kinds` would build.
859 /// The short-circuit fires on the SECOND populated slot
860 /// — strictly cheaper than the widened primitive on every
861 /// arm past the second populated slot.
862 ///
863 /// # Sibling to the Boolean cardinality trichotomy
864 ///
865 /// Third arm of the {0, 1, ≥2} cardinality trichotomy on
866 /// the populated axis. Together with [`Self::is_empty`]
867 /// (zero-arm) and [`Self::has_unique_populated_kind`]
868 /// (one-arm), these three Boolean primitives partition
869 /// every tagged-union state coherently — EXACTLY ONE of
870 /// the three returns `true` on any given parent. Maps
871 /// directly onto the three arms of the resolver contract
872 /// [`Self::variant`] returns:
873 /// `is_empty()` ↔ `Err(Error::empty)`,
874 /// `has_unique_populated_kind()` ↔ `Ok(Variant)`,
875 /// `has_multiple_populated_kinds()` ↔ `Err(Error::ambiguous)`.
876 ///
877 /// The composition law
878 /// `parent.has_multiple_populated_kinds() == (parent.populated_kind_count() >= 2)`
879 /// is pinned as a first-class typed invariant by the
880 /// trait's own default body and swept substrate-wide by
881 /// [`crate::tagged_union::assert_has_multiple_populated_kinds_matches_populated_kind_count`].
882 pub fn has_multiple_populated_kinds(&self) -> bool {
883 <Self as $crate::tagged_union::TaggedUnion>::has_multiple_populated_kinds(self)
884 }
885
886 /// Boolean cardinality many-arm peer of
887 /// [`Self::has_unique_missing_kind`] — `true` iff TWO OR
888 /// MORE slots on this tagged union are missing.
889 ///
890 /// One-line inherent forwarder that delegates to the
891 /// substrate primitive
892 /// [`crate::tagged_union::TaggedUnion::has_multiple_missing_kinds`],
893 /// whose default body is a two-step-short-circuit closed-
894 /// set walk under a NEGATED [`Self::has`] predicate that
895 /// returns `true` iff the filtered iterator yields at
896 /// least two hits, WITHOUT materializing the `Vec`
897 /// `missing_kinds` would build. Byte-for-byte symmetrical
898 /// with `parent.has_multiple_populated_kinds()` under the
899 /// (populated, missing) complement axis.
900 ///
901 /// Third arm of the {0, 1, ≥2} cardinality trichotomy on
902 /// the missing axis. Together with [`Self::is_saturated`]
903 /// (zero-arm) and [`Self::has_unique_missing_kind`]
904 /// (one-arm), these three Boolean primitives partition
905 /// every tagged-union state coherently on the complement
906 /// axis. The composition law
907 /// `parent.has_multiple_missing_kinds() == (parent.missing_kind_count() >= 2)`
908 /// is pinned as a first-class typed invariant by the
909 /// trait's own default body and swept substrate-wide by
910 /// [`crate::tagged_union::assert_has_multiple_missing_kinds_matches_missing_kind_count`].
911 pub fn has_multiple_missing_kinds(&self) -> bool {
912 <Self as $crate::tagged_union::TaggedUnion>::has_multiple_missing_kinds(self)
913 }
914
915 /// Boolean cardinality "≤ 1" peer of
916 /// [`Self::has_multiple_populated_kinds`] — `true` iff AT
917 /// MOST ONE slot on this tagged union is populated (i.e.
918 /// zero or one populated slot).
919 ///
920 /// One-line inherent forwarder that delegates to the
921 /// substrate primitive
922 /// [`crate::tagged_union::TaggedUnion::has_at_most_one_populated_kind`],
923 /// whose default body is the definitional Boolean negation
924 /// of [`Self::has_multiple_populated_kinds`] — reuses the
925 /// SAME two-step-short-circuit closed-set walk without
926 /// re-authoring the fused loop; the short-circuit fires on
927 /// the SECOND populated slot, and the negation flips the
928 /// return in-place without a second walk over the closed
929 /// set. Strictly cheaper than the widened union composition
930 /// `self.is_empty() || self.has_unique_populated_kind()`
931 /// (which walks the closed set twice) on every arm.
932 ///
933 /// # Sibling to the Boolean cardinality "≥ 2" primitive
934 ///
935 /// Boolean-negation peer under `!(≥ 2) == (≤ 1)` — where
936 /// [`Self::has_multiple_populated_kinds`] names the
937 /// AMBIGUOUS arm of the resolver contract (the arm
938 /// [`Self::variant`] returns `Err(Error::ambiguous)` on),
939 /// `has_at_most_one_populated_kind` names its complement —
940 /// the RESOLVEABLE-OR-EMPTY arm (the two arms of the
941 /// resolver contract that DON'T return `Err(Error::ambiguous)`).
942 /// The typed predicate for "this parent is not ambiguous"
943 /// without inverting a `!parent.has_multiple_populated_kinds()`
944 /// at every callsite.
945 ///
946 /// # Composition laws
947 ///
948 /// - `has_at_most_one_populated_kind() == !has_multiple_populated_kinds()`
949 /// — the definitional Boolean negation, at the trait
950 /// default body's SAME fused short-circuit walk.
951 /// - `has_at_most_one_populated_kind() == (populated_kind_count() <= 1)`
952 /// — the scalar cardinality composition.
953 /// - `has_at_most_one_populated_kind() == is_empty() || has_unique_populated_kind()`
954 /// — the union of the zero-arm and the one-arm of the
955 /// {0, 1, ≥ 2} cardinality trichotomy.
956 ///
957 /// All three composition laws are pinned as first-class
958 /// typed invariants by the trait's own default body and
959 /// swept substrate-wide by
960 /// [`crate::tagged_union::assert_has_at_most_one_populated_kind_matches_populated_kind_count`].
961 pub fn has_at_most_one_populated_kind(&self) -> bool {
962 <Self as $crate::tagged_union::TaggedUnion>::has_at_most_one_populated_kind(self)
963 }
964
965 /// Boolean cardinality "≤ 1" peer of
966 /// [`Self::has_multiple_missing_kinds`] — `true` iff AT
967 /// MOST ONE slot on this tagged union is missing (i.e.
968 /// zero or one missing slot).
969 ///
970 /// One-line inherent forwarder that delegates to the
971 /// substrate primitive
972 /// [`crate::tagged_union::TaggedUnion::has_at_most_one_missing_kind`],
973 /// whose default body is the definitional Boolean negation
974 /// of [`Self::has_multiple_missing_kinds`] — reuses the
975 /// SAME two-step-short-circuit closed-set walk under a
976 /// negated [`Self::has`] predicate without re-authoring the
977 /// fused loop. Strictly cheaper than the widened union
978 /// composition
979 /// `self.is_saturated() || self.has_unique_missing_kind()`
980 /// (two closed-set walks) on every arm.
981 ///
982 /// # Sibling to the Boolean cardinality "≥ 2" primitive
983 ///
984 /// Boolean-negation peer under `!(≥ 2) == (≤ 1)` —
985 /// byte-for-byte symmetrical with
986 /// `parent.has_at_most_one_populated_kind()` under the
987 /// (populated, missing) complement axis. Names the arm
988 /// where the parent is SATURATED-OR-NEAR-SATURATED (zero
989 /// or exactly one missing slot).
990 ///
991 /// # Composition laws
992 ///
993 /// - `has_at_most_one_missing_kind() == !has_multiple_missing_kinds()`
994 /// — the definitional Boolean negation.
995 /// - `has_at_most_one_missing_kind() == (missing_kind_count() <= 1)`
996 /// — the scalar complement-cardinality composition.
997 /// - `has_at_most_one_missing_kind() == is_saturated() || has_unique_missing_kind()`
998 /// — the union of the zero-missing-arm and the
999 /// one-missing-arm of the {0, 1, ≥ 2} cardinality
1000 /// trichotomy on the missing axis.
1001 ///
1002 /// All three composition laws are pinned as first-class
1003 /// typed invariants by the trait's own default body and
1004 /// swept substrate-wide by
1005 /// [`crate::tagged_union::assert_has_at_most_one_missing_kind_matches_missing_kind_count`].
1006 pub fn has_at_most_one_missing_kind(&self) -> bool {
1007 <Self as $crate::tagged_union::TaggedUnion>::has_at_most_one_missing_kind(self)
1008 }
1009
1010 /// Boolean parent-state middle-arm projection — `true` iff
1011 /// this tagged union has AT LEAST ONE populated slot AND AT
1012 /// LEAST ONE missing slot, i.e. it is neither
1013 /// [`Self::is_empty`] nor [`Self::is_saturated`].
1014 ///
1015 /// One-line inherent forwarder that delegates to the
1016 /// substrate primitive
1017 /// [`crate::tagged_union::TaggedUnion::is_partially_populated`],
1018 /// whose default body is a FUSED short-circuit closed-set
1019 /// walk that returns `true` at the EARLIEST slot where both
1020 /// a populated AND a missing kind have been observed —
1021 /// byte-for-byte cheaper than the widened composition
1022 /// `!self.is_empty() && !self.is_saturated()` (two closed-
1023 /// set walks) on every partially-populated arm.
1024 ///
1025 /// # Sibling to the parent-state trichotomy
1026 ///
1027 /// Middle arm of the natural `{Empty | Partial | Saturated}`
1028 /// parent-state trichotomy — orthogonal to the {0, 1, ≥2}
1029 /// cardinality trichotomies on the populated / missing
1030 /// axes. Together with [`Self::is_empty`] (all-missing arm)
1031 /// and [`Self::is_saturated`] (all-populated arm), these
1032 /// three Boolean primitives partition every tagged-union
1033 /// state coherently on the parent-state axis — EXACTLY ONE
1034 /// of the three returns `true` on any given parent. The
1035 /// trichotomy partition law
1036 /// `usize::from(is_empty()) + usize::from(is_partially_populated())
1037 /// + usize::from(is_saturated()) == 1` is pinned as a first-
1038 /// class typed invariant by the trait's own default body
1039 /// and swept substrate-wide by
1040 /// [`crate::tagged_union::assert_is_partially_populated_matches_cardinality`].
1041 pub fn is_partially_populated(&self) -> bool {
1042 <Self as $crate::tagged_union::TaggedUnion>::is_partially_populated(self)
1043 }
1044
1045 /// Kind-scoped strict refinement of [`Self::has`] — `true`
1046 /// iff the given `kind` is populated AND no OTHER slot on
1047 /// this tagged union is populated. The "exactly this one
1048 /// variant" predicate.
1049 ///
1050 /// One-line inherent forwarder that delegates to the
1051 /// substrate primitive
1052 /// [`crate::tagged_union::TaggedUnion::has_only`], whose
1053 /// default body is a FUSED short-circuit closed-set walk
1054 /// that returns `false` at the EARLIEST populated slot
1055 /// whose kind is NOT `kind`, and returns `true` iff the
1056 /// sweep completes with `kind` seen as the sole populated
1057 /// slot. Byte-for-byte cheaper than either widened
1058 /// composition `self.unique_populated_kind() ==
1059 /// Some(kind)` (which walks until the SECOND populated
1060 /// slot) or `self.has(kind) &&
1061 /// self.has_unique_populated_kind()` (which walks the
1062 /// closed set twice) on every arm where the parent
1063 /// carries a populated slot that isn't `kind`.
1064 ///
1065 /// # Sibling to [`Self::has`]
1066 ///
1067 /// Kind-scoped strict-refinement peer: `has(kind)` is the
1068 /// SUBSET predicate; `has_only(kind)` is the EQUAL
1069 /// predicate. The implication
1070 /// `has_only(kind) → has(kind)` binds the pair on the
1071 /// strict-refinement axis. The composition law
1072 /// `parent.has_only(kind) ==
1073 /// (parent.unique_populated_kind() == Some(kind))` is
1074 /// pinned as a first-class typed invariant by the trait's
1075 /// own default body and swept substrate-wide by
1076 /// [`crate::tagged_union::assert_has_only_matches_unique_populated_kind`].
1077 pub fn has_only(&self, kind: $kind) -> bool {
1078 <Self as $crate::tagged_union::TaggedUnion>::has_only(self, kind)
1079 }
1080
1081 /// Closed-set-complement peer of [`Self::has_only`] —
1082 /// `true` iff the given `kind` is MISSING AND no OTHER slot
1083 /// on this tagged union is missing.
1084 ///
1085 /// One-line inherent forwarder that delegates the fused
1086 /// short-circuit walk to the substrate primitive
1087 /// [`crate::tagged_union::TaggedUnion::lacks_only`], whose
1088 /// default body walks
1089 /// `<Self::Kind as ClosedSet>::ALL` under a negated
1090 /// [`crate::tagged_union::TaggedUnion::has`] and returns
1091 /// `false` at the EARLIEST missing slot whose kind is not
1092 /// `kind`. Byte-for-byte cheaper than either widened
1093 /// composition
1094 /// `self.unique_missing_kind() == Some(kind)` (which walks
1095 /// until the SECOND missing slot before comparing) or
1096 /// `!self.has(kind) && self.has_unique_missing_kind()`
1097 /// (two closed-set walks) on every arm where the parent
1098 /// carries a missing slot that isn't `kind`.
1099 ///
1100 /// # Sibling to [`Self::has_only`]
1101 ///
1102 /// Closed-set-complement peer: `has_only(kind)` names
1103 /// parents whose SOLE populated slot is `kind`;
1104 /// `lacks_only(kind)` names parents whose SOLE missing slot
1105 /// is `kind`. The composition law
1106 /// `parent.lacks_only(kind) ==
1107 /// (parent.unique_missing_kind() == Some(kind))` and the
1108 /// cardinality-refinement law
1109 /// `parent.lacks_only(kind) == (!parent.has(kind) &&
1110 /// parent.has_unique_missing_kind())` are pinned as first-
1111 /// class typed invariants by the trait's own default body
1112 /// and swept substrate-wide by
1113 /// [`crate::tagged_union::assert_lacks_only_matches_unique_missing_kind`].
1114 pub fn lacks_only(&self, kind: $kind) -> bool {
1115 <Self as $crate::tagged_union::TaggedUnion>::lacks_only(self, kind)
1116 }
1117 }
1118
1119 impl $crate::tagged_union::VariantSelector<$parent> for $kind {
1120 type Variant<'a> = $variant<'a>;
1121 fn select<'a>(self, parent: &'a $parent) -> ::std::option::Option<$variant<'a>>
1122 where
1123 Self: 'a,
1124 {
1125 <$kind>::select(self, parent)
1126 }
1127 }
1128
1129 impl $crate::tagged_union::TaggedUnion for $parent {
1130 type Kind = $kind;
1131 type Error = $err;
1132 const KIND_LIST: &'static str = $kind_list;
1133 }
1134 };
1135}
1136
1137/// Project the borrowed-view of a tagged-union variant addressed by
1138/// this closed-set discriminator.
1139///
1140/// Companion trait to [`TaggedUnion`] — binds a `Kind` closed-set to
1141/// the parent `P` it discriminates AND to the borrowed-view
1142/// [`Self::Variant<'a>`] the resolver hands out. Every one of the
1143/// four production `.variant()` sites on `ProcessSpec`
1144/// ([`crate::intent::Intent`], [`crate::encapsulates::EncapsulationKind`],
1145/// [`crate::export::ArtifactSource`], [`crate::export::VectorChannel`])
1146/// pre-lift restated the same
1147/// `Self::Kind::ALL.into_iter().map(|k| k.select(self))` sweep body
1148/// verbatim at its inherent `.variant()`. Post-lift the trait binds
1149/// `(k.select(self), Variant<'a>)` onto ONE typed contract per Kind
1150/// so [`TaggedUnion::variant`]'s default body can dispatch the sweep
1151/// generically — the four sibling inherent bodies collapse to
1152/// one-line delegations and a fifth sibling picks up the sweep for
1153/// free through ONE `impl VariantSelector` block.
1154///
1155/// The GAT `Variant<'a>` carries the parent's lifetime so a borrowed
1156/// view projected from `&'a P` composes typed with the resolver's
1157/// short-circuit — every projection stays a compile-time refinement,
1158/// no `Box<dyn ...>` erasure. The GAT is additionally bound to
1159/// [`VariantKind<Self>`] so every implementor's borrowed view knows
1160/// its addressing Kind — the reverse projection of [`Self::select`]
1161/// closed at compile-time so a fifth sibling that adds `impl
1162/// VariantSelector` without opening the peer `impl VariantKind` fails
1163/// at the trait bound, not later at a per-consumer round-trip test.
1164pub trait VariantSelector<P: ?Sized>: Copy + 'static {
1165 /// The borrowed-view enum returned by the parent's inherent
1166 /// `.variant()` method — one arm per closed-set variant, each
1167 /// arm carrying a `&'a` reference into the parent's populated
1168 /// slot. Bound generically here so [`TaggedUnion::variant`]'s
1169 /// default body can name the return type without restating it
1170 /// per parent. Additionally bound to [`VariantKind<Self>`] so
1171 /// the reverse projection `Variant<'a> → Self` is closed at the
1172 /// trait boundary — every implementor's borrowed view knows its
1173 /// addressing Kind through ONE typed contract, and the substrate
1174 /// testkit [`assert_variant_round_trip`] composes `select`
1175 /// (forward) with `variant_kind` (reverse) generically.
1176 type Variant<'a>: VariantKind<Self>
1177 where
1178 P: 'a,
1179 Self: 'a;
1180
1181 /// Project a `&'a P` borrow into the optional typed variant view
1182 /// for `self` (the addressed discriminator). Returns `None` iff
1183 /// the matching slot on `P` is `None`. Composes the closed-set
1184 /// sweep [`TaggedUnion::variant`] loops over.
1185 fn select<'a>(self, parent: &'a P) -> Option<Self::Variant<'a>>
1186 where
1187 Self: 'a;
1188}
1189
1190/// Reverse projection — every borrowed-variant view enum knows its
1191/// closed-set `K` discriminator.
1192///
1193/// Dual of [`VariantSelector<P>::select`] on the addressed Kind:
1194/// where the selector projects a parent borrow forward into an
1195/// optional Variant, this trait projects a populated Variant back
1196/// into the Kind that addresses it. Together they compose the
1197/// round-trip contract every tagged-union `.variant()` site pins
1198/// via the substrate testkit [`assert_variant_round_trip`]:
1199/// `k.select(&parent).map(|v| v.variant_kind()) == Some(k)` on the
1200/// populated side, and `parent.variant().unwrap().variant_kind() == k`
1201/// through the [`TaggedUnion::variant`] resolver's default body.
1202///
1203/// Every borrowed-view enum on `ProcessSpec`'s tagged-union axis
1204/// ([`crate::intent::IntentVariant<'_>`],
1205/// [`crate::lifetime::LifetimeVariant<'_>`],
1206/// [`crate::encapsulates::EncapsulationKindVariant<'_>`],
1207/// [`crate::export::ArtifactVariant<'_>`],
1208/// [`crate::export::ChannelVariant<'_>`]) pre-lift restated the same
1209/// `match self { Self::A(_) => K::A, Self::B(_) => K::B, ... }`
1210/// per-arm mapping at its own inherent method (named `.kind()` on
1211/// four of five sites; `.target()` on
1212/// [`crate::encapsulates::EncapsulationKindVariant`] where the
1213/// discriminator's semantic role is a target of encapsulation, not
1214/// a kind of parent). The reverse-projection body must stay
1215/// per-implementor — it names the ground-truth arm-to-Kind mapping
1216/// only the site knows — but the CONTRACT lives at ONE typed
1217/// surface so:
1218///
1219/// * Every downstream generic consumer binds through
1220/// `<T::Variant<'_> as VariantKind<T::Kind>>::variant_kind(&v)`
1221/// instead of a per-parent inherent-method restatement.
1222/// * [`VariantSelector<P>::Variant<'a>`] bounds this trait — a
1223/// fifth sibling that adds `impl VariantSelector<P> for XKind`
1224/// without the peer `impl VariantKind<XKind> for XVariant<'_>`
1225/// fails at the associated-type bound, so the reverse projection
1226/// is closed at compile-time across every implementor.
1227/// * The generic testkit [`assert_variant_round_trip`] composes
1228/// `select` (forward) with `variant_kind` (reverse) at ONE
1229/// substrate site — the four sibling
1230/// `_kind_round_trips_through_variant_kind` /
1231/// `_target_round_trips_through_variant_target` test bodies
1232/// collapse to one-line invocations.
1233///
1234/// The trait method is named [`Self::variant_kind`] rather than
1235/// `kind` to avoid shadowing the inherent `.kind()` (or
1236/// `.target()`) methods each borrowed-view enum already publishes.
1237/// Every impl body is a one-line delegation to the site's inherent
1238/// method — the substrate stays the projection, not the mapping.
1239pub trait VariantKind<K: Copy + 'static> {
1240 /// Project a borrowed-variant view back into its addressing
1241 /// closed-set `K` discriminator. Round-trips the closed set on
1242 /// the populated side against [`VariantSelector::select`] — a
1243 /// value returned by `k.select(&parent).unwrap()` must satisfy
1244 /// `variant_kind() == k`, and a value returned by
1245 /// `parent.variant().unwrap()` must satisfy `variant_kind() ==
1246 /// k` for the populated slot's `k`.
1247 fn variant_kind(&self) -> K;
1248}
1249
1250/// Generic round-trip testkit — pins that
1251/// [`VariantSelector::select`] (forward projection) and
1252/// [`VariantKind::variant_kind`] (reverse projection) compose the
1253/// closed set in both directions on the populated side.
1254///
1255/// Substrate primitive for the four sibling
1256/// `_kind_round_trips_through_variant_kind` /
1257/// `_target_round_trips_through_variant_target` tests on
1258/// `ProcessSpec` ([`crate::intent::Intent`],
1259/// [`crate::encapsulates::EncapsulationKind`],
1260/// [`crate::export::ArtifactSource`],
1261/// [`crate::export::VectorChannel`]) that pre-lift each restated the
1262/// same two-arm round-trip probe at their own test bodies:
1263///
1264/// 1. For each `k in K::ALL`, construct a parent with only slot `k`
1265/// populated (via a site-local `single_slot_X(k) -> Parent`
1266/// helper).
1267/// 2. Assert that `k.select(&parent).unwrap().variant_kind() == k`
1268/// (the forward-then-reverse round-trip).
1269/// 3. Assert that `parent.variant().unwrap().variant_kind() == k`
1270/// (the resolver-then-reverse round-trip).
1271///
1272/// Post-lift each site's round-trip test collapses to ONE
1273/// `assert_variant_round_trip::<T, _>(single_slot_X)` invocation
1274/// whose body is the substrate primitive's own dispatch. A fifth
1275/// sibling picks up the round-trip check through ONE call site.
1276///
1277/// The `make_parent` closure stays per-site — every one of the four
1278/// production sites already owns a
1279/// `single_slot_intent(k) / single_slot_source(k) /
1280/// single_slot_channel(k) / single_slot_kind(t)` helper that
1281/// constructs a minimally-valid parent with the addressed slot's
1282/// inner spec populated; the closure IS the round-trip's ground
1283/// truth for "populate slot k", and lifting it into the primitive
1284/// would collapse the per-site construction knowledge that stays
1285/// deliberately local.
1286///
1287/// The [`crate::lifetime::Lifetime`] site is DELIBERATELY excluded
1288/// — `Lifetime` doesn't impl [`TaggedUnion`] (its `variant()` returns
1289/// `Ok(Permanent)` on empty, not an `Empty` typed error), so the
1290/// `<T: TaggedUnion>` bound doesn't reach it. Its per-site
1291/// round-trip test binds through [`VariantKind`] directly on
1292/// [`crate::lifetime::LifetimeVariant`] instead.
1293#[track_caller]
1294pub fn assert_variant_round_trip<T, F>(make_parent: F)
1295where
1296 T: TaggedUnion,
1297 T::Kind: PartialEq + std::fmt::Debug,
1298 F: Fn(T::Kind) -> T,
1299{
1300 for k in <T::Kind as tatara_closed_set::ClosedSet>::ALL
1301 .iter()
1302 .copied()
1303 {
1304 let parent = make_parent(k);
1305 let selected = k.select(&parent).unwrap_or_else(|| {
1306 panic!("VariantSelector::select must return Some for populated slot {k:?}")
1307 });
1308 assert_eq!(
1309 <<T::Kind as VariantSelector<T>>::Variant<'_> as VariantKind<T::Kind>>::variant_kind(
1310 &selected,
1311 ),
1312 k,
1313 "select→variant_kind round-trip failed for {k:?}",
1314 );
1315 let resolved = parent.variant().ok().unwrap_or_else(|| {
1316 panic!("TaggedUnion::variant must resolve exactly-one populated for {k:?}")
1317 });
1318 assert_eq!(
1319 <<T::Kind as VariantSelector<T>>::Variant<'_> as VariantKind<T::Kind>>::variant_kind(
1320 &resolved,
1321 ),
1322 k,
1323 "variant()→variant_kind resolver disagreed on {k:?}",
1324 );
1325 }
1326}
1327
1328/// Declarative surface that names the (Kind, Error, KIND_LIST) triple
1329/// a tagged-union `.variant()` site publishes to the substrate — and
1330/// provides the sweep body as ONE default method every implementor
1331/// picks up for free.
1332///
1333/// Every one of the four production `.variant()` sites on `ProcessSpec`
1334/// ([`crate::intent::Intent`], [`crate::encapsulates::EncapsulationKind`],
1335/// [`crate::export::ArtifactSource`], [`crate::export::VectorChannel`])
1336/// exposes the SAME three-piece surface: a closed-set discriminator
1337/// [`Self::Kind`], a typed [`Self::Error`] carrier that projects onto
1338/// the shared [`TaggedUnionError`] contract, and a slash-joined
1339/// operator diagnostic literal [`Self::KIND_LIST`]. Pre-lift the
1340/// triple lived on each parent type as independent inherent items —
1341/// the (Kind, Error) types cross-referenced only by module-doc prose,
1342/// the `KIND_LIST` `&'static str` maintained separately at each site
1343/// alongside the inherent `.variant()` body. Post-lift the trait
1344/// binds the three onto ONE typed contract per parent so downstream
1345/// generic code binds to `<T: TaggedUnion>` instead of restating the
1346/// per-parent quadruple of associated names.
1347///
1348/// The [`Self::variant`] default method is the substrate primitive
1349/// every inherent `.variant()` on the four production sites delegates
1350/// to — one-line inherent forwarders preserve the load-bearing
1351/// calling convention (so no downstream callsite needs
1352/// `use crate::tagged_union::TaggedUnion` to reach `.variant()`) while
1353/// the resolve-sweep body lives at ONE substrate site. Adding a fifth
1354/// sibling means ONE `impl TaggedUnion` block + ONE
1355/// `impl VariantSelector<Self>` block on the sibling `Kind` + ONE
1356/// one-line inherent forwarder — no re-authored 5-line
1357/// `resolve_or_err(K::ALL.into_iter().map(|k| k.select(self)),
1358/// KIND_LIST)` sweep body.
1359///
1360/// The `Kind` type is bound to [`tatara_closed_set::ClosedSet`] so
1361/// generic testkit primitives (starting with
1362/// [`assert_kind_list_matches_closed_set`]) can compose
1363/// `<Self::Kind as ClosedSet>::labels_joined("/")` against
1364/// [`Self::KIND_LIST`] byte-identically across every implementor —
1365/// the diagnostic-stability invariant every sibling pre-lift pinned
1366/// through a hand-rolled per-site test body. It is additionally
1367/// bound to [`VariantSelector<Self>`] so [`Self::variant`]'s default
1368/// body reaches `k.select(self)` generically.
1369///
1370/// The [`crate::lifetime::Lifetime`] site is DELIBERATELY not routed
1371/// through this trait — its `variant()` returns `Ok(Permanent)` on
1372/// empty rather than an `Empty` typed error, so its projection shape
1373/// diverges from the four Empty-projecting siblings. Same reasoning
1374/// as [`resolve_or_err`]'s explicit exclusion of `Lifetime`.
1375pub trait TaggedUnion: Sized {
1376 /// The closed-set discriminator over this tagged-union's variants.
1377 /// Bound to [`tatara_closed_set::ClosedSet`] so the generic
1378 /// diagnostic-stability testkit ([`assert_kind_list_matches_closed_set`])
1379 /// can project `<Self::Kind as ClosedSet>::labels_joined("/")`
1380 /// against [`Self::KIND_LIST`] byte-identically. Additionally
1381 /// bound to [`VariantSelector<Self>`] so [`Self::variant`]'s
1382 /// default body can dispatch `k.select(self)` at each
1383 /// [`ClosedSet::ALL`] entry generically.
1384 type Kind: tatara_closed_set::ClosedSet + VariantSelector<Self>;
1385
1386 /// The typed error carrier returned by the parent's inherent
1387 /// `.variant()` method — projects onto the shared
1388 /// [`TaggedUnionError`] contract so [`resolve_or_err`]'s two-arm
1389 /// dispatch reaches every implementor uniformly.
1390 type Error: TaggedUnionError;
1391
1392 /// Slash-joined operator diagnostic literal — the payload of
1393 /// [`TaggedUnionError::empty`] when no slot is populated on this
1394 /// tagged union. Pinned against
1395 /// `<Self::Kind as tatara_closed_set::ClosedSet>::labels_joined("/")`
1396 /// by [`assert_kind_list_matches_closed_set`] so a variant added
1397 /// to `Self::Kind` without updating this constant (or a renamed
1398 /// variant) fails-loudly at the testkit boundary.
1399 const KIND_LIST: &'static str;
1400
1401 /// Sweep over every [`Self::Kind`] discriminator in
1402 /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) order,
1403 /// projecting each into the parent's borrowed variant view via
1404 /// [`VariantSelector::select`], and resolve to exactly one populated
1405 /// variant through [`resolve_or_err`]. Errors on zero (with
1406 /// [`Self::KIND_LIST`] carried on the [`TaggedUnionError::empty`]
1407 /// arm) or many.
1408 ///
1409 /// The substrate primitive every one of the four production
1410 /// `.variant()` sites on `ProcessSpec` dispatches through — the
1411 /// per-parent inherent `.variant()` is a one-line delegation to
1412 /// this default so the calling convention (`intent.variant()`,
1413 /// `channel.variant()`, ...) stays load-bearing at the callsite
1414 /// without every consumer picking up `use TaggedUnion`.
1415 ///
1416 /// Adding a fifth sibling picks up this body for free — no
1417 /// re-authored `resolve_or_err(...)` sweep at the impl block.
1418 fn variant(&self) -> Result<<Self::Kind as VariantSelector<Self>>::Variant<'_>, Self::Error> {
1419 resolve_or_err(
1420 <Self::Kind as tatara_closed_set::ClosedSet>::ALL
1421 .iter()
1422 .copied()
1423 .map(|k| k.select(self)),
1424 Self::KIND_LIST,
1425 )
1426 }
1427
1428 /// Widened peer of [`Self::has`] — projects a `&'a Self` borrow
1429 /// into the optional borrowed-variant view addressed by `kind`,
1430 /// or `None` when the matching slot on `Self` is empty.
1431 ///
1432 /// One-liner that delegates to [`VariantSelector::select`] on the
1433 /// closed-set discriminator; the substrate primitive both
1434 /// [`Self::has`] (via the default `self.find(kind).is_some()`
1435 /// body) and future diagnostic consumers (an operator-facing
1436 /// require-tag classifier that reads the populated slot's inner
1437 /// payload for a `param.key=value` message, a coherence check
1438 /// that projects the borrowed variant into its
1439 /// [`VariantKind::variant_kind`] Kind for round-trip validation
1440 /// without going through the resolver's Empty/Ambiguous carriers)
1441 /// compose against.
1442 ///
1443 /// # Sibling to [`Self::has`]
1444 ///
1445 /// One refinement wider: `has` collapses the return to a `bool`;
1446 /// `find` returns the matching borrowed [`VariantSelector::Variant`]
1447 /// so callers can read the populated slot's inner spec without
1448 /// re-projecting through `kind.select(self)` at the callsite (and
1449 /// without pulling `use VariantSelector` into scope). The default
1450 /// body of `has` is `self.find(kind).is_some()` — the two methods
1451 /// share ONE walk semantics by construction, so a regression that
1452 /// drifted the presence probe from the widened probe becomes
1453 /// structurally impossible past the trait boundary.
1454 ///
1455 /// # Peer to [`crate::boundary::ConditionSliceExt::find_kind`]
1456 ///
1457 /// Same shape, same axis, second instance in the workspace-wide
1458 /// `(K) -> Option<&V>` widened presence-probe algebra:
1459 /// [`ConditionSliceExt::find_kind`] returns `Option<&Condition>`
1460 /// on the slice-level ONE-shape probe; `find` here returns
1461 /// `Option<Variant<'_>>` on the tagged-union parent-level
1462 /// N-slot probe. Both refine their `has_kind` / `has` bool peer
1463 /// through the same `find(...).is_some()` composition law.
1464 ///
1465 /// # Semantics
1466 ///
1467 /// Returns `Some(v)` where `v` is the borrowed-view projection of
1468 /// the populated slot addressed by `kind`, or `None` iff that
1469 /// slot is `None`. Byte-for-byte equivalent to
1470 /// `kind.select(self)`; existing `k.select(&parent)` callsites
1471 /// route through this inherent surface after the macro-emitted
1472 /// forwarder lands.
1473 fn find(&self, kind: Self::Kind) -> Option<<Self::Kind as VariantSelector<Self>>::Variant<'_>> {
1474 kind.select(self)
1475 }
1476
1477 /// Presence probe — does this tagged union carry a populated
1478 /// slot addressed by the given closed-set discriminator?
1479 ///
1480 /// Default body: `self.find(kind).is_some()`. The presence half
1481 /// of the resolve contract, without allocating an [`Self::Error`]
1482 /// carrier when the caller only needs the yes/no answer.
1483 /// Substrate primitive for closed-set-driven dispatch tables
1484 /// (e.g. tatara-check's `intent-<kind>` requires-tag sweep) where
1485 /// a hand-authored per-slot `spec.<field>.is_some()` chain
1486 /// otherwise drifts from the
1487 /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL)
1488 /// enumeration as new variants land.
1489 ///
1490 /// Every one of the four production `.variant()` sites on
1491 /// `ProcessSpec` picks this up for free through the trait default
1492 /// — the [`declare_tagged_union_impls!`] macro emits a one-line
1493 /// inherent forwarder so `intent.has(kind)` reads at consumer
1494 /// callsites without `use TaggedUnion`. Adding a fifth sibling
1495 /// picks up the presence probe with zero re-authored body.
1496 fn has(&self, kind: Self::Kind) -> bool {
1497 self.find(kind).is_some()
1498 }
1499
1500 /// Closed-set-complement peer of [`Self::has`] — `true` iff the
1501 /// given `kind` is MISSING (its slot on this tagged union is
1502 /// empty). The definitional dual of the presence probe on the
1503 /// MISSING axis.
1504 ///
1505 /// Default body: `!self.has(kind)`. One bit-flip; the primitive
1506 /// value here is naming — every consumer that reads "the missing
1507 /// set contains `kind`" or "the parent lacks this dependency"
1508 /// gets a first-class typed predicate whose call-site text reads
1509 /// correctly on the missing axis, without inverting the reader's
1510 /// parse of `!parent.has(...)` at every site.
1511 ///
1512 /// # Sibling to [`Self::has`]
1513 ///
1514 /// Closed-set-complement peer on the (populated, missing)
1515 /// duality: `has(kind)` names parents whose POPULATED set
1516 /// contains `kind`; `lacks(kind)` names parents whose MISSING
1517 /// set contains `kind`. The definitional complement law
1518 /// `lacks(kind) == !has(kind)` holds on every arm and every kind
1519 /// — pinned as a first-class typed invariant by the trait's own
1520 /// default body and swept substrate-wide by
1521 /// [`assert_lacks_matches_has_complement`].
1522 ///
1523 /// # Sibling to [`Self::lacks_only`]
1524 ///
1525 /// Kind-scoped strict-refinement peer on the MISSING axis:
1526 /// `lacks(kind)` is the SUBSET predicate (`kind` missing, maybe
1527 /// others too); `lacks_only(kind)` is the EQUAL predicate
1528 /// (`kind` missing AND ONLY `kind`). The implication
1529 /// `lacks_only(kind) → lacks(kind)` binds the pair on the
1530 /// strict-refinement axis — byte-for-byte missing-axis peer of
1531 /// the populated-axis `has_only(kind) → has(kind)` implication.
1532 /// Together with `has(kind)`, `has_only(kind)`, and
1533 /// `lacks_only(kind)` the four predicates close the 2×2
1534 /// (populated, missing) × (subset, equal) grid on the
1535 /// kind-scoped tagged-union axis.
1536 ///
1537 /// # Truth table on the exactly-one-slot tagged-union contract
1538 ///
1539 /// For a tagged union with `<Self::Kind as ClosedSet>::ALL` of
1540 /// cardinality `N ≥ 2` and a fixed argument `kind`:
1541 ///
1542 /// - Empty parent (0 populated, N missing): `true` — every kind
1543 /// is missing, so any `kind` satisfies the predicate.
1544 /// - Well-formed parent with `kind` populated (1 populated ==
1545 /// kind): `false` — the populated slot addresses `kind`, so
1546 /// `kind` is not missing.
1547 /// - Well-formed parent with OTHER kind populated (1 populated
1548 /// != kind): `true` — the sole populated slot is not `kind`,
1549 /// so `kind` is missing.
1550 /// - Saturated parent (N populated, 0 missing): `false` — every
1551 /// kind is populated, so `kind` is not missing.
1552 ///
1553 /// # Kind-domain cardinality
1554 ///
1555 /// `<Self::Kind as ClosedSet>::ALL.iter().filter(|k| parent.lacks(*k)).count()
1556 /// == parent.missing_kind_count()` — the count of kinds
1557 /// satisfying `lacks` on any arm is exactly the parent's
1558 /// missing-slot count. Closed-set-complement peer of the
1559 /// populated-axis law `count k where has(k) ==
1560 /// populated_kind_count()`. Binds the kind-scoped SUBSET
1561 /// primitive on the missing axis to the arg-less cardinality
1562 /// scalar at ONE substrate site.
1563 ///
1564 /// # Compounding future consumers
1565 ///
1566 /// - Any consumer whose semantic reading is "the missing set
1567 /// contains this kind" — a "still missing: <kind>" diagnostic,
1568 /// a `lacks-<kind>` require-tag classifier arm, a
1569 /// dependency-satisfaction check — reads `parent.lacks(kind)`
1570 /// through the inherent surface rather than negating
1571 /// `parent.has(kind)` at the call site. The primitive costs
1572 /// one bit-flip past [`Self::has`]; the reader-facing win is
1573 /// that `!parent.has(k)` no longer needs to be re-parsed as
1574 /// "the missing set contains k" at every missing-axis call
1575 /// site.
1576 /// - The kind-scoped implication
1577 /// `lacks_only(kind) → lacks(kind)` becomes a first-class
1578 /// typed law binding [`Self::lacks_only`] to `lacks` on the
1579 /// strict-refinement axis — byte-for-byte missing-axis peer
1580 /// of `has_only(kind) → has(kind)`.
1581 ///
1582 /// A new [`Self::Kind`] variant added to
1583 /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) reaches
1584 /// this primitive mechanically through the delegated
1585 /// [`Self::has`] — the closed-set walk extended by
1586 /// [`Self::has`]'s default body composition picks up the new
1587 /// slot at every downstream callsite without further per-caller
1588 /// edit.
1589 ///
1590 /// # Theory grounding
1591 ///
1592 /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
1593 /// The closed-set-complement projection lives at ONE substrate
1594 /// site as a definitional negation of [`Self::has`]. The
1595 /// complement law `lacks(kind) == !has(kind)` and the
1596 /// kind-scoped implication `lacks_only(kind) → lacks(kind)`
1597 /// are pinned across every production tagged union at compile
1598 /// time via the trait's default body composition, not
1599 /// per-parent.
1600 /// - THEORY.md §VI.1 — generation over composition. A new
1601 /// [`Self::Kind`] variant added to `ALL` reaches this
1602 /// primitive mechanically through the delegated [`Self::has`]
1603 /// — every downstream consumer sees the widened kind set
1604 /// without further per-caller edit.
1605 fn lacks(&self, kind: Self::Kind) -> bool {
1606 !self.has(kind)
1607 }
1608
1609 /// Closed-set-inversion refinement — enumerate the set of
1610 /// [`Self::Kind`] discriminators whose corresponding slot on
1611 /// `self` is populated, in canonical
1612 /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) order.
1613 ///
1614 /// Default body:
1615 /// `<Kind as ClosedSet>::ALL.iter().copied().filter(|k| self.has(*k)).collect()`.
1616 /// A tagged-union parent that satisfies the exactly-one-slot
1617 /// contract returns a `Vec` of length 0 (empty parent — matches
1618 /// [`Self::variant`]'s `Empty` arm) or 1 (well-formed — matches
1619 /// the `Ok` arm); a malformed parent with multiple populated
1620 /// slots returns a `Vec` of length ≥ 2 in canonical `ALL` order
1621 /// (matches the `Ambiguous` arm and NAMES which slots are
1622 /// populated, unlike the payload-free `Ambiguous` carrier).
1623 ///
1624 /// # Sibling to [`Self::has`] / [`Self::find`]
1625 ///
1626 /// One refinement wider on the ORTHOGONAL axis: `has(k) / find(k)`
1627 /// fix a `Self::Kind` and vary the return type (`bool` /
1628 /// `Option<Variant>`); this refinement INVERTS the axis by fixing
1629 /// the parent and varying over `Kind::ALL`, returning the SET of
1630 /// populated kinds. The composition law
1631 /// `populated_kinds().contains(&k) == has(k)` for every
1632 /// `k ∈ Kind::ALL` binds the two axes structurally through the
1633 /// default body — a regression that overrode `populated_kinds`
1634 /// to skip a kind, return duplicates, or drift the walk order
1635 /// surfaces at the substrate testkit
1636 /// [`assert_populated_kinds_matches_has`].
1637 ///
1638 /// # Peer to [`crate::boundary::ConditionSliceExt::distinct_kinds`]
1639 ///
1640 /// Same shape, same axis, second instance in the workspace-wide
1641 /// closed-set-inversion refinement algebra:
1642 /// [`ConditionSliceExt::distinct_kinds`] returns
1643 /// `Vec<ConditionKind>` on the slice-level presence-probe axis
1644 /// (fixes the slice, varies over `ConditionKind::ALL`);
1645 /// `populated_kinds` here returns `Vec<Self::Kind>` on the
1646 /// tagged-union parent-level presence-probe axis (fixes the
1647 /// parent, varies over `<Self::Kind as ClosedSet>::ALL`). Both
1648 /// refine their `has(k) / has_kind(k)` bool peer through the
1649 /// same `ALL.filter(has).collect()` composition law.
1650 ///
1651 /// # Compounding future consumers
1652 ///
1653 /// - An operator-facing `Ambiguous(Vec<Kind>)` diagnostic that
1654 /// NAMES which slots collide (upgrading the payload-free
1655 /// [`TaggedUnionError::ambiguous`] carrier without touching the
1656 /// resolver's short-circuit) reads `parent.populated_kinds()`
1657 /// directly on the malformed arm.
1658 /// - A closed-set audit dispatcher that enumerates every
1659 /// populated slot for a fleet-wide "which parents carry
1660 /// {Container, Nix, Aplicacao}" query reaches ONE substrate
1661 /// primitive rather than paying for a per-kind `has(k)` sweep
1662 /// at every callsite.
1663 /// - A hypothetical `populated-kind-count-<n>` require-tag
1664 /// classifier prefix family that publishes the populated-set
1665 /// cardinality as a scalar reads `parent.populated_kinds().len()`.
1666 ///
1667 /// A new [`Self::Kind`] variant added to
1668 /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) reaches
1669 /// this primitive mechanically (the closed-set walk picks up the
1670 /// new entry) and every downstream consumer sees the wider set
1671 /// without further per-caller edit.
1672 ///
1673 /// # Theory grounding
1674 ///
1675 /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
1676 /// The closed-set-inversion refinement lives at ONE substrate
1677 /// site as a typed projection of [`Self::has`] over the closed
1678 /// set `<Self::Kind as ClosedSet>::ALL`. Every downstream
1679 /// aggregate consumer binds through the SAME shape rather
1680 /// than restating the `ALL`-filter closure body.
1681 /// - THEORY.md §VI.1 — generation over composition. A new
1682 /// [`Self::Kind`] variant added to `ALL` reaches this primitive
1683 /// mechanically and every downstream consumer sees the wider
1684 /// set with no per-caller edit.
1685 fn populated_kinds(&self) -> ::std::vec::Vec<Self::Kind> {
1686 self.iter_populated_kinds().collect()
1687 }
1688
1689 /// Zero-allocation iterator peer of [`Self::populated_kinds`] —
1690 /// walk [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) in
1691 /// canonical order and yield every Kind whose corresponding slot
1692 /// on `self` is populated, WITHOUT materializing an intermediate
1693 /// [`Vec`].
1694 ///
1695 /// Default body:
1696 /// `<Self::Kind as ClosedSet>::ALL.iter().copied().filter(|&k| self.has(k))`.
1697 /// The composition law
1698 /// `populated_kinds() == iter_populated_kinds().collect::<Vec<_>>()`
1699 /// holds by construction — [`Self::populated_kinds`]'s default
1700 /// body IS `self.iter_populated_kinds().collect()`, so a caller
1701 /// that overrides the widened Vec primitive with a divergent walk
1702 /// simultaneously drifts both surfaces (surfacing at the substrate
1703 /// testkit [`assert_iter_populated_kinds_matches_populated_kinds`]
1704 /// which pins the Vec projection equals `iter().collect()`).
1705 ///
1706 /// # Sibling to [`Self::populated_kinds`] / [`Self::populated_kind_count`]
1707 ///
1708 /// Load-bearing iterator peer of the closed-set-inversion axis —
1709 /// where `populated_kinds` returns the SET (heap-allocated `Vec`,
1710 /// canonical `ClosedSet::ALL` order) and `populated_kind_count`
1711 /// scalar-projects its cardinality, `iter_populated_kinds` opens
1712 /// the walk as a `Copy` iterator so consumers that need a
1713 /// short-circuiting fold (`.any(|k| pred(k))`, `.find(|&k|
1714 /// pred(k))`, `.take_while(|k| pred(k))`, `.map(|k| project(k))`)
1715 /// avoid the intermediate allocation entirely.
1716 ///
1717 /// # Peer to [`Self::iter_missing_kinds`]
1718 ///
1719 /// Closed-set-COMPLEMENT peer under a NEGATED point-probe. The two
1720 /// iterators PARTITION `ClosedSet::ALL`:
1721 /// `iter_populated_kinds().chain(iter_missing_kinds()).collect::<HashSet<_>>()`
1722 /// equals `<Self::Kind as ClosedSet>::ALL.iter().copied().collect()`,
1723 /// and the two iterators yield disjoint element sets.
1724 ///
1725 /// # Compounding future consumers
1726 ///
1727 /// - Every scalar closed-set-inversion peer already at the trait
1728 /// (`populated_kind_count`, `first_populated_kind`,
1729 /// `last_populated_kind`, `unique_populated_kind`, `is_empty`,
1730 /// `has_any_populated_kind`, `has_unique_populated_kind`,
1731 /// `has_multiple_populated_kinds`, `has_at_most_one_populated_kind`,
1732 /// `has_only`) folds a specialization of
1733 /// `<Kind::ALL>.iter().copied().filter(|k| self.has(*k))` —
1734 /// they can now compose over `iter_populated_kinds()` at ONE
1735 /// substrate site rather than restating the closed-set walk
1736 /// body per peer. A future run's `iter_populated_kinds`-fold
1737 /// refactor at those peers collapses ≥ 9 walk bodies onto ONE
1738 /// substrate primitive.
1739 /// - A new kind-cardinality peer (e.g. a hypothetical
1740 /// `populated-kind-count-<n>` require-tag classifier that returns
1741 /// the FIRST N populated kinds without allocating) reaches
1742 /// `parent.iter_populated_kinds().take(n)` at ONE call site,
1743 /// without the `Vec<Kind>` allocation-then-slice overhead
1744 /// `populated_kinds().into_iter().take(n).collect()` pays.
1745 /// - A downstream diagnostic composer (an operator-facing
1746 /// "populated: [{}]" message that streams the label list into a
1747 /// `write!` buffer) reads
1748 /// `parent.iter_populated_kinds().map(|k| k.label())` and folds
1749 /// through `itertools::join` without the allocation `Vec<Kind>
1750 /// -> String` pays.
1751 ///
1752 /// # Theory grounding
1753 ///
1754 /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
1755 /// The load-bearing iterator projection lives at ONE substrate
1756 /// site; every downstream aggregate consumer refines it through
1757 /// a standard-library iterator fold rather than restating the
1758 /// `Kind::ALL`-walk closure body.
1759 /// - THEORY.md §VI.1 — generation over composition. A new
1760 /// [`Self::Kind`] variant added to `ALL` reaches the walk
1761 /// mechanically (the closed-set filter picks up the new entry)
1762 /// and every downstream fold sees the wider set without further
1763 /// per-caller edit.
1764 fn iter_populated_kinds(&self) -> impl Iterator<Item = Self::Kind> + '_ {
1765 <Self::Kind as tatara_closed_set::ClosedSet>::ALL
1766 .iter()
1767 .copied()
1768 .filter(|&k| self.has(k))
1769 }
1770
1771 /// Scalar cardinality refinement on the closed-set-inversion axis —
1772 /// the number of [`Self::Kind`] discriminators whose corresponding
1773 /// slot on `self` is populated.
1774 ///
1775 /// Default body:
1776 /// `<Self::Kind as ClosedSet>::ALL.iter().copied().filter(|k| self.has(*k)).count()`
1777 /// — a closed-set walk that composes against [`Self::has`] per
1778 /// variant WITHOUT materializing an intermediate `Vec`. A tagged-
1779 /// union parent that satisfies the exactly-one-slot contract
1780 /// returns `0` (empty — matches [`Self::variant`]'s `Empty` arm),
1781 /// `1` (well-formed — matches the `Ok` arm), or `≥ 2` (malformed
1782 /// — matches the `Ambiguous` arm) exactly aligned with
1783 /// [`Self::populated_kinds`]`().len()` but without paying for the
1784 /// heap allocation and dealloc a caller only needing the scalar
1785 /// cardinality otherwise pays.
1786 ///
1787 /// # Sibling to [`Self::populated_kinds`]
1788 ///
1789 /// Scalar projection of the closed-set-inversion widened primitive
1790 /// — where `populated_kinds` returns the SET (a `Vec<Self::Kind>`
1791 /// in canonical `ClosedSet::ALL` order), `populated_kind_count`
1792 /// collapses that set to its cardinality. The composition law
1793 /// `populated_kind_count() == populated_kinds().len()` binds the
1794 /// scalar projection to the widened primitive at the trait's
1795 /// default body — a regression that overrode
1796 /// `populated_kind_count` to skip a kind, double-count a slot, or
1797 /// drift the walk from `ClosedSet::ALL` surfaces at the substrate
1798 /// testkit
1799 /// [`assert_populated_kind_count_matches_populated_kinds`].
1800 ///
1801 /// # Peer to [`crate::boundary::ConditionSliceExt::count_kind`]
1802 ///
1803 /// Not a direct peer — `count_kind(k)` on the slice-level axis
1804 /// fixes a `ConditionKind` and returns the per-kind cardinality
1805 /// (how many `Condition`s in the slice carry `k`);
1806 /// `populated_kind_count` on the tagged-union parent-level axis
1807 /// INVERTS by fixing the parent and returning the cardinality of
1808 /// the populated-kind SET (how many distinct slots on the parent
1809 /// are populated). The distinct peer to `count_kind` on the
1810 /// tagged-union axis would be a hypothetical `populated_slots(k)
1811 /// -> usize` — but since every tagged-union slot is `Option<T>`
1812 /// (populated or not, cardinality ∈ {0, 1}), that peer reduces
1813 /// to `has(k) as usize` and doesn't earn its own name. The
1814 /// canonical scalar peer on the tagged-union axis is this
1815 /// closed-set-inversion cardinality.
1816 ///
1817 /// # Sibling of [`Self::has`] / [`Self::find`] / [`Self::populated_kinds`]
1818 ///
1819 /// Fourth refinement on the tagged-union presence-probe algebra,
1820 /// scalar-valued on the closed-set-inversion axis: `has` collapses
1821 /// per-kind presence to a `bool`, `find` widens per-kind to
1822 /// `Option<Variant>`, `populated_kinds` inverts to the SET of
1823 /// populated kinds, and `populated_kind_count` scalar-projects
1824 /// that set to its cardinality. Every downstream consumer picks
1825 /// the coarsest refinement that answers its question — a
1826 /// `populated-kind-count-<n>` require-tag classifier prefix
1827 /// (called out in [`Self::populated_kinds`]'s doc-comment as a
1828 /// hypothetical compounding-future consumer) now reaches
1829 /// `parent.populated_kind_count()` at ONE substrate site rather
1830 /// than paying for `parent.populated_kinds().len()` (with its
1831 /// intermediate heap allocation) or the per-kind
1832 /// `<Kind::ALL>.iter().filter(|k| parent.has(*k)).count()` closure
1833 /// body at the callsite.
1834 ///
1835 /// # Compounding future consumers
1836 ///
1837 /// - A `populated-kind-count-<n>` require-tag classifier prefix
1838 /// family that publishes the populated-set cardinality as a
1839 /// scalar (the exact use case named in
1840 /// [`Self::populated_kinds`]'s doc-comment) reaches this ONE
1841 /// primitive without allocating.
1842 /// - A fast-path branch on `Ambiguous`-arm callers that need to
1843 /// distinguish "well-formed" from "malformed with N slots" reads
1844 /// `parent.populated_kind_count() > 1` at ONE call site rather
1845 /// than reaching for the Vec-materializing widened primitive.
1846 /// - Any coherence check that verifies "every well-formed process
1847 /// parent has exactly one populated slot" now reads
1848 /// `parent.populated_kind_count() == 1` at ONE site rather than
1849 /// restating `parent.populated_kinds().len() == 1` with its
1850 /// allocation cost, or the semantically-equivalent (but
1851 /// parent-arm-projected) `parent.variant().is_ok()`.
1852 ///
1853 /// # Theory grounding
1854 ///
1855 /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
1856 /// The scalar cardinality lives at ONE substrate site as a
1857 /// typed projection of [`Self::populated_kinds`] onto its
1858 /// `.len()`, and the default body composes against
1859 /// [`Self::has`] over the closed set `<Self::Kind as
1860 /// ClosedSet>::ALL` byte-identically to `populated_kinds`
1861 /// without the intermediate `Vec`. Every downstream aggregate
1862 /// consumer binds through the SAME shape rather than paying
1863 /// for the allocation to reach the cardinality.
1864 /// - THEORY.md §VI.1 — generation over composition. A new
1865 /// [`Self::Kind`] variant added to `ALL` reaches this primitive
1866 /// mechanically (the closed-set walk picks up the new entry)
1867 /// and every downstream consumer sees the wider cardinality
1868 /// without further per-caller edit.
1869 fn populated_kind_count(&self) -> usize {
1870 self.iter_populated_kinds().count()
1871 }
1872
1873 /// Closed-set-COMPLEMENT refinement — enumerate the set of
1874 /// [`Self::Kind`] discriminators whose corresponding slot on
1875 /// `self` is EMPTY, in canonical
1876 /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) order.
1877 ///
1878 /// Default body:
1879 /// `<Kind as ClosedSet>::ALL.iter().copied().filter(|k| !self.has(*k)).collect()`.
1880 /// A tagged-union parent that satisfies the exactly-one-slot
1881 /// contract returns a `Vec` of length `ALL.len()` (empty parent —
1882 /// every slot is missing, aligns with [`Self::variant`]'s `Empty`
1883 /// arm) or `ALL.len() - 1` (well-formed — every slot BUT the
1884 /// populated one is missing, aligns with the `Ok` arm); a
1885 /// malformed parent with N populated slots returns a `Vec` of
1886 /// length `ALL.len() - N` in canonical `ALL` order (aligns with
1887 /// the `Ambiguous` arm and NAMES which slots are absent,
1888 /// complementing [`Self::populated_kinds`] which NAMES which are
1889 /// populated).
1890 ///
1891 /// # Sibling to [`Self::populated_kinds`]
1892 ///
1893 /// Closed-set-complement peer of the closed-set-inversion widened
1894 /// primitive — where `populated_kinds` returns the SET of
1895 /// populated kinds, `missing_kinds` returns its COMPLEMENT within
1896 /// `ClosedSet::ALL`. The two primitives PARTITION the closed set:
1897 /// `populated_kinds() ∪ missing_kinds() == ClosedSet::ALL` and the
1898 /// two sets are disjoint. The composition law
1899 /// `missing_kinds().contains(&k) == !has(k)` for every
1900 /// `k ∈ Kind::ALL` binds the two axes structurally through the
1901 /// default body — a regression that overrode `missing_kinds` to
1902 /// skip a kind, return duplicates, or drift the walk order
1903 /// surfaces at the substrate testkit
1904 /// [`assert_missing_kinds_matches_has`].
1905 ///
1906 /// # Peer to [`crate::boundary::ConditionSliceExt::missing_kinds`]
1907 ///
1908 /// Same shape, same axis, second instance in the workspace-wide
1909 /// closed-set-complement refinement algebra:
1910 /// [`ConditionSliceExt::missing_kinds`] returns
1911 /// `Vec<ConditionKind>` on the slice-level presence-probe axis
1912 /// (fixes the slice, varies over `ConditionKind::ALL` under a
1913 /// negated predicate); `missing_kinds` here returns
1914 /// `Vec<Self::Kind>` on the tagged-union parent-level presence-
1915 /// probe axis (fixes the parent, varies over `<Self::Kind as
1916 /// ClosedSet>::ALL` under a negated predicate). Both refine their
1917 /// `has(k) / has_kind(k)` bool peer through the same
1918 /// `ALL.filter(!has).collect()` composition law — the parent-axis
1919 /// complement of the widened `populated_kinds` primitive.
1920 ///
1921 /// # Compounding future consumers
1922 ///
1923 /// - An operator-facing "which slots are still absent" diagnostic
1924 /// on the malformed / partially-populated arm reads
1925 /// `parent.missing_kinds()` at ONE substrate site rather than
1926 /// paying for a negated `<Kind::ALL>.iter().filter(|k|
1927 /// !parent.has(*k)).collect()` closure body at the callsite —
1928 /// or the strictly-worse
1929 /// `<Kind::ALL>.iter().filter(|k| !parent.populated_kinds().contains(k)).collect()`
1930 /// double-loop.
1931 /// - A future require-tag classifier arm that publishes the
1932 /// missing-set membership at fleet audit time (`missing-<kind>`
1933 /// as the negated peer of a hypothetical `populated-<kind>`) reads
1934 /// `parent.missing_kinds().contains(&k)` at ONE call site.
1935 /// - A hypothetical `missing-kind-count-<n>` require-tag
1936 /// classifier prefix family that publishes the missing-set
1937 /// cardinality as a scalar reads [`Self::missing_kind_count`]
1938 /// (the scalar-cardinality peer of this widened primitive)
1939 /// without allocating.
1940 ///
1941 /// A new [`Self::Kind`] variant added to
1942 /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) reaches
1943 /// this primitive mechanically (the closed-set walk picks up the
1944 /// new entry on the missing side WITHOUT further per-caller edit
1945 /// — any parent that doesn't yet populate the new slot sees it
1946 /// listed as missing at every downstream callsite).
1947 ///
1948 /// # Theory grounding
1949 ///
1950 /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
1951 /// The closed-set complement lives at ONE substrate site as a
1952 /// typed projection of [`Self::has`] over the closed set
1953 /// `<Self::Kind as ClosedSet>::ALL` under negation. Every
1954 /// downstream gap-analysis consumer binds through the SAME shape
1955 /// rather than restating the negated `ALL`-filter closure body.
1956 /// - THEORY.md §VI.1 — generation over composition. A new
1957 /// [`Self::Kind`] variant added to `ALL` reaches this primitive
1958 /// mechanically and every downstream consumer sees the wider
1959 /// complement without further per-caller edit.
1960 fn missing_kinds(&self) -> ::std::vec::Vec<Self::Kind> {
1961 self.iter_missing_kinds().collect()
1962 }
1963
1964 /// Zero-allocation iterator peer of [`Self::missing_kinds`] —
1965 /// walk [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) in
1966 /// canonical order and yield every Kind whose corresponding slot
1967 /// on `self` is EMPTY, WITHOUT materializing an intermediate
1968 /// [`Vec`].
1969 ///
1970 /// Default body:
1971 /// `<Self::Kind as ClosedSet>::ALL.iter().copied().filter(|&k| !self.has(k))`.
1972 /// The composition law
1973 /// `missing_kinds() == iter_missing_kinds().collect::<Vec<_>>()`
1974 /// holds by construction — [`Self::missing_kinds`]'s default body
1975 /// IS `self.iter_missing_kinds().collect()`, so a caller that
1976 /// overrides the widened Vec primitive with a divergent walk
1977 /// simultaneously drifts both surfaces (surfacing at the substrate
1978 /// testkit [`assert_iter_missing_kinds_matches_missing_kinds`]
1979 /// which pins the Vec projection equals `iter().collect()`).
1980 ///
1981 /// # Sibling to [`Self::missing_kinds`] / [`Self::missing_kind_count`]
1982 ///
1983 /// Load-bearing iterator peer of the closed-set-complement axis
1984 /// — where `missing_kinds` returns the SET (heap-allocated `Vec`,
1985 /// canonical `ClosedSet::ALL` order) and `missing_kind_count`
1986 /// scalar-projects its cardinality, `iter_missing_kinds` opens
1987 /// the walk as a `Copy` iterator so consumers that need a
1988 /// short-circuiting fold (`.any(|k| pred(k))`, `.find(|&k|
1989 /// pred(k))`, `.take_while(|k| pred(k))`, `.map(|k| project(k))`)
1990 /// avoid the intermediate allocation entirely.
1991 ///
1992 /// # Peer to [`Self::iter_populated_kinds`]
1993 ///
1994 /// Closed-set-INVERSION peer under a POSITIVE point-probe. The
1995 /// two iterators PARTITION `ClosedSet::ALL`:
1996 /// `iter_populated_kinds().chain(iter_missing_kinds()).collect::<HashSet<_>>()`
1997 /// equals `<Self::Kind as ClosedSet>::ALL.iter().copied().collect()`,
1998 /// and the two iterators yield disjoint element sets.
1999 ///
2000 /// # Compounding future consumers
2001 ///
2002 /// - Every scalar closed-set-complement peer already at the trait
2003 /// (`missing_kind_count`, `first_missing_kind`,
2004 /// `last_missing_kind`, `unique_missing_kind`, `is_saturated`,
2005 /// `has_any_missing_kind`, `has_unique_missing_kind`,
2006 /// `has_multiple_missing_kinds`, `has_at_most_one_missing_kind`)
2007 /// folds a specialization of
2008 /// `<Kind::ALL>.iter().copied().filter(|k| !self.has(*k))` —
2009 /// they can now compose over `iter_missing_kinds()` at ONE
2010 /// substrate site rather than restating the closed-set walk
2011 /// body per peer. A future run's `iter_missing_kinds`-fold
2012 /// refactor at those peers collapses ≥ 9 walk bodies onto ONE
2013 /// substrate primitive on the complement side, symmetrical with
2014 /// the closed-set-inversion side.
2015 /// - A downstream diagnostic composer (an operator-facing
2016 /// "still missing: [{}]" message that streams the label list
2017 /// into a `write!` buffer on the partially-populated arm) reads
2018 /// `parent.iter_missing_kinds().map(|k| k.label())` and folds
2019 /// through `itertools::join` without the allocation `Vec<Kind>
2020 /// -> String` pays.
2021 ///
2022 /// # Theory grounding
2023 ///
2024 /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
2025 /// The load-bearing iterator projection on the complement side
2026 /// lives at ONE substrate site, byte-for-byte symmetrical with
2027 /// [`Self::iter_populated_kinds`] under negated `has` predicate.
2028 /// - THEORY.md §VI.1 — generation over composition. A new
2029 /// [`Self::Kind`] variant added to `ALL` reaches the walk
2030 /// mechanically (the closed-set filter picks up the new entry
2031 /// on the missing side) and every downstream fold sees the
2032 /// wider complement without further per-caller edit.
2033 fn iter_missing_kinds(&self) -> impl Iterator<Item = Self::Kind> + '_ {
2034 <Self::Kind as tatara_closed_set::ClosedSet>::ALL
2035 .iter()
2036 .copied()
2037 .filter(|&k| !self.has(k))
2038 }
2039
2040 /// Scalar cardinality refinement on the closed-set-complement axis —
2041 /// the number of [`Self::Kind`] discriminators whose corresponding
2042 /// slot on `self` is EMPTY.
2043 ///
2044 /// Default body:
2045 /// `<Self::Kind as ClosedSet>::ALL.iter().copied().filter(|k| !self.has(*k)).count()`
2046 /// — a closed-set walk that composes against [`Self::has`] per
2047 /// variant under a NEGATED point-probe, WITHOUT materializing an
2048 /// intermediate `Vec`. A tagged-union parent that satisfies the
2049 /// exactly-one-slot contract returns `ALL.len()` (empty — every
2050 /// slot missing, matches [`Self::variant`]'s `Empty` arm),
2051 /// `ALL.len() - 1` (well-formed — matches the `Ok` arm), or
2052 /// `ALL.len() - N` for N-populated (malformed — matches the
2053 /// `Ambiguous` arm), exactly aligned with [`Self::missing_kinds`]
2054 /// `().len()` but without paying for the heap allocation a caller
2055 /// only needing the scalar cardinality otherwise pays.
2056 ///
2057 /// # Sibling to [`Self::missing_kinds`] / [`Self::populated_kind_count`]
2058 ///
2059 /// Scalar projection of the closed-set-complement widened primitive
2060 /// — where `missing_kinds` returns the SET (a `Vec<Self::Kind>` in
2061 /// canonical `ClosedSet::ALL` order), `missing_kind_count`
2062 /// collapses that set to its cardinality. The composition law
2063 /// `missing_kind_count() == missing_kinds().len()` binds the
2064 /// scalar projection to the widened primitive at the trait's
2065 /// default body — a regression that overrode `missing_kind_count`
2066 /// to skip a kind, double-count a slot, or drift the walk from
2067 /// `ClosedSet::ALL` surfaces at the substrate testkit
2068 /// [`assert_missing_kind_count_matches_missing_kinds`].
2069 ///
2070 /// Byte-for-byte peer of [`Self::populated_kind_count`] one axis
2071 /// over (under a negated `has` predicate): where
2072 /// `populated_kind_count` scalar-projects the closed-set-INVERSION
2073 /// widened primitive `populated_kinds`, this method scalar-projects
2074 /// the closed-set-COMPLEMENT widened primitive `missing_kinds`.
2075 /// The two scalar projections PARTITION the closed-set cardinality:
2076 /// `populated_kind_count() + missing_kind_count() ==
2077 /// <Self::Kind as ClosedSet>::ALL.len()` — the scalar consequence
2078 /// of the `(populated_kinds, missing_kinds)` partition law that
2079 /// [`assert_missing_kinds_matches_has`] pins at the widened-
2080 /// primitive layer.
2081 ///
2082 /// # Peer to [`crate::boundary::ConditionSliceExt::missing_kind_count`]
2083 ///
2084 /// Same shape at the peer axis one struct layer down: fixing the
2085 /// slice-side carrier and inverting the presence probe over the
2086 /// closed set under a negated predicate. The two primitives close
2087 /// the "closed-set-complement scalar cardinality" refinement at
2088 /// two adjacent typescape sites — one per closed-set-addressed
2089 /// slice-level refinement, one per closed-set-addressed
2090 /// tagged-union parent-level refinement (this primitive).
2091 ///
2092 /// # Compounding future consumers
2093 ///
2094 /// - A `missing-kind-count-<n>` require-tag classifier prefix
2095 /// family that publishes the missing-set cardinality as a scalar
2096 /// (the exact use case named in [`Self::missing_kinds`]'s
2097 /// doc-comment as a hypothetical compounding-future consumer)
2098 /// reaches this ONE primitive without allocating.
2099 /// - A fast-path branch on `Ambiguous`-arm callers that need to
2100 /// distinguish "one missing slot" (well-formed exactly-one) from
2101 /// "N missing slots" (malformed with populated_kind_count > 1)
2102 /// reads `parent.missing_kind_count() == ALL.len() - 1` at ONE
2103 /// call site rather than reaching for the Vec-materializing
2104 /// widened primitive.
2105 /// - Any coherence check that verifies "every well-formed process
2106 /// parent has exactly `ALL.len() - 1` missing slots" now reads
2107 /// `parent.missing_kind_count() == <Kind as ClosedSet>::ALL.len() - 1`
2108 /// at ONE site rather than restating
2109 /// `parent.missing_kinds().len() == ALL.len() - 1` with its
2110 /// allocation cost, or the semantically-equivalent (but
2111 /// parent-arm-projected) `parent.variant().is_ok()`.
2112 ///
2113 /// # Theory grounding
2114 ///
2115 /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
2116 /// The scalar cardinality lives at ONE substrate site as a typed
2117 /// projection of [`Self::missing_kinds`] onto its `.len()`, and
2118 /// the default body composes against [`Self::has`] over the
2119 /// closed set `<Self::Kind as ClosedSet>::ALL` under negation
2120 /// byte-identically to `missing_kinds` without the intermediate
2121 /// `Vec`. Every downstream aggregate consumer binds through the
2122 /// SAME shape rather than paying for the allocation to reach the
2123 /// cardinality.
2124 /// - THEORY.md §VI.1 — generation over composition. A new
2125 /// [`Self::Kind`] variant added to `ALL` reaches this primitive
2126 /// mechanically (the closed-set walk picks up the new entry on
2127 /// the missing side WITHOUT further per-caller edit — any parent
2128 /// that doesn't yet populate the new slot sees the cardinality
2129 /// rise by one at every downstream callsite).
2130 fn missing_kind_count(&self) -> usize {
2131 self.iter_missing_kinds().count()
2132 }
2133
2134 /// Short-circuiting `Option<Self::Kind>` peer of
2135 /// [`Self::populated_kinds`] — the FIRST populated kind on this
2136 /// tagged union in canonical
2137 /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) order, or
2138 /// `None` when no slot is populated.
2139 ///
2140 /// Default body:
2141 /// `<Kind as ClosedSet>::ALL.iter().copied().find(|k| self.has(*k))`
2142 /// — a closed-set walk that composes against [`Self::has`] per
2143 /// variant and SHORT-CIRCUITS at the earliest match. An empty parent
2144 /// returns `None` (matches [`Self::variant`]'s `Empty` arm); a
2145 /// well-formed parent returns `Some(k)` where `k` is the sole
2146 /// populated slot (matches the `Ok` arm's variant kind through
2147 /// [`VariantKind`]); a malformed parent with multiple populated
2148 /// slots returns `Some(k)` where `k` is the EARLIEST populated
2149 /// slot in canonical `ALL` order — a strictly more informative
2150 /// projection than the payload-free [`TaggedUnionError::ambiguous`]
2151 /// carrier, without materializing the intermediate
2152 /// `Vec<Self::Kind>` [`Self::populated_kinds`] otherwise pays for.
2153 ///
2154 /// # Sibling to [`Self::populated_kinds`] / [`Self::populated_kind_count`]
2155 ///
2156 /// Third refinement on the closed-set-inversion axis, `Option<Kind>`-
2157 /// valued: `populated_kinds` returns the SET, `populated_kind_count`
2158 /// scalar-projects that set's cardinality, and `first_populated_kind`
2159 /// scalar-projects the SET onto its earliest element. The
2160 /// composition law `first_populated_kind() ==
2161 /// populated_kinds().first().copied()` binds the earliest-element
2162 /// projection to the widened primitive at the trait's default body —
2163 /// pinned substrate-wide by
2164 /// [`assert_first_populated_kind_matches_populated_kinds`]. Both
2165 /// coarser projections agree on emptiness:
2166 /// `first_populated_kind().is_none() == (populated_kind_count() == 0)`.
2167 ///
2168 /// # Peer to [`Self::variant`] on the malformed arm
2169 ///
2170 /// On well-formed parents the two projections agree
2171 /// (`self.variant().ok().map(|v| v.variant_kind()) ==
2172 /// first_populated_kind()`). On malformed (Ambiguous) parents they
2173 /// diverge: `variant()` returns `Err(Ambiguous)` payload-free,
2174 /// while `first_populated_kind()` names the earliest populated
2175 /// slot. Operator diagnostics that want "started at X first" text
2176 /// on the Ambiguous arm reach this ONE primitive with O(1) storage
2177 /// and short-circuit walk cost, without paying for the widened
2178 /// `populated_kinds().first().copied()` allocation the
2179 /// composition law equates it to.
2180 ///
2181 /// # Compounding future consumers
2182 ///
2183 /// - An operator-facing "Ambiguous, starting at Nix" upgrade of the
2184 /// payload-free [`TaggedUnionError::ambiguous`] carrier reads
2185 /// `parent.first_populated_kind()` at ONE substrate site.
2186 /// - A `first-populated-<kind>` require-tag classifier arm reads
2187 /// this primitive with no allocation, byte-for-byte symmetrical
2188 /// with `parent.has(kind)`.
2189 /// - A fast-path branch that discriminates "empty" from "any
2190 /// populated" reads `parent.first_populated_kind().is_some()` at
2191 /// ONE call site rather than allocating a `Vec` through
2192 /// `!populated_kinds().is_empty()`.
2193 ///
2194 /// # Theory grounding
2195 ///
2196 /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
2197 /// The earliest-element projection lives at ONE substrate site as
2198 /// a typed projection of [`Self::has`] over the closed set
2199 /// `<Self::Kind as ClosedSet>::ALL` under short-circuit walk
2200 /// semantics. Every downstream consumer binds through the SAME
2201 /// shape rather than reaching for
2202 /// `populated_kinds().first().copied()` with its allocation cost.
2203 /// - THEORY.md §VI.1 — generation over composition. A new
2204 /// [`Self::Kind`] variant added to `ALL` reaches this primitive
2205 /// mechanically (the closed-set walk picks up the new entry) —
2206 /// any parent that populates only the new variant returns
2207 /// `Some(new_variant)` at every downstream callsite without
2208 /// further per-caller edit.
2209 fn first_populated_kind(&self) -> Option<Self::Kind> {
2210 self.iter_populated_kinds().next()
2211 }
2212
2213 /// Short-circuiting `Option<Self::Kind>` peer of
2214 /// [`Self::missing_kinds`] — the FIRST missing kind on this tagged
2215 /// union in canonical
2216 /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) order, or
2217 /// `None` when EVERY slot is populated.
2218 ///
2219 /// Default body:
2220 /// `<Kind as ClosedSet>::ALL.iter().copied().find(|k| !self.has(*k))`
2221 /// — a closed-set walk composed against [`Self::has`] per variant
2222 /// under NEGATION with SHORT-CIRCUIT at the earliest empty slot. An
2223 /// empty parent returns `Some(ALL[0])` (every slot missing, first
2224 /// hit is index 0); a well-formed parent populating slot `k`
2225 /// returns `Some(ALL[0])` if `k != ALL[0]`, else `Some(ALL[1])`
2226 /// (the earliest non-`k` entry); a saturated parent with every
2227 /// slot populated (structurally impossible on the exactly-one
2228 /// contract but semantically well-defined) returns `None`.
2229 ///
2230 /// # Sibling to [`Self::missing_kinds`] / [`Self::missing_kind_count`]
2231 ///
2232 /// Third refinement on the closed-set-complement axis,
2233 /// `Option<Kind>`-valued: `missing_kinds` returns the COMPLEMENT SET,
2234 /// `missing_kind_count` scalar-projects its cardinality, and
2235 /// `first_missing_kind` scalar-projects the SET onto its earliest
2236 /// element. The composition law `first_missing_kind() ==
2237 /// missing_kinds().first().copied()` binds the earliest-element
2238 /// projection to the widened primitive at the trait's default
2239 /// body — pinned substrate-wide by
2240 /// [`assert_first_missing_kind_matches_missing_kinds`]. Both
2241 /// coarser projections agree on saturation:
2242 /// `first_missing_kind().is_none() == (missing_kind_count() == 0)`.
2243 ///
2244 /// # Peer to [`Self::first_populated_kind`]
2245 ///
2246 /// Closed-set-complement peer of the closed-set-inversion earliest-
2247 /// element primitive under a negated `has` predicate. The two
2248 /// primitives PARTITION `ClosedSet::ALL`'s earliest-element
2249 /// projection: at least one of `first_populated_kind()` and
2250 /// `first_missing_kind()` is `Some` on any non-degenerate closed
2251 /// set (they are both `Some` iff `1 ≤ populated_kind_count() <
2252 /// ALL.len()`).
2253 ///
2254 /// # Compounding future consumers
2255 ///
2256 /// - An operator-facing "first still-unfilled dependency" diagnostic
2257 /// on the partially-populated arm of an aggregate boundary check
2258 /// reads `parent.first_missing_kind()` at ONE substrate site.
2259 /// - A `first-missing-<kind>` require-tag classifier arm reads this
2260 /// primitive with no allocation, byte-for-byte symmetrical with
2261 /// `parent.first_populated_kind()`.
2262 /// - A fast-path branch that discriminates "saturated" from "at
2263 /// least one missing" reads `parent.first_missing_kind().is_some()`
2264 /// at ONE call site rather than allocating through
2265 /// `!missing_kinds().is_empty()` or paying for the full
2266 /// `missing_kind_count() > 0` walk.
2267 ///
2268 /// # Theory grounding
2269 ///
2270 /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
2271 /// The complement-earliest-element projection lives at ONE
2272 /// substrate site as a typed projection of [`Self::has`] over the
2273 /// closed set `<Self::Kind as ClosedSet>::ALL` under negation
2274 /// with short-circuit walk semantics.
2275 /// - THEORY.md §VI.1 — generation over composition. A new
2276 /// [`Self::Kind`] variant added to `ALL` reaches this primitive
2277 /// mechanically (the closed-set walk picks up the new entry on
2278 /// the missing side) — every downstream consumer sees the wider
2279 /// complement's earliest hit without further per-caller edit.
2280 fn first_missing_kind(&self) -> Option<Self::Kind> {
2281 self.iter_missing_kinds().next()
2282 }
2283
2284 /// Short-circuiting `Option<Self::Kind>` peer of
2285 /// [`Self::populated_kinds`] — the LAST populated kind on this
2286 /// tagged union in canonical
2287 /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) order, or
2288 /// `None` when no slot is populated.
2289 ///
2290 /// Default body:
2291 /// `<Kind as ClosedSet>::ALL.iter().rev().copied().find(|k|
2292 /// self.has(*k))` — a REVERSED closed-set walk that composes
2293 /// against [`Self::has`] per variant and SHORT-CIRCUITS at the
2294 /// latest match. Byte-for-byte time-reversed peer of
2295 /// [`Self::first_populated_kind`] under identical predicate
2296 /// composition. An empty parent returns `None`; a well-formed
2297 /// parent returns `Some(k)` where `k` is the sole populated slot
2298 /// (matches the `Ok` arm's variant kind through [`VariantKind`]);
2299 /// a malformed parent with multiple populated slots returns
2300 /// `Some(k)` where `k` is the LATEST populated slot in canonical
2301 /// `ALL` order — the operator-diagnostic peer of
2302 /// [`Self::first_populated_kind`] on the malformed arm.
2303 ///
2304 /// # Sibling to [`Self::first_populated_kind`]
2305 ///
2306 /// FOURTH refinement on the closed-set-inversion axis under a
2307 /// REVERSED walk, `Option<Kind>`-valued: together with
2308 /// [`Self::first_populated_kind`] the two primitives project
2309 /// [`Self::populated_kinds`] onto its endpoint pair (earliest,
2310 /// latest). On the well-formed (exactly-one) arm they agree
2311 /// (`first_populated_kind() == last_populated_kind()` = `Some(k)`);
2312 /// on the empty arm they agree (`None`); on the malformed
2313 /// (Ambiguous) arm they disagree exactly when the populated set
2314 /// has cardinality `> 1` (the operator-diagnostic contract
2315 /// `"Ambiguous, from X to Y"` reads both projections at ONE call
2316 /// site through this trait's default bodies).
2317 ///
2318 /// The composition law `last_populated_kind() ==
2319 /// populated_kinds().last().copied()` binds the latest-element
2320 /// projection to the widened primitive at the trait's default
2321 /// body — pinned substrate-wide by
2322 /// [`assert_last_populated_kind_matches_populated_kinds`]. Both
2323 /// coarser projections agree on emptiness:
2324 /// `last_populated_kind().is_none() == (populated_kind_count() == 0)`.
2325 ///
2326 /// # Compounding future consumers
2327 ///
2328 /// - The `"Ambiguous, from X to Y"` upgrade of the payload-free
2329 /// [`TaggedUnionError::ambiguous`] carrier reads
2330 /// `parent.first_populated_kind()` AND
2331 /// `parent.last_populated_kind()` at TWO substrate primitives
2332 /// with O(1) storage on each side.
2333 /// - A `last-populated-<kind>` require-tag classifier arm reads
2334 /// this primitive with no allocation, byte-for-byte symmetrical
2335 /// with `parent.first_populated_kind()`.
2336 /// - A fast-path branch that discriminates "empty" from "any
2337 /// populated" gains a REVERSED short-circuit option
2338 /// (`parent.last_populated_kind().is_some()`) that commits to
2339 /// the latest-populated slot's identity rather than the
2340 /// earliest.
2341 ///
2342 /// # Theory grounding
2343 ///
2344 /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
2345 /// The latest-element projection lives at ONE substrate site as
2346 /// a typed projection of [`Self::has`] over the closed set
2347 /// `<Self::Kind as ClosedSet>::ALL` under REVERSED short-circuit
2348 /// walk semantics — byte-for-byte time-reversed peer of the
2349 /// earliest-element projection.
2350 /// - THEORY.md §VI.1 — generation over composition. A new
2351 /// [`Self::Kind`] variant added to `ALL` reaches this primitive
2352 /// mechanically (the reversed closed-set walk picks up the new
2353 /// entry at its canonical `ALL` position) — every downstream
2354 /// consumer sees the wider latest-hit projection with no
2355 /// per-caller edit.
2356 fn last_populated_kind(&self) -> Option<Self::Kind> {
2357 self.iter_populated_kinds().last()
2358 }
2359
2360 /// Short-circuiting `Option<Self::Kind>` peer of
2361 /// [`Self::missing_kinds`] — the LAST missing kind on this tagged
2362 /// union in canonical
2363 /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) order, or
2364 /// `None` when EVERY slot is populated.
2365 ///
2366 /// Default body:
2367 /// `<Kind as ClosedSet>::ALL.iter().rev().copied().find(|k|
2368 /// !self.has(*k))` — a REVERSED closed-set walk composed against
2369 /// [`Self::has`] per variant under NEGATION with SHORT-CIRCUIT at
2370 /// the latest empty slot. Byte-for-byte time-reversed peer of
2371 /// [`Self::first_missing_kind`] under identical predicate
2372 /// composition. An empty parent returns `Some(ALL[ALL.len()-1])`
2373 /// (every slot missing, latest hit is the last index); a well-
2374 /// formed parent populating slot `k` returns
2375 /// `Some(ALL[ALL.len()-1])` when `k != ALL[ALL.len()-1]`, else
2376 /// `Some(ALL[ALL.len()-2])` (the latest non-`k` entry); a
2377 /// saturated parent returns `None`.
2378 ///
2379 /// # Sibling to [`Self::first_missing_kind`]
2380 ///
2381 /// FOURTH refinement on the closed-set-complement axis under a
2382 /// REVERSED walk, `Option<Kind>`-valued: together with
2383 /// [`Self::first_missing_kind`] the two primitives project
2384 /// [`Self::missing_kinds`] onto its endpoint pair (earliest,
2385 /// latest). The composition law `last_missing_kind() ==
2386 /// missing_kinds().last().copied()` binds the latest-element
2387 /// projection to the widened primitive at the trait's default
2388 /// body — pinned substrate-wide by
2389 /// [`assert_last_missing_kind_matches_missing_kinds`]. Both
2390 /// coarser projections agree on saturation:
2391 /// `last_missing_kind().is_none() == (missing_kind_count() == 0)`.
2392 ///
2393 /// # Endpoint partition
2394 ///
2395 /// Together with [`Self::first_populated_kind`],
2396 /// [`Self::first_missing_kind`], and [`Self::last_populated_kind`],
2397 /// this primitive closes the FOUR-corner endpoint projection of
2398 /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) on the
2399 /// (populated, missing) × (earliest, latest) product — every
2400 /// endpoint-addressable coherence check reads ONE of the four at
2401 /// ONE call site without allocating a `Vec<Self::Kind>` through
2402 /// `populated_kinds()` / `missing_kinds()`.
2403 ///
2404 /// # Compounding future consumers
2405 ///
2406 /// - An operator-facing "last still-unfilled dependency"
2407 /// diagnostic on the partially-populated arm of an aggregate
2408 /// boundary check reads `parent.last_missing_kind()` at ONE
2409 /// substrate site.
2410 /// - A `last-missing-<kind>` require-tag classifier arm reads this
2411 /// primitive with no allocation, byte-for-byte symmetrical with
2412 /// `parent.last_populated_kind()`.
2413 /// - A fast-path branch that discriminates "saturated" from "at
2414 /// least one missing" now has two symmetric short-circuit walk
2415 /// options (`parent.first_missing_kind().is_some()` from the
2416 /// FORWARD walk, `parent.last_missing_kind().is_some()` from
2417 /// the REVERSED walk) both returning the same Boolean
2418 /// projection but committing to different endpoint disclosures.
2419 ///
2420 /// # Theory grounding
2421 ///
2422 /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
2423 /// The complement-latest-element projection lives at ONE
2424 /// substrate site as a typed projection of [`Self::has`] over
2425 /// the closed set `<Self::Kind as ClosedSet>::ALL` under
2426 /// REVERSED negation-and-short-circuit walk semantics.
2427 /// - THEORY.md §VI.1 — generation over composition. A new
2428 /// [`Self::Kind`] variant added to `ALL` reaches this primitive
2429 /// mechanically (the reversed closed-set walk picks up the new
2430 /// entry at its canonical `ALL` position on the missing side).
2431 fn last_missing_kind(&self) -> Option<Self::Kind> {
2432 self.iter_missing_kinds().last()
2433 }
2434
2435 /// Exactly-one-populated `Option<Self::Kind>` peer of
2436 /// [`Self::populated_kinds`] — `Some(k)` iff `k` is the SOLE
2437 /// populated kind on this tagged union, else `None`.
2438 ///
2439 /// Default body walks `<Self::Kind as ClosedSet>::ALL` under
2440 /// [`Self::has`] and returns `Some(k)` iff EXACTLY ONE hit is seen,
2441 /// short-circuiting at the SECOND hit — a two-step iterator peer
2442 /// of the earliest / latest short-circuit walks whose truth-table
2443 /// projection is disjoint from `first_populated_kind` /
2444 /// `last_populated_kind` on the malformed arm (both endpoints name
2445 /// SOME populated slot on a two-populated parent, `unique` names
2446 /// `None`).
2447 ///
2448 /// # Sibling to [`Self::first_populated_kind`] / [`Self::last_populated_kind`]
2449 ///
2450 /// FIFTH refinement on the closed-set-inversion axis under
2451 /// exactly-one-hit semantics, `Option<Kind>`-valued: together with
2452 /// [`Self::first_populated_kind`] and [`Self::last_populated_kind`]
2453 /// the three primitives project [`Self::populated_kinds`] onto its
2454 /// cardinality-conditioned scalar identity. On the well-formed
2455 /// (exactly-one) arm all three agree (`unique == first == last =
2456 /// Some(k)`); on the empty arm all three agree (`None`); on the
2457 /// malformed (Ambiguous, cardinality ≥ 2) arm the three DIVERGE:
2458 /// `first`/`last` name the endpoint populated slots (Some), while
2459 /// `unique` returns `None` — the ONLY endpoint-projection primitive
2460 /// in the algebra that distinguishes well-formed from malformed at
2461 /// its return type without paying for a [`Self::variant`] error-
2462 /// carrier allocation.
2463 ///
2464 /// The composition laws
2465 /// `unique_populated_kind().is_some() == (populated_kind_count() == 1)`
2466 /// and (on the `Some` arm) `unique_populated_kind() ==
2467 /// first_populated_kind() == last_populated_kind()` bind the
2468 /// exactly-one scalar identity to the widened primitives at the
2469 /// trait's default body — pinned substrate-wide by
2470 /// [`assert_unique_populated_kind_matches_populated_kinds`].
2471 ///
2472 /// # Peer to [`Self::variant`] as a kind-only projection
2473 ///
2474 /// Byte-for-byte equivalent to
2475 /// `self.variant().ok().map(|v| v.variant_kind())` on the trait's
2476 /// exactly-one contract, but WITHOUT paying for the [`Self::Error`]
2477 /// carrier's allocation on the failing arms, and WITHOUT reaching
2478 /// [`VariantSelector::Variant`] / [`VariantKind::variant_kind`]. A
2479 /// `use TaggedUnion` scope at the consumer is enough; the borrowed
2480 /// variant view is not needed. On well-formed parents the two
2481 /// projections agree; on empty AND malformed parents they agree by
2482 /// returning `None` (unlike `first_populated_kind`, which returns
2483 /// `Some` on malformed).
2484 ///
2485 /// # Compounding future consumers
2486 ///
2487 /// - A closed-set-driven "resolved kind identity" dispatch that
2488 /// only needs the Kind (not the borrowed variant) reads
2489 /// `parent.unique_populated_kind()` at ONE substrate site — one
2490 /// short-circuit walk, no error-carrier allocation, no
2491 /// VariantKind projection.
2492 /// - A coherence check that verifies "every well-formed process
2493 /// parent has a unique populated kind" now reads
2494 /// `parent.unique_populated_kind().is_some()` at ONE site rather
2495 /// than restating `parent.populated_kind_count() == 1` (which
2496 /// discards the resolved kind identity) or
2497 /// `parent.variant().is_ok()` (which pays for the error carrier).
2498 /// - A future require-tag classifier arm that publishes the
2499 /// exactly-one resolved kind (`unique-populated-<kind>`) at fleet
2500 /// audit time reads this primitive with no allocation, byte-for-
2501 /// byte symmetrical with the `first-populated-<kind>` and
2502 /// `last-populated-<kind>` sibling classifier families.
2503 /// - A fast-path branch on the (empty, well-formed, ambiguous)
2504 /// trichotomy that needs to distinguish "well-formed with kind X"
2505 /// from BOTH "empty" AND "ambiguous" reaches this primitive at
2506 /// ONE call site: `Some(k)` names the well-formed arm's kind,
2507 /// `None` collapses the two failing arms together.
2508 ///
2509 /// # Theory grounding
2510 ///
2511 /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
2512 /// The exactly-one-hit projection lives at ONE substrate site as
2513 /// a typed two-step-short-circuit walk over
2514 /// `<Self::Kind as ClosedSet>::ALL` under [`Self::has`]. The
2515 /// composition laws above compose the SAME shape as the endpoint
2516 /// projections, differing only in the truth-table arm on the
2517 /// malformed side.
2518 /// - THEORY.md §VI.1 — generation over composition. A new
2519 /// [`Self::Kind`] variant added to `ALL` reaches this primitive
2520 /// mechanically — any parent populating only the new variant
2521 /// returns `Some(new_variant)` at every downstream callsite
2522 /// without further per-caller edit.
2523 fn unique_populated_kind(&self) -> Option<Self::Kind> {
2524 let mut iter = self.iter_populated_kinds();
2525 let first = iter.next()?;
2526 match iter.next() {
2527 None => Some(first),
2528 Some(_) => None,
2529 }
2530 }
2531
2532 /// Exactly-one-missing `Option<Self::Kind>` peer of
2533 /// [`Self::missing_kinds`] — `Some(k)` iff `k` is the SOLE missing
2534 /// kind on this tagged union, else `None`.
2535 ///
2536 /// Default body walks `<Self::Kind as ClosedSet>::ALL` under a
2537 /// NEGATED [`Self::has`] predicate and returns `Some(k)` iff
2538 /// EXACTLY ONE empty slot is seen, short-circuiting at the SECOND
2539 /// empty slot. Byte-for-byte peer of
2540 /// [`Self::unique_populated_kind`] under the complement axis.
2541 ///
2542 /// # Sibling to [`Self::first_missing_kind`] / [`Self::last_missing_kind`]
2543 ///
2544 /// FIFTH refinement on the closed-set-complement axis under
2545 /// exactly-one-hit semantics, `Option<Kind>`-valued: together with
2546 /// [`Self::first_missing_kind`] and [`Self::last_missing_kind`] the
2547 /// three primitives project [`Self::missing_kinds`] onto its
2548 /// cardinality-conditioned scalar identity on the empty side. The
2549 /// composition laws
2550 /// `unique_missing_kind().is_some() == (missing_kind_count() == 1)`
2551 /// and (on the `Some` arm) `unique_missing_kind() ==
2552 /// first_missing_kind() == last_missing_kind()` bind the exactly-
2553 /// one scalar identity to the widened primitives at the trait's
2554 /// default body — pinned substrate-wide by
2555 /// [`assert_unique_missing_kind_matches_missing_kinds`].
2556 ///
2557 /// # Truth table on the exactly-one-slot tagged-union contract
2558 ///
2559 /// For a tagged union with `<Self::Kind as ClosedSet>::ALL` of
2560 /// cardinality `N`:
2561 ///
2562 /// - Empty parent (0 populated, N missing): `None` (N ≥ 2 missing
2563 /// on any non-degenerate closed set, so not unique).
2564 /// - Well-formed parent (1 populated, N-1 missing): `None` when
2565 /// `N > 2` (N-1 ≥ 2 missing, not unique), `Some(the-one-missing)`
2566 /// when `N == 2` (exactly one missing — the peer of the
2567 /// populated slot).
2568 /// - N-1-populated parent (structurally the missing-side peer of
2569 /// the well-formed arm): `Some(the-lone-empty)` — the ONLY arm
2570 /// where `unique_missing_kind` returns `Some` on a `N > 2`
2571 /// closed set.
2572 /// - Saturated parent (N populated, 0 missing): `None`.
2573 ///
2574 /// # Peer to [`Self::unique_populated_kind`]
2575 ///
2576 /// Closed-set-complement peer of the closed-set-inversion exactly-
2577 /// one-hit primitive under a negated `has` predicate. The two
2578 /// primitives are useful in DIFFERENT structural regimes: the
2579 /// populated peer names well-formed parents (1 populated of N),
2580 /// the missing peer names the missing-side complement (1 missing
2581 /// of N). On tagged unions with `N == 2` (rare — most `ALL`s are
2582 /// ≥ 3) the two coincide (a well-formed 1-of-2 parent has 1
2583 /// missing too).
2584 ///
2585 /// # Compounding future consumers
2586 ///
2587 /// - An operator-facing "one dependency still unfulfilled: X"
2588 /// diagnostic on an aggregate boundary check reads
2589 /// `parent.unique_missing_kind()` at ONE substrate site — one
2590 /// short-circuit walk, no allocation.
2591 /// - A `unique-missing-<kind>` require-tag classifier arm reads
2592 /// this primitive with no allocation, byte-for-byte symmetrical
2593 /// with `parent.unique_populated_kind()`.
2594 /// - A fast-path branch on the near-saturation arm that
2595 /// discriminates "exactly one slot still empty" from "0 or ≥ 2
2596 /// still empty" reads `parent.unique_missing_kind().is_some()`
2597 /// at ONE call site.
2598 ///
2599 /// # Theory grounding
2600 ///
2601 /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
2602 /// The complement-exactly-one-hit projection lives at ONE
2603 /// substrate site as a typed two-step-short-circuit walk over
2604 /// `<Self::Kind as ClosedSet>::ALL` under a negated
2605 /// [`Self::has`] predicate — byte-for-byte peer of the
2606 /// populated-side primitive under complement.
2607 /// - THEORY.md §VI.1 — generation over composition. A new
2608 /// [`Self::Kind`] variant added to `ALL` reaches this primitive
2609 /// mechanically on the missing side.
2610 fn unique_missing_kind(&self) -> Option<Self::Kind> {
2611 let mut iter = self.iter_missing_kinds();
2612 let first = iter.next()?;
2613 match iter.next() {
2614 None => Some(first),
2615 Some(_) => None,
2616 }
2617 }
2618
2619 /// Boolean cardinality-endpoint peer of [`Self::populated_kinds`] —
2620 /// `true` iff NO slot on this tagged union is populated.
2621 ///
2622 /// Default body:
2623 /// `!<Self::Kind as ClosedSet>::ALL.iter().copied().any(|k| self.has(k))`
2624 /// — a short-circuiting closed-set walk under [`Self::has`] that
2625 /// returns `true` iff every point-probe returns `false`, WITHOUT
2626 /// materializing the [`Vec`] `populated_kinds` would build and
2627 /// WITHOUT paying for the `usize` `populated_kind_count` would
2628 /// count. The `!any` composition short-circuits at the FIRST
2629 /// populated slot on the non-empty arms — strictly cheaper than
2630 /// either widened primitive on every arm where the parent has ≥ 1
2631 /// populated slot.
2632 ///
2633 /// # Sibling to [`Self::populated_kind_count`]
2634 ///
2635 /// Boolean cardinality-endpoint peer of the scalar cardinality
2636 /// primitive — where `populated_kind_count` returns the FULL scalar
2637 /// (any `usize` in `0..=ALL.len()`), `is_empty` collapses that
2638 /// scalar to its zero-arm Boolean projection. The composition law
2639 /// `is_empty() == (populated_kind_count() == 0)` binds the Boolean
2640 /// projection to the scalar primitive at the trait's default body —
2641 /// swept substrate-wide by
2642 /// [`assert_is_empty_matches_populated_kind_count`]. Byte-for-byte
2643 /// symmetrical with [`Self::is_saturated`] under the (populated,
2644 /// missing) complement axis: where `is_empty` names the zero-arm
2645 /// of the populated cardinality, `is_saturated` names the zero-arm
2646 /// of the missing cardinality (equivalently, the top-arm of the
2647 /// populated cardinality — `populated_kind_count() == ALL.len()`).
2648 ///
2649 /// # Truth table on the exactly-one-slot tagged-union contract
2650 ///
2651 /// For a tagged union with `<Self::Kind as ClosedSet>::ALL` of
2652 /// cardinality `N ≥ 1`:
2653 ///
2654 /// - Empty parent (0 populated, N missing): `true` — the SOLE
2655 /// arm where `is_empty` returns `true`. Aligns with
2656 /// [`Self::variant`]'s `Empty` arm (which returns
2657 /// [`TaggedUnionError::empty`] carrying `KIND_LIST` verbatim).
2658 /// The [`Self::empty`](TaggedUnionError::empty) factory produces
2659 /// parents on this arm — pins one direction of the "empty ↔
2660 /// is_empty()" symmetry.
2661 /// - Well-formed parent (1 populated, N-1 missing): `false`.
2662 /// - K-populated parent for `1 ≤ K ≤ N`: `false`.
2663 /// - Saturated parent (N populated, 0 missing): `false`.
2664 ///
2665 /// # Compounding future consumers
2666 ///
2667 /// - A fast-path branch that discriminates "any content at all"
2668 /// from "empty carrier" — the most common tagged-union top-level
2669 /// guard — reads `parent.is_empty()` at ONE substrate site with
2670 /// ONE short-circuit walk (returns at the first populated slot),
2671 /// rather than reaching for either `populated_kind_count() == 0`
2672 /// (which walks every slot) or `!variant().is_ok()` (which pays
2673 /// for the borrowed-view projection and the error-carrier
2674 /// materialization on failing arms).
2675 /// - An operator-facing "carrier missing content" diagnostic on
2676 /// the `Empty` arm of [`Self::variant`] reads `parent.is_empty()`
2677 /// at ONE substrate site — one short-circuit walk, no allocation,
2678 /// no error-carrier materialization.
2679 /// - An `is-empty` require-tag classifier arm reaches this
2680 /// primitive at ONE call site, byte-for-byte symmetrical with
2681 /// the sibling `is-saturated` arm.
2682 /// - A coherence check verifying "every well-formed parent has at
2683 /// least one populated slot" reads `!parent.is_empty()` at ONE
2684 /// site rather than the widened-primitive composition
2685 /// `!parent.populated_kinds().is_empty()` (which pays for the
2686 /// Vec) or `parent.populated_kind_count() > 0` (which walks every
2687 /// slot).
2688 ///
2689 /// A new [`Self::Kind`] variant added to
2690 /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) reaches
2691 /// this primitive mechanically (the closed-set walk picks up the
2692 /// new entry as an additional short-circuit slot — a parent that
2693 /// populates ONLY the new variant returns `false` at every
2694 /// downstream callsite without further per-caller edit; an all-
2695 /// empty parent continues to return `true` past every entry
2696 /// including the new one).
2697 ///
2698 /// # Theory grounding
2699 ///
2700 /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
2701 /// The Boolean cardinality-endpoint projection lives at ONE
2702 /// substrate site as a typed short-circuiting closed-set walk
2703 /// `!<Self::Kind as ClosedSet>::ALL.iter().any(has)` — byte-
2704 /// for-byte peer of `populated_kind_count()` composed against
2705 /// `== 0`, but without the counter allocation on every arm and
2706 /// with a first-populated-slot short-circuit that neither
2707 /// widened primitive offers.
2708 /// - THEORY.md §VI.1 — generation over composition. A new
2709 /// [`Self::Kind`] variant added to `ALL` reaches this primitive
2710 /// mechanically through the `any` short-circuit.
2711 fn is_empty(&self) -> bool {
2712 self.iter_populated_kinds().next().is_none()
2713 }
2714
2715 /// Boolean cardinality-endpoint peer of [`Self::missing_kinds`] —
2716 /// `true` iff EVERY slot on this tagged union is populated (i.e.
2717 /// the missing set is empty).
2718 ///
2719 /// Default body:
2720 /// `<Self::Kind as ClosedSet>::ALL.iter().copied().all(|k| self.has(k))`
2721 /// — a short-circuiting closed-set walk under [`Self::has`] that
2722 /// returns `true` iff every point-probe returns `true`, WITHOUT
2723 /// materializing the [`Vec`] `missing_kinds` would build and
2724 /// WITHOUT paying for the `usize` `missing_kind_count` would
2725 /// count. The `all` composition short-circuits at the FIRST
2726 /// missing slot on the non-saturated arms — strictly cheaper than
2727 /// either widened primitive on every arm where the parent has ≥ 1
2728 /// missing slot.
2729 ///
2730 /// # Sibling to [`Self::missing_kind_count`]
2731 ///
2732 /// Boolean cardinality-endpoint peer of the scalar cardinality
2733 /// primitive — where `missing_kind_count` returns the FULL scalar
2734 /// (any `usize` in `0..=ALL.len()`), `is_saturated` collapses that
2735 /// scalar to its zero-arm Boolean projection. The composition law
2736 /// `is_saturated() == (missing_kind_count() == 0)` binds the
2737 /// Boolean projection to the scalar primitive at the trait's
2738 /// default body — swept substrate-wide by
2739 /// [`assert_is_saturated_matches_missing_kind_count`]. Byte-for-
2740 /// byte symmetrical with [`Self::is_empty`] under the (populated,
2741 /// missing) complement axis: where `is_empty` names the zero-arm
2742 /// of the populated cardinality, `is_saturated` names the zero-arm
2743 /// of the missing cardinality.
2744 ///
2745 /// # Truth table on the exactly-one-slot tagged-union contract
2746 ///
2747 /// For a tagged union with `<Self::Kind as ClosedSet>::ALL` of
2748 /// cardinality `N ≥ 1`:
2749 ///
2750 /// - Empty parent (0 populated, N missing): `false`.
2751 /// - Well-formed parent (1 populated, N-1 missing): `false` (on
2752 /// any `N ≥ 2` closed set). On the degenerate `N == 1` closed
2753 /// set the well-formed and saturated arms coincide — both
2754 /// primitives return `false` on the empty arm and `true` on the
2755 /// single-populated arm — but real-world tagged unions in this
2756 /// workspace all have `N ≥ 2`.
2757 /// - K-populated parent for `0 ≤ K < N`: `false`.
2758 /// - Saturated parent (N populated, 0 missing): `true` — the SOLE
2759 /// arm where `is_saturated` returns `true`.
2760 ///
2761 /// # Compounding future consumers
2762 ///
2763 /// - A fast-path branch that discriminates "over-populated"
2764 /// (saturated, structurally malformed on any `N ≥ 2` tagged
2765 /// union) from "well-formed or partial" reads
2766 /// `parent.is_saturated()` at ONE substrate site with ONE short-
2767 /// circuit walk (returns at the first missing slot), rather than
2768 /// reaching for either `missing_kind_count() == 0` (which walks
2769 /// every slot) or `populated_kind_count() == ALL.len()` (same
2770 /// cost, different axis).
2771 /// - An operator-facing "over-populated carrier" diagnostic that
2772 /// surfaces the pathological case where every slot on a `N ≥ 2`
2773 /// tagged union is populated reads `parent.is_saturated()` at
2774 /// ONE substrate site — one short-circuit walk, no allocation.
2775 /// - An `is-saturated` require-tag classifier arm reaches this
2776 /// primitive at ONE call site, byte-for-byte symmetrical with
2777 /// the sibling `is-empty` arm.
2778 /// - A coherence check verifying "no production tagged union has
2779 /// ever been observed saturated" reads `!parent.is_saturated()`
2780 /// at ONE site — the substrate's structural pin on the top-arm
2781 /// of the cardinality lattice.
2782 ///
2783 /// A new [`Self::Kind`] variant added to
2784 /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) reaches
2785 /// this primitive mechanically (the closed-set walk picks up the
2786 /// new entry as an additional short-circuit slot — a parent that
2787 /// was previously saturated is no longer saturated at every
2788 /// downstream callsite unless it also populates the new slot; a
2789 /// parent that populates every slot including the new one
2790 /// continues to return `true`).
2791 ///
2792 /// # Theory grounding
2793 ///
2794 /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
2795 /// The Boolean cardinality-top-endpoint projection lives at ONE
2796 /// substrate site as a typed short-circuiting closed-set walk
2797 /// `<Self::Kind as ClosedSet>::ALL.iter().all(has)` — byte-for-
2798 /// byte peer of `missing_kind_count()` composed against `== 0`,
2799 /// but without the counter allocation on every arm and with a
2800 /// first-missing-slot short-circuit that neither widened
2801 /// primitive offers.
2802 /// - THEORY.md §VI.1 — generation over composition. A new
2803 /// [`Self::Kind`] variant added to `ALL` reaches this primitive
2804 /// mechanically through the `all` short-circuit.
2805 fn is_saturated(&self) -> bool {
2806 self.iter_missing_kinds().next().is_none()
2807 }
2808
2809 /// Boolean cardinality "at-least-one" peer of
2810 /// [`Self::populated_kinds`] — `true` iff AT LEAST ONE slot on this
2811 /// tagged union is populated (i.e. the populated set is NON-empty).
2812 ///
2813 /// Default body:
2814 /// `<Self::Kind as ClosedSet>::ALL.iter().copied().any(|k| self.has(k))`
2815 /// — a short-circuiting closed-set walk under [`Self::has`] that
2816 /// returns `true` at the FIRST populated slot, WITHOUT materializing
2817 /// the [`Vec`] `populated_kinds` would build and WITHOUT paying for
2818 /// the `usize` `populated_kind_count` would count. The `any`
2819 /// composition short-circuits at the FIRST populated slot on every
2820 /// non-empty arm — strictly cheaper than either widened primitive
2821 /// `populated_kind_count() > 0` (which walks every slot) or
2822 /// `!populated_kinds().is_empty()` (which pays for the `Vec`
2823 /// allocation before the emptiness check).
2824 ///
2825 /// # Sibling to [`Self::is_empty`]
2826 ///
2827 /// Definitional-complement Boolean peer on the SAME populated
2828 /// cardinality axis: where [`Self::is_empty`] names the zero-arm
2829 /// (0 populated), `has_any_populated_kind` names the ≥ 1 halfspace
2830 /// (any positive cardinality). The composition law
2831 /// `has_any_populated_kind() == !is_empty()` binds the two primitives
2832 /// at the trait's default body — one bit-flip past [`Self::is_empty`]'s
2833 /// `!any` short-circuit. Byte-for-byte peer of
2834 /// [`Self::has_any_missing_kind`] under the (populated, missing)
2835 /// complement axis: where `has_any_missing_kind` names the ≥ 1
2836 /// missing halfspace via the negated `has`, this primitive names
2837 /// the ≥ 1 populated halfspace via the plain `has`.
2838 ///
2839 /// # Cardinality-grid closure
2840 ///
2841 /// Third row of the Boolean cardinality grid on the tagged-union
2842 /// parent axis — the SUBSET side of the complement dichotomy between
2843 /// the zero-arm and the at-least-one halfspace. The four rows now
2844 /// close the {0, ≥1, =1, ≥2} cardinality lattice on both the
2845 /// populated and missing axes:
2846 ///
2847 /// | | populated axis | missing axis |
2848 /// |----------------|-----------------------------------------|----------------------------------------|
2849 /// | ZERO (== 0) | [`Self::is_empty`] | [`Self::is_saturated`] |
2850 /// | AT LEAST ONE | `has_any_populated_kind` (this) | [`Self::has_any_missing_kind`] |
2851 /// | UNIQUE (== 1) | [`Self::has_unique_populated_kind`] | [`Self::has_unique_missing_kind`] |
2852 /// | AT LEAST TWO | [`Self::has_multiple_populated_kinds`] | [`Self::has_multiple_missing_kinds`] |
2853 ///
2854 /// The AT LEAST ONE row partitions the ZERO row's exhaustive
2855 /// complement — for any given parent, `is_empty()` and
2856 /// `has_any_populated_kind()` XOR to `true` (exactly one returns
2857 /// `true`). The row is ALSO the disjunction of the UNIQUE and AT
2858 /// LEAST TWO rows: `has_any_populated_kind() ==
2859 /// has_unique_populated_kind() || has_multiple_populated_kinds()`
2860 /// — the {=1, ≥2} refinement of the ≥ 1 halfspace at ONE substrate
2861 /// site.
2862 ///
2863 /// # Truth table on the exactly-one-slot tagged-union contract
2864 ///
2865 /// For a tagged union with `<Self::Kind as ClosedSet>::ALL` of
2866 /// cardinality `N ≥ 1`:
2867 ///
2868 /// - Empty parent (0 populated, N missing): `false` — the SOLE arm
2869 /// where `has_any_populated_kind` returns `false`.
2870 /// - Well-formed parent (1 populated, N-1 missing): `true`.
2871 /// - K-populated parent for `1 ≤ K ≤ N`: `true`.
2872 /// - Saturated parent (N populated, 0 missing): `true`.
2873 ///
2874 /// # Compounding future consumers
2875 ///
2876 /// - A boundary-progress "any content at all" diagnostic on an
2877 /// aggregate condition-carrier reads
2878 /// `parent.has_any_populated_kind()` at ONE substrate site — one
2879 /// short-circuit walk, no allocation, and no readerly parse of
2880 /// `!parent.is_empty()` inversion at the callsite.
2881 /// - An `is-non-empty` require-tag classifier arm reaches this
2882 /// primitive at ONE call site — the SUBSET peer of the sibling
2883 /// `is-empty` classifier arm, byte-for-byte symmetrical with the
2884 /// sibling `has-any-missing-kind` arm under the (populated,
2885 /// missing) complement axis.
2886 /// - A fast-path branch that discriminates "some populated" from
2887 /// "all missing" (the resolver's non-`Empty`-arm halfspace) reads
2888 /// `parent.has_any_populated_kind()` at ONE call site — same
2889 /// FIRST-populated-slot short-circuit as [`Self::is_empty`], no
2890 /// inversion.
2891 /// - A coherence check verifying "every production parent from a
2892 /// `single_slot_X` factory is NON-empty" reads
2893 /// `parent.has_any_populated_kind()` at ONE site rather than
2894 /// `!parent.is_empty()` (which asks the reader to invert the
2895 /// parse) or `parent.populated_kind_count() > 0` (which walks
2896 /// every slot).
2897 ///
2898 /// A new [`Self::Kind`] variant added to
2899 /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) reaches
2900 /// this primitive mechanically — the `any` short-circuit picks up
2901 /// the new slot as an additional first-hit candidate at every
2902 /// downstream callsite without further per-caller edit.
2903 ///
2904 /// # Theory grounding
2905 ///
2906 /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
2907 /// The Boolean at-least-one projection on the populated axis
2908 /// lives at ONE substrate site as a typed short-circuiting
2909 /// closed-set walk `<Self::Kind as ClosedSet>::ALL.iter().any(has)`
2910 /// — byte-for-byte definitional complement of [`Self::is_empty`]'s
2911 /// `!<ALL>.iter().any(has)`, semantically identical to
2912 /// `populated_kind_count() > 0` on every arm with the same
2913 /// first-hit short-circuit that [`Self::is_empty`] enjoys.
2914 /// - THEORY.md §VI.1 — generation over composition. A new
2915 /// [`Self::Kind`] variant added to `ALL` reaches this primitive
2916 /// mechanically through the `any` short-circuit.
2917 fn has_any_populated_kind(&self) -> bool {
2918 self.iter_populated_kinds().next().is_some()
2919 }
2920
2921 /// Boolean cardinality "at-least-one" peer of [`Self::missing_kinds`]
2922 /// — `true` iff AT LEAST ONE slot on this tagged union is missing
2923 /// (i.e. the missing set is NON-empty).
2924 ///
2925 /// Default body:
2926 /// `<Self::Kind as ClosedSet>::ALL.iter().copied().any(|k| !self.has(k))`
2927 /// — a short-circuiting closed-set walk under a NEGATED [`Self::has`]
2928 /// that returns `true` at the FIRST missing slot, WITHOUT
2929 /// materializing the [`Vec`] `missing_kinds` would build and WITHOUT
2930 /// paying for the `usize` `missing_kind_count` would count. The
2931 /// `any` composition short-circuits at the FIRST missing slot on
2932 /// every non-saturated arm — strictly cheaper than either widened
2933 /// primitive `missing_kind_count() > 0` (which walks every slot) or
2934 /// `!missing_kinds().is_empty()` (which pays for the `Vec`
2935 /// allocation before the emptiness check).
2936 ///
2937 /// # Sibling to [`Self::is_saturated`]
2938 ///
2939 /// Definitional-complement Boolean peer on the SAME missing
2940 /// cardinality axis: where [`Self::is_saturated`] names the zero-arm
2941 /// (0 missing), `has_any_missing_kind` names the ≥ 1 missing
2942 /// halfspace (any positive missing cardinality). The composition
2943 /// law `has_any_missing_kind() == !is_saturated()` binds the two
2944 /// primitives at the trait's default body — one bit-flip past
2945 /// [`Self::is_saturated`]'s `all` short-circuit. Byte-for-byte peer
2946 /// of [`Self::has_any_populated_kind`] under the (populated,
2947 /// missing) complement axis: where `has_any_populated_kind` names
2948 /// the ≥ 1 populated halfspace via the plain `has`, this primitive
2949 /// names the ≥ 1 missing halfspace via the negated `has`.
2950 ///
2951 /// # Cardinality-grid closure
2952 ///
2953 /// Third row of the Boolean cardinality grid on the tagged-union
2954 /// parent axis — see [`Self::has_any_populated_kind`] for the full
2955 /// grid. The disjunctive decomposition
2956 /// `has_any_missing_kind() == has_unique_missing_kind() ||
2957 /// has_multiple_missing_kinds()` binds the ≥ 1 halfspace to the
2958 /// {=1, ≥2} refinement at ONE substrate site — byte-for-byte peer
2959 /// of the populated-axis disjunctive decomposition.
2960 ///
2961 /// # Truth table on the exactly-one-slot tagged-union contract
2962 ///
2963 /// For a tagged union with `<Self::Kind as ClosedSet>::ALL` of
2964 /// cardinality `N ≥ 1`:
2965 ///
2966 /// - Empty parent (0 populated, N missing): `true` — the empty
2967 /// parent has EVERY slot missing.
2968 /// - Well-formed parent (1 populated, N-1 missing): `true` on any
2969 /// `N ≥ 2`. On the degenerate `N == 1` closed set the well-formed
2970 /// parent has 0 missing, so `has_any_missing_kind()` returns
2971 /// `false` — but real-world tagged unions in this workspace all
2972 /// have `N ≥ 2`.
2973 /// - K-populated parent for `0 ≤ K < N`: `true`.
2974 /// - Saturated parent (N populated, 0 missing): `false` — the SOLE
2975 /// arm where `has_any_missing_kind` returns `false`.
2976 ///
2977 /// # Compounding future consumers
2978 ///
2979 /// - An operator-facing "not fully populated" diagnostic on an
2980 /// aggregate condition-carrier reads
2981 /// `parent.has_any_missing_kind()` at ONE substrate site — one
2982 /// short-circuit walk, no allocation, no readerly parse of
2983 /// `!parent.is_saturated()` inversion at the callsite.
2984 /// - A `has-any-missing-kind` require-tag classifier arm reaches
2985 /// this primitive at ONE call site — the SUBSET peer of the
2986 /// sibling `is-saturated` classifier arm, closed-set-complement
2987 /// mirror of `has-any-populated-kind` on the populated axis.
2988 /// - A fast-path branch that discriminates "any slot still absent"
2989 /// from "over-populated / saturated" reads
2990 /// `parent.has_any_missing_kind()` at ONE call site — same
2991 /// FIRST-missing-slot short-circuit as [`Self::is_saturated`],
2992 /// no inversion.
2993 /// - A coherence check verifying "no production parent from a
2994 /// `single_slot_X` factory is saturated" reads
2995 /// `parent.has_any_missing_kind()` at ONE site — every
2996 /// `ALL.len() ≥ 2` well-formed parent leaves `ALL.len() - 1 ≥ 1`
2997 /// slot missing, so this predicate is a substrate structural pin
2998 /// on the well-formed diagonal.
2999 ///
3000 /// A new [`Self::Kind`] variant added to
3001 /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) reaches
3002 /// this primitive mechanically — the `any` short-circuit picks up
3003 /// the new slot as an additional first-hit candidate at every
3004 /// downstream callsite without further per-caller edit.
3005 ///
3006 /// # Theory grounding
3007 ///
3008 /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
3009 /// The Boolean at-least-one projection on the missing axis lives
3010 /// at ONE substrate site as a typed short-circuiting closed-set
3011 /// walk `<Self::Kind as ClosedSet>::ALL.iter().any(|k| !has(k))`
3012 /// — byte-for-byte definitional complement of
3013 /// [`Self::is_saturated`]'s `<ALL>.iter().all(has)` (via the De
3014 /// Morgan dual), semantically identical to
3015 /// `missing_kind_count() > 0` on every arm with the same first-
3016 /// hit short-circuit that [`Self::is_saturated`] enjoys.
3017 /// - THEORY.md §VI.1 — generation over composition. A new
3018 /// [`Self::Kind`] variant added to `ALL` reaches this primitive
3019 /// mechanically through the `any` short-circuit.
3020 fn has_any_missing_kind(&self) -> bool {
3021 self.iter_missing_kinds().next().is_some()
3022 }
3023
3024 /// Boolean cardinality-mid-endpoint peer of
3025 /// [`Self::unique_populated_kind`] — `true` iff EXACTLY ONE slot on
3026 /// this tagged union is populated.
3027 ///
3028 /// Default body: `self.unique_populated_kind().is_some()` — the
3029 /// Boolean projection of the two-step-short-circuit closed-set walk
3030 /// [`Self::unique_populated_kind`] already performs, without paying
3031 /// for the [`Vec`] `populated_kinds` would build or the counter
3032 /// walk `populated_kind_count` would perform. The `unique_*`
3033 /// primitive short-circuits at the SECOND populated slot on the
3034 /// malformed arms, so the `is_some` projection here short-circuits
3035 /// on the same schedule — strictly cheaper than the widened
3036 /// primitives on every arm where the parent has ≥ 2 populated
3037 /// slots.
3038 ///
3039 /// # Sibling to [`Self::populated_kind_count`]
3040 ///
3041 /// Boolean cardinality-mid-endpoint peer of the scalar cardinality
3042 /// primitive — where `populated_kind_count` returns the FULL scalar
3043 /// (any `usize` in `0..=ALL.len()`), `has_unique_populated_kind`
3044 /// collapses that scalar to its one-arm Boolean projection. The
3045 /// composition law
3046 /// `has_unique_populated_kind() == (populated_kind_count() == 1)`
3047 /// binds the Boolean projection to the scalar primitive at the
3048 /// trait's default body — swept substrate-wide by
3049 /// [`assert_has_unique_populated_kind_matches_populated_kind_count`].
3050 /// Together with [`Self::is_empty`] (zero-arm of the populated
3051 /// axis) and [`Self::is_saturated`] (zero-arm of the missing
3052 /// axis), these three Boolean cardinality primitives close the
3053 /// substrate's 2×2 endpoint grid on the tagged-union parent axis:
3054 ///
3055 /// | | populated | missing |
3056 /// |----------|-------------------------------|--------------------------------|
3057 /// | zero-arm | [`Self::is_empty`] | [`Self::is_saturated`] |
3058 /// | one-arm | [`Self::has_unique_populated_kind`] | [`Self::has_unique_missing_kind`] |
3059 ///
3060 /// # Truth table on the exactly-one-slot tagged-union contract
3061 ///
3062 /// For a tagged union with `<Self::Kind as ClosedSet>::ALL` of
3063 /// cardinality `N ≥ 2`:
3064 ///
3065 /// - Empty parent (0 populated, N missing): `false`.
3066 /// - Well-formed parent (1 populated, N-1 missing): `true` — the
3067 /// SOLE arm where `has_unique_populated_kind` returns `true`.
3068 /// Aligns with [`Self::variant`]'s `Ok` arm (the single-populated
3069 /// arm where the resolver returns exactly one variant) — this
3070 /// primitive is the `bool`-valued projection of that Ok arm.
3071 /// - K-populated parent for `K ≥ 2`: `false`.
3072 /// - Saturated parent (N populated, 0 missing on any `N ≥ 2`
3073 /// closed set): `false`.
3074 ///
3075 /// # Compounding future consumers
3076 ///
3077 /// - A fast-path branch that discriminates "well-formed" from
3078 /// "empty or ambiguous" reads `parent.has_unique_populated_kind()`
3079 /// at ONE substrate site with the same two-step short-circuit
3080 /// walk `unique_populated_kind` already performs, rather than
3081 /// reaching for `parent.variant().is_ok()` (which pays for the
3082 /// borrowed-view projection AND the error-carrier
3083 /// materialization on failing arms) or
3084 /// `parent.populated_kind_count() == 1` (which walks every slot).
3085 /// - An operator-facing "well-formed" diagnostic on the resolver's
3086 /// Ok arm reads `parent.has_unique_populated_kind()` at ONE
3087 /// substrate site — one two-step short-circuit walk, no
3088 /// allocation, no borrowed-view materialization.
3089 /// - A `has-unique-populated-kind` require-tag classifier arm
3090 /// reaches this primitive at ONE call site, byte-for-byte
3091 /// symmetrical with the sibling `is-empty` / `is-saturated` /
3092 /// `has-unique-missing-kind` arms across the closed 2×2 grid.
3093 /// - A coherence check verifying "every production parent from a
3094 /// `single_slot_X` factory is well-formed" reads
3095 /// `parent.has_unique_populated_kind()` at ONE site rather than
3096 /// the widened-primitive composition
3097 /// `parent.populated_kind_count() == 1`.
3098 ///
3099 /// A new [`Self::Kind`] variant added to
3100 /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) reaches
3101 /// this primitive mechanically through the `unique_populated_kind`
3102 /// short-circuit (the closed-set walk picks up the new entry as an
3103 /// additional short-circuit slot — a parent that populates ONLY
3104 /// the new variant returns `true` at every downstream callsite
3105 /// without further per-caller edit).
3106 ///
3107 /// # Theory grounding
3108 ///
3109 /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
3110 /// The Boolean cardinality-mid-endpoint projection lives at ONE
3111 /// substrate site as the `is_some` projection of the
3112 /// `unique_populated_kind` two-step short-circuit walk — byte-
3113 /// for-byte peer of `populated_kind_count()` composed against
3114 /// `== 1`, but with a second-populated-slot short-circuit that
3115 /// the scalar counter primitive does not offer.
3116 /// - THEORY.md §VI.1 — generation over composition. A new
3117 /// [`Self::Kind`] variant added to `ALL` reaches this primitive
3118 /// mechanically through the `unique_populated_kind` short-circuit.
3119 fn has_unique_populated_kind(&self) -> bool {
3120 self.unique_populated_kind().is_some()
3121 }
3122
3123 /// Boolean cardinality-mid-endpoint peer of
3124 /// [`Self::unique_missing_kind`] — `true` iff EXACTLY ONE slot on
3125 /// this tagged union is missing.
3126 ///
3127 /// Default body: `self.unique_missing_kind().is_some()` — the
3128 /// Boolean projection of the two-step-short-circuit closed-set
3129 /// walk [`Self::unique_missing_kind`] already performs under a
3130 /// negated `has` predicate, without paying for the [`Vec`]
3131 /// `missing_kinds` would build or the counter walk
3132 /// `missing_kind_count` would perform. The `unique_*` primitive
3133 /// short-circuits at the SECOND missing slot on the partial arms,
3134 /// so the `is_some` projection here short-circuits on the same
3135 /// schedule — strictly cheaper than the widened primitives on
3136 /// every arm where the parent has ≥ 2 missing slots.
3137 ///
3138 /// # Sibling to [`Self::missing_kind_count`]
3139 ///
3140 /// Boolean cardinality-mid-endpoint peer of the scalar complement
3141 /// cardinality primitive — where `missing_kind_count` returns the
3142 /// FULL scalar (any `usize` in `0..=ALL.len()`),
3143 /// `has_unique_missing_kind` collapses that scalar to its one-arm
3144 /// Boolean projection. The composition law
3145 /// `has_unique_missing_kind() == (missing_kind_count() == 1)`
3146 /// binds the Boolean projection to the scalar primitive at the
3147 /// trait's default body — swept substrate-wide by
3148 /// [`assert_has_unique_missing_kind_matches_missing_kind_count`].
3149 /// Byte-for-byte symmetrical with [`Self::has_unique_populated_kind`]
3150 /// under the (populated, missing) complement axis.
3151 ///
3152 /// # Truth table on the exactly-one-slot tagged-union contract
3153 ///
3154 /// For a tagged union with `<Self::Kind as ClosedSet>::ALL` of
3155 /// cardinality `N ≥ 2`:
3156 ///
3157 /// - Empty parent (0 populated, N missing): `false` on any
3158 /// `N ≥ 2` closed set (on the degenerate `N == 1` closed set
3159 /// empty and one-missing coincide; no production tagged union
3160 /// in this workspace has `N == 1`).
3161 /// - Well-formed parent (1 populated, N-1 missing): `false` on
3162 /// any `N ≥ 3` closed set. On `N == 2` well-formed and one-
3163 /// missing coincide — the primitive returns `true` because
3164 /// `N - 1 == 1`.
3165 /// - K-populated parent for `2 ≤ K ≤ N-1` on `N ≥ 3` closed sets:
3166 /// `false` in general; `true` only on the `(N-1)`-populated arm
3167 /// (near-saturation, one slot missing).
3168 /// - Saturated parent (N populated, 0 missing): `false`.
3169 ///
3170 /// # Compounding future consumers
3171 ///
3172 /// - A fast-path branch on the near-saturation arm (exactly one
3173 /// slot missing, structurally malformed on any `N ≥ 3` tagged
3174 /// union in that it composes multiple populated slots) reads
3175 /// `parent.has_unique_missing_kind()` at ONE substrate site
3176 /// with the same two-step short-circuit walk
3177 /// `unique_missing_kind` already performs, rather than reaching
3178 /// for `parent.missing_kind_count() == 1` (which walks every
3179 /// slot).
3180 /// - An operator-facing "one slot away from saturated" diagnostic
3181 /// on the near-saturation arm reads
3182 /// `parent.has_unique_missing_kind()` at ONE substrate site.
3183 /// - A `has-unique-missing-kind` require-tag classifier arm
3184 /// reaches this primitive at ONE call site, byte-for-byte
3185 /// symmetrical with the sibling `has-unique-populated-kind` arm
3186 /// under the (populated, missing) complement axis.
3187 ///
3188 /// A new [`Self::Kind`] variant added to
3189 /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) reaches
3190 /// this primitive mechanically through the `unique_missing_kind`
3191 /// short-circuit.
3192 ///
3193 /// # Theory grounding
3194 ///
3195 /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
3196 /// The Boolean cardinality-mid-endpoint projection on the
3197 /// missing axis lives at ONE substrate site as the `is_some`
3198 /// projection of the `unique_missing_kind` two-step short-circuit
3199 /// walk — byte-for-byte peer of `missing_kind_count()` composed
3200 /// against `== 1`, but with a second-missing-slot short-circuit
3201 /// that the scalar counter primitive does not offer.
3202 /// - THEORY.md §VI.1 — generation over composition. A new
3203 /// [`Self::Kind`] variant added to `ALL` reaches this primitive
3204 /// mechanically through the `unique_missing_kind` short-circuit.
3205 fn has_unique_missing_kind(&self) -> bool {
3206 self.unique_missing_kind().is_some()
3207 }
3208
3209 /// Boolean cardinality many-arm peer of
3210 /// [`Self::has_unique_populated_kind`] — `true` iff TWO OR MORE
3211 /// slots on this tagged union are populated.
3212 ///
3213 /// Default body: a two-step-short-circuit closed-set walk under
3214 /// [`Self::has`] that pulls two hits off the filtered iterator
3215 /// and returns `true` iff both are `Some`, WITHOUT paying for the
3216 /// [`Vec`] `populated_kinds` would build or the counter walk
3217 /// `populated_kind_count` would perform. Short-circuits at the
3218 /// SECOND populated slot — strictly cheaper than either widened
3219 /// primitive on every arm past the second populated slot.
3220 ///
3221 /// # Sibling to the Boolean cardinality trichotomy
3222 ///
3223 /// Third arm of the {0, 1, ≥2} cardinality trichotomy on the
3224 /// populated axis, closing the natural partition alongside
3225 /// [`Self::is_empty`] (zero-arm) and
3226 /// [`Self::has_unique_populated_kind`] (one-arm). Every tagged-
3227 /// union state satisfies EXACTLY ONE of the three predicates —
3228 /// the three Boolean projections partition
3229 /// `0..=<Self::Kind as ClosedSet>::ALL.len()` at 0, 1, and ≥2
3230 /// respectively. Maps directly onto the three arms of the
3231 /// resolver contract [`Self::variant`] returns:
3232 ///
3233 /// | populated count | Boolean primitive | `variant()` |
3234 /// |-----------------|-----------------------------------------|-------------------------|
3235 /// | 0 | [`Self::is_empty`] | `Err(Error::empty)` |
3236 /// | 1 | [`Self::has_unique_populated_kind`] | `Ok(Variant)` |
3237 /// | ≥ 2 | `has_multiple_populated_kinds` (this) | `Err(Error::ambiguous)` |
3238 ///
3239 /// The composition law `has_multiple_populated_kinds() ==
3240 /// (populated_kind_count() >= 2)` binds the Boolean projection
3241 /// to the scalar primitive at the trait's default body — swept
3242 /// substrate-wide by
3243 /// [`assert_has_multiple_populated_kinds_matches_populated_kind_count`].
3244 ///
3245 /// # Truth table on the exactly-one-slot tagged-union contract
3246 ///
3247 /// For a tagged union with `<Self::Kind as ClosedSet>::ALL` of
3248 /// cardinality `N ≥ 2`:
3249 ///
3250 /// - Empty parent (0 populated): `false`.
3251 /// - Well-formed parent (1 populated): `false`.
3252 /// - K-populated parent for `K ≥ 2`: `true`.
3253 /// - Saturated parent (N populated, `N ≥ 2`): `true`.
3254 ///
3255 /// # Compounding future consumers
3256 ///
3257 /// - A fast-path branch that discriminates "ambiguous" from
3258 /// "empty or well-formed" reads
3259 /// `parent.has_multiple_populated_kinds()` at ONE substrate
3260 /// site with a two-step short-circuit walk, rather than
3261 /// `parent.variant().is_err_and(|e| matches!(e,
3262 /// TaggedUnionError::Ambiguous))` (which materializes the
3263 /// borrowed-view AND the error-carrier) or
3264 /// `parent.populated_kind_count() >= 2` (which walks every
3265 /// slot).
3266 /// - An operator-facing "over-populated / ambiguous carrier"
3267 /// diagnostic reads `parent.has_multiple_populated_kinds()`
3268 /// at ONE substrate site — one two-step short-circuit walk,
3269 /// no allocation.
3270 /// - A `has-multiple-populated-kinds` require-tag classifier
3271 /// arm reaches this primitive at ONE call site, byte-for-byte
3272 /// symmetrical with the sibling zero-arm / one-arm classifier
3273 /// arms across the closed 2×3 grid.
3274 ///
3275 /// A new [`Self::Kind`] variant added to
3276 /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) reaches
3277 /// this primitive mechanically — the closed-set walk picks up
3278 /// the new slot as an additional two-step-short-circuit
3279 /// candidate.
3280 ///
3281 /// # Theory grounding
3282 ///
3283 /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
3284 /// The Boolean cardinality many-arm projection lives at ONE
3285 /// substrate site as a typed two-step-short-circuit walk over
3286 /// `<Self::Kind as ClosedSet>::ALL` under [`Self::has`] — byte-
3287 /// for-byte peer of `populated_kind_count()` composed against
3288 /// `>= 2`, but with a second-populated-slot short-circuit that
3289 /// the scalar counter primitive does not offer.
3290 /// - THEORY.md §VI.1 — generation over composition. A new
3291 /// [`Self::Kind`] variant added to `ALL` reaches this
3292 /// primitive mechanically.
3293 fn has_multiple_populated_kinds(&self) -> bool {
3294 let mut iter = self.iter_populated_kinds();
3295 iter.next().is_some() && iter.next().is_some()
3296 }
3297
3298 /// Boolean cardinality many-arm peer of
3299 /// [`Self::has_unique_missing_kind`] — `true` iff TWO OR MORE
3300 /// slots on this tagged union are missing.
3301 ///
3302 /// Default body: a two-step-short-circuit closed-set walk under
3303 /// a NEGATED [`Self::has`] predicate that pulls two hits off the
3304 /// filtered iterator and returns `true` iff both are `Some`.
3305 /// Byte-for-byte peer of [`Self::has_multiple_populated_kinds`]
3306 /// under the (populated, missing) complement axis.
3307 ///
3308 /// # Sibling to the Boolean cardinality trichotomy
3309 ///
3310 /// Third arm of the {0, 1, ≥2} cardinality trichotomy on the
3311 /// missing axis, closing the natural partition alongside
3312 /// [`Self::is_saturated`] (zero-arm) and
3313 /// [`Self::has_unique_missing_kind`] (one-arm). The composition
3314 /// law `has_multiple_missing_kinds() == (missing_kind_count() >=
3315 /// 2)` binds the Boolean projection to the scalar complement
3316 /// cardinality primitive at the trait's default body — swept
3317 /// substrate-wide by
3318 /// [`assert_has_multiple_missing_kinds_matches_missing_kind_count`].
3319 ///
3320 /// # Truth table on the exactly-one-slot tagged-union contract
3321 ///
3322 /// For a tagged union with `<Self::Kind as ClosedSet>::ALL` of
3323 /// cardinality `N`:
3324 ///
3325 /// - Empty parent (0 populated, N missing): `true` iff `N ≥ 2`
3326 /// (every production union in the workspace).
3327 /// - Well-formed parent (1 populated, N-1 missing): `true` iff
3328 /// `N ≥ 3`. On `N == 2` the well-formed arm has exactly one
3329 /// missing slot, so this primitive returns `false`.
3330 /// - K-populated parent for `K ≤ N-2`: `true`.
3331 /// - Near-saturated parent (N-1 populated, 1 missing): `false`
3332 /// (exactly one missing, not many).
3333 /// - Saturated parent (N populated, 0 missing): `false`.
3334 ///
3335 /// # Compounding future consumers
3336 ///
3337 /// - A fast-path branch that discriminates "≥ 2 slots still
3338 /// unfulfilled" from "0 or 1 slot still unfulfilled" (an
3339 /// aggregate boundary progress-guard: at least two conditions
3340 /// still open) reads `parent.has_multiple_missing_kinds()` at
3341 /// ONE substrate site.
3342 /// - An operator-facing "≥ 2 dependencies still unfulfilled"
3343 /// diagnostic reads `parent.has_multiple_missing_kinds()` at
3344 /// ONE substrate site — one two-step short-circuit walk under
3345 /// the negated predicate.
3346 /// - A `has-multiple-missing-kinds` require-tag classifier arm
3347 /// reaches this primitive at ONE call site, byte-for-byte
3348 /// symmetrical with `has_multiple_populated_kinds` under the
3349 /// complement axis.
3350 ///
3351 /// # Theory grounding
3352 ///
3353 /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
3354 /// - THEORY.md §VI.1 — generation over composition.
3355 fn has_multiple_missing_kinds(&self) -> bool {
3356 let mut iter = self.iter_missing_kinds();
3357 iter.next().is_some() && iter.next().is_some()
3358 }
3359
3360 /// Boolean cardinality "≤ 1" peer of
3361 /// [`Self::has_multiple_populated_kinds`] — `true` iff AT MOST ONE
3362 /// slot on this tagged union is populated (i.e. zero or one
3363 /// populated slot).
3364 ///
3365 /// Default body: the definitional Boolean negation
3366 /// `!self.has_multiple_populated_kinds()` — one bit-flip over the
3367 /// SAME two-step-short-circuit closed-set walk that
3368 /// [`Self::has_multiple_populated_kinds`] already runs, without
3369 /// re-authoring the fused loop and WITHOUT a second walk over the
3370 /// closed set. Strictly cheaper than either widened composition
3371 /// `self.is_empty() || self.has_unique_populated_kind()` (which
3372 /// walks the closed set TWICE — once under `all-missing`, once
3373 /// under `exactly-one`) or `self.populated_kind_count() <= 1`
3374 /// (which walks the closed set fully counting hits) on every arm.
3375 ///
3376 /// # Sibling to the Boolean cardinality "≥ 2" primitive
3377 ///
3378 /// Boolean-negation peer under `!(≥ 2) == (≤ 1)` — where
3379 /// [`Self::has_multiple_populated_kinds`] names the AMBIGUOUS arm
3380 /// of the resolver contract (the arm [`Self::variant`] returns
3381 /// `Err(Error::ambiguous)` on), `has_at_most_one_populated_kind`
3382 /// names its complement — the RESOLVEABLE-OR-EMPTY arm (the two
3383 /// arms of the resolver contract that DON'T return
3384 /// `Err(Error::ambiguous)`, i.e. `Ok(Variant)` OR
3385 /// `Err(Error::empty)`). The typed predicate for "this parent is
3386 /// not ambiguous" without inverting a
3387 /// `!parent.has_multiple_populated_kinds()` at every callsite.
3388 ///
3389 /// # Composition laws
3390 ///
3391 /// - `has_at_most_one_populated_kind() == !has_multiple_populated_kinds()`
3392 /// — the definitional Boolean negation, at the trait default
3393 /// body's SAME fused short-circuit walk.
3394 /// - `has_at_most_one_populated_kind() == (populated_kind_count() <= 1)`
3395 /// — the scalar cardinality composition.
3396 /// - `has_at_most_one_populated_kind() == is_empty() || has_unique_populated_kind()`
3397 /// — the union of the zero-arm and the one-arm of the
3398 /// {0, 1, ≥ 2} cardinality trichotomy.
3399 ///
3400 /// All three laws hold on every arm and every closed-set kind —
3401 /// pinned as first-class typed invariants by the trait's own
3402 /// default body and swept substrate-wide by
3403 /// [`assert_has_at_most_one_populated_kind_matches_populated_kind_count`].
3404 ///
3405 /// # Truth table on the exactly-one-slot tagged-union contract
3406 ///
3407 /// For a tagged union with `<Self::Kind as ClosedSet>::ALL` of
3408 /// cardinality `N ≥ 2`:
3409 ///
3410 /// - Empty parent (0 populated, N missing): `true` (0 ≤ 1).
3411 /// - Well-formed parent (1 populated, N-1 missing): `true` (1 ≤ 1)
3412 /// — the SOLE `Ok` arm of [`Self::variant`] lies inside the
3413 /// at-most-one region.
3414 /// - K-populated parent for `K ≥ 2`: `false` (K > 1).
3415 /// - Saturated parent (N populated, 0 missing on any `N ≥ 2`):
3416 /// `false` (N ≥ 2 > 1).
3417 ///
3418 /// # Compounding future consumers
3419 ///
3420 /// - A fast-path branch on the resolver-clean arm that
3421 /// discriminates "not ambiguous" (0 or 1 populated) from
3422 /// "ambiguous" (≥ 2 populated) reads
3423 /// `parent.has_at_most_one_populated_kind()` at ONE substrate
3424 /// site — one two-step short-circuit walk with a bit-flip,
3425 /// strictly cheaper than the widened union of the zero-arm and
3426 /// one-arm.
3427 /// - An operator-facing "at most one populated variant" diagnostic
3428 /// (the guard for downstream code that assumes non-ambiguous
3429 /// dispatch) reads this primitive at ONE substrate site.
3430 /// - A `has-at-most-one-populated-kind` require-tag classifier arm
3431 /// reaches this primitive at ONE call site, closing the
3432 /// {0, 1, ≥ 2, ≤ 1} cardinality-Boolean grid alongside its
3433 /// sibling `has-multiple-populated-kinds` under the Boolean
3434 /// negation axis.
3435 ///
3436 /// A new [`Self::Kind`] variant added to
3437 /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) reaches
3438 /// this primitive mechanically through the delegated
3439 /// [`Self::has_multiple_populated_kinds`] — the fused walk picks
3440 /// up the new slot as an additional short-circuit candidate at
3441 /// every downstream callsite without further per-caller edit.
3442 ///
3443 /// # Theory grounding
3444 ///
3445 /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
3446 /// The "≤ 1" Boolean projection lives at ONE substrate site as
3447 /// a definitional negation of the "≥ 2" projection; the two
3448 /// forms `!has_multiple_populated_kinds()`,
3449 /// `populated_kind_count() <= 1`, and
3450 /// `is_empty() || has_unique_populated_kind()` compose through
3451 /// the SAME two-step-short-circuit walk shape, byte-for-byte
3452 /// identical on every arm.
3453 /// - THEORY.md §VI.1 — generation over composition. A new
3454 /// [`Self::Kind`] variant added to `ALL` reaches this primitive
3455 /// mechanically through the delegated
3456 /// [`Self::has_multiple_populated_kinds`].
3457 fn has_at_most_one_populated_kind(&self) -> bool {
3458 !self.has_multiple_populated_kinds()
3459 }
3460
3461 /// Boolean cardinality "≤ 1" peer of
3462 /// [`Self::has_multiple_missing_kinds`] — `true` iff AT MOST ONE
3463 /// slot on this tagged union is missing (i.e. zero or one missing
3464 /// slot).
3465 ///
3466 /// Default body: the definitional Boolean negation
3467 /// `!self.has_multiple_missing_kinds()` — one bit-flip over the
3468 /// SAME two-step-short-circuit closed-set walk under a NEGATED
3469 /// [`Self::has`] predicate that [`Self::has_multiple_missing_kinds`]
3470 /// already runs, without re-authoring the fused loop and WITHOUT a
3471 /// second walk over the closed set. Strictly cheaper than either
3472 /// widened composition
3473 /// `self.is_saturated() || self.has_unique_missing_kind()` (which
3474 /// walks the closed set TWICE — once under `all-populated`, once
3475 /// under `exactly-one-missing`) or `self.missing_kind_count() <= 1`
3476 /// (which walks the closed set fully counting missing hits) on
3477 /// every arm.
3478 ///
3479 /// # Sibling to the Boolean cardinality "≥ 2" primitive
3480 ///
3481 /// Boolean-negation peer under `!(≥ 2) == (≤ 1)` — byte-for-byte
3482 /// symmetrical with [`Self::has_at_most_one_populated_kind`]
3483 /// under the (populated, missing) complement axis. Names the arm
3484 /// where the parent is SATURATED-OR-NEAR-SATURATED (zero or
3485 /// exactly one missing slot).
3486 ///
3487 /// # Composition laws
3488 ///
3489 /// - `has_at_most_one_missing_kind() == !has_multiple_missing_kinds()`
3490 /// — the definitional Boolean negation.
3491 /// - `has_at_most_one_missing_kind() == (missing_kind_count() <= 1)`
3492 /// — the scalar complement-cardinality composition.
3493 /// - `has_at_most_one_missing_kind() == is_saturated() || has_unique_missing_kind()`
3494 /// — the union of the zero-missing-arm and the one-missing-arm
3495 /// of the {0, 1, ≥ 2} cardinality trichotomy on the missing
3496 /// axis.
3497 ///
3498 /// All three laws hold on every arm and every closed-set kind —
3499 /// pinned as first-class typed invariants by the trait's own
3500 /// default body and swept substrate-wide by
3501 /// [`assert_has_at_most_one_missing_kind_matches_missing_kind_count`].
3502 ///
3503 /// # Truth table on the exactly-one-slot tagged-union contract
3504 ///
3505 /// For a tagged union with `<Self::Kind as ClosedSet>::ALL` of
3506 /// cardinality `N`:
3507 ///
3508 /// - Empty parent (0 populated, N missing): `true` iff `N ≤ 1`
3509 /// (every production union in the workspace has `N ≥ 2`, so on
3510 /// every production union the empty arm returns `false`).
3511 /// - Well-formed parent (1 populated, N-1 missing): `true` iff
3512 /// `N - 1 ≤ 1`, i.e. `N ≤ 2` (on `N == 2` the well-formed arm
3513 /// has exactly one missing slot; on `N ≥ 3` it has ≥ 2).
3514 /// - Near-saturated parent (N-1 populated, 1 missing): `true` (1 ≤ 1).
3515 /// - K-missing parent for `K ≥ 2`: `false`.
3516 /// - Saturated parent (N populated, 0 missing): `true` (0 ≤ 1).
3517 ///
3518 /// # Compounding future consumers
3519 ///
3520 /// - A fast-path branch on the near-saturated / saturated arms
3521 /// that discriminates "at most one dependency still open" from
3522 /// "≥ 2 dependencies still open" reads
3523 /// `parent.has_at_most_one_missing_kind()` at ONE substrate
3524 /// site — one two-step short-circuit walk with a bit-flip,
3525 /// strictly cheaper than the widened union of the zero-arm and
3526 /// one-arm.
3527 /// - An operator-facing "at most one dependency still unfulfilled"
3528 /// diagnostic on an aggregate boundary progress-guard reads
3529 /// this primitive at ONE substrate site.
3530 /// - A `has-at-most-one-missing-kind` require-tag classifier arm
3531 /// reaches this primitive at ONE call site, closing the
3532 /// {0, 1, ≥ 2, ≤ 1} cardinality-Boolean grid on the missing
3533 /// axis alongside its sibling `has-multiple-missing-kinds`
3534 /// under the Boolean negation axis.
3535 ///
3536 /// # Theory grounding
3537 ///
3538 /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
3539 /// The "≤ 1" Boolean projection on the missing axis lives at
3540 /// ONE substrate site as a definitional negation of the "≥ 2"
3541 /// projection; the three composition forms
3542 /// (`!has_multiple_missing_kinds()`,
3543 /// `missing_kind_count() <= 1`, and
3544 /// `is_saturated() || has_unique_missing_kind()`) compose
3545 /// through the SAME two-step-short-circuit walk shape,
3546 /// byte-for-byte identical on every arm.
3547 /// - THEORY.md §VI.1 — generation over composition. A new
3548 /// [`Self::Kind`] variant added to `ALL` reaches this primitive
3549 /// mechanically through the delegated
3550 /// [`Self::has_multiple_missing_kinds`].
3551 fn has_at_most_one_missing_kind(&self) -> bool {
3552 !self.has_multiple_missing_kinds()
3553 }
3554
3555 /// Boolean parent-state middle-arm projection — `true` iff this
3556 /// tagged union has AT LEAST ONE populated slot AND AT LEAST ONE
3557 /// missing slot, i.e. it is neither [`Self::is_empty`] nor
3558 /// [`Self::is_saturated`].
3559 ///
3560 /// Default body: a FUSED short-circuit closed-set walk that tracks
3561 /// two Boolean flags (`has_populated`, `has_missing`) across
3562 /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) under
3563 /// [`Self::has`] and returns `true` at the EARLIEST slot where
3564 /// both flags have flipped. Best-case O(2) walk (index 0 populated
3565 /// combined with index 1 missing, or vice versa); worst case walks
3566 /// the full closed set only when EVERY slot is populated or EVERY
3567 /// slot is missing (the two arms where the return value is `false`).
3568 /// Byte-for-byte cheaper than the widened composition
3569 /// `!self.is_empty() && !self.is_saturated()` (which walks the
3570 /// closed set TWICE — once under `any`, once under `all`) on every
3571 /// partially-populated arm.
3572 ///
3573 /// # Sibling to the parent-state trichotomy
3574 ///
3575 /// Middle arm of the natural `{Empty | Partial | Saturated}`
3576 /// parent-state trichotomy — orthogonal to the {0, 1, ≥2}
3577 /// cardinality trichotomies already closed on the populated /
3578 /// missing axes. Together with [`Self::is_empty`] (all-missing
3579 /// arm) and [`Self::is_saturated`] (all-populated arm), these three
3580 /// Boolean primitives partition every tagged-union state on the
3581 /// parent-state axis — EXACTLY ONE of the three returns `true` on
3582 /// any given parent whose `<Self::Kind as ClosedSet>::ALL.len() ≥
3583 /// 1`:
3584 ///
3585 /// | parent state | primitive | populated cardinality |
3586 /// |--------------|------------------------------------|-----------------------------|
3587 /// | Empty | [`Self::is_empty`] | `0` |
3588 /// | Partial | `is_partially_populated` (this) | `0 < populated < ALL.len()` |
3589 /// | Saturated | [`Self::is_saturated`] | `ALL.len()` |
3590 ///
3591 /// The trichotomy partition law
3592 /// `usize::from(is_empty()) + usize::from(is_partially_populated())
3593 /// + usize::from(is_saturated()) == 1` on every arm is a genuinely
3594 /// new proof binding the three parent-state endpoints together as
3595 /// a typed algebraic invariant — swept substrate-wide by
3596 /// [`assert_is_partially_populated_matches_cardinality`].
3597 ///
3598 /// # Composition laws
3599 ///
3600 /// - `is_partially_populated() == !is_empty() && !is_saturated()`
3601 /// — the negation-of-both-endpoints composition, at the trait
3602 /// default body's SAME fused short-circuit walk.
3603 /// - `is_partially_populated() == (populated_kind_count() > 0
3604 /// && missing_kind_count() > 0)` — the paired scalar-projection
3605 /// composition.
3606 /// - `is_partially_populated() == (0 < populated_kind_count()
3607 /// && populated_kind_count() < ALL.len())` — the single-axis
3608 /// strict-inequality composition (populated cardinality lies in
3609 /// the open interval `(0, ALL.len())`).
3610 ///
3611 /// # Truth table on the exactly-one-slot tagged-union contract
3612 ///
3613 /// For a tagged union with `<Self::Kind as ClosedSet>::ALL` of
3614 /// cardinality `N ≥ 2`:
3615 ///
3616 /// - Empty parent (0 populated, N missing): `false` (empty arm).
3617 /// - Well-formed parent (1 populated, N-1 missing on any `N ≥ 2`):
3618 /// `true` — the SOLE `Ok` arm of [`Self::variant`] lies inside
3619 /// the partial region.
3620 /// - K-populated parent for `0 < K < N`: `true`.
3621 /// - Saturated parent (N populated, 0 missing on any `N ≥ 2`):
3622 /// `false` (saturated arm).
3623 ///
3624 /// # Compounding future consumers
3625 ///
3626 /// - A boundary-progress "some done, some pending" diagnostic on
3627 /// an aggregate condition-carrier reads
3628 /// `parent.is_partially_populated()` at ONE substrate site —
3629 /// the exact "in flight" arm — rather than composing
3630 /// `!parent.is_empty() && !parent.is_saturated()` (two closed-
3631 /// set walks) or `parent.populated_kind_count() > 0 &&
3632 /// parent.missing_kind_count() > 0` (two counter walks).
3633 /// - A fast-path branch that discriminates "mixed" from "empty or
3634 /// saturated" reads this primitive with ONE fused short-circuit
3635 /// walk, strictly cheaper than either widened composition.
3636 /// - An `is-partially-populated` require-tag classifier arm
3637 /// reaches this primitive at ONE call site, byte-for-byte
3638 /// symmetrical with the sibling `is-empty` / `is-saturated`
3639 /// arms on the closed parent-state trichotomy.
3640 /// - An operator-facing "in-flight ambiguous carrier" diagnostic
3641 /// (the resolver's `Err(Ambiguous)` arm's non-saturated sub-arm)
3642 /// reads `parent.is_partially_populated() && parent.has_multiple_populated_kinds()`
3643 /// composing two short-circuit walks — strictly cheaper than
3644 /// materializing the `variant()` error carrier.
3645 ///
3646 /// A new [`Self::Kind`] variant added to
3647 /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) reaches
3648 /// this primitive mechanically — the fused walk picks up the new
3649 /// slot as an additional short-circuit candidate (a parent that
3650 /// previously satisfied `is_partially_populated` because it had
3651 /// both populated and missing slots continues to satisfy it; a
3652 /// previously-saturated parent that leaves the new slot missing
3653 /// becomes partially populated at every downstream callsite
3654 /// without further per-caller edit).
3655 ///
3656 /// # Theory grounding
3657 ///
3658 /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
3659 /// The parent-state middle-arm projection lives at ONE
3660 /// substrate site as a fused short-circuit walk over
3661 /// `<Self::Kind as ClosedSet>::ALL` under [`Self::has`] with
3662 /// early exit on the first observed populated/missing pair —
3663 /// byte-for-byte cheaper than the widened negation-of-both-
3664 /// endpoints composition, and semantically identical on every
3665 /// arm. The trichotomy partition law
3666 /// `is_empty + is_partially_populated + is_saturated == 1`
3667 /// lives at ONE substrate site inside the testkit's per-arm
3668 /// sweep — pinned across every production tagged union at
3669 /// compile time via the trait's default body composition, not
3670 /// per-parent.
3671 /// - THEORY.md §VI.1 — generation over composition. A new
3672 /// [`Self::Kind`] variant added to `ALL` reaches this primitive
3673 /// mechanically through the fused walk — the trichotomy holds
3674 /// on the widened kind set without further per-caller edit.
3675 fn is_partially_populated(&self) -> bool {
3676 let mut has_populated = false;
3677 let mut has_missing = false;
3678 for k in <Self::Kind as tatara_closed_set::ClosedSet>::ALL
3679 .iter()
3680 .copied()
3681 {
3682 if self.has(k) {
3683 has_populated = true;
3684 } else {
3685 has_missing = true;
3686 }
3687 if has_populated && has_missing {
3688 return true;
3689 }
3690 }
3691 false
3692 }
3693
3694 /// Kind-scoped strict refinement of [`Self::has`] — `true` iff the
3695 /// given `kind` is populated AND no OTHER slot on this tagged union
3696 /// is populated. The "exactly this one variant" predicate.
3697 ///
3698 /// Default body: a FUSED short-circuit closed-set walk under
3699 /// [`Self::has`] that returns `false` at the EARLIEST populated
3700 /// slot whose kind is NOT `kind`, and returns `true` iff the sweep
3701 /// completes with `kind` seen as the sole populated slot. Byte-for-
3702 /// byte cheaper than either widened composition
3703 /// `self.unique_populated_kind() == Some(kind)` (which walks until
3704 /// the SECOND populated slot before comparing) or
3705 /// `self.has(kind) && self.has_unique_populated_kind()` (two
3706 /// closed-set walks) on every arm where the parent carries a
3707 /// populated slot that isn't `kind`.
3708 ///
3709 /// # Sibling to [`Self::has`]
3710 ///
3711 /// Kind-scoped strict-refinement peer: `has(kind)` is the SUBSET
3712 /// predicate (`kind` populated, maybe others too); `has_only(kind)`
3713 /// is the EQUAL predicate (`kind` populated AND ONLY `kind`). The
3714 /// implication `has_only(kind) → has(kind)` binds the pair on the
3715 /// strict-refinement axis; the reverse implication holds only on
3716 /// well-formed parents (`has_unique_populated_kind() == true`).
3717 ///
3718 /// # Peer to [`Self::unique_populated_kind`]
3719 ///
3720 /// Same axis, argument-scoped projection: where
3721 /// `unique_populated_kind()` returns `Some(k)` iff exactly one slot
3722 /// is populated AND names which one, `has_only(kind)` returns
3723 /// `true` iff exactly one slot is populated AND that slot is the
3724 /// passed `kind`. The composition law
3725 /// `has_only(kind) == (unique_populated_kind() == Some(kind))`
3726 /// binds the two primitives at the trait's default body — swept
3727 /// substrate-wide by
3728 /// [`assert_has_only_matches_unique_populated_kind`].
3729 ///
3730 /// # Truth table on the exactly-one-slot tagged-union contract
3731 ///
3732 /// For a tagged union with `<Self::Kind as ClosedSet>::ALL` of
3733 /// cardinality `N ≥ 2` and a fixed argument `kind`:
3734 ///
3735 /// - Empty parent (0 populated, N missing): `false` — no populated
3736 /// slot, so `kind` isn't the sole populated kind.
3737 /// - Well-formed parent with `kind` populated (1 populated ==
3738 /// kind): `true` — the SOLE arm where `has_only(kind)` returns
3739 /// `true`. Aligns with [`Self::variant`]'s `Ok(Variant)` arm
3740 /// where the resolver names the same kind.
3741 /// - Well-formed parent with other kind populated (1 populated !=
3742 /// kind): `false` — the populated slot addresses a different
3743 /// kind.
3744 /// - K-populated parent for `K ≥ 2`: `false` — multiple populated
3745 /// slots, so no single kind is the "only" one.
3746 /// - Saturated parent (N populated, 0 missing on any `N ≥ 2`):
3747 /// `false`.
3748 ///
3749 /// # Kind-domain exhaustivity
3750 ///
3751 /// A parent satisfies `has_only(k)` for AT MOST one `k`, since two
3752 /// distinct kinds cannot both be the sole populated slot. On the
3753 /// well-formed arm the count is exactly 1 (the addressed kind); on
3754 /// every non-well-formed arm the count is 0. This kind-domain
3755 /// exhaustivity law binds the argument-scoped projection to the
3756 /// arg-less uniqueness predicate at ONE substrate site.
3757 ///
3758 /// # Compounding future consumers
3759 ///
3760 /// - A dispatch table that runs a per-kind branch only when the
3761 /// parent is unambiguously that kind reads `parent.has_only(k)`
3762 /// at ONE substrate site with ONE fused short-circuit walk —
3763 /// strictly cheaper than either widened composition.
3764 /// - An `is-only-<kind>` require-tag classifier arm reaches this
3765 /// primitive at ONE call site — the kind-scoped peer of the
3766 /// arg-less `has_unique_populated_kind` classifier.
3767 /// - A coherence check verifying "every parent from a
3768 /// `single_slot_X(k)` factory is unambiguously kind `k`" reads
3769 /// `parent.has_only(k)` at ONE site — the strongest structural
3770 /// pin on the well-formed diagonal.
3771 /// - An operator-facing "unambiguously kind=<k>" diagnostic on the
3772 /// resolver's Ok arm reads `parent.has_only(k)` after
3773 /// `first_populated_kind` names the resolved kind — one walk, no
3774 /// allocation, no `Option<Kind>` construction.
3775 ///
3776 /// A new [`Self::Kind`] variant added to
3777 /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) reaches
3778 /// this primitive mechanically — the fused walk picks up the new
3779 /// slot as an additional short-circuit candidate at every
3780 /// downstream callsite without further per-caller edit.
3781 ///
3782 /// # Theory grounding
3783 ///
3784 /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
3785 /// The kind-scoped strict-refinement projection lives at ONE
3786 /// substrate site as a fused short-circuit walk over
3787 /// `<Self::Kind as ClosedSet>::ALL` under [`Self::has`] with
3788 /// early exit on the first populated slot whose kind is not
3789 /// `kind` — byte-for-byte cheaper than the widened composition
3790 /// `unique_populated_kind() == Some(kind)`, semantically
3791 /// identical on every arm.
3792 /// - THEORY.md §VI.1 — generation over composition. A new
3793 /// [`Self::Kind`] variant added to `ALL` reaches this primitive
3794 /// mechanically through the fused walk.
3795 fn has_only(&self, kind: Self::Kind) -> bool
3796 where
3797 Self::Kind: PartialEq,
3798 {
3799 let mut saw_kind = false;
3800 for k in <Self::Kind as tatara_closed_set::ClosedSet>::ALL
3801 .iter()
3802 .copied()
3803 {
3804 if !self.has(k) {
3805 continue;
3806 }
3807 if k == kind {
3808 saw_kind = true;
3809 } else {
3810 return false;
3811 }
3812 }
3813 saw_kind
3814 }
3815
3816 /// Kind-scoped strict refinement of `!Self::has(kind)` — `true` iff
3817 /// the given `kind` is MISSING AND no OTHER slot on this tagged
3818 /// union is missing. The "exactly this one variant is absent"
3819 /// predicate — closed-set-complement mirror of [`Self::has_only`].
3820 ///
3821 /// Default body: a FUSED short-circuit closed-set walk under a
3822 /// negated [`Self::has`] that returns `false` at the EARLIEST
3823 /// missing slot whose kind is NOT `kind`, and returns `true` iff
3824 /// the sweep completes with `kind` seen as the sole missing slot.
3825 /// Byte-for-byte cheaper than either widened composition
3826 /// `self.unique_missing_kind() == Some(kind)` (which walks until
3827 /// the SECOND missing slot before comparing) or
3828 /// `!self.has(kind) && self.has_unique_missing_kind()` (two
3829 /// closed-set walks) on every arm where the parent carries a
3830 /// missing slot that isn't `kind`.
3831 ///
3832 /// # Sibling to [`Self::has_only`]
3833 ///
3834 /// Closed-set-complement peer of [`Self::has_only`] under a negated
3835 /// [`Self::has`] predicate — where `has_only(kind)` names parents
3836 /// whose SOLE populated slot is `kind`, `lacks_only(kind)` names
3837 /// parents whose SOLE missing slot is `kind`. Byte-for-byte
3838 /// symmetrical fused-walk shape; the two primitives are useful in
3839 /// DIFFERENT structural regimes: `has_only` names well-formed
3840 /// parents (1 of N populated); `lacks_only` names the missing-side
3841 /// complement (N-1 of N populated — the near-saturation arm). On
3842 /// tagged unions with `N == 2` the two coincide (a well-formed
3843 /// 1-of-2 parent has 1 missing too, so `has_only(a)` and
3844 /// `lacks_only(b)` name the same arm iff `a != b`).
3845 ///
3846 /// # Peer to [`Self::unique_missing_kind`]
3847 ///
3848 /// Same axis, argument-scoped projection: where
3849 /// `unique_missing_kind()` returns `Some(k)` iff exactly one slot
3850 /// is missing AND names which one, `lacks_only(kind)` returns
3851 /// `true` iff exactly one slot is missing AND that slot is the
3852 /// passed `kind`. The composition law
3853 /// `lacks_only(kind) == (unique_missing_kind() == Some(kind))`
3854 /// binds the two primitives at the trait's default body — swept
3855 /// substrate-wide by
3856 /// [`assert_lacks_only_matches_unique_missing_kind`].
3857 ///
3858 /// # Truth table on the exactly-one-slot tagged-union contract
3859 ///
3860 /// For a tagged union with `<Self::Kind as ClosedSet>::ALL` of
3861 /// cardinality `N ≥ 2` and a fixed argument `kind`:
3862 ///
3863 /// - Empty parent (0 populated, N missing): `false` on any `N ≥ 2`
3864 /// — N missing slots, so `kind` isn't the sole missing kind.
3865 /// - Well-formed parent (1 populated, N-1 missing): `false` when
3866 /// `N > 2` (N-1 ≥ 2 missing, no unique missing); on `N == 2`
3867 /// with populated `p`, `lacks_only(kind) == (kind != p)` (the
3868 /// one missing slot is the non-populated one).
3869 /// - N-1-populated parent (missing-side peer of the well-formed
3870 /// arm, 1 missing): `true` iff `kind` names the sole missing
3871 /// slot — the SOLE arm where `lacks_only(kind)` returns `true`
3872 /// on any `N > 2` closed set.
3873 /// - Saturated parent (N populated, 0 missing): `false`.
3874 ///
3875 /// # Kind-domain exhaustivity
3876 ///
3877 /// A parent satisfies `lacks_only(k)` for AT MOST one `k`, since
3878 /// two distinct kinds cannot both be the sole missing slot. On
3879 /// the near-saturation arm the count is exactly 1 (the addressed
3880 /// missing kind); on every other arm the count is 0. This kind-
3881 /// domain exhaustivity law binds the argument-scoped projection
3882 /// to the arg-less uniqueness predicate at ONE substrate site,
3883 /// byte-for-byte peer of the `has_only` exhaustivity law under
3884 /// complement.
3885 ///
3886 /// # Kind-scoped implication
3887 ///
3888 /// `lacks_only(kind) → !has(kind)` — if `kind` is the sole missing
3889 /// slot then `kind` cannot be populated. Complement mirror of the
3890 /// `has_only(kind) → has(kind)` implication that binds
3891 /// [`Self::has_only`] to [`Self::has`] on the strict-refinement
3892 /// axis; here the implication binds `lacks_only` to `!has` on the
3893 /// closed-set-complement axis.
3894 ///
3895 /// # Compounding future consumers
3896 ///
3897 /// - An operator-facing "exactly one dependency still unfulfilled:
3898 /// X" diagnostic on an aggregate boundary check whose `X` is
3899 /// known statically reads `parent.lacks_only(X)` at ONE
3900 /// substrate site — one fused short-circuit walk, no allocation,
3901 /// strictly cheaper than the widened composition.
3902 /// - A `lacks-only-<kind>` require-tag classifier arm reaches this
3903 /// primitive at ONE call site — the argument-scoped peer of the
3904 /// arg-less `has_unique_missing_kind` classifier, closed-set-
3905 /// complement mirror of the `is-only-<kind>` classifier arm on
3906 /// the populated axis.
3907 /// - A coherence check verifying "the near-saturation parent from
3908 /// an `all_but_one_slot_X(k)` factory is unambiguously missing
3909 /// kind `k`" reads `parent.lacks_only(k)` at ONE site — the
3910 /// strongest structural pin on the missing-side well-formed
3911 /// diagonal.
3912 /// - A fast-path branch on the near-saturation arm that
3913 /// discriminates "exactly one specific slot still empty" from
3914 /// "0 or ≥ 2 still empty or some OTHER slot empty" reads
3915 /// `parent.lacks_only(kind)` at ONE call site — the fused-walk
3916 /// short-circuit is strictly cheaper than
3917 /// `parent.unique_missing_kind() == Some(kind)` on every arm
3918 /// where a first-missing-slot mismatch would prune the walk
3919 /// before the second missing slot.
3920 ///
3921 /// A new [`Self::Kind`] variant added to
3922 /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) reaches
3923 /// this primitive mechanically — the fused walk picks up the new
3924 /// slot as an additional short-circuit candidate at every
3925 /// downstream callsite without further per-caller edit.
3926 ///
3927 /// # Theory grounding
3928 ///
3929 /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
3930 /// The kind-scoped strict-refinement projection on the missing
3931 /// axis lives at ONE substrate site as a fused short-circuit
3932 /// walk over `<Self::Kind as ClosedSet>::ALL` under a negated
3933 /// [`Self::has`] with early exit on the first missing slot
3934 /// whose kind is not `kind` — byte-for-byte peer of
3935 /// [`Self::has_only`]'s fused walk under complement,
3936 /// semantically identical to
3937 /// `unique_missing_kind() == Some(kind)` on every arm.
3938 /// - THEORY.md §VI.1 — generation over composition. A new
3939 /// [`Self::Kind`] variant added to `ALL` reaches this primitive
3940 /// mechanically through the fused walk.
3941 fn lacks_only(&self, kind: Self::Kind) -> bool
3942 where
3943 Self::Kind: PartialEq,
3944 {
3945 let mut saw_kind = false;
3946 for k in <Self::Kind as tatara_closed_set::ClosedSet>::ALL
3947 .iter()
3948 .copied()
3949 {
3950 if self.has(k) {
3951 continue;
3952 }
3953 if k == kind {
3954 saw_kind = true;
3955 } else {
3956 return false;
3957 }
3958 }
3959 saw_kind
3960 }
3961}
3962
3963/// Generic diagnostic-stability testkit — pins that [`TaggedUnion::KIND_LIST`]
3964/// matches `<T::Kind as tatara_closed_set::ClosedSet>::labels_joined("/")`
3965/// byte-identically for every implementor.
3966///
3967/// Substrate primitive for the four sibling
3968/// `_error_empty_lists_every_kind_in_canonical_order` tests on
3969/// `ProcessSpec` ([`crate::intent::Intent`],
3970/// [`crate::encapsulates::EncapsulationKind`],
3971/// [`crate::export::ArtifactSource`], [`crate::export::VectorChannel`])
3972/// that pre-lift each restated the same
3973/// `assert_eq!(<XxxKind as ClosedSet>::labels_joined("/"),
3974/// XXX_KIND_LIST)` two-argument comparison at their own test bodies —
3975/// byte-identical projections whose only per-carrier knobs (the Kind
3976/// type + the KIND_LIST constant) are the two associated items the
3977/// [`TaggedUnion`] trait names. Post-lift each site collapses to ONE
3978/// `assert_kind_list_matches_closed_set::<Xxx>()` invocation whose
3979/// body is the substrate primitive's own dispatch.
3980///
3981/// A fifth sibling tagged-union parent picks up the diagnostic-
3982/// stability check through ONE `impl TaggedUnion for X` block + ONE
3983/// `assert_kind_list_matches_closed_set::<X>()` call site — no
3984/// re-authored `<XKind as ClosedSet>::labels_joined("/")` composition
3985/// at the test site, no re-authored per-site `assert_eq!` pair.
3986#[track_caller]
3987pub fn assert_kind_list_matches_closed_set<T: TaggedUnion>() {
3988 let derived = <T::Kind as tatara_closed_set::ClosedSet>::labels_joined("/");
3989 assert_eq!(
3990 derived,
3991 T::KIND_LIST,
3992 "TaggedUnion KIND_LIST drift — must equal <T::Kind as ClosedSet>::labels_joined(\"/\")",
3993 );
3994}
3995
3996/// Generic presence-probe testkit — pins that [`TaggedUnion::has`]
3997/// agrees with [`VariantSelector::select`]`.is_some()` across every
3998/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) entry, both
3999/// on the diagonal (populated slot AND matching kind → `true`) and
4000/// off the diagonal (populated slot BUT other kind → `false`).
4001///
4002/// Substrate primitive for the presence-probe half of the tagged-
4003/// union contract — dispatch tables that key off `intent-<kind>` /
4004/// `channel-<kind>` / `source-<kind>` require-tags gain a `.has(k)`
4005/// call that structurally CANNOT drift from the closed-set sweep,
4006/// but the pin here surfaces a `has` override that would break the
4007/// contract (e.g. a future specialization that always returned
4008/// `false`) at ONE call site rather than at every downstream
4009/// dispatcher.
4010///
4011/// A fifth sibling tagged-union parent picks up the presence-probe
4012/// check through ONE `assert_has_matches_select::<X, _>(single_slot)`
4013/// invocation — no re-authored `for k in K::ALL { … }` sweep at the
4014/// test site.
4015#[track_caller]
4016pub fn assert_has_matches_select<T, F>(single_slot: F)
4017where
4018 T: TaggedUnion,
4019 T::Kind: PartialEq + std::fmt::Debug,
4020 F: Fn(T::Kind) -> T,
4021{
4022 for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
4023 .iter()
4024 .copied()
4025 {
4026 let parent = single_slot(populated);
4027 for probed in <T::Kind as tatara_closed_set::ClosedSet>::ALL
4028 .iter()
4029 .copied()
4030 {
4031 let expected = probed == populated;
4032 assert_eq!(
4033 parent.has(probed),
4034 expected,
4035 "TaggedUnion::has drift — populated={populated:?} probed={probed:?} expected={expected}",
4036 );
4037 assert_eq!(
4038 probed.select(&parent).is_some(),
4039 expected,
4040 "VariantSelector::select drift — populated={populated:?} probed={probed:?} expected={expected}",
4041 );
4042 }
4043 }
4044}
4045
4046/// Generic widened-probe testkit — pins that [`TaggedUnion::find`]
4047/// agrees with [`TaggedUnion::has`] AND with
4048/// [`VariantSelector::select`] across every
4049/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) entry, and
4050/// that the returned borrowed view round-trips through
4051/// [`VariantKind::variant_kind`] back to the addressing Kind on the
4052/// populated diagonal.
4053///
4054/// Substrate primitive for the widened half of the presence-probe
4055/// contract — dispatch tables that key off `intent-<kind>` /
4056/// `channel-<kind>` / `source-<kind>` require-tags gain a `.find(k)`
4057/// call whose return type carries the borrowed variant payload for
4058/// diagnostic composition (an operator-facing "channel-<kind>
4059/// matched with e.channel.<field>.<key>=<value>" message, a
4060/// coherence check that projects the borrowed variant into its
4061/// Kind for round-trip validation), and the pin here surfaces a
4062/// `find` override that would drift from the composition law
4063/// `has(k) == find(k).is_some()` at ONE call site rather than at
4064/// every downstream dispatcher.
4065///
4066/// The three sub-assertions swept per (populated, probed) pair:
4067///
4068/// 1. `parent.find(probed).is_some() == parent.has(probed)` — the
4069/// composition law binding [`TaggedUnion::has`] to
4070/// [`TaggedUnion::find`] via `find(k).is_some()`.
4071/// 2. `parent.find(probed).is_some() == probed.select(&parent).is_some()`
4072/// — the widened primitive delegates to
4073/// [`VariantSelector::select`] on the Kind, so a regression that
4074/// inlined a divergent walk body at the trait's `find` default
4075/// fails here rather than as silent drift at every downstream
4076/// diagnostic consumer.
4077/// 3. On the populated diagonal (`probed == populated`), the
4078/// returned borrowed view satisfies
4079/// `find(k).unwrap().variant_kind() == k` — the round-trip
4080/// contract that closes `find` (forward-widened) against
4081/// [`VariantKind::variant_kind`] (reverse projection).
4082///
4083/// A fifth sibling tagged-union parent picks up the widened-probe
4084/// check through ONE `assert_find_agrees_with_has::<X, _>(single_slot)`
4085/// invocation — no re-authored `for k in K::ALL { … }` sweep at the
4086/// test site.
4087#[track_caller]
4088pub fn assert_find_agrees_with_has<T, F>(single_slot: F)
4089where
4090 T: TaggedUnion,
4091 T::Kind: PartialEq + std::fmt::Debug,
4092 F: Fn(T::Kind) -> T,
4093{
4094 for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
4095 .iter()
4096 .copied()
4097 {
4098 let parent = single_slot(populated);
4099 for probed in <T::Kind as tatara_closed_set::ClosedSet>::ALL
4100 .iter()
4101 .copied()
4102 {
4103 let expected = probed == populated;
4104 let via_has = parent.has(probed);
4105 let via_find = parent.find(probed).is_some();
4106 let via_select = probed.select(&parent).is_some();
4107 assert_eq!(
4108 via_find, via_has,
4109 "TaggedUnion::find drifted from has — populated={populated:?} probed={probed:?}",
4110 );
4111 assert_eq!(
4112 via_find, via_select,
4113 "TaggedUnion::find drifted from VariantSelector::select — populated={populated:?} probed={probed:?}",
4114 );
4115 assert_eq!(
4116 via_find, expected,
4117 "TaggedUnion::find truth-table drift — populated={populated:?} probed={probed:?} expected={expected}",
4118 );
4119 if expected {
4120 let variant = parent.find(probed).unwrap_or_else(|| {
4121 panic!("TaggedUnion::find must return Some for populated slot {probed:?}",)
4122 });
4123 assert_eq!(
4124 <<T::Kind as VariantSelector<T>>::Variant<'_> as VariantKind<T::Kind>>::variant_kind(
4125 &variant,
4126 ),
4127 probed,
4128 "find→variant_kind round-trip failed for {probed:?}",
4129 );
4130 }
4131 }
4132 }
4133}
4134
4135/// Generic closed-set-inversion testkit — pins that
4136/// [`TaggedUnion::populated_kinds`] composes over
4137/// [`TaggedUnion::has`] across every
4138/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) entry on
4139/// the single-slot side, that the returned `Vec` is the canonical
4140/// [`ClosedSet::ALL`]-ordered filter of `has(k)`, and that on the
4141/// populated diagonal `single_slot(k).populated_kinds()` equals
4142/// `vec![k]` exactly (length 1, canonical ordered, no drift).
4143///
4144/// Parent-axis substrate primitive for the tagged-union closed-set-
4145/// inversion refinement — the peer of
4146/// [`crate::boundary::assert_slice_refinement_composition_laws`]'s
4147/// `distinct_kinds` sub-arm on the slice-level presence-probe axis,
4148/// lifted here to the tagged-union parent-level presence-probe axis
4149/// (same shape, same composition operator, second instance in the
4150/// workspace-wide closed-set-inversion refinement algebra).
4151///
4152/// The three sub-assertions swept per (populated, probed) pair:
4153///
4154/// 1. Per-kind membership: `parent.populated_kinds().contains(&k) ==
4155/// parent.has(k)` for every `k ∈ ClosedSet::ALL` — a regression
4156/// that overrode `populated_kinds` to skip a kind, drift the walk
4157/// order from canonical `ALL` to slot-encounter order, or return
4158/// a superset containing absent kinds surfaces at the specific
4159/// kind's per-pair assertion.
4160/// 2. Canonical `ALL`-filter equality:
4161/// `parent.populated_kinds() == ALL.iter().copied().filter(|k|
4162/// parent.has(*k)).collect()` — a regression that returned
4163/// duplicates (a naive override that skipped dedup by
4164/// construction) or drifted the walk order surfaces at the
4165/// post-loop equality assert.
4166/// 3. Single-slot diagonal: `single_slot(k).populated_kinds() ==
4167/// vec![k]` exactly — pins the single-populated arm's cardinality
4168/// (length 1) and ordering (the addressed kind's own position in
4169/// `ALL`) together at ONE assert.
4170///
4171/// Substrate primitive for future per-parent
4172/// `X_populated_kinds_matches_has` tests that would otherwise each
4173/// restate the same nested-`for populated in K::ALL { for probed in
4174/// K::ALL { … } }` sweep + canonical-order equality + single-slot
4175/// diagonal pin — every one of the four production `.variant()`
4176/// parents on `ProcessSpec` binds through this ONE primitive with a
4177/// per-site `single_slot` factory. A fifth sibling picks up the
4178/// closed-set-inversion check through ONE call site — no re-authored
4179/// `for k in K::ALL { … }` sweep at the test surface, no re-authored
4180/// `assert_eq!` triad.
4181///
4182/// The `single_slot` closure stays per-site — reused verbatim from
4183/// the sibling primitives ([`assert_variant_round_trip`],
4184/// [`assert_find_agrees_with_has`],
4185/// [`assert_single_slot_key_matches_label`]) — the closure IS the
4186/// "populate slot k" ground truth for the parent's field structure.
4187///
4188/// The [`crate::lifetime::Lifetime`] site is DELIBERATELY excluded
4189/// through the `T: TaggedUnion` bound — `Lifetime`'s `variant()`
4190/// returns `Ok(Permanent)` on empty rather than an `Empty` typed
4191/// error, so its projection shape diverges from the four
4192/// Empty-projecting parents. Same reasoning as
4193/// [`assert_variant_round_trip`]'s /
4194/// [`assert_find_agrees_with_has`]'s exclusions.
4195#[track_caller]
4196pub fn assert_populated_kinds_matches_has<T, F>(single_slot: F)
4197where
4198 T: TaggedUnion,
4199 T::Kind: PartialEq + std::fmt::Debug,
4200 F: Fn(T::Kind) -> T,
4201{
4202 for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
4203 .iter()
4204 .copied()
4205 {
4206 let parent = single_slot(populated);
4207 let kinds = parent.populated_kinds();
4208 // Per-kind membership composition law.
4209 for probed in <T::Kind as tatara_closed_set::ClosedSet>::ALL
4210 .iter()
4211 .copied()
4212 {
4213 assert_eq!(
4214 kinds.contains(&probed),
4215 parent.has(probed),
4216 "TaggedUnion::populated_kinds().contains({probed:?}) drifted from has({probed:?}) — populated={populated:?}",
4217 );
4218 }
4219 // Canonical ALL-filter equality — pins dedup, walk order, and
4220 // membership consistency at ONE assert.
4221 let canonical: Vec<T::Kind> = <T::Kind as tatara_closed_set::ClosedSet>::ALL
4222 .iter()
4223 .copied()
4224 .filter(|k| parent.has(*k))
4225 .collect();
4226 assert_eq!(
4227 kinds, canonical,
4228 "TaggedUnion::populated_kinds() must yield ClosedSet::ALL-ordered subsequence where has is true (no duplicates, canonical order) — populated={populated:?}",
4229 );
4230 // Single-slot diagonal — the addressed slot IS the ONLY
4231 // populated slot on the parent single_slot produces, so the
4232 // canonical filter yields exactly [populated].
4233 assert_eq!(
4234 kinds,
4235 vec![populated],
4236 "TaggedUnion::populated_kinds() on single_slot({populated:?}) must return vec![{populated:?}] exactly",
4237 );
4238 }
4239}
4240
4241/// Generic zero-allocation-iterator testkit — pins that
4242/// [`TaggedUnion::iter_populated_kinds`] yields byte-identically to
4243/// [`TaggedUnion::populated_kinds`] after `.collect::<Vec<_>>()`,
4244/// and that repeated calls yield the same sequence (the iterator is
4245/// pure over `&self`).
4246///
4247/// Substrate primitive for the load-bearing iterator half of the
4248/// closed-set-inversion axis — [`TaggedUnion::populated_kinds`]'s
4249/// default body IS `self.iter_populated_kinds().collect()`, so the
4250/// composition law
4251/// `populated_kinds() == iter_populated_kinds().collect::<Vec<_>>()`
4252/// holds by construction. The pin here surfaces an
4253/// `iter_populated_kinds` override that would drift from the Vec
4254/// projection (a specialization that yields kinds out of
4255/// `Kind::ALL` order, duplicates an entry, or short-circuits before
4256/// reaching a populated slot) at ONE substrate site rather than at
4257/// every downstream fold that composes over the iterator.
4258///
4259/// The three sub-assertions swept per populated slot:
4260///
4261/// 1. `iter_populated_kinds().collect::<Vec<_>>() == populated_kinds()`
4262/// — the composition law binding the iterator peer to the Vec
4263/// widened primitive at the trait-default boundary.
4264/// 2. `iter_populated_kinds().collect::<Vec<_>>() ==
4265/// iter_populated_kinds().collect::<Vec<_>>()` (called twice) —
4266/// the iterator is pure over `&self`, so repeated calls yield
4267/// the same sequence. Pins that no closure-captured state leaks
4268/// between invocations.
4269/// 3. On the single-slot diagonal, the collected vec equals
4270/// `vec![populated]` — the single-slot round-trip through the
4271/// iterator peer matches the round-trip through the widened Vec
4272/// peer at exactly one populated entry.
4273///
4274/// A fifth sibling tagged-union parent picks up the iterator-side
4275/// composition-law check through ONE
4276/// `assert_iter_populated_kinds_matches_populated_kinds::<X, _>(single_slot)`
4277/// invocation — no re-authored `for k in K::ALL { … }` sweep at the
4278/// test site, no re-authored `.collect::<Vec<_>>()` assertion
4279/// against the widened Vec peer.
4280#[track_caller]
4281pub fn assert_iter_populated_kinds_matches_populated_kinds<T, F>(single_slot: F)
4282where
4283 T: TaggedUnion,
4284 T::Kind: PartialEq + std::fmt::Debug,
4285 F: Fn(T::Kind) -> T,
4286{
4287 for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
4288 .iter()
4289 .copied()
4290 {
4291 let parent = single_slot(populated);
4292 let via_iter: Vec<T::Kind> = parent.iter_populated_kinds().collect();
4293 let via_vec = parent.populated_kinds();
4294 assert_eq!(
4295 via_iter, via_vec,
4296 "TaggedUnion::iter_populated_kinds().collect() drifted from populated_kinds() — populated={populated:?}",
4297 );
4298 // Purity — repeated invocations yield the same sequence.
4299 let via_iter_again: Vec<T::Kind> = parent.iter_populated_kinds().collect();
4300 assert_eq!(
4301 via_iter, via_iter_again,
4302 "TaggedUnion::iter_populated_kinds() must be pure over &self — populated={populated:?}",
4303 );
4304 // Single-slot diagonal — round-trip yields exactly [populated].
4305 assert_eq!(
4306 via_iter,
4307 vec![populated],
4308 "TaggedUnion::iter_populated_kinds() on single_slot({populated:?}) must yield exactly [{populated:?}]",
4309 );
4310 }
4311}
4312
4313/// Generic two-slot closed-set-inversion testkit — peer of
4314/// [`assert_populated_kinds_matches_has`] on the ambiguous-parent
4315/// side. Pins that a `two_slot(a, b)` parent's `populated_kinds()`
4316/// yields the canonical `ClosedSet::ALL`-ordered pair
4317/// `[min_all(a,b), max_all(a,b)]` (length exactly 2, dedup + walk
4318/// order enforced), and that per-kind membership composes
4319/// byte-identically against `has(k)` on the malformed-parent arm.
4320///
4321/// The two-slot fixture is the SAME factory production sites already
4322/// hand [`assert_two_slots_ambiguous`] — every one of the four
4323/// production `.variant()` parents on `ProcessSpec` composes
4324/// `two_slot(a, b)` through per-field `Option::or` on
4325/// `single_slot(a)` and `single_slot(b)`, so BOTH slots on the
4326/// resulting parent are populated. The primitive's off-diagonal
4327/// sweep (`a != b`) pins that `populated_kinds()` NAMES both
4328/// populated slots on the malformed arm — the diagnostic-surface
4329/// promise the payload-free
4330/// [`TaggedUnionError::ambiguous`] carrier stops short of.
4331///
4332/// The three sub-assertions swept per `(a, b)` off-diagonal pair:
4333///
4334/// 1. Cardinality: `populated_kinds().len() == 2` — a regression
4335/// that returned a length-1 vec (silently short-circuiting on
4336/// the first populated slot; drifting the walk from `ALL` to
4337/// single-match `find`) fails HERE at the length assert.
4338/// 2. Per-kind membership: `populated_kinds().contains(&k) ==
4339/// has(k)` for every `k ∈ ClosedSet::ALL` — the composition law
4340/// of the closed-set-inversion refinement, pinned on the
4341/// multi-populated arm.
4342/// 3. Canonical `ALL`-filter equality:
4343/// `populated_kinds() == ALL.iter().copied().filter(|k|
4344/// parent.has(*k)).collect()` — pins the walk order (a
4345/// regression that yielded `[b, a]` because it walked the two
4346/// populated slots in construction order instead of
4347/// `ClosedSet::ALL` order fails at the equality assert).
4348///
4349/// A fifth sibling tagged-union parent picks up the two-slot
4350/// closed-set-inversion check through ONE call site — no
4351/// re-authored nested-for sweep at the test surface, no re-authored
4352/// `assert_eq!` triad.
4353///
4354/// Same `Lifetime` exclusion as [`assert_populated_kinds_matches_has`]:
4355/// the `T: TaggedUnion` bound doesn't reach it.
4356#[track_caller]
4357pub fn assert_populated_kinds_across_pairs<T, F>(two_slot: F)
4358where
4359 T: TaggedUnion,
4360 T::Kind: PartialEq + std::fmt::Debug,
4361 F: Fn(T::Kind, T::Kind) -> T,
4362{
4363 for a in <T::Kind as tatara_closed_set::ClosedSet>::ALL
4364 .iter()
4365 .copied()
4366 {
4367 for b in <T::Kind as tatara_closed_set::ClosedSet>::ALL
4368 .iter()
4369 .copied()
4370 {
4371 if a == b {
4372 continue;
4373 }
4374 let parent = two_slot(a, b);
4375 let kinds = parent.populated_kinds();
4376 assert_eq!(
4377 kinds.len(),
4378 2,
4379 "TaggedUnion::populated_kinds() on two_slot({a:?}, {b:?}) must return exactly two populated kinds, got {kinds:?}",
4380 );
4381 for probed in <T::Kind as tatara_closed_set::ClosedSet>::ALL
4382 .iter()
4383 .copied()
4384 {
4385 assert_eq!(
4386 kinds.contains(&probed),
4387 parent.has(probed),
4388 "TaggedUnion::populated_kinds().contains({probed:?}) drifted from has({probed:?}) — (a, b)=({a:?}, {b:?})",
4389 );
4390 }
4391 let canonical: Vec<T::Kind> = <T::Kind as tatara_closed_set::ClosedSet>::ALL
4392 .iter()
4393 .copied()
4394 .filter(|k| parent.has(*k))
4395 .collect();
4396 assert_eq!(
4397 kinds, canonical,
4398 "TaggedUnion::populated_kinds() must yield ClosedSet::ALL-ordered pair on two_slot({a:?}, {b:?}) — got {kinds:?}, expected {canonical:?}",
4399 );
4400 }
4401 }
4402}
4403
4404/// Generic scalar-cardinality testkit — pins that
4405/// [`TaggedUnion::populated_kind_count`] agrees with
4406/// [`TaggedUnion::populated_kinds`]`.len()` across every
4407/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
4408/// arrangement AND that on the populated diagonal
4409/// `single_slot(k).populated_kind_count()` equals `1` exactly (aligned
4410/// with the single-slot arm's `populated_kinds()` returning
4411/// `vec![k]`).
4412///
4413/// Parent-axis substrate primitive for the scalar-cardinality
4414/// refinement of the tagged-union closed-set-inversion axis — the
4415/// scalar projection of [`assert_populated_kinds_matches_has`]'s
4416/// widened primitive. Together they close the two-refinement
4417/// composition contract that binds
4418/// [`TaggedUnion::populated_kind_count`] against
4419/// [`TaggedUnion::populated_kinds`]:
4420///
4421/// 1. **`count ↔ kinds.len()`**: `populated_kind_count() ==
4422/// populated_kinds().len()` — a regression that overrode
4423/// `populated_kind_count` to skip a kind (returning `0` on a
4424/// populated parent), double-count a slot (returning `2` on a
4425/// single-slot parent), or drift the walk from `ClosedSet::ALL`
4426/// surfaces at the substrate boundary here.
4427/// 2. **Single-slot diagonal**: `single_slot(k).populated_kind_count()
4428/// == 1` — pins the well-formed arm's expected cardinality
4429/// against the empty (`0`) and Ambiguous (`≥ 2`) arms, at ONE
4430/// `assert_eq!` per addressed kind.
4431///
4432/// Substrate primitive for future per-parent
4433/// `X_populated_kind_count_matches_populated_kinds_len` tests that
4434/// would otherwise each restate the same nested-`for k in K::ALL {
4435/// … }` sweep + composition-law equality + single-slot cardinality
4436/// pin — every one of the four production `.variant()` parents on
4437/// `ProcessSpec` binds through this ONE primitive with a per-site
4438/// `single_slot` factory. A fifth sibling picks up the scalar-
4439/// cardinality check through ONE call site — no re-authored
4440/// `for k in K::ALL { … }` sweep at the test surface, no re-authored
4441/// `assert_eq!` pair.
4442///
4443/// The `single_slot` closure stays per-site — reused verbatim from
4444/// the sibling primitives ([`assert_variant_round_trip`],
4445/// [`assert_find_agrees_with_has`],
4446/// [`assert_populated_kinds_matches_has`],
4447/// [`assert_single_slot_key_matches_label`]) — the closure IS the
4448/// "populate slot k" ground truth for the parent's field structure.
4449///
4450/// The [`crate::lifetime::Lifetime`] site is DELIBERATELY excluded
4451/// through the `T: TaggedUnion` bound — `Lifetime`'s `variant()`
4452/// returns `Ok(Permanent)` on empty rather than an `Empty` typed
4453/// error, so its projection shape diverges from the four
4454/// Empty-projecting parents. Same reasoning as
4455/// [`assert_variant_round_trip`]'s /
4456/// [`assert_find_agrees_with_has`]'s /
4457/// [`assert_populated_kinds_matches_has`]'s exclusions.
4458#[track_caller]
4459pub fn assert_populated_kind_count_matches_populated_kinds<T, F>(single_slot: F)
4460where
4461 T: TaggedUnion,
4462 T::Kind: PartialEq + std::fmt::Debug,
4463 F: Fn(T::Kind) -> T,
4464{
4465 for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
4466 .iter()
4467 .copied()
4468 {
4469 let parent = single_slot(populated);
4470 let count = parent.populated_kind_count();
4471 let kinds_len = parent.populated_kinds().len();
4472 // Composition law: scalar cardinality projection agrees with
4473 // the widened primitive's `Vec::len()`.
4474 assert_eq!(
4475 count, kinds_len,
4476 "TaggedUnion::populated_kind_count() drifted from populated_kinds().len() — populated={populated:?}",
4477 );
4478 // Single-slot diagonal — a well-formed parent from single_slot
4479 // populates exactly the addressed slot, so the scalar cardinality
4480 // is 1.
4481 assert_eq!(
4482 count, 1,
4483 "TaggedUnion::populated_kind_count() on single_slot({populated:?}) must equal 1 exactly (well-formed arm cardinality)",
4484 );
4485 }
4486}
4487
4488/// Generic closed-set-COMPLEMENT testkit — pins that
4489/// [`TaggedUnion::missing_kinds`] composes over
4490/// [`TaggedUnion::has`] under NEGATION across every
4491/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) entry on
4492/// the single-slot side, that the returned `Vec` is the canonical
4493/// [`ClosedSet::ALL`]-ordered filter of `!has(k)`, that on the
4494/// populated diagonal `single_slot(k).missing_kinds()` equals
4495/// `ALL \ {k}` exactly (length `ALL.len() - 1`, canonical ordered,
4496/// `k` absent), AND that the partition law
4497/// `populated_kinds() ∪ missing_kinds() == ClosedSet::ALL` (with
4498/// the two sets disjoint) holds byte-identically.
4499///
4500/// Parent-axis substrate primitive for the tagged-union closed-set-
4501/// complement refinement — the peer of
4502/// [`crate::boundary::assert_slice_refinement_composition_laws`]'s
4503/// `missing_kinds` sub-arm on the slice-level presence-probe axis,
4504/// lifted here to the tagged-union parent-level presence-probe axis
4505/// (same shape, same composition operator under negation, second
4506/// instance in the workspace-wide closed-set-complement refinement
4507/// algebra).
4508///
4509/// The FOUR sub-assertions swept per populated slot:
4510///
4511/// 1. Per-kind membership under negation:
4512/// `parent.missing_kinds().contains(&k) == !parent.has(k)` for
4513/// every `k ∈ ClosedSet::ALL` — a regression that overrode
4514/// `missing_kinds` to skip a kind, drift the walk order from
4515/// canonical `ALL`, or return a superset containing populated
4516/// kinds surfaces at the specific kind's per-pair assertion.
4517/// 2. Canonical `ALL`-filter equality under negation:
4518/// `parent.missing_kinds() == ALL.iter().copied().filter(|k|
4519/// !parent.has(*k)).collect()` — a regression that returned
4520/// duplicates or drifted the walk order surfaces at the
4521/// post-loop equality assert.
4522/// 3. Single-slot diagonal: `single_slot(k).missing_kinds()`
4523/// equals `ALL` with `k` removed — length exactly `ALL.len() - 1`,
4524/// canonical order preserved. Pins the well-formed arm's
4525/// complement cardinality.
4526/// 4. Partition law: `populated_kinds() ∪ missing_kinds() ==
4527/// ClosedSet::ALL` byte-identically (concatenated then re-sorted
4528/// into canonical `ALL` order) AND the two sets are disjoint
4529/// (no kind appears in both). A regression on either side of the
4530/// partition (a kind that appears in NEITHER, or in BOTH) fails
4531/// HERE at the partition assert — the compound-lift's most-
4532/// load-bearing invariant.
4533///
4534/// Substrate primitive for future per-parent
4535/// `X_missing_kinds_matches_has` tests that would otherwise each
4536/// restate the same nested-`for populated in K::ALL { for probed
4537/// in K::ALL { … } }` sweep + canonical-order equality + single-
4538/// slot diagonal pin + partition-law composition — every one of
4539/// the four production `.variant()` parents on `ProcessSpec` binds
4540/// through this ONE primitive with a per-site `single_slot`
4541/// factory. A fifth sibling picks up the closed-set-complement
4542/// check through ONE call site — no re-authored `for k in K::ALL
4543/// { … }` sweep at the test surface, no re-authored `assert_eq!`
4544/// quad.
4545///
4546/// The `single_slot` closure stays per-site — reused verbatim from
4547/// the sibling primitives ([`assert_variant_round_trip`],
4548/// [`assert_find_agrees_with_has`],
4549/// [`assert_populated_kinds_matches_has`],
4550/// [`assert_populated_kind_count_matches_populated_kinds`],
4551/// [`assert_single_slot_key_matches_label`]).
4552///
4553/// The [`crate::lifetime::Lifetime`] site is DELIBERATELY excluded
4554/// through the `T: TaggedUnion` bound — same reasoning as the
4555/// sibling primitives.
4556#[track_caller]
4557pub fn assert_missing_kinds_matches_has<T, F>(single_slot: F)
4558where
4559 T: TaggedUnion,
4560 T::Kind: PartialEq + std::fmt::Debug,
4561 F: Fn(T::Kind) -> T,
4562{
4563 for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
4564 .iter()
4565 .copied()
4566 {
4567 let parent = single_slot(populated);
4568 let missing = parent.missing_kinds();
4569 let populated_kinds = parent.populated_kinds();
4570 // Per-kind membership composition law under negation, AND the
4571 // XOR partition arm: every k ∈ ALL appears in exactly one of
4572 // (populated_kinds, missing_kinds).
4573 for probed in <T::Kind as tatara_closed_set::ClosedSet>::ALL
4574 .iter()
4575 .copied()
4576 {
4577 assert_eq!(
4578 missing.contains(&probed),
4579 !parent.has(probed),
4580 "TaggedUnion::missing_kinds().contains({probed:?}) drifted from !has({probed:?}) — populated={populated:?}",
4581 );
4582 // XOR partition law: k ∈ populated_kinds ⊕ k ∈ missing_kinds
4583 // — every closed-set entry lives on EXACTLY ONE side of the
4584 // partition (populated OR missing, never both, never neither).
4585 let in_populated = populated_kinds.contains(&probed);
4586 let in_missing = missing.contains(&probed);
4587 assert!(
4588 in_populated ^ in_missing,
4589 "partition law violated — {probed:?} appears in {} of (populated_kinds, missing_kinds), not exactly one (populated={populated:?})",
4590 (in_populated as u8) + (in_missing as u8),
4591 );
4592 }
4593 // Canonical ALL-filter equality under negation — pins dedup,
4594 // walk order, and membership consistency at ONE assert.
4595 let canonical: Vec<T::Kind> = <T::Kind as tatara_closed_set::ClosedSet>::ALL
4596 .iter()
4597 .copied()
4598 .filter(|k| !parent.has(*k))
4599 .collect();
4600 assert_eq!(
4601 missing, canonical,
4602 "TaggedUnion::missing_kinds() must yield ClosedSet::ALL-ordered subsequence where !has is true (no duplicates, canonical order) — populated={populated:?}",
4603 );
4604 // Single-slot diagonal — a well-formed parent from single_slot
4605 // populates exactly the addressed slot, so the missing set is
4606 // `ALL \ {populated}` in canonical order (length ALL.len() - 1,
4607 // `populated` absent).
4608 let expected_missing: Vec<T::Kind> = <T::Kind as tatara_closed_set::ClosedSet>::ALL
4609 .iter()
4610 .copied()
4611 .filter(|k| *k != populated)
4612 .collect();
4613 assert_eq!(
4614 missing, expected_missing,
4615 "TaggedUnion::missing_kinds() on single_slot({populated:?}) must return ClosedSet::ALL with {populated:?} removed",
4616 );
4617 }
4618}
4619
4620/// Generic zero-allocation-iterator testkit for the closed-set-
4621/// complement axis — pins that [`TaggedUnion::iter_missing_kinds`]
4622/// yields byte-identically to [`TaggedUnion::missing_kinds`] after
4623/// `.collect::<Vec<_>>()`, and that repeated calls yield the same
4624/// sequence (the iterator is pure over `&self`).
4625///
4626/// Complement-side peer of
4627/// [`assert_iter_populated_kinds_matches_populated_kinds`] on the
4628/// closed-set-complement axis — [`TaggedUnion::missing_kinds`]'s
4629/// default body IS `self.iter_missing_kinds().collect()`, so the
4630/// composition law
4631/// `missing_kinds() == iter_missing_kinds().collect::<Vec<_>>()`
4632/// holds by construction. The pin here surfaces an
4633/// `iter_missing_kinds` override that would drift from the Vec
4634/// projection (a specialization that yields kinds out of
4635/// `Kind::ALL` order, duplicates an entry, or short-circuits before
4636/// reaching an empty slot) at ONE substrate site rather than at
4637/// every downstream fold that composes over the complement-side
4638/// iterator.
4639///
4640/// The three sub-assertions swept per populated slot:
4641///
4642/// 1. `iter_missing_kinds().collect::<Vec<_>>() == missing_kinds()`
4643/// — the composition law binding the iterator peer to the Vec
4644/// widened primitive at the trait-default boundary.
4645/// 2. `iter_missing_kinds().collect::<Vec<_>>() ==
4646/// iter_missing_kinds().collect::<Vec<_>>()` (called twice) —
4647/// the iterator is pure over `&self`.
4648/// 3. On the single-slot diagonal, the collected vec equals
4649/// `ClosedSet::ALL \ {populated}` in canonical order — the
4650/// single-slot round-trip through the iterator peer matches
4651/// the round-trip through the widened Vec peer on the
4652/// complement side (length `ALL.len() - 1`, `populated`
4653/// absent).
4654///
4655/// A fifth sibling tagged-union parent picks up the complement-
4656/// side iterator composition-law check through ONE
4657/// `assert_iter_missing_kinds_matches_missing_kinds::<X, _>(single_slot)`
4658/// invocation — no re-authored `for k in K::ALL { … }` sweep at the
4659/// test site, no re-authored `.collect::<Vec<_>>()` assertion
4660/// against the widened Vec peer.
4661#[track_caller]
4662pub fn assert_iter_missing_kinds_matches_missing_kinds<T, F>(single_slot: F)
4663where
4664 T: TaggedUnion,
4665 T::Kind: PartialEq + std::fmt::Debug,
4666 F: Fn(T::Kind) -> T,
4667{
4668 for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
4669 .iter()
4670 .copied()
4671 {
4672 let parent = single_slot(populated);
4673 let via_iter: Vec<T::Kind> = parent.iter_missing_kinds().collect();
4674 let via_vec = parent.missing_kinds();
4675 assert_eq!(
4676 via_iter, via_vec,
4677 "TaggedUnion::iter_missing_kinds().collect() drifted from missing_kinds() — populated={populated:?}",
4678 );
4679 // Purity — repeated invocations yield the same sequence.
4680 let via_iter_again: Vec<T::Kind> = parent.iter_missing_kinds().collect();
4681 assert_eq!(
4682 via_iter, via_iter_again,
4683 "TaggedUnion::iter_missing_kinds() must be pure over &self — populated={populated:?}",
4684 );
4685 // Single-slot diagonal — round-trip yields ALL \ {populated}.
4686 let expected_missing: Vec<T::Kind> = <T::Kind as tatara_closed_set::ClosedSet>::ALL
4687 .iter()
4688 .copied()
4689 .filter(|k| *k != populated)
4690 .collect();
4691 assert_eq!(
4692 via_iter, expected_missing,
4693 "TaggedUnion::iter_missing_kinds() on single_slot({populated:?}) must yield ClosedSet::ALL with {populated:?} removed",
4694 );
4695 }
4696}
4697
4698/// Generic scalar-cardinality testkit for the closed-set-complement
4699/// axis — pins that [`TaggedUnion::missing_kind_count`] agrees with
4700/// [`TaggedUnion::missing_kinds`]`.len()` across every
4701/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
4702/// arrangement AND that on the populated diagonal
4703/// `single_slot(k).missing_kind_count()` equals `ALL.len() - 1`
4704/// exactly (aligned with the single-slot arm's `missing_kinds()`
4705/// returning `ALL \ {k}`) AND that the scalar partition law
4706/// `populated_kind_count() + missing_kind_count() == ALL.len()`
4707/// holds byte-identically.
4708///
4709/// Parent-axis substrate primitive for the scalar-cardinality
4710/// refinement of the tagged-union closed-set-complement axis — the
4711/// scalar projection of [`assert_missing_kinds_matches_has`]'s
4712/// widened primitive. Together they close the three-refinement
4713/// composition contract that binds
4714/// [`TaggedUnion::missing_kind_count`] against
4715/// [`TaggedUnion::missing_kinds`] and against
4716/// [`TaggedUnion::populated_kind_count`]:
4717///
4718/// 1. **`count ↔ kinds.len()`**: `missing_kind_count() ==
4719/// missing_kinds().len()` — a regression that overrode
4720/// `missing_kind_count` to skip a kind (returning the populated
4721/// count instead), double-count a slot, or drift the walk from
4722/// `ClosedSet::ALL` surfaces at the substrate boundary here.
4723/// 2. **Single-slot diagonal**: `single_slot(k).missing_kind_count()
4724/// == ALL.len() - 1` — pins the well-formed arm's complement
4725/// cardinality against the empty (`ALL.len()`) and Ambiguous
4726/// (`< ALL.len() - 1`) arms.
4727/// 3. **Scalar partition law**: `populated_kind_count() +
4728/// missing_kind_count() == ALL.len()` — the scalar consequence
4729/// of the `(populated_kinds, missing_kinds)` partition law that
4730/// [`assert_missing_kinds_matches_has`] pins at the widened-
4731/// primitive layer. A regression on either scalar side (an
4732/// off-by-one on missing, a drift on populated) fails HERE at
4733/// the sum assertion.
4734///
4735/// Substrate primitive for future per-parent
4736/// `X_missing_kind_count_matches_missing_kinds_len` tests that
4737/// would otherwise each restate the same nested-`for k in K::ALL {
4738/// … }` sweep + composition-law equality + single-slot cardinality
4739/// pin + scalar partition — every one of the four production
4740/// `.variant()` parents on `ProcessSpec` binds through this ONE
4741/// primitive with a per-site `single_slot` factory. A fifth sibling
4742/// picks up the scalar-cardinality check through ONE call site.
4743///
4744/// The `single_slot` closure stays per-site — reused verbatim from
4745/// the sibling primitives ([`assert_variant_round_trip`],
4746/// [`assert_find_agrees_with_has`],
4747/// [`assert_populated_kinds_matches_has`],
4748/// [`assert_populated_kind_count_matches_populated_kinds`],
4749/// [`assert_missing_kinds_matches_has`],
4750/// [`assert_single_slot_key_matches_label`]).
4751///
4752/// The [`crate::lifetime::Lifetime`] site is DELIBERATELY excluded
4753/// through the `T: TaggedUnion` bound — same reasoning as the
4754/// sibling primitives.
4755#[track_caller]
4756pub fn assert_missing_kind_count_matches_missing_kinds<T, F>(single_slot: F)
4757where
4758 T: TaggedUnion,
4759 T::Kind: PartialEq + std::fmt::Debug,
4760 F: Fn(T::Kind) -> T,
4761{
4762 let all_len = <T::Kind as tatara_closed_set::ClosedSet>::ALL.len();
4763 for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
4764 .iter()
4765 .copied()
4766 {
4767 let parent = single_slot(populated);
4768 let count = parent.missing_kind_count();
4769 let missing_len = parent.missing_kinds().len();
4770 // Composition law: scalar cardinality projection agrees with
4771 // the widened primitive's `Vec::len()`.
4772 assert_eq!(
4773 count, missing_len,
4774 "TaggedUnion::missing_kind_count() drifted from missing_kinds().len() — populated={populated:?}",
4775 );
4776 // Single-slot diagonal — a well-formed parent from single_slot
4777 // populates exactly the addressed slot, so the missing count is
4778 // ALL.len() - 1.
4779 assert_eq!(
4780 count,
4781 all_len - 1,
4782 "TaggedUnion::missing_kind_count() on single_slot({populated:?}) must equal ALL.len() - 1 exactly (well-formed arm complement cardinality)",
4783 );
4784 // Scalar partition law: populated_kind_count + missing_kind_count == ALL.len().
4785 let populated_count = parent.populated_kind_count();
4786 assert_eq!(
4787 populated_count + count,
4788 all_len,
4789 "scalar partition law violated — populated_kind_count + missing_kind_count must equal ClosedSet::ALL.len() (populated={populated:?})",
4790 );
4791 }
4792}
4793
4794/// Generic earliest-populated-kind testkit — pins that
4795/// [`TaggedUnion::first_populated_kind`] agrees with
4796/// [`TaggedUnion::populated_kinds`]`.first().copied()` across every
4797/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
4798/// arrangement AND that on the populated diagonal
4799/// `single_slot(k).first_populated_kind()` equals `Some(k)` exactly.
4800///
4801/// Parent-axis substrate primitive for the earliest-element scalar
4802/// projection of the tagged-union closed-set-inversion axis — the
4803/// `Option<Kind>`-valued projection of
4804/// [`assert_populated_kinds_matches_has`]'s widened primitive. The
4805/// three sub-assertions swept per populated slot:
4806///
4807/// 1. **`first ↔ kinds.first().copied()`**: `first_populated_kind() ==
4808/// populated_kinds().first().copied()` — a regression that
4809/// overrode `first_populated_kind` to skip the earliest match (a
4810/// `.rev().find(...)` inlined by mistake), drop the short-circuit
4811/// (allocating a full `Vec` at the callsite), or drift the walk
4812/// from `ClosedSet::ALL` surfaces here.
4813/// 2. **Single-slot diagonal**: `single_slot(k).first_populated_kind()
4814/// == Some(k)` — the earliest populated slot on a well-formed
4815/// parent IS the sole populated slot.
4816/// 3. **Emptiness composition law**: `first_populated_kind().is_none()
4817/// == (populated_kind_count() == 0)` — the earliest-element
4818/// projection agrees with the scalar cardinality on the empty
4819/// boundary. (Trivially `false == false` on every single-slot
4820/// arrangement; the load-bearing case is the sibling
4821/// empty-parent probe outside this primitive.)
4822///
4823/// A fifth sibling picks up the earliest-populated check through ONE
4824/// call site — no re-authored `for k in K::ALL` sweep, no re-authored
4825/// `assert_eq!(single_slot(k).first_populated_kind(), Some(k))`.
4826///
4827/// Same `Lifetime` exclusion as the sibling primitives.
4828#[track_caller]
4829pub fn assert_first_populated_kind_matches_populated_kinds<T, F>(single_slot: F)
4830where
4831 T: TaggedUnion,
4832 T::Kind: PartialEq + std::fmt::Debug,
4833 F: Fn(T::Kind) -> T,
4834{
4835 for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
4836 .iter()
4837 .copied()
4838 {
4839 let parent = single_slot(populated);
4840 let first = parent.first_populated_kind();
4841 let via_kinds = parent.populated_kinds().first().copied();
4842 // Composition law: earliest-element projection agrees with the
4843 // widened primitive's `Vec::first().copied()`.
4844 assert_eq!(
4845 first, via_kinds,
4846 "TaggedUnion::first_populated_kind() drifted from populated_kinds().first().copied() — populated={populated:?}",
4847 );
4848 // Single-slot diagonal — a well-formed parent from single_slot
4849 // populates exactly the addressed slot, so the earliest
4850 // populated slot IS that slot.
4851 assert_eq!(
4852 first,
4853 Some(populated),
4854 "TaggedUnion::first_populated_kind() on single_slot({populated:?}) must equal Some({populated:?}) exactly",
4855 );
4856 // Emptiness composition law on the well-formed diagonal —
4857 // exactly-one is a strictly non-empty populated set, so the
4858 // scalar cardinality and the earliest-element `is_some()`
4859 // agree.
4860 assert_eq!(
4861 first.is_some(),
4862 parent.populated_kind_count() > 0,
4863 "first_populated_kind().is_some() drifted from (populated_kind_count() > 0) — populated={populated:?}",
4864 );
4865 }
4866}
4867
4868/// Generic earliest-missing-kind testkit — pins that
4869/// [`TaggedUnion::first_missing_kind`] agrees with
4870/// [`TaggedUnion::missing_kinds`]`.first().copied()` across every
4871/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
4872/// arrangement AND that on the populated diagonal
4873/// `single_slot(k).first_missing_kind()` equals the earliest `ALL`
4874/// entry NOT equal to `k`.
4875///
4876/// Parent-axis substrate primitive for the earliest-element scalar
4877/// projection of the tagged-union closed-set-complement axis — the
4878/// `Option<Kind>`-valued projection of
4879/// [`assert_missing_kinds_matches_has`]'s widened primitive under a
4880/// negated `has` predicate. The three sub-assertions swept per
4881/// populated slot:
4882///
4883/// 1. **`first ↔ missing.first().copied()`**: `first_missing_kind()
4884/// == missing_kinds().first().copied()` — a regression that
4885/// overrode `first_missing_kind` to drop the negation (returning
4886/// the populated side instead) or drift the walk from
4887/// `ClosedSet::ALL` surfaces here.
4888/// 2. **Single-slot diagonal**: `single_slot(k).first_missing_kind()`
4889/// equals the earliest `ALL` entry not equal to `k` — a well-
4890/// formed parent's missing set is `ALL \ {k}` in canonical order,
4891/// so its earliest element is `ALL[0]` when `k != ALL[0]`, else
4892/// `ALL[1]`.
4893/// 3. **Emptiness composition law**: `first_missing_kind().is_some()
4894/// == (missing_kind_count() > 0)` — the earliest-missing
4895/// projection agrees with the scalar complement cardinality.
4896/// Non-trivial on the single-slot arm when `ALL.len() > 1`.
4897///
4898/// A fifth sibling picks up the earliest-missing check through ONE
4899/// call site.
4900///
4901/// Same `Lifetime` exclusion as the sibling primitives.
4902#[track_caller]
4903pub fn assert_first_missing_kind_matches_missing_kinds<T, F>(single_slot: F)
4904where
4905 T: TaggedUnion,
4906 T::Kind: PartialEq + std::fmt::Debug,
4907 F: Fn(T::Kind) -> T,
4908{
4909 for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
4910 .iter()
4911 .copied()
4912 {
4913 let parent = single_slot(populated);
4914 let first = parent.first_missing_kind();
4915 let via_missing = parent.missing_kinds().first().copied();
4916 // Composition law: earliest-element projection agrees with the
4917 // widened primitive's `Vec::first().copied()`.
4918 assert_eq!(
4919 first, via_missing,
4920 "TaggedUnion::first_missing_kind() drifted from missing_kinds().first().copied() — populated={populated:?}",
4921 );
4922 // Single-slot diagonal — the missing set is ALL \ {populated}
4923 // in canonical order, so its earliest element is the earliest
4924 // ALL entry not equal to populated.
4925 let expected_first_missing = <T::Kind as tatara_closed_set::ClosedSet>::ALL
4926 .iter()
4927 .copied()
4928 .find(|k| *k != populated);
4929 assert_eq!(
4930 first, expected_first_missing,
4931 "TaggedUnion::first_missing_kind() on single_slot({populated:?}) must equal earliest ClosedSet::ALL entry != {populated:?}",
4932 );
4933 // Emptiness composition law — the earliest-missing projection
4934 // agrees with the scalar complement cardinality's positivity.
4935 assert_eq!(
4936 first.is_some(),
4937 parent.missing_kind_count() > 0,
4938 "first_missing_kind().is_some() drifted from (missing_kind_count() > 0) — populated={populated:?}",
4939 );
4940 }
4941}
4942
4943/// Generic latest-populated-kind testkit — pins that
4944/// [`TaggedUnion::last_populated_kind`] agrees with
4945/// [`TaggedUnion::populated_kinds`]`.last().copied()` across every
4946/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
4947/// arrangement AND that on the populated diagonal
4948/// `single_slot(k).last_populated_kind()` equals `Some(k)` exactly.
4949///
4950/// Parent-axis substrate primitive for the latest-element scalar
4951/// projection of the tagged-union closed-set-inversion axis — the
4952/// `Option<Kind>`-valued REVERSED-walk peer of
4953/// [`assert_first_populated_kind_matches_populated_kinds`]'s
4954/// earliest-element projection. The three sub-assertions swept per
4955/// populated slot:
4956///
4957/// 1. **`last ↔ kinds.last().copied()`**: `last_populated_kind() ==
4958/// populated_kinds().last().copied()` — a regression that overrode
4959/// `last_populated_kind` to walk `ALL` forward (defeating the
4960/// time-reversal), drop the short-circuit, or drift the walk from
4961/// `ClosedSet::ALL` surfaces here.
4962/// 2. **Single-slot diagonal**: `single_slot(k).last_populated_kind()
4963/// == Some(k)` — the sole populated slot on a well-formed parent
4964/// IS both the earliest AND the latest populated slot (the
4965/// endpoint projections agree on the exactly-one arm).
4966/// 3. **Emptiness composition law**: `last_populated_kind().is_none()
4967/// == (populated_kind_count() == 0)` — the latest-element
4968/// projection agrees with the scalar cardinality on the empty
4969/// boundary. (Trivially `false == false` on every single-slot
4970/// arrangement; the load-bearing case is the sibling empty-parent
4971/// probe outside this primitive.)
4972///
4973/// A fifth sibling picks up the latest-populated check through ONE
4974/// call site — no re-authored reversed `for k in K::ALL.iter().rev()`
4975/// sweep at the test surface, no re-authored
4976/// `assert_eq!(single_slot(k).last_populated_kind(), Some(k))`.
4977///
4978/// Same `Lifetime` exclusion as the sibling primitives.
4979#[track_caller]
4980pub fn assert_last_populated_kind_matches_populated_kinds<T, F>(single_slot: F)
4981where
4982 T: TaggedUnion,
4983 T::Kind: PartialEq + std::fmt::Debug,
4984 F: Fn(T::Kind) -> T,
4985{
4986 for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
4987 .iter()
4988 .copied()
4989 {
4990 let parent = single_slot(populated);
4991 let last = parent.last_populated_kind();
4992 let via_kinds = parent.populated_kinds().last().copied();
4993 // Composition law: latest-element projection agrees with the
4994 // widened primitive's `Vec::last().copied()`.
4995 assert_eq!(
4996 last, via_kinds,
4997 "TaggedUnion::last_populated_kind() drifted from populated_kinds().last().copied() — populated={populated:?}",
4998 );
4999 // Single-slot diagonal — the sole populated slot IS both the
5000 // earliest and the latest, so the endpoint projections
5001 // coincide.
5002 assert_eq!(
5003 last,
5004 Some(populated),
5005 "TaggedUnion::last_populated_kind() on single_slot({populated:?}) must equal Some({populated:?}) exactly",
5006 );
5007 // Emptiness composition law on the well-formed diagonal.
5008 assert_eq!(
5009 last.is_some(),
5010 parent.populated_kind_count() > 0,
5011 "last_populated_kind().is_some() drifted from (populated_kind_count() > 0) — populated={populated:?}",
5012 );
5013 }
5014}
5015
5016/// Generic latest-missing-kind testkit — pins that
5017/// [`TaggedUnion::last_missing_kind`] agrees with
5018/// [`TaggedUnion::missing_kinds`]`.last().copied()` across every
5019/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
5020/// arrangement AND that on the populated diagonal
5021/// `single_slot(k).last_missing_kind()` equals the latest `ALL` entry
5022/// NOT equal to `k`.
5023///
5024/// Parent-axis substrate primitive for the latest-element scalar
5025/// projection of the tagged-union closed-set-complement axis — the
5026/// `Option<Kind>`-valued REVERSED-walk peer of
5027/// [`assert_first_missing_kind_matches_missing_kinds`]'s
5028/// earliest-element projection under a negated `has` predicate. The
5029/// three sub-assertions swept per populated slot:
5030///
5031/// 1. **`last ↔ missing.last().copied()`**: `last_missing_kind() ==
5032/// missing_kinds().last().copied()` — a regression that overrode
5033/// `last_missing_kind` to walk `ALL` forward (defeating the
5034/// time-reversal), drop the negation (returning the populated
5035/// side's latest instead), or drift the walk from `ClosedSet::ALL`
5036/// surfaces here.
5037/// 2. **Single-slot diagonal**: `single_slot(k).last_missing_kind()`
5038/// equals the LATEST `ALL` entry not equal to `k` — a well-formed
5039/// parent's missing set is `ALL \ {k}` in canonical order, so its
5040/// latest element is `ALL[ALL.len()-1]` when `k != ALL[ALL.len()-1]`,
5041/// else `ALL[ALL.len()-2]`.
5042/// 3. **Emptiness composition law**: `last_missing_kind().is_some()
5043/// == (missing_kind_count() > 0)` — the latest-missing projection
5044/// agrees with the scalar complement cardinality. Non-trivial on
5045/// the single-slot arm when `ALL.len() > 1`.
5046///
5047/// A fifth sibling picks up the latest-missing check through ONE call
5048/// site.
5049///
5050/// Same `Lifetime` exclusion as the sibling primitives.
5051#[track_caller]
5052pub fn assert_last_missing_kind_matches_missing_kinds<T, F>(single_slot: F)
5053where
5054 T: TaggedUnion,
5055 T::Kind: PartialEq + std::fmt::Debug,
5056 F: Fn(T::Kind) -> T,
5057{
5058 for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
5059 .iter()
5060 .copied()
5061 {
5062 let parent = single_slot(populated);
5063 let last = parent.last_missing_kind();
5064 let via_missing = parent.missing_kinds().last().copied();
5065 // Composition law: latest-element projection agrees with the
5066 // widened primitive's `Vec::last().copied()`.
5067 assert_eq!(
5068 last, via_missing,
5069 "TaggedUnion::last_missing_kind() drifted from missing_kinds().last().copied() — populated={populated:?}",
5070 );
5071 // Single-slot diagonal — the missing set is ALL \ {populated}
5072 // in canonical order, so its latest element is the latest ALL
5073 // entry not equal to populated.
5074 let expected_last_missing = <T::Kind as tatara_closed_set::ClosedSet>::ALL
5075 .iter()
5076 .rev()
5077 .copied()
5078 .find(|k| *k != populated);
5079 assert_eq!(
5080 last, expected_last_missing,
5081 "TaggedUnion::last_missing_kind() on single_slot({populated:?}) must equal latest ClosedSet::ALL entry != {populated:?}",
5082 );
5083 // Emptiness composition law — the latest-missing projection
5084 // agrees with the scalar complement cardinality's positivity.
5085 assert_eq!(
5086 last.is_some(),
5087 parent.missing_kind_count() > 0,
5088 "last_missing_kind().is_some() drifted from (missing_kind_count() > 0) — populated={populated:?}",
5089 );
5090 }
5091}
5092
5093/// Generic exactly-one-populated-kind testkit — pins that
5094/// [`TaggedUnion::unique_populated_kind`] returns `Some(k)` iff exactly
5095/// one slot is populated (and names that slot's kind), and `None` on
5096/// every empty / ambiguous parent, across every
5097/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
5098/// arrangement.
5099///
5100/// Parent-axis substrate primitive for the exactly-one-hit scalar
5101/// projection of the tagged-union closed-set-inversion axis — the
5102/// `Option<Kind>`-valued exactly-one peer of
5103/// [`assert_first_populated_kind_matches_populated_kinds`] and
5104/// [`assert_last_populated_kind_matches_populated_kinds`]'s endpoint
5105/// projections. The four sub-assertions swept per populated slot:
5106///
5107/// 1. **`unique ↔ exactly-one on kinds`**: `unique_populated_kind() ==
5108/// Some(k)` iff `populated_kinds() == vec![k]` — a regression that
5109/// dropped the second-hit short-circuit (returning `Some(first)`
5110/// on a two-populated parent) fails on the sibling
5111/// two-populated pin above.
5112/// 2. **Single-slot diagonal**: `single_slot(k).unique_populated_kind()
5113/// == Some(k)` — the sole populated slot IS the unique populated
5114/// kind.
5115/// 3. **Cardinality composition law**:
5116/// `unique_populated_kind().is_some() == (populated_kind_count()
5117/// == 1)` — the exactly-one predicate agrees with the scalar
5118/// cardinality on every well-formed / empty / ambiguous arm.
5119/// 4. **Endpoint agreement on Some**: on the `Some` arm,
5120/// `unique_populated_kind() == first_populated_kind() ==
5121/// last_populated_kind()` — the three endpoint-projection
5122/// primitives coincide on the exactly-one arm and DIVERGE only on
5123/// the ambiguous arm.
5124///
5125/// A fifth sibling picks up the exactly-one-populated check through
5126/// ONE call site — no re-authored `count == 1` composition at the
5127/// test surface, no re-authored `single_slot(k).unique_populated_kind()
5128/// == Some(k)` diagonal pin, no re-authored endpoint-agreement
5129/// projection.
5130///
5131/// Same `Lifetime` exclusion as the sibling primitives.
5132#[track_caller]
5133pub fn assert_unique_populated_kind_matches_populated_kinds<T, F>(single_slot: F)
5134where
5135 T: TaggedUnion,
5136 T::Kind: PartialEq + std::fmt::Debug,
5137 F: Fn(T::Kind) -> T,
5138{
5139 for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
5140 .iter()
5141 .copied()
5142 {
5143 let parent = single_slot(populated);
5144 let unique = parent.unique_populated_kind();
5145 // Composition law: exactly-one predicate on the widened primitive.
5146 let kinds = parent.populated_kinds();
5147 let expected = if kinds.len() == 1 {
5148 Some(kinds[0])
5149 } else {
5150 None
5151 };
5152 assert_eq!(
5153 unique, expected,
5154 "TaggedUnion::unique_populated_kind() drifted from (populated_kinds().len() == 1 ? Some(kinds[0]) : None) — populated={populated:?}",
5155 );
5156 // Single-slot diagonal — a well-formed parent from single_slot
5157 // populates exactly the addressed slot, so the unique populated
5158 // kind IS that slot.
5159 assert_eq!(
5160 unique,
5161 Some(populated),
5162 "TaggedUnion::unique_populated_kind() on single_slot({populated:?}) must equal Some({populated:?}) exactly",
5163 );
5164 // Cardinality composition law — exactly-one predicate agrees
5165 // with the scalar cardinality's equality-to-one.
5166 assert_eq!(
5167 unique.is_some(),
5168 parent.populated_kind_count() == 1,
5169 "unique_populated_kind().is_some() drifted from (populated_kind_count() == 1) — populated={populated:?}",
5170 );
5171 // Endpoint-agreement — on the Some arm the three endpoint
5172 // projections coincide.
5173 if unique.is_some() {
5174 assert_eq!(
5175 unique,
5176 parent.first_populated_kind(),
5177 "unique_populated_kind() must equal first_populated_kind() on the Some arm — populated={populated:?}",
5178 );
5179 assert_eq!(
5180 unique,
5181 parent.last_populated_kind(),
5182 "unique_populated_kind() must equal last_populated_kind() on the Some arm — populated={populated:?}",
5183 );
5184 }
5185 }
5186}
5187
5188/// Generic exactly-one-missing-kind testkit — pins that
5189/// [`TaggedUnion::unique_missing_kind`] returns `Some(k)` iff exactly
5190/// one slot is missing (and names that slot's kind), and `None` on
5191/// every parent whose missing-set cardinality is not one, across
5192/// every [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-
5193/// slot arrangement.
5194///
5195/// Parent-axis substrate primitive for the exactly-one-hit scalar
5196/// projection of the tagged-union closed-set-COMPLEMENT axis under a
5197/// negated `has` predicate. The three sub-assertions swept per
5198/// populated slot (single-slot diagonal only — on any tagged union
5199/// with `ALL.len() > 2` the single-slot arrangement has ≥ 2 missing
5200/// slots, so the primitive returns `None`; the load-bearing `Some`
5201/// pins are the sibling near-saturation probes outside this
5202/// primitive):
5203///
5204/// 1. **`unique ↔ exactly-one on missing`**: `unique_missing_kind()
5205/// == Some(k)` iff `missing_kinds() == vec![k]` — a regression
5206/// that dropped the second-hit short-circuit (returning
5207/// `Some(first)` on a two-missing parent) fails here.
5208/// 2. **Cardinality composition law**:
5209/// `unique_missing_kind().is_some() == (missing_kind_count() ==
5210/// 1)` — the exactly-one predicate agrees with the scalar
5211/// complement cardinality on every well-formed / empty / ambiguous
5212/// arm.
5213/// 3. **Endpoint agreement on Some**: on the `Some` arm,
5214/// `unique_missing_kind() == first_missing_kind() ==
5215/// last_missing_kind()` — the three endpoint-projection
5216/// primitives on the missing axis coincide when exactly one slot
5217/// is empty.
5218///
5219/// A fifth sibling picks up the exactly-one-missing check through
5220/// ONE call site.
5221///
5222/// Same `Lifetime` exclusion as the sibling primitives.
5223#[track_caller]
5224pub fn assert_unique_missing_kind_matches_missing_kinds<T, F>(single_slot: F)
5225where
5226 T: TaggedUnion,
5227 T::Kind: PartialEq + std::fmt::Debug,
5228 F: Fn(T::Kind) -> T,
5229{
5230 for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
5231 .iter()
5232 .copied()
5233 {
5234 let parent = single_slot(populated);
5235 let unique = parent.unique_missing_kind();
5236 // Composition law: exactly-one predicate on the widened
5237 // primitive.
5238 let missing = parent.missing_kinds();
5239 let expected = if missing.len() == 1 {
5240 Some(missing[0])
5241 } else {
5242 None
5243 };
5244 assert_eq!(
5245 unique, expected,
5246 "TaggedUnion::unique_missing_kind() drifted from (missing_kinds().len() == 1 ? Some(missing[0]) : None) — populated={populated:?}",
5247 );
5248 // Cardinality composition law — exactly-one predicate agrees
5249 // with the scalar complement cardinality's equality-to-one.
5250 assert_eq!(
5251 unique.is_some(),
5252 parent.missing_kind_count() == 1,
5253 "unique_missing_kind().is_some() drifted from (missing_kind_count() == 1) — populated={populated:?}",
5254 );
5255 // Endpoint-agreement — on the Some arm the three endpoint
5256 // projections on the missing axis coincide.
5257 if unique.is_some() {
5258 assert_eq!(
5259 unique,
5260 parent.first_missing_kind(),
5261 "unique_missing_kind() must equal first_missing_kind() on the Some arm — populated={populated:?}",
5262 );
5263 assert_eq!(
5264 unique,
5265 parent.last_missing_kind(),
5266 "unique_missing_kind() must equal last_missing_kind() on the Some arm — populated={populated:?}",
5267 );
5268 }
5269 }
5270}
5271
5272/// Generic zero-populated-cardinality Boolean testkit — pins that
5273/// [`TaggedUnion::is_empty`] agrees with the scalar cardinality
5274/// primitive's equality-to-zero across every
5275/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
5276/// arrangement AND the empty-parent baseline.
5277///
5278/// Parent-axis substrate primitive for the Boolean cardinality-
5279/// endpoint scalar projection of the tagged-union closed-set-inversion
5280/// axis under a zero-arm equality — the `bool`-valued zero-endpoint
5281/// peer of [`assert_populated_kind_count_matches_populated_kinds`]'s
5282/// scalar cardinality projection. The three sub-assertions swept per
5283/// populated slot + the ONE baseline sub-assertion on the empty
5284/// parent:
5285///
5286/// 1. **Cardinality composition law**: `is_empty() ==
5287/// (populated_kind_count() == 0)` — the Boolean projection agrees
5288/// with the scalar cardinality's zero-arm equality on every empty /
5289/// well-formed / partial / saturated arm. Byte-identical to the
5290/// trait's default body, pinning it substrate-wide so a regression
5291/// that overrides `is_empty` to skip the sweep or return the wrong
5292/// Boolean fails here.
5293/// 2. **Widened-primitive agreement**: `is_empty() ==
5294/// populated_kinds().is_empty()` — the two zero-arm projections of
5295/// the populated cardinality (via `is_empty()` short-circuit walk
5296/// vs. via `populated_kinds()` Vec materialization then `.is_empty()`)
5297/// coincide byte-identically.
5298/// 3. **Single-slot diagonal**: `single_slot(k).is_empty() == false` —
5299/// a well-formed parent from `single_slot` populates exactly the
5300/// addressed slot, so it CANNOT be empty. Pins that the primitive
5301/// doesn't drift onto the populated side of the endpoint.
5302/// 4. **Empty-parent baseline** (swept once outside the per-`k` loop):
5303/// `T::empty(T::KIND_LIST).is_empty() == true` (via a constructed
5304/// all-`None` parent since [`TaggedUnionError::empty`] is on the
5305/// error carrier, not the parent factory — the parent-side empty
5306/// fixture is composed by the caller through `Default` on the
5307/// sibling scaffold). Pins the primitive's zero-arm — a regression
5308/// that inverted the negation surfaces here.
5309///
5310/// A fifth sibling tagged-union parent picks up the zero-cardinality-
5311/// Boolean check through ONE `impl TaggedUnion for X` block + ONE
5312/// per-site `single_slot_X` factory + ONE per-site `empty_X` factory,
5313/// plus ONE call site — no re-authored `is_empty` sweep at the test
5314/// surface.
5315///
5316/// Same `Lifetime` exclusion as the sibling primitives — see
5317/// [`assert_two_slots_ambiguous`].
5318///
5319/// # Theory grounding
5320///
5321/// - THEORY.md §II.1 invariant 5 — composition preserves proofs. The
5322/// Boolean zero-endpoint projection binds through the SAME shape
5323/// the scalar cardinality binds through (a closed-set walk under
5324/// `Self::has`), differing only in the return-type collapse
5325/// (`bool` vs. `usize`) and the short-circuit gate (`!any` vs.
5326/// `count`).
5327/// - THEORY.md §VI.1 — generation over composition. A new
5328/// [`Self::Kind`] variant added to `ALL` reaches this primitive
5329/// mechanically through the `any` short-circuit at the trait's
5330/// default body.
5331#[track_caller]
5332pub fn assert_is_empty_matches_populated_kind_count<T, F, G>(single_slot: F, empty_parent: G)
5333where
5334 T: TaggedUnion,
5335 T::Kind: PartialEq + std::fmt::Debug,
5336 F: Fn(T::Kind) -> T,
5337 G: Fn() -> T,
5338{
5339 // Empty-parent baseline — the SOLE arm where `is_empty()` returns
5340 // `true`. The caller supplies the empty-parent fixture (an all-
5341 // `None` construction on the sibling scaffold's field structure).
5342 let empty = empty_parent();
5343 assert!(
5344 empty.is_empty(),
5345 "TaggedUnion::is_empty() on empty_parent() must equal true",
5346 );
5347 assert_eq!(
5348 empty.is_empty(),
5349 empty.populated_kind_count() == 0,
5350 "empty_parent().is_empty() drifted from (populated_kind_count() == 0)",
5351 );
5352 assert_eq!(
5353 empty.is_empty(),
5354 empty.populated_kinds().is_empty(),
5355 "empty_parent().is_empty() drifted from populated_kinds().is_empty()",
5356 );
5357
5358 for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
5359 .iter()
5360 .copied()
5361 {
5362 let parent = single_slot(populated);
5363 let is_empty = parent.is_empty();
5364 // Cardinality composition law — Boolean projection agrees with
5365 // the scalar cardinality's zero-arm equality.
5366 assert_eq!(
5367 is_empty,
5368 parent.populated_kind_count() == 0,
5369 "TaggedUnion::is_empty() drifted from (populated_kind_count() == 0) — populated={populated:?}",
5370 );
5371 // Widened-primitive agreement — the two zero-arm projections
5372 // of the populated cardinality coincide.
5373 assert_eq!(
5374 is_empty,
5375 parent.populated_kinds().is_empty(),
5376 "TaggedUnion::is_empty() drifted from populated_kinds().is_empty() — populated={populated:?}",
5377 );
5378 // Single-slot diagonal — a well-formed parent from single_slot
5379 // is NEVER empty.
5380 assert!(
5381 !is_empty,
5382 "TaggedUnion::is_empty() on single_slot({populated:?}) must equal false",
5383 );
5384 }
5385}
5386
5387/// Generic zero-missing-cardinality Boolean testkit — pins that
5388/// [`TaggedUnion::is_saturated`] agrees with the scalar complement
5389/// cardinality primitive's equality-to-zero across every
5390/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
5391/// arrangement AND the empty-parent baseline.
5392///
5393/// Parent-axis substrate primitive for the Boolean cardinality-
5394/// endpoint scalar projection of the tagged-union closed-set-COMPLEMENT
5395/// axis under a zero-arm equality — the `bool`-valued top-endpoint
5396/// peer of [`assert_missing_kind_count_matches_missing_kinds`]'s
5397/// scalar complement cardinality projection. The three sub-assertions
5398/// swept per populated slot + the ONE baseline sub-assertion on the
5399/// empty parent:
5400///
5401/// 1. **Cardinality composition law**: `is_saturated() ==
5402/// (missing_kind_count() == 0)` — the Boolean projection agrees
5403/// with the scalar complement cardinality's zero-arm equality on
5404/// every empty / well-formed / partial / saturated arm. Byte-
5405/// identical to the trait's default body, pinning it substrate-
5406/// wide so a regression that overrides `is_saturated` to skip the
5407/// sweep or return the wrong Boolean fails here.
5408/// 2. **Widened-primitive agreement**: `is_saturated() ==
5409/// missing_kinds().is_empty()` — the two zero-arm projections of
5410/// the missing cardinality (via `is_saturated()` short-circuit walk
5411/// vs. via `missing_kinds()` Vec materialization then
5412/// `.is_empty()`) coincide byte-identically.
5413/// 3. **Single-slot diagonal** (on `ALL.len() ≥ 2` closed sets):
5414/// `single_slot(k).is_saturated() == false` — a well-formed parent
5415/// from `single_slot` populates exactly one slot, leaving at least
5416/// one slot missing (`ALL.len() - 1 ≥ 1`), so it CANNOT be
5417/// saturated on any real-world tagged union in this workspace.
5418/// Pins that the primitive doesn't drift onto the missing-side
5419/// zero endpoint.
5420/// 4. **Empty-parent baseline** (swept once outside the per-`k` loop):
5421/// `empty_parent().is_saturated() == false` (empty has EVERY slot
5422/// missing, so `ALL.len() ≥ 1` missing, NEVER zero). Pins the
5423/// primitive's opposite-arm on the same fixture the empty-Boolean
5424/// peer pins its zero-arm.
5425///
5426/// A fifth sibling tagged-union parent picks up the zero-complement-
5427/// cardinality-Boolean check through ONE `impl TaggedUnion for X`
5428/// block + ONE per-site `single_slot_X` factory + ONE per-site
5429/// `empty_X` factory + ONE call site — no re-authored `is_saturated`
5430/// sweep at the test surface.
5431///
5432/// Same `Lifetime` exclusion as the sibling primitives.
5433///
5434/// # Theory grounding
5435///
5436/// - THEORY.md §II.1 invariant 5 — composition preserves proofs. The
5437/// Boolean top-endpoint projection binds through the SAME shape
5438/// the scalar complement cardinality binds through (a closed-set
5439/// walk under `Self::has`), differing only in the return-type
5440/// collapse (`bool` vs. `usize`) and the short-circuit gate (`all`
5441/// vs. `count`).
5442/// - THEORY.md §VI.1 — generation over composition. A new
5443/// [`Self::Kind`] variant added to `ALL` reaches this primitive
5444/// mechanically through the `all` short-circuit at the trait's
5445/// default body.
5446#[track_caller]
5447pub fn assert_is_saturated_matches_missing_kind_count<T, F, G>(single_slot: F, empty_parent: G)
5448where
5449 T: TaggedUnion,
5450 T::Kind: PartialEq + std::fmt::Debug,
5451 F: Fn(T::Kind) -> T,
5452 G: Fn() -> T,
5453{
5454 // Empty-parent baseline — the empty parent has EVERY slot missing,
5455 // so `is_saturated()` returns `false` (the opposite endpoint of
5456 // where `is_empty()` returns `true`).
5457 let empty = empty_parent();
5458 assert!(
5459 !empty.is_saturated(),
5460 "TaggedUnion::is_saturated() on empty_parent() must equal false — every slot is missing",
5461 );
5462 assert_eq!(
5463 empty.is_saturated(),
5464 empty.missing_kind_count() == 0,
5465 "empty_parent().is_saturated() drifted from (missing_kind_count() == 0)",
5466 );
5467 assert_eq!(
5468 empty.is_saturated(),
5469 empty.missing_kinds().is_empty(),
5470 "empty_parent().is_saturated() drifted from missing_kinds().is_empty()",
5471 );
5472
5473 for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
5474 .iter()
5475 .copied()
5476 {
5477 let parent = single_slot(populated);
5478 let is_saturated = parent.is_saturated();
5479 // Cardinality composition law — Boolean projection agrees with
5480 // the scalar complement cardinality's zero-arm equality.
5481 assert_eq!(
5482 is_saturated,
5483 parent.missing_kind_count() == 0,
5484 "TaggedUnion::is_saturated() drifted from (missing_kind_count() == 0) — populated={populated:?}",
5485 );
5486 // Widened-primitive agreement — the two zero-arm projections
5487 // of the missing cardinality coincide.
5488 assert_eq!(
5489 is_saturated,
5490 parent.missing_kinds().is_empty(),
5491 "TaggedUnion::is_saturated() drifted from missing_kinds().is_empty() — populated={populated:?}",
5492 );
5493 // Single-slot diagonal (on any `ALL.len() ≥ 2` closed set) — a
5494 // well-formed parent leaves `ALL.len() - 1 ≥ 1` missing, so it
5495 // CANNOT be saturated. This holds for every production tagged
5496 // union in the workspace (all have `ALL.len() ≥ 2`).
5497 assert!(
5498 !is_saturated,
5499 "TaggedUnion::is_saturated() on single_slot({populated:?}) must equal false — ALL.len() >= 2",
5500 );
5501 }
5502}
5503
5504/// Generic at-least-one-populated-cardinality Boolean testkit — pins
5505/// that [`TaggedUnion::has_any_populated_kind`] agrees with its
5506/// definitional complement [`TaggedUnion::is_empty`] AND with the
5507/// scalar cardinality primitive's strict-inequality-to-zero across
5508/// every [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-
5509/// slot arrangement AND the empty-parent baseline.
5510///
5511/// Parent-axis substrate primitive for the Boolean at-least-one
5512/// halfspace projection on the tagged-union closed-set-inversion axis
5513/// — the `bool`-valued definitional complement of
5514/// [`assert_is_empty_matches_populated_kind_count`]'s zero-endpoint
5515/// Boolean projection, and the SUBSET peer of the zero-arm Boolean on
5516/// the populated cardinality lattice. The four sub-assertions swept
5517/// per populated slot + the ONE baseline sub-assertion on the empty
5518/// parent:
5519///
5520/// 1. **Definitional complement law**: `has_any_populated_kind() ==
5521/// !is_empty()` — the SUBSET Boolean is the bit-flip of the
5522/// zero-endpoint Boolean on every empty / well-formed / partial /
5523/// saturated arm. Byte-identical to the trait's default body
5524/// (both walk `<Self::Kind as ClosedSet>::ALL.iter().any(has)`,
5525/// the endpoint arm negates the whole expression), pinning the
5526/// pair substrate-wide so a regression that overrides
5527/// `has_any_populated_kind` to skip the sweep or drift off the
5528/// complement law surfaces here.
5529/// 2. **Cardinality composition law**: `has_any_populated_kind() ==
5530/// (populated_kind_count() > 0)` — the ≥ 1 halfspace agrees with
5531/// the scalar cardinality's strict-inequality-to-zero on every arm.
5532/// 3. **Widened-primitive agreement**: `has_any_populated_kind() ==
5533/// !populated_kinds().is_empty()` — the two at-least-one
5534/// projections of the populated cardinality (via
5535/// `has_any_populated_kind()` short-circuit walk vs. via
5536/// `populated_kinds()` `Vec` materialization then `!is_empty()`)
5537/// coincide byte-identically.
5538/// 4. **Single-slot diagonal**: `single_slot(k).has_any_populated_kind()
5539/// == true` — a well-formed parent from `single_slot` populates
5540/// exactly one slot, so the ≥ 1 halfspace returns `true`. Pins
5541/// that the primitive doesn't drift off the well-formed arm.
5542/// 5. **Empty-parent baseline** (swept once outside the per-`k` loop):
5543/// `empty_parent().has_any_populated_kind() == false` (empty has
5544/// zero populated). Pins the primitive's opposite arm on the same
5545/// fixture the zero-endpoint peer pins its zero-arm — the only arm
5546/// where the ≥ 1 halfspace returns `false`.
5547///
5548/// A fifth sibling tagged-union parent picks up the at-least-one-
5549/// populated-cardinality-Boolean check through ONE `impl TaggedUnion
5550/// for X` block + ONE per-site `single_slot_X` factory + ONE per-site
5551/// `empty_X` factory + ONE call site — no re-authored
5552/// `has_any_populated_kind` sweep at the test surface.
5553///
5554/// Same `Lifetime` exclusion as the sibling primitives — see
5555/// [`assert_two_slots_ambiguous`].
5556///
5557/// # Theory grounding
5558///
5559/// - THEORY.md §II.1 invariant 5 — composition preserves proofs. The
5560/// Boolean at-least-one halfspace projection binds through the SAME
5561/// shape [`assert_is_empty_matches_populated_kind_count`] binds
5562/// through (a closed-set `any` walk under `Self::has`), differing
5563/// only in the final negation the zero-endpoint applies — pinned as
5564/// the definitional-complement law at ONE substrate site inside the
5565/// testkit's per-arm sweep.
5566/// - THEORY.md §VI.1 — generation over composition. A new
5567/// [`Self::Kind`] variant added to `ALL` reaches this primitive
5568/// mechanically through the `any` short-circuit at the trait's
5569/// default body.
5570#[track_caller]
5571pub fn assert_has_any_populated_kind_matches_populated_kind_count<T, F, G>(
5572 single_slot: F,
5573 empty_parent: G,
5574) where
5575 T: TaggedUnion,
5576 T::Kind: PartialEq + std::fmt::Debug,
5577 F: Fn(T::Kind) -> T,
5578 G: Fn() -> T,
5579{
5580 // Empty-parent baseline — the SOLE arm where
5581 // `has_any_populated_kind()` returns `false`. The definitional
5582 // complement law binds this to `is_empty() == true`.
5583 let empty = empty_parent();
5584 assert!(
5585 !empty.has_any_populated_kind(),
5586 "TaggedUnion::has_any_populated_kind() on empty_parent() must equal false",
5587 );
5588 assert_eq!(
5589 empty.has_any_populated_kind(),
5590 !empty.is_empty(),
5591 "empty_parent().has_any_populated_kind() drifted from !is_empty()",
5592 );
5593 assert_eq!(
5594 empty.has_any_populated_kind(),
5595 empty.populated_kind_count() > 0,
5596 "empty_parent().has_any_populated_kind() drifted from (populated_kind_count() > 0)",
5597 );
5598 assert_eq!(
5599 empty.has_any_populated_kind(),
5600 !empty.populated_kinds().is_empty(),
5601 "empty_parent().has_any_populated_kind() drifted from !populated_kinds().is_empty()",
5602 );
5603
5604 for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
5605 .iter()
5606 .copied()
5607 {
5608 let parent = single_slot(populated);
5609 let has_any = parent.has_any_populated_kind();
5610 // Definitional complement law — SUBSET Boolean is the bit-flip
5611 // of the zero-endpoint Boolean.
5612 assert_eq!(
5613 has_any,
5614 !parent.is_empty(),
5615 "TaggedUnion::has_any_populated_kind() drifted from !is_empty() — populated={populated:?}",
5616 );
5617 // Cardinality composition law — ≥ 1 halfspace agrees with
5618 // scalar cardinality's strict-inequality-to-zero.
5619 assert_eq!(
5620 has_any,
5621 parent.populated_kind_count() > 0,
5622 "TaggedUnion::has_any_populated_kind() drifted from (populated_kind_count() > 0) — populated={populated:?}",
5623 );
5624 // Widened-primitive agreement — the two at-least-one projections
5625 // of the populated cardinality coincide.
5626 assert_eq!(
5627 has_any,
5628 !parent.populated_kinds().is_empty(),
5629 "TaggedUnion::has_any_populated_kind() drifted from !populated_kinds().is_empty() — populated={populated:?}",
5630 );
5631 // Single-slot diagonal — a well-formed parent from single_slot
5632 // is ALWAYS at least one populated.
5633 assert!(
5634 has_any,
5635 "TaggedUnion::has_any_populated_kind() on single_slot({populated:?}) must equal true",
5636 );
5637 }
5638}
5639
5640/// Generic at-least-one-missing-cardinality Boolean testkit — pins
5641/// that [`TaggedUnion::has_any_missing_kind`] agrees with its
5642/// definitional complement [`TaggedUnion::is_saturated`] AND with the
5643/// scalar complement cardinality primitive's strict-inequality-to-zero
5644/// across every [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL)
5645/// single-slot arrangement AND the empty-parent baseline.
5646///
5647/// Parent-axis substrate primitive for the Boolean at-least-one
5648/// halfspace projection on the tagged-union closed-set-COMPLEMENT axis
5649/// — the `bool`-valued definitional complement of
5650/// [`assert_is_saturated_matches_missing_kind_count`]'s zero-endpoint
5651/// Boolean projection, and the SUBSET peer of the zero-arm Boolean on
5652/// the missing cardinality lattice. Byte-for-byte symmetrical with
5653/// [`assert_has_any_populated_kind_matches_populated_kind_count`]
5654/// under the (populated, missing) complement axis.
5655///
5656/// The four sub-assertions swept per populated slot + the ONE baseline
5657/// sub-assertion on the empty parent:
5658///
5659/// 1. **Definitional complement law**: `has_any_missing_kind() ==
5660/// !is_saturated()` — the SUBSET Boolean is the bit-flip of the
5661/// zero-endpoint Boolean on every arm. Byte-identical to the trait's
5662/// default body (via De Morgan: `any(|k| !has(k)) == !all(|k|
5663/// has(k))`), pinning the pair substrate-wide.
5664/// 2. **Cardinality composition law**: `has_any_missing_kind() ==
5665/// (missing_kind_count() > 0)` — the ≥ 1 halfspace agrees with the
5666/// scalar complement cardinality's strict-inequality-to-zero on
5667/// every arm.
5668/// 3. **Widened-primitive agreement**: `has_any_missing_kind() ==
5669/// !missing_kinds().is_empty()` — the two at-least-one projections
5670/// of the missing cardinality coincide byte-identically.
5671/// 4. **Single-slot diagonal** (on `ALL.len() ≥ 2` closed sets):
5672/// `single_slot(k).has_any_missing_kind() == true` — a well-formed
5673/// parent from `single_slot` populates exactly one slot, leaving at
5674/// least one slot missing (`ALL.len() - 1 ≥ 1`), so the ≥ 1 missing
5675/// halfspace returns `true` on every real-world tagged union in
5676/// this workspace.
5677/// 5. **Empty-parent baseline** (swept once outside the per-`k` loop):
5678/// `empty_parent().has_any_missing_kind() == true` (empty has EVERY
5679/// slot missing on any `N ≥ 1`, so ≥ 1 missing). Pins the
5680/// primitive's non-saturated arm on the same fixture the zero-
5681/// endpoint peer pins its opposite arm.
5682///
5683/// Same `Lifetime` exclusion as the sibling primitives.
5684///
5685/// # Theory grounding
5686///
5687/// - THEORY.md §II.1 invariant 5 — composition preserves proofs. The
5688/// Boolean at-least-one halfspace projection on the missing axis
5689/// binds through the SAME shape
5690/// [`assert_is_saturated_matches_missing_kind_count`] binds through
5691/// (a closed-set walk under `Self::has`), pinned as the
5692/// definitional-complement law at ONE substrate site inside the
5693/// testkit's per-arm sweep — the trait's default body composes
5694/// `any(|k| !has(k))` which is De-Morgan-equivalent to
5695/// `!all(|k| has(k))`, the exact expression `is_saturated()`
5696/// negates.
5697/// - THEORY.md §VI.1 — generation over composition. A new
5698/// [`Self::Kind`] variant added to `ALL` reaches this primitive
5699/// mechanically through the `any` short-circuit at the trait's
5700/// default body.
5701#[track_caller]
5702pub fn assert_has_any_missing_kind_matches_missing_kind_count<T, F, G>(
5703 single_slot: F,
5704 empty_parent: G,
5705) where
5706 T: TaggedUnion,
5707 T::Kind: PartialEq + std::fmt::Debug,
5708 F: Fn(T::Kind) -> T,
5709 G: Fn() -> T,
5710{
5711 // Empty-parent baseline — the empty parent has EVERY slot missing,
5712 // so `has_any_missing_kind()` returns `true` (the opposite endpoint
5713 // of where `is_saturated()` returns `true`).
5714 let empty = empty_parent();
5715 assert!(
5716 empty.has_any_missing_kind(),
5717 "TaggedUnion::has_any_missing_kind() on empty_parent() must equal true — every slot is missing",
5718 );
5719 assert_eq!(
5720 empty.has_any_missing_kind(),
5721 !empty.is_saturated(),
5722 "empty_parent().has_any_missing_kind() drifted from !is_saturated()",
5723 );
5724 assert_eq!(
5725 empty.has_any_missing_kind(),
5726 empty.missing_kind_count() > 0,
5727 "empty_parent().has_any_missing_kind() drifted from (missing_kind_count() > 0)",
5728 );
5729 assert_eq!(
5730 empty.has_any_missing_kind(),
5731 !empty.missing_kinds().is_empty(),
5732 "empty_parent().has_any_missing_kind() drifted from !missing_kinds().is_empty()",
5733 );
5734
5735 for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
5736 .iter()
5737 .copied()
5738 {
5739 let parent = single_slot(populated);
5740 let has_any = parent.has_any_missing_kind();
5741 // Definitional complement law — SUBSET Boolean is the bit-flip
5742 // of the zero-endpoint Boolean.
5743 assert_eq!(
5744 has_any,
5745 !parent.is_saturated(),
5746 "TaggedUnion::has_any_missing_kind() drifted from !is_saturated() — populated={populated:?}",
5747 );
5748 // Cardinality composition law — ≥ 1 halfspace agrees with
5749 // scalar complement cardinality's strict-inequality-to-zero.
5750 assert_eq!(
5751 has_any,
5752 parent.missing_kind_count() > 0,
5753 "TaggedUnion::has_any_missing_kind() drifted from (missing_kind_count() > 0) — populated={populated:?}",
5754 );
5755 // Widened-primitive agreement — the two at-least-one projections
5756 // of the missing cardinality coincide.
5757 assert_eq!(
5758 has_any,
5759 !parent.missing_kinds().is_empty(),
5760 "TaggedUnion::has_any_missing_kind() drifted from !missing_kinds().is_empty() — populated={populated:?}",
5761 );
5762 // Single-slot diagonal (on any `ALL.len() ≥ 2` closed set) — a
5763 // well-formed parent leaves `ALL.len() - 1 ≥ 1` missing, so
5764 // ≥ 1 missing halfspace holds. Every production tagged union
5765 // in the workspace has `ALL.len() ≥ 2`.
5766 assert!(
5767 has_any,
5768 "TaggedUnion::has_any_missing_kind() on single_slot({populated:?}) must equal true — ALL.len() >= 2",
5769 );
5770 }
5771}
5772
5773/// Generic one-populated-cardinality Boolean testkit — pins that
5774/// [`TaggedUnion::has_unique_populated_kind`] agrees with the scalar
5775/// cardinality primitive's equality-to-one across every
5776/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
5777/// arrangement AND the empty-parent baseline.
5778///
5779/// Parent-axis substrate primitive for the Boolean cardinality-mid-
5780/// endpoint scalar projection of the tagged-union closed-set-inversion
5781/// axis under a one-arm equality — the `bool`-valued one-endpoint peer
5782/// of [`assert_populated_kind_count_matches_populated_kinds`]'s scalar
5783/// cardinality projection. Together with [`assert_is_empty_matches_populated_kind_count`]
5784/// and [`assert_is_saturated_matches_missing_kind_count`] this closes
5785/// the substrate's 2×2 Boolean-endpoint sweep on the tagged-union
5786/// parent axis. The three sub-assertions swept per populated slot +
5787/// the ONE baseline sub-assertion on the empty parent:
5788///
5789/// 1. **Cardinality composition law**: `has_unique_populated_kind() ==
5790/// (populated_kind_count() == 1)` — the Boolean projection agrees
5791/// with the scalar cardinality's one-arm equality on every empty /
5792/// well-formed / partial / saturated arm. Byte-identical to the
5793/// trait's default body composed with `unique_populated_kind`,
5794/// pinning it substrate-wide so a regression that overrides
5795/// `has_unique_populated_kind` to skip the sweep or return the
5796/// wrong Boolean fails here.
5797/// 2. **Unique-primitive agreement**: `has_unique_populated_kind() ==
5798/// unique_populated_kind().is_some()` — the trait's default body,
5799/// pinned explicitly so a regression on the `unique_*` primitive
5800/// or on the Boolean projection's `is_some` collapse surfaces at
5801/// ONE assertion.
5802/// 3. **Single-slot diagonal**: `single_slot(k).has_unique_populated_kind()
5803/// == true` — a well-formed parent from `single_slot` populates
5804/// exactly one slot, so the one-arm Boolean returns `true`. Pins
5805/// that the primitive doesn't drift off the well-formed arm.
5806/// 4. **Empty-parent baseline** (swept once outside the per-`k` loop):
5807/// `empty_parent().has_unique_populated_kind() == false` (zero
5808/// populated, not one). Pins the primitive's opposite-arm on the
5809/// same fixture the zero-endpoint peer pins its zero-arm.
5810///
5811/// A fifth sibling tagged-union parent picks up the one-cardinality-
5812/// Boolean check through ONE `impl TaggedUnion for X` block plus ONE
5813/// per-site `single_slot_X` factory plus ONE per-site `empty_X` factory
5814/// plus ONE call site — no re-authored `has_unique_populated_kind`
5815/// sweep at the test surface.
5816///
5817/// Same `Lifetime` exclusion as the sibling primitives — see
5818/// [`assert_two_slots_ambiguous`].
5819///
5820/// # Theory grounding
5821///
5822/// - THEORY.md §II.1 invariant 5 — composition preserves proofs. The
5823/// Boolean one-endpoint projection binds through the SAME shape
5824/// the scalar cardinality binds through (a closed-set walk under
5825/// `Self::has` composed with a two-step short-circuit), differing
5826/// only in the return-type collapse (`bool` vs. `usize`) and the
5827/// equality gate (`is_some` vs. `== 1`).
5828/// - THEORY.md §VI.1 — generation over composition. A new
5829/// [`Self::Kind`] variant added to `ALL` reaches this primitive
5830/// mechanically through the `unique_populated_kind` two-step short-
5831/// circuit at the trait's default body.
5832#[track_caller]
5833pub fn assert_has_unique_populated_kind_matches_populated_kind_count<T, F, G>(
5834 single_slot: F,
5835 empty_parent: G,
5836) where
5837 T: TaggedUnion,
5838 T::Kind: PartialEq + std::fmt::Debug,
5839 F: Fn(T::Kind) -> T,
5840 G: Fn() -> T,
5841{
5842 // Empty-parent baseline — the empty parent has ZERO populated
5843 // slots, so `has_unique_populated_kind()` returns `false` (the
5844 // opposite endpoint of where a single-slot parent returns `true`).
5845 let empty = empty_parent();
5846 assert!(
5847 !empty.has_unique_populated_kind(),
5848 "TaggedUnion::has_unique_populated_kind() on empty_parent() must equal false",
5849 );
5850 assert_eq!(
5851 empty.has_unique_populated_kind(),
5852 empty.populated_kind_count() == 1,
5853 "empty_parent().has_unique_populated_kind() drifted from (populated_kind_count() == 1)",
5854 );
5855 assert_eq!(
5856 empty.has_unique_populated_kind(),
5857 empty.unique_populated_kind().is_some(),
5858 "empty_parent().has_unique_populated_kind() drifted from unique_populated_kind().is_some()",
5859 );
5860
5861 for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
5862 .iter()
5863 .copied()
5864 {
5865 let parent = single_slot(populated);
5866 let has_unique = parent.has_unique_populated_kind();
5867 // Cardinality composition law — Boolean projection agrees with
5868 // the scalar cardinality's one-arm equality.
5869 assert_eq!(
5870 has_unique,
5871 parent.populated_kind_count() == 1,
5872 "TaggedUnion::has_unique_populated_kind() drifted from (populated_kind_count() == 1) — populated={populated:?}",
5873 );
5874 // Unique-primitive agreement — the Boolean is the `is_some`
5875 // projection of the Option-valued unique primitive.
5876 assert_eq!(
5877 has_unique,
5878 parent.unique_populated_kind().is_some(),
5879 "TaggedUnion::has_unique_populated_kind() drifted from unique_populated_kind().is_some() — populated={populated:?}",
5880 );
5881 // Single-slot diagonal — a well-formed parent from single_slot
5882 // has exactly one populated slot, so the one-arm Boolean is
5883 // `true`.
5884 assert!(
5885 has_unique,
5886 "TaggedUnion::has_unique_populated_kind() on single_slot({populated:?}) must equal true",
5887 );
5888 }
5889}
5890
5891/// Generic one-missing-cardinality Boolean testkit — pins that
5892/// [`TaggedUnion::has_unique_missing_kind`] agrees with the scalar
5893/// complement cardinality primitive's equality-to-one across every
5894/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
5895/// arrangement AND the empty-parent baseline.
5896///
5897/// Parent-axis substrate primitive for the Boolean cardinality-mid-
5898/// endpoint scalar projection of the tagged-union closed-set-COMPLEMENT
5899/// axis under a one-arm equality — the `bool`-valued one-endpoint peer
5900/// of [`assert_missing_kind_count_matches_missing_kinds`]'s scalar
5901/// complement cardinality projection. Byte-for-byte symmetrical with
5902/// [`assert_has_unique_populated_kind_matches_populated_kind_count`]
5903/// under the (populated, missing) complement axis. The three
5904/// sub-assertions swept per populated slot + the baseline sub-assertion
5905/// on the empty parent:
5906///
5907/// 1. **Cardinality composition law**: `has_unique_missing_kind() ==
5908/// (missing_kind_count() == 1)` — the Boolean projection agrees
5909/// with the scalar complement cardinality's one-arm equality on
5910/// every empty / well-formed / partial / saturated arm.
5911/// 2. **Unique-primitive agreement**: `has_unique_missing_kind() ==
5912/// unique_missing_kind().is_some()` — the trait's default body,
5913/// pinned explicitly.
5914/// 3. **Single-slot diagonal on `ALL.len() ≥ 3` closed sets**:
5915/// `single_slot(k).has_unique_missing_kind() == false` — a well-
5916/// formed parent leaves `ALL.len() - 1 ≥ 2` missing on any
5917/// `ALL.len() ≥ 3` closed set, so the one-arm Boolean returns
5918/// `false`. On the degenerate `ALL.len() == 2` closed set (e.g.
5919/// `Lifetime`, which this testkit excludes through the `TaggedUnion`
5920/// bound) well-formed and one-missing coincide; on every
5921/// production tagged union in the workspace (`ALL.len() ≥ 3`) the
5922/// diagonal returns `false`.
5923/// 4. **Empty-parent baseline**: `empty_parent().has_unique_missing_kind()
5924/// == false` (empty has EVERY slot missing, `ALL.len() ≥ 2` on
5925/// every production union, so never exactly one).
5926///
5927/// A fifth sibling tagged-union parent picks up the one-complement-
5928/// cardinality-Boolean check through ONE `impl TaggedUnion for X`
5929/// block plus ONE per-site `single_slot_X` factory plus ONE per-site
5930/// `empty_X` factory plus ONE call site — no re-authored
5931/// `has_unique_missing_kind` sweep at the test surface.
5932///
5933/// Same `Lifetime` exclusion as the sibling primitives.
5934///
5935/// # Theory grounding
5936///
5937/// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
5938/// - THEORY.md §VI.1 — generation over composition.
5939#[track_caller]
5940pub fn assert_has_unique_missing_kind_matches_missing_kind_count<T, F, G>(
5941 single_slot: F,
5942 empty_parent: G,
5943) where
5944 T: TaggedUnion,
5945 T::Kind: PartialEq + std::fmt::Debug,
5946 F: Fn(T::Kind) -> T,
5947 G: Fn() -> T,
5948{
5949 // Empty-parent baseline — the empty parent has ALL.len() missing
5950 // slots, so `has_unique_missing_kind()` returns `false` on any
5951 // ALL.len() >= 2 closed set (every production union).
5952 let empty = empty_parent();
5953 assert!(
5954 !empty.has_unique_missing_kind(),
5955 "TaggedUnion::has_unique_missing_kind() on empty_parent() must equal false — ALL.len() >= 2 missing",
5956 );
5957 assert_eq!(
5958 empty.has_unique_missing_kind(),
5959 empty.missing_kind_count() == 1,
5960 "empty_parent().has_unique_missing_kind() drifted from (missing_kind_count() == 1)",
5961 );
5962 assert_eq!(
5963 empty.has_unique_missing_kind(),
5964 empty.unique_missing_kind().is_some(),
5965 "empty_parent().has_unique_missing_kind() drifted from unique_missing_kind().is_some()",
5966 );
5967
5968 let all_len = <T::Kind as tatara_closed_set::ClosedSet>::ALL.len();
5969 for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
5970 .iter()
5971 .copied()
5972 {
5973 let parent = single_slot(populated);
5974 let has_unique = parent.has_unique_missing_kind();
5975 // Cardinality composition law — Boolean projection agrees with
5976 // the scalar complement cardinality's one-arm equality.
5977 assert_eq!(
5978 has_unique,
5979 parent.missing_kind_count() == 1,
5980 "TaggedUnion::has_unique_missing_kind() drifted from (missing_kind_count() == 1) — populated={populated:?}",
5981 );
5982 // Unique-primitive agreement — the Boolean is the `is_some`
5983 // projection of the Option-valued unique primitive.
5984 assert_eq!(
5985 has_unique,
5986 parent.unique_missing_kind().is_some(),
5987 "TaggedUnion::has_unique_missing_kind() drifted from unique_missing_kind().is_some() — populated={populated:?}",
5988 );
5989 // Single-slot diagonal — a well-formed parent has ALL.len() - 1
5990 // missing slots. On ALL.len() == 2 the diagonal returns `true`
5991 // (2 - 1 == 1); on ALL.len() >= 3 it returns `false`.
5992 let expected_diagonal = all_len == 2;
5993 assert_eq!(
5994 has_unique,
5995 expected_diagonal,
5996 "TaggedUnion::has_unique_missing_kind() on single_slot({populated:?}) must equal {expected_diagonal} (ALL.len() == {all_len} → missing == {})",
5997 all_len - 1,
5998 );
5999 }
6000}
6001
6002/// Generic ≥2-populated-cardinality Boolean testkit — pins that
6003/// [`TaggedUnion::has_multiple_populated_kinds`] agrees with the
6004/// scalar cardinality primitive's `>= 2` inequality across every
6005/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
6006/// arrangement, every off-diagonal two-slot pair, AND the empty-
6007/// parent baseline.
6008///
6009/// Parent-axis substrate primitive for the Boolean cardinality many-
6010/// arm scalar projection of the tagged-union closed-set-inversion
6011/// axis under a `>= 2` inequality — third arm of the {0, 1, ≥2}
6012/// cardinality trichotomy on the populated axis, byte-for-byte peer
6013/// of [`assert_is_empty_matches_populated_kind_count`] (zero-arm) and
6014/// [`assert_has_unique_populated_kind_matches_populated_kind_count`]
6015/// (one-arm). The primitives partition every tagged-union state — on
6016/// any parent EXACTLY ONE of `is_empty()`,
6017/// `has_unique_populated_kind()`, `has_multiple_populated_kinds()`
6018/// returns `true`, closing the trichotomy at the trait's default
6019/// bodies. The four sub-assertions swept per populated slot + the
6020/// baseline sub-assertions + the two-slot sweep:
6021///
6022/// 1. **Cardinality composition law**: `has_multiple_populated_kinds()
6023/// == (populated_kind_count() >= 2)` on every empty / well-formed
6024/// / two-slot / saturated arm.
6025/// 2. **Trichotomy partition law**: EXACTLY ONE of `is_empty()`,
6026/// `has_unique_populated_kind()`, `has_multiple_populated_kinds()`
6027/// returns `true` on every arm swept — pinned as
6028/// `usize::from(is_empty()) + usize::from(has_unique_populated_kind())
6029/// + usize::from(has_multiple_populated_kinds()) == 1`.
6030/// 3. **Empty-parent baseline**: `empty_parent().has_multiple_populated_kinds()
6031/// == false` (zero populated, not many).
6032/// 4. **Single-slot diagonal**:
6033/// `single_slot(k).has_multiple_populated_kinds() == false` on
6034/// every `k` in `ClosedSet::ALL` (one populated, not many).
6035/// 5. **Two-slot diagonal**: for every off-diagonal `(a, b)` pair,
6036/// `two_slot(a, b).has_multiple_populated_kinds() == true` (two
6037/// populated, definitively many).
6038///
6039/// A fifth sibling tagged-union parent picks up the many-cardinality
6040/// Boolean check through ONE `impl TaggedUnion for X` block plus ONE
6041/// per-site `single_slot_X` factory plus ONE per-site `two_slot_X`
6042/// factory plus ONE per-site `empty_X` factory plus ONE call site.
6043///
6044/// Same [`crate::lifetime::Lifetime`] exclusion as the sibling
6045/// primitives — `Lifetime` doesn't impl [`TaggedUnion`].
6046///
6047/// # Theory grounding
6048///
6049/// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
6050/// - THEORY.md §VI.1 — generation over composition.
6051#[track_caller]
6052pub fn assert_has_multiple_populated_kinds_matches_populated_kind_count<T, F, G, H>(
6053 single_slot: F,
6054 two_slot: G,
6055 empty_parent: H,
6056) where
6057 T: TaggedUnion,
6058 T::Kind: PartialEq + std::fmt::Debug,
6059 F: Fn(T::Kind) -> T,
6060 G: Fn(T::Kind, T::Kind) -> T,
6061 H: Fn() -> T,
6062{
6063 // Empty-parent baseline — zero populated slots, so
6064 // `has_multiple_populated_kinds()` returns `false`.
6065 let empty = empty_parent();
6066 assert!(
6067 !empty.has_multiple_populated_kinds(),
6068 "TaggedUnion::has_multiple_populated_kinds() on empty_parent() must equal false",
6069 );
6070 assert_eq!(
6071 empty.has_multiple_populated_kinds(),
6072 empty.populated_kind_count() >= 2,
6073 "empty_parent().has_multiple_populated_kinds() drifted from (populated_kind_count() >= 2)",
6074 );
6075 // Trichotomy partition on the empty arm — is_empty is true, the
6076 // other two are false.
6077 assert_eq!(
6078 usize::from(empty.is_empty())
6079 + usize::from(empty.has_unique_populated_kind())
6080 + usize::from(empty.has_multiple_populated_kinds()),
6081 1,
6082 "empty_parent() must satisfy EXACTLY ONE of is_empty / has_unique_populated_kind / has_multiple_populated_kinds",
6083 );
6084
6085 for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
6086 .iter()
6087 .copied()
6088 {
6089 let parent = single_slot(populated);
6090 let has_multiple = parent.has_multiple_populated_kinds();
6091 // Cardinality composition law.
6092 assert_eq!(
6093 has_multiple,
6094 parent.populated_kind_count() >= 2,
6095 "TaggedUnion::has_multiple_populated_kinds() drifted from (populated_kind_count() >= 2) — populated={populated:?}",
6096 );
6097 // Single-slot diagonal — one populated, not many.
6098 assert!(
6099 !has_multiple,
6100 "TaggedUnion::has_multiple_populated_kinds() on single_slot({populated:?}) must equal false",
6101 );
6102 // Trichotomy partition on the well-formed arm —
6103 // has_unique_populated_kind is true, the other two are false.
6104 assert_eq!(
6105 usize::from(parent.is_empty())
6106 + usize::from(parent.has_unique_populated_kind())
6107 + usize::from(has_multiple),
6108 1,
6109 "single_slot({populated:?}) must satisfy EXACTLY ONE of is_empty / has_unique_populated_kind / has_multiple_populated_kinds",
6110 );
6111 }
6112
6113 // Two-slot sweep — every off-diagonal pair has ≥ 2 populated.
6114 for a in <T::Kind as tatara_closed_set::ClosedSet>::ALL
6115 .iter()
6116 .copied()
6117 {
6118 for b in <T::Kind as tatara_closed_set::ClosedSet>::ALL
6119 .iter()
6120 .copied()
6121 {
6122 if a == b {
6123 continue;
6124 }
6125 let parent = two_slot(a, b);
6126 let has_multiple = parent.has_multiple_populated_kinds();
6127 assert!(
6128 has_multiple,
6129 "TaggedUnion::has_multiple_populated_kinds() on two_slot({a:?}, {b:?}) must equal true",
6130 );
6131 assert_eq!(
6132 has_multiple,
6133 parent.populated_kind_count() >= 2,
6134 "TaggedUnion::has_multiple_populated_kinds() drifted from (populated_kind_count() >= 2) — pair=({a:?}, {b:?})",
6135 );
6136 // Trichotomy partition on the two-slot arm —
6137 // has_multiple_populated_kinds is true, the other two
6138 // are false.
6139 assert_eq!(
6140 usize::from(parent.is_empty())
6141 + usize::from(parent.has_unique_populated_kind())
6142 + usize::from(has_multiple),
6143 1,
6144 "two_slot({a:?}, {b:?}) must satisfy EXACTLY ONE of is_empty / has_unique_populated_kind / has_multiple_populated_kinds",
6145 );
6146 }
6147 }
6148}
6149
6150/// Generic ≥2-missing-cardinality Boolean testkit — pins that
6151/// [`TaggedUnion::has_multiple_missing_kinds`] agrees with the scalar
6152/// complement cardinality primitive's `>= 2` inequality across every
6153/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
6154/// arrangement, every off-diagonal two-slot pair, AND the empty-
6155/// parent baseline.
6156///
6157/// Byte-for-byte peer of
6158/// [`assert_has_multiple_populated_kinds_matches_populated_kind_count`]
6159/// under the (populated, missing) complement axis. Third arm of the
6160/// {0, 1, ≥2} cardinality trichotomy on the missing axis, closing the
6161/// natural partition alongside
6162/// [`assert_is_saturated_matches_missing_kind_count`] (zero-arm) and
6163/// [`assert_has_unique_missing_kind_matches_missing_kind_count`]
6164/// (one-arm). Same trichotomy partition law:
6165/// `is_saturated() + has_unique_missing_kind() +
6166/// has_multiple_missing_kinds() == 1` on every arm.
6167///
6168/// The single-slot diagonal expectation depends on `ALL.len()`:
6169///
6170/// - `ALL.len() == 2`: well-formed has 1 missing, so
6171/// `has_multiple_missing_kinds() == false` (production `Lifetime`
6172/// is excluded via the `TaggedUnion` bound anyway).
6173/// - `ALL.len() >= 3`: well-formed has `ALL.len() - 1 >= 2` missing,
6174/// so `has_multiple_missing_kinds() == true`.
6175///
6176/// The two-slot diagonal expectation similarly depends:
6177///
6178/// - `ALL.len() == 3`: two_slot has `3 - 2 == 1` missing → `false`.
6179/// - `ALL.len() >= 4`: two_slot has `ALL.len() - 2 >= 2` missing →
6180/// `true`.
6181///
6182/// A fifth sibling tagged-union parent picks up the many-complement-
6183/// cardinality Boolean check through ONE `impl TaggedUnion for X`
6184/// block plus ONE per-site `single_slot_X` factory plus ONE per-site
6185/// `two_slot_X` factory plus ONE per-site `empty_X` factory plus ONE
6186/// call site.
6187///
6188/// # Theory grounding
6189///
6190/// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
6191/// - THEORY.md §VI.1 — generation over composition.
6192#[track_caller]
6193pub fn assert_has_multiple_missing_kinds_matches_missing_kind_count<T, F, G, H>(
6194 single_slot: F,
6195 two_slot: G,
6196 empty_parent: H,
6197) where
6198 T: TaggedUnion,
6199 T::Kind: PartialEq + std::fmt::Debug,
6200 F: Fn(T::Kind) -> T,
6201 G: Fn(T::Kind, T::Kind) -> T,
6202 H: Fn() -> T,
6203{
6204 let all_len = <T::Kind as tatara_closed_set::ClosedSet>::ALL.len();
6205 // Empty-parent baseline — ALL.len() missing slots, so
6206 // `has_multiple_missing_kinds()` returns `true` on any
6207 // ALL.len() >= 2 closed set.
6208 let empty = empty_parent();
6209 let empty_expected = all_len >= 2;
6210 assert_eq!(
6211 empty.has_multiple_missing_kinds(),
6212 empty_expected,
6213 "TaggedUnion::has_multiple_missing_kinds() on empty_parent() must equal {empty_expected} (ALL.len() == {all_len})",
6214 );
6215 assert_eq!(
6216 empty.has_multiple_missing_kinds(),
6217 empty.missing_kind_count() >= 2,
6218 "empty_parent().has_multiple_missing_kinds() drifted from (missing_kind_count() >= 2)",
6219 );
6220 // Trichotomy partition on the empty arm — has_multiple_missing_kinds
6221 // is true (ALL.len() >= 2), is_saturated + has_unique_missing_kind
6222 // are false.
6223 assert_eq!(
6224 usize::from(empty.is_saturated())
6225 + usize::from(empty.has_unique_missing_kind())
6226 + usize::from(empty.has_multiple_missing_kinds()),
6227 1,
6228 "empty_parent() must satisfy EXACTLY ONE of is_saturated / has_unique_missing_kind / has_multiple_missing_kinds",
6229 );
6230
6231 for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
6232 .iter()
6233 .copied()
6234 {
6235 let parent = single_slot(populated);
6236 let has_multiple = parent.has_multiple_missing_kinds();
6237 // Cardinality composition law.
6238 assert_eq!(
6239 has_multiple,
6240 parent.missing_kind_count() >= 2,
6241 "TaggedUnion::has_multiple_missing_kinds() drifted from (missing_kind_count() >= 2) — populated={populated:?}",
6242 );
6243 // Single-slot diagonal — well-formed has ALL.len() - 1
6244 // missing. `>= 2` iff `ALL.len() >= 3`.
6245 let expected_diagonal = all_len >= 3;
6246 assert_eq!(
6247 has_multiple,
6248 expected_diagonal,
6249 "TaggedUnion::has_multiple_missing_kinds() on single_slot({populated:?}) must equal {expected_diagonal} (ALL.len() == {all_len} → missing == {})",
6250 all_len - 1,
6251 );
6252 // Trichotomy partition on the well-formed arm.
6253 assert_eq!(
6254 usize::from(parent.is_saturated())
6255 + usize::from(parent.has_unique_missing_kind())
6256 + usize::from(has_multiple),
6257 1,
6258 "single_slot({populated:?}) must satisfy EXACTLY ONE of is_saturated / has_unique_missing_kind / has_multiple_missing_kinds",
6259 );
6260 }
6261
6262 // Two-slot sweep — every off-diagonal pair has ALL.len() - 2
6263 // missing.
6264 for a in <T::Kind as tatara_closed_set::ClosedSet>::ALL
6265 .iter()
6266 .copied()
6267 {
6268 for b in <T::Kind as tatara_closed_set::ClosedSet>::ALL
6269 .iter()
6270 .copied()
6271 {
6272 if a == b {
6273 continue;
6274 }
6275 let parent = two_slot(a, b);
6276 let has_multiple = parent.has_multiple_missing_kinds();
6277 let expected_two_slot = all_len >= 4;
6278 assert_eq!(
6279 has_multiple,
6280 expected_two_slot,
6281 "TaggedUnion::has_multiple_missing_kinds() on two_slot({a:?}, {b:?}) must equal {expected_two_slot} (ALL.len() == {all_len} → missing == {})",
6282 all_len - 2,
6283 );
6284 assert_eq!(
6285 has_multiple,
6286 parent.missing_kind_count() >= 2,
6287 "TaggedUnion::has_multiple_missing_kinds() drifted from (missing_kind_count() >= 2) — pair=({a:?}, {b:?})",
6288 );
6289 // Trichotomy partition on the two-slot arm.
6290 assert_eq!(
6291 usize::from(parent.is_saturated())
6292 + usize::from(parent.has_unique_missing_kind())
6293 + usize::from(has_multiple),
6294 1,
6295 "two_slot({a:?}, {b:?}) must satisfy EXACTLY ONE of is_saturated / has_unique_missing_kind / has_multiple_missing_kinds",
6296 );
6297 }
6298 }
6299}
6300
6301/// Generic ≤1-populated-cardinality Boolean testkit — pins that
6302/// [`TaggedUnion::has_at_most_one_populated_kind`] agrees with all
6303/// THREE of its composition laws across every
6304/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
6305/// arrangement, every off-diagonal two-slot pair, AND the empty-parent
6306/// baseline.
6307///
6308/// Boolean-negation peer of
6309/// [`assert_has_multiple_populated_kinds_matches_populated_kind_count`]
6310/// under `!(≥ 2) == (≤ 1)` — closes the `{≥ 2, ≤ 1}` Boolean-negation
6311/// pair on the populated cardinality axis. The three composition laws
6312/// swept per arm:
6313///
6314/// 1. **Definitional Boolean-negation law**:
6315/// `has_at_most_one_populated_kind() == !has_multiple_populated_kinds()`
6316/// — the trait's default body binds the two forms as one bit-flip
6317/// over the SAME two-step-short-circuit closed-set walk.
6318/// 2. **Scalar cardinality composition law**:
6319/// `has_at_most_one_populated_kind() == (populated_kind_count() <= 1)`
6320/// — the Boolean projection agrees with the scalar count's `<= 1`
6321/// inequality.
6322/// 3. **Trichotomy union composition law**:
6323/// `has_at_most_one_populated_kind() == is_empty() || has_unique_populated_kind()`
6324/// — the union of the zero-arm and the one-arm of the
6325/// {0, 1, ≥ 2} cardinality trichotomy.
6326///
6327/// The three arm expectations:
6328///
6329/// - **Empty-parent baseline**: `has_at_most_one_populated_kind() ==
6330/// true` (0 ≤ 1).
6331/// - **Single-slot diagonal**: `has_at_most_one_populated_kind() ==
6332/// true` (1 ≤ 1) — the SOLE `Ok` arm of [`TaggedUnion::variant`]
6333/// lies inside the at-most-one region.
6334/// - **Two-slot sweep**: `has_at_most_one_populated_kind() == false`
6335/// (2 > 1) — the AMBIGUOUS arm sits outside the at-most-one region.
6336///
6337/// A fifth sibling tagged-union parent picks up the ≤1-populated-
6338/// cardinality Boolean check through ONE `impl TaggedUnion for X`
6339/// block plus ONE per-site `single_slot_X` factory plus ONE per-site
6340/// `two_slot_X` factory plus ONE per-site `empty_X` factory plus ONE
6341/// call site — no re-authored per-site sweep.
6342///
6343/// Same [`crate::lifetime::Lifetime`] exclusion as the sibling
6344/// primitives — `Lifetime` doesn't impl [`TaggedUnion`].
6345///
6346/// # Theory grounding
6347///
6348/// - THEORY.md §II.1 invariant 5 — composition preserves proofs. The
6349/// three composition laws bind the ≤1-populated Boolean projection
6350/// to the widened `!has_multiple_populated_kinds`, the scalar
6351/// `populated_kind_count <= 1`, and the union of zero-arm ∪ one-arm
6352/// at ONE substrate site each — swept across every production
6353/// tagged union at the testkit's per-arm sweep, not per-parent.
6354/// - THEORY.md §VI.1 — generation over composition. A new
6355/// [`Self::Kind`] variant added to `ALL` reaches the primitive
6356/// mechanically through the delegated
6357/// [`TaggedUnion::has_multiple_populated_kinds`].
6358#[track_caller]
6359pub fn assert_has_at_most_one_populated_kind_matches_populated_kind_count<T, F, G, H>(
6360 single_slot: F,
6361 two_slot: G,
6362 empty_parent: H,
6363) where
6364 T: TaggedUnion,
6365 T::Kind: PartialEq + std::fmt::Debug,
6366 F: Fn(T::Kind) -> T,
6367 G: Fn(T::Kind, T::Kind) -> T,
6368 H: Fn() -> T,
6369{
6370 // Empty-parent baseline — zero populated slots, so
6371 // `has_at_most_one_populated_kind()` returns `true` (0 <= 1).
6372 let empty = empty_parent();
6373 assert!(
6374 empty.has_at_most_one_populated_kind(),
6375 "TaggedUnion::has_at_most_one_populated_kind() on empty_parent() must equal true",
6376 );
6377 // Definitional Boolean-negation composition law on the empty arm.
6378 assert_eq!(
6379 empty.has_at_most_one_populated_kind(),
6380 !empty.has_multiple_populated_kinds(),
6381 "empty_parent().has_at_most_one_populated_kind() drifted from !has_multiple_populated_kinds()",
6382 );
6383 // Scalar cardinality composition law on the empty arm.
6384 assert_eq!(
6385 empty.has_at_most_one_populated_kind(),
6386 empty.populated_kind_count() <= 1,
6387 "empty_parent().has_at_most_one_populated_kind() drifted from (populated_kind_count() <= 1)",
6388 );
6389 // Trichotomy union composition law on the empty arm.
6390 assert_eq!(
6391 empty.has_at_most_one_populated_kind(),
6392 empty.is_empty() || empty.has_unique_populated_kind(),
6393 "empty_parent().has_at_most_one_populated_kind() drifted from (is_empty() || has_unique_populated_kind())",
6394 );
6395
6396 for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
6397 .iter()
6398 .copied()
6399 {
6400 let parent = single_slot(populated);
6401 let has_at_most_one = parent.has_at_most_one_populated_kind();
6402 // Single-slot diagonal — one populated (1 <= 1).
6403 assert!(
6404 has_at_most_one,
6405 "TaggedUnion::has_at_most_one_populated_kind() on single_slot({populated:?}) must equal true",
6406 );
6407 // Definitional Boolean-negation composition law.
6408 assert_eq!(
6409 has_at_most_one,
6410 !parent.has_multiple_populated_kinds(),
6411 "TaggedUnion::has_at_most_one_populated_kind() drifted from !has_multiple_populated_kinds() — populated={populated:?}",
6412 );
6413 // Scalar cardinality composition law.
6414 assert_eq!(
6415 has_at_most_one,
6416 parent.populated_kind_count() <= 1,
6417 "TaggedUnion::has_at_most_one_populated_kind() drifted from (populated_kind_count() <= 1) — populated={populated:?}",
6418 );
6419 // Trichotomy union composition law.
6420 assert_eq!(
6421 has_at_most_one,
6422 parent.is_empty() || parent.has_unique_populated_kind(),
6423 "TaggedUnion::has_at_most_one_populated_kind() drifted from (is_empty() || has_unique_populated_kind()) — populated={populated:?}",
6424 );
6425 }
6426
6427 // Two-slot sweep — every off-diagonal pair has 2 populated (> 1).
6428 for a in <T::Kind as tatara_closed_set::ClosedSet>::ALL
6429 .iter()
6430 .copied()
6431 {
6432 for b in <T::Kind as tatara_closed_set::ClosedSet>::ALL
6433 .iter()
6434 .copied()
6435 {
6436 if a == b {
6437 continue;
6438 }
6439 let parent = two_slot(a, b);
6440 let has_at_most_one = parent.has_at_most_one_populated_kind();
6441 assert!(
6442 !has_at_most_one,
6443 "TaggedUnion::has_at_most_one_populated_kind() on two_slot({a:?}, {b:?}) must equal false",
6444 );
6445 // Definitional Boolean-negation composition law.
6446 assert_eq!(
6447 has_at_most_one,
6448 !parent.has_multiple_populated_kinds(),
6449 "TaggedUnion::has_at_most_one_populated_kind() drifted from !has_multiple_populated_kinds() — pair=({a:?}, {b:?})",
6450 );
6451 // Scalar cardinality composition law.
6452 assert_eq!(
6453 has_at_most_one,
6454 parent.populated_kind_count() <= 1,
6455 "TaggedUnion::has_at_most_one_populated_kind() drifted from (populated_kind_count() <= 1) — pair=({a:?}, {b:?})",
6456 );
6457 // Trichotomy union composition law.
6458 assert_eq!(
6459 has_at_most_one,
6460 parent.is_empty() || parent.has_unique_populated_kind(),
6461 "TaggedUnion::has_at_most_one_populated_kind() drifted from (is_empty() || has_unique_populated_kind()) — pair=({a:?}, {b:?})",
6462 );
6463 }
6464 }
6465}
6466
6467/// Generic ≤1-missing-cardinality Boolean testkit — pins that
6468/// [`TaggedUnion::has_at_most_one_missing_kind`] agrees with all THREE
6469/// of its composition laws across every
6470/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
6471/// arrangement, every off-diagonal two-slot pair, AND the empty-parent
6472/// baseline.
6473///
6474/// Byte-for-byte peer of
6475/// [`assert_has_at_most_one_populated_kind_matches_populated_kind_count`]
6476/// under the (populated, missing) complement axis, and Boolean-negation
6477/// peer of
6478/// [`assert_has_multiple_missing_kinds_matches_missing_kind_count`]
6479/// under `!(≥ 2) == (≤ 1)` — closes the `{≥ 2, ≤ 1}` Boolean-negation
6480/// pair on the missing cardinality axis. Same three composition laws:
6481///
6482/// 1. **Definitional Boolean-negation law**:
6483/// `has_at_most_one_missing_kind() == !has_multiple_missing_kinds()`.
6484/// 2. **Scalar complement-cardinality composition law**:
6485/// `has_at_most_one_missing_kind() == (missing_kind_count() <= 1)`.
6486/// 3. **Trichotomy union composition law**:
6487/// `has_at_most_one_missing_kind() == is_saturated() || has_unique_missing_kind()`.
6488///
6489/// The three arm expectations depend on `ALL.len()`:
6490///
6491/// - **Empty-parent baseline** (on `ALL.len() ≥ 2`):
6492/// `has_at_most_one_missing_kind() == false` (ALL.len() missing
6493/// slots, so ≥ 2).
6494/// - **Single-slot diagonal**: `has_at_most_one_missing_kind() == true`
6495/// iff `ALL.len() - 1 <= 1`, i.e. `ALL.len() <= 2`. Every production
6496/// tagged union in this workspace has `ALL.len() ≥ 3`, so the
6497/// single-slot diagonal returns `false` on every production arm.
6498/// (Kept general for future 2-variant tagged unions.)
6499/// - **Two-slot sweep**: `has_at_most_one_missing_kind() == true` iff
6500/// `ALL.len() - 2 <= 1`, i.e. `ALL.len() <= 3`. On production unions
6501/// with `ALL.len() == 3` (e.g. two-arm plus one — none currently),
6502/// two_slot returns `true`; on `ALL.len() >= 4` it returns `false`.
6503///
6504/// A fifth sibling tagged-union parent picks up the ≤1-missing-
6505/// cardinality Boolean check through ONE `impl TaggedUnion for X`
6506/// block plus ONE per-site `single_slot_X` factory plus ONE per-site
6507/// `two_slot_X` factory plus ONE per-site `empty_X` factory plus ONE
6508/// call site.
6509///
6510/// # Theory grounding
6511///
6512/// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
6513/// - THEORY.md §VI.1 — generation over composition.
6514#[track_caller]
6515pub fn assert_has_at_most_one_missing_kind_matches_missing_kind_count<T, F, G, H>(
6516 single_slot: F,
6517 two_slot: G,
6518 empty_parent: H,
6519) where
6520 T: TaggedUnion,
6521 T::Kind: PartialEq + std::fmt::Debug,
6522 F: Fn(T::Kind) -> T,
6523 G: Fn(T::Kind, T::Kind) -> T,
6524 H: Fn() -> T,
6525{
6526 let all_len = <T::Kind as tatara_closed_set::ClosedSet>::ALL.len();
6527 // Empty-parent baseline — ALL.len() missing slots, so
6528 // `has_at_most_one_missing_kind()` returns `true` iff ALL.len() <= 1.
6529 let empty = empty_parent();
6530 let empty_expected = all_len <= 1;
6531 assert_eq!(
6532 empty.has_at_most_one_missing_kind(),
6533 empty_expected,
6534 "TaggedUnion::has_at_most_one_missing_kind() on empty_parent() must equal {empty_expected} (ALL.len() == {all_len})",
6535 );
6536 // Definitional Boolean-negation composition law on the empty arm.
6537 assert_eq!(
6538 empty.has_at_most_one_missing_kind(),
6539 !empty.has_multiple_missing_kinds(),
6540 "empty_parent().has_at_most_one_missing_kind() drifted from !has_multiple_missing_kinds()",
6541 );
6542 // Scalar complement-cardinality composition law on the empty arm.
6543 assert_eq!(
6544 empty.has_at_most_one_missing_kind(),
6545 empty.missing_kind_count() <= 1,
6546 "empty_parent().has_at_most_one_missing_kind() drifted from (missing_kind_count() <= 1)",
6547 );
6548 // Trichotomy union composition law on the empty arm.
6549 assert_eq!(
6550 empty.has_at_most_one_missing_kind(),
6551 empty.is_saturated() || empty.has_unique_missing_kind(),
6552 "empty_parent().has_at_most_one_missing_kind() drifted from (is_saturated() || has_unique_missing_kind())",
6553 );
6554
6555 for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
6556 .iter()
6557 .copied()
6558 {
6559 let parent = single_slot(populated);
6560 let has_at_most_one = parent.has_at_most_one_missing_kind();
6561 // Single-slot diagonal — well-formed parent has ALL.len() - 1
6562 // missing. `<= 1` iff `ALL.len() <= 2`.
6563 let expected_diagonal = all_len <= 2;
6564 assert_eq!(
6565 has_at_most_one,
6566 expected_diagonal,
6567 "TaggedUnion::has_at_most_one_missing_kind() on single_slot({populated:?}) must equal {expected_diagonal} (ALL.len() == {all_len} → missing == {})",
6568 all_len - 1,
6569 );
6570 // Definitional Boolean-negation composition law.
6571 assert_eq!(
6572 has_at_most_one,
6573 !parent.has_multiple_missing_kinds(),
6574 "TaggedUnion::has_at_most_one_missing_kind() drifted from !has_multiple_missing_kinds() — populated={populated:?}",
6575 );
6576 // Scalar complement-cardinality composition law.
6577 assert_eq!(
6578 has_at_most_one,
6579 parent.missing_kind_count() <= 1,
6580 "TaggedUnion::has_at_most_one_missing_kind() drifted from (missing_kind_count() <= 1) — populated={populated:?}",
6581 );
6582 // Trichotomy union composition law.
6583 assert_eq!(
6584 has_at_most_one,
6585 parent.is_saturated() || parent.has_unique_missing_kind(),
6586 "TaggedUnion::has_at_most_one_missing_kind() drifted from (is_saturated() || has_unique_missing_kind()) — populated={populated:?}",
6587 );
6588 }
6589
6590 // Two-slot sweep — every off-diagonal pair has ALL.len() - 2
6591 // missing. `<= 1` iff `ALL.len() <= 3`.
6592 for a in <T::Kind as tatara_closed_set::ClosedSet>::ALL
6593 .iter()
6594 .copied()
6595 {
6596 for b in <T::Kind as tatara_closed_set::ClosedSet>::ALL
6597 .iter()
6598 .copied()
6599 {
6600 if a == b {
6601 continue;
6602 }
6603 let parent = two_slot(a, b);
6604 let has_at_most_one = parent.has_at_most_one_missing_kind();
6605 let expected_two_slot = all_len <= 3;
6606 assert_eq!(
6607 has_at_most_one,
6608 expected_two_slot,
6609 "TaggedUnion::has_at_most_one_missing_kind() on two_slot({a:?}, {b:?}) must equal {expected_two_slot} (ALL.len() == {all_len} → missing == {})",
6610 all_len - 2,
6611 );
6612 // Definitional Boolean-negation composition law.
6613 assert_eq!(
6614 has_at_most_one,
6615 !parent.has_multiple_missing_kinds(),
6616 "TaggedUnion::has_at_most_one_missing_kind() drifted from !has_multiple_missing_kinds() — pair=({a:?}, {b:?})",
6617 );
6618 // Scalar complement-cardinality composition law.
6619 assert_eq!(
6620 has_at_most_one,
6621 parent.missing_kind_count() <= 1,
6622 "TaggedUnion::has_at_most_one_missing_kind() drifted from (missing_kind_count() <= 1) — pair=({a:?}, {b:?})",
6623 );
6624 // Trichotomy union composition law.
6625 assert_eq!(
6626 has_at_most_one,
6627 parent.is_saturated() || parent.has_unique_missing_kind(),
6628 "TaggedUnion::has_at_most_one_missing_kind() drifted from (is_saturated() || has_unique_missing_kind()) — pair=({a:?}, {b:?})",
6629 );
6630 }
6631 }
6632}
6633
6634/// Generic parent-state-middle-arm Boolean testkit — pins that
6635/// [`TaggedUnion::is_partially_populated`] agrees with the paired
6636/// scalar-cardinality strict-inequality composition
6637/// `(populated_kind_count() > 0 && missing_kind_count() > 0)` across
6638/// every [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-
6639/// slot arrangement, every off-diagonal two-slot pair, AND the empty-
6640/// parent baseline.
6641///
6642/// Parent-state-axis substrate primitive for the Boolean middle-arm
6643/// projection of the `{Empty | Partial | Saturated}` trichotomy —
6644/// orthogonal to the {0, 1, ≥2} cardinality trichotomies already
6645/// closed on the populated / missing axes. The four sub-assertions
6646/// swept per populated slot + the four baseline sub-assertions on the
6647/// empty parent + the four sub-assertions swept per off-diagonal pair
6648/// bind FOUR composition laws per arm:
6649///
6650/// 1. **Widened negation-of-both-endpoints composition law**:
6651/// `is_partially_populated() == !is_empty() && !is_saturated()` —
6652/// the natural composition that the trait's default body's fused
6653/// walk collapses into ONE closed-set traversal. Pinned so a
6654/// regression that overrides `is_partially_populated` to skip the
6655/// sweep or return the wrong Boolean fails here at the widened
6656/// negation.
6657/// 2. **Paired scalar-cardinality composition law**:
6658/// `is_partially_populated() == (populated_kind_count() > 0 &&
6659/// missing_kind_count() > 0)` — the Boolean projection agrees with
6660/// the paired scalar-cardinality strict-inequality composition on
6661/// every empty / well-formed / partial / saturated arm.
6662/// 3. **Single-axis open-interval composition law**:
6663/// `is_partially_populated() == (0 < populated_kind_count() &&
6664/// populated_kind_count() < ALL.len())` — the Boolean projection
6665/// agrees with the single-axis strict-inequality composition
6666/// (populated cardinality lies in the open interval `(0, ALL.len())`).
6667/// 4. **Parent-state trichotomy partition law**:
6668/// `usize::from(is_empty()) + usize::from(is_partially_populated()) + usize::from(is_saturated()) == 1`
6669/// — EXACTLY ONE of the three parent-state Boolean primitives
6670/// returns `true` on every arm. This is the genuinely new proof
6671/// this testkit adds: the natural parent-state trichotomy
6672/// partitions every tagged-union state coherently, and this law
6673/// lives at ONE substrate site inside the testkit's per-arm sweep,
6674/// pinned across every production tagged union.
6675///
6676/// The three arm expectations:
6677///
6678/// - **Empty-parent baseline** (swept once outside the per-`k` loop):
6679/// `empty_parent().is_partially_populated() == false` (zero
6680/// populated, so the negation `!is_empty()` fails). Pins the
6681/// primitive's opposite-arm on the same fixture the empty-Boolean
6682/// peer pins its zero-arm.
6683/// - **Single-slot diagonal** (on `ALL.len() ≥ 2` closed sets):
6684/// `single_slot(k).is_partially_populated() == true` — a well-formed
6685/// parent from `single_slot` populates exactly one slot (0 <
6686/// populated < N), so the middle arm returns `true`. Pins the
6687/// primitive doesn't drift onto either endpoint.
6688/// - **Two-slot sweep** (on `ALL.len() ≥ 3` closed sets, which every
6689/// production tagged union in the workspace satisfies):
6690/// `two_slot(a, b).is_partially_populated() == true` — an
6691/// off-diagonal pair populates exactly two slots (0 < 2 <= N-1 < N
6692/// for N ≥ 3), so the middle arm returns `true`. On `ALL.len() ==
6693/// 2` (production `Lifetime` excluded via the `TaggedUnion` bound)
6694/// two_slot would be saturated (`false`), but no production tagged
6695/// union has `ALL.len() == 2`.
6696///
6697/// A fifth sibling tagged-union parent picks up the middle-arm-
6698/// Boolean check through ONE `impl TaggedUnion for X` block plus ONE
6699/// per-site `single_slot_X` factory plus ONE per-site `two_slot_X`
6700/// factory plus ONE per-site `empty_X` factory plus ONE call site —
6701/// no re-authored `is_partially_populated` sweep at the test surface.
6702///
6703/// Same `Lifetime` exclusion as the sibling primitives — see
6704/// [`assert_two_slots_ambiguous`].
6705///
6706/// # Theory grounding
6707///
6708/// - THEORY.md §II.1 invariant 5 — composition preserves proofs. The
6709/// Boolean parent-state middle-arm projection binds through the
6710/// SAME shape the two endpoint primitives bind through (a closed-
6711/// set walk under `Self::has`), differing only in the fused
6712/// short-circuit gate (both flags flipped) versus the endpoint
6713/// primitives' single-flag `any` / `all` short-circuits. The
6714/// trichotomy partition law lives at ONE substrate site inside the
6715/// testkit's per-arm sweep — pinned across every production tagged
6716/// union at compile time via the trait's default body composition,
6717/// not per-parent.
6718/// - THEORY.md §VI.1 — generation over composition. A new
6719/// [`Self::Kind`] variant added to `ALL` reaches this primitive
6720/// mechanically through the fused walk at the trait's default body.
6721#[track_caller]
6722pub fn assert_is_partially_populated_matches_cardinality<T, F, G, H>(
6723 single_slot: F,
6724 two_slot: G,
6725 empty_parent: H,
6726) where
6727 T: TaggedUnion,
6728 T::Kind: PartialEq + std::fmt::Debug,
6729 F: Fn(T::Kind) -> T,
6730 G: Fn(T::Kind, T::Kind) -> T,
6731 H: Fn() -> T,
6732{
6733 let all_len = <T::Kind as tatara_closed_set::ClosedSet>::ALL.len();
6734
6735 // Empty-parent baseline — zero populated slots, so
6736 // `is_partially_populated()` returns `false` (the empty arm of the
6737 // parent-state trichotomy, not the partial arm).
6738 let empty = empty_parent();
6739 // Anchor the baseline factory on the genuine empty arm — a saturated
6740 // factory would also return `false` from `is_partially_populated()`
6741 // (both endpoints of the trichotomy sit on the `false` side of the
6742 // middle-arm), so this explicit `is_empty()` pin distinguishes the
6743 // empty arm from the saturated arm on the baseline.
6744 assert!(
6745 empty.is_empty(),
6746 "TaggedUnion::is_partially_populated() testkit: empty_parent() must satisfy is_empty() == true",
6747 );
6748 assert!(
6749 !empty.is_partially_populated(),
6750 "TaggedUnion::is_partially_populated() on empty_parent() must equal false",
6751 );
6752 // Widened negation-of-both-endpoints composition law on the empty
6753 // arm.
6754 assert_eq!(
6755 empty.is_partially_populated(),
6756 !empty.is_empty() && !empty.is_saturated(),
6757 "empty_parent().is_partially_populated() drifted from (!is_empty() && !is_saturated())",
6758 );
6759 // Paired scalar-cardinality composition law on the empty arm.
6760 assert_eq!(
6761 empty.is_partially_populated(),
6762 empty.populated_kind_count() > 0 && empty.missing_kind_count() > 0,
6763 "empty_parent().is_partially_populated() drifted from (populated_kind_count() > 0 && missing_kind_count() > 0)",
6764 );
6765 // Parent-state trichotomy partition law on the empty arm —
6766 // is_empty is true, the other two are false.
6767 assert_eq!(
6768 usize::from(empty.is_empty())
6769 + usize::from(empty.is_partially_populated())
6770 + usize::from(empty.is_saturated()),
6771 1,
6772 "empty_parent() must satisfy EXACTLY ONE of is_empty / is_partially_populated / is_saturated",
6773 );
6774
6775 for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
6776 .iter()
6777 .copied()
6778 {
6779 let parent = single_slot(populated);
6780 let is_partial = parent.is_partially_populated();
6781 // Widened negation-of-both-endpoints composition law.
6782 assert_eq!(
6783 is_partial,
6784 !parent.is_empty() && !parent.is_saturated(),
6785 "TaggedUnion::is_partially_populated() drifted from (!is_empty() && !is_saturated()) — populated={populated:?}",
6786 );
6787 // Paired scalar-cardinality composition law.
6788 assert_eq!(
6789 is_partial,
6790 parent.populated_kind_count() > 0 && parent.missing_kind_count() > 0,
6791 "TaggedUnion::is_partially_populated() drifted from (populated_kind_count() > 0 && missing_kind_count() > 0) — populated={populated:?}",
6792 );
6793 // Single-axis open-interval composition law.
6794 assert_eq!(
6795 is_partial,
6796 0 < parent.populated_kind_count() && parent.populated_kind_count() < all_len,
6797 "TaggedUnion::is_partially_populated() drifted from (0 < populated_kind_count() < ALL.len()) — populated={populated:?}",
6798 );
6799 // Single-slot diagonal (on any `ALL.len() ≥ 2` closed set) —
6800 // well-formed has 1 populated + `ALL.len() - 1 ≥ 1` missing,
6801 // so the middle arm returns `true`. This holds for every
6802 // production tagged union in the workspace (all have
6803 // `ALL.len() ≥ 2`).
6804 assert!(
6805 is_partial,
6806 "TaggedUnion::is_partially_populated() on single_slot({populated:?}) must equal true — ALL.len() >= 2",
6807 );
6808 // Parent-state trichotomy partition on the well-formed arm.
6809 assert_eq!(
6810 usize::from(parent.is_empty())
6811 + usize::from(is_partial)
6812 + usize::from(parent.is_saturated()),
6813 1,
6814 "single_slot({populated:?}) must satisfy EXACTLY ONE of is_empty / is_partially_populated / is_saturated",
6815 );
6816 }
6817
6818 // Two-slot sweep — every off-diagonal pair has 2 populated
6819 // + `ALL.len() - 2` missing.
6820 for a in <T::Kind as tatara_closed_set::ClosedSet>::ALL
6821 .iter()
6822 .copied()
6823 {
6824 for b in <T::Kind as tatara_closed_set::ClosedSet>::ALL
6825 .iter()
6826 .copied()
6827 {
6828 if a == b {
6829 continue;
6830 }
6831 let parent = two_slot(a, b);
6832 let is_partial = parent.is_partially_populated();
6833 // Widened negation-of-both-endpoints composition law.
6834 assert_eq!(
6835 is_partial,
6836 !parent.is_empty() && !parent.is_saturated(),
6837 "TaggedUnion::is_partially_populated() drifted from (!is_empty() && !is_saturated()) — pair=({a:?}, {b:?})",
6838 );
6839 // Paired scalar-cardinality composition law.
6840 assert_eq!(
6841 is_partial,
6842 parent.populated_kind_count() > 0 && parent.missing_kind_count() > 0,
6843 "TaggedUnion::is_partially_populated() drifted from (populated_kind_count() > 0 && missing_kind_count() > 0) — pair=({a:?}, {b:?})",
6844 );
6845 // Two-slot diagonal — on `ALL.len() >= 3` the two-slot
6846 // parent has 2 populated + `ALL.len() - 2 >= 1` missing,
6847 // so the middle arm returns `true`. On `ALL.len() == 2`
6848 // (excluded via the `TaggedUnion` bound anyway) two_slot
6849 // would be saturated (`false`).
6850 let expected_two_slot = all_len >= 3;
6851 assert_eq!(
6852 is_partial,
6853 expected_two_slot,
6854 "TaggedUnion::is_partially_populated() on two_slot({a:?}, {b:?}) must equal {expected_two_slot} (ALL.len() == {all_len})",
6855 );
6856 // Parent-state trichotomy partition on the two-slot arm.
6857 assert_eq!(
6858 usize::from(parent.is_empty())
6859 + usize::from(is_partial)
6860 + usize::from(parent.is_saturated()),
6861 1,
6862 "two_slot({a:?}, {b:?}) must satisfy EXACTLY ONE of is_empty / is_partially_populated / is_saturated",
6863 );
6864 }
6865 }
6866}
6867
6868/// Generic kind-scoped strict-refinement testkit — pins that
6869/// [`TaggedUnion::has_only`] agrees with the widened composition
6870/// `unique_populated_kind() == Some(kind)` across every
6871/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) `× ALL`
6872/// single-slot (populated, probed) pair, every off-diagonal two-slot
6873/// pair `× ALL`, AND the empty-parent baseline `× ALL`.
6874///
6875/// Kind-scoped-strict-refinement-axis substrate primitive for the
6876/// argument-taking uniqueness peer of [`TaggedUnion::has`] — the
6877/// EQUAL predicate to `has`'s SUBSET predicate. FIVE composition laws
6878/// per arm are pinned per (populated / pair / empty × probed) sub-
6879/// assertion:
6880///
6881/// 1. **Widened uniqueness composition law**:
6882/// `has_only(kind) == (unique_populated_kind() == Some(kind))` —
6883/// the canonical composition that the trait's default body's fused
6884/// walk collapses into ONE short-circuit closed-set traversal.
6885/// Pinned so a regression that overrides `has_only` to skip the
6886/// sweep, drop the "no other populated" check, or return the wrong
6887/// Boolean fails here at the widened uniqueness composition.
6888/// 2. **Cardinality-refinement composition law**:
6889/// `has_only(kind) == (has(kind) && has_unique_populated_kind())`
6890/// — the paired-endpoint composition binding the strict refinement
6891/// to the arg-less uniqueness predicate. Pinned so a regression
6892/// that drops the "exactly one populated" check (returning `true`
6893/// on a multi-populated parent whose SET of populated kinds
6894/// contains `kind`) is caught here.
6895/// 3. **Kind-scoped implication law**:
6896/// `has_only(kind) → has(kind)` — every arm where `has_only`
6897/// returns `true` must satisfy `has(kind) == true` (the SUBSET
6898/// predicate must accept every parent the EQUAL predicate
6899/// accepts). Pinned so a regression that returns `true` on an
6900/// empty parent or a parent that populates a DIFFERENT kind is
6901/// caught here.
6902/// 4. **Kind-domain exhaustivity law**:
6903/// `<Kind as ClosedSet>::ALL.iter().filter(|k|
6904/// parent.has_only(*k)).count() ≤ 1` on every arm — a parent
6905/// satisfies `has_only(k)` for AT MOST one `k`, since two distinct
6906/// kinds cannot both be the sole populated slot. On the well-
6907/// formed arm the count is exactly 1 (the addressed kind); on the
6908/// empty AND multi-populated arms the count is 0. This kind-domain
6909/// exhaustivity law binds the argument-scoped projection to the
6910/// arg-less uniqueness predicate at ONE substrate site.
6911/// 5. **Well-formed diagonal law**:
6912/// `single_slot(k).has_only(k) == true` on every `k ∈
6913/// ClosedSet::ALL` — the single-slot factory constructs a well-
6914/// formed parent, so every `has_only(k)` on the diagonal is
6915/// `true`. Pinned so a regression that returns `false` on the
6916/// well-formed arm (e.g. a typo `!self.has(k)` in the trait
6917/// default) is caught here.
6918///
6919/// The three arm expectations:
6920///
6921/// - **Empty-parent baseline** (swept `× ALL` outside the per-slot
6922/// loop): `empty_parent().has_only(k) == false` for every `k` — no
6923/// populated slot, so no kind is the sole populated kind.
6924/// - **Single-slot sweep** (swept on `ClosedSet::ALL × ALL`):
6925/// `single_slot(populated).has_only(kind) == (populated == kind)`
6926/// — the well-formed truth table.
6927/// - **Two-slot sweep** (swept on the off-diagonal `× ALL`):
6928/// `two_slot(a, b).has_only(k) == false` for every `k` — multi-
6929/// populated parents satisfy `has_only(k)` for NO kind.
6930///
6931/// A fifth sibling tagged-union parent picks up the kind-scoped-
6932/// strict-refinement check through ONE `impl TaggedUnion for X`
6933/// block plus ONE per-site `single_slot_X` factory plus ONE per-site
6934/// `two_slot_X` factory plus ONE per-site `empty_X` factory plus ONE
6935/// call site — no re-authored `has_only` sweep at the test surface.
6936///
6937/// Same [`crate::lifetime::Lifetime`] exclusion as the sibling
6938/// primitives — the `T: TaggedUnion` bound doesn't reach it.
6939///
6940/// # Theory grounding
6941///
6942/// - THEORY.md §II.1 invariant 5 — composition preserves proofs. The
6943/// kind-scoped strict-refinement projection binds through the SAME
6944/// shape the arg-less uniqueness peer binds through (a closed-set
6945/// walk under `Self::has`), differing only in the argument-scoped
6946/// short-circuit gate (first populated slot mismatched → `false`).
6947/// The kind-domain exhaustivity law
6948/// `count k where has_only(k) ≤ 1` lives at ONE substrate site
6949/// inside the testkit's per-arm sweep — pinned across every
6950/// production tagged union at compile time via the trait's default
6951/// body composition, not per-parent.
6952/// - THEORY.md §VI.1 — generation over composition. A new
6953/// [`Self::Kind`] variant added to `ALL` reaches this primitive
6954/// mechanically through the fused walk at the trait's default body.
6955#[track_caller]
6956pub fn assert_has_only_matches_unique_populated_kind<T, F, G, H>(
6957 single_slot: F,
6958 two_slot: G,
6959 empty_parent: H,
6960) where
6961 T: TaggedUnion,
6962 T::Kind: PartialEq + std::fmt::Debug,
6963 F: Fn(T::Kind) -> T,
6964 G: Fn(T::Kind, T::Kind) -> T,
6965 H: Fn() -> T,
6966{
6967 // Empty-parent baseline — every `has_only(k)` returns `false`
6968 // because no slot is populated.
6969 let empty = empty_parent();
6970 assert!(
6971 empty.is_empty(),
6972 "TaggedUnion::has_only() testkit: empty_parent() must satisfy is_empty() == true",
6973 );
6974 for k in <T::Kind as tatara_closed_set::ClosedSet>::ALL
6975 .iter()
6976 .copied()
6977 {
6978 let via_has_only = empty.has_only(k);
6979 assert!(
6980 !via_has_only,
6981 "empty_parent().has_only({k:?}) must equal false",
6982 );
6983 // Widened uniqueness composition law on the empty arm.
6984 assert_eq!(
6985 via_has_only,
6986 empty.unique_populated_kind() == Some(k),
6987 "empty_parent().has_only({k:?}) drifted from (unique_populated_kind() == Some({k:?}))",
6988 );
6989 // Cardinality-refinement composition law on the empty arm.
6990 assert_eq!(
6991 via_has_only,
6992 empty.has(k) && empty.has_unique_populated_kind(),
6993 "empty_parent().has_only({k:?}) drifted from (has({k:?}) && has_unique_populated_kind())",
6994 );
6995 }
6996 // Kind-domain exhaustivity on the empty arm — no kind is the sole
6997 // populated kind, so the count is 0.
6998 let empty_count = <T::Kind as tatara_closed_set::ClosedSet>::ALL
6999 .iter()
7000 .copied()
7001 .filter(|k| empty.has_only(*k))
7002 .count();
7003 assert_eq!(
7004 empty_count, 0,
7005 "empty_parent(): exactly 0 kinds must satisfy has_only, got {empty_count}",
7006 );
7007
7008 // Single-slot sweep — the well-formed truth table across
7009 // `ClosedSet::ALL × ALL`.
7010 for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
7011 .iter()
7012 .copied()
7013 {
7014 let parent = single_slot(populated);
7015 for probed in <T::Kind as tatara_closed_set::ClosedSet>::ALL
7016 .iter()
7017 .copied()
7018 {
7019 let expected = probed == populated;
7020 let via_has_only = parent.has_only(probed);
7021 // Truth table on the well-formed diagonal — `true` iff the
7022 // probed kind equals the populated kind.
7023 assert_eq!(
7024 via_has_only, expected,
7025 "single_slot({populated:?}).has_only({probed:?}) must equal {expected}",
7026 );
7027 // Widened uniqueness composition law.
7028 assert_eq!(
7029 via_has_only,
7030 parent.unique_populated_kind() == Some(probed),
7031 "single_slot({populated:?}).has_only({probed:?}) drifted from (unique_populated_kind() == Some({probed:?}))",
7032 );
7033 // Cardinality-refinement composition law.
7034 assert_eq!(
7035 via_has_only,
7036 parent.has(probed) && parent.has_unique_populated_kind(),
7037 "single_slot({populated:?}).has_only({probed:?}) drifted from (has({probed:?}) && has_unique_populated_kind())",
7038 );
7039 // Kind-scoped implication law — has_only implies has.
7040 if via_has_only {
7041 assert!(
7042 parent.has(probed),
7043 "single_slot({populated:?}).has_only({probed:?}) == true but has({probed:?}) == false",
7044 );
7045 }
7046 }
7047 // Kind-domain exhaustivity on the well-formed arm — exactly 1
7048 // kind (the populated one) satisfies has_only.
7049 let well_formed_count = <T::Kind as tatara_closed_set::ClosedSet>::ALL
7050 .iter()
7051 .copied()
7052 .filter(|k| parent.has_only(*k))
7053 .count();
7054 assert_eq!(
7055 well_formed_count, 1,
7056 "single_slot({populated:?}): exactly 1 kind must satisfy has_only, got {well_formed_count}",
7057 );
7058 }
7059
7060 // Two-slot sweep — every off-diagonal pair populates two slots, so
7061 // has_only(k) == false for every k, and no kind satisfies has_only
7062 // on the multi-populated arm.
7063 for a in <T::Kind as tatara_closed_set::ClosedSet>::ALL
7064 .iter()
7065 .copied()
7066 {
7067 for b in <T::Kind as tatara_closed_set::ClosedSet>::ALL
7068 .iter()
7069 .copied()
7070 {
7071 if a == b {
7072 continue;
7073 }
7074 let parent = two_slot(a, b);
7075 for k in <T::Kind as tatara_closed_set::ClosedSet>::ALL
7076 .iter()
7077 .copied()
7078 {
7079 let via_has_only = parent.has_only(k);
7080 assert!(
7081 !via_has_only,
7082 "two_slot({a:?}, {b:?}).has_only({k:?}) must equal false",
7083 );
7084 // Widened uniqueness composition law on the multi-
7085 // populated arm.
7086 assert_eq!(
7087 via_has_only,
7088 parent.unique_populated_kind() == Some(k),
7089 "two_slot({a:?}, {b:?}).has_only({k:?}) drifted from (unique_populated_kind() == Some({k:?}))",
7090 );
7091 // Cardinality-refinement composition law.
7092 assert_eq!(
7093 via_has_only,
7094 parent.has(k) && parent.has_unique_populated_kind(),
7095 "two_slot({a:?}, {b:?}).has_only({k:?}) drifted from (has({k:?}) && has_unique_populated_kind())",
7096 );
7097 }
7098 // Kind-domain exhaustivity on the multi-populated arm — no
7099 // kind is the sole populated kind.
7100 let multi_count = <T::Kind as tatara_closed_set::ClosedSet>::ALL
7101 .iter()
7102 .copied()
7103 .filter(|k| parent.has_only(*k))
7104 .count();
7105 assert_eq!(
7106 multi_count, 0,
7107 "two_slot({a:?}, {b:?}): exactly 0 kinds must satisfy has_only, got {multi_count}",
7108 );
7109 }
7110 }
7111}
7112
7113/// Generic kind-scoped strict-refinement testkit on the MISSING axis —
7114/// pins that [`TaggedUnion::lacks_only`] agrees with
7115/// [`TaggedUnion::unique_missing_kind`]'s
7116/// argument-scoped projection, [`TaggedUnion::has`]'s negated
7117/// cardinality-refinement, AND the kind-scoped implication
7118/// `lacks_only(kind) → !has(kind)` across every
7119/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
7120/// arrangement, every off-diagonal two-slot pair, AND the empty-parent
7121/// baseline.
7122///
7123/// Closed-set-complement mirror of
7124/// [`assert_has_only_matches_unique_populated_kind`] under the
7125/// (populated, missing) duality — where the populated-axis primitive
7126/// binds `has_only(kind)` to `unique_populated_kind()`, this primitive
7127/// binds `lacks_only(kind)` to `unique_missing_kind()` through the
7128/// same shape (a closed-set walk under `Self::has`, differing only in
7129/// the negation of the presence probe). The four sub-assertions swept
7130/// per single-slot arrangement + the two-slot sweep + the empty-parent
7131/// baseline:
7132///
7133/// 1. **Widened uniqueness composition law**:
7134/// `lacks_only(kind) == (unique_missing_kind() == Some(kind))` on
7135/// every arm — the fused walk's argument-scoped projection agrees
7136/// with the arg-less unique-missing primitive's `Option::eq` on
7137/// `Some(kind)`. Byte-for-byte peer of
7138/// [`assert_has_only_matches_unique_populated_kind`]'s widened
7139/// uniqueness law under complement.
7140/// 2. **Cardinality-refinement composition law**:
7141/// `lacks_only(kind) == (!has(kind) && has_unique_missing_kind())`
7142/// on every arm — the fused walk agrees with the two-step
7143/// composition of the negated presence probe and the arg-less
7144/// missing-cardinality Boolean. Closed-set-complement mirror of
7145/// the populated-axis cardinality-refinement law.
7146/// 3. **Kind-scoped implication law**:
7147/// `lacks_only(kind) → !has(kind)` on every arm — if `kind` is the
7148/// sole missing slot then `kind` cannot be populated. Complement
7149/// mirror of the `has_only(kind) → has(kind)` implication that
7150/// binds [`TaggedUnion::has_only`] to [`TaggedUnion::has`] on the
7151/// strict-refinement axis; here the implication binds `lacks_only`
7152/// to `!has` on the closed-set-complement axis.
7153/// 4. **Kind-domain exhaustivity law**: `<T::Kind as ClosedSet>::ALL
7154/// .iter().filter(|k| parent.lacks_only(*k)).count() ≤ 1` on every
7155/// arm — a parent satisfies `lacks_only(k)` for AT MOST one `k`,
7156/// since two distinct kinds cannot both be the sole missing slot.
7157/// On the near-saturation arm (exactly 1 missing) the count is 1;
7158/// on every other arm the count is 0. Closed-set-complement mirror
7159/// of the populated-axis exhaustivity law under complement.
7160/// 5. **Missing-diagonal well-formed law**:
7161/// `unique_missing_kind()` is the source of truth for which kind
7162/// (if any) is uniquely missing on each arm — the testkit reads it
7163/// directly and asserts `lacks_only(k) == (unique_missing_kind()
7164/// == Some(k))` for every `k`, so the testkit doesn't hard-code
7165/// `ALL.len()`-dependent arm expectations (an empty parent on
7166/// `ALL.len() == 1` is uniquely missing that one kind, whereas on
7167/// `ALL.len() >= 2` no kind is uniquely missing; a single-slot
7168/// parent on `ALL.len() == 2` has one missing kind, whereas on
7169/// `ALL.len() >= 3` it has ≥ 2 missing; a two-slot parent on
7170/// `ALL.len() == 3` has one missing kind, whereas on `ALL.len()
7171/// >= 4` it has ≥ 2 missing). The composition-law shape binds
7172/// every `ALL.len()` regime through the same substrate site.
7173///
7174/// The three arm expectations:
7175///
7176/// - **Empty-parent baseline** (swept `× ALL` outside the per-slot
7177/// loop): on any `ALL.len() >= 2` closed set every kind is missing,
7178/// so `lacks_only(k) == false` for every `k` — no kind is the sole
7179/// missing kind. Every production parent is `ALL.len() >= 3`.
7180/// - **Single-slot sweep** (swept on `ClosedSet::ALL × ALL`): the
7181/// composition-law shape reads `unique_missing_kind()` directly, so
7182/// the testkit binds every `ALL.len()` regime without a hard-coded
7183/// arm expectation. Assertion messages carry the (`populated`,
7184/// `probed`) pair verbatim.
7185/// - **Two-slot sweep** (swept on the off-diagonal `× ALL`): on
7186/// `ALL.len() == 3` every off-diagonal pair leaves exactly 1 slot
7187/// missing (the third kind) — the SOLE `ALL.len()` regime where
7188/// `lacks_only(third) == true` on the two-slot arm. On `ALL.len()
7189/// >= 4` the two-slot arm has ≥ 2 missing, so `lacks_only(k) ==
7190/// false` for every `k`. The composition-law shape binds every
7191/// regime.
7192///
7193/// A fifth sibling tagged-union parent picks up the kind-scoped-
7194/// strict-refinement check on the missing axis through ONE `impl
7195/// TaggedUnion for X` block plus ONE per-site `single_slot_X` factory
7196/// plus ONE per-site `two_slot_X` factory plus ONE per-site `empty_X`
7197/// factory plus ONE call site — no re-authored `lacks_only` sweep at
7198/// the test surface.
7199///
7200/// Same [`crate::lifetime::Lifetime`] exclusion as the sibling
7201/// primitives — the `T: TaggedUnion` bound doesn't reach it.
7202///
7203/// # Theory grounding
7204///
7205/// - THEORY.md §II.1 invariant 5 — composition preserves proofs. The
7206/// kind-scoped strict-refinement projection on the MISSING axis
7207/// binds through the SAME shape the populated-axis peer binds
7208/// through (a closed-set walk under `Self::has`), differing only in
7209/// the negation of the presence probe. The composition laws
7210/// (widened uniqueness on the missing side, cardinality-refinement
7211/// under complement, kind-scoped implication under complement,
7212/// kind-domain exhaustivity on the missing side) live at ONE
7213/// substrate site inside the testkit's per-arm sweep — pinned
7214/// across every production tagged union at compile time via the
7215/// trait's default body composition, not per-parent.
7216/// - THEORY.md §VI.1 — generation over composition. A new
7217/// [`Self::Kind`] variant added to `ALL` reaches this primitive
7218/// mechanically through the fused walk at the trait's default body.
7219#[track_caller]
7220pub fn assert_lacks_only_matches_unique_missing_kind<T, F, G, H>(
7221 single_slot: F,
7222 two_slot: G,
7223 empty_parent: H,
7224) where
7225 T: TaggedUnion,
7226 T::Kind: PartialEq + std::fmt::Debug,
7227 F: Fn(T::Kind) -> T,
7228 G: Fn(T::Kind, T::Kind) -> T,
7229 H: Fn() -> T,
7230{
7231 // Empty-parent baseline — every `lacks_only(k)` returns `false` on
7232 // any `ALL.len() >= 2` closed set (every production union) because
7233 // every kind is missing so no kind is uniquely missing. The
7234 // composition-law shape below reads `unique_missing_kind()`
7235 // directly, so the testkit binds every `ALL.len()` regime without
7236 // a hard-coded arm expectation.
7237 let empty = empty_parent();
7238 assert!(
7239 empty.is_empty(),
7240 "TaggedUnion::lacks_only() testkit: empty_parent() must satisfy is_empty() == true",
7241 );
7242 for k in <T::Kind as tatara_closed_set::ClosedSet>::ALL
7243 .iter()
7244 .copied()
7245 {
7246 let via_lacks_only = empty.lacks_only(k);
7247 // Widened uniqueness composition law on the empty arm.
7248 assert_eq!(
7249 via_lacks_only,
7250 empty.unique_missing_kind() == Some(k),
7251 "empty_parent().lacks_only({k:?}) drifted from (unique_missing_kind() == Some({k:?}))",
7252 );
7253 // Cardinality-refinement composition law on the empty arm
7254 // under complement.
7255 assert_eq!(
7256 via_lacks_only,
7257 !empty.has(k) && empty.has_unique_missing_kind(),
7258 "empty_parent().lacks_only({k:?}) drifted from (!has({k:?}) && has_unique_missing_kind())",
7259 );
7260 // Kind-scoped implication law on the empty arm — lacks_only
7261 // implies !has.
7262 if via_lacks_only {
7263 assert!(
7264 !empty.has(k),
7265 "empty_parent().lacks_only({k:?}) == true but has({k:?}) == true",
7266 );
7267 }
7268 }
7269 // Kind-domain exhaustivity on the empty arm — at most 1 kind is
7270 // the sole missing kind. On `ALL.len() >= 2` the count is 0; on
7271 // the degenerate `ALL.len() == 1` regime (no production parent)
7272 // the count is 1.
7273 let empty_count = <T::Kind as tatara_closed_set::ClosedSet>::ALL
7274 .iter()
7275 .copied()
7276 .filter(|k| empty.lacks_only(*k))
7277 .count();
7278 assert!(
7279 empty_count <= 1,
7280 "empty_parent(): at most 1 kind may satisfy lacks_only, got {empty_count}",
7281 );
7282
7283 let all_len = <T::Kind as tatara_closed_set::ClosedSet>::ALL.len();
7284
7285 // Single-slot sweep — the composition-law shape across
7286 // `ClosedSet::ALL × ALL`, plus a factory-precondition truth-table
7287 // pin whose expected shape is derived from the abstract factory
7288 // contract (`single_slot(populated)` populates exactly `populated`
7289 // → the missing set is `ALL - {populated}`, size `all_len - 1`).
7290 for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
7291 .iter()
7292 .copied()
7293 {
7294 let parent = single_slot(populated);
7295 for probed in <T::Kind as tatara_closed_set::ClosedSet>::ALL
7296 .iter()
7297 .copied()
7298 {
7299 let via_lacks_only = parent.lacks_only(probed);
7300 // Factory-precondition truth table on the well-formed
7301 // single-slot arm: the missing set is `ALL - {populated}`,
7302 // so lacks_only(probed) is `true` iff exactly one slot is
7303 // missing (`all_len == 2`) AND probed names that missing
7304 // slot (`probed != populated`). This hard-codes the well-
7305 // formed diagonal expectation so a factory drift that
7306 // populates the wrong kind — or an empty parent, or the
7307 // saturated parent — surfaces here BEFORE any composition
7308 // law reconciles two internally-drifted trait bodies.
7309 let expected_single = all_len == 2 && probed != populated;
7310 assert_eq!(
7311 via_lacks_only, expected_single,
7312 "single_slot({populated:?}).lacks_only({probed:?}) must equal {expected_single} on ALL.len() == {all_len}",
7313 );
7314 // Widened uniqueness composition law — the primary
7315 // pin-point on the missing axis.
7316 assert_eq!(
7317 via_lacks_only,
7318 parent.unique_missing_kind() == Some(probed),
7319 "single_slot({populated:?}).lacks_only({probed:?}) drifted from (unique_missing_kind() == Some({probed:?}))",
7320 );
7321 // Cardinality-refinement composition law under complement.
7322 assert_eq!(
7323 via_lacks_only,
7324 !parent.has(probed) && parent.has_unique_missing_kind(),
7325 "single_slot({populated:?}).lacks_only({probed:?}) drifted from (!has({probed:?}) && has_unique_missing_kind())",
7326 );
7327 // Kind-scoped implication law under complement —
7328 // lacks_only implies !has.
7329 if via_lacks_only {
7330 assert!(
7331 !parent.has(probed),
7332 "single_slot({populated:?}).lacks_only({probed:?}) == true but has({probed:?}) == true",
7333 );
7334 }
7335 }
7336 // Kind-domain exhaustivity on the well-formed arm — at most 1
7337 // kind satisfies lacks_only. On `ALL.len() == 2` the count is
7338 // exactly 1 (the non-populated kind); on `ALL.len() >= 3` the
7339 // count is 0.
7340 let well_formed_count = <T::Kind as tatara_closed_set::ClosedSet>::ALL
7341 .iter()
7342 .copied()
7343 .filter(|k| parent.lacks_only(*k))
7344 .count();
7345 let expected_well_formed_count = usize::from(all_len == 2);
7346 assert_eq!(
7347 well_formed_count, expected_well_formed_count,
7348 "single_slot({populated:?}): exactly {expected_well_formed_count} kinds must satisfy lacks_only on ALL.len() == {all_len}, got {well_formed_count}",
7349 );
7350 }
7351
7352 // Two-slot sweep — every off-diagonal pair populates two slots, so
7353 // the missing set is `ALL - {a, b}`, size `all_len - 2`. On
7354 // `ALL.len() == 3` exactly 1 slot is missing (the third kind), so
7355 // exactly 1 kind satisfies lacks_only. On `ALL.len() >= 4` ≥ 2
7356 // slots are missing, so no kind satisfies lacks_only. The
7357 // composition-law shape binds every regime; the factory-
7358 // precondition truth-table pin catches drift like a saturated /
7359 // empty / single-slot two_slot factory that would otherwise slip
7360 // past the internally-consistent composition laws.
7361 for a in <T::Kind as tatara_closed_set::ClosedSet>::ALL
7362 .iter()
7363 .copied()
7364 {
7365 for b in <T::Kind as tatara_closed_set::ClosedSet>::ALL
7366 .iter()
7367 .copied()
7368 {
7369 if a == b {
7370 continue;
7371 }
7372 let parent = two_slot(a, b);
7373 for k in <T::Kind as tatara_closed_set::ClosedSet>::ALL
7374 .iter()
7375 .copied()
7376 {
7377 let via_lacks_only = parent.lacks_only(k);
7378 // Factory-precondition truth table on the two-slot
7379 // arm: the missing set is `ALL - {a, b}`, so
7380 // lacks_only(k) is `true` iff exactly one slot is
7381 // missing (`all_len == 3`) AND k names that missing
7382 // slot (`k != a && k != b`).
7383 let expected_two = all_len == 3 && k != a && k != b;
7384 assert_eq!(
7385 via_lacks_only, expected_two,
7386 "two_slot({a:?}, {b:?}).lacks_only({k:?}) must equal {expected_two} on ALL.len() == {all_len}",
7387 );
7388 // Widened uniqueness composition law on the multi-
7389 // populated arm.
7390 assert_eq!(
7391 via_lacks_only,
7392 parent.unique_missing_kind() == Some(k),
7393 "two_slot({a:?}, {b:?}).lacks_only({k:?}) drifted from (unique_missing_kind() == Some({k:?}))",
7394 );
7395 // Cardinality-refinement composition law under
7396 // complement.
7397 assert_eq!(
7398 via_lacks_only,
7399 !parent.has(k) && parent.has_unique_missing_kind(),
7400 "two_slot({a:?}, {b:?}).lacks_only({k:?}) drifted from (!has({k:?}) && has_unique_missing_kind())",
7401 );
7402 // Kind-scoped implication law under complement.
7403 if via_lacks_only {
7404 assert!(
7405 !parent.has(k),
7406 "two_slot({a:?}, {b:?}).lacks_only({k:?}) == true but has({k:?}) == true",
7407 );
7408 }
7409 }
7410 // Kind-domain exhaustivity on the multi-populated arm — at
7411 // most 1 kind is the sole missing kind. On `ALL.len() ==
7412 // 3` the count is exactly 1 (the third kind); on
7413 // `ALL.len() >= 4` the count is 0.
7414 let multi_count = <T::Kind as tatara_closed_set::ClosedSet>::ALL
7415 .iter()
7416 .copied()
7417 .filter(|k| parent.lacks_only(*k))
7418 .count();
7419 let expected_multi_count = usize::from(all_len == 3);
7420 assert_eq!(
7421 multi_count, expected_multi_count,
7422 "two_slot({a:?}, {b:?}): exactly {expected_multi_count} kinds must satisfy lacks_only on ALL.len() == {all_len}, got {multi_count}",
7423 );
7424 }
7425 }
7426}
7427
7428/// Generic closed-set-complement testkit on the kind-scoped SUBSET
7429/// axis — pins that [`TaggedUnion::lacks`] agrees with the negated
7430/// [`TaggedUnion::has`], the missing-set membership projection
7431/// [`TaggedUnion::missing_kinds`], the kind-scoped strict-refinement
7432/// peer [`TaggedUnion::lacks_only`], AND the missing-axis cardinality
7433/// scalar [`TaggedUnion::missing_kind_count`] across every
7434/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
7435/// arrangement, every off-diagonal two-slot pair, AND the empty-
7436/// parent baseline.
7437///
7438/// Closed-set-complement mirror of [`TaggedUnion::has`] under the
7439/// (populated, missing) duality — where `has(kind)` is the populated-
7440/// axis SUBSET primitive, `lacks(kind)` is the missing-axis SUBSET
7441/// primitive. Together with [`TaggedUnion::has_only`] (populated-axis
7442/// EQUAL) and [`TaggedUnion::lacks_only`] (missing-axis EQUAL) they
7443/// close the 2×2 kind-scoped (populated, missing) × (subset, equal)
7444/// grid. The five sub-assertions swept per arrangement + the empty-
7445/// parent baseline:
7446///
7447/// 1. **Definitional complement law**: `lacks(kind) == !has(kind)`
7448/// on every arm — the trait's default body composition is a
7449/// single bit-flip past [`TaggedUnion::has`], and no override
7450/// may drift the two primitives apart.
7451/// 2. **Missing-set membership composition law**:
7452/// `lacks(kind) == missing_kinds().contains(&kind)` on every
7453/// arm — closed-set-complement peer of the populated-axis law
7454/// `has(kind) == populated_kinds().contains(&kind)` swept by
7455/// [`assert_populated_kinds_matches_has`].
7456/// 3. **Kind-scoped implication law**: `lacks_only(kind) →
7457/// lacks(kind)` on every arm — if `kind` is the SOLE missing
7458/// slot then `kind` is missing. Byte-for-byte missing-axis peer
7459/// of the `has_only(kind) → has(kind)` implication that binds
7460/// [`TaggedUnion::has_only`] to [`TaggedUnion::has`] on the
7461/// strict-refinement axis.
7462/// 4. **Cardinality-partition law**: `<T::Kind as ClosedSet>::ALL
7463/// .iter().filter(|k| parent.lacks(*k)).count() ==
7464/// parent.missing_kind_count()` on every arm — the count of
7465/// kinds satisfying `lacks` equals the parent's missing-slot
7466/// count. Closed-set-complement peer of the populated-axis law
7467/// `count k where has(k) == populated_kind_count()`.
7468/// 5. **Factory-precondition truth table** whose expected shape is
7469/// derived from the abstract factory contract (`empty_parent()`
7470/// missing set is all of `ALL`, size `all_len`;
7471/// `single_slot(populated)` missing set is `ALL - {populated}`,
7472/// size `all_len - 1`; `two_slot(a, b)` missing set is `ALL -
7473/// {a, b}`, size `all_len - 2`) — hard-codes the arm expectation
7474/// across every `ALL.len()` regime so a factory drift that
7475/// yields a saturated / drifted parent surfaces BEFORE any
7476/// composition law reconciles two internally-drifted trait
7477/// bodies.
7478///
7479/// A fifth sibling tagged-union parent picks up the closed-set-
7480/// complement check on the kind-scoped SUBSET axis through ONE
7481/// `impl TaggedUnion for X` block plus ONE per-site `single_slot_X`
7482/// factory plus ONE per-site `two_slot_X` factory plus ONE per-site
7483/// `empty_X` factory plus ONE call site — no re-authored `lacks`
7484/// sweep at the test surface.
7485///
7486/// Same [`crate::lifetime::Lifetime`] exclusion as the sibling
7487/// primitives — the `T: TaggedUnion` bound doesn't reach it.
7488///
7489/// # Theory grounding
7490///
7491/// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
7492/// The kind-scoped closed-set-complement projection lives at ONE
7493/// substrate site as a definitional negation of
7494/// [`TaggedUnion::has`]. The five composition laws (definitional
7495/// complement, missing-set membership, kind-scoped implication
7496/// from `lacks_only`, cardinality partition against
7497/// `missing_kind_count`, factory-precondition truth table) live at
7498/// ONE substrate site inside the testkit's per-arm sweep — pinned
7499/// across every production tagged union at compile time via the
7500/// trait's default body composition, not per-parent.
7501/// - THEORY.md §VI.1 — generation over composition. A new
7502/// [`Self::Kind`] variant added to `ALL` reaches this primitive
7503/// mechanically through the delegated [`Self::has`] — the five
7504/// laws hold on the widened kind set without further per-caller
7505/// edit.
7506#[track_caller]
7507pub fn assert_lacks_matches_has_complement<T, F, G, H>(single_slot: F, two_slot: G, empty_parent: H)
7508where
7509 T: TaggedUnion,
7510 T::Kind: PartialEq + std::fmt::Debug,
7511 F: Fn(T::Kind) -> T,
7512 G: Fn(T::Kind, T::Kind) -> T,
7513 H: Fn() -> T,
7514{
7515 let all_len = <T::Kind as tatara_closed_set::ClosedSet>::ALL.len();
7516
7517 // Empty-parent baseline — every `lacks(k)` returns `true`
7518 // (empty parent has every slot missing). The factory-
7519 // precondition truth-table pin catches an `empty_parent` that
7520 // drifts from empty (a single-slot or saturated factory
7521 // masquerading as empty) BEFORE any composition law reconciles
7522 // two internally-drifted trait bodies.
7523 let empty = empty_parent();
7524 assert!(
7525 empty.is_empty(),
7526 "TaggedUnion::lacks() testkit: empty_parent() must satisfy is_empty() == true",
7527 );
7528 let empty_missing_count = empty.missing_kind_count();
7529 for k in <T::Kind as tatara_closed_set::ClosedSet>::ALL
7530 .iter()
7531 .copied()
7532 {
7533 let via_lacks = empty.lacks(k);
7534 // Factory-precondition truth table on the empty arm: the
7535 // missing set is all of `ALL`, so `lacks(k) == true` for
7536 // every `k`.
7537 assert!(
7538 via_lacks,
7539 "empty_parent().lacks({k:?}) must equal true (empty parent has every slot missing)",
7540 );
7541 // Definitional complement law on the empty arm.
7542 assert_eq!(
7543 via_lacks,
7544 !empty.has(k),
7545 "empty_parent().lacks({k:?}) drifted from !has({k:?})",
7546 );
7547 // Missing-set membership composition law on the empty arm.
7548 assert_eq!(
7549 via_lacks,
7550 empty.missing_kinds().contains(&k),
7551 "empty_parent().lacks({k:?}) drifted from missing_kinds().contains(&{k:?})",
7552 );
7553 // Kind-scoped implication law on the empty arm — lacks_only
7554 // implies lacks. On any `ALL.len() >= 2` closed set the
7555 // empty parent has ≥ 2 missing so lacks_only(k) == false on
7556 // every k, and the implication is vacuously true; on the
7557 // degenerate `ALL.len() == 1` regime lacks_only(k) == true
7558 // on the sole k, and the implication holds because lacks(k)
7559 // == true too.
7560 if empty.lacks_only(k) {
7561 assert!(
7562 via_lacks,
7563 "empty_parent().lacks_only({k:?}) == true but lacks({k:?}) == false",
7564 );
7565 }
7566 }
7567 // Cardinality-partition law on the empty arm — every kind
7568 // satisfies lacks, so the count equals missing_kind_count()
7569 // which equals ALL.len().
7570 let empty_count = <T::Kind as tatara_closed_set::ClosedSet>::ALL
7571 .iter()
7572 .copied()
7573 .filter(|k| empty.lacks(*k))
7574 .count();
7575 assert_eq!(
7576 empty_count, empty_missing_count,
7577 "empty_parent(): count of kinds satisfying lacks ({empty_count}) drifted from missing_kind_count() ({empty_missing_count})",
7578 );
7579 assert_eq!(
7580 empty_count, all_len,
7581 "empty_parent(): count of kinds satisfying lacks must equal ALL.len() ({all_len}), got {empty_count}",
7582 );
7583
7584 // Single-slot sweep — the composition-law shape across
7585 // `ClosedSet::ALL × ALL`, plus a factory-precondition truth-
7586 // table pin whose expected shape is derived from the abstract
7587 // factory contract (`single_slot(populated)` populates exactly
7588 // `populated` → the missing set is `ALL - {populated}`, so
7589 // `lacks(probed) == true` iff `probed != populated`).
7590 for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
7591 .iter()
7592 .copied()
7593 {
7594 let parent = single_slot(populated);
7595 let parent_missing_count = parent.missing_kind_count();
7596 for probed in <T::Kind as tatara_closed_set::ClosedSet>::ALL
7597 .iter()
7598 .copied()
7599 {
7600 let via_lacks = parent.lacks(probed);
7601 // Factory-precondition truth table on the well-formed
7602 // single-slot arm.
7603 let expected_single = probed != populated;
7604 assert_eq!(
7605 via_lacks, expected_single,
7606 "single_slot({populated:?}).lacks({probed:?}) must equal {expected_single}",
7607 );
7608 // Definitional complement law.
7609 assert_eq!(
7610 via_lacks,
7611 !parent.has(probed),
7612 "single_slot({populated:?}).lacks({probed:?}) drifted from !has({probed:?})",
7613 );
7614 // Missing-set membership composition law.
7615 assert_eq!(
7616 via_lacks,
7617 parent.missing_kinds().contains(&probed),
7618 "single_slot({populated:?}).lacks({probed:?}) drifted from missing_kinds().contains(&{probed:?})",
7619 );
7620 // Kind-scoped implication law — lacks_only implies
7621 // lacks.
7622 if parent.lacks_only(probed) {
7623 assert!(
7624 via_lacks,
7625 "single_slot({populated:?}).lacks_only({probed:?}) == true but lacks({probed:?}) == false",
7626 );
7627 }
7628 }
7629 // Cardinality-partition law on the well-formed arm — the
7630 // count of kinds satisfying lacks equals
7631 // missing_kind_count() which equals ALL.len() - 1.
7632 let well_formed_count = <T::Kind as tatara_closed_set::ClosedSet>::ALL
7633 .iter()
7634 .copied()
7635 .filter(|k| parent.lacks(*k))
7636 .count();
7637 assert_eq!(
7638 well_formed_count, parent_missing_count,
7639 "single_slot({populated:?}): count of kinds satisfying lacks ({well_formed_count}) drifted from missing_kind_count() ({parent_missing_count})",
7640 );
7641 let expected_single_missing = all_len - 1;
7642 assert_eq!(
7643 well_formed_count, expected_single_missing,
7644 "single_slot({populated:?}): count of kinds satisfying lacks must equal ALL.len() - 1 ({expected_single_missing}), got {well_formed_count}",
7645 );
7646 }
7647
7648 // Two-slot sweep — every off-diagonal pair populates two slots,
7649 // so the missing set is `ALL - {a, b}`, size `all_len - 2`, and
7650 // `lacks(k) == true` iff `k != a && k != b`. On `ALL.len() == 2`
7651 // `all_len - 2 == 0` (the two-slot arm saturates), so `lacks(k)
7652 // == false` on every k; the composition-law shape binds every
7653 // regime.
7654 for a in <T::Kind as tatara_closed_set::ClosedSet>::ALL
7655 .iter()
7656 .copied()
7657 {
7658 for b in <T::Kind as tatara_closed_set::ClosedSet>::ALL
7659 .iter()
7660 .copied()
7661 {
7662 if a == b {
7663 continue;
7664 }
7665 let parent = two_slot(a, b);
7666 let parent_missing_count = parent.missing_kind_count();
7667 for k in <T::Kind as tatara_closed_set::ClosedSet>::ALL
7668 .iter()
7669 .copied()
7670 {
7671 let via_lacks = parent.lacks(k);
7672 // Factory-precondition truth table on the two-slot
7673 // arm.
7674 let expected_two = k != a && k != b;
7675 assert_eq!(
7676 via_lacks, expected_two,
7677 "two_slot({a:?}, {b:?}).lacks({k:?}) must equal {expected_two}",
7678 );
7679 // Definitional complement law.
7680 assert_eq!(
7681 via_lacks,
7682 !parent.has(k),
7683 "two_slot({a:?}, {b:?}).lacks({k:?}) drifted from !has({k:?})",
7684 );
7685 // Missing-set membership composition law.
7686 assert_eq!(
7687 via_lacks,
7688 parent.missing_kinds().contains(&k),
7689 "two_slot({a:?}, {b:?}).lacks({k:?}) drifted from missing_kinds().contains(&{k:?})",
7690 );
7691 // Kind-scoped implication law.
7692 if parent.lacks_only(k) {
7693 assert!(
7694 via_lacks,
7695 "two_slot({a:?}, {b:?}).lacks_only({k:?}) == true but lacks({k:?}) == false",
7696 );
7697 }
7698 }
7699 // Cardinality-partition law on the two-slot arm.
7700 let multi_count = <T::Kind as tatara_closed_set::ClosedSet>::ALL
7701 .iter()
7702 .copied()
7703 .filter(|k| parent.lacks(*k))
7704 .count();
7705 assert_eq!(
7706 multi_count, parent_missing_count,
7707 "two_slot({a:?}, {b:?}): count of kinds satisfying lacks ({multi_count}) drifted from missing_kind_count() ({parent_missing_count})",
7708 );
7709 let expected_two_missing = all_len - 2;
7710 assert_eq!(
7711 multi_count, expected_two_missing,
7712 "two_slot({a:?}, {b:?}): count of kinds satisfying lacks must equal ALL.len() - 2 ({expected_two_missing}), got {multi_count}",
7713 );
7714 }
7715 }
7716}
7717
7718/// Generic ambiguity testkit — pins that [`TaggedUnion::variant`]
7719/// resolves to [`TaggedUnionError::ambiguous`] on EVERY off-diagonal
7720/// `(a, b)` pair in [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL)
7721/// `× ALL`.
7722///
7723/// Substrate primitive for the sibling
7724/// `_two_slots_is_ambiguous_across_every_pair` tests on `ProcessSpec`
7725/// ([`crate::encapsulates::EncapsulationKind`],
7726/// [`crate::export::ArtifactSource`], [`crate::export::VectorChannel`])
7727/// that pre-lift each restated the same nested-`for a in K::ALL { for
7728/// b in K::ALL { if a == b { continue; } … } }` sweep at their own
7729/// test bodies — byte-identical projections whose only per-carrier
7730/// knobs are the (Kind type + the `two_slot_X(a, b) -> Parent`
7731/// two-slot factory) pair. Post-lift each site collapses to ONE
7732/// `assert_two_slots_ambiguous::<Xxx, _>(two_slot_X)` invocation.
7733///
7734/// The `two_slot` closure stays per-site — every one of the three
7735/// production sites already owns a `two_slot_kind /
7736/// two_slot_source / two_slot_channel` helper that composes two
7737/// `single_slot_X`s per-field. The closure IS the "populate both
7738/// slots a and b" ground truth for the carrier's field structure;
7739/// lifting it into the primitive would collapse per-site field-
7740/// composition knowledge that stays deliberately local.
7741///
7742/// The pair sweep excludes the diagonal (`a == b`) — a single slot
7743/// populated is exactly-one, not many, and the round-trip primitive
7744/// [`assert_variant_round_trip`] already pins that populated slot's
7745/// resolution. This primitive is the peer contract for the Many arm.
7746///
7747/// A fifth sibling tagged-union parent picks up the ambiguity check
7748/// through ONE `impl TaggedUnion for X` block + ONE per-site
7749/// `two_slot_X` helper + ONE `assert_two_slots_ambiguous::<X, _>`
7750/// call site — no re-authored nested-for sweep at the test surface,
7751/// no re-authored `assert_eq!(..., X::Error::Ambiguous, ...)` arm.
7752///
7753/// The [`crate::lifetime::Lifetime`] site is DELIBERATELY excluded
7754/// — `Lifetime` doesn't impl [`TaggedUnion`] (its error carrier has
7755/// no `Empty` arm; its `variant()` returns `Ok(Permanent)` on empty
7756/// rather than an `Empty` typed error), so the `<T: TaggedUnion>`
7757/// bound doesn't reach it. Its per-site ambiguity assertion binds
7758/// through the inherent `.variant()` + hand-authored two-slot
7759/// probe. Same reasoning as [`resolve_or_err`]'s and
7760/// [`assert_variant_round_trip`]'s exclusions.
7761#[track_caller]
7762pub fn assert_two_slots_ambiguous<T, F>(two_slot: F)
7763where
7764 T: TaggedUnion,
7765 T::Kind: PartialEq + std::fmt::Debug,
7766 T::Error: PartialEq + std::fmt::Debug,
7767 F: Fn(T::Kind, T::Kind) -> T,
7768{
7769 let expected = T::Error::ambiguous();
7770 for a in <T::Kind as tatara_closed_set::ClosedSet>::ALL
7771 .iter()
7772 .copied()
7773 {
7774 for b in <T::Kind as tatara_closed_set::ClosedSet>::ALL
7775 .iter()
7776 .copied()
7777 {
7778 if a == b {
7779 continue;
7780 }
7781 let parent = two_slot(a, b);
7782 let err = parent.variant().err().unwrap_or_else(|| {
7783 panic!("({a:?}, {b:?}) two-slot parent must not resolve to a variant")
7784 });
7785 assert_eq!(err, expected, "({a:?}, {b:?}) should resolve Ambiguous");
7786 }
7787 }
7788}
7789
7790/// Generic wire-key / kind-label alignment testkit — pins that every
7791/// single-slot parent serializes to a JSON object with EXACTLY ONE key
7792/// whose name equals `<T::Kind as tatara_closed_set::ClosedSet>::label`
7793/// on the populated slot's kind.
7794///
7795/// Substrate primitive for the four sibling
7796/// `X_kind_as_str_matches_field_name` / `intent_kind_as_str_matches_intent_field_name`
7797/// tests on `ProcessSpec` ([`crate::intent::Intent`],
7798/// [`crate::encapsulates::EncapsulationKind`],
7799/// [`crate::export::ArtifactSource`], [`crate::export::VectorChannel`])
7800/// that pre-lift each restated the same wire-format sweep at their own
7801/// test bodies:
7802///
7803/// 1. For each `k in K::ALL`, construct a single-slot parent via
7804/// the site-local `single_slot_X(k) -> Parent` factory.
7805/// 2. Serialize it to the wire format and assert that the emitted
7806/// key matches `k.as_str()`.
7807///
7808/// Post-lift each site's alignment test collapses to ONE
7809/// `assert_single_slot_key_matches_label::<T, _>(single_slot_X)`
7810/// invocation whose body IS the substrate primitive's own dispatch.
7811/// A fifth sibling picks up the alignment check through ONE call site.
7812///
7813/// The primitive projects through `serde_json::to_value` rather than
7814/// `serde_yaml::to_string` for two reasons: (1) the check is
7815/// structural (exactly-one-key + name equality), not textual (substring
7816/// against a `"{key}:"` YAML fragment), so a future site that gains
7817/// non-tagged-union metadata fields is caught HERE at the exactly-one
7818/// arm — the YAML-substring check the three encapsulates / export sites
7819/// carried pre-lift would silently pass on such drift. (2) serde's
7820/// field-rename projection (`rename_all = "camelCase"`) is format-
7821/// agnostic, so a JSON check pins the SAME invariant a YAML check
7822/// would pin, byte-identically. Every one of the four production
7823/// parents already emits exactly one key on a single-slot populate —
7824/// their `#[serde(default, skip_serializing_if = "Option::is_none")]`
7825/// annotations on every tagged-union slot guarantee it — so upgrading
7826/// the three YAML sites to the JSON exactly-one check is a strict
7827/// strengthening.
7828///
7829/// The `single_slot` closure stays per-site — every one of the four
7830/// production sites already owns a `single_slot_intent /
7831/// single_slot_kind / single_slot_source / single_slot_channel` helper
7832/// that constructs a minimally-valid parent with the addressed slot's
7833/// inner spec populated; the closure IS the "populate slot k" ground
7834/// truth for the carrier's field structure. Reused verbatim from the
7835/// [`assert_variant_round_trip`] primitive.
7836///
7837/// The [`crate::lifetime::Lifetime`] site is DELIBERATELY excluded
7838/// from THIS trait-projected surface — `Lifetime` doesn't impl
7839/// [`TaggedUnion`] (its `variant()` returns `Ok(Permanent)` on empty
7840/// rather than an `Empty` typed error), so the `<T: TaggedUnion>`
7841/// bound doesn't reach it. The bound-relaxed peer
7842/// [`assert_wire_key_matches_label`] carries the SAME sweep body
7843/// under `<T: Serialize>` + `<K: ClosedSet>` alone — Lifetime binds
7844/// through it directly and this trait-projected surface becomes a
7845/// one-line delegation whose only load-bearing purpose is to name
7846/// the TaggedUnion parent's `T::Kind` associated type at the call
7847/// site (existing `assert_single_slot_key_matches_label::<T, _>(f)`
7848/// callers stay unchanged; the peer inflects the same body onto
7849/// non-TaggedUnion parents).
7850#[track_caller]
7851pub fn assert_single_slot_key_matches_label<T, F>(single_slot: F)
7852where
7853 T: TaggedUnion + serde::Serialize,
7854 T::Kind: PartialEq + std::fmt::Debug,
7855 F: Fn(T::Kind) -> T,
7856{
7857 assert_wire_key_matches_label::<T, T::Kind, F>(single_slot);
7858}
7859
7860/// Bound-relaxed peer of [`assert_single_slot_key_matches_label`] —
7861/// the SAME wire-key alignment sweep, but on any `(K, T)` pair where
7862/// `K: ClosedSet` addresses `T: Serialize` through a caller-supplied
7863/// `single_slot: Fn(K) -> T` factory. Drops the `T: TaggedUnion`
7864/// bound the sibling primitive carries so parents whose empty
7865/// resolution shape diverges from the tagged-union convention (the
7866/// canonical example: [`crate::lifetime::Lifetime`], whose empty
7867/// resolves to `Permanent(&DEFAULT_PERMANENT)` rather than to an
7868/// [`TaggedUnionError::empty`] carrier) still bind through ONE
7869/// substrate wire-key alignment site.
7870///
7871/// The two primitives share ONE sweep body; the trait-projected
7872/// [`assert_single_slot_key_matches_label`] is now a one-line
7873/// delegation to this bound-relaxed peer, so every drift-arm the
7874/// sibling `#[should_panic]` probe pins on the delegating surface
7875/// mechanically pins here too. The compounding gain: a fifth parent
7876/// whose closed-set kind K doesn't ride the TaggedUnion trait (a
7877/// future variant surface with a default-arm on empty; a wire-only
7878/// enum whose parent is a wrapper struct that never publishes a
7879/// resolver; a K-addressed `HashMap<K, Payload>` where the payload
7880/// isn't a tagged-union variant carrier at all) picks up wire-key
7881/// alignment through ONE call site — no re-authored serialize +
7882/// exactly-one-key + name-equality body at the test surface, no
7883/// per-parent drift risk where the trait-projected surface catches
7884/// it and the bespoke surface forgets.
7885///
7886/// The primitive binds `<K: ClosedSet + PartialEq + Debug>` (the
7887/// strict union of the sweep body's projection + the panic-message
7888/// substrate-wide shape) — every production `ClosedSet` implementor
7889/// across the crate carries `Debug + PartialEq` through the
7890/// substrate-wide `#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash,
7891/// DeriveClosedSet)]` shape, so no site pays a bound-widening cost
7892/// to bind through this peer.
7893#[track_caller]
7894pub fn assert_wire_key_matches_label<T, K, F>(single_slot: F)
7895where
7896 T: serde::Serialize,
7897 K: tatara_closed_set::ClosedSet + PartialEq + std::fmt::Debug,
7898 F: Fn(K) -> T,
7899{
7900 for k in <K as tatara_closed_set::ClosedSet>::ALL.iter().copied() {
7901 let parent = single_slot(k);
7902 let value = serde_json::to_value(&parent)
7903 .unwrap_or_else(|e| panic!("single_slot({k:?}) must serialize as JSON: {e}"));
7904 let obj = value.as_object().unwrap_or_else(|| {
7905 panic!("single_slot({k:?}) must serialize to a JSON object, got {value}")
7906 });
7907 let keys: Vec<&String> = obj.keys().collect();
7908 assert_eq!(
7909 keys.len(),
7910 1,
7911 "single_slot({k:?}) must serialize to exactly one populated field, got keys: {keys:?}",
7912 );
7913 let expected = <K as tatara_closed_set::ClosedSet>::label(k);
7914 assert_eq!(
7915 keys[0].as_str(),
7916 expected,
7917 "wire-key drift for {k:?}: single_slot's populated field '{}' must equal <K as ClosedSet>::label ({expected:?})",
7918 keys[0],
7919 );
7920 }
7921}
7922
7923/// Generic Display / [`ClosedSet::label`](tatara_closed_set::ClosedSet::label)
7924/// alignment testkit — pins that [`core::fmt::Display`] renders each variant
7925/// BYTE-IDENTICALLY to the trait-visible `ClosedSet::label` projection for
7926/// every implementor.
7927///
7928/// Substrate primitive for the 29 sibling
7929/// `X_display_matches_as_str` tests across `tatara-process`
7930/// (`AllocationPhase`, `IntentKind`, `WorkloadKind`, `EncapsulationMode`,
7931/// `EncapsulationTarget`, `ConditionKind`, `TerminateReasonKind`,
7932/// `AutoTerminateKind`, `SighupStrategy`, `ReplacementPolicy`,
7933/// `ReturnPolicy`, `MemberState`, `PoolPhase`, `VerificationPhase`,
7934/// `SelectStrategyKind`, `MustReachPhase`, `ExportTrigger`,
7935/// `ReportFormat`, `ReportPayloadShape`, `ArtifactKind`, `ChannelKind`,
7936/// `DataClassification`, `ConvergencePointType`, `Arity`,
7937/// `SubstrateType`, `CalmClassification`, `OptimizationDirection`,
7938/// `HorizonKind`, `TeardownPolicy`) that pre-lift each restated the
7939/// same
7940/// ```text
7941/// for v in K::ALL {
7942/// assert_eq!(v.to_string(), v.as_str());
7943/// }
7944/// ```
7945/// two-line probe verbatim at their own test bodies — byte-identical
7946/// projections whose only per-carrier knob is the closed-set type name.
7947/// Post-lift each site collapses to ONE
7948/// `assert_display_matches_label::<X>()` invocation whose body IS the
7949/// substrate primitive's own dispatch.
7950///
7951/// The primitive projects through the STABLE trait-visible name
7952/// [`ClosedSet::label`](tatara_closed_set::ClosedSet::label) rather
7953/// than the inherent `.as_str()` each site publishes locally. Every
7954/// production implementor here derives its `label` body from `as_str`
7955/// via `#[closed_set(via = "as_str", display)]` (the substrate-wide
7956/// derive shape), so the two are byte-identical by construction; the
7957/// primitive's projection through `label` therefore pins the SAME
7958/// invariant the pre-lift bodies pinned while binding to the
7959/// stable trait-visible surface. A future implementor whose inherent
7960/// canonical projection is named something other than `as_str` (e.g.
7961/// `.keyword()`, `.spelling()`) but still routes through
7962/// `#[closed_set(via = "...", display)]` picks up the alignment check
7963/// through ONE `assert_display_matches_label::<X>()` invocation with
7964/// no inherent-name coupling at the test site.
7965///
7966/// A fifth (or thirtieth, or hundredth) implementor picks up the
7967/// Display-alignment check through ONE
7968/// `#[derive(tatara_closed_set::DeriveClosedSet)]` + `display`
7969/// attribute + ONE `assert_display_matches_label::<X>()` call site —
7970/// no re-authored two-line
7971/// `for v in K::ALL { assert_eq!(v.to_string(), v.as_str()) }` body
7972/// at the test surface, no per-site drift risk where 28 sibling
7973/// tests carry the assertion and the 29th forgets.
7974///
7975/// Sibling shape to [`assert_kind_list_matches_closed_set`] on the
7976/// (`T::KIND_LIST` slash-join, `Display` byte-identity) axis: both
7977/// project the closed-set's label surface onto ONE typed contract
7978/// and pin it against a per-implementor rendering; the former for
7979/// the tagged-union parent's [`TaggedUnion::KIND_LIST`] `&'static str`,
7980/// this one for the enum's `Display` byte stream. Together they close
7981/// the "label surface must round-trip verbatim" invariant every
7982/// closed-set-carrying implementor across the crate publishes.
7983#[track_caller]
7984pub fn assert_display_matches_label<T>()
7985where
7986 T: tatara_closed_set::ClosedSet + core::fmt::Display + PartialEq + core::fmt::Debug,
7987{
7988 let type_name = core::any::type_name::<T>();
7989 for &v in <T as tatara_closed_set::ClosedSet>::ALL {
7990 let rendered = v.to_string();
7991 let expected = <T as tatara_closed_set::ClosedSet>::label(v);
7992 assert_eq!(
7993 rendered.as_str(),
7994 expected,
7995 "{type_name}: Display drifted from ClosedSet::label for {v:?} — expected {expected:?}, got {rendered:?}",
7996 );
7997 }
7998}
7999
8000/// CANONICAL-KEY CONTRACT testkit — pins that each variant's serde
8001/// serialization (as a JSON string value, unquoted) matches its
8002/// canonical [`ClosedSet::label`](tatara_closed_set::ClosedSet::label)
8003/// projection BYTE-IDENTICALLY for every implementor.
8004///
8005/// Substrate primitive for the 20 sibling
8006/// `X_as_str_matches_serde` tests across `tatara-process`
8007/// (`TeardownPolicy`, `EncapsulationMode`, `ConditionKind`,
8008/// `SighupStrategy`, `ReplacementPolicy`, `ReturnPolicy`, `MemberState`,
8009/// `PoolPhase`, `VerificationPhase`, `MustReachPhase`, `WorkloadKind`,
8010/// `ExportTrigger`, `ReportFormat`, `DataClassification`,
8011/// `ConvergencePointType`, `SubstrateType`, `CalmClassification`,
8012/// `OptimizationDirection`, `HorizonKind`, `AllocationPhase`) that
8013/// pre-lift each restated the same
8014/// ```text
8015/// for v in K::ALL {
8016/// let serialized = serde_json::to_string(&v).expect("serialize");
8017/// let unquoted = serialized
8018/// .trim_start_matches('"')
8019/// .trim_end_matches('"')
8020/// .to_string();
8021/// assert_eq!(unquoted, v.as_str(), "as_str drift for {v:?}: ...");
8022/// }
8023/// ```
8024/// four-line probe verbatim at their own test bodies — byte-identical
8025/// projections whose only per-carrier knob is the closed-set type name.
8026/// Post-lift each site collapses to ONE
8027/// `assert_label_matches_serde_serialization::<X>()` invocation whose
8028/// body IS the substrate primitive's own dispatch.
8029///
8030/// The primitive projects through the STABLE trait-visible name
8031/// [`ClosedSet::label`](tatara_closed_set::ClosedSet::label) rather
8032/// than the inherent `.as_str()` each site publishes locally. Every
8033/// production implementor here derives its `label` body from `as_str`
8034/// via `#[closed_set(via = "as_str", display)]` + `#[serde(rename_all
8035/// = "PascalCase")]` (the substrate-wide derive shape), so the two are
8036/// byte-identical by construction; the primitive's projection through
8037/// `label` therefore pins the SAME invariant the pre-lift bodies
8038/// pinned while binding to the stable trait-visible surface. A future
8039/// implementor whose canonical inherent projection is named something
8040/// other than `as_str` (e.g. `.keyword()`, `.spelling()`) but still
8041/// routes through `#[closed_set(via = "...")]` picks up the wire-format
8042/// alignment check through ONE call with no inherent-name coupling at
8043/// the test site.
8044///
8045/// A twenty-first (or hundredth) implementor picks up the alignment
8046/// check through ONE `#[derive(tatara_closed_set::DeriveClosedSet)]` +
8047/// `#[derive(serde::Serialize)]` + `#[serde(rename_all = "...")]`
8048/// attribute + ONE `assert_label_matches_serde_serialization::<X>()`
8049/// call site — no re-authored four-line probe body at the test surface,
8050/// no per-site drift risk where 19 sibling tests carry the assertion
8051/// and the 20th forgets, no `serde_json::to_string`+`trim_matches`+
8052/// `assert_eq!` composition re-derived per implementor.
8053///
8054/// Sibling shape to [`assert_display_matches_label`] on the
8055/// (Display byte-identity, serde-wire-format byte-identity) axis: both
8056/// project the closed-set's label surface onto ONE typed contract and
8057/// pin it against a per-implementor rendering; the former for the
8058/// enum's [`Display`](core::fmt::Display) byte stream, this one for
8059/// the serde JSON-string wire format. Together they close the "label
8060/// surface renders verbatim across every projection consumers reach
8061/// for" invariant every closed-set-carrying implementor across the
8062/// crate publishes.
8063#[track_caller]
8064pub fn assert_label_matches_serde_serialization<T>()
8065where
8066 T: tatara_closed_set::ClosedSet + serde::Serialize + core::fmt::Debug,
8067{
8068 let type_name = core::any::type_name::<T>();
8069 for &v in <T as tatara_closed_set::ClosedSet>::ALL {
8070 let serialized = serde_json::to_string(&v).unwrap_or_else(|e| {
8071 panic!("{type_name}: closed-set variant {v:?} must serialize: {e}")
8072 });
8073 let unquoted = serialized.trim_start_matches('"').trim_end_matches('"');
8074 let expected = <T as tatara_closed_set::ClosedSet>::label(v);
8075 assert_eq!(
8076 unquoted,
8077 expected,
8078 "{type_name}: serde output drifted from ClosedSet::label for {v:?} — expected {expected:?}, got {unquoted:?} (full serialization {serialized:?})",
8079 );
8080 }
8081}
8082
8083/// CLOSED-SET CONVENTION PANEL testkit — pins the FULL three-axis
8084/// label-surface convention (parse round-trip, Display byte-identity,
8085/// serde-JSON-string byte-identity) at ONE substrate call site per
8086/// implementor.
8087///
8088/// Compound-lift of [`tatara_closed_set::assert_closed_set_well_formed`]
8089/// + [`assert_display_matches_label`] + [`assert_label_matches_serde_
8090/// serialization`] — every closed-set enum on `ProcessSpec` that
8091/// carries the substrate-wide `#[derive(DeriveClosedSet)] +
8092/// #[derive(Serialize)] + #[closed_set(via = "as_str", display)] +
8093/// #[serde(rename_all = "PascalCase")]` shape publishes ALL THREE
8094/// axes of the label surface, and pre-lift each production test
8095/// module hand-authored three sibling one-line tests
8096/// (`X_is_well_formed_closed_set`, `X_display_matches_as_str`,
8097/// `X_as_str_matches_serde`) that each restated the SAME
8098/// `crate::tagged_union::assert_<axis>::<X>()` invocation with only
8099/// the axis name varying between siblings. Post-lift each site
8100/// collapses to ONE `assert_closed_set_convention_panel::<X>()`
8101/// invocation whose body IS the three-axis composition dispatched
8102/// through the substrate primitive here.
8103///
8104/// The three sub-assertions stay independently callable — a future
8105/// implementor that publishes only two of the three axes (a
8106/// `Display`-less internal enum, e.g., or a `Serialize`-less
8107/// runtime-only enum) still binds through the two sibling primitives
8108/// individually. The compound is a strict superset: any implementor
8109/// that satisfies the compound's bounds already satisfies each
8110/// sub-assertion's bounds by construction, and the failure mode of
8111/// each sub-assertion still surfaces with the exact-message
8112/// granularity `#[track_caller]` gives the individual primitives
8113/// (the compound is `#[track_caller]` too, so a sub-assertion panic
8114/// surfaces at the compound's call site — a future promotion could
8115/// wrap each sub-assertion in a `std::panic::catch_unwind` to
8116/// aggregate all three axis failures into ONE panic message, but the
8117/// pre-lift discipline is that each axis's failure surfaces with its
8118/// own diagnostic).
8119///
8120/// The compound's bounds are the strict union of the three sub-
8121/// assertions' bounds:
8122/// - [`assert_closed_set_well_formed`] requires
8123/// `T: ClosedSet + PartialEq + Debug` + `T::Unknown: Display`;
8124/// - [`assert_display_matches_label`] requires
8125/// `T: ClosedSet + Display + PartialEq + Debug`;
8126/// - [`assert_label_matches_serde_serialization`] requires
8127/// `T: ClosedSet + Serialize + Debug`.
8128/// The union `T: ClosedSet + Serialize + Display + PartialEq + Debug`
8129/// + `T::Unknown: Display` is what every 3-axis production consumer
8130/// already satisfies through the substrate-wide derive shape — any
8131/// implementor that fails the compound's bounds would ALSO fail the
8132/// individual sub-assertions' bounds, so the compound doesn't shrink
8133/// the reachable set of implementors relative to hand-authoring the
8134/// three sibling calls.
8135///
8136/// A future FOURTH label-surface projection (e.g. a `serde_yaml`
8137/// byte-identity axis if the crate gains a YAML wire form on closed-
8138/// set enums, or a `kubectl_annotation` axis if the reconciler grows
8139/// an annotation-carried label surface) lands as ONE new
8140/// `assert_<axis>_matches_label::<T>()` substrate primitive + ONE
8141/// new line inside this compound's body. Every one of the ~20
8142/// production implementors of the panel picks up the fourth-axis
8143/// alignment check mechanically at their sole `assert_closed_set_
8144/// convention_panel::<X>()` call site — no per-implementor test-site
8145/// authoring, no per-crate test-site drop pathway where 19 sibling
8146/// call sites carry the check and the 20th forgets. The exact
8147/// promise `e4a4eba`'s future gain #2 named after
8148/// `assert_label_matches_serde_serialization` opened the wire-format
8149/// axis: a workspace-wide panel with byte-identical calling shapes
8150/// (`assert_X::<T>()`) that composes as freely as its sub-primitives.
8151///
8152/// Sibling shape to [`assert_variant_round_trip`] +
8153/// [`assert_kind_list_matches_closed_set`] +
8154/// [`assert_two_slots_ambiguous`] +
8155/// [`assert_single_slot_key_matches_label`] on the tagged-union
8156/// PARENT axis: the parent-side compound would compose the four
8157/// parent-side per-axis primitives, this one composes the three
8158/// child-side per-axis primitives on the child's [`ClosedSet`]
8159/// surface. Together the two compounds close the "closed-set
8160/// convention holds across every projection consumers reach for" at
8161/// two adjacent panels — one per closed-set-carrying enum, one per
8162/// tagged-union parent.
8163///
8164/// Theory anchor: THEORY.md §V.1 (knowable platform) — the
8165/// three-axis label-surface convention becomes ONE typed theorem
8166/// provable generically over any
8167/// `T: ClosedSet + Serialize + Display + PartialEq + Debug` bound
8168/// rather than THREE hand-authored per-implementor one-line probes
8169/// held coherent by test-module convention. THEORY.md §II.1
8170/// invariant 5 (composition preserves proofs) — the three sub-
8171/// assertions compose structurally through ONE primitive here, so a
8172/// regression at ONE axis surfaces at the sub-assertion's own
8173/// panic message rather than as silent drift at every consumer that
8174/// might otherwise forget to include the axis in its per-site
8175/// author-time enumeration.
8176#[track_caller]
8177pub fn assert_closed_set_convention_panel<T>()
8178where
8179 T: tatara_closed_set::ClosedSet
8180 + serde::Serialize
8181 + core::fmt::Display
8182 + PartialEq
8183 + core::fmt::Debug,
8184 T::Unknown: core::fmt::Display,
8185{
8186 tatara_closed_set::assert_closed_set_well_formed::<T>();
8187 assert_display_matches_label::<T>();
8188 assert_label_matches_serde_serialization::<T>();
8189}
8190
8191/// TAGGED-UNION CONVENTION PANEL testkit — pins the FULL four-axis
8192/// tagged-union parent convention (KIND_LIST diagnostic-stability,
8193/// variant round-trip on the single-slot side, ALL×ALL two-slot
8194/// ambiguity, wire-key alignment on the single-slot side) at ONE
8195/// substrate call site per parent.
8196///
8197/// Parent-side compound-lift, sibling to
8198/// [`assert_closed_set_convention_panel`] on the child's
8199/// [`tatara_closed_set::ClosedSet`] axis. Composes
8200/// [`assert_kind_list_matches_closed_set`] (no fixture) +
8201/// [`assert_variant_round_trip`] (`single_slot`) +
8202/// [`assert_two_slots_ambiguous`] (`two_slot`) +
8203/// [`assert_single_slot_key_matches_label`] (`single_slot`).
8204///
8205/// Every one of the four production `.variant()` parents on
8206/// `ProcessSpec` ([`crate::intent::Intent`],
8207/// [`crate::encapsulates::EncapsulationKind`],
8208/// [`crate::export::ArtifactSource`],
8209/// [`crate::export::VectorChannel`]) publishes the four-axis
8210/// convention through the shared substrate-wide attribute-set:
8211/// `#[derive(DeriveClosedSet)]` on the addressing `Kind`,
8212/// `declare_tagged_union_impls!` for the resolver+selector+trait
8213/// triple, `#[serde(rename_all = "camelCase")]` +
8214/// `#[serde(default, skip_serializing_if = "Option::is_none")]` on
8215/// every tagged-union slot. Pre-lift each production site
8216/// hand-authored FOUR sibling per-axis tests (`X_kind_round_trips_through_variant_kind`
8217/// / `X_kind_list_matches_ClosedSet_labels` /
8218/// `X_two_slots_are_ambiguous` /
8219/// `X_kind_as_str_matches_field_name`) that each restated the
8220/// SAME `crate::tagged_union::assert_<axis>::<T, _>(fixture)`
8221/// invocation with only the axis name + fixture arity varying
8222/// between siblings. Post-lift each site's four per-axis sibling
8223/// tests can collapse to ONE
8224/// `assert_tagged_union_convention_panel::<T, _, _>(
8225/// single_slot_X, two_slot_X)` invocation whose body IS the
8226/// four-axis composition dispatched through the substrate
8227/// primitive here.
8228///
8229/// The two closures stay per-site — every one of the four
8230/// production parents already owns a `single_slot_X(k) -> Parent`
8231/// / `two_slot_X(a, b) -> Parent` pair, and the substrate-local
8232/// `{single,two}_slot_*_probe` peers (siblings to the wire-key
8233/// sweep's substrate-local probes) let the substrate-wide sweep
8234/// below bind through the compound without reaching across the
8235/// per-crate test-module boundaries. Lifting the two closures
8236/// into the primitive would collapse the per-site construction
8237/// knowledge that stays deliberately local — the closure IS the
8238/// "populate slot k" / "populate the (a, b) pair" ground truth
8239/// for the parent's field structure.
8240///
8241/// Bounds are the strict union of the four sub-assertions' bounds:
8242/// [`assert_kind_list_matches_closed_set`] requires
8243/// `T: TaggedUnion`; [`assert_variant_round_trip`] requires
8244/// `T: TaggedUnion` + `T::Kind: PartialEq + Debug`
8245/// + `F: Fn(T::Kind) -> T`; [`assert_two_slots_ambiguous`] requires
8246/// `T: TaggedUnion` + `T::Kind: PartialEq + Debug`
8247/// + `T::Error: PartialEq + Debug` + `F: Fn(T::Kind, T::Kind) -> T`;
8248/// [`assert_single_slot_key_matches_label`] requires
8249/// `T: TaggedUnion + Serialize` + `T::Kind: PartialEq + Debug`
8250/// + `F: Fn(T::Kind) -> T`. The union
8251/// `T: TaggedUnion + Serialize` + `T::Kind: PartialEq + Debug`
8252/// + `T::Error: PartialEq + Debug` + `F1: Fn(T::Kind) -> T`
8253/// + `F2: Fn(T::Kind, T::Kind) -> T` is what every one of the four
8254/// production parents already satisfies through the shared
8255/// substrate-wide impls — any implementor that fails the compound's
8256/// bounds would ALSO fail the individual sub-assertions' bounds,
8257/// so the compound doesn't shrink the reachable set of
8258/// implementors relative to hand-authoring the four sibling calls.
8259/// The `single_slot` closure is dispatched to
8260/// [`assert_variant_round_trip`] by reference so the compound can
8261/// re-dispatch it to [`assert_single_slot_key_matches_label`] by
8262/// value on the final call — a caller passes ONE `Fn(T::Kind) -> T`
8263/// factory (not `FnOnce`) at the two axes that need it.
8264///
8265/// `#[track_caller]` on both the compound and each sub-primitive,
8266/// so a sub-assertion panic surfaces at the compound's caller site
8267/// with the failing axis's exact panic-message substring
8268/// (e.g. "TaggedUnion KIND_LIST drift", "select→variant_kind
8269/// round-trip failed", "should resolve Ambiguous", "wire-key
8270/// drift"). The four sub-assertions stay independently callable —
8271/// a future parent that publishes only three of the four axes (a
8272/// wire-format-less runtime parent, e.g., or an
8273/// ambiguity-less parent whose `.variant()` short-circuits on
8274/// the first populated slot) still binds through the sibling
8275/// primitives individually.
8276///
8277/// A future FIFTH parent-side projection (e.g. a
8278/// `two_slots_have_stable_diagnostic` axis if the ambiguity error
8279/// gains a per-parent operator-facing message, or a
8280/// `variant_kind_stays_stable_across_generation` axis if the
8281/// resolver's iteration order becomes load-bearing) lands as ONE
8282/// new `assert_<axis>::<T, _>(...)` substrate primitive + ONE new
8283/// line inside this compound's body. Every one of the four
8284/// production parents picks up the fifth-axis alignment check
8285/// mechanically at their sole
8286/// `assert_tagged_union_convention_panel::<T, _, _>(single_slot,
8287/// two_slot)` call site — no per-parent test-site authoring, no
8288/// per-crate test-site drop pathway where 3 sibling call sites
8289/// carry the check and the 4th forgets. The exact promise the
8290/// child-side [`assert_closed_set_convention_panel`] compound's
8291/// docstring named on the child axis, extended here to the parent
8292/// axis: a workspace-wide panel with byte-identical calling shapes
8293/// (`assert_<compound>::<T, _, _>(single_slot, two_slot)`) that
8294/// composes as freely as its sub-primitives.
8295///
8296/// The [`crate::lifetime::Lifetime`] site is DELIBERATELY excluded
8297/// through the `T: TaggedUnion` bound — `Lifetime`'s `variant()`
8298/// returns `Ok(Permanent)` on empty rather than an `Empty` typed
8299/// error, so its projection shape diverges from the four
8300/// Empty-projecting parents. Same reasoning as [`resolve_or_err`]'s
8301/// / [`assert_variant_round_trip`]'s / [`assert_two_slots_ambiguous`]'s
8302/// / [`assert_single_slot_key_matches_label`]'s exclusions.
8303///
8304/// Theory anchor: THEORY.md §V.1 (knowable platform) — the
8305/// four-axis parent-side tagged-union convention becomes ONE typed
8306/// theorem provable generically over any
8307/// `T: TaggedUnion + Serialize` bound rather than FOUR
8308/// hand-authored per-parent tests held coherent by test-module
8309/// convention. THEORY.md §II.1 invariant 5 (composition preserves
8310/// proofs) — the four sub-assertions compose structurally through
8311/// ONE primitive here, so a regression at ONE axis surfaces at the
8312/// sub-assertion's own panic message rather than as silent drift
8313/// at every parent that might otherwise forget to include the
8314/// axis in its per-site author-time enumeration.
8315#[track_caller]
8316pub fn assert_tagged_union_convention_panel<T, F1, F2>(single_slot: F1, two_slot: F2)
8317where
8318 T: TaggedUnion + serde::Serialize,
8319 T::Kind: PartialEq + std::fmt::Debug,
8320 T::Error: PartialEq + std::fmt::Debug,
8321 F1: Fn(T::Kind) -> T,
8322 F2: Fn(T::Kind, T::Kind) -> T,
8323{
8324 assert_kind_list_matches_closed_set::<T>();
8325 assert_variant_round_trip::<T, _>(&single_slot);
8326 assert_two_slots_ambiguous::<T, _>(two_slot);
8327 assert_has_matches_select::<T, _>(&single_slot);
8328 assert_find_agrees_with_has::<T, _>(&single_slot);
8329 assert_iter_populated_kinds_matches_populated_kinds::<T, _>(&single_slot);
8330 assert_iter_missing_kinds_matches_missing_kinds::<T, _>(&single_slot);
8331 assert_scalar_peers_fold_through_iter_kinds::<T, _>(&single_slot);
8332 assert_single_slot_key_matches_label::<T, _>(single_slot);
8333}
8334
8335/// Generic scalar-peers-fold-through-iter-kinds testkit — pins that
8336/// every scalar closed-set peer on [`TaggedUnion`] equals its
8337/// standard-library `Iterator` fold over the load-bearing iterator
8338/// peer [`TaggedUnion::iter_populated_kinds`] (populated side) or
8339/// [`TaggedUnion::iter_missing_kinds`] (missing side), on every
8340/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
8341/// arrangement.
8342///
8343/// The load-bearing iterator peer is the ONE substrate site every
8344/// scalar peer folds through — a regression that overrides ANY
8345/// scalar peer with a divergent walk (short-circuit skipping a kind,
8346/// forgetting the negation on the complement side, drifting from
8347/// `ClosedSet::ALL` order, ignoring the load-bearing iterator entirely
8348/// with a duplicate closed-set walk of its own) surfaces at this ONE
8349/// testkit rather than as silent skew between the scalar callsite and
8350/// the iterator callsite at every downstream consumer.
8351///
8352/// Sixteen composition arms swept per single-slot arrangement — one per
8353/// rebased scalar peer:
8354///
8355/// **Populated side (folds through [`TaggedUnion::iter_populated_kinds`]):**
8356///
8357/// 1. `populated_kind_count() == iter_populated_kinds().count()`
8358/// 2. `first_populated_kind() == iter_populated_kinds().next()`
8359/// 3. `last_populated_kind() == iter_populated_kinds().last()`
8360/// 4. `unique_populated_kind()` matches the two-step short-circuit
8361/// (first present + second absent).
8362/// 5. `is_empty() == iter_populated_kinds().next().is_none()`
8363/// 6. `has_any_populated_kind() == iter_populated_kinds().next().is_some()`
8364/// 7. `has_multiple_populated_kinds()` matches the two-step short-circuit
8365/// (first present + second present).
8366///
8367/// **Missing side (folds through [`TaggedUnion::iter_missing_kinds`]):**
8368///
8369/// 8. `missing_kind_count() == iter_missing_kinds().count()`
8370/// 9. `first_missing_kind() == iter_missing_kinds().next()`
8371/// 10. `last_missing_kind() == iter_missing_kinds().last()`
8372/// 11. `unique_missing_kind()` matches the two-step short-circuit.
8373/// 12. `is_saturated() == iter_missing_kinds().next().is_none()`
8374/// 13. `has_any_missing_kind() == iter_missing_kinds().next().is_some()`
8375/// 14. `has_multiple_missing_kinds()` matches the two-step short-circuit.
8376///
8377/// Peer of [`crate::boundary::assert_slice_refinement_composition_laws`]'s
8378/// load-bearing-iterator arms at the slice level under symmetric
8379/// (present/absent) point-probes — closes the "every scalar peer folds
8380/// through the load-bearing iterator" invariant at both trait sites.
8381///
8382/// Same `Lifetime` exclusion as [`assert_populated_kinds_matches_has`]:
8383/// the `T: TaggedUnion` bound doesn't reach it. Any of the four
8384/// production `.variant()` parents on `ProcessSpec` binds through this
8385/// ONE primitive with its per-site `single_slot` factory. A fifth
8386/// sibling picks up the composition-law sweep through ONE call site —
8387/// no re-authored per-peer assertion at the test surface.
8388///
8389/// Theory grounding: THEORY.md §II.1 invariant 5 (composition preserves
8390/// proofs) — every scalar peer's default body composes through the
8391/// load-bearing iterator peer at ONE substrate site; this testkit pins
8392/// that composition as a first-class typed invariant. A future run that
8393/// specializes `iter_populated_kinds` with a fast path (e.g. a bitmap
8394/// scan on a compact-representation tagged union) reaches every scalar
8395/// peer through THIS ONE testkit's binding — an override that
8396/// re-inlines the closed-set walk at a scalar peer independently of
8397/// the iter override drifts HERE.
8398#[track_caller]
8399pub fn assert_scalar_peers_fold_through_iter_kinds<T, F>(single_slot: F)
8400where
8401 T: TaggedUnion,
8402 T::Kind: PartialEq + std::fmt::Debug,
8403 F: Fn(T::Kind) -> T,
8404{
8405 for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
8406 .iter()
8407 .copied()
8408 {
8409 let parent = single_slot(populated);
8410
8411 // -------- Populated side ----------------------------------------
8412 assert_eq!(
8413 parent.populated_kind_count(),
8414 parent.iter_populated_kinds().count(),
8415 "TaggedUnion::populated_kind_count() drifted from iter_populated_kinds().count() — populated={populated:?}",
8416 );
8417 assert_eq!(
8418 parent.first_populated_kind(),
8419 parent.iter_populated_kinds().next(),
8420 "TaggedUnion::first_populated_kind() drifted from iter_populated_kinds().next() — populated={populated:?}",
8421 );
8422 assert_eq!(
8423 parent.last_populated_kind(),
8424 parent.iter_populated_kinds().last(),
8425 "TaggedUnion::last_populated_kind() drifted from iter_populated_kinds().last() — populated={populated:?}",
8426 );
8427 let via_iter_unique_populated = {
8428 let mut it = parent.iter_populated_kinds();
8429 let first = it.next();
8430 match (first, it.next()) {
8431 (Some(k), None) => Some(k),
8432 _ => None,
8433 }
8434 };
8435 assert_eq!(
8436 parent.unique_populated_kind(),
8437 via_iter_unique_populated,
8438 "TaggedUnion::unique_populated_kind() drifted from iter_populated_kinds() two-step short-circuit — populated={populated:?}",
8439 );
8440 assert_eq!(
8441 parent.is_empty(),
8442 parent.iter_populated_kinds().next().is_none(),
8443 "TaggedUnion::is_empty() drifted from iter_populated_kinds().next().is_none() — populated={populated:?}",
8444 );
8445 assert_eq!(
8446 parent.has_any_populated_kind(),
8447 parent.iter_populated_kinds().next().is_some(),
8448 "TaggedUnion::has_any_populated_kind() drifted from iter_populated_kinds().next().is_some() — populated={populated:?}",
8449 );
8450 let via_iter_multi_populated = {
8451 let mut it = parent.iter_populated_kinds();
8452 it.next().is_some() && it.next().is_some()
8453 };
8454 assert_eq!(
8455 parent.has_multiple_populated_kinds(),
8456 via_iter_multi_populated,
8457 "TaggedUnion::has_multiple_populated_kinds() drifted from iter_populated_kinds() two-step short-circuit — populated={populated:?}",
8458 );
8459
8460 // -------- Missing side ------------------------------------------
8461 assert_eq!(
8462 parent.missing_kind_count(),
8463 parent.iter_missing_kinds().count(),
8464 "TaggedUnion::missing_kind_count() drifted from iter_missing_kinds().count() — populated={populated:?}",
8465 );
8466 assert_eq!(
8467 parent.first_missing_kind(),
8468 parent.iter_missing_kinds().next(),
8469 "TaggedUnion::first_missing_kind() drifted from iter_missing_kinds().next() — populated={populated:?}",
8470 );
8471 assert_eq!(
8472 parent.last_missing_kind(),
8473 parent.iter_missing_kinds().last(),
8474 "TaggedUnion::last_missing_kind() drifted from iter_missing_kinds().last() — populated={populated:?}",
8475 );
8476 let via_iter_unique_missing = {
8477 let mut it = parent.iter_missing_kinds();
8478 let first = it.next();
8479 match (first, it.next()) {
8480 (Some(k), None) => Some(k),
8481 _ => None,
8482 }
8483 };
8484 assert_eq!(
8485 parent.unique_missing_kind(),
8486 via_iter_unique_missing,
8487 "TaggedUnion::unique_missing_kind() drifted from iter_missing_kinds() two-step short-circuit — populated={populated:?}",
8488 );
8489 assert_eq!(
8490 parent.is_saturated(),
8491 parent.iter_missing_kinds().next().is_none(),
8492 "TaggedUnion::is_saturated() drifted from iter_missing_kinds().next().is_none() — populated={populated:?}",
8493 );
8494 assert_eq!(
8495 parent.has_any_missing_kind(),
8496 parent.iter_missing_kinds().next().is_some(),
8497 "TaggedUnion::has_any_missing_kind() drifted from iter_missing_kinds().next().is_some() — populated={populated:?}",
8498 );
8499 let via_iter_multi_missing = {
8500 let mut it = parent.iter_missing_kinds();
8501 it.next().is_some() && it.next().is_some()
8502 };
8503 assert_eq!(
8504 parent.has_multiple_missing_kinds(),
8505 via_iter_multi_missing,
8506 "TaggedUnion::has_multiple_missing_kinds() drifted from iter_missing_kinds() two-step short-circuit — populated={populated:?}",
8507 );
8508 }
8509}
8510
8511#[cfg(test)]
8512mod tests {
8513 use super::*;
8514
8515 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
8516 enum V {
8517 A,
8518 B,
8519 C,
8520 }
8521
8522 #[test]
8523 fn empty_candidate_list_is_none() {
8524 let r: Result<V, _> = resolve(std::iter::empty());
8525 assert_eq!(r.unwrap_err(), ResolveError::None);
8526 }
8527
8528 #[test]
8529 fn all_none_is_none() {
8530 let r: Result<V, _> = resolve([None, None, None]);
8531 assert_eq!(r.unwrap_err(), ResolveError::None);
8532 }
8533
8534 #[test]
8535 fn single_some_is_resolved_regardless_of_position() {
8536 assert_eq!(resolve([Some(V::A), None, None]).unwrap(), V::A);
8537 assert_eq!(resolve([None, Some(V::B), None]).unwrap(), V::B);
8538 assert_eq!(resolve([None, None, Some(V::C)]).unwrap(), V::C);
8539 }
8540
8541 #[test]
8542 fn two_or_more_some_is_many() {
8543 assert_eq!(
8544 resolve([Some(V::A), Some(V::B), None]).unwrap_err(),
8545 ResolveError::Many
8546 );
8547 assert_eq!(
8548 resolve([Some(V::A), None, Some(V::C)]).unwrap_err(),
8549 ResolveError::Many
8550 );
8551 assert_eq!(
8552 resolve([None, Some(V::B), Some(V::C)]).unwrap_err(),
8553 ResolveError::Many
8554 );
8555 assert_eq!(
8556 resolve([Some(V::A), Some(V::B), Some(V::C)]).unwrap_err(),
8557 ResolveError::Many
8558 );
8559 }
8560
8561 /// Short-circuit invariant: once `Many` is decided, the sweep does
8562 /// NOT inspect further candidates. Encode it as a side-effect probe.
8563 #[test]
8564 fn many_short_circuits_after_second_some() {
8565 let mut visited = 0usize;
8566 let candidates = (0..4).map(|i| {
8567 visited += 1;
8568 // first two are Some, the rest would be Some too if we got there.
8569 Some(i)
8570 });
8571 // We can't actually consume `visited` here because it's borrowed in
8572 // the closure — fold the count via the resolver's short-circuit.
8573 let _ = resolve(candidates);
8574 // The resolver evaluates the iterator lazily up to the second
8575 // Some — index 0 (found = Some(0)), index 1 (Many → return).
8576 assert_eq!(visited, 2);
8577 }
8578
8579 /// The helper is value-agnostic — works with borrowed enum-view
8580 /// types matching the actual on-the-typescape callsites.
8581 #[test]
8582 fn works_with_borrowed_enum_view() {
8583 #[derive(Debug, PartialEq)]
8584 enum View<'a> {
8585 X(&'a u32),
8586 Y(&'a String),
8587 }
8588 let x = 7u32;
8589 let r = resolve([Some(View::X(&x)), None]).unwrap();
8590 assert_eq!(r, View::X(&7));
8591 }
8592
8593 /// Local sibling-shaped carrier used to pin the trait +
8594 /// [`resolve_or_err`] dispatch without depending on the
8595 /// crate's real error types.
8596 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
8597 enum E {
8598 Empty(&'static str),
8599 Ambiguous,
8600 }
8601
8602 impl TaggedUnionError for E {
8603 fn empty(kinds: &'static str) -> Self {
8604 E::Empty(kinds)
8605 }
8606 fn ambiguous() -> Self {
8607 E::Ambiguous
8608 }
8609 }
8610
8611 /// Four-outcome truth table at the compound-lift boundary.
8612 /// Pins that the two failure arms of [`resolve`] project onto
8613 /// the trait's two typed constructors byte-identically, and
8614 /// that the Ok arm falls through untouched.
8615 #[test]
8616 fn resolve_or_err_dispatches_each_arm_through_the_trait() {
8617 const KINDS: &str = "a/b/c";
8618
8619 assert_eq!(
8620 resolve_or_err::<V, E>([Some(V::A), None, None], KINDS).unwrap(),
8621 V::A
8622 );
8623 assert_eq!(
8624 resolve_or_err::<V, E>([None, Some(V::B), None], KINDS).unwrap(),
8625 V::B
8626 );
8627
8628 assert_eq!(
8629 resolve_or_err::<V, E>([None, None, None], KINDS).unwrap_err(),
8630 E::Empty(KINDS)
8631 );
8632
8633 assert_eq!(
8634 resolve_or_err::<V, E>([Some(V::A), Some(V::B), None], KINDS).unwrap_err(),
8635 E::Ambiguous
8636 );
8637 }
8638
8639 /// The trait's Empty arm carries the &'static str the caller
8640 /// hands `resolve_or_err`, verbatim — a rename at the caller's
8641 /// `KINDS` constant reaches the diagnostic surface intact.
8642 #[test]
8643 fn resolve_or_err_empty_carries_the_caller_kinds_verbatim() {
8644 const KINDS_ALPHA: &str = "alpha/beta";
8645 const KINDS_GAMMA: &str = "gamma/delta/epsilon";
8646
8647 assert_eq!(
8648 resolve_or_err::<V, E>([None, None], KINDS_ALPHA).unwrap_err(),
8649 E::Empty(KINDS_ALPHA)
8650 );
8651 assert_eq!(
8652 resolve_or_err::<V, E>([None, None, None], KINDS_GAMMA).unwrap_err(),
8653 E::Empty(KINDS_GAMMA)
8654 );
8655 }
8656
8657 /// The compound-lift preserves [`resolve`]'s short-circuit at
8658 /// the Many arm — a third-and-later candidate is not
8659 /// inspected once the second populated entry is seen.
8660 #[test]
8661 fn resolve_or_err_short_circuits_on_many() {
8662 let mut visited = 0usize;
8663 let candidates = (0..4).map(|i| {
8664 visited += 1;
8665 Some(i)
8666 });
8667 let _ = resolve_or_err::<i32, E>(candidates, "irrelevant");
8668 assert_eq!(visited, 2);
8669 }
8670
8671 // -------------------------------------------------------------------
8672 // `declare_tagged_union_error!` macro-emitted carrier — pins the
8673 // shape a fifth sibling would land through the macro instead of
8674 // hand-rolling the enum + `impl TaggedUnionError` block.
8675 // -------------------------------------------------------------------
8676
8677 crate::declare_tagged_union_error! {
8678 pub(super) MacroEmittedError,
8679 empty = "test carrier has no variant set (one of {0} required)",
8680 ambiguous = "test carrier has multiple variants set; exactly one required",
8681 }
8682
8683 /// The macro-emitted carrier's [`TaggedUnionError`] impl dispatches
8684 /// the same four-outcome truth table [`resolve_or_err`] pins for a
8685 /// hand-rolled carrier — pins that swapping a hand-rolled carrier
8686 /// for a macro-emitted one preserves the compound-lift's projection
8687 /// byte-identically.
8688 #[test]
8689 fn macro_emitted_carrier_projects_through_resolve_or_err() {
8690 const KINDS: &str = "one/two/three";
8691
8692 assert_eq!(
8693 resolve_or_err::<V, MacroEmittedError>([Some(V::A), None, None], KINDS).unwrap(),
8694 V::A
8695 );
8696 assert_eq!(
8697 resolve_or_err::<V, MacroEmittedError>([None, None, None], KINDS).unwrap_err(),
8698 MacroEmittedError::Empty(KINDS)
8699 );
8700 assert_eq!(
8701 resolve_or_err::<V, MacroEmittedError>([Some(V::A), Some(V::B), None], KINDS)
8702 .unwrap_err(),
8703 MacroEmittedError::Ambiguous
8704 );
8705 }
8706
8707 /// The macro-emitted carrier's `#[error(...)]` messages render the
8708 /// two operator-facing diagnostic strings the caller handed the
8709 /// macro, verbatim — a rename at the caller's literal reaches the
8710 /// operator diagnostic surface intact.
8711 #[test]
8712 fn macro_emitted_carrier_display_renders_caller_literals_verbatim() {
8713 assert_eq!(
8714 MacroEmittedError::Empty("alpha/beta").to_string(),
8715 "test carrier has no variant set (one of alpha/beta required)",
8716 );
8717 assert_eq!(
8718 MacroEmittedError::Ambiguous.to_string(),
8719 "test carrier has multiple variants set; exactly one required",
8720 );
8721 }
8722
8723 /// The macro-emitted carrier is `Copy` — a substrate-wide promise
8724 /// pinned by the macro's `#[derive(..., Copy, ...)]` header so a
8725 /// consumer treating the carrier as a value type (memcpy-cheap
8726 /// return, `.copied()` on an `Option<&E>`) stays valid across every
8727 /// carrier the macro emits.
8728 #[test]
8729 fn macro_emitted_carrier_is_copy() {
8730 fn assert_copy<T: Copy>() {}
8731 assert_copy::<MacroEmittedError>();
8732 }
8733
8734 // -------------------------------------------------------------------
8735 // `TaggedUnion` trait — declarative surface pinning the
8736 // (Kind, Error, KIND_LIST) triple. `assert_kind_list_matches_closed_set`
8737 // is the generic diagnostic-stability testkit primitive shared by
8738 // every implementor's `_error_empty_lists_every_kind_in_canonical_order`
8739 // site.
8740 // -------------------------------------------------------------------
8741
8742 /// Local sibling-shaped Kind enum used to pin the trait's
8743 /// diagnostic-stability primitive without depending on the crate's
8744 /// four production tagged unions. Uses [`tatara_closed_set::DeriveClosedSet`]
8745 /// so `<Self as ClosedSet>::labels_joined("/")` reaches the same
8746 /// substrate composition the four production sites bind through.
8747 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, tatara_closed_set::DeriveClosedSet)]
8748 #[closed_set(via = "as_str", generate_unknown, display)]
8749 enum LocalKind {
8750 Alpha,
8751 Beta,
8752 Gamma,
8753 }
8754
8755 impl LocalKind {
8756 const ALL: [Self; 3] = [Self::Alpha, Self::Beta, Self::Gamma];
8757 const fn as_str(self) -> &'static str {
8758 match self {
8759 Self::Alpha => "alpha",
8760 Self::Beta => "beta",
8761 Self::Gamma => "gamma",
8762 }
8763 }
8764 }
8765
8766 /// Local parent type — impls [`TaggedUnion`] with a `KIND_LIST`
8767 /// literal that matches the canonical `<LocalKind as
8768 /// ClosedSet>::labels_joined("/")` projection. Carries three
8769 /// `Option<u32>` slots so the substrate-primitive
8770 /// [`TaggedUnion::variant`] default method can be exercised
8771 /// directly on a sibling-shaped-but-crate-local parent, isolated
8772 /// from the four production tagged unions.
8773 ///
8774 /// Derives [`serde::Serialize`] with `skip_serializing_if =
8775 /// "Option::is_none"` on every slot so the wire-format primitive
8776 /// [`assert_single_slot_key_matches_label`] can be exercised
8777 /// directly against the sibling-shaped scaffold — mirrors the
8778 /// `#[serde(default, skip_serializing_if = "Option::is_none")]`
8779 /// annotation every one of the four production tagged unions
8780 /// carries on its own slots.
8781 #[derive(Default, serde::Serialize)]
8782 struct LocalParent {
8783 #[serde(skip_serializing_if = "Option::is_none")]
8784 alpha: Option<u32>,
8785 #[serde(skip_serializing_if = "Option::is_none")]
8786 beta: Option<u32>,
8787 #[serde(skip_serializing_if = "Option::is_none")]
8788 gamma: Option<u32>,
8789 }
8790
8791 /// Borrowed-view of a populated slot on [`LocalParent`] — the
8792 /// return type of [`LocalKind::select`] and the substrate-primitive
8793 /// [`TaggedUnion::variant`] default on `LocalParent`.
8794 #[derive(Debug, PartialEq)]
8795 enum LocalVariant<'a> {
8796 Alpha(&'a u32),
8797 Beta(&'a u32),
8798 Gamma(&'a u32),
8799 }
8800
8801 impl VariantSelector<LocalParent> for LocalKind {
8802 type Variant<'a> = LocalVariant<'a>;
8803 fn select<'a>(self, parent: &'a LocalParent) -> Option<LocalVariant<'a>>
8804 where
8805 Self: 'a,
8806 {
8807 match self {
8808 Self::Alpha => parent.alpha.as_ref().map(LocalVariant::Alpha),
8809 Self::Beta => parent.beta.as_ref().map(LocalVariant::Beta),
8810 Self::Gamma => parent.gamma.as_ref().map(LocalVariant::Gamma),
8811 }
8812 }
8813 }
8814
8815 impl VariantKind<LocalKind> for LocalVariant<'_> {
8816 fn variant_kind(&self) -> LocalKind {
8817 match self {
8818 Self::Alpha(_) => LocalKind::Alpha,
8819 Self::Beta(_) => LocalKind::Beta,
8820 Self::Gamma(_) => LocalKind::Gamma,
8821 }
8822 }
8823 }
8824
8825 crate::declare_tagged_union_error! {
8826 pub(super) LocalParentError,
8827 empty = "local carrier has no variant set (one of {0} required)",
8828 ambiguous = "local carrier has multiple variants set; exactly one required",
8829 }
8830
8831 impl TaggedUnion for LocalParent {
8832 type Kind = LocalKind;
8833 type Error = LocalParentError;
8834 const KIND_LIST: &'static str = "alpha/beta/gamma";
8835 }
8836
8837 /// The testkit primitive resolves the canonical join of every
8838 /// `LocalKind` variant's label against the trait's `KIND_LIST`
8839 /// constant byte-identically — the four production sites bind
8840 /// through this exact dispatch. The Ok arm is the "no drift"
8841 /// outcome; a divergence surfaces as a labeled assertion failure.
8842 #[test]
8843 fn assert_kind_list_matches_closed_set_accepts_coherent_impl() {
8844 assert_kind_list_matches_closed_set::<LocalParent>();
8845 }
8846
8847 /// The testkit primitive is a `#[track_caller]` compound-lift:
8848 /// a drift between `<T::Kind as ClosedSet>::labels_joined("/")`
8849 /// and `T::KIND_LIST` fails the assertion at the caller's site,
8850 /// not inside the primitive body. Pin the failing case with a
8851 /// local parent whose `KIND_LIST` is deliberately mis-authored
8852 /// (a variant reorder), so a regression that drops the drift
8853 /// detection fails-loudly here.
8854 #[test]
8855 #[should_panic(expected = "TaggedUnion KIND_LIST drift")]
8856 fn assert_kind_list_matches_closed_set_rejects_drifted_impl() {
8857 struct Drifted;
8858 // The `TaggedUnion` trait bounds `Kind: VariantSelector<Self>`
8859 // with `Variant<'a>: VariantKind<Self>`; the drift test only
8860 // exercises `assert_kind_list_matches_closed_set` (which reaches
8861 // the (Kind, KIND_LIST) pair, not the sweep body), so reusing
8862 // the sibling `LocalVariant<'a>` (with its already-load-bearing
8863 // `impl VariantKind<LocalKind>`) + always-`None` `select`
8864 // satisfies both bounds without wiring a real projection.
8865 impl VariantSelector<Drifted> for LocalKind {
8866 type Variant<'a> = LocalVariant<'a>;
8867 fn select<'a>(self, _: &'a Drifted) -> Option<LocalVariant<'a>>
8868 where
8869 Self: 'a,
8870 {
8871 None
8872 }
8873 }
8874 impl TaggedUnion for Drifted {
8875 type Kind = LocalKind;
8876 type Error = LocalParentError;
8877 // Deliberate drift — canonical join is "alpha/beta/gamma".
8878 const KIND_LIST: &'static str = "beta/alpha/gamma";
8879 }
8880 assert_kind_list_matches_closed_set::<Drifted>();
8881 }
8882
8883 /// Every one of the four production `.variant()` sites on
8884 /// `ProcessSpec` impls [`TaggedUnion`] with `KIND_LIST` reaching
8885 /// the substrate primitive `assert_kind_list_matches_closed_set`
8886 /// coherently. Sweep every production implementor at ONE
8887 /// substrate boundary so a regression that drifts a production
8888 /// site's `KIND_LIST` (or renames a `Kind` variant without
8889 /// updating the constant) fails BOTH at the per-crate test site
8890 /// AND at this substrate-wide sweep — no per-implementor test
8891 /// site can drop the check silently.
8892 #[test]
8893 fn every_production_tagged_union_binds_through_the_testkit_primitive() {
8894 assert_kind_list_matches_closed_set::<crate::intent::Intent>();
8895 assert_kind_list_matches_closed_set::<crate::encapsulates::EncapsulationKind>();
8896 assert_kind_list_matches_closed_set::<crate::export::ArtifactSource>();
8897 assert_kind_list_matches_closed_set::<crate::export::VectorChannel>();
8898 }
8899
8900 /// Every one of the four production `.variant()` sites on
8901 /// `ProcessSpec` binds through the wire-key primitive
8902 /// [`assert_single_slot_key_matches_label`] coherently — every
8903 /// per-site `single_slot_X(k)` factory serializes to a JSON object
8904 /// with EXACTLY ONE key whose name equals `k.label()` (delegating
8905 /// to each Kind's inherent `as_str`, matching the parent's serde
8906 /// `rename_all = "camelCase"` projection). Sweep every production
8907 /// implementor at ONE substrate boundary so a regression that
8908 /// drifts a production site's `single_slot_X` factory (populates
8909 /// the wrong slot; leaks residual slots between calls) OR the
8910 /// parent's field-to-kind alignment (`as_str` returns "receipts"
8911 /// but the field is named `receipt`) fails BOTH at the per-crate
8912 /// test site AND at this substrate-wide sweep — no per-implementor
8913 /// test site can drop the check silently.
8914 #[test]
8915 fn every_production_tagged_union_binds_through_the_wire_key_testkit_primitive() {
8916 assert_single_slot_key_matches_label::<crate::intent::Intent, _>(single_slot_intent_probe);
8917 assert_single_slot_key_matches_label::<crate::encapsulates::EncapsulationKind, _>(
8918 single_slot_encapsulation_kind_probe,
8919 );
8920 assert_single_slot_key_matches_label::<crate::export::ArtifactSource, _>(
8921 single_slot_artifact_source_probe,
8922 );
8923 assert_single_slot_key_matches_label::<crate::export::VectorChannel, _>(
8924 single_slot_vector_channel_probe,
8925 );
8926 }
8927
8928 /// The parent-side four-axis compound-lift dispatches Ok on a
8929 /// coherent implementor — the [`LocalParent`] scaffold publishes
8930 /// every axis (`TaggedUnion` via
8931 /// [`crate::declare_tagged_union_error`]-emitted `LocalParentError`
8932 /// + Serialize via `#[derive(serde::Serialize)]` +
8933 /// `LocalKind: PartialEq + Debug` +
8934 /// `LocalParentError: PartialEq + Debug`), matching the
8935 /// substrate-wide four-axis convention every one of the four
8936 /// production parents carries. The Ok arm is the "no drift"
8937 /// outcome; a divergence at ANY sub-assertion's composition
8938 /// inside the compound (accidentally dropped, silently reordered,
8939 /// or short-circuited) surfaces at the sub-primitive's own
8940 /// panic message (each sub-primitive is `#[track_caller]`), and
8941 /// the per-axis failing arms are pinned by the sibling
8942 /// `#[should_panic]` probes already at the per-axis primitive
8943 /// layer (`assert_kind_list_matches_closed_set_rejects_drifted_impl`,
8944 /// `assert_variant_round_trip_rejects_factory_that_leaves_slot_empty`,
8945 /// `assert_two_slots_ambiguous_rejects_factory_that_populates_only_one_slot`,
8946 /// `assert_single_slot_key_matches_label_rejects_factory_that_populates_wrong_slot`).
8947 /// Re-authoring per-axis drift probes at the compound layer
8948 /// would restate the SAME four axis-typed contracts through a
8949 /// compound wrapper without adding a new gate.
8950 #[test]
8951 fn assert_tagged_union_convention_panel_accepts_coherent_local_impl() {
8952 fn single_slot(k: LocalKind) -> LocalParent {
8953 match k {
8954 LocalKind::Alpha => LocalParent {
8955 alpha: Some(11),
8956 ..Default::default()
8957 },
8958 LocalKind::Beta => LocalParent {
8959 beta: Some(22),
8960 ..Default::default()
8961 },
8962 LocalKind::Gamma => LocalParent {
8963 gamma: Some(33),
8964 ..Default::default()
8965 },
8966 }
8967 }
8968 fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
8969 let mut p = LocalParent::default();
8970 for k in [a, b] {
8971 match k {
8972 LocalKind::Alpha => p.alpha = Some(11),
8973 LocalKind::Beta => p.beta = Some(22),
8974 LocalKind::Gamma => p.gamma = Some(33),
8975 }
8976 }
8977 p
8978 }
8979 assert_tagged_union_convention_panel::<LocalParent, _, _>(single_slot, two_slot);
8980 }
8981
8982 /// Every one of the four production `.variant()` parents on
8983 /// `ProcessSpec` binds through the four-axis convention-panel
8984 /// primitive [`assert_tagged_union_convention_panel`] coherently.
8985 /// Sweep every production parent at ONE substrate boundary so a
8986 /// regression that (a) drops ANY of the four sub-assertions from
8987 /// the compound's body, (b) reorders them in a way that skips
8988 /// one on Ok, (c) silently binds the compound against a
8989 /// hollowed-out sub-assertion body, or (d) drifts a substrate-
8990 /// local `{single,two}_slot_*_probe` fixture (populates the
8991 /// wrong slot; leaks residual slots between calls; the `.or()`
8992 /// composition drops a slot on the two-slot side) fails BOTH at
8993 /// the per-crate test site AND at this substrate-wide sweep.
8994 ///
8995 /// Pinned in lock-step with the sibling
8996 /// `every_production_tagged_union_binds_through_the_testkit_primitive`
8997 /// (KIND_LIST axis) and
8998 /// `every_production_tagged_union_binds_through_the_wire_key_testkit_primitive`
8999 /// (wire-key axis) sweeps — every parent enumerated below is a
9000 /// member of BOTH sibling sweeps (their bounds are strict
9001 /// subsets of the compound's `T: TaggedUnion + Serialize` +
9002 /// `T::Kind: PartialEq + Debug` + `T::Error: PartialEq + Debug`
9003 /// bound), and every parent additionally publishes both a
9004 /// substrate-local `single_slot_*_probe` and a
9005 /// substrate-local `two_slot_*_probe` peer above. Post-sweep the
9006 /// substrate-wide four-axis parent-side convention-panel
9007 /// discipline is a property of the workspace, not a per-file
9008 /// convention — even before any per-site test-body sweep
9009 /// collapses the four per-parent sibling tests into ONE compound
9010 /// call each.
9011 #[test]
9012 fn every_production_tagged_union_binds_through_the_convention_panel_testkit_primitive() {
9013 assert_tagged_union_convention_panel::<crate::intent::Intent, _, _>(
9014 single_slot_intent_probe,
9015 two_slot_intent_probe,
9016 );
9017 assert_tagged_union_convention_panel::<crate::encapsulates::EncapsulationKind, _, _>(
9018 single_slot_encapsulation_kind_probe,
9019 two_slot_encapsulation_kind_probe,
9020 );
9021 assert_tagged_union_convention_panel::<crate::export::ArtifactSource, _, _>(
9022 single_slot_artifact_source_probe,
9023 two_slot_artifact_source_probe,
9024 );
9025 assert_tagged_union_convention_panel::<crate::export::VectorChannel, _, _>(
9026 single_slot_vector_channel_probe,
9027 two_slot_vector_channel_probe,
9028 );
9029 }
9030
9031 /// The Display / label alignment primitive dispatches Ok on a
9032 /// coherent implementor — the [`LocalKind`] scaffold derives
9033 /// `Display` from `label` via `#[closed_set(via = "as_str",
9034 /// display)]`, matching the substrate-wide derive shape every
9035 /// production implementor across the crate carries. The Ok arm
9036 /// is the "no drift" outcome; a divergence surfaces as a labeled
9037 /// assertion failure at the caller site (this test's own line).
9038 #[test]
9039 fn assert_display_matches_label_accepts_coherent_impl() {
9040 assert_display_matches_label::<LocalKind>();
9041 }
9042
9043 /// A local closed-set scaffold whose `Display` deliberately
9044 /// diverges from `label` — pins the failing arm of the primitive.
9045 /// The `#[closed_set(via = "as_str")]` attribute WITHOUT `display`
9046 /// leaves the `Display` impl uncovered by the derive, and the
9047 /// hand-authored `impl Display` below emits a suffixed rendering
9048 /// that no `label` projection returns. A regression that drops
9049 /// the alignment assertion inside
9050 /// [`assert_display_matches_label`] fails-loudly at this
9051 /// `#[should_panic]` probe before it can silently thread through
9052 /// the 29 production `X_display_matches_as_str` sites.
9053 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, tatara_closed_set::DeriveClosedSet)]
9054 #[closed_set(via = "as_str", generate_unknown)]
9055 enum DisplayDriftKind {
9056 Alpha,
9057 Beta,
9058 }
9059
9060 impl DisplayDriftKind {
9061 const ALL: [Self; 2] = [Self::Alpha, Self::Beta];
9062 const fn as_str(self) -> &'static str {
9063 match self {
9064 Self::Alpha => "alpha",
9065 Self::Beta => "beta",
9066 }
9067 }
9068 }
9069
9070 impl std::fmt::Display for DisplayDriftKind {
9071 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
9072 // Deliberate drift — Display suffixes the label with a
9073 // marker no `label` projection returns.
9074 write!(f, "{}!", self.as_str())
9075 }
9076 }
9077
9078 #[test]
9079 #[should_panic(expected = "Display drifted from ClosedSet::label")]
9080 fn assert_display_matches_label_rejects_drifted_impl() {
9081 assert_display_matches_label::<DisplayDriftKind>();
9082 }
9083
9084 /// Every closed-set enum across `tatara-process` that carried a
9085 /// hand-rolled `X_display_matches_as_str` test pre-lift now binds
9086 /// through the substrate primitive at ONE call site each. This
9087 /// substrate-wide sweep pins every production Display-alignment
9088 /// consumer at ONE boundary so a per-crate test-site drop cannot
9089 /// silently disable the check — the sweep here catches the drift
9090 /// even when the per-site test body is removed. Mirrors the
9091 /// `every_production_tagged_union_binds_through_the_testkit_primitive`
9092 /// and `every_production_tagged_union_binds_through_the_wire_key_testkit_primitive`
9093 /// sibling sweeps on the (`KIND_LIST` slash-join, wire-key)
9094 /// axes; this one closes the (`Display` byte-identity) axis.
9095 #[test]
9096 fn every_production_display_impl_binds_through_the_testkit_primitive() {
9097 assert_display_matches_label::<crate::allocation::AllocationPhase>();
9098 assert_display_matches_label::<crate::boundary::ConditionKind>();
9099 assert_display_matches_label::<crate::classification::Arity>();
9100 assert_display_matches_label::<crate::classification::CalmClassification>();
9101 assert_display_matches_label::<crate::classification::ConvergencePointType>();
9102 assert_display_matches_label::<crate::classification::DataClassification>();
9103 assert_display_matches_label::<crate::classification::HorizonKind>();
9104 assert_display_matches_label::<crate::classification::OptimizationDirection>();
9105 assert_display_matches_label::<crate::classification::SubstrateType>();
9106 assert_display_matches_label::<crate::compliance::VerificationPhase>();
9107 assert_display_matches_label::<crate::encapsulates::EncapsulationMode>();
9108 assert_display_matches_label::<crate::encapsulates::EncapsulationTarget>();
9109 assert_display_matches_label::<crate::export::ArtifactKind>();
9110 assert_display_matches_label::<crate::export::ChannelKind>();
9111 assert_display_matches_label::<crate::export::ExportTrigger>();
9112 assert_display_matches_label::<crate::export::ReportFormat>();
9113 assert_display_matches_label::<crate::export::ReportPayloadShape>();
9114 assert_display_matches_label::<crate::intent::IntentKind>();
9115 assert_display_matches_label::<crate::intent::WorkloadKind>();
9116 assert_display_matches_label::<crate::lifetime::LifetimeKind>();
9117 assert_display_matches_label::<crate::lifetime::TeardownPolicy>();
9118 assert_display_matches_label::<crate::lifetime_clock::AutoTerminateKind>();
9119 assert_display_matches_label::<crate::lifetime_clock::TerminateReasonKind>();
9120 assert_display_matches_label::<crate::matrix::SelectStrategyKind>();
9121 assert_display_matches_label::<crate::pool::MemberState>();
9122 assert_display_matches_label::<crate::pool::PoolPhase>();
9123 assert_display_matches_label::<crate::pool::ReplacementPolicy>();
9124 assert_display_matches_label::<crate::pool::ReturnPolicy>();
9125 assert_display_matches_label::<crate::signal::SighupStrategy>();
9126 assert_display_matches_label::<crate::spec::MustReachPhase>();
9127 }
9128
9129 /// Local closed-set scaffold whose serde `rename_all = "lowercase"`
9130 /// projection matches its `via = "as_str"` label byte-identically —
9131 /// pins the Ok arm of the wire-format primitive. Every production
9132 /// implementor across the crate carries the substrate-wide
9133 /// `#[closed_set(via = "as_str")]` + `#[serde(rename_all = ...)]`
9134 /// pair whose alignment this scaffold pins on the sibling-shaped
9135 /// local surface.
9136 #[derive(
9137 Clone,
9138 Copy,
9139 Debug,
9140 PartialEq,
9141 Eq,
9142 Hash,
9143 serde::Serialize,
9144 tatara_closed_set::DeriveClosedSet,
9145 )]
9146 #[serde(rename_all = "lowercase")]
9147 #[closed_set(via = "as_str", generate_unknown)]
9148 enum SerdeAlignedKind {
9149 Alpha,
9150 Beta,
9151 }
9152
9153 impl SerdeAlignedKind {
9154 const ALL: [Self; 2] = [Self::Alpha, Self::Beta];
9155 const fn as_str(self) -> &'static str {
9156 match self {
9157 Self::Alpha => "alpha",
9158 Self::Beta => "beta",
9159 }
9160 }
9161 }
9162
9163 #[test]
9164 fn assert_label_matches_serde_serialization_accepts_coherent_impl() {
9165 assert_label_matches_serde_serialization::<SerdeAlignedKind>();
9166 }
9167
9168 /// A local closed-set scaffold whose serde output deliberately
9169 /// diverges from `label` — pins the failing arm of the wire-format
9170 /// primitive. The `#[serde(rename_all = "UPPERCASE")]` projection
9171 /// emits uppercase JSON strings while the `via = "as_str"` label
9172 /// stays lowercase. A regression that drops the alignment assertion
9173 /// inside [`assert_label_matches_serde_serialization`] fails-loudly
9174 /// at this `#[should_panic]` probe before it can silently thread
9175 /// through the 20 production `X_as_str_matches_serde` sites.
9176 #[derive(
9177 Clone,
9178 Copy,
9179 Debug,
9180 PartialEq,
9181 Eq,
9182 Hash,
9183 serde::Serialize,
9184 tatara_closed_set::DeriveClosedSet,
9185 )]
9186 #[serde(rename_all = "UPPERCASE")]
9187 #[closed_set(via = "as_str", generate_unknown)]
9188 enum SerdeDriftKind {
9189 Alpha,
9190 Beta,
9191 }
9192
9193 impl SerdeDriftKind {
9194 const ALL: [Self; 2] = [Self::Alpha, Self::Beta];
9195 const fn as_str(self) -> &'static str {
9196 match self {
9197 Self::Alpha => "alpha",
9198 Self::Beta => "beta",
9199 }
9200 }
9201 }
9202
9203 #[test]
9204 #[should_panic(expected = "serde output drifted from ClosedSet::label")]
9205 fn assert_label_matches_serde_serialization_rejects_drifted_impl() {
9206 assert_label_matches_serde_serialization::<SerdeDriftKind>();
9207 }
9208
9209 /// Local closed-set scaffold whose ALL THREE axes of the label-
9210 /// surface convention align by construction — pins the Ok arm of
9211 /// the compound-panel primitive.
9212 ///
9213 /// `#[serde(rename_all = "lowercase")]` matches the `via = "as_str"`
9214 /// labels byte-identically (the serde-alignment axis). The
9215 /// `display` sub-attribute on `#[closed_set(via = "as_str",
9216 /// display)]` derives `impl Display` from the same `as_str`
9217 /// projection (the Display-alignment axis). The `generate_unknown`
9218 /// sub-attribute emits the `T::Unknown` carrier the round-trip
9219 /// axis's `parse_label` returns on unknown input. Together these
9220 /// three attributes stamp the substrate-wide derive shape every
9221 /// production 3-axis-panel consumer carries; a caller that lands
9222 /// through this scaffold satisfies EVERY bound the compound's
9223 /// where-clause names.
9224 ///
9225 /// Peer to the sibling per-axis fixtures [`LocalKind`] (Display
9226 /// axis, no serde) and [`SerdeAlignedKind`] (serde axis, no
9227 /// Display) on the label-surface primitive family; this fixture
9228 /// closes the diagonal by carrying both attribute-sets at once,
9229 /// so a regression at ANY sub-assertion's composition inside the
9230 /// compound (the compound accidentally dropping the well-formed
9231 /// call, silently reordering the three calls, wrapping them in a
9232 /// short-circuit that skips the middle one on Ok, …) fails the
9233 /// compound's happy-path pin below rather than as silent drift at
9234 /// every 3-axis consumer.
9235 #[derive(
9236 Clone,
9237 Copy,
9238 Debug,
9239 PartialEq,
9240 Eq,
9241 Hash,
9242 serde::Serialize,
9243 tatara_closed_set::DeriveClosedSet,
9244 )]
9245 #[serde(rename_all = "lowercase")]
9246 #[closed_set(via = "as_str", generate_unknown, display)]
9247 enum PanelAlignedKind {
9248 Alpha,
9249 Beta,
9250 }
9251
9252 impl PanelAlignedKind {
9253 const ALL: [Self; 2] = [Self::Alpha, Self::Beta];
9254 const fn as_str(self) -> &'static str {
9255 match self {
9256 Self::Alpha => "alpha",
9257 Self::Beta => "beta",
9258 }
9259 }
9260 }
9261
9262 /// The compound-panel primitive dispatches Ok on a coherent
9263 /// implementor — [`PanelAlignedKind`] carries every attribute the
9264 /// substrate-wide 3-axis derive shape publishes, so all three
9265 /// sub-assertions the compound composes (well-formed, Display /
9266 /// label, serde / label) pass by construction. The Ok arm is the
9267 /// "no drift on any axis" outcome; a divergence at any single
9268 /// sub-assertion surfaces as that sub-assertion's own labeled
9269 /// panic message (with the caller-attributed line via
9270 /// `#[track_caller]` on both the compound and its sub-
9271 /// primitives), NOT as a silent pass.
9272 ///
9273 /// The per-axis failing arms are pinned by the sibling per-axis
9274 /// #[should_panic] probes above:
9275 /// - the round-trip axis's failing arm is pinned by
9276 /// [`tatara_closed_set::assert_closed_set_well_formed`]'s own
9277 /// `#[should_panic]` probe in the `tatara-closed-set` crate;
9278 /// - the Display axis's failing arm is pinned by
9279 /// [`assert_display_matches_label_rejects_drifted_impl`] on
9280 /// [`DisplayDriftKind`];
9281 /// - the serde axis's failing arm is pinned by
9282 /// [`assert_label_matches_serde_serialization_rejects_drifted_impl`]
9283 /// on [`SerdeDriftKind`].
9284 /// Each per-axis drift fixture already surfaces its axis's exact
9285 /// panic-message substring, so re-authoring per-axis
9286 /// `#[should_panic]` probes at the compound layer would restate
9287 /// the SAME three axis-typed contracts through a compound
9288 /// wrapper — one more copy of the same three pins, not a new
9289 /// gate. The compound's happy-path pin here suffices to verify
9290 /// the composition doesn't lose ANY sub-assertion (a regression
9291 /// that swallows one axis silently would still fail the sibling
9292 /// sub-assertion's own drift probe on the drift fixture).
9293 #[test]
9294 fn assert_closed_set_convention_panel_accepts_coherent_impl() {
9295 assert_closed_set_convention_panel::<PanelAlignedKind>();
9296 }
9297
9298 /// Every closed-set enum across `tatara-process` that publishes
9299 /// ALL THREE axes of the label-surface convention (well-formed +
9300 /// Display-alignment + serde-alignment) now binds through the
9301 /// substrate compound-panel primitive at ONE call site each in
9302 /// this sweep. Pinned in lock-step with the sibling
9303 /// `every_production_serde_serialization_binds_through_the_testkit_primitive`
9304 /// sweep — every enum enumerated below is a member of BOTH sweeps
9305 /// (the compound's `T: Serialize + Display + ClosedSet + ...`
9306 /// bound is a strict superset of `assert_label_matches_serde_
9307 /// serialization`'s `T: ClosedSet + Serialize + Debug` bound, and
9308 /// the 20 wire-format consumers all additionally impl Display via
9309 /// `#[closed_set(via = "as_str", display)]`).
9310 ///
9311 /// A regression that (a) drops the compound's `assert_closed_set_
9312 /// well_formed` dispatch, (b) reorders the three sub-assertions
9313 /// in a way that skips one on Ok, or (c) silently binds the
9314 /// compound against a hollowed-out sub-assertion body catches
9315 /// here at the substrate-wide boundary — the sweep pins every
9316 /// production 3-axis consumer's compound-panel discipline through
9317 /// ONE test even before any per-site test-body sweep collapses
9318 /// the three per-enum sibling tests into ONE compound call each.
9319 /// Post-sweep the substrate-wide compound-panel discipline is a
9320 /// property of the workspace, not a per-file convention.
9321 #[test]
9322 fn every_production_convention_panel_binds_through_the_testkit_primitive() {
9323 assert_closed_set_convention_panel::<crate::allocation::AllocationPhase>();
9324 assert_closed_set_convention_panel::<crate::boundary::ConditionKind>();
9325 assert_closed_set_convention_panel::<crate::classification::CalmClassification>();
9326 assert_closed_set_convention_panel::<crate::classification::ConvergencePointType>();
9327 assert_closed_set_convention_panel::<crate::classification::DataClassification>();
9328 assert_closed_set_convention_panel::<crate::classification::HorizonKind>();
9329 assert_closed_set_convention_panel::<crate::classification::OptimizationDirection>();
9330 assert_closed_set_convention_panel::<crate::classification::SubstrateType>();
9331 assert_closed_set_convention_panel::<crate::compliance::VerificationPhase>();
9332 assert_closed_set_convention_panel::<crate::encapsulates::EncapsulationMode>();
9333 assert_closed_set_convention_panel::<crate::export::ExportTrigger>();
9334 assert_closed_set_convention_panel::<crate::export::ReportFormat>();
9335 assert_closed_set_convention_panel::<crate::intent::WorkloadKind>();
9336 assert_closed_set_convention_panel::<crate::lifetime::TeardownPolicy>();
9337 assert_closed_set_convention_panel::<crate::pool::MemberState>();
9338 assert_closed_set_convention_panel::<crate::pool::PoolPhase>();
9339 assert_closed_set_convention_panel::<crate::pool::ReplacementPolicy>();
9340 assert_closed_set_convention_panel::<crate::pool::ReturnPolicy>();
9341 assert_closed_set_convention_panel::<crate::signal::SighupStrategy>();
9342 assert_closed_set_convention_panel::<crate::spec::MustReachPhase>();
9343 }
9344
9345 /// Every closed-set enum across `tatara-process` that carried a
9346 /// hand-rolled `X_as_str_matches_serde` test pre-lift now binds
9347 /// through the substrate primitive at ONE call site each. This
9348 /// substrate-wide sweep pins every production wire-format alignment
9349 /// consumer at ONE boundary so a per-crate test-site drop cannot
9350 /// silently disable the check — the sweep here catches the drift
9351 /// even when the per-site test body is removed. Mirrors the sibling
9352 /// `every_production_display_impl_binds_through_the_testkit_primitive`
9353 /// sweep on the (Display byte-identity) axis; this one closes the
9354 /// (serde JSON-string byte-identity) axis.
9355 #[test]
9356 fn every_production_serde_serialization_binds_through_the_testkit_primitive() {
9357 assert_label_matches_serde_serialization::<crate::allocation::AllocationPhase>();
9358 assert_label_matches_serde_serialization::<crate::boundary::ConditionKind>();
9359 assert_label_matches_serde_serialization::<crate::classification::CalmClassification>();
9360 assert_label_matches_serde_serialization::<crate::classification::ConvergencePointType>();
9361 assert_label_matches_serde_serialization::<crate::classification::DataClassification>();
9362 assert_label_matches_serde_serialization::<crate::classification::HorizonKind>();
9363 assert_label_matches_serde_serialization::<crate::classification::OptimizationDirection>();
9364 assert_label_matches_serde_serialization::<crate::classification::SubstrateType>();
9365 assert_label_matches_serde_serialization::<crate::compliance::VerificationPhase>();
9366 assert_label_matches_serde_serialization::<crate::encapsulates::EncapsulationMode>();
9367 assert_label_matches_serde_serialization::<crate::export::ExportTrigger>();
9368 assert_label_matches_serde_serialization::<crate::export::ReportFormat>();
9369 assert_label_matches_serde_serialization::<crate::intent::WorkloadKind>();
9370 assert_label_matches_serde_serialization::<crate::lifetime::TeardownPolicy>();
9371 assert_label_matches_serde_serialization::<crate::pool::MemberState>();
9372 assert_label_matches_serde_serialization::<crate::pool::PoolPhase>();
9373 assert_label_matches_serde_serialization::<crate::pool::ReplacementPolicy>();
9374 assert_label_matches_serde_serialization::<crate::pool::ReturnPolicy>();
9375 assert_label_matches_serde_serialization::<crate::signal::SighupStrategy>();
9376 assert_label_matches_serde_serialization::<crate::spec::MustReachPhase>();
9377 }
9378
9379 // Substrate-local single-slot factories — mirror the per-site
9380 // `single_slot_X` test helpers each production site owns, so the
9381 // substrate-wide sweep above binds through the wire-key primitive
9382 // without reaching across the per-crate test-module boundaries the
9383 // per-site helpers are scoped to. The primitive only requires that
9384 // the addressed slot on the parent is populated; the inner spec's
9385 // exact field values are irrelevant to the wire-key check.
9386
9387 fn single_slot_intent_probe(kind: crate::intent::IntentKind) -> crate::intent::Intent {
9388 use crate::intent::{
9389 AplicacaoIntent, ContainerIntent, FluxIntent, GuestIntent, Intent, IntentKind,
9390 LispIntent, NixIntent, WorkloadKind,
9391 };
9392 match kind {
9393 IntentKind::Nix => Intent {
9394 nix: Some(NixIntent {
9395 flake_ref: "f".into(),
9396 attribute: "a".into(),
9397 system: None,
9398 attic_cache: None,
9399 extra_args: vec![],
9400 delegate_to_nix_build: false,
9401 }),
9402 ..Intent::default()
9403 },
9404 IntentKind::Flux => Intent {
9405 flux: Some(FluxIntent {
9406 git_repository: "g".into(),
9407 path: "p".into(),
9408 git_repository_namespace: None,
9409 target_namespace: None,
9410 decrypt_sops: true,
9411 helm_chart: None,
9412 helm_values: None,
9413 }),
9414 ..Intent::default()
9415 },
9416 IntentKind::Lisp => Intent {
9417 lisp: Some(LispIntent {
9418 source: "()".into(),
9419 reader: "tatara-lisp".into(),
9420 version: "v1".into(),
9421 bindings: std::collections::BTreeMap::new(),
9422 }),
9423 ..Intent::default()
9424 },
9425 IntentKind::Container => Intent {
9426 container: Some(ContainerIntent {
9427 image: "x".into(),
9428 replicas: None,
9429 command: vec![],
9430 args: vec![],
9431 env: std::collections::BTreeMap::new(),
9432 workload_kind: WorkloadKind::default(),
9433 }),
9434 ..Intent::default()
9435 },
9436 IntentKind::Aplicacao => Intent {
9437 aplicacao: Some(AplicacaoIntent::chart_only("x", "1")),
9438 ..Intent::default()
9439 },
9440 IntentKind::Guest => Intent {
9441 guest: Some(GuestIntent {
9442 spec: serde_json::json!({"name": "x"}),
9443 state_dir: None,
9444 allow_remote_build: None,
9445 }),
9446 ..Intent::default()
9447 },
9448 }
9449 }
9450
9451 fn single_slot_encapsulation_kind_probe(
9452 target: crate::encapsulates::EncapsulationTarget,
9453 ) -> crate::encapsulates::EncapsulationKind {
9454 use crate::encapsulates::{
9455 BareWorkload, EncapsulationKind, EncapsulationTarget, ExistingHelmRelease,
9456 ExistingKustomization,
9457 };
9458 match target {
9459 EncapsulationTarget::ExistingHelmRelease => EncapsulationKind {
9460 existing_helm_release: Some(ExistingHelmRelease {
9461 namespace: "ns".into(),
9462 name: "hr".into(),
9463 release_name: "rel".into(),
9464 }),
9465 ..EncapsulationKind::default()
9466 },
9467 EncapsulationTarget::ExistingKustomization => EncapsulationKind {
9468 existing_kustomization: Some(ExistingKustomization {
9469 namespace: "ns".into(),
9470 name: "ks".into(),
9471 }),
9472 ..EncapsulationKind::default()
9473 },
9474 EncapsulationTarget::BareWorkload => {
9475 let mut sel = std::collections::BTreeMap::new();
9476 sel.insert("app".into(), "x".into());
9477 EncapsulationKind {
9478 bare_workload: Some(BareWorkload {
9479 namespace: "ns".into(),
9480 selector: sel,
9481 }),
9482 ..EncapsulationKind::default()
9483 }
9484 }
9485 }
9486 }
9487
9488 fn single_slot_artifact_source_probe(
9489 kind: crate::export::ArtifactKind,
9490 ) -> crate::export::ArtifactSource {
9491 use crate::export::{
9492 ArtifactKind, ArtifactSource, ProcessSnapshotSource, ReceiptsSource, ReportFormat,
9493 RunMarkerSource, TestReportSource,
9494 };
9495 match kind {
9496 ArtifactKind::Receipts => ArtifactSource {
9497 receipts: Some(ReceiptsSource::default()),
9498 ..ArtifactSource::default()
9499 },
9500 ArtifactKind::TestReport => ArtifactSource {
9501 test_report: Some(TestReportSource {
9502 configmap: "cm".into(),
9503 key: "k".into(),
9504 format: ReportFormat::Junit,
9505 namespace: None,
9506 }),
9507 ..ArtifactSource::default()
9508 },
9509 ArtifactKind::ProcessSnapshot => ArtifactSource {
9510 process_snapshot: Some(ProcessSnapshotSource::default()),
9511 ..ArtifactSource::default()
9512 },
9513 ArtifactKind::RunMarker => ArtifactSource {
9514 run_marker: Some(RunMarkerSource::default()),
9515 ..ArtifactSource::default()
9516 },
9517 }
9518 }
9519
9520 fn single_slot_vector_channel_probe(
9521 kind: crate::export::ChannelKind,
9522 ) -> crate::export::VectorChannel {
9523 use crate::export::{
9524 ChannelKind, HttpEventChannel, NatsSubjectChannel, StdoutChannel, VectorChannel,
9525 };
9526 match kind {
9527 ChannelKind::HttpEvent => VectorChannel {
9528 http_event: Some(HttpEventChannel::signal("x")),
9529 ..VectorChannel::default()
9530 },
9531 ChannelKind::NatsSubject => VectorChannel {
9532 nats_subject: Some(NatsSubjectChannel::publish("s", "S")),
9533 ..VectorChannel::default()
9534 },
9535 ChannelKind::Stdout => VectorChannel {
9536 stdout: Some(StdoutChannel::default()),
9537 ..VectorChannel::default()
9538 },
9539 }
9540 }
9541
9542 // Substrate-local two-slot factories — peers to the sibling
9543 // `single_slot_*_probe` block above. Each composes
9544 // `single_slot_*_probe(a)` with `single_slot_*_probe(b)`
9545 // through per-field `Option::or` on the parent's tagged-union
9546 // slots, matching the shape every per-site `two_slot_X(a, b)`
9547 // helper across the four production parents already carries.
9548 // The ambiguity-primitive only requires that BOTH addressed
9549 // slots on the parent are populated; the inner spec's exact
9550 // field values are irrelevant to the two-slot ambiguity check.
9551
9552 fn two_slot_intent_probe(
9553 a: crate::intent::IntentKind,
9554 b: crate::intent::IntentKind,
9555 ) -> crate::intent::Intent {
9556 let ia = single_slot_intent_probe(a);
9557 let ib = single_slot_intent_probe(b);
9558 crate::intent::Intent {
9559 nix: ia.nix.or(ib.nix),
9560 flux: ia.flux.or(ib.flux),
9561 lisp: ia.lisp.or(ib.lisp),
9562 container: ia.container.or(ib.container),
9563 aplicacao: ia.aplicacao.or(ib.aplicacao),
9564 guest: ia.guest.or(ib.guest),
9565 }
9566 }
9567
9568 fn two_slot_encapsulation_kind_probe(
9569 a: crate::encapsulates::EncapsulationTarget,
9570 b: crate::encapsulates::EncapsulationTarget,
9571 ) -> crate::encapsulates::EncapsulationKind {
9572 let ka = single_slot_encapsulation_kind_probe(a);
9573 let kb = single_slot_encapsulation_kind_probe(b);
9574 crate::encapsulates::EncapsulationKind {
9575 existing_helm_release: ka.existing_helm_release.or(kb.existing_helm_release),
9576 existing_kustomization: ka.existing_kustomization.or(kb.existing_kustomization),
9577 bare_workload: ka.bare_workload.or(kb.bare_workload),
9578 }
9579 }
9580
9581 fn two_slot_artifact_source_probe(
9582 a: crate::export::ArtifactKind,
9583 b: crate::export::ArtifactKind,
9584 ) -> crate::export::ArtifactSource {
9585 let sa = single_slot_artifact_source_probe(a);
9586 let sb = single_slot_artifact_source_probe(b);
9587 crate::export::ArtifactSource {
9588 receipts: sa.receipts.or(sb.receipts),
9589 test_report: sa.test_report.or(sb.test_report),
9590 process_snapshot: sa.process_snapshot.or(sb.process_snapshot),
9591 run_marker: sa.run_marker.or(sb.run_marker),
9592 }
9593 }
9594
9595 fn two_slot_vector_channel_probe(
9596 a: crate::export::ChannelKind,
9597 b: crate::export::ChannelKind,
9598 ) -> crate::export::VectorChannel {
9599 let ca = single_slot_vector_channel_probe(a);
9600 let cb = single_slot_vector_channel_probe(b);
9601 crate::export::VectorChannel {
9602 http_event: ca.http_event.or(cb.http_event),
9603 nats_subject: ca.nats_subject.or(cb.nats_subject),
9604 stdout: ca.stdout.or(cb.stdout),
9605 }
9606 }
9607
9608 /// The trait's `KIND_LIST` associated const IS the same
9609 /// `&'static str` the inherent `_LIST` constant publishes at
9610 /// each production site — pin identity via `std::ptr::eq` so a
9611 /// future silent copy (e.g. `const KIND_LIST: &'static str =
9612 /// "...literal...";` at the impl block) is caught here.
9613 #[test]
9614 fn production_tagged_union_kind_list_borrows_the_inherent_constant() {
9615 assert!(std::ptr::eq(
9616 <crate::intent::Intent as TaggedUnion>::KIND_LIST,
9617 crate::intent::INTENT_KIND_LIST,
9618 ));
9619 assert!(std::ptr::eq(
9620 <crate::encapsulates::EncapsulationKind as TaggedUnion>::KIND_LIST,
9621 crate::encapsulates::ENCAPSULATION_TARGET_LIST,
9622 ));
9623 assert!(std::ptr::eq(
9624 <crate::export::ArtifactSource as TaggedUnion>::KIND_LIST,
9625 crate::export::ARTIFACT_KIND_LIST,
9626 ));
9627 assert!(std::ptr::eq(
9628 <crate::export::VectorChannel as TaggedUnion>::KIND_LIST,
9629 crate::export::CHANNEL_KIND_LIST,
9630 ));
9631 }
9632
9633 // -------------------------------------------------------------------
9634 // `TaggedUnion::variant` default method — substrate primitive every
9635 // production `.variant()` inherent method delegates to. Pin the
9636 // four-outcome truth table (Empty on all-none, Ambiguous on many,
9637 // Ok on exactly-one at every position) directly on the sibling-
9638 // shaped local parent + local kind + local variant scaffold, so a
9639 // regression on the default body's short-circuit or
9640 // ClosedSet::ALL iteration shape fails here — before any per-parent
9641 // inherent test surfaces the drift.
9642 // -------------------------------------------------------------------
9643
9644 /// Every populated position across [`LocalKind::ALL`] resolves to
9645 /// its own [`LocalVariant`] arm through the default body's
9646 /// `resolve_or_err(<Kind as ClosedSet>::ALL.iter().copied()
9647 /// .map(|k| k.select(self)), KIND_LIST)` sweep. Pin every position
9648 /// so a regression that drifts the iteration order (or drops the
9649 /// `.iter().copied()` bridge to owned-`Copy` Kinds) fails at ONE
9650 /// substrate boundary rather than at four per-parent inherent test
9651 /// sites.
9652 #[test]
9653 fn tagged_union_default_variant_resolves_each_populated_slot() {
9654 let mut p = LocalParent {
9655 alpha: Some(11),
9656 ..Default::default()
9657 };
9658 assert_eq!(
9659 <LocalParent as TaggedUnion>::variant(&p).unwrap(),
9660 LocalVariant::Alpha(&11)
9661 );
9662 p = LocalParent {
9663 beta: Some(22),
9664 ..Default::default()
9665 };
9666 assert_eq!(
9667 <LocalParent as TaggedUnion>::variant(&p).unwrap(),
9668 LocalVariant::Beta(&22)
9669 );
9670 p = LocalParent {
9671 gamma: Some(33),
9672 ..Default::default()
9673 };
9674 assert_eq!(
9675 <LocalParent as TaggedUnion>::variant(&p).unwrap(),
9676 LocalVariant::Gamma(&33)
9677 );
9678 }
9679
9680 /// A [`LocalParent`] with no populated slot resolves through the
9681 /// default body to a [`TaggedUnionError::empty`] carrier whose
9682 /// payload IS the trait's [`TaggedUnion::KIND_LIST`] constant —
9683 /// pin identity via [`std::ptr::eq`] so a regression that
9684 /// composes a fresh `&'static str` at the empty arm (instead of
9685 /// carrying the trait's constant verbatim) is caught here. This
9686 /// is the substrate-wide guarantee the four production sites'
9687 /// operator diagnostics depend on: a rename at
9688 /// `<Parent as TaggedUnion>::KIND_LIST` reaches the error surface
9689 /// intact through ONE `&'static str` handoff.
9690 #[test]
9691 fn tagged_union_default_variant_empty_carries_kind_list_by_pointer() {
9692 let empty = LocalParent::default();
9693 let err = <LocalParent as TaggedUnion>::variant(&empty).unwrap_err();
9694 match err {
9695 LocalParentError::Empty(list) => {
9696 assert!(
9697 std::ptr::eq(list, <LocalParent as TaggedUnion>::KIND_LIST),
9698 "TaggedUnion::variant default must carry KIND_LIST by pointer, not by re-composition",
9699 );
9700 }
9701 LocalParentError::Ambiguous => {
9702 panic!("expected Empty carrier, got Ambiguous");
9703 }
9704 }
9705 }
9706
9707 /// A [`LocalParent`] with two populated slots resolves through
9708 /// the default body to a [`TaggedUnionError::ambiguous`] carrier —
9709 /// pin the Many arm at the substrate boundary so a regression
9710 /// that drops the short-circuit (or misroutes the Many arm to
9711 /// Empty) is caught here.
9712 #[test]
9713 fn tagged_union_default_variant_ambiguous_on_multiple_populated_slots() {
9714 let p = LocalParent {
9715 alpha: Some(1),
9716 beta: Some(2),
9717 gamma: None,
9718 };
9719 assert_eq!(
9720 <LocalParent as TaggedUnion>::variant(&p).unwrap_err(),
9721 LocalParentError::Ambiguous
9722 );
9723 }
9724
9725 /// Every one of the four production `.variant()` inherent methods
9726 /// dispatches through the trait's default body byte-identically —
9727 /// pin the delegation shape (inherent forwarder → trait default)
9728 /// on a probe per parent so a regression that copies the pre-lift
9729 /// hand-rolled `resolve_or_err(...)` body back into the inherent
9730 /// method (instead of the `<Self as TaggedUnion>::variant(self)`
9731 /// one-line delegation) reaches this substrate boundary before it
9732 /// reaches any operator diagnostic.
9733 #[test]
9734 fn every_production_inherent_variant_dispatches_through_trait_default() {
9735 use crate::encapsulates::{EncapsulationKind, EncapsulationKindError};
9736 use crate::export::{ArtifactError, ArtifactSource, ChannelError, VectorChannel};
9737 use crate::intent::{Intent, IntentError};
9738
9739 // Intent: default of all-None resolves to Empty via the delegation.
9740 let i = Intent::default();
9741 match (i.variant(), <Intent as TaggedUnion>::variant(&i)) {
9742 (Err(IntentError::Empty(a)), Err(IntentError::Empty(b))) => assert!(
9743 std::ptr::eq(a, b),
9744 "Intent inherent and trait dispatch must return the same &'static str",
9745 ),
9746 (a, b) => panic!("Intent inherent/trait mismatch: inherent={a:?}, trait={b:?}"),
9747 }
9748
9749 // EncapsulationKind: same Empty projection through both dispatch paths.
9750 let k = EncapsulationKind::default();
9751 match (k.variant(), <EncapsulationKind as TaggedUnion>::variant(&k)) {
9752 (Err(EncapsulationKindError::Empty(a)), Err(EncapsulationKindError::Empty(b))) => {
9753 assert!(
9754 std::ptr::eq(a, b),
9755 "EncapsulationKind inherent and trait dispatch must return the same &'static str",
9756 )
9757 }
9758 (a, b) => {
9759 panic!("EncapsulationKind inherent/trait mismatch: inherent={a:?}, trait={b:?}")
9760 }
9761 }
9762
9763 // ArtifactSource: same Empty projection through both dispatch paths.
9764 let s = ArtifactSource::default();
9765 match (s.variant(), <ArtifactSource as TaggedUnion>::variant(&s)) {
9766 (Err(ArtifactError::Empty(a)), Err(ArtifactError::Empty(b))) => assert!(
9767 std::ptr::eq(a, b),
9768 "ArtifactSource inherent and trait dispatch must return the same &'static str",
9769 ),
9770 (a, b) => panic!("ArtifactSource inherent/trait mismatch: inherent={a:?}, trait={b:?}"),
9771 }
9772
9773 // VectorChannel: same Empty projection through both dispatch paths.
9774 let c = VectorChannel::default();
9775 match (c.variant(), <VectorChannel as TaggedUnion>::variant(&c)) {
9776 (Err(ChannelError::Empty(a)), Err(ChannelError::Empty(b))) => assert!(
9777 std::ptr::eq(a, b),
9778 "VectorChannel inherent and trait dispatch must return the same &'static str",
9779 ),
9780 (a, b) => panic!("VectorChannel inherent/trait mismatch: inherent={a:?}, trait={b:?}"),
9781 }
9782 }
9783
9784 // -------------------------------------------------------------------
9785 // `declare_tagged_union_impls!` macro — the three-block impl stanza
9786 // (inherent `.variant()` forwarder + `VariantSelector<Parent>` on
9787 // the Kind + `TaggedUnion` on the parent) as ONE authoring surface.
9788 // Pin the macro's shape against a sibling-shaped local family so a
9789 // regression on any of the three emitted blocks fails here before
9790 // it reaches the four production sites.
9791 // -------------------------------------------------------------------
9792
9793 /// Local sibling-shaped Kind for the macro-emitted-impls test — a
9794 /// dedicated closed set so this test can't share substrate with the
9795 /// hand-rolled [`LocalKind`] block above. Uses
9796 /// [`tatara_closed_set::DeriveClosedSet`] so the macro's
9797 /// `TaggedUnion` bound (`Kind: ClosedSet + VariantSelector<Self>`)
9798 /// is satisfied through the derive.
9799 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, tatara_closed_set::DeriveClosedSet)]
9800 #[closed_set(via = "as_str", generate_unknown)]
9801 enum MacroLocalKind {
9802 Foo,
9803 Bar,
9804 }
9805
9806 impl MacroLocalKind {
9807 const ALL: [Self; 2] = [Self::Foo, Self::Bar];
9808 const fn as_str(self) -> &'static str {
9809 match self {
9810 Self::Foo => "foo",
9811 Self::Bar => "bar",
9812 }
9813 }
9814 fn select<'a>(self, parent: &'a MacroLocalParent) -> Option<MacroLocalVariant<'a>> {
9815 match self {
9816 Self::Foo => parent.foo.as_ref().map(MacroLocalVariant::Foo),
9817 Self::Bar => parent.bar.as_ref().map(MacroLocalVariant::Bar),
9818 }
9819 }
9820 }
9821
9822 /// Local sibling-shaped parent for the macro-emitted-impls test —
9823 /// distinct from [`LocalParent`] so the macro's emitted impls
9824 /// don't collide with the hand-rolled trait impls above.
9825 ///
9826 /// Derives [`serde::Serialize`] with `skip_serializing_if =
9827 /// "Option::is_none"` on every slot so the wire-format primitive
9828 /// [`assert_single_slot_key_matches_label`] can be exercised
9829 /// through the macro-emitted `TaggedUnion` impl path — pins the
9830 /// substrate-wide guarantee that a fifth sibling landing through
9831 /// [`declare_tagged_union_impls!`] picks up the wire-alignment
9832 /// check for free.
9833 #[derive(Default, serde::Serialize)]
9834 struct MacroLocalParent {
9835 #[serde(skip_serializing_if = "Option::is_none")]
9836 foo: Option<u32>,
9837 #[serde(skip_serializing_if = "Option::is_none")]
9838 bar: Option<u32>,
9839 }
9840
9841 /// Borrowed-view of a populated slot on [`MacroLocalParent`] — the
9842 /// return type of the macro-emitted inherent `.variant()`.
9843 #[derive(Debug, PartialEq)]
9844 enum MacroLocalVariant<'a> {
9845 Foo(&'a u32),
9846 Bar(&'a u32),
9847 }
9848
9849 impl VariantKind<MacroLocalKind> for MacroLocalVariant<'_> {
9850 fn variant_kind(&self) -> MacroLocalKind {
9851 match self {
9852 Self::Foo(_) => MacroLocalKind::Foo,
9853 Self::Bar(_) => MacroLocalKind::Bar,
9854 }
9855 }
9856 }
9857
9858 crate::declare_tagged_union_error! {
9859 pub(super) MacroLocalError,
9860 empty = "macro-local parent has no variant set (one of {0} required)",
9861 ambiguous = "macro-local parent has multiple variants set; exactly one required",
9862 }
9863
9864 /// Slash-joined kind list — literal peer of
9865 /// [`crate::intent::INTENT_KIND_LIST`] etc. that the macro's
9866 /// `KIND_LIST` associated const borrows verbatim.
9867 const MACRO_LOCAL_KIND_LIST: &str = "foo/bar";
9868
9869 // ONE macro call emits: inherent `MacroLocalParent::variant`,
9870 // `impl VariantSelector<MacroLocalParent> for MacroLocalKind`, and
9871 // `impl TaggedUnion for MacroLocalParent`. The four production
9872 // sites bind through this exact same call shape.
9873 crate::declare_tagged_union_impls! {
9874 parent = MacroLocalParent,
9875 kind = MacroLocalKind,
9876 variant = MacroLocalVariant,
9877 error = MacroLocalError,
9878 kind_list = MACRO_LOCAL_KIND_LIST,
9879 }
9880
9881 /// The macro-emitted `impl TaggedUnion` binds the (Kind, Error,
9882 /// KIND_LIST) triple exactly as a hand-rolled block would — pin
9883 /// the diagnostic-stability testkit primitive through the macro's
9884 /// output so a regression on any of the three associated items
9885 /// (say the macro pulling `KIND_LIST` from the wrong argument
9886 /// slot) fails here.
9887 #[test]
9888 fn macro_emitted_tagged_union_impl_binds_kind_list_coherently() {
9889 assert_kind_list_matches_closed_set::<MacroLocalParent>();
9890 assert!(std::ptr::eq(
9891 <MacroLocalParent as TaggedUnion>::KIND_LIST,
9892 MACRO_LOCAL_KIND_LIST,
9893 ));
9894 }
9895
9896 /// The macro-emitted inherent `.variant()` forwarder dispatches
9897 /// through the trait default body — every populated slot resolves
9898 /// to its own [`MacroLocalVariant`] arm, all-none resolves to
9899 /// [`TaggedUnionError::empty`] carrying the trait's `KIND_LIST`
9900 /// by pointer, two-populated resolves to
9901 /// [`TaggedUnionError::ambiguous`]. The four production sites
9902 /// exercise the same four-outcome truth table through the same
9903 /// macro-emitted delegation shape.
9904 #[test]
9905 fn macro_emitted_inherent_variant_dispatches_the_four_outcome_truth_table() {
9906 // Foo populated.
9907 let p = MacroLocalParent {
9908 foo: Some(11),
9909 bar: None,
9910 };
9911 assert_eq!(p.variant().unwrap(), MacroLocalVariant::Foo(&11));
9912
9913 // Bar populated.
9914 let p = MacroLocalParent {
9915 foo: None,
9916 bar: Some(22),
9917 };
9918 assert_eq!(p.variant().unwrap(), MacroLocalVariant::Bar(&22));
9919
9920 // All none — Empty arm carries the trait's KIND_LIST value.
9921 // The by-pointer preservation across the trait default body is
9922 // pinned substrate-wide by
9923 // `tagged_union_default_variant_empty_carries_kind_list_by_pointer`
9924 // on the sibling hand-rolled `LocalParent`; this test only pins
9925 // that the macro-emitted `KIND_LIST = MACRO_LOCAL_KIND_LIST`
9926 // assignment reaches the operator diagnostic value-identically.
9927 let p = MacroLocalParent::default();
9928 match p.variant().unwrap_err() {
9929 MacroLocalError::Empty(list) => assert_eq!(list, MACRO_LOCAL_KIND_LIST),
9930 MacroLocalError::Ambiguous => panic!("expected Empty, got Ambiguous"),
9931 }
9932
9933 // Two populated — Ambiguous.
9934 let p = MacroLocalParent {
9935 foo: Some(1),
9936 bar: Some(2),
9937 };
9938 assert_eq!(p.variant().unwrap_err(), MacroLocalError::Ambiguous);
9939 }
9940
9941 /// The macro-emitted inherent `.has()` forwarder dispatches
9942 /// through the trait default body — the presence probe agrees
9943 /// with `Kind::select(&parent).is_some()` on the diagonal
9944 /// (populated slot AND matching Kind → `true`) and off the
9945 /// diagonal (populated slot BUT other Kind → `false`) for the
9946 /// same four-outcome truth table the macro-emitted `.variant()`
9947 /// covers. The four production sites bind through this exact
9948 /// same macro-emitted delegation shape; the substrate testkit
9949 /// primitive [`assert_has_matches_select`] sweeps this contract
9950 /// generically once each production Kind picks up the macro's
9951 /// output.
9952 #[test]
9953 fn macro_emitted_inherent_has_dispatches_the_presence_probe_diagonal() {
9954 // Foo populated → has(Foo) is true, has(Bar) is false.
9955 let p = MacroLocalParent {
9956 foo: Some(11),
9957 bar: None,
9958 };
9959 assert!(p.has(MacroLocalKind::Foo));
9960 assert!(!p.has(MacroLocalKind::Bar));
9961
9962 // Bar populated → has(Bar) is true, has(Foo) is false.
9963 let p = MacroLocalParent {
9964 foo: None,
9965 bar: Some(22),
9966 };
9967 assert!(!p.has(MacroLocalKind::Foo));
9968 assert!(p.has(MacroLocalKind::Bar));
9969
9970 // All none — every probe is false; no Empty carrier
9971 // allocation on this path (the presence-probe half of the
9972 // resolve contract deliberately elides diagnostic composition
9973 // when the caller only needs yes/no).
9974 let p = MacroLocalParent::default();
9975 assert!(!p.has(MacroLocalKind::Foo));
9976 assert!(!p.has(MacroLocalKind::Bar));
9977
9978 // Two populated — has(k) is true for BOTH populated slots
9979 // (the probe is a per-slot projection, not the parent-wide
9980 // resolver — Ambiguous is a resolve outcome, not a presence
9981 // outcome).
9982 let p = MacroLocalParent {
9983 foo: Some(1),
9984 bar: Some(2),
9985 };
9986 assert!(p.has(MacroLocalKind::Foo));
9987 assert!(p.has(MacroLocalKind::Bar));
9988 }
9989
9990 /// The macro-emitted inherent `.find()` forwarder dispatches
9991 /// through the trait default body — every populated slot resolves
9992 /// to `Some(matching-borrow)`, empty slots to `None`, and the
9993 /// composition law `parent.has(k) == parent.find(k).is_some()`
9994 /// holds at every arm of the four-outcome truth table. Additional
9995 /// pointer-identity pin: the borrowed reference returned by
9996 /// `p.find(k)` on a populated slot IS the same reference that
9997 /// `<Kind>::select(k, &p)` returns — a regression that inlines a
9998 /// divergent projection body at the macro's emitted forwarder
9999 /// (rather than reaching the trait's `<Self as
10000 /// TaggedUnion>::find(self, kind)` one-line delegation) is caught
10001 /// here.
10002 #[test]
10003 fn macro_emitted_inherent_find_dispatches_the_presence_probe_diagonal() {
10004 // Foo populated → find(Foo) borrows the inner ref, find(Bar)
10005 // is None, and `has` agrees with `find(...).is_some()` on
10006 // both arms.
10007 let p = MacroLocalParent {
10008 foo: Some(77),
10009 bar: None,
10010 };
10011 match p.find(MacroLocalKind::Foo) {
10012 Some(MacroLocalVariant::Foo(v)) => {
10013 assert_eq!(*v, 77, "find must borrow the populated inner");
10014 assert_eq!(
10015 p.has(MacroLocalKind::Foo),
10016 true,
10017 "composition law: has must agree with find(...).is_some() on populated slot",
10018 );
10019 // Pointer-identity check: `find` delegates to
10020 // `kind.select(self)` byte-identically. The returned
10021 // borrow IS the borrow `select` returns.
10022 let via_select = MacroLocalKind::Foo.select(&p).unwrap();
10023 match via_select {
10024 MacroLocalVariant::Foo(w) => assert!(
10025 std::ptr::eq(v, w),
10026 "macro-emitted find must return the SAME borrow as VariantSelector::select",
10027 ),
10028 MacroLocalVariant::Bar(_) => {
10029 panic!(
10030 "VariantSelector::select disagreed with find on the populated Foo slot"
10031 )
10032 }
10033 }
10034 }
10035 other => panic!("expected Foo populated, got {other:?}"),
10036 }
10037 assert!(p.find(MacroLocalKind::Bar).is_none());
10038 assert_eq!(
10039 p.has(MacroLocalKind::Bar),
10040 false,
10041 "composition law: has must agree with find(...).is_some() on empty slot",
10042 );
10043
10044 // All none — find returns None for every kind; has agrees.
10045 let p = MacroLocalParent::default();
10046 for kind in MacroLocalKind::ALL {
10047 assert!(p.find(kind).is_none());
10048 assert_eq!(
10049 p.has(kind),
10050 false,
10051 "composition law on empty parent: has must equal find(...).is_some()",
10052 );
10053 }
10054
10055 // Two populated — find(k) is Some for BOTH populated slots
10056 // (the widened primitive is a per-slot projection, not the
10057 // parent-wide resolver — Ambiguous is a resolve outcome, not
10058 // a find outcome).
10059 let p = MacroLocalParent {
10060 foo: Some(1),
10061 bar: Some(2),
10062 };
10063 assert!(p.find(MacroLocalKind::Foo).is_some());
10064 assert!(p.find(MacroLocalKind::Bar).is_some());
10065 }
10066
10067 /// The macro-emitted `VariantSelector` impl's `select` body
10068 /// delegates to the Kind's inherent `<Kind>::select(self, parent)`
10069 /// — pin the delegation via `std::ptr::eq` on the returned
10070 /// borrowed view so a regression that inlines a divergent select
10071 /// body (rather than reaching the inherent method) is caught here.
10072 #[test]
10073 fn macro_emitted_variant_selector_delegates_to_inherent_select() {
10074 let p = MacroLocalParent {
10075 foo: Some(7),
10076 bar: None,
10077 };
10078 // Trait-dispatched select projects through the macro-emitted body.
10079 let via_trait =
10080 <MacroLocalKind as VariantSelector<MacroLocalParent>>::select(MacroLocalKind::Foo, &p)
10081 .unwrap();
10082 // Inherent select projects through the direct impl.
10083 let via_inherent = MacroLocalKind::Foo.select(&p).unwrap();
10084 match (via_trait, via_inherent) {
10085 (MacroLocalVariant::Foo(a), MacroLocalVariant::Foo(b)) => {
10086 assert!(
10087 std::ptr::eq(a, b),
10088 "macro-emitted VariantSelector::select must delegate to <Kind>::select — same borrow, not a copy",
10089 );
10090 }
10091 _ => panic!("expected Foo arm on both dispatch paths"),
10092 }
10093 }
10094
10095 /// The trait's default body sweeps `<Kind as ClosedSet>::ALL` in
10096 /// declaration order — pin the iteration order against the
10097 /// production `Kind::ALL` inherent const on every implementor so
10098 /// a regression on `DeriveClosedSet`'s ALL-projection (or a
10099 /// silent reorder of the enum's variant declarations that drifts
10100 /// only ONE of the two arrays) fails at ONE substrate boundary.
10101 #[test]
10102 fn every_production_kind_closedset_all_matches_inherent_all() {
10103 use crate::encapsulates::EncapsulationTarget;
10104 use crate::export::{ArtifactKind, ChannelKind};
10105 use crate::intent::IntentKind;
10106
10107 assert_eq!(
10108 <IntentKind as tatara_closed_set::ClosedSet>::ALL,
10109 IntentKind::ALL.as_slice(),
10110 );
10111 assert_eq!(
10112 <EncapsulationTarget as tatara_closed_set::ClosedSet>::ALL,
10113 EncapsulationTarget::ALL.as_slice(),
10114 );
10115 assert_eq!(
10116 <ArtifactKind as tatara_closed_set::ClosedSet>::ALL,
10117 ArtifactKind::ALL.as_slice(),
10118 );
10119 assert_eq!(
10120 <ChannelKind as tatara_closed_set::ClosedSet>::ALL,
10121 ChannelKind::ALL.as_slice(),
10122 );
10123 }
10124
10125 // -------------------------------------------------------------------
10126 // `VariantKind<K>` trait — reverse projection from a borrowed-variant
10127 // view back into its addressing Kind, and `assert_variant_round_trip`
10128 // as the substrate testkit primitive that composes it with
10129 // `VariantSelector::select` on the populated side. Pin the four-arm
10130 // truth table (every position round-trips through select→variant_kind
10131 // AND through variant()→variant_kind) directly on the sibling-shaped
10132 // local scaffold, so a regression on either projection or on the
10133 // resolver default body fails here — before any per-parent inherent
10134 // test surfaces the drift.
10135 // -------------------------------------------------------------------
10136
10137 /// Every populated position across [`LocalKind::ALL`] round-trips
10138 /// through both `select→variant_kind` AND `variant()→variant_kind`
10139 /// on the sibling-shaped local scaffold. Pins the substrate
10140 /// primitive's four-arm truth table at ONE boundary — a regression
10141 /// on either projection direction (or on the resolver default
10142 /// short-circuit / iteration order) fails here before any per-parent
10143 /// inherent test surfaces the drift.
10144 #[test]
10145 fn assert_variant_round_trip_accepts_coherent_local_impl() {
10146 fn make_local(k: LocalKind) -> LocalParent {
10147 match k {
10148 LocalKind::Alpha => LocalParent {
10149 alpha: Some(11),
10150 ..Default::default()
10151 },
10152 LocalKind::Beta => LocalParent {
10153 beta: Some(22),
10154 ..Default::default()
10155 },
10156 LocalKind::Gamma => LocalParent {
10157 gamma: Some(33),
10158 ..Default::default()
10159 },
10160 }
10161 }
10162 assert_variant_round_trip::<LocalParent, _>(make_local);
10163 }
10164
10165 /// The testkit primitive is a `#[track_caller]` compound-lift: a
10166 /// factory that fails to populate the addressed slot fails at the
10167 /// caller's site with a labeled panic message, not silently. Pin
10168 /// the failing case with a deliberately empty parent factory so a
10169 /// regression that drops the "select must return Some" check
10170 /// fails-loudly here — the missing-slot arm is the substrate
10171 /// primitive's first failure mode.
10172 #[test]
10173 #[should_panic(expected = "VariantSelector::select must return Some for populated slot")]
10174 fn assert_variant_round_trip_rejects_factory_that_leaves_slot_empty() {
10175 // Factory that returns an all-empty parent regardless of k —
10176 // every `k.select(&parent)` returns None, so the primitive
10177 // panics at the "must return Some" arm.
10178 fn empty_factory(_: LocalKind) -> LocalParent {
10179 LocalParent::default()
10180 }
10181 assert_variant_round_trip::<LocalParent, _>(empty_factory);
10182 }
10183
10184 // -------------------------------------------------------------------
10185 // `TaggedUnion::find` — the widened peer of `TaggedUnion::has` on the
10186 // presence-probe algebra. Pin every arm of the four-outcome truth
10187 // table (empty parent → None, populated-diagonal → Some(matching
10188 // borrow), populated-off-diagonal → None, two-populated → Some for
10189 // BOTH populated slots) directly on the sibling-shaped local scaffold
10190 // AND on the macro-emitted inherent surface. A regression on the
10191 // default body's `kind.select(self)` delegation (or on the emitted
10192 // inherent forwarder's `<Self as TaggedUnion>::find(self, kind)`
10193 // one-line body) fails here before it reaches any of the four
10194 // production sites.
10195 // -------------------------------------------------------------------
10196
10197 /// EMPTY-PARENT pin — a default [`LocalParent`] returns `None` at
10198 /// `find` for EVERY [`LocalKind`], sweeping `ClosedSet::ALL` so a
10199 /// new variant added without a matching arm in the primitive
10200 /// surfaces at rustc's exhaustiveness gate on the ALL literal
10201 /// rather than as a silent false-positive at every downstream
10202 /// consumer composing this primitive.
10203 #[test]
10204 fn tagged_union_default_find_returns_none_on_empty_parent_for_every_kind() {
10205 let empty = LocalParent::default();
10206 for kind in <LocalKind as tatara_closed_set::ClosedSet>::ALL
10207 .iter()
10208 .copied()
10209 {
10210 assert!(
10211 <LocalParent as TaggedUnion>::find(&empty, kind).is_none(),
10212 "empty parent must return None at find for {kind:?}",
10213 );
10214 }
10215 }
10216
10217 /// DELEGATION pin — every populated position across
10218 /// [`LocalKind::ALL`] returns `Some(matching-borrow)` at `find`,
10219 /// AND the returned borrowed view carries the SAME reference as
10220 /// `probed.select(&parent).unwrap()` (byte-identical delegation:
10221 /// `find` IS `kind.select(self)`, not a re-projection).
10222 /// Composition-law pin: `has(k) == find(k).is_some()` on both
10223 /// diagonal (populated slot AND matching Kind → true) and
10224 /// off-diagonal (populated slot BUT other Kind → false).
10225 #[test]
10226 fn tagged_union_default_find_delegates_to_select_across_every_kind() {
10227 for populated in <LocalKind as tatara_closed_set::ClosedSet>::ALL
10228 .iter()
10229 .copied()
10230 {
10231 let parent = match populated {
10232 LocalKind::Alpha => LocalParent {
10233 alpha: Some(101),
10234 ..Default::default()
10235 },
10236 LocalKind::Beta => LocalParent {
10237 beta: Some(202),
10238 ..Default::default()
10239 },
10240 LocalKind::Gamma => LocalParent {
10241 gamma: Some(303),
10242 ..Default::default()
10243 },
10244 };
10245 for probed in <LocalKind as tatara_closed_set::ClosedSet>::ALL
10246 .iter()
10247 .copied()
10248 {
10249 let via_find = <LocalParent as TaggedUnion>::find(&parent, probed);
10250 let via_select = probed.select(&parent);
10251 assert_eq!(
10252 via_find.is_some(),
10253 via_select.is_some(),
10254 "find drifted from select — populated={populated:?} probed={probed:?}",
10255 );
10256 assert_eq!(
10257 parent.has(probed),
10258 via_find.is_some(),
10259 "has drifted from find(k).is_some() — populated={populated:?} probed={probed:?}",
10260 );
10261 if let Some(v) = via_find {
10262 assert_eq!(
10263 <LocalVariant<'_> as VariantKind<LocalKind>>::variant_kind(&v),
10264 probed,
10265 "find→variant_kind round-trip failed — populated={populated:?} probed={probed:?}",
10266 );
10267 // Populated iff probed == populated (single-slot
10268 // parent) — off-diagonal arms return None above
10269 // and never reach this Some-branch.
10270 assert_eq!(
10271 probed, populated,
10272 "off-diagonal probe should have returned None at find",
10273 );
10274 }
10275 }
10276 }
10277 }
10278
10279 /// TWO-POPULATED pin — a parent with two populated slots returns
10280 /// `Some(matching-borrow)` at `find` for BOTH populated Kinds
10281 /// (unlike `variant()` which resolves to `Ambiguous`), and `None`
10282 /// for the empty third Kind. Locks the presence-probe axis of the
10283 /// widened primitive against a regression that inlined the
10284 /// resolver's short-circuit body into `find` (silently narrowing
10285 /// two populated to Ambiguous instead of a per-slot borrow).
10286 #[test]
10287 fn tagged_union_default_find_projects_per_slot_on_multi_populated_parent() {
10288 let parent = LocalParent {
10289 alpha: Some(1),
10290 beta: Some(2),
10291 gamma: None,
10292 };
10293 assert!(
10294 <LocalParent as TaggedUnion>::find(&parent, LocalKind::Alpha).is_some(),
10295 "find must project Alpha slot in a two-populated parent",
10296 );
10297 assert!(
10298 <LocalParent as TaggedUnion>::find(&parent, LocalKind::Beta).is_some(),
10299 "find must project Beta slot in a two-populated parent",
10300 );
10301 assert!(
10302 <LocalParent as TaggedUnion>::find(&parent, LocalKind::Gamma).is_none(),
10303 "find must return None for the empty Gamma slot",
10304 );
10305 }
10306
10307 /// `assert_find_agrees_with_has` testkit accepts the coherent
10308 /// local scaffold — sweeping every `(populated, probed)` pair
10309 /// through the three sub-assertions (find↔has, find↔select,
10310 /// diagonal round-trip). A regression on any of the three
10311 /// composition laws fails at the substrate primitive's
10312 /// `#[track_caller]` boundary here rather than at four per-parent
10313 /// production sites downstream.
10314 #[test]
10315 fn assert_find_agrees_with_has_accepts_coherent_local_impl() {
10316 fn make_local(k: LocalKind) -> LocalParent {
10317 match k {
10318 LocalKind::Alpha => LocalParent {
10319 alpha: Some(11),
10320 ..Default::default()
10321 },
10322 LocalKind::Beta => LocalParent {
10323 beta: Some(22),
10324 ..Default::default()
10325 },
10326 LocalKind::Gamma => LocalParent {
10327 gamma: Some(33),
10328 ..Default::default()
10329 },
10330 }
10331 }
10332 assert_find_agrees_with_has::<LocalParent, _>(make_local);
10333 }
10334
10335 // -------------------------------------------------------------------
10336 // `TaggedUnion::populated_kinds` default method + the
10337 // closed-set-inversion refinement's per-parent semantics — pin the
10338 // three arms (empty parent → empty vec, single-slot → vec![k],
10339 // multi-populated → vec[a..b] in ClosedSet::ALL order) directly on
10340 // the sibling-shaped `LocalParent` scaffold. Peer of the boundary-
10341 // side `ConditionSliceExt::distinct_kinds` primitive's three-arm
10342 // pin on the slice-level presence-probe axis.
10343 // -------------------------------------------------------------------
10344
10345 /// EMPTY parent — the default body's `ALL.filter(has).collect()`
10346 /// sweep yields an empty vec when no slot is populated. Pins the
10347 /// zero-cardinality arm: a regression that mis-composed the
10348 /// `ALL.iter()` bridge (short-circuiting past the empty case),
10349 /// returned a non-empty sentinel on empty input, or leaked stale
10350 /// closed-set entries as false-positive members fails HERE at the
10351 /// substrate boundary.
10352 #[test]
10353 fn tagged_union_default_populated_kinds_returns_empty_vec_on_empty_parent() {
10354 let empty = LocalParent::default();
10355 assert!(
10356 <LocalParent as TaggedUnion>::populated_kinds(&empty).is_empty(),
10357 "populated_kinds() must return empty Vec when no slot is populated",
10358 );
10359 }
10360
10361 /// SINGLE-SLOT parent — the default body sweeps `ClosedSet::ALL`
10362 /// with `has(k)` and collects the singleton `[k]` for each
10363 /// single-populated arrangement. Pins the length-1 arm's
10364 /// cardinality (must be exactly 1) AND ordering (the addressed
10365 /// kind's own position in `ClosedSet::ALL`) at ONE `assert_eq!`
10366 /// per kind — a regression that projected the wrong Kind, drifted
10367 /// the walk from `has` to a divergent projection, or paired two
10368 /// kinds together on a single-slot input fails HERE per addressed
10369 /// kind. Sweeps every `LocalKind::ALL` entry so no per-variant
10370 /// specialization can silently drop the check.
10371 #[test]
10372 fn tagged_union_default_populated_kinds_returns_single_element_vec_per_variant() {
10373 for populated in <LocalKind as tatara_closed_set::ClosedSet>::ALL
10374 .iter()
10375 .copied()
10376 {
10377 let parent = match populated {
10378 LocalKind::Alpha => LocalParent {
10379 alpha: Some(11),
10380 ..Default::default()
10381 },
10382 LocalKind::Beta => LocalParent {
10383 beta: Some(22),
10384 ..Default::default()
10385 },
10386 LocalKind::Gamma => LocalParent {
10387 gamma: Some(33),
10388 ..Default::default()
10389 },
10390 };
10391 assert_eq!(
10392 <LocalParent as TaggedUnion>::populated_kinds(&parent),
10393 vec![populated],
10394 "single-slot parent must return exactly [{populated:?}] on populated_kinds",
10395 );
10396 }
10397 }
10398
10399 /// MULTI-POPULATED parent — the default body yields the canonical
10400 /// `ClosedSet::ALL`-ordered pair `[Alpha, Beta]` for a two-slot
10401 /// arrangement populated in the CONSTRUCTION order `(Beta, Alpha)`.
10402 /// Pins the walk order arm: a regression that yielded slot-
10403 /// construction-order (`[Beta, Alpha]`) instead of canonical
10404 /// `ALL`-order fails HERE at the equality assert. Also pins the
10405 /// non-short-circuiting arm — a regression that inlined the
10406 /// resolver's short-circuit body into `populated_kinds` (silently
10407 /// narrowing two populated to a length-1 vec containing the first
10408 /// slot) fails at the length side of the equality.
10409 #[test]
10410 fn tagged_union_default_populated_kinds_walks_canonical_all_order_on_multi_populated_parent() {
10411 let parent = LocalParent {
10412 alpha: Some(1),
10413 beta: Some(2),
10414 gamma: None,
10415 };
10416 assert_eq!(
10417 <LocalParent as TaggedUnion>::populated_kinds(&parent),
10418 vec![LocalKind::Alpha, LocalKind::Beta],
10419 "multi-populated parent must return canonical ClosedSet::ALL-ordered kinds",
10420 );
10421 }
10422
10423 /// SATURATED parent — every slot populated returns
10424 /// `LocalKind::ALL.to_vec()` exactly. Pins the full-closed-set-
10425 /// coverage arm: a `[1..]` or `[..ALL.len() - 1]` walk bug that
10426 /// silently truncated the swept range at either end surfaces at
10427 /// the equality assert here.
10428 #[test]
10429 fn tagged_union_default_populated_kinds_covers_full_closed_set_on_saturated_parent() {
10430 let saturated = LocalParent {
10431 alpha: Some(1),
10432 beta: Some(2),
10433 gamma: Some(3),
10434 };
10435 assert_eq!(
10436 <LocalParent as TaggedUnion>::populated_kinds(&saturated),
10437 <LocalKind as tatara_closed_set::ClosedSet>::ALL.to_vec(),
10438 "saturated parent must return ClosedSet::ALL.to_vec() on populated_kinds",
10439 );
10440 }
10441
10442 /// `assert_populated_kinds_matches_has` testkit accepts the
10443 /// coherent local scaffold — sweeping every `(populated, probed)`
10444 /// pair through the three sub-assertions (per-kind membership,
10445 /// canonical `ALL`-filter equality, single-slot diagonal). A
10446 /// regression on any of the three composition laws fails at the
10447 /// substrate primitive's `#[track_caller]` boundary here rather
10448 /// than at four per-parent production sites downstream.
10449 #[test]
10450 fn assert_populated_kinds_matches_has_accepts_coherent_local_impl() {
10451 fn make_local(k: LocalKind) -> LocalParent {
10452 match k {
10453 LocalKind::Alpha => LocalParent {
10454 alpha: Some(11),
10455 ..Default::default()
10456 },
10457 LocalKind::Beta => LocalParent {
10458 beta: Some(22),
10459 ..Default::default()
10460 },
10461 LocalKind::Gamma => LocalParent {
10462 gamma: Some(33),
10463 ..Default::default()
10464 },
10465 }
10466 }
10467 assert_populated_kinds_matches_has::<LocalParent, _>(make_local);
10468 }
10469
10470 /// A factory that yields an all-empty parent (so
10471 /// `populated_kinds()` returns `[]`) MUST fail-loudly at the
10472 /// caller's site through the primitive's single-slot diagonal
10473 /// arm — the empty vec does not equal `vec![populated]` for the
10474 /// swept `populated` kind. Pin the diagonal-arm failure mode so
10475 /// a regression that silently succeeded on an all-empty factory
10476 /// (e.g. the primitive was refactored to skip the diagonal
10477 /// assert on `kinds.is_empty()`) is caught here.
10478 #[test]
10479 #[should_panic(expected = "must return vec![Alpha] exactly")]
10480 fn assert_populated_kinds_matches_has_rejects_factory_that_populates_no_slots() {
10481 fn empty_factory(_: LocalKind) -> LocalParent {
10482 LocalParent::default()
10483 }
10484 assert_populated_kinds_matches_has::<LocalParent, _>(empty_factory);
10485 }
10486
10487 /// A factory that yields a two-slot parent (so
10488 /// `populated_kinds()` returns `[k1, k2]` for TWO populated
10489 /// slots on a supposedly single-slot factory) MUST fail-loudly at
10490 /// the caller's site through the primitive's single-slot diagonal
10491 /// arm — the length-2 vec does not equal `vec![populated]`. Pin
10492 /// the diagonal-arm cardinality failure mode so a regression that
10493 /// silently succeeded on a broken factory (populating both the
10494 /// addressed slot AND an extra one) is caught here.
10495 #[test]
10496 #[should_panic(expected = "must return vec![Alpha] exactly")]
10497 fn assert_populated_kinds_matches_has_rejects_factory_that_populates_extra_slot() {
10498 fn always_pair(k: LocalKind) -> LocalParent {
10499 let mut p = LocalParent {
10500 gamma: Some(99),
10501 ..Default::default()
10502 };
10503 match k {
10504 LocalKind::Alpha => p.alpha = Some(11),
10505 LocalKind::Beta => p.beta = Some(22),
10506 LocalKind::Gamma => p.gamma = Some(33),
10507 }
10508 p
10509 }
10510 assert_populated_kinds_matches_has::<LocalParent, _>(always_pair);
10511 }
10512
10513 /// The trait's default `iter_populated_kinds` body composes over
10514 /// [`ClosedSet::ALL`] under a positive `has` predicate WITHOUT
10515 /// materializing an intermediate `Vec` — pin the walk shape on
10516 /// the sibling-shaped scaffold at every arm of the exactly-one
10517 /// contract (empty, single-slot, two-slot, saturated) so a
10518 /// regression that inlined a divergent walk body at the trait's
10519 /// `iter_populated_kinds` default fails here rather than as
10520 /// silent drift at every downstream fold.
10521 #[test]
10522 fn tagged_union_default_iter_populated_kinds_folds_over_closed_set_all_arms() {
10523 // Empty — yields nothing.
10524 let empty = LocalParent::default();
10525 assert!(empty.iter_populated_kinds().next().is_none());
10526 assert_eq!(empty.iter_populated_kinds().count(), 0);
10527
10528 // Single-slot — yields exactly [populated] in canonical order.
10529 for populated in LocalKind::ALL.iter().copied() {
10530 let parent = match populated {
10531 LocalKind::Alpha => LocalParent {
10532 alpha: Some(11),
10533 ..Default::default()
10534 },
10535 LocalKind::Beta => LocalParent {
10536 beta: Some(22),
10537 ..Default::default()
10538 },
10539 LocalKind::Gamma => LocalParent {
10540 gamma: Some(33),
10541 ..Default::default()
10542 },
10543 };
10544 let walk: Vec<LocalKind> = parent.iter_populated_kinds().collect();
10545 assert_eq!(walk, vec![populated]);
10546 }
10547
10548 // Two-slot — yields both kinds in canonical `ClosedSet::ALL`
10549 // order, regardless of struct-field assignment order.
10550 let ab = LocalParent {
10551 alpha: Some(1),
10552 beta: Some(2),
10553 gamma: None,
10554 };
10555 assert_eq!(
10556 ab.iter_populated_kinds().collect::<Vec<_>>(),
10557 vec![LocalKind::Alpha, LocalKind::Beta],
10558 );
10559 let ag = LocalParent {
10560 alpha: Some(1),
10561 beta: None,
10562 gamma: Some(3),
10563 };
10564 assert_eq!(
10565 ag.iter_populated_kinds().collect::<Vec<_>>(),
10566 vec![LocalKind::Alpha, LocalKind::Gamma],
10567 );
10568 let bg = LocalParent {
10569 alpha: None,
10570 beta: Some(2),
10571 gamma: Some(3),
10572 };
10573 assert_eq!(
10574 bg.iter_populated_kinds().collect::<Vec<_>>(),
10575 vec![LocalKind::Beta, LocalKind::Gamma],
10576 );
10577
10578 // Saturated — yields every kind in `ClosedSet::ALL`.
10579 let saturated = LocalParent {
10580 alpha: Some(1),
10581 beta: Some(2),
10582 gamma: Some(3),
10583 };
10584 assert_eq!(
10585 saturated.iter_populated_kinds().collect::<Vec<_>>(),
10586 LocalKind::ALL.to_vec(),
10587 );
10588 }
10589
10590 /// [`TaggedUnion::populated_kinds`]'s default body IS
10591 /// `self.iter_populated_kinds().collect()`, so the composition
10592 /// law
10593 /// `populated_kinds() == iter_populated_kinds().collect::<Vec<_>>()`
10594 /// holds by construction across every closed-set arrangement.
10595 /// Pin the composition law directly on the sibling-shaped
10596 /// scaffold at every arm of the exactly-one contract so a
10597 /// regression that split the two peer bodies (specialized
10598 /// `populated_kinds` past its `.collect()` delegation, or
10599 /// specialized `iter_populated_kinds` past its `Kind::ALL`
10600 /// filter walk) fails at ONE substrate test rather than as
10601 /// silent drift at downstream folds.
10602 #[test]
10603 fn tagged_union_default_iter_populated_kinds_collect_matches_populated_kinds_vec() {
10604 let parents = [
10605 LocalParent::default(),
10606 LocalParent {
10607 alpha: Some(11),
10608 ..Default::default()
10609 },
10610 LocalParent {
10611 beta: Some(22),
10612 ..Default::default()
10613 },
10614 LocalParent {
10615 gamma: Some(33),
10616 ..Default::default()
10617 },
10618 LocalParent {
10619 alpha: Some(1),
10620 beta: Some(2),
10621 gamma: None,
10622 },
10623 LocalParent {
10624 alpha: Some(1),
10625 beta: Some(2),
10626 gamma: Some(3),
10627 },
10628 ];
10629 for parent in &parents {
10630 let via_iter: Vec<LocalKind> = parent.iter_populated_kinds().collect();
10631 let via_vec = parent.populated_kinds();
10632 assert_eq!(
10633 via_iter, via_vec,
10634 "iter_populated_kinds().collect() must match populated_kinds() byte-identically",
10635 );
10636 }
10637 }
10638
10639 /// `assert_iter_populated_kinds_matches_populated_kinds` testkit
10640 /// accepts the coherent local scaffold — sweeping every populated
10641 /// slot through the three sub-assertions (Vec-equality, iterator
10642 /// purity, single-slot diagonal). A regression on any of the
10643 /// three composition laws fails at the substrate primitive's
10644 /// `#[track_caller]` boundary here rather than at four per-parent
10645 /// production sites downstream.
10646 #[test]
10647 fn assert_iter_populated_kinds_matches_populated_kinds_accepts_coherent_local_impl() {
10648 fn make_local(k: LocalKind) -> LocalParent {
10649 match k {
10650 LocalKind::Alpha => LocalParent {
10651 alpha: Some(11),
10652 ..Default::default()
10653 },
10654 LocalKind::Beta => LocalParent {
10655 beta: Some(22),
10656 ..Default::default()
10657 },
10658 LocalKind::Gamma => LocalParent {
10659 gamma: Some(33),
10660 ..Default::default()
10661 },
10662 }
10663 }
10664 assert_iter_populated_kinds_matches_populated_kinds::<LocalParent, _>(make_local);
10665 }
10666
10667 /// `assert_populated_kinds_across_pairs` testkit accepts the
10668 /// coherent local scaffold — sweeping every off-diagonal `(a, b)`
10669 /// pair through the three sub-assertions (cardinality-2,
10670 /// per-kind membership, canonical `ALL`-filter equality). A
10671 /// regression on any of the three composition laws (or on the
10672 /// diagonal-skip) fails at the substrate primitive's
10673 /// `#[track_caller]` boundary here rather than at four per-parent
10674 /// production sites downstream.
10675 #[test]
10676 fn assert_populated_kinds_across_pairs_accepts_coherent_local_impl() {
10677 fn two_local(a: LocalKind, b: LocalKind) -> LocalParent {
10678 let mut p = LocalParent::default();
10679 for k in [a, b] {
10680 match k {
10681 LocalKind::Alpha => p.alpha = Some(11),
10682 LocalKind::Beta => p.beta = Some(22),
10683 LocalKind::Gamma => p.gamma = Some(33),
10684 }
10685 }
10686 p
10687 }
10688 assert_populated_kinds_across_pairs::<LocalParent, _>(two_local);
10689 }
10690
10691 /// A two-slot factory that yields a single-populated parent (so
10692 /// `populated_kinds()` returns `[k1]` for a two-slot input) MUST
10693 /// fail-loudly at the caller's site through the primitive's
10694 /// cardinality-2 arm — the length-1 vec does not satisfy
10695 /// `kinds.len() == 2`. Pin the cardinality-arm failure mode so a
10696 /// regression that silently succeeded on a broken factory
10697 /// (populating only the first of the two addressed slots) is
10698 /// caught here.
10699 #[test]
10700 #[should_panic(expected = "must return exactly two populated kinds")]
10701 fn assert_populated_kinds_across_pairs_rejects_factory_that_populates_only_one_slot() {
10702 fn single_only(a: LocalKind, _: LocalKind) -> LocalParent {
10703 let mut p = LocalParent::default();
10704 match a {
10705 LocalKind::Alpha => p.alpha = Some(11),
10706 LocalKind::Beta => p.beta = Some(22),
10707 LocalKind::Gamma => p.gamma = Some(33),
10708 }
10709 p
10710 }
10711 assert_populated_kinds_across_pairs::<LocalParent, _>(single_only);
10712 }
10713
10714 /// Every one of the four production `.variant()` sites on
10715 /// `ProcessSpec` binds through the single-slot closed-set-inversion
10716 /// primitive `assert_populated_kinds_matches_has` coherently — every
10717 /// per-site `single_slot_X(k)` factory produces a parent whose
10718 /// `populated_kinds()` equals `vec![k]` and whose per-kind
10719 /// composition law `populated_kinds().contains(&k) == has(k)` holds
10720 /// for every `k ∈ ClosedSet::ALL`. Sweep every production
10721 /// implementor at ONE substrate boundary so a regression that
10722 /// drifts a production site's `single_slot_X` factory OR the
10723 /// default `populated_kinds` body (a specialization that
10724 /// short-circuited, drifted the walk order, or returned duplicates)
10725 /// fails BOTH at any future per-crate test site AND at this
10726 /// substrate-wide sweep.
10727 #[test]
10728 fn every_production_tagged_union_binds_through_the_populated_kinds_testkit_primitive() {
10729 assert_populated_kinds_matches_has::<crate::intent::Intent, _>(single_slot_intent_probe);
10730 assert_populated_kinds_matches_has::<crate::encapsulates::EncapsulationKind, _>(
10731 single_slot_encapsulation_kind_probe,
10732 );
10733 assert_populated_kinds_matches_has::<crate::export::ArtifactSource, _>(
10734 single_slot_artifact_source_probe,
10735 );
10736 assert_populated_kinds_matches_has::<crate::export::VectorChannel, _>(
10737 single_slot_vector_channel_probe,
10738 );
10739 }
10740
10741 /// Peer of
10742 /// `every_production_tagged_union_binds_through_the_populated_kinds_testkit_primitive`
10743 /// on the two-slot ambiguous-parent side — every production
10744 /// `.variant()` parent binds through the pair primitive
10745 /// `assert_populated_kinds_across_pairs` coherently, so a
10746 /// regression that inlined the resolver's short-circuit body into
10747 /// `populated_kinds` on any production site (silently narrowing
10748 /// two populated slots to a length-1 vec) fails at ONE substrate
10749 /// boundary across all four parents.
10750 #[test]
10751 fn every_production_tagged_union_binds_through_the_populated_kinds_pair_testkit_primitive() {
10752 assert_populated_kinds_across_pairs::<crate::intent::Intent, _>(two_slot_intent_probe);
10753 assert_populated_kinds_across_pairs::<crate::encapsulates::EncapsulationKind, _>(
10754 two_slot_encapsulation_kind_probe,
10755 );
10756 assert_populated_kinds_across_pairs::<crate::export::ArtifactSource, _>(
10757 two_slot_artifact_source_probe,
10758 );
10759 assert_populated_kinds_across_pairs::<crate::export::VectorChannel, _>(
10760 two_slot_vector_channel_probe,
10761 );
10762 }
10763
10764 // -------------------------------------------------------------------
10765 // `TaggedUnion::populated_kind_count` — scalar cardinality refinement
10766 // on the closed-set-inversion axis. Pin the three arms (empty parent
10767 // → 0, single-slot → 1, multi-populated → N) directly on the sibling-
10768 // shaped `LocalParent` scaffold and the composition law
10769 // `populated_kind_count() == populated_kinds().len()` at the substrate
10770 // testkit `assert_populated_kind_count_matches_populated_kinds`. Peer
10771 // of the widened primitive `populated_kinds` (see the block above);
10772 // the scalar projection collapses the widened Vec to its length
10773 // without allocating.
10774 // -------------------------------------------------------------------
10775
10776 /// EMPTY parent — the default body's `ALL.filter(has).count()`
10777 /// sweep yields `0` when no slot is populated. Pins the zero-
10778 /// cardinality arm: a regression that mis-composed the
10779 /// `ALL.iter()` bridge (short-circuiting past the empty case),
10780 /// returned a non-zero sentinel on empty input, or leaked stale
10781 /// closed-set entries as false-positive members fails HERE at the
10782 /// substrate boundary.
10783 #[test]
10784 fn tagged_union_default_populated_kind_count_returns_zero_on_empty_parent() {
10785 let empty = LocalParent::default();
10786 assert_eq!(
10787 <LocalParent as TaggedUnion>::populated_kind_count(&empty),
10788 0,
10789 "populated_kind_count() must return 0 when no slot is populated",
10790 );
10791 }
10792
10793 /// SINGLE-SLOT parent — the default body sweeps `ClosedSet::ALL`
10794 /// with `has(k)` and counts the singleton `1` for each single-
10795 /// populated arrangement. Pins the length-1 arm's cardinality at
10796 /// ONE `assert_eq!` per kind — a regression that projected the
10797 /// wrong Kind, drifted the walk from `has` to a divergent
10798 /// projection, or paired two kinds together on a single-slot input
10799 /// fails HERE per addressed kind. Sweeps every `LocalKind::ALL`
10800 /// entry so no per-variant specialization can silently drop the
10801 /// check.
10802 #[test]
10803 fn tagged_union_default_populated_kind_count_returns_one_per_single_slot_variant() {
10804 for populated in <LocalKind as tatara_closed_set::ClosedSet>::ALL
10805 .iter()
10806 .copied()
10807 {
10808 let parent = match populated {
10809 LocalKind::Alpha => LocalParent {
10810 alpha: Some(11),
10811 ..Default::default()
10812 },
10813 LocalKind::Beta => LocalParent {
10814 beta: Some(22),
10815 ..Default::default()
10816 },
10817 LocalKind::Gamma => LocalParent {
10818 gamma: Some(33),
10819 ..Default::default()
10820 },
10821 };
10822 assert_eq!(
10823 <LocalParent as TaggedUnion>::populated_kind_count(&parent),
10824 1,
10825 "single-slot parent must return 1 on populated_kind_count for {populated:?}",
10826 );
10827 }
10828 }
10829
10830 /// MULTI-POPULATED parent — the default body yields `2` for a two-
10831 /// slot arrangement, `3` for a fully-saturated three-slot parent.
10832 /// Pins the non-short-circuiting arm — a regression that inlined
10833 /// the resolver's short-circuit body into `populated_kind_count`
10834 /// (silently narrowing two populated to `1`) fails HERE at the
10835 /// equality assert.
10836 #[test]
10837 fn tagged_union_default_populated_kind_count_walks_full_closed_set_on_multi_populated_parent() {
10838 let two = LocalParent {
10839 alpha: Some(1),
10840 beta: Some(2),
10841 gamma: None,
10842 };
10843 assert_eq!(
10844 <LocalParent as TaggedUnion>::populated_kind_count(&two),
10845 2,
10846 "two-populated parent must return 2 on populated_kind_count",
10847 );
10848 let saturated = LocalParent {
10849 alpha: Some(1),
10850 beta: Some(2),
10851 gamma: Some(3),
10852 };
10853 assert_eq!(
10854 <LocalParent as TaggedUnion>::populated_kind_count(&saturated),
10855 3,
10856 "saturated parent must return LocalKind::ALL.len() on populated_kind_count",
10857 );
10858 }
10859
10860 /// Composition law `populated_kind_count() == populated_kinds().len()`
10861 /// binds the scalar cardinality projection to the widened primitive
10862 /// across every `ClosedSet::ALL × {empty, single_slot, two_slot,
10863 /// saturated}` combination. Pins the byte-identity of the two
10864 /// projections on the empty / single / multi / saturated arms — a
10865 /// regression that overrode `populated_kind_count` with an
10866 /// off-by-one walk, a `find(k).is_none()`-inverted body (returning
10867 /// the ABSENT count), or a divergent short-circuit fails HERE at
10868 /// the equality assert.
10869 #[test]
10870 fn tagged_union_default_populated_kind_count_matches_populated_kinds_len() {
10871 let arrangements: [LocalParent; 4] = [
10872 LocalParent::default(),
10873 LocalParent {
10874 alpha: Some(1),
10875 ..Default::default()
10876 },
10877 LocalParent {
10878 alpha: Some(1),
10879 beta: Some(2),
10880 gamma: None,
10881 },
10882 LocalParent {
10883 alpha: Some(1),
10884 beta: Some(2),
10885 gamma: Some(3),
10886 },
10887 ];
10888 for (idx, parent) in arrangements.iter().enumerate() {
10889 assert_eq!(
10890 <LocalParent as TaggedUnion>::populated_kind_count(parent),
10891 <LocalParent as TaggedUnion>::populated_kinds(parent).len(),
10892 "populated_kind_count() must equal populated_kinds().len() for arrangement idx {idx}",
10893 );
10894 }
10895 }
10896
10897 /// `assert_populated_kind_count_matches_populated_kinds` testkit
10898 /// accepts the coherent local scaffold — sweeping every populated
10899 /// kind through the two sub-assertions (composition law
10900 /// `count == kinds.len()` + single-slot diagonal `count == 1`). A
10901 /// regression on either composition law fails at the substrate
10902 /// primitive's `#[track_caller]` boundary here rather than at four
10903 /// per-parent production sites downstream.
10904 #[test]
10905 fn assert_populated_kind_count_matches_populated_kinds_accepts_coherent_local_impl() {
10906 fn make_local(k: LocalKind) -> LocalParent {
10907 match k {
10908 LocalKind::Alpha => LocalParent {
10909 alpha: Some(11),
10910 ..Default::default()
10911 },
10912 LocalKind::Beta => LocalParent {
10913 beta: Some(22),
10914 ..Default::default()
10915 },
10916 LocalKind::Gamma => LocalParent {
10917 gamma: Some(33),
10918 ..Default::default()
10919 },
10920 }
10921 }
10922 assert_populated_kind_count_matches_populated_kinds::<LocalParent, _>(make_local);
10923 }
10924
10925 /// A factory that yields an all-empty parent (so
10926 /// `populated_kind_count()` returns `0`) MUST fail-loudly at the
10927 /// caller's site through the primitive's single-slot diagonal arm
10928 /// — the `0` cardinality does not satisfy `count == 1` on the
10929 /// swept `populated` kind. Pin the diagonal-arm failure mode so a
10930 /// regression that silently succeeded on an all-empty factory
10931 /// (e.g. the primitive was refactored to skip the diagonal assert
10932 /// on `count == 0`) is caught here.
10933 #[test]
10934 #[should_panic(expected = "must equal 1 exactly (well-formed arm cardinality)")]
10935 fn assert_populated_kind_count_matches_populated_kinds_rejects_empty_factory() {
10936 fn empty_factory(_: LocalKind) -> LocalParent {
10937 LocalParent::default()
10938 }
10939 assert_populated_kind_count_matches_populated_kinds::<LocalParent, _>(empty_factory);
10940 }
10941
10942 /// A factory that yields a two-slot parent (so
10943 /// `populated_kind_count()` returns `2` on a supposedly single-slot
10944 /// factory) MUST fail-loudly at the caller's site through the
10945 /// primitive's single-slot diagonal arm — the `2` cardinality does
10946 /// not satisfy `count == 1`. Pin the diagonal-arm cardinality
10947 /// failure mode so a regression that silently succeeded on a
10948 /// broken factory (populating both the addressed slot AND an extra
10949 /// one) is caught here.
10950 #[test]
10951 #[should_panic(expected = "must equal 1 exactly (well-formed arm cardinality)")]
10952 fn assert_populated_kind_count_matches_populated_kinds_rejects_two_slot_factory() {
10953 fn always_pair(k: LocalKind) -> LocalParent {
10954 let mut p = LocalParent {
10955 gamma: Some(99),
10956 ..Default::default()
10957 };
10958 match k {
10959 LocalKind::Alpha => p.alpha = Some(11),
10960 LocalKind::Beta => p.beta = Some(22),
10961 LocalKind::Gamma => p.gamma = Some(33),
10962 }
10963 p
10964 }
10965 assert_populated_kind_count_matches_populated_kinds::<LocalParent, _>(always_pair);
10966 }
10967
10968 /// Every one of the four production `.variant()` sites on
10969 /// `ProcessSpec` binds through the scalar-cardinality primitive
10970 /// `assert_populated_kind_count_matches_populated_kinds` coherently
10971 /// — every per-site `single_slot_X(k)` factory produces a parent
10972 /// whose `populated_kind_count()` equals `1` AND whose composition
10973 /// law `count == populated_kinds().len()` holds. Sweep every
10974 /// production implementor at ONE substrate boundary so a regression
10975 /// that drifts a production site's `single_slot_X` factory OR the
10976 /// default `populated_kind_count` body (a specialization that
10977 /// short-circuited, drifted the walk order, or double-counted a
10978 /// slot) fails BOTH at any future per-crate test site AND at this
10979 /// substrate-wide sweep.
10980 #[test]
10981 fn every_production_tagged_union_binds_through_the_populated_kind_count_testkit_primitive() {
10982 assert_populated_kind_count_matches_populated_kinds::<crate::intent::Intent, _>(
10983 single_slot_intent_probe,
10984 );
10985 assert_populated_kind_count_matches_populated_kinds::<
10986 crate::encapsulates::EncapsulationKind,
10987 _,
10988 >(single_slot_encapsulation_kind_probe);
10989 assert_populated_kind_count_matches_populated_kinds::<crate::export::ArtifactSource, _>(
10990 single_slot_artifact_source_probe,
10991 );
10992 assert_populated_kind_count_matches_populated_kinds::<crate::export::VectorChannel, _>(
10993 single_slot_vector_channel_probe,
10994 );
10995 }
10996
10997 // -------------------------------------------------------------------
10998 // `TaggedUnion::missing_kinds` default method + the
10999 // closed-set-COMPLEMENT refinement's per-parent semantics — pin the
11000 // three arms (empty parent → full closed set, single-slot → ALL \
11001 // {k} in canonical order, saturated → empty vec) directly on the
11002 // sibling-shaped `LocalParent` scaffold. Peer of the boundary-side
11003 // `ConditionSliceExt::missing_kinds` primitive's three-arm pin on
11004 // the slice-level presence-probe axis; closed-set-COMPLEMENT peer
11005 // of the parent-level `populated_kinds` primitive above.
11006 // -------------------------------------------------------------------
11007
11008 /// EMPTY parent — the default body's `ALL.filter(!has).collect()`
11009 /// sweep yields the FULL `ClosedSet::ALL` vec when no slot is
11010 /// populated (every kind is missing). Pins the full-cardinality
11011 /// arm: a regression that mis-composed the `ALL.iter()` bridge
11012 /// (short-circuiting past the empty case), inverted the negation
11013 /// (returning `populated_kinds`), or dropped closed-set entries as
11014 /// false-negative absences fails HERE at the substrate boundary.
11015 #[test]
11016 fn tagged_union_default_missing_kinds_returns_full_closed_set_on_empty_parent() {
11017 let empty = LocalParent::default();
11018 assert_eq!(
11019 <LocalParent as TaggedUnion>::missing_kinds(&empty),
11020 <LocalKind as tatara_closed_set::ClosedSet>::ALL.to_vec(),
11021 "missing_kinds() must return ClosedSet::ALL when no slot is populated",
11022 );
11023 }
11024
11025 /// SINGLE-SLOT parent — the default body sweeps `ClosedSet::ALL`
11026 /// with `!has(k)` and collects `ALL \ {populated}` for each
11027 /// single-populated arrangement. Pins the length-(ALL.len()-1)
11028 /// arm's cardinality AND ordering (canonical `ClosedSet::ALL`
11029 /// order, `populated` absent) at ONE `assert_eq!` per kind — a
11030 /// regression that inverted the negation (returning `vec![populated]`
11031 /// instead of `ALL \ {populated}`) fails HERE per addressed kind.
11032 #[test]
11033 fn tagged_union_default_missing_kinds_returns_complement_per_variant() {
11034 for populated in <LocalKind as tatara_closed_set::ClosedSet>::ALL
11035 .iter()
11036 .copied()
11037 {
11038 let parent = match populated {
11039 LocalKind::Alpha => LocalParent {
11040 alpha: Some(11),
11041 ..Default::default()
11042 },
11043 LocalKind::Beta => LocalParent {
11044 beta: Some(22),
11045 ..Default::default()
11046 },
11047 LocalKind::Gamma => LocalParent {
11048 gamma: Some(33),
11049 ..Default::default()
11050 },
11051 };
11052 let expected: Vec<LocalKind> = <LocalKind as tatara_closed_set::ClosedSet>::ALL
11053 .iter()
11054 .copied()
11055 .filter(|k| *k != populated)
11056 .collect();
11057 assert_eq!(
11058 <LocalParent as TaggedUnion>::missing_kinds(&parent),
11059 expected,
11060 "single-slot parent must return ClosedSet::ALL \\ {{{populated:?}}} on missing_kinds",
11061 );
11062 }
11063 }
11064
11065 /// SATURATED parent — every slot populated returns an empty vec on
11066 /// `missing_kinds`. Pins the zero-cardinality arm on the complement
11067 /// side (mirror of `populated_kinds` returning `ALL.to_vec()` on
11068 /// the saturated arm).
11069 #[test]
11070 fn tagged_union_default_missing_kinds_returns_empty_vec_on_saturated_parent() {
11071 let saturated = LocalParent {
11072 alpha: Some(1),
11073 beta: Some(2),
11074 gamma: Some(3),
11075 };
11076 assert!(
11077 <LocalParent as TaggedUnion>::missing_kinds(&saturated).is_empty(),
11078 "saturated parent must return empty Vec on missing_kinds",
11079 );
11080 }
11081
11082 /// Partition law binding `populated_kinds` and `missing_kinds` on
11083 /// every `LocalParent` arrangement: every `k ∈ ClosedSet::ALL`
11084 /// lives on EXACTLY ONE side of the partition (populated OR
11085 /// missing, never both, never neither). Pins the compound-lift's
11086 /// most-load-bearing invariant at ONE `assert!` per (arrangement,
11087 /// kind) pair — a regression that returned overlapping or
11088 /// disjoint-but-incomplete sets fails HERE at the XOR arm.
11089 #[test]
11090 fn tagged_union_default_populated_kinds_and_missing_kinds_partition_the_closed_set() {
11091 let arrangements: [LocalParent; 4] = [
11092 LocalParent::default(),
11093 LocalParent {
11094 alpha: Some(1),
11095 ..Default::default()
11096 },
11097 LocalParent {
11098 alpha: Some(1),
11099 beta: Some(2),
11100 gamma: None,
11101 },
11102 LocalParent {
11103 alpha: Some(1),
11104 beta: Some(2),
11105 gamma: Some(3),
11106 },
11107 ];
11108 for (idx, parent) in arrangements.iter().enumerate() {
11109 let populated = <LocalParent as TaggedUnion>::populated_kinds(parent);
11110 let missing = <LocalParent as TaggedUnion>::missing_kinds(parent);
11111 for &k in <LocalKind as tatara_closed_set::ClosedSet>::ALL.iter() {
11112 let in_populated = populated.contains(&k);
11113 let in_missing = missing.contains(&k);
11114 assert!(
11115 in_populated ^ in_missing,
11116 "arrangement idx {idx} — {k:?} must live on exactly one side of (populated, missing), got in_populated={in_populated} in_missing={in_missing}",
11117 );
11118 }
11119 }
11120 }
11121
11122 /// `assert_missing_kinds_matches_has` testkit accepts the coherent
11123 /// local scaffold — sweeping every populated slot through the
11124 /// per-kind negation + canonical `ALL`-filter + single-slot
11125 /// diagonal + XOR partition arms. A regression on any of the four
11126 /// composition laws fails at the substrate primitive's
11127 /// `#[track_caller]` boundary here rather than at four per-parent
11128 /// production sites downstream.
11129 #[test]
11130 fn assert_missing_kinds_matches_has_accepts_coherent_local_impl() {
11131 fn make_local(k: LocalKind) -> LocalParent {
11132 match k {
11133 LocalKind::Alpha => LocalParent {
11134 alpha: Some(11),
11135 ..Default::default()
11136 },
11137 LocalKind::Beta => LocalParent {
11138 beta: Some(22),
11139 ..Default::default()
11140 },
11141 LocalKind::Gamma => LocalParent {
11142 gamma: Some(33),
11143 ..Default::default()
11144 },
11145 }
11146 }
11147 assert_missing_kinds_matches_has::<LocalParent, _>(make_local);
11148 }
11149
11150 /// A factory that yields an all-empty parent MUST fail-loudly at
11151 /// the caller's site through the primitive's single-slot diagonal
11152 /// arm — the full `ALL` vec (every kind missing) does not equal
11153 /// `ALL \ {populated}` (which excludes `populated`). Pin the
11154 /// diagonal-arm failure mode so a regression that silently
11155 /// succeeded on an all-empty factory is caught here.
11156 #[test]
11157 #[should_panic(expected = "must return ClosedSet::ALL with Alpha removed")]
11158 fn assert_missing_kinds_matches_has_rejects_factory_that_populates_no_slots() {
11159 fn empty_factory(_: LocalKind) -> LocalParent {
11160 LocalParent::default()
11161 }
11162 assert_missing_kinds_matches_has::<LocalParent, _>(empty_factory);
11163 }
11164
11165 /// The trait's default `iter_missing_kinds` body composes over
11166 /// [`ClosedSet::ALL`] under a NEGATED `has` predicate WITHOUT
11167 /// materializing an intermediate `Vec` — pin the walk shape on
11168 /// the sibling-shaped scaffold at every arm of the exactly-one
11169 /// contract (empty → full ALL, single-slot → ALL\\{k}, two-slot
11170 /// → ALL\\{a,b}, saturated → empty). Complement-side peer of
11171 /// [`tagged_union_default_iter_populated_kinds_folds_over_closed_set_all_arms`].
11172 #[test]
11173 fn tagged_union_default_iter_missing_kinds_folds_over_closed_set_all_arms() {
11174 // Empty parent — every slot missing, yields every ALL entry.
11175 let empty = LocalParent::default();
11176 assert_eq!(
11177 empty.iter_missing_kinds().collect::<Vec<_>>(),
11178 LocalKind::ALL.to_vec(),
11179 );
11180
11181 // Single-slot — yields ALL\\{populated} in canonical order.
11182 for populated in LocalKind::ALL.iter().copied() {
11183 let parent = match populated {
11184 LocalKind::Alpha => LocalParent {
11185 alpha: Some(11),
11186 ..Default::default()
11187 },
11188 LocalKind::Beta => LocalParent {
11189 beta: Some(22),
11190 ..Default::default()
11191 },
11192 LocalKind::Gamma => LocalParent {
11193 gamma: Some(33),
11194 ..Default::default()
11195 },
11196 };
11197 let expected: Vec<LocalKind> = LocalKind::ALL
11198 .iter()
11199 .copied()
11200 .filter(|&k| k != populated)
11201 .collect();
11202 assert_eq!(parent.iter_missing_kinds().collect::<Vec<_>>(), expected);
11203 }
11204
11205 // Two-slot — yields the single remaining slot.
11206 let ab = LocalParent {
11207 alpha: Some(1),
11208 beta: Some(2),
11209 gamma: None,
11210 };
11211 assert_eq!(
11212 ab.iter_missing_kinds().collect::<Vec<_>>(),
11213 vec![LocalKind::Gamma],
11214 );
11215
11216 // Saturated — yields nothing.
11217 let saturated = LocalParent {
11218 alpha: Some(1),
11219 beta: Some(2),
11220 gamma: Some(3),
11221 };
11222 assert!(saturated.iter_missing_kinds().next().is_none());
11223 }
11224
11225 /// [`TaggedUnion::missing_kinds`]'s default body IS
11226 /// `self.iter_missing_kinds().collect()`, so the composition law
11227 /// `missing_kinds() == iter_missing_kinds().collect::<Vec<_>>()`
11228 /// holds by construction across every closed-set arrangement.
11229 /// Complement-side peer of
11230 /// [`tagged_union_default_iter_populated_kinds_collect_matches_populated_kinds_vec`].
11231 #[test]
11232 fn tagged_union_default_iter_missing_kinds_collect_matches_missing_kinds_vec() {
11233 let parents = [
11234 LocalParent::default(),
11235 LocalParent {
11236 alpha: Some(11),
11237 ..Default::default()
11238 },
11239 LocalParent {
11240 beta: Some(22),
11241 ..Default::default()
11242 },
11243 LocalParent {
11244 alpha: Some(1),
11245 beta: Some(2),
11246 gamma: None,
11247 },
11248 LocalParent {
11249 alpha: Some(1),
11250 beta: Some(2),
11251 gamma: Some(3),
11252 },
11253 ];
11254 for parent in &parents {
11255 let via_iter: Vec<LocalKind> = parent.iter_missing_kinds().collect();
11256 let via_vec = parent.missing_kinds();
11257 assert_eq!(
11258 via_iter, via_vec,
11259 "iter_missing_kinds().collect() must match missing_kinds() byte-identically",
11260 );
11261 }
11262 }
11263
11264 /// `assert_iter_missing_kinds_matches_missing_kinds` testkit
11265 /// accepts the coherent local scaffold — sweeping every populated
11266 /// slot through the three sub-assertions (Vec-equality, iterator
11267 /// purity, single-slot diagonal). Complement-side peer of
11268 /// [`assert_iter_populated_kinds_matches_populated_kinds_accepts_coherent_local_impl`].
11269 #[test]
11270 fn assert_iter_missing_kinds_matches_missing_kinds_accepts_coherent_local_impl() {
11271 fn make_local(k: LocalKind) -> LocalParent {
11272 match k {
11273 LocalKind::Alpha => LocalParent {
11274 alpha: Some(11),
11275 ..Default::default()
11276 },
11277 LocalKind::Beta => LocalParent {
11278 beta: Some(22),
11279 ..Default::default()
11280 },
11281 LocalKind::Gamma => LocalParent {
11282 gamma: Some(33),
11283 ..Default::default()
11284 },
11285 }
11286 }
11287 assert_iter_missing_kinds_matches_missing_kinds::<LocalParent, _>(make_local);
11288 }
11289
11290 /// Every one of the four production `.variant()` sites on
11291 /// `ProcessSpec` binds through the single-slot closed-set-complement
11292 /// primitive `assert_missing_kinds_matches_has` coherently — every
11293 /// per-site `single_slot_X(k)` factory produces a parent whose
11294 /// `missing_kinds()` equals `ALL \ {k}` and whose per-kind
11295 /// negation composition law `missing_kinds().contains(&k) == !has(k)`
11296 /// holds for every `k ∈ ClosedSet::ALL`, AND the XOR partition law
11297 /// with `populated_kinds` binds byte-identically at every closed-
11298 /// set entry. Sweep every production implementor at ONE substrate
11299 /// boundary so a regression that drifts a production site's
11300 /// `single_slot_X` factory OR the default `missing_kinds` body (a
11301 /// specialization that inverted the negation, short-circuited, or
11302 /// drifted the walk order) fails BOTH at any future per-crate test
11303 /// site AND at this substrate-wide sweep.
11304 #[test]
11305 fn every_production_tagged_union_binds_through_the_missing_kinds_testkit_primitive() {
11306 assert_missing_kinds_matches_has::<crate::intent::Intent, _>(single_slot_intent_probe);
11307 assert_missing_kinds_matches_has::<crate::encapsulates::EncapsulationKind, _>(
11308 single_slot_encapsulation_kind_probe,
11309 );
11310 assert_missing_kinds_matches_has::<crate::export::ArtifactSource, _>(
11311 single_slot_artifact_source_probe,
11312 );
11313 assert_missing_kinds_matches_has::<crate::export::VectorChannel, _>(
11314 single_slot_vector_channel_probe,
11315 );
11316 }
11317
11318 // -------------------------------------------------------------------
11319 // `TaggedUnion::missing_kind_count` — scalar cardinality refinement
11320 // on the closed-set-COMPLEMENT axis. Pin the three arms (empty parent
11321 // → ALL.len(), single-slot → ALL.len() - 1, saturated → 0) directly
11322 // on the sibling-shaped `LocalParent` scaffold and the composition
11323 // law `missing_kind_count() == missing_kinds().len()` + the scalar
11324 // partition law `populated_kind_count + missing_kind_count ==
11325 // ALL.len()` at the substrate testkit
11326 // `assert_missing_kind_count_matches_missing_kinds`.
11327 // -------------------------------------------------------------------
11328
11329 /// EMPTY parent — the default body's `ALL.filter(!has).count()`
11330 /// sweep yields `ALL.len()` when no slot is populated. Pins the
11331 /// full-cardinality complement arm.
11332 #[test]
11333 fn tagged_union_default_missing_kind_count_returns_all_len_on_empty_parent() {
11334 let empty = LocalParent::default();
11335 assert_eq!(
11336 <LocalParent as TaggedUnion>::missing_kind_count(&empty),
11337 <LocalKind as tatara_closed_set::ClosedSet>::ALL.len(),
11338 "missing_kind_count() must return ALL.len() when no slot is populated",
11339 );
11340 }
11341
11342 /// SINGLE-SLOT parent — the default body sweeps `ClosedSet::ALL`
11343 /// with `!has(k)` and counts `ALL.len() - 1` for each single-
11344 /// populated arrangement. Pins the well-formed arm's complement
11345 /// cardinality per addressed kind.
11346 #[test]
11347 fn tagged_union_default_missing_kind_count_returns_all_len_minus_one_per_single_slot_variant() {
11348 let expected = <LocalKind as tatara_closed_set::ClosedSet>::ALL.len() - 1;
11349 for populated in <LocalKind as tatara_closed_set::ClosedSet>::ALL
11350 .iter()
11351 .copied()
11352 {
11353 let parent = match populated {
11354 LocalKind::Alpha => LocalParent {
11355 alpha: Some(11),
11356 ..Default::default()
11357 },
11358 LocalKind::Beta => LocalParent {
11359 beta: Some(22),
11360 ..Default::default()
11361 },
11362 LocalKind::Gamma => LocalParent {
11363 gamma: Some(33),
11364 ..Default::default()
11365 },
11366 };
11367 assert_eq!(
11368 <LocalParent as TaggedUnion>::missing_kind_count(&parent),
11369 expected,
11370 "single-slot parent must return ALL.len() - 1 on missing_kind_count for {populated:?}",
11371 );
11372 }
11373 }
11374
11375 /// SATURATED parent — every slot populated returns `0` on
11376 /// `missing_kind_count`. Pins the zero-cardinality complement arm
11377 /// (mirror of `populated_kind_count` returning `ALL.len()` on the
11378 /// saturated arm).
11379 #[test]
11380 fn tagged_union_default_missing_kind_count_returns_zero_on_saturated_parent() {
11381 let saturated = LocalParent {
11382 alpha: Some(1),
11383 beta: Some(2),
11384 gamma: Some(3),
11385 };
11386 assert_eq!(
11387 <LocalParent as TaggedUnion>::missing_kind_count(&saturated),
11388 0,
11389 "saturated parent must return 0 on missing_kind_count",
11390 );
11391 }
11392
11393 /// Composition law `missing_kind_count() == missing_kinds().len()`
11394 /// binds the scalar cardinality projection to the widened primitive
11395 /// across every `ClosedSet::ALL × {empty, single_slot, two_slot,
11396 /// saturated}` combination. AND the scalar partition law
11397 /// `populated_kind_count() + missing_kind_count() == ALL.len()`
11398 /// binds the two axes byte-identically. Pins BOTH invariants at
11399 /// ONE test.
11400 #[test]
11401 fn tagged_union_default_missing_kind_count_matches_missing_kinds_len_and_partitions() {
11402 let all_len = <LocalKind as tatara_closed_set::ClosedSet>::ALL.len();
11403 let arrangements: [LocalParent; 4] = [
11404 LocalParent::default(),
11405 LocalParent {
11406 alpha: Some(1),
11407 ..Default::default()
11408 },
11409 LocalParent {
11410 alpha: Some(1),
11411 beta: Some(2),
11412 gamma: None,
11413 },
11414 LocalParent {
11415 alpha: Some(1),
11416 beta: Some(2),
11417 gamma: Some(3),
11418 },
11419 ];
11420 for (idx, parent) in arrangements.iter().enumerate() {
11421 let count = <LocalParent as TaggedUnion>::missing_kind_count(parent);
11422 let missing_len = <LocalParent as TaggedUnion>::missing_kinds(parent).len();
11423 assert_eq!(
11424 count, missing_len,
11425 "missing_kind_count() must equal missing_kinds().len() for arrangement idx {idx}",
11426 );
11427 let populated_count = <LocalParent as TaggedUnion>::populated_kind_count(parent);
11428 assert_eq!(
11429 populated_count + count,
11430 all_len,
11431 "scalar partition law violated at arrangement idx {idx} — populated_kind_count + missing_kind_count must equal ALL.len()",
11432 );
11433 }
11434 }
11435
11436 /// `assert_missing_kind_count_matches_missing_kinds` testkit
11437 /// accepts the coherent local scaffold — sweeping every populated
11438 /// kind through the three sub-assertions (composition law
11439 /// `count == missing_kinds.len()` + single-slot diagonal `count ==
11440 /// ALL.len() - 1` + scalar partition law
11441 /// `populated_kind_count + missing_kind_count == ALL.len()`). A
11442 /// regression on any of the three fails at the substrate
11443 /// primitive's `#[track_caller]` boundary.
11444 #[test]
11445 fn assert_missing_kind_count_matches_missing_kinds_accepts_coherent_local_impl() {
11446 fn make_local(k: LocalKind) -> LocalParent {
11447 match k {
11448 LocalKind::Alpha => LocalParent {
11449 alpha: Some(11),
11450 ..Default::default()
11451 },
11452 LocalKind::Beta => LocalParent {
11453 beta: Some(22),
11454 ..Default::default()
11455 },
11456 LocalKind::Gamma => LocalParent {
11457 gamma: Some(33),
11458 ..Default::default()
11459 },
11460 }
11461 }
11462 assert_missing_kind_count_matches_missing_kinds::<LocalParent, _>(make_local);
11463 }
11464
11465 /// A factory that yields an all-empty parent (so
11466 /// `missing_kind_count()` returns `ALL.len()`) MUST fail-loudly at
11467 /// the caller's site through the primitive's single-slot diagonal
11468 /// arm — the `ALL.len()` cardinality does not equal `ALL.len() - 1`.
11469 #[test]
11470 #[should_panic(expected = "must equal ALL.len() - 1 exactly")]
11471 fn assert_missing_kind_count_matches_missing_kinds_rejects_empty_factory() {
11472 fn empty_factory(_: LocalKind) -> LocalParent {
11473 LocalParent::default()
11474 }
11475 assert_missing_kind_count_matches_missing_kinds::<LocalParent, _>(empty_factory);
11476 }
11477
11478 /// Every one of the four production `.variant()` sites on
11479 /// `ProcessSpec` binds through the scalar-cardinality complement
11480 /// primitive `assert_missing_kind_count_matches_missing_kinds`
11481 /// coherently — every per-site `single_slot_X(k)` factory produces
11482 /// a parent whose `missing_kind_count()` equals `ALL.len() - 1`
11483 /// AND whose composition law `count == missing_kinds().len()` AND
11484 /// scalar partition law `populated_kind_count + missing_kind_count
11485 /// == ALL.len()` all hold. Sweep every production implementor at
11486 /// ONE substrate boundary.
11487 #[test]
11488 fn every_production_tagged_union_binds_through_the_missing_kind_count_testkit_primitive() {
11489 assert_missing_kind_count_matches_missing_kinds::<crate::intent::Intent, _>(
11490 single_slot_intent_probe,
11491 );
11492 assert_missing_kind_count_matches_missing_kinds::<crate::encapsulates::EncapsulationKind, _>(
11493 single_slot_encapsulation_kind_probe,
11494 );
11495 assert_missing_kind_count_matches_missing_kinds::<crate::export::ArtifactSource, _>(
11496 single_slot_artifact_source_probe,
11497 );
11498 assert_missing_kind_count_matches_missing_kinds::<crate::export::VectorChannel, _>(
11499 single_slot_vector_channel_probe,
11500 );
11501 }
11502
11503 // -------------------------------------------------------------------
11504 // `TaggedUnion::first_populated_kind` / `first_missing_kind` — the
11505 // short-circuiting `Option<Kind>` peers of `populated_kinds` /
11506 // `missing_kinds`. Pin the four-outcome truth table (empty parent
11507 // → `first_populated_kind` is `None`, `first_missing_kind` is
11508 // `Some(ALL[0])`; populated diagonal → `first_populated_kind` is
11509 // `Some(k)`, `first_missing_kind` is the earliest `ALL` entry
11510 // != `k`; multi-populated → `first_populated_kind` names the
11511 // EARLIEST populated slot in canonical `ALL` order) directly on
11512 // the `LocalParent` scaffold AND via the substrate testkit
11513 // primitives, so a regression on the default body's short-circuit
11514 // or negation composition fails here before any per-parent
11515 // inherent test surfaces the drift.
11516 // -------------------------------------------------------------------
11517
11518 /// EMPTY-PARENT pin — a default [`LocalParent`] returns `None` at
11519 /// `first_populated_kind` (no slot populated) and `Some(ALL[0])` at
11520 /// `first_missing_kind` (every slot missing, earliest hit is
11521 /// index 0 of the canonical closed-set walk). Composition-law pin:
11522 /// `first_populated_kind().is_none() == (populated_kind_count() ==
11523 /// 0)` and `first_missing_kind() == Some(ALL[0])` on the empty
11524 /// boundary.
11525 #[test]
11526 fn tagged_union_default_first_kinds_on_empty_parent() {
11527 let empty = LocalParent::default();
11528 assert_eq!(
11529 <LocalParent as TaggedUnion>::first_populated_kind(&empty),
11530 None,
11531 );
11532 assert_eq!(
11533 <LocalParent as TaggedUnion>::first_missing_kind(&empty),
11534 Some(<LocalKind as tatara_closed_set::ClosedSet>::ALL[0]),
11535 );
11536 }
11537
11538 /// SINGLE-SLOT DIAGONAL pin — every populated position across
11539 /// [`LocalKind::ALL`] returns `Some(k)` at `first_populated_kind`
11540 /// (the sole populated slot IS the earliest one) AND the earliest
11541 /// `ALL` entry != `k` at `first_missing_kind`. Both projections
11542 /// agree with the widened primitives via
11543 /// `first_populated_kind() == populated_kinds().first().copied()`
11544 /// and `first_missing_kind() == missing_kinds().first().copied()`.
11545 #[test]
11546 fn tagged_union_default_first_kinds_on_single_slot_diagonal() {
11547 for populated in <LocalKind as tatara_closed_set::ClosedSet>::ALL
11548 .iter()
11549 .copied()
11550 {
11551 let parent = match populated {
11552 LocalKind::Alpha => LocalParent {
11553 alpha: Some(11),
11554 ..Default::default()
11555 },
11556 LocalKind::Beta => LocalParent {
11557 beta: Some(22),
11558 ..Default::default()
11559 },
11560 LocalKind::Gamma => LocalParent {
11561 gamma: Some(33),
11562 ..Default::default()
11563 },
11564 };
11565 assert_eq!(
11566 <LocalParent as TaggedUnion>::first_populated_kind(&parent),
11567 Some(populated),
11568 );
11569 let expected_first_missing = <LocalKind as tatara_closed_set::ClosedSet>::ALL
11570 .iter()
11571 .copied()
11572 .find(|k| *k != populated);
11573 assert_eq!(
11574 <LocalParent as TaggedUnion>::first_missing_kind(&parent),
11575 expected_first_missing,
11576 );
11577 // Composition laws vs. widened primitives.
11578 assert_eq!(
11579 parent.first_populated_kind(),
11580 parent.populated_kinds().first().copied(),
11581 );
11582 assert_eq!(
11583 parent.first_missing_kind(),
11584 parent.missing_kinds().first().copied(),
11585 );
11586 }
11587 }
11588
11589 /// TWO-POPULATED pin — a `LocalParent` with two populated slots
11590 /// returns `first_populated_kind() == Some(min_all(a, b))` (the
11591 /// EARLIEST populated slot in canonical `ClosedSet::ALL` order —
11592 /// strictly more informative than the payload-free
11593 /// [`LocalParentError::Ambiguous`] carrier `variant()` returns on
11594 /// the same input). Pins the walk order on the Ambiguous arm at
11595 /// ONE substrate boundary — a regression that iterates `ALL` in
11596 /// reverse or in construction order fails here.
11597 #[test]
11598 fn tagged_union_default_first_populated_kind_names_earliest_of_two_populated_slots() {
11599 // Alpha + Beta populated → earliest is Alpha (ALL[0]).
11600 let p = LocalParent {
11601 alpha: Some(1),
11602 beta: Some(2),
11603 gamma: None,
11604 };
11605 assert_eq!(p.first_populated_kind(), Some(LocalKind::Alpha));
11606 // Missing set is [Gamma]; earliest missing is Gamma.
11607 assert_eq!(p.first_missing_kind(), Some(LocalKind::Gamma));
11608
11609 // Beta + Gamma populated → earliest is Beta.
11610 let p = LocalParent {
11611 alpha: None,
11612 beta: Some(1),
11613 gamma: Some(2),
11614 };
11615 assert_eq!(p.first_populated_kind(), Some(LocalKind::Beta));
11616 assert_eq!(p.first_missing_kind(), Some(LocalKind::Alpha));
11617
11618 // Alpha + Gamma populated → earliest is Alpha.
11619 let p = LocalParent {
11620 alpha: Some(1),
11621 beta: None,
11622 gamma: Some(2),
11623 };
11624 assert_eq!(p.first_populated_kind(), Some(LocalKind::Alpha));
11625 assert_eq!(p.first_missing_kind(), Some(LocalKind::Beta));
11626 }
11627
11628 /// SATURATED-PARENT pin — a `LocalParent` with EVERY slot
11629 /// populated returns `Some(ALL[0])` at `first_populated_kind`
11630 /// (earliest hit on the all-`true` predicate is index 0) and
11631 /// `None` at `first_missing_kind` (no missing slot exists). Pins
11632 /// the earliest-missing projection's `None` arm at ONE substrate
11633 /// boundary — a regression that returned `Some(ALL[0])` (dropping
11634 /// the negation) or `Some(ALL[ALL.len()-1])` (walking in reverse)
11635 /// fails here.
11636 #[test]
11637 fn tagged_union_default_first_missing_kind_returns_none_on_saturated_parent() {
11638 let p = LocalParent {
11639 alpha: Some(1),
11640 beta: Some(2),
11641 gamma: Some(3),
11642 };
11643 assert_eq!(p.first_populated_kind(), Some(LocalKind::Alpha));
11644 assert_eq!(p.first_missing_kind(), None);
11645 }
11646
11647 /// The `assert_first_populated_kind_matches_populated_kinds`
11648 /// primitive accepts the [`LocalParent`] scaffold coherently — the
11649 /// Ok arm is the "no drift" outcome.
11650 #[test]
11651 fn assert_first_populated_kind_matches_populated_kinds_accepts_coherent_local_impl() {
11652 fn make_local(k: LocalKind) -> LocalParent {
11653 match k {
11654 LocalKind::Alpha => LocalParent {
11655 alpha: Some(11),
11656 ..Default::default()
11657 },
11658 LocalKind::Beta => LocalParent {
11659 beta: Some(22),
11660 ..Default::default()
11661 },
11662 LocalKind::Gamma => LocalParent {
11663 gamma: Some(33),
11664 ..Default::default()
11665 },
11666 }
11667 }
11668 assert_first_populated_kind_matches_populated_kinds::<LocalParent, _>(make_local);
11669 }
11670
11671 /// A factory that yields an all-empty parent (so
11672 /// `first_populated_kind()` returns `None`) MUST fail-loudly at
11673 /// the caller's site through the primitive's single-slot diagonal
11674 /// arm — `None` does not equal `Some(populated)`.
11675 #[test]
11676 #[should_panic(expected = "must equal Some(")]
11677 fn assert_first_populated_kind_matches_populated_kinds_rejects_empty_factory() {
11678 fn empty_factory(_: LocalKind) -> LocalParent {
11679 LocalParent::default()
11680 }
11681 assert_first_populated_kind_matches_populated_kinds::<LocalParent, _>(empty_factory);
11682 }
11683
11684 /// The `assert_first_missing_kind_matches_missing_kinds` primitive
11685 /// accepts the [`LocalParent`] scaffold coherently.
11686 #[test]
11687 fn assert_first_missing_kind_matches_missing_kinds_accepts_coherent_local_impl() {
11688 fn make_local(k: LocalKind) -> LocalParent {
11689 match k {
11690 LocalKind::Alpha => LocalParent {
11691 alpha: Some(11),
11692 ..Default::default()
11693 },
11694 LocalKind::Beta => LocalParent {
11695 beta: Some(22),
11696 ..Default::default()
11697 },
11698 LocalKind::Gamma => LocalParent {
11699 gamma: Some(33),
11700 ..Default::default()
11701 },
11702 }
11703 }
11704 assert_first_missing_kind_matches_missing_kinds::<LocalParent, _>(make_local);
11705 }
11706
11707 /// Every one of the four production `.variant()` sites on
11708 /// `ProcessSpec` binds through the earliest-populated primitive
11709 /// coherently — every per-site `single_slot_X(k)` factory produces
11710 /// a parent whose `first_populated_kind()` equals `Some(k)`.
11711 #[test]
11712 fn every_production_tagged_union_binds_through_the_first_populated_kind_testkit_primitive() {
11713 assert_first_populated_kind_matches_populated_kinds::<crate::intent::Intent, _>(
11714 single_slot_intent_probe,
11715 );
11716 assert_first_populated_kind_matches_populated_kinds::<
11717 crate::encapsulates::EncapsulationKind,
11718 _,
11719 >(single_slot_encapsulation_kind_probe);
11720 assert_first_populated_kind_matches_populated_kinds::<crate::export::ArtifactSource, _>(
11721 single_slot_artifact_source_probe,
11722 );
11723 assert_first_populated_kind_matches_populated_kinds::<crate::export::VectorChannel, _>(
11724 single_slot_vector_channel_probe,
11725 );
11726 }
11727
11728 /// Every one of the four production `.variant()` sites on
11729 /// `ProcessSpec` binds through the earliest-missing primitive
11730 /// coherently.
11731 #[test]
11732 fn every_production_tagged_union_binds_through_the_first_missing_kind_testkit_primitive() {
11733 assert_first_missing_kind_matches_missing_kinds::<crate::intent::Intent, _>(
11734 single_slot_intent_probe,
11735 );
11736 assert_first_missing_kind_matches_missing_kinds::<crate::encapsulates::EncapsulationKind, _>(
11737 single_slot_encapsulation_kind_probe,
11738 );
11739 assert_first_missing_kind_matches_missing_kinds::<crate::export::ArtifactSource, _>(
11740 single_slot_artifact_source_probe,
11741 );
11742 assert_first_missing_kind_matches_missing_kinds::<crate::export::VectorChannel, _>(
11743 single_slot_vector_channel_probe,
11744 );
11745 }
11746
11747 // -------------------------------------------------------------------
11748 // `TaggedUnion::last_populated_kind` / `last_missing_kind` — the
11749 // short-circuiting REVERSED-walk `Option<Kind>` peers of
11750 // `first_populated_kind` / `first_missing_kind`. Pin the four-outcome
11751 // truth table (empty parent → `last_populated_kind` is `None`,
11752 // `last_missing_kind` is `Some(ALL[ALL.len()-1])`; populated diagonal
11753 // → `last_populated_kind` is `Some(k)`, `last_missing_kind` is the
11754 // latest `ALL` entry != `k`; multi-populated → `last_populated_kind`
11755 // names the LATEST populated slot in canonical `ALL` order;
11756 // saturated → `last_missing_kind` is `None`) directly on the
11757 // `LocalParent` scaffold AND via the substrate testkit primitives,
11758 // so a regression on the reversed default body's short-circuit or
11759 // negation composition fails here before any per-parent inherent
11760 // test surfaces the drift.
11761 // -------------------------------------------------------------------
11762
11763 /// EMPTY-PARENT pin — a default [`LocalParent`] returns `None` at
11764 /// `last_populated_kind` (no slot populated) and
11765 /// `Some(ALL[ALL.len()-1])` at `last_missing_kind` (every slot
11766 /// missing, latest hit is the last index of the canonical closed-
11767 /// set walk under REVERSED iteration). Composition-law pin:
11768 /// `last_populated_kind().is_none() == (populated_kind_count() ==
11769 /// 0)` and `last_missing_kind() == Some(ALL[ALL.len()-1])` on the
11770 /// empty boundary.
11771 #[test]
11772 fn tagged_union_default_last_kinds_on_empty_parent() {
11773 let empty = LocalParent::default();
11774 assert_eq!(
11775 <LocalParent as TaggedUnion>::last_populated_kind(&empty),
11776 None,
11777 );
11778 let all_len = <LocalKind as tatara_closed_set::ClosedSet>::ALL.len();
11779 assert_eq!(
11780 <LocalParent as TaggedUnion>::last_missing_kind(&empty),
11781 Some(<LocalKind as tatara_closed_set::ClosedSet>::ALL[all_len - 1]),
11782 );
11783 }
11784
11785 /// SINGLE-SLOT DIAGONAL pin — every populated position across
11786 /// [`LocalKind::ALL`] returns `Some(k)` at `last_populated_kind`
11787 /// (the sole populated slot IS both the earliest AND the latest)
11788 /// AND the LATEST `ALL` entry != `k` at `last_missing_kind`. Both
11789 /// projections agree with the widened primitives via
11790 /// `last_populated_kind() == populated_kinds().last().copied()`
11791 /// and `last_missing_kind() == missing_kinds().last().copied()`.
11792 #[test]
11793 fn tagged_union_default_last_kinds_on_single_slot_diagonal() {
11794 for populated in <LocalKind as tatara_closed_set::ClosedSet>::ALL
11795 .iter()
11796 .copied()
11797 {
11798 let parent = match populated {
11799 LocalKind::Alpha => LocalParent {
11800 alpha: Some(11),
11801 ..Default::default()
11802 },
11803 LocalKind::Beta => LocalParent {
11804 beta: Some(22),
11805 ..Default::default()
11806 },
11807 LocalKind::Gamma => LocalParent {
11808 gamma: Some(33),
11809 ..Default::default()
11810 },
11811 };
11812 assert_eq!(
11813 <LocalParent as TaggedUnion>::last_populated_kind(&parent),
11814 Some(populated),
11815 );
11816 let expected_last_missing = <LocalKind as tatara_closed_set::ClosedSet>::ALL
11817 .iter()
11818 .rev()
11819 .copied()
11820 .find(|k| *k != populated);
11821 assert_eq!(
11822 <LocalParent as TaggedUnion>::last_missing_kind(&parent),
11823 expected_last_missing,
11824 );
11825 // Composition laws vs. widened primitives.
11826 assert_eq!(
11827 parent.last_populated_kind(),
11828 parent.populated_kinds().last().copied(),
11829 );
11830 assert_eq!(
11831 parent.last_missing_kind(),
11832 parent.missing_kinds().last().copied(),
11833 );
11834 }
11835 }
11836
11837 /// TWO-POPULATED pin — a `LocalParent` with two populated slots
11838 /// returns `last_populated_kind() == Some(max_all(a, b))` (the
11839 /// LATEST populated slot in canonical `ClosedSet::ALL` order —
11840 /// byte-for-byte time-reversed peer of the earliest-populated
11841 /// projection). Pins the walk order on the Ambiguous arm at ONE
11842 /// substrate boundary — a regression that iterates `ALL` forward
11843 /// (defeating the time-reversal) fails here.
11844 #[test]
11845 fn tagged_union_default_last_populated_kind_names_latest_of_two_populated_slots() {
11846 // Alpha + Beta populated → latest is Beta (ALL[1]).
11847 let p = LocalParent {
11848 alpha: Some(1),
11849 beta: Some(2),
11850 gamma: None,
11851 };
11852 assert_eq!(p.last_populated_kind(), Some(LocalKind::Beta));
11853 // Missing set is [Gamma]; latest missing is Gamma.
11854 assert_eq!(p.last_missing_kind(), Some(LocalKind::Gamma));
11855
11856 // Beta + Gamma populated → latest is Gamma.
11857 let p = LocalParent {
11858 alpha: None,
11859 beta: Some(1),
11860 gamma: Some(2),
11861 };
11862 assert_eq!(p.last_populated_kind(), Some(LocalKind::Gamma));
11863 assert_eq!(p.last_missing_kind(), Some(LocalKind::Alpha));
11864
11865 // Alpha + Gamma populated → latest is Gamma.
11866 let p = LocalParent {
11867 alpha: Some(1),
11868 beta: None,
11869 gamma: Some(2),
11870 };
11871 assert_eq!(p.last_populated_kind(), Some(LocalKind::Gamma));
11872 assert_eq!(p.last_missing_kind(), Some(LocalKind::Beta));
11873 }
11874
11875 /// SATURATED-PARENT pin — a `LocalParent` with EVERY slot
11876 /// populated returns `Some(ALL[ALL.len()-1])` at
11877 /// `last_populated_kind` (latest hit on the all-`true` predicate
11878 /// under REVERSED iteration is the last index) and `None` at
11879 /// `last_missing_kind` (no missing slot exists). Pins the latest-
11880 /// missing projection's `None` arm at ONE substrate boundary — a
11881 /// regression that returned `Some(ALL[ALL.len()-1])` (dropping the
11882 /// negation) or `Some(ALL[0])` (defeating the time-reversal)
11883 /// fails here.
11884 #[test]
11885 fn tagged_union_default_last_missing_kind_returns_none_on_saturated_parent() {
11886 let p = LocalParent {
11887 alpha: Some(1),
11888 beta: Some(2),
11889 gamma: Some(3),
11890 };
11891 let all_len = <LocalKind as tatara_closed_set::ClosedSet>::ALL.len();
11892 assert_eq!(
11893 p.last_populated_kind(),
11894 Some(<LocalKind as tatara_closed_set::ClosedSet>::ALL[all_len - 1]),
11895 );
11896 assert_eq!(p.last_missing_kind(), None);
11897 }
11898
11899 /// The `assert_last_populated_kind_matches_populated_kinds`
11900 /// primitive accepts the [`LocalParent`] scaffold coherently — the
11901 /// Ok arm is the "no drift" outcome.
11902 #[test]
11903 fn assert_last_populated_kind_matches_populated_kinds_accepts_coherent_local_impl() {
11904 fn make_local(k: LocalKind) -> LocalParent {
11905 match k {
11906 LocalKind::Alpha => LocalParent {
11907 alpha: Some(11),
11908 ..Default::default()
11909 },
11910 LocalKind::Beta => LocalParent {
11911 beta: Some(22),
11912 ..Default::default()
11913 },
11914 LocalKind::Gamma => LocalParent {
11915 gamma: Some(33),
11916 ..Default::default()
11917 },
11918 }
11919 }
11920 assert_last_populated_kind_matches_populated_kinds::<LocalParent, _>(make_local);
11921 }
11922
11923 /// A factory that yields an all-empty parent (so
11924 /// `last_populated_kind()` returns `None`) MUST fail-loudly at the
11925 /// caller's site through the primitive's single-slot diagonal arm
11926 /// — `None` does not equal `Some(populated)`.
11927 #[test]
11928 #[should_panic(expected = "must equal Some(")]
11929 fn assert_last_populated_kind_matches_populated_kinds_rejects_empty_factory() {
11930 fn empty_factory(_: LocalKind) -> LocalParent {
11931 LocalParent::default()
11932 }
11933 assert_last_populated_kind_matches_populated_kinds::<LocalParent, _>(empty_factory);
11934 }
11935
11936 /// The `assert_last_missing_kind_matches_missing_kinds` primitive
11937 /// accepts the [`LocalParent`] scaffold coherently.
11938 #[test]
11939 fn assert_last_missing_kind_matches_missing_kinds_accepts_coherent_local_impl() {
11940 fn make_local(k: LocalKind) -> LocalParent {
11941 match k {
11942 LocalKind::Alpha => LocalParent {
11943 alpha: Some(11),
11944 ..Default::default()
11945 },
11946 LocalKind::Beta => LocalParent {
11947 beta: Some(22),
11948 ..Default::default()
11949 },
11950 LocalKind::Gamma => LocalParent {
11951 gamma: Some(33),
11952 ..Default::default()
11953 },
11954 }
11955 }
11956 assert_last_missing_kind_matches_missing_kinds::<LocalParent, _>(make_local);
11957 }
11958
11959 /// Every one of the four production `.variant()` sites on
11960 /// `ProcessSpec` binds through the latest-populated primitive
11961 /// coherently — every per-site `single_slot_X(k)` factory produces
11962 /// a parent whose `last_populated_kind()` equals `Some(k)`.
11963 #[test]
11964 fn every_production_tagged_union_binds_through_the_last_populated_kind_testkit_primitive() {
11965 assert_last_populated_kind_matches_populated_kinds::<crate::intent::Intent, _>(
11966 single_slot_intent_probe,
11967 );
11968 assert_last_populated_kind_matches_populated_kinds::<
11969 crate::encapsulates::EncapsulationKind,
11970 _,
11971 >(single_slot_encapsulation_kind_probe);
11972 assert_last_populated_kind_matches_populated_kinds::<crate::export::ArtifactSource, _>(
11973 single_slot_artifact_source_probe,
11974 );
11975 assert_last_populated_kind_matches_populated_kinds::<crate::export::VectorChannel, _>(
11976 single_slot_vector_channel_probe,
11977 );
11978 }
11979
11980 /// Every one of the four production `.variant()` sites on
11981 /// `ProcessSpec` binds through the latest-missing primitive
11982 /// coherently.
11983 #[test]
11984 fn every_production_tagged_union_binds_through_the_last_missing_kind_testkit_primitive() {
11985 assert_last_missing_kind_matches_missing_kinds::<crate::intent::Intent, _>(
11986 single_slot_intent_probe,
11987 );
11988 assert_last_missing_kind_matches_missing_kinds::<crate::encapsulates::EncapsulationKind, _>(
11989 single_slot_encapsulation_kind_probe,
11990 );
11991 assert_last_missing_kind_matches_missing_kinds::<crate::export::ArtifactSource, _>(
11992 single_slot_artifact_source_probe,
11993 );
11994 assert_last_missing_kind_matches_missing_kinds::<crate::export::VectorChannel, _>(
11995 single_slot_vector_channel_probe,
11996 );
11997 }
11998
11999 // -------------------------------------------------------------------
12000 // `TaggedUnion::unique_populated_kind` / `unique_missing_kind` — the
12001 // short-circuiting `Option<Kind>` peers on the exactly-one-hit axis.
12002 // Pin the four-outcome truth table (empty parent → both `None`;
12003 // single-slot diagonal → `unique_populated_kind` is `Some(k)`,
12004 // `unique_missing_kind` is `None` on `ALL.len() > 2`; two-populated
12005 // parent → `unique_populated_kind` is `None`, `unique_missing_kind`
12006 // is `Some(the-one-missing)`; saturated → both `None`) directly on
12007 // the `LocalParent` scaffold AND via the substrate testkit
12008 // primitives, so a regression on the two-step short-circuit's
12009 // second-hit truncation or the negation composition fails here
12010 // before any per-parent inherent test surfaces the drift.
12011 // -------------------------------------------------------------------
12012
12013 /// EMPTY-PARENT pin — a default [`LocalParent`] returns `None` at
12014 /// BOTH `unique_populated_kind` (zero populated, not exactly-one)
12015 /// and `unique_missing_kind` (three missing on a `ALL.len() == 3`
12016 /// closed set, not exactly-one). Pins the empty-arm collapse — the
12017 /// two primitives agree on `None` when the closed-set cardinality
12018 /// is ≥ 3, distinguishing the exactly-one primitive from the
12019 /// endpoint primitives (`first_missing_kind` on an empty parent
12020 /// returns `Some(ALL[0])`, not `None`).
12021 #[test]
12022 fn tagged_union_default_unique_kinds_on_empty_parent() {
12023 let empty = LocalParent::default();
12024 assert_eq!(
12025 <LocalParent as TaggedUnion>::unique_populated_kind(&empty),
12026 None,
12027 );
12028 assert_eq!(
12029 <LocalParent as TaggedUnion>::unique_missing_kind(&empty),
12030 None,
12031 );
12032 }
12033
12034 /// SINGLE-SLOT DIAGONAL pin — every populated position across
12035 /// [`LocalKind::ALL`] returns `Some(k)` at `unique_populated_kind`
12036 /// (the sole populated slot IS the exactly-one hit) AND `None` at
12037 /// `unique_missing_kind` (two missing slots on the `ALL.len() == 3`
12038 /// closed set, not exactly-one). The `Some` arm's endpoint
12039 /// agreement composes with `first_populated_kind` /
12040 /// `last_populated_kind` at the trait defaults (`unique == first
12041 /// == last` on exactly-one).
12042 #[test]
12043 fn tagged_union_default_unique_kinds_on_single_slot_diagonal() {
12044 for populated in <LocalKind as tatara_closed_set::ClosedSet>::ALL
12045 .iter()
12046 .copied()
12047 {
12048 let parent = match populated {
12049 LocalKind::Alpha => LocalParent {
12050 alpha: Some(11),
12051 ..Default::default()
12052 },
12053 LocalKind::Beta => LocalParent {
12054 beta: Some(22),
12055 ..Default::default()
12056 },
12057 LocalKind::Gamma => LocalParent {
12058 gamma: Some(33),
12059 ..Default::default()
12060 },
12061 };
12062 assert_eq!(
12063 <LocalParent as TaggedUnion>::unique_populated_kind(&parent),
12064 Some(populated),
12065 );
12066 assert_eq!(
12067 <LocalParent as TaggedUnion>::unique_missing_kind(&parent),
12068 None,
12069 );
12070 // Endpoint-agreement composition — on Some, the three
12071 // endpoint-projection primitives agree.
12072 assert_eq!(
12073 parent.unique_populated_kind(),
12074 parent.first_populated_kind()
12075 );
12076 assert_eq!(parent.unique_populated_kind(), parent.last_populated_kind());
12077 }
12078 }
12079
12080 /// TWO-POPULATED pin — a `LocalParent` with two populated slots
12081 /// returns `unique_populated_kind() == None` (two populated, not
12082 /// exactly-one) and `unique_missing_kind() == Some(the-one-missing)`
12083 /// (one missing, exactly-one — the ONLY arm where the missing-side
12084 /// primitive returns `Some` on a `ALL.len() == 3` closed set). Pins
12085 /// the two-step short-circuit's second-hit collapse at ONE
12086 /// substrate boundary — a regression that returned `Some(first)`
12087 /// after seeing two populated slots (defeating the exactly-one
12088 /// contract) fails here.
12089 #[test]
12090 fn tagged_union_default_unique_kinds_on_two_populated_parent() {
12091 // Alpha + Beta populated → 2 populated (unique_populated=None),
12092 // 1 missing = Gamma (unique_missing=Some(Gamma)).
12093 let p = LocalParent {
12094 alpha: Some(1),
12095 beta: Some(2),
12096 gamma: None,
12097 };
12098 assert_eq!(p.unique_populated_kind(), None);
12099 assert_eq!(p.unique_missing_kind(), Some(LocalKind::Gamma));
12100 // Endpoint-agreement composition on the missing-side Some arm.
12101 assert_eq!(p.unique_missing_kind(), p.first_missing_kind());
12102 assert_eq!(p.unique_missing_kind(), p.last_missing_kind());
12103
12104 // Beta + Gamma populated → unique_missing=Some(Alpha).
12105 let p = LocalParent {
12106 alpha: None,
12107 beta: Some(1),
12108 gamma: Some(2),
12109 };
12110 assert_eq!(p.unique_populated_kind(), None);
12111 assert_eq!(p.unique_missing_kind(), Some(LocalKind::Alpha));
12112
12113 // Alpha + Gamma populated → unique_missing=Some(Beta).
12114 let p = LocalParent {
12115 alpha: Some(1),
12116 beta: None,
12117 gamma: Some(2),
12118 };
12119 assert_eq!(p.unique_populated_kind(), None);
12120 assert_eq!(p.unique_missing_kind(), Some(LocalKind::Beta));
12121 }
12122
12123 /// SATURATED-PARENT pin — a `LocalParent` with EVERY slot
12124 /// populated returns `None` at BOTH `unique_populated_kind` (three
12125 /// populated, not exactly-one) AND `unique_missing_kind` (zero
12126 /// missing, not exactly-one). Pins the saturated-arm collapse — the
12127 /// two primitives agree on `None` when the closed-set cardinality
12128 /// is ≥ 3, distinguishing the exactly-one primitive from the
12129 /// endpoint primitives (`last_populated_kind` on a saturated
12130 /// parent returns `Some(ALL[ALL.len()-1])`, not `None`).
12131 #[test]
12132 fn tagged_union_default_unique_kinds_on_saturated_parent() {
12133 let p = LocalParent {
12134 alpha: Some(1),
12135 beta: Some(2),
12136 gamma: Some(3),
12137 };
12138 assert_eq!(p.unique_populated_kind(), None);
12139 assert_eq!(p.unique_missing_kind(), None);
12140 }
12141
12142 /// The `assert_unique_populated_kind_matches_populated_kinds`
12143 /// primitive accepts the [`LocalParent`] scaffold coherently — the
12144 /// Ok arm is the "no drift" outcome.
12145 #[test]
12146 fn assert_unique_populated_kind_matches_populated_kinds_accepts_coherent_local_impl() {
12147 fn make_local(k: LocalKind) -> LocalParent {
12148 match k {
12149 LocalKind::Alpha => LocalParent {
12150 alpha: Some(11),
12151 ..Default::default()
12152 },
12153 LocalKind::Beta => LocalParent {
12154 beta: Some(22),
12155 ..Default::default()
12156 },
12157 LocalKind::Gamma => LocalParent {
12158 gamma: Some(33),
12159 ..Default::default()
12160 },
12161 }
12162 }
12163 assert_unique_populated_kind_matches_populated_kinds::<LocalParent, _>(make_local);
12164 }
12165
12166 /// A factory that yields an all-empty parent (so
12167 /// `unique_populated_kind()` returns `None`) MUST fail-loudly at
12168 /// the caller's site through the primitive's single-slot diagonal
12169 /// arm — `None` does not equal `Some(populated)`.
12170 #[test]
12171 #[should_panic(expected = "must equal Some(")]
12172 fn assert_unique_populated_kind_matches_populated_kinds_rejects_empty_factory() {
12173 fn empty_factory(_: LocalKind) -> LocalParent {
12174 LocalParent::default()
12175 }
12176 assert_unique_populated_kind_matches_populated_kinds::<LocalParent, _>(empty_factory);
12177 }
12178
12179 /// The `assert_unique_missing_kind_matches_missing_kinds` primitive
12180 /// accepts the [`LocalParent`] scaffold coherently.
12181 #[test]
12182 fn assert_unique_missing_kind_matches_missing_kinds_accepts_coherent_local_impl() {
12183 fn make_local(k: LocalKind) -> LocalParent {
12184 match k {
12185 LocalKind::Alpha => LocalParent {
12186 alpha: Some(11),
12187 ..Default::default()
12188 },
12189 LocalKind::Beta => LocalParent {
12190 beta: Some(22),
12191 ..Default::default()
12192 },
12193 LocalKind::Gamma => LocalParent {
12194 gamma: Some(33),
12195 ..Default::default()
12196 },
12197 }
12198 }
12199 assert_unique_missing_kind_matches_missing_kinds::<LocalParent, _>(make_local);
12200 }
12201
12202 /// Every one of the four production `.variant()` sites on
12203 /// `ProcessSpec` binds through the exactly-one-populated primitive
12204 /// coherently — every per-site `single_slot_X(k)` factory produces
12205 /// a parent whose `unique_populated_kind()` equals `Some(k)`.
12206 #[test]
12207 fn every_production_tagged_union_binds_through_the_unique_populated_kind_testkit_primitive() {
12208 assert_unique_populated_kind_matches_populated_kinds::<crate::intent::Intent, _>(
12209 single_slot_intent_probe,
12210 );
12211 assert_unique_populated_kind_matches_populated_kinds::<
12212 crate::encapsulates::EncapsulationKind,
12213 _,
12214 >(single_slot_encapsulation_kind_probe);
12215 assert_unique_populated_kind_matches_populated_kinds::<crate::export::ArtifactSource, _>(
12216 single_slot_artifact_source_probe,
12217 );
12218 assert_unique_populated_kind_matches_populated_kinds::<crate::export::VectorChannel, _>(
12219 single_slot_vector_channel_probe,
12220 );
12221 }
12222
12223 /// Every one of the four production `.variant()` sites on
12224 /// `ProcessSpec` binds through the exactly-one-missing primitive
12225 /// coherently.
12226 #[test]
12227 fn every_production_tagged_union_binds_through_the_unique_missing_kind_testkit_primitive() {
12228 assert_unique_missing_kind_matches_missing_kinds::<crate::intent::Intent, _>(
12229 single_slot_intent_probe,
12230 );
12231 assert_unique_missing_kind_matches_missing_kinds::<crate::encapsulates::EncapsulationKind, _>(
12232 single_slot_encapsulation_kind_probe,
12233 );
12234 assert_unique_missing_kind_matches_missing_kinds::<crate::export::ArtifactSource, _>(
12235 single_slot_artifact_source_probe,
12236 );
12237 assert_unique_missing_kind_matches_missing_kinds::<crate::export::VectorChannel, _>(
12238 single_slot_vector_channel_probe,
12239 );
12240 }
12241
12242 // -------------------------------------------------------------------
12243 // `TaggedUnion::is_empty` / `TaggedUnion::is_saturated` trait-level
12244 // truth-table pins on the sibling-shaped `LocalParent` scaffold.
12245 // The two primitives are the Boolean cardinality-endpoint peers of
12246 // `populated_kind_count() == 0` and `missing_kind_count() == 0`
12247 // respectively — every arm below pins one truth-table entry directly
12248 // on the trait's default body without reaching for either scalar
12249 // primitive.
12250 // -------------------------------------------------------------------
12251
12252 /// EMPTY-PARENT pin — a default-constructed `LocalParent` (every
12253 /// slot None) returns `true` at `is_empty` (zero populated slots)
12254 /// AND `false` at `is_saturated` (three missing slots, not zero).
12255 /// Pins the zero-arm of the `is_empty` primitive and the negation
12256 /// of the `is_saturated` primitive on the same fixture — a
12257 /// regression that inverted either default body's composition
12258 /// direction fails here.
12259 #[test]
12260 fn tagged_union_default_is_empty_and_is_saturated_on_empty_parent() {
12261 let p = LocalParent::default();
12262 assert!(p.is_empty(), "empty parent must be is_empty");
12263 assert!(!p.is_saturated(), "empty parent must NOT be is_saturated");
12264 // Composition law with the scalar cardinality primitives.
12265 assert_eq!(p.is_empty(), p.populated_kind_count() == 0);
12266 assert_eq!(p.is_saturated(), p.missing_kind_count() == 0);
12267 // Widened-primitive agreement.
12268 assert_eq!(p.is_empty(), p.populated_kinds().is_empty());
12269 assert_eq!(p.is_saturated(), p.missing_kinds().is_empty());
12270 }
12271
12272 /// SINGLE-SLOT-DIAGONAL pin — a `LocalParent` populating exactly
12273 /// one slot returns `false` at BOTH `is_empty` (one populated, not
12274 /// zero) AND `is_saturated` (two missing, not zero). Pins that a
12275 /// well-formed parent lands OUTSIDE both cardinality endpoints —
12276 /// the Boolean primitives coincide on `false` on this arm, and
12277 /// only on the empty parent (`is_empty` true) or a saturated
12278 /// parent (`is_saturated` true) do they diverge.
12279 #[test]
12280 fn tagged_union_default_is_empty_and_is_saturated_on_single_slot_diagonal() {
12281 for (populated, parent) in [
12282 (
12283 LocalKind::Alpha,
12284 LocalParent {
12285 alpha: Some(1),
12286 ..Default::default()
12287 },
12288 ),
12289 (
12290 LocalKind::Beta,
12291 LocalParent {
12292 beta: Some(2),
12293 ..Default::default()
12294 },
12295 ),
12296 (
12297 LocalKind::Gamma,
12298 LocalParent {
12299 gamma: Some(3),
12300 ..Default::default()
12301 },
12302 ),
12303 ] {
12304 assert!(
12305 !parent.is_empty(),
12306 "single_slot({populated:?}) must NOT be is_empty",
12307 );
12308 assert!(
12309 !parent.is_saturated(),
12310 "single_slot({populated:?}) must NOT be is_saturated",
12311 );
12312 assert_eq!(parent.is_empty(), parent.populated_kind_count() == 0);
12313 assert_eq!(parent.is_saturated(), parent.missing_kind_count() == 0);
12314 }
12315 }
12316
12317 /// SATURATED-PARENT pin — a `LocalParent` with EVERY slot populated
12318 /// returns `false` at `is_empty` (three populated, not zero) AND
12319 /// `true` at `is_saturated` (zero missing). Pins the top-arm of
12320 /// the `is_saturated` primitive and the negation of the `is_empty`
12321 /// primitive on the same fixture — the mirror of the empty-parent
12322 /// pin above, distinguishing the two cardinality endpoints on
12323 /// opposite arms of the same closed-set walk.
12324 #[test]
12325 fn tagged_union_default_is_empty_and_is_saturated_on_saturated_parent() {
12326 let p = LocalParent {
12327 alpha: Some(1),
12328 beta: Some(2),
12329 gamma: Some(3),
12330 };
12331 assert!(!p.is_empty(), "saturated parent must NOT be is_empty");
12332 assert!(p.is_saturated(), "saturated parent must be is_saturated");
12333 assert_eq!(p.is_empty(), p.populated_kind_count() == 0);
12334 assert_eq!(p.is_saturated(), p.missing_kind_count() == 0);
12335 assert_eq!(p.is_empty(), p.populated_kinds().is_empty());
12336 assert_eq!(p.is_saturated(), p.missing_kinds().is_empty());
12337 }
12338
12339 // -------------------------------------------------------------------
12340 // Truth-table pins for `TaggedUnion::has_unique_populated_kind` and
12341 // `TaggedUnion::has_unique_missing_kind` — three arms (empty,
12342 // single-slot diagonal, saturated) on the sibling-shaped
12343 // `LocalParent` scaffold. The two primitives are the Boolean
12344 // cardinality-mid-endpoint peers of `populated_kind_count() == 1`
12345 // and `missing_kind_count() == 1` respectively — every arm below
12346 // pins one truth-table entry directly on the trait's default body
12347 // without reaching for either scalar primitive.
12348 // -------------------------------------------------------------------
12349
12350 /// EMPTY-PARENT pin — a default-constructed `LocalParent` (every
12351 /// slot None) returns `false` at BOTH `has_unique_populated_kind`
12352 /// (zero populated, not one) AND `has_unique_missing_kind` (three
12353 /// missing on `ALL.len() == 3`, not one). Pins the zero-populated
12354 /// arm of the first primitive and the ALL.len()-missing arm of the
12355 /// second on the same fixture.
12356 #[test]
12357 fn tagged_union_default_has_unique_kinds_on_empty_parent() {
12358 let p = LocalParent::default();
12359 assert!(
12360 !p.has_unique_populated_kind(),
12361 "empty parent must NOT be has_unique_populated_kind (zero populated)",
12362 );
12363 assert!(
12364 !p.has_unique_missing_kind(),
12365 "empty parent must NOT be has_unique_missing_kind (three missing)",
12366 );
12367 // Composition law with the scalar cardinality primitives.
12368 assert_eq!(p.has_unique_populated_kind(), p.populated_kind_count() == 1);
12369 assert_eq!(p.has_unique_missing_kind(), p.missing_kind_count() == 1);
12370 // Unique-primitive agreement.
12371 assert_eq!(
12372 p.has_unique_populated_kind(),
12373 p.unique_populated_kind().is_some()
12374 );
12375 assert_eq!(
12376 p.has_unique_missing_kind(),
12377 p.unique_missing_kind().is_some()
12378 );
12379 }
12380
12381 /// SINGLE-SLOT-DIAGONAL pin — a `LocalParent` populating exactly
12382 /// one slot returns `true` at `has_unique_populated_kind` (one
12383 /// populated) AND `false` at `has_unique_missing_kind` (two
12384 /// missing on `ALL.len() == 3`, not one). Pins that the well-
12385 /// formed arm coincides with the one-arm of the populated
12386 /// cardinality and lies OUTSIDE the one-arm of the missing
12387 /// cardinality on any `ALL.len() ≥ 3` closed set.
12388 #[test]
12389 fn tagged_union_default_has_unique_kinds_on_single_slot_diagonal() {
12390 for (populated, parent) in [
12391 (
12392 LocalKind::Alpha,
12393 LocalParent {
12394 alpha: Some(1),
12395 ..Default::default()
12396 },
12397 ),
12398 (
12399 LocalKind::Beta,
12400 LocalParent {
12401 beta: Some(2),
12402 ..Default::default()
12403 },
12404 ),
12405 (
12406 LocalKind::Gamma,
12407 LocalParent {
12408 gamma: Some(3),
12409 ..Default::default()
12410 },
12411 ),
12412 ] {
12413 assert!(
12414 parent.has_unique_populated_kind(),
12415 "single_slot({populated:?}) must be has_unique_populated_kind",
12416 );
12417 assert!(
12418 !parent.has_unique_missing_kind(),
12419 "single_slot({populated:?}) must NOT be has_unique_missing_kind (2 missing on ALL.len()==3)",
12420 );
12421 assert_eq!(
12422 parent.has_unique_populated_kind(),
12423 parent.populated_kind_count() == 1
12424 );
12425 assert_eq!(
12426 parent.has_unique_missing_kind(),
12427 parent.missing_kind_count() == 1
12428 );
12429 }
12430 }
12431
12432 /// SATURATED-PARENT pin — a `LocalParent` with EVERY slot populated
12433 /// returns `false` at BOTH `has_unique_populated_kind` (three
12434 /// populated, not one) AND `has_unique_missing_kind` (zero missing,
12435 /// not one). Pins the top-arm of the populated cardinality (which
12436 /// is NOT the one-arm) and the zero-arm of the missing cardinality
12437 /// (also NOT the one-arm) on the same fixture — the two primitives
12438 /// coincide on `false` here, distinguishing them from the
12439 /// (near-)saturation and near-empty arms outside the LocalParent
12440 /// scaffold's reach.
12441 #[test]
12442 fn tagged_union_default_has_unique_kinds_on_saturated_parent() {
12443 let p = LocalParent {
12444 alpha: Some(1),
12445 beta: Some(2),
12446 gamma: Some(3),
12447 };
12448 assert!(
12449 !p.has_unique_populated_kind(),
12450 "saturated parent must NOT be has_unique_populated_kind (three populated)",
12451 );
12452 assert!(
12453 !p.has_unique_missing_kind(),
12454 "saturated parent must NOT be has_unique_missing_kind (zero missing)",
12455 );
12456 assert_eq!(p.has_unique_populated_kind(), p.populated_kind_count() == 1);
12457 assert_eq!(p.has_unique_missing_kind(), p.missing_kind_count() == 1);
12458 }
12459
12460 /// NEAR-SATURATED (two-slot) pin — a `LocalParent` with exactly
12461 /// two slots populated returns `false` at `has_unique_populated_kind`
12462 /// (two populated, not one) AND `true` at `has_unique_missing_kind`
12463 /// (one missing on `ALL.len() == 3`). This is the SOLE arm on the
12464 /// LocalParent scaffold where the two Boolean cardinality-mid-
12465 /// endpoint peers DIVERGE — the pin distinguishes them from every
12466 /// other truth-table arm where they coincide.
12467 #[test]
12468 fn tagged_union_default_has_unique_kinds_on_near_saturated_parent() {
12469 for parent in [
12470 LocalParent {
12471 alpha: Some(1),
12472 beta: Some(2),
12473 ..Default::default()
12474 },
12475 LocalParent {
12476 alpha: Some(1),
12477 gamma: Some(3),
12478 ..Default::default()
12479 },
12480 LocalParent {
12481 beta: Some(2),
12482 gamma: Some(3),
12483 ..Default::default()
12484 },
12485 ] {
12486 assert!(
12487 !parent.has_unique_populated_kind(),
12488 "near-saturated parent must NOT be has_unique_populated_kind (2 populated)",
12489 );
12490 assert!(
12491 parent.has_unique_missing_kind(),
12492 "near-saturated parent must be has_unique_missing_kind (1 missing)",
12493 );
12494 assert_eq!(
12495 parent.has_unique_populated_kind(),
12496 parent.populated_kind_count() == 1,
12497 );
12498 assert_eq!(
12499 parent.has_unique_missing_kind(),
12500 parent.missing_kind_count() == 1,
12501 );
12502 }
12503 }
12504
12505 // -------------------------------------------------------------------
12506 // `TaggedUnion::has_multiple_(populated|missing)_kinds` default-body
12507 // truth table — pin the four cardinality arms (empty, single-slot
12508 // diagonal, near-saturated, saturated) on the sibling-shaped
12509 // `LocalParent` scaffold. These two primitives are the Boolean
12510 // cardinality many-arm peers of `populated_kind_count() >= 2` and
12511 // `missing_kind_count() >= 2` — the third arm of the {0, 1, ≥2}
12512 // cardinality trichotomy that closes alongside `is_empty` /
12513 // `has_unique_populated_kind` (populated axis) and `is_saturated` /
12514 // `has_unique_missing_kind` (missing axis).
12515 // -------------------------------------------------------------------
12516
12517 /// EMPTY-PARENT pin — an empty `LocalParent` returns `false` at
12518 /// `has_multiple_populated_kinds` (zero populated) AND `true` at
12519 /// `has_multiple_missing_kinds` (three missing on `ALL.len() == 3`,
12520 /// which is `>= 2`). Also pins the trichotomy partition law: on
12521 /// the empty arm exactly `is_empty()` is true on the populated
12522 /// axis, and exactly `has_multiple_missing_kinds()` is true on
12523 /// the missing axis.
12524 #[test]
12525 fn tagged_union_default_has_multiple_kinds_on_empty_parent() {
12526 let p = LocalParent::default();
12527 assert!(
12528 !p.has_multiple_populated_kinds(),
12529 "empty parent must NOT be has_multiple_populated_kinds (zero populated)",
12530 );
12531 assert!(
12532 p.has_multiple_missing_kinds(),
12533 "empty parent must be has_multiple_missing_kinds (three missing on ALL.len() == 3)",
12534 );
12535 // Composition laws.
12536 assert_eq!(
12537 p.has_multiple_populated_kinds(),
12538 p.populated_kind_count() >= 2
12539 );
12540 assert_eq!(p.has_multiple_missing_kinds(), p.missing_kind_count() >= 2);
12541 // Trichotomy partition — EXACTLY ONE of the three Boolean
12542 // primitives on each axis is true.
12543 assert_eq!(
12544 usize::from(p.is_empty())
12545 + usize::from(p.has_unique_populated_kind())
12546 + usize::from(p.has_multiple_populated_kinds()),
12547 1,
12548 "populated-axis trichotomy must be exactly-one on the empty arm",
12549 );
12550 assert_eq!(
12551 usize::from(p.is_saturated())
12552 + usize::from(p.has_unique_missing_kind())
12553 + usize::from(p.has_multiple_missing_kinds()),
12554 1,
12555 "missing-axis trichotomy must be exactly-one on the empty arm",
12556 );
12557 }
12558
12559 /// SINGLE-SLOT-DIAGONAL pin — a `LocalParent` populating exactly
12560 /// one slot returns `false` at `has_multiple_populated_kinds` AND
12561 /// `true` at `has_multiple_missing_kinds` (two missing on
12562 /// `ALL.len() == 3`, which is `>= 2`).
12563 #[test]
12564 fn tagged_union_default_has_multiple_kinds_on_single_slot_diagonal() {
12565 for (populated, parent) in [
12566 (
12567 LocalKind::Alpha,
12568 LocalParent {
12569 alpha: Some(1),
12570 ..Default::default()
12571 },
12572 ),
12573 (
12574 LocalKind::Beta,
12575 LocalParent {
12576 beta: Some(2),
12577 ..Default::default()
12578 },
12579 ),
12580 (
12581 LocalKind::Gamma,
12582 LocalParent {
12583 gamma: Some(3),
12584 ..Default::default()
12585 },
12586 ),
12587 ] {
12588 assert!(
12589 !parent.has_multiple_populated_kinds(),
12590 "single_slot({populated:?}) must NOT be has_multiple_populated_kinds",
12591 );
12592 assert!(
12593 parent.has_multiple_missing_kinds(),
12594 "single_slot({populated:?}) must be has_multiple_missing_kinds (2 missing on ALL.len() == 3)",
12595 );
12596 assert_eq!(
12597 parent.has_multiple_populated_kinds(),
12598 parent.populated_kind_count() >= 2,
12599 );
12600 assert_eq!(
12601 parent.has_multiple_missing_kinds(),
12602 parent.missing_kind_count() >= 2,
12603 );
12604 // Trichotomy partition — well-formed arm satisfies
12605 // `has_unique_populated_kind` on the populated axis and
12606 // `has_multiple_missing_kinds` on the missing axis.
12607 assert_eq!(
12608 usize::from(parent.is_empty())
12609 + usize::from(parent.has_unique_populated_kind())
12610 + usize::from(parent.has_multiple_populated_kinds()),
12611 1,
12612 "populated-axis trichotomy must be exactly-one on single_slot({populated:?})",
12613 );
12614 assert_eq!(
12615 usize::from(parent.is_saturated())
12616 + usize::from(parent.has_unique_missing_kind())
12617 + usize::from(parent.has_multiple_missing_kinds()),
12618 1,
12619 "missing-axis trichotomy must be exactly-one on single_slot({populated:?})",
12620 );
12621 }
12622 }
12623
12624 /// NEAR-SATURATED (two-slot) pin — a `LocalParent` with exactly
12625 /// two slots populated returns `true` at `has_multiple_populated_kinds`
12626 /// (two populated) AND `false` at `has_multiple_missing_kinds`
12627 /// (one missing on `ALL.len() == 3`).
12628 #[test]
12629 fn tagged_union_default_has_multiple_kinds_on_near_saturated_parent() {
12630 for parent in [
12631 LocalParent {
12632 alpha: Some(1),
12633 beta: Some(2),
12634 ..Default::default()
12635 },
12636 LocalParent {
12637 alpha: Some(1),
12638 gamma: Some(3),
12639 ..Default::default()
12640 },
12641 LocalParent {
12642 beta: Some(2),
12643 gamma: Some(3),
12644 ..Default::default()
12645 },
12646 ] {
12647 assert!(
12648 parent.has_multiple_populated_kinds(),
12649 "near-saturated parent must be has_multiple_populated_kinds (2 populated)",
12650 );
12651 assert!(
12652 !parent.has_multiple_missing_kinds(),
12653 "near-saturated parent must NOT be has_multiple_missing_kinds (1 missing)",
12654 );
12655 assert_eq!(
12656 parent.has_multiple_populated_kinds(),
12657 parent.populated_kind_count() >= 2,
12658 );
12659 assert_eq!(
12660 parent.has_multiple_missing_kinds(),
12661 parent.missing_kind_count() >= 2,
12662 );
12663 // Trichotomy partition — near-saturated arm satisfies
12664 // `has_multiple_populated_kinds` on the populated axis and
12665 // `has_unique_missing_kind` on the missing axis.
12666 assert_eq!(
12667 usize::from(parent.is_empty())
12668 + usize::from(parent.has_unique_populated_kind())
12669 + usize::from(parent.has_multiple_populated_kinds()),
12670 1,
12671 "populated-axis trichotomy must be exactly-one on near-saturated arm",
12672 );
12673 assert_eq!(
12674 usize::from(parent.is_saturated())
12675 + usize::from(parent.has_unique_missing_kind())
12676 + usize::from(parent.has_multiple_missing_kinds()),
12677 1,
12678 "missing-axis trichotomy must be exactly-one on near-saturated arm",
12679 );
12680 }
12681 }
12682
12683 /// SATURATED-PARENT pin — a `LocalParent` with EVERY slot
12684 /// populated returns `true` at `has_multiple_populated_kinds`
12685 /// (three populated) AND `false` at `has_multiple_missing_kinds`
12686 /// (zero missing).
12687 #[test]
12688 fn tagged_union_default_has_multiple_kinds_on_saturated_parent() {
12689 let p = LocalParent {
12690 alpha: Some(1),
12691 beta: Some(2),
12692 gamma: Some(3),
12693 };
12694 assert!(
12695 p.has_multiple_populated_kinds(),
12696 "saturated parent must be has_multiple_populated_kinds (three populated)",
12697 );
12698 assert!(
12699 !p.has_multiple_missing_kinds(),
12700 "saturated parent must NOT be has_multiple_missing_kinds (zero missing)",
12701 );
12702 assert_eq!(
12703 p.has_multiple_populated_kinds(),
12704 p.populated_kind_count() >= 2
12705 );
12706 assert_eq!(p.has_multiple_missing_kinds(), p.missing_kind_count() >= 2);
12707 // Trichotomy partition — saturated arm satisfies
12708 // `has_multiple_populated_kinds` on the populated axis and
12709 // `is_saturated` on the missing axis.
12710 assert_eq!(
12711 usize::from(p.is_empty())
12712 + usize::from(p.has_unique_populated_kind())
12713 + usize::from(p.has_multiple_populated_kinds()),
12714 1,
12715 "populated-axis trichotomy must be exactly-one on saturated arm",
12716 );
12717 assert_eq!(
12718 usize::from(p.is_saturated())
12719 + usize::from(p.has_unique_missing_kind())
12720 + usize::from(p.has_multiple_missing_kinds()),
12721 1,
12722 "missing-axis trichotomy must be exactly-one on saturated arm",
12723 );
12724 }
12725
12726 /// The `assert_is_empty_matches_populated_kind_count` primitive
12727 /// accepts the [`LocalParent`] scaffold coherently.
12728 #[test]
12729 fn assert_is_empty_matches_populated_kind_count_accepts_coherent_local_impl() {
12730 fn make_local(k: LocalKind) -> LocalParent {
12731 match k {
12732 LocalKind::Alpha => LocalParent {
12733 alpha: Some(11),
12734 ..Default::default()
12735 },
12736 LocalKind::Beta => LocalParent {
12737 beta: Some(22),
12738 ..Default::default()
12739 },
12740 LocalKind::Gamma => LocalParent {
12741 gamma: Some(33),
12742 ..Default::default()
12743 },
12744 }
12745 }
12746 assert_is_empty_matches_populated_kind_count::<LocalParent, _, _>(
12747 make_local,
12748 LocalParent::default,
12749 );
12750 }
12751
12752 /// A factory that yields an all-empty parent on the single-slot
12753 /// diagonal (so `is_empty()` returns `true` when the diagonal
12754 /// contract requires `false`) MUST fail-loudly at the caller's
12755 /// site through the primitive's single-slot-diagonal arm — a
12756 /// regression that dropped the `!is_empty` assertion on the
12757 /// well-formed arm surfaces here.
12758 #[test]
12759 #[should_panic(expected = "must equal false")]
12760 fn assert_is_empty_matches_populated_kind_count_rejects_empty_factory() {
12761 fn empty_factory(_: LocalKind) -> LocalParent {
12762 LocalParent::default()
12763 }
12764 assert_is_empty_matches_populated_kind_count::<LocalParent, _, _>(
12765 empty_factory,
12766 LocalParent::default,
12767 );
12768 }
12769
12770 /// A factory that yields a NON-empty parent from `empty_parent()`
12771 /// (so `is_empty()` returns `false` when the baseline contract
12772 /// requires `true`) MUST fail-loudly at the caller's site through
12773 /// the primitive's baseline arm — a regression that dropped the
12774 /// empty-parent baseline assertion surfaces here.
12775 #[test]
12776 #[should_panic(expected = "on empty_parent() must equal true")]
12777 fn assert_is_empty_matches_populated_kind_count_rejects_non_empty_baseline() {
12778 fn make_local(k: LocalKind) -> LocalParent {
12779 match k {
12780 LocalKind::Alpha => LocalParent {
12781 alpha: Some(11),
12782 ..Default::default()
12783 },
12784 LocalKind::Beta => LocalParent {
12785 beta: Some(22),
12786 ..Default::default()
12787 },
12788 LocalKind::Gamma => LocalParent {
12789 gamma: Some(33),
12790 ..Default::default()
12791 },
12792 }
12793 }
12794 fn non_empty_baseline() -> LocalParent {
12795 LocalParent {
12796 alpha: Some(999),
12797 ..Default::default()
12798 }
12799 }
12800 assert_is_empty_matches_populated_kind_count::<LocalParent, _, _>(
12801 make_local,
12802 non_empty_baseline,
12803 );
12804 }
12805
12806 /// The `assert_is_saturated_matches_missing_kind_count` primitive
12807 /// accepts the [`LocalParent`] scaffold coherently.
12808 #[test]
12809 fn assert_is_saturated_matches_missing_kind_count_accepts_coherent_local_impl() {
12810 fn make_local(k: LocalKind) -> LocalParent {
12811 match k {
12812 LocalKind::Alpha => LocalParent {
12813 alpha: Some(11),
12814 ..Default::default()
12815 },
12816 LocalKind::Beta => LocalParent {
12817 beta: Some(22),
12818 ..Default::default()
12819 },
12820 LocalKind::Gamma => LocalParent {
12821 gamma: Some(33),
12822 ..Default::default()
12823 },
12824 }
12825 }
12826 assert_is_saturated_matches_missing_kind_count::<LocalParent, _, _>(
12827 make_local,
12828 LocalParent::default,
12829 );
12830 }
12831
12832 /// A factory that yields a saturated parent on the single-slot
12833 /// diagonal (so `is_saturated()` returns `true` when the diagonal
12834 /// contract requires `false`) MUST fail-loudly at the caller's
12835 /// site through the primitive's single-slot-diagonal arm.
12836 #[test]
12837 #[should_panic(expected = "must equal false")]
12838 fn assert_is_saturated_matches_missing_kind_count_rejects_saturated_factory() {
12839 fn saturated_factory(_: LocalKind) -> LocalParent {
12840 LocalParent {
12841 alpha: Some(1),
12842 beta: Some(2),
12843 gamma: Some(3),
12844 }
12845 }
12846 assert_is_saturated_matches_missing_kind_count::<LocalParent, _, _>(
12847 saturated_factory,
12848 LocalParent::default,
12849 );
12850 }
12851
12852 /// A factory that yields a saturated parent from `empty_parent()`
12853 /// (so `is_saturated()` returns `true` when the baseline contract
12854 /// requires `false`) MUST fail-loudly at the caller's site through
12855 /// the primitive's baseline arm.
12856 #[test]
12857 #[should_panic(expected = "on empty_parent() must equal false")]
12858 fn assert_is_saturated_matches_missing_kind_count_rejects_saturated_baseline() {
12859 fn make_local(k: LocalKind) -> LocalParent {
12860 match k {
12861 LocalKind::Alpha => LocalParent {
12862 alpha: Some(11),
12863 ..Default::default()
12864 },
12865 LocalKind::Beta => LocalParent {
12866 beta: Some(22),
12867 ..Default::default()
12868 },
12869 LocalKind::Gamma => LocalParent {
12870 gamma: Some(33),
12871 ..Default::default()
12872 },
12873 }
12874 }
12875 fn saturated_baseline() -> LocalParent {
12876 LocalParent {
12877 alpha: Some(1),
12878 beta: Some(2),
12879 gamma: Some(3),
12880 }
12881 }
12882 assert_is_saturated_matches_missing_kind_count::<LocalParent, _, _>(
12883 make_local,
12884 saturated_baseline,
12885 );
12886 }
12887
12888 /// Every one of the four production `.variant()` sites on
12889 /// `ProcessSpec` binds through the zero-populated-cardinality
12890 /// Boolean primitive coherently — every per-site `single_slot_X(k)`
12891 /// factory produces a `!is_empty()` parent, and
12892 /// `X::default().is_empty() == true` on the empty-parent baseline.
12893 #[test]
12894 fn every_production_tagged_union_binds_through_the_is_empty_testkit_primitive() {
12895 assert_is_empty_matches_populated_kind_count::<crate::intent::Intent, _, _>(
12896 single_slot_intent_probe,
12897 crate::intent::Intent::default,
12898 );
12899 assert_is_empty_matches_populated_kind_count::<crate::encapsulates::EncapsulationKind, _, _>(
12900 single_slot_encapsulation_kind_probe,
12901 crate::encapsulates::EncapsulationKind::default,
12902 );
12903 assert_is_empty_matches_populated_kind_count::<crate::export::ArtifactSource, _, _>(
12904 single_slot_artifact_source_probe,
12905 crate::export::ArtifactSource::default,
12906 );
12907 assert_is_empty_matches_populated_kind_count::<crate::export::VectorChannel, _, _>(
12908 single_slot_vector_channel_probe,
12909 crate::export::VectorChannel::default,
12910 );
12911 }
12912
12913 /// Every one of the four production `.variant()` sites on
12914 /// `ProcessSpec` binds through the zero-missing-cardinality
12915 /// Boolean primitive coherently — every per-site `single_slot_X(k)`
12916 /// factory produces a `!is_saturated()` parent (there are ≥ 2
12917 /// missing slots on every real-world tagged union in the
12918 /// workspace), and `X::default().is_saturated() == false` on the
12919 /// empty-parent baseline.
12920 #[test]
12921 fn every_production_tagged_union_binds_through_the_is_saturated_testkit_primitive() {
12922 assert_is_saturated_matches_missing_kind_count::<crate::intent::Intent, _, _>(
12923 single_slot_intent_probe,
12924 crate::intent::Intent::default,
12925 );
12926 assert_is_saturated_matches_missing_kind_count::<
12927 crate::encapsulates::EncapsulationKind,
12928 _,
12929 _,
12930 >(
12931 single_slot_encapsulation_kind_probe,
12932 crate::encapsulates::EncapsulationKind::default,
12933 );
12934 assert_is_saturated_matches_missing_kind_count::<crate::export::ArtifactSource, _, _>(
12935 single_slot_artifact_source_probe,
12936 crate::export::ArtifactSource::default,
12937 );
12938 assert_is_saturated_matches_missing_kind_count::<crate::export::VectorChannel, _, _>(
12939 single_slot_vector_channel_probe,
12940 crate::export::VectorChannel::default,
12941 );
12942 }
12943
12944 /// The `assert_has_any_populated_kind_matches_populated_kind_count`
12945 /// primitive accepts the [`LocalParent`] scaffold coherently.
12946 #[test]
12947 fn assert_has_any_populated_kind_matches_populated_kind_count_accepts_coherent_local_impl() {
12948 fn make_local(k: LocalKind) -> LocalParent {
12949 match k {
12950 LocalKind::Alpha => LocalParent {
12951 alpha: Some(11),
12952 ..Default::default()
12953 },
12954 LocalKind::Beta => LocalParent {
12955 beta: Some(22),
12956 ..Default::default()
12957 },
12958 LocalKind::Gamma => LocalParent {
12959 gamma: Some(33),
12960 ..Default::default()
12961 },
12962 }
12963 }
12964 assert_has_any_populated_kind_matches_populated_kind_count::<LocalParent, _, _>(
12965 make_local,
12966 LocalParent::default,
12967 );
12968 }
12969
12970 /// A factory that yields an all-empty parent on the single-slot
12971 /// diagonal (so `has_any_populated_kind()` returns `false` when the
12972 /// diagonal contract requires `true`) MUST fail-loudly at the
12973 /// caller's site through the primitive's single-slot-diagonal arm.
12974 #[test]
12975 #[should_panic(expected = "must equal true")]
12976 fn assert_has_any_populated_kind_matches_populated_kind_count_rejects_empty_factory() {
12977 fn empty_factory(_: LocalKind) -> LocalParent {
12978 LocalParent::default()
12979 }
12980 assert_has_any_populated_kind_matches_populated_kind_count::<LocalParent, _, _>(
12981 empty_factory,
12982 LocalParent::default,
12983 );
12984 }
12985
12986 /// A factory that yields a NON-empty parent from `empty_parent()`
12987 /// (so `has_any_populated_kind()` returns `true` when the baseline
12988 /// contract requires `false`) MUST fail-loudly at the caller's site
12989 /// through the primitive's baseline arm.
12990 #[test]
12991 #[should_panic(expected = "on empty_parent() must equal false")]
12992 fn assert_has_any_populated_kind_matches_populated_kind_count_rejects_non_empty_baseline() {
12993 fn make_local(k: LocalKind) -> LocalParent {
12994 match k {
12995 LocalKind::Alpha => LocalParent {
12996 alpha: Some(11),
12997 ..Default::default()
12998 },
12999 LocalKind::Beta => LocalParent {
13000 beta: Some(22),
13001 ..Default::default()
13002 },
13003 LocalKind::Gamma => LocalParent {
13004 gamma: Some(33),
13005 ..Default::default()
13006 },
13007 }
13008 }
13009 fn non_empty_baseline() -> LocalParent {
13010 LocalParent {
13011 alpha: Some(999),
13012 ..Default::default()
13013 }
13014 }
13015 assert_has_any_populated_kind_matches_populated_kind_count::<LocalParent, _, _>(
13016 make_local,
13017 non_empty_baseline,
13018 );
13019 }
13020
13021 /// The `assert_has_any_missing_kind_matches_missing_kind_count`
13022 /// primitive accepts the [`LocalParent`] scaffold coherently.
13023 /// `LocalKind::ALL.len() == 3` so a well-formed single-slot parent
13024 /// has `3 - 1 == 2` missing slots, meaning `has_any_missing_kind()
13025 /// == true` on the diagonal.
13026 #[test]
13027 fn assert_has_any_missing_kind_matches_missing_kind_count_accepts_coherent_local_impl() {
13028 fn make_local(k: LocalKind) -> LocalParent {
13029 match k {
13030 LocalKind::Alpha => LocalParent {
13031 alpha: Some(11),
13032 ..Default::default()
13033 },
13034 LocalKind::Beta => LocalParent {
13035 beta: Some(22),
13036 ..Default::default()
13037 },
13038 LocalKind::Gamma => LocalParent {
13039 gamma: Some(33),
13040 ..Default::default()
13041 },
13042 }
13043 }
13044 assert_has_any_missing_kind_matches_missing_kind_count::<LocalParent, _, _>(
13045 make_local,
13046 LocalParent::default,
13047 );
13048 }
13049
13050 /// A factory that yields a saturated parent on the single-slot
13051 /// diagonal (so `has_any_missing_kind()` returns `false` when the
13052 /// diagonal contract requires `true`) MUST fail-loudly at the
13053 /// caller's site through the primitive's single-slot-diagonal arm.
13054 #[test]
13055 #[should_panic(expected = "must equal true")]
13056 fn assert_has_any_missing_kind_matches_missing_kind_count_rejects_saturated_factory() {
13057 fn saturated_factory(_: LocalKind) -> LocalParent {
13058 LocalParent {
13059 alpha: Some(1),
13060 beta: Some(2),
13061 gamma: Some(3),
13062 }
13063 }
13064 assert_has_any_missing_kind_matches_missing_kind_count::<LocalParent, _, _>(
13065 saturated_factory,
13066 LocalParent::default,
13067 );
13068 }
13069
13070 /// A factory that yields a saturated parent from `empty_parent()`
13071 /// (so `has_any_missing_kind()` returns `false` when the baseline
13072 /// contract requires `true`) MUST fail-loudly at the caller's site
13073 /// through the primitive's baseline arm.
13074 #[test]
13075 #[should_panic(expected = "on empty_parent() must equal true")]
13076 fn assert_has_any_missing_kind_matches_missing_kind_count_rejects_saturated_baseline() {
13077 fn make_local(k: LocalKind) -> LocalParent {
13078 match k {
13079 LocalKind::Alpha => LocalParent {
13080 alpha: Some(11),
13081 ..Default::default()
13082 },
13083 LocalKind::Beta => LocalParent {
13084 beta: Some(22),
13085 ..Default::default()
13086 },
13087 LocalKind::Gamma => LocalParent {
13088 gamma: Some(33),
13089 ..Default::default()
13090 },
13091 }
13092 }
13093 fn saturated_baseline() -> LocalParent {
13094 LocalParent {
13095 alpha: Some(1),
13096 beta: Some(2),
13097 gamma: Some(3),
13098 }
13099 }
13100 assert_has_any_missing_kind_matches_missing_kind_count::<LocalParent, _, _>(
13101 make_local,
13102 saturated_baseline,
13103 );
13104 }
13105
13106 /// Every one of the four production `.variant()` sites on
13107 /// `ProcessSpec` binds through the at-least-one-populated-
13108 /// cardinality Boolean primitive coherently — every per-site
13109 /// `single_slot_X(k)` factory produces a `has_any_populated_kind()
13110 /// == true` parent, and `X::default().has_any_populated_kind() ==
13111 /// false` on the empty-parent baseline.
13112 #[test]
13113 fn every_production_tagged_union_binds_through_the_has_any_populated_kind_testkit_primitive() {
13114 assert_has_any_populated_kind_matches_populated_kind_count::<crate::intent::Intent, _, _>(
13115 single_slot_intent_probe,
13116 crate::intent::Intent::default,
13117 );
13118 assert_has_any_populated_kind_matches_populated_kind_count::<
13119 crate::encapsulates::EncapsulationKind,
13120 _,
13121 _,
13122 >(
13123 single_slot_encapsulation_kind_probe,
13124 crate::encapsulates::EncapsulationKind::default,
13125 );
13126 assert_has_any_populated_kind_matches_populated_kind_count::<
13127 crate::export::ArtifactSource,
13128 _,
13129 _,
13130 >(
13131 single_slot_artifact_source_probe,
13132 crate::export::ArtifactSource::default,
13133 );
13134 assert_has_any_populated_kind_matches_populated_kind_count::<
13135 crate::export::VectorChannel,
13136 _,
13137 _,
13138 >(
13139 single_slot_vector_channel_probe,
13140 crate::export::VectorChannel::default,
13141 );
13142 }
13143
13144 /// Every one of the four production `.variant()` sites on
13145 /// `ProcessSpec` binds through the at-least-one-missing-
13146 /// cardinality Boolean primitive coherently — every per-site
13147 /// `single_slot_X(k)` factory produces a `has_any_missing_kind() ==
13148 /// true` parent (there are ≥ 2 missing slots on every real-world
13149 /// tagged union in the workspace, since `ALL.len() ≥ 2`), and
13150 /// `X::default().has_any_missing_kind() == true` on the empty-
13151 /// parent baseline (every slot is missing).
13152 #[test]
13153 fn every_production_tagged_union_binds_through_the_has_any_missing_kind_testkit_primitive() {
13154 assert_has_any_missing_kind_matches_missing_kind_count::<crate::intent::Intent, _, _>(
13155 single_slot_intent_probe,
13156 crate::intent::Intent::default,
13157 );
13158 assert_has_any_missing_kind_matches_missing_kind_count::<
13159 crate::encapsulates::EncapsulationKind,
13160 _,
13161 _,
13162 >(
13163 single_slot_encapsulation_kind_probe,
13164 crate::encapsulates::EncapsulationKind::default,
13165 );
13166 assert_has_any_missing_kind_matches_missing_kind_count::<crate::export::ArtifactSource, _, _>(
13167 single_slot_artifact_source_probe,
13168 crate::export::ArtifactSource::default,
13169 );
13170 assert_has_any_missing_kind_matches_missing_kind_count::<crate::export::VectorChannel, _, _>(
13171 single_slot_vector_channel_probe,
13172 crate::export::VectorChannel::default,
13173 );
13174 }
13175
13176 /// The `assert_has_unique_populated_kind_matches_populated_kind_count`
13177 /// primitive accepts the [`LocalParent`] scaffold coherently.
13178 #[test]
13179 fn assert_has_unique_populated_kind_matches_populated_kind_count_accepts_coherent_local_impl() {
13180 fn make_local(k: LocalKind) -> LocalParent {
13181 match k {
13182 LocalKind::Alpha => LocalParent {
13183 alpha: Some(11),
13184 ..Default::default()
13185 },
13186 LocalKind::Beta => LocalParent {
13187 beta: Some(22),
13188 ..Default::default()
13189 },
13190 LocalKind::Gamma => LocalParent {
13191 gamma: Some(33),
13192 ..Default::default()
13193 },
13194 }
13195 }
13196 assert_has_unique_populated_kind_matches_populated_kind_count::<LocalParent, _, _>(
13197 make_local,
13198 LocalParent::default,
13199 );
13200 }
13201
13202 /// A factory that yields an all-empty parent on the single-slot
13203 /// diagonal (so `has_unique_populated_kind()` returns `false` when
13204 /// the diagonal contract requires `true`) MUST fail-loudly at the
13205 /// caller's site through the primitive's single-slot-diagonal arm.
13206 #[test]
13207 #[should_panic(expected = "must equal true")]
13208 fn assert_has_unique_populated_kind_matches_populated_kind_count_rejects_empty_factory() {
13209 fn empty_factory(_: LocalKind) -> LocalParent {
13210 LocalParent::default()
13211 }
13212 assert_has_unique_populated_kind_matches_populated_kind_count::<LocalParent, _, _>(
13213 empty_factory,
13214 LocalParent::default,
13215 );
13216 }
13217
13218 /// A factory that yields a WELL-FORMED parent from `empty_parent()`
13219 /// (so `has_unique_populated_kind()` returns `true` when the
13220 /// baseline contract requires `false`) MUST fail-loudly at the
13221 /// caller's site through the primitive's baseline arm.
13222 #[test]
13223 #[should_panic(expected = "on empty_parent() must equal false")]
13224 fn assert_has_unique_populated_kind_matches_populated_kind_count_rejects_wellformed_baseline() {
13225 fn make_local(k: LocalKind) -> LocalParent {
13226 match k {
13227 LocalKind::Alpha => LocalParent {
13228 alpha: Some(11),
13229 ..Default::default()
13230 },
13231 LocalKind::Beta => LocalParent {
13232 beta: Some(22),
13233 ..Default::default()
13234 },
13235 LocalKind::Gamma => LocalParent {
13236 gamma: Some(33),
13237 ..Default::default()
13238 },
13239 }
13240 }
13241 fn wellformed_baseline() -> LocalParent {
13242 LocalParent {
13243 alpha: Some(999),
13244 ..Default::default()
13245 }
13246 }
13247 assert_has_unique_populated_kind_matches_populated_kind_count::<LocalParent, _, _>(
13248 make_local,
13249 wellformed_baseline,
13250 );
13251 }
13252
13253 /// The `assert_has_unique_missing_kind_matches_missing_kind_count`
13254 /// primitive accepts the [`LocalParent`] scaffold coherently.
13255 /// `LocalKind::ALL.len() == 3` so a well-formed single-slot parent
13256 /// has `3 - 1 == 2` missing slots, meaning
13257 /// `has_unique_missing_kind() == false` on the diagonal.
13258 #[test]
13259 fn assert_has_unique_missing_kind_matches_missing_kind_count_accepts_coherent_local_impl() {
13260 fn make_local(k: LocalKind) -> LocalParent {
13261 match k {
13262 LocalKind::Alpha => LocalParent {
13263 alpha: Some(11),
13264 ..Default::default()
13265 },
13266 LocalKind::Beta => LocalParent {
13267 beta: Some(22),
13268 ..Default::default()
13269 },
13270 LocalKind::Gamma => LocalParent {
13271 gamma: Some(33),
13272 ..Default::default()
13273 },
13274 }
13275 }
13276 assert_has_unique_missing_kind_matches_missing_kind_count::<LocalParent, _, _>(
13277 make_local,
13278 LocalParent::default,
13279 );
13280 }
13281
13282 /// A factory that yields a NEAR-SATURATED (two-slot) parent on the
13283 /// single-slot diagonal — so `has_unique_missing_kind()` returns
13284 /// `true` (exactly one missing on an `ALL.len() == 3` closed set)
13285 /// when the diagonal contract on this scaffold requires `false`
13286 /// (a well-formed one-slot parent has two missing, not one) — MUST
13287 /// fail-loudly at the caller's site through the primitive's
13288 /// single-slot-diagonal arm.
13289 #[test]
13290 #[should_panic(expected = "must equal false")]
13291 fn assert_has_unique_missing_kind_matches_missing_kind_count_rejects_near_saturated_factory() {
13292 fn near_saturated(k: LocalKind) -> LocalParent {
13293 // Populate two slots regardless of `k`, leaving exactly one
13294 // missing — mimics a factory that "helpfully" pre-populates
13295 // extras and drifts off the well-formed diagonal.
13296 let mut p = LocalParent {
13297 alpha: Some(1),
13298 beta: Some(2),
13299 ..Default::default()
13300 };
13301 if let LocalKind::Gamma = k {
13302 p.gamma = Some(3);
13303 // Now saturated — drop back to two-slot by clearing
13304 // alpha, so exactly one missing again.
13305 p.alpha = None;
13306 }
13307 p
13308 }
13309 assert_has_unique_missing_kind_matches_missing_kind_count::<LocalParent, _, _>(
13310 near_saturated,
13311 LocalParent::default,
13312 );
13313 }
13314
13315 /// A factory that yields a NEAR-SATURATED parent from
13316 /// `empty_parent()` (so `has_unique_missing_kind()` returns `true`
13317 /// when the baseline contract requires `false`) MUST fail-loudly
13318 /// at the caller's site through the primitive's baseline arm.
13319 #[test]
13320 #[should_panic(expected = "on empty_parent() must equal false")]
13321 fn assert_has_unique_missing_kind_matches_missing_kind_count_rejects_near_saturated_baseline() {
13322 fn make_local(k: LocalKind) -> LocalParent {
13323 match k {
13324 LocalKind::Alpha => LocalParent {
13325 alpha: Some(11),
13326 ..Default::default()
13327 },
13328 LocalKind::Beta => LocalParent {
13329 beta: Some(22),
13330 ..Default::default()
13331 },
13332 LocalKind::Gamma => LocalParent {
13333 gamma: Some(33),
13334 ..Default::default()
13335 },
13336 }
13337 }
13338 fn near_saturated_baseline() -> LocalParent {
13339 LocalParent {
13340 alpha: Some(1),
13341 beta: Some(2),
13342 ..Default::default()
13343 }
13344 }
13345 assert_has_unique_missing_kind_matches_missing_kind_count::<LocalParent, _, _>(
13346 make_local,
13347 near_saturated_baseline,
13348 );
13349 }
13350
13351 /// Every one of the four production `.variant()` sites on
13352 /// `ProcessSpec` binds through the one-populated-cardinality
13353 /// Boolean primitive coherently — every per-site `single_slot_X(k)`
13354 /// factory produces a `has_unique_populated_kind() == true` parent,
13355 /// and `X::default().has_unique_populated_kind() == false` on the
13356 /// empty-parent baseline.
13357 #[test]
13358 fn every_production_tagged_union_binds_through_the_has_unique_populated_kind_testkit_primitive()
13359 {
13360 assert_has_unique_populated_kind_matches_populated_kind_count::<crate::intent::Intent, _, _>(
13361 single_slot_intent_probe,
13362 crate::intent::Intent::default,
13363 );
13364 assert_has_unique_populated_kind_matches_populated_kind_count::<
13365 crate::encapsulates::EncapsulationKind,
13366 _,
13367 _,
13368 >(
13369 single_slot_encapsulation_kind_probe,
13370 crate::encapsulates::EncapsulationKind::default,
13371 );
13372 assert_has_unique_populated_kind_matches_populated_kind_count::<
13373 crate::export::ArtifactSource,
13374 _,
13375 _,
13376 >(
13377 single_slot_artifact_source_probe,
13378 crate::export::ArtifactSource::default,
13379 );
13380 assert_has_unique_populated_kind_matches_populated_kind_count::<
13381 crate::export::VectorChannel,
13382 _,
13383 _,
13384 >(
13385 single_slot_vector_channel_probe,
13386 crate::export::VectorChannel::default,
13387 );
13388 }
13389
13390 /// Every one of the four production `.variant()` sites on
13391 /// `ProcessSpec` binds through the one-missing-cardinality Boolean
13392 /// primitive coherently — every per-site `single_slot_X(k)` factory
13393 /// produces a `has_unique_missing_kind() == false` parent (there
13394 /// are ≥ 2 missing slots on every real-world tagged union in the
13395 /// workspace: `Intent` `ALL.len() == 6`, `EncapsulationKind` `>= 3`,
13396 /// `ArtifactSource` `>= 3`, `VectorChannel` `>= 3`), and
13397 /// `X::default().has_unique_missing_kind() == false` on the empty-
13398 /// parent baseline (every slot missing, not exactly one).
13399 #[test]
13400 fn every_production_tagged_union_binds_through_the_has_unique_missing_kind_testkit_primitive() {
13401 assert_has_unique_missing_kind_matches_missing_kind_count::<crate::intent::Intent, _, _>(
13402 single_slot_intent_probe,
13403 crate::intent::Intent::default,
13404 );
13405 assert_has_unique_missing_kind_matches_missing_kind_count::<
13406 crate::encapsulates::EncapsulationKind,
13407 _,
13408 _,
13409 >(
13410 single_slot_encapsulation_kind_probe,
13411 crate::encapsulates::EncapsulationKind::default,
13412 );
13413 assert_has_unique_missing_kind_matches_missing_kind_count::<
13414 crate::export::ArtifactSource,
13415 _,
13416 _,
13417 >(
13418 single_slot_artifact_source_probe,
13419 crate::export::ArtifactSource::default,
13420 );
13421 assert_has_unique_missing_kind_matches_missing_kind_count::<
13422 crate::export::VectorChannel,
13423 _,
13424 _,
13425 >(
13426 single_slot_vector_channel_probe,
13427 crate::export::VectorChannel::default,
13428 );
13429 }
13430
13431 // -------------------------------------------------------------------
13432 // `assert_has_multiple_(populated|missing)_kinds_matches_(populated|
13433 // missing)_kind_count` — the ≥2-cardinality Boolean testkit
13434 // primitives. Pin acceptance on the coherent LocalParent scaffold +
13435 // rejection on the two obvious factory drifts + a production sweep
13436 // binding all four `.variant()` sites through the trichotomy law
13437 // (is_empty + has_unique_populated_kind + has_multiple_populated_kinds
13438 // == 1 on every arm, and the missing-axis peer).
13439 // -------------------------------------------------------------------
13440
13441 /// The `assert_has_multiple_populated_kinds_matches_populated_kind_count`
13442 /// primitive accepts the [`LocalParent`] scaffold coherently — the
13443 /// coherent-impl side has no false-positive drift on the empty
13444 /// baseline, the single-slot diagonal, or the two-slot sweep.
13445 #[test]
13446 fn assert_has_multiple_populated_kinds_matches_populated_kind_count_accepts_coherent_local_impl(
13447 ) {
13448 fn single_slot(k: LocalKind) -> LocalParent {
13449 match k {
13450 LocalKind::Alpha => LocalParent {
13451 alpha: Some(1),
13452 ..Default::default()
13453 },
13454 LocalKind::Beta => LocalParent {
13455 beta: Some(2),
13456 ..Default::default()
13457 },
13458 LocalKind::Gamma => LocalParent {
13459 gamma: Some(3),
13460 ..Default::default()
13461 },
13462 }
13463 }
13464 fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
13465 let mut p = LocalParent::default();
13466 for k in [a, b] {
13467 match k {
13468 LocalKind::Alpha => p.alpha = Some(1),
13469 LocalKind::Beta => p.beta = Some(2),
13470 LocalKind::Gamma => p.gamma = Some(3),
13471 }
13472 }
13473 p
13474 }
13475 assert_has_multiple_populated_kinds_matches_populated_kind_count::<LocalParent, _, _, _>(
13476 single_slot,
13477 two_slot,
13478 LocalParent::default,
13479 );
13480 }
13481
13482 /// The primitive rejects an `empty_parent` factory that yields a
13483 /// two-slot parent (baseline expects zero-populated on empty).
13484 #[test]
13485 #[should_panic(
13486 expected = "TaggedUnion::has_multiple_populated_kinds() on empty_parent() must equal false"
13487 )]
13488 fn assert_has_multiple_populated_kinds_matches_populated_kind_count_rejects_two_slot_baseline()
13489 {
13490 fn single_slot(k: LocalKind) -> LocalParent {
13491 match k {
13492 LocalKind::Alpha => LocalParent {
13493 alpha: Some(1),
13494 ..Default::default()
13495 },
13496 LocalKind::Beta => LocalParent {
13497 beta: Some(2),
13498 ..Default::default()
13499 },
13500 LocalKind::Gamma => LocalParent {
13501 gamma: Some(3),
13502 ..Default::default()
13503 },
13504 }
13505 }
13506 fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
13507 let mut p = LocalParent::default();
13508 for k in [a, b] {
13509 match k {
13510 LocalKind::Alpha => p.alpha = Some(1),
13511 LocalKind::Beta => p.beta = Some(2),
13512 LocalKind::Gamma => p.gamma = Some(3),
13513 }
13514 }
13515 p
13516 }
13517 fn two_slot_baseline() -> LocalParent {
13518 LocalParent {
13519 alpha: Some(1),
13520 beta: Some(2),
13521 ..Default::default()
13522 }
13523 }
13524 assert_has_multiple_populated_kinds_matches_populated_kind_count::<LocalParent, _, _, _>(
13525 single_slot,
13526 two_slot,
13527 two_slot_baseline,
13528 );
13529 }
13530
13531 /// The primitive rejects a `two_slot` factory that yields a
13532 /// single-slot parent (two-slot sweep expects has_multiple ==
13533 /// true).
13534 #[test]
13535 #[should_panic(expected = "TaggedUnion::has_multiple_populated_kinds() on two_slot(")]
13536 fn assert_has_multiple_populated_kinds_matches_populated_kind_count_rejects_single_slot_two_slot_factory(
13537 ) {
13538 fn single_slot(k: LocalKind) -> LocalParent {
13539 match k {
13540 LocalKind::Alpha => LocalParent {
13541 alpha: Some(1),
13542 ..Default::default()
13543 },
13544 LocalKind::Beta => LocalParent {
13545 beta: Some(2),
13546 ..Default::default()
13547 },
13548 LocalKind::Gamma => LocalParent {
13549 gamma: Some(3),
13550 ..Default::default()
13551 },
13552 }
13553 }
13554 fn drifted_two_slot(a: LocalKind, _: LocalKind) -> LocalParent {
13555 // Only populates the first slot — the two-slot invariant
13556 // is violated.
13557 single_slot(a)
13558 }
13559 assert_has_multiple_populated_kinds_matches_populated_kind_count::<LocalParent, _, _, _>(
13560 single_slot,
13561 drifted_two_slot,
13562 LocalParent::default,
13563 );
13564 }
13565
13566 /// The `assert_has_multiple_missing_kinds_matches_missing_kind_count`
13567 /// primitive accepts the [`LocalParent`] scaffold coherently.
13568 #[test]
13569 fn assert_has_multiple_missing_kinds_matches_missing_kind_count_accepts_coherent_local_impl() {
13570 fn single_slot(k: LocalKind) -> LocalParent {
13571 match k {
13572 LocalKind::Alpha => LocalParent {
13573 alpha: Some(1),
13574 ..Default::default()
13575 },
13576 LocalKind::Beta => LocalParent {
13577 beta: Some(2),
13578 ..Default::default()
13579 },
13580 LocalKind::Gamma => LocalParent {
13581 gamma: Some(3),
13582 ..Default::default()
13583 },
13584 }
13585 }
13586 fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
13587 let mut p = LocalParent::default();
13588 for k in [a, b] {
13589 match k {
13590 LocalKind::Alpha => p.alpha = Some(1),
13591 LocalKind::Beta => p.beta = Some(2),
13592 LocalKind::Gamma => p.gamma = Some(3),
13593 }
13594 }
13595 p
13596 }
13597 assert_has_multiple_missing_kinds_matches_missing_kind_count::<LocalParent, _, _, _>(
13598 single_slot,
13599 two_slot,
13600 LocalParent::default,
13601 );
13602 }
13603
13604 /// The primitive rejects a `two_slot` factory that yields an
13605 /// empty parent (two-slot expects `ALL.len() - 2 == 1` missing
13606 /// on `LocalParent`, whose composition law asserts
13607 /// `has_multiple_missing_kinds() == false`; an empty factory
13608 /// yields `ALL.len() == 3` missing where the primitive returns
13609 /// `true` — the composition law and the trichotomy both drift).
13610 #[test]
13611 #[should_panic]
13612 fn assert_has_multiple_missing_kinds_matches_missing_kind_count_rejects_empty_two_slot_factory()
13613 {
13614 fn single_slot(k: LocalKind) -> LocalParent {
13615 match k {
13616 LocalKind::Alpha => LocalParent {
13617 alpha: Some(1),
13618 ..Default::default()
13619 },
13620 LocalKind::Beta => LocalParent {
13621 beta: Some(2),
13622 ..Default::default()
13623 },
13624 LocalKind::Gamma => LocalParent {
13625 gamma: Some(3),
13626 ..Default::default()
13627 },
13628 }
13629 }
13630 fn empty_two_slot(_: LocalKind, _: LocalKind) -> LocalParent {
13631 // Always yields an empty parent — zero populated, three
13632 // missing. The two-slot invariant is violated.
13633 LocalParent::default()
13634 }
13635 assert_has_multiple_missing_kinds_matches_missing_kind_count::<LocalParent, _, _, _>(
13636 single_slot,
13637 empty_two_slot,
13638 LocalParent::default,
13639 );
13640 }
13641
13642 /// The primitive rejects a `empty_parent` factory that yields a
13643 /// saturated parent (empty baseline expects has_multiple_missing
13644 /// == true on ALL.len() == 3 since 3 missing >= 2).
13645 #[test]
13646 #[should_panic]
13647 fn assert_has_multiple_missing_kinds_matches_missing_kind_count_rejects_saturated_empty_baseline(
13648 ) {
13649 fn single_slot(k: LocalKind) -> LocalParent {
13650 match k {
13651 LocalKind::Alpha => LocalParent {
13652 alpha: Some(1),
13653 ..Default::default()
13654 },
13655 LocalKind::Beta => LocalParent {
13656 beta: Some(2),
13657 ..Default::default()
13658 },
13659 LocalKind::Gamma => LocalParent {
13660 gamma: Some(3),
13661 ..Default::default()
13662 },
13663 }
13664 }
13665 fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
13666 let mut p = LocalParent::default();
13667 for k in [a, b] {
13668 match k {
13669 LocalKind::Alpha => p.alpha = Some(1),
13670 LocalKind::Beta => p.beta = Some(2),
13671 LocalKind::Gamma => p.gamma = Some(3),
13672 }
13673 }
13674 p
13675 }
13676 fn saturated_baseline() -> LocalParent {
13677 LocalParent {
13678 alpha: Some(1),
13679 beta: Some(2),
13680 gamma: Some(3),
13681 }
13682 }
13683 assert_has_multiple_missing_kinds_matches_missing_kind_count::<LocalParent, _, _, _>(
13684 single_slot,
13685 two_slot,
13686 saturated_baseline,
13687 );
13688 }
13689
13690 /// Every one of the four production `.variant()` sites on
13691 /// `ProcessSpec` binds through the many-cardinality Boolean
13692 /// primitive on the populated axis coherently — every per-site
13693 /// `single_slot_X(k)` factory produces `has_multiple_populated_kinds()
13694 /// == false`, every `two_slot_X(a, b)` produces `== true`, and
13695 /// `X::default().has_multiple_populated_kinds() == false`. The
13696 /// trichotomy partition law (`is_empty` plus `has_unique_populated_kind`
13697 /// plus `has_multiple_populated_kinds` sums to `1`) is pinned inside
13698 /// the testkit on every arm.
13699 #[test]
13700 fn every_production_tagged_union_binds_through_the_has_multiple_populated_kinds_testkit_primitive(
13701 ) {
13702 assert_has_multiple_populated_kinds_matches_populated_kind_count::<
13703 crate::intent::Intent,
13704 _,
13705 _,
13706 _,
13707 >(
13708 single_slot_intent_probe,
13709 two_slot_intent_probe,
13710 crate::intent::Intent::default,
13711 );
13712 assert_has_multiple_populated_kinds_matches_populated_kind_count::<
13713 crate::encapsulates::EncapsulationKind,
13714 _,
13715 _,
13716 _,
13717 >(
13718 single_slot_encapsulation_kind_probe,
13719 two_slot_encapsulation_kind_probe,
13720 crate::encapsulates::EncapsulationKind::default,
13721 );
13722 assert_has_multiple_populated_kinds_matches_populated_kind_count::<
13723 crate::export::ArtifactSource,
13724 _,
13725 _,
13726 _,
13727 >(
13728 single_slot_artifact_source_probe,
13729 two_slot_artifact_source_probe,
13730 crate::export::ArtifactSource::default,
13731 );
13732 assert_has_multiple_populated_kinds_matches_populated_kind_count::<
13733 crate::export::VectorChannel,
13734 _,
13735 _,
13736 _,
13737 >(
13738 single_slot_vector_channel_probe,
13739 two_slot_vector_channel_probe,
13740 crate::export::VectorChannel::default,
13741 );
13742 }
13743
13744 /// Every one of the four production `.variant()` sites on
13745 /// `ProcessSpec` binds through the many-cardinality Boolean
13746 /// primitive on the missing axis coherently. On `Intent`
13747 /// (`ALL.len() == 6`), `EncapsulationKind` (`>= 3`),
13748 /// `ArtifactSource` (`>= 3`), `VectorChannel` (`>= 3`), the
13749 /// single-slot diagonal returns `true` (`ALL.len() - 1 >= 2`);
13750 /// on `Intent` (`ALL.len() == 6 >= 4`) the two-slot sweep also
13751 /// returns `true`. The trichotomy partition law on the missing
13752 /// axis (`is_saturated + has_unique_missing_kind +
13753 /// has_multiple_missing_kinds == 1`) is pinned inside the testkit
13754 /// on every arm.
13755 #[test]
13756 fn every_production_tagged_union_binds_through_the_has_multiple_missing_kinds_testkit_primitive(
13757 ) {
13758 assert_has_multiple_missing_kinds_matches_missing_kind_count::<
13759 crate::intent::Intent,
13760 _,
13761 _,
13762 _,
13763 >(
13764 single_slot_intent_probe,
13765 two_slot_intent_probe,
13766 crate::intent::Intent::default,
13767 );
13768 assert_has_multiple_missing_kinds_matches_missing_kind_count::<
13769 crate::encapsulates::EncapsulationKind,
13770 _,
13771 _,
13772 _,
13773 >(
13774 single_slot_encapsulation_kind_probe,
13775 two_slot_encapsulation_kind_probe,
13776 crate::encapsulates::EncapsulationKind::default,
13777 );
13778 assert_has_multiple_missing_kinds_matches_missing_kind_count::<
13779 crate::export::ArtifactSource,
13780 _,
13781 _,
13782 _,
13783 >(
13784 single_slot_artifact_source_probe,
13785 two_slot_artifact_source_probe,
13786 crate::export::ArtifactSource::default,
13787 );
13788 assert_has_multiple_missing_kinds_matches_missing_kind_count::<
13789 crate::export::VectorChannel,
13790 _,
13791 _,
13792 _,
13793 >(
13794 single_slot_vector_channel_probe,
13795 two_slot_vector_channel_probe,
13796 crate::export::VectorChannel::default,
13797 );
13798 }
13799
13800 // -------------------------------------------------------------------
13801 // `assert_has_at_most_one_(populated|missing)_kind_matches_(populated|
13802 // missing)_kind_count` — the ≤1-cardinality Boolean testkit
13803 // primitives. Boolean-negation peer of the ≥2 testkits above;
13804 // pin acceptance on the coherent LocalParent scaffold + a
13805 // production sweep binding all four `.variant()` sites through
13806 // the three composition laws (definitional Boolean-negation,
13807 // scalar cardinality, and trichotomy union).
13808 // -------------------------------------------------------------------
13809
13810 /// The `assert_has_at_most_one_populated_kind_matches_populated_kind_count`
13811 /// primitive accepts the [`LocalParent`] scaffold coherently — the
13812 /// coherent-impl side reads `true` on the empty baseline (0 ≤ 1)
13813 /// and every single-slot arrangement (1 ≤ 1), and `false` on every
13814 /// off-diagonal two-slot arrangement (2 > 1). All three composition
13815 /// laws hold on every arm.
13816 #[test]
13817 fn assert_has_at_most_one_populated_kind_matches_populated_kind_count_accepts_coherent_local_impl(
13818 ) {
13819 fn single_slot(k: LocalKind) -> LocalParent {
13820 match k {
13821 LocalKind::Alpha => LocalParent {
13822 alpha: Some(1),
13823 ..Default::default()
13824 },
13825 LocalKind::Beta => LocalParent {
13826 beta: Some(2),
13827 ..Default::default()
13828 },
13829 LocalKind::Gamma => LocalParent {
13830 gamma: Some(3),
13831 ..Default::default()
13832 },
13833 }
13834 }
13835 fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
13836 let mut p = LocalParent::default();
13837 for k in [a, b] {
13838 match k {
13839 LocalKind::Alpha => p.alpha = Some(1),
13840 LocalKind::Beta => p.beta = Some(2),
13841 LocalKind::Gamma => p.gamma = Some(3),
13842 }
13843 }
13844 p
13845 }
13846 assert_has_at_most_one_populated_kind_matches_populated_kind_count::<LocalParent, _, _, _>(
13847 single_slot,
13848 two_slot,
13849 LocalParent::default,
13850 );
13851 }
13852
13853 /// The primitive rejects a `two_slot` factory that yields a
13854 /// well-formed single-populated parent — the two-slot sweep expects
13855 /// `has_at_most_one_populated_kind() == false` (2 > 1), but a
13856 /// single-slot yields `true` (1 ≤ 1).
13857 #[test]
13858 #[should_panic(expected = "TaggedUnion::has_at_most_one_populated_kind() on two_slot(")]
13859 fn assert_has_at_most_one_populated_kind_matches_populated_kind_count_rejects_single_slot_two_slot_factory(
13860 ) {
13861 fn single_slot(k: LocalKind) -> LocalParent {
13862 match k {
13863 LocalKind::Alpha => LocalParent {
13864 alpha: Some(1),
13865 ..Default::default()
13866 },
13867 LocalKind::Beta => LocalParent {
13868 beta: Some(2),
13869 ..Default::default()
13870 },
13871 LocalKind::Gamma => LocalParent {
13872 gamma: Some(3),
13873 ..Default::default()
13874 },
13875 }
13876 }
13877 fn single_slot_two_slot(a: LocalKind, _b: LocalKind) -> LocalParent {
13878 match a {
13879 LocalKind::Alpha => LocalParent {
13880 alpha: Some(1),
13881 ..Default::default()
13882 },
13883 LocalKind::Beta => LocalParent {
13884 beta: Some(2),
13885 ..Default::default()
13886 },
13887 LocalKind::Gamma => LocalParent {
13888 gamma: Some(3),
13889 ..Default::default()
13890 },
13891 }
13892 }
13893 assert_has_at_most_one_populated_kind_matches_populated_kind_count::<LocalParent, _, _, _>(
13894 single_slot,
13895 single_slot_two_slot,
13896 LocalParent::default,
13897 );
13898 }
13899
13900 /// The `assert_has_at_most_one_missing_kind_matches_missing_kind_count`
13901 /// primitive accepts the [`LocalParent`] scaffold coherently. On
13902 /// `ALL.len() == 3` the missing counts are: empty=3, single_slot=2,
13903 /// two_slot=1, saturated=0. So `has_at_most_one_missing_kind()`
13904 /// reads `false` on empty (3 > 1), `false` on single_slot (2 > 1),
13905 /// `true` on two_slot (1 ≤ 1). All three composition laws hold on
13906 /// every arm.
13907 #[test]
13908 fn assert_has_at_most_one_missing_kind_matches_missing_kind_count_accepts_coherent_local_impl()
13909 {
13910 fn single_slot(k: LocalKind) -> LocalParent {
13911 match k {
13912 LocalKind::Alpha => LocalParent {
13913 alpha: Some(1),
13914 ..Default::default()
13915 },
13916 LocalKind::Beta => LocalParent {
13917 beta: Some(2),
13918 ..Default::default()
13919 },
13920 LocalKind::Gamma => LocalParent {
13921 gamma: Some(3),
13922 ..Default::default()
13923 },
13924 }
13925 }
13926 fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
13927 let mut p = LocalParent::default();
13928 for k in [a, b] {
13929 match k {
13930 LocalKind::Alpha => p.alpha = Some(1),
13931 LocalKind::Beta => p.beta = Some(2),
13932 LocalKind::Gamma => p.gamma = Some(3),
13933 }
13934 }
13935 p
13936 }
13937 assert_has_at_most_one_missing_kind_matches_missing_kind_count::<LocalParent, _, _, _>(
13938 single_slot,
13939 two_slot,
13940 LocalParent::default,
13941 );
13942 }
13943
13944 /// The primitive rejects a saturated `empty_parent` factory — on
13945 /// `ALL.len() == 3` the baseline expects `has_at_most_one_missing_kind()
13946 /// == false` (all 3 missing on the genuine empty arm), but a
13947 /// saturated factory yields 0 missing → `true`.
13948 #[test]
13949 #[should_panic(
13950 expected = "TaggedUnion::has_at_most_one_missing_kind() on empty_parent() must equal false"
13951 )]
13952 fn assert_has_at_most_one_missing_kind_matches_missing_kind_count_rejects_saturated_empty_baseline(
13953 ) {
13954 fn single_slot(k: LocalKind) -> LocalParent {
13955 match k {
13956 LocalKind::Alpha => LocalParent {
13957 alpha: Some(1),
13958 ..Default::default()
13959 },
13960 LocalKind::Beta => LocalParent {
13961 beta: Some(2),
13962 ..Default::default()
13963 },
13964 LocalKind::Gamma => LocalParent {
13965 gamma: Some(3),
13966 ..Default::default()
13967 },
13968 }
13969 }
13970 fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
13971 let mut p = LocalParent::default();
13972 for k in [a, b] {
13973 match k {
13974 LocalKind::Alpha => p.alpha = Some(1),
13975 LocalKind::Beta => p.beta = Some(2),
13976 LocalKind::Gamma => p.gamma = Some(3),
13977 }
13978 }
13979 p
13980 }
13981 fn saturated_baseline() -> LocalParent {
13982 LocalParent {
13983 alpha: Some(1),
13984 beta: Some(2),
13985 gamma: Some(3),
13986 }
13987 }
13988 assert_has_at_most_one_missing_kind_matches_missing_kind_count::<LocalParent, _, _, _>(
13989 single_slot,
13990 two_slot,
13991 saturated_baseline,
13992 );
13993 }
13994
13995 /// Every one of the four production `.variant()` sites on
13996 /// `ProcessSpec` binds through the ≤1-populated-cardinality Boolean
13997 /// primitive coherently — every per-site `single_slot_X(k)` factory
13998 /// produces `has_at_most_one_populated_kind() == true` (1 ≤ 1),
13999 /// every `two_slot_X(a, b)` produces `== false` (2 > 1), and
14000 /// `X::default().has_at_most_one_populated_kind() == true` on the
14001 /// empty-parent baseline (0 ≤ 1). All three composition laws
14002 /// (definitional negation, scalar cardinality, trichotomy union)
14003 /// are pinned inside the testkit on every arm.
14004 #[test]
14005 fn every_production_tagged_union_binds_through_the_has_at_most_one_populated_kind_testkit_primitive(
14006 ) {
14007 assert_has_at_most_one_populated_kind_matches_populated_kind_count::<
14008 crate::intent::Intent,
14009 _,
14010 _,
14011 _,
14012 >(
14013 single_slot_intent_probe,
14014 two_slot_intent_probe,
14015 crate::intent::Intent::default,
14016 );
14017 assert_has_at_most_one_populated_kind_matches_populated_kind_count::<
14018 crate::encapsulates::EncapsulationKind,
14019 _,
14020 _,
14021 _,
14022 >(
14023 single_slot_encapsulation_kind_probe,
14024 two_slot_encapsulation_kind_probe,
14025 crate::encapsulates::EncapsulationKind::default,
14026 );
14027 assert_has_at_most_one_populated_kind_matches_populated_kind_count::<
14028 crate::export::ArtifactSource,
14029 _,
14030 _,
14031 _,
14032 >(
14033 single_slot_artifact_source_probe,
14034 two_slot_artifact_source_probe,
14035 crate::export::ArtifactSource::default,
14036 );
14037 assert_has_at_most_one_populated_kind_matches_populated_kind_count::<
14038 crate::export::VectorChannel,
14039 _,
14040 _,
14041 _,
14042 >(
14043 single_slot_vector_channel_probe,
14044 two_slot_vector_channel_probe,
14045 crate::export::VectorChannel::default,
14046 );
14047 }
14048
14049 /// Every one of the four production `.variant()` sites on
14050 /// `ProcessSpec` binds through the ≤1-missing-cardinality Boolean
14051 /// primitive coherently. On `Intent` (`ALL.len() == 6`),
14052 /// `EncapsulationKind` (`>= 3`), `ArtifactSource` (`>= 3`),
14053 /// `VectorChannel` (`>= 3`), the single-slot diagonal returns
14054 /// `false` (`ALL.len() - 1 >= 2`), the two-slot sweep returns
14055 /// `false` on any `ALL.len() >= 4` (Intent) and `true` on
14056 /// `ALL.len() == 3` (the smaller unions have `1 <= 1` missing on
14057 /// the two-slot arm), and the empty baseline returns `false`
14058 /// (`ALL.len() >= 2`).
14059 #[test]
14060 fn every_production_tagged_union_binds_through_the_has_at_most_one_missing_kind_testkit_primitive(
14061 ) {
14062 assert_has_at_most_one_missing_kind_matches_missing_kind_count::<
14063 crate::intent::Intent,
14064 _,
14065 _,
14066 _,
14067 >(
14068 single_slot_intent_probe,
14069 two_slot_intent_probe,
14070 crate::intent::Intent::default,
14071 );
14072 assert_has_at_most_one_missing_kind_matches_missing_kind_count::<
14073 crate::encapsulates::EncapsulationKind,
14074 _,
14075 _,
14076 _,
14077 >(
14078 single_slot_encapsulation_kind_probe,
14079 two_slot_encapsulation_kind_probe,
14080 crate::encapsulates::EncapsulationKind::default,
14081 );
14082 assert_has_at_most_one_missing_kind_matches_missing_kind_count::<
14083 crate::export::ArtifactSource,
14084 _,
14085 _,
14086 _,
14087 >(
14088 single_slot_artifact_source_probe,
14089 two_slot_artifact_source_probe,
14090 crate::export::ArtifactSource::default,
14091 );
14092 assert_has_at_most_one_missing_kind_matches_missing_kind_count::<
14093 crate::export::VectorChannel,
14094 _,
14095 _,
14096 _,
14097 >(
14098 single_slot_vector_channel_probe,
14099 two_slot_vector_channel_probe,
14100 crate::export::VectorChannel::default,
14101 );
14102 }
14103
14104 /// The `assert_is_partially_populated_matches_cardinality` primitive
14105 /// accepts the [`LocalParent`] scaffold coherently — the middle-arm
14106 /// Boolean projection reads `true` on every single-slot and two-slot
14107 /// arrangement (0 < populated < 3) and `false` on the empty
14108 /// baseline (0 populated), and the parent-state trichotomy partition
14109 /// (`is_empty + is_partially_populated + is_saturated == 1`) holds
14110 /// on every arm.
14111 #[test]
14112 fn assert_is_partially_populated_matches_cardinality_accepts_coherent_local_impl() {
14113 fn single_slot(k: LocalKind) -> LocalParent {
14114 match k {
14115 LocalKind::Alpha => LocalParent {
14116 alpha: Some(1),
14117 ..Default::default()
14118 },
14119 LocalKind::Beta => LocalParent {
14120 beta: Some(2),
14121 ..Default::default()
14122 },
14123 LocalKind::Gamma => LocalParent {
14124 gamma: Some(3),
14125 ..Default::default()
14126 },
14127 }
14128 }
14129 fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
14130 let mut p = LocalParent::default();
14131 for k in [a, b] {
14132 match k {
14133 LocalKind::Alpha => p.alpha = Some(1),
14134 LocalKind::Beta => p.beta = Some(2),
14135 LocalKind::Gamma => p.gamma = Some(3),
14136 }
14137 }
14138 p
14139 }
14140 assert_is_partially_populated_matches_cardinality::<LocalParent, _, _, _>(
14141 single_slot,
14142 two_slot,
14143 LocalParent::default,
14144 );
14145 }
14146
14147 /// The primitive rejects a `single_slot` factory that yields an
14148 /// empty parent (single-slot expects `is_partially_populated() ==
14149 /// true` because on `ALL.len() == 3` a well-formed parent has
14150 /// `1 populated + 2 missing` — but an empty factory yields 0
14151 /// populated, so the middle-arm assertion drifts).
14152 #[test]
14153 #[should_panic(expected = "must equal true")]
14154 fn assert_is_partially_populated_matches_cardinality_rejects_empty_single_slot_factory() {
14155 fn empty_single_slot(_: LocalKind) -> LocalParent {
14156 LocalParent::default()
14157 }
14158 fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
14159 let mut p = LocalParent::default();
14160 for k in [a, b] {
14161 match k {
14162 LocalKind::Alpha => p.alpha = Some(1),
14163 LocalKind::Beta => p.beta = Some(2),
14164 LocalKind::Gamma => p.gamma = Some(3),
14165 }
14166 }
14167 p
14168 }
14169 assert_is_partially_populated_matches_cardinality::<LocalParent, _, _, _>(
14170 empty_single_slot,
14171 two_slot,
14172 LocalParent::default,
14173 );
14174 }
14175
14176 /// The primitive rejects an `empty_parent` factory that yields a
14177 /// saturated parent (empty baseline expects
14178 /// `is_partially_populated() == false` because 0 populated is the
14179 /// empty arm — a saturated factory has `ALL.len()` populated + 0
14180 /// missing, which is ALSO the `false` arm of the middle Boolean
14181 /// but drifts on the trichotomy partition since
14182 /// `is_saturated == true` while the primitive expected
14183 /// `is_empty == true` on the baseline).
14184 #[test]
14185 #[should_panic]
14186 fn assert_is_partially_populated_matches_cardinality_rejects_saturated_empty_baseline() {
14187 fn single_slot(k: LocalKind) -> LocalParent {
14188 match k {
14189 LocalKind::Alpha => LocalParent {
14190 alpha: Some(1),
14191 ..Default::default()
14192 },
14193 LocalKind::Beta => LocalParent {
14194 beta: Some(2),
14195 ..Default::default()
14196 },
14197 LocalKind::Gamma => LocalParent {
14198 gamma: Some(3),
14199 ..Default::default()
14200 },
14201 }
14202 }
14203 fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
14204 let mut p = LocalParent::default();
14205 for k in [a, b] {
14206 match k {
14207 LocalKind::Alpha => p.alpha = Some(1),
14208 LocalKind::Beta => p.beta = Some(2),
14209 LocalKind::Gamma => p.gamma = Some(3),
14210 }
14211 }
14212 p
14213 }
14214 fn saturated_baseline() -> LocalParent {
14215 LocalParent {
14216 alpha: Some(1),
14217 beta: Some(2),
14218 gamma: Some(3),
14219 }
14220 }
14221 assert_is_partially_populated_matches_cardinality::<LocalParent, _, _, _>(
14222 single_slot,
14223 two_slot,
14224 saturated_baseline,
14225 );
14226 }
14227
14228 /// Every one of the four production `.variant()` sites on
14229 /// `ProcessSpec` binds through the parent-state-middle-arm Boolean
14230 /// primitive coherently — every per-site `single_slot_X(k)` factory
14231 /// produces `is_partially_populated() == true` (well-formed has
14232 /// `1 populated + ALL.len() - 1 ≥ 1 missing`), every
14233 /// `two_slot_X(a, b)` produces `== true` (`ALL.len() ≥ 3` on every
14234 /// production union so two_slot has `2 populated + ALL.len() - 2
14235 /// ≥ 1 missing`), and `X::default().is_partially_populated() ==
14236 /// false` on the empty-parent baseline. The parent-state
14237 /// trichotomy partition law (`is_empty + is_partially_populated
14238 /// + is_saturated == 1`) is pinned inside the testkit on every arm.
14239 #[test]
14240 fn every_production_tagged_union_binds_through_the_is_partially_populated_testkit_primitive() {
14241 assert_is_partially_populated_matches_cardinality::<crate::intent::Intent, _, _, _>(
14242 single_slot_intent_probe,
14243 two_slot_intent_probe,
14244 crate::intent::Intent::default,
14245 );
14246 assert_is_partially_populated_matches_cardinality::<
14247 crate::encapsulates::EncapsulationKind,
14248 _,
14249 _,
14250 _,
14251 >(
14252 single_slot_encapsulation_kind_probe,
14253 two_slot_encapsulation_kind_probe,
14254 crate::encapsulates::EncapsulationKind::default,
14255 );
14256 assert_is_partially_populated_matches_cardinality::<crate::export::ArtifactSource, _, _, _>(
14257 single_slot_artifact_source_probe,
14258 two_slot_artifact_source_probe,
14259 crate::export::ArtifactSource::default,
14260 );
14261 assert_is_partially_populated_matches_cardinality::<crate::export::VectorChannel, _, _, _>(
14262 single_slot_vector_channel_probe,
14263 two_slot_vector_channel_probe,
14264 crate::export::VectorChannel::default,
14265 );
14266 }
14267
14268 /// The `assert_has_only_matches_unique_populated_kind` primitive
14269 /// accepts the [`LocalParent`] scaffold coherently — the kind-scoped
14270 /// strict-refinement predicate reads `true` iff the probed kind
14271 /// equals the populated kind on every single-slot arrangement (the
14272 /// diagonal), `false` on every off-diagonal pair regardless of
14273 /// probed kind, and `false` on the empty baseline for every kind.
14274 /// The five composition laws (widened uniqueness, cardinality-
14275 /// refinement, kind-scoped implication, kind-domain exhaustivity,
14276 /// well-formed diagonal) hold on every arm.
14277 #[test]
14278 fn assert_has_only_matches_unique_populated_kind_accepts_coherent_local_impl() {
14279 fn single_slot(k: LocalKind) -> LocalParent {
14280 match k {
14281 LocalKind::Alpha => LocalParent {
14282 alpha: Some(1),
14283 ..Default::default()
14284 },
14285 LocalKind::Beta => LocalParent {
14286 beta: Some(2),
14287 ..Default::default()
14288 },
14289 LocalKind::Gamma => LocalParent {
14290 gamma: Some(3),
14291 ..Default::default()
14292 },
14293 }
14294 }
14295 fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
14296 let mut p = LocalParent::default();
14297 for k in [a, b] {
14298 match k {
14299 LocalKind::Alpha => p.alpha = Some(1),
14300 LocalKind::Beta => p.beta = Some(2),
14301 LocalKind::Gamma => p.gamma = Some(3),
14302 }
14303 }
14304 p
14305 }
14306 assert_has_only_matches_unique_populated_kind::<LocalParent, _, _, _>(
14307 single_slot,
14308 two_slot,
14309 LocalParent::default,
14310 );
14311 }
14312
14313 /// The primitive rejects a `single_slot` factory that populates
14314 /// the WRONG kind (always `Beta` regardless of what kind is asked
14315 /// for) — the well-formed diagonal law
14316 /// `single_slot(k).has_only(k) == true` fails on
14317 /// `k ∈ {Alpha, Gamma}` where the factory populated `Beta` instead.
14318 #[test]
14319 #[should_panic(expected = "must equal true")]
14320 fn assert_has_only_matches_unique_populated_kind_rejects_wrong_slot_factory() {
14321 fn always_beta(_: LocalKind) -> LocalParent {
14322 LocalParent {
14323 beta: Some(2),
14324 ..Default::default()
14325 }
14326 }
14327 fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
14328 let mut p = LocalParent::default();
14329 for k in [a, b] {
14330 match k {
14331 LocalKind::Alpha => p.alpha = Some(1),
14332 LocalKind::Beta => p.beta = Some(2),
14333 LocalKind::Gamma => p.gamma = Some(3),
14334 }
14335 }
14336 p
14337 }
14338 assert_has_only_matches_unique_populated_kind::<LocalParent, _, _, _>(
14339 always_beta,
14340 two_slot,
14341 LocalParent::default,
14342 );
14343 }
14344
14345 /// The primitive rejects an `empty_parent` factory that yields a
14346 /// saturated parent — the empty-baseline exhaustivity assertion
14347 /// `empty_parent().is_empty() == true` fails on the saturated
14348 /// baseline, catching a factory that mis-represents the empty arm.
14349 #[test]
14350 #[should_panic(expected = "must satisfy is_empty() == true")]
14351 fn assert_has_only_matches_unique_populated_kind_rejects_saturated_empty_baseline() {
14352 fn single_slot(k: LocalKind) -> LocalParent {
14353 match k {
14354 LocalKind::Alpha => LocalParent {
14355 alpha: Some(1),
14356 ..Default::default()
14357 },
14358 LocalKind::Beta => LocalParent {
14359 beta: Some(2),
14360 ..Default::default()
14361 },
14362 LocalKind::Gamma => LocalParent {
14363 gamma: Some(3),
14364 ..Default::default()
14365 },
14366 }
14367 }
14368 fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
14369 let mut p = LocalParent::default();
14370 for k in [a, b] {
14371 match k {
14372 LocalKind::Alpha => p.alpha = Some(1),
14373 LocalKind::Beta => p.beta = Some(2),
14374 LocalKind::Gamma => p.gamma = Some(3),
14375 }
14376 }
14377 p
14378 }
14379 fn saturated_baseline() -> LocalParent {
14380 LocalParent {
14381 alpha: Some(1),
14382 beta: Some(2),
14383 gamma: Some(3),
14384 }
14385 }
14386 assert_has_only_matches_unique_populated_kind::<LocalParent, _, _, _>(
14387 single_slot,
14388 two_slot,
14389 saturated_baseline,
14390 );
14391 }
14392
14393 /// Every one of the four production `.variant()` sites on
14394 /// `ProcessSpec` binds through the kind-scoped strict-refinement
14395 /// Boolean primitive coherently — every per-site `single_slot_X(k)`
14396 /// factory produces `has_only(k) == true` (well-formed truth table
14397 /// on the diagonal), every off-diagonal probe returns `false`
14398 /// (well-formed truth table off the diagonal), every
14399 /// `two_slot_X(a, b)` produces `has_only(k) == false` for every
14400 /// `k` (multi-populated arm), and `X::default().has_only(k) ==
14401 /// false` on the empty baseline for every `k`. The kind-domain
14402 /// exhaustivity law (`count k where has_only(k) ≤ 1` per parent,
14403 /// with equality iff well-formed) is pinned inside the testkit on
14404 /// every arm.
14405 #[test]
14406 fn every_production_tagged_union_binds_through_the_has_only_testkit_primitive() {
14407 assert_has_only_matches_unique_populated_kind::<crate::intent::Intent, _, _, _>(
14408 single_slot_intent_probe,
14409 two_slot_intent_probe,
14410 crate::intent::Intent::default,
14411 );
14412 assert_has_only_matches_unique_populated_kind::<
14413 crate::encapsulates::EncapsulationKind,
14414 _,
14415 _,
14416 _,
14417 >(
14418 single_slot_encapsulation_kind_probe,
14419 two_slot_encapsulation_kind_probe,
14420 crate::encapsulates::EncapsulationKind::default,
14421 );
14422 assert_has_only_matches_unique_populated_kind::<crate::export::ArtifactSource, _, _, _>(
14423 single_slot_artifact_source_probe,
14424 two_slot_artifact_source_probe,
14425 crate::export::ArtifactSource::default,
14426 );
14427 assert_has_only_matches_unique_populated_kind::<crate::export::VectorChannel, _, _, _>(
14428 single_slot_vector_channel_probe,
14429 two_slot_vector_channel_probe,
14430 crate::export::VectorChannel::default,
14431 );
14432 }
14433
14434 // -------------------------------------------------------------------
14435 // `assert_lacks_only_matches_unique_missing_kind` — the closed-set-
14436 // complement mirror of `assert_has_only_matches_unique_populated_kind`
14437 // on the MISSING axis. Pin the composition-law truth table
14438 // (`lacks_only(kind) == (unique_missing_kind() == Some(kind))`,
14439 // cardinality-refinement under complement, kind-scoped implication
14440 // under complement, kind-domain exhaustivity ≤ 1) directly on the
14441 // sibling-shaped `LocalParent` scaffold + on every one of the four
14442 // production `.variant()` parents — a regression on either the fused
14443 // walk's negated presence probe, the argument-scoped short-circuit,
14444 // or the exhaustivity partition fails here before any per-parent
14445 // consumer surfaces the drift.
14446 // -------------------------------------------------------------------
14447
14448 /// The `assert_lacks_only_matches_unique_missing_kind` primitive
14449 /// accepts the [`LocalParent`] scaffold coherently — the closed-set-
14450 /// complement mirror of the populated-axis kind-scoped strict-
14451 /// refinement predicate reads `true` iff the probed kind names the
14452 /// SOLE missing slot. On `LocalParent`'s `ALL.len() == 3` closed
14453 /// set: the empty baseline has 3 missing (so `lacks_only(k) ==
14454 /// false` for every `k`), every single-slot arm has 2 missing (so
14455 /// `lacks_only(k) == false` for every `k`), and every off-diagonal
14456 /// two-slot arm has 1 missing — the third kind, where `lacks_only`
14457 /// returns `true` for that one probe and `false` for the two
14458 /// populated probes. The four composition laws (widened
14459 /// uniqueness, cardinality-refinement under complement, kind-
14460 /// scoped implication under complement, kind-domain exhaustivity)
14461 /// hold on every arm.
14462 #[test]
14463 fn assert_lacks_only_matches_unique_missing_kind_accepts_coherent_local_impl() {
14464 fn single_slot(k: LocalKind) -> LocalParent {
14465 match k {
14466 LocalKind::Alpha => LocalParent {
14467 alpha: Some(1),
14468 ..Default::default()
14469 },
14470 LocalKind::Beta => LocalParent {
14471 beta: Some(2),
14472 ..Default::default()
14473 },
14474 LocalKind::Gamma => LocalParent {
14475 gamma: Some(3),
14476 ..Default::default()
14477 },
14478 }
14479 }
14480 fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
14481 let mut p = LocalParent::default();
14482 for k in [a, b] {
14483 match k {
14484 LocalKind::Alpha => p.alpha = Some(1),
14485 LocalKind::Beta => p.beta = Some(2),
14486 LocalKind::Gamma => p.gamma = Some(3),
14487 }
14488 }
14489 p
14490 }
14491 assert_lacks_only_matches_unique_missing_kind::<LocalParent, _, _, _>(
14492 single_slot,
14493 two_slot,
14494 LocalParent::default,
14495 );
14496 }
14497
14498 /// The primitive rejects a `two_slot` factory that yields a
14499 /// saturated parent (all three slots populated, zero missing) —
14500 /// the factory-precondition truth table on the two-slot arm reads
14501 /// `expected == (k != a && k != b)` for the third kind on
14502 /// `ALL.len() == 3`, but the saturated factory has zero missing so
14503 /// `lacks_only(third) == false` where `expected == true`. Caught
14504 /// by the hard-coded arm expectation BEFORE any composition law
14505 /// reconciles two internally-drifted trait bodies.
14506 #[test]
14507 #[should_panic(expected = "must equal true on ALL.len() == 3")]
14508 fn assert_lacks_only_matches_unique_missing_kind_rejects_saturated_two_slot_factory() {
14509 fn single_slot(k: LocalKind) -> LocalParent {
14510 match k {
14511 LocalKind::Alpha => LocalParent {
14512 alpha: Some(1),
14513 ..Default::default()
14514 },
14515 LocalKind::Beta => LocalParent {
14516 beta: Some(2),
14517 ..Default::default()
14518 },
14519 LocalKind::Gamma => LocalParent {
14520 gamma: Some(3),
14521 ..Default::default()
14522 },
14523 }
14524 }
14525 fn saturated_two_slot(_: LocalKind, _: LocalKind) -> LocalParent {
14526 // Always yields a saturated parent — zero missing.
14527 LocalParent {
14528 alpha: Some(1),
14529 beta: Some(2),
14530 gamma: Some(3),
14531 }
14532 }
14533 assert_lacks_only_matches_unique_missing_kind::<LocalParent, _, _, _>(
14534 single_slot,
14535 saturated_two_slot,
14536 LocalParent::default,
14537 );
14538 }
14539
14540 /// The primitive rejects a `empty_parent` factory that yields a
14541 /// saturated parent — the empty-baseline exhaustivity assertion
14542 /// `empty_parent().is_empty() == true` fails on the saturated
14543 /// baseline, catching a factory that mis-represents the empty arm.
14544 #[test]
14545 #[should_panic(expected = "must satisfy is_empty() == true")]
14546 fn assert_lacks_only_matches_unique_missing_kind_rejects_saturated_empty_baseline() {
14547 fn single_slot(k: LocalKind) -> LocalParent {
14548 match k {
14549 LocalKind::Alpha => LocalParent {
14550 alpha: Some(1),
14551 ..Default::default()
14552 },
14553 LocalKind::Beta => LocalParent {
14554 beta: Some(2),
14555 ..Default::default()
14556 },
14557 LocalKind::Gamma => LocalParent {
14558 gamma: Some(3),
14559 ..Default::default()
14560 },
14561 }
14562 }
14563 fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
14564 let mut p = LocalParent::default();
14565 for k in [a, b] {
14566 match k {
14567 LocalKind::Alpha => p.alpha = Some(1),
14568 LocalKind::Beta => p.beta = Some(2),
14569 LocalKind::Gamma => p.gamma = Some(3),
14570 }
14571 }
14572 p
14573 }
14574 fn saturated_baseline() -> LocalParent {
14575 LocalParent {
14576 alpha: Some(1),
14577 beta: Some(2),
14578 gamma: Some(3),
14579 }
14580 }
14581 assert_lacks_only_matches_unique_missing_kind::<LocalParent, _, _, _>(
14582 single_slot,
14583 two_slot,
14584 saturated_baseline,
14585 );
14586 }
14587
14588 /// Every one of the four production `.variant()` sites on
14589 /// `ProcessSpec` binds through the kind-scoped strict-refinement
14590 /// Boolean primitive on the MISSING axis coherently — on the
14591 /// three `ALL.len() == 3` sites (`EncapsulationKind`,
14592 /// `ArtifactSource`, `VectorChannel`) every off-diagonal
14593 /// `two_slot_X(a, b)` produces `lacks_only(third) == true` for
14594 /// exactly the third kind and `lacks_only(k) == false` for the
14595 /// two populated kinds; on the `ALL.len() == 6` site (`Intent`)
14596 /// every off-diagonal two-slot arm has 4 missing so `lacks_only(k)
14597 /// == false` for every `k`. Every single-slot arm on every site
14598 /// has `ALL.len() - 1 >= 2` missing, so `lacks_only(k) == false`
14599 /// for every `k`. The `X::default()` empty baseline on every site
14600 /// has `ALL.len() >= 3` missing, so `lacks_only(k) == false` for
14601 /// every `k`. The composition-law shape binds every regime
14602 /// through the same substrate site. The kind-domain exhaustivity
14603 /// law (`count k where lacks_only(k) ≤ 1` per parent, with
14604 /// equality iff exactly one slot is missing) is pinned inside the
14605 /// testkit on every arm.
14606 #[test]
14607 fn every_production_tagged_union_binds_through_the_lacks_only_testkit_primitive() {
14608 assert_lacks_only_matches_unique_missing_kind::<crate::intent::Intent, _, _, _>(
14609 single_slot_intent_probe,
14610 two_slot_intent_probe,
14611 crate::intent::Intent::default,
14612 );
14613 assert_lacks_only_matches_unique_missing_kind::<
14614 crate::encapsulates::EncapsulationKind,
14615 _,
14616 _,
14617 _,
14618 >(
14619 single_slot_encapsulation_kind_probe,
14620 two_slot_encapsulation_kind_probe,
14621 crate::encapsulates::EncapsulationKind::default,
14622 );
14623 assert_lacks_only_matches_unique_missing_kind::<crate::export::ArtifactSource, _, _, _>(
14624 single_slot_artifact_source_probe,
14625 two_slot_artifact_source_probe,
14626 crate::export::ArtifactSource::default,
14627 );
14628 assert_lacks_only_matches_unique_missing_kind::<crate::export::VectorChannel, _, _, _>(
14629 single_slot_vector_channel_probe,
14630 two_slot_vector_channel_probe,
14631 crate::export::VectorChannel::default,
14632 );
14633 }
14634
14635 // -------------------------------------------------------------------
14636 // `assert_lacks_matches_has_complement` — the missing-axis SUBSET
14637 // primitive testkit. Pin the composition-law truth table
14638 // (definitional complement, missing-set membership, kind-scoped
14639 // implication from lacks_only, cardinality partition against
14640 // missing_kind_count, factory-precondition arm expectation) directly
14641 // on the sibling-shaped `LocalParent` scaffold + on every one of the
14642 // four production `.variant()` parents — a regression on either the
14643 // definitional negation, the missing-set membership projection, or
14644 // the cardinality partition fails here before any per-parent
14645 // consumer surfaces the drift.
14646 // -------------------------------------------------------------------
14647
14648 /// The `assert_lacks_matches_has_complement` primitive accepts the
14649 /// [`LocalParent`] scaffold coherently — the closed-set-complement
14650 /// peer of the kind-scoped SUBSET populated-axis predicate reads
14651 /// `true` iff the probed kind is missing. On `LocalParent`'s
14652 /// `ALL.len() == 3` closed set: the empty baseline has 3 missing
14653 /// (so `lacks(k) == true` for every `k`), every single-slot arm
14654 /// has 2 missing (so `lacks(k) == true` for every `k != populated`
14655 /// and `false` for `k == populated`), and every off-diagonal
14656 /// two-slot arm has 1 missing (so `lacks(k) == true` for the third
14657 /// kind and `false` for the two populated kinds). The five
14658 /// composition laws (definitional complement, missing-set
14659 /// membership, kind-scoped implication from lacks_only,
14660 /// cardinality partition against missing_kind_count, factory-
14661 /// precondition arm expectation) hold on every arm.
14662 #[test]
14663 fn assert_lacks_matches_has_complement_accepts_coherent_local_impl() {
14664 fn single_slot(k: LocalKind) -> LocalParent {
14665 match k {
14666 LocalKind::Alpha => LocalParent {
14667 alpha: Some(1),
14668 ..Default::default()
14669 },
14670 LocalKind::Beta => LocalParent {
14671 beta: Some(2),
14672 ..Default::default()
14673 },
14674 LocalKind::Gamma => LocalParent {
14675 gamma: Some(3),
14676 ..Default::default()
14677 },
14678 }
14679 }
14680 fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
14681 let mut p = LocalParent::default();
14682 for k in [a, b] {
14683 match k {
14684 LocalKind::Alpha => p.alpha = Some(1),
14685 LocalKind::Beta => p.beta = Some(2),
14686 LocalKind::Gamma => p.gamma = Some(3),
14687 }
14688 }
14689 p
14690 }
14691 assert_lacks_matches_has_complement::<LocalParent, _, _, _>(
14692 single_slot,
14693 two_slot,
14694 LocalParent::default,
14695 );
14696 }
14697
14698 /// The primitive rejects a `single_slot` factory that yields a
14699 /// saturated parent (all three slots populated, zero missing) —
14700 /// the factory-precondition truth table on the well-formed
14701 /// single-slot arm reads `expected == (probed != populated)`, but
14702 /// the saturated factory has zero missing so `lacks(probed) ==
14703 /// false` for EVERY probe, mismatching the `true` expectation
14704 /// on every off-diagonal probe. Caught by the hard-coded arm
14705 /// expectation BEFORE the definitional complement law reconciles
14706 /// two internally-drifted trait bodies.
14707 #[test]
14708 #[should_panic(expected = "must equal true")]
14709 fn assert_lacks_matches_has_complement_rejects_saturated_single_slot_factory() {
14710 fn saturated_single_slot(_: LocalKind) -> LocalParent {
14711 LocalParent {
14712 alpha: Some(1),
14713 beta: Some(2),
14714 gamma: Some(3),
14715 }
14716 }
14717 fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
14718 let mut p = LocalParent::default();
14719 for k in [a, b] {
14720 match k {
14721 LocalKind::Alpha => p.alpha = Some(1),
14722 LocalKind::Beta => p.beta = Some(2),
14723 LocalKind::Gamma => p.gamma = Some(3),
14724 }
14725 }
14726 p
14727 }
14728 assert_lacks_matches_has_complement::<LocalParent, _, _, _>(
14729 saturated_single_slot,
14730 two_slot,
14731 LocalParent::default,
14732 );
14733 }
14734
14735 /// The primitive rejects an `empty_parent` factory that yields a
14736 /// saturated parent — the empty-baseline exhaustivity assertion
14737 /// `empty_parent().is_empty() == true` fails on the saturated
14738 /// baseline, catching a factory that mis-represents the empty arm
14739 /// BEFORE any composition law reconciles two internally-drifted
14740 /// trait bodies.
14741 #[test]
14742 #[should_panic(expected = "must satisfy is_empty() == true")]
14743 fn assert_lacks_matches_has_complement_rejects_saturated_empty_baseline() {
14744 fn single_slot(k: LocalKind) -> LocalParent {
14745 match k {
14746 LocalKind::Alpha => LocalParent {
14747 alpha: Some(1),
14748 ..Default::default()
14749 },
14750 LocalKind::Beta => LocalParent {
14751 beta: Some(2),
14752 ..Default::default()
14753 },
14754 LocalKind::Gamma => LocalParent {
14755 gamma: Some(3),
14756 ..Default::default()
14757 },
14758 }
14759 }
14760 fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
14761 let mut p = LocalParent::default();
14762 for k in [a, b] {
14763 match k {
14764 LocalKind::Alpha => p.alpha = Some(1),
14765 LocalKind::Beta => p.beta = Some(2),
14766 LocalKind::Gamma => p.gamma = Some(3),
14767 }
14768 }
14769 p
14770 }
14771 fn saturated_baseline() -> LocalParent {
14772 LocalParent {
14773 alpha: Some(1),
14774 beta: Some(2),
14775 gamma: Some(3),
14776 }
14777 }
14778 assert_lacks_matches_has_complement::<LocalParent, _, _, _>(
14779 single_slot,
14780 two_slot,
14781 saturated_baseline,
14782 );
14783 }
14784
14785 /// Every one of the four production `.variant()` sites on
14786 /// `ProcessSpec` binds through the closed-set-complement peer of
14787 /// `has` on the kind-scoped SUBSET axis coherently — every
14788 /// `single_slot_X(k)` factory produces `lacks(k) == false` on the
14789 /// diagonal and `lacks(other) == true` off-diagonal, every
14790 /// `two_slot_X(a, b)` produces `lacks(k) == true` iff `k != a && k
14791 /// != b`, and `X::default().lacks(k) == true` on the empty
14792 /// baseline for every `k`. The cardinality-partition law (`count k
14793 /// where lacks(k) == missing_kind_count()` per parent) is pinned
14794 /// inside the testkit on every arm.
14795 #[test]
14796 fn every_production_tagged_union_binds_through_the_lacks_testkit_primitive() {
14797 assert_lacks_matches_has_complement::<crate::intent::Intent, _, _, _>(
14798 single_slot_intent_probe,
14799 two_slot_intent_probe,
14800 crate::intent::Intent::default,
14801 );
14802 assert_lacks_matches_has_complement::<crate::encapsulates::EncapsulationKind, _, _, _>(
14803 single_slot_encapsulation_kind_probe,
14804 two_slot_encapsulation_kind_probe,
14805 crate::encapsulates::EncapsulationKind::default,
14806 );
14807 assert_lacks_matches_has_complement::<crate::export::ArtifactSource, _, _, _>(
14808 single_slot_artifact_source_probe,
14809 two_slot_artifact_source_probe,
14810 crate::export::ArtifactSource::default,
14811 );
14812 assert_lacks_matches_has_complement::<crate::export::VectorChannel, _, _, _>(
14813 single_slot_vector_channel_probe,
14814 two_slot_vector_channel_probe,
14815 crate::export::VectorChannel::default,
14816 );
14817 }
14818
14819 // -------------------------------------------------------------------
14820 // `assert_two_slots_ambiguous` — the ALL×ALL ambiguity sweep as ONE
14821 // substrate primitive. Pin the truth table (every off-diagonal pair
14822 // resolves to `TaggedUnionError::ambiguous`, diagonal pairs are
14823 // skipped, a factory that yields a non-Ambiguous parent fails-loudly
14824 // at the caller's site) directly on the sibling-shaped `LocalParent`
14825 // scaffold — a regression on either the pair-iteration order or the
14826 // expected-carrier composition fails here before any per-parent test
14827 // surfaces the drift.
14828 // -------------------------------------------------------------------
14829
14830 /// Every off-diagonal pair across [`LocalKind::ALL`] × `ALL`
14831 /// resolves through the substrate primitive to
14832 /// [`LocalParentError::Ambiguous`] on the sibling-shaped local
14833 /// scaffold. Pins the primitive's Ok arm (no false positives on the
14834 /// coherent-impl side) at ONE boundary — a regression that drops
14835 /// the diagonal skip, mis-iterates `ClosedSet::ALL`, or composes a
14836 /// divergent expected carrier fails here before any per-parent
14837 /// inherent test surfaces the drift.
14838 #[test]
14839 fn assert_two_slots_ambiguous_accepts_coherent_local_impl() {
14840 fn two_local(a: LocalKind, b: LocalKind) -> LocalParent {
14841 let mut p = LocalParent::default();
14842 for k in [a, b] {
14843 match k {
14844 LocalKind::Alpha => p.alpha = Some(11),
14845 LocalKind::Beta => p.beta = Some(22),
14846 LocalKind::Gamma => p.gamma = Some(33),
14847 }
14848 }
14849 p
14850 }
14851 assert_two_slots_ambiguous::<LocalParent, _>(two_local);
14852 }
14853
14854 /// A factory that yields a single-slot parent for the FIRST kind
14855 /// (ignoring the second) — every off-diagonal pair resolves to
14856 /// exactly-one Ok(Variant), NOT Ambiguous — MUST fail-loudly at
14857 /// the caller's site through the primitive's "two-slot parent
14858 /// must not resolve to a variant" arm. Pin the Ok-side failure
14859 /// mode so a regression that mis-routes the substrate primitive's
14860 /// resolved-Ok arm past the assertion (silently succeeding on a
14861 /// single-slot factory) is caught here.
14862 #[test]
14863 #[should_panic(expected = "two-slot parent must not resolve to a variant")]
14864 fn assert_two_slots_ambiguous_rejects_factory_that_populates_only_one_slot() {
14865 fn single_only(a: LocalKind, _: LocalKind) -> LocalParent {
14866 let mut p = LocalParent::default();
14867 match a {
14868 LocalKind::Alpha => p.alpha = Some(11),
14869 LocalKind::Beta => p.beta = Some(22),
14870 LocalKind::Gamma => p.gamma = Some(33),
14871 }
14872 p
14873 }
14874 assert_two_slots_ambiguous::<LocalParent, _>(single_only);
14875 }
14876
14877 /// A factory that yields an all-empty parent (so `.variant()`
14878 /// resolves to the `Empty` carrier, NOT `Ambiguous`) MUST
14879 /// fail-loudly at the caller's site through the primitive's
14880 /// `assert_eq!` arm — the composed expected carrier
14881 /// [`TaggedUnionError::ambiguous`] mismatches the resolved
14882 /// [`TaggedUnionError::empty`] carrier. Pin the Empty-arm failure
14883 /// mode so a regression that mis-projects the None arm of
14884 /// [`ResolveError`] onto Ambiguous (silently succeeding on an
14885 /// empty factory) is caught here.
14886 #[test]
14887 #[should_panic(expected = "should resolve Ambiguous")]
14888 fn assert_two_slots_ambiguous_rejects_factory_that_populates_no_slots() {
14889 fn empty_factory(_: LocalKind, _: LocalKind) -> LocalParent {
14890 LocalParent::default()
14891 }
14892 assert_two_slots_ambiguous::<LocalParent, _>(empty_factory);
14893 }
14894
14895 // -------------------------------------------------------------------
14896 // `assert_single_slot_key_matches_label` — the wire-key / kind-label
14897 // alignment sweep as ONE substrate primitive. Pin the truth table
14898 // (every populated slot serializes to exactly one JSON key whose
14899 // name equals the addressing kind's ClosedSet label; a factory that
14900 // populates the wrong slot / no slot / multiple slots fails-loudly
14901 // at the caller's site) directly on the sibling-shaped `LocalParent`
14902 // scaffold — a regression on either the exactly-one arm or the
14903 // name-equality arm fails here before any per-parent inherent test
14904 // surfaces the drift.
14905 // -------------------------------------------------------------------
14906
14907 /// Every kind across [`LocalKind::ALL`] serializes through the
14908 /// substrate primitive to a JSON object with EXACTLY ONE key whose
14909 /// name equals `<LocalKind as ClosedSet>::label` on the addressed
14910 /// kind. Pins the primitive's Ok arm (no false positives on the
14911 /// coherent-impl side) at ONE boundary — a regression that inspects
14912 /// the wrong serde value (e.g. `to_string` instead of `to_value`),
14913 /// counts fields off-by-one, or projects the wrong `ClosedSet`
14914 /// method (`labels_joined` instead of `label`) fails here before any
14915 /// per-parent inherent test surfaces the drift.
14916 #[test]
14917 fn assert_single_slot_key_matches_label_accepts_coherent_local_impl() {
14918 fn make_local(k: LocalKind) -> LocalParent {
14919 match k {
14920 LocalKind::Alpha => LocalParent {
14921 alpha: Some(11),
14922 ..Default::default()
14923 },
14924 LocalKind::Beta => LocalParent {
14925 beta: Some(22),
14926 ..Default::default()
14927 },
14928 LocalKind::Gamma => LocalParent {
14929 gamma: Some(33),
14930 ..Default::default()
14931 },
14932 }
14933 }
14934 assert_single_slot_key_matches_label::<LocalParent, _>(make_local);
14935 }
14936
14937 /// A factory that returns a single-slot parent for the WRONG kind
14938 /// (populates `beta` regardless of what kind is asked for) MUST
14939 /// fail-loudly at the caller's site through the primitive's
14940 /// name-equality arm — the emitted key does not match the addressed
14941 /// kind's label. Pins the drift-detection failure mode so a
14942 /// regression that drops the `assert_eq!(keys[0], label)` arm
14943 /// (silently succeeding on any-key-at-all) is caught here. The
14944 /// caller's site is the `#[should_panic]` boundary through the
14945 /// primitive's `#[track_caller]` compound-lift.
14946 #[test]
14947 #[should_panic(expected = "wire-key drift")]
14948 fn assert_single_slot_key_matches_label_rejects_factory_that_populates_wrong_slot() {
14949 fn always_beta(_: LocalKind) -> LocalParent {
14950 LocalParent {
14951 beta: Some(22),
14952 ..Default::default()
14953 }
14954 }
14955 assert_single_slot_key_matches_label::<LocalParent, _>(always_beta);
14956 }
14957
14958 /// A factory that returns an all-empty parent (so serializing
14959 /// yields ZERO keys, not exactly-one) MUST fail-loudly at the
14960 /// caller's site through the primitive's exactly-one arm. Pins the
14961 /// zero-key failure mode so a regression that projects
14962 /// `obj.keys().count() >= 1` (rather than `== 1`) is caught here.
14963 #[test]
14964 #[should_panic(expected = "exactly one populated field")]
14965 fn assert_single_slot_key_matches_label_rejects_factory_that_populates_no_slots() {
14966 fn empty_factory(_: LocalKind) -> LocalParent {
14967 LocalParent::default()
14968 }
14969 assert_single_slot_key_matches_label::<LocalParent, _>(empty_factory);
14970 }
14971
14972 /// A factory that returns a parent with TWO populated slots (so
14973 /// serializing yields two keys, not exactly-one) MUST fail-loudly
14974 /// at the caller's site through the primitive's exactly-one arm.
14975 /// Pins the many-keys failure mode so a regression that projects
14976 /// `obj.keys().count() <= 1` (rather than `== 1`) is caught here.
14977 /// Cross-pins the substrate promise that a single-slot factory
14978 /// truly populates ONE slot — a future factory bug that leaks
14979 /// residual populated slots between calls (e.g. via shared mutable
14980 /// state) is caught HERE at the primitive boundary.
14981 #[test]
14982 #[should_panic(expected = "exactly one populated field")]
14983 fn assert_single_slot_key_matches_label_rejects_factory_that_populates_two_slots() {
14984 fn two_slot_factory(_: LocalKind) -> LocalParent {
14985 LocalParent {
14986 alpha: Some(1),
14987 beta: Some(2),
14988 gamma: None,
14989 }
14990 }
14991 assert_single_slot_key_matches_label::<LocalParent, _>(two_slot_factory);
14992 }
14993
14994 /// The macro-emitted [`MacroLocalParent`] scaffold impls
14995 /// [`TaggedUnion`] through the [`declare_tagged_union_impls!`]
14996 /// three-block macro AND additionally derives `serde::Serialize` +
14997 /// `#[serde(skip_serializing_if = "Option::is_none")]` on every
14998 /// slot — so the wire-key primitive dispatches on the MACRO-emitted
14999 /// impl path byte-identically with the hand-rolled [`LocalParent`]
15000 /// path above. Pins the substrate-wide guarantee that a fifth
15001 /// sibling landing through the macro picks up the wire-alignment
15002 /// check for free, without a hand-rolled `TaggedUnion` block, so
15003 /// long as its serde derives match the substrate-wide
15004 /// `skip_serializing_if = "Option::is_none"` shape every production
15005 /// site already carries. A regression that mis-routes the
15006 /// primitive's serialize call through the WRONG entry point (e.g.
15007 /// calling a bespoke `to_json` that bypasses serde) is caught here.
15008 #[test]
15009 fn assert_single_slot_key_matches_label_accepts_macro_emitted_impl() {
15010 fn make_macro_local(k: MacroLocalKind) -> MacroLocalParent {
15011 match k {
15012 MacroLocalKind::Foo => MacroLocalParent {
15013 foo: Some(7),
15014 bar: None,
15015 },
15016 MacroLocalKind::Bar => MacroLocalParent {
15017 foo: None,
15018 bar: Some(8),
15019 },
15020 }
15021 }
15022 assert_single_slot_key_matches_label::<MacroLocalParent, _>(make_macro_local);
15023 }
15024
15025 // -------------------------------------------------------------------
15026 // `assert_wire_key_matches_label` — bound-relaxed peer of the
15027 // `assert_single_slot_key_matches_label` primitive. Pin the truth
15028 // table (every populated slot serializes to exactly one JSON key
15029 // whose name equals the addressing kind's ClosedSet label; a
15030 // factory that populates the wrong slot / no slot / multiple slots
15031 // fails-loudly at the caller's site) on a NON-TaggedUnion parent
15032 // scaffold — the delegation-only path from the trait-projected
15033 // primitive would silently pass this test if the bound-relaxed
15034 // primitive's body regressed, so the direct-dispatch probes here
15035 // pin the bound-relaxed pathway independently.
15036 // -------------------------------------------------------------------
15037
15038 /// Local parent that carries the wire-format shape (`Option<T>`
15039 /// slots + `#[serde(skip_serializing_if = "Option::is_none")]`
15040 /// annotations) but DELIBERATELY does NOT impl [`TaggedUnion`] —
15041 /// pins the bound-relaxed sweep on the exact shape [`crate::lifetime::Lifetime`]
15042 /// carries in production (empty resolves to a default variant,
15043 /// not to a typed error, so the trait's `T::Error` bound doesn't
15044 /// hold and the trait-projected surface excludes it).
15045 #[derive(Default, serde::Serialize)]
15046 struct BareParent {
15047 #[serde(skip_serializing_if = "Option::is_none")]
15048 alpha: Option<u32>,
15049 #[serde(skip_serializing_if = "Option::is_none")]
15050 beta: Option<u32>,
15051 #[serde(skip_serializing_if = "Option::is_none")]
15052 gamma: Option<u32>,
15053 }
15054
15055 /// The bound-relaxed primitive dispatches Ok on a coherent
15056 /// non-TaggedUnion impl — pin the happy path directly on the
15057 /// [`BareParent`] scaffold so a regression that gates the sweep
15058 /// body on the `T: TaggedUnion` bound (accidentally re-adding it,
15059 /// or projecting through `T::Kind` instead of the caller-supplied
15060 /// `K` generic) fails HERE at the primitive-independent boundary
15061 /// rather than at the [`crate::lifetime::Lifetime`] production
15062 /// site alone. The Ok arm is the "no drift" outcome; a divergence
15063 /// surfaces as a labeled assertion failure at the caller site
15064 /// (this test's own line) via the primitive's `#[track_caller]`.
15065 #[test]
15066 fn assert_wire_key_matches_label_accepts_coherent_bare_parent_impl() {
15067 fn make_bare(k: LocalKind) -> BareParent {
15068 match k {
15069 LocalKind::Alpha => BareParent {
15070 alpha: Some(11),
15071 ..Default::default()
15072 },
15073 LocalKind::Beta => BareParent {
15074 beta: Some(22),
15075 ..Default::default()
15076 },
15077 LocalKind::Gamma => BareParent {
15078 gamma: Some(33),
15079 ..Default::default()
15080 },
15081 }
15082 }
15083 assert_wire_key_matches_label::<BareParent, LocalKind, _>(make_bare);
15084 }
15085
15086 /// A factory that returns a bare-parent for the WRONG kind
15087 /// (populates `beta` regardless of what kind is asked for) MUST
15088 /// fail-loudly at the caller's site through the bound-relaxed
15089 /// primitive's name-equality arm — the emitted key does not match
15090 /// the addressed kind's label. Pins the drift-detection failure
15091 /// mode on the non-TaggedUnion pathway so a regression that drops
15092 /// the `assert_eq!(keys[0], label)` arm (silently succeeding on
15093 /// any-key-at-all) is caught here — mechanical peer of the
15094 /// sibling `assert_single_slot_key_matches_label_rejects_factory_that_populates_wrong_slot`
15095 /// on the TaggedUnion pathway.
15096 #[test]
15097 #[should_panic(expected = "wire-key drift")]
15098 fn assert_wire_key_matches_label_rejects_factory_that_populates_wrong_slot() {
15099 fn always_beta(_: LocalKind) -> BareParent {
15100 BareParent {
15101 beta: Some(22),
15102 ..Default::default()
15103 }
15104 }
15105 assert_wire_key_matches_label::<BareParent, LocalKind, _>(always_beta);
15106 }
15107
15108 /// A factory that returns an all-empty bare-parent (so serializing
15109 /// yields ZERO keys, not exactly-one) MUST fail-loudly at the
15110 /// caller's site through the bound-relaxed primitive's
15111 /// exactly-one arm. Pins the zero-key failure mode on the
15112 /// non-TaggedUnion pathway.
15113 #[test]
15114 #[should_panic(expected = "exactly one populated field")]
15115 fn assert_wire_key_matches_label_rejects_factory_that_populates_no_slots() {
15116 fn empty_factory(_: LocalKind) -> BareParent {
15117 BareParent::default()
15118 }
15119 assert_wire_key_matches_label::<BareParent, LocalKind, _>(empty_factory);
15120 }
15121
15122 /// The trait-projected [`assert_single_slot_key_matches_label`]
15123 /// is a one-line delegation to the bound-relaxed
15124 /// [`assert_wire_key_matches_label`] peer — pin the delegation
15125 /// shape at ONE boundary so a regression that inlines a
15126 /// divergent sweep body into the trait-projected surface (rather
15127 /// than the one-line dispatch) is caught here. Ok on a coherent
15128 /// impl means BOTH primitives dispatch through the SAME body on
15129 /// the same fixture — [`LocalParent`] impls [`TaggedUnion`], so
15130 /// both the trait-projected surface and the bound-relaxed peer
15131 /// reach it, and a divergence between the two dispatches would
15132 /// surface here as one succeeding + the other failing.
15133 #[test]
15134 fn assert_single_slot_key_matches_label_delegates_to_wire_key_matches_label() {
15135 fn make_local(k: LocalKind) -> LocalParent {
15136 match k {
15137 LocalKind::Alpha => LocalParent {
15138 alpha: Some(11),
15139 ..Default::default()
15140 },
15141 LocalKind::Beta => LocalParent {
15142 beta: Some(22),
15143 ..Default::default()
15144 },
15145 LocalKind::Gamma => LocalParent {
15146 gamma: Some(33),
15147 ..Default::default()
15148 },
15149 }
15150 }
15151 // Both surfaces reach the same body — dispatched here through
15152 // BOTH entry points so a divergence between them fails one
15153 // arm while the other passes.
15154 assert_single_slot_key_matches_label::<LocalParent, _>(make_local);
15155 assert_wire_key_matches_label::<LocalParent, LocalKind, _>(make_local);
15156 }
15157
15158 /// Every one of the five production borrowed-view enums impls
15159 /// [`VariantKind`] byte-identically with its inherent `.kind()`
15160 /// (or `.target()` on `EncapsulationKindVariant`) — pin the
15161 /// delegation shape at ONE substrate boundary so a regression that
15162 /// inlines a divergent match body into the trait impl (rather than
15163 /// the one-line delegation) is caught here. `Lifetime`'s
15164 /// borrowed-view is included even though `Lifetime` isn't a
15165 /// [`TaggedUnion`] impl — the reverse projection applies uniformly.
15166 #[test]
15167 fn every_production_variant_kind_impl_matches_inherent_projection() {
15168 use crate::encapsulates::{EncapsulationKindVariant, ExistingHelmRelease};
15169 use crate::export::{ArtifactVariant, ChannelVariant, HttpEventChannel, ReceiptsSource};
15170 use crate::intent::{IntentVariant, NixIntent};
15171 use crate::lifetime::{LifetimeVariant, PermanentLifetime};
15172
15173 let nix = NixIntent {
15174 flake_ref: "github:a/b".into(),
15175 attribute: "x".into(),
15176 system: None,
15177 attic_cache: None,
15178 extra_args: vec![],
15179 delegate_to_nix_build: false,
15180 };
15181 let iv = IntentVariant::Nix(&nix);
15182 assert_eq!(iv.kind(), iv.variant_kind());
15183
15184 let perm = PermanentLifetime::default();
15185 let lv = LifetimeVariant::Permanent(&perm);
15186 assert_eq!(lv.kind(), lv.variant_kind());
15187
15188 let hr = ExistingHelmRelease {
15189 namespace: "ns".into(),
15190 name: "n".into(),
15191 release_name: "r".into(),
15192 };
15193 let ev = EncapsulationKindVariant::ExistingHelmRelease(&hr);
15194 assert_eq!(ev.target(), ev.variant_kind());
15195
15196 let rs = ReceiptsSource {};
15197 let av = ArtifactVariant::Receipts(&rs);
15198 assert_eq!(av.kind(), av.variant_kind());
15199
15200 let ch = HttpEventChannel::signal("s");
15201 let cv = ChannelVariant::HttpEvent(&ch);
15202 assert_eq!(cv.kind(), cv.variant_kind());
15203 }
15204}