caixa_core/upgrade.rs
1//! Erlang/OTP-style appup — declarative upgrade instructions per
2//! prior caixa version. Composes with the `:behavior :on-state-change`
3//! callback to deliver state migration during hot upgrades.
4//!
5//! See `theory/INSPIRATIONS.md` §II.4 for the prior-art frame.
6//!
7//! ```lisp
8//! (defcaixa
9//! :nome "hello-rio"
10//! :versao "0.2.0"
11//! :upgrade-from
12//! ((:from "0.1.0"
13//! :instructions ((:load-module "hello-rio")
14//! (:state-change "lib/migrations/v01-to-v02.lisp")
15//! (:soft-purge "hello-rio-old")))
16//! (:from "0.1.5"
17//! :instructions ((:load-module "hello-rio")
18//! (:soft-purge "hello-rio-old")))))
19//! ```
20//!
21//! Each `(:from <prior>)` block declares the upgrade path *from* that
22//! version *to* the current `:versao`. wasm-operator picks the
23//! matching block at upgrade time, runs the instructions in order,
24//! and only swaps traffic to the new instance after all instructions
25//! succeed (transactional upgrade). On any failure, the current
26//! version stays load-bearing — a typed atomic upgrade.
27
28use std::path::PathBuf;
29
30use serde::{Deserialize, Serialize};
31use thiserror::Error;
32
33/// One upgrade instruction. The set mirrors OTP's appup low-level
34/// instructions: enough to express every common upgrade pattern,
35/// few enough that the wasm-operator can implement each
36/// deterministically.
37#[derive(
38 Serialize,
39 Deserialize,
40 Debug,
41 Clone,
42 PartialEq,
43 Eq,
44 gen_platform::TypedDispatcher,
45 gen_platform::Discriminant,
46 gen_platform::IsVariant,
47)]
48#[serde(tag = "kind", rename_all = "kebab-case")]
49pub enum UpgradeInstruction {
50 /// Load a new wasm module alongside the current one — the analog
51 /// of OTP's `code:load_module/1`. Both versions remain in memory
52 /// after this instruction; in-flight requests stay on the old
53 /// version, new requests route to the new version.
54 LoadModule { module: String },
55
56 /// Run a state-migration tatara-lisp file. Receives the old state
57 /// + the prior version string; returns the new state. Analog of
58 /// `gen_server:code_change/3`.
59 StateChange { script: PathBuf },
60
61 /// Wait for in-flight requests on a named module to drain, then
62 /// GC it — the analog of `code:soft_purge/1`. Default cooldown is
63 /// 60s; longer-running requests block the upgrade.
64 SoftPurge { module: String },
65
66 /// Discard a named module immediately, without waiting for
67 /// drain — the analog of `code:purge/1`. Used when we don't
68 /// care about in-flight callers (cron, oneShot).
69 Purge { module: String },
70
71 /// Fall back to a full restart for this entry. Used when a typed
72 /// upgrade is impossible (e.g. wasm component world incompatible).
73 Restart,
74}
75
76// Fleet-wide dispatcher-catalog registration. UpgradeInstruction is
77// the OTP-style hot-upgrade primitive (load_module/code_change/
78// soft_purge/purge/restart) — the first NON-ADAPTER consumer of
79// gen-platform's typed-dispatcher catamorphism, satisfying the ★★
80// "two classes of consumer" promotion criterion from
81// theory/QUIRK-APPLIER.md §V.1.
82//
83// Operators query via:
84// gen dispatchers --from-catalog | jq '.[] | select(.label=="caixa.upgrade-instruction")'
85//
86// The substrate's lib/build/shared/fleet-catalog-coverage-test.nix
87// adds an assertion row for this label on the next snapshot refresh.
88gen_platform::register_dispatcher!("caixa.upgrade-instruction", UpgradeInstruction);
89
90/// One upgrade entry: the *prior* version we're upgrading from, plus
91/// the instruction sequence to execute.
92#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
93#[serde(rename_all = "camelCase")]
94pub struct UpgradeFromEntry {
95 /// Semver of the *prior* version. Authored as a literal string;
96 /// validated lazily by [`UpgradeFromEntry::validate`].
97 pub from: String,
98
99 /// Ordered list of instructions to execute. Empty list = "no-op
100 /// upgrade" (rare; usually means only documentation changed).
101 #[serde(default)]
102 pub instructions: Vec<UpgradeInstruction>,
103}
104
105impl UpgradeFromEntry {
106 /// Prior-versao semver-2 literal this entry declares an upgrade
107 /// path *from* — the string the OTP-shape `release_handler:install_release/1`
108 /// analog matches the running caixa's `:versao` against at hot-
109 /// upgrade dispatch time to pick this entry's `:instructions`
110 /// sequence. Returned byte-for-byte from the typed slot's own
111 /// `String` storage; no cloning, no re-parsing.
112 ///
113 /// The M2 companion of the closed M3 mesh-slot scalar-accessor
114 /// family — sibling in shape to [`crate::Membro::versao_requirement`]
115 /// (a40b0e3), [`crate::Membro::nome`] (4a32abf), and the
116 /// [`crate::WitContract::{source, destination, world_ref}`]
117 /// (7f0fd43 / 0804823) / [`crate::Entrada::{hostname, destination}`]
118 /// (11f3dfe / 6db982c) `&str` accessors already routing every
119 /// per-mesh-slot-atom scalar-value axis through one typed dispatch
120 /// on the substrate primitive — extended here onto the first per-
121 /// M2-slot scalar-value axis. Every downstream consumer of the
122 /// M2 `:upgrade-from :from` axis (the [`UpgradeFromEntry::validate`]
123 /// SemVer-2 parse gate, the [`validate_upgrade_from`] cross-entry
124 /// duplicate-detection re-parse assertion, the
125 /// [`validate_upgrade_from_against_versao`] precedence gate,
126 /// the [`validate_upgrade_from_against_behavior`] state-change-
127 /// callback coherence gate, every per-arm error variant carrying
128 /// the offending `:from` verbatim for `feira lint` rendering)
129 /// now reads through this one accessor rather than open-coding
130 /// `&self.from` / `&entry.from` / `self.from.clone()` /
131 /// `entry.from.clone()`.
132 ///
133 /// A future extension of the axis (an M4 typed `:from`-range slot
134 /// composing multiple prior versions into one entry, an operator-
135 /// side pre-parsed [`semver::Version`] cache the accessor could
136 /// materialize behind the same `&str` return contract, a per-
137 /// cluster `:placement`-scoped prior-versao overlay the
138 /// `caixa-operator` reconciles ahead of dispatch) migrates as a
139 /// single caixa-core edit rather than a coordinated rewrite of
140 /// the four validate-side call sites + every downstream error-
141 /// variant carrying `:from`.
142 #[must_use]
143 pub const fn prior_versao(&self) -> &str {
144 self.from.as_str()
145 }
146
147 /// Substrate-canonical per-`:upgrade-from :instructions`
148 /// OTP-appup migration-instruction-list slice-return accessor
149 /// every per-entry instructions-list reader keys off — returns
150 /// the author-declared `:instructions` list verbatim as a
151 /// `&[UpgradeInstruction]` slice-view over the same backing
152 /// buffer the raw `self.instructions.as_slice()` field access
153 /// borrows from. Non-optional: an empty slice is the load-bearing
154 /// "author declared `:instructions ()`" sentinel — the
155 /// `Vec<UpgradeInstruction>::default()`-produced empty tail the
156 /// [`UpgradeFromEntry::instructions`] field's own docstring already
157 /// names as the "no-op upgrade" shape (a metadata-only upgrade
158 /// entry — the operator's `:from`-match dispatch matches the entry
159 /// but runs no instructions, advancing straight to the "traffic
160 /// swap" step) and every peer within-entry cross-instruction gate
161 /// no-ops against without allocating a new `Vec` per gate.
162 ///
163 /// The `:upgrade-from :instructions` slot carries the per-`:from`
164 /// OTP-appup ordered instruction list the wasm-operator's hot-
165 /// upgrade dispatch materializes one per-instruction runtime
166 /// primitive from — the Erlang/OTP appup's per-`{from, to,
167 /// UpgradeInstructions, DowngradeInstructions}` entry's
168 /// `UpgradeInstructions` list (`code:load_module/1` /
169 /// `gen_server:code_change/3` / `code:soft_purge/1` /
170 /// `code:purge/1` / `restart_new_emulator` — see INSPIRATIONS
171 /// §II.4), projected through the tatara-lisp
172 /// `:upgrade-from ((:from … :instructions …))` author surface
173 /// onto a typed `Vec<UpgradeInstruction>` whose per-element
174 /// variant is [`UpgradeInstruction::LoadModule`] /
175 /// [`UpgradeInstruction::StateChange`] /
176 /// [`UpgradeInstruction::SoftPurge`] / [`UpgradeInstruction::Purge`]
177 /// / [`UpgradeInstruction::Restart`]. Every downstream consumer
178 /// that fans on the per-entry instruction list keys off this
179 /// slice (the [`UpgradeFromEntry::validate`] per-instruction
180 /// shape-check fan-out, the seven paired within-entry cross-
181 /// instruction gates [`Self::validate_restart_exclusive`] /
182 /// [`Self::validate_state_change_ordering`] /
183 /// [`Self::validate_purge_ordering`] /
184 /// [`Self::validate_state_change_before_cleanup`] /
185 /// [`Self::validate_load_singularity`] /
186 /// [`Self::validate_state_change_singularity`] /
187 /// [`Self::validate_cleanup_singularity`], the layout-side
188 /// [`crate::layout::StandardLayout`]'s per-`:state-change`
189 /// script-existence fan-out
190 /// ([`crate::layout::LayoutError::MissingEntry`]'s
191 /// `LAYOUT_MISSING_ENTRY_KIND_UPGRADE_SCRIPT` arm), the cross-slot
192 /// [`validate_upgrade_from_against_behavior`] gate's per-entry
193 /// `:state-change`-instruction detection loop, every future
194 /// wasm-operator (M2.5) per-`:from`-match hot-upgrade dispatch's
195 /// per-instruction runtime-primitive fan-out, every future M4
196 /// `mesh.pleme.io/v1alpha1/Caixa` CR materializer's per-entry
197 /// upgrade-plan admission-webhook fan-out).
198 ///
199 /// Prior to this lift the `.instructions` `Vec<UpgradeInstruction>`
200 /// was accessed inline at nine production sites across
201 /// `caixa-core/src/upgrade.rs` and `caixa-core/src/layout.rs` —
202 /// the [`UpgradeFromEntry::validate`] per-instruction shape-check
203 /// fan-out (`for instr in &self.instructions`), the paired
204 /// [`Self::validate_restart_exclusive`] restart-count / other-kind
205 /// projections + `.len()` probe (three raw-access sites in one
206 /// gate), the [`Self::validate_state_change_ordering`] /
207 /// [`Self::validate_purge_ordering`] /
208 /// [`Self::validate_state_change_before_cleanup`] /
209 /// [`Self::validate_load_singularity`] /
210 /// [`Self::validate_state_change_singularity`] /
211 /// [`Self::validate_cleanup_singularity`] within-entry cross-
212 /// instruction gate traversal heads, the peer
213 /// [`validate_upgrade_from_against_behavior`] cross-slot
214 /// composition gate's `for instr in &entry.instructions`
215 /// per-entry `:state-change` detection loop, and the
216 /// [`crate::layout::StandardLayout`]-side
217 /// `for instr in &entry.instructions` per-`:state-change`
218 /// script-existence fan-out — nine open-coded field-accesses
219 /// that expressed no compile-time link back to the typed slot.
220 /// A future extension of the `:instructions` axis to a richer
221 /// author surface (a per-cluster overlay the operator pins
222 /// through a future `:upgrade-from :instructions-overrides` slot
223 /// so a canary cluster runs a `(:state-change …)` before the
224 /// production fleet does, a per-tenant instruction-list overlay
225 /// the M4 CR materializer resolves per-CR to inject cluster-
226 /// specific `(:soft-purge …)` cooldown adjustments, a promotion
227 /// of the plain `Vec<UpgradeInstruction>` to a richer
228 /// `{static, dynamic}` partition once virtual-actor-style
229 /// dynamic-instruction composition (an operator-derived
230 /// `(:load-module …)` sequence computed from the running
231 /// module set at upgrade time) comes into typed scope, a
232 /// per-instruction pre-condition scalar the future adaptive-
233 /// upgrade engine reads to bias per-instruction retry
234 /// strategy) would have had to be threaded through all nine
235 /// open-coded copies in lockstep or one consumer would silently
236 /// disagree with the peers on which instruction sequence a
237 /// given `:upgrade-from` entry resolves to — the per-
238 /// instruction shape-check reading the raw slot while the
239 /// paired within-entry ordering gates read an operator-resolved
240 /// slot would silently split the build-time per-entry gate
241 /// cohort from the layout-side script-existence gate + the
242 /// cross-slot behavior-composition gate + the runtime hot-
243 /// upgrade dispatch, a nine-consumer split across the seven
244 /// within-entry cross-instruction gates + the layout invariant +
245 /// the cross-slot composition gate far from the source
246 /// `caixa.lisp` with no field naming the instruction-sequence-
247 /// drift root cause. Lifting the resolution rule to a typed
248 /// method on the substrate primitive means every downstream
249 /// consumer of the per-entry OTP-appup instruction-list surface
250 /// reaches for exactly one typed dispatch — the resolver's
251 /// accept-set migrates as a unit on any future axis addition.
252 ///
253 /// Fifth slice-return (`&[T]`) accessor on any M2 or M3 typed
254 /// slot — sibling to the seed M2
255 /// [`crate::SupervisorSpec::children`] (bc92bce) `&[ChildSpec]`
256 /// accessor on the peer per-`:supervisor` static-child-list
257 /// `Vec`-carry axis, the M3 [`crate::Placement::clusters`]
258 /// (a6e18d7) `&[String]` accessor on the peer per-`:placement`
259 /// distribution-target-list `Vec`-carry axis, the M3
260 /// [`crate::AplicacaoSpec::membros`] (6c77e36) `&[Membro]`
261 /// accessor on the peer per-`:membros` node-list `Vec`-carry
262 /// axis, and the M3 [`crate::AplicacaoSpec::contratos`]
263 /// (0dcc926) `&[WitContract]` accessor on the peer per-
264 /// `:contratos` edge-list `Vec`-carry axis. This lift closes the
265 /// last unlifted `Vec`-carry axis on any M2 or M3 typed slot in
266 /// the substrate — the four peer axes named in the
267 /// [`crate::SupervisorSpec::children`] seed docstring
268 /// (`Placement::clusters`, `AplicacaoSpec::membros`,
269 /// `AplicacaoSpec::contratos`, `UpgradeFromEntry::instructions`)
270 /// are now all closed. The per-`UpgradeFromEntry` type carried
271 /// two axes: the scalar `Copy`-return
272 /// [`UpgradeFromEntry::prior_versao`] (75d27a8) on the
273 /// `:from` axis, and now the slice-return
274 /// [`UpgradeFromEntry::instructions`] on the peer
275 /// `:instructions` axis. Named `instructions()` to match the
276 /// storage field's name verbatim and the tatara-lisp
277 /// author-surface term (`:instructions`) the field's own
278 /// docstring already carries; the accessor's identity maps
279 /// onto the canonical OTP-appup vocabulary the
280 /// [`crate::upgrade`] module doc already reaches for ("runs
281 /// the instructions in order"). Returns `&[UpgradeInstruction]`
282 /// (not `&Vec<UpgradeInstruction>`) because every downstream
283 /// consumer of the instruction list treats it as a read-only
284 /// sequence — the slice-view is the narrowest borrow that
285 /// supports every present + roadmapped consumer (`.iter()`,
286 /// `.len()`, `.filter(...).count()`) without leaking the
287 /// backing `Vec`'s grow/push/reserve surface that no consumer
288 /// of the typed view reaches for (the storage-side `Vec`
289 /// remains reachable through the `pub instructions` field for
290 /// the mutation-carrying `Serialize`/`Deserialize` derive
291 /// round-trip and per-test fixture-mutation paths).
292 #[must_use]
293 pub const fn instructions(&self) -> &[UpgradeInstruction] {
294 self.instructions.as_slice()
295 }
296
297 /// Verify the `:from` field is a valid semver, every instruction's
298 /// typed shape, the within-entry `(:restart)`-exclusivity invariant
299 /// (an entry containing `(:restart)` must contain exactly one
300 /// `(:restart)` and nothing else — see
301 /// [`Self::validate_restart_exclusive`]), the within-entry
302 /// state-change-ordering invariant (every `(:state-change …)` must
303 /// be preceded by a `(:load-module …)` — see
304 /// [`Self::validate_state_change_ordering`]), the within-entry
305 /// purge-ordering invariant (every `(:soft-purge …)` / `(:purge …)`
306 /// must be preceded by a `(:load-module …)` — see
307 /// [`Self::validate_purge_ordering`]), the within-entry
308 /// state-change-before-cleanup ordering invariant (no
309 /// `(:state-change …)` may appear after any `(:soft-purge …)` /
310 /// `(:purge …)` — see
311 /// [`Self::validate_state_change_before_cleanup`]), the within-
312 /// entry load-singularity invariant (no module appears as the
313 /// target of `(:load-module …)` more than once — see
314 /// [`Self::validate_load_singularity`]), the within-entry
315 /// state-change-singularity invariant (no script appears as the
316 /// target of `(:state-change …)` more than once — see
317 /// [`Self::validate_state_change_singularity`]), and the within-
318 /// entry cleanup-singularity invariant (no module appears as the
319 /// target of `(:soft-purge …)` or `(:purge …)` more than once
320 /// total — see [`Self::validate_cleanup_singularity`]).
321 pub fn validate(&self) -> Result<(), UpgradeError> {
322 use semver::Version;
323 Version::parse(self.prior_versao())
324 .map_err(|e| UpgradeError::from_invalid(self.prior_versao(), &e.to_string()))?;
325 // Per-instruction typed shape: kind-tagged `:module` /
326 // `:script` value-shape gates fire here, *before* the
327 // within-entry restart-exclusivity gate below — so a
328 // malformed-shape diagnostic on a Module/Script-bearing
329 // instruction surfaces with its narrower self-locating
330 // wording (`ModuleEmpty`, `ModuleInvalid`, `EmptyScript`,
331 // `AbsoluteScript`, `ParentEscapeScript`) rather than
332 // collapsing two unrelated authoring errors into a single
333 // exclusivity diagnostic. Same empty-first cascade discipline
334 // every peer DNS-1123 / path-shape gate inside this module
335 // uses (`validate_module`'s ModuleEmpty arm precedes the
336 // DNS-1123 predicate; `validate` on `StateChange` consults
337 // the lifted `is_sandboxed_relative_path` shape gate first).
338 // Route the per-instruction shape-check fan-out through the
339 // lifted [`Self::instructions`] slice-return accessor rather
340 // than the raw `self.instructions` field access — first of
341 // nine paired production consumers of the per-`:upgrade-from
342 // :instructions` OTP-appup migration-instruction-list surface
343 // that now key off exactly one typed dispatch on the substrate
344 // primitive.
345 for instr in self.instructions() {
346 instr.validate()?;
347 }
348 self.validate_restart_exclusive()?;
349 self.validate_state_change_ordering()?;
350 self.validate_purge_ordering()?;
351 self.validate_state_change_before_cleanup()?;
352 self.validate_load_singularity()?;
353 self.validate_state_change_singularity()?;
354 self.validate_cleanup_singularity()?;
355 Ok(())
356 }
357
358 /// Reject `:upgrade-from :instructions` lists that carry
359 /// `(:restart)` alongside any other instruction, or that carry
360 /// more than one `(:restart)`. The valid Restart-bearing shape is
361 /// exactly `((:restart))` — a single `Restart` as the entry's
362 /// whole instructions list.
363 ///
364 /// Per [`UpgradeInstruction::Restart`]'s doc comment, `(:restart)`
365 /// is the *fallback* for an entry whose typed upgrade is
366 /// impossible (wasm component-model world incompatibility,
367 /// irreversible state shape change). The fallback is terminal by
368 /// construction: the operator restarts the pod and the new version
369 /// comes up fresh, so any other instructions in the same entry
370 /// are dead code in both directions — either the typed sequence
371 /// would have succeeded and `(:restart)` is unreached, or it
372 /// wouldn't and the typed instructions are dead because the
373 /// operator restarts anyway. Two canonical authoring footguns
374 /// close here:
375 ///
376 /// - `((:load-module …) (:state-change …) (:restart))` — the
377 /// "I'll try the typed path *then* restart anyway" footgun.
378 /// There is no coherent OTP-shaped semantic for this: if the
379 /// typed sequence succeeds, the trailing restart discards the
380 /// work that just succeeded (defeating the whole point of
381 /// declaring it); if it fails, the restart is never reached
382 /// because the entry already failed.
383 /// - `((:restart) (:restart))` — multiple `Restart` variants in
384 /// one entry. The fallback is a single semantic; repeating it
385 /// is at best redundant, at worst suggests the author thought
386 /// the second one would re-trigger after the first.
387 ///
388 /// Same within-entry exclusivity discipline OTP's `relup` enforces
389 /// at the `restart_new_emulator | restart_emulator` instruction
390 /// boundary — those instructions are terminal in the upgrade
391 /// script (`systools(3)` rejects sequences that continue past
392 /// them); pleme-io lifts the same shape to a build-time gate,
393 /// matching the CAIXA-SDLC §III "build errors, not runtime
394 /// surprises" frame.
395 ///
396 /// Same within-entry cross-instruction discipline the
397 /// [`crate::AplicacaoSpec::validate_placement`] strategy ↔
398 /// shard-key partition (934bc58) and
399 /// [`validate_upgrade_from_against_versao`]'s `:from` ↔ `:versao`
400 /// precedence partition (de7ab1a) apply on cross-slot axes — now
401 /// extended onto the first within-list cross-instruction axis on
402 /// the `:upgrade-from` typed slot.
403 fn validate_restart_exclusive(&self) -> Result<(), UpgradeError> {
404 // Route the paired restart-count / instructions-len / other-
405 // kind projections through the lifted [`Self::instructions`]
406 // slice-return accessor rather than the raw `self.instructions`
407 // field access — three raw-access sites in one gate collapse
408 // onto exactly one typed dispatch on the substrate primitive.
409 //
410 // The paired positive / negated `Self::Restart` arm-discriminator
411 // predicates route through the `gen_platform::IsVariant`
412 // derive-generated [`UpgradeInstruction::is_restart`] rather than
413 // the raw `matches!(i, UpgradeInstruction::Restart)` /
414 // `!matches!(i, UpgradeInstruction::Restart)` open-coded pattern-
415 // matches — same closed-set-typed-enum arm-discriminator dispatch
416 // discipline the sibling [`crate::CaixaKind`] `IsVariant` derive
417 // (f5bba80) extended onto its ten `caixa.kind() == CaixaKind::X`
418 // / `!= CaixaKind::X` production sites in the substrate's own
419 // layout invariant verifier + typed-view projection gates,
420 // extended here onto the last unlifted `matches!`-based
421 // arm-discriminator axis on the [`UpgradeInstruction`] closed-set
422 // typed enum. A future sixth `UpgradeInstruction` arm (an
423 // adaptive-upgrade-shaped `AwaitReadiness` gate the M2.5
424 // wasm-operator's hot-upgrade runtime could adopt to bracket the
425 // typed instruction sequence against a per-cluster readiness
426 // probe, a `Downgrade` variant OTP's `relup` acknowledges on the
427 // reverse axis, a `CanaryTraffic` split-traffic variant the M4 CR
428 // materializer could resolve per-CR) migrates as a single
429 // enum-declaration edit — the derive auto-generates the paired
430 // `.is_<new_arm>()` predicate; every consumer inherits the new
431 // arm on the next re-derive, rather than the two `matches!` sites
432 // here having to be threaded through in lockstep.
433 let instructions = self.instructions();
434 let restart_count = instructions.iter().filter(|i| i.is_restart()).count();
435 if restart_count == 0 {
436 return Ok(());
437 }
438 if restart_count == 1 && instructions.len() == 1 {
439 return Ok(());
440 }
441 let other_kinds: Vec<&'static str> = instructions
442 .iter()
443 .filter(|i| !i.is_restart())
444 .map(UpgradeInstruction::lisp_form)
445 .collect();
446 Err(UpgradeError::restart_not_exclusive(
447 self.prior_versao(),
448 restart_count,
449 other_kinds,
450 ))
451 }
452
453 /// Reject an entry whose `(:state-change …)` is not preceded by a
454 /// `(:load-module …)` in the same `:instructions` list.
455 ///
456 /// `StateChange` is the `gen_server:code_change/3` analog
457 /// ([`UpgradeInstruction::StateChange`] doc; INSPIRATIONS §II.4):
458 /// it runs the migration script that folds the *old* state into the
459 /// shape the *new* code expects. In OTP, `code_change/3` is invoked
460 /// in the context of the newly-loaded code — `release_handler`
461 /// always loads the new module before running the advanced update
462 /// that triggers the callback. caixa decomposes that into two
463 /// explicit instructions (`LoadModule` brings the new version up
464 /// "alongside the current one"; `StateChange` migrates the state),
465 /// and the module doc pins that the operator "runs the instructions
466 /// in order" and only swaps traffic after all succeed. So a
467 /// `:state-change` with no preceding `:load-module` migrates state
468 /// into code that was never loaded — the migration script runs while
469 /// the only resident version is still the *old* one, which expects
470 /// the *old* state. Two authoring footguns close here:
471 ///
472 /// - `((:state-change "…"))` — the "I wrote the migration but
473 /// forgot to load the new module" footgun. The new code that
474 /// defines the new state representation (and that the migration
475 /// output is destined for) never comes up; the operator runs
476 /// the script against the old code and either no-ops or corrupts
477 /// live state.
478 /// - `((:state-change "…") (:load-module "…"))` — the
479 /// right-instructions-wrong-order footgun. Because the operator
480 /// executes in declared order, the migration runs *before* the
481 /// new code is resident, then the load brings up code expecting
482 /// already-migrated state that the just-run script produced
483 /// against the old version's shape. The canonical order is
484 /// `(:load-module …) (:state-change …) (:soft-purge …)`
485 /// (module doc example).
486 ///
487 /// Same within-entry cross-instruction discipline as
488 /// [`Self::validate_restart_exclusive`] (the `(:restart)` terminal-
489 /// exclusivity gate it runs beside): both reject an
490 /// `:instructions` list whose instructions are individually
491 /// well-shaped but jointly incoherent, at the typed build surface
492 /// rather than as a runtime surprise. Runs *after*
493 /// `validate_restart_exclusive` so a `((:state-change …)
494 /// (:restart))` shape still surfaces the more-fundamental
495 /// `RestartNotExclusive` (a valid `(:restart)` entry is `(:restart)`
496 /// alone, so no Restart-bearing entry reaches this gate carrying a
497 /// `StateChange`).
498 fn validate_state_change_ordering(&self) -> Result<(), UpgradeError> {
499 // Route the per-instruction load-family arm-discriminator through
500 // the `gen_platform::IsVariant`-derive-generated
501 // [`UpgradeInstruction::is_load_module`] predicate and the
502 // per-instruction migration-family `:script` scalar projection
503 // through the sibling lifted [`UpgradeInstruction::declared_path`]
504 // `Option<&PathBuf>` accessor rather than the raw two-arm
505 // `match instr { UpgradeInstruction::LoadModule { .. } =>
506 // loaded = true, UpgradeInstruction::StateChange { script } if
507 // !loaded => …, _ => {} }` open-coded pattern-match — closes the
508 // last unlifted `match`-shaped per-arm-hand-rolled load-family
509 // arm-discriminator + migration-family script-projection pair
510 // inside `impl UpgradeFromEntry`. Sibling of the peer
511 // [`Self::validate_purge_ordering`] (580d0f1) routing already
512 // lifted onto [`UpgradeInstruction::is_load_module`] on the paired
513 // load → cleanup ordering axis, the peer
514 // [`Self::validate_load_singularity`] (c9ce91d) routing lifted
515 // onto the [`UpgradeInstruction::is_load_module`] +
516 // [`UpgradeInstruction::declared_module`] pair on the singularity
517 // axis, and the peer [`Self::validate_state_change_singularity`]
518 // routing already lifted onto the sibling
519 // [`UpgradeInstruction::declared_path`] `Option<&PathBuf>`
520 // accessor on the migration-family script-projection axis — both
521 // ordering-gate load-family sticky-latch dispatches now key off
522 // exactly one typed dispatch on the substrate primitive for
523 // their load-family arm-discriminator, and both migration-family
524 // projection sites (this ordering gate + the peer singularity
525 // gate) now key off exactly one typed dispatch on the substrate
526 // primitive for the `:script`-carrying axis. A future sixth arm
527 // on [`UpgradeInstruction`] (an `AwaitReadiness` gate, a
528 // `Downgrade` reverse-axis variant OTP's `relup` acknowledges, a
529 // `CanaryTraffic` split-traffic variant the M4 CR materializer
530 // could resolve per-CR — INSPIRATIONS §II.4) migrates as one
531 // enum-declaration edit through the derive rather than a
532 // coordinated rewrite of every ordering / singularity gate's
533 // per-arm hand-rolled pattern-match. Byte-identity of this
534 // dispatch against the pre-lift `match` shape is pinned by
535 // [`tests::validate_state_change_ordering_projects_scripts_through_is_load_module_and_declared_path_accessors`].
536 let mut loaded = false;
537 for instr in self.instructions() {
538 if instr.is_load_module() {
539 loaded = true;
540 } else if !loaded && let Some(script) = instr.declared_path() {
541 return Err(UpgradeError::state_change_without_prior_load(
542 self.prior_versao(),
543 script,
544 ));
545 }
546 }
547 Ok(())
548 }
549
550 /// Reject an entry whose `(:soft-purge …)` or `(:purge …)` is not
551 /// preceded by a `(:load-module …)` in the same `:instructions` list.
552 ///
553 /// `SoftPurge` and `Purge` are the `code:soft_purge/1` /
554 /// `code:purge/1` analogs (INSPIRATIONS §II.4): they remove the
555 /// *old* module from memory after the new one is resident. OTP's
556 /// two-phase code load is `code:load_module/1` *then*
557 /// `code:soft_purge/1` — load the new version alongside the old
558 /// (both in memory, new requests route to new), then purge the old
559 /// after in-flight callers drain. caixa decomposes that into two
560 /// explicit instructions (`LoadModule` brings the new version up
561 /// "alongside the current one", per [`UpgradeInstruction::LoadModule`]
562 /// doc; `SoftPurge` "waits for in-flight requests on a named module
563 /// to drain, then GC it", per [`UpgradeInstruction::SoftPurge`] doc),
564 /// and the module doc pins that the operator "runs the instructions
565 /// in order". So a `:soft-purge` / `:purge` with no preceding
566 /// `:load-module` purges old code while the only resident version is
567 /// still the *same* old code, leaving the upgrade entry asking the
568 /// operator to drain or discard the live module with no replacement
569 /// resident. Two authoring footguns close here:
570 ///
571 /// - `((:soft-purge "…"))` / `((:purge "…"))` — the "I wrote the
572 /// cleanup but forgot to load the new module" footgun. The new
573 /// code never comes up alongside; the operator either drains the
574 /// old version to nothing (`SoftPurge`) or discards it outright
575 /// mid-request (`Purge`), with no replacement to route in-flight
576 /// or future requests to.
577 /// - `((:soft-purge "…") (:load-module "…"))` /
578 /// `((:purge "…") (:load-module "…"))` — the right-instructions-
579 /// wrong-order footgun. Because the operator executes in declared
580 /// order, the cleanup runs *before* the new code is resident,
581 /// leaving a window during which neither version is available;
582 /// the canonical order is `(:load-module …) (:state-change …)
583 /// (:soft-purge …)` (module doc example).
584 ///
585 /// Same within-entry cross-instruction discipline as
586 /// [`Self::validate_state_change_ordering`] (the `:state-change`-
587 /// ordering gate it runs beside): both close the same load-before-X
588 /// post-condition on the OTP appup ordering contract, now extending
589 /// the typed coverage from "new code resident before its state
590 /// migration runs" to "new code resident before the old code is
591 /// drained or discarded" — the second half of OTP's two-phase code
592 /// load. Runs *after* `validate_state_change_ordering` so an entry
593 /// like `((:state-change …) (:soft-purge …))` surfaces the more-
594 /// fundamental `StateChangeWithoutPriorLoad` first (both instructions
595 /// are load-less, but state-change is the load-bearing semantic — the
596 /// purge is meaningless either way without a preceding load, so the
597 /// author should see the migration-side diagnostic first).
598 fn validate_purge_ordering(&self) -> Result<(), UpgradeError> {
599 let mut loaded = false;
600 for instr in self.instructions() {
601 // Route the per-instruction cleanup-family arm-discriminator
602 // through the lifted [`UpgradeInstruction::is_cleanup`] typed
603 // predicate rather than the raw
604 // `UpgradeInstruction::SoftPurge { module } |
605 // UpgradeInstruction::Purge { module }` open-coded per-arm
606 // union pattern-match — the first of three within-entry cross-
607 // instruction cleanup-facing gates now keys off exactly one
608 // typed dispatch on the substrate primitive, so any future
609 // fifth cleanup-shaped variant (a `Discard` variant the
610 // `code:delete/1` peer inspires) added to
611 // [`UpgradeInstruction`] + a composing `|| self.is_discard()`
612 // term at [`UpgradeInstruction::is_cleanup`] reaches this gate
613 // through the accessor's one body. The paired cleanup-arm
614 // `:module` scalar is routed through the sibling
615 // [`UpgradeInstruction::declared_module`] accessor rather than
616 // the raw pattern-bound `module` binding — same substrate-
617 // primitive-owns-the-scalar discipline every peer
618 // per-`UpgradeInstruction` scalar-value axis already routes
619 // through, with the `is_cleanup`-implies-`declared_module`-is-
620 // `Some` composition pin at
621 // [`tests::upgrade_instruction_is_cleanup_implies_declared_module_is_some`]
622 // making the `.expect(…)` structurally infallible at build
623 // time. Peer of the sibling
624 // [`UpgradeFromEntry::validate_restart_exclusive`]
625 // paired positive / negated
626 // [`UpgradeInstruction::is_restart`] routing (915a934) on the
627 // per-arm terminal-fallback partition — same closed-set-typed-
628 // enum arm-discriminator dispatch discipline extended from
629 // the single-arm terminal-fallback family onto the two-arm
630 // cleanup family here.
631 //
632 // Route the paired load-family arm-discriminator through the
633 // `gen_platform::IsVariant`-derive-generated
634 // [`UpgradeInstruction::is_load_module`] predicate rather than
635 // the raw `matches!(instr, UpgradeInstruction::LoadModule
636 // { .. })` open-coded pattern-match — closes the last
637 // unlifted `matches!`-based per-variant arm-discriminator
638 // axis on the [`UpgradeInstruction`] closed-set typed enum,
639 // sibling of the [`UpgradeInstruction::is_restart`] terminal-
640 // fallback routing (915a934) and the
641 // [`UpgradeInstruction::is_cleanup`] two-arm cleanup-family
642 // routing (0bc469f) that already lifted the paired
643 // arm-discriminator sites in this method. Every arm-family
644 // partition the gate keys off — load-family (`LoadModule`),
645 // cleanup-family (`SoftPurge | Purge`), terminal-fallback
646 // (`Restart`) — now consults exactly one typed dispatch on
647 // the substrate primitive, so a future sixth arm added to
648 // [`UpgradeInstruction`] (an `AwaitReadiness` gate, a
649 // `Downgrade` reverse-axis variant OTP's `relup` acknowledges,
650 // a `CanaryTraffic` split-traffic variant the M4 CR
651 // materializer could resolve per-CR — INSPIRATIONS §II.4)
652 // migrates as a single enum-declaration edit through the
653 // derive rather than a scattered per-consumer rewrite. The
654 // partition invariant is pinned by
655 // [`tests::upgrade_instruction_is_load_module_predicate_partitions_the_arm_set`]
656 // and the byte-identity of this dispatch against the pre-lift
657 // `matches!` pattern by
658 // [`tests::validate_purge_ordering_routes_through_is_load_module_predicate`].
659 if instr.is_load_module() {
660 loaded = true;
661 } else if instr.is_cleanup() && !loaded {
662 return Err(UpgradeError::purge_without_prior_load(
663 self.prior_versao(),
664 instr.lisp_form(),
665 instr
666 .declared_module()
667 .expect("is_cleanup() implies declared_module() is Some"),
668 ));
669 }
670 }
671 Ok(())
672 }
673
674 /// Reject an entry whose `(:state-change …)` appears after any
675 /// `(:soft-purge …)` / `(:purge …)` in the same `:instructions`
676 /// list — completing the canonical OTP appup `code:load_module/1`
677 /// → `gen_server:code_change/3` → `code:soft_purge/1` ordering
678 /// chain on the typed `:upgrade-from` slot.
679 ///
680 /// `StateChange` is the `gen_server:code_change/3` analog
681 /// ([`UpgradeInstruction::StateChange`] doc; INSPIRATIONS §II.4
682 /// verbatim: "State migration uses `gen_server:code_change/3` …
683 /// migrate state from v0.1.0 shape to current shape"). The
684 /// callback's input is the *prior* version's state shape, which
685 /// only exists while the prior code is still resident — the running
686 /// `gen_server` processes hold the v0.1.0 state, and the operator's
687 /// dispatch invokes `code_change/3` to fold that state into the
688 /// current shape. `SoftPurge` / `Purge` are the `code:soft_purge/1`
689 /// / `code:purge/1` analogs ([`UpgradeInstruction::SoftPurge`] /
690 /// [`UpgradeInstruction::Purge`] docs): they drain or discard the
691 /// *old* module after the new one is resident. The operator runs
692 /// instructions in declared order (module doc), so a cleanup ahead
693 /// of a state-change discards the prior code before the migration
694 /// fold runs against the state it held — the canonical OTP error
695 /// mode "`code_change/3` invoked on a purged module" the
696 /// `release_handler` enforces by always emitting the migration
697 /// callback before the soft-purge step.
698 ///
699 /// `systools`-generated `.relup` files always emit `code_change`
700 /// before `soft_purge` for this reason; the appup cookbook's
701 /// canonical pattern (`[{load_module, m}, {update, m, soft},
702 /// {soft_purge, m}]`) places the migration-triggering `update`
703 /// strictly between the load and the cleanup. The caixa module
704 /// doc pins the same canonical order verbatim — `(:load-module
705 /// …) (:state-change …) (:soft-purge …)` — and this gate makes
706 /// that ordering a structural property at build time. Three
707 /// authoring footguns close here:
708 ///
709 /// - `((:load-module "x") (:soft-purge "x-old") (:state-change
710 /// "lib/m.lisp"))` — the right-instructions-wrong-order
711 /// footgun on the migrate ↔ cleanup axis. Because the operator
712 /// executes in declared order, the cleanup drains the v0.1.0
713 /// module to nothing before the migration callback runs, and
714 /// the script either no-ops (no v0.1.0 state left to fold) or
715 /// crashes (`code_change/3` invoked on an unloaded version).
716 /// The canonical order is `(:load-module …) (:state-change
717 /// …) (:soft-purge …)` (module doc example).
718 /// - `((:load-module "x") (:purge "x-old") (:state-change
719 /// "lib/m.lisp"))` — same shape on the more catastrophic
720 /// `:purge` variant. The immediate-discard semantic destroys
721 /// v0.1.0 state mid-request; the trailing migration script
722 /// has nothing to fold from and the `gen_server` processes that
723 /// held v0.1.0 state were killed by the `:purge`.
724 /// - `((:load-module "x") (:soft-purge "x-old") (:state-change
725 /// "lib/m1.lisp") (:soft-purge "y-old"))` — the "migration
726 /// sandwiched between two cleanups" footgun. The first
727 /// cleanup discards v0.1.0; the migration runs against
728 /// drained state; the second cleanup is irrelevant. The first
729 /// cleanup → state-change boundary is the load-bearing defect
730 /// surfaced.
731 ///
732 /// Same within-entry cross-instruction discipline as
733 /// [`Self::validate_state_change_ordering`] (the load → state-
734 /// change ordering gate it runs after) and
735 /// [`Self::validate_purge_ordering`] (the load → cleanup ordering
736 /// gate it runs after): all three close one boundary of the OTP
737 /// canonical sequence `code:load_module/1` →
738 /// `gen_server:code_change/3` → `code:soft_purge/1`. The
739 /// state-change-ordering gate closes the load → migrate boundary;
740 /// the purge-ordering gate closes the load → cleanup boundary;
741 /// this gate closes the migrate → cleanup boundary, completing
742 /// the typed coverage of the canonical sequence. Runs *after*
743 /// [`Self::validate_purge_ordering`] (and therefore after
744 /// [`Self::validate_state_change_ordering`]) so an entry like
745 /// `((:soft-purge "x-old") (:state-change "lib/m.lisp"))` —
746 /// which violates *both* the purge-without-load gate and this
747 /// state-change-after-cleanup gate — surfaces the more-
748 /// fundamental `PurgeWithoutPriorLoad` first (the missing-load
749 /// defect is load-bearing; once a coherent `(:load-module …)`
750 /// precedes both, the migrate ↔ cleanup ordering becomes the
751 /// next live defect). Runs *before* the per-instruction-class
752 /// singularity gates ([`Self::validate_load_singularity`],
753 /// [`Self::validate_state_change_singularity`],
754 /// [`Self::validate_cleanup_singularity`]) so an entry like
755 /// `((:load-module "x") (:soft-purge "x-old") (:state-change
756 /// "lib/m.lisp") (:state-change "lib/m.lisp"))` — which violates
757 /// *both* this ordering gate and the state-change-singularity
758 /// gate — surfaces the ordering defect first; the canonical
759 /// "ordering before singularity" precedence the peer
760 /// `validate_state_change_ordering` / `validate_purge_ordering`
761 /// gates already establish.
762 ///
763 /// Detection: linear scan of the instructions list with a
764 /// `prior_cleanup: Option<(module, kind)>` sticky-once latch
765 /// recording the first cleanup encountered; on any subsequent
766 /// `StateChange` the gate fires with the script + the prior
767 /// cleanup's kind/module. Diagnostic-order pin: the first
768 /// colliding state-change-after-cleanup pair surfaces, not the
769 /// last — mirrors every peer ordering gate's first-collision
770 /// posture ([`Self::validate_state_change_ordering`] returns on
771 /// the first `StateChange` without prior load,
772 /// [`Self::validate_purge_ordering`] on the first cleanup
773 /// without prior load).
774 fn validate_state_change_before_cleanup(&self) -> Result<(), UpgradeError> {
775 let mut prior_cleanup: Option<(&str, &'static str)> = None;
776 for instr in self.instructions() {
777 // Route the per-instruction cleanup-family arm-discriminator
778 // through the lifted [`UpgradeInstruction::is_cleanup`] typed
779 // predicate rather than the raw
780 // `UpgradeInstruction::SoftPurge { module } |
781 // UpgradeInstruction::Purge { module }` open-coded per-arm
782 // union pattern-match — the second of three within-entry
783 // cross-instruction cleanup-facing gates the peer
784 // [`Self::validate_purge_ordering`] routing already lifted;
785 // both now key off exactly one typed dispatch on the substrate
786 // primitive so the "which arms belong to the cleanup family"
787 // question resolves at exactly one caixa-core edit. The
788 // sticky-once latch's `:module` scalar is routed through the
789 // sibling [`UpgradeInstruction::declared_module`] accessor
790 // rather than the raw pattern-bound `module.as_str()`
791 // projection, with the `is_cleanup`-implies-`declared_module`-
792 // is-`Some` composition pin at
793 // [`tests::upgrade_instruction_is_cleanup_implies_declared_module_is_some`]
794 // making the `.expect(…)` structurally infallible at build
795 // time.
796 if instr.is_cleanup() && prior_cleanup.is_none() {
797 prior_cleanup = Some((
798 instr
799 .declared_module()
800 .expect("is_cleanup() implies declared_module() is Some"),
801 instr.lisp_form(),
802 ));
803 } else if let Some(script) = instr.declared_path()
804 && let Some((prior_module, prior_kind)) = prior_cleanup
805 {
806 // Route the per-instruction `StateChange`-arm script-path
807 // projection through the sibling lifted
808 // [`UpgradeInstruction::declared_path`] `Option<&PathBuf>`
809 // accessor rather than the raw
810 // `if let UpgradeInstruction::StateChange { script } = instr`
811 // open-coded pattern-match — the last unlifted per-
812 // `UpgradeInstruction` `PathBuf`-carrying-axis consumer
813 // inside `impl UpgradeFromEntry`, sibling to the four peer
814 // per-`UpgradeInstruction` consumers already routed through
815 // the accessor: [`UpgradeInstruction::validate`]'s per-
816 // `StateChange` sandbox-path fan-out, the layout-side per-
817 // `StateChange` script-existence fan-out at
818 // [`crate::layout::StandardLayout::verify`]
819 // (caixa-core/src/layout.rs:1058), the within-entry
820 // [`UpgradeFromEntry::validate_state_change_singularity`]
821 // per-`StateChange` script-projection fan-out, and the
822 // cross-slot
823 // [`validate_upgrade_from_against_behavior`]
824 // per-`StateChange` detection loop. Byte-equal today
825 // (`declared_path` returns `Some(script)` iff the
826 // instruction is [`UpgradeInstruction::StateChange`], per
827 // the sibling `declared_path_only_for_state_change` pin),
828 // so a state-change-after-cleanup surfaces
829 // `StateChangeAfterCleanup` byte-identical to the pattern-
830 // match shape. Any future accessor extension that promotes
831 // an additional variant onto the `PathBuf`-carrying axis
832 // reaches this gate through one caixa-core edit rather
833 // than a coordinated rewrite of five call sites — the
834 // migrate→cleanup ordering discipline extends to the
835 // promoted variant by construction. Same "one typed
836 // dispatch on the substrate primitive, thin projections at
837 // each consumer" trajectory the sibling
838 // [`UpgradeInstruction::declared_module`] `String`-axis
839 // per-variant unifier already established.
840 return Err(UpgradeError::state_change_after_cleanup(
841 self.prior_versao(),
842 script,
843 prior_kind,
844 prior_module,
845 ));
846 }
847 }
848 Ok(())
849 }
850
851 /// Reject an entry whose `:instructions` list names the same module
852 /// as the target of more than one cleanup instruction (`:soft-purge`
853 /// or `:purge`) in total — set-not-multiset on the (cleanup-class,
854 /// module) axis, narrowed to the cleanup class.
855 ///
856 /// `SoftPurge` and `Purge` are the `code:soft_purge/1` /
857 /// `code:purge/1` analogs (INSPIRATIONS §II.4 verbatim: "1.
858 /// `code:load_module/1` — load v2 alongside v1 … 2.
859 /// `code:soft_purge/1` — wait until no process is running v1, then
860 /// discard. (`code:purge/1` kills v1 immediately if you don't
861 /// care.)"). The author picks *one* cleanup semantic per old
862 /// module — `:soft-purge` (preferred: waits for in-flight callers
863 /// to drain) or `:purge` (when the drain isn't possible) — and the
864 /// operator runs that one in declared order alongside any other
865 /// distinct-module cleanups. systools-generated `.relup` files
866 /// always emit at most one purge per module for this reason; any
867 /// retry / fallback decision is the operator's job on
868 /// instruction failure, not authored into the entry. Three
869 /// authoring footguns close here:
870 ///
871 /// - `((:load-module "x") (:soft-purge "x-old") (:soft-purge "x-old"))`
872 /// — the "I copy-pasted the cleanup line twice" footgun. The
873 /// second `:soft-purge` is a no-op (the module is already gone
874 /// after the first drain-and-discard) or undefined depending
875 /// on the operator's handling of a non-resident-module purge
876 /// request; either way the second instruction carries no
877 /// observable semantic, far from the source caixa.lisp.
878 /// - `((:load-module "x") (:soft-purge "x-old") (:purge "x-old"))`
879 /// — the "soft-then-hard fallback" footgun. The author wrote
880 /// "drain, and if drain didn't clean it up, force-discard",
881 /// but the operator runs instructions unconditionally in
882 /// declared order — the `:purge` fires whether the
883 /// `:soft-purge` already discarded the module or not, so the
884 /// fallback semantic the author imagined is missing; the
885 /// pair is incoherent (drain *and* force-discard semantics
886 /// on one module is two contradictory dispositions). The
887 /// operator's failure-handling surface is its own
888 /// responsibility: if `:soft-purge` doesn't drain within its
889 /// cooldown the operator escalates, not the author's entry.
890 /// - `((:load-module "x") (:purge "x-old") (:soft-purge "x-old"))`
891 /// — same shape on the reversed ordering. The `:purge`
892 /// discards immediately; the trailing `:soft-purge` has no
893 /// module to drain.
894 ///
895 /// Same within-entry exclusivity discipline as
896 /// [`Self::validate_restart_exclusive`] (the `(:restart)` terminal-
897 /// exclusivity gate it joins on the per-module cleanup axis): both
898 /// reject an `:instructions` list whose instructions are
899 /// individually well-shaped but jointly incoherent on a chosen
900 /// semantic axis (restart-fallback for the whole entry there;
901 /// cleanup-semantic for one module here), at the typed build
902 /// surface rather than as a runtime surprise. Runs *after*
903 /// [`Self::validate_purge_ordering`] (the load-before-cleanup
904 /// ordering gate) so an entry like `((:soft-purge "x-old")
905 /// (:soft-purge "x-old"))` surfaces the more-fundamental
906 /// `PurgeWithoutPriorLoad` first (both cleanups are load-less, and
907 /// the missing-load defect is the load-bearing one — the duplicate
908 /// is meaningless either way without the preceding load).
909 ///
910 /// Same set-not-multiset discipline applied to every peer
911 /// duplicate-target axis: `:children :caixa` (dbf50a9 —
912 /// `SupervisorError::DuplicateChildCaixa`), `:membros :caixa`
913 /// (4bb3f3d — `AplicacaoError::MembroDuplicate`), `:contratos`
914 /// (5dbcfaf — `AplicacaoError::ContratoDuplicate`), `:placement
915 /// :clusters` (c7c7799 — `AplicacaoError::PlacementClusterDuplicate`),
916 /// `:entrada :paths` (eb3456d — `AplicacaoError::EntradaPathDuplicate`),
917 /// and `:upgrade-from :from` ([`UpgradeError::DuplicateFrom`]).
918 /// Each closes the same authoring footgun: a Vec authoring surface
919 /// that silently accepts duplicate entries and renders the "second
920 /// wins" (or "operator processes both, second is a no-op or
921 /// errors") shape downstream, far from the source caixa.lisp.
922 /// This gate extends the discipline onto the within-entry
923 /// instruction-target axis — duplicate cleanup targets *within*
924 /// one `:upgrade-from` entry — the peer of the cross-entry
925 /// duplicate-`:from` axis at one level of nesting deeper.
926 ///
927 /// Detection: linear scan of the instructions list collecting
928 /// the (module, kind) pair from every `SoftPurge` / `Purge`
929 /// encountered; on the second occurrence of any module the gate
930 /// fires with the prior kind and the colliding kind in declaration
931 /// order. Diagnostic-order pin: the first colliding pair surfaces,
932 /// not the last — mirrors
933 /// [`validate_upgrade_from`]'s
934 /// `validate_upgrade_from_duplicate_diagnostic_names_second_collision`
935 /// posture (the first detected collision wins) and every peer
936 /// duplicate gate's first-collision discipline.
937 fn validate_cleanup_singularity(&self) -> Result<(), UpgradeError> {
938 let mut seen: Vec<(&str, &'static str)> = Vec::new();
939 for instr in self.instructions() {
940 // Route the per-instruction cleanup-family arm-discriminator
941 // through the lifted [`UpgradeInstruction::is_cleanup`] typed
942 // predicate rather than the raw two-arm
943 // `UpgradeInstruction::SoftPurge { module } => (module.as_str(),
944 // M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE)` /
945 // `UpgradeInstruction::Purge { module } => (module.as_str(),
946 // M2_UPGRADE_INSTRUCTION_KIND_PURGE)` / `_ => continue`
947 // per-arm dispatch — the third of three within-entry cross-
948 // instruction cleanup-facing gates the peer
949 // [`Self::validate_purge_ordering`] +
950 // [`Self::validate_state_change_before_cleanup`] routing
951 // already lifted; all three now key off exactly one typed
952 // dispatch on the substrate primitive, structurally. The
953 // cleanup-target `(module, kind)` pair is projected through
954 // the peer [`UpgradeInstruction::declared_module`] /
955 // [`UpgradeInstruction::lisp_form`] accessors rather than
956 // the per-arm-hand-rolled scalar-value + kind-const pair,
957 // with the `is_cleanup`-implies-`declared_module`-is-`Some`
958 // composition pin at
959 // [`tests::upgrade_instruction_is_cleanup_implies_declared_module_is_some`]
960 // making the `.expect(…)` structurally infallible at build
961 // time. Any future fifth cleanup-shaped variant added under
962 // the `is_cleanup` predicate + registered through the peer
963 // `lisp_form` per-arm kebab-case-const dispatch reaches this
964 // dedup gate through the accessor's one body rather than a
965 // fourth per-arm-hand-rolled scalar/kind projection here.
966 if !instr.is_cleanup() {
967 continue;
968 }
969 let module = instr
970 .declared_module()
971 .expect("is_cleanup() implies declared_module() is Some");
972 let kind = instr.lisp_form();
973 if let Some(prior_idx) = seen.iter().position(|(m, _)| *m == module) {
974 let prior_kind = seen[prior_idx].1;
975 return Err(UpgradeError::duplicate_cleanup(
976 self.prior_versao(),
977 module,
978 vec![prior_kind, kind],
979 ));
980 }
981 seen.push((module, kind));
982 }
983 Ok(())
984 }
985
986 /// Reject an entry whose `:instructions` list names the same module
987 /// as the target of more than one `(:load-module …)` instruction —
988 /// set-not-multiset on the `LoadModule` axis.
989 ///
990 /// `LoadModule` is the `code:load_module/1` analog (INSPIRATIONS
991 /// §II.4 verbatim: "1. `code:load_module/1` — load v2 alongside v1;
992 /// new code is 'current', old code is 'old'."). The instruction
993 /// brings the new wasm component up resident alongside the old
994 /// one so the operator can route new traffic to the new code
995 /// while in-flight callers drain on the old — and the operator's
996 /// dispatch table reads the module *name* (a caixa name) to bind
997 /// the component, so two `(:load-module "x")` instructions in one
998 /// entry ask the operator to re-bind the same component twice.
999 /// `systools`-generated `.relup` files emit at most one
1000 /// `load_module` per module per upgrade step for this reason; the
1001 /// second load has no observable semantic relative to the first
1002 /// (the component is already resident). Three authoring footguns
1003 /// close here:
1004 ///
1005 /// - `((:load-module "x") (:load-module "x"))` — the "I
1006 /// copy-pasted the load line twice" footgun. The second
1007 /// `:load-module` re-reads the same module name and re-binds
1008 /// the same wasm component — a no-op in both directions
1009 /// (no new code becomes resident; no old code is purged) —
1010 /// and any cleanup / migration the author intended for a
1011 /// *distinct* module is silently absent from the entry.
1012 /// - `((:load-module "x") (:load-module "x") (:state-change …))`
1013 /// — the "I meant to load two distinct modules" typo. The
1014 /// author intended `((:load-module "x") (:load-module "y"))`
1015 /// but renamed both to "x" (or copied the first line and
1016 /// forgot to change the module). The migration runs against
1017 /// code that's resident only on one module name, and the
1018 /// second module the author imagined was being loaded never
1019 /// comes up at all — far from the source caixa.lisp.
1020 /// - `((:load-module "x") (:load-module "x") (:soft-purge "x-old"))`
1021 /// — same shape with a trailing cleanup. The duplicate load
1022 /// is dead code; the cleanup still fires correctly, masking
1023 /// the load-side duplication as a silently-passing entry.
1024 ///
1025 /// Same within-entry exclusivity discipline as
1026 /// [`Self::validate_cleanup_singularity`] (the per-module cleanup-
1027 /// singularity gate this runs beside) on the sibling
1028 /// `LoadModule` axis: both reject an `:instructions` list whose
1029 /// instructions are individually well-shaped but jointly
1030 /// incoherent on a per-module-per-class basis (load-once for the
1031 /// load axis here; cleanup-once for the cleanup axis there), at
1032 /// the typed build surface rather than as a runtime surprise.
1033 /// Runs *after* [`Self::validate_purge_ordering`] (the load-
1034 /// before-cleanup ordering gate) so an entry like
1035 /// `((:state-change "m.lisp") (:load-module "x") (:load-module "x"))`
1036 /// surfaces the more-fundamental `StateChangeWithoutPriorLoad`
1037 /// first (the missing-load defect is load-bearing — the migration
1038 /// runs against unloaded code; the duplicate is meaningless either
1039 /// way without the preceding load). Runs *before*
1040 /// [`Self::validate_cleanup_singularity`] so an entry like
1041 /// `((:load-module "x") (:load-module "x") (:soft-purge "y-old")
1042 /// (:soft-purge "y-old"))` surfaces `DuplicateLoadModule` first —
1043 /// the load axis precedes the cleanup axis in the canonical OTP
1044 /// sequence (`code:load_module/1` then `code:soft_purge/1`) and
1045 /// in [`UpgradeInstruction`] declaration order (`LoadModule`
1046 /// before `SoftPurge`/`Purge`), so the load-side singularity is
1047 /// the load-bearing diagnostic when both fire.
1048 ///
1049 /// Same set-not-multiset discipline applied to every peer
1050 /// duplicate-target axis: `:children :caixa` (dbf50a9 —
1051 /// `SupervisorError::DuplicateChildCaixa`), `:membros :caixa`
1052 /// (4bb3f3d — `AplicacaoError::MembroDuplicate`), `:contratos`
1053 /// (5dbcfaf — `AplicacaoError::ContratoDuplicate`), `:placement
1054 /// :clusters` (c7c7799 — `AplicacaoError::PlacementClusterDuplicate`),
1055 /// `:entrada :paths` (eb3456d — `AplicacaoError::EntradaPathDuplicate`),
1056 /// `:upgrade-from :from` ([`UpgradeError::DuplicateFrom`]), and
1057 /// the per-module cleanup-target axis (9cedd8b —
1058 /// [`UpgradeError::DuplicateCleanup`]). This gate extends the
1059 /// discipline onto the within-entry `LoadModule` instruction-target
1060 /// axis — the third within-entry per-module singularity completing
1061 /// the load+cleanup pair across the OTP two-phase code-load
1062 /// contract.
1063 ///
1064 /// Detection: linear scan of the instructions list collecting the
1065 /// module name from every `LoadModule` encountered; on the second
1066 /// occurrence of any module the gate fires. Diagnostic-order pin:
1067 /// the first colliding occurrence surfaces, not the last — mirrors
1068 /// [`Self::validate_cleanup_singularity`]'s first-collision posture
1069 /// and every peer duplicate gate's first-collision discipline.
1070 fn validate_load_singularity(&self) -> Result<(), UpgradeError> {
1071 let mut seen: Vec<&str> = Vec::new();
1072 for instr in self.instructions() {
1073 // Route the per-instruction load-family arm-discriminator
1074 // through the `gen_platform::IsVariant`-derive-generated
1075 // [`UpgradeInstruction::is_load_module`] predicate rather
1076 // than the raw single-arm `match instr {
1077 // UpgradeInstruction::LoadModule { module } =>
1078 // module.as_str(), _ => continue }` open-coded pattern-
1079 // match — closes the last unlifted `matches!`-shaped
1080 // per-arm-hand-rolled scalar-value + arm-discriminator
1081 // pair inside `impl UpgradeFromEntry`, sibling of the
1082 // peer [`Self::validate_cleanup_singularity`] (0bc469f)
1083 // routing already lifted onto the two-arm cleanup-family
1084 // axis's per-arm arm-discriminator + `:module` projection
1085 // dispatch. The load-target `:module` scalar is projected
1086 // through the sibling [`UpgradeInstruction::declared_module`]
1087 // accessor rather than the per-arm-hand-rolled scalar-
1088 // value binding, with the
1089 // `is_load_module`-implies-`declared_module`-is-`Some`
1090 // composition pin at
1091 // [`tests::upgrade_instruction_is_load_module_implies_declared_module_is_some`]
1092 // making the `.expect(…)` structurally infallible at
1093 // build time. Every arm-family partition the three
1094 // within-entry per-instruction-class singularity gates
1095 // key off — load-family
1096 // ([`UpgradeInstruction::LoadModule`]), cleanup-family
1097 // ([`UpgradeInstruction::SoftPurge`] |
1098 // [`UpgradeInstruction::Purge`]), migration-family
1099 // ([`UpgradeInstruction::StateChange`]) — now consults
1100 // exactly one typed dispatch on the substrate primitive
1101 // (`is_load_module()` here, `is_cleanup()` at
1102 // [`Self::validate_cleanup_singularity`],
1103 // `declared_path()` at
1104 // [`Self::validate_state_change_singularity`]), so a
1105 // future sixth arm added to [`UpgradeInstruction`] (an
1106 // `AwaitReadiness` gate, a `Downgrade` reverse-axis
1107 // variant OTP's `relup` acknowledges, a `CanaryTraffic`
1108 // split-traffic variant the M4 CR materializer could
1109 // resolve per-CR — INSPIRATIONS §II.4) migrates as a
1110 // single enum-declaration edit through the derive rather
1111 // than a scattered per-consumer rewrite. Byte-identity of
1112 // this dispatch against the pre-lift match-pattern is
1113 // pinned by
1114 // [`tests::validate_load_singularity_projects_modules_through_is_load_module_and_declared_module_accessors`].
1115 if !instr.is_load_module() {
1116 continue;
1117 }
1118 let module = instr
1119 .declared_module()
1120 .expect("is_load_module() implies declared_module() is Some");
1121 if seen.contains(&module) {
1122 return Err(UpgradeError::duplicate_load_module(
1123 self.prior_versao(),
1124 module,
1125 ));
1126 }
1127 seen.push(module);
1128 }
1129 Ok(())
1130 }
1131
1132 /// Reject an entry whose `:instructions` list names the same script
1133 /// as the target of more than one `(:state-change …)` instruction —
1134 /// set-not-multiset on the `StateChange` axis.
1135 ///
1136 /// `StateChange` is the `gen_server:code_change/3` analog
1137 /// (INSPIRATIONS §II.4: "State migration uses
1138 /// `gen_server:code_change/3`"). The instruction folds the *old*
1139 /// state into the shape the *new* code expects — a one-shot
1140 /// transition from one declared state representation to another.
1141 /// OTP's `release_handler:install_release/1` invokes `code_change/3`
1142 /// exactly once per upgrade per `gen_server`; `systools`-generated
1143 /// `.relup` files emit at most one `code_change` per `gen_server` per
1144 /// upgrade step for this reason. A second `(:state-change "m.lisp")`
1145 /// instruction targeting the same script in one entry re-runs the
1146 /// migration fold — at best a no-op (idempotent script masking a
1147 /// typo where the author intended two distinct scripts) and at
1148 /// worst silent state corruption (non-idempotent fold double-
1149 /// applied: an `add column` migration that runs twice, an
1150 /// `increment counter` that double-bumps, a `rename field` that
1151 /// renames-then-fails the second time). Three authoring footguns
1152 /// close here:
1153 ///
1154 /// - `((:load-module "x") (:state-change "lib/m.lisp")
1155 /// (:state-change "lib/m.lisp"))` — the "I copy-pasted the
1156 /// migration line twice" footgun. The second `:state-change`
1157 /// re-runs the same fold on the already-migrated state — a
1158 /// no-op if the script is idempotent (dead code masking the
1159 /// duplication) or state corruption if not (the migration's
1160 /// pre-condition no longer holds because the post-condition is
1161 /// already in place).
1162 /// - `((:load-module "x") (:state-change "lib/m.lisp")
1163 /// (:state-change "lib/m.lisp") (:soft-purge "x-old"))` — the
1164 /// "duplicate migrate masked by trailing cleanup" footgun. The
1165 /// cleanup still fires correctly, masking the migration-side
1166 /// duplication as a silently-passing entry.
1167 /// - `((:load-module "x") (:state-change "lib/m1.lisp")
1168 /// (:state-change "lib/m1.lisp"))` — the "I meant to migrate
1169 /// two distinct modules" typo. The author intended
1170 /// `(:state-change "lib/m1.lisp") (:state-change "lib/m2.lisp")`
1171 /// but renamed both to `m1.lisp` (or copy-pasted the first line
1172 /// and forgot to change the script). The migration that should
1173 /// have folded the second module's state never runs, far from
1174 /// the source caixa.lisp.
1175 ///
1176 /// Same within-entry exclusivity discipline as
1177 /// [`Self::validate_load_singularity`] (the per-module load-
1178 /// singularity gate it runs after) and
1179 /// [`Self::validate_cleanup_singularity`] (the per-module cleanup-
1180 /// singularity gate it runs before) on the sibling `StateChange`
1181 /// axis: each rejects an `:instructions` list whose instructions
1182 /// are individually well-shaped but jointly incoherent on a per-
1183 /// instruction-class basis (load-once per module for the load
1184 /// axis; migrate-once per script for the migration axis here;
1185 /// cleanup-once per module for the cleanup axis), at the typed
1186 /// build surface rather than as a runtime surprise. Runs *after*
1187 /// [`Self::validate_load_singularity`] so an entry like
1188 /// `((:load-module "x") (:load-module "x") (:state-change
1189 /// "lib/m.lisp") (:state-change "lib/m.lisp"))` surfaces
1190 /// `DuplicateLoadModule` first — the load axis precedes the
1191 /// migration axis in the canonical OTP sequence
1192 /// (`code:load_module/1` then `gen_server:code_change/3`) and in
1193 /// [`UpgradeInstruction`] declaration order (`LoadModule` before
1194 /// `StateChange`), so the load-side singularity is the load-
1195 /// bearing diagnostic when both fire. Runs *before*
1196 /// [`Self::validate_cleanup_singularity`] so an entry like
1197 /// `((:load-module "x") (:state-change "lib/m.lisp") (:state-change
1198 /// "lib/m.lisp") (:soft-purge "y-old") (:soft-purge "y-old"))`
1199 /// surfaces `DuplicateStateChange` first — the migration axis
1200 /// precedes the cleanup axis in the canonical OTP sequence
1201 /// (`code:code_change/3` then `code:soft_purge/1`) and in
1202 /// [`UpgradeInstruction`] declaration order (`StateChange` before
1203 /// `SoftPurge`/`Purge`).
1204 ///
1205 /// Same set-not-multiset discipline applied to every peer
1206 /// duplicate-target axis: `:children :caixa` (dbf50a9 —
1207 /// `SupervisorError::DuplicateChildCaixa`), `:membros :caixa`
1208 /// (4bb3f3d — `AplicacaoError::MembroDuplicate`), `:contratos`
1209 /// (5dbcfaf — `AplicacaoError::ContratoDuplicate`), `:placement
1210 /// :clusters` (c7c7799 — `AplicacaoError::PlacementClusterDuplicate`),
1211 /// `:entrada :paths` (eb3456d — `AplicacaoError::EntradaPathDuplicate`),
1212 /// `:upgrade-from :from` ([`UpgradeError::DuplicateFrom`]), the
1213 /// per-module cleanup-target axis (9cedd8b —
1214 /// [`UpgradeError::DuplicateCleanup`]), and the per-module load-
1215 /// target axis (a503978 — [`UpgradeError::DuplicateLoadModule`]).
1216 /// This gate extends the discipline onto the within-entry
1217 /// `StateChange` instruction-target axis — the third within-entry
1218 /// per-instruction-class singularity, completing the OTP two-phase
1219 /// code-load + state-migration coverage triad
1220 /// (`code:load_module/1` → `gen_server:code_change/3` →
1221 /// `code:soft_purge/1`).
1222 ///
1223 /// Detection: linear scan of the instructions list collecting the
1224 /// script path from every `StateChange` encountered; on the second
1225 /// occurrence of any script the gate fires. Diagnostic-order pin:
1226 /// the first colliding occurrence surfaces, not the last — mirrors
1227 /// [`Self::validate_load_singularity`]'s and
1228 /// [`Self::validate_cleanup_singularity`]'s first-collision posture
1229 /// and every peer duplicate gate's first-collision discipline.
1230 fn validate_state_change_singularity(&self) -> Result<(), UpgradeError> {
1231 // Route the per-instruction `StateChange`-arm script-path
1232 // projection through the sibling lifted
1233 // [`UpgradeInstruction::declared_path`] `Option<&PathBuf>`
1234 // accessor rather than the raw
1235 // `match instr { UpgradeInstruction::StateChange { script } =>
1236 // script.as_path(), _ => continue }` open-coded pattern-match —
1237 // the third within-entry singularity gate's per-instruction
1238 // script-projection site now keys off exactly one typed
1239 // dispatch on the substrate primitive's `PathBuf`-carrying
1240 // axis, sibling to the four peer per-`UpgradeInstruction`
1241 // consumers ([`Self::validate`]'s per-`StateChange`
1242 // sandbox-path fan-out, the layout-side per-`StateChange`
1243 // script-existence fan-out at
1244 // `caixa-core/src/layout.rs:1017`, the cross-slot
1245 // [`validate_upgrade_from_against_behavior`] gate's
1246 // per-`StateChange` detection loop, the future wasm-operator's
1247 // per-`StateChange` runtime hook-dispatch) that already route
1248 // through `declared_path` / `declared_module`. Byte-equal
1249 // today (`declared_path` returns `Some(script)` iff the
1250 // instruction is [`UpgradeInstruction::StateChange`], per the
1251 // sibling `declared_path_only_for_state_change` pin), so a
1252 // duplicate `:state-change` script surfaces
1253 // `DuplicateStateChange` byte-identical to the pattern-match
1254 // shape. Same "one typed dispatch on the substrate primitive,
1255 // thin projections at each consumer" discipline the sibling
1256 // [`UpgradeInstruction::declared_module`] accessor established
1257 // (b13c4f9) on the peer `String`-carrying axis's per-variant
1258 // consumers, extended here onto the last unlifted
1259 // pattern-match on the `PathBuf`-carrying axis inside
1260 // `impl UpgradeFromEntry`.
1261 let mut seen: Vec<&std::path::Path> = Vec::new();
1262 for instr in self.instructions() {
1263 let Some(script) = instr.declared_path() else {
1264 continue;
1265 };
1266 let script = script.as_path();
1267 if seen.contains(&script) {
1268 return Err(UpgradeError::duplicate_state_change(
1269 self.prior_versao(),
1270 script,
1271 ));
1272 }
1273 seen.push(script);
1274 }
1275 Ok(())
1276 }
1277}
1278
1279/// Validate a whole `:upgrade-from` list: per-entry typed shape via
1280/// [`UpgradeFromEntry::validate`] *and* the cross-entry graph-edge-set
1281/// invariant — at most one `(:from <prior>)` block per parsed semver.
1282///
1283/// OTP's appup picks at most one matching block to apply to the running
1284/// release (`release_handler:install_release/1` matches the loaded
1285/// `:from` against the currently-running version and executes the
1286/// associated instruction sequence; the wasm-operator picks the matching
1287/// block at upgrade time, per `upgrade.rs` module doc). Two blocks with
1288/// the same parsed-semver `:from` are an ambiguous edge in the typed
1289/// upgrade graph — the operator can pick either set deterministically,
1290/// but each set may carry different `LoadModule | StateChange |
1291/// SoftPurge | Purge | Restart` instructions, so the *chosen* path is
1292/// non-deterministic relative to the source caixa.lisp. The author's
1293/// intent is one path per prior version; the typed graph must enforce
1294/// that shape.
1295///
1296/// Same set-not-multiset discipline already applied to every peer
1297/// typed-graph axis: `:children :caixa` (dbf50a9 —
1298/// `SupervisorError::DuplicateChildCaixa`, `child_spec.id` is required-
1299/// unique per supervisor in OTP), `:membros :caixa` (4bb3f3d —
1300/// `AplicacaoError::MembroDuplicate`), `:contratos`
1301/// (5dbcfaf — `AplicacaoError::ContratoDuplicate`), `:placement
1302/// :clusters` (c7c7799 — `AplicacaoError::PlacementClusterDuplicate`),
1303/// and `:entrada :paths` (eb3456d — `AplicacaoError::EntradaPathDuplicate`).
1304/// Each closes the same authoring footgun: a Vec authoring surface that
1305/// silently accepts duplicate entries and renders the "second wins"
1306/// (or "operator picks arbitrarily") shape downstream, far from the
1307/// source caixa.lisp.
1308///
1309/// Duplicates are detected by [`semver::Version`] equality (the
1310/// crate's `PartialEq` compares the full identity — major.minor.patch +
1311/// pre-release + build metadata — so `1.0.0` and `1.0.0-rc.1` and
1312/// `1.0.0+build1` and `1.0.0+build2` are all distinct upgrade paths).
1313/// The conservative choice mirrors what the wasm-operator's
1314/// `:from`-match dispatch can see; collapsing build metadata to catch
1315/// a wider net of duplicates is a future tightening that requires
1316/// coordinating with the operator's match step.
1317///
1318/// Per-entry shape errors fire before the duplicate gate so the
1319/// diagnostic names the malformed slot (`FromInvalid`, `EmptyScript`,
1320/// `ModuleInvalid`, …) rather than collapsing two unrelated authoring
1321/// errors into a single duplicate diagnostic. Mirrors the
1322/// `*_invalid_fires_before_duplicate_check` order pins on every peer
1323/// axis ([`crate::SupervisorSpec::validate`],
1324/// [`crate::AplicacaoSpec::validate_membros`],
1325/// [`crate::AplicacaoSpec::validate_placement`]).
1326pub fn validate_upgrade_from(entries: &[UpgradeFromEntry]) -> Result<(), UpgradeError> {
1327 use semver::Version;
1328 let mut seen: Vec<Version> = Vec::with_capacity(entries.len());
1329 for entry in entries {
1330 entry.validate()?;
1331 // `entry.validate()` accepted this `:from`, so parse cannot
1332 // fail here — the FromInvalid arm above is the only gate
1333 // and both call `Version::parse(entry.prior_versao())`.
1334 let parsed = Version::parse(entry.prior_versao()).expect(
1335 "UpgradeFromEntry::validate must accept `:from` iff Version::parse does — keep the \
1336 two gates aligned",
1337 );
1338 if seen.contains(&parsed) {
1339 return Err(UpgradeError::duplicate_from(entry));
1340 }
1341 seen.push(parsed);
1342 }
1343 Ok(())
1344}
1345
1346/// Reject `:upgrade-from` entries whose `:from` is not strictly less
1347/// than the caixa's current `:versao` (under SemVer-2 precedence — the
1348/// same ordering [`semver::Version::cmp`] implements, with build
1349/// metadata ignored per [SemVer §11][semver-11]).
1350///
1351/// The whole point of an `:upgrade-from :from "<prior>"` block is the
1352/// declarative answer to "given the wasm-operator is loading a node
1353/// running `<prior>`, how do I upgrade it to the *current* `:versao`?"
1354/// (`upgrade.rs` module doc, OTP appup `release_handler:install_release/1`
1355/// semantic). The operator's `:from`-match dispatch loads the
1356/// current `:versao` and matches the *running* version against each
1357/// entry's `:from`; an entry whose `:from >= :versao` is structurally
1358/// unreachable — the operator never runs a version greater than or
1359/// equal to the current `:versao` that it could then "upgrade *to*"
1360/// the current `:versao`. Two authoring footguns close here:
1361///
1362/// - `:from > :versao` (downgrade-shaped) — the canonical
1363/// "I copy-pasted from the next minor version and forgot to bump
1364/// `:versao`" / "I bumped `:versao` then reverted but left the
1365/// `:upgrade-from` entry behind" footgun. Until this gate landed
1366/// `(defcaixa :versao "0.1.5" :upgrade-from ((:from "0.2.0" …)))`
1367/// silently passed `feira build` and the wasm-operator's
1368/// `:from`-match dispatch would never fire on the entry — the
1369/// instructions sat dormant in the caixa.lisp forever, the
1370/// author's intent ("upgrade users coming from 0.2.0") permanently
1371/// unreached because they actually meant to bump `:versao`.
1372///
1373/// - `:from == :versao` (precedence-equal self-upgrade) — the
1374/// "I declared an upgrade from myself to myself" no-op the
1375/// operator's dispatch would either skip silently (no semantic
1376/// transition) or attempt and trivially "succeed" with no
1377/// observable state change. Includes the build-metadata-only
1378/// difference case (`:versao "0.2.0"`, `:from "0.2.0+build.1"`):
1379/// SemVer-2 precedence ignores build metadata so they compare
1380/// equal under [`semver::Version::cmp`] — the gate rejects this
1381/// even though [`UpgradeError::DuplicateFrom`] doesn't (the peer
1382/// gate uses derived `PartialEq` which keeps them distinct;
1383/// they're distinct dispatch keys but the same "from" version
1384/// for our purposes here).
1385///
1386/// Same cross-slot value-shape discipline as
1387/// [`crate::AplicacaoSpec::validate_placement`]'s strategy ↔ shard-key
1388/// partition (934bc58 — the typed partition between two declared
1389/// slots): one slot's value constrains the valid set of another's,
1390/// and the constraint is a structural property visible at validate
1391/// time. The validated set after this gate satisfies
1392/// `entry.from.parse::<Version>().unwrap() < versao.parse::<Version>().unwrap()`
1393/// for every entry, so the future operator-side hot-upgrade dispatch
1394/// step can reach for `entry.from` knowing the precedence relation
1395/// holds without re-deriving it from inline checks.
1396///
1397/// Silent-pass semantics on malformed inputs:
1398///
1399/// - When `versao` itself doesn't parse as semver, this gate
1400/// returns `Ok(())` silently — the narrower
1401/// [`crate::ManifestError::VersaoInvalid`] / [`UpgradeError::FromInvalid`]
1402/// diagnostics are the load-bearing surfaces for those failure
1403/// modes, and surfacing a `FromNotBeforeVersao` over an
1404/// unparseable `:versao` would mask the more actionable root
1405/// cause.
1406/// - Likewise, an entry whose `:from` itself doesn't parse falls
1407/// through to its narrower diagnostic surface
1408/// ([`UpgradeError::FromInvalid`]), which is expected to fire
1409/// via [`validate_upgrade_from`] *before* this gate runs at the
1410/// [`crate::LayoutInvariants`] call site.
1411///
1412/// [semver-11]: https://semver.org/#spec-item-11
1413pub fn validate_upgrade_from_against_versao(
1414 entries: &[UpgradeFromEntry],
1415 versao: &str,
1416) -> Result<(), UpgradeError> {
1417 use semver::Version;
1418 let Ok(current) = Version::parse(versao) else {
1419 // Malformed `:versao` is a separate gate (ManifestError::VersaoInvalid);
1420 // surfacing a precedence-relation diagnostic over an unparseable
1421 // top-level version would mask the more actionable root cause.
1422 return Ok(());
1423 };
1424 for entry in entries {
1425 // Per-entry shape — including a malformed `:from` — is gated
1426 // by [`validate_upgrade_from`] / [`UpgradeFromEntry::validate`]
1427 // upstream at the LayoutInvariants call site; an unparseable
1428 // `:from` here falls through silently to keep the
1429 // FromInvalid diagnostic load-bearing. Same fall-through
1430 // posture as the `versao` arm above.
1431 let Ok(prior) = Version::parse(entry.prior_versao()) else {
1432 continue;
1433 };
1434 if prior >= current {
1435 return Err(UpgradeError::from_not_before_versao(
1436 entry.prior_versao(),
1437 versao,
1438 ));
1439 }
1440 }
1441 Ok(())
1442}
1443
1444/// Reject `:upgrade-from` entries whose `:instructions` list carries any
1445/// `(:state-change <script>)` instruction unless the caixa also declares
1446/// `:behavior :on-state-change` — the runtime callback the per-version
1447/// migration script is delivered through during hot upgrade.
1448///
1449/// The module doc on [`crate::upgrade`] pins the composition verbatim:
1450/// the `:upgrade-from` slot "Composes with the `:behavior :on-state-change`
1451/// callback to deliver state migration during hot upgrades." The peer
1452/// module doc on [`crate::BehaviorSpec::on_state_change`] mirrors the
1453/// promise from the callback side: the slot is the
1454/// `gen_server:code_change/3` analog — "receives old state + version,
1455/// returns new state. Composes with the `:upgrade-from` slot declared at
1456/// the Caixa root." OTP's `release_handler:install_release/1` realizes
1457/// the composition by invoking the running `gen_server`'s
1458/// `code_change/3` callback during the appup's `code_change` /
1459/// `update, m, soft` step — the appup's instruction triggers the
1460/// callback, the callback folds the prior-version state shape into the
1461/// current-version shape, and the operator advances to the next
1462/// instruction only after the callback returns successfully. caixa
1463/// decomposes the same composition into two typed slots: the per-version
1464/// migration logic lives in the `(:state-change "lib/migrations/v01-to-v02.lisp")`
1465/// instruction's `:script` (the `:upgrade-from` author surface), and the
1466/// runtime hook the operator dispatches the migration through lives in
1467/// the `:behavior :on-state-change` callback (the `:behavior` author
1468/// surface). A `:state-change` instruction declared without the callback
1469/// is half the composition: the per-version script the author wrote has
1470/// no runtime delivery path, and the operator's hot-upgrade dispatch
1471/// reaches for `caixa.behavior.on_state_change` at the migration step,
1472/// finds `None`, and either fails the upgrade mid-flight (the
1473/// transactional rollback the module doc names — "On any failure, the
1474/// current version stays load-bearing — a typed atomic upgrade") or
1475/// silently skips the migration depending on the operator's handling of
1476/// a missing callback, both far from the source caixa.lisp.
1477///
1478/// Two authoring footguns close here:
1479///
1480/// - `(:behavior ((:on-init …)))` + `(:upgrade-from ((:from "0.1.0"
1481/// :instructions ((:load-module "x") (:state-change "lib/m.lisp")
1482/// (:soft-purge "x-old")))))` — the "I declared the migration script
1483/// but forgot the callback" footgun. The author wrote the per-version
1484/// fold against the prior state shape, the typed `:upgrade-from`
1485/// slot validated every per-instruction shape + ordering + singularity
1486/// gate, and the missing callback only surfaces at upgrade time as
1487/// either a transactional rollback to the prior version (no progress
1488/// across the upgrade) or as a silently-skipped migration that leaves
1489/// v0.2.0 code running against unmigrated v0.1.0 state (corrupted
1490/// state shape).
1491/// - `:behavior` absent entirely + `:upgrade-from` carrying any
1492/// `:state-change` — the "I added the upgrade path but never declared
1493/// `:behavior`" footgun. `:behavior` is optional at the typed root
1494/// ([`crate::Caixa::behavior: Option<BehaviorSpec>`]) so the typed
1495/// `:upgrade-from` slot validates on its own merits, but a `Caixa`
1496/// with `behavior: None` and a `:state-change` instruction is the
1497/// same missing-callback shape — the operator's dispatch can't reach
1498/// a callback that doesn't exist.
1499///
1500/// Same cross-slot composition discipline as
1501/// [`validate_upgrade_from_against_versao`] (the `:from` ↔ `:versao`
1502/// precedence gate at the peer wire-up site): one slot's value
1503/// (`:from` < `:versao` there; `:state-change` declared here) constrains
1504/// the valid set of another's (the entry must be dispatchable there; the
1505/// callback must be declared here), and the constraint is a structural
1506/// property visible at validate time. The validated set after this gate
1507/// satisfies the documented composition: every `:state-change`
1508/// instruction the operator iterates at hot-upgrade time has a
1509/// corresponding `:on-state-change` callback declared on the same caixa,
1510/// so the future wasm-operator's hot-upgrade dispatch (the OTP
1511/// `release_handler` canonical-sequence loop) can reach for
1512/// `behavior.on_state_change` at the migration step knowing the
1513/// `Option<PathBuf>` is `Some(_)` without re-deriving the precondition
1514/// from inline checks.
1515///
1516/// Diagnostic-precedence:
1517///
1518/// - Runs *after* [`UpgradeFromEntry::validate`] (per-instruction
1519/// shape + the within-entry ordering / singularity gates) and
1520/// [`validate_upgrade_from`] (the cross-entry duplicate-`:from`
1521/// gate), so a malformed `:state-change` (`EmptyScript`,
1522/// `AbsoluteScript`, `ParentEscapeScript`) or an ill-ordered entry
1523/// (`StateChangeWithoutPriorLoad`, `StateChangeAfterCleanup`) or a
1524/// duplicate `:from` (`DuplicateFrom`) surfaces its narrower
1525/// self-locating diagnostic first — the canonical "per-instr-shape +
1526/// within-entry ordering + cross-entry uniqueness before
1527/// cross-slot composition" precedence the peer
1528/// `validate_upgrade_from_against_versao` gate establishes at the
1529/// same wire-up site. Without this precedence pin a malformed
1530/// `:state-change` instruction would surface this gate's
1531/// missing-callback diagnostic over the narrower
1532/// `EmptyScript` / `StateChangeWithoutPriorLoad`, masking the
1533/// load-bearing per-instruction defect with a cross-slot composition
1534/// diagnostic.
1535/// - Within the entries, walks the list in declaration order and
1536/// surfaces the *first* `:state-change` instruction encountered —
1537/// mirrors every peer first-collision diagnostic posture on this
1538/// module (`validate_state_change_ordering` returns on the first
1539/// `StateChange` without prior load,
1540/// `validate_load_singularity` returns on the second matching
1541/// module, etc.). A future entry's later `:state-change` doesn't
1542/// surface a different diagnostic — the missing callback is the same
1543/// defect regardless of which entry's `:state-change` exposes it.
1544///
1545/// Silent-pass semantics:
1546///
1547/// - Entries carrying no `:state-change` instruction (load-only,
1548/// cleanup-only, restart-only, or empty `:instructions`) leave the
1549/// gate vacuous — no per-version migration means no callback to
1550/// dispatch through, so the absence of `:on-state-change` is
1551/// coherent. Pins the gate's identity element on the empty-set side
1552/// of the composition.
1553/// - `behavior: None` is *not* a free pass when a `:state-change`
1554/// instruction is present — the same missing-callback shape as
1555/// `behavior: Some(_)` with `on_state_change: None`. The gate reads
1556/// `behavior.and_then(BehaviorSpec::on_state_change)` so both shapes
1557/// surface the same diagnostic.
1558pub fn validate_upgrade_from_against_behavior(
1559 entries: &[UpgradeFromEntry],
1560 behavior: Option<&crate::BehaviorSpec>,
1561) -> Result<(), UpgradeError> {
1562 if behavior
1563 .and_then(crate::BehaviorSpec::on_state_change)
1564 .is_some()
1565 {
1566 return Ok(());
1567 }
1568 for entry in entries {
1569 // Route the per-instruction `StateChange`-arm script-path
1570 // projection through the sibling lifted
1571 // [`UpgradeInstruction::declared_path`] `Option<&PathBuf>`
1572 // accessor rather than the raw
1573 // `if let UpgradeInstruction::StateChange { script } = instr`
1574 // open-coded pattern-match — the cross-slot
1575 // `:upgrade-from ↔ :behavior` composition gate's per-instruction
1576 // script-projection site now keys off exactly one typed dispatch
1577 // on the substrate primitive's `PathBuf`-carrying axis, sibling
1578 // to the four peer per-`UpgradeInstruction` consumers
1579 // ([`UpgradeInstruction::validate`]'s per-`StateChange`
1580 // sandbox-path fan-out, the layout-side per-`StateChange`
1581 // script-existence fan-out at
1582 // [`crate::layout::StandardLayout::verify`] (caixa-core/src/layout.rs:1058),
1583 // the within-entry [`UpgradeFromEntry::validate_state_change_singularity`]
1584 // (2bf3ce5) per-`StateChange` script-projection fan-out, the
1585 // peer [`UpgradeInstruction::declared_module`] `String`-axis
1586 // per-variant unifier) that already route through
1587 // `declared_path` / `declared_module`. Byte-equal today
1588 // (`declared_path` returns `Some(script)` iff the instruction is
1589 // [`UpgradeInstruction::StateChange`], per the sibling
1590 // `declared_path_only_for_state_change` pin), so a
1591 // `:state-change`-without-`:on-state-change`-callback
1592 // composition surfaces `StateChangeWithoutOnStateChangeCallback`
1593 // byte-identical to the pattern-match shape. Fourth (and last)
1594 // per-`UpgradeInstruction`-consumer of the `PathBuf`-carrying
1595 // axis now routed through the accessor — closes the last
1596 // unlifted `if let UpgradeInstruction::StateChange { script } = instr`
1597 // site outside `impl UpgradeFromEntry`, so the peer four
1598 // consumer set named in the sibling
1599 // `validate_state_change_singularity_projects_scripts_through_declared_path_accessor`
1600 // pin (caixa-core/src/upgrade.rs:4598) is now structurally
1601 // closed.
1602 for instr in entry.instructions() {
1603 if let Some(script) = instr.declared_path() {
1604 return Err(UpgradeError::state_change_without_on_state_change_callback(
1605 entry.prior_versao(),
1606 script,
1607 ));
1608 }
1609 }
1610 }
1611 Ok(())
1612}
1613
1614impl UpgradeInstruction {
1615 /// Kebab-case lisp form name for this instruction, used as the
1616 /// `:kind` tag in [`UpgradeError::ModuleEmpty`] /
1617 /// [`UpgradeError::ModuleInvalid`] diagnostics so the author can
1618 /// grep their caixa.lisp for `(:load-module …)` / `(:soft-purge …)`
1619 /// / `(:purge …)` and fix it in one edit. Mirrors the kebab-case
1620 /// slot tags `BehaviorError::EmptyPath` (b0c8389) and
1621 /// `UpgradeFromEntry`'s `:from` field already carry.
1622 #[must_use]
1623 const fn lisp_form(&self) -> &'static str {
1624 match self {
1625 Self::LoadModule { .. } => crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE,
1626 Self::StateChange { .. } => crate::render::M2_UPGRADE_INSTRUCTION_KIND_STATE_CHANGE,
1627 Self::SoftPurge { .. } => crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
1628 Self::Purge { .. } => crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
1629 Self::Restart => crate::render::M2_UPGRADE_INSTRUCTION_KIND_RESTART,
1630 }
1631 }
1632
1633 /// Validate the instruction's typed shape. Path existence is
1634 /// checked separately by [`crate::layout::StandardLayout`].
1635 ///
1636 /// The per-variant scalar the value-shape gates fire against is
1637 /// read through this method's two sibling accessors — the
1638 /// `String`-carrying axis via [`Self::declared_module`] (the
1639 /// `LoadModule` / `SoftPurge` / `Purge` variants unifying on their
1640 /// K8s DNS-1123-label `:module` reference) and the `PathBuf`-
1641 /// carrying axis via [`Self::declared_path`] (the `StateChange`
1642 /// variant's tatara-lisp `:script`) — rather than the per-arm
1643 /// `Self::LoadModule { module } | Self::SoftPurge { module } |
1644 /// Self::Purge { module }` pattern the module-axis previously
1645 /// open-coded and the per-arm `Self::StateChange { script }` the
1646 /// script-axis previously open-coded. Every scalar this enum
1647 /// carries now flows through one of the two `Option<&…>`
1648 /// accessors, so a future extension of either axis (a fifth
1649 /// module-bearing variant, an operator-side pre-parsed scalar
1650 /// cache the accessors materialize behind the same return
1651 /// contract, an M4 typed sub-slot the accessors could route
1652 /// alongside the existing scalar) migrates as a single edit on
1653 /// the accessor rather than a coordinated rewrite of every
1654 /// downstream value-shape gate. `Restart` (the only variant that
1655 /// carries neither scalar) falls through both `Option` checks and
1656 /// returns `Ok(())` — the terminal-fallback shape the
1657 /// [`Self::Restart`] variant doc pins.
1658 pub fn validate(&self) -> Result<(), UpgradeError> {
1659 if let Some(module) = self.declared_module() {
1660 return validate_module(self.lisp_form(), module);
1661 }
1662 if let Some(script) = self.declared_path() {
1663 // Delegate the four-arm cascade (empty / absolute /
1664 // parent-escape / non-`.lisp`-extension) to the lifted
1665 // [`crate::render::require_sandboxed_lisp_path`] helper —
1666 // same `Empty → Absolute → ParentEscape → NonLispExtension`
1667 // arm-ordering this method previously inlined verbatim,
1668 // now shared with [`crate::BehaviorSpec::validate`]'s
1669 // per-`:on-*`-callback gate so every author-supplied
1670 // tatara-lisp source path on every M2 typed slot consults
1671 // one gate, not two-and-counting verbatim copies of the
1672 // same four-arm cascade. Each closure wraps the tag in
1673 // the same `*Script` variant the original inline code
1674 // raised, so the diagnostic shape every caller depends
1675 // on (the `:state-change :script` self-locating error)
1676 // is preserved by construction. See
1677 // [`crate::render::require_sandboxed_lisp_path`] for the
1678 // smallest-scope-arm-fires-last ordering rationale.
1679 crate::render::require_sandboxed_lisp_path(
1680 script,
1681 || UpgradeError::EmptyScript,
1682 || UpgradeError::absolute_script(script),
1683 || UpgradeError::parent_escape_script(script),
1684 || UpgradeError::non_lisp_extension_script(script),
1685 )?;
1686 }
1687 // `Restart` (the only variant with no `Option<&…>`-carrying
1688 // scalar) falls through both accessor gates and returns
1689 // `Ok(())` — the terminal-fallback shape.
1690 Ok(())
1691 }
1692
1693 /// The `:module` scalar carried by this instruction — the
1694 /// K8s DNS-1123-label OTP-appup caixa-name reference every
1695 /// [`Self::LoadModule`] / [`Self::SoftPurge`] / [`Self::Purge`]
1696 /// variant declares against, and every author expects `feira lint`
1697 /// to name verbatim in per-instruction diagnostics. Returns `None`
1698 /// on [`Self::StateChange`] (which carries a `:script` — closed by
1699 /// the sibling [`Self::declared_path`]) and on [`Self::Restart`]
1700 /// (which carries no data at all, the OTP terminal-fallback
1701 /// shape).
1702 ///
1703 /// Sibling in shape to [`Self::declared_path`] on the second and
1704 /// final scalar-carrying axis of [`UpgradeInstruction`]:
1705 /// `declared_path` closes the `PathBuf`-carrying arm
1706 /// (`StateChange`); `declared_module` closes the `String`-carrying
1707 /// arms (`LoadModule` / `SoftPurge` / `Purge`). Every scalar the
1708 /// enum carries now routes through one of the two `Option<&…>`
1709 /// accessors — a caller that doesn't care which variant declared
1710 /// the scalar reads through one `if let Some(…)` rather than a
1711 /// per-variant pattern match. The pair is the enum-variant-
1712 /// unifying peer of the per-mesh-slot-atom scalar-accessor family
1713 /// on the M3 side ([`crate::WitContract::source`] /
1714 /// [`crate::WitContract::destination`] /
1715 /// [`crate::WitContract::world_ref`] closing `:contratos`;
1716 /// [`crate::Entrada::hostname`] / [`crate::Entrada::destination`]
1717 /// closing `:entrada`; [`crate::Membro::nome`] /
1718 /// [`crate::Membro::versao_requirement`] closing `:membros`) and
1719 /// on the M2 side ([`crate::UpgradeFromEntry::prior_versao`]
1720 /// closing per-entry `:from`; the [`crate::LimitsSpec`] /
1721 /// [`crate::BehaviorSpec`] closed families; the [`crate::ChildSpec`]
1722 /// closed OTP-shape supervisor family) — those peer accessors
1723 /// return a struct field verbatim; this pair unifies enum-
1724 /// variant-carried scalars into one accessor per typed axis.
1725 ///
1726 /// Byte-for-byte from the typed variant's own `String` storage;
1727 /// no cloning, no re-parsing. A future extension of the axis (an
1728 /// M4 typed sub-slot the module string is derived from, an
1729 /// operator-side pre-parsed caixa-name cache the accessor could
1730 /// materialize behind the same `&str` return contract, a fifth
1731 /// module-bearing OTP-appup variant the enum grows) migrates as
1732 /// a single caixa-core edit rather than a coordinated rewrite
1733 /// of every downstream module-axis consumer (currently
1734 /// [`Self::validate`]'s DNS-1123-label gate through
1735 /// [`validate_module`]; extensible to future consumers on the
1736 /// same axis without further per-variant match sites).
1737 #[must_use]
1738 pub const fn declared_module(&self) -> Option<&str> {
1739 match self {
1740 Self::LoadModule { module } | Self::SoftPurge { module } | Self::Purge { module } => {
1741 Some(module.as_str())
1742 }
1743 Self::StateChange { .. } | Self::Restart => None,
1744 }
1745 }
1746
1747 /// If the instruction references an on-disk path, return it —
1748 /// used by the layout checker to verify the path resolves.
1749 ///
1750 /// Sibling on the `PathBuf`-carrying axis to [`Self::declared_module`]
1751 /// on the `String`-carrying axis: `declared_path` closes the
1752 /// `StateChange` arm's `:script`; `declared_module` closes the
1753 /// `LoadModule` / `SoftPurge` / `Purge` arms' `:module`. Together
1754 /// they route every scalar this enum carries through one of two
1755 /// `Option<&…>` accessors, so [`Self::validate`]'s value-shape
1756 /// gates dispatch on the accessor return rather than a per-variant
1757 /// pattern match on the enum shape itself.
1758 ///
1759 /// Four per-`UpgradeInstruction` consumers now key off this
1760 /// accessor's `PathBuf`-carrying axis:
1761 /// [`Self::validate`]'s per-`StateChange` sandbox-path fan-out,
1762 /// [`crate::layout::StandardLayout::verify`]'s per-`StateChange`
1763 /// script-existence fan-out at `caixa-core/src/layout.rs:1058`, the
1764 /// within-entry
1765 /// [`UpgradeFromEntry::validate_state_change_singularity`] (2bf3ce5)
1766 /// per-`StateChange` script-projection fan-out, and the cross-slot
1767 /// [`validate_upgrade_from_against_behavior`] `:upgrade-from ↔
1768 /// :behavior` composition gate's per-`StateChange` detection loop
1769 /// — every downstream consumer of the `PathBuf`-carrying axis
1770 /// reaches through this one dispatch, so a future accessor
1771 /// extension (an M4 typed sub-slot the script path is derived from,
1772 /// an operator-side pre-resolved-path cache the accessor
1773 /// materializes behind the same `Option<&PathBuf>` return contract,
1774 /// a fifth `PathBuf`-bearing OTP-appup variant the enum grows)
1775 /// migrates as a single caixa-core edit rather than a coordinated
1776 /// rewrite of four call sites.
1777 #[must_use]
1778 pub const fn declared_path(&self) -> Option<&PathBuf> {
1779 match self {
1780 Self::StateChange { script } => Some(script),
1781 _ => None,
1782 }
1783 }
1784
1785 /// Substrate-canonical per-`UpgradeInstruction` OTP-appup cleanup-
1786 /// family arm-discriminator predicate every within-entry cross-
1787 /// instruction cleanup-facing gate keys off — true iff `self` is
1788 /// [`Self::SoftPurge`] (`code:soft_purge/1` analog: drain the
1789 /// named module until no process is running it, then GC) or
1790 /// [`Self::Purge`] (`code:purge/1` analog: discard the named
1791 /// module immediately, without waiting for drain), the two OTP
1792 /// two-phase-code-load cleanup arms the closed-set enum's
1793 /// non-terminal / non-migration / non-load variants exhaust.
1794 /// Every non-cleanup arm ([`Self::LoadModule`] on the paired
1795 /// two-phase-load half, [`Self::StateChange`] on the
1796 /// `gen_server:code_change/3`-analog migration axis,
1797 /// [`Self::Restart`] on the OTP terminal-fallback shape)
1798 /// returns `false`.
1799 ///
1800 /// Prior to this lift the `Self::SoftPurge { module } |
1801 /// Self::Purge { module }` two-arm cleanup-family pattern-
1802 /// match sat inline at three within-entry cross-instruction
1803 /// gate sites, each hand-rolling its own copy of the union
1804 /// with no compile-time link back to the substrate primitive's
1805 /// closed-set arm-family: [`UpgradeFromEntry::validate_purge_ordering`]
1806 /// at caixa-core/src/upgrade.rs:570 (guarded arm firing
1807 /// [`UpgradeError::PurgeWithoutPriorLoad`] on any cleanup
1808 /// arriving before a preceding [`Self::LoadModule`]),
1809 /// [`UpgradeFromEntry::validate_state_change_before_cleanup`]
1810 /// at caixa-core/src/upgrade.rs:689 (sticky-once latch
1811 /// recording the first-encountered cleanup so a subsequent
1812 /// [`Self::StateChange`] fires [`UpgradeError::StateChangeAfterCleanup`]),
1813 /// and [`UpgradeFromEntry::validate_cleanup_singularity`] at
1814 /// caixa-core/src/upgrade.rs:800 (per-module cleanup-target
1815 /// dedup ejecting [`UpgradeError::DuplicateCleanup`] on the
1816 /// second cleanup targeting the same `:module`). Three open-
1817 /// coded per-arm-union pattern-matches that expressed no
1818 /// compile-time link back to the substrate primitive. A future
1819 /// fifth cleanup-shaped variant (a `Discard` variant the
1820 /// `code:delete/1` peer inspires that folds under the same
1821 /// two-phase-load cleanup partition, an M4 `SoftPurge` split
1822 /// into `SoftPurgeCoop` / `SoftPurgeForce` peers as the drain-
1823 /// cool-down policy grows a two-arm shape, an operator-side
1824 /// pre-resolved cleanup-decision cache the predicate could
1825 /// route through the same `bool` return contract) would have
1826 /// had to be threaded through every open-coded per-arm-union
1827 /// pattern-match in lockstep or one gate would silently
1828 /// classify the new arm outside the cleanup family while the
1829 /// peer gates classified it in (or vice versa) — a
1830 /// classification split across the three within-entry cross-
1831 /// instruction gates at build time that lands far from the
1832 /// source [`UpgradeInstruction`] declaration with no field
1833 /// naming which gate carries the drifted arm-set. Lifting the
1834 /// resolution to a typed predicate on the substrate primitive
1835 /// means every downstream cleanup-facing consumer of the
1836 /// [`UpgradeInstruction`] closed-set enum reaches for exactly
1837 /// one typed dispatch — the resolver's arm-set migrates as a
1838 /// unit on any future arm addition composing under this
1839 /// predicate's `||` chain.
1840 ///
1841 /// Sibling in shape to the peer [`gen_platform::IsVariant`]-
1842 /// derive-generated [`Self::is_restart`] terminal-fallback
1843 /// arm-discriminator predicate on the same closed-set
1844 /// [`UpgradeInstruction`] enum (each names an OTP-appup arm-
1845 /// family partition as one typed dispatch on the substrate
1846 /// primitive; `is_restart` on the single-arm terminal-
1847 /// fallback family, `is_cleanup` on the two-arm cleanup
1848 /// family), extended here from the single-arm case onto the
1849 /// two-arm arm-family union case. Composes through the
1850 /// [`gen_platform::IsVariant`]-derive-generated
1851 /// [`Self::is_soft_purge`] / [`Self::is_purge`] per-variant
1852 /// predicates rather than an open-coded raw `matches!`
1853 /// pattern-match, so a future rebrand on either underlying
1854 /// per-arm classifier flows through this predicate's one
1855 /// body without a coordinated per-consumer rewrite across
1856 /// the three within-entry cross-instruction gates that route
1857 /// through it. Peer of the sibling per-`:contratos`
1858 /// shape-family union predicates [`crate::WitContract::is_http`] /
1859 /// [`crate::WitContract::is_pubsub`] / [`crate::WitContract::is_store`]
1860 /// on the M3 mesh-slot per-`:wit` world-ref axis (each unions a
1861 /// per-shape WIT-prefix rule the substrate primitive's arm-
1862 /// family partition names as one typed dispatch) — the same
1863 /// "one typed dispatch on the substrate primitive, thin
1864 /// projections at each consumer" discipline extended onto the
1865 /// M2 `:upgrade-from :instructions` per-`UpgradeInstruction`
1866 /// cleanup-family axis.
1867 ///
1868 /// The name `is_cleanup` maps directly onto the canonical
1869 /// OTP-appup vocabulary (INSPIRATIONS §II.4 verbatim: "2.
1870 /// `code:soft_purge/1` — wait until no process is running v1,
1871 /// then discard. (`code:purge/1` kills v1 immediately if you
1872 /// don't care.)" — the two `code:*_purge/1` operations are
1873 /// the two-phase-load contract's cleanup half, paired under
1874 /// one concept), and the peer [`Self::validate_cleanup_singularity`]
1875 /// / [`UpgradeError::DuplicateCleanup`] / [`UpgradeError::PurgeWithoutPriorLoad`]
1876 /// / [`UpgradeError::StateChangeAfterCleanup`] surface already
1877 /// reaches for the same "cleanup" vocabulary in identifier +
1878 /// diagnostic form.
1879 #[must_use]
1880 pub const fn is_cleanup(&self) -> bool {
1881 self.is_soft_purge() || self.is_purge()
1882 }
1883}
1884
1885/// Reject upgrade instruction `:module` values that aren't K8s
1886/// DNS-1123 labels. Thin wrapper around
1887/// [`crate::render::is_dns_1123_label`] that maps the shared
1888/// parser-shaped reason into the kind-tagged
1889/// [`UpgradeError::ModuleEmpty`] / [`UpgradeError::ModuleInvalid`]
1890/// diagnostics, so the author can grep their caixa.lisp for the
1891/// offending `(:<kind> <module>)` form and fix it in one edit.
1892///
1893/// The contract — the same DNS-1123 label rule the K8s apiserver
1894/// enforces on every `metadata.name` / Service name / label value the
1895/// module name lands in. Each upgrade instruction's `:module` is a
1896/// reference to a caixa name (the wasm-engine resolves it through the
1897/// same `ComputeUnit` registry the operator manages), so the value must
1898/// match every downstream apiserver-side schema: the per-Servico
1899/// `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name` the operator
1900/// creates, the `LABEL_PROGRAM` label value the wasm-engine matches
1901/// against the loaded-module table at hot-upgrade dispatch, and the
1902/// future `:upgrade-from`-driven `app-operator` rolling-load CR's
1903/// per-module reference axis. Same trajectory as `:children :caixa`
1904/// (31bfa43), `:membros :caixa` (3f9d7a0), and `:placement :clusters`
1905/// (6cbb900) onto the fourth DNS-1123-label-shaped identifier axis —
1906/// appup's `LoadModule | SoftPurge | Purge` `:module` references.
1907///
1908/// Empty input is rejected via the narrower [`UpgradeError::ModuleEmpty`]
1909/// variant before this predicate is consulted, mirroring
1910/// `validate_membro_caixa`'s empty-first cascade.
1911fn validate_module(kind: &'static str, module: &str) -> Result<(), UpgradeError> {
1912 // Routes through the shared
1913 // [`crate::render::require_valid_dns_1123_label`] gate the peer
1914 // name axes each land on. The `kind: &'static str` field flows
1915 // through both error variants so the diagnostic names which
1916 // per-instruction slot (`LoadModule` / `SoftPurge` / `Purge`) the
1917 // offending value came from.
1918 crate::render::require_valid_dns_1123_label(
1919 module,
1920 || UpgradeError::ModuleEmpty { kind },
1921 |reason| UpgradeError::ModuleInvalid {
1922 kind,
1923 module: module.to_string(),
1924 reason,
1925 },
1926 )
1927}
1928
1929#[derive(Debug, Error, PartialEq, Eq)]
1930pub enum UpgradeError {
1931 #[error(
1932 ":upgrade-from :from {from:?} is not a valid SemVer-2 version: {reason} (the substrate \
1933 consumes this string as `semver::Version` — three-part `MAJOR.MINOR.PATCH` with optional \
1934 `-prerelease` and `+build`, the same shape every top-level `:versao` carries — across \
1935 every artifact derived from `:from`: the wasm-operator's `:from`-match dispatch loads \
1936 the running version through `semver::Version::parse` and matches it against each entry's \
1937 `:from`, so a malformed `:from` is structurally unreachable at dispatch time; use a \
1938 SemVer-2 literal like `\"0.1.0\"`, `\"0.2.0-rc.1\"`, or `\"1.0.0+build.42\"` — not a \
1939 git-tag-shape like `\"v0.1.0\"`, a docker-tag-shape like `\"latest\"`, a \
1940 requirement-shape like `\"^0.1\"`, or a four-part `\"0.1.0.0\"`)"
1941 )]
1942 FromInvalid { from: String, reason: String },
1943 #[error(
1944 "upgrade instruction `{kind}` :module is empty (every appup module reference \
1945 must name a caixa; use a non-empty caixa name like `\"hello-rio\"` or omit \
1946 the instruction entirely)"
1947 )]
1948 ModuleEmpty { kind: &'static str },
1949 #[error(
1950 "upgrade instruction `{kind}` :module {module:?} is not a valid DNS-1123 label: \
1951 {reason} (every appup module reference resolves to a caixa name, which lands \
1952 verbatim as a K8s `metadata.name` on the per-Servico ComputeUnit the operator \
1953 creates, the `LABEL_PROGRAM` label value the wasm-engine matches at hot-upgrade \
1954 dispatch, and every future `app-operator` rolling-load CR's per-module reference \
1955 axis; use a lowercase alphanumeric + hyphen identifier like `\"hello-rio\"` or \
1956 `\"cache-v2\"`)"
1957 )]
1958 ModuleInvalid {
1959 kind: &'static str,
1960 module: String,
1961 reason: String,
1962 },
1963 #[error("instruction's :script is empty")]
1964 EmptyScript,
1965 #[error(
1966 "instruction's :script {} is absolute — upgrade scripts must be relative to the caixa \
1967 root (Path::join would otherwise escape the project sandbox)",
1968 script.display()
1969 )]
1970 AbsoluteScript { script: PathBuf },
1971 #[error(
1972 "instruction's :script {} contains a `..` component — upgrade scripts must not traverse \
1973 above the caixa root",
1974 script.display()
1975 )]
1976 ParentEscapeScript { script: PathBuf },
1977 #[error(
1978 ":upgrade-from (:state-change {}) does not terminate in the `.lisp` extension — the M2.5 \
1979 wasm-engine instantiator reads every migration script as tatara-lisp source through \
1980 `tatara_lisp::read` at hot-upgrade migration time (the same downstream consumer the \
1981 peer `:behavior :on-*` axis routes through at instance-start time, c97815a), so any \
1982 other extension (`.txt`, `.rs`, `.lisp.bak`) or no-extension shape is structurally a \
1983 parser error far from the source caixa.lisp, with no field naming the offending \
1984 `(:state-change …)` instruction. Pin a relative path under the caixa root whose \
1985 terminating extension is lowercase-`.lisp` (e.g. `\"lib/migrations.lisp\"`, \
1986 `\"lib/migrations/v01-to-v02.lisp\"`).",
1987 script.display()
1988 )]
1989 NonLispExtensionScript { script: PathBuf },
1990 #[error(
1991 ":upgrade-from carries more than one `(:from {from:?})` entry — OTP appup picks at most \
1992 one matching block per running version (`release_handler:install_release/1` dispatches \
1993 on the loaded `:from` against the currently-running release), so two entries with the \
1994 same parsed semver are an ambiguous edge in the typed upgrade graph (the operator would \
1995 pick either set non-deterministically). Author one path per prior version; if two \
1996 distinct instruction sequences are needed, fold them into one ordered list under the \
1997 single matching `(:from {from:?} :instructions (…))` block."
1998 )]
1999 DuplicateFrom { from: String },
2000 #[error(
2001 ":upgrade-from `(:from {from:?})` is not strictly less than the caixa's current \
2002 `:versao {versao:?}` under SemVer-2 precedence — an upgrade block whose `:from` is \
2003 greater than or equal to the caixa's own version is structurally unreachable \
2004 (the wasm-operator's `:from`-match dispatch loads the current `:versao` and matches \
2005 the running version against each entry's `:from`; an entry whose `:from >= :versao` \
2006 is never reached because the operator never runs a version greater than or equal to \
2007 the current one that it could then upgrade *to* the current one). Bump the caixa's \
2008 `:versao` past {from:?} (the typical fix — you added the entry intending to upgrade \
2009 *to* a new version but forgot to bump `:versao`), drop the entry (if it's a stale \
2010 reference left over from a reverted `:versao` bump), or correct `:from` to a prior \
2011 version (if it's a typo). Pre-release values like `\"0.2.0-rc.1\"` are strictly less \
2012 than the corresponding release `\"0.2.0\"` under SemVer §11 precedence; build-metadata \
2013 values like `\"0.2.0+build.1\"` are equal to `\"0.2.0\"` under precedence and rejected \
2014 here as a self-upgrade no-op."
2015 )]
2016 FromNotBeforeVersao { from: String, versao: String },
2017 #[error(
2018 ":upgrade-from `(:from {from:?})` :instructions list violates the `(:restart)` \
2019 exclusivity invariant — an entry containing `(:restart)` must contain exactly one \
2020 `(:restart)` and nothing else (found {restart_count} `(:restart)` plus other \
2021 instruction(s): {other_kinds:?}). Per the UpgradeInstruction::Restart doc comment, \
2022 `(:restart)` is the fallback for an entry whose typed upgrade is impossible (wasm \
2023 component-model world incompatibility, irreversible state shape change), and the \
2024 fallback is terminal by construction (the operator restarts the pod and the new \
2025 version comes up fresh). Mixing the fallback with the typed sequence is dead code \
2026 in both directions: if the typed instructions would succeed, `(:restart)` is \
2027 unreached; if they wouldn't, the typed instructions are dead because the operator \
2028 restarts anyway. Author *either* a typed sequence (`(:load-module …) \
2029 (:state-change …) (:soft-purge …)`) *or* a single `((:restart))` — never both, \
2030 never repeated. If two distinct upgrade strategies are needed for the same prior \
2031 version, that is itself a typed-graph ambiguity (the operator's `:from`-match \
2032 dispatch picks exactly one block per running version) — keep the typed sequence; \
2033 the fallback restart is what the operator does on any typed-sequence failure \
2034 already."
2035 )]
2036 RestartNotExclusive {
2037 from: String,
2038 restart_count: usize,
2039 other_kinds: Vec<&'static str>,
2040 },
2041 #[error(
2042 ":upgrade-from `(:from {from:?})` runs `(:state-change {})` before any \
2043 `(:load-module …)` in its :instructions list — a state migration is the \
2044 gen_server:code_change/3 analog and must run in the context of the newly-loaded \
2045 code, but the operator executes instructions in declared order, so this migration \
2046 runs while the only resident version is still the prior one (which expects the \
2047 pre-migration state shape). Load the new module first: author the canonical \
2048 `(:load-module …) (:state-change {}) (:soft-purge …)` order so the new code is \
2049 resident before its state migration runs.",
2050 script.display(),
2051 script.display()
2052 )]
2053 StateChangeWithoutPriorLoad { from: String, script: PathBuf },
2054 #[error(
2055 ":upgrade-from `(:from {from:?})` runs `({kind} {module:?})` before any \
2056 `(:load-module …)` in its :instructions list — `:soft-purge` and `:purge` are the \
2057 code:soft_purge/1 / code:purge/1 analogs and must run after the new code is \
2058 resident alongside the old (OTP's two-phase code load: `code:load_module/1` \
2059 then `code:soft_purge/1`), but the operator executes instructions in declared \
2060 order, so this cleanup runs while the only resident version is still the same \
2061 old code (`:soft-purge` drains it to nothing; `:purge` discards it outright \
2062 mid-request), leaving no replacement to route in-flight or future requests \
2063 to. Load the new module first: author the canonical `(:load-module …) \
2064 (:state-change …) ({kind} {module:?})` order so the new code is resident \
2065 before the old code is drained or discarded."
2066 )]
2067 PurgeWithoutPriorLoad {
2068 from: String,
2069 kind: &'static str,
2070 module: String,
2071 },
2072 #[error(
2073 ":upgrade-from `(:from {from:?})` :instructions list targets module {module:?} with \
2074 more than one cleanup instruction ({kinds:?}) — `:soft-purge` and `:purge` are the \
2075 code:soft_purge/1 / code:purge/1 analogs (INSPIRATIONS §II.4: \"`code:soft_purge/1` — \
2076 wait until no process is running v1, then discard. (`code:purge/1` kills v1 immediately \
2077 if you don't care.)\"), and each module's old version is cleaned up by exactly one of \
2078 them: either drain-then-discard (`:soft-purge`) or immediate-discard (`:purge`), never \
2079 both, never repeated. systools-generated `.relup` files emit at most one purge per \
2080 module for this reason. A second cleanup on the same module is at best redundant (the \
2081 module is already gone after the first cleanup, so the second is a no-op or undefined \
2082 depending on the operator's handling of a non-resident-module purge request) and at \
2083 worst incoherent (mixing drain and discard semantics on one module suggests the author \
2084 wanted a fallback, but the operator runs declared instructions unconditionally — \
2085 fallback on cleanup failure is the operator's job, not authored into the entry). \
2086 Author one cleanup per module: prefer `(:soft-purge {module:?})` (waits for in-flight \
2087 callers to drain before GC); fall back to `(:purge {module:?})` only when the drain \
2088 can't complete (cron / oneShot / stuck callers). If two distinct old versions need \
2089 cleanup, name them distinctly (e.g. `(:soft-purge {module:?}) (:soft-purge \"…-older\")`)."
2090 )]
2091 DuplicateCleanup {
2092 from: String,
2093 module: String,
2094 kinds: Vec<&'static str>,
2095 },
2096 #[error(
2097 ":upgrade-from `(:from {from:?})` :instructions list loads module {module:?} more than \
2098 once — `:load-module` is the code:load_module/1 analog (INSPIRATIONS §II.4: \"1. \
2099 `code:load_module/1` — load v2 alongside v1; new code is 'current', old code is \
2100 'old'.\"), and the instruction binds the named wasm component once: the operator's \
2101 dispatch table reads the module name and brings up the corresponding component \
2102 alongside the running version. systools-generated `.relup` files emit at most one \
2103 `load_module` per module per upgrade step for this reason. A second `(:load-module \
2104 {module:?})` instruction has no observable semantic relative to the first (the \
2105 component is already resident) — either dead code (copy-pasted load line) or a typo \
2106 masking a distinct module the author intended to load alongside (renamed both to \
2107 {module:?} by mistake), leaving the second module silently absent from the entry. \
2108 Author one `(:load-module {module:?})` per old module per entry; if two distinct old \
2109 versions need loading alongside the running one, name them distinctly (e.g. \
2110 `(:load-module {module:?}) (:load-module \"…-v2\")`)."
2111 )]
2112 DuplicateLoadModule { from: String, module: String },
2113 #[error(
2114 ":upgrade-from `(:from {from:?})` :instructions list runs state migration {} more than \
2115 once — `:state-change` is the gen_server:code_change/3 analog (INSPIRATIONS §II.4: \
2116 \"State migration uses gen_server:code_change/3\"), and the script folds the prior-version \
2117 state shape into the current-version shape: a one-shot transition, not a step that \
2118 composes with itself. systools-generated `.relup` files emit at most one `code_change` \
2119 per gen_server per upgrade step for this reason; OTP's release_handler invokes the \
2120 callback exactly once. A second `(:state-change {})` instruction re-runs the same fold on \
2121 the already-migrated state — at best a no-op (idempotent script masking a typo where the \
2122 author intended two distinct migration scripts) and at worst silent state corruption \
2123 (non-idempotent fold double-applied: an `add column` that runs twice, an `increment \
2124 counter` that double-bumps, a `rename field` that renames-then-fails the second time). \
2125 Author one `(:state-change {})` per migration script per entry; if two distinct state \
2126 transitions are needed (e.g. one module's schema *and* another module's projection), \
2127 name them distinctly (e.g. `(:state-change {}) (:state-change \"lib/migrations/v01-to-v02-projection.lisp\")`).",
2128 script.display(),
2129 script.display(),
2130 script.display(),
2131 script.display()
2132 )]
2133 DuplicateStateChange { from: String, script: PathBuf },
2134 #[error(
2135 ":upgrade-from `(:from {from:?})` runs `(:state-change {})` after `({prior_cleanup_kind} \
2136 {prior_cleanup_module:?})` in its :instructions list — `:state-change` is the \
2137 gen_server:code_change/3 analog and folds the prior-version state shape into the \
2138 current shape, but the prior version's state only exists while the prior code is \
2139 still resident; `:soft-purge` and `:purge` are the code:soft_purge/1 / code:purge/1 \
2140 analogs and drain or discard that prior code. The operator executes instructions in \
2141 declared order, so a cleanup ahead of a state-change has already drained the prior \
2142 module to nothing (`:soft-purge`) or discarded it mid-request (`:purge`) by the time \
2143 the migration script runs, leaving the script either no-op (no prior-version state \
2144 left to fold) or crashing (`code_change/3` invoked on an unloaded version). The OTP \
2145 canonical sequence is `code:load_module/1` → `gen_server:code_change/3` → \
2146 `code:soft_purge/1`; the appup cookbook's recommended pattern is `[{{load_module, m}}, \
2147 {{update, m, soft}}, {{soft_purge, m}}]` with the migration-triggering `update` \
2148 strictly between load and cleanup. Author the canonical `(:load-module …) \
2149 (:state-change {}) ({prior_cleanup_kind} {prior_cleanup_module:?})` order so the \
2150 migration runs against the prior-version state before the cleanup drains it.",
2151 script.display(),
2152 script.display()
2153 )]
2154 StateChangeAfterCleanup {
2155 from: String,
2156 script: PathBuf,
2157 prior_cleanup_kind: &'static str,
2158 prior_cleanup_module: String,
2159 },
2160 #[error(
2161 ":upgrade-from `(:from {from:?})` declares `(:state-change {})` but the caixa does not \
2162 declare `:behavior :on-state-change` — the per-version migration script is the \
2163 gen_server:code_change/3 analog and the runtime hook it is delivered through during \
2164 hot upgrade is the `:on-state-change` callback. OTP's release_handler:install_release/1 \
2165 realizes the composition by invoking the running gen_server's code_change/3 callback \
2166 during the appup's `code_change` / `update, m, soft` step; caixa decomposes the same \
2167 composition into two typed slots, the per-version migration logic in this \
2168 `(:state-change …)` instruction's `:script` and the runtime dispatch hook in the \
2169 `:behavior :on-state-change` callback (the upgrade.rs module doc pins the composition \
2170 verbatim: \"Composes with the `:behavior :on-state-change` callback to deliver state \
2171 migration during hot upgrades\"). The missing callback leaves the per-version script \
2172 with no runtime delivery path: the operator's hot-upgrade dispatch reaches for the \
2173 callback at the migration step, finds it absent, and either fails the upgrade \
2174 mid-flight (the transactional rollback the module doc names — \"On any failure, the \
2175 current version stays load-bearing\") or silently skips the migration leaving the \
2176 new code running against unmigrated prior-version state. Add the callback: \
2177 `(:behavior ((:on-state-change \"lib/migrations.lisp\") …))` (the runtime delivery \
2178 path) alongside the existing `(:state-change {})` instruction (the per-version \
2179 script). If the upgrade truly carries no state migration, drop the `(:state-change \
2180 …)` instruction from the entry (a metadata-only upgrade — load + cleanup, no \
2181 migration — is the canonical shape).",
2182 script.display(),
2183 script.display()
2184 )]
2185 StateChangeWithoutOnStateChangeCallback { from: String, script: PathBuf },
2186}
2187
2188// Fold the three `UpgradeError::{StateChangeWithoutPriorLoad,
2189// DuplicateStateChange, StateChangeWithoutOnStateChangeCallback}
2190// { from: <prior-versao>.to_string(), script: <script>.to_path_buf() }`
2191// two-slot struct-variant wire-up sites at
2192// [`UpgradeFromEntry::validate_state_change_ordering`] (`self.prior_versao()`
2193// / `script` from `instr.declared_path()`),
2194// [`UpgradeFromEntry::validate_state_change_uniqueness`]
2195// (`self.prior_versao()` / `script.as_path()` from
2196// `instr.declared_path()`), and
2197// [`validate_state_change_on_state_change_callback`] (`entry.prior_versao()`
2198// / `script` from `instr.declared_path()`) onto one substrate primitive
2199// per typed variant — the paired `{ from: String, script: PathBuf }`
2200// two-slot sibling on [`UpgradeError`] of the peer
2201// [`crate::supervisor::supervisor_caixa_only_ctors!`] (db09650, 3
2202// variants on `{ caixa: String }`) on the sibling `SupervisorError`
2203// envelope, the peer [`crate::aplicacao::contrato_empty_pair_ctors!`]
2204// (8580068, 4 variants on `{ de, para }`),
2205// [`crate::aplicacao::contrato_target_ctors!`] (14b81d5, 2 variants on
2206// `{ de, para, wit, expected }`),
2207// [`crate::aplicacao::aplicacao_field_reason_ctors!`] (981060b, 7
2208// variants on `{ <field>: String, reason: String }`), and
2209// [`crate::aplicacao::contrato_pair_value_reason_ctors!`] (14e13f1, 3
2210// variants on `{ de, para, <field>: String, reason: String }`) on the
2211// sibling `AplicacaoError` envelopes, and the peer
2212// [`crate::layout::layout_violation_ctors!`] (131ca0d, 16 variants on
2213// `{ caixa, issue }`), [`crate::layout::layout_slot_kind_ctors!`]
2214// (0419438, 4 variants on `{ caixa, kind, slots }`),
2215// [`crate::LayoutError::missing_entry`] (1b09f9d, one variant on
2216// `{ kind, path }`), and [`crate::layout::layout_nome_only_ctors!`]
2217// (3fe3dd7, 6 variants on `<Variant>(String)`) on the sibling
2218// `LayoutError` envelopes, plus the peer
2219// [`crate::limits::limits_codec_value_only_ctors!`] /
2220// [`crate::limits::limits_codec_value_byte_ctors!`] /
2221// [`crate::limits::limits_codec_value_char_ctors!`] (81c856c, 12 codec
2222// wire-ups) on the sibling `LimitsError` envelopes.
2223//
2224// Each of the three wire-up sites on this shape opens the identical
2225// `UpgradeError::<Variant> { from: <prior-versao>.to_string(),
2226// script: <script>.to_path_buf() }` struct-literal against a local
2227// `prior_versao()` and `declared_path()` accessor pair — the exact
2228// "same block re-inlined at every consumer" shape the PRIME DIRECTIVE
2229// names as a bug, on the same altitude the peer `SupervisorError` /
2230// `AplicacaoError` / `LayoutError` / `LimitsError` families each
2231// closed on their sibling envelopes. The three variants share one
2232// `{ from: String, script: PathBuf }` shape, so the fold routes each
2233// wire-up site through one dispatch per typed variant.
2234//
2235// The macro below generates one `#[must_use]` inherent constructor per
2236// variant of shape `fn <ctor>(from: &str, script: &std::path::Path) ->
2237// Self`, so every wire-up site collapses onto one dispatch:
2238// `UpgradeError::<ctor>(<prior-versao>, <script>)`, byte-equal to the
2239// pre-lift struct-literal on the same `(&str, &Path)` fixture. The
2240// uniform two-field construction (`from.to_string()` /
2241// `script.to_path_buf()`) is spelled once — inside the macro — rather
2242// than at every wire-up site. The `&Path` parameter accepts both
2243// `&Path` (from `script.as_path()` at the uniqueness gate) and
2244// `&PathBuf` (from `instr.declared_path()` at the ordering /
2245// callback-declaration gates, via Deref coercion), so every existing
2246// wire-up threads through the ctor without a pre-conversion.
2247//
2248// Every future consumer that wants to construct one of these three
2249// variants outside the three in-crate `UpgradeFromEntry` /
2250// `validate_state_change_on_state_change_callback` gates (a deferred
2251// wasm-operator's `install_release/1` per-entry ordering / uniqueness
2252// re-checker at hot-upgrade dispatch time, a future
2253// `feira validate --upgrade-from` per-caixa admission verb re-checking
2254// the three axes, a per-`Caixa` overlay resolver rejecting an
2255// ordering / uniqueness / callback-declaration invariant against a
2256// cluster-local snapshot) now reaches each variant through one call
2257// rather than re-inlining the three-line struct-literal in lockstep
2258// with the three in-crate wire-up sites.
2259macro_rules! upgrade_from_script_ctors {
2260 ($($ctor:ident => $variant:ident),* $(,)?) => {
2261 impl UpgradeError {
2262 $(
2263 #[doc = concat!(
2264 "Construct an [`UpgradeError::",
2265 stringify!($variant),
2266 "`] naming the offending `(:from <prior-versao>)` and ",
2267 "`(:state-change <script>)` pair. Folds the uniform ",
2268 "`Self::",
2269 stringify!($variant),
2270 " { from: from.to_string(), script: script.to_path_buf() }` ",
2271 "two-field struct-literal onto one substrate primitive so ",
2272 "every wire-up on this variant reads through one dispatch ",
2273 "rather than the pre-lift three-line open-coded block. The ",
2274 "`from` string threads verbatim from ",
2275 "[`UpgradeFromEntry::prior_versao`] and the `script` path ",
2276 "from [`UpgradeInstruction::declared_path`] at the call site."
2277 )]
2278 #[must_use]
2279 pub fn $ctor(from: &str, script: &std::path::Path) -> Self {
2280 Self::$variant {
2281 from: from.to_string(),
2282 script: script.to_path_buf(),
2283 }
2284 }
2285 )*
2286 }
2287 };
2288}
2289
2290upgrade_from_script_ctors! {
2291 state_change_without_prior_load => StateChangeWithoutPriorLoad,
2292 duplicate_state_change => DuplicateStateChange,
2293 state_change_without_on_state_change_callback => StateChangeWithoutOnStateChangeCallback,
2294}
2295
2296// Fold the three `UpgradeError::{AbsoluteScript, ParentEscapeScript,
2297// NonLispExtensionScript} { script: <script>.clone() }` single-slot
2298// struct-variant wire-up sites at [`UpgradeInstruction::validate`]'s
2299// three closures passed to [`crate::render::require_sandboxed_lisp_path`]
2300// onto one substrate primitive per typed variant — the paired
2301// `{ script: PathBuf }` single-slot sibling on [`UpgradeError`] of the
2302// sibling [`upgrade_from_script_ctors!`] (8e67041, 3 variants on
2303// `{ from: String, script: PathBuf }`) two-slot family on the same
2304// envelope, and of the peer
2305// [`crate::supervisor::supervisor_caixa_only_ctors!`] (db09650, 3
2306// variants on `{ caixa: String }`) and
2307// [`crate::dep::dep_nome_only_ctors!`] (792aa92, 5 variants on
2308// `{ nome: String }`) single-slot families on the sibling
2309// `SupervisorError` / `DepError` envelopes, and of the peer
2310// [`crate::aplicacao::contrato_empty_pair_ctors!`] (8580068, 4 variants
2311// on `{ de, para }`), [`crate::aplicacao::contrato_target_ctors!`]
2312// (14b81d5, 2 variants on `{ de, para, wit, expected }`),
2313// [`crate::aplicacao::aplicacao_field_reason_ctors!`] (981060b, 7
2314// variants on `{ <field>: String, reason: String }`), and
2315// [`crate::aplicacao::contrato_pair_value_reason_ctors!`] (14e13f1, 3
2316// variants on `{ de, para, <field>: String, reason: String }`) on the
2317// sibling `AplicacaoError` envelopes, plus the peer four `LayoutError`
2318// families ([`crate::layout::layout_violation_ctors!`] 131ca0d;
2319// [`crate::layout::layout_slot_kind_ctors!`] 0419438;
2320// [`crate::LayoutError::missing_entry`] 1b09f9d;
2321// [`crate::layout::layout_nome_only_ctors!`] 3fe3dd7), the three
2322// `LimitsError` codec families (81c856c), and the sibling
2323// [`crate::dep::fonte_caminho_ctors!`] (f85f145, 11 variants on
2324// `{ nome, caminho }`) two-slot family.
2325//
2326// The three wire-up sites this fold closes are the three closures
2327// (`|| UpgradeError::AbsoluteScript { script: script.clone() }`,
2328// `|| UpgradeError::ParentEscapeScript { script: script.clone() }`,
2329// `|| UpgradeError::NonLispExtensionScript { script: script.clone() }`)
2330// passed to [`crate::render::require_sandboxed_lisp_path`] at
2331// [`UpgradeInstruction::validate`] — each opens the identical
2332// `UpgradeError::<Variant> { script: script.clone() }` three-line
2333// struct-literal against the same `script: &PathBuf` local threaded
2334// from [`UpgradeInstruction::declared_path`], the exact "same block
2335// re-inlined at every consumer" shape the PRIME DIRECTIVE names as a
2336// bug. The three variants share one `{ script: PathBuf }` shape, so
2337// the fold routes each closure through one dispatch per typed variant.
2338// The sibling `EmptyScript` unit-variant on the same envelope stays on
2339// its pre-lift open-coded shape — it carries no `script` field (the
2340// offending `:script` value *is* the empty path this variant catches),
2341// so the uniform `fn(script: &Path) -> Self` signature this macro
2342// promises does not apply, and the peer helper's `|| Self::EmptyScript`
2343// closure is already a one-liner. This is the second fold family on
2344// the `UpgradeError` envelope (sibling of the [`upgrade_from_script_ctors!`]
2345// two-slot family established in 8e67041, which explicitly named this
2346// `{ script: PathBuf }` single-slot family as the next fold to land
2347// on the envelope; per that commit's coverage roster, both of the two
2348// most-populated shapes on `UpgradeError` — the two-slot
2349// `{ from, script }` and the one-slot `{ script }` — are now closed.)
2350//
2351// The macro below generates one `#[must_use]` inherent constructor per
2352// variant of shape `fn <ctor>(script: &std::path::Path) -> Self`, so
2353// every closure collapses onto one dispatch:
2354// `UpgradeError::<ctor>(script)`, byte-equal to the pre-lift
2355// struct-literal on the same `&Path` fixture. The uniform one-field
2356// construction (`script.to_path_buf()`) is spelled once — inside the
2357// macro — rather than at every wire-up site. The `&Path` parameter
2358// accepts both `&Path` (direct `Path::new(…)`) and `&PathBuf` (from
2359// `instr.declared_path()` at the three closures, via Deref coercion),
2360// so every existing closure threads through the ctor without a
2361// pre-conversion.
2362//
2363// Every future consumer that wants to construct one of these three
2364// variants outside the three in-crate closures (a deferred
2365// wasm-operator's `install_release/1` per-instruction script-shape
2366// re-checker at hot-upgrade dispatch time, a future
2367// `feira validate --upgrade-from` per-caixa admission verb re-checking
2368// the same script-shape axis, a per-`Caixa` overlay resolver rejecting
2369// an author-supplied `:state-change :script` against a cluster-local
2370// snapshot) now reaches each variant through one call rather than
2371// re-inlining the three-line struct-literal in lockstep with the three
2372// in-crate closure sites.
2373macro_rules! upgrade_script_only_ctors {
2374 ($($ctor:ident => $variant:ident),* $(,)?) => {
2375 impl UpgradeError {
2376 $(
2377 #[doc = concat!(
2378 "Construct an [`UpgradeError::",
2379 stringify!($variant),
2380 "`] naming the offending `(:state-change <script>)`. ",
2381 "Folds the uniform `Self::",
2382 stringify!($variant),
2383 " { script: script.to_path_buf() }` one-field ",
2384 "struct-literal onto one substrate primitive so every ",
2385 "closure passed to ",
2386 "[`crate::render::require_sandboxed_lisp_path`] at ",
2387 "[`UpgradeInstruction::validate`] on this variant reads ",
2388 "through one dispatch rather than the pre-lift three-line ",
2389 "open-coded block. The `script` path threads verbatim ",
2390 "from [`UpgradeInstruction::declared_path`] at the call ",
2391 "site."
2392 )]
2393 #[must_use]
2394 pub fn $ctor(script: &std::path::Path) -> Self {
2395 Self::$variant {
2396 script: script.to_path_buf(),
2397 }
2398 }
2399 )*
2400 }
2401 };
2402}
2403
2404upgrade_script_only_ctors! {
2405 absolute_script => AbsoluteScript,
2406 parent_escape_script => ParentEscapeScript,
2407 non_lisp_extension_script => NonLispExtensionScript,
2408}
2409
2410// Fold the three `UpgradeError::{FromInvalid, FromNotBeforeVersao,
2411// DuplicateLoadModule} { from: <from>.to_string(), <axis>:
2412// <value>.to_string() }` two-slot struct-variant wire-up sites at
2413// [`UpgradeFromEntry::validate`]'s per-`:from` SemVer-2 parse gate
2414// (`Version::parse(self.prior_versao()).map_err(|e| … FromInvalid
2415// { from: self.prior_versao().to_string(), reason: e.to_string() })`),
2416// [`UpgradeFromEntry::validate_load_singularity`]'s per-module
2417// dedup gate (`return Err(UpgradeError::DuplicateLoadModule { from:
2418// self.prior_versao().to_string(), module: module.to_string() });`),
2419// and [`validate_upgrade_from_against_versao`]'s per-`:from >= :versao`
2420// self-upgrade gate (`return Err(UpgradeError::FromNotBeforeVersao
2421// { from: entry.prior_versao().to_string(), versao: versao.to_string()
2422// });`) onto one substrate-primitive family per typed variant — the
2423// missing paired two-slot rung on the `UpgradeError`-side four-family
2424// ladder ([`upgrade_script_only_ctors!`] (7468ca9) one-slot
2425// `{ script: PathBuf }` → this two-slot `{ from: String, <axis>: String }`
2426// → [`upgrade_from_script_ctors!`] (8e67041) two-slot `{ from: String,
2427// script: PathBuf }`), and mirror-symmetric sibling of the peer
2428// [`crate::dep::dep_nome_axis_ctors!`] (7f7c950) two-slot `{ nome:
2429// String, <axis>: String }` fold on the `DepError` envelope — same
2430// `<axis>: <value>.to_string()` owned-forward payload shape, `nome`
2431// axis renamed `from` at the per-`:upgrade-from :from`-owned altitude
2432// the `UpgradeError` envelope keys off (every `UpgradeError` variant
2433// carries the offending prior-version `:from` verbatim so the author
2434// can grep their caixa.lisp for the offending `(:from "<value>")` /
2435// `(:load-module …)` / `:versao` block in one edit). The three
2436// variants share the same `{ from: String, <axis>: String }` two-slot
2437// shape: the `from` field names the offending per-`:upgrade-from` block's
2438// prior-version tag the diagnostic points the author back at, and the
2439// middle `<axis>: String` field carries the offending per-envelope axis
2440// value verbatim (`reason` on `FromInvalid` carries the wrapped
2441// `semver::Version::parse` error message that pinpoints why the tag
2442// failed SemVer-2; `versao` on `FromNotBeforeVersao` carries the caixa's
2443// own current-`:versao` the entry's `:from` failed to precede; `module`
2444// on `DuplicateLoadModule` carries the caixa name the second
2445// `(:load-module …)` instruction re-loaded within the same entry).
2446// The middle axis-field name differs across variants (`reason` /
2447// `versao` / `module`) so the ctor family below takes the axis field
2448// name as a macro parameter (`$axis:ident`) alongside the ctor +
2449// variant names, generating one `pub fn $ctor(from: &str, $axis: &str)
2450// -> Self` inherent constructor per typed variant that spells the
2451// uniform two-field construction (`from.to_string()` /
2452// `<axis>.to_string()`) exactly once.
2453//
2454// Peer of the sibling [`upgrade_from_script_ctors!`] (8e67041, 3
2455// variants on `{ from: String, script: PathBuf }`) two-slot family on
2456// the same envelope — both key off the same `from: String` axis at the
2457// same per-`:upgrade-from :from`-owned altitude; this family carries the
2458// owned-`String` second axis (per-`reason` / per-`versao` / per-`module`
2459// carrier) where the script-slot family carries the owned-`PathBuf`
2460// second axis. Peer also of the sibling [`upgrade_script_only_ctors!`]
2461// (7468ca9, 3 variants on `{ script: PathBuf }`) one-slot family on the
2462// same envelope, of the sibling
2463// [`crate::supervisor::supervisor_caixa_only_ctors!`] (db09650, 3
2464// variants on `{ caixa: String }`) and
2465// [`crate::dep::dep_nome_only_ctors!`] (792aa92, 5 variants on
2466// `{ nome: String }`) single-slot families on the sibling
2467// `SupervisorError` / `DepError` envelopes, and of the peer
2468// [`crate::aplicacao::contrato_empty_pair_ctors!`] (8580068, 4 variants
2469// on `{ de, para }`), [`crate::aplicacao::contrato_target_ctors!`]
2470// (14b81d5, 2 variants on `{ de, para, wit, expected }`),
2471// [`crate::aplicacao::aplicacao_field_reason_ctors!`] (981060b, 7
2472// variants on `{ <field>: String, reason: String }`),
2473// [`crate::aplicacao::aplicacao_caixa_only_ctors!`] (d9f6867, 5
2474// variants on `{ caixa: String }`),
2475// [`crate::aplicacao::aplicacao_path_only_ctors!`] (3ba8de6, 3 variants
2476// on `{ path: String }`), and
2477// [`crate::aplicacao::contrato_pair_value_reason_ctors!`] (14e13f1, 3
2478// variants on `{ de, para, <field>: String, reason: String }`) on the
2479// sibling `AplicacaoError` envelopes, plus the peer four `LayoutError`
2480// families ([`crate::layout::layout_violation_ctors!`] 131ca0d;
2481// [`crate::layout::layout_slot_kind_ctors!`] 0419438;
2482// [`crate::LayoutError::missing_entry`] 1b09f9d;
2483// [`crate::layout::layout_nome_only_ctors!`] 3fe3dd7), the three
2484// `LimitsError` codec families (81c856c), the sibling
2485// [`crate::dep::fonte_caminho_ctors!`] (f85f145, 11 variants on
2486// `{ nome, caminho }`), [`crate::dep::fonte_caminho_byte_ctors!`]
2487// (0e35793, 12 variants on `{ nome, caminho, byte }`),
2488// [`crate::dep::dep_nome_list_ctors!`] (6f5e0cd, 4 variants on
2489// `{ nome, list: &'static str }`), and
2490// [`crate::dep::dep_nome_axis_reason_ctors!`] (5621f8a, 3 variants on
2491// `{ nome, <axis>: String, reason: String }`) families.
2492//
2493// Each of the three wire-up sites on this shape opens the identical
2494// `UpgradeError::<Variant> { from: <from>.to_string(), <axis>:
2495// <value>.to_string() }` four-line struct-literal against a local
2496// `(prior_versao(), <axis-value>)` pair threaded from
2497// [`UpgradeFromEntry::prior_versao`] (or, at the
2498// [`validate_upgrade_from_against_versao`] site, directly from the
2499// caller-supplied `versao: &str` argument) — the exact "same block
2500// re-inlined at every consumer" shape the PRIME DIRECTIVE names as a
2501// bug, on the same altitude the peer sibling `upgrade_from_script_ctors!`
2502// / `upgrade_script_only_ctors!` families closed on the sibling
2503// `{ from, script }` / `{ script }` shape-envelopes. The three variant /
2504// axis-field discriminators are the only things that vary between them;
2505// the rest of the struct-literal is a byte-for-byte re-inline.
2506//
2507// The macro below generates one `#[must_use]` inherent constructor per
2508// variant of shape `fn <ctor>(from: &str, <axis>: &str) -> Self`, so
2509// every wire-up site collapses onto one dispatch:
2510// `UpgradeError::<ctor>(<from>, <axis-value>)`, byte-equal to the
2511// pre-lift struct-literal on the same `(&str, &str)` fixture. Both
2512// parameters accept `&str` literals and `&String` (via Deref coercion)
2513// so every existing wire-up threads through the ctor without a
2514// pre-conversion.
2515//
2516// Every future consumer that wants to construct one of these three
2517// variants outside the three in-crate `UpgradeFromEntry::validate` /
2518// `validate_load_singularity` / `validate_upgrade_from_against_versao`
2519// gates (a deferred wasm-operator's `install_release/1` per-entry
2520// `:from`-parse / per-`:load-module` singularity / per-entry
2521// `:from < :versao` re-checker at hot-upgrade dispatch time, a future
2522// `feira validate --upgrade-from` per-caixa admission verb re-checking
2523// the three axes, a per-`Caixa` overlay resolver rejecting a
2524// `:from`-shape / `:load-module`-singularity / `:from < :versao`
2525// invariant against a cluster-local snapshot) now reaches each variant
2526// through one call rather than re-inlining the four-line struct-literal
2527// in lockstep with the three in-crate wire-up sites.
2528macro_rules! upgrade_from_axis_ctors {
2529 ($($ctor:ident => $variant:ident { $axis:ident }),* $(,)?) => {
2530 impl UpgradeError {
2531 $(
2532 #[doc = concat!(
2533 "Construct an [`UpgradeError::",
2534 stringify!($variant),
2535 "`] naming the offending `(:from <prior-versao>)` and ",
2536 "the offending `:", stringify!($axis), "` axis value. ",
2537 "Folds the uniform `Self::",
2538 stringify!($variant),
2539 " { from: from.to_string(), ",
2540 stringify!($axis),
2541 ": ",
2542 stringify!($axis),
2543 ".to_string() }` two-field struct-literal onto one ",
2544 "substrate primitive so every in-crate wire-up on ",
2545 "this variant reads through one dispatch rather than ",
2546 "the pre-lift four-line open-coded block. Both `from: ",
2547 "&str` and `",
2548 stringify!($axis),
2549 ": &str` parameters accept `&str` literals and ",
2550 "`&String` (via Deref coercion) so every existing ",
2551 "wire-up threads through the ctor without a pre-",
2552 "conversion."
2553 )]
2554 #[must_use]
2555 pub fn $ctor(from: &str, $axis: &str) -> Self {
2556 Self::$variant {
2557 from: from.to_string(),
2558 $axis: $axis.to_string(),
2559 }
2560 }
2561 )*
2562 }
2563 };
2564}
2565
2566upgrade_from_axis_ctors! {
2567 from_invalid => FromInvalid { reason },
2568 from_not_before_versao => FromNotBeforeVersao { versao },
2569 duplicate_load_module => DuplicateLoadModule { module },
2570}
2571
2572// Fold the last open-coded `UpgradeError::DuplicateFrom { from:
2573// entry.prior_versao().to_string() }` one-slot struct-literal inside
2574// [`validate_upgrade_from`]'s cross-entry `:from`-duplicate gate onto
2575// one substrate primitive on the [`UpgradeError`] envelope, projecting
2576// through the paired [`UpgradeFromEntry::prior_versao`] scalar accessor
2577// on the substrate primitive. The `DuplicateFrom` variant is the last
2578// unlifted single-slot `{ from: String }` envelope on `UpgradeError` —
2579// every peer envelope shape (`{ script: PathBuf }` one-slot via
2580// [`upgrade_script_only_ctors!`] 7468ca9; `{ from: String, <axis>:
2581// String }` two-slot via [`upgrade_from_axis_ctors!`] 41d08db; `{ from:
2582// String, script: PathBuf }` two-slot via [`upgrade_from_script_ctors!`]
2583// 8e67041) already reads through one substrate-primitive dispatch, so
2584// this fold closes the last one-off single-slot on the envelope.
2585//
2586// Peer of the sibling standalone-ctor `AplicacaoError::contrato_self_loop`
2587// (b30edfe) on the paired [`WitContract`] projection — same
2588// `pub fn <ctor>(primitive: &<Primitive>) -> Self` shape, projecting
2589// through the substrate primitive's own scalar accessor rather than
2590// re-inlining the `.to_string()` at the call site. Extended here onto
2591// the sibling [`UpgradeFromEntry`] scalar-accessor family the closed
2592// M2 companion of the M3 mesh-slot accessors (see
2593// [`UpgradeFromEntry::prior_versao`] doc — sibling in shape to
2594// [`crate::Membro::versao_requirement`] a40b0e3, [`crate::Membro::nome`]
2595// 4a32abf, and the [`crate::WitContract::{source, destination,
2596// world_ref}`] 7f0fd43 / 0804823 / [`crate::Entrada::{hostname,
2597// destination}`] 11f3dfe / 6db982c `&str` accessors) established.
2598//
2599// The one wire-up site this fold closes opens the identical
2600// `UpgradeError::DuplicateFrom { from: entry.prior_versao().to_string() }`
2601// three-line struct-literal against the `entry: &UpgradeFromEntry` local
2602// threaded from [`validate_upgrade_from`]'s per-entry loop — the exact
2603// "same block re-inlined at every consumer" shape the PRIME DIRECTIVE
2604// names as a bug, on the same altitude the peer `contrato_self_loop`
2605// closed on the sibling `{ caixa: String, wit: String }` two-slot
2606// envelope inside `impl AplicacaoSpec`. The `entry: &UpgradeFromEntry`
2607// parameter accepts the borrowed entry verbatim so the wire-up site
2608// threads through the ctor without a pre-projection — the ctor body
2609// spells the paired `prior_versao().to_string()` projection once.
2610//
2611// Every future consumer that wants to construct this variant outside
2612// `validate_upgrade_from`'s cross-entry duplicate gate — a deferred
2613// wasm-operator's `install_release/1` cross-entry `:from`-duplicate
2614// re-checker at hot-upgrade dispatch time rejecting a second entry
2615// with the same prior-versao tag, a future `feira validate --upgrade-
2616// from` per-caixa admission verb re-running the cross-entry duplicate
2617// pass on demand, a per-`Caixa` overlay resolver rejecting an author-
2618// supplied duplicate `(:from "<value>")` against a cluster-local
2619// snapshot — now reaches the variant through one call rather than
2620// re-inlining the three-line struct-literal in lockstep with the one
2621// in-crate wire-up site.
2622impl UpgradeError {
2623 /// Construct an [`UpgradeError::DuplicateFrom`] naming the offending
2624 /// duplicate `(:from <prior-versao>)` entry, projecting through the
2625 /// paired [`UpgradeFromEntry::prior_versao`] scalar accessor on the
2626 /// substrate primitive. Folds the uniform `Self::DuplicateFrom {
2627 /// from: entry.prior_versao().to_string() }` one-field struct-literal
2628 /// onto one substrate primitive so every wire-up on this variant
2629 /// reads through one dispatch, matching the sibling
2630 /// [`crate::AplicacaoError::contrato_self_loop`] (b30edfe)
2631 /// substrate-primitive-projection ctor's shape on the peer
2632 /// [`AplicacaoError`] envelope. The `entry: &UpgradeFromEntry`
2633 /// parameter accepts the borrowed entry verbatim so the paired
2634 /// `prior_versao().to_string()` projection is spelled once — inside
2635 /// the ctor body — rather than at every wire-up site.
2636 #[must_use]
2637 pub fn duplicate_from(entry: &UpgradeFromEntry) -> Self {
2638 Self::DuplicateFrom {
2639 from: entry.prior_versao().to_string(),
2640 }
2641 }
2642
2643 /// Construct an [`UpgradeError::PurgeWithoutPriorLoad`] naming the
2644 /// offending `(:from <prior-versao>)` entry, the offending cleanup
2645 /// instruction's `:kind` lisp-form (`:soft-purge` / `:purge`), and
2646 /// its `:module` target. Folds the uniform
2647 /// `Self::PurgeWithoutPriorLoad { from: from.to_string(), kind,
2648 /// module: module.to_string() }` three-field struct-literal onto one
2649 /// substrate primitive so every wire-up on this sole-variant
2650 /// cleanup-family load-before-cleanup ordering-refusal envelope reads
2651 /// through one dispatch rather than the pre-lift seven-line
2652 /// open-coded block.
2653 ///
2654 /// The `from: &str` parameter accepts `&str` literals and `&String`
2655 /// via Deref coercion so the sole in-crate wire-up site threads
2656 /// [`UpgradeFromEntry::prior_versao`] verbatim without a
2657 /// pre-conversion. The `kind: &'static str` parameter accepts the
2658 /// lisp-form `&'static str` [`UpgradeInstruction::lisp_form`]
2659 /// returns for the two [`UpgradeInstruction::is_cleanup`] arms —
2660 /// `M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE` /
2661 /// `M2_UPGRADE_INSTRUCTION_KIND_PURGE` — verbatim without a per-arm
2662 /// re-projection at the ctor path. The `module: &str` parameter
2663 /// takes the `&str` [`UpgradeInstruction::declared_module`] returns
2664 /// via `.expect("is_cleanup() implies declared_module() is Some")`
2665 /// at the caller — the `is_cleanup`-implies-`declared_module`-is-
2666 /// `Some` composition pin at
2667 /// [`tests::upgrade_instruction_is_cleanup_implies_declared_module_is_some`]
2668 /// makes the `.expect(…)` structurally infallible at build time.
2669 ///
2670 /// Peer of the sibling one-off standalone-ctor
2671 /// [`UpgradeError::duplicate_from`] on the paired one-slot `{ from:
2672 /// String }` envelope on the same `UpgradeError` envelope, and of
2673 /// the sibling `AplicacaoError::contrato_endpoint_not_absolute`
2674 /// (cdf1a2c) three-slot `{ de, para, endpoint: String }` sole-
2675 /// variant standalone ctor on the peer `AplicacaoError` envelope.
2676 /// Closes the last unlifted `{ from: String, kind: &'static str,
2677 /// module: String }` three-slot open-coded struct-literal wire-up
2678 /// on the OTP-appup load-before-cleanup ordering axis, sibling of
2679 /// the peer sub-family generated by [`upgrade_from_axis_ctors!`]
2680 /// (41d08db, three variants on `{ from: String, <axis>: String }`)
2681 /// on the paired ordering / uniqueness / callback-declaration axes,
2682 /// and of the peer standalone [`UpgradeError::duplicate_from`]
2683 /// (7e52aec) one-slot ctor on the sibling cross-entry duplicate-
2684 /// `:from` gate. Every future consumer that raises this refusal
2685 /// outside `UpgradeFromEntry::validate_purge_ordering` — a deferred
2686 /// wasm-operator's `install_release/1` per-entry load-before-cleanup
2687 /// re-checker at hot-upgrade dispatch time, a future
2688 /// `feira validate --upgrade-from` per-caixa admission verb
2689 /// re-running the load-before-cleanup gate on demand, a per-`Caixa`
2690 /// overlay resolver rejecting a cluster-local `:soft-purge` /
2691 /// `:purge` overlay lacking a preceding `:load-module` — reaches
2692 /// the variant through one call rather than re-inlining the
2693 /// seven-line struct-literal in lockstep with the sole in-crate
2694 /// wire-up site.
2695 #[must_use]
2696 pub fn purge_without_prior_load(from: &str, kind: &'static str, module: &str) -> Self {
2697 Self::PurgeWithoutPriorLoad {
2698 from: from.to_string(),
2699 kind,
2700 module: module.to_string(),
2701 }
2702 }
2703
2704 /// Construct an [`UpgradeError::StateChangeAfterCleanup`] naming the
2705 /// offending `(:from <prior-versao>)` entry, the offending
2706 /// `(:state-change …)` `:script` path, and the prior cleanup
2707 /// instruction's `:kind` lisp-form (`:soft-purge` / `:purge`) +
2708 /// `:module` target. Folds the uniform
2709 /// `Self::StateChangeAfterCleanup { from: from.to_string(), script:
2710 /// script.to_path_buf(), prior_cleanup_kind, prior_cleanup_module:
2711 /// prior_cleanup_module.to_string() }` four-field struct-literal
2712 /// onto one substrate primitive so every wire-up on this sole-
2713 /// variant migrate-after-cleanup ordering-refusal envelope reads
2714 /// through one dispatch rather than the pre-lift seven-line open-
2715 /// coded block. Closes the last unlifted `{ from: String, script:
2716 /// PathBuf, prior_cleanup_kind: &'static str, prior_cleanup_module:
2717 /// String }` four-slot open-coded struct-literal wire-up on the
2718 /// OTP-appup migrate-before-cleanup ordering axis, filling the
2719 /// missing four-slot rung on the `UpgradeError`-side ctor-family
2720 /// ladder alongside the sibling one-slot
2721 /// [`UpgradeError::duplicate_from`] (7e52aec) and three-slot
2722 /// [`UpgradeError::purge_without_prior_load`] (9752da1) standalone
2723 /// ctors, the two-slot [`upgrade_from_axis_ctors!`] (41d08db) /
2724 /// [`upgrade_from_script_ctors!`] (8e67041) macro-generated
2725 /// families, and the one-slot [`upgrade_script_only_ctors!`]
2726 /// (7468ca9) family. Sole in-crate wire-up site is inside
2727 /// [`UpgradeFromEntry::validate_state_change_before_cleanup`]'s
2728 /// migrate-family sticky-latch dispatch — the third of three
2729 /// within-entry cross-instruction OTP-appup ordering gates the
2730 /// module doc pins (`validate_state_change_ordering` on the load →
2731 /// migrate boundary via [`upgrade_from_script_ctors!`]-generated
2732 /// `state_change_without_prior_load`; `validate_purge_ordering` on
2733 /// the load → cleanup boundary via `purge_without_prior_load`;
2734 /// `validate_state_change_before_cleanup` on the migrate → cleanup
2735 /// boundary via this ctor — now).
2736 ///
2737 /// The `from: &str` parameter accepts `&str` literals and `&String`
2738 /// via Deref coercion so the sole in-crate wire-up site threads
2739 /// [`UpgradeFromEntry::prior_versao`] (a `&str` accessor) verbatim
2740 /// without a pre-conversion. The `script: &std::path::Path`
2741 /// parameter accepts `&Path` (direct `Path::new(…)`) and `&PathBuf`
2742 /// (from [`UpgradeInstruction::declared_path`]'s `Option<&PathBuf>`
2743 /// via Deref coercion) so the wire-up threads the sticky-latch
2744 /// script projection through the ctor without a pre-conversion; the
2745 /// uniform `script.to_path_buf()` one-field construction is spelled
2746 /// once — inside the ctor body — rather than at every wire-up site.
2747 /// The `prior_cleanup_kind: &'static str` parameter accepts the
2748 /// lisp-form `&'static str` [`UpgradeInstruction::lisp_form`]
2749 /// returns for the two [`UpgradeInstruction::is_cleanup`] arms —
2750 /// `M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE` /
2751 /// `M2_UPGRADE_INSTRUCTION_KIND_PURGE` — verbatim without a per-arm
2752 /// re-projection at the ctor path. The `prior_cleanup_module: &str`
2753 /// parameter takes the `&str` [`UpgradeInstruction::declared_module`]
2754 /// returns via `.expect("is_cleanup() implies declared_module() is
2755 /// Some")` at the caller — the `is_cleanup`-implies-`declared_module`-
2756 /// is-`Some` composition pin at
2757 /// [`tests::upgrade_instruction_is_cleanup_implies_declared_module_is_some`]
2758 /// makes the `.expect(…)` structurally infallible at build time.
2759 ///
2760 /// Every future consumer that raises this refusal outside
2761 /// [`UpgradeFromEntry::validate_state_change_before_cleanup`] — a
2762 /// deferred wasm-operator's `install_release/1` per-entry
2763 /// migrate-before-cleanup re-checker at hot-upgrade dispatch time,
2764 /// a future `feira validate --upgrade-from` per-caixa admission verb
2765 /// re-running the migrate-before-cleanup gate on demand, a
2766 /// per-`Caixa` overlay resolver rejecting a cluster-local
2767 /// `:state-change` overlay authored after a `:soft-purge` /
2768 /// `:purge`, the M4 `mesh.pleme.io/v1alpha1/Caixa` CR admission
2769 /// webhook re-checking a per-`:upgrade-from`-patched candidate
2770 /// before the migrate-before-cleanup gate re-fires — reaches the
2771 /// variant through one call rather than re-inlining the seven-line
2772 /// struct-literal in lockstep with the sole in-crate wire-up site.
2773 #[must_use]
2774 pub fn state_change_after_cleanup(
2775 from: &str,
2776 script: &std::path::Path,
2777 prior_cleanup_kind: &'static str,
2778 prior_cleanup_module: &str,
2779 ) -> Self {
2780 Self::StateChangeAfterCleanup {
2781 from: from.to_string(),
2782 script: script.to_path_buf(),
2783 prior_cleanup_kind,
2784 prior_cleanup_module: prior_cleanup_module.to_string(),
2785 }
2786 }
2787
2788 /// Construct an [`UpgradeError::DuplicateCleanup`] naming the
2789 /// offending `(:from <prior-versao>)` entry, the colliding `:module`
2790 /// target, and the ordered pair of colliding cleanup `:kind` lisp-
2791 /// forms (`:soft-purge` / `:purge`). Folds the uniform
2792 /// `Self::DuplicateCleanup { from: from.to_string(), module:
2793 /// module.to_string(), kinds }` three-field struct-literal onto one
2794 /// substrate primitive so every wire-up on this sole-variant within-
2795 /// entry per-module cleanup-singularity refusal envelope reads
2796 /// through one dispatch rather than the pre-lift five-line open-coded
2797 /// block. Closes the last unlifted `{ from: String, module: String,
2798 /// kinds: Vec<&'static str> }` three-slot open-coded struct-literal
2799 /// wire-up on the OTP-appup per-module cleanup-singularity axis,
2800 /// filling a peer three-slot rung on the `UpgradeError`-side ctor-
2801 /// family ladder alongside the sibling three-slot
2802 /// [`UpgradeError::purge_without_prior_load`] (9752da1) standalone
2803 /// ctor on the paired within-entry load → cleanup ordering axis, the
2804 /// one-slot [`UpgradeError::duplicate_from`] (7e52aec) standalone
2805 /// ctor on the sibling cross-entry duplicate-`:from` gate, the four-
2806 /// slot [`UpgradeError::state_change_after_cleanup`] (be68237)
2807 /// standalone ctor on the migrate → cleanup boundary, the two-slot
2808 /// [`upgrade_from_axis_ctors!`] (41d08db) /
2809 /// [`upgrade_from_script_ctors!`] (8e67041) macro-generated families,
2810 /// and the one-slot [`upgrade_script_only_ctors!`] (7468ca9) family.
2811 /// Sole in-crate wire-up site is inside
2812 /// [`UpgradeFromEntry::validate_cleanup_singularity`]'s per-module
2813 /// cleanup-family dedup arm.
2814 ///
2815 /// The `from: &str` parameter accepts `&str` literals and `&String`
2816 /// via Deref coercion so the sole in-crate wire-up threads
2817 /// [`UpgradeFromEntry::prior_versao`] (a `&str` accessor) verbatim
2818 /// without a pre-conversion. The `module: &str` parameter takes the
2819 /// `&str` [`UpgradeInstruction::declared_module`] returns via
2820 /// `.expect("is_cleanup() implies declared_module() is Some")` at the
2821 /// caller — the `is_cleanup`-implies-`declared_module`-is-`Some`
2822 /// composition pin at
2823 /// [`tests::upgrade_instruction_is_cleanup_implies_declared_module_is_some`]
2824 /// makes the `.expect(…)` structurally infallible at build time. The
2825 /// `kinds: Vec<&'static str>` parameter takes the ordered pair
2826 /// `vec![prior_kind, kind]` built at the caller from the two
2827 /// [`UpgradeInstruction::lisp_form`] `&'static str` returns
2828 /// (`M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE` /
2829 /// `M2_UPGRADE_INSTRUCTION_KIND_PURGE`) — the same substrate-
2830 /// primitive `&'static str` projection the paired three-slot
2831 /// [`UpgradeError::purge_without_prior_load`] ctor threads on the
2832 /// sibling load → cleanup ordering axis.
2833 ///
2834 /// Every future consumer that raises this refusal outside
2835 /// [`UpgradeFromEntry::validate_cleanup_singularity`] — a deferred
2836 /// wasm-operator's `install_release/1` per-entry per-module
2837 /// cleanup-singularity re-checker at hot-upgrade dispatch time, a
2838 /// future `feira validate --upgrade-from` per-caixa admission verb
2839 /// re-running the singularity pass on demand, a per-`Caixa` overlay
2840 /// resolver rejecting a cluster-local `:soft-purge` / `:purge`
2841 /// overlay that collides with a base-entry cleanup on the same
2842 /// module, the M4 `mesh.pleme.io/v1alpha1/Caixa` CR admission webhook
2843 /// re-checking a per-`:upgrade-from`-patched candidate before the
2844 /// singularity gate re-fires — reaches the variant through one call
2845 /// rather than re-inlining the five-line struct-literal in lockstep
2846 /// with the sole in-crate wire-up site.
2847 #[must_use]
2848 pub fn duplicate_cleanup(from: &str, module: &str, kinds: Vec<&'static str>) -> Self {
2849 Self::DuplicateCleanup {
2850 from: from.to_string(),
2851 module: module.to_string(),
2852 kinds,
2853 }
2854 }
2855
2856 /// Construct an [`UpgradeError::RestartNotExclusive`] naming the
2857 /// offending `(:from <prior-versao>)` entry, the observed `(:restart)`
2858 /// instruction count, and the ordered list of non-`:restart`
2859 /// instruction lisp-forms the entry mixed with the terminal fallback.
2860 /// Folds the uniform `Self::RestartNotExclusive { from: from.to_string(),
2861 /// restart_count, other_kinds }` three-field struct-literal onto one
2862 /// substrate primitive so every wire-up on this sole-variant within-
2863 /// entry `(:restart)`-exclusivity refusal envelope reads through one
2864 /// dispatch rather than the pre-lift five-line open-coded block. Closes
2865 /// the last unlifted `{ from: String, restart_count: usize, other_kinds:
2866 /// Vec<&'static str> }` three-slot open-coded struct-literal wire-up on
2867 /// the OTP-appup within-entry `(:restart)`-fallback-exclusivity axis —
2868 /// the last-remaining open-coded emission site the sibling
2869 /// [`UpgradeError::duplicate_cleanup`] (10a5b48) commit body pinned as
2870 /// the natural next lift on the `UpgradeError` envelope. Fills a peer
2871 /// three-slot rung on the `UpgradeError`-side ctor-family ladder
2872 /// alongside the sibling three-slot
2873 /// [`UpgradeError::purge_without_prior_load`] (9752da1) standalone
2874 /// ctor on the paired within-entry load → cleanup ordering axis and
2875 /// [`UpgradeError::duplicate_cleanup`] (10a5b48) standalone ctor on
2876 /// the per-module cleanup-singularity axis, the one-slot
2877 /// [`UpgradeError::duplicate_from`] (7e52aec) standalone ctor on the
2878 /// cross-entry duplicate-`:from` gate, the four-slot
2879 /// [`UpgradeError::state_change_after_cleanup`] (be68237) standalone
2880 /// ctor on the migrate → cleanup boundary, the two-slot
2881 /// [`upgrade_from_axis_ctors!`] (41d08db) /
2882 /// [`upgrade_from_script_ctors!`] (8e67041) macro-generated families,
2883 /// and the one-slot [`upgrade_script_only_ctors!`] (7468ca9) family.
2884 /// Sole in-crate wire-up site is inside
2885 /// [`UpgradeFromEntry::validate_restart_exclusive`]'s mixed-`(:restart)`
2886 /// arm.
2887 ///
2888 /// The `from: &str` parameter accepts `&str` literals and `&String`
2889 /// via Deref coercion so the sole in-crate wire-up threads
2890 /// [`UpgradeFromEntry::prior_versao`] (a `&str` accessor) verbatim
2891 /// without a pre-conversion. The `restart_count: usize` parameter
2892 /// takes the observed `(:restart)` occurrence count built at the
2893 /// caller from `instructions.iter().filter(|i| i.is_restart()).count()`
2894 /// — the same `IsVariant`-derived arm-discriminator dispatch the
2895 /// paired `other_kinds` projection routes through — so the diagnostic
2896 /// surfaces the duplication mode unambiguously even when `other_kinds`
2897 /// is empty (the `((:restart) (:restart))` shape the sibling
2898 /// `validate_rejects_restart_duplicated` test pins with
2899 /// `restart_count: 2, other_kinds: vec![]`). The `other_kinds:
2900 /// Vec<&'static str>` parameter takes the ordered list of non-
2901 /// `:restart` instruction lisp-forms built at the caller from
2902 /// `instructions.iter().filter(|i| !i.is_restart()).map(
2903 /// UpgradeInstruction::lisp_form).collect()` — the same substrate-
2904 /// primitive `&'static str` projection the peer three-slot
2905 /// [`UpgradeError::purge_without_prior_load`] /
2906 /// [`UpgradeError::duplicate_cleanup`] ctors thread on the sibling
2907 /// within-entry cleanup axes.
2908 ///
2909 /// Every future consumer that raises this refusal outside
2910 /// [`UpgradeFromEntry::validate_restart_exclusive`] — a deferred
2911 /// wasm-operator's `install_release/1` per-entry `(:restart)`-
2912 /// exclusivity re-checker at hot-upgrade dispatch time, a future
2913 /// `feira validate --upgrade-from` per-caixa admission verb re-running
2914 /// the exclusivity pass on demand, a per-`Caixa` overlay resolver
2915 /// rejecting a cluster-local `(:restart)` overlay that mixes with a
2916 /// base-entry typed sequence, the M4 `mesh.pleme.io/v1alpha1/Caixa`
2917 /// CR admission webhook re-checking a per-`:upgrade-from`-patched
2918 /// candidate before the exclusivity gate re-fires — reaches the
2919 /// variant through one call rather than re-inlining the five-line
2920 /// struct-literal in lockstep with the sole in-crate wire-up site.
2921 #[must_use]
2922 pub fn restart_not_exclusive(
2923 from: &str,
2924 restart_count: usize,
2925 other_kinds: Vec<&'static str>,
2926 ) -> Self {
2927 Self::RestartNotExclusive {
2928 from: from.to_string(),
2929 restart_count,
2930 other_kinds,
2931 }
2932 }
2933}
2934
2935#[cfg(test)]
2936mod tests {
2937 use std::path::Path;
2938
2939 use super::*;
2940
2941 fn entry(from: &str, instrs: Vec<UpgradeInstruction>) -> UpgradeFromEntry {
2942 UpgradeFromEntry {
2943 from: from.into(),
2944 instructions: instrs,
2945 }
2946 }
2947
2948 #[test]
2949 fn upgrade_from_entry_prior_versao_accessor_is_const_fn() {
2950 // Fail-before-pass-after pin on
2951 // [`UpgradeFromEntry::prior_versao`]'s `const`-eval-surface
2952 // posture. The accessor projects the per-`:upgrade-from :from`
2953 // [`String`] storage through the `pub const fn`
2954 // [`String::as_str`] (const-stable since Rust 1.87, well within
2955 // the workspace MSRV) — any future accidental downgrade to
2956 // non-`const` fails `prior_versao_via_const_fn` at caixa-core
2957 // build time with E0015 (`cannot call non-const method`),
2958 // strictly stronger than a runtime `assert!`. Sibling of the
2959 // peer M2/M3 slot family pins on the sibling `const`-eval-
2960 // surface passes ([`crate::Caixa::nome`] /
2961 // [`crate::Caixa::versao`], [`crate::CaixaVersion::as_str`],
2962 // [`crate::aplicacao::Membro::nome`] /
2963 // [`crate::aplicacao::Membro::versao_requirement`],
2964 // [`crate::aplicacao::Entrada::hostname`] /
2965 // [`crate::aplicacao::Entrada::destination`],
2966 // [`crate::supervisor::ChildSpec::nome`] /
2967 // [`crate::supervisor::ChildSpec::versao_requirement`],
2968 // [`crate::dep::Dep::nome`] /
2969 // [`crate::dep::Dep::versao_requirement`], and the
2970 // per-`:contratos`
2971 // [`crate::aplicacao::WitContract::source`] /
2972 // [`crate::aplicacao::WitContract::destination`] /
2973 // [`crate::aplicacao::WitContract::world_ref`] trio the
2974 // sibling pin at 279823b already anchors).
2975 const fn prior_versao_via_const_fn(e: &UpgradeFromEntry) -> &str {
2976 e.prior_versao()
2977 }
2978 for from in ["0.1.0", "1.2.3-alpha.1", "0.0.0"] {
2979 let e = entry(from, vec![]);
2980 assert_eq!(prior_versao_via_const_fn(&e), e.prior_versao());
2981 assert_eq!(e.prior_versao(), from);
2982 }
2983 }
2984
2985 #[test]
2986 fn upgrade_from_entry_instructions_slice_return_accessor_is_const_fn() {
2987 // Fail-before-pass-after pin on
2988 // [`UpgradeFromEntry::instructions`]'s `const`-eval-surface
2989 // posture. The accessor destructures the per-`:upgrade-from
2990 // :instructions` `Vec<UpgradeInstruction>` storage through the
2991 // `pub const fn` [`Vec::as_slice`] (const-stable since Rust
2992 // 1.66, well within the workspace MSRV) — any future
2993 // accidental downgrade to non-`const` fails
2994 // `instructions_via_const_fn` at caixa-core build time with
2995 // E0015 (`cannot call non-const method`), strictly stronger
2996 // than a runtime `assert!`. Sibling of the peer per-M3-mesh-
2997 // slot `Vec → &[T]` slice-return accessor family pin
2998 // [`crate::aplicacao::tests::m3_reference_return_accessor_family_is_const_fn`]
2999 // on the M3 mesh-slot per-`:clusters` / per-`:paths` /
3000 // per-`:membros` / per-`:contratos` slice-return axes, and of
3001 // the peer M2 supervisor-tree axis pin
3002 // [`crate::supervisor::tests::supervisor_children_slice_return_accessor_is_const_fn`]
3003 // on the per-`:children` slice-return axis.
3004 const fn instructions_via_const_fn(e: &UpgradeFromEntry) -> &[UpgradeInstruction] {
3005 e.instructions()
3006 }
3007 // Sweep both the empty-instructions arm (author-declared
3008 // per-`:from` entry with no migration steps — the degenerate
3009 // shape the appup `restart`-only path folds through) and the
3010 // populated-instructions arm (the canonical OTP-appup shape
3011 // carrying a `LoadModule` + `StateChange` + `SoftPurge`
3012 // chain) so the accessor carries a const-dispatch pin on
3013 // both arms.
3014 let e_empty = entry("0.1.0", vec![]);
3015 assert!(instructions_via_const_fn(&e_empty).is_empty());
3016 assert_eq!(instructions_via_const_fn(&e_empty), e_empty.instructions());
3017 let e_full = entry(
3018 "0.1.0",
3019 vec![
3020 UpgradeInstruction::LoadModule {
3021 module: "hello-rio".into(),
3022 },
3023 UpgradeInstruction::StateChange {
3024 script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
3025 },
3026 UpgradeInstruction::SoftPurge {
3027 module: "hello-rio-old".into(),
3028 },
3029 ],
3030 );
3031 assert_eq!(instructions_via_const_fn(&e_full).len(), 3);
3032 assert_eq!(instructions_via_const_fn(&e_full), e_full.instructions());
3033 }
3034
3035 #[test]
3036 fn round_trip_load_module() {
3037 let i = UpgradeInstruction::LoadModule {
3038 module: "hello-rio".into(),
3039 };
3040 let json = serde_json::to_string(&i).unwrap();
3041 assert!(json.contains("\"kind\":\"load-module\""));
3042 let back: UpgradeInstruction = serde_json::from_str(&json).unwrap();
3043 assert_eq!(i, back);
3044 }
3045
3046 #[test]
3047 fn round_trip_all_variants() {
3048 let cases = vec![
3049 UpgradeInstruction::LoadModule { module: "x".into() },
3050 UpgradeInstruction::StateChange {
3051 script: PathBuf::from("lib/migrations.lisp"),
3052 },
3053 UpgradeInstruction::SoftPurge {
3054 module: "x-old".into(),
3055 },
3056 UpgradeInstruction::Purge {
3057 module: "x-old".into(),
3058 },
3059 UpgradeInstruction::Restart,
3060 ];
3061 for c in cases {
3062 let json = serde_json::to_string(&c).unwrap();
3063 let back: UpgradeInstruction = serde_json::from_str(&json).unwrap();
3064 assert_eq!(c, back);
3065 }
3066 }
3067
3068 #[test]
3069 fn validate_accepts_well_formed() {
3070 let e = entry(
3071 "0.1.0",
3072 vec![
3073 UpgradeInstruction::LoadModule {
3074 module: "hello-rio".into(),
3075 },
3076 UpgradeInstruction::StateChange {
3077 script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
3078 },
3079 UpgradeInstruction::SoftPurge {
3080 module: "hello-rio-old".into(),
3081 },
3082 ],
3083 );
3084 e.validate().unwrap();
3085 }
3086
3087 #[test]
3088 fn validate_rejects_non_semver_from() {
3089 let e = entry("not-a-semver", vec![]);
3090 let err = e.validate().unwrap_err();
3091 assert!(
3092 matches!(err, UpgradeError::FromInvalid { ref from, .. } if from == "not-a-semver")
3093 );
3094 }
3095
3096 #[test]
3097 fn from_invalid_diagnostic_carries_offending_from_and_reason() {
3098 // Diagnostic-shape pin: the error names the offending
3099 // `:upgrade-from :from` verbatim with a non-empty parser-shaped
3100 // reason, so a `feira lint` run can render the diagnostic
3101 // without re-parsing — the author can grep their caixa.lisp for
3102 // `:from "<value>"` and fix it in one edit. Mirrors the peer
3103 // `versao_invalid_diagnostic_carries_offending_versao` pin on
3104 // the sibling SemVer-2 axis (the top-level `:versao`), the
3105 // peer `membro_versao_invalid_diagnostic_carries_offending_value`
3106 // pin on `:membros :versao`, and the peer
3107 // `deps_invalid_diagnostic_carries_offending_value` pin on
3108 // `:deps :versao` — every SemVer-2-parsing slot's invalid
3109 // diagnostic is now structurally equivalent.
3110 let e = entry("v0.1.0", vec![]);
3111 let err = e.validate().unwrap_err();
3112 let UpgradeError::FromInvalid { from, reason } = err else {
3113 panic!("expected FromInvalid variant, got {err:?}");
3114 };
3115 assert_eq!(from, "v0.1.0");
3116 assert!(
3117 !reason.is_empty(),
3118 "FromInvalid `reason` must carry the parser's wording verbatim"
3119 );
3120 }
3121
3122 #[test]
3123 fn prior_versao_returns_from_byte_equal_across_permutations() {
3124 // Byte-identity pin on the lifted `UpgradeFromEntry::prior_versao`
3125 // accessor across the SemVer-2 shape lattice every consumer
3126 // reaches through it — the numeric-triad canonical shape, a
3127 // pre-release build with a dotted identifier chain, a full-
3128 // metadata build, a large-magnitude triad, and the empty
3129 // string (which reaches this accessor unchanged before any
3130 // validate gate rejects it). Sibling to the peer
3131 // `membro_versao_requirement_returns_versao_byte_equal_across_permutations`
3132 // (a40b0e3) / `membro_nome_returns_caixa_byte_equal_across_permutations`
3133 // (4a32abf) pins on the sibling M3 mesh-slot scalar-accessor
3134 // family — extended here onto the first M2 slot scalar-value
3135 // axis. Any silent detour on the accessor (a `.to_string()`
3136 // + retained ownership shape, a canonicalization pass, a
3137 // trim-whitespace on the return path) surfaces as a byte-
3138 // inequality failure here rather than as a downstream error-
3139 // diagnostic drift.
3140 let cases = ["0.1.0", "0.2.0-rc.1", "1.0.0+build.42", "10.20.30", ""];
3141 for from in cases {
3142 let e = entry(from, vec![]);
3143 assert_eq!(
3144 e.prior_versao(),
3145 from,
3146 "prior_versao() must return the `:from` field byte-for-byte for {from:?}",
3147 );
3148 assert_eq!(
3149 e.prior_versao().len(),
3150 from.len(),
3151 "prior_versao() byte-length must equal the `:from` field's for {from:?}",
3152 );
3153 }
3154 }
3155
3156 #[test]
3157 fn prior_versao_borrows_from_from_storage() {
3158 // Same-address pin: `UpgradeFromEntry::prior_versao` returns
3159 // a borrow into `self.from`'s heap allocation, never a fresh
3160 // owned copy. Guards against a future silent detour where
3161 // the accessor materializes a `Cow<'_, str>` / `String` /
3162 // `Rc<str>` intermediate — the return path stays zero-cost
3163 // even under a refactor that reshapes the storage. Sibling
3164 // to the peer `membro_versao_requirement_borrows_from_versao_storage`
3165 // (a40b0e3) / `membro_nome_borrows_from_caixa_storage`
3166 // (4a32abf) pins — extended onto the M2 slot's first
3167 // scalar-value axis.
3168 let e = entry("0.1.0", vec![]);
3169 assert!(
3170 std::ptr::eq(e.prior_versao().as_ptr(), e.from.as_ptr()),
3171 "prior_versao() must borrow from `self.from`'s storage, not allocate a fresh copy",
3172 );
3173 }
3174
3175 #[test]
3176 fn validate_parses_prior_versao_through_lifted_accessor() {
3177 // Coherence pin between the accessor and the SemVer-2 parse
3178 // gate: every `:upgrade-from :from` value the validator
3179 // accepts (resp. rejects) must be identical to what
3180 // `Version::parse(entry.prior_versao())` accepts (resp.
3181 // rejects) — the two must remain in lockstep across the
3182 // shape lattice so `validate_upgrade_from`'s
3183 // `Version::parse(entry.prior_versao()).expect(...)` re-parse
3184 // assertion holds by construction. If a future extension of
3185 // `prior_versao` reshapes the return (a canonicalization
3186 // pass, a leading/trailing whitespace trim, an empty-to-
3187 // "0.0.0" fallback) it would either loosen the validator
3188 // (silently accepting shapes the parser rejects) or
3189 // tighten the parser's re-parse (silently panicking on
3190 // shapes the validator accepts) — this pin catches either
3191 // shift at caixa-core build time.
3192 let accepted = ["0.1.0", "0.2.0-rc.1", "1.0.0+build.42", "10.20.30"];
3193 for from in accepted {
3194 let e = entry(from, vec![]);
3195 e.validate().unwrap_or_else(|err| {
3196 panic!("validate() must accept {from:?} that Version::parse accepts, got {err:?}");
3197 });
3198 semver::Version::parse(e.prior_versao()).unwrap_or_else(|err| {
3199 panic!(
3200 "Version::parse(prior_versao()) must accept {from:?} that validate() accepts, \
3201 got {err:?}",
3202 );
3203 });
3204 }
3205 let rejected = ["", "v0.1.0", "0.1", "not-a-semver", "0.1.0.0"];
3206 for from in rejected {
3207 let e = entry(from, vec![]);
3208 assert!(
3209 matches!(e.validate(), Err(UpgradeError::FromInvalid { .. })),
3210 "validate() must reject {from:?} that Version::parse rejects",
3211 );
3212 assert!(
3213 semver::Version::parse(e.prior_versao()).is_err(),
3214 "Version::parse(prior_versao()) must reject {from:?} that validate() rejects",
3215 );
3216 }
3217 }
3218
3219 #[test]
3220 fn validate_rejects_empty_module() {
3221 // Per-arm coverage: every Module-bearing variant surfaces the
3222 // kind-tagged `ModuleEmpty` diagnostic naming its lisp-form,
3223 // so the author can grep their caixa.lisp for `(:load-module
3224 // …)` / `(:soft-purge …)` / `(:purge …)` and fix it in one
3225 // edit — same self-locating shape `BehaviorError::EmptyPath`
3226 // (b0c8389) carries on the peer M2 typed slot.
3227 let cases: &[(UpgradeInstruction, &'static str)] = &[
3228 (
3229 UpgradeInstruction::LoadModule {
3230 module: String::new(),
3231 },
3232 crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE,
3233 ),
3234 (
3235 UpgradeInstruction::SoftPurge {
3236 module: String::new(),
3237 },
3238 crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
3239 ),
3240 (
3241 UpgradeInstruction::Purge {
3242 module: String::new(),
3243 },
3244 crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
3245 ),
3246 ];
3247 for (instr, expected_kind) in cases {
3248 assert_eq!(
3249 instr.validate().unwrap_err(),
3250 UpgradeError::ModuleEmpty {
3251 kind: expected_kind
3252 },
3253 "empty :module on {instr:?} must surface as ModuleEmpty {{ kind: {expected_kind:?} }}"
3254 );
3255 }
3256 }
3257
3258 #[test]
3259 fn validate_rejects_non_dns_1123_module() {
3260 // Every appup `:module` reference is a caixa name (the
3261 // wasm-engine resolves it through the same ComputeUnit
3262 // registry the operator manages), so the value-shape gate
3263 // matches the K8s apiserver-side DNS-1123 label rule. Sweep
3264 // the canonical authoring footguns — uppercase letters, `_`
3265 // separator, embedded `.`, leading/trailing `-`, an embedded
3266 // whitespace byte, the >63-byte UUID-shaped slug — across
3267 // every Module-bearing variant; each must surface as
3268 // `ModuleInvalid { kind, module, reason }` carrying the
3269 // offending value verbatim and the parser-shaped reason.
3270 type Build = fn(String) -> UpgradeInstruction;
3271 let footguns: &[&str] = &[
3272 "Hello-Rio",
3273 "hello_rio",
3274 "hello.rio",
3275 "-hello",
3276 "hello-",
3277 "hello rio",
3278 &"x".repeat(crate::render::DNS_1123_LABEL_MAX_LEN + 1),
3279 ];
3280 let variants: &[(Build, &'static str)] = &[
3281 (
3282 |m| UpgradeInstruction::LoadModule { module: m },
3283 crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE,
3284 ),
3285 (
3286 |m| UpgradeInstruction::SoftPurge { module: m },
3287 crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
3288 ),
3289 (
3290 |m| UpgradeInstruction::Purge { module: m },
3291 crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
3292 ),
3293 ];
3294 for (build, expected_kind) in variants {
3295 for module in footguns {
3296 let instr = build((*module).to_string());
3297 let err = instr.validate().unwrap_err();
3298 match err {
3299 UpgradeError::ModuleInvalid {
3300 kind,
3301 module: m,
3302 reason,
3303 } => {
3304 assert_eq!(
3305 kind, *expected_kind,
3306 ":module footgun on {instr:?} must tag the lisp-form"
3307 );
3308 assert_eq!(
3309 m, *module,
3310 "ModuleInvalid must carry the offending value verbatim"
3311 );
3312 assert!(
3313 !reason.is_empty(),
3314 "ModuleInvalid reason must name the specific violation \
3315 (the predicate's parser-shaped wording from \
3316 `is_dns_1123_label`), got empty"
3317 );
3318 }
3319 other => panic!("expected ModuleInvalid on {instr:?}, got {other:?}"),
3320 }
3321 }
3322 }
3323 }
3324
3325 #[test]
3326 fn validate_accepts_canonical_module_names() {
3327 // Positive control: every documented authoring shape — bare
3328 // identifier, with hyphens, with digits, the
3329 // suffix-versioned alias `<nome>-old` `SoftPurge` typically
3330 // references — passes the gate. Drift here = a future
3331 // tighten that rejects any of these surfaces as a
3332 // test-failure at the predicate boundary, not piecemeal
3333 // across per-instruction call sites.
3334 let canonical: &[&str] = &[
3335 "hello-rio",
3336 "hello-rio-old",
3337 "cache",
3338 "cache-v2",
3339 "x",
3340 "a1",
3341 "0a",
3342 "abc-123-def",
3343 ];
3344 for module in canonical {
3345 UpgradeInstruction::LoadModule {
3346 module: (*module).to_string(),
3347 }
3348 .validate()
3349 .unwrap_or_else(|e| panic!("LoadModule {module:?} must pass, got {e:?}"));
3350 UpgradeInstruction::SoftPurge {
3351 module: (*module).to_string(),
3352 }
3353 .validate()
3354 .unwrap_or_else(|e| panic!("SoftPurge {module:?} must pass, got {e:?}"));
3355 UpgradeInstruction::Purge {
3356 module: (*module).to_string(),
3357 }
3358 .validate()
3359 .unwrap_or_else(|e| panic!("Purge {module:?} must pass, got {e:?}"));
3360 }
3361 }
3362
3363 #[test]
3364 fn validate_empty_takes_precedence_over_invalid() {
3365 // Empty input is rejected via the narrower `ModuleEmpty`
3366 // diagnostic before the DNS-1123 predicate is consulted, so
3367 // a future tighten that adds another stage between the two
3368 // doesn't accidentally reorder the diagnostic precedence.
3369 // Mirrors the empty-first cascade on every peer DNS-1123
3370 // gate (`validate_membro_caixa`, `validate_placement_cluster`,
3371 // `SupervisorSpec::validate`'s child-name arm).
3372 let err = UpgradeInstruction::LoadModule {
3373 module: String::new(),
3374 }
3375 .validate()
3376 .unwrap_err();
3377 assert_eq!(
3378 err,
3379 UpgradeError::ModuleEmpty {
3380 kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE
3381 }
3382 );
3383 }
3384
3385 #[test]
3386 fn validate_rejects_empty_script() {
3387 let i = UpgradeInstruction::StateChange {
3388 script: PathBuf::new(),
3389 };
3390 assert_eq!(i.validate().unwrap_err(), UpgradeError::EmptyScript);
3391 }
3392
3393 #[test]
3394 fn validate_rejects_absolute_script() {
3395 let i = UpgradeInstruction::StateChange {
3396 script: PathBuf::from("/etc/migrations.lisp"),
3397 };
3398 assert!(matches!(
3399 i.validate().unwrap_err(),
3400 UpgradeError::AbsoluteScript { .. }
3401 ));
3402 }
3403
3404 #[test]
3405 fn validate_rejects_parent_escape_script() {
3406 let i = UpgradeInstruction::StateChange {
3407 script: PathBuf::from("../sibling/migrations.lisp"),
3408 };
3409 assert!(matches!(
3410 i.validate().unwrap_err(),
3411 UpgradeError::ParentEscapeScript { .. }
3412 ));
3413 // mid-path `..` is also caught
3414 let i2 = UpgradeInstruction::StateChange {
3415 script: PathBuf::from("lib/../../escaped.lisp"),
3416 };
3417 assert!(matches!(
3418 i2.validate().unwrap_err(),
3419 UpgradeError::ParentEscapeScript { .. }
3420 ));
3421 }
3422
3423 // ── :upgrade-from :state-change :script `.lisp` extension gate ─
3424 // Mirrors the c97815a `BehaviorError::NonLispExtension` arm on
3425 // the peer `:behavior :on-*` tatara-lisp-source-path axis. Both
3426 // axes route through the same M2.5 wasm-engine `tatara_lisp::read`
3427 // consumer; the file-type contract is identical, so the per-axis
3428 // test grid is mirrored leg-for-leg.
3429
3430 #[test]
3431 fn validate_rejects_no_extension_script() {
3432 // Fail-before-pass-after: the canonical "I declared the
3433 // migration script but forgot the `.lisp` extension"
3434 // authoring footgun (e.g. `(:state-change "lib/migrations")`).
3435 // The wasm-engine's `tatara_lisp::read` consumer needs a
3436 // file-type contract beyond the structural-shape gate; a
3437 // no-extension path past `is_sandboxed_relative_path` would
3438 // surface a parser-shaped diagnostic at hot-upgrade migration
3439 // time far from the source caixa.lisp.
3440 for relpath in ["lib/migrations", "migrations", "lib/handlers/migrate"] {
3441 let i = UpgradeInstruction::StateChange {
3442 script: PathBuf::from(relpath),
3443 };
3444 let err = i.validate().unwrap_err();
3445 assert!(
3446 matches!(&err, UpgradeError::NonLispExtensionScript { script: s }
3447 if s == Path::new(relpath)),
3448 "no-extension script {relpath:?} must surface as NonLispExtensionScript \
3449 carrying the offending path verbatim, got {err:?}"
3450 );
3451 }
3452 }
3453
3454 #[test]
3455 fn validate_rejects_non_lisp_extension_script() {
3456 // Wrong-extension sweep across common authoring footguns: the
3457 // `.txt` / `.md` / `.json` / `.yaml` shapes an author might
3458 // drag in from the workspace tree, the `.rs` shape that an
3459 // IDE auto-complete might propose, the `.lisp.bak` shape an
3460 // editor might leave behind, and the `.lispx` near-miss that
3461 // a typo would produce. Each must surface as
3462 // `NonLispExtensionScript` carrying the offending path
3463 // verbatim — the wasm-engine's `tatara_lisp::read` consumer
3464 // rejects all of these at hot-upgrade migration time, and
3465 // the gate lifts that contract to validate time. Mirrors the
3466 // peer `BehaviorError::NonLispExtension` sweep (c97815a) on
3467 // the `:behavior :on-*` axis leg-for-leg — same downstream
3468 // consumer, same accepted set, same per-axis test grid.
3469 let footguns: &[&str] = &[
3470 "lib/migrations.rs",
3471 "lib/migrations.txt",
3472 "lib/migrations.md",
3473 "lib/migrations.json",
3474 "lib/migrations.yaml",
3475 "lib/migrations.toml",
3476 "lib/migrations.lisp.bak",
3477 "lib/migrations.lispx",
3478 "lib/migrations.lis",
3479 ];
3480 for relpath in footguns {
3481 let i = UpgradeInstruction::StateChange {
3482 script: PathBuf::from(relpath),
3483 };
3484 let err = i.validate().unwrap_err();
3485 assert!(
3486 matches!(&err, UpgradeError::NonLispExtensionScript { script: s }
3487 if s == Path::new(relpath)),
3488 "wrong-extension script {relpath:?} must surface as NonLispExtensionScript \
3489 carrying the offending path verbatim, got {err:?}"
3490 );
3491 }
3492 }
3493
3494 #[test]
3495 fn validate_rejects_uppercase_lisp_extension_script() {
3496 // Strict lowercase: `.LISP` / `.Lisp` / `.LiSp` are
3497 // case-folded shapes a case-insensitive volume's existence
3498 // check would match the on-disk file — but the
3499 // canonical-form codec emits lowercase `.lisp` verbatim, so
3500 // a case-folded shape mismatches the round-trip-stable
3501 // canonical form (THEORY.md §V.2.7 render-determinism).
3502 // Same case-sensitive discipline the byte-size / duration
3503 // codecs use on unit suffixes (`MiB`, `ms`, `s`, `m`, `h`)
3504 // and every other shape-gate predicate in `render.rs` (label
3505 // / scheme / unit boundaries). Mirrors the peer
3506 // `BehaviorError::NonLispExtension` case-fold sweep (c97815a).
3507 for relpath in [
3508 "lib/migrations.LISP",
3509 "lib/migrations.Lisp",
3510 "lib/migrations.LiSp",
3511 "lib/migrations.lISP",
3512 ] {
3513 let i = UpgradeInstruction::StateChange {
3514 script: PathBuf::from(relpath),
3515 };
3516 let err = i.validate().unwrap_err();
3517 assert!(
3518 matches!(&err, UpgradeError::NonLispExtensionScript { script: s }
3519 if s == Path::new(relpath)),
3520 "case-folded `.lisp` extension {relpath:?} must surface as \
3521 NonLispExtensionScript (strict lowercase, canonical-form \
3522 round-trip pin), got {err:?}"
3523 );
3524 }
3525 }
3526
3527 #[test]
3528 fn validate_accepts_canonical_lisp_extension_scripts() {
3529 // Positive-control sweep across every canonical in-tree
3530 // authoring shape: bare filename, standard `lib/`
3531 // subdirectory, deeply-nested migrations subdirectory,
3532 // explicit current-dir-relative prefix, mid-path `./`
3533 // segment, multi-dot stem (the version-suffix shape
3534 // `lib/migrations/v.0.1.lisp` an author might use to encode
3535 // the migration's `:from` version into the filename). Drift
3536 // here = a future tightening that rejects any of these
3537 // surfaces as a test-failure at the per-axis validator
3538 // boundary, not piecemeal across renderer / layout-checker
3539 // call sites. Mirrors the peer `BehaviorSpec` positive-set
3540 // sweep (c97815a).
3541 let canonical: &[&str] = &[
3542 "lib/migrations.lisp",
3543 "lib/migrations/v01-to-v02.lisp",
3544 "migrations.lisp",
3545 "a.lisp",
3546 "./lib/migrations.lisp",
3547 "lib/./migrations.lisp",
3548 "lib/migrations/v.0.1.lisp",
3549 ];
3550 for relpath in canonical {
3551 UpgradeInstruction::StateChange {
3552 script: PathBuf::from(relpath),
3553 }
3554 .validate()
3555 .unwrap_or_else(|e| {
3556 panic!("canonical `.lisp` script {relpath:?} must pass, got {e:?}")
3557 });
3558 }
3559 }
3560
3561 #[test]
3562 fn validate_sandbox_shape_takes_precedence_over_lisp_extension() {
3563 // Cross-arm precedence pin: a script that is *both*
3564 // sandbox-escaping (Empty / Absolute / ParentEscape) and
3565 // non-`.lisp` must surface the more-fundamental
3566 // sandbox-shape diagnostic first — the canonical fix
3567 // collapses both into "pin a relative `.lisp` path under the
3568 // caixa root", and the `.lisp` remediation would be
3569 // misleading when the offending path can never resolve under
3570 // the caixa root anyway. Mirrors the peer
3571 // `BehaviorError` cross-arm precedence (c97815a) and the
3572 // sibling `LimitsError`
3573 // (`MemoryZero` → `MemoryBelowWasm32Page` →
3574 // `MemoryExceedsWasm32Cap` → `MemoryNotPageMultiple`)
3575 // smallest-scope-arm-fires-last posture.
3576 let i_empty = UpgradeInstruction::StateChange {
3577 script: PathBuf::new(),
3578 };
3579 assert_eq!(i_empty.validate().unwrap_err(), UpgradeError::EmptyScript);
3580 let i_abs = UpgradeInstruction::StateChange {
3581 script: PathBuf::from("/etc/migrations.txt"),
3582 };
3583 assert!(
3584 matches!(
3585 i_abs.validate().unwrap_err(),
3586 UpgradeError::AbsoluteScript { .. }
3587 ),
3588 "absolute + non-`.lisp` must surface AbsoluteScript first"
3589 );
3590 let i_esc = UpgradeInstruction::StateChange {
3591 script: PathBuf::from("../sibling/migrations.rs"),
3592 };
3593 assert!(
3594 matches!(
3595 i_esc.validate().unwrap_err(),
3596 UpgradeError::ParentEscapeScript { .. }
3597 ),
3598 "parent-escape + non-`.lisp` must surface ParentEscapeScript first"
3599 );
3600 }
3601
3602 #[test]
3603 fn non_lisp_extension_script_diagnostic_carries_offending_path() {
3604 // Diagnostic-shape pin: the surfaced error message names the
3605 // offending path verbatim (so the author can grep their
3606 // caixa.lisp for the literal value), the `.lisp` extension
3607 // is named in the remediation, and the downstream consumer
3608 // (`tatara_lisp::read` at hot-upgrade migration time) is
3609 // named so the author can trace the contract back to its
3610 // source. Same self-locating shape every per-axis variant
3611 // carries (`BehaviorError::NonLispExtension`, c97815a;
3612 // `LimitsError::MemoryNotPageMultiple`, ec266d8).
3613 let bad = PathBuf::from("lib/migrations.txt");
3614 let err = UpgradeInstruction::StateChange {
3615 script: bad.clone(),
3616 }
3617 .validate()
3618 .unwrap_err();
3619 let msg = err.to_string();
3620 assert!(
3621 msg.contains("lib/migrations.txt"),
3622 "diagnostic must name the offending path verbatim, got {msg:?}"
3623 );
3624 assert!(
3625 msg.contains(".lisp"),
3626 "diagnostic must name the expected `.lisp` extension, got {msg:?}"
3627 );
3628 assert!(
3629 msg.contains(crate::render::M2_UPGRADE_INSTRUCTION_KIND_STATE_CHANGE),
3630 "diagnostic must name the offending `:state-change` instruction, got {msg:?}"
3631 );
3632 match err {
3633 UpgradeError::NonLispExtensionScript { script } => {
3634 assert_eq!(
3635 script, bad,
3636 "variant must carry the offending path verbatim"
3637 );
3638 }
3639 other => panic!("expected NonLispExtensionScript, got {other:?}"),
3640 }
3641 }
3642
3643 #[test]
3644 fn declared_path_only_for_state_change() {
3645 let load = UpgradeInstruction::LoadModule { module: "x".into() };
3646 assert!(load.declared_path().is_none());
3647 let mig = UpgradeInstruction::StateChange {
3648 script: PathBuf::from("lib/m.lisp"),
3649 };
3650 assert_eq!(mig.declared_path(), Some(&PathBuf::from("lib/m.lisp")));
3651 }
3652
3653 #[test]
3654 fn upgrade_instruction_is_restart_predicate_partitions_the_arm_set() {
3655 // The fail-before-pass-after pin on the `gen_platform::IsVariant`
3656 // derive's [`UpgradeInstruction::is_restart`] arm-discriminator
3657 // predicate: [`UpgradeInstruction::Restart`] is the only variant
3658 // that satisfies `.is_restart()`; every module-bearing arm
3659 // (`LoadModule` / `SoftPurge` / `Purge`) and the script-carrying
3660 // `StateChange` arm all return `false`. This pin makes the
3661 // partition invariant load-bearing at caixa-core test time so a
3662 // future derive regression (a hole that returns `false` for
3663 // `Restart` too, or a byte-collision that flips a second variant
3664 // to `true`) trips here rather than laundering the arm at
3665 // [`Self::validate_restart_exclusive`]'s paired positive /
3666 // negated filter sites (a hole flips restart-count to 0 →
3667 // vacuous OK; a collision flips restart-count > 1 → false
3668 // `RestartNotExclusive` on an entry the author declared without
3669 // any `(:restart)`). Peer of the sibling
3670 // [`crate::kind::tests::caixa_kind_is_variant_predicates_partition_the_arm_set`]
3671 // pin on the M0 `CaixaKind` axis.
3672 let cases: &[(UpgradeInstruction, bool)] = &[
3673 (UpgradeInstruction::LoadModule { module: "a".into() }, false),
3674 (UpgradeInstruction::SoftPurge { module: "b".into() }, false),
3675 (UpgradeInstruction::Purge { module: "c".into() }, false),
3676 (
3677 UpgradeInstruction::StateChange {
3678 script: PathBuf::from("lib/m.lisp"),
3679 },
3680 false,
3681 ),
3682 (UpgradeInstruction::Restart, true),
3683 ];
3684 for (variant, expected) in cases {
3685 assert_eq!(
3686 variant.is_restart(),
3687 *expected,
3688 "UpgradeInstruction::{variant:?}.is_restart() must \
3689 return {expected} (partition invariant on the \
3690 IsVariant-derived arm-discriminator predicate)"
3691 );
3692 }
3693 }
3694
3695 #[test]
3696 fn validate_restart_exclusive_routes_through_is_restart_predicate() {
3697 // Byte-identity pin on the paired positive / negated
3698 // `.is_restart()` filters at
3699 // [`Self::validate_restart_exclusive`] against the pre-lift
3700 // `matches!(i, UpgradeInstruction::Restart)` /
3701 // `!matches!(i, UpgradeInstruction::Restart)` predicates every
3702 // consumer of the gate previously coupled to inline. Asserts
3703 // the two projections agree byte-for-byte on every arm of the
3704 // enum, so a future derive regression that flipped either
3705 // predicate's arm-set would surface here at caixa-core test
3706 // time rather than at
3707 // [`Self::validate_restart_exclusive`]'s per-entry restart-
3708 // count / other-kinds tabulation far from the derive site.
3709 // Same peer-shape pin every sibling
3710 // `IsVariant`-derive-routed gate carries on the substrate's
3711 // closed-set typed-enum surface.
3712 let cases: Vec<UpgradeInstruction> = vec![
3713 UpgradeInstruction::LoadModule { module: "a".into() },
3714 UpgradeInstruction::SoftPurge { module: "b".into() },
3715 UpgradeInstruction::Purge { module: "c".into() },
3716 UpgradeInstruction::StateChange {
3717 script: PathBuf::from("lib/m.lisp"),
3718 },
3719 UpgradeInstruction::Restart,
3720 ];
3721 for instr in &cases {
3722 let via_predicate = instr.is_restart();
3723 let via_matches = matches!(instr, UpgradeInstruction::Restart);
3724 assert_eq!(
3725 via_predicate, via_matches,
3726 "UpgradeInstruction::{instr:?}: is_restart() must \
3727 byte-equal matches!(_, UpgradeInstruction::Restart) — \
3728 the pre-lift open-coded pattern and the \
3729 IsVariant-derived predicate are the same axis, \
3730 one typed dispatch"
3731 );
3732 }
3733 }
3734
3735 #[test]
3736 fn upgrade_instruction_is_cleanup_predicate_partitions_the_arm_set() {
3737 // The fail-before-pass-after pin on the lifted
3738 // [`UpgradeInstruction::is_cleanup`] two-arm cleanup-family
3739 // arm-discriminator predicate:
3740 // [`UpgradeInstruction::SoftPurge`] and
3741 // [`UpgradeInstruction::Purge`] are the two OTP-appup two-
3742 // phase-code-load cleanup arms that satisfy `.is_cleanup()`;
3743 // every non-cleanup arm ([`UpgradeInstruction::LoadModule`]
3744 // on the paired two-phase-load half,
3745 // [`UpgradeInstruction::StateChange`] on the
3746 // `gen_server:code_change/3`-analog migration axis,
3747 // [`UpgradeInstruction::Restart`] on the OTP terminal-
3748 // fallback shape) returns `false`. This pin makes the
3749 // partition invariant load-bearing at caixa-core test time
3750 // so a future accessor regression (a hole that returns
3751 // `false` for `SoftPurge` or `Purge`, or a byte-collision
3752 // that flips `LoadModule` / `StateChange` / `Restart` to
3753 // `true`) trips here rather than laundering the arm at the
3754 // three within-entry cross-instruction cleanup-facing gates
3755 // ([`UpgradeFromEntry::validate_purge_ordering`],
3756 // [`UpgradeFromEntry::validate_state_change_before_cleanup`],
3757 // [`UpgradeFromEntry::validate_cleanup_singularity`]) — a
3758 // hole would silently accept a cleanup-shaped entry the
3759 // three gates should refuse; a collision would fire a
3760 // `PurgeWithoutPriorLoad` / `StateChangeAfterCleanup` /
3761 // `DuplicateCleanup` refusal on a well-shaped
3762 // [`UpgradeInstruction::LoadModule`] / `StateChange` /
3763 // `Restart` arm the three gates should pass through. Peer
3764 // of the sibling
3765 // [`upgrade_instruction_is_restart_predicate_partitions_the_arm_set`]
3766 // pin on the single-arm terminal-fallback partition —
3767 // extended here from the single-arm case onto the two-arm
3768 // cleanup-family union case.
3769 let cases: &[(UpgradeInstruction, bool)] = &[
3770 (UpgradeInstruction::LoadModule { module: "a".into() }, false),
3771 (UpgradeInstruction::SoftPurge { module: "b".into() }, true),
3772 (UpgradeInstruction::Purge { module: "c".into() }, true),
3773 (
3774 UpgradeInstruction::StateChange {
3775 script: PathBuf::from("lib/m.lisp"),
3776 },
3777 false,
3778 ),
3779 (UpgradeInstruction::Restart, false),
3780 ];
3781 for (variant, expected) in cases {
3782 assert_eq!(
3783 variant.is_cleanup(),
3784 *expected,
3785 "UpgradeInstruction::{variant:?}.is_cleanup() must \
3786 return {expected} (partition invariant on the \
3787 lifted OTP-appup two-arm cleanup-family arm-\
3788 discriminator predicate)"
3789 );
3790 }
3791 }
3792
3793 #[test]
3794 fn upgrade_instruction_is_cleanup_composes_through_is_soft_purge_or_is_purge() {
3795 // Byte-identity pin on the [`UpgradeInstruction::is_cleanup`]
3796 // composition against the two [`gen_platform::IsVariant`]-
3797 // derive-generated per-variant classifiers it routes through
3798 // — the accessor's one body must byte-equal
3799 // `self.is_soft_purge() || self.is_purge()` across every arm
3800 // of the closed-set enum, so a future silent detour that
3801 // reintroduced a raw `matches!` pattern or that stopped
3802 // composing through the derive-generated per-variant
3803 // predicates (an accidental `self.is_soft_purge()` on its
3804 // own — silently dropping the `Purge` arm; an accidental
3805 // `self.is_purge() || self.is_state_change()` — silently
3806 // folding the migration arm into the cleanup family; a
3807 // typo `&&` for the union `||` — silently classifying no
3808 // arm as cleanup) trips here at caixa-core test time
3809 // rather than laundering the arm at the three within-entry
3810 // cross-instruction cleanup-facing gates. Same peer-shape
3811 // pin the sibling
3812 // [`validate_restart_exclusive_routes_through_is_restart_predicate`]
3813 // carries on the paired terminal-fallback axis.
3814 let cases: Vec<UpgradeInstruction> = vec![
3815 UpgradeInstruction::LoadModule { module: "a".into() },
3816 UpgradeInstruction::SoftPurge { module: "b".into() },
3817 UpgradeInstruction::Purge { module: "c".into() },
3818 UpgradeInstruction::StateChange {
3819 script: PathBuf::from("lib/m.lisp"),
3820 },
3821 UpgradeInstruction::Restart,
3822 ];
3823 for instr in &cases {
3824 let via_predicate = instr.is_cleanup();
3825 let via_composition = instr.is_soft_purge() || instr.is_purge();
3826 assert_eq!(
3827 via_predicate, via_composition,
3828 "UpgradeInstruction::{instr:?}: is_cleanup() must \
3829 byte-equal is_soft_purge() || is_purge() — the \
3830 lifted union predicate and its per-variant \
3831 composition are the same axis, one typed dispatch"
3832 );
3833 }
3834 }
3835
3836 #[test]
3837 fn upgrade_instruction_is_cleanup_implies_declared_module_is_some() {
3838 // Composition-pin the load-bearing invariant every consumer
3839 // that routes through `is_cleanup()` + `declared_module()`
3840 // relies on: any [`UpgradeInstruction`] value whose
3841 // `.is_cleanup()` returns `true` must have a `Some(_)`
3842 // `.declared_module()`. This makes the three within-entry
3843 // cross-instruction cleanup-facing gates' `.expect("is_cleanup()
3844 // implies declared_module() is Some")` structurally
3845 // infallible at build time — a future refactor that added
3846 // a cleanup-shaped variant carrying no `:module` would trip
3847 // here rather than panic at
3848 // [`UpgradeFromEntry::validate_purge_ordering`] /
3849 // [`UpgradeFromEntry::validate_state_change_before_cleanup`] /
3850 // [`UpgradeFromEntry::validate_cleanup_singularity`] at
3851 // runtime on the offending author's caixa.lisp.
3852 let cases: Vec<UpgradeInstruction> = vec![
3853 UpgradeInstruction::LoadModule { module: "a".into() },
3854 UpgradeInstruction::SoftPurge { module: "b".into() },
3855 UpgradeInstruction::Purge { module: "c".into() },
3856 UpgradeInstruction::StateChange {
3857 script: PathBuf::from("lib/m.lisp"),
3858 },
3859 UpgradeInstruction::Restart,
3860 ];
3861 for instr in &cases {
3862 if instr.is_cleanup() {
3863 assert!(
3864 instr.declared_module().is_some(),
3865 "UpgradeInstruction::{instr:?}: is_cleanup() \
3866 must imply declared_module().is_some() — the \
3867 three within-entry cross-instruction cleanup-\
3868 facing gates rely on this invariant to route \
3869 the cleanup-target :module scalar through the \
3870 sibling declared_module accessor without a \
3871 pattern-bound `module` binding"
3872 );
3873 }
3874 }
3875 }
3876
3877 #[test]
3878 fn upgrade_instruction_is_load_module_implies_declared_module_is_some() {
3879 // Composition-pin the load-bearing invariant
3880 // [`UpgradeFromEntry::validate_load_singularity`] relies on
3881 // when routing the per-instruction load-family arm-discriminator
3882 // through the sibling
3883 // [`UpgradeInstruction::is_load_module`] +
3884 // [`UpgradeInstruction::declared_module`] accessor pair: any
3885 // [`UpgradeInstruction`] value whose `.is_load_module()`
3886 // returns `true` must have a `Some(_)` `.declared_module()`.
3887 // This makes the gate's `.expect("is_load_module() implies
3888 // declared_module() is Some")` structurally infallible at
3889 // build time — a future refactor that added a load-shaped
3890 // variant carrying no `:module` would trip here rather than
3891 // panic at [`UpgradeFromEntry::validate_load_singularity`]
3892 // at runtime on the offending author's caixa.lisp. Sibling
3893 // of the peer
3894 // [`upgrade_instruction_is_cleanup_implies_declared_module_is_some`]
3895 // composition pin on the two-arm cleanup-family axis — same
3896 // "predicate implies accessor" discipline extended onto the
3897 // single-arm load-family axis, closes the load-vs-cleanup
3898 // pair on the substrate primitive's typed dispatch discipline.
3899 let cases: Vec<UpgradeInstruction> = vec![
3900 UpgradeInstruction::LoadModule { module: "a".into() },
3901 UpgradeInstruction::SoftPurge { module: "b".into() },
3902 UpgradeInstruction::Purge { module: "c".into() },
3903 UpgradeInstruction::StateChange {
3904 script: PathBuf::from("lib/m.lisp"),
3905 },
3906 UpgradeInstruction::Restart,
3907 ];
3908 for instr in &cases {
3909 if instr.is_load_module() {
3910 assert!(
3911 instr.declared_module().is_some(),
3912 "UpgradeInstruction::{instr:?}: is_load_module() \
3913 must imply declared_module().is_some() — the \
3914 within-entry load-singularity gate relies on this \
3915 invariant to route the load-target :module scalar \
3916 through the sibling declared_module accessor \
3917 without a pattern-bound `module` binding"
3918 );
3919 }
3920 }
3921 }
3922
3923 #[test]
3924 fn validate_load_singularity_projects_modules_through_is_load_module_and_declared_module_accessors()
3925 {
3926 // Byte-identity pin on the
3927 // [`UpgradeFromEntry::validate_load_singularity`] load-family
3928 // dispatch against the pre-lift
3929 // `match instr { UpgradeInstruction::LoadModule { module } =>
3930 // module.as_str(), _ => continue }` open-coded pattern-match
3931 // the site previously carried. Asserts the two projections
3932 // agree byte-for-byte on every arm of the enum — the
3933 // arm-discriminator via `is_load_module()` and the `:module`
3934 // scalar via `declared_module()` — so a future derive
3935 // regression that flipped the predicate's arm-set (a hole
3936 // returning `false` for [`UpgradeInstruction::LoadModule`], a
3937 // byte-collision flipping a second variant to `true`) or an
3938 // accessor extension that promoted an additional variant onto
3939 // the `String`-carrying axis would trip here at caixa-core
3940 // test time rather than laundering the arm at the gate's
3941 // per-entry load-singularity scan far from the derive site.
3942 // Peer of the sibling
3943 // [`validate_purge_ordering_routes_through_is_load_module_predicate`]
3944 // byte-identity pin on the paired ordering-side load-family
3945 // sticky-latch dispatch (both consumers now agree on one
3946 // typed dispatch for the load-family axis) and the peer
3947 // [`validate_state_change_singularity_projects_scripts_through_declared_path_accessor`]
3948 // pin on the migration-family script-projection axis — the
3949 // three within-entry per-instruction-class singularity gates
3950 // now share one byte-identity pin apiece against their
3951 // respective substrate-primitive typed dispatches.
3952 //
3953 // Three-arm projective coverage:
3954 // (a) `LoadModule` modules project through
3955 // `declared_module()` byte-equal to the raw
3956 // `module.as_str()` field access;
3957 // (b) a duplicate-`LoadModule` input trips the gate on the
3958 // second occurrence with `DuplicateLoadModule` carrying
3959 // the offending module verbatim;
3960 // (c) a non-`LoadModule`-only input (`SoftPurge` / `Purge` /
3961 // `StateChange` / `Restart`) leaves the gate vacuous
3962 // with `Ok(())` — the `!instr.is_load_module()`
3963 // `continue` fall-through pins.
3964 //
3965 // Fail-before-pass-after verified locally: swapping the
3966 // production `if !instr.is_load_module() { continue; } let
3967 // module = instr.declared_module().expect(…);` back to `let
3968 // module = match instr { UpgradeInstruction::LoadModule
3969 // { module } => module.as_str(), _ => continue, };` keeps
3970 // arms (a)-(c) passing but silently detaches the gate from
3971 // the accessor's typed dispatch — any future
3972 // `is_load_module` / `declared_module` extension (a hole in
3973 // either predicate, a promotion of an additional variant
3974 // onto the `String`-carrying axis, an operator-side
3975 // pre-parsed caixa-name cache the accessor materializes)
3976 // would then silently disagree between this gate's raw
3977 // pattern-match and the peer per-`UpgradeInstruction`
3978 // consumers that route through the accessor pair.
3979
3980 // (a) LoadModule projection byte-equal via
3981 // is_load_module() + declared_module().
3982 let lm = UpgradeInstruction::LoadModule {
3983 module: "hello-rio".into(),
3984 };
3985 assert!(
3986 lm.is_load_module(),
3987 "LoadModule must satisfy is_load_module() — the gate's \
3988 load-family arm-discriminator relies on this partition"
3989 );
3990 assert_eq!(
3991 lm.declared_module(),
3992 Some("hello-rio"),
3993 "declared_module() must project the LoadModule :module \
3994 byte-equal to the raw field access — accessor divergence \
3995 would silently detach the gate from the projection every \
3996 peer per-`UpgradeInstruction` consumer routes through"
3997 );
3998
3999 // (b) Duplicate-LoadModule input trips the gate.
4000 let dup = entry(
4001 "0.1.0",
4002 vec![
4003 UpgradeInstruction::LoadModule { module: "x".into() },
4004 UpgradeInstruction::LoadModule { module: "x".into() },
4005 ],
4006 );
4007 assert_eq!(
4008 dup.validate_load_singularity(),
4009 Err(UpgradeError::DuplicateLoadModule {
4010 from: "0.1.0".into(),
4011 module: "x".into(),
4012 }),
4013 "duplicate LoadModule modules within one entry must fire \
4014 DuplicateLoadModule byte-identical to the pre-lift \
4015 pattern-match shape"
4016 );
4017
4018 // (c) Non-LoadModule-only input leaves the gate vacuous.
4019 let no_load = entry(
4020 "0.1.0",
4021 vec![
4022 UpgradeInstruction::StateChange {
4023 script: PathBuf::from("lib/m.lisp"),
4024 },
4025 UpgradeInstruction::Restart,
4026 ],
4027 );
4028 assert_eq!(
4029 no_load.validate_load_singularity(),
4030 Ok(()),
4031 "non-LoadModule-only entries must leave the load-\
4032 singularity gate vacuous — the `!is_load_module()` \
4033 continue fall-through pins"
4034 );
4035 }
4036
4037 #[test]
4038 fn upgrade_instruction_is_load_module_predicate_partitions_the_arm_set() {
4039 // The fail-before-pass-after pin on the `gen_platform::IsVariant`
4040 // derive's [`UpgradeInstruction::is_load_module`] arm-discriminator
4041 // predicate: [`UpgradeInstruction::LoadModule`] is the only
4042 // variant that satisfies `.is_load_module()`; every cleanup arm
4043 // (`SoftPurge` / `Purge`), the migration arm (`StateChange`),
4044 // and the terminal-fallback arm (`Restart`) all return `false`.
4045 // This pin makes the partition invariant load-bearing at
4046 // caixa-core test time so a future derive regression (a hole
4047 // that returns `false` for `LoadModule` too, or a byte-collision
4048 // that flips a second variant to `true`) trips here rather than
4049 // laundering the arm at
4050 // [`Self::validate_purge_ordering`]'s load-family sticky-latch
4051 // dispatch — a hole would silently keep `loaded = false` through
4052 // a well-shaped [`UpgradeInstruction::LoadModule`] prefix and
4053 // false-fire `PurgeWithoutPriorLoad` on the trailing cleanup;
4054 // a collision would flip `loaded = true` on a well-shaped
4055 // cleanup-only entry and silently swallow the load-less
4056 // `PurgeWithoutPriorLoad` refusal. Peer of the sibling
4057 // [`upgrade_instruction_is_restart_predicate_partitions_the_arm_set`]
4058 // and
4059 // [`upgrade_instruction_is_cleanup_predicate_partitions_the_arm_set`]
4060 // pins on the paired terminal-fallback and cleanup-family
4061 // arm-discriminator axes — closes the last unlifted `matches!`-
4062 // based arm-discriminator axis on the OTP-appup closed-set
4063 // typed enum.
4064 let cases: &[(UpgradeInstruction, bool)] = &[
4065 (UpgradeInstruction::LoadModule { module: "a".into() }, true),
4066 (UpgradeInstruction::SoftPurge { module: "b".into() }, false),
4067 (UpgradeInstruction::Purge { module: "c".into() }, false),
4068 (
4069 UpgradeInstruction::StateChange {
4070 script: PathBuf::from("lib/m.lisp"),
4071 },
4072 false,
4073 ),
4074 (UpgradeInstruction::Restart, false),
4075 ];
4076 for (variant, expected) in cases {
4077 assert_eq!(
4078 variant.is_load_module(),
4079 *expected,
4080 "UpgradeInstruction::{variant:?}.is_load_module() must \
4081 return {expected} (partition invariant on the \
4082 IsVariant-derived arm-discriminator predicate)"
4083 );
4084 }
4085 }
4086
4087 #[test]
4088 fn validate_purge_ordering_routes_through_is_load_module_predicate() {
4089 // Byte-identity pin on the [`Self::validate_purge_ordering`]
4090 // load-family sticky-latch dispatch against the pre-lift
4091 // `matches!(instr, UpgradeInstruction::LoadModule { .. })`
4092 // predicate the site previously open-coded. Asserts the two
4093 // projections agree byte-for-byte on every arm of the enum, so
4094 // a future derive regression that flipped the predicate's
4095 // arm-set would surface here at caixa-core test time rather
4096 // than at [`Self::validate_purge_ordering`]'s per-entry
4097 // load-before-cleanup ordering scan far from the derive site.
4098 // Same peer-shape pin the sibling
4099 // [`validate_restart_exclusive_routes_through_is_restart_predicate`]
4100 // carries on the paired terminal-fallback axis and the
4101 // [`upgrade_instruction_is_cleanup_composes_through_is_soft_purge_or_is_purge`]
4102 // carries on the two-arm cleanup-family axis — the third and
4103 // final byte-identity pin closes the substrate primitive's
4104 // arm-discriminator dispatch discipline on the OTP-appup
4105 // closed-set typed enum.
4106 let cases: Vec<UpgradeInstruction> = vec![
4107 UpgradeInstruction::LoadModule { module: "a".into() },
4108 UpgradeInstruction::SoftPurge { module: "b".into() },
4109 UpgradeInstruction::Purge { module: "c".into() },
4110 UpgradeInstruction::StateChange {
4111 script: PathBuf::from("lib/m.lisp"),
4112 },
4113 UpgradeInstruction::Restart,
4114 ];
4115 for instr in &cases {
4116 let via_predicate = instr.is_load_module();
4117 let via_matches = matches!(instr, UpgradeInstruction::LoadModule { .. });
4118 assert_eq!(
4119 via_predicate, via_matches,
4120 "UpgradeInstruction::{instr:?}: is_load_module() must \
4121 byte-equal matches!(_, UpgradeInstruction::LoadModule \
4122 {{ .. }}) — the pre-lift open-coded pattern and the \
4123 IsVariant-derived predicate are the same axis, one \
4124 typed dispatch"
4125 );
4126 }
4127 }
4128
4129 #[test]
4130 fn declared_module_only_for_module_bearing_variants() {
4131 // Pinned partition of the `UpgradeInstruction` closed-set
4132 // variant space against the sibling of the peer
4133 // `declared_path` accessor: every OTP-appup module-bearing
4134 // variant (`LoadModule` / `SoftPurge` / `Purge`) surfaces its
4135 // `:module` string byte-for-byte through the lifted
4136 // `declared_module` accessor; every non-module-bearing variant
4137 // (`StateChange` on the peer `:script`-carrying axis;
4138 // `Restart` on the OTP terminal-fallback data-less axis)
4139 // returns `None`. Mirrors the peer
4140 // `declared_path_only_for_state_change` pin — the pair now
4141 // closes both scalar-carrying axes on the enum on one lifted
4142 // `Option<&…>` accessor apiece.
4143 let load = UpgradeInstruction::LoadModule {
4144 module: "hello-rio".into(),
4145 };
4146 assert_eq!(load.declared_module(), Some("hello-rio"));
4147 let soft = UpgradeInstruction::SoftPurge {
4148 module: "hello-rio-old".into(),
4149 };
4150 assert_eq!(soft.declared_module(), Some("hello-rio-old"));
4151 let hard = UpgradeInstruction::Purge {
4152 module: "hello-rio-ancient".into(),
4153 };
4154 assert_eq!(hard.declared_module(), Some("hello-rio-ancient"));
4155 let mig = UpgradeInstruction::StateChange {
4156 script: PathBuf::from("lib/m.lisp"),
4157 };
4158 assert!(mig.declared_module().is_none());
4159 assert!(UpgradeInstruction::Restart.declared_module().is_none());
4160 }
4161
4162 #[test]
4163 fn declared_module_and_declared_path_partition_the_enum_variant_space() {
4164 // Byte-identity pin on the two-accessor partition: every
4165 // `UpgradeInstruction` variant returns `Some` from *exactly
4166 // one* of {`declared_module`, `declared_path`} (the two
4167 // module-bearing / script-carrying axes) or from *neither*
4168 // (the OTP terminal-fallback `Restart` shape). No variant
4169 // returns `Some` from both — the two axes are disjoint by
4170 // construction, and this pin closes the disjointness at the
4171 // test surface so a future variant that leaks a scalar across
4172 // both axes fails at build time. Mirrors the peer
4173 // `declared_paths_iter_covers_each_declared_slot_exactly_once`
4174 // discipline on the `BehaviorSpec` per-slot family.
4175 let cases: Vec<UpgradeInstruction> = vec![
4176 UpgradeInstruction::LoadModule { module: "a".into() },
4177 UpgradeInstruction::SoftPurge { module: "b".into() },
4178 UpgradeInstruction::Purge { module: "c".into() },
4179 UpgradeInstruction::StateChange {
4180 script: PathBuf::from("lib/m.lisp"),
4181 },
4182 UpgradeInstruction::Restart,
4183 ];
4184 for instr in &cases {
4185 let has_module = instr.declared_module().is_some();
4186 let has_path = instr.declared_path().is_some();
4187 assert!(
4188 !(has_module && has_path),
4189 "no variant may declare both a module and a path — offending: {instr:?}"
4190 );
4191 match instr {
4192 UpgradeInstruction::LoadModule { .. }
4193 | UpgradeInstruction::SoftPurge { .. }
4194 | UpgradeInstruction::Purge { .. } => {
4195 assert!(has_module && !has_path, "module axis: {instr:?}");
4196 }
4197 UpgradeInstruction::StateChange { .. } => {
4198 assert!(!has_module && has_path, "script axis: {instr:?}");
4199 }
4200 UpgradeInstruction::Restart => {
4201 assert!(!has_module && !has_path, "data-less axis: {instr:?}");
4202 }
4203 }
4204 }
4205 }
4206
4207 #[test]
4208 fn entry_with_chain_of_versions() {
4209 // Middle entry pairs a `:load-module` with the trailing
4210 // `:soft-purge` so it satisfies the within-entry purge-ordering
4211 // gate (`PurgeWithoutPriorLoad` rejects `:soft-purge` without a
4212 // preceding `:load-module`, mirroring the state-change-ordering
4213 // gate's `StateChangeWithoutPriorLoad`). The chain shape under
4214 // test is *cross-entry* `:from` values; the within-entry shape
4215 // is incidental — keeping it canonical (`:load-module` before
4216 // `:soft-purge`) leaves the chain assertion load-bearing.
4217 let entries = vec![
4218 entry(
4219 "0.1.0",
4220 vec![UpgradeInstruction::LoadModule { module: "x".into() }],
4221 ),
4222 entry(
4223 "0.1.5",
4224 vec![
4225 UpgradeInstruction::LoadModule { module: "x".into() },
4226 UpgradeInstruction::SoftPurge {
4227 module: "x-old".into(),
4228 },
4229 ],
4230 ),
4231 entry("0.2.0-rc.1", vec![UpgradeInstruction::Restart]),
4232 ];
4233 for e in &entries {
4234 e.validate().unwrap();
4235 }
4236 let json = serde_json::to_string(&entries).unwrap();
4237 let back: Vec<UpgradeFromEntry> = serde_json::from_str(&json).unwrap();
4238 assert_eq!(entries, back);
4239 }
4240
4241 #[test]
4242 fn empty_instructions_list_is_valid() {
4243 let e = entry("0.1.0", vec![]);
4244 e.validate().unwrap();
4245 }
4246
4247 #[test]
4248 fn json_uses_kebab_case_kind_tags() {
4249 let i = UpgradeInstruction::SoftPurge {
4250 module: "x-old".into(),
4251 };
4252 let json = serde_json::to_string(&i).unwrap();
4253 assert!(json.contains("\"kind\":\"soft-purge\""));
4254 let i2 = UpgradeInstruction::StateChange {
4255 script: PathBuf::from("m.lisp"),
4256 };
4257 let json2 = serde_json::to_string(&i2).unwrap();
4258 assert!(json2.contains("\"kind\":\"state-change\""));
4259 }
4260
4261 // ── validate_upgrade_from: cross-entry graph-edge-set invariant ────
4262
4263 #[test]
4264 fn validate_upgrade_from_accepts_disjoint_versions() {
4265 // Positive control: the canonical "chain v0.1.0 → 0.1.5 →
4266 // 0.2.0-rc.1" authoring shape from ABSORPTION-ROADMAP §M2.3
4267 // (and `entry_with_chain_of_versions` above) passes the cross-
4268 // entry gate. Different `:from` per entry is the intended
4269 // shape; the gate must not regress this baseline. Middle entry
4270 // pairs `:load-module` with `:soft-purge` to satisfy the
4271 // within-entry purge-ordering gate (see
4272 // `entry_with_chain_of_versions` for the same shape).
4273 let entries = vec![
4274 entry(
4275 "0.1.0",
4276 vec![UpgradeInstruction::LoadModule { module: "x".into() }],
4277 ),
4278 entry(
4279 "0.1.5",
4280 vec![
4281 UpgradeInstruction::LoadModule { module: "x".into() },
4282 UpgradeInstruction::SoftPurge {
4283 module: "x-old".into(),
4284 },
4285 ],
4286 ),
4287 entry("0.2.0-rc.1", vec![UpgradeInstruction::Restart]),
4288 ];
4289 validate_upgrade_from(&entries).unwrap();
4290 }
4291
4292 #[test]
4293 fn validate_upgrade_from_accepts_empty_list() {
4294 // Absent `:upgrade-from` (the bare `feira init` shape) — the
4295 // gate must trivially pass an empty list. Mirrors the per-axis
4296 // "empty list passes" positive control on every peer typed-
4297 // graph gate (`validate_membros` empty list, `validate_placement`
4298 // requires non-empty clusters but only after a `Placement`
4299 // exists, etc.).
4300 validate_upgrade_from(&[]).unwrap();
4301 }
4302
4303 #[test]
4304 fn validate_upgrade_from_rejects_duplicate_from() {
4305 // Fail-before-pass-after pin: two entries with the same parsed-
4306 // semver `:from` are an ambiguous edge in the typed upgrade
4307 // graph (OTP appup picks at most one matching block per running
4308 // version; with two matching blocks the operator picks either
4309 // set non-deterministically — author intent is one path per
4310 // prior version). Same set-not-multiset discipline as
4311 // `:children :caixa` (dbf50a9), `:membros :caixa` (4bb3f3d),
4312 // `:contratos` (5dbcfaf), `:placement :clusters` (c7c7799),
4313 // `:entrada :paths` (eb3456d) — now extended onto the fifth
4314 // typed-graph axis.
4315 let entries = vec![
4316 entry(
4317 "0.1.0",
4318 vec![UpgradeInstruction::LoadModule { module: "x".into() }],
4319 ),
4320 entry(
4321 "0.1.0",
4322 vec![
4323 UpgradeInstruction::LoadModule { module: "x".into() },
4324 UpgradeInstruction::SoftPurge {
4325 module: "x-old".into(),
4326 },
4327 ],
4328 ),
4329 ];
4330 let err = validate_upgrade_from(&entries).unwrap_err();
4331 assert_eq!(
4332 err,
4333 UpgradeError::DuplicateFrom {
4334 from: "0.1.0".into()
4335 },
4336 "two entries with `:from \"0.1.0\"` must surface as DuplicateFrom carrying the \
4337 offending value verbatim"
4338 );
4339 }
4340
4341 #[test]
4342 fn validate_upgrade_from_treats_pre_release_as_distinct() {
4343 // Negative-of-positive: `1.0.0` and `1.0.0-rc.1` are *not*
4344 // equal under semver (pre-release version is part of the
4345 // identity), so they're distinct upgrade paths and must not
4346 // collide. A future tightening that collapses pre-release into
4347 // the release version surfaces here.
4348 let entries = vec![
4349 entry("1.0.0", vec![UpgradeInstruction::Restart]),
4350 entry("1.0.0-rc.1", vec![UpgradeInstruction::Restart]),
4351 ];
4352 validate_upgrade_from(&entries).unwrap();
4353 }
4354
4355 #[test]
4356 fn validate_upgrade_from_treats_build_metadata_as_distinct() {
4357 // Conservative-by-design: [`semver::Version`]'s `PartialEq`
4358 // compares build metadata (it derives equality across all
4359 // fields including `pre` + `build`), so `1.0.0+build1` and
4360 // `1.0.0+build2` are *not* duplicates from the gate's
4361 // perspective — the operator may treat the build-metadata
4362 // suffix as a tiebreaker even though the semver spec says
4363 // build metadata is ignored for precedence
4364 // (https://semver.org/#spec-item-10). Pin the conservative
4365 // behavior here so a future switch to a build-metadata-
4366 // stripping comparator surfaces as a test failure first; that
4367 // change would require coordinating with the wasm-operator's
4368 // `:from`-match dispatch step, which is the load-bearing
4369 // semantic we'd be mirroring.
4370 let entries = vec![
4371 entry("1.0.0+build1", vec![UpgradeInstruction::Restart]),
4372 entry("1.0.0+build2", vec![UpgradeInstruction::Restart]),
4373 ];
4374 validate_upgrade_from(&entries).unwrap();
4375 }
4376
4377 #[test]
4378 fn validate_upgrade_from_per_entry_shape_fires_before_duplicate() {
4379 // Order pin: a malformed `:from` on the second entry surfaces
4380 // its `FromInvalid` diagnostic, not a (less-useful)
4381 // `DuplicateFrom`. The per-entry shape pass runs *inline*
4382 // before the duplicate-key insert — parallel to
4383 // `child_versao_invalid_fires_before_duplicate_check`
4384 // (b38ff3a) and `membro_versao_invalid_fires_before_duplicate_check`
4385 // (9888b13). Without this pin a future shortcut that runs the
4386 // cross-entry gate first would surface a duplicate diagnostic
4387 // on a string that isn't even parsable as a version.
4388 let entries = vec![
4389 entry("0.1.0", vec![UpgradeInstruction::Restart]),
4390 entry("not-a-semver", vec![UpgradeInstruction::Restart]),
4391 ];
4392 let err = validate_upgrade_from(&entries).unwrap_err();
4393 assert!(
4394 matches!(err, UpgradeError::FromInvalid { ref from, .. } if from == "not-a-semver"),
4395 "malformed `:from` on a non-duplicate entry must surface as FromInvalid, got {err:?}"
4396 );
4397 }
4398
4399 #[test]
4400 fn validate_upgrade_from_per_entry_shape_fires_before_duplicate_on_first_entry() {
4401 // Symmetric arm: a malformed shape on the *first* entry of a
4402 // duplicate pair surfaces its per-entry diagnostic too (not
4403 // the duplicate diagnostic that would otherwise fire on the
4404 // second entry). Pinned separately so a future shortcut that
4405 // walks the duplicate-check ahead of the per-entry pass for the
4406 // first entry only — easy regression to introduce — surfaces
4407 // here.
4408 let entries = vec![
4409 entry(
4410 "0.1.0",
4411 vec![UpgradeInstruction::LoadModule {
4412 module: String::new(),
4413 }],
4414 ),
4415 entry("0.1.0", vec![UpgradeInstruction::Restart]),
4416 ];
4417 let err = validate_upgrade_from(&entries).unwrap_err();
4418 assert_eq!(
4419 err,
4420 UpgradeError::ModuleEmpty {
4421 kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE
4422 },
4423 "malformed instruction on the first entry of a duplicate pair must surface its \
4424 per-entry diagnostic before the duplicate gate fires, got {err:?}"
4425 );
4426 }
4427
4428 #[test]
4429 fn validate_upgrade_from_duplicate_diagnostic_names_second_collision() {
4430 // Diagnostic-shape pin: when three entries carry the same
4431 // `:from`, the gate reports the *first* collision (the second
4432 // entry) and stops — the third entry's duplicate is masked by
4433 // the first surfaced one. Mirrors
4434 // `validate_duplicate_child_diagnostic_names_first_collision`
4435 // (dbf50a9) on the supervisor axis.
4436 let entries = vec![
4437 entry("0.1.0", vec![UpgradeInstruction::Restart]),
4438 entry("0.1.0", vec![UpgradeInstruction::Restart]),
4439 entry("0.1.0", vec![UpgradeInstruction::Restart]),
4440 ];
4441 let err = validate_upgrade_from(&entries).unwrap_err();
4442 assert_eq!(
4443 err,
4444 UpgradeError::DuplicateFrom {
4445 from: "0.1.0".into()
4446 }
4447 );
4448 }
4449
4450 #[test]
4451 fn validate_upgrade_from_single_entry_never_duplicates() {
4452 // Boundary control: a list of one entry can never produce a
4453 // duplicate, regardless of `:from` value (any single-element
4454 // set is trivially without duplicates). Pin this so a future
4455 // off-by-one in the seen-set insert doesn't accidentally flag
4456 // a single entry as duplicating itself.
4457 let entries = vec![entry("0.1.0", vec![UpgradeInstruction::Restart])];
4458 validate_upgrade_from(&entries).unwrap();
4459 }
4460
4461 // ── validate_upgrade_from_against_versao: cross-slot precedence gate ─
4462
4463 #[test]
4464 fn versao_gate_accepts_strict_upgrade() {
4465 // Positive control: the canonical "chain prior versions →
4466 // current" authoring shape from ABSORPTION-ROADMAP §M2.3 — each
4467 // `:from` strictly less than the current `:versao` under
4468 // SemVer-2 precedence. The gate must not regress this baseline.
4469 let entries = vec![
4470 entry("0.1.0", vec![UpgradeInstruction::Restart]),
4471 entry("0.1.5", vec![UpgradeInstruction::Restart]),
4472 entry("0.1.9", vec![UpgradeInstruction::Restart]),
4473 ];
4474 validate_upgrade_from_against_versao(&entries, "0.2.0").unwrap();
4475 }
4476
4477 #[test]
4478 fn versao_gate_accepts_empty_entries() {
4479 // Bare `feira init` shape (no `:upgrade-from`) trivially passes;
4480 // the gate is a no-op when the entries list is empty. Mirrors
4481 // `validate_upgrade_from_accepts_empty_list` on the peer gate.
4482 validate_upgrade_from_against_versao(&[], "0.1.0").unwrap();
4483 }
4484
4485 #[test]
4486 fn versao_gate_rejects_equal_from() {
4487 // Self-upgrade no-op: declaring `:from "0.2.0"` while
4488 // `:versao "0.2.0"` means "upgrade from myself to myself" —
4489 // the operator's dispatch either skips silently or
4490 // trivially "succeeds" with no observable state change.
4491 // Reject as the canonical "I forgot to bump :versao when
4492 // adding this entry" footgun.
4493 let entries = vec![entry("0.2.0", vec![UpgradeInstruction::Restart])];
4494 let err = validate_upgrade_from_against_versao(&entries, "0.2.0").unwrap_err();
4495 assert_eq!(
4496 err,
4497 UpgradeError::FromNotBeforeVersao {
4498 from: "0.2.0".into(),
4499 versao: "0.2.0".into(),
4500 },
4501 ":from == :versao under precedence must surface as FromNotBeforeVersao naming both \
4502 values verbatim, got {err:?}"
4503 );
4504 }
4505
4506 #[test]
4507 fn versao_gate_rejects_downgrade_from() {
4508 // Downgrade-shaped: `:from "0.3.0"` while `:versao "0.2.0"`
4509 // means "upgrade nodes coming from 0.3.0 to 0.2.0", which
4510 // the operator's `:from`-match dispatch can never reach (it
4511 // never runs a version >= the current one). Reject as the
4512 // canonical "I copy-pasted from the next minor version and
4513 // forgot to bump :versao" footgun.
4514 let entries = vec![entry("0.3.0", vec![UpgradeInstruction::Restart])];
4515 let err = validate_upgrade_from_against_versao(&entries, "0.2.0").unwrap_err();
4516 assert_eq!(
4517 err,
4518 UpgradeError::FromNotBeforeVersao {
4519 from: "0.3.0".into(),
4520 versao: "0.2.0".into(),
4521 }
4522 );
4523 }
4524
4525 #[test]
4526 fn versao_gate_accepts_prerelease_before_release() {
4527 // SemVer §11 precedence: pre-release versions are *less than*
4528 // the corresponding release (`0.2.0-rc.1 < 0.2.0`). Upgrading
4529 // FROM an RC TO the GA release is the canonical authoring
4530 // shape — must pass. A regression that collapses pre-release
4531 // into the release version (treating them as equal) surfaces
4532 // here as a false-positive rejection.
4533 let entries = vec![entry("0.2.0-rc.1", vec![UpgradeInstruction::Restart])];
4534 validate_upgrade_from_against_versao(&entries, "0.2.0").unwrap();
4535 }
4536
4537 #[test]
4538 fn versao_gate_rejects_release_after_prerelease() {
4539 // Symmetric arm: with `:versao "0.2.0-rc.1"` and
4540 // `:from "0.2.0"`, precedence says `0.2.0 > 0.2.0-rc.1` —
4541 // the typical "I'm on an RC of a release that already
4542 // shipped" footgun. The gate names both values verbatim
4543 // so the author can grep for either side and fix in one
4544 // edit.
4545 let entries = vec![entry("0.2.0", vec![UpgradeInstruction::Restart])];
4546 let err = validate_upgrade_from_against_versao(&entries, "0.2.0-rc.1").unwrap_err();
4547 assert_eq!(
4548 err,
4549 UpgradeError::FromNotBeforeVersao {
4550 from: "0.2.0".into(),
4551 versao: "0.2.0-rc.1".into(),
4552 }
4553 );
4554 }
4555
4556 #[test]
4557 fn versao_gate_rejects_build_metadata_only_difference() {
4558 // SemVer §11 explicitly excludes build metadata from
4559 // precedence comparison: `0.2.0+build.1` and `0.2.0` are
4560 // *equal* under [`semver::Version::cmp`]. From the
4561 // operator's `:from`-match dispatch perspective this is a
4562 // self-upgrade no-op (no semantic transition between the
4563 // two), so the gate rejects it — *unlike* the peer
4564 // duplicate-`:from` gate which uses derived `PartialEq` and
4565 // treats build-metadata variants as distinct dispatch keys.
4566 // The two gates' different equality notions are deliberate:
4567 // duplicate-check is conservative (preserves operator-side
4568 // tiebreaking surface), precedence-check is permissive
4569 // (matches operator-side dispatch semantic).
4570 let entries = vec![entry("0.2.0+build.1", vec![UpgradeInstruction::Restart])];
4571 let err = validate_upgrade_from_against_versao(&entries, "0.2.0").unwrap_err();
4572 assert_eq!(
4573 err,
4574 UpgradeError::FromNotBeforeVersao {
4575 from: "0.2.0+build.1".into(),
4576 versao: "0.2.0".into(),
4577 }
4578 );
4579 }
4580
4581 #[test]
4582 fn versao_gate_silently_passes_on_unparseable_versao() {
4583 // Defensive arm: a malformed `:versao` (gated by the
4584 // narrower `ManifestError::VersaoInvalid` surface at the
4585 // load-bearing call site) must not regress into a
4586 // `FromNotBeforeVersao` diagnostic from this gate. Surfacing
4587 // the precedence error over an unparseable `:versao` would
4588 // mask the more actionable root cause (the author meant to
4589 // type `"0.2.0"`, not `"v0.2.0"`).
4590 let entries = vec![entry("0.1.0", vec![UpgradeInstruction::Restart])];
4591 validate_upgrade_from_against_versao(&entries, "not-a-semver").unwrap();
4592 }
4593
4594 #[test]
4595 fn versao_gate_silently_passes_on_unparseable_from() {
4596 // Symmetric defensive arm: a malformed `:from` is gated by
4597 // [`UpgradeFromEntry::validate`] / [`validate_upgrade_from`]
4598 // upstream at the LayoutInvariants call site. Surfacing the
4599 // precedence error over an unparseable `:from` from this
4600 // gate alone would mask the narrower `FromInvalid`
4601 // diagnostic that's expected to lead — same fall-through
4602 // posture as the unparseable-`:versao` arm above. The
4603 // wiring in `LayoutInvariants::verify` runs
4604 // `validate_upgrade_from` *before* this gate, so in practice
4605 // an unparseable `:from` surfaces as `FromInvalid` first
4606 // and this gate is never reached on that input.
4607 let entries = vec![entry("not-a-semver", vec![UpgradeInstruction::Restart])];
4608 validate_upgrade_from_against_versao(&entries, "0.2.0").unwrap();
4609 }
4610
4611 #[test]
4612 fn versao_gate_reports_first_offending_entry() {
4613 // Determinism pin: with multiple offending entries the gate
4614 // surfaces the *first* one in declaration order — same
4615 // posture as `validate_upgrade_from_duplicate_diagnostic_names_second_collision`
4616 // on the peer gate. Walks the entries in order; first
4617 // failing `:from >= :versao` short-circuits.
4618 let entries = vec![
4619 entry("0.1.0", vec![UpgradeInstruction::Restart]),
4620 entry("0.3.0", vec![UpgradeInstruction::Restart]),
4621 entry("0.4.0", vec![UpgradeInstruction::Restart]),
4622 ];
4623 let err = validate_upgrade_from_against_versao(&entries, "0.2.0").unwrap_err();
4624 assert_eq!(
4625 err,
4626 UpgradeError::FromNotBeforeVersao {
4627 from: "0.3.0".into(),
4628 versao: "0.2.0".into(),
4629 },
4630 "the first offending `:from` (0.3.0) must surface, not the later one (0.4.0)"
4631 );
4632 }
4633
4634 // ── UpgradeFromEntry::validate_restart_exclusive: within-entry gate ─
4635
4636 #[test]
4637 fn validate_rejects_restart_mixed_with_load_module() {
4638 // The "I'll try the typed path *then* restart anyway" footgun:
4639 // an instructions list with `(:restart)` plus `(:load-module …)`
4640 // is dead code in both directions (succeed → restart discards
4641 // the work that just succeeded, defeating the typed sequence's
4642 // whole point; fail → restart never reached because the entry
4643 // already failed). The gate names the offending entry's `:from`
4644 // verbatim plus the kebab-case lisp-form of every non-`:restart`
4645 // peer so the author can grep their caixa.lisp for either side
4646 // and fix in one edit.
4647 let e = entry(
4648 "0.1.0",
4649 vec![
4650 UpgradeInstruction::LoadModule {
4651 module: "hello-rio".into(),
4652 },
4653 UpgradeInstruction::Restart,
4654 ],
4655 );
4656 let err = e.validate().unwrap_err();
4657 assert_eq!(
4658 err,
4659 UpgradeError::RestartNotExclusive {
4660 from: "0.1.0".into(),
4661 restart_count: 1,
4662 other_kinds: vec![crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE],
4663 },
4664 "restart + load-module mix must surface as RestartNotExclusive naming the \
4665 offending `:from` + the non-:restart kinds verbatim, got {err:?}"
4666 );
4667 }
4668
4669 #[test]
4670 fn validate_rejects_restart_mixed_with_full_typed_sequence() {
4671 // Sweep the typed-sequence universe — every non-`:restart`
4672 // variant alongside `:restart` — and assert every typed
4673 // instruction's lisp-form appears in `other_kinds` in
4674 // declaration order. The author should be able to grep for
4675 // each verbatim (`:load-module`, `:state-change`, `:soft-purge`,
4676 // `:purge`) and resolve in one pass. Drift in the `lisp_form`
4677 // mapping surfaces here.
4678 let e = entry(
4679 "0.1.0",
4680 vec![
4681 UpgradeInstruction::LoadModule {
4682 module: "hello-rio".into(),
4683 },
4684 UpgradeInstruction::StateChange {
4685 script: PathBuf::from("lib/m.lisp"),
4686 },
4687 UpgradeInstruction::SoftPurge {
4688 module: "hello-rio-old".into(),
4689 },
4690 UpgradeInstruction::Purge {
4691 module: "hello-rio-old".into(),
4692 },
4693 UpgradeInstruction::Restart,
4694 ],
4695 );
4696 let err = e.validate().unwrap_err();
4697 assert_eq!(
4698 err,
4699 UpgradeError::RestartNotExclusive {
4700 from: "0.1.0".into(),
4701 restart_count: 1,
4702 other_kinds: vec![
4703 crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE,
4704 crate::render::M2_UPGRADE_INSTRUCTION_KIND_STATE_CHANGE,
4705 crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
4706 crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
4707 ],
4708 },
4709 );
4710 }
4711
4712 #[test]
4713 fn validate_rejects_restart_duplicated() {
4714 // `((:restart) (:restart))` — multiple Restart variants in one
4715 // entry. The fallback is a single semantic (restart the pod;
4716 // the new version comes up fresh); repeating it is at best
4717 // redundant, at worst suggests the author thought the second
4718 // would re-trigger after the first. The gate reports
4719 // `restart_count: 2` so the diagnostic surfaces the duplication
4720 // mode unambiguously even when `other_kinds` is empty.
4721 let e = entry(
4722 "0.1.0",
4723 vec![UpgradeInstruction::Restart, UpgradeInstruction::Restart],
4724 );
4725 let err = e.validate().unwrap_err();
4726 assert_eq!(
4727 err,
4728 UpgradeError::RestartNotExclusive {
4729 from: "0.1.0".into(),
4730 restart_count: 2,
4731 other_kinds: vec![],
4732 },
4733 );
4734 }
4735
4736 #[test]
4737 fn validate_accepts_sole_restart() {
4738 // Positive control: the canonical "this prior version's typed
4739 // upgrade is impossible — restart" authoring shape from the
4740 // UpgradeInstruction::Restart doc comment. `((:restart))` alone
4741 // is the entry's whole instructions list and the only valid
4742 // Restart-bearing shape.
4743 let e = entry("0.1.0", vec![UpgradeInstruction::Restart]);
4744 e.validate().unwrap();
4745 }
4746
4747 #[test]
4748 fn validate_accepts_typed_sequence_without_restart() {
4749 // Positive control: the canonical typed hot-upgrade authoring
4750 // shape from ABSORPTION-ROADMAP §M2.3 — `:load-module` →
4751 // `:state-change` → `:soft-purge`. Absent `:restart` is the
4752 // only shape that lets the sequence run to completion under
4753 // the wasm-operator's `:from`-match dispatch. Drift here =
4754 // a future tighten that rejects any canonical typed-only shape
4755 // surfaces as a regression at this gate.
4756 let e = entry(
4757 "0.1.0",
4758 vec![
4759 UpgradeInstruction::LoadModule {
4760 module: "hello-rio".into(),
4761 },
4762 UpgradeInstruction::StateChange {
4763 script: PathBuf::from("lib/m.lisp"),
4764 },
4765 UpgradeInstruction::SoftPurge {
4766 module: "hello-rio-old".into(),
4767 },
4768 ],
4769 );
4770 e.validate().unwrap();
4771 }
4772
4773 // ── within-entry state-change-ordering invariant ───────────────────
4774
4775 #[test]
4776 fn validate_rejects_state_change_without_load() {
4777 // Fail-before-pass-after pin: a `:state-change` migrates state
4778 // into the newly-loaded code (gen_server:code_change/3 analog),
4779 // so an entry that runs it with no preceding `:load-module`
4780 // migrates state into code that was never loaded. The operator
4781 // runs instructions in declared order, so this is a build error,
4782 // not a runtime surprise (CAIXA-SDLC §III).
4783 let e = entry(
4784 "0.1.0",
4785 vec![UpgradeInstruction::StateChange {
4786 script: PathBuf::from("lib/m.lisp"),
4787 }],
4788 );
4789 let err = e.validate().unwrap_err();
4790 assert_eq!(
4791 err,
4792 UpgradeError::StateChangeWithoutPriorLoad {
4793 from: "0.1.0".into(),
4794 script: PathBuf::from("lib/m.lisp"),
4795 },
4796 "a `:state-change` with no preceding `:load-module` must surface as \
4797 StateChangeWithoutPriorLoad naming the offending entry + script verbatim"
4798 );
4799 }
4800
4801 #[test]
4802 fn validate_rejects_state_change_before_load() {
4803 // Right-instructions-wrong-order: the load is present but runs
4804 // *after* the migration. Because the operator executes in
4805 // declared order, the migration runs before the new code is
4806 // resident — the same incoherence as the missing-load case.
4807 let e = entry(
4808 "0.1.0",
4809 vec![
4810 UpgradeInstruction::StateChange {
4811 script: PathBuf::from("lib/m.lisp"),
4812 },
4813 UpgradeInstruction::LoadModule {
4814 module: "hello-rio".into(),
4815 },
4816 ],
4817 );
4818 let err = e.validate().unwrap_err();
4819 assert!(
4820 matches!(err, UpgradeError::StateChangeWithoutPriorLoad { .. }),
4821 "a `:state-change` ahead of its `:load-module` must surface as \
4822 StateChangeWithoutPriorLoad, got {err:?}"
4823 );
4824 }
4825
4826 #[test]
4827 fn validate_accepts_state_change_after_load() {
4828 // Positive control: the canonical `(:load-module …)
4829 // (:state-change …)` order validates. The load need not name
4830 // the same module the migration targets (StateChange carries a
4831 // script, not a module ref), so any preceding `:load-module`
4832 // satisfies "new code is resident before its migration runs".
4833 let e = entry(
4834 "0.1.0",
4835 vec![
4836 UpgradeInstruction::LoadModule {
4837 module: "hello-rio".into(),
4838 },
4839 UpgradeInstruction::StateChange {
4840 script: PathBuf::from("lib/m.lisp"),
4841 },
4842 ],
4843 );
4844 e.validate().unwrap();
4845 }
4846
4847 #[test]
4848 fn validate_accepts_multiple_state_changes_after_one_load() {
4849 // A single leading `:load-module` covers every subsequent
4850 // `:state-change` — the `loaded` latch stays set once the new
4851 // code is resident.
4852 let e = entry(
4853 "0.1.0",
4854 vec![
4855 UpgradeInstruction::LoadModule {
4856 module: "hello-rio".into(),
4857 },
4858 UpgradeInstruction::StateChange {
4859 script: PathBuf::from("lib/m1.lisp"),
4860 },
4861 UpgradeInstruction::StateChange {
4862 script: PathBuf::from("lib/m2.lisp"),
4863 },
4864 ],
4865 );
4866 e.validate().unwrap();
4867 }
4868
4869 #[test]
4870 fn validate_state_change_ordering_projects_scripts_through_is_load_module_and_declared_path_accessors()
4871 {
4872 // Byte-identity pin on the
4873 // [`UpgradeFromEntry::validate_state_change_ordering`] load →
4874 // migrate ordering dispatch against the pre-lift
4875 // `match instr { UpgradeInstruction::LoadModule { .. } =>
4876 // loaded = true, UpgradeInstruction::StateChange { script } if
4877 // !loaded => …, _ => {} }` open-coded pattern-match the site
4878 // previously carried. Asserts the two projections agree
4879 // byte-for-byte on every arm of the enum — the load-family
4880 // arm-discriminator via `is_load_module()` and the migration-
4881 // family `:script` scalar via `declared_path()` — so a future
4882 // derive regression that flipped the predicate's arm-set (a
4883 // hole returning `false` for [`UpgradeInstruction::LoadModule`],
4884 // a byte-collision flipping a second variant to `true`) or an
4885 // accessor extension that promoted an additional variant onto
4886 // the `PathBuf`-carrying axis would trip here at caixa-core
4887 // test time rather than laundering the arm at the gate's
4888 // per-entry ordering scan far from the derive site.
4889 //
4890 // Peer of the sibling
4891 // [`validate_load_singularity_projects_modules_through_is_load_module_and_declared_module_accessors`]
4892 // (c9ce91d) pin on the peer within-entry per-instruction-class
4893 // singularity gate's load-family + `String`-carrying dispatch,
4894 // the [`validate_purge_ordering_routes_through_is_load_module_predicate`]
4895 // (580d0f1) pin on the paired load → cleanup ordering gate's
4896 // load-family sticky-latch dispatch, and the
4897 // [`validate_state_change_singularity_projects_scripts_through_declared_path_accessor`]
4898 // pin on the peer within-entry per-instruction-class singularity
4899 // gate's migration-family script-projection dispatch — closes
4900 // the last unlifted `match`-shaped per-arm-hand-rolled load-
4901 // family arm-discriminator + migration-family script-projection
4902 // pair inside `impl UpgradeFromEntry`. The four within-entry
4903 // ordering / singularity gates now share one byte-identity pin
4904 // apiece against their respective substrate-primitive typed
4905 // dispatches on the OTP-appup closed-set enum.
4906 //
4907 // Three-arm projective coverage:
4908 // (a) `LoadModule` satisfies `is_load_module()`, so the
4909 // sticky-latch advances byte-equal to the pre-lift
4910 // `UpgradeInstruction::LoadModule { .. }` arm; every
4911 // other variant leaves the latch untouched;
4912 // (b) a `((:state-change …))`-only entry (no preceding load)
4913 // trips the gate on the first `StateChange` with
4914 // `StateChangeWithoutPriorLoad` carrying the offending
4915 // script verbatim — the migration-family script surfaces
4916 // through `declared_path()` byte-equal to the raw
4917 // `StateChange { script }` pattern-bound field;
4918 // (c) a `((:load-module …) (:state-change …))` entry leaves
4919 // the gate vacuous with `Ok(())` — the `loaded = true`
4920 // latch on the first arm satisfies the `!loaded` guard
4921 // negation on the second, so the `declared_path()`
4922 // `Some(script)` fall-through does not fire — and a
4923 // non-`StateChange`-non-`LoadModule` sequence
4924 // (`SoftPurge` / `Purge` / `Restart` alone) also leaves
4925 // the gate vacuous because `declared_path()` is `None`
4926 // on all three of those arms.
4927 //
4928 // Fail-before-pass-after verified locally: swapping the
4929 // production `if instr.is_load_module() { loaded = true; }
4930 // else if !loaded && let Some(script) = instr.declared_path()
4931 // { … }` back to `match instr { UpgradeInstruction::LoadModule
4932 // { .. } => loaded = true, UpgradeInstruction::StateChange
4933 // { script } if !loaded => …, _ => {} }` keeps arms (a)-(c)
4934 // passing but silently detaches the gate from the accessor's
4935 // typed dispatch — any future `is_load_module` / `declared_path`
4936 // extension (a hole in either predicate, a promotion of an
4937 // additional variant onto either axis, an operator-side
4938 // pre-resolved-path cache the accessor materializes) would
4939 // then silently disagree between this gate's raw pattern-match
4940 // and the peer per-`UpgradeInstruction` consumers that route
4941 // through the accessor pair.
4942
4943 // (a) is_load_module() partitions the arm-set byte-equal to
4944 // the pre-lift `matches!(_, UpgradeInstruction::LoadModule
4945 // { .. })` and declared_path() surfaces the StateChange
4946 // `:script` byte-equal to the raw field access.
4947 let lm = UpgradeInstruction::LoadModule {
4948 module: "hello-rio".into(),
4949 };
4950 assert!(
4951 lm.is_load_module(),
4952 "LoadModule must satisfy is_load_module() — the gate's \
4953 load-family sticky-latch relies on this partition"
4954 );
4955 assert!(
4956 lm.declared_path().is_none(),
4957 "LoadModule must not carry a declared_path — the gate's \
4958 else-if migration-family arm must not fire on load arms"
4959 );
4960 let sc = UpgradeInstruction::StateChange {
4961 script: PathBuf::from("lib/m.lisp"),
4962 };
4963 assert!(
4964 !sc.is_load_module(),
4965 "StateChange must not satisfy is_load_module() — the gate's \
4966 sticky-latch must not advance on migration arms"
4967 );
4968 assert_eq!(
4969 sc.declared_path().map(std::path::PathBuf::as_path),
4970 Some(PathBuf::from("lib/m.lisp").as_path()),
4971 "declared_path() must project the StateChange :script \
4972 byte-equal to the raw field access — accessor divergence \
4973 would silently detach the gate from the projection every \
4974 peer per-`UpgradeInstruction` consumer routes through"
4975 );
4976
4977 // (b) A `((:state-change …))`-only entry trips
4978 // StateChangeWithoutPriorLoad byte-identical to the
4979 // pre-lift match-pattern shape.
4980 let no_prior_load = entry(
4981 "0.1.0",
4982 vec![UpgradeInstruction::StateChange {
4983 script: PathBuf::from("lib/m.lisp"),
4984 }],
4985 );
4986 assert_eq!(
4987 no_prior_load.validate_state_change_ordering(),
4988 Err(UpgradeError::StateChangeWithoutPriorLoad {
4989 from: "0.1.0".into(),
4990 script: PathBuf::from("lib/m.lisp"),
4991 }),
4992 "a `:state-change` with no preceding `:load-module` must fire \
4993 StateChangeWithoutPriorLoad carrying the offending script \
4994 verbatim through the declared_path() accessor"
4995 );
4996
4997 // (c) `((:load-module …) (:state-change …))` leaves the gate
4998 // vacuous; so does a non-StateChange-non-LoadModule
4999 // sequence (SoftPurge / Purge / Restart alone).
5000 let load_before_migrate = entry(
5001 "0.1.0",
5002 vec![
5003 UpgradeInstruction::LoadModule {
5004 module: "hello-rio".into(),
5005 },
5006 UpgradeInstruction::StateChange {
5007 script: PathBuf::from("lib/m.lisp"),
5008 },
5009 ],
5010 );
5011 assert_eq!(
5012 load_before_migrate.validate_state_change_ordering(),
5013 Ok(()),
5014 "load-before-migrate entries must leave the ordering gate \
5015 vacuous — the `loaded = true` sticky-latch on the first arm \
5016 satisfies the `!loaded` guard negation on the else-if arm"
5017 );
5018 for instr in [
5019 UpgradeInstruction::SoftPurge {
5020 module: "x-old".into(),
5021 },
5022 UpgradeInstruction::Purge {
5023 module: "x-old".into(),
5024 },
5025 UpgradeInstruction::Restart,
5026 ] {
5027 let e = entry("0.1.0", vec![instr.clone()]);
5028 assert_eq!(
5029 e.validate_state_change_ordering(),
5030 Ok(()),
5031 "non-StateChange-non-LoadModule sequence ({instr:?}) must \
5032 leave the ordering gate vacuous — declared_path() is None \
5033 on every non-StateChange arm, so the else-if migration-\
5034 family arm never fires"
5035 );
5036 }
5037 }
5038
5039 #[test]
5040 fn validate_state_change_ordering_fires_after_restart_exclusive() {
5041 // Diagnostic-precedence pin: a `((:state-change …) (:restart))`
5042 // shape is *both* state-change-without-load and restart-mixed.
5043 // The more-fundamental `RestartNotExclusive` must win (a valid
5044 // `(:restart)` entry is `(:restart)` alone, so no Restart-bearing
5045 // entry should reach the ordering gate). Guards the call order
5046 // in `validate` against silent reordering.
5047 let e = entry(
5048 "0.1.0",
5049 vec![
5050 UpgradeInstruction::StateChange {
5051 script: PathBuf::from("lib/m.lisp"),
5052 },
5053 UpgradeInstruction::Restart,
5054 ],
5055 );
5056 let err = e.validate().unwrap_err();
5057 assert!(
5058 matches!(err, UpgradeError::RestartNotExclusive { .. }),
5059 "restart-mixed must surface before the ordering gate, got {err:?}"
5060 );
5061 }
5062
5063 // ── within-entry purge-ordering invariant ──────────────────────────
5064
5065 #[test]
5066 fn validate_rejects_soft_purge_without_load() {
5067 // Fail-before-pass-after pin: `:soft-purge` drains the *old*
5068 // module after the new one is resident (OTP's two-phase code
5069 // load — code:load_module/1 then code:soft_purge/1), so an
5070 // entry that runs it with no preceding `:load-module` drains
5071 // the live module with no replacement. The operator runs
5072 // instructions in declared order, so this is a build error,
5073 // not a runtime surprise (CAIXA-SDLC §III).
5074 let e = entry(
5075 "0.1.0",
5076 vec![UpgradeInstruction::SoftPurge {
5077 module: "x-old".into(),
5078 }],
5079 );
5080 let err = e.validate().unwrap_err();
5081 assert_eq!(
5082 err,
5083 UpgradeError::PurgeWithoutPriorLoad {
5084 from: "0.1.0".into(),
5085 kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
5086 module: "x-old".into(),
5087 },
5088 "a `:soft-purge` with no preceding `:load-module` must surface as \
5089 PurgeWithoutPriorLoad naming the offending entry + kind + module verbatim"
5090 );
5091 }
5092
5093 #[test]
5094 fn validate_rejects_purge_without_load() {
5095 // Per-arm coverage: `:purge` (immediate discard, no drain) is
5096 // the more catastrophic peer of `:soft-purge`; same gate, same
5097 // shape, kind-tag differs so the author can grep their
5098 // caixa.lisp for the offending `(:purge …)` form.
5099 let e = entry(
5100 "0.1.0",
5101 vec![UpgradeInstruction::Purge {
5102 module: "x-old".into(),
5103 }],
5104 );
5105 let err = e.validate().unwrap_err();
5106 assert_eq!(
5107 err,
5108 UpgradeError::PurgeWithoutPriorLoad {
5109 from: "0.1.0".into(),
5110 kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
5111 module: "x-old".into(),
5112 },
5113 );
5114 }
5115
5116 #[test]
5117 fn validate_rejects_soft_purge_before_load() {
5118 // Right-instructions-wrong-order: the load is present but runs
5119 // *after* the purge. Because the operator executes in declared
5120 // order, the cleanup drains the old code before the new code
5121 // is resident — same incoherence as the missing-load case,
5122 // leaving a window during which neither version is available.
5123 let e = entry(
5124 "0.1.0",
5125 vec![
5126 UpgradeInstruction::SoftPurge {
5127 module: "x-old".into(),
5128 },
5129 UpgradeInstruction::LoadModule { module: "x".into() },
5130 ],
5131 );
5132 let err = e.validate().unwrap_err();
5133 assert!(
5134 matches!(
5135 err,
5136 UpgradeError::PurgeWithoutPriorLoad {
5137 kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
5138 ..
5139 }
5140 ),
5141 "a `:soft-purge` ahead of its `:load-module` must surface as \
5142 PurgeWithoutPriorLoad, got {err:?}"
5143 );
5144 }
5145
5146 #[test]
5147 fn validate_rejects_purge_before_load() {
5148 // Symmetric arm on the `:purge` variant — the kind tag
5149 // distinguishes the diagnostic so the author lands on the
5150 // offending form directly.
5151 let e = entry(
5152 "0.1.0",
5153 vec![
5154 UpgradeInstruction::Purge {
5155 module: "x-old".into(),
5156 },
5157 UpgradeInstruction::LoadModule { module: "x".into() },
5158 ],
5159 );
5160 let err = e.validate().unwrap_err();
5161 assert!(
5162 matches!(
5163 err,
5164 UpgradeError::PurgeWithoutPriorLoad {
5165 kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
5166 ..
5167 }
5168 ),
5169 "a `:purge` ahead of its `:load-module` must surface as \
5170 PurgeWithoutPriorLoad, got {err:?}"
5171 );
5172 }
5173
5174 #[test]
5175 fn validate_accepts_soft_purge_after_load() {
5176 // Positive control: the canonical `(:load-module …)
5177 // (:soft-purge …)` order validates. The load need not name the
5178 // same module the purge targets — the cleanup typically targets
5179 // the *old* module name (e.g. `"x-old"`) and the load brings up
5180 // the *new* one (`"x"`); the gate only requires that *some*
5181 // `:load-module` precedes the purge, so the new code is resident
5182 // before the old one is drained.
5183 let e = entry(
5184 "0.1.0",
5185 vec![
5186 UpgradeInstruction::LoadModule { module: "x".into() },
5187 UpgradeInstruction::SoftPurge {
5188 module: "x-old".into(),
5189 },
5190 ],
5191 );
5192 e.validate().unwrap();
5193 }
5194
5195 #[test]
5196 fn validate_accepts_multiple_purges_after_one_load() {
5197 // A single leading `:load-module` covers every subsequent
5198 // `:soft-purge` / `:purge` — the `loaded` latch stays set once
5199 // the new code is resident. Same shape as
5200 // `validate_accepts_multiple_state_changes_after_one_load` on
5201 // the peer ordering gate.
5202 let e = entry(
5203 "0.1.0",
5204 vec![
5205 UpgradeInstruction::LoadModule { module: "x".into() },
5206 UpgradeInstruction::SoftPurge {
5207 module: "x-old".into(),
5208 },
5209 UpgradeInstruction::Purge {
5210 module: "x-oldest".into(),
5211 },
5212 ],
5213 );
5214 e.validate().unwrap();
5215 }
5216
5217 #[test]
5218 fn validate_purge_ordering_fires_after_state_change_ordering() {
5219 // Diagnostic-precedence pin: an entry like `((:state-change …)
5220 // (:soft-purge …))` is *both* state-change-without-load and
5221 // purge-without-load. The state-change gate must win — it's
5222 // the load-bearing semantic on this ordering contract, and
5223 // surfacing the purge diagnostic first would mask the more-
5224 // fundamental migration-against-stale-code defect. Guards the
5225 // call order in `validate` against silent reordering.
5226 let e = entry(
5227 "0.1.0",
5228 vec![
5229 UpgradeInstruction::StateChange {
5230 script: PathBuf::from("lib/m.lisp"),
5231 },
5232 UpgradeInstruction::SoftPurge {
5233 module: "x-old".into(),
5234 },
5235 ],
5236 );
5237 let err = e.validate().unwrap_err();
5238 assert!(
5239 matches!(err, UpgradeError::StateChangeWithoutPriorLoad { .. }),
5240 "state-change-without-load must surface before purge-without-load, got {err:?}"
5241 );
5242 }
5243
5244 #[test]
5245 fn validate_purge_ordering_fires_after_per_instr_shape() {
5246 // Order pin: a malformed `:module` value on a `:soft-purge` (an
5247 // empty string) surfaces its narrower kind-tagged `ModuleEmpty`
5248 // diagnostic *before* the within-entry purge-ordering gate fires.
5249 // The per-instruction shape pass walks the list inline before
5250 // the ordering checks, so the narrower self-locating diagnostic
5251 // surfaces first — mirrors the empty-first cascade on every peer
5252 // DNS-1123 gate and the `validate_restart_exclusive_fires_after_
5253 // per_instr_shape` pin on the sibling ordering gate.
5254 let e = entry(
5255 "0.1.0",
5256 vec![UpgradeInstruction::SoftPurge {
5257 module: String::new(),
5258 }],
5259 );
5260 let err = e.validate().unwrap_err();
5261 assert_eq!(
5262 err,
5263 UpgradeError::ModuleEmpty {
5264 kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE
5265 },
5266 "malformed instruction must surface its kind-tagged diagnostic before the \
5267 purge-ordering gate fires, got {err:?}"
5268 );
5269 }
5270
5271 #[test]
5272 fn validate_purge_ordering_threads_through_validate_upgrade_from() {
5273 // The whole-list entry-point surfaces the per-entry ordering
5274 // error (mirrors
5275 // `validate_state_change_ordering_threads_through_validate_upgrade_from`):
5276 // the gate is reachable from the LayoutInvariants call site, not
5277 // only from a direct `entry.validate()`.
5278 let entries = vec![entry(
5279 "0.1.0",
5280 vec![UpgradeInstruction::Purge {
5281 module: "x-old".into(),
5282 }],
5283 )];
5284 let err = validate_upgrade_from(&entries).unwrap_err();
5285 assert!(
5286 matches!(
5287 err,
5288 UpgradeError::PurgeWithoutPriorLoad {
5289 kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
5290 ..
5291 }
5292 ),
5293 "validate_upgrade_from must thread the purge-ordering error, got {err:?}"
5294 );
5295 }
5296
5297 #[test]
5298 fn validate_state_change_ordering_threads_through_validate_upgrade_from() {
5299 // The whole-list entry-point surfaces the per-entry ordering
5300 // error (mirrors `validate_restart_exclusive_threads_through_…`):
5301 // the gate is reachable from the LayoutInvariants call site, not
5302 // only from a direct `entry.validate()`.
5303 let entries = vec![entry(
5304 "0.1.0",
5305 vec![UpgradeInstruction::StateChange {
5306 script: PathBuf::from("lib/m.lisp"),
5307 }],
5308 )];
5309 let err = validate_upgrade_from(&entries).unwrap_err();
5310 assert!(
5311 matches!(err, UpgradeError::StateChangeWithoutPriorLoad { .. }),
5312 "validate_upgrade_from must thread the ordering error, got {err:?}"
5313 );
5314 }
5315
5316 // ── within-entry cleanup-singularity invariant ─────────────────────
5317
5318 #[test]
5319 fn validate_rejects_duplicate_soft_purge_for_same_module() {
5320 // Fail-before-pass-after pin: `:soft-purge` drains-then-GCs
5321 // its target module (code:soft_purge/1 analog); after the
5322 // first the module is gone, so a second `:soft-purge` of the
5323 // same module is at best a no-op and at worst undefined
5324 // (depending on the operator's handling of a non-resident-
5325 // module purge). Author one cleanup per module.
5326 let e = entry(
5327 "0.1.0",
5328 vec![
5329 UpgradeInstruction::LoadModule { module: "x".into() },
5330 UpgradeInstruction::SoftPurge {
5331 module: "x-old".into(),
5332 },
5333 UpgradeInstruction::SoftPurge {
5334 module: "x-old".into(),
5335 },
5336 ],
5337 );
5338 let err = e.validate().unwrap_err();
5339 assert_eq!(
5340 err,
5341 UpgradeError::DuplicateCleanup {
5342 from: "0.1.0".into(),
5343 module: "x-old".into(),
5344 kinds: vec![
5345 crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
5346 crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
5347 ],
5348 },
5349 "two `:soft-purge` of the same module must surface as DuplicateCleanup naming the \
5350 module + both kinds in declaration order, got {err:?}"
5351 );
5352 }
5353
5354 #[test]
5355 fn validate_rejects_duplicate_purge_for_same_module() {
5356 // Per-arm coverage: `:purge` (immediate discard, no drain) is
5357 // the more catastrophic peer of `:soft-purge`; same gate, same
5358 // shape, kind-tag distinguishes so the author can grep their
5359 // caixa.lisp for the offending `(:purge …)` form.
5360 let e = entry(
5361 "0.1.0",
5362 vec![
5363 UpgradeInstruction::LoadModule { module: "x".into() },
5364 UpgradeInstruction::Purge {
5365 module: "x-old".into(),
5366 },
5367 UpgradeInstruction::Purge {
5368 module: "x-old".into(),
5369 },
5370 ],
5371 );
5372 let err = e.validate().unwrap_err();
5373 assert_eq!(
5374 err,
5375 UpgradeError::DuplicateCleanup {
5376 from: "0.1.0".into(),
5377 module: "x-old".into(),
5378 kinds: vec![
5379 crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
5380 crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
5381 ],
5382 },
5383 );
5384 }
5385
5386 #[test]
5387 fn validate_rejects_soft_purge_then_purge_for_same_module() {
5388 // Soft-then-hard footgun: the author wrote "drain, and if
5389 // drain doesn't clean up, force-discard", but the operator
5390 // runs declared instructions unconditionally — the `:purge`
5391 // fires whether the `:soft-purge` already discarded the
5392 // module or not, so the imagined fallback semantic is
5393 // missing. Fallback on cleanup failure is the operator's
5394 // job, not authored into the entry. Both kinds carry in
5395 // declaration order so the author can grep for either side
5396 // and pick one.
5397 let e = entry(
5398 "0.1.0",
5399 vec![
5400 UpgradeInstruction::LoadModule { module: "x".into() },
5401 UpgradeInstruction::SoftPurge {
5402 module: "x-old".into(),
5403 },
5404 UpgradeInstruction::Purge {
5405 module: "x-old".into(),
5406 },
5407 ],
5408 );
5409 let err = e.validate().unwrap_err();
5410 assert_eq!(
5411 err,
5412 UpgradeError::DuplicateCleanup {
5413 from: "0.1.0".into(),
5414 module: "x-old".into(),
5415 kinds: vec![
5416 crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
5417 crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
5418 ],
5419 },
5420 );
5421 }
5422
5423 #[test]
5424 fn validate_rejects_purge_then_soft_purge_for_same_module() {
5425 // Reversed-ordering arm: `:purge` discards immediately; the
5426 // trailing `:soft-purge` has no module to drain. The kinds
5427 // list reflects declaration order so the diagnostic locates
5428 // both forms in the source.
5429 let e = entry(
5430 "0.1.0",
5431 vec![
5432 UpgradeInstruction::LoadModule { module: "x".into() },
5433 UpgradeInstruction::Purge {
5434 module: "x-old".into(),
5435 },
5436 UpgradeInstruction::SoftPurge {
5437 module: "x-old".into(),
5438 },
5439 ],
5440 );
5441 let err = e.validate().unwrap_err();
5442 assert_eq!(
5443 err,
5444 UpgradeError::DuplicateCleanup {
5445 from: "0.1.0".into(),
5446 module: "x-old".into(),
5447 kinds: vec![
5448 crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
5449 crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
5450 ],
5451 },
5452 );
5453 }
5454
5455 #[test]
5456 fn validate_accepts_distinct_cleanup_modules() {
5457 // Positive control: `:soft-purge` and `:purge` on *different*
5458 // modules pass the gate. Mirrors
5459 // `validate_accepts_multiple_purges_after_one_load` — the
5460 // cleanup-singularity gate is keyed on (module), not on
5461 // (kind, module) pair, so distinct old-version names render
5462 // distinct cleanup targets and don't collide. Sweep both
5463 // same-class (two `:soft-purge` distinct modules) and cross-
5464 // class (`:soft-purge` then `:purge` distinct modules) so a
5465 // future tighten to a kind-only key (which would over-fire on
5466 // distinct modules) surfaces here.
5467 let two_soft = entry(
5468 "0.1.0",
5469 vec![
5470 UpgradeInstruction::LoadModule { module: "x".into() },
5471 UpgradeInstruction::SoftPurge {
5472 module: "x-old".into(),
5473 },
5474 UpgradeInstruction::SoftPurge {
5475 module: "x-older".into(),
5476 },
5477 ],
5478 );
5479 two_soft.validate().unwrap();
5480 let mixed = entry(
5481 "0.1.0",
5482 vec![
5483 UpgradeInstruction::LoadModule { module: "x".into() },
5484 UpgradeInstruction::SoftPurge {
5485 module: "x-old".into(),
5486 },
5487 UpgradeInstruction::Purge {
5488 module: "x-oldest".into(),
5489 },
5490 ],
5491 );
5492 mixed.validate().unwrap();
5493 }
5494
5495 #[test]
5496 fn validate_accepts_single_cleanup_per_module() {
5497 // Boundary control: a list with exactly one `:soft-purge` and
5498 // one `:purge` (distinct modules, the canonical "drain one,
5499 // hard-discard the other" shape) is the gate's identity
5500 // element. Pin so a future off-by-one in the duplicate-detection
5501 // scan doesn't accidentally flag a single occurrence as
5502 // duplicating itself — mirrors
5503 // `validate_upgrade_from_single_entry_never_duplicates` on
5504 // the peer cross-entry duplicate axis.
5505 let e = entry(
5506 "0.1.0",
5507 vec![
5508 UpgradeInstruction::LoadModule { module: "x".into() },
5509 UpgradeInstruction::SoftPurge {
5510 module: "x-old".into(),
5511 },
5512 UpgradeInstruction::Purge {
5513 module: "y-old".into(),
5514 },
5515 ],
5516 );
5517 e.validate().unwrap();
5518 }
5519
5520 #[test]
5521 fn validate_cleanup_singularity_fires_after_purge_ordering() {
5522 // Diagnostic-precedence pin: an entry like `((:soft-purge "x")
5523 // (:soft-purge "x"))` is *both* purge-without-load and
5524 // duplicate-cleanup. The more-fundamental ordering gate must
5525 // win — the missing-load defect is load-bearing (the canonical
5526 // OTP shape requires the new code be resident before any
5527 // cleanup runs), and surfacing the duplicate diagnostic first
5528 // would mask the no-replacement-window defect the ordering
5529 // gate exists to close. Guards the call order in `validate`
5530 // against silent reordering. Same posture as
5531 // `validate_purge_ordering_fires_after_state_change_ordering`
5532 // on the sibling ordering gate.
5533 let e = entry(
5534 "0.1.0",
5535 vec![
5536 UpgradeInstruction::SoftPurge {
5537 module: "x-old".into(),
5538 },
5539 UpgradeInstruction::SoftPurge {
5540 module: "x-old".into(),
5541 },
5542 ],
5543 );
5544 let err = e.validate().unwrap_err();
5545 assert!(
5546 matches!(
5547 err,
5548 UpgradeError::PurgeWithoutPriorLoad {
5549 kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
5550 ..
5551 }
5552 ),
5553 "purge-without-load must surface before duplicate-cleanup, got {err:?}"
5554 );
5555 }
5556
5557 #[test]
5558 fn validate_cleanup_singularity_fires_after_per_instr_shape() {
5559 // Order pin: a malformed `:module` value on a `:soft-purge`
5560 // (an empty string) surfaces its narrower kind-tagged
5561 // `ModuleEmpty` diagnostic *before* the within-entry cleanup-
5562 // singularity gate fires. The per-instruction shape pass walks
5563 // the list inline before the singularity check, so the
5564 // narrower self-locating diagnostic surfaces first — mirrors
5565 // the empty-first cascade on every peer DNS-1123 gate and the
5566 // `validate_purge_ordering_fires_after_per_instr_shape` pin on
5567 // the sibling ordering gate.
5568 //
5569 // Two empty-string `:soft-purge` would *otherwise* duplicate
5570 // (both modules are the same empty string), so this pin
5571 // double-locks the precedence: the per-instr shape gate must
5572 // win on the first malformed instruction before the duplicate
5573 // scan even reaches the second.
5574 let e = entry(
5575 "0.1.0",
5576 vec![
5577 UpgradeInstruction::LoadModule { module: "x".into() },
5578 UpgradeInstruction::SoftPurge {
5579 module: String::new(),
5580 },
5581 UpgradeInstruction::SoftPurge {
5582 module: String::new(),
5583 },
5584 ],
5585 );
5586 let err = e.validate().unwrap_err();
5587 assert_eq!(
5588 err,
5589 UpgradeError::ModuleEmpty {
5590 kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE
5591 },
5592 "malformed instruction must surface its kind-tagged diagnostic before the \
5593 cleanup-singularity gate fires, got {err:?}"
5594 );
5595 }
5596
5597 #[test]
5598 fn validate_cleanup_singularity_reports_first_collision() {
5599 // Determinism pin: with three cleanups of the same module the
5600 // gate reports the *first* collision (the second occurrence)
5601 // and stops — the third's duplicate is masked by the first
5602 // surfaced one. Mirrors
5603 // `validate_upgrade_from_duplicate_diagnostic_names_second_collision`
5604 // on the peer cross-entry duplicate axis.
5605 let e = entry(
5606 "0.1.0",
5607 vec![
5608 UpgradeInstruction::LoadModule { module: "x".into() },
5609 UpgradeInstruction::SoftPurge {
5610 module: "x-old".into(),
5611 },
5612 UpgradeInstruction::SoftPurge {
5613 module: "x-old".into(),
5614 },
5615 UpgradeInstruction::Purge {
5616 module: "x-old".into(),
5617 },
5618 ],
5619 );
5620 let err = e.validate().unwrap_err();
5621 assert_eq!(
5622 err,
5623 UpgradeError::DuplicateCleanup {
5624 from: "0.1.0".into(),
5625 module: "x-old".into(),
5626 kinds: vec![
5627 crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
5628 crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
5629 ],
5630 },
5631 "the first colliding pair must surface, not the later `:purge` collision"
5632 );
5633 }
5634
5635 #[test]
5636 fn validate_cleanup_singularity_threads_through_validate_upgrade_from() {
5637 // The whole-list entry-point surfaces the per-entry singularity
5638 // error (mirrors
5639 // `validate_purge_ordering_threads_through_validate_upgrade_from`):
5640 // the gate is reachable from the LayoutInvariants call site,
5641 // not only from a direct `entry.validate()`.
5642 let entries = vec![entry(
5643 "0.1.0",
5644 vec![
5645 UpgradeInstruction::LoadModule { module: "x".into() },
5646 UpgradeInstruction::SoftPurge {
5647 module: "x-old".into(),
5648 },
5649 UpgradeInstruction::Purge {
5650 module: "x-old".into(),
5651 },
5652 ],
5653 )];
5654 let err = validate_upgrade_from(&entries).unwrap_err();
5655 assert!(
5656 matches!(err, UpgradeError::DuplicateCleanup { .. }),
5657 "validate_upgrade_from must thread the cleanup-singularity error, got {err:?}"
5658 );
5659 }
5660
5661 #[test]
5662 fn validate_rejects_duplicate_load_module_for_same_module() {
5663 // `LoadModule` is the `code:load_module/1` analog (INSPIRATIONS
5664 // §II.4): each module is loaded exactly once per upgrade entry,
5665 // the operator's dispatch table reads the module name to bind
5666 // the wasm component, and a second `(:load-module "x")` re-reads
5667 // the same module name and re-binds the same component — a
5668 // no-op the second time. systools-generated `.relup` files emit
5669 // at most one `load_module` per module per upgrade step for
5670 // this reason. Author one `(:load-module "x")` per old module.
5671 let e = entry(
5672 "0.1.0",
5673 vec![
5674 UpgradeInstruction::LoadModule { module: "x".into() },
5675 UpgradeInstruction::LoadModule { module: "x".into() },
5676 ],
5677 );
5678 let err = e.validate().unwrap_err();
5679 assert_eq!(
5680 err,
5681 UpgradeError::DuplicateLoadModule {
5682 from: "0.1.0".into(),
5683 module: "x".into(),
5684 },
5685 "two `:load-module` of the same module must surface as DuplicateLoadModule naming \
5686 the module, got {err:?}"
5687 );
5688 }
5689
5690 #[test]
5691 fn validate_accepts_distinct_load_modules() {
5692 // Positive control: `:load-module` instructions on *different*
5693 // modules pass the gate. Mirrors
5694 // `validate_accepts_distinct_cleanup_modules` on the sibling
5695 // singularity axis — the load-singularity gate is keyed on
5696 // (module), so distinct module names render distinct load
5697 // targets and don't collide. Sweep both the bare two-load shape
5698 // and the canonical load-pair-with-cleanup shape so a future
5699 // tighten that over-fires on distinct loads surfaces here.
5700 let two_loads = entry(
5701 "0.1.0",
5702 vec![
5703 UpgradeInstruction::LoadModule { module: "x".into() },
5704 UpgradeInstruction::LoadModule { module: "y".into() },
5705 ],
5706 );
5707 two_loads.validate().unwrap();
5708 let with_cleanup = entry(
5709 "0.1.0",
5710 vec![
5711 UpgradeInstruction::LoadModule { module: "x".into() },
5712 UpgradeInstruction::LoadModule { module: "y".into() },
5713 UpgradeInstruction::SoftPurge {
5714 module: "x-old".into(),
5715 },
5716 UpgradeInstruction::SoftPurge {
5717 module: "y-old".into(),
5718 },
5719 ],
5720 );
5721 with_cleanup.validate().unwrap();
5722 }
5723
5724 #[test]
5725 fn validate_accepts_single_load_per_module() {
5726 // Boundary control: a list with exactly one `:load-module`
5727 // followed by the canonical `:state-change` + `:soft-purge`
5728 // sequence (the module-doc OTP shape) is the gate's identity
5729 // element. Pin so a future off-by-one in the duplicate-
5730 // detection scan doesn't accidentally flag a single occurrence
5731 // as duplicating itself — mirrors
5732 // `validate_accepts_single_cleanup_per_module` on the sibling
5733 // singularity axis.
5734 let e = entry(
5735 "0.1.0",
5736 vec![
5737 UpgradeInstruction::LoadModule { module: "x".into() },
5738 UpgradeInstruction::StateChange {
5739 script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
5740 },
5741 UpgradeInstruction::SoftPurge {
5742 module: "x-old".into(),
5743 },
5744 ],
5745 );
5746 e.validate().unwrap();
5747 }
5748
5749 #[test]
5750 fn validate_load_singularity_fires_after_state_change_ordering() {
5751 // Diagnostic-precedence pin: an entry like `((:state-change
5752 // "m.lisp") (:load-module "x") (:load-module "x"))` is *both*
5753 // state-change-without-load and duplicate-load. The more-
5754 // fundamental ordering gate must win — the missing-load defect
5755 // is load-bearing (the migration runs against unloaded code),
5756 // and surfacing the duplicate diagnostic first would mask the
5757 // migrate-into-unloaded-code defect the ordering gate exists
5758 // to close. Guards the call order in `validate` against silent
5759 // reordering. Same posture as
5760 // `validate_cleanup_singularity_fires_after_purge_ordering`
5761 // on the sibling singularity gate.
5762 let e = entry(
5763 "0.1.0",
5764 vec![
5765 UpgradeInstruction::StateChange {
5766 script: PathBuf::from("lib/m.lisp"),
5767 },
5768 UpgradeInstruction::LoadModule { module: "x".into() },
5769 UpgradeInstruction::LoadModule { module: "x".into() },
5770 ],
5771 );
5772 let err = e.validate().unwrap_err();
5773 assert!(
5774 matches!(err, UpgradeError::StateChangeWithoutPriorLoad { .. }),
5775 "state-change-without-load must surface before duplicate-load, got {err:?}"
5776 );
5777 }
5778
5779 #[test]
5780 fn validate_load_singularity_fires_after_purge_ordering() {
5781 // Diagnostic-precedence pin: an entry like `((:soft-purge
5782 // "x-old") (:load-module "x") (:load-module "x"))` is *both*
5783 // purge-without-load and duplicate-load. The more-fundamental
5784 // ordering gate must win — the missing-load defect is load-
5785 // bearing (the cleanup runs against no-replacement-window),
5786 // and surfacing the duplicate diagnostic first would mask the
5787 // drain-to-nothing defect the ordering gate exists to close.
5788 // Sibling of
5789 // `validate_cleanup_singularity_fires_after_purge_ordering` on
5790 // the load-singularity axis.
5791 let e = entry(
5792 "0.1.0",
5793 vec![
5794 UpgradeInstruction::SoftPurge {
5795 module: "x-old".into(),
5796 },
5797 UpgradeInstruction::LoadModule { module: "x".into() },
5798 UpgradeInstruction::LoadModule { module: "x".into() },
5799 ],
5800 );
5801 let err = e.validate().unwrap_err();
5802 assert!(
5803 matches!(
5804 err,
5805 UpgradeError::PurgeWithoutPriorLoad {
5806 kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
5807 ..
5808 }
5809 ),
5810 "purge-without-load must surface before duplicate-load, got {err:?}"
5811 );
5812 }
5813
5814 #[test]
5815 fn validate_load_singularity_fires_after_per_instr_shape() {
5816 // Order pin: a malformed `:module` value on a `:load-module`
5817 // (an empty string) surfaces its narrower kind-tagged
5818 // `ModuleEmpty` diagnostic *before* the within-entry load-
5819 // singularity gate fires. The per-instruction shape pass walks
5820 // the list inline before the singularity check, so the
5821 // narrower self-locating diagnostic surfaces first — mirrors
5822 // the empty-first cascade on every peer DNS-1123 gate and the
5823 // `validate_cleanup_singularity_fires_after_per_instr_shape`
5824 // pin on the sibling singularity gate.
5825 //
5826 // Two empty-string `:load-module` would *otherwise* duplicate
5827 // (both modules are the same empty string), so this pin
5828 // double-locks the precedence: the per-instr shape gate must
5829 // win on the first malformed instruction before the duplicate
5830 // scan even reaches the second.
5831 let e = entry(
5832 "0.1.0",
5833 vec![
5834 UpgradeInstruction::LoadModule {
5835 module: String::new(),
5836 },
5837 UpgradeInstruction::LoadModule {
5838 module: String::new(),
5839 },
5840 ],
5841 );
5842 let err = e.validate().unwrap_err();
5843 assert_eq!(
5844 err,
5845 UpgradeError::ModuleEmpty {
5846 kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE,
5847 },
5848 "malformed instruction must surface its kind-tagged diagnostic before the \
5849 load-singularity gate fires, got {err:?}"
5850 );
5851 }
5852
5853 #[test]
5854 fn validate_load_singularity_fires_before_cleanup_singularity() {
5855 // Diagnostic-precedence pin: an entry that violates *both*
5856 // singularities — duplicate load on "x" *and* duplicate cleanup
5857 // on "y-old" — must surface the load-side diagnostic first.
5858 // The load axis precedes the cleanup axis in the canonical OTP
5859 // sequence (`code:load_module/1` then `code:soft_purge/1`) and
5860 // in [`UpgradeInstruction`] declaration order (LoadModule
5861 // before SoftPurge/Purge), so the load-side singularity is the
5862 // load-bearing diagnostic when both fire — the cleanup-side
5863 // duplicate is meaningless either way without a coherent load.
5864 // Guards the call order in `validate`: `validate_load_singularity`
5865 // runs before `validate_cleanup_singularity`.
5866 let e = entry(
5867 "0.1.0",
5868 vec![
5869 UpgradeInstruction::LoadModule { module: "x".into() },
5870 UpgradeInstruction::LoadModule { module: "x".into() },
5871 UpgradeInstruction::SoftPurge {
5872 module: "y-old".into(),
5873 },
5874 UpgradeInstruction::SoftPurge {
5875 module: "y-old".into(),
5876 },
5877 ],
5878 );
5879 let err = e.validate().unwrap_err();
5880 assert_eq!(
5881 err,
5882 UpgradeError::DuplicateLoadModule {
5883 from: "0.1.0".into(),
5884 module: "x".into(),
5885 },
5886 "duplicate-load must surface before duplicate-cleanup, got {err:?}"
5887 );
5888 }
5889
5890 #[test]
5891 fn validate_load_singularity_reports_first_collision() {
5892 // Determinism pin: with three loads of the same module the gate
5893 // reports the *first* collision (the second occurrence) and
5894 // stops — the third's duplicate is masked by the first surfaced
5895 // one. Mirrors
5896 // `validate_cleanup_singularity_reports_first_collision` on the
5897 // sibling singularity axis and every peer duplicate gate's
5898 // first-collision discipline.
5899 let e = entry(
5900 "0.1.0",
5901 vec![
5902 UpgradeInstruction::LoadModule { module: "x".into() },
5903 UpgradeInstruction::LoadModule { module: "x".into() },
5904 UpgradeInstruction::LoadModule { module: "x".into() },
5905 ],
5906 );
5907 let err = e.validate().unwrap_err();
5908 assert_eq!(
5909 err,
5910 UpgradeError::DuplicateLoadModule {
5911 from: "0.1.0".into(),
5912 module: "x".into(),
5913 },
5914 "the first colliding occurrence must surface, not the later third-load collision"
5915 );
5916 }
5917
5918 #[test]
5919 fn validate_load_singularity_threads_through_validate_upgrade_from() {
5920 // The whole-list entry-point surfaces the per-entry singularity
5921 // error (mirrors
5922 // `validate_cleanup_singularity_threads_through_validate_upgrade_from`):
5923 // the gate is reachable from the LayoutInvariants call site,
5924 // not only from a direct `entry.validate()`.
5925 let entries = vec![entry(
5926 "0.1.0",
5927 vec![
5928 UpgradeInstruction::LoadModule { module: "x".into() },
5929 UpgradeInstruction::LoadModule { module: "x".into() },
5930 ],
5931 )];
5932 let err = validate_upgrade_from(&entries).unwrap_err();
5933 assert!(
5934 matches!(err, UpgradeError::DuplicateLoadModule { .. }),
5935 "validate_upgrade_from must thread the load-singularity error, got {err:?}"
5936 );
5937 }
5938
5939 // ── within-entry state-change-singularity invariant ────────────────
5940
5941 #[test]
5942 fn validate_rejects_duplicate_state_change_for_same_script() {
5943 // `StateChange` is the `gen_server:code_change/3` analog
5944 // (INSPIRATIONS §II.4): the script folds the prior-version
5945 // state shape into the current-version shape — a one-shot
5946 // transition, not a step that composes with itself. OTP's
5947 // release_handler invokes `code_change/3` exactly once per
5948 // upgrade per gen_server; systools-generated `.relup` files
5949 // emit at most one `code_change` per gen_server per upgrade
5950 // step for this reason. A second `(:state-change "m.lisp")`
5951 // re-runs the same fold on the already-migrated state — at
5952 // best a no-op and at worst silent state corruption from
5953 // double-applied non-idempotent transforms (`add column`,
5954 // `increment counter`, `rename field`). Author one
5955 // `(:state-change "m.lisp")` per migration script per entry.
5956 let e = entry(
5957 "0.1.0",
5958 vec![
5959 UpgradeInstruction::LoadModule { module: "x".into() },
5960 UpgradeInstruction::StateChange {
5961 script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
5962 },
5963 UpgradeInstruction::StateChange {
5964 script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
5965 },
5966 ],
5967 );
5968 let err = e.validate().unwrap_err();
5969 assert_eq!(
5970 err,
5971 UpgradeError::DuplicateStateChange {
5972 from: "0.1.0".into(),
5973 script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
5974 },
5975 "two `:state-change` of the same script must surface as DuplicateStateChange naming \
5976 the script, got {err:?}"
5977 );
5978 }
5979
5980 #[test]
5981 fn validate_accepts_distinct_state_change_scripts() {
5982 // Positive control: `:state-change` instructions on *different*
5983 // scripts pass the gate. Mirrors
5984 // `validate_accepts_distinct_cleanup_modules` /
5985 // `validate_accepts_distinct_load_modules` on the sibling
5986 // singularity axes — the state-change-singularity gate is keyed
5987 // on the script PathBuf, so distinct scripts render distinct
5988 // migration targets and don't collide. Sweep both the bare two-
5989 // migration shape and the canonical load-pair-with-cleanup shape
5990 // so a future tighten that over-fires on distinct scripts
5991 // surfaces here. This positive control is the gate-level peer of
5992 // `validate_accepts_multiple_state_changes_after_one_load` (the
5993 // ordering-gate positive control on distinct scripts), pinned
5994 // here independently so a future refactor that decouples the
5995 // gates can't accidentally drop coverage on either.
5996 let two_migrations = entry(
5997 "0.1.0",
5998 vec![
5999 UpgradeInstruction::LoadModule { module: "x".into() },
6000 UpgradeInstruction::StateChange {
6001 script: PathBuf::from("lib/m1.lisp"),
6002 },
6003 UpgradeInstruction::StateChange {
6004 script: PathBuf::from("lib/m2.lisp"),
6005 },
6006 ],
6007 );
6008 two_migrations.validate().unwrap();
6009 let with_cleanup = entry(
6010 "0.1.0",
6011 vec![
6012 UpgradeInstruction::LoadModule { module: "x".into() },
6013 UpgradeInstruction::StateChange {
6014 script: PathBuf::from("lib/m1.lisp"),
6015 },
6016 UpgradeInstruction::StateChange {
6017 script: PathBuf::from("lib/m2.lisp"),
6018 },
6019 UpgradeInstruction::SoftPurge {
6020 module: "x-old".into(),
6021 },
6022 ],
6023 );
6024 with_cleanup.validate().unwrap();
6025 }
6026
6027 #[test]
6028 fn validate_accepts_single_state_change_per_script() {
6029 // Boundary control: a list with exactly one `:state-change`
6030 // wrapped by the canonical `:load-module` + `:soft-purge`
6031 // sequence (the module-doc OTP shape) is the gate's identity
6032 // element. Pin so a future off-by-one in the duplicate-
6033 // detection scan doesn't accidentally flag a single occurrence
6034 // as duplicating itself — mirrors
6035 // `validate_accepts_single_load_per_module` /
6036 // `validate_accepts_single_cleanup_per_module` on the sibling
6037 // singularity axes.
6038 let e = entry(
6039 "0.1.0",
6040 vec![
6041 UpgradeInstruction::LoadModule { module: "x".into() },
6042 UpgradeInstruction::StateChange {
6043 script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
6044 },
6045 UpgradeInstruction::SoftPurge {
6046 module: "x-old".into(),
6047 },
6048 ],
6049 );
6050 e.validate().unwrap();
6051 }
6052
6053 #[test]
6054 fn validate_state_change_singularity_fires_after_state_change_ordering() {
6055 // Diagnostic-precedence pin: an entry like `((:state-change
6056 // "m.lisp") (:state-change "m.lisp"))` is *both* state-change-
6057 // without-load and duplicate-state-change. The more-fundamental
6058 // ordering gate must win — the missing-load defect is load-
6059 // bearing (the migration runs against unloaded code), and
6060 // surfacing the duplicate diagnostic first would mask the
6061 // migrate-into-unloaded-code defect the ordering gate exists to
6062 // close. Guards the call order in `validate` against silent
6063 // reordering. Same posture as
6064 // `validate_load_singularity_fires_after_state_change_ordering`
6065 // on the sibling singularity gate.
6066 //
6067 // Two same-script `:state-change` would *otherwise* duplicate
6068 // (both scripts collide on the very first `:state-change`-
6069 // without-load encountered), so this pin double-locks the
6070 // precedence: the ordering gate must win on the first un-loaded
6071 // `:state-change` before the singularity scan even reaches the
6072 // second.
6073 let e = entry(
6074 "0.1.0",
6075 vec![
6076 UpgradeInstruction::StateChange {
6077 script: PathBuf::from("lib/m.lisp"),
6078 },
6079 UpgradeInstruction::StateChange {
6080 script: PathBuf::from("lib/m.lisp"),
6081 },
6082 ],
6083 );
6084 let err = e.validate().unwrap_err();
6085 assert!(
6086 matches!(err, UpgradeError::StateChangeWithoutPriorLoad { .. }),
6087 "state-change-without-load must surface before duplicate-state-change, got {err:?}"
6088 );
6089 }
6090
6091 #[test]
6092 fn validate_state_change_singularity_fires_after_purge_ordering() {
6093 // Diagnostic-precedence pin: an entry like `((:soft-purge
6094 // "x-old") (:load-module "x") (:state-change "m.lisp")
6095 // (:state-change "m.lisp"))` is *both* purge-without-load and
6096 // duplicate-state-change. The more-fundamental ordering gate
6097 // must win — the missing-load defect (a cleanup that drains the
6098 // only resident version to nothing) is load-bearing, and
6099 // surfacing the duplicate diagnostic first would mask the
6100 // drain-to-nothing defect the ordering gate exists to close.
6101 // Sibling of `validate_load_singularity_fires_after_purge_ordering`
6102 // on the state-change-singularity axis.
6103 let e = entry(
6104 "0.1.0",
6105 vec![
6106 UpgradeInstruction::SoftPurge {
6107 module: "x-old".into(),
6108 },
6109 UpgradeInstruction::LoadModule { module: "x".into() },
6110 UpgradeInstruction::StateChange {
6111 script: PathBuf::from("lib/m.lisp"),
6112 },
6113 UpgradeInstruction::StateChange {
6114 script: PathBuf::from("lib/m.lisp"),
6115 },
6116 ],
6117 );
6118 let err = e.validate().unwrap_err();
6119 assert!(
6120 matches!(
6121 err,
6122 UpgradeError::PurgeWithoutPriorLoad {
6123 kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
6124 ..
6125 }
6126 ),
6127 "purge-without-load must surface before duplicate-state-change, got {err:?}"
6128 );
6129 }
6130
6131 #[test]
6132 fn validate_state_change_singularity_fires_after_per_instr_shape() {
6133 // Order pin: a malformed `:script` value on a `:state-change`
6134 // (an empty path) surfaces its narrower `EmptyScript` diagnostic
6135 // *before* the within-entry state-change-singularity gate fires.
6136 // The per-instruction shape pass walks the list inline before
6137 // the singularity check, so the narrower self-locating
6138 // diagnostic surfaces first — mirrors the empty-first cascade on
6139 // every peer path-shape gate and the
6140 // `validate_load_singularity_fires_after_per_instr_shape` /
6141 // `validate_cleanup_singularity_fires_after_per_instr_shape`
6142 // pins on the sibling singularity gates.
6143 //
6144 // Two empty-path `:state-change` would *otherwise* duplicate
6145 // (both scripts are the same empty PathBuf), so this pin double-
6146 // locks the precedence: the per-instr shape gate must win on the
6147 // first malformed instruction before the duplicate scan even
6148 // reaches the second.
6149 let e = entry(
6150 "0.1.0",
6151 vec![
6152 UpgradeInstruction::LoadModule { module: "x".into() },
6153 UpgradeInstruction::StateChange {
6154 script: PathBuf::new(),
6155 },
6156 UpgradeInstruction::StateChange {
6157 script: PathBuf::new(),
6158 },
6159 ],
6160 );
6161 let err = e.validate().unwrap_err();
6162 assert_eq!(
6163 err,
6164 UpgradeError::EmptyScript,
6165 "malformed instruction must surface its narrower diagnostic before the \
6166 state-change-singularity gate fires, got {err:?}"
6167 );
6168 }
6169
6170 #[test]
6171 fn validate_state_change_singularity_fires_after_load_singularity() {
6172 // Diagnostic-precedence pin: an entry that violates *both*
6173 // singularities — duplicate load on "x" *and* duplicate
6174 // state-change on "m.lisp" — must surface the load-side
6175 // diagnostic first. The load axis precedes the migration axis
6176 // in the canonical OTP sequence (`code:load_module/1` then
6177 // `gen_server:code_change/3`) and in [`UpgradeInstruction`]
6178 // declaration order (LoadModule before StateChange), so the
6179 // load-side singularity is the load-bearing diagnostic when
6180 // both fire — the migration-side duplicate is meaningless
6181 // either way without a coherent load. Guards the call order in
6182 // `validate`: `validate_load_singularity` runs before
6183 // `validate_state_change_singularity`.
6184 let e = entry(
6185 "0.1.0",
6186 vec![
6187 UpgradeInstruction::LoadModule { module: "x".into() },
6188 UpgradeInstruction::LoadModule { module: "x".into() },
6189 UpgradeInstruction::StateChange {
6190 script: PathBuf::from("lib/m.lisp"),
6191 },
6192 UpgradeInstruction::StateChange {
6193 script: PathBuf::from("lib/m.lisp"),
6194 },
6195 ],
6196 );
6197 let err = e.validate().unwrap_err();
6198 assert_eq!(
6199 err,
6200 UpgradeError::DuplicateLoadModule {
6201 from: "0.1.0".into(),
6202 module: "x".into(),
6203 },
6204 "duplicate-load must surface before duplicate-state-change, got {err:?}"
6205 );
6206 }
6207
6208 #[test]
6209 fn validate_state_change_singularity_fires_before_cleanup_singularity() {
6210 // Diagnostic-precedence pin: an entry that violates *both*
6211 // singularities — duplicate state-change on "m.lisp" *and*
6212 // duplicate cleanup on "y-old" — must surface the migration-
6213 // side diagnostic first. The migration axis precedes the
6214 // cleanup axis in the canonical OTP sequence
6215 // (`gen_server:code_change/3` then `code:soft_purge/1`) and in
6216 // [`UpgradeInstruction`] declaration order (StateChange before
6217 // SoftPurge/Purge), so the migration-side singularity is the
6218 // load-bearing diagnostic when both fire — the cleanup-side
6219 // duplicate is irrelevant once the migration has corrupted
6220 // state by double-applying. Guards the call order in
6221 // `validate`: `validate_state_change_singularity` runs before
6222 // `validate_cleanup_singularity`.
6223 let e = entry(
6224 "0.1.0",
6225 vec![
6226 UpgradeInstruction::LoadModule { module: "x".into() },
6227 UpgradeInstruction::StateChange {
6228 script: PathBuf::from("lib/m.lisp"),
6229 },
6230 UpgradeInstruction::StateChange {
6231 script: PathBuf::from("lib/m.lisp"),
6232 },
6233 UpgradeInstruction::SoftPurge {
6234 module: "y-old".into(),
6235 },
6236 UpgradeInstruction::SoftPurge {
6237 module: "y-old".into(),
6238 },
6239 ],
6240 );
6241 let err = e.validate().unwrap_err();
6242 assert_eq!(
6243 err,
6244 UpgradeError::DuplicateStateChange {
6245 from: "0.1.0".into(),
6246 script: PathBuf::from("lib/m.lisp"),
6247 },
6248 "duplicate-state-change must surface before duplicate-cleanup, got {err:?}"
6249 );
6250 }
6251
6252 #[test]
6253 fn validate_state_change_singularity_reports_first_collision() {
6254 // Determinism pin: with three state-changes on the same script
6255 // the gate reports the *first* collision (the second
6256 // occurrence) and stops — the third's duplicate is masked by
6257 // the first surfaced one. Mirrors
6258 // `validate_load_singularity_reports_first_collision` /
6259 // `validate_cleanup_singularity_reports_first_collision` on the
6260 // sibling singularity axes and every peer duplicate gate's
6261 // first-collision discipline.
6262 let e = entry(
6263 "0.1.0",
6264 vec![
6265 UpgradeInstruction::LoadModule { module: "x".into() },
6266 UpgradeInstruction::StateChange {
6267 script: PathBuf::from("lib/m.lisp"),
6268 },
6269 UpgradeInstruction::StateChange {
6270 script: PathBuf::from("lib/m.lisp"),
6271 },
6272 UpgradeInstruction::StateChange {
6273 script: PathBuf::from("lib/m.lisp"),
6274 },
6275 ],
6276 );
6277 let err = e.validate().unwrap_err();
6278 assert_eq!(
6279 err,
6280 UpgradeError::DuplicateStateChange {
6281 from: "0.1.0".into(),
6282 script: PathBuf::from("lib/m.lisp"),
6283 },
6284 "the first colliding occurrence must surface, not the later third-migration collision"
6285 );
6286 }
6287
6288 #[test]
6289 fn validate_state_change_singularity_threads_through_validate_upgrade_from() {
6290 // The whole-list entry-point surfaces the per-entry singularity
6291 // error (mirrors
6292 // `validate_load_singularity_threads_through_validate_upgrade_from`
6293 // / `validate_cleanup_singularity_threads_through_validate_upgrade_from`):
6294 // the gate is reachable from the LayoutInvariants call site,
6295 // not only from a direct `entry.validate()`.
6296 let entries = vec![entry(
6297 "0.1.0",
6298 vec![
6299 UpgradeInstruction::LoadModule { module: "x".into() },
6300 UpgradeInstruction::StateChange {
6301 script: PathBuf::from("lib/m.lisp"),
6302 },
6303 UpgradeInstruction::StateChange {
6304 script: PathBuf::from("lib/m.lisp"),
6305 },
6306 ],
6307 )];
6308 let err = validate_upgrade_from(&entries).unwrap_err();
6309 assert!(
6310 matches!(err, UpgradeError::DuplicateStateChange { .. }),
6311 "validate_upgrade_from must thread the state-change-singularity error, got {err:?}"
6312 );
6313 }
6314
6315 #[test]
6316 fn validate_state_change_singularity_projects_scripts_through_declared_path_accessor() {
6317 // Composition pin: [`UpgradeFromEntry::validate_state_change_singularity`]'s
6318 // per-instruction `StateChange`-arm script-path projection must
6319 // route through the sibling lifted
6320 // [`UpgradeInstruction::declared_path`] `Option<&PathBuf>`
6321 // accessor, not the raw
6322 // `match instr { UpgradeInstruction::StateChange { script } =>
6323 // script.as_path(), _ => continue }` open-coded pattern-match
6324 // the gate previously carried.
6325 //
6326 // Structurally: the gate's projection accept-set is the union
6327 // of every [`UpgradeInstruction`] variant for which
6328 // `declared_path().is_some()` — today exactly
6329 // [`UpgradeInstruction::StateChange`] per the sibling
6330 // `declared_path_only_for_state_change` pin, so a
6331 // duplicate-scripts input trips `DuplicateStateChange` and a
6332 // non-`StateChange` input (module-bearing / terminal) leaves
6333 // `seen` empty and the gate returns `Ok(())` byte-identical to
6334 // the pattern-match shape.
6335 //
6336 // Byte-equal today (`declared_path` returns `Some(script)` iff
6337 // `StateChange`, byte-for-byte from the variant's own storage);
6338 // the pin catches any future accessor extension that promotes
6339 // an additional variant onto the `PathBuf`-carrying axis — the
6340 // gate then fires on duplicate scripts from that variant too,
6341 // and the singularity discipline the sibling
6342 // `validate_load_singularity` / `validate_cleanup_singularity`
6343 // gates share on the `String`-carrying axis's per-variant
6344 // consumers extends to the promoted variant by construction.
6345 //
6346 // Peer of the sibling four per-`UpgradeInstruction` consumers
6347 // ([`UpgradeInstruction::validate`]'s per-`StateChange`
6348 // sandbox-path fan-out, the layout-side per-`StateChange`
6349 // script-existence fan-out at
6350 // `caixa-core/src/layout.rs:1017`, the cross-slot
6351 // [`validate_upgrade_from_against_behavior`] gate's per-
6352 // `StateChange` detection loop, the peer
6353 // [`UpgradeInstruction::declared_module`] `String`-axis
6354 // per-variant unifier) — this gate now shares one typed
6355 // dispatch on the substrate primitive's `PathBuf`-carrying
6356 // axis with those consumers, so a future rebrand on the axis
6357 // migrates as a single caixa-core edit rather than a
6358 // coordinated rewrite of five call sites.
6359 //
6360 // Three-arm projective coverage:
6361 // (a) `StateChange` scripts project through `declared_path()`
6362 // byte-equal to the raw `script.as_path()` field access;
6363 // (b) a duplicate-`StateChange` input trips the gate on the
6364 // second occurrence with `DuplicateStateChange` carrying
6365 // the offending script verbatim;
6366 // (c) a non-`StateChange`-only input (`LoadModule` /
6367 // `SoftPurge` / `Purge` / `Restart`) leaves the gate
6368 // vacuous with `Ok(())` — the `declared_path().is_none()`
6369 // arm's `continue` fall-through pins.
6370 //
6371 // Fail-before-pass-after verified locally: swapping the
6372 // production `let Some(script) = instr.declared_path() else {
6373 // continue };` back to `let script = match instr {
6374 // UpgradeInstruction::StateChange { script } =>
6375 // script.as_path(), _ => continue, };` keeps arms (a)-(c)
6376 // passing but silently detaches the gate from the accessor's
6377 // typed dispatch — any future `declared_path` extension
6378 // (promotion of an additional variant onto the axis, an
6379 // operator-side pre-resolved-path cache the accessor
6380 // materializes) would then silently disagree between this
6381 // gate's raw pattern-match and the peer four sibling consumers
6382 // that route through the accessor.
6383 use std::path::PathBuf;
6384
6385 // (a) StateChange projection byte-equal via declared_path.
6386 let sc = UpgradeInstruction::StateChange {
6387 script: PathBuf::from("lib/m.lisp"),
6388 };
6389 assert_eq!(
6390 sc.declared_path().map(std::path::PathBuf::as_path),
6391 Some(PathBuf::from("lib/m.lisp").as_path()),
6392 "declared_path() must project the StateChange :script byte-equal to the raw \
6393 field access — accessor divergence would silently detach the gate from the \
6394 projection every peer per-`UpgradeInstruction` consumer routes through"
6395 );
6396
6397 // (b) Duplicate-StateChange input trips the gate.
6398 let dup = entry(
6399 "0.1.0",
6400 vec![
6401 UpgradeInstruction::LoadModule { module: "x".into() },
6402 UpgradeInstruction::StateChange {
6403 script: PathBuf::from("lib/m.lisp"),
6404 },
6405 UpgradeInstruction::StateChange {
6406 script: PathBuf::from("lib/m.lisp"),
6407 },
6408 ],
6409 );
6410 assert_eq!(
6411 dup.validate_state_change_singularity(),
6412 Err(UpgradeError::DuplicateStateChange {
6413 from: "0.1.0".into(),
6414 script: PathBuf::from("lib/m.lisp"),
6415 }),
6416 "duplicate StateChange scripts must trip the gate on the second occurrence \
6417 through the declared_path accessor's Some(script) arm"
6418 );
6419
6420 // (c) Non-StateChange-only inputs leave the gate vacuous.
6421 for instrs in [
6422 vec![UpgradeInstruction::LoadModule { module: "x".into() }],
6423 vec![
6424 UpgradeInstruction::LoadModule { module: "x".into() },
6425 UpgradeInstruction::SoftPurge {
6426 module: "x-old".into(),
6427 },
6428 ],
6429 vec![
6430 UpgradeInstruction::LoadModule { module: "x".into() },
6431 UpgradeInstruction::Purge {
6432 module: "x-old".into(),
6433 },
6434 ],
6435 vec![UpgradeInstruction::Restart],
6436 ] {
6437 for instr in &instrs {
6438 assert!(
6439 instr.declared_path().is_none(),
6440 "non-StateChange variants must project None through declared_path — \
6441 accessor divergence would let this gate silently fire on a duplicate \
6442 module reference far from any :state-change site"
6443 );
6444 }
6445 let e = entry("0.1.0", instrs);
6446 assert_eq!(
6447 e.validate_state_change_singularity(),
6448 Ok(()),
6449 "the state-change-singularity gate must return Ok(()) on an entry whose \
6450 instructions all project None through declared_path — the accessor's \
6451 continue arm the pattern-match's `_ => continue` previously carried"
6452 );
6453 }
6454 }
6455
6456 // ── within-entry state-change-before-cleanup ordering invariant ──
6457
6458 #[test]
6459 fn validate_rejects_state_change_after_soft_purge() {
6460 // Fail-before-pass-after pin: `:state-change` is the
6461 // gen_server:code_change/3 analog and folds the prior-version
6462 // state shape into the current shape; `:soft-purge` drains the
6463 // prior code. The operator runs instructions in declared order,
6464 // so a `:soft-purge` ahead of a `:state-change` drains the
6465 // prior module before the migration callback runs against the
6466 // state it held — the canonical OTP error mode
6467 // "`code_change/3` invoked on a purged module" the
6468 // release_handler closes by always ordering the migration
6469 // before the cleanup.
6470 let e = entry(
6471 "0.1.0",
6472 vec![
6473 UpgradeInstruction::LoadModule { module: "x".into() },
6474 UpgradeInstruction::SoftPurge {
6475 module: "x-old".into(),
6476 },
6477 UpgradeInstruction::StateChange {
6478 script: PathBuf::from("lib/m.lisp"),
6479 },
6480 ],
6481 );
6482 let err = e.validate().unwrap_err();
6483 assert_eq!(
6484 err,
6485 UpgradeError::StateChangeAfterCleanup {
6486 from: "0.1.0".into(),
6487 script: PathBuf::from("lib/m.lisp"),
6488 prior_cleanup_kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
6489 prior_cleanup_module: "x-old".into(),
6490 },
6491 "a `:state-change` after a `:soft-purge` must surface as StateChangeAfterCleanup \
6492 naming the offending entry + script + the prior cleanup's kind/module, got {err:?}"
6493 );
6494 }
6495
6496 #[test]
6497 fn validate_rejects_state_change_after_purge() {
6498 // Per-arm coverage: `:purge` (immediate discard, no drain) is
6499 // the more catastrophic peer of `:soft-purge` on the cleanup
6500 // axis; same gate, same shape, the `prior_cleanup_kind` field
6501 // distinguishes the diagnostic so the author can grep their
6502 // caixa.lisp for the offending `(:purge …)` form.
6503 let e = entry(
6504 "0.1.0",
6505 vec![
6506 UpgradeInstruction::LoadModule { module: "x".into() },
6507 UpgradeInstruction::Purge {
6508 module: "x-old".into(),
6509 },
6510 UpgradeInstruction::StateChange {
6511 script: PathBuf::from("lib/m.lisp"),
6512 },
6513 ],
6514 );
6515 let err = e.validate().unwrap_err();
6516 assert_eq!(
6517 err,
6518 UpgradeError::StateChangeAfterCleanup {
6519 from: "0.1.0".into(),
6520 script: PathBuf::from("lib/m.lisp"),
6521 prior_cleanup_kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
6522 prior_cleanup_module: "x-old".into(),
6523 },
6524 "a `:state-change` after a `:purge` must surface as StateChangeAfterCleanup with \
6525 `prior_cleanup_kind: \":purge\"`, got {err:?}"
6526 );
6527 }
6528
6529 #[test]
6530 fn validate_accepts_state_change_before_cleanup() {
6531 // Positive control: the canonical `(:load-module …)
6532 // (:state-change …) (:soft-purge …)` order validates — the
6533 // exact shape the module doc example and `validate_accepts_
6534 // well_formed` already pin, restated here on the new gate's
6535 // identity element so a future shortcut that runs the
6536 // singularity gates first doesn't silently mask a regression
6537 // here.
6538 let e = entry(
6539 "0.1.0",
6540 vec![
6541 UpgradeInstruction::LoadModule { module: "x".into() },
6542 UpgradeInstruction::StateChange {
6543 script: PathBuf::from("lib/m.lisp"),
6544 },
6545 UpgradeInstruction::SoftPurge {
6546 module: "x-old".into(),
6547 },
6548 ],
6549 );
6550 e.validate().unwrap();
6551 }
6552
6553 #[test]
6554 fn validate_accepts_cleanup_without_state_change() {
6555 // Empty-set identity: an entry that carries no `:state-change`
6556 // at all has nothing to order against the cleanup, so the gate
6557 // passes regardless of how the cleanups are placed (after the
6558 // single required `:load-module`). Mirrors the
6559 // `validate_accepts_multiple_purges_after_one_load` positive
6560 // control on the peer purge-ordering gate; metadata-only
6561 // upgrades with cleanup-but-no-migration land here.
6562 let e = entry(
6563 "0.1.0",
6564 vec![
6565 UpgradeInstruction::LoadModule { module: "x".into() },
6566 UpgradeInstruction::SoftPurge {
6567 module: "x-old".into(),
6568 },
6569 UpgradeInstruction::Purge {
6570 module: "x-oldest".into(),
6571 },
6572 ],
6573 );
6574 e.validate().unwrap();
6575 }
6576
6577 #[test]
6578 fn validate_accepts_state_change_without_cleanup() {
6579 // Empty-set identity on the dual axis: an entry that carries no
6580 // cleanup at all has nothing to order against the state-change,
6581 // so the gate passes — additive-upgrade shapes (load new code,
6582 // migrate state, leave old code resident for in-flight callers
6583 // to drain naturally) land here.
6584 let e = entry(
6585 "0.1.0",
6586 vec![
6587 UpgradeInstruction::LoadModule { module: "x".into() },
6588 UpgradeInstruction::StateChange {
6589 script: PathBuf::from("lib/m.lisp"),
6590 },
6591 ],
6592 );
6593 e.validate().unwrap();
6594 }
6595
6596 #[test]
6597 fn validate_accepts_multiple_state_changes_before_cleanup() {
6598 // Coverage: every state-change must precede every cleanup, not
6599 // just the first. A chain `(load) (sc) (sc) (sp)` is the
6600 // canonical "two distinct migration scripts on a chained
6601 // upgrade" shape (one module's schema *and* another's
6602 // projection per the DuplicateStateChange diagnostic), and
6603 // it must pass when each state-change has distinct script
6604 // paths. Pinned here so a future shortcut that only checks
6605 // the first state-change doesn't silently accept a
6606 // `(load) (sc-1) (sp) (sc-2)` regression.
6607 let e = entry(
6608 "0.1.0",
6609 vec![
6610 UpgradeInstruction::LoadModule { module: "x".into() },
6611 UpgradeInstruction::StateChange {
6612 script: PathBuf::from("lib/m1.lisp"),
6613 },
6614 UpgradeInstruction::StateChange {
6615 script: PathBuf::from("lib/m2.lisp"),
6616 },
6617 UpgradeInstruction::SoftPurge {
6618 module: "x-old".into(),
6619 },
6620 ],
6621 );
6622 e.validate().unwrap();
6623 }
6624
6625 #[test]
6626 fn validate_rejects_state_change_sandwiched_between_cleanups() {
6627 // First-cleanup-wins pin: an entry like `(load) (sp-1) (sc)
6628 // (sp-2)` violates the gate because the state-change runs
6629 // after the first cleanup. The reported `prior_cleanup_*`
6630 // names the *first* cleanup (the load-bearing one), not the
6631 // last — mirrors every peer first-collision diagnostic
6632 // posture on this module (`validate_state_change_ordering`,
6633 // `validate_purge_ordering`, `validate_load_singularity`,
6634 // `validate_state_change_singularity`,
6635 // `validate_cleanup_singularity` all report the first
6636 // colliding instruction, not the last).
6637 let e = entry(
6638 "0.1.0",
6639 vec![
6640 UpgradeInstruction::LoadModule { module: "x".into() },
6641 UpgradeInstruction::SoftPurge {
6642 module: "x-old".into(),
6643 },
6644 UpgradeInstruction::StateChange {
6645 script: PathBuf::from("lib/m.lisp"),
6646 },
6647 UpgradeInstruction::Purge {
6648 module: "y-old".into(),
6649 },
6650 ],
6651 );
6652 let err = e.validate().unwrap_err();
6653 assert_eq!(
6654 err,
6655 UpgradeError::StateChangeAfterCleanup {
6656 from: "0.1.0".into(),
6657 script: PathBuf::from("lib/m.lisp"),
6658 prior_cleanup_kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
6659 prior_cleanup_module: "x-old".into(),
6660 },
6661 "the first cleanup the state-change follows must surface (not the trailing one), \
6662 got {err:?}"
6663 );
6664 }
6665
6666 #[test]
6667 fn validate_state_change_before_cleanup_fires_after_purge_ordering() {
6668 // Diagnostic-precedence pin: an entry like `((:soft-purge
6669 // "x-old") (:load-module "x") (:state-change "m.lisp"))` is
6670 // *both* purge-without-load (the cleanup runs before the
6671 // load) and state-change-after-cleanup (the state-change
6672 // runs after the cleanup). The more-fundamental ordering
6673 // gate must win — the missing-load defect (a cleanup that
6674 // drains the only resident version to nothing) is load-
6675 // bearing, and surfacing the state-change-after-cleanup
6676 // diagnostic first would mask the drain-to-nothing defect
6677 // the peer purge-ordering gate exists to close. Guards the
6678 // call order in `validate` against silent reordering. Same
6679 // posture as `validate_purge_ordering_fires_after_state_
6680 // change_ordering` on the sibling ordering gate.
6681 //
6682 // Pin specifically uses the load-after-cleanup shape (rather
6683 // than load-less) so the state-change-ordering gate (which
6684 // would otherwise fire first on a `((:soft-purge …)
6685 // (:state-change …))` shape with no leading load) is
6686 // sidestepped: with the load present after the cleanup,
6687 // state-change-ordering passes (its `loaded` latch is set
6688 // before the state-change is encountered) but purge-ordering
6689 // still fails (the cleanup precedes the load). That isolates
6690 // the precedence between purge-ordering and this gate
6691 // cleanly.
6692 let e = entry(
6693 "0.1.0",
6694 vec![
6695 UpgradeInstruction::SoftPurge {
6696 module: "x-old".into(),
6697 },
6698 UpgradeInstruction::LoadModule { module: "x".into() },
6699 UpgradeInstruction::StateChange {
6700 script: PathBuf::from("lib/m.lisp"),
6701 },
6702 ],
6703 );
6704 let err = e.validate().unwrap_err();
6705 assert!(
6706 matches!(
6707 err,
6708 UpgradeError::PurgeWithoutPriorLoad {
6709 kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
6710 ..
6711 }
6712 ),
6713 "purge-without-load must surface before state-change-after-cleanup, got {err:?}"
6714 );
6715 }
6716
6717 #[test]
6718 fn validate_state_change_before_cleanup_fires_after_state_change_ordering() {
6719 // Diagnostic-precedence pin: an entry like `((:state-change
6720 // "m.lisp") (:soft-purge "x-old"))` is state-change-without-
6721 // load (because no `:load-module` precedes the state-change)
6722 // but *not* state-change-after-cleanup (the state-change
6723 // precedes the cleanup textually). The state-change-ordering
6724 // gate must surface first regardless — the missing-load
6725 // defect on the migration axis is the load-bearing semantic
6726 // and surfacing a different ordering diagnostic would mask
6727 // the migration-against-stale-code defect. Guards the call
6728 // order in `validate` against silent reordering on a shape
6729 // that fires only the state-change-ordering gate (not this
6730 // one), pinning that the state-change-ordering gate wins
6731 // ahead of this gate's chance to look at the list.
6732 let e = entry(
6733 "0.1.0",
6734 vec![
6735 UpgradeInstruction::StateChange {
6736 script: PathBuf::from("lib/m.lisp"),
6737 },
6738 UpgradeInstruction::SoftPurge {
6739 module: "x-old".into(),
6740 },
6741 ],
6742 );
6743 let err = e.validate().unwrap_err();
6744 assert!(
6745 matches!(err, UpgradeError::StateChangeWithoutPriorLoad { .. }),
6746 "state-change-without-load must surface before purge-without-load (the canonical \
6747 validate_purge_ordering_fires_after_state_change_ordering pin), got {err:?}"
6748 );
6749 }
6750
6751 #[test]
6752 fn validate_state_change_before_cleanup_fires_after_per_instr_shape() {
6753 // Order pin: a malformed `:script` value on a `:state-change`
6754 // (an empty path) surfaces its narrower `EmptyScript`
6755 // diagnostic *before* the within-entry state-change-before-
6756 // cleanup gate fires. The per-instruction shape pass walks
6757 // the list inline before the ordering check, so the narrower
6758 // self-locating diagnostic surfaces first — mirrors the
6759 // empty-first cascade on every peer path-shape gate and the
6760 // `validate_purge_ordering_fires_after_per_instr_shape` pin
6761 // on the sibling ordering gate.
6762 let e = entry(
6763 "0.1.0",
6764 vec![
6765 UpgradeInstruction::LoadModule { module: "x".into() },
6766 UpgradeInstruction::SoftPurge {
6767 module: "x-old".into(),
6768 },
6769 UpgradeInstruction::StateChange {
6770 script: PathBuf::new(),
6771 },
6772 ],
6773 );
6774 let err = e.validate().unwrap_err();
6775 assert_eq!(
6776 err,
6777 UpgradeError::EmptyScript,
6778 "malformed instruction must surface its narrower diagnostic before the \
6779 state-change-before-cleanup gate fires, got {err:?}"
6780 );
6781 }
6782
6783 #[test]
6784 fn validate_state_change_before_cleanup_fires_before_state_change_singularity() {
6785 // Diagnostic-precedence pin: an entry like `((:load-module
6786 // "x") (:soft-purge "x-old") (:state-change "m.lisp")
6787 // (:state-change "m.lisp"))` violates *both* this ordering
6788 // gate (the first state-change follows the cleanup) and the
6789 // state-change-singularity gate (the same script appears
6790 // twice). The ordering gate must win — the canonical
6791 // "ordering before singularity" precedence the peer
6792 // `validate_state_change_ordering` / `validate_purge_
6793 // ordering` gates already establish over their own singularity
6794 // gates, applied uniformly across the OTP canonical-sequence
6795 // ordering axis here. Guards the call order in `validate`:
6796 // `validate_state_change_before_cleanup` runs before the
6797 // per-instruction-class singularity gates.
6798 let e = entry(
6799 "0.1.0",
6800 vec![
6801 UpgradeInstruction::LoadModule { module: "x".into() },
6802 UpgradeInstruction::SoftPurge {
6803 module: "x-old".into(),
6804 },
6805 UpgradeInstruction::StateChange {
6806 script: PathBuf::from("lib/m.lisp"),
6807 },
6808 UpgradeInstruction::StateChange {
6809 script: PathBuf::from("lib/m.lisp"),
6810 },
6811 ],
6812 );
6813 let err = e.validate().unwrap_err();
6814 assert!(
6815 matches!(err, UpgradeError::StateChangeAfterCleanup { .. }),
6816 "state-change-after-cleanup must surface before duplicate-state-change, got {err:?}"
6817 );
6818 }
6819
6820 #[test]
6821 fn validate_state_change_before_cleanup_threads_through_validate_upgrade_from() {
6822 // The whole-list entry-point surfaces the per-entry ordering
6823 // error (mirrors `validate_purge_ordering_threads_through_
6824 // validate_upgrade_from` and every peer wiring pin): the gate
6825 // is reachable from the LayoutInvariants call site, not only
6826 // from a direct `entry.validate()`.
6827 let entries = vec![entry(
6828 "0.1.0",
6829 vec![
6830 UpgradeInstruction::LoadModule { module: "x".into() },
6831 UpgradeInstruction::SoftPurge {
6832 module: "x-old".into(),
6833 },
6834 UpgradeInstruction::StateChange {
6835 script: PathBuf::from("lib/m.lisp"),
6836 },
6837 ],
6838 )];
6839 let err = validate_upgrade_from(&entries).unwrap_err();
6840 assert!(
6841 matches!(err, UpgradeError::StateChangeAfterCleanup { .. }),
6842 "validate_upgrade_from must thread the state-change-before-cleanup error, \
6843 got {err:?}"
6844 );
6845 }
6846
6847 #[test]
6848 fn validate_state_change_before_cleanup_projects_scripts_through_declared_path_accessor() {
6849 // Composition pin: [`UpgradeFromEntry::validate_state_change_before_cleanup`]'s
6850 // per-instruction `StateChange`-arm script-path projection must
6851 // route through the sibling lifted
6852 // [`UpgradeInstruction::declared_path`] `Option<&PathBuf>`
6853 // accessor, not the raw
6854 // `if let UpgradeInstruction::StateChange { script } = instr`
6855 // open-coded pattern-match the gate previously carried inside
6856 // `impl UpgradeFromEntry` at caixa-core/src/upgrade.rs:806.
6857 //
6858 // Structurally: the gate's projection accept-set is the union
6859 // of every [`UpgradeInstruction`] variant for which
6860 // `declared_path().is_some()` — today exactly
6861 // [`UpgradeInstruction::StateChange`] per the sibling
6862 // `declared_path_only_for_state_change` pin, so a
6863 // state-change-after-cleanup input trips
6864 // `StateChangeAfterCleanup` and a non-`StateChange` input
6865 // (module-bearing / terminal) leaves the sticky-once latch
6866 // sweep quiet byte-identical to the pattern-match shape.
6867 //
6868 // Byte-equal today (`declared_path` returns `Some(script)` iff
6869 // `StateChange`, byte-for-byte from the variant's own storage);
6870 // the pin catches any future accessor extension that promotes
6871 // an additional variant onto the `PathBuf`-carrying axis — the
6872 // gate then fires on migrate-after-cleanup for that variant too,
6873 // and the migrate→cleanup ordering discipline the peer
6874 // [`validate_state_change_singularity`] /
6875 // [`validate_upgrade_from_against_behavior`] gates share on the
6876 // same axis extends to the promoted variant by construction.
6877 //
6878 // Peer of the sibling four per-`UpgradeInstruction` consumers
6879 // ([`UpgradeInstruction::validate`]'s per-`StateChange`
6880 // sandbox-path fan-out, the layout-side per-`StateChange`
6881 // script-existence fan-out at
6882 // `caixa-core/src/layout.rs:1058`, the within-entry
6883 // [`UpgradeFromEntry::validate_state_change_singularity`]
6884 // per-`StateChange` script-projection fan-out, the cross-slot
6885 // [`validate_upgrade_from_against_behavior`] per-`StateChange`
6886 // detection loop) — the fifth (and last unlifted inside
6887 // `impl UpgradeFromEntry`) per-`UpgradeInstruction`-consumer of
6888 // the `PathBuf`-carrying axis to now route through the accessor.
6889 // Same shape as the sibling
6890 // `validate_state_change_singularity_projects_scripts_through_declared_path_accessor`
6891 // and `validate_upgrade_from_against_behavior_projects_scripts_through_declared_path_accessor`
6892 // pins extended onto the within-entry migrate→cleanup ordering
6893 // gate.
6894 //
6895 // Three-arm projective coverage:
6896 // (a) `StateChange` scripts project through `declared_path()`
6897 // byte-equal to the raw `script.clone()` field access
6898 // the diagnostic previously carried;
6899 // (b) a `:state-change`-after-cleanup input trips the gate
6900 // with `StateChangeAfterCleanup` carrying the offending
6901 // script + the prior cleanup's kind/module verbatim;
6902 // (c) a non-`StateChange`-only input (`LoadModule` /
6903 // `SoftPurge` / `Purge` / `Restart`) leaves the gate
6904 // vacuous with `Ok(())` — the `declared_path().is_none()`
6905 // arm's fall-through pins.
6906 //
6907 // Fail-before-pass-after verified structurally: swapping the
6908 // production
6909 // `else if let Some(script) = instr.declared_path() && … { … }`
6910 // back to
6911 // `else if let UpgradeInstruction::StateChange { script } = instr && … { … }`
6912 // keeps arms (a)-(c) passing but silently detaches this within-
6913 // entry ordering gate from the accessor's typed dispatch — any
6914 // future `declared_path` extension (promotion of an additional
6915 // variant onto the axis, an operator-side pre-resolved-path
6916 // cache the accessor materializes) would then silently disagree
6917 // between this gate's raw pattern-match and the peer four
6918 // sibling consumers that route through the accessor.
6919
6920 // (a) StateChange projection byte-equal via declared_path.
6921 let sc = UpgradeInstruction::StateChange {
6922 script: PathBuf::from("lib/m.lisp"),
6923 };
6924 assert_eq!(
6925 sc.declared_path().cloned(),
6926 Some(PathBuf::from("lib/m.lisp")),
6927 "declared_path() must project the StateChange :script byte-equal to the raw \
6928 field access — accessor divergence would silently detach this within-entry \
6929 migrate→cleanup ordering gate from the projection every peer per-`UpgradeInstruction` \
6930 consumer routes through"
6931 );
6932
6933 // (b) StateChange-after-cleanup trips the gate through the accessor.
6934 let after = entry(
6935 "0.1.0",
6936 vec![
6937 UpgradeInstruction::LoadModule { module: "x".into() },
6938 UpgradeInstruction::SoftPurge {
6939 module: "x-old".into(),
6940 },
6941 UpgradeInstruction::StateChange {
6942 script: PathBuf::from("lib/m.lisp"),
6943 },
6944 ],
6945 );
6946 assert_eq!(
6947 after.validate(),
6948 Err(UpgradeError::StateChangeAfterCleanup {
6949 from: "0.1.0".into(),
6950 script: PathBuf::from("lib/m.lisp"),
6951 prior_cleanup_kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
6952 prior_cleanup_module: "x-old".into(),
6953 }),
6954 "a :state-change following a cleanup must trip the gate through the declared_path \
6955 accessor's Some(script) arm — carrying the offending script + the prior cleanup's \
6956 kind/module verbatim byte-identical to the pattern-match shape"
6957 );
6958
6959 // (c) Non-StateChange-only inputs leave the gate vacuous.
6960 for instrs in [
6961 vec![UpgradeInstruction::LoadModule { module: "x".into() }],
6962 vec![
6963 UpgradeInstruction::LoadModule { module: "x".into() },
6964 UpgradeInstruction::SoftPurge {
6965 module: "x-old".into(),
6966 },
6967 ],
6968 vec![
6969 UpgradeInstruction::LoadModule { module: "x".into() },
6970 UpgradeInstruction::Purge {
6971 module: "x-old".into(),
6972 },
6973 ],
6974 vec![UpgradeInstruction::Restart],
6975 ] {
6976 for instr in &instrs {
6977 assert!(
6978 instr.declared_path().is_none(),
6979 "non-StateChange variants must project None through declared_path — \
6980 accessor divergence would let this within-entry ordering gate silently \
6981 fire on a cleanup-only sequence far from any :state-change site"
6982 );
6983 }
6984 let e = entry("0.1.0", instrs);
6985 assert_eq!(
6986 e.validate(),
6987 Ok(()),
6988 "the state-change-before-cleanup gate must return Ok(()) on an entry whose \
6989 instructions all project None through declared_path — the accessor's \
6990 None arm the pattern-match's implicit fall-through previously carried"
6991 );
6992 }
6993 }
6994
6995 #[test]
6996 fn validate_restart_order_independent() {
6997 // Position-agnostic: `(:restart)` leading or trailing the
6998 // mixed sequence surfaces the same RestartNotExclusive shape.
6999 // Mirrors OTP appup's order-insensitive
7000 // `restart_emulator | restart_new_emulator` terminal rule —
7001 // the position of the restart instruction in the script is
7002 // irrelevant; what matters is the script *contains* it
7003 // alongside other instructions at all. The gate must not
7004 // gain a false positive by depending on instruction ordering.
7005 let leading = entry(
7006 "0.1.0",
7007 vec![
7008 UpgradeInstruction::Restart,
7009 UpgradeInstruction::LoadModule { module: "x".into() },
7010 ],
7011 );
7012 let trailing = entry(
7013 "0.1.0",
7014 vec![
7015 UpgradeInstruction::LoadModule { module: "x".into() },
7016 UpgradeInstruction::Restart,
7017 ],
7018 );
7019 let middle = entry(
7020 "0.1.0",
7021 vec![
7022 UpgradeInstruction::LoadModule { module: "a".into() },
7023 UpgradeInstruction::Restart,
7024 UpgradeInstruction::SoftPurge {
7025 module: "a-old".into(),
7026 },
7027 ],
7028 );
7029 for e in [&leading, &trailing, &middle] {
7030 assert!(
7031 matches!(
7032 e.validate().unwrap_err(),
7033 UpgradeError::RestartNotExclusive {
7034 restart_count: 1,
7035 ..
7036 }
7037 ),
7038 "mixed-with-:restart entry must surface RestartNotExclusive regardless of \
7039 instruction order, got {:?}",
7040 e.validate()
7041 );
7042 }
7043 }
7044
7045 #[test]
7046 fn validate_restart_exclusive_fires_after_per_instr_shape() {
7047 // Order pin: a malformed `:module` value on a Module-bearing
7048 // instruction (an empty string) surfaces its narrower
7049 // kind-tagged `ModuleEmpty` diagnostic *before* the within-
7050 // entry restart-exclusivity gate fires. The per-instruction
7051 // shape pass walks the list inline before the restart-
7052 // exclusive check, so the narrower self-locating diagnostic
7053 // surfaces first — mirrors the empty-first cascade on every
7054 // peer DNS-1123 gate (`validate_module`,
7055 // `validate_membro_caixa`, `validate_placement_cluster`) and
7056 // the `*_invalid_fires_before_duplicate_check` arm-ordering
7057 // pins on every typed-graph axis. Without this pin a future
7058 // shortcut that runs the restart-exclusive check ahead of
7059 // per-instruction shape would surface a less-actionable
7060 // RestartNotExclusive over an instruction list that's also
7061 // malformed at the per-instruction layer.
7062 let e = entry(
7063 "0.1.0",
7064 vec![
7065 UpgradeInstruction::LoadModule {
7066 module: String::new(),
7067 },
7068 UpgradeInstruction::Restart,
7069 ],
7070 );
7071 let err = e.validate().unwrap_err();
7072 assert_eq!(
7073 err,
7074 UpgradeError::ModuleEmpty {
7075 kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE
7076 },
7077 "malformed instruction must surface its kind-tagged diagnostic before the \
7078 restart-exclusivity gate fires, got {err:?}"
7079 );
7080 }
7081
7082 fn behavior_with_state_change_callback() -> crate::BehaviorSpec {
7083 // Helper for the cross-slot composition gate's pass arm: a
7084 // BehaviorSpec carrying just the `:on-state-change` callback,
7085 // the runtime hook the per-version `(:state-change "…")`
7086 // instruction is delivered through during hot upgrade. Mirrors
7087 // the canonical authoring shape pinned in the module doc.
7088 crate::BehaviorSpec {
7089 on_state_change: Some(PathBuf::from("lib/migrations.lisp")),
7090 ..Default::default()
7091 }
7092 }
7093
7094 #[test]
7095 fn behavior_gate_rejects_state_change_without_any_behavior() {
7096 // `:upgrade-from` with a `(:state-change "lib/m.lisp")` and the
7097 // caixa carries no `:behavior` at all surfaces the missing-
7098 // callback diagnostic naming the offending entry's `:from` +
7099 // script. The "I added the upgrade path but never declared
7100 // `:behavior`" footgun: `:behavior` is optional at the typed
7101 // root, the typed `:upgrade-from` slot validates on its own
7102 // merits, and the operator's hot-upgrade dispatch reaches for
7103 // a callback that doesn't exist.
7104 let entries = vec![entry(
7105 "0.1.0",
7106 vec![
7107 UpgradeInstruction::LoadModule { module: "x".into() },
7108 UpgradeInstruction::StateChange {
7109 script: PathBuf::from("lib/m.lisp"),
7110 },
7111 ],
7112 )];
7113 let err = validate_upgrade_from_against_behavior(&entries, None).unwrap_err();
7114 assert_eq!(
7115 err,
7116 UpgradeError::StateChangeWithoutOnStateChangeCallback {
7117 from: "0.1.0".into(),
7118 script: PathBuf::from("lib/m.lisp"),
7119 },
7120 );
7121 }
7122
7123 #[test]
7124 fn behavior_gate_rejects_state_change_when_on_state_change_is_none() {
7125 // `:behavior` declared with *other* callbacks set
7126 // (`:on-init`, `:on-terminate`, etc.) but `:on-state-change`
7127 // None still surfaces the missing-callback diagnostic — only
7128 // the `:on-state-change` axis matters for this gate. The
7129 // "I declared `:behavior` but missed the migration callback"
7130 // footgun: a caixa that registers its lifecycle hooks but
7131 // forgets the migration delivery path leaves the
7132 // `:state-change` instruction with no runtime hook to
7133 // dispatch through.
7134 let entries = vec![entry(
7135 "0.1.0",
7136 vec![
7137 UpgradeInstruction::LoadModule { module: "x".into() },
7138 UpgradeInstruction::StateChange {
7139 script: PathBuf::from("lib/m.lisp"),
7140 },
7141 ],
7142 )];
7143 let b = crate::BehaviorSpec {
7144 on_init: Some(PathBuf::from("lib/init.lisp")),
7145 on_terminate: Some(PathBuf::from("lib/cleanup.lisp")),
7146 ..Default::default()
7147 };
7148 let err = validate_upgrade_from_against_behavior(&entries, Some(&b)).unwrap_err();
7149 assert_eq!(
7150 err,
7151 UpgradeError::StateChangeWithoutOnStateChangeCallback {
7152 from: "0.1.0".into(),
7153 script: PathBuf::from("lib/m.lisp"),
7154 },
7155 "only `:on-state-change` satisfies the composition; other callbacks must not mask \
7156 the missing migration hook"
7157 );
7158 }
7159
7160 #[test]
7161 fn behavior_gate_accepts_state_change_with_on_state_change_callback() {
7162 // The canonical composition shape: a per-version
7163 // `(:state-change "lib/m.lisp")` instruction paired with the
7164 // `:behavior :on-state-change "lib/migrations.lisp"` callback
7165 // it is delivered through at hot-upgrade time. Pins the gate's
7166 // pass arm — drift here = a future tighten that rejects the
7167 // canonical OTP-shape composition surfaces as a regression at
7168 // this positive-control pin.
7169 let entries = vec![entry(
7170 "0.1.0",
7171 vec![
7172 UpgradeInstruction::LoadModule { module: "x".into() },
7173 UpgradeInstruction::StateChange {
7174 script: PathBuf::from("lib/m.lisp"),
7175 },
7176 ],
7177 )];
7178 let b = behavior_with_state_change_callback();
7179 validate_upgrade_from_against_behavior(&entries, Some(&b)).unwrap();
7180 }
7181
7182 #[test]
7183 fn behavior_gate_accepts_entries_without_any_state_change() {
7184 // Empty-set identity: entries carrying no `:state-change`
7185 // instruction at all (load + cleanup only — the metadata-only
7186 // upgrade shape the module doc names, "On any failure, the
7187 // current version stays load-bearing — a typed atomic
7188 // upgrade") leave the gate vacuous. The composition only
7189 // requires a callback when the per-version script exists; a
7190 // load + cleanup pair has no migration to deliver, so the
7191 // absence of `:on-state-change` is coherent.
7192 let entries = vec![entry(
7193 "0.1.0",
7194 vec![
7195 UpgradeInstruction::LoadModule { module: "x".into() },
7196 UpgradeInstruction::SoftPurge {
7197 module: "x-old".into(),
7198 },
7199 ],
7200 )];
7201 validate_upgrade_from_against_behavior(&entries, None).unwrap();
7202 }
7203
7204 #[test]
7205 fn behavior_gate_accepts_restart_only_entry() {
7206 // The terminal-fallback `((:restart))` shape carries no
7207 // `:state-change` — the operator restarts the pod and the
7208 // new version comes up fresh against its initial state, no
7209 // migration. Pinned alongside the metadata-only positive
7210 // control above as the second empty-state-change shape.
7211 let entries = vec![entry("0.1.0", vec![UpgradeInstruction::Restart])];
7212 validate_upgrade_from_against_behavior(&entries, None).unwrap();
7213 }
7214
7215 #[test]
7216 fn behavior_gate_accepts_empty_entries_list() {
7217 // Empty `:upgrade-from` (a caixa with no declared upgrade
7218 // paths — the v0.1.0 caixa before any upgrade entries are
7219 // added) trivially passes the gate. Pinned so the gate
7220 // doesn't accidentally fire on a caixa that hasn't yet
7221 // declared any upgrades.
7222 let entries: Vec<UpgradeFromEntry> = vec![];
7223 validate_upgrade_from_against_behavior(&entries, None).unwrap();
7224 }
7225
7226 #[test]
7227 fn behavior_gate_reports_first_state_change_in_first_entry() {
7228 // First-collision determinism: with multiple `:state-change`
7229 // instructions across multiple entries, the gate reports the
7230 // *first* one encountered in declaration order — the entry's
7231 // declaration order first, then the within-entry instruction
7232 // order. Mirrors every peer first-collision diagnostic posture
7233 // on this module (`validate_state_change_ordering`,
7234 // `validate_purge_ordering`, the singularity gates), so a
7235 // future shortcut that walks the list in reverse or returns
7236 // the last collision surfaces as a regression here.
7237 let entries = vec![
7238 entry(
7239 "0.1.0",
7240 vec![
7241 UpgradeInstruction::LoadModule { module: "x".into() },
7242 UpgradeInstruction::StateChange {
7243 script: PathBuf::from("lib/m1.lisp"),
7244 },
7245 UpgradeInstruction::StateChange {
7246 script: PathBuf::from("lib/m2.lisp"),
7247 },
7248 ],
7249 ),
7250 entry(
7251 "0.1.5",
7252 vec![
7253 UpgradeInstruction::LoadModule { module: "x".into() },
7254 UpgradeInstruction::StateChange {
7255 script: PathBuf::from("lib/m3.lisp"),
7256 },
7257 ],
7258 ),
7259 ];
7260 let err = validate_upgrade_from_against_behavior(&entries, None).unwrap_err();
7261 assert_eq!(
7262 err,
7263 UpgradeError::StateChangeWithoutOnStateChangeCallback {
7264 from: "0.1.0".into(),
7265 script: PathBuf::from("lib/m1.lisp"),
7266 },
7267 "the first :state-change in the first entry must surface, not later collisions"
7268 );
7269 }
7270
7271 #[test]
7272 fn behavior_gate_reports_second_entry_when_first_has_no_state_change() {
7273 // Cross-entry pin: a first entry with no `:state-change` (just
7274 // a load + cleanup) leaves the gate's per-entry walk continuing
7275 // to the second entry, where the offending instruction lives.
7276 // The diagnostic names the *second* entry's `:from` because
7277 // that's where the missing-callback shape is exposed — pinned
7278 // so a shortcut that bails on the first entry without a
7279 // `:state-change` (rather than continuing) doesn't mask the
7280 // defect in a later entry.
7281 let entries = vec![
7282 entry(
7283 "0.1.0",
7284 vec![
7285 UpgradeInstruction::LoadModule { module: "x".into() },
7286 UpgradeInstruction::SoftPurge {
7287 module: "x-old".into(),
7288 },
7289 ],
7290 ),
7291 entry(
7292 "0.1.5",
7293 vec![
7294 UpgradeInstruction::LoadModule { module: "x".into() },
7295 UpgradeInstruction::StateChange {
7296 script: PathBuf::from("lib/m.lisp"),
7297 },
7298 ],
7299 ),
7300 ];
7301 let err = validate_upgrade_from_against_behavior(&entries, None).unwrap_err();
7302 assert_eq!(
7303 err,
7304 UpgradeError::StateChangeWithoutOnStateChangeCallback {
7305 from: "0.1.5".into(),
7306 script: PathBuf::from("lib/m.lisp"),
7307 },
7308 "the offending entry's `:from` must surface even when an earlier entry carries no \
7309 :state-change"
7310 );
7311 }
7312
7313 #[test]
7314 fn behavior_gate_does_not_fire_when_callback_is_declared_across_many_entries() {
7315 // Positive control: a multi-entry `:upgrade-from` (chained
7316 // upgrades from v0.1.0 *and* v0.1.5) where every entry carries
7317 // a `:state-change` passes when the callback is declared once
7318 // at the caixa root. The callback is a single per-caixa
7319 // runtime hook; one declaration covers every entry's
7320 // `:state-change`, mirroring OTP's
7321 // `release_handler:install_release/1` which dispatches every
7322 // appup's `code_change` instruction through the single
7323 // `gen_server:code_change/3` callback registered on the
7324 // module.
7325 let entries = vec![
7326 entry(
7327 "0.1.0",
7328 vec![
7329 UpgradeInstruction::LoadModule { module: "x".into() },
7330 UpgradeInstruction::StateChange {
7331 script: PathBuf::from("lib/m1.lisp"),
7332 },
7333 ],
7334 ),
7335 entry(
7336 "0.1.5",
7337 vec![
7338 UpgradeInstruction::LoadModule { module: "x".into() },
7339 UpgradeInstruction::StateChange {
7340 script: PathBuf::from("lib/m2.lisp"),
7341 },
7342 ],
7343 ),
7344 ];
7345 let b = behavior_with_state_change_callback();
7346 validate_upgrade_from_against_behavior(&entries, Some(&b)).unwrap();
7347 }
7348
7349 #[test]
7350 fn behavior_gate_accepts_load_and_cleanup_only_when_behavior_carries_on_state_change() {
7351 // Symmetry pin: the gate's pass arm doesn't depend on the
7352 // entry actually carrying a `:state-change` — if no
7353 // `:state-change` is declared, the gate is vacuous regardless
7354 // of the callback (an `:on-state-change` declared without a
7355 // matching per-version script is fine, the callback is the
7356 // runtime default for any *future* migration the author hasn't
7357 // yet added). Pins that a caixa author can declare the
7358 // callback ahead of any migration without the gate
7359 // complaining.
7360 let entries = vec![entry(
7361 "0.1.0",
7362 vec![
7363 UpgradeInstruction::LoadModule { module: "x".into() },
7364 UpgradeInstruction::SoftPurge {
7365 module: "x-old".into(),
7366 },
7367 ],
7368 )];
7369 let b = behavior_with_state_change_callback();
7370 validate_upgrade_from_against_behavior(&entries, Some(&b)).unwrap();
7371 }
7372
7373 #[test]
7374 fn validate_upgrade_from_against_behavior_projects_scripts_through_declared_path_accessor() {
7375 // Composition pin: [`validate_upgrade_from_against_behavior`]'s
7376 // per-instruction `StateChange`-arm script-path projection must
7377 // route through the sibling lifted
7378 // [`UpgradeInstruction::declared_path`] `Option<&PathBuf>`
7379 // accessor, not the raw
7380 // `if let UpgradeInstruction::StateChange { script } = instr`
7381 // open-coded pattern-match the cross-slot gate previously
7382 // carried at caixa-core/src/upgrade.rs:1365.
7383 //
7384 // Structurally: the gate's projection accept-set is the union
7385 // of every [`UpgradeInstruction`] variant for which
7386 // `declared_path().is_some()` — today exactly
7387 // [`UpgradeInstruction::StateChange`] per the sibling
7388 // `declared_path_only_for_state_change` pin, so a
7389 // `:state-change`-carrying entry without an `:on-state-change`
7390 // callback trips `StateChangeWithoutOnStateChangeCallback` and
7391 // a non-`StateChange` entry (load-only / cleanup-only /
7392 // restart-only / empty-`:instructions`) leaves the per-entry
7393 // walk continuing past every non-projecting instruction
7394 // byte-identical to the pattern-match shape.
7395 //
7396 // Byte-equal today (`declared_path` returns `Some(script)` iff
7397 // `StateChange`, byte-for-byte from the variant's own storage);
7398 // the pin catches any future accessor extension that promotes
7399 // an additional variant onto the `PathBuf`-carrying axis — the
7400 // gate then fires on scripts from that variant too, and the
7401 // cross-slot composition discipline the sibling per-
7402 // `UpgradeInstruction` consumers share on the `PathBuf`-
7403 // carrying axis extends to the promoted variant by
7404 // construction.
7405 //
7406 // Peer of the sibling four per-`UpgradeInstruction` consumers
7407 // ([`UpgradeInstruction::validate`]'s per-`StateChange`
7408 // sandbox-path fan-out, the layout-side per-`StateChange`
7409 // script-existence fan-out at
7410 // `caixa-core/src/layout.rs:1058`, the within-entry
7411 // [`UpgradeFromEntry::validate_state_change_singularity`]
7412 // (2bf3ce5) per-`StateChange` script-projection fan-out, the
7413 // peer [`UpgradeInstruction::declared_module`] `String`-axis
7414 // per-variant unifier) — the fourth (and last) per-
7415 // `UpgradeInstruction`-consumer of the `PathBuf`-carrying axis
7416 // to now route through the accessor. Same shape as the
7417 // sibling
7418 // `validate_state_change_singularity_projects_scripts_through_declared_path_accessor`
7419 // pin extended onto the cross-slot composition gate.
7420 //
7421 // Three-arm projective coverage:
7422 // (a) `StateChange` scripts project through `declared_path()`
7423 // byte-equal to the raw `script.clone()` field access
7424 // the diagnostic previously carried;
7425 // (b) a `:state-change`-carrying entry with `behavior: None`
7426 // trips the gate with `StateChangeWithoutOnStateChangeCallback`
7427 // carrying the offending script verbatim;
7428 // (c) a non-`StateChange`-only entry (`LoadModule` /
7429 // `SoftPurge` / `Purge` / `Restart`) leaves the gate
7430 // vacuous with `Ok(())` — the `declared_path().is_none()`
7431 // arm's fall-through pins.
7432 //
7433 // Fail-before-pass-after verified structurally: swapping the
7434 // production
7435 // `if let Some(script) = instr.declared_path() { … }`
7436 // back to
7437 // `if let UpgradeInstruction::StateChange { script } = instr { … }`
7438 // keeps arms (a)-(c) passing but silently detaches the gate
7439 // from the accessor's typed dispatch — any future
7440 // `declared_path` extension (promotion of an additional
7441 // variant onto the axis, an operator-side pre-resolved-path
7442 // cache the accessor materializes) would then silently
7443 // disagree between this cross-slot gate's raw pattern-match
7444 // and the peer four sibling consumers that route through the
7445 // accessor.
7446
7447 // (a) StateChange projection byte-equal via declared_path.
7448 let sc = UpgradeInstruction::StateChange {
7449 script: PathBuf::from("lib/m.lisp"),
7450 };
7451 assert_eq!(
7452 sc.declared_path().cloned(),
7453 Some(PathBuf::from("lib/m.lisp")),
7454 "declared_path() must project the StateChange :script byte-equal to the raw \
7455 field access — accessor divergence would silently detach this cross-slot \
7456 composition gate from the projection every peer per-`UpgradeInstruction` \
7457 consumer routes through"
7458 );
7459
7460 // (b) StateChange-carrying entry with behavior: None trips gate.
7461 let entries = vec![entry(
7462 "0.1.0",
7463 vec![
7464 UpgradeInstruction::LoadModule { module: "x".into() },
7465 UpgradeInstruction::StateChange {
7466 script: PathBuf::from("lib/m.lisp"),
7467 },
7468 ],
7469 )];
7470 assert_eq!(
7471 validate_upgrade_from_against_behavior(&entries, None),
7472 Err(UpgradeError::StateChangeWithoutOnStateChangeCallback {
7473 from: "0.1.0".into(),
7474 script: PathBuf::from("lib/m.lisp"),
7475 }),
7476 "a :state-change-carrying entry with behavior: None must trip the gate through \
7477 the declared_path accessor's Some(script) arm — carrying the offending script \
7478 verbatim byte-identical to the pattern-match shape"
7479 );
7480
7481 // (c) Non-StateChange-only inputs leave the gate vacuous.
7482 for instrs in [
7483 vec![UpgradeInstruction::LoadModule { module: "x".into() }],
7484 vec![
7485 UpgradeInstruction::LoadModule { module: "x".into() },
7486 UpgradeInstruction::SoftPurge {
7487 module: "x-old".into(),
7488 },
7489 ],
7490 vec![
7491 UpgradeInstruction::LoadModule { module: "x".into() },
7492 UpgradeInstruction::Purge {
7493 module: "x-old".into(),
7494 },
7495 ],
7496 vec![UpgradeInstruction::Restart],
7497 ] {
7498 for instr in &instrs {
7499 assert!(
7500 instr.declared_path().is_none(),
7501 "non-StateChange variants must project None through declared_path — \
7502 accessor divergence would let this cross-slot composition gate silently \
7503 fire on a module reference far from any :state-change site"
7504 );
7505 }
7506 let entries = vec![entry("0.1.0", instrs)];
7507 assert_eq!(
7508 validate_upgrade_from_against_behavior(&entries, None),
7509 Ok(()),
7510 "the cross-slot composition gate must return Ok(()) on an entry whose \
7511 instructions all project None through declared_path — the accessor's \
7512 None arm the pattern-match's implicit fall-through previously carried"
7513 );
7514 }
7515 }
7516
7517 #[test]
7518 fn validate_restart_exclusive_threads_through_validate_upgrade_from() {
7519 // Wiring pin: the within-entry restart-exclusivity gate fires
7520 // through [`validate_upgrade_from`] (which delegates to
7521 // [`UpgradeFromEntry::validate`] per entry) before the cross-
7522 // entry duplicate-`:from` gate would have a chance to run on
7523 // the malformed entry. Pinned here so a future refactor that
7524 // walks the cross-entry gate first doesn't accidentally
7525 // surface a DuplicateFrom over an entry that's also malformed
7526 // at the within-entry restart-exclusivity layer.
7527 let entries = vec![
7528 entry(
7529 "0.1.0",
7530 vec![
7531 UpgradeInstruction::LoadModule { module: "x".into() },
7532 UpgradeInstruction::Restart,
7533 ],
7534 ),
7535 entry("0.1.0", vec![UpgradeInstruction::Restart]),
7536 ];
7537 let err = validate_upgrade_from(&entries).unwrap_err();
7538 assert!(
7539 matches!(
7540 err,
7541 UpgradeError::RestartNotExclusive {
7542 restart_count: 1,
7543 ..
7544 }
7545 ),
7546 "within-entry restart-exclusivity diagnostic must surface before the cross-entry \
7547 duplicate-`:from` gate fires, got {err:?}"
7548 );
7549 }
7550
7551 // ── drift-detection: serde-derive-to-M2_UPGRADE_FROM_KEY_* identity ──
7552
7553 #[test]
7554 fn upgrade_from_entry_serde_keys_match_lifted_m2_upgrade_from_key_consts() {
7555 // Load-bearing invariant: the two `M2_UPGRADE_FROM_KEY_*` consts
7556 // (`M2_UPGRADE_FROM_KEY_FROM` / `M2_UPGRADE_FROM_KEY_INSTRUCTIONS`)
7557 // name the exact camelCase JSON keys the `#[serde(rename_all =
7558 // "camelCase")]` attribute on `UpgradeFromEntry` emits, and every
7559 // test-side probe across the caixa-core / caixa-flux renderer
7560 // test fixtures navigates into each element of the rendered
7561 // `:upgrade-from` overlay sequence by consulting one of these two
7562 // `&'static str`s. Serialize a fully-populated UpgradeFromEntry
7563 // and pin that each canonical byte-sequence appears verbatim in
7564 // the JSON — a future accidental `rename_all = "snake_case"` /
7565 // `"kebab-case"` / verbatim-field-name flip at the derive
7566 // attribute (any of which would silently break every test-side
7567 // probe that reaches for one of the two consts) surfaces here as
7568 // a build-time test failure at `upgrade.rs`, not as an apply-time
7569 // `.get(<stale-canonical-const>)` returning `None` far from the
7570 // derive-attr drift's commit. Same discipline the sibling
7571 // `limits_spec_serde_keys_match_lifted_m2_limits_key_consts`
7572 // (d8b8b4f) and
7573 // `behavior_spec_serde_keys_match_lifted_m2_behavior_key_consts`
7574 // (21fe462) pins established on the peer `:limits` / `:behavior`
7575 // sub-slot axes: one canonical byte-string per typed sub-key
7576 // axis, pinned to the load-bearing serde derivation at the type
7577 // itself.
7578 let e = UpgradeFromEntry {
7579 from: "0.1.0".into(),
7580 instructions: vec![UpgradeInstruction::LoadModule {
7581 module: "hello-rio".into(),
7582 }],
7583 };
7584 let json = serde_json::to_string(&e).unwrap();
7585 for key in [
7586 crate::render::M2_UPGRADE_FROM_KEY_FROM,
7587 crate::render::M2_UPGRADE_FROM_KEY_INSTRUCTIONS,
7588 ] {
7589 let quoted = format!("\"{key}\"");
7590 assert!(
7591 json.contains("ed),
7592 "serialized UpgradeFromEntry must carry the lifted \
7593 M2_UPGRADE_FROM_KEY_* byte-sequence {quoted} verbatim in \
7594 the JSON emission (got: {json})",
7595 );
7596 }
7597 }
7598
7599 #[test]
7600 fn m2_upgrade_from_key_consts_are_pairwise_distinct() {
7601 // Cross-axis drift-detection pin: a future collapse of the two
7602 // canonical sub-key byte-strings onto the same value (e.g. an
7603 // accidental copy-paste flip of `M2_UPGRADE_FROM_KEY_INSTRUCTIONS`
7604 // to also read `"from"`) would silently reroute every test-side
7605 // probe on one axis onto the sibling axis's per-entry field and
7606 // pass every propagation-probe test that expected only the stale
7607 // axis's value. Peer of `m2_limits_key_consts_are_pairwise_distinct`
7608 // (d8b8b4f) and `m2_behavior_key_consts_are_pairwise_distinct`
7609 // (21fe462) on the sibling `:limits` / `:behavior` sub-slot axes.
7610 let all = [
7611 crate::render::M2_UPGRADE_FROM_KEY_FROM,
7612 crate::render::M2_UPGRADE_FROM_KEY_INSTRUCTIONS,
7613 ];
7614 for (i, a) in all.iter().enumerate() {
7615 for b in all.iter().skip(i + 1) {
7616 assert_ne!(
7617 a, b,
7618 "M2_UPGRADE_FROM_KEY_* consts must be pairwise-distinct \
7619 canonical byte-sequences — got `{a}` == `{b}`",
7620 );
7621 }
7622 }
7623 }
7624
7625 #[test]
7626 fn upgrade_instruction_serde_tag_key_matches_lifted_m2_upgrade_instruction_key_kind_const() {
7627 // Load-bearing invariant on the M2 `:upgrade-from :instructions`
7628 // per-entry OTP-appup [`UpgradeInstruction`] enum's internally-
7629 // tagged variant-discriminator key axis: the
7630 // `M2_UPGRADE_INSTRUCTION_KEY_KIND` const names the exact tag-slot
7631 // JSON key the `#[serde(tag = "kind", rename_all = "kebab-case")]`
7632 // attribute on [`UpgradeInstruction`] emits, and every downstream
7633 // consumer that navigates the serialized instruction blob to
7634 // route by variant (the caixa-core reflection-vs-serde round-trip
7635 // check in `dispatcher_registration.rs` that probes
7636 // `v.get("kind")` against every variant's expected kebab-case
7637 // tag, the future M4 admission-webhook path, any wasm-operator
7638 // dispatch step consuming the serialized instruction blob) reads
7639 // through the same `&'static str`. Serialize every variant and
7640 // pin that the const's byte-sequence appears verbatim as the
7641 // tag-slot JSON key with the expected kebab-case value — a
7642 // future accidental `tag = "type"` / `tag = "op"` /
7643 // `tag = "instruction"` rebrand at the derive attribute (any of
7644 // which would silently break every consumer probe reaching for
7645 // the stale-tag-key const) surfaces here as a build-time test
7646 // failure at `upgrade.rs`, not as an apply-time
7647 // `.get(<stale-tag-key>)` returning `None` far from the derive-
7648 // attr drift's commit.
7649 //
7650 // Same "one canonical byte-string per typed axis" discipline the
7651 // sibling `upgrade_from_entry_serde_keys_match_lifted_m2_upgrade_from_key_consts`
7652 // pin (36ffe65) established on the peer `:upgrade-from` per-entry
7653 // outer-container axis — this pin extends the discipline one
7654 // altitude deeper onto the per-instruction *tag* axis inside
7655 // each element of the `:instructions` list, completing the
7656 // typed coverage of the `:upgrade-from :instructions` dual
7657 // (key = "kind" + five variant-value tags): the five
7658 // `M2_UPGRADE_INSTRUCTION_KIND_*` consts (56120ef) pin the
7659 // per-variant kebab-case *values*; this pin pins the tag *key*
7660 // above them.
7661 let samples: [(UpgradeInstruction, &'static str); 5] = [
7662 (
7663 UpgradeInstruction::LoadModule {
7664 module: "hello-rio".into(),
7665 },
7666 crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE.trim_start_matches(':'),
7667 ),
7668 (
7669 UpgradeInstruction::StateChange {
7670 script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
7671 },
7672 crate::render::M2_UPGRADE_INSTRUCTION_KIND_STATE_CHANGE.trim_start_matches(':'),
7673 ),
7674 (
7675 UpgradeInstruction::SoftPurge {
7676 module: "hello-rio-old".into(),
7677 },
7678 crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE.trim_start_matches(':'),
7679 ),
7680 (
7681 UpgradeInstruction::Purge {
7682 module: "hello-rio-old".into(),
7683 },
7684 crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE.trim_start_matches(':'),
7685 ),
7686 (
7687 UpgradeInstruction::Restart,
7688 crate::render::M2_UPGRADE_INSTRUCTION_KIND_RESTART.trim_start_matches(':'),
7689 ),
7690 ];
7691 for (sample, expected_value) in &samples {
7692 let v: serde_json::Value = serde_json::to_value(sample).unwrap();
7693 let got = v
7694 .get(crate::render::M2_UPGRADE_INSTRUCTION_KEY_KIND)
7695 .and_then(|k| k.as_str());
7696 assert_eq!(
7697 got,
7698 Some(*expected_value),
7699 "serialized {sample:?} must carry the lifted \
7700 M2_UPGRADE_INSTRUCTION_KEY_KIND byte-sequence \
7701 ({:?}) verbatim as the tag-slot JSON key, holding the \
7702 expected kebab-case value {expected_value:?} (got: {v})",
7703 crate::render::M2_UPGRADE_INSTRUCTION_KEY_KIND,
7704 );
7705 }
7706 }
7707
7708 #[test]
7709 fn m2_upgrade_instruction_key_kind_const_is_lower_camel_case_shape() {
7710 // Shape-pin: the `M2_UPGRADE_INSTRUCTION_KEY_KIND` const must be
7711 // a lowerCamelCase byte-sequence (non-empty, ASCII-lowercase
7712 // leader, ASCII-alphanumeric only — no `snake_case` underscores,
7713 // no `kebab-case` hyphens, no `PascalCase` leading capital, no
7714 // whitespace / colons / dots) — the canonical shape a serde
7715 // internally-tagged discriminator key takes across every peer
7716 // enum in this crate. A future flip to a non-camelCase byte at
7717 // the const surfaces here at build time. Peer of
7718 // `m2_upgrade_from_key_consts_are_lower_camel_case_shape` on the
7719 // sibling per-entry outer-container axis.
7720 let key = crate::render::M2_UPGRADE_INSTRUCTION_KEY_KIND;
7721 assert!(
7722 !key.is_empty(),
7723 "M2_UPGRADE_INSTRUCTION_KEY_KIND must be non-empty (got {key:?})"
7724 );
7725 let first = key.chars().next().unwrap();
7726 assert!(
7727 first.is_ascii_lowercase(),
7728 "M2_UPGRADE_INSTRUCTION_KEY_KIND must lead with an ASCII-lowercase \
7729 byte (got {key:?}, leads with {first:?})",
7730 );
7731 assert!(
7732 key.chars().all(|c| c.is_ascii_alphanumeric()),
7733 "M2_UPGRADE_INSTRUCTION_KEY_KIND must be ASCII-alphanumeric only \
7734 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
7735 );
7736 }
7737
7738 #[test]
7739 fn m2_upgrade_instruction_key_kind_const_disjoint_from_variant_data_keys() {
7740 // Cross-axis drift-detection pin: the tag-slot key
7741 // `M2_UPGRADE_INSTRUCTION_KEY_KIND` (`"kind"`) must be
7742 // disjoint from every per-variant data-field key the
7743 // internally-tagged serialization also emits (`"module"` for
7744 // LoadModule/SoftPurge/Purge, `"script"` for StateChange). A
7745 // future accidental rebrand that collapses `tag = "kind"` onto
7746 // one of the data-field names (e.g. `tag = "module"`) would
7747 // silently corrupt every serialized LoadModule blob (the
7748 // module string and the variant tag would collide on the same
7749 // JSON key) and every consumer probe would either misread the
7750 // tag or fail to distinguish variants. Pin the disjointness at
7751 // build time. Same cross-axis discipline the sibling
7752 // `m2_upgrade_from_key_consts_are_pairwise_distinct` pin
7753 // (36ffe65) established on the outer container's own
7754 // `from`/`instructions` pair.
7755 let key = crate::render::M2_UPGRADE_INSTRUCTION_KEY_KIND;
7756 // Enumerate every per-variant data-field key across all five
7757 // variants of [`UpgradeInstruction`], routing through the two
7758 // lifted `M2_UPGRADE_INSTRUCTION_FIELD_KEY_*` byte-string consts
7759 // that name the same per-variant data-field JSON keys the
7760 // `variant_fields` reflection in
7761 // `caixa-core/tests/dispatcher_registration.rs` surfaces. A future
7762 // per-variant struct-field rebrand (`module` → `component`,
7763 // `script` → `path`) lands as an edit to exactly one const and
7764 // reaches this disjointness pin by construction — the two axes
7765 // (tag-slot key on one side, per-variant data-field keys on the
7766 // other) share one source of truth per axis.
7767 for data_field in [
7768 crate::render::M2_UPGRADE_INSTRUCTION_FIELD_KEY_MODULE,
7769 crate::render::M2_UPGRADE_INSTRUCTION_FIELD_KEY_SCRIPT,
7770 ] {
7771 assert_ne!(
7772 key, data_field,
7773 "M2_UPGRADE_INSTRUCTION_KEY_KIND (the serde `tag` slot) \
7774 must be disjoint from every UpgradeInstruction per-variant \
7775 data-field key — got tag-key {key:?} colliding with \
7776 data-field {data_field:?}, which would silently corrupt \
7777 the internally-tagged serialization",
7778 );
7779 }
7780 }
7781
7782 #[test]
7783 fn upgrade_instruction_variant_data_field_keys_match_lifted_field_key_consts() {
7784 // Load-bearing invariant on the M2 `:upgrade-from :instructions`
7785 // per-entry OTP-appup [`UpgradeInstruction`] enum's per-variant
7786 // data-field JSON key axis: the two
7787 // `M2_UPGRADE_INSTRUCTION_FIELD_KEY_*` consts (`_MODULE`,
7788 // `_SCRIPT`) name the exact per-variant field JSON keys the
7789 // `#[serde(tag = "kind", rename_all = "kebab-case")]` attribute on
7790 // [`UpgradeInstruction`] emits alongside the tag-slot key from the
7791 // sibling [`crate::render::M2_UPGRADE_INSTRUCTION_KEY_KIND`]
7792 // const — the `module: String` struct-field on
7793 // `LoadModule`/`SoftPurge`/`Purge` and the `script: PathBuf`
7794 // struct-field on `StateChange` are promoted to sibling JSON keys
7795 // at the same nesting level as the tag by the internally-tagged
7796 // serialization, and every downstream consumer that navigates the
7797 // serialized instruction blob to reach the payload (the caixa-core
7798 // reflection round-trip in `dispatcher_registration.rs` that
7799 // consults `variant_fields`, the sibling disjointness pin below,
7800 // any future wasm-operator upgrade-dispatch step consuming the
7801 // serialized instruction blob to route the per-module load /
7802 // soft-purge / purge action or the per-script state-change action)
7803 // reads through the same `&'static str`. Serialize one Module-
7804 // bearing variant and one Script-bearing variant, then pin that
7805 // each const's byte-sequence appears verbatim in the JSON emission
7806 // — a future accidental struct-field rebrand (`module: String` →
7807 // `component: String`, `script: PathBuf` → `path: PathBuf`) at
7808 // either variant surfaces here as a build-time test failure at
7809 // `upgrade.rs`, not as an apply-time `.get(<stale-field-key>)`
7810 // returning `None` far from the field-name drift's commit.
7811 //
7812 // Same "one canonical byte-string per typed axis" discipline the
7813 // sibling `upgrade_instruction_serde_tag_key_matches_lifted_m2_upgrade_instruction_key_kind_const`
7814 // pin established on the peer tag-slot key axis on the same
7815 // enum — this pin extends the discipline onto the per-variant
7816 // data-field key axis, completing the `:upgrade-from :instructions`
7817 // variant-JSON dual (tag key + tag values + per-variant field keys)
7818 // fully into caixa-core.
7819 let module_sample = UpgradeInstruction::LoadModule {
7820 module: "hello-rio".into(),
7821 };
7822 let v: serde_json::Value = serde_json::to_value(&module_sample).unwrap();
7823 assert_eq!(
7824 v.get(crate::render::M2_UPGRADE_INSTRUCTION_FIELD_KEY_MODULE)
7825 .and_then(|k| k.as_str()),
7826 Some("hello-rio"),
7827 "serialized {module_sample:?} must carry the lifted \
7828 M2_UPGRADE_INSTRUCTION_FIELD_KEY_MODULE byte-sequence \
7829 ({:?}) verbatim as the data-field JSON key holding the \
7830 module string (got: {v})",
7831 crate::render::M2_UPGRADE_INSTRUCTION_FIELD_KEY_MODULE,
7832 );
7833
7834 let script_sample = UpgradeInstruction::StateChange {
7835 script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
7836 };
7837 let v: serde_json::Value = serde_json::to_value(&script_sample).unwrap();
7838 assert_eq!(
7839 v.get(crate::render::M2_UPGRADE_INSTRUCTION_FIELD_KEY_SCRIPT)
7840 .and_then(|k| k.as_str()),
7841 Some("lib/migrations/v01-to-v02.lisp"),
7842 "serialized {script_sample:?} must carry the lifted \
7843 M2_UPGRADE_INSTRUCTION_FIELD_KEY_SCRIPT byte-sequence \
7844 ({:?}) verbatim as the data-field JSON key holding the \
7845 script path (got: {v})",
7846 crate::render::M2_UPGRADE_INSTRUCTION_FIELD_KEY_SCRIPT,
7847 );
7848 }
7849
7850 #[test]
7851 fn m2_upgrade_instruction_field_key_consts_are_lower_camel_case_shape() {
7852 // Shape-pin: every `M2_UPGRADE_INSTRUCTION_FIELD_KEY_*` const must
7853 // be a lowerCamelCase byte-sequence (non-empty, ASCII-lowercase
7854 // leader, ASCII-alphanumeric only — no `snake_case` underscores,
7855 // no `kebab-case` hyphens, no `PascalCase` leading capital, no
7856 // whitespace / colons / dots) — the canonical shape a Rust
7857 // struct-field name promoted to a JSON key by serde takes on this
7858 // internally-tagged variant surface, matching the sibling
7859 // [`crate::render::M2_UPGRADE_INSTRUCTION_KEY_KIND`] tag-slot key
7860 // shape. A future flip to a non-camelCase byte at either const
7861 // (an accidental `rename_all` regime interleave, or a struct-
7862 // field flip like `module` → `module_name`) surfaces here at
7863 // build time. Peer of
7864 // `m2_upgrade_instruction_key_kind_const_is_lower_camel_case_shape`
7865 // and `m2_upgrade_from_key_consts_are_lower_camel_case_shape` on
7866 // the sibling wire-key axes.
7867 for key in [
7868 crate::render::M2_UPGRADE_INSTRUCTION_FIELD_KEY_MODULE,
7869 crate::render::M2_UPGRADE_INSTRUCTION_FIELD_KEY_SCRIPT,
7870 ] {
7871 assert!(
7872 !key.is_empty(),
7873 "M2_UPGRADE_INSTRUCTION_FIELD_KEY_* must be non-empty (got {key:?})"
7874 );
7875 let first = key.chars().next().unwrap();
7876 assert!(
7877 first.is_ascii_lowercase(),
7878 "M2_UPGRADE_INSTRUCTION_FIELD_KEY_* must lead with an ASCII-lowercase \
7879 byte (got {key:?}, leads with {first:?})",
7880 );
7881 assert!(
7882 key.chars().all(|c| c.is_ascii_alphanumeric()),
7883 "M2_UPGRADE_INSTRUCTION_FIELD_KEY_* must be ASCII-alphanumeric only \
7884 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
7885 );
7886 }
7887 }
7888
7889 #[test]
7890 fn m2_upgrade_instruction_field_key_consts_are_pairwise_distinct() {
7891 // Cross-axis drift-detection pin: a future collapse of the two
7892 // canonical per-variant data-field byte-strings onto the same
7893 // value (e.g. an accidental copy-paste flip of
7894 // `M2_UPGRADE_INSTRUCTION_FIELD_KEY_SCRIPT` to also read
7895 // `"module"`) would silently reroute every test-side probe on one
7896 // variant's payload onto the sibling variant's payload and pass
7897 // every propagation-probe test that expected only the stale
7898 // axis's value. Peer of `m2_upgrade_from_key_consts_are_pairwise_distinct`
7899 // on the sibling per-entry outer-container axis, and of
7900 // `m2_upgrade_instruction_key_kind_const_disjoint_from_variant_data_keys`
7901 // on the sibling tag-slot key ↔ per-variant data-field key axis.
7902 let all = [
7903 crate::render::M2_UPGRADE_INSTRUCTION_FIELD_KEY_MODULE,
7904 crate::render::M2_UPGRADE_INSTRUCTION_FIELD_KEY_SCRIPT,
7905 ];
7906 for (i, a) in all.iter().enumerate() {
7907 for b in all.iter().skip(i + 1) {
7908 assert_ne!(
7909 a, b,
7910 "M2_UPGRADE_INSTRUCTION_FIELD_KEY_* consts must be pairwise-distinct \
7911 canonical byte-sequences — got `{a}` == `{b}`",
7912 );
7913 }
7914 }
7915 }
7916
7917 #[test]
7918 fn m2_upgrade_from_key_consts_are_lower_camel_case_shape() {
7919 // Shape-pin: every `M2_UPGRADE_FROM_KEY_*` const must be a
7920 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
7921 // `kebab-case` hyphens, no `PascalCase` leading capital, no
7922 // whitespace / colons / dots) — the canonical shape the
7923 // `#[serde(rename_all = "camelCase")]` derive produces on
7924 // `UpgradeFromEntry`. A future flip to a non-camelCase attribute
7925 // at the derive surfaces both here (this test fails on the
7926 // stale-constant shape) and at
7927 // `upgrade_from_entry_serde_keys_match_lifted_m2_upgrade_from_key_consts`
7928 // (that test fails on the mismatch between const and derive).
7929 // Peer of `m2_limits_key_consts_are_lower_camel_case_shape`
7930 // (d8b8b4f) and `m2_behavior_key_consts_are_lower_camel_case_shape`
7931 // (21fe462) on the sibling `:limits` / `:behavior` sub-slot axes.
7932 for key in [
7933 crate::render::M2_UPGRADE_FROM_KEY_FROM,
7934 crate::render::M2_UPGRADE_FROM_KEY_INSTRUCTIONS,
7935 ] {
7936 assert!(
7937 !key.is_empty(),
7938 "M2_UPGRADE_FROM_KEY_* must be non-empty (got {key:?})"
7939 );
7940 let first = key.chars().next().unwrap();
7941 assert!(
7942 first.is_ascii_lowercase(),
7943 "M2_UPGRADE_FROM_KEY_* must lead with an ASCII-lowercase \
7944 byte (got {key:?}, leads with {first:?})",
7945 );
7946 assert!(
7947 key.chars().all(|c| c.is_ascii_alphanumeric()),
7948 "M2_UPGRADE_FROM_KEY_* must be ASCII-alphanumeric only \
7949 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
7950 );
7951 }
7952 }
7953
7954 #[test]
7955 fn m2_upgrade_instruction_kind_consts_pin_canonical_kebab_case_labels() {
7956 // Scalar-value pin on the M2 `:upgrade-from :instructions` per-entry
7957 // OTP-appup variant-tag axis: the five canonical author-facing
7958 // kebab-case labels (`:load-module` / `:state-change` /
7959 // `:soft-purge` / `:purge` / `:restart`) the substrate's
7960 // per-variant [`UpgradeInstruction::lisp_form`] dispatch reads
7961 // from and every downstream consumer probes for verbatim. Same
7962 // scalar-value discipline the peer
7963 // `contrato_author_key_consts_pin_canonical_kebab_case_labels`
7964 // (f50c875), `m3_top_level_author_key_consts_pin_canonical_kebab_case_labels`
7965 // (882f498), `m2_top_level_author_key_consts_pin_canonical_kebab_case_labels`
7966 // (f49c8b0), and `supervisor_top_level_author_key_consts_pin_canonical_kebab_case_labels`
7967 // (be40492) established for the sibling M2 / M3 / Supervisor
7968 // top-level and sub-slot author-facing-label axes. Fail-before-
7969 // pass-after locally verified by mutating
7970 // `M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE` to `":load"` — this
7971 // pin fires as expected; restoring passes.
7972 //
7973 // A future OTP-lineage per-variant rebrand (e.g.
7974 // `:load-module` → `:load` matching Erlang's abbreviated
7975 // `code:load_module` name, `:state-change` → `:code-change`
7976 // matching Erlang's verbatim `code_change/3` callback,
7977 // `:soft-purge` → `:drain` matching a hypothetical operator-side
7978 // vocabulary flip, `:purge` → `:discard` matching a hypothetical
7979 // Elixir/Phoenix hot-reload rebrand, `:restart` → `:reboot`
7980 // matching a supervisor-tree vocabulary alignment) lands as an
7981 // edit to exactly one const, and every consumer that reaches for
7982 // the label (the [`UpgradeInstruction::lisp_form`] dispatch, the
7983 // [`validate_cleanup_singularity`] per-variant `kind:` tagger,
7984 // every [`UpgradeError`] `kind:` / `kinds:` / `other_kinds:` /
7985 // `prior_cleanup_kind:` diagnostic field, the
7986 // [`LayoutError::UpgradeViolation`] `issue:` probe in
7987 // `layout.rs`) picks it up at build time rather than at runtime
7988 // as a downstream `kind: <stale-kebab-case>` diagnostic mismatch
7989 // far from the rename's commit.
7990 assert_eq!(
7991 crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE,
7992 ":load-module"
7993 );
7994 assert_eq!(
7995 crate::render::M2_UPGRADE_INSTRUCTION_KIND_STATE_CHANGE,
7996 ":state-change"
7997 );
7998 assert_eq!(
7999 crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
8000 ":soft-purge"
8001 );
8002 assert_eq!(crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE, ":purge");
8003 assert_eq!(
8004 crate::render::M2_UPGRADE_INSTRUCTION_KIND_RESTART,
8005 ":restart"
8006 );
8007 }
8008
8009 #[test]
8010 fn m2_upgrade_instruction_kind_consts_are_pairwise_distinct() {
8011 // Cross-arm drift-detection pin on the M2
8012 // [`crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE`] /
8013 // [`crate::render::M2_UPGRADE_INSTRUCTION_KIND_STATE_CHANGE`] /
8014 // [`crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE`] /
8015 // [`crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE`] /
8016 // [`crate::render::M2_UPGRADE_INSTRUCTION_KIND_RESTART`]
8017 // closed-set OTP-appup variant-tag pentad: a future collapse
8018 // of two canonical variant byte-strings onto the same value
8019 // (an accidental copy-paste flip of
8020 // [`crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE`]
8021 // to also read `":purge"`, a per-arm rebrand that lands one
8022 // const without touching its paired peer) would silently
8023 // reroute every downstream OTP-appup dispatcher's per-
8024 // instruction branch onto the sibling arm's runtime
8025 // behavior and pass every propagation-probe test that
8026 // expected only the stale arm's tag — a `:soft-purge`
8027 // instruction (drain-then-swap: existing callers finish
8028 // under the old module, new callers land on the new one)
8029 // would come up under the `:purge` reconcile branch
8030 // (drop-existing: every in-flight caller terminates
8031 // immediately) on every hot-upgrade cycle, so a rolling
8032 // module swap would silently downgrade to a hard cutover
8033 // against its declared appup discipline, with no field
8034 // naming the instruction-tag drift root cause. Every
8035 // [`crate::UpgradeError`] diagnostic that surfaces the tag
8036 // ([`crate::UpgradeError::ModuleEmpty`] with `kind:` field,
8037 // [`crate::UpgradeError::CleanupCollision`] with `kinds:`
8038 // slice, [`crate::UpgradeError::CleanupPrecedes`] with
8039 // `prior_cleanup_kind:` field, the
8040 // [`crate::LayoutError::UpgradeViolation`] `issue:` probe in
8041 // `layout.rs`) would emit the sibling arm's stale bytes at
8042 // the operator's console, far from the source rebrand
8043 // commit. Peer of the sibling
8044 // [`crate::supervisor::tests::supervisor_estrategia_consts_are_pairwise_distinct`]
8045 // (09ffb2d) /
8046 // [`crate::supervisor::tests::supervisor_child_restart_consts_are_pairwise_distinct`]
8047 // (ccdf955) /
8048 // [`crate::kind::tests::caixa_kind_label_consts_are_pairwise_distinct`]
8049 // (d739850) distinctness pins on the sibling OTP-shape /
8050 // caixa-kind closed-set typed-enum discriminator axes —
8051 // the fifth closed-set OTP-appup / typed-enum axis to
8052 // converge on the same
8053 // "pairwise-distinct-by-construction" discipline, and the
8054 // canonical companion to the peer
8055 // [`m2_upgrade_instruction_field_key_consts_are_pairwise_distinct`]
8056 // (ff980bb) distinctness pin on the sibling internally-
8057 // tagged-JSON per-variant data-field-key axis (the tag axis
8058 // this pin covers vs. the data-field-key axis its peer
8059 // covers — two paired axes on the same
8060 // [`crate::UpgradeInstruction`] typed enum surface).
8061 //
8062 // Fail-before-pass-after locally verified by mutating
8063 // [`crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE`]
8064 // to also read `":purge"` — this pin fires as expected;
8065 // restoring passes.
8066 let all = [
8067 crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE,
8068 crate::render::M2_UPGRADE_INSTRUCTION_KIND_STATE_CHANGE,
8069 crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
8070 crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
8071 crate::render::M2_UPGRADE_INSTRUCTION_KIND_RESTART,
8072 ];
8073 for (i, a) in all.iter().enumerate() {
8074 for (j, b) in all.iter().enumerate() {
8075 if i != j {
8076 assert_ne!(
8077 a, b,
8078 "M2_UPGRADE_INSTRUCTION_KIND_* consts must be pairwise \
8079 distinct — got duplicate {a:?} at indices {i} and {j}",
8080 );
8081 }
8082 }
8083 }
8084 }
8085
8086 #[test]
8087 fn upgrade_instruction_lisp_form_routes_through_lifted_kind_consts() {
8088 // Production-through-const pin: the five per-variant labels
8089 // [`UpgradeInstruction::lisp_form`] returns route through the
8090 // lifted [`crate::render::M2_UPGRADE_INSTRUCTION_KIND_*`] consts,
8091 // so a future rebrand that reaches the const but not the
8092 // dispatch (or vice versa) surfaces here at build time rather
8093 // than at runtime as a downstream
8094 // [`UpgradeError::ModuleEmpty`] `kind: <stale-kebab-case>`
8095 // diagnostic drift far from the rename's commit. Mirror of the
8096 // peer `contrato_shape_gate_routes_through_lifted_contrato_author_key_consts`
8097 // (f50c875), `declared_mesh_slots_route_through_lifted_m3_author_key_consts`
8098 // (882f498), and `declared_servico_slots_route_through_lifted_m2_author_key_consts`
8099 // (f49c8b0) production-through-const pins on the sibling M3 /
8100 // M2 top-level slot axes.
8101 //
8102 // Fail-before-pass-after locally verified by mutating
8103 // `UpgradeInstruction::lisp_form`'s `Self::Purge` arm to return
8104 // `":purge-drift"` — this pin fires as expected; restoring
8105 // passes.
8106 let cases: &[(UpgradeInstruction, &'static str)] = &[
8107 (
8108 UpgradeInstruction::LoadModule { module: "x".into() },
8109 crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE,
8110 ),
8111 (
8112 UpgradeInstruction::StateChange {
8113 script: PathBuf::from("lib/m.lisp"),
8114 },
8115 crate::render::M2_UPGRADE_INSTRUCTION_KIND_STATE_CHANGE,
8116 ),
8117 (
8118 UpgradeInstruction::SoftPurge {
8119 module: "x-old".into(),
8120 },
8121 crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
8122 ),
8123 (
8124 UpgradeInstruction::Purge {
8125 module: "x-old".into(),
8126 },
8127 crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
8128 ),
8129 (
8130 UpgradeInstruction::Restart,
8131 crate::render::M2_UPGRADE_INSTRUCTION_KIND_RESTART,
8132 ),
8133 ];
8134 for (instr, expected) in cases {
8135 assert_eq!(
8136 instr.lisp_form(),
8137 *expected,
8138 "UpgradeInstruction::lisp_form on {instr:?} must route through the lifted \
8139 const (expected {expected:?})",
8140 );
8141 }
8142 }
8143
8144 #[test]
8145 fn upgrade_from_entry_instructions_returns_instructions_slice_byte_equal_across_permutations() {
8146 // The canonical per-`:upgrade-from :instructions` OTP-appup
8147 // migration-instruction-list slice-shape pin:
8148 // [`UpgradeFromEntry::instructions`] must return the
8149 // `:instructions` typed `Vec<UpgradeInstruction>` verbatim as
8150 // a `&[UpgradeInstruction]` slice-view over the same backing
8151 // buffer the raw `self.instructions.as_slice()` field access
8152 // borrows from, byte-equal across every representative fixture
8153 // in the accept-set — the empty slice (the "no-op upgrade" /
8154 // metadata-only sentinel the [`UpgradeFromEntry::instructions`]
8155 // field's own docstring names), the singleton slice on every
8156 // variant of the [`UpgradeInstruction`] arm-space
8157 // (`LoadModule` / `StateChange` / `SoftPurge` / `Purge` /
8158 // `Restart` — the five OTP-appup runtime-primitive variants),
8159 // and multi-instruction cohorts (the canonical
8160 // `LoadModule → StateChange → SoftPurge` OTP two-phase code-
8161 // load + state-migration triad the module doc names as the
8162 // "runs the instructions in order" example).
8163 //
8164 // Pins against a future silent detour that returned
8165 // `&Vec<UpgradeInstruction>` (which would type-check but leak
8166 // the storage-side `Vec`'s grow/push/reserve surface no
8167 // consumer of the typed view reaches for), a fresh-allocated
8168 // `Vec<UpgradeInstruction>` copy (which would type-check via
8169 // a coercion but silently break every downstream caller that
8170 // relied on the slice sharing the backing buffer's identity),
8171 // or an out-of-order or length-drifted projection (which
8172 // would silently split the paired within-entry cross-
8173 // instruction ordering gates' inputs from the peer per-
8174 // instruction shape-check loop's input, one seven-gate cohort
8175 // silently drifting from the peer gate's actual traversal
8176 // input).
8177 //
8178 // Peer of the sibling
8179 // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations`
8180 // (0dcc926) `&[WitContract]` byte-equal pin on the M3 per-
8181 // `:contratos` edge-list axis, extended onto the M2 per-
8182 // `:upgrade-from :instructions` migration-instruction-list
8183 // axis — the fifth `&[T]`-return byte-equal pin, closing the
8184 // last unlifted `Vec`-carry axis on any M2 or M3 typed slot.
8185 let fixtures: Vec<Vec<UpgradeInstruction>> = vec![
8186 Vec::new(),
8187 vec![UpgradeInstruction::LoadModule { module: "x".into() }],
8188 vec![UpgradeInstruction::StateChange {
8189 script: PathBuf::from("lib/m.lisp"),
8190 }],
8191 vec![UpgradeInstruction::SoftPurge {
8192 module: "x-old".into(),
8193 }],
8194 vec![UpgradeInstruction::Purge {
8195 module: "x-old".into(),
8196 }],
8197 vec![UpgradeInstruction::Restart],
8198 vec![
8199 UpgradeInstruction::LoadModule { module: "x".into() },
8200 UpgradeInstruction::StateChange {
8201 script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
8202 },
8203 UpgradeInstruction::SoftPurge {
8204 module: "x-old".into(),
8205 },
8206 ],
8207 ];
8208 for instructions in fixtures {
8209 let e = UpgradeFromEntry {
8210 from: "0.1.0".into(),
8211 instructions: instructions.clone(),
8212 };
8213 assert_eq!(
8214 e.instructions(),
8215 e.instructions.as_slice(),
8216 "UpgradeFromEntry::instructions must project the raw \
8217 `:instructions` `Vec<UpgradeInstruction>` verbatim as a \
8218 `&[UpgradeInstruction]` slice-view over the same backing buffer \
8219 (fixture: {instructions:?})",
8220 );
8221 assert_eq!(
8222 e.instructions().len(),
8223 instructions.len(),
8224 "UpgradeFromEntry::instructions length must match the raw \
8225 `:instructions` `Vec<UpgradeInstruction>` length (fixture: {instructions:?})",
8226 );
8227 }
8228 }
8229
8230 #[test]
8231 fn validate_reads_through_lifted_instructions_accessor() {
8232 // Three-consumer coherence pin on the lifted
8233 // [`UpgradeFromEntry::instructions`] slice-return accessor:
8234 // exercises three of the nine paired production consumers of
8235 // the per-`:upgrade-from :instructions` OTP-appup migration-
8236 // instruction-list surface through end-to-end validate() paths
8237 // that require the accessor to reach each of the fixture's
8238 // instructions.
8239 //
8240 // (1) The per-instruction shape-check fan-out
8241 // ([`UpgradeFromEntry::validate`]'s `for instr in
8242 // self.instructions()` loop): pass the well-formed load →
8243 // state-change → soft-purge triad — `validate()` must accept
8244 // it, which requires the accessor to project every entry so
8245 // each `instr.validate()` fires.
8246 //
8247 // (2) The within-entry state-change-ordering gate
8248 // ([`Self::validate_state_change_ordering`]): pass a
8249 // `((:state-change …))` singleton — `validate()` must return
8250 // [`UpgradeError::StateChangeWithoutPriorLoad`], which
8251 // requires the accessor to reach the state-change so the
8252 // no-prior-load probe fires.
8253 //
8254 // (3) The within-entry per-module cleanup-singularity gate
8255 // ([`Self::validate_cleanup_singularity`]): pass a
8256 // `((:load-module "x") (:soft-purge "x-old") (:soft-purge
8257 // "x-old"))` cohort — `validate()` must return
8258 // [`UpgradeError::DuplicateCleanup`], which requires the
8259 // accessor to iterate the whole list so the second `SoftPurge`
8260 // matches the first via the `seen` set.
8261 //
8262 // Peer of the sibling
8263 // `validate_reads_through_lifted_contratos_accessor` (0dcc926)
8264 // three-consumer coherence pin on the M3 per-`:contratos`
8265 // edge-list axis, extended onto the M2 per-`:upgrade-from
8266 // :instructions` migration-instruction-list axis.
8267
8268 // (1) accept the well-formed OTP two-phase code-load triad
8269 let well_formed = entry(
8270 "0.1.0",
8271 vec![
8272 UpgradeInstruction::LoadModule { module: "x".into() },
8273 UpgradeInstruction::StateChange {
8274 script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
8275 },
8276 UpgradeInstruction::SoftPurge {
8277 module: "x-old".into(),
8278 },
8279 ],
8280 );
8281 assert!(
8282 well_formed.validate().is_ok(),
8283 "well-formed `LoadModule → StateChange → SoftPurge` triad must accept — \
8284 the per-instruction shape-check fan-out requires the accessor to reach every entry"
8285 );
8286
8287 // (2) refuse a `((:state-change …))` singleton — the
8288 // state-change-without-prior-load gate must fire, which
8289 // requires the accessor to reach the single instruction.
8290 let no_prior_load = entry(
8291 "0.1.0",
8292 vec![UpgradeInstruction::StateChange {
8293 script: PathBuf::from("lib/m.lisp"),
8294 }],
8295 );
8296 match no_prior_load.validate() {
8297 Err(UpgradeError::StateChangeWithoutPriorLoad { .. }) => {}
8298 other => panic!(
8299 "expected StateChangeWithoutPriorLoad on a `((:state-change …))` singleton \
8300 — the within-entry state-change-ordering gate must reach the single \
8301 instruction through the lifted accessor; got: {other:?}"
8302 ),
8303 }
8304
8305 // (3) refuse a `((:load-module "x") (:soft-purge "x-old")
8306 // (:soft-purge "x-old"))` cohort — the per-module cleanup-
8307 // singularity gate must fire on the second `SoftPurge`, which
8308 // requires the accessor to iterate the whole list.
8309 let duplicate_cleanup = entry(
8310 "0.1.0",
8311 vec![
8312 UpgradeInstruction::LoadModule { module: "x".into() },
8313 UpgradeInstruction::SoftPurge {
8314 module: "x-old".into(),
8315 },
8316 UpgradeInstruction::SoftPurge {
8317 module: "x-old".into(),
8318 },
8319 ],
8320 );
8321 match duplicate_cleanup.validate() {
8322 Err(UpgradeError::DuplicateCleanup { module, .. }) => {
8323 assert_eq!(
8324 module, "x-old",
8325 "DuplicateCleanup must name the colliding module `x-old` — the per-module \
8326 cleanup-singularity gate must iterate through the lifted accessor to \
8327 match the second SoftPurge against the first via the `seen` set"
8328 );
8329 }
8330 other => panic!(
8331 "expected DuplicateCleanup on `((:load-module x) (:soft-purge x-old) \
8332 (:soft-purge x-old))` — the within-entry cleanup-singularity gate must \
8333 iterate the whole list through the lifted accessor; got: {other:?}"
8334 ),
8335 }
8336
8337 // Path::new suppresses the unused-import warning if the
8338 // outer module trims `use std::path::Path;` in a future edit.
8339 let _ = Path::new("lib/m.lisp");
8340 }
8341
8342 // Per-variant equivalence pins for the [`upgrade_from_script_ctors!`]
8343 // macro definition (see the paired doc-block above the macro
8344 // definition) — every generated `<ctor>(from: &str, script: &Path)
8345 // -> Self` constructor folds the uniform `Self::<Variant> { from:
8346 // from.to_string(), script: script.to_path_buf() }` two-field
8347 // struct-literal onto one substrate primitive. The three per-variant
8348 // equivalence pins below (fail-before-pass-after by construction — a
8349 // byte-mismatched macro arm would trip its equivalence pin first)
8350 // lock each generated constructor to its struct-literal peer under
8351 // `PartialEq`, so every wire-up in
8352 // [`UpgradeFromEntry::validate_state_change_ordering`],
8353 // [`UpgradeFromEntry::validate_state_change_uniqueness`], and
8354 // [`validate_state_change_on_state_change_callback`] on that
8355 // variant produces a byte-equal `UpgradeError` to the pre-lift
8356 // open-coded struct-literal. The cross-axis pin that follows
8357 // (non-default `(from, script)` pair) routes both constructor input
8358 // axes through `.to_string()` / `.to_path_buf()`, so the fold does
8359 // not silently collapse onto a fixed `from` / `script` value.
8360 //
8361 // Peer of the sibling `empty_child_version_ctor_matches_struct_
8362 // literal_wrap` / `duplicate_child_caixa_ctor_matches_struct_
8363 // literal_wrap` / `child_supervises_self_ctor_matches_struct_
8364 // literal_wrap` / `supervisor_caixa_only_ctors_route_caixa_through_
8365 // to_string` equivalence + cross-axis pins the sibling
8366 // [`crate::supervisor::supervisor_caixa_only_ctors!`] family (db09650)
8367 // established on the peer `SupervisorError` envelope; extended
8368 // here onto the `UpgradeError` `{ from: String, script: PathBuf }`
8369 // two-slot envelope so every substrate-primitive ctor family in
8370 // caixa-core guarantees the same-shape fold every wire-up on the
8371 // family reads through one dispatch.
8372
8373 #[test]
8374 fn state_change_without_prior_load_ctor_matches_struct_literal_wrap() {
8375 let from = "0.1.0";
8376 let script = Path::new("lib/migrations/v01-to-v02.lisp");
8377 assert_eq!(
8378 UpgradeError::state_change_without_prior_load(from, script),
8379 UpgradeError::StateChangeWithoutPriorLoad {
8380 from: from.to_string(),
8381 script: script.to_path_buf(),
8382 },
8383 "generated state_change_without_prior_load ctor must produce \
8384 byte-equal UpgradeError to the open-coded struct-literal \
8385 wrap on the same (&str, &Path) fixture",
8386 );
8387 }
8388
8389 #[test]
8390 fn duplicate_state_change_ctor_matches_struct_literal_wrap() {
8391 let from = "0.1.0";
8392 let script = Path::new("lib/migrations/v01-to-v02.lisp");
8393 assert_eq!(
8394 UpgradeError::duplicate_state_change(from, script),
8395 UpgradeError::DuplicateStateChange {
8396 from: from.to_string(),
8397 script: script.to_path_buf(),
8398 },
8399 "generated duplicate_state_change ctor must produce byte-equal \
8400 UpgradeError to the open-coded struct-literal wrap on the \
8401 same (&str, &Path) fixture",
8402 );
8403 }
8404
8405 #[test]
8406 fn state_change_without_on_state_change_callback_ctor_matches_struct_literal_wrap() {
8407 let from = "0.1.0";
8408 let script = Path::new("lib/migrations/v01-to-v02.lisp");
8409 assert_eq!(
8410 UpgradeError::state_change_without_on_state_change_callback(from, script),
8411 UpgradeError::StateChangeWithoutOnStateChangeCallback {
8412 from: from.to_string(),
8413 script: script.to_path_buf(),
8414 },
8415 "generated state_change_without_on_state_change_callback ctor \
8416 must produce byte-equal UpgradeError to the open-coded \
8417 struct-literal wrap on the same (&str, &Path) fixture",
8418 );
8419 }
8420
8421 #[test]
8422 fn upgrade_from_script_ctors_route_from_and_script_verbatim() {
8423 // Cross-axis pin: sweep both constructor input axes (`from:
8424 // &str`, `script: &Path`) through non-default fixtures against
8425 // every generated arm in the [`upgrade_from_script_ctors!`]
8426 // macro, so any wrapper-side lowercase / trim / truncate /
8427 // re-order / fixed-path substitution on the two-field
8428 // construction surfaces here rather than at a downstream
8429 // diagnostic-shape mismatch. Also exercises the `&Path`
8430 // parameter under both `&Path` (direct `Path::new`) and
8431 // `&PathBuf` (via Deref coercion), matching the two shapes the
8432 // three wire-up sites thread through — the ordering /
8433 // callback-declaration gates hand a `&PathBuf` from
8434 // `instr.declared_path()`; the uniqueness gate hands a `&Path`
8435 // from `script.as_path()`. Peer of the sibling
8436 // `supervisor_caixa_only_ctors_route_caixa_through_to_string`
8437 // cross-axis pin on the peer `SupervisorError` `{ caixa:
8438 // String }` envelope.
8439 let from = "1.2.3-rc.1";
8440 let script_owned = PathBuf::from("lib/migrations/v02-to-v03.lisp");
8441 let script_ref: &Path = script_owned.as_path();
8442 for script in [script_ref, &script_owned as &Path] {
8443 assert_eq!(
8444 UpgradeError::state_change_without_prior_load(from, script),
8445 UpgradeError::StateChangeWithoutPriorLoad {
8446 from: from.to_string(),
8447 script: script.to_path_buf(),
8448 },
8449 );
8450 assert_eq!(
8451 UpgradeError::duplicate_state_change(from, script),
8452 UpgradeError::DuplicateStateChange {
8453 from: from.to_string(),
8454 script: script.to_path_buf(),
8455 },
8456 );
8457 assert_eq!(
8458 UpgradeError::state_change_without_on_state_change_callback(from, script),
8459 UpgradeError::StateChangeWithoutOnStateChangeCallback {
8460 from: from.to_string(),
8461 script: script.to_path_buf(),
8462 },
8463 );
8464 }
8465 }
8466
8467 // Per-variant equivalence pins for the [`upgrade_script_only_ctors!`]
8468 // macro definition (see the paired doc-block above the macro
8469 // definition) — every generated `<ctor>(script: &Path) -> Self`
8470 // constructor folds the uniform `Self::<Variant> { script:
8471 // script.to_path_buf() }` one-field struct-literal onto one substrate
8472 // primitive. The three per-variant equivalence pins below
8473 // (fail-before-pass-after by construction — a byte-mismatched macro
8474 // arm would trip its equivalence pin first) lock each generated
8475 // constructor to its struct-literal peer under `PartialEq`, so every
8476 // closure passed to [`crate::render::require_sandboxed_lisp_path`]
8477 // at [`UpgradeInstruction::validate`] on that variant produces a
8478 // byte-equal `UpgradeError` to the pre-lift open-coded
8479 // struct-literal. The cross-axis pin that follows (non-default
8480 // `script` path, both `&Path` and `&PathBuf` shapes) routes the
8481 // constructor input axis through `.to_path_buf()`, so the fold does
8482 // not silently collapse onto a fixed `script` value or drop the
8483 // Deref-coercion arm the wire-up sites depend on.
8484 //
8485 // Peer of the sibling
8486 // `state_change_without_prior_load_ctor_matches_struct_literal_wrap`
8487 // / `duplicate_state_change_ctor_matches_struct_literal_wrap` /
8488 // `state_change_without_on_state_change_callback_ctor_matches_struct_literal_wrap`
8489 // / `upgrade_from_script_ctors_route_from_and_script_verbatim`
8490 // equivalence + cross-axis pins the sibling
8491 // [`upgrade_from_script_ctors!`] family (8e67041) established on the
8492 // peer `{ from: String, script: PathBuf }` two-slot envelope shape;
8493 // extended here onto the `{ script: PathBuf }` one-slot envelope
8494 // shape so every substrate-primitive ctor family on `UpgradeError`
8495 // guarantees the same-shape fold every wire-up on the family reads
8496 // through one dispatch.
8497
8498 #[test]
8499 fn absolute_script_ctor_matches_struct_literal_wrap() {
8500 let script = Path::new("/etc/nope.lisp");
8501 assert_eq!(
8502 UpgradeError::absolute_script(script),
8503 UpgradeError::AbsoluteScript {
8504 script: script.to_path_buf(),
8505 },
8506 "generated absolute_script ctor must produce byte-equal \
8507 UpgradeError to the open-coded struct-literal wrap on the \
8508 same &Path fixture",
8509 );
8510 }
8511
8512 #[test]
8513 fn parent_escape_script_ctor_matches_struct_literal_wrap() {
8514 let script = Path::new("../oops.lisp");
8515 assert_eq!(
8516 UpgradeError::parent_escape_script(script),
8517 UpgradeError::ParentEscapeScript {
8518 script: script.to_path_buf(),
8519 },
8520 "generated parent_escape_script ctor must produce byte-equal \
8521 UpgradeError to the open-coded struct-literal wrap on the \
8522 same &Path fixture",
8523 );
8524 }
8525
8526 #[test]
8527 fn non_lisp_extension_script_ctor_matches_struct_literal_wrap() {
8528 let script = Path::new("lib/migrations.rs");
8529 assert_eq!(
8530 UpgradeError::non_lisp_extension_script(script),
8531 UpgradeError::NonLispExtensionScript {
8532 script: script.to_path_buf(),
8533 },
8534 "generated non_lisp_extension_script ctor must produce \
8535 byte-equal UpgradeError to the open-coded struct-literal \
8536 wrap on the same &Path fixture",
8537 );
8538 }
8539
8540 #[test]
8541 fn upgrade_script_only_ctors_route_script_through_to_path_buf() {
8542 // Cross-axis pin: sweep the constructor input axis (`script:
8543 // &Path`) through a non-default fixture against every generated
8544 // arm in the [`upgrade_script_only_ctors!`] macro, so any
8545 // wrapper-side lowercase / trim / truncate / re-order /
8546 // fixed-path substitution on the one-field construction
8547 // surfaces here rather than at a downstream diagnostic-shape
8548 // mismatch. Also exercises the `&Path` parameter under both
8549 // `&Path` (direct `Path::new`) and `&PathBuf` (via Deref
8550 // coercion), matching the shape the three closures at
8551 // [`UpgradeInstruction::validate`] thread through — the
8552 // wire-ups hand a `&PathBuf` from `instr.declared_path()` into
8553 // each closure, so the Deref-coercion arm the ctor advertises
8554 // must actually route through `.to_path_buf()` and not
8555 // silently swap in a fixed path.
8556 //
8557 // Peer of the sibling
8558 // `upgrade_from_script_ctors_route_from_and_script_verbatim`
8559 // cross-axis pin on the sibling `{ from, script }` two-slot
8560 // envelope shape.
8561 let script_owned = PathBuf::from("lib/migrations/v02-to-v03.lisp");
8562 let script_ref: &Path = script_owned.as_path();
8563 for script in [script_ref, &script_owned as &Path] {
8564 assert_eq!(
8565 UpgradeError::absolute_script(script),
8566 UpgradeError::AbsoluteScript {
8567 script: script.to_path_buf(),
8568 },
8569 );
8570 assert_eq!(
8571 UpgradeError::parent_escape_script(script),
8572 UpgradeError::ParentEscapeScript {
8573 script: script.to_path_buf(),
8574 },
8575 );
8576 assert_eq!(
8577 UpgradeError::non_lisp_extension_script(script),
8578 UpgradeError::NonLispExtensionScript {
8579 script: script.to_path_buf(),
8580 },
8581 );
8582 }
8583 }
8584
8585 // Per-variant equivalence pins for the [`upgrade_from_axis_ctors!`]
8586 // macro definition (see the paired doc-block above the macro
8587 // definition) — every generated `<ctor>(from: &str, <axis>: &str)
8588 // -> Self` constructor folds the uniform `Self::<Variant> { from:
8589 // from.to_string(), <axis>: <axis>.to_string() }` two-field
8590 // struct-literal onto one substrate primitive. The three per-variant
8591 // equivalence pins below (fail-before-pass-after by construction — a
8592 // byte-mismatched macro arm would trip its equivalence pin first)
8593 // lock each generated constructor to its struct-literal peer under
8594 // `PartialEq`, so every wire-up in
8595 // [`UpgradeFromEntry::validate`]'s `:from` SemVer-2 parse gate,
8596 // [`UpgradeFromEntry::validate_load_singularity`]'s per-module dedup
8597 // gate, and [`validate_upgrade_from_against_versao`]'s per-entry
8598 // `:from < :versao` gate on that variant produces a byte-equal
8599 // `UpgradeError` to the pre-lift open-coded struct-literal. The
8600 // cross-axis pin that follows (distinct-per-axis `from` / `<axis>`
8601 // pair) routes both constructor input axes through `.to_string()`
8602 // in declared field order, so the fold does not silently swap `from`
8603 // and the middle `<axis>` field, or silently collapse onto a fixed
8604 // `from` / `<axis>` value on any one variant.
8605 //
8606 // Peer of the sibling `state_change_without_prior_load_ctor_matches_
8607 // struct_literal_wrap` / `duplicate_state_change_ctor_matches_
8608 // struct_literal_wrap` / `state_change_without_on_state_change_
8609 // callback_ctor_matches_struct_literal_wrap` / `upgrade_from_script_
8610 // ctors_route_from_and_script_verbatim` equivalence + cross-axis
8611 // pins the sibling [`upgrade_from_script_ctors!`] family (8e67041)
8612 // established on the sibling `{ from: String, script: PathBuf }`
8613 // two-slot envelope shape; extended here onto the `{ from: String,
8614 // <axis>: String }` two-slot envelope shape so every substrate-
8615 // primitive ctor family on `UpgradeError` guarantees the same-shape
8616 // fold every wire-up on the family reads through one dispatch. Also
8617 // mirror-symmetric peer of the sibling
8618 // `dep_nome_axis_ctors_route_nome_and_axis_through_to_string_uniformly`
8619 // (7f7c950) cross-axis pin on the peer `DepError` `{ nome: String,
8620 // <axis>: String }` two-slot envelope shape.
8621
8622 #[test]
8623 fn from_invalid_ctor_matches_struct_literal_wrap() {
8624 let from = "not-a-semver";
8625 let reason = "unexpected character '-' at position 3";
8626 assert_eq!(
8627 UpgradeError::from_invalid(from, reason),
8628 UpgradeError::FromInvalid {
8629 from: from.to_string(),
8630 reason: reason.to_string(),
8631 },
8632 "generated from_invalid ctor must produce byte-equal \
8633 UpgradeError to the open-coded struct-literal wrap on the \
8634 same (&str, &str) fixture",
8635 );
8636 }
8637
8638 #[test]
8639 fn from_not_before_versao_ctor_matches_struct_literal_wrap() {
8640 let from = "0.2.0";
8641 let versao = "0.1.0";
8642 assert_eq!(
8643 UpgradeError::from_not_before_versao(from, versao),
8644 UpgradeError::FromNotBeforeVersao {
8645 from: from.to_string(),
8646 versao: versao.to_string(),
8647 },
8648 "generated from_not_before_versao ctor must produce byte-equal \
8649 UpgradeError to the open-coded struct-literal wrap on the \
8650 same (&str, &str) fixture",
8651 );
8652 }
8653
8654 #[test]
8655 fn duplicate_load_module_ctor_matches_struct_literal_wrap() {
8656 let from = "0.1.0";
8657 let module = "hello-rio";
8658 assert_eq!(
8659 UpgradeError::duplicate_load_module(from, module),
8660 UpgradeError::DuplicateLoadModule {
8661 from: from.to_string(),
8662 module: module.to_string(),
8663 },
8664 "generated duplicate_load_module ctor must produce byte-equal \
8665 UpgradeError to the open-coded struct-literal wrap on the \
8666 same (&str, &str) fixture",
8667 );
8668 }
8669
8670 #[test]
8671 fn upgrade_from_axis_ctors_route_from_and_axis_through_to_string_uniformly() {
8672 // Cross-axis routing pin: sweep the two constructor input axes
8673 // (`from: &str`, `<axis>: &str`) through distinct-per-axis
8674 // fixtures against every generated arm in the
8675 // [`upgrade_from_axis_ctors!`] macro, so any wrapper-side
8676 // lowercase / trim / truncate at codegen time — a silent field
8677 // swap between `from` and the middle `<axis>` field, or a
8678 // `<axis>` axis silently rerouted through the wrong field on any
8679 // one variant — surfaces here rather than at a downstream
8680 // diagnostic-shape mismatch. Peer of the sibling
8681 // `upgrade_from_script_ctors_route_from_and_script_verbatim`
8682 // (8e67041) cross-axis pin on the same envelope's sibling
8683 // `{ from: String, script: PathBuf }` two-slot family, and of the
8684 // sibling
8685 // `dep_nome_axis_ctors_route_nome_and_axis_through_to_string_uniformly`
8686 // (7f7c950) cross-axis pin on the peer `DepError` `{ nome:
8687 // String, <axis>: String }` two-slot envelope. Distinct-per-
8688 // axis fixtures rule out any two-axis swap (`from` ↔ `<axis>`)
8689 // that would still pass a same-fixture-per-axis pin. Both
8690 // `&str`-literal and `&String` (via Deref coercion) carriers
8691 // are exercised because the three wire-up sites hand a mix of
8692 // both (the `from_invalid` site hands `&e.to_string()` — an
8693 // owned `String` — for `reason`; the `duplicate_load_module`
8694 // site hands a `&str` slice for `module`; the
8695 // `from_not_before_versao` site hands the caller-supplied
8696 // `versao: &str` for `versao`).
8697 let from = "0.1.0";
8698 let axis = "distinct-axis-value";
8699 let from_owned: String = from.to_string();
8700 let axis_owned: String = axis.to_string();
8701 for (from_in, axis_in) in [(from, axis), (from_owned.as_str(), axis_owned.as_str())] {
8702 assert_eq!(
8703 UpgradeError::from_invalid(from_in, axis_in),
8704 UpgradeError::FromInvalid {
8705 from: from.to_string(),
8706 reason: axis.to_string(),
8707 },
8708 "from_invalid must route `from` → `from`, `axis` → `reason` \
8709 in declared field order",
8710 );
8711 assert_eq!(
8712 UpgradeError::from_not_before_versao(from_in, axis_in),
8713 UpgradeError::FromNotBeforeVersao {
8714 from: from.to_string(),
8715 versao: axis.to_string(),
8716 },
8717 "from_not_before_versao must route `from` → `from`, \
8718 `axis` → `versao` in declared field order",
8719 );
8720 assert_eq!(
8721 UpgradeError::duplicate_load_module(from_in, axis_in),
8722 UpgradeError::DuplicateLoadModule {
8723 from: from.to_string(),
8724 module: axis.to_string(),
8725 },
8726 "duplicate_load_module must route `from` → `from`, \
8727 `axis` → `module` in declared field order",
8728 );
8729 }
8730 }
8731
8732 // Per-variant equivalence + accessor-fidelity + cross-axis pins for
8733 // the standalone [`UpgradeError::duplicate_from`] inherent ctor (see
8734 // the paired doc-block above the ctor definition) — the fold of the
8735 // last open-coded one-slot `{ from: entry.prior_versao().to_string() }`
8736 // struct-literal inside [`validate_upgrade_from`]'s cross-entry
8737 // duplicate gate onto one substrate primitive on the
8738 // [`UpgradeError`] envelope, projecting through the paired
8739 // [`UpgradeFromEntry::prior_versao`] scalar accessor on the substrate
8740 // primitive. A byte-mismatched ctor body would trip the equivalence
8741 // pin first, ahead of any downstream diagnostic-shape drift.
8742 //
8743 // Peer of the sibling standalone-ctor equivalence pins on the peer
8744 // one-off variants across caixa-core:
8745 // `contrato_self_loop_ctor_matches_struct_literal_wrap` (b30edfe) on
8746 // the paired two-slot `{ caixa, wit }` [`AplicacaoError`] envelope,
8747 // `contrato_endpoint_not_absolute_ctor_matches_struct_literal_wrap`
8748 // (cdf1a2c) on the paired three-slot `{ de, para, endpoint }`
8749 // envelope, the sibling
8750 // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap` +
8751 // `contrato_endpoint_invalid_ctor_matches_struct_literal_wrap` pins,
8752 // and the sibling `entrada_host_invalid_ctor_matches_struct_literal_wrap`
8753 // pin on the sibling standalone `{ host, reason }` two-slot ctor.
8754
8755 #[test]
8756 fn duplicate_from_ctor_matches_struct_literal_wrap() {
8757 // Equivalence pin: the ctor produces byte-equal
8758 // `UpgradeError::DuplicateFrom` to the pre-lift open-coded
8759 // struct-literal that read the same `from` field through
8760 // [`UpgradeFromEntry::prior_versao`]. Guards any future field-
8761 // addition / reordering / string-conversion tweak on the
8762 // variant. Same equivalence-pin shape as the sibling
8763 // `contrato_self_loop_ctor_matches_struct_literal_wrap`
8764 // (b30edfe) on the paired two-slot `{ caixa, wit }`
8765 // envelope inside `impl AplicacaoSpec`.
8766 let entry = entry("0.1.0", vec![UpgradeInstruction::Restart]);
8767 let lifted = UpgradeError::duplicate_from(&entry);
8768 let struct_literal = UpgradeError::DuplicateFrom {
8769 from: entry.prior_versao().to_string(),
8770 };
8771 assert_eq!(lifted, struct_literal);
8772 }
8773
8774 #[test]
8775 fn duplicate_from_ctor_routes_prior_versao_through_verbatim() {
8776 // Routing pin sweeping a non-default `:from` value
8777 // (`"1.2.3-rc.4+build.5"` — a full SemVer-2 identity with pre-
8778 // release and build metadata) through the paired
8779 // [`UpgradeFromEntry::prior_versao`] scalar accessor axis so any
8780 // wrapper-side lowercase / trim / truncate on the one-field
8781 // construction surfaces here rather than at a downstream
8782 // diagnostic-shape drift. Peer of the sibling
8783 // `contrato_self_loop_ctor_routes_source_and_world_ref_through_verbatim`
8784 // (b30edfe) routing pin on the sibling two-slot envelope.
8785 //
8786 // The pre-release + build-metadata carrier value is deliberately
8787 // chosen to exercise the `.to_string()` path against a `:from`
8788 // shape [`semver::Version::PartialEq`] treats as distinct from
8789 // its release-only sibling (per the
8790 // `validate_upgrade_from_treats_pre_release_as_distinct` and
8791 // build-metadata-tightening-note doc-block on
8792 // [`validate_upgrade_from`]) — so any silent normalization at
8793 // the ctor body (a `.trim_matches('+')` / `.split_once('+')` /
8794 // `.split_once('-')` collapse) would drop bytes from the
8795 // rendered diagnostic and surface here.
8796 let entry = entry("1.2.3-rc.4+build.5", vec![UpgradeInstruction::Restart]);
8797 let built = UpgradeError::duplicate_from(&entry);
8798 match built {
8799 UpgradeError::DuplicateFrom { from } => {
8800 assert_eq!(
8801 from, "1.2.3-rc.4+build.5",
8802 "from slot must thread UpgradeFromEntry::prior_versao() verbatim, \
8803 preserving pre-release + build-metadata bytes"
8804 );
8805 }
8806 other => panic!("expected DuplicateFrom, got {other:?}"),
8807 }
8808 }
8809
8810 #[test]
8811 fn duplicate_from_ctor_projects_prior_versao_scalar_accessor() {
8812 // Accessor-fidelity pin: the ctor's `from` slot keys off the
8813 // [`UpgradeFromEntry::prior_versao`] scalar accessor (matching
8814 // the pre-lift open-coded body's field selection), not any
8815 // stringified rendering of the full entry (e.g. the
8816 // `impl Display for UpgradeFromEntry` output, if one were later
8817 // added, or a `format!("{:?}", entry)` debug dump). Pins the
8818 // projection axis so a silent swap at the ctor body — say, a
8819 // future refactor that projects through `entry.instructions()`
8820 // in shape (dropping the `:from` axis entirely) or through a
8821 // whole-entry `format!` — surfaces here rather than at a
8822 // downstream diagnostic mis-attribution far from the duplicate
8823 // gate's owner.
8824 //
8825 // A future consumer that constructs the ctor against a not-yet-
8826 // gated candidate entry (an M4 `mesh.pleme.io/v1alpha1/Caixa`
8827 // CR admission webhook re-checking a per-`:upgrade-from`-patched
8828 // candidate before the cross-entry duplicate gate re-fires, a
8829 // per-tenant per-`Caixa` overlay resolver rejecting a duplicate
8830 // `(:from …)` introduced by a cluster-local `:upgrade-from`
8831 // override) needs the pre-lift projection axis pinned.
8832 //
8833 // The fixture threads a distinctive `:from` (`"0.2.0-alpha.7"`)
8834 // paired with a distinctive multi-instruction sequence so a
8835 // silent swap that projects through the whole-entry rendering
8836 // instead of the paired scalar accessor would land debug bytes
8837 // from the `:instructions` list into the `from` slot and trip
8838 // the assertion here.
8839 let entry = entry(
8840 "0.2.0-alpha.7",
8841 vec![
8842 UpgradeInstruction::LoadModule {
8843 module: "distinctive-load-target".into(),
8844 },
8845 UpgradeInstruction::StateChange {
8846 script: PathBuf::from("lib/distinctive-migrate.lisp"),
8847 },
8848 UpgradeInstruction::Restart,
8849 ],
8850 );
8851 let built = UpgradeError::duplicate_from(&entry);
8852 match built {
8853 UpgradeError::DuplicateFrom { from } => {
8854 assert_eq!(
8855 from, "0.2.0-alpha.7",
8856 "from slot must project UpgradeFromEntry::prior_versao() \
8857 (not any whole-entry rendering)"
8858 );
8859 }
8860 other => panic!("expected DuplicateFrom, got {other:?}"),
8861 }
8862 }
8863
8864 // Per-variant equivalence + cross-axis + end-to-end wire-up pins for
8865 // the standalone [`UpgradeError::purge_without_prior_load`] inherent
8866 // ctor (see the paired doc-block above the ctor definition) — the
8867 // fold of the last open-coded three-slot `{ from: String, kind:
8868 // &'static str, module: String }` struct-literal wire-up on
8869 // [`UpgradeError`] closes the sole in-crate wire-up site inside
8870 // [`UpgradeFromEntry::validate_purge_ordering`]'s per-instruction
8871 // load-family sticky-latch dispatch onto one substrate primitive.
8872 // A byte-mismatched ctor body would trip the equivalence pin first,
8873 // ahead of any downstream diagnostic-shape drift.
8874 //
8875 // Peer of the sibling standalone-ctor equivalence + routing pins on
8876 // the sibling one-off variants across `UpgradeError`
8877 // (`duplicate_from_ctor_matches_struct_literal_wrap` /
8878 // `duplicate_from_ctor_routes_prior_versao_through_verbatim` /
8879 // `duplicate_from_ctor_projects_prior_versao_scalar_accessor` on
8880 // the paired one-slot `{ from: String }` envelope) and across
8881 // caixa-core (`contrato_endpoint_not_absolute_ctor_matches_struct_
8882 // literal_wrap` on the paired three-slot `{ de, para, endpoint:
8883 // String }` `AplicacaoError` envelope).
8884
8885 #[test]
8886 fn purge_without_prior_load_ctor_matches_struct_literal_wrap() {
8887 // Equivalence pin: the ctor produces byte-equal
8888 // `UpgradeError::PurgeWithoutPriorLoad` to the pre-lift
8889 // open-coded three-field struct-literal on the same `(&str,
8890 // &'static str, &str)` fixture. Guards any future field-
8891 // addition / reordering / string-conversion tweak on the
8892 // variant. Same equivalence-pin shape as the sibling
8893 // `duplicate_from_ctor_matches_struct_literal_wrap` (7e52aec)
8894 // on the peer one-slot `{ from: String }` envelope.
8895 let from = "0.1.0";
8896 let kind = crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE;
8897 let module = "hello-rio-old";
8898 assert_eq!(
8899 UpgradeError::purge_without_prior_load(from, kind, module),
8900 UpgradeError::PurgeWithoutPriorLoad {
8901 from: from.to_string(),
8902 kind,
8903 module: module.to_string(),
8904 },
8905 "generated purge_without_prior_load ctor must produce \
8906 byte-equal UpgradeError to the open-coded struct-literal \
8907 wrap on the same (&str, &'static str, &str) fixture",
8908 );
8909 }
8910
8911 #[test]
8912 fn purge_without_prior_load_ctor_routes_from_kind_and_module_through_verbatim() {
8913 // Cross-axis routing pin: sweep the three constructor input
8914 // axes (`from: &str`, `kind: &'static str`, `module: &str`)
8915 // through distinct-per-axis fixtures across every cleanup-family
8916 // [`UpgradeInstruction::lisp_form`] variant + a boundary mix of
8917 // SemVer-2 `from` shapes (pre-release, build-metadata) + DNS-1123
8918 // module shapes (leaf, hyphenated, deeply-hyphenated) so any
8919 // wrapper-side lowercase / trim / truncate / silent axis-swap
8920 // (`from` ↔ `module`, `kind` misrouted onto `from`) on the
8921 // three-field construction surfaces at assert time rather than
8922 // at a downstream diagnostic consumer that reads the fields
8923 // back and gets a different value than the one it stored. Both
8924 // `&str`-literal and `&String` (via Deref coercion) carriers
8925 // are exercised for `from` / `module` because the sole wire-up
8926 // hands `self.prior_versao()` (a `&str` accessor) and
8927 // `instr.declared_module().expect(…)` (also a `&str`) — the
8928 // ctor must accept both shapes without a pre-conversion.
8929 let kinds: [&'static str; 2] = [
8930 crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
8931 crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
8932 ];
8933 let froms: [&str; 4] = ["0.1.0", "1.2.3-rc.1", "0.2.0-alpha.7+build.5", "0.0.0"];
8934 let modules: [&str; 4] = ["x", "hello-rio-old", "cache-v2-ancient", "a-b-c-d-e-f"];
8935 for kind in kinds {
8936 for from in froms {
8937 for module in modules {
8938 let from_owned: String = from.to_string();
8939 let module_owned: String = module.to_string();
8940 for (from_in, module_in) in
8941 [(from, module), (from_owned.as_str(), module_owned.as_str())]
8942 {
8943 assert_eq!(
8944 UpgradeError::purge_without_prior_load(from_in, kind, module_in),
8945 UpgradeError::PurgeWithoutPriorLoad {
8946 from: from.to_string(),
8947 kind,
8948 module: module.to_string(),
8949 },
8950 "purge_without_prior_load must route from → from, \
8951 kind → kind, module → module in declared field \
8952 order verbatim on ({from:?}, {kind:?}, {module:?})",
8953 );
8954 }
8955 }
8956 }
8957 }
8958 }
8959
8960 #[test]
8961 fn validate_purge_ordering_arm_routes_through_purge_without_prior_load_ctor() {
8962 // End-to-end wire-up pin: build an entry whose declared
8963 // `:instructions` list places a `:soft-purge` (and separately a
8964 // `:purge`) before any `:load-module` so
8965 // [`UpgradeFromEntry::validate_purge_ordering`]'s load-family
8966 // sticky-latch dispatch surfaces
8967 // `UpgradeError::PurgeWithoutPriorLoad`, then pin that the
8968 // observed `Err` byte-equals the substrate-primitive
8969 // [`UpgradeError::purge_without_prior_load`] ctor's output on
8970 // the same fixture. A future silent de-lift of the wire-up back
8971 // to the open-coded struct-literal (or a silent axis-swap on
8972 // the three-field construction at the wire-up site) trips at
8973 // caixa-core test time rather than at a downstream diagnostic
8974 // consumer far from the wire-up commit. Same end-to-end-wire-up
8975 // discipline as the sibling
8976 // `validate_upgrade_from_duplicate_diagnostic_arm_routes_through_duplicate_from_ctor`
8977 // on the peer cross-entry duplicate-`:from` gate; both key off
8978 // exactly one typed dispatch on the substrate primitive.
8979 let cases: [(&str, UpgradeInstruction, &'static str, &str); 2] = [
8980 (
8981 "0.1.0",
8982 UpgradeInstruction::SoftPurge {
8983 module: "hello-rio-old".into(),
8984 },
8985 crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
8986 "hello-rio-old",
8987 ),
8988 (
8989 "1.2.3-rc.1",
8990 UpgradeInstruction::Purge {
8991 module: "cache-v2-ancient".into(),
8992 },
8993 crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
8994 "cache-v2-ancient",
8995 ),
8996 ];
8997 for (from, instr, kind, module) in cases {
8998 let e = entry(from, vec![instr]);
8999 let observed = e.validate().unwrap_err();
9000 assert_eq!(
9001 observed,
9002 UpgradeError::purge_without_prior_load(from, kind, module),
9003 "validate_purge_ordering must route its refusal through \
9004 UpgradeError::purge_without_prior_load(from, kind, \
9005 module) on a bare-cleanup {kind:?} entry, byte-equal \
9006 to the pre-lift open-coded struct-literal wrap on the \
9007 same fixture",
9008 );
9009 }
9010 }
9011
9012 // Per-variant equivalence + cross-axis + end-to-end wire-up pins for
9013 // the standalone [`UpgradeError::state_change_after_cleanup`]
9014 // inherent ctor (see the paired doc-block above the ctor
9015 // definition) — the fold of the last open-coded four-slot `{ from:
9016 // String, script: PathBuf, prior_cleanup_kind: &'static str,
9017 // prior_cleanup_module: String }` struct-literal wire-up on
9018 // [`UpgradeError`] closes the sole in-crate wire-up site inside
9019 // [`UpgradeFromEntry::validate_state_change_before_cleanup`]'s
9020 // migrate-family sticky-latch dispatch onto one substrate primitive.
9021 // A byte-mismatched ctor body would trip the equivalence pin first,
9022 // ahead of any downstream diagnostic-shape drift. Peer of the
9023 // sibling standalone-ctor equivalence + routing pins on the sibling
9024 // one-off variants across `UpgradeError`
9025 // (`purge_without_prior_load_ctor_matches_struct_literal_wrap` /
9026 // `purge_without_prior_load_ctor_routes_from_kind_and_module_through_verbatim`
9027 // / `validate_purge_ordering_arm_routes_through_purge_without_prior_load_ctor`
9028 // on the paired three-slot `{ from, kind, module }` envelope;
9029 // `duplicate_from_ctor_matches_struct_literal_wrap` on the paired
9030 // one-slot `{ from }` envelope).
9031
9032 #[test]
9033 fn state_change_after_cleanup_ctor_matches_struct_literal_wrap() {
9034 // Equivalence pin: the ctor produces byte-equal
9035 // `UpgradeError::StateChangeAfterCleanup` to the pre-lift
9036 // open-coded four-field struct-literal on the same `(&str,
9037 // &Path, &'static str, &str)` fixture. Guards any future
9038 // field-addition / reordering / string-conversion tweak on the
9039 // variant. Same equivalence-pin shape as the sibling
9040 // `purge_without_prior_load_ctor_matches_struct_literal_wrap`
9041 // (9752da1) on the peer three-slot envelope.
9042 let from = "0.1.0";
9043 let script = Path::new("lib/m.lisp");
9044 let prior_cleanup_kind = crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE;
9045 let prior_cleanup_module = "x-old";
9046 assert_eq!(
9047 UpgradeError::state_change_after_cleanup(
9048 from,
9049 script,
9050 prior_cleanup_kind,
9051 prior_cleanup_module,
9052 ),
9053 UpgradeError::StateChangeAfterCleanup {
9054 from: from.to_string(),
9055 script: script.to_path_buf(),
9056 prior_cleanup_kind,
9057 prior_cleanup_module: prior_cleanup_module.to_string(),
9058 },
9059 "generated state_change_after_cleanup ctor must produce \
9060 byte-equal UpgradeError to the open-coded struct-literal \
9061 wrap on the same (&str, &Path, &'static str, &str) fixture",
9062 );
9063 }
9064
9065 #[test]
9066 fn state_change_after_cleanup_ctor_routes_from_script_kind_and_module_through_verbatim() {
9067 // Cross-axis routing pin: sweep the four constructor input
9068 // axes (`from: &str`, `script: &Path`, `prior_cleanup_kind:
9069 // &'static str`, `prior_cleanup_module: &str`) through
9070 // distinct-per-axis fixtures across every cleanup-family
9071 // [`UpgradeInstruction::lisp_form`] variant + a boundary mix of
9072 // SemVer-2 `from` shapes (release, pre-release, pre-release +
9073 // build-metadata, zero), sibling-`.lisp` script-path shapes
9074 // (leaf, nested, deeply-nested), and DNS-1123 module shapes
9075 // (leaf, hyphenated, deeply-hyphenated) so any wrapper-side
9076 // lowercase / trim / truncate / silent axis-swap
9077 // (`from` ↔ `prior_cleanup_module`, `script` misrouted onto
9078 // `from`, `prior_cleanup_kind` misrouted onto
9079 // `prior_cleanup_module`) on the four-field construction
9080 // surfaces at assert time rather than at a downstream diagnostic
9081 // consumer that reads the fields back and gets a different value
9082 // than the one it stored. Both `&str`-literal and `&String` (via
9083 // Deref coercion) carriers are exercised for `from` /
9084 // `prior_cleanup_module` because the sole wire-up hands
9085 // `self.prior_versao()` (a `&str` accessor) and `prior_module`
9086 // (also `&str`, from `declared_module().expect(…)`) — the ctor
9087 // must accept both shapes without a pre-conversion. Both
9088 // `&Path`-direct and `&PathBuf` (via Deref coercion) carriers
9089 // are exercised for `script` because the sole wire-up hands a
9090 // `&PathBuf` sticky-latch projection from `declared_path()`'s
9091 // `Option<&PathBuf>` return — the ctor must accept both shapes
9092 // without a pre-conversion.
9093 let kinds: [&'static str; 2] = [
9094 crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
9095 crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
9096 ];
9097 let froms: [&str; 4] = ["0.1.0", "1.2.3-rc.1", "0.2.0-alpha.7+build.5", "0.0.0"];
9098 let scripts: [&str; 3] = [
9099 "m.lisp",
9100 "lib/migrations.lisp",
9101 "lib/migrations/v01/step-1.lisp",
9102 ];
9103 let modules: [&str; 3] = ["x", "hello-rio-old", "cache-v2-ancient"];
9104 for kind in kinds {
9105 for from in froms {
9106 for script_str in scripts {
9107 for module in modules {
9108 let from_owned: String = from.to_string();
9109 let module_owned: String = module.to_string();
9110 let script_path = Path::new(script_str);
9111 let script_pathbuf = PathBuf::from(script_str);
9112 for (from_in, module_in, script_in) in [
9113 (from, module, script_path),
9114 (
9115 from_owned.as_str(),
9116 module_owned.as_str(),
9117 script_pathbuf.as_path(),
9118 ),
9119 ] {
9120 assert_eq!(
9121 UpgradeError::state_change_after_cleanup(
9122 from_in, script_in, kind, module_in,
9123 ),
9124 UpgradeError::StateChangeAfterCleanup {
9125 from: from.to_string(),
9126 script: PathBuf::from(script_str),
9127 prior_cleanup_kind: kind,
9128 prior_cleanup_module: module.to_string(),
9129 },
9130 "state_change_after_cleanup must route from → from, \
9131 script → script, prior_cleanup_kind → prior_cleanup_kind, \
9132 prior_cleanup_module → prior_cleanup_module in declared \
9133 field order verbatim on ({from:?}, {script_str:?}, \
9134 {kind:?}, {module:?})",
9135 );
9136 }
9137 }
9138 }
9139 }
9140 }
9141 }
9142
9143 #[test]
9144 fn validate_state_change_before_cleanup_arm_routes_through_state_change_after_cleanup_ctor() {
9145 // End-to-end wire-up pin: build an entry whose declared
9146 // `:instructions` list places a `:soft-purge` (and separately a
9147 // `:purge`) before a `:state-change` so
9148 // [`UpgradeFromEntry::validate_state_change_before_cleanup`]'s
9149 // migrate-family sticky-latch dispatch surfaces
9150 // `UpgradeError::StateChangeAfterCleanup`, then pin that the
9151 // observed `Err` byte-equals the substrate-primitive
9152 // [`UpgradeError::state_change_after_cleanup`] ctor's output on
9153 // the same fixture. A future silent de-lift of the wire-up back
9154 // to the open-coded struct-literal (or a silent axis-swap on
9155 // the four-field construction at the wire-up site) trips at
9156 // caixa-core test time rather than at a downstream diagnostic
9157 // consumer far from the wire-up commit. Same end-to-end-wire-up
9158 // discipline as the sibling
9159 // `validate_purge_ordering_arm_routes_through_purge_without_prior_load_ctor`
9160 // on the peer load → cleanup ordering gate; both key off
9161 // exactly one typed dispatch on the substrate primitive. Every
9162 // entry here front-loads a `:load-module` so the sole surviving
9163 // ordering refusal is the migrate → cleanup one this gate
9164 // owns — the peer `validate_purge_ordering` load → cleanup gate
9165 // returns `Ok(())` on these fixtures, so the migrate-after-
9166 // cleanup arm is the only path to an `Err`.
9167 let cases: [(&str, UpgradeInstruction, &'static str, &str, &str); 2] = [
9168 (
9169 "0.1.0",
9170 UpgradeInstruction::SoftPurge {
9171 module: "hello-rio-old".into(),
9172 },
9173 crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
9174 "hello-rio-old",
9175 "lib/migrations/v01.lisp",
9176 ),
9177 (
9178 "1.2.3-rc.1",
9179 UpgradeInstruction::Purge {
9180 module: "cache-v2-ancient".into(),
9181 },
9182 crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
9183 "cache-v2-ancient",
9184 "lib/migrations/v02.lisp",
9185 ),
9186 ];
9187 for (from, cleanup, kind, module, script_str) in cases {
9188 let script = PathBuf::from(script_str);
9189 let e = entry(
9190 from,
9191 vec![
9192 UpgradeInstruction::LoadModule {
9193 module: "hello-rio".into(),
9194 },
9195 cleanup,
9196 UpgradeInstruction::StateChange {
9197 script: script.clone(),
9198 },
9199 ],
9200 );
9201 let observed = e.validate().unwrap_err();
9202 assert_eq!(
9203 observed,
9204 UpgradeError::state_change_after_cleanup(from, &script, kind, module),
9205 "validate_state_change_before_cleanup must route its \
9206 refusal through \
9207 UpgradeError::state_change_after_cleanup(from, script, \
9208 prior_cleanup_kind, prior_cleanup_module) on a \
9209 `:state-change` after a bare-cleanup {kind:?} entry, \
9210 byte-equal to the pre-lift open-coded struct-literal \
9211 wrap on the same fixture",
9212 );
9213 }
9214 }
9215
9216 // Per-variant equivalence + cross-axis + end-to-end wire-up pins for
9217 // the standalone [`UpgradeError::duplicate_cleanup`] inherent ctor
9218 // (see the paired doc-block above the ctor definition) — the fold of
9219 // the last open-coded three-slot `{ from: String, module: String,
9220 // kinds: Vec<&'static str> }` struct-literal wire-up on
9221 // [`UpgradeError`] closes the sole in-crate wire-up site inside
9222 // [`UpgradeFromEntry::validate_cleanup_singularity`]'s per-module
9223 // cleanup-family dedup arm onto one substrate primitive. A byte-
9224 // mismatched ctor body would trip the equivalence pin first, ahead of
9225 // any downstream diagnostic-shape drift. Peer of the sibling
9226 // standalone-ctor equivalence + routing pins on the sibling one-off
9227 // variants across `UpgradeError`
9228 // (`purge_without_prior_load_ctor_matches_struct_literal_wrap` on the
9229 // paired three-slot `{ from, kind, module }` envelope for the sibling
9230 // load → cleanup ordering axis;
9231 // `state_change_after_cleanup_ctor_matches_struct_literal_wrap` on
9232 // the paired four-slot `{ from, script, prior_cleanup_kind,
9233 // prior_cleanup_module }` envelope for the migrate → cleanup
9234 // boundary; `duplicate_from_ctor_matches_struct_literal_wrap` on the
9235 // paired one-slot `{ from }` envelope for the cross-entry duplicate-
9236 // `:from` gate).
9237
9238 #[test]
9239 fn duplicate_cleanup_ctor_matches_struct_literal_wrap() {
9240 // Equivalence pin: the ctor produces byte-equal
9241 // `UpgradeError::DuplicateCleanup` to the pre-lift open-coded
9242 // three-field struct-literal on the same `(&str, &str,
9243 // Vec<&'static str>)` fixture. Guards any future field-addition /
9244 // reordering / string-conversion tweak on the variant. Same
9245 // equivalence-pin shape as the sibling
9246 // `purge_without_prior_load_ctor_matches_struct_literal_wrap`
9247 // (9752da1) on the peer three-slot envelope.
9248 let from = "0.1.0";
9249 let module = "x-old";
9250 let kinds: Vec<&'static str> = vec![
9251 crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
9252 crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
9253 ];
9254 assert_eq!(
9255 UpgradeError::duplicate_cleanup(from, module, kinds.clone()),
9256 UpgradeError::DuplicateCleanup {
9257 from: from.to_string(),
9258 module: module.to_string(),
9259 kinds,
9260 },
9261 "generated duplicate_cleanup ctor must produce byte-equal \
9262 UpgradeError to the open-coded struct-literal wrap on the \
9263 same (&str, &str, Vec<&'static str>) fixture",
9264 );
9265 }
9266
9267 #[test]
9268 fn duplicate_cleanup_ctor_routes_from_module_and_kinds_through_verbatim() {
9269 // Cross-axis routing pin: sweep the three constructor input axes
9270 // (`from: &str`, `module: &str`, `kinds: Vec<&'static str>`)
9271 // through distinct-per-axis fixtures across every ordered pair of
9272 // cleanup-family [`UpgradeInstruction::lisp_form`] variants (the
9273 // four `(prior_kind, kind)` combinations `validate_cleanup_
9274 // singularity` can emit: SS, PP, SP, PS) + a boundary mix of
9275 // SemVer-2 `from` shapes (release, pre-release, pre-release +
9276 // build-metadata, zero) + DNS-1123 module shapes (leaf,
9277 // hyphenated, deeply-hyphenated) so any wrapper-side lowercase /
9278 // trim / truncate / silent axis-swap (`from` ↔ `module`, kinds
9279 // pair-reorder, kinds-vec drop-or-duplicate on the two-element
9280 // owned `Vec<&'static str>`) on the three-field construction
9281 // surfaces at assert time rather than at a downstream diagnostic
9282 // consumer that reads the fields back and gets a different value
9283 // than the one it stored. Both `&str`-literal and `&String` (via
9284 // Deref coercion) carriers are exercised for `from` / `module`
9285 // because the sole wire-up hands `self.prior_versao()` (a `&str`
9286 // accessor) and `module` (also `&str`, from `declared_module().
9287 // expect(…)`) — the ctor must accept both shapes without a
9288 // pre-conversion.
9289 let all_kinds: [&'static str; 2] = [
9290 crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
9291 crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
9292 ];
9293 let froms: [&str; 4] = ["0.1.0", "1.2.3-rc.1", "0.2.0-alpha.7+build.5", "0.0.0"];
9294 let modules: [&str; 3] = ["x", "hello-rio-old", "cache-v2-ancient"];
9295 for prior_kind in all_kinds {
9296 for kind in all_kinds {
9297 for from in froms {
9298 for module in modules {
9299 let from_owned: String = from.to_string();
9300 let module_owned: String = module.to_string();
9301 for (from_in, module_in) in
9302 [(from, module), (from_owned.as_str(), module_owned.as_str())]
9303 {
9304 let kinds: Vec<&'static str> = vec![prior_kind, kind];
9305 assert_eq!(
9306 UpgradeError::duplicate_cleanup(from_in, module_in, kinds.clone(),),
9307 UpgradeError::DuplicateCleanup {
9308 from: from.to_string(),
9309 module: module.to_string(),
9310 kinds,
9311 },
9312 "duplicate_cleanup must route from → from, \
9313 module → module, kinds → kinds in declared \
9314 field order verbatim on ({from:?}, \
9315 {module:?}, [{prior_kind:?}, {kind:?}])",
9316 );
9317 }
9318 }
9319 }
9320 }
9321 }
9322 }
9323
9324 #[test]
9325 fn validate_cleanup_singularity_arm_routes_through_duplicate_cleanup_ctor() {
9326 // End-to-end wire-up pin: build an entry whose declared
9327 // `:instructions` list front-loads a `:load-module` (so the
9328 // sibling `validate_purge_ordering` load → cleanup gate returns
9329 // `Ok(())` on the fixture) and then places two cleanup
9330 // instructions targeting the same module so
9331 // [`UpgradeFromEntry::validate_cleanup_singularity`]'s per-module
9332 // cleanup-family dedup arm surfaces
9333 // `UpgradeError::DuplicateCleanup`, then pin that the observed
9334 // `Err` byte-equals the substrate-primitive
9335 // [`UpgradeError::duplicate_cleanup`] ctor's output on the same
9336 // fixture. A future silent de-lift of the wire-up back to the
9337 // open-coded struct-literal (or a silent axis-swap on the three-
9338 // field construction at the wire-up site, or a kinds-pair
9339 // reorder) trips at caixa-core test time rather than at a
9340 // downstream diagnostic consumer far from the wire-up commit.
9341 // Same end-to-end-wire-up discipline as the sibling
9342 // `validate_purge_ordering_arm_routes_through_purge_without_prior_load_ctor`
9343 // on the peer load → cleanup ordering gate and
9344 // `validate_state_change_before_cleanup_arm_routes_through_state_change_after_cleanup_ctor`
9345 // on the peer migrate → cleanup boundary; all three key off
9346 // exactly one typed dispatch on the substrate primitive.
9347 let cases: [(
9348 &str,
9349 UpgradeInstruction,
9350 UpgradeInstruction,
9351 &str,
9352 [&'static str; 2],
9353 ); 4] = [
9354 (
9355 "0.1.0",
9356 UpgradeInstruction::SoftPurge {
9357 module: "hello-rio-old".into(),
9358 },
9359 UpgradeInstruction::SoftPurge {
9360 module: "hello-rio-old".into(),
9361 },
9362 "hello-rio-old",
9363 [
9364 crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
9365 crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
9366 ],
9367 ),
9368 (
9369 "1.2.3-rc.1",
9370 UpgradeInstruction::Purge {
9371 module: "cache-v2-ancient".into(),
9372 },
9373 UpgradeInstruction::Purge {
9374 module: "cache-v2-ancient".into(),
9375 },
9376 "cache-v2-ancient",
9377 [
9378 crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
9379 crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
9380 ],
9381 ),
9382 (
9383 "0.2.0-alpha.7+build.5",
9384 UpgradeInstruction::SoftPurge {
9385 module: "x-old".into(),
9386 },
9387 UpgradeInstruction::Purge {
9388 module: "x-old".into(),
9389 },
9390 "x-old",
9391 [
9392 crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
9393 crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
9394 ],
9395 ),
9396 (
9397 "0.0.0",
9398 UpgradeInstruction::Purge {
9399 module: "x-old".into(),
9400 },
9401 UpgradeInstruction::SoftPurge {
9402 module: "x-old".into(),
9403 },
9404 "x-old",
9405 [
9406 crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
9407 crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
9408 ],
9409 ),
9410 ];
9411 for (from, first, second, module, kinds) in cases {
9412 let e = entry(
9413 from,
9414 vec![
9415 UpgradeInstruction::LoadModule {
9416 module: "hello-rio".into(),
9417 },
9418 first,
9419 second,
9420 ],
9421 );
9422 let observed = e.validate().unwrap_err();
9423 assert_eq!(
9424 observed,
9425 UpgradeError::duplicate_cleanup(from, module, kinds.to_vec()),
9426 "validate_cleanup_singularity must route its refusal \
9427 through UpgradeError::duplicate_cleanup(from, module, \
9428 kinds) on a two-cleanup {kinds:?} entry targeting the \
9429 same module, byte-equal to the pre-lift open-coded \
9430 struct-literal wrap on the same fixture",
9431 );
9432 }
9433 }
9434
9435 #[test]
9436 fn restart_not_exclusive_ctor_matches_struct_literal_wrap() {
9437 // Equivalence pin: the ctor produces byte-equal
9438 // `UpgradeError::RestartNotExclusive` to the pre-lift open-coded
9439 // three-field struct-literal on the same `(&str, usize,
9440 // Vec<&'static str>)` fixture. Guards any future field-addition /
9441 // reordering / string-conversion tweak on the variant. Same
9442 // equivalence-pin shape as the sibling
9443 // `duplicate_cleanup_ctor_matches_struct_literal_wrap` (10a5b48)
9444 // on the peer three-slot envelope.
9445 let from = "0.1.0";
9446 let restart_count: usize = 1;
9447 let other_kinds: Vec<&'static str> =
9448 vec![crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE];
9449 assert_eq!(
9450 UpgradeError::restart_not_exclusive(from, restart_count, other_kinds.clone()),
9451 UpgradeError::RestartNotExclusive {
9452 from: from.to_string(),
9453 restart_count,
9454 other_kinds,
9455 },
9456 "generated restart_not_exclusive ctor must produce byte-equal \
9457 UpgradeError to the open-coded struct-literal wrap on the \
9458 same (&str, usize, Vec<&'static str>) fixture",
9459 );
9460 }
9461
9462 #[test]
9463 fn restart_not_exclusive_ctor_routes_from_restart_count_and_other_kinds_through_verbatim() {
9464 // Cross-axis routing pin: sweep the three constructor input axes
9465 // (`from: &str`, `restart_count: usize`, `other_kinds:
9466 // Vec<&'static str>`) through distinct-per-axis fixtures across a
9467 // boundary matrix of SemVer-2 `from` shapes (release, pre-release,
9468 // pre-release + build-metadata, zero) × non-degenerate
9469 // `restart_count` values (1 — the mixed-with-typed shape, 2 — the
9470 // pure-duplication shape, 3 — the deeply-duplicated shape) ×
9471 // ordered `other_kinds` lisp-form lists spanning the four
9472 // non-`:restart` [`UpgradeInstruction::lisp_form`] arms
9473 // (`:load-module`, `:state-change`, `:soft-purge`, `:purge`) —
9474 // empty (the `((:restart) (:restart))` shape), singleton
9475 // (`((:load-module …) (:restart))`), and the full typed sequence
9476 // (`((:load-module …) (:state-change …) (:soft-purge …) (:purge
9477 // …) (:restart))`) — so any wrapper-side silent lowercase / trim
9478 // / truncate / silent axis-swap (`from` ↔ swap onto
9479 // `restart_count`'s numeric axis, `other_kinds`-vec drop-or-
9480 // duplicate on the four-element owned `Vec<&'static str>`,
9481 // `other_kinds` reorder against declared instruction order) on
9482 // the three-field construction surfaces at assert time rather
9483 // than at a downstream diagnostic consumer that reads the fields
9484 // back and gets a different value than the one it stored. Both
9485 // `&str`-literal and `&String` (via Deref coercion) carriers are
9486 // exercised for `from` because the sole wire-up hands
9487 // `self.prior_versao()` (a `&str` accessor).
9488 let all_typed_kinds: [&'static str; 4] = [
9489 crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE,
9490 crate::render::M2_UPGRADE_INSTRUCTION_KIND_STATE_CHANGE,
9491 crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
9492 crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
9493 ];
9494 let other_kinds_matrix: [Vec<&'static str>; 3] =
9495 [vec![], vec![all_typed_kinds[0]], all_typed_kinds.to_vec()];
9496 let froms: [&str; 4] = ["0.1.0", "1.2.3-rc.1", "0.2.0-alpha.7+build.5", "0.0.0"];
9497 let restart_counts: [usize; 3] = [1, 2, 3];
9498 for other_kinds in &other_kinds_matrix {
9499 for restart_count in restart_counts {
9500 for from in froms {
9501 let from_owned: String = from.to_string();
9502 for from_in in [from, from_owned.as_str()] {
9503 assert_eq!(
9504 UpgradeError::restart_not_exclusive(
9505 from_in,
9506 restart_count,
9507 other_kinds.clone(),
9508 ),
9509 UpgradeError::RestartNotExclusive {
9510 from: from.to_string(),
9511 restart_count,
9512 other_kinds: other_kinds.clone(),
9513 },
9514 "restart_not_exclusive must route from → from, \
9515 restart_count → restart_count, other_kinds → \
9516 other_kinds in declared field order verbatim \
9517 on ({from:?}, {restart_count:?}, \
9518 {other_kinds:?})",
9519 );
9520 }
9521 }
9522 }
9523 }
9524 }
9525
9526 #[test]
9527 fn validate_restart_exclusive_arm_routes_through_restart_not_exclusive_ctor() {
9528 // End-to-end wire-up pin: sweep the three canonical exclusivity-
9529 // violation shapes the `validate_restart_exclusive` gate can
9530 // refuse — restart + one typed instruction (`restart_count: 1,
9531 // other_kinds: [load-module]`), restart + full typed sequence
9532 // (`restart_count: 1, other_kinds: [load-module, state-change,
9533 // soft-purge, purge]`), and duplicated restart only
9534 // (`restart_count: 2, other_kinds: []`) — and pin that each
9535 // observed `Err` byte-equals the substrate-primitive
9536 // [`UpgradeError::restart_not_exclusive`] ctor's output on the
9537 // same fixture. A future silent de-lift of the wire-up back to
9538 // the open-coded struct-literal (or a silent axis-swap on the
9539 // three-field construction at the wire-up site, or an
9540 // `other_kinds` reorder / drop) trips at caixa-core test time
9541 // rather than at a downstream diagnostic consumer far from the
9542 // wire-up commit. Same end-to-end-wire-up discipline as the
9543 // sibling
9544 // `validate_cleanup_singularity_arm_routes_through_duplicate_cleanup_ctor`
9545 // (10a5b48) on the peer per-module cleanup-singularity axis and
9546 // `validate_purge_ordering_arm_routes_through_purge_without_prior_load_ctor`
9547 // on the peer load → cleanup ordering gate; all three key off
9548 // exactly one typed dispatch on the substrate primitive.
9549 let cases: [(&str, Vec<UpgradeInstruction>, usize, Vec<&'static str>); 3] = [
9550 (
9551 "0.1.0",
9552 vec![
9553 UpgradeInstruction::LoadModule {
9554 module: "hello-rio".into(),
9555 },
9556 UpgradeInstruction::Restart,
9557 ],
9558 1,
9559 vec![crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE],
9560 ),
9561 (
9562 "1.2.3-rc.1",
9563 vec![
9564 UpgradeInstruction::LoadModule {
9565 module: "hello-rio".into(),
9566 },
9567 UpgradeInstruction::StateChange {
9568 script: PathBuf::from("lib/m.lisp"),
9569 },
9570 UpgradeInstruction::SoftPurge {
9571 module: "hello-rio-old".into(),
9572 },
9573 UpgradeInstruction::Purge {
9574 module: "hello-rio-old".into(),
9575 },
9576 UpgradeInstruction::Restart,
9577 ],
9578 1,
9579 vec![
9580 crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE,
9581 crate::render::M2_UPGRADE_INSTRUCTION_KIND_STATE_CHANGE,
9582 crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
9583 crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
9584 ],
9585 ),
9586 (
9587 "0.0.0",
9588 vec![UpgradeInstruction::Restart, UpgradeInstruction::Restart],
9589 2,
9590 vec![],
9591 ),
9592 ];
9593 for (from, instructions, restart_count, other_kinds) in cases {
9594 let e = entry(from, instructions);
9595 let observed = e.validate().unwrap_err();
9596 assert_eq!(
9597 observed,
9598 UpgradeError::restart_not_exclusive(from, restart_count, other_kinds.clone()),
9599 "validate_restart_exclusive must route its refusal \
9600 through UpgradeError::restart_not_exclusive(from, \
9601 restart_count, other_kinds) on a mixed-`(:restart)` \
9602 entry, byte-equal to the pre-lift open-coded struct-\
9603 literal wrap on the same fixture",
9604 );
9605 }
9606 }
9607}