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 fn prior_versao(&self) -> &str {
144 &self.from
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 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()).map_err(|e| UpgradeError::FromInvalid {
324 from: self.prior_versao().to_string(),
325 reason: e.to_string(),
326 })?;
327 // Per-instruction typed shape: kind-tagged `:module` /
328 // `:script` value-shape gates fire here, *before* the
329 // within-entry restart-exclusivity gate below — so a
330 // malformed-shape diagnostic on a Module/Script-bearing
331 // instruction surfaces with its narrower self-locating
332 // wording (`ModuleEmpty`, `ModuleInvalid`, `EmptyScript`,
333 // `AbsoluteScript`, `ParentEscapeScript`) rather than
334 // collapsing two unrelated authoring errors into a single
335 // exclusivity diagnostic. Same empty-first cascade discipline
336 // every peer DNS-1123 / path-shape gate inside this module
337 // uses (`validate_module`'s ModuleEmpty arm precedes the
338 // DNS-1123 predicate; `validate` on `StateChange` consults
339 // the lifted `is_sandboxed_relative_path` shape gate first).
340 // Route the per-instruction shape-check fan-out through the
341 // lifted [`Self::instructions`] slice-return accessor rather
342 // than the raw `self.instructions` field access — first of
343 // nine paired production consumers of the per-`:upgrade-from
344 // :instructions` OTP-appup migration-instruction-list surface
345 // that now key off exactly one typed dispatch on the substrate
346 // primitive.
347 for instr in self.instructions() {
348 instr.validate()?;
349 }
350 self.validate_restart_exclusive()?;
351 self.validate_state_change_ordering()?;
352 self.validate_purge_ordering()?;
353 self.validate_state_change_before_cleanup()?;
354 self.validate_load_singularity()?;
355 self.validate_state_change_singularity()?;
356 self.validate_cleanup_singularity()?;
357 Ok(())
358 }
359
360 /// Reject `:upgrade-from :instructions` lists that carry
361 /// `(:restart)` alongside any other instruction, or that carry
362 /// more than one `(:restart)`. The valid Restart-bearing shape is
363 /// exactly `((:restart))` — a single `Restart` as the entry's
364 /// whole instructions list.
365 ///
366 /// Per [`UpgradeInstruction::Restart`]'s doc comment, `(:restart)`
367 /// is the *fallback* for an entry whose typed upgrade is
368 /// impossible (wasm component-model world incompatibility,
369 /// irreversible state shape change). The fallback is terminal by
370 /// construction: the operator restarts the pod and the new version
371 /// comes up fresh, so any other instructions in the same entry
372 /// are dead code in both directions — either the typed sequence
373 /// would have succeeded and `(:restart)` is unreached, or it
374 /// wouldn't and the typed instructions are dead because the
375 /// operator restarts anyway. Two canonical authoring footguns
376 /// close here:
377 ///
378 /// - `((:load-module …) (:state-change …) (:restart))` — the
379 /// "I'll try the typed path *then* restart anyway" footgun.
380 /// There is no coherent OTP-shaped semantic for this: if the
381 /// typed sequence succeeds, the trailing restart discards the
382 /// work that just succeeded (defeating the whole point of
383 /// declaring it); if it fails, the restart is never reached
384 /// because the entry already failed.
385 /// - `((:restart) (:restart))` — multiple `Restart` variants in
386 /// one entry. The fallback is a single semantic; repeating it
387 /// is at best redundant, at worst suggests the author thought
388 /// the second one would re-trigger after the first.
389 ///
390 /// Same within-entry exclusivity discipline OTP's `relup` enforces
391 /// at the `restart_new_emulator | restart_emulator` instruction
392 /// boundary — those instructions are terminal in the upgrade
393 /// script (`systools(3)` rejects sequences that continue past
394 /// them); pleme-io lifts the same shape to a build-time gate,
395 /// matching the CAIXA-SDLC §III "build errors, not runtime
396 /// surprises" frame.
397 ///
398 /// Same within-entry cross-instruction discipline the
399 /// [`crate::AplicacaoSpec::validate_placement`] strategy ↔
400 /// shard-key partition (934bc58) and
401 /// [`validate_upgrade_from_against_versao`]'s `:from` ↔ `:versao`
402 /// precedence partition (de7ab1a) apply on cross-slot axes — now
403 /// extended onto the first within-list cross-instruction axis on
404 /// the `:upgrade-from` typed slot.
405 fn validate_restart_exclusive(&self) -> Result<(), UpgradeError> {
406 // Route the paired restart-count / instructions-len / other-
407 // kind projections through the lifted [`Self::instructions`]
408 // slice-return accessor rather than the raw `self.instructions`
409 // field access — three raw-access sites in one gate collapse
410 // onto exactly one typed dispatch on the substrate primitive.
411 //
412 // The paired positive / negated `Self::Restart` arm-discriminator
413 // predicates route through the `gen_platform::IsVariant`
414 // derive-generated [`UpgradeInstruction::is_restart`] rather than
415 // the raw `matches!(i, UpgradeInstruction::Restart)` /
416 // `!matches!(i, UpgradeInstruction::Restart)` open-coded pattern-
417 // matches — same closed-set-typed-enum arm-discriminator dispatch
418 // discipline the sibling [`crate::CaixaKind`] `IsVariant` derive
419 // (f5bba80) extended onto its ten `caixa.kind() == CaixaKind::X`
420 // / `!= CaixaKind::X` production sites in the substrate's own
421 // layout invariant verifier + typed-view projection gates,
422 // extended here onto the last unlifted `matches!`-based
423 // arm-discriminator axis on the [`UpgradeInstruction`] closed-set
424 // typed enum. A future sixth `UpgradeInstruction` arm (an
425 // adaptive-upgrade-shaped `AwaitReadiness` gate the M2.5
426 // wasm-operator's hot-upgrade runtime could adopt to bracket the
427 // typed instruction sequence against a per-cluster readiness
428 // probe, a `Downgrade` variant OTP's `relup` acknowledges on the
429 // reverse axis, a `CanaryTraffic` split-traffic variant the M4 CR
430 // materializer could resolve per-CR) migrates as a single
431 // enum-declaration edit — the derive auto-generates the paired
432 // `.is_<new_arm>()` predicate; every consumer inherits the new
433 // arm on the next re-derive, rather than the two `matches!` sites
434 // here having to be threaded through in lockstep.
435 let instructions = self.instructions();
436 let restart_count = instructions.iter().filter(|i| i.is_restart()).count();
437 if restart_count == 0 {
438 return Ok(());
439 }
440 if restart_count == 1 && instructions.len() == 1 {
441 return Ok(());
442 }
443 let other_kinds: Vec<&'static str> = instructions
444 .iter()
445 .filter(|i| !i.is_restart())
446 .map(UpgradeInstruction::lisp_form)
447 .collect();
448 Err(UpgradeError::RestartNotExclusive {
449 from: self.prior_versao().to_string(),
450 restart_count,
451 other_kinds,
452 })
453 }
454
455 /// Reject an entry whose `(:state-change …)` is not preceded by a
456 /// `(:load-module …)` in the same `:instructions` list.
457 ///
458 /// `StateChange` is the `gen_server:code_change/3` analog
459 /// ([`UpgradeInstruction::StateChange`] doc; INSPIRATIONS §II.4):
460 /// it runs the migration script that folds the *old* state into the
461 /// shape the *new* code expects. In OTP, `code_change/3` is invoked
462 /// in the context of the newly-loaded code — `release_handler`
463 /// always loads the new module before running the advanced update
464 /// that triggers the callback. caixa decomposes that into two
465 /// explicit instructions (`LoadModule` brings the new version up
466 /// "alongside the current one"; `StateChange` migrates the state),
467 /// and the module doc pins that the operator "runs the instructions
468 /// in order" and only swaps traffic after all succeed. So a
469 /// `:state-change` with no preceding `:load-module` migrates state
470 /// into code that was never loaded — the migration script runs while
471 /// the only resident version is still the *old* one, which expects
472 /// the *old* state. Two authoring footguns close here:
473 ///
474 /// - `((:state-change "…"))` — the "I wrote the migration but
475 /// forgot to load the new module" footgun. The new code that
476 /// defines the new state representation (and that the migration
477 /// output is destined for) never comes up; the operator runs
478 /// the script against the old code and either no-ops or corrupts
479 /// live state.
480 /// - `((:state-change "…") (:load-module "…"))` — the
481 /// right-instructions-wrong-order footgun. Because the operator
482 /// executes in declared order, the migration runs *before* the
483 /// new code is resident, then the load brings up code expecting
484 /// already-migrated state that the just-run script produced
485 /// against the old version's shape. The canonical order is
486 /// `(:load-module …) (:state-change …) (:soft-purge …)`
487 /// (module doc example).
488 ///
489 /// Same within-entry cross-instruction discipline as
490 /// [`Self::validate_restart_exclusive`] (the `(:restart)` terminal-
491 /// exclusivity gate it runs beside): both reject an
492 /// `:instructions` list whose instructions are individually
493 /// well-shaped but jointly incoherent, at the typed build surface
494 /// rather than as a runtime surprise. Runs *after*
495 /// `validate_restart_exclusive` so a `((:state-change …)
496 /// (:restart))` shape still surfaces the more-fundamental
497 /// `RestartNotExclusive` (a valid `(:restart)` entry is `(:restart)`
498 /// alone, so no Restart-bearing entry reaches this gate carrying a
499 /// `StateChange`).
500 fn validate_state_change_ordering(&self) -> Result<(), UpgradeError> {
501 // Route the per-instruction load-family arm-discriminator through
502 // the `gen_platform::IsVariant`-derive-generated
503 // [`UpgradeInstruction::is_load_module`] predicate and the
504 // per-instruction migration-family `:script` scalar projection
505 // through the sibling lifted [`UpgradeInstruction::declared_path`]
506 // `Option<&PathBuf>` accessor rather than the raw two-arm
507 // `match instr { UpgradeInstruction::LoadModule { .. } =>
508 // loaded = true, UpgradeInstruction::StateChange { script } if
509 // !loaded => …, _ => {} }` open-coded pattern-match — closes the
510 // last unlifted `match`-shaped per-arm-hand-rolled load-family
511 // arm-discriminator + migration-family script-projection pair
512 // inside `impl UpgradeFromEntry`. Sibling of the peer
513 // [`Self::validate_purge_ordering`] (580d0f1) routing already
514 // lifted onto [`UpgradeInstruction::is_load_module`] on the paired
515 // load → cleanup ordering axis, the peer
516 // [`Self::validate_load_singularity`] (c9ce91d) routing lifted
517 // onto the [`UpgradeInstruction::is_load_module`] +
518 // [`UpgradeInstruction::declared_module`] pair on the singularity
519 // axis, and the peer [`Self::validate_state_change_singularity`]
520 // routing already lifted onto the sibling
521 // [`UpgradeInstruction::declared_path`] `Option<&PathBuf>`
522 // accessor on the migration-family script-projection axis — both
523 // ordering-gate load-family sticky-latch dispatches now key off
524 // exactly one typed dispatch on the substrate primitive for
525 // their load-family arm-discriminator, and both migration-family
526 // projection sites (this ordering gate + the peer singularity
527 // gate) now key off exactly one typed dispatch on the substrate
528 // primitive for the `:script`-carrying axis. A future sixth arm
529 // on [`UpgradeInstruction`] (an `AwaitReadiness` gate, a
530 // `Downgrade` reverse-axis variant OTP's `relup` acknowledges, a
531 // `CanaryTraffic` split-traffic variant the M4 CR materializer
532 // could resolve per-CR — INSPIRATIONS §II.4) migrates as one
533 // enum-declaration edit through the derive rather than a
534 // coordinated rewrite of every ordering / singularity gate's
535 // per-arm hand-rolled pattern-match. Byte-identity of this
536 // dispatch against the pre-lift `match` shape is pinned by
537 // [`tests::validate_state_change_ordering_projects_scripts_through_is_load_module_and_declared_path_accessors`].
538 let mut loaded = false;
539 for instr in self.instructions() {
540 if instr.is_load_module() {
541 loaded = true;
542 } else if !loaded && let Some(script) = instr.declared_path() {
543 return Err(UpgradeError::StateChangeWithoutPriorLoad {
544 from: self.prior_versao().to_string(),
545 script: script.clone(),
546 });
547 }
548 }
549 Ok(())
550 }
551
552 /// Reject an entry whose `(:soft-purge …)` or `(:purge …)` is not
553 /// preceded by a `(:load-module …)` in the same `:instructions` list.
554 ///
555 /// `SoftPurge` and `Purge` are the `code:soft_purge/1` /
556 /// `code:purge/1` analogs (INSPIRATIONS §II.4): they remove the
557 /// *old* module from memory after the new one is resident. OTP's
558 /// two-phase code load is `code:load_module/1` *then*
559 /// `code:soft_purge/1` — load the new version alongside the old
560 /// (both in memory, new requests route to new), then purge the old
561 /// after in-flight callers drain. caixa decomposes that into two
562 /// explicit instructions (`LoadModule` brings the new version up
563 /// "alongside the current one", per [`UpgradeInstruction::LoadModule`]
564 /// doc; `SoftPurge` "waits for in-flight requests on a named module
565 /// to drain, then GC it", per [`UpgradeInstruction::SoftPurge`] doc),
566 /// and the module doc pins that the operator "runs the instructions
567 /// in order". So a `:soft-purge` / `:purge` with no preceding
568 /// `:load-module` purges old code while the only resident version is
569 /// still the *same* old code, leaving the upgrade entry asking the
570 /// operator to drain or discard the live module with no replacement
571 /// resident. Two authoring footguns close here:
572 ///
573 /// - `((:soft-purge "…"))` / `((:purge "…"))` — the "I wrote the
574 /// cleanup but forgot to load the new module" footgun. The new
575 /// code never comes up alongside; the operator either drains the
576 /// old version to nothing (`SoftPurge`) or discards it outright
577 /// mid-request (`Purge`), with no replacement to route in-flight
578 /// or future requests to.
579 /// - `((:soft-purge "…") (:load-module "…"))` /
580 /// `((:purge "…") (:load-module "…"))` — the right-instructions-
581 /// wrong-order footgun. Because the operator executes in declared
582 /// order, the cleanup runs *before* the new code is resident,
583 /// leaving a window during which neither version is available;
584 /// the canonical order is `(:load-module …) (:state-change …)
585 /// (:soft-purge …)` (module doc example).
586 ///
587 /// Same within-entry cross-instruction discipline as
588 /// [`Self::validate_state_change_ordering`] (the `:state-change`-
589 /// ordering gate it runs beside): both close the same load-before-X
590 /// post-condition on the OTP appup ordering contract, now extending
591 /// the typed coverage from "new code resident before its state
592 /// migration runs" to "new code resident before the old code is
593 /// drained or discarded" — the second half of OTP's two-phase code
594 /// load. Runs *after* `validate_state_change_ordering` so an entry
595 /// like `((:state-change …) (:soft-purge …))` surfaces the more-
596 /// fundamental `StateChangeWithoutPriorLoad` first (both instructions
597 /// are load-less, but state-change is the load-bearing semantic — the
598 /// purge is meaningless either way without a preceding load, so the
599 /// author should see the migration-side diagnostic first).
600 fn validate_purge_ordering(&self) -> Result<(), UpgradeError> {
601 let mut loaded = false;
602 for instr in self.instructions() {
603 // Route the per-instruction cleanup-family arm-discriminator
604 // through the lifted [`UpgradeInstruction::is_cleanup`] typed
605 // predicate rather than the raw
606 // `UpgradeInstruction::SoftPurge { module } |
607 // UpgradeInstruction::Purge { module }` open-coded per-arm
608 // union pattern-match — the first of three within-entry cross-
609 // instruction cleanup-facing gates now keys off exactly one
610 // typed dispatch on the substrate primitive, so any future
611 // fifth cleanup-shaped variant (a `Discard` variant the
612 // `code:delete/1` peer inspires) added to
613 // [`UpgradeInstruction`] + a composing `|| self.is_discard()`
614 // term at [`UpgradeInstruction::is_cleanup`] reaches this gate
615 // through the accessor's one body. The paired cleanup-arm
616 // `:module` scalar is routed through the sibling
617 // [`UpgradeInstruction::declared_module`] accessor rather than
618 // the raw pattern-bound `module` binding — same substrate-
619 // primitive-owns-the-scalar discipline every peer
620 // per-`UpgradeInstruction` scalar-value axis already routes
621 // through, with the `is_cleanup`-implies-`declared_module`-is-
622 // `Some` composition pin at
623 // [`tests::upgrade_instruction_is_cleanup_implies_declared_module_is_some`]
624 // making the `.expect(…)` structurally infallible at build
625 // time. Peer of the sibling
626 // [`UpgradeFromEntry::validate_restart_exclusive`]
627 // paired positive / negated
628 // [`UpgradeInstruction::is_restart`] routing (915a934) on the
629 // per-arm terminal-fallback partition — same closed-set-typed-
630 // enum arm-discriminator dispatch discipline extended from
631 // the single-arm terminal-fallback family onto the two-arm
632 // cleanup family here.
633 //
634 // Route the paired load-family arm-discriminator through the
635 // `gen_platform::IsVariant`-derive-generated
636 // [`UpgradeInstruction::is_load_module`] predicate rather than
637 // the raw `matches!(instr, UpgradeInstruction::LoadModule
638 // { .. })` open-coded pattern-match — closes the last
639 // unlifted `matches!`-based per-variant arm-discriminator
640 // axis on the [`UpgradeInstruction`] closed-set typed enum,
641 // sibling of the [`UpgradeInstruction::is_restart`] terminal-
642 // fallback routing (915a934) and the
643 // [`UpgradeInstruction::is_cleanup`] two-arm cleanup-family
644 // routing (0bc469f) that already lifted the paired
645 // arm-discriminator sites in this method. Every arm-family
646 // partition the gate keys off — load-family (`LoadModule`),
647 // cleanup-family (`SoftPurge | Purge`), terminal-fallback
648 // (`Restart`) — now consults exactly one typed dispatch on
649 // the substrate primitive, so a future sixth arm added to
650 // [`UpgradeInstruction`] (an `AwaitReadiness` gate, a
651 // `Downgrade` reverse-axis variant OTP's `relup` acknowledges,
652 // a `CanaryTraffic` split-traffic variant the M4 CR
653 // materializer could resolve per-CR — INSPIRATIONS §II.4)
654 // migrates as a single enum-declaration edit through the
655 // derive rather than a scattered per-consumer rewrite. The
656 // partition invariant is pinned by
657 // [`tests::upgrade_instruction_is_load_module_predicate_partitions_the_arm_set`]
658 // and the byte-identity of this dispatch against the pre-lift
659 // `matches!` pattern by
660 // [`tests::validate_purge_ordering_routes_through_is_load_module_predicate`].
661 if instr.is_load_module() {
662 loaded = true;
663 } else if instr.is_cleanup() && !loaded {
664 return Err(UpgradeError::PurgeWithoutPriorLoad {
665 from: self.prior_versao().to_string(),
666 kind: instr.lisp_form(),
667 module: instr
668 .declared_module()
669 .expect("is_cleanup() implies declared_module() is Some")
670 .to_string(),
671 });
672 }
673 }
674 Ok(())
675 }
676
677 /// Reject an entry whose `(:state-change …)` appears after any
678 /// `(:soft-purge …)` / `(:purge …)` in the same `:instructions`
679 /// list — completing the canonical OTP appup `code:load_module/1`
680 /// → `gen_server:code_change/3` → `code:soft_purge/1` ordering
681 /// chain on the typed `:upgrade-from` slot.
682 ///
683 /// `StateChange` is the `gen_server:code_change/3` analog
684 /// ([`UpgradeInstruction::StateChange`] doc; INSPIRATIONS §II.4
685 /// verbatim: "State migration uses `gen_server:code_change/3` …
686 /// migrate state from v0.1.0 shape to current shape"). The
687 /// callback's input is the *prior* version's state shape, which
688 /// only exists while the prior code is still resident — the running
689 /// `gen_server` processes hold the v0.1.0 state, and the operator's
690 /// dispatch invokes `code_change/3` to fold that state into the
691 /// current shape. `SoftPurge` / `Purge` are the `code:soft_purge/1`
692 /// / `code:purge/1` analogs ([`UpgradeInstruction::SoftPurge`] /
693 /// [`UpgradeInstruction::Purge`] docs): they drain or discard the
694 /// *old* module after the new one is resident. The operator runs
695 /// instructions in declared order (module doc), so a cleanup ahead
696 /// of a state-change discards the prior code before the migration
697 /// fold runs against the state it held — the canonical OTP error
698 /// mode "`code_change/3` invoked on a purged module" the
699 /// `release_handler` enforces by always emitting the migration
700 /// callback before the soft-purge step.
701 ///
702 /// `systools`-generated `.relup` files always emit `code_change`
703 /// before `soft_purge` for this reason; the appup cookbook's
704 /// canonical pattern (`[{load_module, m}, {update, m, soft},
705 /// {soft_purge, m}]`) places the migration-triggering `update`
706 /// strictly between the load and the cleanup. The caixa module
707 /// doc pins the same canonical order verbatim — `(:load-module
708 /// …) (:state-change …) (:soft-purge …)` — and this gate makes
709 /// that ordering a structural property at build time. Three
710 /// authoring footguns close here:
711 ///
712 /// - `((:load-module "x") (:soft-purge "x-old") (:state-change
713 /// "lib/m.lisp"))` — the right-instructions-wrong-order
714 /// footgun on the migrate ↔ cleanup axis. Because the operator
715 /// executes in declared order, the cleanup drains the v0.1.0
716 /// module to nothing before the migration callback runs, and
717 /// the script either no-ops (no v0.1.0 state left to fold) or
718 /// crashes (`code_change/3` invoked on an unloaded version).
719 /// The canonical order is `(:load-module …) (:state-change
720 /// …) (:soft-purge …)` (module doc example).
721 /// - `((:load-module "x") (:purge "x-old") (:state-change
722 /// "lib/m.lisp"))` — same shape on the more catastrophic
723 /// `:purge` variant. The immediate-discard semantic destroys
724 /// v0.1.0 state mid-request; the trailing migration script
725 /// has nothing to fold from and the `gen_server` processes that
726 /// held v0.1.0 state were killed by the `:purge`.
727 /// - `((:load-module "x") (:soft-purge "x-old") (:state-change
728 /// "lib/m1.lisp") (:soft-purge "y-old"))` — the "migration
729 /// sandwiched between two cleanups" footgun. The first
730 /// cleanup discards v0.1.0; the migration runs against
731 /// drained state; the second cleanup is irrelevant. The first
732 /// cleanup → state-change boundary is the load-bearing defect
733 /// surfaced.
734 ///
735 /// Same within-entry cross-instruction discipline as
736 /// [`Self::validate_state_change_ordering`] (the load → state-
737 /// change ordering gate it runs after) and
738 /// [`Self::validate_purge_ordering`] (the load → cleanup ordering
739 /// gate it runs after): all three close one boundary of the OTP
740 /// canonical sequence `code:load_module/1` →
741 /// `gen_server:code_change/3` → `code:soft_purge/1`. The
742 /// state-change-ordering gate closes the load → migrate boundary;
743 /// the purge-ordering gate closes the load → cleanup boundary;
744 /// this gate closes the migrate → cleanup boundary, completing
745 /// the typed coverage of the canonical sequence. Runs *after*
746 /// [`Self::validate_purge_ordering`] (and therefore after
747 /// [`Self::validate_state_change_ordering`]) so an entry like
748 /// `((:soft-purge "x-old") (:state-change "lib/m.lisp"))` —
749 /// which violates *both* the purge-without-load gate and this
750 /// state-change-after-cleanup gate — surfaces the more-
751 /// fundamental `PurgeWithoutPriorLoad` first (the missing-load
752 /// defect is load-bearing; once a coherent `(:load-module …)`
753 /// precedes both, the migrate ↔ cleanup ordering becomes the
754 /// next live defect). Runs *before* the per-instruction-class
755 /// singularity gates ([`Self::validate_load_singularity`],
756 /// [`Self::validate_state_change_singularity`],
757 /// [`Self::validate_cleanup_singularity`]) so an entry like
758 /// `((:load-module "x") (:soft-purge "x-old") (:state-change
759 /// "lib/m.lisp") (:state-change "lib/m.lisp"))` — which violates
760 /// *both* this ordering gate and the state-change-singularity
761 /// gate — surfaces the ordering defect first; the canonical
762 /// "ordering before singularity" precedence the peer
763 /// `validate_state_change_ordering` / `validate_purge_ordering`
764 /// gates already establish.
765 ///
766 /// Detection: linear scan of the instructions list with a
767 /// `prior_cleanup: Option<(module, kind)>` sticky-once latch
768 /// recording the first cleanup encountered; on any subsequent
769 /// `StateChange` the gate fires with the script + the prior
770 /// cleanup's kind/module. Diagnostic-order pin: the first
771 /// colliding state-change-after-cleanup pair surfaces, not the
772 /// last — mirrors every peer ordering gate's first-collision
773 /// posture ([`Self::validate_state_change_ordering`] returns on
774 /// the first `StateChange` without prior load,
775 /// [`Self::validate_purge_ordering`] on the first cleanup
776 /// without prior load).
777 fn validate_state_change_before_cleanup(&self) -> Result<(), UpgradeError> {
778 let mut prior_cleanup: Option<(&str, &'static str)> = None;
779 for instr in self.instructions() {
780 // Route the per-instruction cleanup-family arm-discriminator
781 // through the lifted [`UpgradeInstruction::is_cleanup`] typed
782 // predicate rather than the raw
783 // `UpgradeInstruction::SoftPurge { module } |
784 // UpgradeInstruction::Purge { module }` open-coded per-arm
785 // union pattern-match — the second of three within-entry
786 // cross-instruction cleanup-facing gates the peer
787 // [`Self::validate_purge_ordering`] routing already lifted;
788 // both now key off exactly one typed dispatch on the substrate
789 // primitive so the "which arms belong to the cleanup family"
790 // question resolves at exactly one caixa-core edit. The
791 // sticky-once latch's `:module` scalar is routed through the
792 // sibling [`UpgradeInstruction::declared_module`] accessor
793 // rather than the raw pattern-bound `module.as_str()`
794 // projection, with the `is_cleanup`-implies-`declared_module`-
795 // is-`Some` composition pin at
796 // [`tests::upgrade_instruction_is_cleanup_implies_declared_module_is_some`]
797 // making the `.expect(…)` structurally infallible at build
798 // time.
799 if instr.is_cleanup() && prior_cleanup.is_none() {
800 prior_cleanup = Some((
801 instr
802 .declared_module()
803 .expect("is_cleanup() implies declared_module() is Some"),
804 instr.lisp_form(),
805 ));
806 } else if let Some(script) = instr.declared_path()
807 && let Some((prior_module, prior_kind)) = prior_cleanup
808 {
809 // Route the per-instruction `StateChange`-arm script-path
810 // projection through the sibling lifted
811 // [`UpgradeInstruction::declared_path`] `Option<&PathBuf>`
812 // accessor rather than the raw
813 // `if let UpgradeInstruction::StateChange { script } = instr`
814 // open-coded pattern-match — the last unlifted per-
815 // `UpgradeInstruction` `PathBuf`-carrying-axis consumer
816 // inside `impl UpgradeFromEntry`, sibling to the four peer
817 // per-`UpgradeInstruction` consumers already routed through
818 // the accessor: [`UpgradeInstruction::validate`]'s per-
819 // `StateChange` sandbox-path fan-out, the layout-side per-
820 // `StateChange` script-existence fan-out at
821 // [`crate::layout::StandardLayout::verify`]
822 // (caixa-core/src/layout.rs:1058), the within-entry
823 // [`UpgradeFromEntry::validate_state_change_singularity`]
824 // per-`StateChange` script-projection fan-out, and the
825 // cross-slot
826 // [`validate_upgrade_from_against_behavior`]
827 // per-`StateChange` detection loop. Byte-equal today
828 // (`declared_path` returns `Some(script)` iff the
829 // instruction is [`UpgradeInstruction::StateChange`], per
830 // the sibling `declared_path_only_for_state_change` pin),
831 // so a state-change-after-cleanup surfaces
832 // `StateChangeAfterCleanup` byte-identical to the pattern-
833 // match shape. Any future accessor extension that promotes
834 // an additional variant onto the `PathBuf`-carrying axis
835 // reaches this gate through one caixa-core edit rather
836 // than a coordinated rewrite of five call sites — the
837 // migrate→cleanup ordering discipline extends to the
838 // promoted variant by construction. Same "one typed
839 // dispatch on the substrate primitive, thin projections at
840 // each consumer" trajectory the sibling
841 // [`UpgradeInstruction::declared_module`] `String`-axis
842 // per-variant unifier already established.
843 return Err(UpgradeError::StateChangeAfterCleanup {
844 from: self.prior_versao().to_string(),
845 script: script.clone(),
846 prior_cleanup_kind: prior_kind,
847 prior_cleanup_module: prior_module.to_string(),
848 });
849 }
850 }
851 Ok(())
852 }
853
854 /// Reject an entry whose `:instructions` list names the same module
855 /// as the target of more than one cleanup instruction (`:soft-purge`
856 /// or `:purge`) in total — set-not-multiset on the (cleanup-class,
857 /// module) axis, narrowed to the cleanup class.
858 ///
859 /// `SoftPurge` and `Purge` are the `code:soft_purge/1` /
860 /// `code:purge/1` analogs (INSPIRATIONS §II.4 verbatim: "1.
861 /// `code:load_module/1` — load v2 alongside v1 … 2.
862 /// `code:soft_purge/1` — wait until no process is running v1, then
863 /// discard. (`code:purge/1` kills v1 immediately if you don't
864 /// care.)"). The author picks *one* cleanup semantic per old
865 /// module — `:soft-purge` (preferred: waits for in-flight callers
866 /// to drain) or `:purge` (when the drain isn't possible) — and the
867 /// operator runs that one in declared order alongside any other
868 /// distinct-module cleanups. systools-generated `.relup` files
869 /// always emit at most one purge per module for this reason; any
870 /// retry / fallback decision is the operator's job on
871 /// instruction failure, not authored into the entry. Three
872 /// authoring footguns close here:
873 ///
874 /// - `((:load-module "x") (:soft-purge "x-old") (:soft-purge "x-old"))`
875 /// — the "I copy-pasted the cleanup line twice" footgun. The
876 /// second `:soft-purge` is a no-op (the module is already gone
877 /// after the first drain-and-discard) or undefined depending
878 /// on the operator's handling of a non-resident-module purge
879 /// request; either way the second instruction carries no
880 /// observable semantic, far from the source caixa.lisp.
881 /// - `((:load-module "x") (:soft-purge "x-old") (:purge "x-old"))`
882 /// — the "soft-then-hard fallback" footgun. The author wrote
883 /// "drain, and if drain didn't clean it up, force-discard",
884 /// but the operator runs instructions unconditionally in
885 /// declared order — the `:purge` fires whether the
886 /// `:soft-purge` already discarded the module or not, so the
887 /// fallback semantic the author imagined is missing; the
888 /// pair is incoherent (drain *and* force-discard semantics
889 /// on one module is two contradictory dispositions). The
890 /// operator's failure-handling surface is its own
891 /// responsibility: if `:soft-purge` doesn't drain within its
892 /// cooldown the operator escalates, not the author's entry.
893 /// - `((:load-module "x") (:purge "x-old") (:soft-purge "x-old"))`
894 /// — same shape on the reversed ordering. The `:purge`
895 /// discards immediately; the trailing `:soft-purge` has no
896 /// module to drain.
897 ///
898 /// Same within-entry exclusivity discipline as
899 /// [`Self::validate_restart_exclusive`] (the `(:restart)` terminal-
900 /// exclusivity gate it joins on the per-module cleanup axis): both
901 /// reject an `:instructions` list whose instructions are
902 /// individually well-shaped but jointly incoherent on a chosen
903 /// semantic axis (restart-fallback for the whole entry there;
904 /// cleanup-semantic for one module here), at the typed build
905 /// surface rather than as a runtime surprise. Runs *after*
906 /// [`Self::validate_purge_ordering`] (the load-before-cleanup
907 /// ordering gate) so an entry like `((:soft-purge "x-old")
908 /// (:soft-purge "x-old"))` surfaces the more-fundamental
909 /// `PurgeWithoutPriorLoad` first (both cleanups are load-less, and
910 /// the missing-load defect is the load-bearing one — the duplicate
911 /// is meaningless either way without the preceding load).
912 ///
913 /// Same set-not-multiset discipline applied to every peer
914 /// duplicate-target axis: `:children :caixa` (dbf50a9 —
915 /// `SupervisorError::DuplicateChildCaixa`), `:membros :caixa`
916 /// (4bb3f3d — `AplicacaoError::MembroDuplicate`), `:contratos`
917 /// (5dbcfaf — `AplicacaoError::ContratoDuplicate`), `:placement
918 /// :clusters` (c7c7799 — `AplicacaoError::PlacementClusterDuplicate`),
919 /// `:entrada :paths` (eb3456d — `AplicacaoError::EntradaPathDuplicate`),
920 /// and `:upgrade-from :from` ([`UpgradeError::DuplicateFrom`]).
921 /// Each closes the same authoring footgun: a Vec authoring surface
922 /// that silently accepts duplicate entries and renders the "second
923 /// wins" (or "operator processes both, second is a no-op or
924 /// errors") shape downstream, far from the source caixa.lisp.
925 /// This gate extends the discipline onto the within-entry
926 /// instruction-target axis — duplicate cleanup targets *within*
927 /// one `:upgrade-from` entry — the peer of the cross-entry
928 /// duplicate-`:from` axis at one level of nesting deeper.
929 ///
930 /// Detection: linear scan of the instructions list collecting
931 /// the (module, kind) pair from every `SoftPurge` / `Purge`
932 /// encountered; on the second occurrence of any module the gate
933 /// fires with the prior kind and the colliding kind in declaration
934 /// order. Diagnostic-order pin: the first colliding pair surfaces,
935 /// not the last — mirrors
936 /// [`validate_upgrade_from`]'s
937 /// `validate_upgrade_from_duplicate_diagnostic_names_second_collision`
938 /// posture (the first detected collision wins) and every peer
939 /// duplicate gate's first-collision discipline.
940 fn validate_cleanup_singularity(&self) -> Result<(), UpgradeError> {
941 let mut seen: Vec<(&str, &'static str)> = Vec::new();
942 for instr in self.instructions() {
943 // Route the per-instruction cleanup-family arm-discriminator
944 // through the lifted [`UpgradeInstruction::is_cleanup`] typed
945 // predicate rather than the raw two-arm
946 // `UpgradeInstruction::SoftPurge { module } => (module.as_str(),
947 // M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE)` /
948 // `UpgradeInstruction::Purge { module } => (module.as_str(),
949 // M2_UPGRADE_INSTRUCTION_KIND_PURGE)` / `_ => continue`
950 // per-arm dispatch — the third of three within-entry cross-
951 // instruction cleanup-facing gates the peer
952 // [`Self::validate_purge_ordering`] +
953 // [`Self::validate_state_change_before_cleanup`] routing
954 // already lifted; all three now key off exactly one typed
955 // dispatch on the substrate primitive, structurally. The
956 // cleanup-target `(module, kind)` pair is projected through
957 // the peer [`UpgradeInstruction::declared_module`] /
958 // [`UpgradeInstruction::lisp_form`] accessors rather than
959 // the per-arm-hand-rolled scalar-value + kind-const pair,
960 // with the `is_cleanup`-implies-`declared_module`-is-`Some`
961 // composition pin at
962 // [`tests::upgrade_instruction_is_cleanup_implies_declared_module_is_some`]
963 // making the `.expect(…)` structurally infallible at build
964 // time. Any future fifth cleanup-shaped variant added under
965 // the `is_cleanup` predicate + registered through the peer
966 // `lisp_form` per-arm kebab-case-const dispatch reaches this
967 // dedup gate through the accessor's one body rather than a
968 // fourth per-arm-hand-rolled scalar/kind projection here.
969 if !instr.is_cleanup() {
970 continue;
971 }
972 let module = instr
973 .declared_module()
974 .expect("is_cleanup() implies declared_module() is Some");
975 let kind = instr.lisp_form();
976 if let Some(prior_idx) = seen.iter().position(|(m, _)| *m == module) {
977 let prior_kind = seen[prior_idx].1;
978 return Err(UpgradeError::DuplicateCleanup {
979 from: self.prior_versao().to_string(),
980 module: module.to_string(),
981 kinds: vec![prior_kind, kind],
982 });
983 }
984 seen.push((module, kind));
985 }
986 Ok(())
987 }
988
989 /// Reject an entry whose `:instructions` list names the same module
990 /// as the target of more than one `(:load-module …)` instruction —
991 /// set-not-multiset on the `LoadModule` axis.
992 ///
993 /// `LoadModule` is the `code:load_module/1` analog (INSPIRATIONS
994 /// §II.4 verbatim: "1. `code:load_module/1` — load v2 alongside v1;
995 /// new code is 'current', old code is 'old'."). The instruction
996 /// brings the new wasm component up resident alongside the old
997 /// one so the operator can route new traffic to the new code
998 /// while in-flight callers drain on the old — and the operator's
999 /// dispatch table reads the module *name* (a caixa name) to bind
1000 /// the component, so two `(:load-module "x")` instructions in one
1001 /// entry ask the operator to re-bind the same component twice.
1002 /// `systools`-generated `.relup` files emit at most one
1003 /// `load_module` per module per upgrade step for this reason; the
1004 /// second load has no observable semantic relative to the first
1005 /// (the component is already resident). Three authoring footguns
1006 /// close here:
1007 ///
1008 /// - `((:load-module "x") (:load-module "x"))` — the "I
1009 /// copy-pasted the load line twice" footgun. The second
1010 /// `:load-module` re-reads the same module name and re-binds
1011 /// the same wasm component — a no-op in both directions
1012 /// (no new code becomes resident; no old code is purged) —
1013 /// and any cleanup / migration the author intended for a
1014 /// *distinct* module is silently absent from the entry.
1015 /// - `((:load-module "x") (:load-module "x") (:state-change …))`
1016 /// — the "I meant to load two distinct modules" typo. The
1017 /// author intended `((:load-module "x") (:load-module "y"))`
1018 /// but renamed both to "x" (or copied the first line and
1019 /// forgot to change the module). The migration runs against
1020 /// code that's resident only on one module name, and the
1021 /// second module the author imagined was being loaded never
1022 /// comes up at all — far from the source caixa.lisp.
1023 /// - `((:load-module "x") (:load-module "x") (:soft-purge "x-old"))`
1024 /// — same shape with a trailing cleanup. The duplicate load
1025 /// is dead code; the cleanup still fires correctly, masking
1026 /// the load-side duplication as a silently-passing entry.
1027 ///
1028 /// Same within-entry exclusivity discipline as
1029 /// [`Self::validate_cleanup_singularity`] (the per-module cleanup-
1030 /// singularity gate this runs beside) on the sibling
1031 /// `LoadModule` axis: both reject an `:instructions` list whose
1032 /// instructions are individually well-shaped but jointly
1033 /// incoherent on a per-module-per-class basis (load-once for the
1034 /// load axis here; cleanup-once for the cleanup axis there), at
1035 /// the typed build surface rather than as a runtime surprise.
1036 /// Runs *after* [`Self::validate_purge_ordering`] (the load-
1037 /// before-cleanup ordering gate) so an entry like
1038 /// `((:state-change "m.lisp") (:load-module "x") (:load-module "x"))`
1039 /// surfaces the more-fundamental `StateChangeWithoutPriorLoad`
1040 /// first (the missing-load defect is load-bearing — the migration
1041 /// runs against unloaded code; the duplicate is meaningless either
1042 /// way without the preceding load). Runs *before*
1043 /// [`Self::validate_cleanup_singularity`] so an entry like
1044 /// `((:load-module "x") (:load-module "x") (:soft-purge "y-old")
1045 /// (:soft-purge "y-old"))` surfaces `DuplicateLoadModule` first —
1046 /// the load axis precedes the cleanup axis in the canonical OTP
1047 /// sequence (`code:load_module/1` then `code:soft_purge/1`) and
1048 /// in [`UpgradeInstruction`] declaration order (`LoadModule`
1049 /// before `SoftPurge`/`Purge`), so the load-side singularity is
1050 /// the load-bearing diagnostic when both fire.
1051 ///
1052 /// Same set-not-multiset discipline applied to every peer
1053 /// duplicate-target axis: `:children :caixa` (dbf50a9 —
1054 /// `SupervisorError::DuplicateChildCaixa`), `:membros :caixa`
1055 /// (4bb3f3d — `AplicacaoError::MembroDuplicate`), `:contratos`
1056 /// (5dbcfaf — `AplicacaoError::ContratoDuplicate`), `:placement
1057 /// :clusters` (c7c7799 — `AplicacaoError::PlacementClusterDuplicate`),
1058 /// `:entrada :paths` (eb3456d — `AplicacaoError::EntradaPathDuplicate`),
1059 /// `:upgrade-from :from` ([`UpgradeError::DuplicateFrom`]), and
1060 /// the per-module cleanup-target axis (9cedd8b —
1061 /// [`UpgradeError::DuplicateCleanup`]). This gate extends the
1062 /// discipline onto the within-entry `LoadModule` instruction-target
1063 /// axis — the third within-entry per-module singularity completing
1064 /// the load+cleanup pair across the OTP two-phase code-load
1065 /// contract.
1066 ///
1067 /// Detection: linear scan of the instructions list collecting the
1068 /// module name from every `LoadModule` encountered; on the second
1069 /// occurrence of any module the gate fires. Diagnostic-order pin:
1070 /// the first colliding occurrence surfaces, not the last — mirrors
1071 /// [`Self::validate_cleanup_singularity`]'s first-collision posture
1072 /// and every peer duplicate gate's first-collision discipline.
1073 fn validate_load_singularity(&self) -> Result<(), UpgradeError> {
1074 let mut seen: Vec<&str> = Vec::new();
1075 for instr in self.instructions() {
1076 // Route the per-instruction load-family arm-discriminator
1077 // through the `gen_platform::IsVariant`-derive-generated
1078 // [`UpgradeInstruction::is_load_module`] predicate rather
1079 // than the raw single-arm `match instr {
1080 // UpgradeInstruction::LoadModule { module } =>
1081 // module.as_str(), _ => continue }` open-coded pattern-
1082 // match — closes the last unlifted `matches!`-shaped
1083 // per-arm-hand-rolled scalar-value + arm-discriminator
1084 // pair inside `impl UpgradeFromEntry`, sibling of the
1085 // peer [`Self::validate_cleanup_singularity`] (0bc469f)
1086 // routing already lifted onto the two-arm cleanup-family
1087 // axis's per-arm arm-discriminator + `:module` projection
1088 // dispatch. The load-target `:module` scalar is projected
1089 // through the sibling [`UpgradeInstruction::declared_module`]
1090 // accessor rather than the per-arm-hand-rolled scalar-
1091 // value binding, with the
1092 // `is_load_module`-implies-`declared_module`-is-`Some`
1093 // composition pin at
1094 // [`tests::upgrade_instruction_is_load_module_implies_declared_module_is_some`]
1095 // making the `.expect(…)` structurally infallible at
1096 // build time. Every arm-family partition the three
1097 // within-entry per-instruction-class singularity gates
1098 // key off — load-family
1099 // ([`UpgradeInstruction::LoadModule`]), cleanup-family
1100 // ([`UpgradeInstruction::SoftPurge`] |
1101 // [`UpgradeInstruction::Purge`]), migration-family
1102 // ([`UpgradeInstruction::StateChange`]) — now consults
1103 // exactly one typed dispatch on the substrate primitive
1104 // (`is_load_module()` here, `is_cleanup()` at
1105 // [`Self::validate_cleanup_singularity`],
1106 // `declared_path()` at
1107 // [`Self::validate_state_change_singularity`]), so a
1108 // future sixth arm added to [`UpgradeInstruction`] (an
1109 // `AwaitReadiness` gate, a `Downgrade` reverse-axis
1110 // variant OTP's `relup` acknowledges, a `CanaryTraffic`
1111 // split-traffic variant the M4 CR materializer could
1112 // resolve per-CR — INSPIRATIONS §II.4) migrates as a
1113 // single enum-declaration edit through the derive rather
1114 // than a scattered per-consumer rewrite. Byte-identity of
1115 // this dispatch against the pre-lift match-pattern is
1116 // pinned by
1117 // [`tests::validate_load_singularity_projects_modules_through_is_load_module_and_declared_module_accessors`].
1118 if !instr.is_load_module() {
1119 continue;
1120 }
1121 let module = instr
1122 .declared_module()
1123 .expect("is_load_module() implies declared_module() is Some");
1124 if seen.contains(&module) {
1125 return Err(UpgradeError::DuplicateLoadModule {
1126 from: self.prior_versao().to_string(),
1127 module: module.to_string(),
1128 });
1129 }
1130 seen.push(module);
1131 }
1132 Ok(())
1133 }
1134
1135 /// Reject an entry whose `:instructions` list names the same script
1136 /// as the target of more than one `(:state-change …)` instruction —
1137 /// set-not-multiset on the `StateChange` axis.
1138 ///
1139 /// `StateChange` is the `gen_server:code_change/3` analog
1140 /// (INSPIRATIONS §II.4: "State migration uses
1141 /// `gen_server:code_change/3`"). The instruction folds the *old*
1142 /// state into the shape the *new* code expects — a one-shot
1143 /// transition from one declared state representation to another.
1144 /// OTP's `release_handler:install_release/1` invokes `code_change/3`
1145 /// exactly once per upgrade per `gen_server`; `systools`-generated
1146 /// `.relup` files emit at most one `code_change` per `gen_server` per
1147 /// upgrade step for this reason. A second `(:state-change "m.lisp")`
1148 /// instruction targeting the same script in one entry re-runs the
1149 /// migration fold — at best a no-op (idempotent script masking a
1150 /// typo where the author intended two distinct scripts) and at
1151 /// worst silent state corruption (non-idempotent fold double-
1152 /// applied: an `add column` migration that runs twice, an
1153 /// `increment counter` that double-bumps, a `rename field` that
1154 /// renames-then-fails the second time). Three authoring footguns
1155 /// close here:
1156 ///
1157 /// - `((:load-module "x") (:state-change "lib/m.lisp")
1158 /// (:state-change "lib/m.lisp"))` — the "I copy-pasted the
1159 /// migration line twice" footgun. The second `:state-change`
1160 /// re-runs the same fold on the already-migrated state — a
1161 /// no-op if the script is idempotent (dead code masking the
1162 /// duplication) or state corruption if not (the migration's
1163 /// pre-condition no longer holds because the post-condition is
1164 /// already in place).
1165 /// - `((:load-module "x") (:state-change "lib/m.lisp")
1166 /// (:state-change "lib/m.lisp") (:soft-purge "x-old"))` — the
1167 /// "duplicate migrate masked by trailing cleanup" footgun. The
1168 /// cleanup still fires correctly, masking the migration-side
1169 /// duplication as a silently-passing entry.
1170 /// - `((:load-module "x") (:state-change "lib/m1.lisp")
1171 /// (:state-change "lib/m1.lisp"))` — the "I meant to migrate
1172 /// two distinct modules" typo. The author intended
1173 /// `(:state-change "lib/m1.lisp") (:state-change "lib/m2.lisp")`
1174 /// but renamed both to `m1.lisp` (or copy-pasted the first line
1175 /// and forgot to change the script). The migration that should
1176 /// have folded the second module's state never runs, far from
1177 /// the source caixa.lisp.
1178 ///
1179 /// Same within-entry exclusivity discipline as
1180 /// [`Self::validate_load_singularity`] (the per-module load-
1181 /// singularity gate it runs after) and
1182 /// [`Self::validate_cleanup_singularity`] (the per-module cleanup-
1183 /// singularity gate it runs before) on the sibling `StateChange`
1184 /// axis: each rejects an `:instructions` list whose instructions
1185 /// are individually well-shaped but jointly incoherent on a per-
1186 /// instruction-class basis (load-once per module for the load
1187 /// axis; migrate-once per script for the migration axis here;
1188 /// cleanup-once per module for the cleanup axis), at the typed
1189 /// build surface rather than as a runtime surprise. Runs *after*
1190 /// [`Self::validate_load_singularity`] so an entry like
1191 /// `((:load-module "x") (:load-module "x") (:state-change
1192 /// "lib/m.lisp") (:state-change "lib/m.lisp"))` surfaces
1193 /// `DuplicateLoadModule` first — the load axis precedes the
1194 /// migration axis in the canonical OTP sequence
1195 /// (`code:load_module/1` then `gen_server:code_change/3`) and in
1196 /// [`UpgradeInstruction`] declaration order (`LoadModule` before
1197 /// `StateChange`), so the load-side singularity is the load-
1198 /// bearing diagnostic when both fire. Runs *before*
1199 /// [`Self::validate_cleanup_singularity`] so an entry like
1200 /// `((:load-module "x") (:state-change "lib/m.lisp") (:state-change
1201 /// "lib/m.lisp") (:soft-purge "y-old") (:soft-purge "y-old"))`
1202 /// surfaces `DuplicateStateChange` first — the migration axis
1203 /// precedes the cleanup axis in the canonical OTP sequence
1204 /// (`code:code_change/3` then `code:soft_purge/1`) and in
1205 /// [`UpgradeInstruction`] declaration order (`StateChange` before
1206 /// `SoftPurge`/`Purge`).
1207 ///
1208 /// Same set-not-multiset discipline applied to every peer
1209 /// duplicate-target axis: `:children :caixa` (dbf50a9 —
1210 /// `SupervisorError::DuplicateChildCaixa`), `:membros :caixa`
1211 /// (4bb3f3d — `AplicacaoError::MembroDuplicate`), `:contratos`
1212 /// (5dbcfaf — `AplicacaoError::ContratoDuplicate`), `:placement
1213 /// :clusters` (c7c7799 — `AplicacaoError::PlacementClusterDuplicate`),
1214 /// `:entrada :paths` (eb3456d — `AplicacaoError::EntradaPathDuplicate`),
1215 /// `:upgrade-from :from` ([`UpgradeError::DuplicateFrom`]), the
1216 /// per-module cleanup-target axis (9cedd8b —
1217 /// [`UpgradeError::DuplicateCleanup`]), and the per-module load-
1218 /// target axis (a503978 — [`UpgradeError::DuplicateLoadModule`]).
1219 /// This gate extends the discipline onto the within-entry
1220 /// `StateChange` instruction-target axis — the third within-entry
1221 /// per-instruction-class singularity, completing the OTP two-phase
1222 /// code-load + state-migration coverage triad
1223 /// (`code:load_module/1` → `gen_server:code_change/3` →
1224 /// `code:soft_purge/1`).
1225 ///
1226 /// Detection: linear scan of the instructions list collecting the
1227 /// script path from every `StateChange` encountered; on the second
1228 /// occurrence of any script the gate fires. Diagnostic-order pin:
1229 /// the first colliding occurrence surfaces, not the last — mirrors
1230 /// [`Self::validate_load_singularity`]'s and
1231 /// [`Self::validate_cleanup_singularity`]'s first-collision posture
1232 /// and every peer duplicate gate's first-collision discipline.
1233 fn validate_state_change_singularity(&self) -> Result<(), UpgradeError> {
1234 // Route the per-instruction `StateChange`-arm script-path
1235 // projection through the sibling lifted
1236 // [`UpgradeInstruction::declared_path`] `Option<&PathBuf>`
1237 // accessor rather than the raw
1238 // `match instr { UpgradeInstruction::StateChange { script } =>
1239 // script.as_path(), _ => continue }` open-coded pattern-match —
1240 // the third within-entry singularity gate's per-instruction
1241 // script-projection site now keys off exactly one typed
1242 // dispatch on the substrate primitive's `PathBuf`-carrying
1243 // axis, sibling to the four peer per-`UpgradeInstruction`
1244 // consumers ([`Self::validate`]'s per-`StateChange`
1245 // sandbox-path fan-out, the layout-side per-`StateChange`
1246 // script-existence fan-out at
1247 // `caixa-core/src/layout.rs:1017`, the cross-slot
1248 // [`validate_upgrade_from_against_behavior`] gate's
1249 // per-`StateChange` detection loop, the future wasm-operator's
1250 // per-`StateChange` runtime hook-dispatch) that already route
1251 // through `declared_path` / `declared_module`. Byte-equal
1252 // today (`declared_path` returns `Some(script)` iff the
1253 // instruction is [`UpgradeInstruction::StateChange`], per the
1254 // sibling `declared_path_only_for_state_change` pin), so a
1255 // duplicate `:state-change` script surfaces
1256 // `DuplicateStateChange` byte-identical to the pattern-match
1257 // shape. Same "one typed dispatch on the substrate primitive,
1258 // thin projections at each consumer" discipline the sibling
1259 // [`UpgradeInstruction::declared_module`] accessor established
1260 // (b13c4f9) on the peer `String`-carrying axis's per-variant
1261 // consumers, extended here onto the last unlifted
1262 // pattern-match on the `PathBuf`-carrying axis inside
1263 // `impl UpgradeFromEntry`.
1264 let mut seen: Vec<&std::path::Path> = Vec::new();
1265 for instr in self.instructions() {
1266 let Some(script) = instr.declared_path() else {
1267 continue;
1268 };
1269 let script = script.as_path();
1270 if seen.contains(&script) {
1271 return Err(UpgradeError::DuplicateStateChange {
1272 from: self.prior_versao().to_string(),
1273 script: script.to_path_buf(),
1274 });
1275 }
1276 seen.push(script);
1277 }
1278 Ok(())
1279 }
1280}
1281
1282/// Validate a whole `:upgrade-from` list: per-entry typed shape via
1283/// [`UpgradeFromEntry::validate`] *and* the cross-entry graph-edge-set
1284/// invariant — at most one `(:from <prior>)` block per parsed semver.
1285///
1286/// OTP's appup picks at most one matching block to apply to the running
1287/// release (`release_handler:install_release/1` matches the loaded
1288/// `:from` against the currently-running version and executes the
1289/// associated instruction sequence; the wasm-operator picks the matching
1290/// block at upgrade time, per `upgrade.rs` module doc). Two blocks with
1291/// the same parsed-semver `:from` are an ambiguous edge in the typed
1292/// upgrade graph — the operator can pick either set deterministically,
1293/// but each set may carry different `LoadModule | StateChange |
1294/// SoftPurge | Purge | Restart` instructions, so the *chosen* path is
1295/// non-deterministic relative to the source caixa.lisp. The author's
1296/// intent is one path per prior version; the typed graph must enforce
1297/// that shape.
1298///
1299/// Same set-not-multiset discipline already applied to every peer
1300/// typed-graph axis: `:children :caixa` (dbf50a9 —
1301/// `SupervisorError::DuplicateChildCaixa`, `child_spec.id` is required-
1302/// unique per supervisor in OTP), `:membros :caixa` (4bb3f3d —
1303/// `AplicacaoError::MembroDuplicate`), `:contratos`
1304/// (5dbcfaf — `AplicacaoError::ContratoDuplicate`), `:placement
1305/// :clusters` (c7c7799 — `AplicacaoError::PlacementClusterDuplicate`),
1306/// and `:entrada :paths` (eb3456d — `AplicacaoError::EntradaPathDuplicate`).
1307/// Each closes the same authoring footgun: a Vec authoring surface that
1308/// silently accepts duplicate entries and renders the "second wins"
1309/// (or "operator picks arbitrarily") shape downstream, far from the
1310/// source caixa.lisp.
1311///
1312/// Duplicates are detected by [`semver::Version`] equality (the
1313/// crate's `PartialEq` compares the full identity — major.minor.patch +
1314/// pre-release + build metadata — so `1.0.0` and `1.0.0-rc.1` and
1315/// `1.0.0+build1` and `1.0.0+build2` are all distinct upgrade paths).
1316/// The conservative choice mirrors what the wasm-operator's
1317/// `:from`-match dispatch can see; collapsing build metadata to catch
1318/// a wider net of duplicates is a future tightening that requires
1319/// coordinating with the operator's match step.
1320///
1321/// Per-entry shape errors fire before the duplicate gate so the
1322/// diagnostic names the malformed slot (`FromInvalid`, `EmptyScript`,
1323/// `ModuleInvalid`, …) rather than collapsing two unrelated authoring
1324/// errors into a single duplicate diagnostic. Mirrors the
1325/// `*_invalid_fires_before_duplicate_check` order pins on every peer
1326/// axis ([`crate::SupervisorSpec::validate`],
1327/// [`crate::AplicacaoSpec::validate_membros`],
1328/// [`crate::AplicacaoSpec::validate_placement`]).
1329pub fn validate_upgrade_from(entries: &[UpgradeFromEntry]) -> Result<(), UpgradeError> {
1330 use semver::Version;
1331 let mut seen: Vec<Version> = Vec::with_capacity(entries.len());
1332 for entry in entries {
1333 entry.validate()?;
1334 // `entry.validate()` accepted this `:from`, so parse cannot
1335 // fail here — the FromInvalid arm above is the only gate
1336 // and both call `Version::parse(entry.prior_versao())`.
1337 let parsed = Version::parse(entry.prior_versao()).expect(
1338 "UpgradeFromEntry::validate must accept `:from` iff Version::parse does — keep the \
1339 two gates aligned",
1340 );
1341 if seen.contains(&parsed) {
1342 return Err(UpgradeError::DuplicateFrom {
1343 from: entry.prior_versao().to_string(),
1344 });
1345 }
1346 seen.push(parsed);
1347 }
1348 Ok(())
1349}
1350
1351/// Reject `:upgrade-from` entries whose `:from` is not strictly less
1352/// than the caixa's current `:versao` (under SemVer-2 precedence — the
1353/// same ordering [`semver::Version::cmp`] implements, with build
1354/// metadata ignored per [SemVer §11][semver-11]).
1355///
1356/// The whole point of an `:upgrade-from :from "<prior>"` block is the
1357/// declarative answer to "given the wasm-operator is loading a node
1358/// running `<prior>`, how do I upgrade it to the *current* `:versao`?"
1359/// (`upgrade.rs` module doc, OTP appup `release_handler:install_release/1`
1360/// semantic). The operator's `:from`-match dispatch loads the
1361/// current `:versao` and matches the *running* version against each
1362/// entry's `:from`; an entry whose `:from >= :versao` is structurally
1363/// unreachable — the operator never runs a version greater than or
1364/// equal to the current `:versao` that it could then "upgrade *to*"
1365/// the current `:versao`. Two authoring footguns close here:
1366///
1367/// - `:from > :versao` (downgrade-shaped) — the canonical
1368/// "I copy-pasted from the next minor version and forgot to bump
1369/// `:versao`" / "I bumped `:versao` then reverted but left the
1370/// `:upgrade-from` entry behind" footgun. Until this gate landed
1371/// `(defcaixa :versao "0.1.5" :upgrade-from ((:from "0.2.0" …)))`
1372/// silently passed `feira build` and the wasm-operator's
1373/// `:from`-match dispatch would never fire on the entry — the
1374/// instructions sat dormant in the caixa.lisp forever, the
1375/// author's intent ("upgrade users coming from 0.2.0") permanently
1376/// unreached because they actually meant to bump `:versao`.
1377///
1378/// - `:from == :versao` (precedence-equal self-upgrade) — the
1379/// "I declared an upgrade from myself to myself" no-op the
1380/// operator's dispatch would either skip silently (no semantic
1381/// transition) or attempt and trivially "succeed" with no
1382/// observable state change. Includes the build-metadata-only
1383/// difference case (`:versao "0.2.0"`, `:from "0.2.0+build.1"`):
1384/// SemVer-2 precedence ignores build metadata so they compare
1385/// equal under [`semver::Version::cmp`] — the gate rejects this
1386/// even though [`UpgradeError::DuplicateFrom`] doesn't (the peer
1387/// gate uses derived `PartialEq` which keeps them distinct;
1388/// they're distinct dispatch keys but the same "from" version
1389/// for our purposes here).
1390///
1391/// Same cross-slot value-shape discipline as
1392/// [`crate::AplicacaoSpec::validate_placement`]'s strategy ↔ shard-key
1393/// partition (934bc58 — the typed partition between two declared
1394/// slots): one slot's value constrains the valid set of another's,
1395/// and the constraint is a structural property visible at validate
1396/// time. The validated set after this gate satisfies
1397/// `entry.from.parse::<Version>().unwrap() < versao.parse::<Version>().unwrap()`
1398/// for every entry, so the future operator-side hot-upgrade dispatch
1399/// step can reach for `entry.from` knowing the precedence relation
1400/// holds without re-deriving it from inline checks.
1401///
1402/// Silent-pass semantics on malformed inputs:
1403///
1404/// - When `versao` itself doesn't parse as semver, this gate
1405/// returns `Ok(())` silently — the narrower
1406/// [`crate::ManifestError::VersaoInvalid`] / [`UpgradeError::FromInvalid`]
1407/// diagnostics are the load-bearing surfaces for those failure
1408/// modes, and surfacing a `FromNotBeforeVersao` over an
1409/// unparseable `:versao` would mask the more actionable root
1410/// cause.
1411/// - Likewise, an entry whose `:from` itself doesn't parse falls
1412/// through to its narrower diagnostic surface
1413/// ([`UpgradeError::FromInvalid`]), which is expected to fire
1414/// via [`validate_upgrade_from`] *before* this gate runs at the
1415/// [`crate::LayoutInvariants`] call site.
1416///
1417/// [semver-11]: https://semver.org/#spec-item-11
1418pub fn validate_upgrade_from_against_versao(
1419 entries: &[UpgradeFromEntry],
1420 versao: &str,
1421) -> Result<(), UpgradeError> {
1422 use semver::Version;
1423 let Ok(current) = Version::parse(versao) else {
1424 // Malformed `:versao` is a separate gate (ManifestError::VersaoInvalid);
1425 // surfacing a precedence-relation diagnostic over an unparseable
1426 // top-level version would mask the more actionable root cause.
1427 return Ok(());
1428 };
1429 for entry in entries {
1430 // Per-entry shape — including a malformed `:from` — is gated
1431 // by [`validate_upgrade_from`] / [`UpgradeFromEntry::validate`]
1432 // upstream at the LayoutInvariants call site; an unparseable
1433 // `:from` here falls through silently to keep the
1434 // FromInvalid diagnostic load-bearing. Same fall-through
1435 // posture as the `versao` arm above.
1436 let Ok(prior) = Version::parse(entry.prior_versao()) else {
1437 continue;
1438 };
1439 if prior >= current {
1440 return Err(UpgradeError::FromNotBeforeVersao {
1441 from: entry.prior_versao().to_string(),
1442 versao: versao.to_string(),
1443 });
1444 }
1445 }
1446 Ok(())
1447}
1448
1449/// Reject `:upgrade-from` entries whose `:instructions` list carries any
1450/// `(:state-change <script>)` instruction unless the caixa also declares
1451/// `:behavior :on-state-change` — the runtime callback the per-version
1452/// migration script is delivered through during hot upgrade.
1453///
1454/// The module doc on [`crate::upgrade`] pins the composition verbatim:
1455/// the `:upgrade-from` slot "Composes with the `:behavior :on-state-change`
1456/// callback to deliver state migration during hot upgrades." The peer
1457/// module doc on [`crate::BehaviorSpec::on_state_change`] mirrors the
1458/// promise from the callback side: the slot is the
1459/// `gen_server:code_change/3` analog — "receives old state + version,
1460/// returns new state. Composes with the `:upgrade-from` slot declared at
1461/// the Caixa root." OTP's `release_handler:install_release/1` realizes
1462/// the composition by invoking the running `gen_server`'s
1463/// `code_change/3` callback during the appup's `code_change` /
1464/// `update, m, soft` step — the appup's instruction triggers the
1465/// callback, the callback folds the prior-version state shape into the
1466/// current-version shape, and the operator advances to the next
1467/// instruction only after the callback returns successfully. caixa
1468/// decomposes the same composition into two typed slots: the per-version
1469/// migration logic lives in the `(:state-change "lib/migrations/v01-to-v02.lisp")`
1470/// instruction's `:script` (the `:upgrade-from` author surface), and the
1471/// runtime hook the operator dispatches the migration through lives in
1472/// the `:behavior :on-state-change` callback (the `:behavior` author
1473/// surface). A `:state-change` instruction declared without the callback
1474/// is half the composition: the per-version script the author wrote has
1475/// no runtime delivery path, and the operator's hot-upgrade dispatch
1476/// reaches for `caixa.behavior.on_state_change` at the migration step,
1477/// finds `None`, and either fails the upgrade mid-flight (the
1478/// transactional rollback the module doc names — "On any failure, the
1479/// current version stays load-bearing — a typed atomic upgrade") or
1480/// silently skips the migration depending on the operator's handling of
1481/// a missing callback, both far from the source caixa.lisp.
1482///
1483/// Two authoring footguns close here:
1484///
1485/// - `(:behavior ((:on-init …)))` + `(:upgrade-from ((:from "0.1.0"
1486/// :instructions ((:load-module "x") (:state-change "lib/m.lisp")
1487/// (:soft-purge "x-old")))))` — the "I declared the migration script
1488/// but forgot the callback" footgun. The author wrote the per-version
1489/// fold against the prior state shape, the typed `:upgrade-from`
1490/// slot validated every per-instruction shape + ordering + singularity
1491/// gate, and the missing callback only surfaces at upgrade time as
1492/// either a transactional rollback to the prior version (no progress
1493/// across the upgrade) or as a silently-skipped migration that leaves
1494/// v0.2.0 code running against unmigrated v0.1.0 state (corrupted
1495/// state shape).
1496/// - `:behavior` absent entirely + `:upgrade-from` carrying any
1497/// `:state-change` — the "I added the upgrade path but never declared
1498/// `:behavior`" footgun. `:behavior` is optional at the typed root
1499/// ([`crate::Caixa::behavior: Option<BehaviorSpec>`]) so the typed
1500/// `:upgrade-from` slot validates on its own merits, but a `Caixa`
1501/// with `behavior: None` and a `:state-change` instruction is the
1502/// same missing-callback shape — the operator's dispatch can't reach
1503/// a callback that doesn't exist.
1504///
1505/// Same cross-slot composition discipline as
1506/// [`validate_upgrade_from_against_versao`] (the `:from` ↔ `:versao`
1507/// precedence gate at the peer wire-up site): one slot's value
1508/// (`:from` < `:versao` there; `:state-change` declared here) constrains
1509/// the valid set of another's (the entry must be dispatchable there; the
1510/// callback must be declared here), and the constraint is a structural
1511/// property visible at validate time. The validated set after this gate
1512/// satisfies the documented composition: every `:state-change`
1513/// instruction the operator iterates at hot-upgrade time has a
1514/// corresponding `:on-state-change` callback declared on the same caixa,
1515/// so the future wasm-operator's hot-upgrade dispatch (the OTP
1516/// `release_handler` canonical-sequence loop) can reach for
1517/// `behavior.on_state_change` at the migration step knowing the
1518/// `Option<PathBuf>` is `Some(_)` without re-deriving the precondition
1519/// from inline checks.
1520///
1521/// Diagnostic-precedence:
1522///
1523/// - Runs *after* [`UpgradeFromEntry::validate`] (per-instruction
1524/// shape + the within-entry ordering / singularity gates) and
1525/// [`validate_upgrade_from`] (the cross-entry duplicate-`:from`
1526/// gate), so a malformed `:state-change` (`EmptyScript`,
1527/// `AbsoluteScript`, `ParentEscapeScript`) or an ill-ordered entry
1528/// (`StateChangeWithoutPriorLoad`, `StateChangeAfterCleanup`) or a
1529/// duplicate `:from` (`DuplicateFrom`) surfaces its narrower
1530/// self-locating diagnostic first — the canonical "per-instr-shape +
1531/// within-entry ordering + cross-entry uniqueness before
1532/// cross-slot composition" precedence the peer
1533/// `validate_upgrade_from_against_versao` gate establishes at the
1534/// same wire-up site. Without this precedence pin a malformed
1535/// `:state-change` instruction would surface this gate's
1536/// missing-callback diagnostic over the narrower
1537/// `EmptyScript` / `StateChangeWithoutPriorLoad`, masking the
1538/// load-bearing per-instruction defect with a cross-slot composition
1539/// diagnostic.
1540/// - Within the entries, walks the list in declaration order and
1541/// surfaces the *first* `:state-change` instruction encountered —
1542/// mirrors every peer first-collision diagnostic posture on this
1543/// module (`validate_state_change_ordering` returns on the first
1544/// `StateChange` without prior load,
1545/// `validate_load_singularity` returns on the second matching
1546/// module, etc.). A future entry's later `:state-change` doesn't
1547/// surface a different diagnostic — the missing callback is the same
1548/// defect regardless of which entry's `:state-change` exposes it.
1549///
1550/// Silent-pass semantics:
1551///
1552/// - Entries carrying no `:state-change` instruction (load-only,
1553/// cleanup-only, restart-only, or empty `:instructions`) leave the
1554/// gate vacuous — no per-version migration means no callback to
1555/// dispatch through, so the absence of `:on-state-change` is
1556/// coherent. Pins the gate's identity element on the empty-set side
1557/// of the composition.
1558/// - `behavior: None` is *not* a free pass when a `:state-change`
1559/// instruction is present — the same missing-callback shape as
1560/// `behavior: Some(_)` with `on_state_change: None`. The gate reads
1561/// `behavior.and_then(BehaviorSpec::on_state_change)` so both shapes
1562/// surface the same diagnostic.
1563pub fn validate_upgrade_from_against_behavior(
1564 entries: &[UpgradeFromEntry],
1565 behavior: Option<&crate::BehaviorSpec>,
1566) -> Result<(), UpgradeError> {
1567 if behavior
1568 .and_then(crate::BehaviorSpec::on_state_change)
1569 .is_some()
1570 {
1571 return Ok(());
1572 }
1573 for entry in entries {
1574 // Route the per-instruction `StateChange`-arm script-path
1575 // projection through the sibling lifted
1576 // [`UpgradeInstruction::declared_path`] `Option<&PathBuf>`
1577 // accessor rather than the raw
1578 // `if let UpgradeInstruction::StateChange { script } = instr`
1579 // open-coded pattern-match — the cross-slot
1580 // `:upgrade-from ↔ :behavior` composition gate's per-instruction
1581 // script-projection site now keys off exactly one typed dispatch
1582 // on the substrate primitive's `PathBuf`-carrying axis, sibling
1583 // to the four peer per-`UpgradeInstruction` consumers
1584 // ([`UpgradeInstruction::validate`]'s per-`StateChange`
1585 // sandbox-path fan-out, the layout-side per-`StateChange`
1586 // script-existence fan-out at
1587 // [`crate::layout::StandardLayout::verify`] (caixa-core/src/layout.rs:1058),
1588 // the within-entry [`UpgradeFromEntry::validate_state_change_singularity`]
1589 // (2bf3ce5) per-`StateChange` script-projection fan-out, the
1590 // peer [`UpgradeInstruction::declared_module`] `String`-axis
1591 // per-variant unifier) that already route through
1592 // `declared_path` / `declared_module`. Byte-equal today
1593 // (`declared_path` returns `Some(script)` iff the instruction is
1594 // [`UpgradeInstruction::StateChange`], per the sibling
1595 // `declared_path_only_for_state_change` pin), so a
1596 // `:state-change`-without-`:on-state-change`-callback
1597 // composition surfaces `StateChangeWithoutOnStateChangeCallback`
1598 // byte-identical to the pattern-match shape. Fourth (and last)
1599 // per-`UpgradeInstruction`-consumer of the `PathBuf`-carrying
1600 // axis now routed through the accessor — closes the last
1601 // unlifted `if let UpgradeInstruction::StateChange { script } = instr`
1602 // site outside `impl UpgradeFromEntry`, so the peer four
1603 // consumer set named in the sibling
1604 // `validate_state_change_singularity_projects_scripts_through_declared_path_accessor`
1605 // pin (caixa-core/src/upgrade.rs:4598) is now structurally
1606 // closed.
1607 for instr in entry.instructions() {
1608 if let Some(script) = instr.declared_path() {
1609 return Err(UpgradeError::StateChangeWithoutOnStateChangeCallback {
1610 from: entry.prior_versao().to_string(),
1611 script: script.clone(),
1612 });
1613 }
1614 }
1615 }
1616 Ok(())
1617}
1618
1619impl UpgradeInstruction {
1620 /// Kebab-case lisp form name for this instruction, used as the
1621 /// `:kind` tag in [`UpgradeError::ModuleEmpty`] /
1622 /// [`UpgradeError::ModuleInvalid`] diagnostics so the author can
1623 /// grep their caixa.lisp for `(:load-module …)` / `(:soft-purge …)`
1624 /// / `(:purge …)` and fix it in one edit. Mirrors the kebab-case
1625 /// slot tags `BehaviorError::EmptyPath` (b0c8389) and
1626 /// `UpgradeFromEntry`'s `:from` field already carry.
1627 #[must_use]
1628 const fn lisp_form(&self) -> &'static str {
1629 match self {
1630 Self::LoadModule { .. } => crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE,
1631 Self::StateChange { .. } => crate::render::M2_UPGRADE_INSTRUCTION_KIND_STATE_CHANGE,
1632 Self::SoftPurge { .. } => crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
1633 Self::Purge { .. } => crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
1634 Self::Restart => crate::render::M2_UPGRADE_INSTRUCTION_KIND_RESTART,
1635 }
1636 }
1637
1638 /// Validate the instruction's typed shape. Path existence is
1639 /// checked separately by [`crate::layout::StandardLayout`].
1640 ///
1641 /// The per-variant scalar the value-shape gates fire against is
1642 /// read through this method's two sibling accessors — the
1643 /// `String`-carrying axis via [`Self::declared_module`] (the
1644 /// `LoadModule` / `SoftPurge` / `Purge` variants unifying on their
1645 /// K8s DNS-1123-label `:module` reference) and the `PathBuf`-
1646 /// carrying axis via [`Self::declared_path`] (the `StateChange`
1647 /// variant's tatara-lisp `:script`) — rather than the per-arm
1648 /// `Self::LoadModule { module } | Self::SoftPurge { module } |
1649 /// Self::Purge { module }` pattern the module-axis previously
1650 /// open-coded and the per-arm `Self::StateChange { script }` the
1651 /// script-axis previously open-coded. Every scalar this enum
1652 /// carries now flows through one of the two `Option<&…>`
1653 /// accessors, so a future extension of either axis (a fifth
1654 /// module-bearing variant, an operator-side pre-parsed scalar
1655 /// cache the accessors materialize behind the same return
1656 /// contract, an M4 typed sub-slot the accessors could route
1657 /// alongside the existing scalar) migrates as a single edit on
1658 /// the accessor rather than a coordinated rewrite of every
1659 /// downstream value-shape gate. `Restart` (the only variant that
1660 /// carries neither scalar) falls through both `Option` checks and
1661 /// returns `Ok(())` — the terminal-fallback shape the
1662 /// [`Self::Restart`] variant doc pins.
1663 pub fn validate(&self) -> Result<(), UpgradeError> {
1664 if let Some(module) = self.declared_module() {
1665 return validate_module(self.lisp_form(), module);
1666 }
1667 if let Some(script) = self.declared_path() {
1668 // Delegate the four-arm cascade (empty / absolute /
1669 // parent-escape / non-`.lisp`-extension) to the lifted
1670 // [`crate::render::require_sandboxed_lisp_path`] helper —
1671 // same `Empty → Absolute → ParentEscape → NonLispExtension`
1672 // arm-ordering this method previously inlined verbatim,
1673 // now shared with [`crate::BehaviorSpec::validate`]'s
1674 // per-`:on-*`-callback gate so every author-supplied
1675 // tatara-lisp source path on every M2 typed slot consults
1676 // one gate, not two-and-counting verbatim copies of the
1677 // same four-arm cascade. Each closure wraps the tag in
1678 // the same `*Script` variant the original inline code
1679 // raised, so the diagnostic shape every caller depends
1680 // on (the `:state-change :script` self-locating error)
1681 // is preserved by construction. See
1682 // [`crate::render::require_sandboxed_lisp_path`] for the
1683 // smallest-scope-arm-fires-last ordering rationale.
1684 crate::render::require_sandboxed_lisp_path(
1685 script,
1686 || UpgradeError::EmptyScript,
1687 || UpgradeError::AbsoluteScript {
1688 script: script.clone(),
1689 },
1690 || UpgradeError::ParentEscapeScript {
1691 script: script.clone(),
1692 },
1693 || UpgradeError::NonLispExtensionScript {
1694 script: script.clone(),
1695 },
1696 )?;
1697 }
1698 // `Restart` (the only variant with no `Option<&…>`-carrying
1699 // scalar) falls through both accessor gates and returns
1700 // `Ok(())` — the terminal-fallback shape.
1701 Ok(())
1702 }
1703
1704 /// The `:module` scalar carried by this instruction — the
1705 /// K8s DNS-1123-label OTP-appup caixa-name reference every
1706 /// [`Self::LoadModule`] / [`Self::SoftPurge`] / [`Self::Purge`]
1707 /// variant declares against, and every author expects `feira lint`
1708 /// to name verbatim in per-instruction diagnostics. Returns `None`
1709 /// on [`Self::StateChange`] (which carries a `:script` — closed by
1710 /// the sibling [`Self::declared_path`]) and on [`Self::Restart`]
1711 /// (which carries no data at all, the OTP terminal-fallback
1712 /// shape).
1713 ///
1714 /// Sibling in shape to [`Self::declared_path`] on the second and
1715 /// final scalar-carrying axis of [`UpgradeInstruction`]:
1716 /// `declared_path` closes the `PathBuf`-carrying arm
1717 /// (`StateChange`); `declared_module` closes the `String`-carrying
1718 /// arms (`LoadModule` / `SoftPurge` / `Purge`). Every scalar the
1719 /// enum carries now routes through one of the two `Option<&…>`
1720 /// accessors — a caller that doesn't care which variant declared
1721 /// the scalar reads through one `if let Some(…)` rather than a
1722 /// per-variant pattern match. The pair is the enum-variant-
1723 /// unifying peer of the per-mesh-slot-atom scalar-accessor family
1724 /// on the M3 side ([`crate::WitContract::source`] /
1725 /// [`crate::WitContract::destination`] /
1726 /// [`crate::WitContract::world_ref`] closing `:contratos`;
1727 /// [`crate::Entrada::hostname`] / [`crate::Entrada::destination`]
1728 /// closing `:entrada`; [`crate::Membro::nome`] /
1729 /// [`crate::Membro::versao_requirement`] closing `:membros`) and
1730 /// on the M2 side ([`crate::UpgradeFromEntry::prior_versao`]
1731 /// closing per-entry `:from`; the [`crate::LimitsSpec`] /
1732 /// [`crate::BehaviorSpec`] closed families; the [`crate::ChildSpec`]
1733 /// closed OTP-shape supervisor family) — those peer accessors
1734 /// return a struct field verbatim; this pair unifies enum-
1735 /// variant-carried scalars into one accessor per typed axis.
1736 ///
1737 /// Byte-for-byte from the typed variant's own `String` storage;
1738 /// no cloning, no re-parsing. A future extension of the axis (an
1739 /// M4 typed sub-slot the module string is derived from, an
1740 /// operator-side pre-parsed caixa-name cache the accessor could
1741 /// materialize behind the same `&str` return contract, a fifth
1742 /// module-bearing OTP-appup variant the enum grows) migrates as
1743 /// a single caixa-core edit rather than a coordinated rewrite
1744 /// of every downstream module-axis consumer (currently
1745 /// [`Self::validate`]'s DNS-1123-label gate through
1746 /// [`validate_module`]; extensible to future consumers on the
1747 /// same axis without further per-variant match sites).
1748 #[must_use]
1749 pub fn declared_module(&self) -> Option<&str> {
1750 match self {
1751 Self::LoadModule { module } | Self::SoftPurge { module } | Self::Purge { module } => {
1752 Some(module.as_str())
1753 }
1754 Self::StateChange { .. } | Self::Restart => None,
1755 }
1756 }
1757
1758 /// If the instruction references an on-disk path, return it —
1759 /// used by the layout checker to verify the path resolves.
1760 ///
1761 /// Sibling on the `PathBuf`-carrying axis to [`Self::declared_module`]
1762 /// on the `String`-carrying axis: `declared_path` closes the
1763 /// `StateChange` arm's `:script`; `declared_module` closes the
1764 /// `LoadModule` / `SoftPurge` / `Purge` arms' `:module`. Together
1765 /// they route every scalar this enum carries through one of two
1766 /// `Option<&…>` accessors, so [`Self::validate`]'s value-shape
1767 /// gates dispatch on the accessor return rather than a per-variant
1768 /// pattern match on the enum shape itself.
1769 ///
1770 /// Four per-`UpgradeInstruction` consumers now key off this
1771 /// accessor's `PathBuf`-carrying axis:
1772 /// [`Self::validate`]'s per-`StateChange` sandbox-path fan-out,
1773 /// [`crate::layout::StandardLayout::verify`]'s per-`StateChange`
1774 /// script-existence fan-out at `caixa-core/src/layout.rs:1058`, the
1775 /// within-entry
1776 /// [`UpgradeFromEntry::validate_state_change_singularity`] (2bf3ce5)
1777 /// per-`StateChange` script-projection fan-out, and the cross-slot
1778 /// [`validate_upgrade_from_against_behavior`] `:upgrade-from ↔
1779 /// :behavior` composition gate's per-`StateChange` detection loop
1780 /// — every downstream consumer of the `PathBuf`-carrying axis
1781 /// reaches through this one dispatch, so a future accessor
1782 /// extension (an M4 typed sub-slot the script path is derived from,
1783 /// an operator-side pre-resolved-path cache the accessor
1784 /// materializes behind the same `Option<&PathBuf>` return contract,
1785 /// a fifth `PathBuf`-bearing OTP-appup variant the enum grows)
1786 /// migrates as a single caixa-core edit rather than a coordinated
1787 /// rewrite of four call sites.
1788 #[must_use]
1789 pub fn declared_path(&self) -> Option<&PathBuf> {
1790 match self {
1791 Self::StateChange { script } => Some(script),
1792 _ => None,
1793 }
1794 }
1795
1796 /// Substrate-canonical per-`UpgradeInstruction` OTP-appup cleanup-
1797 /// family arm-discriminator predicate every within-entry cross-
1798 /// instruction cleanup-facing gate keys off — true iff `self` is
1799 /// [`Self::SoftPurge`] (`code:soft_purge/1` analog: drain the
1800 /// named module until no process is running it, then GC) or
1801 /// [`Self::Purge`] (`code:purge/1` analog: discard the named
1802 /// module immediately, without waiting for drain), the two OTP
1803 /// two-phase-code-load cleanup arms the closed-set enum's
1804 /// non-terminal / non-migration / non-load variants exhaust.
1805 /// Every non-cleanup arm ([`Self::LoadModule`] on the paired
1806 /// two-phase-load half, [`Self::StateChange`] on the
1807 /// `gen_server:code_change/3`-analog migration axis,
1808 /// [`Self::Restart`] on the OTP terminal-fallback shape)
1809 /// returns `false`.
1810 ///
1811 /// Prior to this lift the `Self::SoftPurge { module } |
1812 /// Self::Purge { module }` two-arm cleanup-family pattern-
1813 /// match sat inline at three within-entry cross-instruction
1814 /// gate sites, each hand-rolling its own copy of the union
1815 /// with no compile-time link back to the substrate primitive's
1816 /// closed-set arm-family: [`UpgradeFromEntry::validate_purge_ordering`]
1817 /// at caixa-core/src/upgrade.rs:570 (guarded arm firing
1818 /// [`UpgradeError::PurgeWithoutPriorLoad`] on any cleanup
1819 /// arriving before a preceding [`Self::LoadModule`]),
1820 /// [`UpgradeFromEntry::validate_state_change_before_cleanup`]
1821 /// at caixa-core/src/upgrade.rs:689 (sticky-once latch
1822 /// recording the first-encountered cleanup so a subsequent
1823 /// [`Self::StateChange`] fires [`UpgradeError::StateChangeAfterCleanup`]),
1824 /// and [`UpgradeFromEntry::validate_cleanup_singularity`] at
1825 /// caixa-core/src/upgrade.rs:800 (per-module cleanup-target
1826 /// dedup ejecting [`UpgradeError::DuplicateCleanup`] on the
1827 /// second cleanup targeting the same `:module`). Three open-
1828 /// coded per-arm-union pattern-matches that expressed no
1829 /// compile-time link back to the substrate primitive. A future
1830 /// fifth cleanup-shaped variant (a `Discard` variant the
1831 /// `code:delete/1` peer inspires that folds under the same
1832 /// two-phase-load cleanup partition, an M4 `SoftPurge` split
1833 /// into `SoftPurgeCoop` / `SoftPurgeForce` peers as the drain-
1834 /// cool-down policy grows a two-arm shape, an operator-side
1835 /// pre-resolved cleanup-decision cache the predicate could
1836 /// route through the same `bool` return contract) would have
1837 /// had to be threaded through every open-coded per-arm-union
1838 /// pattern-match in lockstep or one gate would silently
1839 /// classify the new arm outside the cleanup family while the
1840 /// peer gates classified it in (or vice versa) — a
1841 /// classification split across the three within-entry cross-
1842 /// instruction gates at build time that lands far from the
1843 /// source [`UpgradeInstruction`] declaration with no field
1844 /// naming which gate carries the drifted arm-set. Lifting the
1845 /// resolution to a typed predicate on the substrate primitive
1846 /// means every downstream cleanup-facing consumer of the
1847 /// [`UpgradeInstruction`] closed-set enum reaches for exactly
1848 /// one typed dispatch — the resolver's arm-set migrates as a
1849 /// unit on any future arm addition composing under this
1850 /// predicate's `||` chain.
1851 ///
1852 /// Sibling in shape to the peer [`gen_platform::IsVariant`]-
1853 /// derive-generated [`Self::is_restart`] terminal-fallback
1854 /// arm-discriminator predicate on the same closed-set
1855 /// [`UpgradeInstruction`] enum (each names an OTP-appup arm-
1856 /// family partition as one typed dispatch on the substrate
1857 /// primitive; `is_restart` on the single-arm terminal-
1858 /// fallback family, `is_cleanup` on the two-arm cleanup
1859 /// family), extended here from the single-arm case onto the
1860 /// two-arm arm-family union case. Composes through the
1861 /// [`gen_platform::IsVariant`]-derive-generated
1862 /// [`Self::is_soft_purge`] / [`Self::is_purge`] per-variant
1863 /// predicates rather than an open-coded raw `matches!`
1864 /// pattern-match, so a future rebrand on either underlying
1865 /// per-arm classifier flows through this predicate's one
1866 /// body without a coordinated per-consumer rewrite across
1867 /// the three within-entry cross-instruction gates that route
1868 /// through it. Peer of the sibling per-`:contratos`
1869 /// shape-family union predicates [`crate::WitContract::is_http`] /
1870 /// [`crate::WitContract::is_pubsub`] / [`crate::WitContract::is_store`]
1871 /// on the M3 mesh-slot per-`:wit` world-ref axis (each unions a
1872 /// per-shape WIT-prefix rule the substrate primitive's arm-
1873 /// family partition names as one typed dispatch) — the same
1874 /// "one typed dispatch on the substrate primitive, thin
1875 /// projections at each consumer" discipline extended onto the
1876 /// M2 `:upgrade-from :instructions` per-`UpgradeInstruction`
1877 /// cleanup-family axis.
1878 ///
1879 /// The name `is_cleanup` maps directly onto the canonical
1880 /// OTP-appup vocabulary (INSPIRATIONS §II.4 verbatim: "2.
1881 /// `code:soft_purge/1` — wait until no process is running v1,
1882 /// then discard. (`code:purge/1` kills v1 immediately if you
1883 /// don't care.)" — the two `code:*_purge/1` operations are
1884 /// the two-phase-load contract's cleanup half, paired under
1885 /// one concept), and the peer [`Self::validate_cleanup_singularity`]
1886 /// / [`UpgradeError::DuplicateCleanup`] / [`UpgradeError::PurgeWithoutPriorLoad`]
1887 /// / [`UpgradeError::StateChangeAfterCleanup`] surface already
1888 /// reaches for the same "cleanup" vocabulary in identifier +
1889 /// diagnostic form.
1890 #[must_use]
1891 pub const fn is_cleanup(&self) -> bool {
1892 self.is_soft_purge() || self.is_purge()
1893 }
1894}
1895
1896/// Reject upgrade instruction `:module` values that aren't K8s
1897/// DNS-1123 labels. Thin wrapper around
1898/// [`crate::render::is_dns_1123_label`] that maps the shared
1899/// parser-shaped reason into the kind-tagged
1900/// [`UpgradeError::ModuleEmpty`] / [`UpgradeError::ModuleInvalid`]
1901/// diagnostics, so the author can grep their caixa.lisp for the
1902/// offending `(:<kind> <module>)` form and fix it in one edit.
1903///
1904/// The contract — the same DNS-1123 label rule the K8s apiserver
1905/// enforces on every `metadata.name` / Service name / label value the
1906/// module name lands in. Each upgrade instruction's `:module` is a
1907/// reference to a caixa name (the wasm-engine resolves it through the
1908/// same `ComputeUnit` registry the operator manages), so the value must
1909/// match every downstream apiserver-side schema: the per-Servico
1910/// `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name` the operator
1911/// creates, the `LABEL_PROGRAM` label value the wasm-engine matches
1912/// against the loaded-module table at hot-upgrade dispatch, and the
1913/// future `:upgrade-from`-driven `app-operator` rolling-load CR's
1914/// per-module reference axis. Same trajectory as `:children :caixa`
1915/// (31bfa43), `:membros :caixa` (3f9d7a0), and `:placement :clusters`
1916/// (6cbb900) onto the fourth DNS-1123-label-shaped identifier axis —
1917/// appup's `LoadModule | SoftPurge | Purge` `:module` references.
1918///
1919/// Empty input is rejected via the narrower [`UpgradeError::ModuleEmpty`]
1920/// variant before this predicate is consulted, mirroring
1921/// `validate_membro_caixa`'s empty-first cascade.
1922fn validate_module(kind: &'static str, module: &str) -> Result<(), UpgradeError> {
1923 // Routes through the shared
1924 // [`crate::render::require_valid_dns_1123_label`] gate the peer
1925 // name axes each land on. The `kind: &'static str` field flows
1926 // through both error variants so the diagnostic names which
1927 // per-instruction slot (`LoadModule` / `SoftPurge` / `Purge`) the
1928 // offending value came from.
1929 crate::render::require_valid_dns_1123_label(
1930 module,
1931 || UpgradeError::ModuleEmpty { kind },
1932 |reason| UpgradeError::ModuleInvalid {
1933 kind,
1934 module: module.to_string(),
1935 reason,
1936 },
1937 )
1938}
1939
1940#[derive(Debug, Error, PartialEq, Eq)]
1941pub enum UpgradeError {
1942 #[error(
1943 ":upgrade-from :from {from:?} is not a valid SemVer-2 version: {reason} (the substrate \
1944 consumes this string as `semver::Version` — three-part `MAJOR.MINOR.PATCH` with optional \
1945 `-prerelease` and `+build`, the same shape every top-level `:versao` carries — across \
1946 every artifact derived from `:from`: the wasm-operator's `:from`-match dispatch loads \
1947 the running version through `semver::Version::parse` and matches it against each entry's \
1948 `:from`, so a malformed `:from` is structurally unreachable at dispatch time; use a \
1949 SemVer-2 literal like `\"0.1.0\"`, `\"0.2.0-rc.1\"`, or `\"1.0.0+build.42\"` — not a \
1950 git-tag-shape like `\"v0.1.0\"`, a docker-tag-shape like `\"latest\"`, a \
1951 requirement-shape like `\"^0.1\"`, or a four-part `\"0.1.0.0\"`)"
1952 )]
1953 FromInvalid { from: String, reason: String },
1954 #[error(
1955 "upgrade instruction `{kind}` :module is empty (every appup module reference \
1956 must name a caixa; use a non-empty caixa name like `\"hello-rio\"` or omit \
1957 the instruction entirely)"
1958 )]
1959 ModuleEmpty { kind: &'static str },
1960 #[error(
1961 "upgrade instruction `{kind}` :module {module:?} is not a valid DNS-1123 label: \
1962 {reason} (every appup module reference resolves to a caixa name, which lands \
1963 verbatim as a K8s `metadata.name` on the per-Servico ComputeUnit the operator \
1964 creates, the `LABEL_PROGRAM` label value the wasm-engine matches at hot-upgrade \
1965 dispatch, and every future `app-operator` rolling-load CR's per-module reference \
1966 axis; use a lowercase alphanumeric + hyphen identifier like `\"hello-rio\"` or \
1967 `\"cache-v2\"`)"
1968 )]
1969 ModuleInvalid {
1970 kind: &'static str,
1971 module: String,
1972 reason: String,
1973 },
1974 #[error("instruction's :script is empty")]
1975 EmptyScript,
1976 #[error(
1977 "instruction's :script {} is absolute — upgrade scripts must be relative to the caixa \
1978 root (Path::join would otherwise escape the project sandbox)",
1979 script.display()
1980 )]
1981 AbsoluteScript { script: PathBuf },
1982 #[error(
1983 "instruction's :script {} contains a `..` component — upgrade scripts must not traverse \
1984 above the caixa root",
1985 script.display()
1986 )]
1987 ParentEscapeScript { script: PathBuf },
1988 #[error(
1989 ":upgrade-from (:state-change {}) does not terminate in the `.lisp` extension — the M2.5 \
1990 wasm-engine instantiator reads every migration script as tatara-lisp source through \
1991 `tatara_lisp::read` at hot-upgrade migration time (the same downstream consumer the \
1992 peer `:behavior :on-*` axis routes through at instance-start time, c97815a), so any \
1993 other extension (`.txt`, `.rs`, `.lisp.bak`) or no-extension shape is structurally a \
1994 parser error far from the source caixa.lisp, with no field naming the offending \
1995 `(:state-change …)` instruction. Pin a relative path under the caixa root whose \
1996 terminating extension is lowercase-`.lisp` (e.g. `\"lib/migrations.lisp\"`, \
1997 `\"lib/migrations/v01-to-v02.lisp\"`).",
1998 script.display()
1999 )]
2000 NonLispExtensionScript { script: PathBuf },
2001 #[error(
2002 ":upgrade-from carries more than one `(:from {from:?})` entry — OTP appup picks at most \
2003 one matching block per running version (`release_handler:install_release/1` dispatches \
2004 on the loaded `:from` against the currently-running release), so two entries with the \
2005 same parsed semver are an ambiguous edge in the typed upgrade graph (the operator would \
2006 pick either set non-deterministically). Author one path per prior version; if two \
2007 distinct instruction sequences are needed, fold them into one ordered list under the \
2008 single matching `(:from {from:?} :instructions (…))` block."
2009 )]
2010 DuplicateFrom { from: String },
2011 #[error(
2012 ":upgrade-from `(:from {from:?})` is not strictly less than the caixa's current \
2013 `:versao {versao:?}` under SemVer-2 precedence — an upgrade block whose `:from` is \
2014 greater than or equal to the caixa's own version is structurally unreachable \
2015 (the wasm-operator's `:from`-match dispatch loads the current `:versao` and matches \
2016 the running version against each entry's `:from`; an entry whose `:from >= :versao` \
2017 is never reached because the operator never runs a version greater than or equal to \
2018 the current one that it could then upgrade *to* the current one). Bump the caixa's \
2019 `:versao` past {from:?} (the typical fix — you added the entry intending to upgrade \
2020 *to* a new version but forgot to bump `:versao`), drop the entry (if it's a stale \
2021 reference left over from a reverted `:versao` bump), or correct `:from` to a prior \
2022 version (if it's a typo). Pre-release values like `\"0.2.0-rc.1\"` are strictly less \
2023 than the corresponding release `\"0.2.0\"` under SemVer §11 precedence; build-metadata \
2024 values like `\"0.2.0+build.1\"` are equal to `\"0.2.0\"` under precedence and rejected \
2025 here as a self-upgrade no-op."
2026 )]
2027 FromNotBeforeVersao { from: String, versao: String },
2028 #[error(
2029 ":upgrade-from `(:from {from:?})` :instructions list violates the `(:restart)` \
2030 exclusivity invariant — an entry containing `(:restart)` must contain exactly one \
2031 `(:restart)` and nothing else (found {restart_count} `(:restart)` plus other \
2032 instruction(s): {other_kinds:?}). Per the UpgradeInstruction::Restart doc comment, \
2033 `(:restart)` is the fallback for an entry whose typed upgrade is impossible (wasm \
2034 component-model world incompatibility, irreversible state shape change), and the \
2035 fallback is terminal by construction (the operator restarts the pod and the new \
2036 version comes up fresh). Mixing the fallback with the typed sequence is dead code \
2037 in both directions: if the typed instructions would succeed, `(:restart)` is \
2038 unreached; if they wouldn't, the typed instructions are dead because the operator \
2039 restarts anyway. Author *either* a typed sequence (`(:load-module …) \
2040 (:state-change …) (:soft-purge …)`) *or* a single `((:restart))` — never both, \
2041 never repeated. If two distinct upgrade strategies are needed for the same prior \
2042 version, that is itself a typed-graph ambiguity (the operator's `:from`-match \
2043 dispatch picks exactly one block per running version) — keep the typed sequence; \
2044 the fallback restart is what the operator does on any typed-sequence failure \
2045 already."
2046 )]
2047 RestartNotExclusive {
2048 from: String,
2049 restart_count: usize,
2050 other_kinds: Vec<&'static str>,
2051 },
2052 #[error(
2053 ":upgrade-from `(:from {from:?})` runs `(:state-change {})` before any \
2054 `(:load-module …)` in its :instructions list — a state migration is the \
2055 gen_server:code_change/3 analog and must run in the context of the newly-loaded \
2056 code, but the operator executes instructions in declared order, so this migration \
2057 runs while the only resident version is still the prior one (which expects the \
2058 pre-migration state shape). Load the new module first: author the canonical \
2059 `(:load-module …) (:state-change {}) (:soft-purge …)` order so the new code is \
2060 resident before its state migration runs.",
2061 script.display(),
2062 script.display()
2063 )]
2064 StateChangeWithoutPriorLoad { from: String, script: PathBuf },
2065 #[error(
2066 ":upgrade-from `(:from {from:?})` runs `({kind} {module:?})` before any \
2067 `(:load-module …)` in its :instructions list — `:soft-purge` and `:purge` are the \
2068 code:soft_purge/1 / code:purge/1 analogs and must run after the new code is \
2069 resident alongside the old (OTP's two-phase code load: `code:load_module/1` \
2070 then `code:soft_purge/1`), but the operator executes instructions in declared \
2071 order, so this cleanup runs while the only resident version is still the same \
2072 old code (`:soft-purge` drains it to nothing; `:purge` discards it outright \
2073 mid-request), leaving no replacement to route in-flight or future requests \
2074 to. Load the new module first: author the canonical `(:load-module …) \
2075 (:state-change …) ({kind} {module:?})` order so the new code is resident \
2076 before the old code is drained or discarded."
2077 )]
2078 PurgeWithoutPriorLoad {
2079 from: String,
2080 kind: &'static str,
2081 module: String,
2082 },
2083 #[error(
2084 ":upgrade-from `(:from {from:?})` :instructions list targets module {module:?} with \
2085 more than one cleanup instruction ({kinds:?}) — `:soft-purge` and `:purge` are the \
2086 code:soft_purge/1 / code:purge/1 analogs (INSPIRATIONS §II.4: \"`code:soft_purge/1` — \
2087 wait until no process is running v1, then discard. (`code:purge/1` kills v1 immediately \
2088 if you don't care.)\"), and each module's old version is cleaned up by exactly one of \
2089 them: either drain-then-discard (`:soft-purge`) or immediate-discard (`:purge`), never \
2090 both, never repeated. systools-generated `.relup` files emit at most one purge per \
2091 module for this reason. A second cleanup on the same module is at best redundant (the \
2092 module is already gone after the first cleanup, so the second is a no-op or undefined \
2093 depending on the operator's handling of a non-resident-module purge request) and at \
2094 worst incoherent (mixing drain and discard semantics on one module suggests the author \
2095 wanted a fallback, but the operator runs declared instructions unconditionally — \
2096 fallback on cleanup failure is the operator's job, not authored into the entry). \
2097 Author one cleanup per module: prefer `(:soft-purge {module:?})` (waits for in-flight \
2098 callers to drain before GC); fall back to `(:purge {module:?})` only when the drain \
2099 can't complete (cron / oneShot / stuck callers). If two distinct old versions need \
2100 cleanup, name them distinctly (e.g. `(:soft-purge {module:?}) (:soft-purge \"…-older\")`)."
2101 )]
2102 DuplicateCleanup {
2103 from: String,
2104 module: String,
2105 kinds: Vec<&'static str>,
2106 },
2107 #[error(
2108 ":upgrade-from `(:from {from:?})` :instructions list loads module {module:?} more than \
2109 once — `:load-module` is the code:load_module/1 analog (INSPIRATIONS §II.4: \"1. \
2110 `code:load_module/1` — load v2 alongside v1; new code is 'current', old code is \
2111 'old'.\"), and the instruction binds the named wasm component once: the operator's \
2112 dispatch table reads the module name and brings up the corresponding component \
2113 alongside the running version. systools-generated `.relup` files emit at most one \
2114 `load_module` per module per upgrade step for this reason. A second `(:load-module \
2115 {module:?})` instruction has no observable semantic relative to the first (the \
2116 component is already resident) — either dead code (copy-pasted load line) or a typo \
2117 masking a distinct module the author intended to load alongside (renamed both to \
2118 {module:?} by mistake), leaving the second module silently absent from the entry. \
2119 Author one `(:load-module {module:?})` per old module per entry; if two distinct old \
2120 versions need loading alongside the running one, name them distinctly (e.g. \
2121 `(:load-module {module:?}) (:load-module \"…-v2\")`)."
2122 )]
2123 DuplicateLoadModule { from: String, module: String },
2124 #[error(
2125 ":upgrade-from `(:from {from:?})` :instructions list runs state migration {} more than \
2126 once — `:state-change` is the gen_server:code_change/3 analog (INSPIRATIONS §II.4: \
2127 \"State migration uses gen_server:code_change/3\"), and the script folds the prior-version \
2128 state shape into the current-version shape: a one-shot transition, not a step that \
2129 composes with itself. systools-generated `.relup` files emit at most one `code_change` \
2130 per gen_server per upgrade step for this reason; OTP's release_handler invokes the \
2131 callback exactly once. A second `(:state-change {})` instruction re-runs the same fold on \
2132 the already-migrated state — at best a no-op (idempotent script masking a typo where the \
2133 author intended two distinct migration scripts) and at worst silent state corruption \
2134 (non-idempotent fold double-applied: an `add column` that runs twice, an `increment \
2135 counter` that double-bumps, a `rename field` that renames-then-fails the second time). \
2136 Author one `(:state-change {})` per migration script per entry; if two distinct state \
2137 transitions are needed (e.g. one module's schema *and* another module's projection), \
2138 name them distinctly (e.g. `(:state-change {}) (:state-change \"lib/migrations/v01-to-v02-projection.lisp\")`).",
2139 script.display(),
2140 script.display(),
2141 script.display(),
2142 script.display()
2143 )]
2144 DuplicateStateChange { from: String, script: PathBuf },
2145 #[error(
2146 ":upgrade-from `(:from {from:?})` runs `(:state-change {})` after `({prior_cleanup_kind} \
2147 {prior_cleanup_module:?})` in its :instructions list — `:state-change` is the \
2148 gen_server:code_change/3 analog and folds the prior-version state shape into the \
2149 current shape, but the prior version's state only exists while the prior code is \
2150 still resident; `:soft-purge` and `:purge` are the code:soft_purge/1 / code:purge/1 \
2151 analogs and drain or discard that prior code. The operator executes instructions in \
2152 declared order, so a cleanup ahead of a state-change has already drained the prior \
2153 module to nothing (`:soft-purge`) or discarded it mid-request (`:purge`) by the time \
2154 the migration script runs, leaving the script either no-op (no prior-version state \
2155 left to fold) or crashing (`code_change/3` invoked on an unloaded version). The OTP \
2156 canonical sequence is `code:load_module/1` → `gen_server:code_change/3` → \
2157 `code:soft_purge/1`; the appup cookbook's recommended pattern is `[{{load_module, m}}, \
2158 {{update, m, soft}}, {{soft_purge, m}}]` with the migration-triggering `update` \
2159 strictly between load and cleanup. Author the canonical `(:load-module …) \
2160 (:state-change {}) ({prior_cleanup_kind} {prior_cleanup_module:?})` order so the \
2161 migration runs against the prior-version state before the cleanup drains it.",
2162 script.display(),
2163 script.display()
2164 )]
2165 StateChangeAfterCleanup {
2166 from: String,
2167 script: PathBuf,
2168 prior_cleanup_kind: &'static str,
2169 prior_cleanup_module: String,
2170 },
2171 #[error(
2172 ":upgrade-from `(:from {from:?})` declares `(:state-change {})` but the caixa does not \
2173 declare `:behavior :on-state-change` — the per-version migration script is the \
2174 gen_server:code_change/3 analog and the runtime hook it is delivered through during \
2175 hot upgrade is the `:on-state-change` callback. OTP's release_handler:install_release/1 \
2176 realizes the composition by invoking the running gen_server's code_change/3 callback \
2177 during the appup's `code_change` / `update, m, soft` step; caixa decomposes the same \
2178 composition into two typed slots, the per-version migration logic in this \
2179 `(:state-change …)` instruction's `:script` and the runtime dispatch hook in the \
2180 `:behavior :on-state-change` callback (the upgrade.rs module doc pins the composition \
2181 verbatim: \"Composes with the `:behavior :on-state-change` callback to deliver state \
2182 migration during hot upgrades\"). The missing callback leaves the per-version script \
2183 with no runtime delivery path: the operator's hot-upgrade dispatch reaches for the \
2184 callback at the migration step, finds it absent, and either fails the upgrade \
2185 mid-flight (the transactional rollback the module doc names — \"On any failure, the \
2186 current version stays load-bearing\") or silently skips the migration leaving the \
2187 new code running against unmigrated prior-version state. Add the callback: \
2188 `(:behavior ((:on-state-change \"lib/migrations.lisp\") …))` (the runtime delivery \
2189 path) alongside the existing `(:state-change {})` instruction (the per-version \
2190 script). If the upgrade truly carries no state migration, drop the `(:state-change \
2191 …)` instruction from the entry (a metadata-only upgrade — load + cleanup, no \
2192 migration — is the canonical shape).",
2193 script.display(),
2194 script.display()
2195 )]
2196 StateChangeWithoutOnStateChangeCallback { from: String, script: PathBuf },
2197}
2198
2199#[cfg(test)]
2200mod tests {
2201 use std::path::Path;
2202
2203 use super::*;
2204
2205 fn entry(from: &str, instrs: Vec<UpgradeInstruction>) -> UpgradeFromEntry {
2206 UpgradeFromEntry {
2207 from: from.into(),
2208 instructions: instrs,
2209 }
2210 }
2211
2212 #[test]
2213 fn round_trip_load_module() {
2214 let i = UpgradeInstruction::LoadModule {
2215 module: "hello-rio".into(),
2216 };
2217 let json = serde_json::to_string(&i).unwrap();
2218 assert!(json.contains("\"kind\":\"load-module\""));
2219 let back: UpgradeInstruction = serde_json::from_str(&json).unwrap();
2220 assert_eq!(i, back);
2221 }
2222
2223 #[test]
2224 fn round_trip_all_variants() {
2225 let cases = vec![
2226 UpgradeInstruction::LoadModule { module: "x".into() },
2227 UpgradeInstruction::StateChange {
2228 script: PathBuf::from("lib/migrations.lisp"),
2229 },
2230 UpgradeInstruction::SoftPurge {
2231 module: "x-old".into(),
2232 },
2233 UpgradeInstruction::Purge {
2234 module: "x-old".into(),
2235 },
2236 UpgradeInstruction::Restart,
2237 ];
2238 for c in cases {
2239 let json = serde_json::to_string(&c).unwrap();
2240 let back: UpgradeInstruction = serde_json::from_str(&json).unwrap();
2241 assert_eq!(c, back);
2242 }
2243 }
2244
2245 #[test]
2246 fn validate_accepts_well_formed() {
2247 let e = entry(
2248 "0.1.0",
2249 vec![
2250 UpgradeInstruction::LoadModule {
2251 module: "hello-rio".into(),
2252 },
2253 UpgradeInstruction::StateChange {
2254 script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
2255 },
2256 UpgradeInstruction::SoftPurge {
2257 module: "hello-rio-old".into(),
2258 },
2259 ],
2260 );
2261 e.validate().unwrap();
2262 }
2263
2264 #[test]
2265 fn validate_rejects_non_semver_from() {
2266 let e = entry("not-a-semver", vec![]);
2267 let err = e.validate().unwrap_err();
2268 assert!(
2269 matches!(err, UpgradeError::FromInvalid { ref from, .. } if from == "not-a-semver")
2270 );
2271 }
2272
2273 #[test]
2274 fn from_invalid_diagnostic_carries_offending_from_and_reason() {
2275 // Diagnostic-shape pin: the error names the offending
2276 // `:upgrade-from :from` verbatim with a non-empty parser-shaped
2277 // reason, so a `feira lint` run can render the diagnostic
2278 // without re-parsing — the author can grep their caixa.lisp for
2279 // `:from "<value>"` and fix it in one edit. Mirrors the peer
2280 // `versao_invalid_diagnostic_carries_offending_versao` pin on
2281 // the sibling SemVer-2 axis (the top-level `:versao`), the
2282 // peer `membro_versao_invalid_diagnostic_carries_offending_value`
2283 // pin on `:membros :versao`, and the peer
2284 // `deps_invalid_diagnostic_carries_offending_value` pin on
2285 // `:deps :versao` — every SemVer-2-parsing slot's invalid
2286 // diagnostic is now structurally equivalent.
2287 let e = entry("v0.1.0", vec![]);
2288 let err = e.validate().unwrap_err();
2289 let UpgradeError::FromInvalid { from, reason } = err else {
2290 panic!("expected FromInvalid variant, got {err:?}");
2291 };
2292 assert_eq!(from, "v0.1.0");
2293 assert!(
2294 !reason.is_empty(),
2295 "FromInvalid `reason` must carry the parser's wording verbatim"
2296 );
2297 }
2298
2299 #[test]
2300 fn prior_versao_returns_from_byte_equal_across_permutations() {
2301 // Byte-identity pin on the lifted `UpgradeFromEntry::prior_versao`
2302 // accessor across the SemVer-2 shape lattice every consumer
2303 // reaches through it — the numeric-triad canonical shape, a
2304 // pre-release build with a dotted identifier chain, a full-
2305 // metadata build, a large-magnitude triad, and the empty
2306 // string (which reaches this accessor unchanged before any
2307 // validate gate rejects it). Sibling to the peer
2308 // `membro_versao_requirement_returns_versao_byte_equal_across_permutations`
2309 // (a40b0e3) / `membro_nome_returns_caixa_byte_equal_across_permutations`
2310 // (4a32abf) pins on the sibling M3 mesh-slot scalar-accessor
2311 // family — extended here onto the first M2 slot scalar-value
2312 // axis. Any silent detour on the accessor (a `.to_string()`
2313 // + retained ownership shape, a canonicalization pass, a
2314 // trim-whitespace on the return path) surfaces as a byte-
2315 // inequality failure here rather than as a downstream error-
2316 // diagnostic drift.
2317 let cases = ["0.1.0", "0.2.0-rc.1", "1.0.0+build.42", "10.20.30", ""];
2318 for from in cases {
2319 let e = entry(from, vec![]);
2320 assert_eq!(
2321 e.prior_versao(),
2322 from,
2323 "prior_versao() must return the `:from` field byte-for-byte for {from:?}",
2324 );
2325 assert_eq!(
2326 e.prior_versao().len(),
2327 from.len(),
2328 "prior_versao() byte-length must equal the `:from` field's for {from:?}",
2329 );
2330 }
2331 }
2332
2333 #[test]
2334 fn prior_versao_borrows_from_from_storage() {
2335 // Same-address pin: `UpgradeFromEntry::prior_versao` returns
2336 // a borrow into `self.from`'s heap allocation, never a fresh
2337 // owned copy. Guards against a future silent detour where
2338 // the accessor materializes a `Cow<'_, str>` / `String` /
2339 // `Rc<str>` intermediate — the return path stays zero-cost
2340 // even under a refactor that reshapes the storage. Sibling
2341 // to the peer `membro_versao_requirement_borrows_from_versao_storage`
2342 // (a40b0e3) / `membro_nome_borrows_from_caixa_storage`
2343 // (4a32abf) pins — extended onto the M2 slot's first
2344 // scalar-value axis.
2345 let e = entry("0.1.0", vec![]);
2346 assert!(
2347 std::ptr::eq(e.prior_versao().as_ptr(), e.from.as_ptr()),
2348 "prior_versao() must borrow from `self.from`'s storage, not allocate a fresh copy",
2349 );
2350 }
2351
2352 #[test]
2353 fn validate_parses_prior_versao_through_lifted_accessor() {
2354 // Coherence pin between the accessor and the SemVer-2 parse
2355 // gate: every `:upgrade-from :from` value the validator
2356 // accepts (resp. rejects) must be identical to what
2357 // `Version::parse(entry.prior_versao())` accepts (resp.
2358 // rejects) — the two must remain in lockstep across the
2359 // shape lattice so `validate_upgrade_from`'s
2360 // `Version::parse(entry.prior_versao()).expect(...)` re-parse
2361 // assertion holds by construction. If a future extension of
2362 // `prior_versao` reshapes the return (a canonicalization
2363 // pass, a leading/trailing whitespace trim, an empty-to-
2364 // "0.0.0" fallback) it would either loosen the validator
2365 // (silently accepting shapes the parser rejects) or
2366 // tighten the parser's re-parse (silently panicking on
2367 // shapes the validator accepts) — this pin catches either
2368 // shift at caixa-core build time.
2369 let accepted = ["0.1.0", "0.2.0-rc.1", "1.0.0+build.42", "10.20.30"];
2370 for from in accepted {
2371 let e = entry(from, vec![]);
2372 e.validate().unwrap_or_else(|err| {
2373 panic!("validate() must accept {from:?} that Version::parse accepts, got {err:?}");
2374 });
2375 semver::Version::parse(e.prior_versao()).unwrap_or_else(|err| {
2376 panic!(
2377 "Version::parse(prior_versao()) must accept {from:?} that validate() accepts, \
2378 got {err:?}",
2379 );
2380 });
2381 }
2382 let rejected = ["", "v0.1.0", "0.1", "not-a-semver", "0.1.0.0"];
2383 for from in rejected {
2384 let e = entry(from, vec![]);
2385 assert!(
2386 matches!(e.validate(), Err(UpgradeError::FromInvalid { .. })),
2387 "validate() must reject {from:?} that Version::parse rejects",
2388 );
2389 assert!(
2390 semver::Version::parse(e.prior_versao()).is_err(),
2391 "Version::parse(prior_versao()) must reject {from:?} that validate() rejects",
2392 );
2393 }
2394 }
2395
2396 #[test]
2397 fn validate_rejects_empty_module() {
2398 // Per-arm coverage: every Module-bearing variant surfaces the
2399 // kind-tagged `ModuleEmpty` diagnostic naming its lisp-form,
2400 // so the author can grep their caixa.lisp for `(:load-module
2401 // …)` / `(:soft-purge …)` / `(:purge …)` and fix it in one
2402 // edit — same self-locating shape `BehaviorError::EmptyPath`
2403 // (b0c8389) carries on the peer M2 typed slot.
2404 let cases: &[(UpgradeInstruction, &'static str)] = &[
2405 (
2406 UpgradeInstruction::LoadModule {
2407 module: String::new(),
2408 },
2409 crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE,
2410 ),
2411 (
2412 UpgradeInstruction::SoftPurge {
2413 module: String::new(),
2414 },
2415 crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
2416 ),
2417 (
2418 UpgradeInstruction::Purge {
2419 module: String::new(),
2420 },
2421 crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
2422 ),
2423 ];
2424 for (instr, expected_kind) in cases {
2425 assert_eq!(
2426 instr.validate().unwrap_err(),
2427 UpgradeError::ModuleEmpty {
2428 kind: expected_kind
2429 },
2430 "empty :module on {instr:?} must surface as ModuleEmpty {{ kind: {expected_kind:?} }}"
2431 );
2432 }
2433 }
2434
2435 #[test]
2436 fn validate_rejects_non_dns_1123_module() {
2437 // Every appup `:module` reference is a caixa name (the
2438 // wasm-engine resolves it through the same ComputeUnit
2439 // registry the operator manages), so the value-shape gate
2440 // matches the K8s apiserver-side DNS-1123 label rule. Sweep
2441 // the canonical authoring footguns — uppercase letters, `_`
2442 // separator, embedded `.`, leading/trailing `-`, an embedded
2443 // whitespace byte, the >63-byte UUID-shaped slug — across
2444 // every Module-bearing variant; each must surface as
2445 // `ModuleInvalid { kind, module, reason }` carrying the
2446 // offending value verbatim and the parser-shaped reason.
2447 type Build = fn(String) -> UpgradeInstruction;
2448 let footguns: &[&str] = &[
2449 "Hello-Rio",
2450 "hello_rio",
2451 "hello.rio",
2452 "-hello",
2453 "hello-",
2454 "hello rio",
2455 &"x".repeat(crate::render::DNS_1123_LABEL_MAX_LEN + 1),
2456 ];
2457 let variants: &[(Build, &'static str)] = &[
2458 (
2459 |m| UpgradeInstruction::LoadModule { module: m },
2460 crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE,
2461 ),
2462 (
2463 |m| UpgradeInstruction::SoftPurge { module: m },
2464 crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
2465 ),
2466 (
2467 |m| UpgradeInstruction::Purge { module: m },
2468 crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
2469 ),
2470 ];
2471 for (build, expected_kind) in variants {
2472 for module in footguns {
2473 let instr = build((*module).to_string());
2474 let err = instr.validate().unwrap_err();
2475 match err {
2476 UpgradeError::ModuleInvalid {
2477 kind,
2478 module: m,
2479 reason,
2480 } => {
2481 assert_eq!(
2482 kind, *expected_kind,
2483 ":module footgun on {instr:?} must tag the lisp-form"
2484 );
2485 assert_eq!(
2486 m, *module,
2487 "ModuleInvalid must carry the offending value verbatim"
2488 );
2489 assert!(
2490 !reason.is_empty(),
2491 "ModuleInvalid reason must name the specific violation \
2492 (the predicate's parser-shaped wording from \
2493 `is_dns_1123_label`), got empty"
2494 );
2495 }
2496 other => panic!("expected ModuleInvalid on {instr:?}, got {other:?}"),
2497 }
2498 }
2499 }
2500 }
2501
2502 #[test]
2503 fn validate_accepts_canonical_module_names() {
2504 // Positive control: every documented authoring shape — bare
2505 // identifier, with hyphens, with digits, the
2506 // suffix-versioned alias `<nome>-old` `SoftPurge` typically
2507 // references — passes the gate. Drift here = a future
2508 // tighten that rejects any of these surfaces as a
2509 // test-failure at the predicate boundary, not piecemeal
2510 // across per-instruction call sites.
2511 let canonical: &[&str] = &[
2512 "hello-rio",
2513 "hello-rio-old",
2514 "cache",
2515 "cache-v2",
2516 "x",
2517 "a1",
2518 "0a",
2519 "abc-123-def",
2520 ];
2521 for module in canonical {
2522 UpgradeInstruction::LoadModule {
2523 module: (*module).to_string(),
2524 }
2525 .validate()
2526 .unwrap_or_else(|e| panic!("LoadModule {module:?} must pass, got {e:?}"));
2527 UpgradeInstruction::SoftPurge {
2528 module: (*module).to_string(),
2529 }
2530 .validate()
2531 .unwrap_or_else(|e| panic!("SoftPurge {module:?} must pass, got {e:?}"));
2532 UpgradeInstruction::Purge {
2533 module: (*module).to_string(),
2534 }
2535 .validate()
2536 .unwrap_or_else(|e| panic!("Purge {module:?} must pass, got {e:?}"));
2537 }
2538 }
2539
2540 #[test]
2541 fn validate_empty_takes_precedence_over_invalid() {
2542 // Empty input is rejected via the narrower `ModuleEmpty`
2543 // diagnostic before the DNS-1123 predicate is consulted, so
2544 // a future tighten that adds another stage between the two
2545 // doesn't accidentally reorder the diagnostic precedence.
2546 // Mirrors the empty-first cascade on every peer DNS-1123
2547 // gate (`validate_membro_caixa`, `validate_placement_cluster`,
2548 // `SupervisorSpec::validate`'s child-name arm).
2549 let err = UpgradeInstruction::LoadModule {
2550 module: String::new(),
2551 }
2552 .validate()
2553 .unwrap_err();
2554 assert_eq!(
2555 err,
2556 UpgradeError::ModuleEmpty {
2557 kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE
2558 }
2559 );
2560 }
2561
2562 #[test]
2563 fn validate_rejects_empty_script() {
2564 let i = UpgradeInstruction::StateChange {
2565 script: PathBuf::new(),
2566 };
2567 assert_eq!(i.validate().unwrap_err(), UpgradeError::EmptyScript);
2568 }
2569
2570 #[test]
2571 fn validate_rejects_absolute_script() {
2572 let i = UpgradeInstruction::StateChange {
2573 script: PathBuf::from("/etc/migrations.lisp"),
2574 };
2575 assert!(matches!(
2576 i.validate().unwrap_err(),
2577 UpgradeError::AbsoluteScript { .. }
2578 ));
2579 }
2580
2581 #[test]
2582 fn validate_rejects_parent_escape_script() {
2583 let i = UpgradeInstruction::StateChange {
2584 script: PathBuf::from("../sibling/migrations.lisp"),
2585 };
2586 assert!(matches!(
2587 i.validate().unwrap_err(),
2588 UpgradeError::ParentEscapeScript { .. }
2589 ));
2590 // mid-path `..` is also caught
2591 let i2 = UpgradeInstruction::StateChange {
2592 script: PathBuf::from("lib/../../escaped.lisp"),
2593 };
2594 assert!(matches!(
2595 i2.validate().unwrap_err(),
2596 UpgradeError::ParentEscapeScript { .. }
2597 ));
2598 }
2599
2600 // ── :upgrade-from :state-change :script `.lisp` extension gate ─
2601 // Mirrors the c97815a `BehaviorError::NonLispExtension` arm on
2602 // the peer `:behavior :on-*` tatara-lisp-source-path axis. Both
2603 // axes route through the same M2.5 wasm-engine `tatara_lisp::read`
2604 // consumer; the file-type contract is identical, so the per-axis
2605 // test grid is mirrored leg-for-leg.
2606
2607 #[test]
2608 fn validate_rejects_no_extension_script() {
2609 // Fail-before-pass-after: the canonical "I declared the
2610 // migration script but forgot the `.lisp` extension"
2611 // authoring footgun (e.g. `(:state-change "lib/migrations")`).
2612 // The wasm-engine's `tatara_lisp::read` consumer needs a
2613 // file-type contract beyond the structural-shape gate; a
2614 // no-extension path past `is_sandboxed_relative_path` would
2615 // surface a parser-shaped diagnostic at hot-upgrade migration
2616 // time far from the source caixa.lisp.
2617 for relpath in ["lib/migrations", "migrations", "lib/handlers/migrate"] {
2618 let i = UpgradeInstruction::StateChange {
2619 script: PathBuf::from(relpath),
2620 };
2621 let err = i.validate().unwrap_err();
2622 assert!(
2623 matches!(&err, UpgradeError::NonLispExtensionScript { script: s }
2624 if s == Path::new(relpath)),
2625 "no-extension script {relpath:?} must surface as NonLispExtensionScript \
2626 carrying the offending path verbatim, got {err:?}"
2627 );
2628 }
2629 }
2630
2631 #[test]
2632 fn validate_rejects_non_lisp_extension_script() {
2633 // Wrong-extension sweep across common authoring footguns: the
2634 // `.txt` / `.md` / `.json` / `.yaml` shapes an author might
2635 // drag in from the workspace tree, the `.rs` shape that an
2636 // IDE auto-complete might propose, the `.lisp.bak` shape an
2637 // editor might leave behind, and the `.lispx` near-miss that
2638 // a typo would produce. Each must surface as
2639 // `NonLispExtensionScript` carrying the offending path
2640 // verbatim — the wasm-engine's `tatara_lisp::read` consumer
2641 // rejects all of these at hot-upgrade migration time, and
2642 // the gate lifts that contract to validate time. Mirrors the
2643 // peer `BehaviorError::NonLispExtension` sweep (c97815a) on
2644 // the `:behavior :on-*` axis leg-for-leg — same downstream
2645 // consumer, same accepted set, same per-axis test grid.
2646 let footguns: &[&str] = &[
2647 "lib/migrations.rs",
2648 "lib/migrations.txt",
2649 "lib/migrations.md",
2650 "lib/migrations.json",
2651 "lib/migrations.yaml",
2652 "lib/migrations.toml",
2653 "lib/migrations.lisp.bak",
2654 "lib/migrations.lispx",
2655 "lib/migrations.lis",
2656 ];
2657 for relpath in footguns {
2658 let i = UpgradeInstruction::StateChange {
2659 script: PathBuf::from(relpath),
2660 };
2661 let err = i.validate().unwrap_err();
2662 assert!(
2663 matches!(&err, UpgradeError::NonLispExtensionScript { script: s }
2664 if s == Path::new(relpath)),
2665 "wrong-extension script {relpath:?} must surface as NonLispExtensionScript \
2666 carrying the offending path verbatim, got {err:?}"
2667 );
2668 }
2669 }
2670
2671 #[test]
2672 fn validate_rejects_uppercase_lisp_extension_script() {
2673 // Strict lowercase: `.LISP` / `.Lisp` / `.LiSp` are
2674 // case-folded shapes a case-insensitive volume's existence
2675 // check would match the on-disk file — but the
2676 // canonical-form codec emits lowercase `.lisp` verbatim, so
2677 // a case-folded shape mismatches the round-trip-stable
2678 // canonical form (THEORY.md §V.2.7 render-determinism).
2679 // Same case-sensitive discipline the byte-size / duration
2680 // codecs use on unit suffixes (`MiB`, `ms`, `s`, `m`, `h`)
2681 // and every other shape-gate predicate in `render.rs` (label
2682 // / scheme / unit boundaries). Mirrors the peer
2683 // `BehaviorError::NonLispExtension` case-fold sweep (c97815a).
2684 for relpath in [
2685 "lib/migrations.LISP",
2686 "lib/migrations.Lisp",
2687 "lib/migrations.LiSp",
2688 "lib/migrations.lISP",
2689 ] {
2690 let i = UpgradeInstruction::StateChange {
2691 script: PathBuf::from(relpath),
2692 };
2693 let err = i.validate().unwrap_err();
2694 assert!(
2695 matches!(&err, UpgradeError::NonLispExtensionScript { script: s }
2696 if s == Path::new(relpath)),
2697 "case-folded `.lisp` extension {relpath:?} must surface as \
2698 NonLispExtensionScript (strict lowercase, canonical-form \
2699 round-trip pin), got {err:?}"
2700 );
2701 }
2702 }
2703
2704 #[test]
2705 fn validate_accepts_canonical_lisp_extension_scripts() {
2706 // Positive-control sweep across every canonical in-tree
2707 // authoring shape: bare filename, standard `lib/`
2708 // subdirectory, deeply-nested migrations subdirectory,
2709 // explicit current-dir-relative prefix, mid-path `./`
2710 // segment, multi-dot stem (the version-suffix shape
2711 // `lib/migrations/v.0.1.lisp` an author might use to encode
2712 // the migration's `:from` version into the filename). Drift
2713 // here = a future tightening that rejects any of these
2714 // surfaces as a test-failure at the per-axis validator
2715 // boundary, not piecemeal across renderer / layout-checker
2716 // call sites. Mirrors the peer `BehaviorSpec` positive-set
2717 // sweep (c97815a).
2718 let canonical: &[&str] = &[
2719 "lib/migrations.lisp",
2720 "lib/migrations/v01-to-v02.lisp",
2721 "migrations.lisp",
2722 "a.lisp",
2723 "./lib/migrations.lisp",
2724 "lib/./migrations.lisp",
2725 "lib/migrations/v.0.1.lisp",
2726 ];
2727 for relpath in canonical {
2728 UpgradeInstruction::StateChange {
2729 script: PathBuf::from(relpath),
2730 }
2731 .validate()
2732 .unwrap_or_else(|e| {
2733 panic!("canonical `.lisp` script {relpath:?} must pass, got {e:?}")
2734 });
2735 }
2736 }
2737
2738 #[test]
2739 fn validate_sandbox_shape_takes_precedence_over_lisp_extension() {
2740 // Cross-arm precedence pin: a script that is *both*
2741 // sandbox-escaping (Empty / Absolute / ParentEscape) and
2742 // non-`.lisp` must surface the more-fundamental
2743 // sandbox-shape diagnostic first — the canonical fix
2744 // collapses both into "pin a relative `.lisp` path under the
2745 // caixa root", and the `.lisp` remediation would be
2746 // misleading when the offending path can never resolve under
2747 // the caixa root anyway. Mirrors the peer
2748 // `BehaviorError` cross-arm precedence (c97815a) and the
2749 // sibling `LimitsError`
2750 // (`MemoryZero` → `MemoryBelowWasm32Page` →
2751 // `MemoryExceedsWasm32Cap` → `MemoryNotPageMultiple`)
2752 // smallest-scope-arm-fires-last posture.
2753 let i_empty = UpgradeInstruction::StateChange {
2754 script: PathBuf::new(),
2755 };
2756 assert_eq!(i_empty.validate().unwrap_err(), UpgradeError::EmptyScript);
2757 let i_abs = UpgradeInstruction::StateChange {
2758 script: PathBuf::from("/etc/migrations.txt"),
2759 };
2760 assert!(
2761 matches!(
2762 i_abs.validate().unwrap_err(),
2763 UpgradeError::AbsoluteScript { .. }
2764 ),
2765 "absolute + non-`.lisp` must surface AbsoluteScript first"
2766 );
2767 let i_esc = UpgradeInstruction::StateChange {
2768 script: PathBuf::from("../sibling/migrations.rs"),
2769 };
2770 assert!(
2771 matches!(
2772 i_esc.validate().unwrap_err(),
2773 UpgradeError::ParentEscapeScript { .. }
2774 ),
2775 "parent-escape + non-`.lisp` must surface ParentEscapeScript first"
2776 );
2777 }
2778
2779 #[test]
2780 fn non_lisp_extension_script_diagnostic_carries_offending_path() {
2781 // Diagnostic-shape pin: the surfaced error message names the
2782 // offending path verbatim (so the author can grep their
2783 // caixa.lisp for the literal value), the `.lisp` extension
2784 // is named in the remediation, and the downstream consumer
2785 // (`tatara_lisp::read` at hot-upgrade migration time) is
2786 // named so the author can trace the contract back to its
2787 // source. Same self-locating shape every per-axis variant
2788 // carries (`BehaviorError::NonLispExtension`, c97815a;
2789 // `LimitsError::MemoryNotPageMultiple`, ec266d8).
2790 let bad = PathBuf::from("lib/migrations.txt");
2791 let err = UpgradeInstruction::StateChange {
2792 script: bad.clone(),
2793 }
2794 .validate()
2795 .unwrap_err();
2796 let msg = err.to_string();
2797 assert!(
2798 msg.contains("lib/migrations.txt"),
2799 "diagnostic must name the offending path verbatim, got {msg:?}"
2800 );
2801 assert!(
2802 msg.contains(".lisp"),
2803 "diagnostic must name the expected `.lisp` extension, got {msg:?}"
2804 );
2805 assert!(
2806 msg.contains(crate::render::M2_UPGRADE_INSTRUCTION_KIND_STATE_CHANGE),
2807 "diagnostic must name the offending `:state-change` instruction, got {msg:?}"
2808 );
2809 match err {
2810 UpgradeError::NonLispExtensionScript { script } => {
2811 assert_eq!(
2812 script, bad,
2813 "variant must carry the offending path verbatim"
2814 );
2815 }
2816 other => panic!("expected NonLispExtensionScript, got {other:?}"),
2817 }
2818 }
2819
2820 #[test]
2821 fn declared_path_only_for_state_change() {
2822 let load = UpgradeInstruction::LoadModule { module: "x".into() };
2823 assert!(load.declared_path().is_none());
2824 let mig = UpgradeInstruction::StateChange {
2825 script: PathBuf::from("lib/m.lisp"),
2826 };
2827 assert_eq!(mig.declared_path(), Some(&PathBuf::from("lib/m.lisp")));
2828 }
2829
2830 #[test]
2831 fn upgrade_instruction_is_restart_predicate_partitions_the_arm_set() {
2832 // The fail-before-pass-after pin on the `gen_platform::IsVariant`
2833 // derive's [`UpgradeInstruction::is_restart`] arm-discriminator
2834 // predicate: [`UpgradeInstruction::Restart`] is the only variant
2835 // that satisfies `.is_restart()`; every module-bearing arm
2836 // (`LoadModule` / `SoftPurge` / `Purge`) and the script-carrying
2837 // `StateChange` arm all return `false`. This pin makes the
2838 // partition invariant load-bearing at caixa-core test time so a
2839 // future derive regression (a hole that returns `false` for
2840 // `Restart` too, or a byte-collision that flips a second variant
2841 // to `true`) trips here rather than laundering the arm at
2842 // [`Self::validate_restart_exclusive`]'s paired positive /
2843 // negated filter sites (a hole flips restart-count to 0 →
2844 // vacuous OK; a collision flips restart-count > 1 → false
2845 // `RestartNotExclusive` on an entry the author declared without
2846 // any `(:restart)`). Peer of the sibling
2847 // [`crate::kind::tests::caixa_kind_is_variant_predicates_partition_the_arm_set`]
2848 // pin on the M0 `CaixaKind` axis.
2849 let cases: &[(UpgradeInstruction, bool)] = &[
2850 (UpgradeInstruction::LoadModule { module: "a".into() }, false),
2851 (UpgradeInstruction::SoftPurge { module: "b".into() }, false),
2852 (UpgradeInstruction::Purge { module: "c".into() }, false),
2853 (
2854 UpgradeInstruction::StateChange {
2855 script: PathBuf::from("lib/m.lisp"),
2856 },
2857 false,
2858 ),
2859 (UpgradeInstruction::Restart, true),
2860 ];
2861 for (variant, expected) in cases {
2862 assert_eq!(
2863 variant.is_restart(),
2864 *expected,
2865 "UpgradeInstruction::{variant:?}.is_restart() must \
2866 return {expected} (partition invariant on the \
2867 IsVariant-derived arm-discriminator predicate)"
2868 );
2869 }
2870 }
2871
2872 #[test]
2873 fn validate_restart_exclusive_routes_through_is_restart_predicate() {
2874 // Byte-identity pin on the paired positive / negated
2875 // `.is_restart()` filters at
2876 // [`Self::validate_restart_exclusive`] against the pre-lift
2877 // `matches!(i, UpgradeInstruction::Restart)` /
2878 // `!matches!(i, UpgradeInstruction::Restart)` predicates every
2879 // consumer of the gate previously coupled to inline. Asserts
2880 // the two projections agree byte-for-byte on every arm of the
2881 // enum, so a future derive regression that flipped either
2882 // predicate's arm-set would surface here at caixa-core test
2883 // time rather than at
2884 // [`Self::validate_restart_exclusive`]'s per-entry restart-
2885 // count / other-kinds tabulation far from the derive site.
2886 // Same peer-shape pin every sibling
2887 // `IsVariant`-derive-routed gate carries on the substrate's
2888 // closed-set typed-enum surface.
2889 let cases: Vec<UpgradeInstruction> = vec![
2890 UpgradeInstruction::LoadModule { module: "a".into() },
2891 UpgradeInstruction::SoftPurge { module: "b".into() },
2892 UpgradeInstruction::Purge { module: "c".into() },
2893 UpgradeInstruction::StateChange {
2894 script: PathBuf::from("lib/m.lisp"),
2895 },
2896 UpgradeInstruction::Restart,
2897 ];
2898 for instr in &cases {
2899 let via_predicate = instr.is_restart();
2900 let via_matches = matches!(instr, UpgradeInstruction::Restart);
2901 assert_eq!(
2902 via_predicate, via_matches,
2903 "UpgradeInstruction::{instr:?}: is_restart() must \
2904 byte-equal matches!(_, UpgradeInstruction::Restart) — \
2905 the pre-lift open-coded pattern and the \
2906 IsVariant-derived predicate are the same axis, \
2907 one typed dispatch"
2908 );
2909 }
2910 }
2911
2912 #[test]
2913 fn upgrade_instruction_is_cleanup_predicate_partitions_the_arm_set() {
2914 // The fail-before-pass-after pin on the lifted
2915 // [`UpgradeInstruction::is_cleanup`] two-arm cleanup-family
2916 // arm-discriminator predicate:
2917 // [`UpgradeInstruction::SoftPurge`] and
2918 // [`UpgradeInstruction::Purge`] are the two OTP-appup two-
2919 // phase-code-load cleanup arms that satisfy `.is_cleanup()`;
2920 // every non-cleanup arm ([`UpgradeInstruction::LoadModule`]
2921 // on the paired two-phase-load half,
2922 // [`UpgradeInstruction::StateChange`] on the
2923 // `gen_server:code_change/3`-analog migration axis,
2924 // [`UpgradeInstruction::Restart`] on the OTP terminal-
2925 // fallback shape) returns `false`. This pin makes the
2926 // partition invariant load-bearing at caixa-core test time
2927 // so a future accessor regression (a hole that returns
2928 // `false` for `SoftPurge` or `Purge`, or a byte-collision
2929 // that flips `LoadModule` / `StateChange` / `Restart` to
2930 // `true`) trips here rather than laundering the arm at the
2931 // three within-entry cross-instruction cleanup-facing gates
2932 // ([`UpgradeFromEntry::validate_purge_ordering`],
2933 // [`UpgradeFromEntry::validate_state_change_before_cleanup`],
2934 // [`UpgradeFromEntry::validate_cleanup_singularity`]) — a
2935 // hole would silently accept a cleanup-shaped entry the
2936 // three gates should refuse; a collision would fire a
2937 // `PurgeWithoutPriorLoad` / `StateChangeAfterCleanup` /
2938 // `DuplicateCleanup` refusal on a well-shaped
2939 // [`UpgradeInstruction::LoadModule`] / `StateChange` /
2940 // `Restart` arm the three gates should pass through. Peer
2941 // of the sibling
2942 // [`upgrade_instruction_is_restart_predicate_partitions_the_arm_set`]
2943 // pin on the single-arm terminal-fallback partition —
2944 // extended here from the single-arm case onto the two-arm
2945 // cleanup-family union case.
2946 let cases: &[(UpgradeInstruction, bool)] = &[
2947 (UpgradeInstruction::LoadModule { module: "a".into() }, false),
2948 (UpgradeInstruction::SoftPurge { module: "b".into() }, true),
2949 (UpgradeInstruction::Purge { module: "c".into() }, true),
2950 (
2951 UpgradeInstruction::StateChange {
2952 script: PathBuf::from("lib/m.lisp"),
2953 },
2954 false,
2955 ),
2956 (UpgradeInstruction::Restart, false),
2957 ];
2958 for (variant, expected) in cases {
2959 assert_eq!(
2960 variant.is_cleanup(),
2961 *expected,
2962 "UpgradeInstruction::{variant:?}.is_cleanup() must \
2963 return {expected} (partition invariant on the \
2964 lifted OTP-appup two-arm cleanup-family arm-\
2965 discriminator predicate)"
2966 );
2967 }
2968 }
2969
2970 #[test]
2971 fn upgrade_instruction_is_cleanup_composes_through_is_soft_purge_or_is_purge() {
2972 // Byte-identity pin on the [`UpgradeInstruction::is_cleanup`]
2973 // composition against the two [`gen_platform::IsVariant`]-
2974 // derive-generated per-variant classifiers it routes through
2975 // — the accessor's one body must byte-equal
2976 // `self.is_soft_purge() || self.is_purge()` across every arm
2977 // of the closed-set enum, so a future silent detour that
2978 // reintroduced a raw `matches!` pattern or that stopped
2979 // composing through the derive-generated per-variant
2980 // predicates (an accidental `self.is_soft_purge()` on its
2981 // own — silently dropping the `Purge` arm; an accidental
2982 // `self.is_purge() || self.is_state_change()` — silently
2983 // folding the migration arm into the cleanup family; a
2984 // typo `&&` for the union `||` — silently classifying no
2985 // arm as cleanup) trips here at caixa-core test time
2986 // rather than laundering the arm at the three within-entry
2987 // cross-instruction cleanup-facing gates. Same peer-shape
2988 // pin the sibling
2989 // [`validate_restart_exclusive_routes_through_is_restart_predicate`]
2990 // carries on the paired terminal-fallback axis.
2991 let cases: Vec<UpgradeInstruction> = vec![
2992 UpgradeInstruction::LoadModule { module: "a".into() },
2993 UpgradeInstruction::SoftPurge { module: "b".into() },
2994 UpgradeInstruction::Purge { module: "c".into() },
2995 UpgradeInstruction::StateChange {
2996 script: PathBuf::from("lib/m.lisp"),
2997 },
2998 UpgradeInstruction::Restart,
2999 ];
3000 for instr in &cases {
3001 let via_predicate = instr.is_cleanup();
3002 let via_composition = instr.is_soft_purge() || instr.is_purge();
3003 assert_eq!(
3004 via_predicate, via_composition,
3005 "UpgradeInstruction::{instr:?}: is_cleanup() must \
3006 byte-equal is_soft_purge() || is_purge() — the \
3007 lifted union predicate and its per-variant \
3008 composition are the same axis, one typed dispatch"
3009 );
3010 }
3011 }
3012
3013 #[test]
3014 fn upgrade_instruction_is_cleanup_implies_declared_module_is_some() {
3015 // Composition-pin the load-bearing invariant every consumer
3016 // that routes through `is_cleanup()` + `declared_module()`
3017 // relies on: any [`UpgradeInstruction`] value whose
3018 // `.is_cleanup()` returns `true` must have a `Some(_)`
3019 // `.declared_module()`. This makes the three within-entry
3020 // cross-instruction cleanup-facing gates' `.expect("is_cleanup()
3021 // implies declared_module() is Some")` structurally
3022 // infallible at build time — a future refactor that added
3023 // a cleanup-shaped variant carrying no `:module` would trip
3024 // here rather than panic at
3025 // [`UpgradeFromEntry::validate_purge_ordering`] /
3026 // [`UpgradeFromEntry::validate_state_change_before_cleanup`] /
3027 // [`UpgradeFromEntry::validate_cleanup_singularity`] at
3028 // runtime on the offending author's caixa.lisp.
3029 let cases: Vec<UpgradeInstruction> = vec![
3030 UpgradeInstruction::LoadModule { module: "a".into() },
3031 UpgradeInstruction::SoftPurge { module: "b".into() },
3032 UpgradeInstruction::Purge { module: "c".into() },
3033 UpgradeInstruction::StateChange {
3034 script: PathBuf::from("lib/m.lisp"),
3035 },
3036 UpgradeInstruction::Restart,
3037 ];
3038 for instr in &cases {
3039 if instr.is_cleanup() {
3040 assert!(
3041 instr.declared_module().is_some(),
3042 "UpgradeInstruction::{instr:?}: is_cleanup() \
3043 must imply declared_module().is_some() — the \
3044 three within-entry cross-instruction cleanup-\
3045 facing gates rely on this invariant to route \
3046 the cleanup-target :module scalar through the \
3047 sibling declared_module accessor without a \
3048 pattern-bound `module` binding"
3049 );
3050 }
3051 }
3052 }
3053
3054 #[test]
3055 fn upgrade_instruction_is_load_module_implies_declared_module_is_some() {
3056 // Composition-pin the load-bearing invariant
3057 // [`UpgradeFromEntry::validate_load_singularity`] relies on
3058 // when routing the per-instruction load-family arm-discriminator
3059 // through the sibling
3060 // [`UpgradeInstruction::is_load_module`] +
3061 // [`UpgradeInstruction::declared_module`] accessor pair: any
3062 // [`UpgradeInstruction`] value whose `.is_load_module()`
3063 // returns `true` must have a `Some(_)` `.declared_module()`.
3064 // This makes the gate's `.expect("is_load_module() implies
3065 // declared_module() is Some")` structurally infallible at
3066 // build time — a future refactor that added a load-shaped
3067 // variant carrying no `:module` would trip here rather than
3068 // panic at [`UpgradeFromEntry::validate_load_singularity`]
3069 // at runtime on the offending author's caixa.lisp. Sibling
3070 // of the peer
3071 // [`upgrade_instruction_is_cleanup_implies_declared_module_is_some`]
3072 // composition pin on the two-arm cleanup-family axis — same
3073 // "predicate implies accessor" discipline extended onto the
3074 // single-arm load-family axis, closes the load-vs-cleanup
3075 // pair on the substrate primitive's typed dispatch discipline.
3076 let cases: Vec<UpgradeInstruction> = vec![
3077 UpgradeInstruction::LoadModule { module: "a".into() },
3078 UpgradeInstruction::SoftPurge { module: "b".into() },
3079 UpgradeInstruction::Purge { module: "c".into() },
3080 UpgradeInstruction::StateChange {
3081 script: PathBuf::from("lib/m.lisp"),
3082 },
3083 UpgradeInstruction::Restart,
3084 ];
3085 for instr in &cases {
3086 if instr.is_load_module() {
3087 assert!(
3088 instr.declared_module().is_some(),
3089 "UpgradeInstruction::{instr:?}: is_load_module() \
3090 must imply declared_module().is_some() — the \
3091 within-entry load-singularity gate relies on this \
3092 invariant to route the load-target :module scalar \
3093 through the sibling declared_module accessor \
3094 without a pattern-bound `module` binding"
3095 );
3096 }
3097 }
3098 }
3099
3100 #[test]
3101 fn validate_load_singularity_projects_modules_through_is_load_module_and_declared_module_accessors()
3102 {
3103 // Byte-identity pin on the
3104 // [`UpgradeFromEntry::validate_load_singularity`] load-family
3105 // dispatch against the pre-lift
3106 // `match instr { UpgradeInstruction::LoadModule { module } =>
3107 // module.as_str(), _ => continue }` open-coded pattern-match
3108 // the site previously carried. Asserts the two projections
3109 // agree byte-for-byte on every arm of the enum — the
3110 // arm-discriminator via `is_load_module()` and the `:module`
3111 // scalar via `declared_module()` — so a future derive
3112 // regression that flipped the predicate's arm-set (a hole
3113 // returning `false` for [`UpgradeInstruction::LoadModule`], a
3114 // byte-collision flipping a second variant to `true`) or an
3115 // accessor extension that promoted an additional variant onto
3116 // the `String`-carrying axis would trip here at caixa-core
3117 // test time rather than laundering the arm at the gate's
3118 // per-entry load-singularity scan far from the derive site.
3119 // Peer of the sibling
3120 // [`validate_purge_ordering_routes_through_is_load_module_predicate`]
3121 // byte-identity pin on the paired ordering-side load-family
3122 // sticky-latch dispatch (both consumers now agree on one
3123 // typed dispatch for the load-family axis) and the peer
3124 // [`validate_state_change_singularity_projects_scripts_through_declared_path_accessor`]
3125 // pin on the migration-family script-projection axis — the
3126 // three within-entry per-instruction-class singularity gates
3127 // now share one byte-identity pin apiece against their
3128 // respective substrate-primitive typed dispatches.
3129 //
3130 // Three-arm projective coverage:
3131 // (a) `LoadModule` modules project through
3132 // `declared_module()` byte-equal to the raw
3133 // `module.as_str()` field access;
3134 // (b) a duplicate-`LoadModule` input trips the gate on the
3135 // second occurrence with `DuplicateLoadModule` carrying
3136 // the offending module verbatim;
3137 // (c) a non-`LoadModule`-only input (`SoftPurge` / `Purge` /
3138 // `StateChange` / `Restart`) leaves the gate vacuous
3139 // with `Ok(())` — the `!instr.is_load_module()`
3140 // `continue` fall-through pins.
3141 //
3142 // Fail-before-pass-after verified locally: swapping the
3143 // production `if !instr.is_load_module() { continue; } let
3144 // module = instr.declared_module().expect(…);` back to `let
3145 // module = match instr { UpgradeInstruction::LoadModule
3146 // { module } => module.as_str(), _ => continue, };` keeps
3147 // arms (a)-(c) passing but silently detaches the gate from
3148 // the accessor's typed dispatch — any future
3149 // `is_load_module` / `declared_module` extension (a hole in
3150 // either predicate, a promotion of an additional variant
3151 // onto the `String`-carrying axis, an operator-side
3152 // pre-parsed caixa-name cache the accessor materializes)
3153 // would then silently disagree between this gate's raw
3154 // pattern-match and the peer per-`UpgradeInstruction`
3155 // consumers that route through the accessor pair.
3156
3157 // (a) LoadModule projection byte-equal via
3158 // is_load_module() + declared_module().
3159 let lm = UpgradeInstruction::LoadModule {
3160 module: "hello-rio".into(),
3161 };
3162 assert!(
3163 lm.is_load_module(),
3164 "LoadModule must satisfy is_load_module() — the gate's \
3165 load-family arm-discriminator relies on this partition"
3166 );
3167 assert_eq!(
3168 lm.declared_module(),
3169 Some("hello-rio"),
3170 "declared_module() must project the LoadModule :module \
3171 byte-equal to the raw field access — accessor divergence \
3172 would silently detach the gate from the projection every \
3173 peer per-`UpgradeInstruction` consumer routes through"
3174 );
3175
3176 // (b) Duplicate-LoadModule input trips the gate.
3177 let dup = entry(
3178 "0.1.0",
3179 vec![
3180 UpgradeInstruction::LoadModule { module: "x".into() },
3181 UpgradeInstruction::LoadModule { module: "x".into() },
3182 ],
3183 );
3184 assert_eq!(
3185 dup.validate_load_singularity(),
3186 Err(UpgradeError::DuplicateLoadModule {
3187 from: "0.1.0".into(),
3188 module: "x".into(),
3189 }),
3190 "duplicate LoadModule modules within one entry must fire \
3191 DuplicateLoadModule byte-identical to the pre-lift \
3192 pattern-match shape"
3193 );
3194
3195 // (c) Non-LoadModule-only input leaves the gate vacuous.
3196 let no_load = entry(
3197 "0.1.0",
3198 vec![
3199 UpgradeInstruction::StateChange {
3200 script: PathBuf::from("lib/m.lisp"),
3201 },
3202 UpgradeInstruction::Restart,
3203 ],
3204 );
3205 assert_eq!(
3206 no_load.validate_load_singularity(),
3207 Ok(()),
3208 "non-LoadModule-only entries must leave the load-\
3209 singularity gate vacuous — the `!is_load_module()` \
3210 continue fall-through pins"
3211 );
3212 }
3213
3214 #[test]
3215 fn upgrade_instruction_is_load_module_predicate_partitions_the_arm_set() {
3216 // The fail-before-pass-after pin on the `gen_platform::IsVariant`
3217 // derive's [`UpgradeInstruction::is_load_module`] arm-discriminator
3218 // predicate: [`UpgradeInstruction::LoadModule`] is the only
3219 // variant that satisfies `.is_load_module()`; every cleanup arm
3220 // (`SoftPurge` / `Purge`), the migration arm (`StateChange`),
3221 // and the terminal-fallback arm (`Restart`) all return `false`.
3222 // This pin makes the partition invariant load-bearing at
3223 // caixa-core test time so a future derive regression (a hole
3224 // that returns `false` for `LoadModule` too, or a byte-collision
3225 // that flips a second variant to `true`) trips here rather than
3226 // laundering the arm at
3227 // [`Self::validate_purge_ordering`]'s load-family sticky-latch
3228 // dispatch — a hole would silently keep `loaded = false` through
3229 // a well-shaped [`UpgradeInstruction::LoadModule`] prefix and
3230 // false-fire `PurgeWithoutPriorLoad` on the trailing cleanup;
3231 // a collision would flip `loaded = true` on a well-shaped
3232 // cleanup-only entry and silently swallow the load-less
3233 // `PurgeWithoutPriorLoad` refusal. Peer of the sibling
3234 // [`upgrade_instruction_is_restart_predicate_partitions_the_arm_set`]
3235 // and
3236 // [`upgrade_instruction_is_cleanup_predicate_partitions_the_arm_set`]
3237 // pins on the paired terminal-fallback and cleanup-family
3238 // arm-discriminator axes — closes the last unlifted `matches!`-
3239 // based arm-discriminator axis on the OTP-appup closed-set
3240 // typed enum.
3241 let cases: &[(UpgradeInstruction, bool)] = &[
3242 (UpgradeInstruction::LoadModule { module: "a".into() }, true),
3243 (UpgradeInstruction::SoftPurge { module: "b".into() }, false),
3244 (UpgradeInstruction::Purge { module: "c".into() }, false),
3245 (
3246 UpgradeInstruction::StateChange {
3247 script: PathBuf::from("lib/m.lisp"),
3248 },
3249 false,
3250 ),
3251 (UpgradeInstruction::Restart, false),
3252 ];
3253 for (variant, expected) in cases {
3254 assert_eq!(
3255 variant.is_load_module(),
3256 *expected,
3257 "UpgradeInstruction::{variant:?}.is_load_module() must \
3258 return {expected} (partition invariant on the \
3259 IsVariant-derived arm-discriminator predicate)"
3260 );
3261 }
3262 }
3263
3264 #[test]
3265 fn validate_purge_ordering_routes_through_is_load_module_predicate() {
3266 // Byte-identity pin on the [`Self::validate_purge_ordering`]
3267 // load-family sticky-latch dispatch against the pre-lift
3268 // `matches!(instr, UpgradeInstruction::LoadModule { .. })`
3269 // predicate the site previously open-coded. Asserts the two
3270 // projections agree byte-for-byte on every arm of the enum, so
3271 // a future derive regression that flipped the predicate's
3272 // arm-set would surface here at caixa-core test time rather
3273 // than at [`Self::validate_purge_ordering`]'s per-entry
3274 // load-before-cleanup ordering scan far from the derive site.
3275 // Same peer-shape pin the sibling
3276 // [`validate_restart_exclusive_routes_through_is_restart_predicate`]
3277 // carries on the paired terminal-fallback axis and the
3278 // [`upgrade_instruction_is_cleanup_composes_through_is_soft_purge_or_is_purge`]
3279 // carries on the two-arm cleanup-family axis — the third and
3280 // final byte-identity pin closes the substrate primitive's
3281 // arm-discriminator dispatch discipline on the OTP-appup
3282 // closed-set typed enum.
3283 let cases: Vec<UpgradeInstruction> = vec![
3284 UpgradeInstruction::LoadModule { module: "a".into() },
3285 UpgradeInstruction::SoftPurge { module: "b".into() },
3286 UpgradeInstruction::Purge { module: "c".into() },
3287 UpgradeInstruction::StateChange {
3288 script: PathBuf::from("lib/m.lisp"),
3289 },
3290 UpgradeInstruction::Restart,
3291 ];
3292 for instr in &cases {
3293 let via_predicate = instr.is_load_module();
3294 let via_matches = matches!(instr, UpgradeInstruction::LoadModule { .. });
3295 assert_eq!(
3296 via_predicate, via_matches,
3297 "UpgradeInstruction::{instr:?}: is_load_module() must \
3298 byte-equal matches!(_, UpgradeInstruction::LoadModule \
3299 {{ .. }}) — the pre-lift open-coded pattern and the \
3300 IsVariant-derived predicate are the same axis, one \
3301 typed dispatch"
3302 );
3303 }
3304 }
3305
3306 #[test]
3307 fn declared_module_only_for_module_bearing_variants() {
3308 // Pinned partition of the `UpgradeInstruction` closed-set
3309 // variant space against the sibling of the peer
3310 // `declared_path` accessor: every OTP-appup module-bearing
3311 // variant (`LoadModule` / `SoftPurge` / `Purge`) surfaces its
3312 // `:module` string byte-for-byte through the lifted
3313 // `declared_module` accessor; every non-module-bearing variant
3314 // (`StateChange` on the peer `:script`-carrying axis;
3315 // `Restart` on the OTP terminal-fallback data-less axis)
3316 // returns `None`. Mirrors the peer
3317 // `declared_path_only_for_state_change` pin — the pair now
3318 // closes both scalar-carrying axes on the enum on one lifted
3319 // `Option<&…>` accessor apiece.
3320 let load = UpgradeInstruction::LoadModule {
3321 module: "hello-rio".into(),
3322 };
3323 assert_eq!(load.declared_module(), Some("hello-rio"));
3324 let soft = UpgradeInstruction::SoftPurge {
3325 module: "hello-rio-old".into(),
3326 };
3327 assert_eq!(soft.declared_module(), Some("hello-rio-old"));
3328 let hard = UpgradeInstruction::Purge {
3329 module: "hello-rio-ancient".into(),
3330 };
3331 assert_eq!(hard.declared_module(), Some("hello-rio-ancient"));
3332 let mig = UpgradeInstruction::StateChange {
3333 script: PathBuf::from("lib/m.lisp"),
3334 };
3335 assert!(mig.declared_module().is_none());
3336 assert!(UpgradeInstruction::Restart.declared_module().is_none());
3337 }
3338
3339 #[test]
3340 fn declared_module_and_declared_path_partition_the_enum_variant_space() {
3341 // Byte-identity pin on the two-accessor partition: every
3342 // `UpgradeInstruction` variant returns `Some` from *exactly
3343 // one* of {`declared_module`, `declared_path`} (the two
3344 // module-bearing / script-carrying axes) or from *neither*
3345 // (the OTP terminal-fallback `Restart` shape). No variant
3346 // returns `Some` from both — the two axes are disjoint by
3347 // construction, and this pin closes the disjointness at the
3348 // test surface so a future variant that leaks a scalar across
3349 // both axes fails at build time. Mirrors the peer
3350 // `declared_paths_iter_covers_each_declared_slot_exactly_once`
3351 // discipline on the `BehaviorSpec` per-slot family.
3352 let cases: Vec<UpgradeInstruction> = vec![
3353 UpgradeInstruction::LoadModule { module: "a".into() },
3354 UpgradeInstruction::SoftPurge { module: "b".into() },
3355 UpgradeInstruction::Purge { module: "c".into() },
3356 UpgradeInstruction::StateChange {
3357 script: PathBuf::from("lib/m.lisp"),
3358 },
3359 UpgradeInstruction::Restart,
3360 ];
3361 for instr in &cases {
3362 let has_module = instr.declared_module().is_some();
3363 let has_path = instr.declared_path().is_some();
3364 assert!(
3365 !(has_module && has_path),
3366 "no variant may declare both a module and a path — offending: {instr:?}"
3367 );
3368 match instr {
3369 UpgradeInstruction::LoadModule { .. }
3370 | UpgradeInstruction::SoftPurge { .. }
3371 | UpgradeInstruction::Purge { .. } => {
3372 assert!(has_module && !has_path, "module axis: {instr:?}");
3373 }
3374 UpgradeInstruction::StateChange { .. } => {
3375 assert!(!has_module && has_path, "script axis: {instr:?}");
3376 }
3377 UpgradeInstruction::Restart => {
3378 assert!(!has_module && !has_path, "data-less axis: {instr:?}");
3379 }
3380 }
3381 }
3382 }
3383
3384 #[test]
3385 fn entry_with_chain_of_versions() {
3386 // Middle entry pairs a `:load-module` with the trailing
3387 // `:soft-purge` so it satisfies the within-entry purge-ordering
3388 // gate (`PurgeWithoutPriorLoad` rejects `:soft-purge` without a
3389 // preceding `:load-module`, mirroring the state-change-ordering
3390 // gate's `StateChangeWithoutPriorLoad`). The chain shape under
3391 // test is *cross-entry* `:from` values; the within-entry shape
3392 // is incidental — keeping it canonical (`:load-module` before
3393 // `:soft-purge`) leaves the chain assertion load-bearing.
3394 let entries = vec![
3395 entry(
3396 "0.1.0",
3397 vec![UpgradeInstruction::LoadModule { module: "x".into() }],
3398 ),
3399 entry(
3400 "0.1.5",
3401 vec![
3402 UpgradeInstruction::LoadModule { module: "x".into() },
3403 UpgradeInstruction::SoftPurge {
3404 module: "x-old".into(),
3405 },
3406 ],
3407 ),
3408 entry("0.2.0-rc.1", vec![UpgradeInstruction::Restart]),
3409 ];
3410 for e in &entries {
3411 e.validate().unwrap();
3412 }
3413 let json = serde_json::to_string(&entries).unwrap();
3414 let back: Vec<UpgradeFromEntry> = serde_json::from_str(&json).unwrap();
3415 assert_eq!(entries, back);
3416 }
3417
3418 #[test]
3419 fn empty_instructions_list_is_valid() {
3420 let e = entry("0.1.0", vec![]);
3421 e.validate().unwrap();
3422 }
3423
3424 #[test]
3425 fn json_uses_kebab_case_kind_tags() {
3426 let i = UpgradeInstruction::SoftPurge {
3427 module: "x-old".into(),
3428 };
3429 let json = serde_json::to_string(&i).unwrap();
3430 assert!(json.contains("\"kind\":\"soft-purge\""));
3431 let i2 = UpgradeInstruction::StateChange {
3432 script: PathBuf::from("m.lisp"),
3433 };
3434 let json2 = serde_json::to_string(&i2).unwrap();
3435 assert!(json2.contains("\"kind\":\"state-change\""));
3436 }
3437
3438 // ── validate_upgrade_from: cross-entry graph-edge-set invariant ────
3439
3440 #[test]
3441 fn validate_upgrade_from_accepts_disjoint_versions() {
3442 // Positive control: the canonical "chain v0.1.0 → 0.1.5 →
3443 // 0.2.0-rc.1" authoring shape from ABSORPTION-ROADMAP §M2.3
3444 // (and `entry_with_chain_of_versions` above) passes the cross-
3445 // entry gate. Different `:from` per entry is the intended
3446 // shape; the gate must not regress this baseline. Middle entry
3447 // pairs `:load-module` with `:soft-purge` to satisfy the
3448 // within-entry purge-ordering gate (see
3449 // `entry_with_chain_of_versions` for the same shape).
3450 let entries = vec![
3451 entry(
3452 "0.1.0",
3453 vec![UpgradeInstruction::LoadModule { module: "x".into() }],
3454 ),
3455 entry(
3456 "0.1.5",
3457 vec![
3458 UpgradeInstruction::LoadModule { module: "x".into() },
3459 UpgradeInstruction::SoftPurge {
3460 module: "x-old".into(),
3461 },
3462 ],
3463 ),
3464 entry("0.2.0-rc.1", vec![UpgradeInstruction::Restart]),
3465 ];
3466 validate_upgrade_from(&entries).unwrap();
3467 }
3468
3469 #[test]
3470 fn validate_upgrade_from_accepts_empty_list() {
3471 // Absent `:upgrade-from` (the bare `feira init` shape) — the
3472 // gate must trivially pass an empty list. Mirrors the per-axis
3473 // "empty list passes" positive control on every peer typed-
3474 // graph gate (`validate_membros` empty list, `validate_placement`
3475 // requires non-empty clusters but only after a `Placement`
3476 // exists, etc.).
3477 validate_upgrade_from(&[]).unwrap();
3478 }
3479
3480 #[test]
3481 fn validate_upgrade_from_rejects_duplicate_from() {
3482 // Fail-before-pass-after pin: two entries with the same parsed-
3483 // semver `:from` are an ambiguous edge in the typed upgrade
3484 // graph (OTP appup picks at most one matching block per running
3485 // version; with two matching blocks the operator picks either
3486 // set non-deterministically — author intent is one path per
3487 // prior version). Same set-not-multiset discipline as
3488 // `:children :caixa` (dbf50a9), `:membros :caixa` (4bb3f3d),
3489 // `:contratos` (5dbcfaf), `:placement :clusters` (c7c7799),
3490 // `:entrada :paths` (eb3456d) — now extended onto the fifth
3491 // typed-graph axis.
3492 let entries = vec![
3493 entry(
3494 "0.1.0",
3495 vec![UpgradeInstruction::LoadModule { module: "x".into() }],
3496 ),
3497 entry(
3498 "0.1.0",
3499 vec![
3500 UpgradeInstruction::LoadModule { module: "x".into() },
3501 UpgradeInstruction::SoftPurge {
3502 module: "x-old".into(),
3503 },
3504 ],
3505 ),
3506 ];
3507 let err = validate_upgrade_from(&entries).unwrap_err();
3508 assert_eq!(
3509 err,
3510 UpgradeError::DuplicateFrom {
3511 from: "0.1.0".into()
3512 },
3513 "two entries with `:from \"0.1.0\"` must surface as DuplicateFrom carrying the \
3514 offending value verbatim"
3515 );
3516 }
3517
3518 #[test]
3519 fn validate_upgrade_from_treats_pre_release_as_distinct() {
3520 // Negative-of-positive: `1.0.0` and `1.0.0-rc.1` are *not*
3521 // equal under semver (pre-release version is part of the
3522 // identity), so they're distinct upgrade paths and must not
3523 // collide. A future tightening that collapses pre-release into
3524 // the release version surfaces here.
3525 let entries = vec![
3526 entry("1.0.0", vec![UpgradeInstruction::Restart]),
3527 entry("1.0.0-rc.1", vec![UpgradeInstruction::Restart]),
3528 ];
3529 validate_upgrade_from(&entries).unwrap();
3530 }
3531
3532 #[test]
3533 fn validate_upgrade_from_treats_build_metadata_as_distinct() {
3534 // Conservative-by-design: [`semver::Version`]'s `PartialEq`
3535 // compares build metadata (it derives equality across all
3536 // fields including `pre` + `build`), so `1.0.0+build1` and
3537 // `1.0.0+build2` are *not* duplicates from the gate's
3538 // perspective — the operator may treat the build-metadata
3539 // suffix as a tiebreaker even though the semver spec says
3540 // build metadata is ignored for precedence
3541 // (https://semver.org/#spec-item-10). Pin the conservative
3542 // behavior here so a future switch to a build-metadata-
3543 // stripping comparator surfaces as a test failure first; that
3544 // change would require coordinating with the wasm-operator's
3545 // `:from`-match dispatch step, which is the load-bearing
3546 // semantic we'd be mirroring.
3547 let entries = vec![
3548 entry("1.0.0+build1", vec![UpgradeInstruction::Restart]),
3549 entry("1.0.0+build2", vec![UpgradeInstruction::Restart]),
3550 ];
3551 validate_upgrade_from(&entries).unwrap();
3552 }
3553
3554 #[test]
3555 fn validate_upgrade_from_per_entry_shape_fires_before_duplicate() {
3556 // Order pin: a malformed `:from` on the second entry surfaces
3557 // its `FromInvalid` diagnostic, not a (less-useful)
3558 // `DuplicateFrom`. The per-entry shape pass runs *inline*
3559 // before the duplicate-key insert — parallel to
3560 // `child_versao_invalid_fires_before_duplicate_check`
3561 // (b38ff3a) and `membro_versao_invalid_fires_before_duplicate_check`
3562 // (9888b13). Without this pin a future shortcut that runs the
3563 // cross-entry gate first would surface a duplicate diagnostic
3564 // on a string that isn't even parsable as a version.
3565 let entries = vec![
3566 entry("0.1.0", vec![UpgradeInstruction::Restart]),
3567 entry("not-a-semver", vec![UpgradeInstruction::Restart]),
3568 ];
3569 let err = validate_upgrade_from(&entries).unwrap_err();
3570 assert!(
3571 matches!(err, UpgradeError::FromInvalid { ref from, .. } if from == "not-a-semver"),
3572 "malformed `:from` on a non-duplicate entry must surface as FromInvalid, got {err:?}"
3573 );
3574 }
3575
3576 #[test]
3577 fn validate_upgrade_from_per_entry_shape_fires_before_duplicate_on_first_entry() {
3578 // Symmetric arm: a malformed shape on the *first* entry of a
3579 // duplicate pair surfaces its per-entry diagnostic too (not
3580 // the duplicate diagnostic that would otherwise fire on the
3581 // second entry). Pinned separately so a future shortcut that
3582 // walks the duplicate-check ahead of the per-entry pass for the
3583 // first entry only — easy regression to introduce — surfaces
3584 // here.
3585 let entries = vec![
3586 entry(
3587 "0.1.0",
3588 vec![UpgradeInstruction::LoadModule {
3589 module: String::new(),
3590 }],
3591 ),
3592 entry("0.1.0", vec![UpgradeInstruction::Restart]),
3593 ];
3594 let err = validate_upgrade_from(&entries).unwrap_err();
3595 assert_eq!(
3596 err,
3597 UpgradeError::ModuleEmpty {
3598 kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE
3599 },
3600 "malformed instruction on the first entry of a duplicate pair must surface its \
3601 per-entry diagnostic before the duplicate gate fires, got {err:?}"
3602 );
3603 }
3604
3605 #[test]
3606 fn validate_upgrade_from_duplicate_diagnostic_names_second_collision() {
3607 // Diagnostic-shape pin: when three entries carry the same
3608 // `:from`, the gate reports the *first* collision (the second
3609 // entry) and stops — the third entry's duplicate is masked by
3610 // the first surfaced one. Mirrors
3611 // `validate_duplicate_child_diagnostic_names_first_collision`
3612 // (dbf50a9) on the supervisor axis.
3613 let entries = vec![
3614 entry("0.1.0", vec![UpgradeInstruction::Restart]),
3615 entry("0.1.0", vec![UpgradeInstruction::Restart]),
3616 entry("0.1.0", vec![UpgradeInstruction::Restart]),
3617 ];
3618 let err = validate_upgrade_from(&entries).unwrap_err();
3619 assert_eq!(
3620 err,
3621 UpgradeError::DuplicateFrom {
3622 from: "0.1.0".into()
3623 }
3624 );
3625 }
3626
3627 #[test]
3628 fn validate_upgrade_from_single_entry_never_duplicates() {
3629 // Boundary control: a list of one entry can never produce a
3630 // duplicate, regardless of `:from` value (any single-element
3631 // set is trivially without duplicates). Pin this so a future
3632 // off-by-one in the seen-set insert doesn't accidentally flag
3633 // a single entry as duplicating itself.
3634 let entries = vec![entry("0.1.0", vec![UpgradeInstruction::Restart])];
3635 validate_upgrade_from(&entries).unwrap();
3636 }
3637
3638 // ── validate_upgrade_from_against_versao: cross-slot precedence gate ─
3639
3640 #[test]
3641 fn versao_gate_accepts_strict_upgrade() {
3642 // Positive control: the canonical "chain prior versions →
3643 // current" authoring shape from ABSORPTION-ROADMAP §M2.3 — each
3644 // `:from` strictly less than the current `:versao` under
3645 // SemVer-2 precedence. The gate must not regress this baseline.
3646 let entries = vec![
3647 entry("0.1.0", vec![UpgradeInstruction::Restart]),
3648 entry("0.1.5", vec![UpgradeInstruction::Restart]),
3649 entry("0.1.9", vec![UpgradeInstruction::Restart]),
3650 ];
3651 validate_upgrade_from_against_versao(&entries, "0.2.0").unwrap();
3652 }
3653
3654 #[test]
3655 fn versao_gate_accepts_empty_entries() {
3656 // Bare `feira init` shape (no `:upgrade-from`) trivially passes;
3657 // the gate is a no-op when the entries list is empty. Mirrors
3658 // `validate_upgrade_from_accepts_empty_list` on the peer gate.
3659 validate_upgrade_from_against_versao(&[], "0.1.0").unwrap();
3660 }
3661
3662 #[test]
3663 fn versao_gate_rejects_equal_from() {
3664 // Self-upgrade no-op: declaring `:from "0.2.0"` while
3665 // `:versao "0.2.0"` means "upgrade from myself to myself" —
3666 // the operator's dispatch either skips silently or
3667 // trivially "succeeds" with no observable state change.
3668 // Reject as the canonical "I forgot to bump :versao when
3669 // adding this entry" footgun.
3670 let entries = vec![entry("0.2.0", vec![UpgradeInstruction::Restart])];
3671 let err = validate_upgrade_from_against_versao(&entries, "0.2.0").unwrap_err();
3672 assert_eq!(
3673 err,
3674 UpgradeError::FromNotBeforeVersao {
3675 from: "0.2.0".into(),
3676 versao: "0.2.0".into(),
3677 },
3678 ":from == :versao under precedence must surface as FromNotBeforeVersao naming both \
3679 values verbatim, got {err:?}"
3680 );
3681 }
3682
3683 #[test]
3684 fn versao_gate_rejects_downgrade_from() {
3685 // Downgrade-shaped: `:from "0.3.0"` while `:versao "0.2.0"`
3686 // means "upgrade nodes coming from 0.3.0 to 0.2.0", which
3687 // the operator's `:from`-match dispatch can never reach (it
3688 // never runs a version >= the current one). Reject as the
3689 // canonical "I copy-pasted from the next minor version and
3690 // forgot to bump :versao" footgun.
3691 let entries = vec![entry("0.3.0", vec![UpgradeInstruction::Restart])];
3692 let err = validate_upgrade_from_against_versao(&entries, "0.2.0").unwrap_err();
3693 assert_eq!(
3694 err,
3695 UpgradeError::FromNotBeforeVersao {
3696 from: "0.3.0".into(),
3697 versao: "0.2.0".into(),
3698 }
3699 );
3700 }
3701
3702 #[test]
3703 fn versao_gate_accepts_prerelease_before_release() {
3704 // SemVer §11 precedence: pre-release versions are *less than*
3705 // the corresponding release (`0.2.0-rc.1 < 0.2.0`). Upgrading
3706 // FROM an RC TO the GA release is the canonical authoring
3707 // shape — must pass. A regression that collapses pre-release
3708 // into the release version (treating them as equal) surfaces
3709 // here as a false-positive rejection.
3710 let entries = vec![entry("0.2.0-rc.1", vec![UpgradeInstruction::Restart])];
3711 validate_upgrade_from_against_versao(&entries, "0.2.0").unwrap();
3712 }
3713
3714 #[test]
3715 fn versao_gate_rejects_release_after_prerelease() {
3716 // Symmetric arm: with `:versao "0.2.0-rc.1"` and
3717 // `:from "0.2.0"`, precedence says `0.2.0 > 0.2.0-rc.1` —
3718 // the typical "I'm on an RC of a release that already
3719 // shipped" footgun. The gate names both values verbatim
3720 // so the author can grep for either side and fix in one
3721 // edit.
3722 let entries = vec![entry("0.2.0", vec![UpgradeInstruction::Restart])];
3723 let err = validate_upgrade_from_against_versao(&entries, "0.2.0-rc.1").unwrap_err();
3724 assert_eq!(
3725 err,
3726 UpgradeError::FromNotBeforeVersao {
3727 from: "0.2.0".into(),
3728 versao: "0.2.0-rc.1".into(),
3729 }
3730 );
3731 }
3732
3733 #[test]
3734 fn versao_gate_rejects_build_metadata_only_difference() {
3735 // SemVer §11 explicitly excludes build metadata from
3736 // precedence comparison: `0.2.0+build.1` and `0.2.0` are
3737 // *equal* under [`semver::Version::cmp`]. From the
3738 // operator's `:from`-match dispatch perspective this is a
3739 // self-upgrade no-op (no semantic transition between the
3740 // two), so the gate rejects it — *unlike* the peer
3741 // duplicate-`:from` gate which uses derived `PartialEq` and
3742 // treats build-metadata variants as distinct dispatch keys.
3743 // The two gates' different equality notions are deliberate:
3744 // duplicate-check is conservative (preserves operator-side
3745 // tiebreaking surface), precedence-check is permissive
3746 // (matches operator-side dispatch semantic).
3747 let entries = vec![entry("0.2.0+build.1", vec![UpgradeInstruction::Restart])];
3748 let err = validate_upgrade_from_against_versao(&entries, "0.2.0").unwrap_err();
3749 assert_eq!(
3750 err,
3751 UpgradeError::FromNotBeforeVersao {
3752 from: "0.2.0+build.1".into(),
3753 versao: "0.2.0".into(),
3754 }
3755 );
3756 }
3757
3758 #[test]
3759 fn versao_gate_silently_passes_on_unparseable_versao() {
3760 // Defensive arm: a malformed `:versao` (gated by the
3761 // narrower `ManifestError::VersaoInvalid` surface at the
3762 // load-bearing call site) must not regress into a
3763 // `FromNotBeforeVersao` diagnostic from this gate. Surfacing
3764 // the precedence error over an unparseable `:versao` would
3765 // mask the more actionable root cause (the author meant to
3766 // type `"0.2.0"`, not `"v0.2.0"`).
3767 let entries = vec![entry("0.1.0", vec![UpgradeInstruction::Restart])];
3768 validate_upgrade_from_against_versao(&entries, "not-a-semver").unwrap();
3769 }
3770
3771 #[test]
3772 fn versao_gate_silently_passes_on_unparseable_from() {
3773 // Symmetric defensive arm: a malformed `:from` is gated by
3774 // [`UpgradeFromEntry::validate`] / [`validate_upgrade_from`]
3775 // upstream at the LayoutInvariants call site. Surfacing the
3776 // precedence error over an unparseable `:from` from this
3777 // gate alone would mask the narrower `FromInvalid`
3778 // diagnostic that's expected to lead — same fall-through
3779 // posture as the unparseable-`:versao` arm above. The
3780 // wiring in `LayoutInvariants::verify` runs
3781 // `validate_upgrade_from` *before* this gate, so in practice
3782 // an unparseable `:from` surfaces as `FromInvalid` first
3783 // and this gate is never reached on that input.
3784 let entries = vec![entry("not-a-semver", vec![UpgradeInstruction::Restart])];
3785 validate_upgrade_from_against_versao(&entries, "0.2.0").unwrap();
3786 }
3787
3788 #[test]
3789 fn versao_gate_reports_first_offending_entry() {
3790 // Determinism pin: with multiple offending entries the gate
3791 // surfaces the *first* one in declaration order — same
3792 // posture as `validate_upgrade_from_duplicate_diagnostic_names_second_collision`
3793 // on the peer gate. Walks the entries in order; first
3794 // failing `:from >= :versao` short-circuits.
3795 let entries = vec![
3796 entry("0.1.0", vec![UpgradeInstruction::Restart]),
3797 entry("0.3.0", vec![UpgradeInstruction::Restart]),
3798 entry("0.4.0", vec![UpgradeInstruction::Restart]),
3799 ];
3800 let err = validate_upgrade_from_against_versao(&entries, "0.2.0").unwrap_err();
3801 assert_eq!(
3802 err,
3803 UpgradeError::FromNotBeforeVersao {
3804 from: "0.3.0".into(),
3805 versao: "0.2.0".into(),
3806 },
3807 "the first offending `:from` (0.3.0) must surface, not the later one (0.4.0)"
3808 );
3809 }
3810
3811 // ── UpgradeFromEntry::validate_restart_exclusive: within-entry gate ─
3812
3813 #[test]
3814 fn validate_rejects_restart_mixed_with_load_module() {
3815 // The "I'll try the typed path *then* restart anyway" footgun:
3816 // an instructions list with `(:restart)` plus `(:load-module …)`
3817 // is dead code in both directions (succeed → restart discards
3818 // the work that just succeeded, defeating the typed sequence's
3819 // whole point; fail → restart never reached because the entry
3820 // already failed). The gate names the offending entry's `:from`
3821 // verbatim plus the kebab-case lisp-form of every non-`:restart`
3822 // peer so the author can grep their caixa.lisp for either side
3823 // and fix in one edit.
3824 let e = entry(
3825 "0.1.0",
3826 vec![
3827 UpgradeInstruction::LoadModule {
3828 module: "hello-rio".into(),
3829 },
3830 UpgradeInstruction::Restart,
3831 ],
3832 );
3833 let err = e.validate().unwrap_err();
3834 assert_eq!(
3835 err,
3836 UpgradeError::RestartNotExclusive {
3837 from: "0.1.0".into(),
3838 restart_count: 1,
3839 other_kinds: vec![crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE],
3840 },
3841 "restart + load-module mix must surface as RestartNotExclusive naming the \
3842 offending `:from` + the non-:restart kinds verbatim, got {err:?}"
3843 );
3844 }
3845
3846 #[test]
3847 fn validate_rejects_restart_mixed_with_full_typed_sequence() {
3848 // Sweep the typed-sequence universe — every non-`:restart`
3849 // variant alongside `:restart` — and assert every typed
3850 // instruction's lisp-form appears in `other_kinds` in
3851 // declaration order. The author should be able to grep for
3852 // each verbatim (`:load-module`, `:state-change`, `:soft-purge`,
3853 // `:purge`) and resolve in one pass. Drift in the `lisp_form`
3854 // mapping surfaces here.
3855 let e = entry(
3856 "0.1.0",
3857 vec![
3858 UpgradeInstruction::LoadModule {
3859 module: "hello-rio".into(),
3860 },
3861 UpgradeInstruction::StateChange {
3862 script: PathBuf::from("lib/m.lisp"),
3863 },
3864 UpgradeInstruction::SoftPurge {
3865 module: "hello-rio-old".into(),
3866 },
3867 UpgradeInstruction::Purge {
3868 module: "hello-rio-old".into(),
3869 },
3870 UpgradeInstruction::Restart,
3871 ],
3872 );
3873 let err = e.validate().unwrap_err();
3874 assert_eq!(
3875 err,
3876 UpgradeError::RestartNotExclusive {
3877 from: "0.1.0".into(),
3878 restart_count: 1,
3879 other_kinds: vec![
3880 crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE,
3881 crate::render::M2_UPGRADE_INSTRUCTION_KIND_STATE_CHANGE,
3882 crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
3883 crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
3884 ],
3885 },
3886 );
3887 }
3888
3889 #[test]
3890 fn validate_rejects_restart_duplicated() {
3891 // `((:restart) (:restart))` — multiple Restart variants in one
3892 // entry. The fallback is a single semantic (restart the pod;
3893 // the new version comes up fresh); repeating it is at best
3894 // redundant, at worst suggests the author thought the second
3895 // would re-trigger after the first. The gate reports
3896 // `restart_count: 2` so the diagnostic surfaces the duplication
3897 // mode unambiguously even when `other_kinds` is empty.
3898 let e = entry(
3899 "0.1.0",
3900 vec![UpgradeInstruction::Restart, UpgradeInstruction::Restart],
3901 );
3902 let err = e.validate().unwrap_err();
3903 assert_eq!(
3904 err,
3905 UpgradeError::RestartNotExclusive {
3906 from: "0.1.0".into(),
3907 restart_count: 2,
3908 other_kinds: vec![],
3909 },
3910 );
3911 }
3912
3913 #[test]
3914 fn validate_accepts_sole_restart() {
3915 // Positive control: the canonical "this prior version's typed
3916 // upgrade is impossible — restart" authoring shape from the
3917 // UpgradeInstruction::Restart doc comment. `((:restart))` alone
3918 // is the entry's whole instructions list and the only valid
3919 // Restart-bearing shape.
3920 let e = entry("0.1.0", vec![UpgradeInstruction::Restart]);
3921 e.validate().unwrap();
3922 }
3923
3924 #[test]
3925 fn validate_accepts_typed_sequence_without_restart() {
3926 // Positive control: the canonical typed hot-upgrade authoring
3927 // shape from ABSORPTION-ROADMAP §M2.3 — `:load-module` →
3928 // `:state-change` → `:soft-purge`. Absent `:restart` is the
3929 // only shape that lets the sequence run to completion under
3930 // the wasm-operator's `:from`-match dispatch. Drift here =
3931 // a future tighten that rejects any canonical typed-only shape
3932 // surfaces as a regression at this gate.
3933 let e = entry(
3934 "0.1.0",
3935 vec![
3936 UpgradeInstruction::LoadModule {
3937 module: "hello-rio".into(),
3938 },
3939 UpgradeInstruction::StateChange {
3940 script: PathBuf::from("lib/m.lisp"),
3941 },
3942 UpgradeInstruction::SoftPurge {
3943 module: "hello-rio-old".into(),
3944 },
3945 ],
3946 );
3947 e.validate().unwrap();
3948 }
3949
3950 // ── within-entry state-change-ordering invariant ───────────────────
3951
3952 #[test]
3953 fn validate_rejects_state_change_without_load() {
3954 // Fail-before-pass-after pin: a `:state-change` migrates state
3955 // into the newly-loaded code (gen_server:code_change/3 analog),
3956 // so an entry that runs it with no preceding `:load-module`
3957 // migrates state into code that was never loaded. The operator
3958 // runs instructions in declared order, so this is a build error,
3959 // not a runtime surprise (CAIXA-SDLC §III).
3960 let e = entry(
3961 "0.1.0",
3962 vec![UpgradeInstruction::StateChange {
3963 script: PathBuf::from("lib/m.lisp"),
3964 }],
3965 );
3966 let err = e.validate().unwrap_err();
3967 assert_eq!(
3968 err,
3969 UpgradeError::StateChangeWithoutPriorLoad {
3970 from: "0.1.0".into(),
3971 script: PathBuf::from("lib/m.lisp"),
3972 },
3973 "a `:state-change` with no preceding `:load-module` must surface as \
3974 StateChangeWithoutPriorLoad naming the offending entry + script verbatim"
3975 );
3976 }
3977
3978 #[test]
3979 fn validate_rejects_state_change_before_load() {
3980 // Right-instructions-wrong-order: the load is present but runs
3981 // *after* the migration. Because the operator executes in
3982 // declared order, the migration runs before the new code is
3983 // resident — the same incoherence as the missing-load case.
3984 let e = entry(
3985 "0.1.0",
3986 vec![
3987 UpgradeInstruction::StateChange {
3988 script: PathBuf::from("lib/m.lisp"),
3989 },
3990 UpgradeInstruction::LoadModule {
3991 module: "hello-rio".into(),
3992 },
3993 ],
3994 );
3995 let err = e.validate().unwrap_err();
3996 assert!(
3997 matches!(err, UpgradeError::StateChangeWithoutPriorLoad { .. }),
3998 "a `:state-change` ahead of its `:load-module` must surface as \
3999 StateChangeWithoutPriorLoad, got {err:?}"
4000 );
4001 }
4002
4003 #[test]
4004 fn validate_accepts_state_change_after_load() {
4005 // Positive control: the canonical `(:load-module …)
4006 // (:state-change …)` order validates. The load need not name
4007 // the same module the migration targets (StateChange carries a
4008 // script, not a module ref), so any preceding `:load-module`
4009 // satisfies "new code is resident before its migration runs".
4010 let e = entry(
4011 "0.1.0",
4012 vec![
4013 UpgradeInstruction::LoadModule {
4014 module: "hello-rio".into(),
4015 },
4016 UpgradeInstruction::StateChange {
4017 script: PathBuf::from("lib/m.lisp"),
4018 },
4019 ],
4020 );
4021 e.validate().unwrap();
4022 }
4023
4024 #[test]
4025 fn validate_accepts_multiple_state_changes_after_one_load() {
4026 // A single leading `:load-module` covers every subsequent
4027 // `:state-change` — the `loaded` latch stays set once the new
4028 // code is resident.
4029 let e = entry(
4030 "0.1.0",
4031 vec![
4032 UpgradeInstruction::LoadModule {
4033 module: "hello-rio".into(),
4034 },
4035 UpgradeInstruction::StateChange {
4036 script: PathBuf::from("lib/m1.lisp"),
4037 },
4038 UpgradeInstruction::StateChange {
4039 script: PathBuf::from("lib/m2.lisp"),
4040 },
4041 ],
4042 );
4043 e.validate().unwrap();
4044 }
4045
4046 #[test]
4047 fn validate_state_change_ordering_projects_scripts_through_is_load_module_and_declared_path_accessors()
4048 {
4049 // Byte-identity pin on the
4050 // [`UpgradeFromEntry::validate_state_change_ordering`] load →
4051 // migrate ordering dispatch against the pre-lift
4052 // `match instr { UpgradeInstruction::LoadModule { .. } =>
4053 // loaded = true, UpgradeInstruction::StateChange { script } if
4054 // !loaded => …, _ => {} }` open-coded pattern-match the site
4055 // previously carried. Asserts the two projections agree
4056 // byte-for-byte on every arm of the enum — the load-family
4057 // arm-discriminator via `is_load_module()` and the migration-
4058 // family `:script` scalar via `declared_path()` — so a future
4059 // derive regression that flipped the predicate's arm-set (a
4060 // hole returning `false` for [`UpgradeInstruction::LoadModule`],
4061 // a byte-collision flipping a second variant to `true`) or an
4062 // accessor extension that promoted an additional variant onto
4063 // the `PathBuf`-carrying axis would trip here at caixa-core
4064 // test time rather than laundering the arm at the gate's
4065 // per-entry ordering scan far from the derive site.
4066 //
4067 // Peer of the sibling
4068 // [`validate_load_singularity_projects_modules_through_is_load_module_and_declared_module_accessors`]
4069 // (c9ce91d) pin on the peer within-entry per-instruction-class
4070 // singularity gate's load-family + `String`-carrying dispatch,
4071 // the [`validate_purge_ordering_routes_through_is_load_module_predicate`]
4072 // (580d0f1) pin on the paired load → cleanup ordering gate's
4073 // load-family sticky-latch dispatch, and the
4074 // [`validate_state_change_singularity_projects_scripts_through_declared_path_accessor`]
4075 // pin on the peer within-entry per-instruction-class singularity
4076 // gate's migration-family script-projection dispatch — closes
4077 // the last unlifted `match`-shaped per-arm-hand-rolled load-
4078 // family arm-discriminator + migration-family script-projection
4079 // pair inside `impl UpgradeFromEntry`. The four within-entry
4080 // ordering / singularity gates now share one byte-identity pin
4081 // apiece against their respective substrate-primitive typed
4082 // dispatches on the OTP-appup closed-set enum.
4083 //
4084 // Three-arm projective coverage:
4085 // (a) `LoadModule` satisfies `is_load_module()`, so the
4086 // sticky-latch advances byte-equal to the pre-lift
4087 // `UpgradeInstruction::LoadModule { .. }` arm; every
4088 // other variant leaves the latch untouched;
4089 // (b) a `((:state-change …))`-only entry (no preceding load)
4090 // trips the gate on the first `StateChange` with
4091 // `StateChangeWithoutPriorLoad` carrying the offending
4092 // script verbatim — the migration-family script surfaces
4093 // through `declared_path()` byte-equal to the raw
4094 // `StateChange { script }` pattern-bound field;
4095 // (c) a `((:load-module …) (:state-change …))` entry leaves
4096 // the gate vacuous with `Ok(())` — the `loaded = true`
4097 // latch on the first arm satisfies the `!loaded` guard
4098 // negation on the second, so the `declared_path()`
4099 // `Some(script)` fall-through does not fire — and a
4100 // non-`StateChange`-non-`LoadModule` sequence
4101 // (`SoftPurge` / `Purge` / `Restart` alone) also leaves
4102 // the gate vacuous because `declared_path()` is `None`
4103 // on all three of those arms.
4104 //
4105 // Fail-before-pass-after verified locally: swapping the
4106 // production `if instr.is_load_module() { loaded = true; }
4107 // else if !loaded && let Some(script) = instr.declared_path()
4108 // { … }` back to `match instr { UpgradeInstruction::LoadModule
4109 // { .. } => loaded = true, UpgradeInstruction::StateChange
4110 // { script } if !loaded => …, _ => {} }` keeps arms (a)-(c)
4111 // passing but silently detaches the gate from the accessor's
4112 // typed dispatch — any future `is_load_module` / `declared_path`
4113 // extension (a hole in either predicate, a promotion of an
4114 // additional variant onto either axis, an operator-side
4115 // pre-resolved-path cache the accessor materializes) would
4116 // then silently disagree between this gate's raw pattern-match
4117 // and the peer per-`UpgradeInstruction` consumers that route
4118 // through the accessor pair.
4119
4120 // (a) is_load_module() partitions the arm-set byte-equal to
4121 // the pre-lift `matches!(_, UpgradeInstruction::LoadModule
4122 // { .. })` and declared_path() surfaces the StateChange
4123 // `:script` byte-equal to the raw field access.
4124 let lm = UpgradeInstruction::LoadModule {
4125 module: "hello-rio".into(),
4126 };
4127 assert!(
4128 lm.is_load_module(),
4129 "LoadModule must satisfy is_load_module() — the gate's \
4130 load-family sticky-latch relies on this partition"
4131 );
4132 assert!(
4133 lm.declared_path().is_none(),
4134 "LoadModule must not carry a declared_path — the gate's \
4135 else-if migration-family arm must not fire on load arms"
4136 );
4137 let sc = UpgradeInstruction::StateChange {
4138 script: PathBuf::from("lib/m.lisp"),
4139 };
4140 assert!(
4141 !sc.is_load_module(),
4142 "StateChange must not satisfy is_load_module() — the gate's \
4143 sticky-latch must not advance on migration arms"
4144 );
4145 assert_eq!(
4146 sc.declared_path().map(std::path::PathBuf::as_path),
4147 Some(PathBuf::from("lib/m.lisp").as_path()),
4148 "declared_path() must project the StateChange :script \
4149 byte-equal to the raw field access — accessor divergence \
4150 would silently detach the gate from the projection every \
4151 peer per-`UpgradeInstruction` consumer routes through"
4152 );
4153
4154 // (b) A `((:state-change …))`-only entry trips
4155 // StateChangeWithoutPriorLoad byte-identical to the
4156 // pre-lift match-pattern shape.
4157 let no_prior_load = entry(
4158 "0.1.0",
4159 vec![UpgradeInstruction::StateChange {
4160 script: PathBuf::from("lib/m.lisp"),
4161 }],
4162 );
4163 assert_eq!(
4164 no_prior_load.validate_state_change_ordering(),
4165 Err(UpgradeError::StateChangeWithoutPriorLoad {
4166 from: "0.1.0".into(),
4167 script: PathBuf::from("lib/m.lisp"),
4168 }),
4169 "a `:state-change` with no preceding `:load-module` must fire \
4170 StateChangeWithoutPriorLoad carrying the offending script \
4171 verbatim through the declared_path() accessor"
4172 );
4173
4174 // (c) `((:load-module …) (:state-change …))` leaves the gate
4175 // vacuous; so does a non-StateChange-non-LoadModule
4176 // sequence (SoftPurge / Purge / Restart alone).
4177 let load_before_migrate = entry(
4178 "0.1.0",
4179 vec![
4180 UpgradeInstruction::LoadModule {
4181 module: "hello-rio".into(),
4182 },
4183 UpgradeInstruction::StateChange {
4184 script: PathBuf::from("lib/m.lisp"),
4185 },
4186 ],
4187 );
4188 assert_eq!(
4189 load_before_migrate.validate_state_change_ordering(),
4190 Ok(()),
4191 "load-before-migrate entries must leave the ordering gate \
4192 vacuous — the `loaded = true` sticky-latch on the first arm \
4193 satisfies the `!loaded` guard negation on the else-if arm"
4194 );
4195 for instr in [
4196 UpgradeInstruction::SoftPurge {
4197 module: "x-old".into(),
4198 },
4199 UpgradeInstruction::Purge {
4200 module: "x-old".into(),
4201 },
4202 UpgradeInstruction::Restart,
4203 ] {
4204 let e = entry("0.1.0", vec![instr.clone()]);
4205 assert_eq!(
4206 e.validate_state_change_ordering(),
4207 Ok(()),
4208 "non-StateChange-non-LoadModule sequence ({instr:?}) must \
4209 leave the ordering gate vacuous — declared_path() is None \
4210 on every non-StateChange arm, so the else-if migration-\
4211 family arm never fires"
4212 );
4213 }
4214 }
4215
4216 #[test]
4217 fn validate_state_change_ordering_fires_after_restart_exclusive() {
4218 // Diagnostic-precedence pin: a `((:state-change …) (:restart))`
4219 // shape is *both* state-change-without-load and restart-mixed.
4220 // The more-fundamental `RestartNotExclusive` must win (a valid
4221 // `(:restart)` entry is `(:restart)` alone, so no Restart-bearing
4222 // entry should reach the ordering gate). Guards the call order
4223 // in `validate` against silent reordering.
4224 let e = entry(
4225 "0.1.0",
4226 vec![
4227 UpgradeInstruction::StateChange {
4228 script: PathBuf::from("lib/m.lisp"),
4229 },
4230 UpgradeInstruction::Restart,
4231 ],
4232 );
4233 let err = e.validate().unwrap_err();
4234 assert!(
4235 matches!(err, UpgradeError::RestartNotExclusive { .. }),
4236 "restart-mixed must surface before the ordering gate, got {err:?}"
4237 );
4238 }
4239
4240 // ── within-entry purge-ordering invariant ──────────────────────────
4241
4242 #[test]
4243 fn validate_rejects_soft_purge_without_load() {
4244 // Fail-before-pass-after pin: `:soft-purge` drains the *old*
4245 // module after the new one is resident (OTP's two-phase code
4246 // load — code:load_module/1 then code:soft_purge/1), so an
4247 // entry that runs it with no preceding `:load-module` drains
4248 // the live module with no replacement. The operator runs
4249 // instructions in declared order, so this is a build error,
4250 // not a runtime surprise (CAIXA-SDLC §III).
4251 let e = entry(
4252 "0.1.0",
4253 vec![UpgradeInstruction::SoftPurge {
4254 module: "x-old".into(),
4255 }],
4256 );
4257 let err = e.validate().unwrap_err();
4258 assert_eq!(
4259 err,
4260 UpgradeError::PurgeWithoutPriorLoad {
4261 from: "0.1.0".into(),
4262 kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
4263 module: "x-old".into(),
4264 },
4265 "a `:soft-purge` with no preceding `:load-module` must surface as \
4266 PurgeWithoutPriorLoad naming the offending entry + kind + module verbatim"
4267 );
4268 }
4269
4270 #[test]
4271 fn validate_rejects_purge_without_load() {
4272 // Per-arm coverage: `:purge` (immediate discard, no drain) is
4273 // the more catastrophic peer of `:soft-purge`; same gate, same
4274 // shape, kind-tag differs so the author can grep their
4275 // caixa.lisp for the offending `(:purge …)` form.
4276 let e = entry(
4277 "0.1.0",
4278 vec![UpgradeInstruction::Purge {
4279 module: "x-old".into(),
4280 }],
4281 );
4282 let err = e.validate().unwrap_err();
4283 assert_eq!(
4284 err,
4285 UpgradeError::PurgeWithoutPriorLoad {
4286 from: "0.1.0".into(),
4287 kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
4288 module: "x-old".into(),
4289 },
4290 );
4291 }
4292
4293 #[test]
4294 fn validate_rejects_soft_purge_before_load() {
4295 // Right-instructions-wrong-order: the load is present but runs
4296 // *after* the purge. Because the operator executes in declared
4297 // order, the cleanup drains the old code before the new code
4298 // is resident — same incoherence as the missing-load case,
4299 // leaving a window during which neither version is available.
4300 let e = entry(
4301 "0.1.0",
4302 vec![
4303 UpgradeInstruction::SoftPurge {
4304 module: "x-old".into(),
4305 },
4306 UpgradeInstruction::LoadModule { module: "x".into() },
4307 ],
4308 );
4309 let err = e.validate().unwrap_err();
4310 assert!(
4311 matches!(
4312 err,
4313 UpgradeError::PurgeWithoutPriorLoad {
4314 kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
4315 ..
4316 }
4317 ),
4318 "a `:soft-purge` ahead of its `:load-module` must surface as \
4319 PurgeWithoutPriorLoad, got {err:?}"
4320 );
4321 }
4322
4323 #[test]
4324 fn validate_rejects_purge_before_load() {
4325 // Symmetric arm on the `:purge` variant — the kind tag
4326 // distinguishes the diagnostic so the author lands on the
4327 // offending form directly.
4328 let e = entry(
4329 "0.1.0",
4330 vec![
4331 UpgradeInstruction::Purge {
4332 module: "x-old".into(),
4333 },
4334 UpgradeInstruction::LoadModule { module: "x".into() },
4335 ],
4336 );
4337 let err = e.validate().unwrap_err();
4338 assert!(
4339 matches!(
4340 err,
4341 UpgradeError::PurgeWithoutPriorLoad {
4342 kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
4343 ..
4344 }
4345 ),
4346 "a `:purge` ahead of its `:load-module` must surface as \
4347 PurgeWithoutPriorLoad, got {err:?}"
4348 );
4349 }
4350
4351 #[test]
4352 fn validate_accepts_soft_purge_after_load() {
4353 // Positive control: the canonical `(:load-module …)
4354 // (:soft-purge …)` order validates. The load need not name the
4355 // same module the purge targets — the cleanup typically targets
4356 // the *old* module name (e.g. `"x-old"`) and the load brings up
4357 // the *new* one (`"x"`); the gate only requires that *some*
4358 // `:load-module` precedes the purge, so the new code is resident
4359 // before the old one is drained.
4360 let e = entry(
4361 "0.1.0",
4362 vec![
4363 UpgradeInstruction::LoadModule { module: "x".into() },
4364 UpgradeInstruction::SoftPurge {
4365 module: "x-old".into(),
4366 },
4367 ],
4368 );
4369 e.validate().unwrap();
4370 }
4371
4372 #[test]
4373 fn validate_accepts_multiple_purges_after_one_load() {
4374 // A single leading `:load-module` covers every subsequent
4375 // `:soft-purge` / `:purge` — the `loaded` latch stays set once
4376 // the new code is resident. Same shape as
4377 // `validate_accepts_multiple_state_changes_after_one_load` on
4378 // the peer ordering gate.
4379 let e = entry(
4380 "0.1.0",
4381 vec![
4382 UpgradeInstruction::LoadModule { module: "x".into() },
4383 UpgradeInstruction::SoftPurge {
4384 module: "x-old".into(),
4385 },
4386 UpgradeInstruction::Purge {
4387 module: "x-oldest".into(),
4388 },
4389 ],
4390 );
4391 e.validate().unwrap();
4392 }
4393
4394 #[test]
4395 fn validate_purge_ordering_fires_after_state_change_ordering() {
4396 // Diagnostic-precedence pin: an entry like `((:state-change …)
4397 // (:soft-purge …))` is *both* state-change-without-load and
4398 // purge-without-load. The state-change gate must win — it's
4399 // the load-bearing semantic on this ordering contract, and
4400 // surfacing the purge diagnostic first would mask the more-
4401 // fundamental migration-against-stale-code defect. Guards the
4402 // call order in `validate` against silent reordering.
4403 let e = entry(
4404 "0.1.0",
4405 vec![
4406 UpgradeInstruction::StateChange {
4407 script: PathBuf::from("lib/m.lisp"),
4408 },
4409 UpgradeInstruction::SoftPurge {
4410 module: "x-old".into(),
4411 },
4412 ],
4413 );
4414 let err = e.validate().unwrap_err();
4415 assert!(
4416 matches!(err, UpgradeError::StateChangeWithoutPriorLoad { .. }),
4417 "state-change-without-load must surface before purge-without-load, got {err:?}"
4418 );
4419 }
4420
4421 #[test]
4422 fn validate_purge_ordering_fires_after_per_instr_shape() {
4423 // Order pin: a malformed `:module` value on a `:soft-purge` (an
4424 // empty string) surfaces its narrower kind-tagged `ModuleEmpty`
4425 // diagnostic *before* the within-entry purge-ordering gate fires.
4426 // The per-instruction shape pass walks the list inline before
4427 // the ordering checks, so the narrower self-locating diagnostic
4428 // surfaces first — mirrors the empty-first cascade on every peer
4429 // DNS-1123 gate and the `validate_restart_exclusive_fires_after_
4430 // per_instr_shape` pin on the sibling ordering gate.
4431 let e = entry(
4432 "0.1.0",
4433 vec![UpgradeInstruction::SoftPurge {
4434 module: String::new(),
4435 }],
4436 );
4437 let err = e.validate().unwrap_err();
4438 assert_eq!(
4439 err,
4440 UpgradeError::ModuleEmpty {
4441 kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE
4442 },
4443 "malformed instruction must surface its kind-tagged diagnostic before the \
4444 purge-ordering gate fires, got {err:?}"
4445 );
4446 }
4447
4448 #[test]
4449 fn validate_purge_ordering_threads_through_validate_upgrade_from() {
4450 // The whole-list entry-point surfaces the per-entry ordering
4451 // error (mirrors
4452 // `validate_state_change_ordering_threads_through_validate_upgrade_from`):
4453 // the gate is reachable from the LayoutInvariants call site, not
4454 // only from a direct `entry.validate()`.
4455 let entries = vec![entry(
4456 "0.1.0",
4457 vec![UpgradeInstruction::Purge {
4458 module: "x-old".into(),
4459 }],
4460 )];
4461 let err = validate_upgrade_from(&entries).unwrap_err();
4462 assert!(
4463 matches!(
4464 err,
4465 UpgradeError::PurgeWithoutPriorLoad {
4466 kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
4467 ..
4468 }
4469 ),
4470 "validate_upgrade_from must thread the purge-ordering error, got {err:?}"
4471 );
4472 }
4473
4474 #[test]
4475 fn validate_state_change_ordering_threads_through_validate_upgrade_from() {
4476 // The whole-list entry-point surfaces the per-entry ordering
4477 // error (mirrors `validate_restart_exclusive_threads_through_…`):
4478 // the gate is reachable from the LayoutInvariants call site, not
4479 // only from a direct `entry.validate()`.
4480 let entries = vec![entry(
4481 "0.1.0",
4482 vec![UpgradeInstruction::StateChange {
4483 script: PathBuf::from("lib/m.lisp"),
4484 }],
4485 )];
4486 let err = validate_upgrade_from(&entries).unwrap_err();
4487 assert!(
4488 matches!(err, UpgradeError::StateChangeWithoutPriorLoad { .. }),
4489 "validate_upgrade_from must thread the ordering error, got {err:?}"
4490 );
4491 }
4492
4493 // ── within-entry cleanup-singularity invariant ─────────────────────
4494
4495 #[test]
4496 fn validate_rejects_duplicate_soft_purge_for_same_module() {
4497 // Fail-before-pass-after pin: `:soft-purge` drains-then-GCs
4498 // its target module (code:soft_purge/1 analog); after the
4499 // first the module is gone, so a second `:soft-purge` of the
4500 // same module is at best a no-op and at worst undefined
4501 // (depending on the operator's handling of a non-resident-
4502 // module purge). Author one cleanup per module.
4503 let e = entry(
4504 "0.1.0",
4505 vec![
4506 UpgradeInstruction::LoadModule { module: "x".into() },
4507 UpgradeInstruction::SoftPurge {
4508 module: "x-old".into(),
4509 },
4510 UpgradeInstruction::SoftPurge {
4511 module: "x-old".into(),
4512 },
4513 ],
4514 );
4515 let err = e.validate().unwrap_err();
4516 assert_eq!(
4517 err,
4518 UpgradeError::DuplicateCleanup {
4519 from: "0.1.0".into(),
4520 module: "x-old".into(),
4521 kinds: vec![
4522 crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
4523 crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
4524 ],
4525 },
4526 "two `:soft-purge` of the same module must surface as DuplicateCleanup naming the \
4527 module + both kinds in declaration order, got {err:?}"
4528 );
4529 }
4530
4531 #[test]
4532 fn validate_rejects_duplicate_purge_for_same_module() {
4533 // Per-arm coverage: `:purge` (immediate discard, no drain) is
4534 // the more catastrophic peer of `:soft-purge`; same gate, same
4535 // shape, kind-tag distinguishes so the author can grep their
4536 // caixa.lisp for the offending `(:purge …)` form.
4537 let e = entry(
4538 "0.1.0",
4539 vec![
4540 UpgradeInstruction::LoadModule { module: "x".into() },
4541 UpgradeInstruction::Purge {
4542 module: "x-old".into(),
4543 },
4544 UpgradeInstruction::Purge {
4545 module: "x-old".into(),
4546 },
4547 ],
4548 );
4549 let err = e.validate().unwrap_err();
4550 assert_eq!(
4551 err,
4552 UpgradeError::DuplicateCleanup {
4553 from: "0.1.0".into(),
4554 module: "x-old".into(),
4555 kinds: vec![
4556 crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
4557 crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
4558 ],
4559 },
4560 );
4561 }
4562
4563 #[test]
4564 fn validate_rejects_soft_purge_then_purge_for_same_module() {
4565 // Soft-then-hard footgun: the author wrote "drain, and if
4566 // drain doesn't clean up, force-discard", but the operator
4567 // runs declared instructions unconditionally — the `:purge`
4568 // fires whether the `:soft-purge` already discarded the
4569 // module or not, so the imagined fallback semantic is
4570 // missing. Fallback on cleanup failure is the operator's
4571 // job, not authored into the entry. Both kinds carry in
4572 // declaration order so the author can grep for either side
4573 // and pick one.
4574 let e = entry(
4575 "0.1.0",
4576 vec![
4577 UpgradeInstruction::LoadModule { module: "x".into() },
4578 UpgradeInstruction::SoftPurge {
4579 module: "x-old".into(),
4580 },
4581 UpgradeInstruction::Purge {
4582 module: "x-old".into(),
4583 },
4584 ],
4585 );
4586 let err = e.validate().unwrap_err();
4587 assert_eq!(
4588 err,
4589 UpgradeError::DuplicateCleanup {
4590 from: "0.1.0".into(),
4591 module: "x-old".into(),
4592 kinds: vec![
4593 crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
4594 crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
4595 ],
4596 },
4597 );
4598 }
4599
4600 #[test]
4601 fn validate_rejects_purge_then_soft_purge_for_same_module() {
4602 // Reversed-ordering arm: `:purge` discards immediately; the
4603 // trailing `:soft-purge` has no module to drain. The kinds
4604 // list reflects declaration order so the diagnostic locates
4605 // both forms in the source.
4606 let e = entry(
4607 "0.1.0",
4608 vec![
4609 UpgradeInstruction::LoadModule { module: "x".into() },
4610 UpgradeInstruction::Purge {
4611 module: "x-old".into(),
4612 },
4613 UpgradeInstruction::SoftPurge {
4614 module: "x-old".into(),
4615 },
4616 ],
4617 );
4618 let err = e.validate().unwrap_err();
4619 assert_eq!(
4620 err,
4621 UpgradeError::DuplicateCleanup {
4622 from: "0.1.0".into(),
4623 module: "x-old".into(),
4624 kinds: vec![
4625 crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
4626 crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
4627 ],
4628 },
4629 );
4630 }
4631
4632 #[test]
4633 fn validate_accepts_distinct_cleanup_modules() {
4634 // Positive control: `:soft-purge` and `:purge` on *different*
4635 // modules pass the gate. Mirrors
4636 // `validate_accepts_multiple_purges_after_one_load` — the
4637 // cleanup-singularity gate is keyed on (module), not on
4638 // (kind, module) pair, so distinct old-version names render
4639 // distinct cleanup targets and don't collide. Sweep both
4640 // same-class (two `:soft-purge` distinct modules) and cross-
4641 // class (`:soft-purge` then `:purge` distinct modules) so a
4642 // future tighten to a kind-only key (which would over-fire on
4643 // distinct modules) surfaces here.
4644 let two_soft = entry(
4645 "0.1.0",
4646 vec![
4647 UpgradeInstruction::LoadModule { module: "x".into() },
4648 UpgradeInstruction::SoftPurge {
4649 module: "x-old".into(),
4650 },
4651 UpgradeInstruction::SoftPurge {
4652 module: "x-older".into(),
4653 },
4654 ],
4655 );
4656 two_soft.validate().unwrap();
4657 let mixed = entry(
4658 "0.1.0",
4659 vec![
4660 UpgradeInstruction::LoadModule { module: "x".into() },
4661 UpgradeInstruction::SoftPurge {
4662 module: "x-old".into(),
4663 },
4664 UpgradeInstruction::Purge {
4665 module: "x-oldest".into(),
4666 },
4667 ],
4668 );
4669 mixed.validate().unwrap();
4670 }
4671
4672 #[test]
4673 fn validate_accepts_single_cleanup_per_module() {
4674 // Boundary control: a list with exactly one `:soft-purge` and
4675 // one `:purge` (distinct modules, the canonical "drain one,
4676 // hard-discard the other" shape) is the gate's identity
4677 // element. Pin so a future off-by-one in the duplicate-detection
4678 // scan doesn't accidentally flag a single occurrence as
4679 // duplicating itself — mirrors
4680 // `validate_upgrade_from_single_entry_never_duplicates` on
4681 // the peer cross-entry duplicate axis.
4682 let e = entry(
4683 "0.1.0",
4684 vec![
4685 UpgradeInstruction::LoadModule { module: "x".into() },
4686 UpgradeInstruction::SoftPurge {
4687 module: "x-old".into(),
4688 },
4689 UpgradeInstruction::Purge {
4690 module: "y-old".into(),
4691 },
4692 ],
4693 );
4694 e.validate().unwrap();
4695 }
4696
4697 #[test]
4698 fn validate_cleanup_singularity_fires_after_purge_ordering() {
4699 // Diagnostic-precedence pin: an entry like `((:soft-purge "x")
4700 // (:soft-purge "x"))` is *both* purge-without-load and
4701 // duplicate-cleanup. The more-fundamental ordering gate must
4702 // win — the missing-load defect is load-bearing (the canonical
4703 // OTP shape requires the new code be resident before any
4704 // cleanup runs), and surfacing the duplicate diagnostic first
4705 // would mask the no-replacement-window defect the ordering
4706 // gate exists to close. Guards the call order in `validate`
4707 // against silent reordering. Same posture as
4708 // `validate_purge_ordering_fires_after_state_change_ordering`
4709 // on the sibling ordering gate.
4710 let e = entry(
4711 "0.1.0",
4712 vec![
4713 UpgradeInstruction::SoftPurge {
4714 module: "x-old".into(),
4715 },
4716 UpgradeInstruction::SoftPurge {
4717 module: "x-old".into(),
4718 },
4719 ],
4720 );
4721 let err = e.validate().unwrap_err();
4722 assert!(
4723 matches!(
4724 err,
4725 UpgradeError::PurgeWithoutPriorLoad {
4726 kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
4727 ..
4728 }
4729 ),
4730 "purge-without-load must surface before duplicate-cleanup, got {err:?}"
4731 );
4732 }
4733
4734 #[test]
4735 fn validate_cleanup_singularity_fires_after_per_instr_shape() {
4736 // Order pin: a malformed `:module` value on a `:soft-purge`
4737 // (an empty string) surfaces its narrower kind-tagged
4738 // `ModuleEmpty` diagnostic *before* the within-entry cleanup-
4739 // singularity gate fires. The per-instruction shape pass walks
4740 // the list inline before the singularity check, so the
4741 // narrower self-locating diagnostic surfaces first — mirrors
4742 // the empty-first cascade on every peer DNS-1123 gate and the
4743 // `validate_purge_ordering_fires_after_per_instr_shape` pin on
4744 // the sibling ordering gate.
4745 //
4746 // Two empty-string `:soft-purge` would *otherwise* duplicate
4747 // (both modules are the same empty string), so this pin
4748 // double-locks the precedence: the per-instr shape gate must
4749 // win on the first malformed instruction before the duplicate
4750 // scan even reaches the second.
4751 let e = entry(
4752 "0.1.0",
4753 vec![
4754 UpgradeInstruction::LoadModule { module: "x".into() },
4755 UpgradeInstruction::SoftPurge {
4756 module: String::new(),
4757 },
4758 UpgradeInstruction::SoftPurge {
4759 module: String::new(),
4760 },
4761 ],
4762 );
4763 let err = e.validate().unwrap_err();
4764 assert_eq!(
4765 err,
4766 UpgradeError::ModuleEmpty {
4767 kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE
4768 },
4769 "malformed instruction must surface its kind-tagged diagnostic before the \
4770 cleanup-singularity gate fires, got {err:?}"
4771 );
4772 }
4773
4774 #[test]
4775 fn validate_cleanup_singularity_reports_first_collision() {
4776 // Determinism pin: with three cleanups of the same module the
4777 // gate reports the *first* collision (the second occurrence)
4778 // and stops — the third's duplicate is masked by the first
4779 // surfaced one. Mirrors
4780 // `validate_upgrade_from_duplicate_diagnostic_names_second_collision`
4781 // on the peer cross-entry duplicate axis.
4782 let e = entry(
4783 "0.1.0",
4784 vec![
4785 UpgradeInstruction::LoadModule { module: "x".into() },
4786 UpgradeInstruction::SoftPurge {
4787 module: "x-old".into(),
4788 },
4789 UpgradeInstruction::SoftPurge {
4790 module: "x-old".into(),
4791 },
4792 UpgradeInstruction::Purge {
4793 module: "x-old".into(),
4794 },
4795 ],
4796 );
4797 let err = e.validate().unwrap_err();
4798 assert_eq!(
4799 err,
4800 UpgradeError::DuplicateCleanup {
4801 from: "0.1.0".into(),
4802 module: "x-old".into(),
4803 kinds: vec![
4804 crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
4805 crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
4806 ],
4807 },
4808 "the first colliding pair must surface, not the later `:purge` collision"
4809 );
4810 }
4811
4812 #[test]
4813 fn validate_cleanup_singularity_threads_through_validate_upgrade_from() {
4814 // The whole-list entry-point surfaces the per-entry singularity
4815 // error (mirrors
4816 // `validate_purge_ordering_threads_through_validate_upgrade_from`):
4817 // the gate is reachable from the LayoutInvariants call site,
4818 // not only from a direct `entry.validate()`.
4819 let entries = vec![entry(
4820 "0.1.0",
4821 vec![
4822 UpgradeInstruction::LoadModule { module: "x".into() },
4823 UpgradeInstruction::SoftPurge {
4824 module: "x-old".into(),
4825 },
4826 UpgradeInstruction::Purge {
4827 module: "x-old".into(),
4828 },
4829 ],
4830 )];
4831 let err = validate_upgrade_from(&entries).unwrap_err();
4832 assert!(
4833 matches!(err, UpgradeError::DuplicateCleanup { .. }),
4834 "validate_upgrade_from must thread the cleanup-singularity error, got {err:?}"
4835 );
4836 }
4837
4838 #[test]
4839 fn validate_rejects_duplicate_load_module_for_same_module() {
4840 // `LoadModule` is the `code:load_module/1` analog (INSPIRATIONS
4841 // §II.4): each module is loaded exactly once per upgrade entry,
4842 // the operator's dispatch table reads the module name to bind
4843 // the wasm component, and a second `(:load-module "x")` re-reads
4844 // the same module name and re-binds the same component — a
4845 // no-op the second time. systools-generated `.relup` files emit
4846 // at most one `load_module` per module per upgrade step for
4847 // this reason. Author one `(:load-module "x")` per old module.
4848 let e = entry(
4849 "0.1.0",
4850 vec![
4851 UpgradeInstruction::LoadModule { module: "x".into() },
4852 UpgradeInstruction::LoadModule { module: "x".into() },
4853 ],
4854 );
4855 let err = e.validate().unwrap_err();
4856 assert_eq!(
4857 err,
4858 UpgradeError::DuplicateLoadModule {
4859 from: "0.1.0".into(),
4860 module: "x".into(),
4861 },
4862 "two `:load-module` of the same module must surface as DuplicateLoadModule naming \
4863 the module, got {err:?}"
4864 );
4865 }
4866
4867 #[test]
4868 fn validate_accepts_distinct_load_modules() {
4869 // Positive control: `:load-module` instructions on *different*
4870 // modules pass the gate. Mirrors
4871 // `validate_accepts_distinct_cleanup_modules` on the sibling
4872 // singularity axis — the load-singularity gate is keyed on
4873 // (module), so distinct module names render distinct load
4874 // targets and don't collide. Sweep both the bare two-load shape
4875 // and the canonical load-pair-with-cleanup shape so a future
4876 // tighten that over-fires on distinct loads surfaces here.
4877 let two_loads = entry(
4878 "0.1.0",
4879 vec![
4880 UpgradeInstruction::LoadModule { module: "x".into() },
4881 UpgradeInstruction::LoadModule { module: "y".into() },
4882 ],
4883 );
4884 two_loads.validate().unwrap();
4885 let with_cleanup = entry(
4886 "0.1.0",
4887 vec![
4888 UpgradeInstruction::LoadModule { module: "x".into() },
4889 UpgradeInstruction::LoadModule { module: "y".into() },
4890 UpgradeInstruction::SoftPurge {
4891 module: "x-old".into(),
4892 },
4893 UpgradeInstruction::SoftPurge {
4894 module: "y-old".into(),
4895 },
4896 ],
4897 );
4898 with_cleanup.validate().unwrap();
4899 }
4900
4901 #[test]
4902 fn validate_accepts_single_load_per_module() {
4903 // Boundary control: a list with exactly one `:load-module`
4904 // followed by the canonical `:state-change` + `:soft-purge`
4905 // sequence (the module-doc OTP shape) is the gate's identity
4906 // element. Pin so a future off-by-one in the duplicate-
4907 // detection scan doesn't accidentally flag a single occurrence
4908 // as duplicating itself — mirrors
4909 // `validate_accepts_single_cleanup_per_module` on the sibling
4910 // singularity axis.
4911 let e = entry(
4912 "0.1.0",
4913 vec![
4914 UpgradeInstruction::LoadModule { module: "x".into() },
4915 UpgradeInstruction::StateChange {
4916 script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
4917 },
4918 UpgradeInstruction::SoftPurge {
4919 module: "x-old".into(),
4920 },
4921 ],
4922 );
4923 e.validate().unwrap();
4924 }
4925
4926 #[test]
4927 fn validate_load_singularity_fires_after_state_change_ordering() {
4928 // Diagnostic-precedence pin: an entry like `((:state-change
4929 // "m.lisp") (:load-module "x") (:load-module "x"))` is *both*
4930 // state-change-without-load and duplicate-load. The more-
4931 // fundamental ordering gate must win — the missing-load defect
4932 // is load-bearing (the migration runs against unloaded code),
4933 // and surfacing the duplicate diagnostic first would mask the
4934 // migrate-into-unloaded-code defect the ordering gate exists
4935 // to close. Guards the call order in `validate` against silent
4936 // reordering. Same posture as
4937 // `validate_cleanup_singularity_fires_after_purge_ordering`
4938 // on the sibling singularity gate.
4939 let e = entry(
4940 "0.1.0",
4941 vec![
4942 UpgradeInstruction::StateChange {
4943 script: PathBuf::from("lib/m.lisp"),
4944 },
4945 UpgradeInstruction::LoadModule { module: "x".into() },
4946 UpgradeInstruction::LoadModule { module: "x".into() },
4947 ],
4948 );
4949 let err = e.validate().unwrap_err();
4950 assert!(
4951 matches!(err, UpgradeError::StateChangeWithoutPriorLoad { .. }),
4952 "state-change-without-load must surface before duplicate-load, got {err:?}"
4953 );
4954 }
4955
4956 #[test]
4957 fn validate_load_singularity_fires_after_purge_ordering() {
4958 // Diagnostic-precedence pin: an entry like `((:soft-purge
4959 // "x-old") (:load-module "x") (:load-module "x"))` is *both*
4960 // purge-without-load and duplicate-load. The more-fundamental
4961 // ordering gate must win — the missing-load defect is load-
4962 // bearing (the cleanup runs against no-replacement-window),
4963 // and surfacing the duplicate diagnostic first would mask the
4964 // drain-to-nothing defect the ordering gate exists to close.
4965 // Sibling of
4966 // `validate_cleanup_singularity_fires_after_purge_ordering` on
4967 // the load-singularity axis.
4968 let e = entry(
4969 "0.1.0",
4970 vec![
4971 UpgradeInstruction::SoftPurge {
4972 module: "x-old".into(),
4973 },
4974 UpgradeInstruction::LoadModule { module: "x".into() },
4975 UpgradeInstruction::LoadModule { module: "x".into() },
4976 ],
4977 );
4978 let err = e.validate().unwrap_err();
4979 assert!(
4980 matches!(
4981 err,
4982 UpgradeError::PurgeWithoutPriorLoad {
4983 kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
4984 ..
4985 }
4986 ),
4987 "purge-without-load must surface before duplicate-load, got {err:?}"
4988 );
4989 }
4990
4991 #[test]
4992 fn validate_load_singularity_fires_after_per_instr_shape() {
4993 // Order pin: a malformed `:module` value on a `:load-module`
4994 // (an empty string) surfaces its narrower kind-tagged
4995 // `ModuleEmpty` diagnostic *before* the within-entry load-
4996 // singularity gate fires. The per-instruction shape pass walks
4997 // the list inline before the singularity check, so the
4998 // narrower self-locating diagnostic surfaces first — mirrors
4999 // the empty-first cascade on every peer DNS-1123 gate and the
5000 // `validate_cleanup_singularity_fires_after_per_instr_shape`
5001 // pin on the sibling singularity gate.
5002 //
5003 // Two empty-string `:load-module` would *otherwise* duplicate
5004 // (both modules are the same empty string), so this pin
5005 // double-locks the precedence: the per-instr shape gate must
5006 // win on the first malformed instruction before the duplicate
5007 // scan even reaches the second.
5008 let e = entry(
5009 "0.1.0",
5010 vec![
5011 UpgradeInstruction::LoadModule {
5012 module: String::new(),
5013 },
5014 UpgradeInstruction::LoadModule {
5015 module: String::new(),
5016 },
5017 ],
5018 );
5019 let err = e.validate().unwrap_err();
5020 assert_eq!(
5021 err,
5022 UpgradeError::ModuleEmpty {
5023 kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE,
5024 },
5025 "malformed instruction must surface its kind-tagged diagnostic before the \
5026 load-singularity gate fires, got {err:?}"
5027 );
5028 }
5029
5030 #[test]
5031 fn validate_load_singularity_fires_before_cleanup_singularity() {
5032 // Diagnostic-precedence pin: an entry that violates *both*
5033 // singularities — duplicate load on "x" *and* duplicate cleanup
5034 // on "y-old" — must surface the load-side diagnostic first.
5035 // The load axis precedes the cleanup axis in the canonical OTP
5036 // sequence (`code:load_module/1` then `code:soft_purge/1`) and
5037 // in [`UpgradeInstruction`] declaration order (LoadModule
5038 // before SoftPurge/Purge), so the load-side singularity is the
5039 // load-bearing diagnostic when both fire — the cleanup-side
5040 // duplicate is meaningless either way without a coherent load.
5041 // Guards the call order in `validate`: `validate_load_singularity`
5042 // runs before `validate_cleanup_singularity`.
5043 let e = entry(
5044 "0.1.0",
5045 vec![
5046 UpgradeInstruction::LoadModule { module: "x".into() },
5047 UpgradeInstruction::LoadModule { module: "x".into() },
5048 UpgradeInstruction::SoftPurge {
5049 module: "y-old".into(),
5050 },
5051 UpgradeInstruction::SoftPurge {
5052 module: "y-old".into(),
5053 },
5054 ],
5055 );
5056 let err = e.validate().unwrap_err();
5057 assert_eq!(
5058 err,
5059 UpgradeError::DuplicateLoadModule {
5060 from: "0.1.0".into(),
5061 module: "x".into(),
5062 },
5063 "duplicate-load must surface before duplicate-cleanup, got {err:?}"
5064 );
5065 }
5066
5067 #[test]
5068 fn validate_load_singularity_reports_first_collision() {
5069 // Determinism pin: with three loads of the same module the gate
5070 // reports the *first* collision (the second occurrence) and
5071 // stops — the third's duplicate is masked by the first surfaced
5072 // one. Mirrors
5073 // `validate_cleanup_singularity_reports_first_collision` on the
5074 // sibling singularity axis and every peer duplicate gate's
5075 // first-collision discipline.
5076 let e = entry(
5077 "0.1.0",
5078 vec![
5079 UpgradeInstruction::LoadModule { module: "x".into() },
5080 UpgradeInstruction::LoadModule { module: "x".into() },
5081 UpgradeInstruction::LoadModule { module: "x".into() },
5082 ],
5083 );
5084 let err = e.validate().unwrap_err();
5085 assert_eq!(
5086 err,
5087 UpgradeError::DuplicateLoadModule {
5088 from: "0.1.0".into(),
5089 module: "x".into(),
5090 },
5091 "the first colliding occurrence must surface, not the later third-load collision"
5092 );
5093 }
5094
5095 #[test]
5096 fn validate_load_singularity_threads_through_validate_upgrade_from() {
5097 // The whole-list entry-point surfaces the per-entry singularity
5098 // error (mirrors
5099 // `validate_cleanup_singularity_threads_through_validate_upgrade_from`):
5100 // the gate is reachable from the LayoutInvariants call site,
5101 // not only from a direct `entry.validate()`.
5102 let entries = vec![entry(
5103 "0.1.0",
5104 vec![
5105 UpgradeInstruction::LoadModule { module: "x".into() },
5106 UpgradeInstruction::LoadModule { module: "x".into() },
5107 ],
5108 )];
5109 let err = validate_upgrade_from(&entries).unwrap_err();
5110 assert!(
5111 matches!(err, UpgradeError::DuplicateLoadModule { .. }),
5112 "validate_upgrade_from must thread the load-singularity error, got {err:?}"
5113 );
5114 }
5115
5116 // ── within-entry state-change-singularity invariant ────────────────
5117
5118 #[test]
5119 fn validate_rejects_duplicate_state_change_for_same_script() {
5120 // `StateChange` is the `gen_server:code_change/3` analog
5121 // (INSPIRATIONS §II.4): the script folds the prior-version
5122 // state shape into the current-version shape — a one-shot
5123 // transition, not a step that composes with itself. OTP's
5124 // release_handler invokes `code_change/3` exactly once per
5125 // upgrade per gen_server; systools-generated `.relup` files
5126 // emit at most one `code_change` per gen_server per upgrade
5127 // step for this reason. A second `(:state-change "m.lisp")`
5128 // re-runs the same fold on the already-migrated state — at
5129 // best a no-op and at worst silent state corruption from
5130 // double-applied non-idempotent transforms (`add column`,
5131 // `increment counter`, `rename field`). Author one
5132 // `(:state-change "m.lisp")` per migration script per entry.
5133 let e = entry(
5134 "0.1.0",
5135 vec![
5136 UpgradeInstruction::LoadModule { module: "x".into() },
5137 UpgradeInstruction::StateChange {
5138 script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
5139 },
5140 UpgradeInstruction::StateChange {
5141 script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
5142 },
5143 ],
5144 );
5145 let err = e.validate().unwrap_err();
5146 assert_eq!(
5147 err,
5148 UpgradeError::DuplicateStateChange {
5149 from: "0.1.0".into(),
5150 script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
5151 },
5152 "two `:state-change` of the same script must surface as DuplicateStateChange naming \
5153 the script, got {err:?}"
5154 );
5155 }
5156
5157 #[test]
5158 fn validate_accepts_distinct_state_change_scripts() {
5159 // Positive control: `:state-change` instructions on *different*
5160 // scripts pass the gate. Mirrors
5161 // `validate_accepts_distinct_cleanup_modules` /
5162 // `validate_accepts_distinct_load_modules` on the sibling
5163 // singularity axes — the state-change-singularity gate is keyed
5164 // on the script PathBuf, so distinct scripts render distinct
5165 // migration targets and don't collide. Sweep both the bare two-
5166 // migration shape and the canonical load-pair-with-cleanup shape
5167 // so a future tighten that over-fires on distinct scripts
5168 // surfaces here. This positive control is the gate-level peer of
5169 // `validate_accepts_multiple_state_changes_after_one_load` (the
5170 // ordering-gate positive control on distinct scripts), pinned
5171 // here independently so a future refactor that decouples the
5172 // gates can't accidentally drop coverage on either.
5173 let two_migrations = entry(
5174 "0.1.0",
5175 vec![
5176 UpgradeInstruction::LoadModule { module: "x".into() },
5177 UpgradeInstruction::StateChange {
5178 script: PathBuf::from("lib/m1.lisp"),
5179 },
5180 UpgradeInstruction::StateChange {
5181 script: PathBuf::from("lib/m2.lisp"),
5182 },
5183 ],
5184 );
5185 two_migrations.validate().unwrap();
5186 let with_cleanup = entry(
5187 "0.1.0",
5188 vec![
5189 UpgradeInstruction::LoadModule { module: "x".into() },
5190 UpgradeInstruction::StateChange {
5191 script: PathBuf::from("lib/m1.lisp"),
5192 },
5193 UpgradeInstruction::StateChange {
5194 script: PathBuf::from("lib/m2.lisp"),
5195 },
5196 UpgradeInstruction::SoftPurge {
5197 module: "x-old".into(),
5198 },
5199 ],
5200 );
5201 with_cleanup.validate().unwrap();
5202 }
5203
5204 #[test]
5205 fn validate_accepts_single_state_change_per_script() {
5206 // Boundary control: a list with exactly one `:state-change`
5207 // wrapped by the canonical `:load-module` + `:soft-purge`
5208 // sequence (the module-doc OTP shape) is the gate's identity
5209 // element. Pin so a future off-by-one in the duplicate-
5210 // detection scan doesn't accidentally flag a single occurrence
5211 // as duplicating itself — mirrors
5212 // `validate_accepts_single_load_per_module` /
5213 // `validate_accepts_single_cleanup_per_module` on the sibling
5214 // singularity axes.
5215 let e = entry(
5216 "0.1.0",
5217 vec![
5218 UpgradeInstruction::LoadModule { module: "x".into() },
5219 UpgradeInstruction::StateChange {
5220 script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
5221 },
5222 UpgradeInstruction::SoftPurge {
5223 module: "x-old".into(),
5224 },
5225 ],
5226 );
5227 e.validate().unwrap();
5228 }
5229
5230 #[test]
5231 fn validate_state_change_singularity_fires_after_state_change_ordering() {
5232 // Diagnostic-precedence pin: an entry like `((:state-change
5233 // "m.lisp") (:state-change "m.lisp"))` is *both* state-change-
5234 // without-load and duplicate-state-change. The more-fundamental
5235 // ordering gate must win — the missing-load defect is load-
5236 // bearing (the migration runs against unloaded code), and
5237 // surfacing the duplicate diagnostic first would mask the
5238 // migrate-into-unloaded-code defect the ordering gate exists to
5239 // close. Guards the call order in `validate` against silent
5240 // reordering. Same posture as
5241 // `validate_load_singularity_fires_after_state_change_ordering`
5242 // on the sibling singularity gate.
5243 //
5244 // Two same-script `:state-change` would *otherwise* duplicate
5245 // (both scripts collide on the very first `:state-change`-
5246 // without-load encountered), so this pin double-locks the
5247 // precedence: the ordering gate must win on the first un-loaded
5248 // `:state-change` before the singularity scan even reaches the
5249 // second.
5250 let e = entry(
5251 "0.1.0",
5252 vec![
5253 UpgradeInstruction::StateChange {
5254 script: PathBuf::from("lib/m.lisp"),
5255 },
5256 UpgradeInstruction::StateChange {
5257 script: PathBuf::from("lib/m.lisp"),
5258 },
5259 ],
5260 );
5261 let err = e.validate().unwrap_err();
5262 assert!(
5263 matches!(err, UpgradeError::StateChangeWithoutPriorLoad { .. }),
5264 "state-change-without-load must surface before duplicate-state-change, got {err:?}"
5265 );
5266 }
5267
5268 #[test]
5269 fn validate_state_change_singularity_fires_after_purge_ordering() {
5270 // Diagnostic-precedence pin: an entry like `((:soft-purge
5271 // "x-old") (:load-module "x") (:state-change "m.lisp")
5272 // (:state-change "m.lisp"))` is *both* purge-without-load and
5273 // duplicate-state-change. The more-fundamental ordering gate
5274 // must win — the missing-load defect (a cleanup that drains the
5275 // only resident version to nothing) is load-bearing, and
5276 // surfacing the duplicate diagnostic first would mask the
5277 // drain-to-nothing defect the ordering gate exists to close.
5278 // Sibling of `validate_load_singularity_fires_after_purge_ordering`
5279 // on the state-change-singularity axis.
5280 let e = entry(
5281 "0.1.0",
5282 vec![
5283 UpgradeInstruction::SoftPurge {
5284 module: "x-old".into(),
5285 },
5286 UpgradeInstruction::LoadModule { module: "x".into() },
5287 UpgradeInstruction::StateChange {
5288 script: PathBuf::from("lib/m.lisp"),
5289 },
5290 UpgradeInstruction::StateChange {
5291 script: PathBuf::from("lib/m.lisp"),
5292 },
5293 ],
5294 );
5295 let err = e.validate().unwrap_err();
5296 assert!(
5297 matches!(
5298 err,
5299 UpgradeError::PurgeWithoutPriorLoad {
5300 kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
5301 ..
5302 }
5303 ),
5304 "purge-without-load must surface before duplicate-state-change, got {err:?}"
5305 );
5306 }
5307
5308 #[test]
5309 fn validate_state_change_singularity_fires_after_per_instr_shape() {
5310 // Order pin: a malformed `:script` value on a `:state-change`
5311 // (an empty path) surfaces its narrower `EmptyScript` diagnostic
5312 // *before* the within-entry state-change-singularity gate fires.
5313 // The per-instruction shape pass walks the list inline before
5314 // the singularity check, so the narrower self-locating
5315 // diagnostic surfaces first — mirrors the empty-first cascade on
5316 // every peer path-shape gate and the
5317 // `validate_load_singularity_fires_after_per_instr_shape` /
5318 // `validate_cleanup_singularity_fires_after_per_instr_shape`
5319 // pins on the sibling singularity gates.
5320 //
5321 // Two empty-path `:state-change` would *otherwise* duplicate
5322 // (both scripts are the same empty PathBuf), so this pin double-
5323 // locks the precedence: the per-instr shape gate must win on the
5324 // first malformed instruction before the duplicate scan even
5325 // reaches the second.
5326 let e = entry(
5327 "0.1.0",
5328 vec![
5329 UpgradeInstruction::LoadModule { module: "x".into() },
5330 UpgradeInstruction::StateChange {
5331 script: PathBuf::new(),
5332 },
5333 UpgradeInstruction::StateChange {
5334 script: PathBuf::new(),
5335 },
5336 ],
5337 );
5338 let err = e.validate().unwrap_err();
5339 assert_eq!(
5340 err,
5341 UpgradeError::EmptyScript,
5342 "malformed instruction must surface its narrower diagnostic before the \
5343 state-change-singularity gate fires, got {err:?}"
5344 );
5345 }
5346
5347 #[test]
5348 fn validate_state_change_singularity_fires_after_load_singularity() {
5349 // Diagnostic-precedence pin: an entry that violates *both*
5350 // singularities — duplicate load on "x" *and* duplicate
5351 // state-change on "m.lisp" — must surface the load-side
5352 // diagnostic first. The load axis precedes the migration axis
5353 // in the canonical OTP sequence (`code:load_module/1` then
5354 // `gen_server:code_change/3`) and in [`UpgradeInstruction`]
5355 // declaration order (LoadModule before StateChange), so the
5356 // load-side singularity is the load-bearing diagnostic when
5357 // both fire — the migration-side duplicate is meaningless
5358 // either way without a coherent load. Guards the call order in
5359 // `validate`: `validate_load_singularity` runs before
5360 // `validate_state_change_singularity`.
5361 let e = entry(
5362 "0.1.0",
5363 vec![
5364 UpgradeInstruction::LoadModule { module: "x".into() },
5365 UpgradeInstruction::LoadModule { module: "x".into() },
5366 UpgradeInstruction::StateChange {
5367 script: PathBuf::from("lib/m.lisp"),
5368 },
5369 UpgradeInstruction::StateChange {
5370 script: PathBuf::from("lib/m.lisp"),
5371 },
5372 ],
5373 );
5374 let err = e.validate().unwrap_err();
5375 assert_eq!(
5376 err,
5377 UpgradeError::DuplicateLoadModule {
5378 from: "0.1.0".into(),
5379 module: "x".into(),
5380 },
5381 "duplicate-load must surface before duplicate-state-change, got {err:?}"
5382 );
5383 }
5384
5385 #[test]
5386 fn validate_state_change_singularity_fires_before_cleanup_singularity() {
5387 // Diagnostic-precedence pin: an entry that violates *both*
5388 // singularities — duplicate state-change on "m.lisp" *and*
5389 // duplicate cleanup on "y-old" — must surface the migration-
5390 // side diagnostic first. The migration axis precedes the
5391 // cleanup axis in the canonical OTP sequence
5392 // (`gen_server:code_change/3` then `code:soft_purge/1`) and in
5393 // [`UpgradeInstruction`] declaration order (StateChange before
5394 // SoftPurge/Purge), so the migration-side singularity is the
5395 // load-bearing diagnostic when both fire — the cleanup-side
5396 // duplicate is irrelevant once the migration has corrupted
5397 // state by double-applying. Guards the call order in
5398 // `validate`: `validate_state_change_singularity` runs before
5399 // `validate_cleanup_singularity`.
5400 let e = entry(
5401 "0.1.0",
5402 vec![
5403 UpgradeInstruction::LoadModule { module: "x".into() },
5404 UpgradeInstruction::StateChange {
5405 script: PathBuf::from("lib/m.lisp"),
5406 },
5407 UpgradeInstruction::StateChange {
5408 script: PathBuf::from("lib/m.lisp"),
5409 },
5410 UpgradeInstruction::SoftPurge {
5411 module: "y-old".into(),
5412 },
5413 UpgradeInstruction::SoftPurge {
5414 module: "y-old".into(),
5415 },
5416 ],
5417 );
5418 let err = e.validate().unwrap_err();
5419 assert_eq!(
5420 err,
5421 UpgradeError::DuplicateStateChange {
5422 from: "0.1.0".into(),
5423 script: PathBuf::from("lib/m.lisp"),
5424 },
5425 "duplicate-state-change must surface before duplicate-cleanup, got {err:?}"
5426 );
5427 }
5428
5429 #[test]
5430 fn validate_state_change_singularity_reports_first_collision() {
5431 // Determinism pin: with three state-changes on the same script
5432 // the gate reports the *first* collision (the second
5433 // occurrence) and stops — the third's duplicate is masked by
5434 // the first surfaced one. Mirrors
5435 // `validate_load_singularity_reports_first_collision` /
5436 // `validate_cleanup_singularity_reports_first_collision` on the
5437 // sibling singularity axes and every peer duplicate gate's
5438 // first-collision discipline.
5439 let e = entry(
5440 "0.1.0",
5441 vec![
5442 UpgradeInstruction::LoadModule { module: "x".into() },
5443 UpgradeInstruction::StateChange {
5444 script: PathBuf::from("lib/m.lisp"),
5445 },
5446 UpgradeInstruction::StateChange {
5447 script: PathBuf::from("lib/m.lisp"),
5448 },
5449 UpgradeInstruction::StateChange {
5450 script: PathBuf::from("lib/m.lisp"),
5451 },
5452 ],
5453 );
5454 let err = e.validate().unwrap_err();
5455 assert_eq!(
5456 err,
5457 UpgradeError::DuplicateStateChange {
5458 from: "0.1.0".into(),
5459 script: PathBuf::from("lib/m.lisp"),
5460 },
5461 "the first colliding occurrence must surface, not the later third-migration collision"
5462 );
5463 }
5464
5465 #[test]
5466 fn validate_state_change_singularity_threads_through_validate_upgrade_from() {
5467 // The whole-list entry-point surfaces the per-entry singularity
5468 // error (mirrors
5469 // `validate_load_singularity_threads_through_validate_upgrade_from`
5470 // / `validate_cleanup_singularity_threads_through_validate_upgrade_from`):
5471 // the gate is reachable from the LayoutInvariants call site,
5472 // not only from a direct `entry.validate()`.
5473 let entries = vec![entry(
5474 "0.1.0",
5475 vec![
5476 UpgradeInstruction::LoadModule { module: "x".into() },
5477 UpgradeInstruction::StateChange {
5478 script: PathBuf::from("lib/m.lisp"),
5479 },
5480 UpgradeInstruction::StateChange {
5481 script: PathBuf::from("lib/m.lisp"),
5482 },
5483 ],
5484 )];
5485 let err = validate_upgrade_from(&entries).unwrap_err();
5486 assert!(
5487 matches!(err, UpgradeError::DuplicateStateChange { .. }),
5488 "validate_upgrade_from must thread the state-change-singularity error, got {err:?}"
5489 );
5490 }
5491
5492 #[test]
5493 fn validate_state_change_singularity_projects_scripts_through_declared_path_accessor() {
5494 // Composition pin: [`UpgradeFromEntry::validate_state_change_singularity`]'s
5495 // per-instruction `StateChange`-arm script-path projection must
5496 // route through the sibling lifted
5497 // [`UpgradeInstruction::declared_path`] `Option<&PathBuf>`
5498 // accessor, not the raw
5499 // `match instr { UpgradeInstruction::StateChange { script } =>
5500 // script.as_path(), _ => continue }` open-coded pattern-match
5501 // the gate previously carried.
5502 //
5503 // Structurally: the gate's projection accept-set is the union
5504 // of every [`UpgradeInstruction`] variant for which
5505 // `declared_path().is_some()` — today exactly
5506 // [`UpgradeInstruction::StateChange`] per the sibling
5507 // `declared_path_only_for_state_change` pin, so a
5508 // duplicate-scripts input trips `DuplicateStateChange` and a
5509 // non-`StateChange` input (module-bearing / terminal) leaves
5510 // `seen` empty and the gate returns `Ok(())` byte-identical to
5511 // the pattern-match shape.
5512 //
5513 // Byte-equal today (`declared_path` returns `Some(script)` iff
5514 // `StateChange`, byte-for-byte from the variant's own storage);
5515 // the pin catches any future accessor extension that promotes
5516 // an additional variant onto the `PathBuf`-carrying axis — the
5517 // gate then fires on duplicate scripts from that variant too,
5518 // and the singularity discipline the sibling
5519 // `validate_load_singularity` / `validate_cleanup_singularity`
5520 // gates share on the `String`-carrying axis's per-variant
5521 // consumers extends to the promoted variant by construction.
5522 //
5523 // Peer of the sibling four per-`UpgradeInstruction` consumers
5524 // ([`UpgradeInstruction::validate`]'s per-`StateChange`
5525 // sandbox-path fan-out, the layout-side per-`StateChange`
5526 // script-existence fan-out at
5527 // `caixa-core/src/layout.rs:1017`, the cross-slot
5528 // [`validate_upgrade_from_against_behavior`] gate's per-
5529 // `StateChange` detection loop, the peer
5530 // [`UpgradeInstruction::declared_module`] `String`-axis
5531 // per-variant unifier) — this gate now shares one typed
5532 // dispatch on the substrate primitive's `PathBuf`-carrying
5533 // axis with those consumers, so a future rebrand on the axis
5534 // migrates as a single caixa-core edit rather than a
5535 // coordinated rewrite of five call sites.
5536 //
5537 // Three-arm projective coverage:
5538 // (a) `StateChange` scripts project through `declared_path()`
5539 // byte-equal to the raw `script.as_path()` field access;
5540 // (b) a duplicate-`StateChange` input trips the gate on the
5541 // second occurrence with `DuplicateStateChange` carrying
5542 // the offending script verbatim;
5543 // (c) a non-`StateChange`-only input (`LoadModule` /
5544 // `SoftPurge` / `Purge` / `Restart`) leaves the gate
5545 // vacuous with `Ok(())` — the `declared_path().is_none()`
5546 // arm's `continue` fall-through pins.
5547 //
5548 // Fail-before-pass-after verified locally: swapping the
5549 // production `let Some(script) = instr.declared_path() else {
5550 // continue };` back to `let script = match instr {
5551 // UpgradeInstruction::StateChange { script } =>
5552 // script.as_path(), _ => continue, };` keeps arms (a)-(c)
5553 // passing but silently detaches the gate from the accessor's
5554 // typed dispatch — any future `declared_path` extension
5555 // (promotion of an additional variant onto the axis, an
5556 // operator-side pre-resolved-path cache the accessor
5557 // materializes) would then silently disagree between this
5558 // gate's raw pattern-match and the peer four sibling consumers
5559 // that route through the accessor.
5560 use std::path::PathBuf;
5561
5562 // (a) StateChange projection byte-equal via declared_path.
5563 let sc = UpgradeInstruction::StateChange {
5564 script: PathBuf::from("lib/m.lisp"),
5565 };
5566 assert_eq!(
5567 sc.declared_path().map(std::path::PathBuf::as_path),
5568 Some(PathBuf::from("lib/m.lisp").as_path()),
5569 "declared_path() must project the StateChange :script byte-equal to the raw \
5570 field access — accessor divergence would silently detach the gate from the \
5571 projection every peer per-`UpgradeInstruction` consumer routes through"
5572 );
5573
5574 // (b) Duplicate-StateChange input trips the gate.
5575 let dup = entry(
5576 "0.1.0",
5577 vec![
5578 UpgradeInstruction::LoadModule { module: "x".into() },
5579 UpgradeInstruction::StateChange {
5580 script: PathBuf::from("lib/m.lisp"),
5581 },
5582 UpgradeInstruction::StateChange {
5583 script: PathBuf::from("lib/m.lisp"),
5584 },
5585 ],
5586 );
5587 assert_eq!(
5588 dup.validate_state_change_singularity(),
5589 Err(UpgradeError::DuplicateStateChange {
5590 from: "0.1.0".into(),
5591 script: PathBuf::from("lib/m.lisp"),
5592 }),
5593 "duplicate StateChange scripts must trip the gate on the second occurrence \
5594 through the declared_path accessor's Some(script) arm"
5595 );
5596
5597 // (c) Non-StateChange-only inputs leave the gate vacuous.
5598 for instrs in [
5599 vec![UpgradeInstruction::LoadModule { module: "x".into() }],
5600 vec![
5601 UpgradeInstruction::LoadModule { module: "x".into() },
5602 UpgradeInstruction::SoftPurge {
5603 module: "x-old".into(),
5604 },
5605 ],
5606 vec![
5607 UpgradeInstruction::LoadModule { module: "x".into() },
5608 UpgradeInstruction::Purge {
5609 module: "x-old".into(),
5610 },
5611 ],
5612 vec![UpgradeInstruction::Restart],
5613 ] {
5614 for instr in &instrs {
5615 assert!(
5616 instr.declared_path().is_none(),
5617 "non-StateChange variants must project None through declared_path — \
5618 accessor divergence would let this gate silently fire on a duplicate \
5619 module reference far from any :state-change site"
5620 );
5621 }
5622 let e = entry("0.1.0", instrs);
5623 assert_eq!(
5624 e.validate_state_change_singularity(),
5625 Ok(()),
5626 "the state-change-singularity gate must return Ok(()) on an entry whose \
5627 instructions all project None through declared_path — the accessor's \
5628 continue arm the pattern-match's `_ => continue` previously carried"
5629 );
5630 }
5631 }
5632
5633 // ── within-entry state-change-before-cleanup ordering invariant ──
5634
5635 #[test]
5636 fn validate_rejects_state_change_after_soft_purge() {
5637 // Fail-before-pass-after pin: `:state-change` is the
5638 // gen_server:code_change/3 analog and folds the prior-version
5639 // state shape into the current shape; `:soft-purge` drains the
5640 // prior code. The operator runs instructions in declared order,
5641 // so a `:soft-purge` ahead of a `:state-change` drains the
5642 // prior module before the migration callback runs against the
5643 // state it held — the canonical OTP error mode
5644 // "`code_change/3` invoked on a purged module" the
5645 // release_handler closes by always ordering the migration
5646 // before the cleanup.
5647 let e = entry(
5648 "0.1.0",
5649 vec![
5650 UpgradeInstruction::LoadModule { module: "x".into() },
5651 UpgradeInstruction::SoftPurge {
5652 module: "x-old".into(),
5653 },
5654 UpgradeInstruction::StateChange {
5655 script: PathBuf::from("lib/m.lisp"),
5656 },
5657 ],
5658 );
5659 let err = e.validate().unwrap_err();
5660 assert_eq!(
5661 err,
5662 UpgradeError::StateChangeAfterCleanup {
5663 from: "0.1.0".into(),
5664 script: PathBuf::from("lib/m.lisp"),
5665 prior_cleanup_kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
5666 prior_cleanup_module: "x-old".into(),
5667 },
5668 "a `:state-change` after a `:soft-purge` must surface as StateChangeAfterCleanup \
5669 naming the offending entry + script + the prior cleanup's kind/module, got {err:?}"
5670 );
5671 }
5672
5673 #[test]
5674 fn validate_rejects_state_change_after_purge() {
5675 // Per-arm coverage: `:purge` (immediate discard, no drain) is
5676 // the more catastrophic peer of `:soft-purge` on the cleanup
5677 // axis; same gate, same shape, the `prior_cleanup_kind` field
5678 // distinguishes the diagnostic so the author can grep their
5679 // caixa.lisp for the offending `(:purge …)` form.
5680 let e = entry(
5681 "0.1.0",
5682 vec![
5683 UpgradeInstruction::LoadModule { module: "x".into() },
5684 UpgradeInstruction::Purge {
5685 module: "x-old".into(),
5686 },
5687 UpgradeInstruction::StateChange {
5688 script: PathBuf::from("lib/m.lisp"),
5689 },
5690 ],
5691 );
5692 let err = e.validate().unwrap_err();
5693 assert_eq!(
5694 err,
5695 UpgradeError::StateChangeAfterCleanup {
5696 from: "0.1.0".into(),
5697 script: PathBuf::from("lib/m.lisp"),
5698 prior_cleanup_kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
5699 prior_cleanup_module: "x-old".into(),
5700 },
5701 "a `:state-change` after a `:purge` must surface as StateChangeAfterCleanup with \
5702 `prior_cleanup_kind: \":purge\"`, got {err:?}"
5703 );
5704 }
5705
5706 #[test]
5707 fn validate_accepts_state_change_before_cleanup() {
5708 // Positive control: the canonical `(:load-module …)
5709 // (:state-change …) (:soft-purge …)` order validates — the
5710 // exact shape the module doc example and `validate_accepts_
5711 // well_formed` already pin, restated here on the new gate's
5712 // identity element so a future shortcut that runs the
5713 // singularity gates first doesn't silently mask a regression
5714 // here.
5715 let e = entry(
5716 "0.1.0",
5717 vec![
5718 UpgradeInstruction::LoadModule { module: "x".into() },
5719 UpgradeInstruction::StateChange {
5720 script: PathBuf::from("lib/m.lisp"),
5721 },
5722 UpgradeInstruction::SoftPurge {
5723 module: "x-old".into(),
5724 },
5725 ],
5726 );
5727 e.validate().unwrap();
5728 }
5729
5730 #[test]
5731 fn validate_accepts_cleanup_without_state_change() {
5732 // Empty-set identity: an entry that carries no `:state-change`
5733 // at all has nothing to order against the cleanup, so the gate
5734 // passes regardless of how the cleanups are placed (after the
5735 // single required `:load-module`). Mirrors the
5736 // `validate_accepts_multiple_purges_after_one_load` positive
5737 // control on the peer purge-ordering gate; metadata-only
5738 // upgrades with cleanup-but-no-migration land here.
5739 let e = entry(
5740 "0.1.0",
5741 vec![
5742 UpgradeInstruction::LoadModule { module: "x".into() },
5743 UpgradeInstruction::SoftPurge {
5744 module: "x-old".into(),
5745 },
5746 UpgradeInstruction::Purge {
5747 module: "x-oldest".into(),
5748 },
5749 ],
5750 );
5751 e.validate().unwrap();
5752 }
5753
5754 #[test]
5755 fn validate_accepts_state_change_without_cleanup() {
5756 // Empty-set identity on the dual axis: an entry that carries no
5757 // cleanup at all has nothing to order against the state-change,
5758 // so the gate passes — additive-upgrade shapes (load new code,
5759 // migrate state, leave old code resident for in-flight callers
5760 // to drain naturally) land here.
5761 let e = entry(
5762 "0.1.0",
5763 vec![
5764 UpgradeInstruction::LoadModule { module: "x".into() },
5765 UpgradeInstruction::StateChange {
5766 script: PathBuf::from("lib/m.lisp"),
5767 },
5768 ],
5769 );
5770 e.validate().unwrap();
5771 }
5772
5773 #[test]
5774 fn validate_accepts_multiple_state_changes_before_cleanup() {
5775 // Coverage: every state-change must precede every cleanup, not
5776 // just the first. A chain `(load) (sc) (sc) (sp)` is the
5777 // canonical "two distinct migration scripts on a chained
5778 // upgrade" shape (one module's schema *and* another's
5779 // projection per the DuplicateStateChange diagnostic), and
5780 // it must pass when each state-change has distinct script
5781 // paths. Pinned here so a future shortcut that only checks
5782 // the first state-change doesn't silently accept a
5783 // `(load) (sc-1) (sp) (sc-2)` regression.
5784 let e = entry(
5785 "0.1.0",
5786 vec![
5787 UpgradeInstruction::LoadModule { module: "x".into() },
5788 UpgradeInstruction::StateChange {
5789 script: PathBuf::from("lib/m1.lisp"),
5790 },
5791 UpgradeInstruction::StateChange {
5792 script: PathBuf::from("lib/m2.lisp"),
5793 },
5794 UpgradeInstruction::SoftPurge {
5795 module: "x-old".into(),
5796 },
5797 ],
5798 );
5799 e.validate().unwrap();
5800 }
5801
5802 #[test]
5803 fn validate_rejects_state_change_sandwiched_between_cleanups() {
5804 // First-cleanup-wins pin: an entry like `(load) (sp-1) (sc)
5805 // (sp-2)` violates the gate because the state-change runs
5806 // after the first cleanup. The reported `prior_cleanup_*`
5807 // names the *first* cleanup (the load-bearing one), not the
5808 // last — mirrors every peer first-collision diagnostic
5809 // posture on this module (`validate_state_change_ordering`,
5810 // `validate_purge_ordering`, `validate_load_singularity`,
5811 // `validate_state_change_singularity`,
5812 // `validate_cleanup_singularity` all report the first
5813 // colliding instruction, not the last).
5814 let e = entry(
5815 "0.1.0",
5816 vec![
5817 UpgradeInstruction::LoadModule { module: "x".into() },
5818 UpgradeInstruction::SoftPurge {
5819 module: "x-old".into(),
5820 },
5821 UpgradeInstruction::StateChange {
5822 script: PathBuf::from("lib/m.lisp"),
5823 },
5824 UpgradeInstruction::Purge {
5825 module: "y-old".into(),
5826 },
5827 ],
5828 );
5829 let err = e.validate().unwrap_err();
5830 assert_eq!(
5831 err,
5832 UpgradeError::StateChangeAfterCleanup {
5833 from: "0.1.0".into(),
5834 script: PathBuf::from("lib/m.lisp"),
5835 prior_cleanup_kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
5836 prior_cleanup_module: "x-old".into(),
5837 },
5838 "the first cleanup the state-change follows must surface (not the trailing one), \
5839 got {err:?}"
5840 );
5841 }
5842
5843 #[test]
5844 fn validate_state_change_before_cleanup_fires_after_purge_ordering() {
5845 // Diagnostic-precedence pin: an entry like `((:soft-purge
5846 // "x-old") (:load-module "x") (:state-change "m.lisp"))` is
5847 // *both* purge-without-load (the cleanup runs before the
5848 // load) and state-change-after-cleanup (the state-change
5849 // runs after the cleanup). The more-fundamental ordering
5850 // gate must win — the missing-load defect (a cleanup that
5851 // drains the only resident version to nothing) is load-
5852 // bearing, and surfacing the state-change-after-cleanup
5853 // diagnostic first would mask the drain-to-nothing defect
5854 // the peer purge-ordering gate exists to close. Guards the
5855 // call order in `validate` against silent reordering. Same
5856 // posture as `validate_purge_ordering_fires_after_state_
5857 // change_ordering` on the sibling ordering gate.
5858 //
5859 // Pin specifically uses the load-after-cleanup shape (rather
5860 // than load-less) so the state-change-ordering gate (which
5861 // would otherwise fire first on a `((:soft-purge …)
5862 // (:state-change …))` shape with no leading load) is
5863 // sidestepped: with the load present after the cleanup,
5864 // state-change-ordering passes (its `loaded` latch is set
5865 // before the state-change is encountered) but purge-ordering
5866 // still fails (the cleanup precedes the load). That isolates
5867 // the precedence between purge-ordering and this gate
5868 // cleanly.
5869 let e = entry(
5870 "0.1.0",
5871 vec![
5872 UpgradeInstruction::SoftPurge {
5873 module: "x-old".into(),
5874 },
5875 UpgradeInstruction::LoadModule { module: "x".into() },
5876 UpgradeInstruction::StateChange {
5877 script: PathBuf::from("lib/m.lisp"),
5878 },
5879 ],
5880 );
5881 let err = e.validate().unwrap_err();
5882 assert!(
5883 matches!(
5884 err,
5885 UpgradeError::PurgeWithoutPriorLoad {
5886 kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
5887 ..
5888 }
5889 ),
5890 "purge-without-load must surface before state-change-after-cleanup, got {err:?}"
5891 );
5892 }
5893
5894 #[test]
5895 fn validate_state_change_before_cleanup_fires_after_state_change_ordering() {
5896 // Diagnostic-precedence pin: an entry like `((:state-change
5897 // "m.lisp") (:soft-purge "x-old"))` is state-change-without-
5898 // load (because no `:load-module` precedes the state-change)
5899 // but *not* state-change-after-cleanup (the state-change
5900 // precedes the cleanup textually). The state-change-ordering
5901 // gate must surface first regardless — the missing-load
5902 // defect on the migration axis is the load-bearing semantic
5903 // and surfacing a different ordering diagnostic would mask
5904 // the migration-against-stale-code defect. Guards the call
5905 // order in `validate` against silent reordering on a shape
5906 // that fires only the state-change-ordering gate (not this
5907 // one), pinning that the state-change-ordering gate wins
5908 // ahead of this gate's chance to look at the list.
5909 let e = entry(
5910 "0.1.0",
5911 vec![
5912 UpgradeInstruction::StateChange {
5913 script: PathBuf::from("lib/m.lisp"),
5914 },
5915 UpgradeInstruction::SoftPurge {
5916 module: "x-old".into(),
5917 },
5918 ],
5919 );
5920 let err = e.validate().unwrap_err();
5921 assert!(
5922 matches!(err, UpgradeError::StateChangeWithoutPriorLoad { .. }),
5923 "state-change-without-load must surface before purge-without-load (the canonical \
5924 validate_purge_ordering_fires_after_state_change_ordering pin), got {err:?}"
5925 );
5926 }
5927
5928 #[test]
5929 fn validate_state_change_before_cleanup_fires_after_per_instr_shape() {
5930 // Order pin: a malformed `:script` value on a `:state-change`
5931 // (an empty path) surfaces its narrower `EmptyScript`
5932 // diagnostic *before* the within-entry state-change-before-
5933 // cleanup gate fires. The per-instruction shape pass walks
5934 // the list inline before the ordering check, so the narrower
5935 // self-locating diagnostic surfaces first — mirrors the
5936 // empty-first cascade on every peer path-shape gate and the
5937 // `validate_purge_ordering_fires_after_per_instr_shape` pin
5938 // on the sibling ordering gate.
5939 let e = entry(
5940 "0.1.0",
5941 vec![
5942 UpgradeInstruction::LoadModule { module: "x".into() },
5943 UpgradeInstruction::SoftPurge {
5944 module: "x-old".into(),
5945 },
5946 UpgradeInstruction::StateChange {
5947 script: PathBuf::new(),
5948 },
5949 ],
5950 );
5951 let err = e.validate().unwrap_err();
5952 assert_eq!(
5953 err,
5954 UpgradeError::EmptyScript,
5955 "malformed instruction must surface its narrower diagnostic before the \
5956 state-change-before-cleanup gate fires, got {err:?}"
5957 );
5958 }
5959
5960 #[test]
5961 fn validate_state_change_before_cleanup_fires_before_state_change_singularity() {
5962 // Diagnostic-precedence pin: an entry like `((:load-module
5963 // "x") (:soft-purge "x-old") (:state-change "m.lisp")
5964 // (:state-change "m.lisp"))` violates *both* this ordering
5965 // gate (the first state-change follows the cleanup) and the
5966 // state-change-singularity gate (the same script appears
5967 // twice). The ordering gate must win — the canonical
5968 // "ordering before singularity" precedence the peer
5969 // `validate_state_change_ordering` / `validate_purge_
5970 // ordering` gates already establish over their own singularity
5971 // gates, applied uniformly across the OTP canonical-sequence
5972 // ordering axis here. Guards the call order in `validate`:
5973 // `validate_state_change_before_cleanup` runs before the
5974 // per-instruction-class singularity gates.
5975 let e = entry(
5976 "0.1.0",
5977 vec![
5978 UpgradeInstruction::LoadModule { module: "x".into() },
5979 UpgradeInstruction::SoftPurge {
5980 module: "x-old".into(),
5981 },
5982 UpgradeInstruction::StateChange {
5983 script: PathBuf::from("lib/m.lisp"),
5984 },
5985 UpgradeInstruction::StateChange {
5986 script: PathBuf::from("lib/m.lisp"),
5987 },
5988 ],
5989 );
5990 let err = e.validate().unwrap_err();
5991 assert!(
5992 matches!(err, UpgradeError::StateChangeAfterCleanup { .. }),
5993 "state-change-after-cleanup must surface before duplicate-state-change, got {err:?}"
5994 );
5995 }
5996
5997 #[test]
5998 fn validate_state_change_before_cleanup_threads_through_validate_upgrade_from() {
5999 // The whole-list entry-point surfaces the per-entry ordering
6000 // error (mirrors `validate_purge_ordering_threads_through_
6001 // validate_upgrade_from` and every peer wiring pin): the gate
6002 // is reachable from the LayoutInvariants call site, not only
6003 // from a direct `entry.validate()`.
6004 let entries = vec![entry(
6005 "0.1.0",
6006 vec![
6007 UpgradeInstruction::LoadModule { module: "x".into() },
6008 UpgradeInstruction::SoftPurge {
6009 module: "x-old".into(),
6010 },
6011 UpgradeInstruction::StateChange {
6012 script: PathBuf::from("lib/m.lisp"),
6013 },
6014 ],
6015 )];
6016 let err = validate_upgrade_from(&entries).unwrap_err();
6017 assert!(
6018 matches!(err, UpgradeError::StateChangeAfterCleanup { .. }),
6019 "validate_upgrade_from must thread the state-change-before-cleanup error, \
6020 got {err:?}"
6021 );
6022 }
6023
6024 #[test]
6025 fn validate_state_change_before_cleanup_projects_scripts_through_declared_path_accessor() {
6026 // Composition pin: [`UpgradeFromEntry::validate_state_change_before_cleanup`]'s
6027 // per-instruction `StateChange`-arm script-path projection must
6028 // route through the sibling lifted
6029 // [`UpgradeInstruction::declared_path`] `Option<&PathBuf>`
6030 // accessor, not the raw
6031 // `if let UpgradeInstruction::StateChange { script } = instr`
6032 // open-coded pattern-match the gate previously carried inside
6033 // `impl UpgradeFromEntry` at caixa-core/src/upgrade.rs:806.
6034 //
6035 // Structurally: the gate's projection accept-set is the union
6036 // of every [`UpgradeInstruction`] variant for which
6037 // `declared_path().is_some()` — today exactly
6038 // [`UpgradeInstruction::StateChange`] per the sibling
6039 // `declared_path_only_for_state_change` pin, so a
6040 // state-change-after-cleanup input trips
6041 // `StateChangeAfterCleanup` and a non-`StateChange` input
6042 // (module-bearing / terminal) leaves the sticky-once latch
6043 // sweep quiet byte-identical to the pattern-match shape.
6044 //
6045 // Byte-equal today (`declared_path` returns `Some(script)` iff
6046 // `StateChange`, byte-for-byte from the variant's own storage);
6047 // the pin catches any future accessor extension that promotes
6048 // an additional variant onto the `PathBuf`-carrying axis — the
6049 // gate then fires on migrate-after-cleanup for that variant too,
6050 // and the migrate→cleanup ordering discipline the peer
6051 // [`validate_state_change_singularity`] /
6052 // [`validate_upgrade_from_against_behavior`] gates share on the
6053 // same axis extends to the promoted variant by construction.
6054 //
6055 // Peer of the sibling four per-`UpgradeInstruction` consumers
6056 // ([`UpgradeInstruction::validate`]'s per-`StateChange`
6057 // sandbox-path fan-out, the layout-side per-`StateChange`
6058 // script-existence fan-out at
6059 // `caixa-core/src/layout.rs:1058`, the within-entry
6060 // [`UpgradeFromEntry::validate_state_change_singularity`]
6061 // per-`StateChange` script-projection fan-out, the cross-slot
6062 // [`validate_upgrade_from_against_behavior`] per-`StateChange`
6063 // detection loop) — the fifth (and last unlifted inside
6064 // `impl UpgradeFromEntry`) per-`UpgradeInstruction`-consumer of
6065 // the `PathBuf`-carrying axis to now route through the accessor.
6066 // Same shape as the sibling
6067 // `validate_state_change_singularity_projects_scripts_through_declared_path_accessor`
6068 // and `validate_upgrade_from_against_behavior_projects_scripts_through_declared_path_accessor`
6069 // pins extended onto the within-entry migrate→cleanup ordering
6070 // gate.
6071 //
6072 // Three-arm projective coverage:
6073 // (a) `StateChange` scripts project through `declared_path()`
6074 // byte-equal to the raw `script.clone()` field access
6075 // the diagnostic previously carried;
6076 // (b) a `:state-change`-after-cleanup input trips the gate
6077 // with `StateChangeAfterCleanup` carrying the offending
6078 // script + the prior cleanup's kind/module verbatim;
6079 // (c) a non-`StateChange`-only input (`LoadModule` /
6080 // `SoftPurge` / `Purge` / `Restart`) leaves the gate
6081 // vacuous with `Ok(())` — the `declared_path().is_none()`
6082 // arm's fall-through pins.
6083 //
6084 // Fail-before-pass-after verified structurally: swapping the
6085 // production
6086 // `else if let Some(script) = instr.declared_path() && … { … }`
6087 // back to
6088 // `else if let UpgradeInstruction::StateChange { script } = instr && … { … }`
6089 // keeps arms (a)-(c) passing but silently detaches this within-
6090 // entry ordering gate from the accessor's typed dispatch — any
6091 // future `declared_path` extension (promotion of an additional
6092 // variant onto the axis, an operator-side pre-resolved-path
6093 // cache the accessor materializes) would then silently disagree
6094 // between this gate's raw pattern-match and the peer four
6095 // sibling consumers that route through the accessor.
6096
6097 // (a) StateChange projection byte-equal via declared_path.
6098 let sc = UpgradeInstruction::StateChange {
6099 script: PathBuf::from("lib/m.lisp"),
6100 };
6101 assert_eq!(
6102 sc.declared_path().cloned(),
6103 Some(PathBuf::from("lib/m.lisp")),
6104 "declared_path() must project the StateChange :script byte-equal to the raw \
6105 field access — accessor divergence would silently detach this within-entry \
6106 migrate→cleanup ordering gate from the projection every peer per-`UpgradeInstruction` \
6107 consumer routes through"
6108 );
6109
6110 // (b) StateChange-after-cleanup trips the gate through the accessor.
6111 let after = entry(
6112 "0.1.0",
6113 vec![
6114 UpgradeInstruction::LoadModule { module: "x".into() },
6115 UpgradeInstruction::SoftPurge {
6116 module: "x-old".into(),
6117 },
6118 UpgradeInstruction::StateChange {
6119 script: PathBuf::from("lib/m.lisp"),
6120 },
6121 ],
6122 );
6123 assert_eq!(
6124 after.validate(),
6125 Err(UpgradeError::StateChangeAfterCleanup {
6126 from: "0.1.0".into(),
6127 script: PathBuf::from("lib/m.lisp"),
6128 prior_cleanup_kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
6129 prior_cleanup_module: "x-old".into(),
6130 }),
6131 "a :state-change following a cleanup must trip the gate through the declared_path \
6132 accessor's Some(script) arm — carrying the offending script + the prior cleanup's \
6133 kind/module verbatim byte-identical to the pattern-match shape"
6134 );
6135
6136 // (c) Non-StateChange-only inputs leave the gate vacuous.
6137 for instrs in [
6138 vec![UpgradeInstruction::LoadModule { module: "x".into() }],
6139 vec![
6140 UpgradeInstruction::LoadModule { module: "x".into() },
6141 UpgradeInstruction::SoftPurge {
6142 module: "x-old".into(),
6143 },
6144 ],
6145 vec![
6146 UpgradeInstruction::LoadModule { module: "x".into() },
6147 UpgradeInstruction::Purge {
6148 module: "x-old".into(),
6149 },
6150 ],
6151 vec![UpgradeInstruction::Restart],
6152 ] {
6153 for instr in &instrs {
6154 assert!(
6155 instr.declared_path().is_none(),
6156 "non-StateChange variants must project None through declared_path — \
6157 accessor divergence would let this within-entry ordering gate silently \
6158 fire on a cleanup-only sequence far from any :state-change site"
6159 );
6160 }
6161 let e = entry("0.1.0", instrs);
6162 assert_eq!(
6163 e.validate(),
6164 Ok(()),
6165 "the state-change-before-cleanup gate must return Ok(()) on an entry whose \
6166 instructions all project None through declared_path — the accessor's \
6167 None arm the pattern-match's implicit fall-through previously carried"
6168 );
6169 }
6170 }
6171
6172 #[test]
6173 fn validate_restart_order_independent() {
6174 // Position-agnostic: `(:restart)` leading or trailing the
6175 // mixed sequence surfaces the same RestartNotExclusive shape.
6176 // Mirrors OTP appup's order-insensitive
6177 // `restart_emulator | restart_new_emulator` terminal rule —
6178 // the position of the restart instruction in the script is
6179 // irrelevant; what matters is the script *contains* it
6180 // alongside other instructions at all. The gate must not
6181 // gain a false positive by depending on instruction ordering.
6182 let leading = entry(
6183 "0.1.0",
6184 vec![
6185 UpgradeInstruction::Restart,
6186 UpgradeInstruction::LoadModule { module: "x".into() },
6187 ],
6188 );
6189 let trailing = entry(
6190 "0.1.0",
6191 vec![
6192 UpgradeInstruction::LoadModule { module: "x".into() },
6193 UpgradeInstruction::Restart,
6194 ],
6195 );
6196 let middle = entry(
6197 "0.1.0",
6198 vec![
6199 UpgradeInstruction::LoadModule { module: "a".into() },
6200 UpgradeInstruction::Restart,
6201 UpgradeInstruction::SoftPurge {
6202 module: "a-old".into(),
6203 },
6204 ],
6205 );
6206 for e in [&leading, &trailing, &middle] {
6207 assert!(
6208 matches!(
6209 e.validate().unwrap_err(),
6210 UpgradeError::RestartNotExclusive {
6211 restart_count: 1,
6212 ..
6213 }
6214 ),
6215 "mixed-with-:restart entry must surface RestartNotExclusive regardless of \
6216 instruction order, got {:?}",
6217 e.validate()
6218 );
6219 }
6220 }
6221
6222 #[test]
6223 fn validate_restart_exclusive_fires_after_per_instr_shape() {
6224 // Order pin: a malformed `:module` value on a Module-bearing
6225 // instruction (an empty string) surfaces its narrower
6226 // kind-tagged `ModuleEmpty` diagnostic *before* the within-
6227 // entry restart-exclusivity gate fires. The per-instruction
6228 // shape pass walks the list inline before the restart-
6229 // exclusive check, so the narrower self-locating diagnostic
6230 // surfaces first — mirrors the empty-first cascade on every
6231 // peer DNS-1123 gate (`validate_module`,
6232 // `validate_membro_caixa`, `validate_placement_cluster`) and
6233 // the `*_invalid_fires_before_duplicate_check` arm-ordering
6234 // pins on every typed-graph axis. Without this pin a future
6235 // shortcut that runs the restart-exclusive check ahead of
6236 // per-instruction shape would surface a less-actionable
6237 // RestartNotExclusive over an instruction list that's also
6238 // malformed at the per-instruction layer.
6239 let e = entry(
6240 "0.1.0",
6241 vec![
6242 UpgradeInstruction::LoadModule {
6243 module: String::new(),
6244 },
6245 UpgradeInstruction::Restart,
6246 ],
6247 );
6248 let err = e.validate().unwrap_err();
6249 assert_eq!(
6250 err,
6251 UpgradeError::ModuleEmpty {
6252 kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE
6253 },
6254 "malformed instruction must surface its kind-tagged diagnostic before the \
6255 restart-exclusivity gate fires, got {err:?}"
6256 );
6257 }
6258
6259 fn behavior_with_state_change_callback() -> crate::BehaviorSpec {
6260 // Helper for the cross-slot composition gate's pass arm: a
6261 // BehaviorSpec carrying just the `:on-state-change` callback,
6262 // the runtime hook the per-version `(:state-change "…")`
6263 // instruction is delivered through during hot upgrade. Mirrors
6264 // the canonical authoring shape pinned in the module doc.
6265 crate::BehaviorSpec {
6266 on_state_change: Some(PathBuf::from("lib/migrations.lisp")),
6267 ..Default::default()
6268 }
6269 }
6270
6271 #[test]
6272 fn behavior_gate_rejects_state_change_without_any_behavior() {
6273 // `:upgrade-from` with a `(:state-change "lib/m.lisp")` and the
6274 // caixa carries no `:behavior` at all surfaces the missing-
6275 // callback diagnostic naming the offending entry's `:from` +
6276 // script. The "I added the upgrade path but never declared
6277 // `:behavior`" footgun: `:behavior` is optional at the typed
6278 // root, the typed `:upgrade-from` slot validates on its own
6279 // merits, and the operator's hot-upgrade dispatch reaches for
6280 // a callback that doesn't exist.
6281 let entries = vec![entry(
6282 "0.1.0",
6283 vec![
6284 UpgradeInstruction::LoadModule { module: "x".into() },
6285 UpgradeInstruction::StateChange {
6286 script: PathBuf::from("lib/m.lisp"),
6287 },
6288 ],
6289 )];
6290 let err = validate_upgrade_from_against_behavior(&entries, None).unwrap_err();
6291 assert_eq!(
6292 err,
6293 UpgradeError::StateChangeWithoutOnStateChangeCallback {
6294 from: "0.1.0".into(),
6295 script: PathBuf::from("lib/m.lisp"),
6296 },
6297 );
6298 }
6299
6300 #[test]
6301 fn behavior_gate_rejects_state_change_when_on_state_change_is_none() {
6302 // `:behavior` declared with *other* callbacks set
6303 // (`:on-init`, `:on-terminate`, etc.) but `:on-state-change`
6304 // None still surfaces the missing-callback diagnostic — only
6305 // the `:on-state-change` axis matters for this gate. The
6306 // "I declared `:behavior` but missed the migration callback"
6307 // footgun: a caixa that registers its lifecycle hooks but
6308 // forgets the migration delivery path leaves the
6309 // `:state-change` instruction with no runtime hook to
6310 // dispatch through.
6311 let entries = vec![entry(
6312 "0.1.0",
6313 vec![
6314 UpgradeInstruction::LoadModule { module: "x".into() },
6315 UpgradeInstruction::StateChange {
6316 script: PathBuf::from("lib/m.lisp"),
6317 },
6318 ],
6319 )];
6320 let b = crate::BehaviorSpec {
6321 on_init: Some(PathBuf::from("lib/init.lisp")),
6322 on_terminate: Some(PathBuf::from("lib/cleanup.lisp")),
6323 ..Default::default()
6324 };
6325 let err = validate_upgrade_from_against_behavior(&entries, Some(&b)).unwrap_err();
6326 assert_eq!(
6327 err,
6328 UpgradeError::StateChangeWithoutOnStateChangeCallback {
6329 from: "0.1.0".into(),
6330 script: PathBuf::from("lib/m.lisp"),
6331 },
6332 "only `:on-state-change` satisfies the composition; other callbacks must not mask \
6333 the missing migration hook"
6334 );
6335 }
6336
6337 #[test]
6338 fn behavior_gate_accepts_state_change_with_on_state_change_callback() {
6339 // The canonical composition shape: a per-version
6340 // `(:state-change "lib/m.lisp")` instruction paired with the
6341 // `:behavior :on-state-change "lib/migrations.lisp"` callback
6342 // it is delivered through at hot-upgrade time. Pins the gate's
6343 // pass arm — drift here = a future tighten that rejects the
6344 // canonical OTP-shape composition surfaces as a regression at
6345 // this positive-control pin.
6346 let entries = vec![entry(
6347 "0.1.0",
6348 vec![
6349 UpgradeInstruction::LoadModule { module: "x".into() },
6350 UpgradeInstruction::StateChange {
6351 script: PathBuf::from("lib/m.lisp"),
6352 },
6353 ],
6354 )];
6355 let b = behavior_with_state_change_callback();
6356 validate_upgrade_from_against_behavior(&entries, Some(&b)).unwrap();
6357 }
6358
6359 #[test]
6360 fn behavior_gate_accepts_entries_without_any_state_change() {
6361 // Empty-set identity: entries carrying no `:state-change`
6362 // instruction at all (load + cleanup only — the metadata-only
6363 // upgrade shape the module doc names, "On any failure, the
6364 // current version stays load-bearing — a typed atomic
6365 // upgrade") leave the gate vacuous. The composition only
6366 // requires a callback when the per-version script exists; a
6367 // load + cleanup pair has no migration to deliver, so the
6368 // absence of `:on-state-change` is coherent.
6369 let entries = vec![entry(
6370 "0.1.0",
6371 vec![
6372 UpgradeInstruction::LoadModule { module: "x".into() },
6373 UpgradeInstruction::SoftPurge {
6374 module: "x-old".into(),
6375 },
6376 ],
6377 )];
6378 validate_upgrade_from_against_behavior(&entries, None).unwrap();
6379 }
6380
6381 #[test]
6382 fn behavior_gate_accepts_restart_only_entry() {
6383 // The terminal-fallback `((:restart))` shape carries no
6384 // `:state-change` — the operator restarts the pod and the
6385 // new version comes up fresh against its initial state, no
6386 // migration. Pinned alongside the metadata-only positive
6387 // control above as the second empty-state-change shape.
6388 let entries = vec![entry("0.1.0", vec![UpgradeInstruction::Restart])];
6389 validate_upgrade_from_against_behavior(&entries, None).unwrap();
6390 }
6391
6392 #[test]
6393 fn behavior_gate_accepts_empty_entries_list() {
6394 // Empty `:upgrade-from` (a caixa with no declared upgrade
6395 // paths — the v0.1.0 caixa before any upgrade entries are
6396 // added) trivially passes the gate. Pinned so the gate
6397 // doesn't accidentally fire on a caixa that hasn't yet
6398 // declared any upgrades.
6399 let entries: Vec<UpgradeFromEntry> = vec![];
6400 validate_upgrade_from_against_behavior(&entries, None).unwrap();
6401 }
6402
6403 #[test]
6404 fn behavior_gate_reports_first_state_change_in_first_entry() {
6405 // First-collision determinism: with multiple `:state-change`
6406 // instructions across multiple entries, the gate reports the
6407 // *first* one encountered in declaration order — the entry's
6408 // declaration order first, then the within-entry instruction
6409 // order. Mirrors every peer first-collision diagnostic posture
6410 // on this module (`validate_state_change_ordering`,
6411 // `validate_purge_ordering`, the singularity gates), so a
6412 // future shortcut that walks the list in reverse or returns
6413 // the last collision surfaces as a regression here.
6414 let entries = vec![
6415 entry(
6416 "0.1.0",
6417 vec![
6418 UpgradeInstruction::LoadModule { module: "x".into() },
6419 UpgradeInstruction::StateChange {
6420 script: PathBuf::from("lib/m1.lisp"),
6421 },
6422 UpgradeInstruction::StateChange {
6423 script: PathBuf::from("lib/m2.lisp"),
6424 },
6425 ],
6426 ),
6427 entry(
6428 "0.1.5",
6429 vec![
6430 UpgradeInstruction::LoadModule { module: "x".into() },
6431 UpgradeInstruction::StateChange {
6432 script: PathBuf::from("lib/m3.lisp"),
6433 },
6434 ],
6435 ),
6436 ];
6437 let err = validate_upgrade_from_against_behavior(&entries, None).unwrap_err();
6438 assert_eq!(
6439 err,
6440 UpgradeError::StateChangeWithoutOnStateChangeCallback {
6441 from: "0.1.0".into(),
6442 script: PathBuf::from("lib/m1.lisp"),
6443 },
6444 "the first :state-change in the first entry must surface, not later collisions"
6445 );
6446 }
6447
6448 #[test]
6449 fn behavior_gate_reports_second_entry_when_first_has_no_state_change() {
6450 // Cross-entry pin: a first entry with no `:state-change` (just
6451 // a load + cleanup) leaves the gate's per-entry walk continuing
6452 // to the second entry, where the offending instruction lives.
6453 // The diagnostic names the *second* entry's `:from` because
6454 // that's where the missing-callback shape is exposed — pinned
6455 // so a shortcut that bails on the first entry without a
6456 // `:state-change` (rather than continuing) doesn't mask the
6457 // defect in a later entry.
6458 let entries = vec![
6459 entry(
6460 "0.1.0",
6461 vec![
6462 UpgradeInstruction::LoadModule { module: "x".into() },
6463 UpgradeInstruction::SoftPurge {
6464 module: "x-old".into(),
6465 },
6466 ],
6467 ),
6468 entry(
6469 "0.1.5",
6470 vec![
6471 UpgradeInstruction::LoadModule { module: "x".into() },
6472 UpgradeInstruction::StateChange {
6473 script: PathBuf::from("lib/m.lisp"),
6474 },
6475 ],
6476 ),
6477 ];
6478 let err = validate_upgrade_from_against_behavior(&entries, None).unwrap_err();
6479 assert_eq!(
6480 err,
6481 UpgradeError::StateChangeWithoutOnStateChangeCallback {
6482 from: "0.1.5".into(),
6483 script: PathBuf::from("lib/m.lisp"),
6484 },
6485 "the offending entry's `:from` must surface even when an earlier entry carries no \
6486 :state-change"
6487 );
6488 }
6489
6490 #[test]
6491 fn behavior_gate_does_not_fire_when_callback_is_declared_across_many_entries() {
6492 // Positive control: a multi-entry `:upgrade-from` (chained
6493 // upgrades from v0.1.0 *and* v0.1.5) where every entry carries
6494 // a `:state-change` passes when the callback is declared once
6495 // at the caixa root. The callback is a single per-caixa
6496 // runtime hook; one declaration covers every entry's
6497 // `:state-change`, mirroring OTP's
6498 // `release_handler:install_release/1` which dispatches every
6499 // appup's `code_change` instruction through the single
6500 // `gen_server:code_change/3` callback registered on the
6501 // module.
6502 let entries = vec![
6503 entry(
6504 "0.1.0",
6505 vec![
6506 UpgradeInstruction::LoadModule { module: "x".into() },
6507 UpgradeInstruction::StateChange {
6508 script: PathBuf::from("lib/m1.lisp"),
6509 },
6510 ],
6511 ),
6512 entry(
6513 "0.1.5",
6514 vec![
6515 UpgradeInstruction::LoadModule { module: "x".into() },
6516 UpgradeInstruction::StateChange {
6517 script: PathBuf::from("lib/m2.lisp"),
6518 },
6519 ],
6520 ),
6521 ];
6522 let b = behavior_with_state_change_callback();
6523 validate_upgrade_from_against_behavior(&entries, Some(&b)).unwrap();
6524 }
6525
6526 #[test]
6527 fn behavior_gate_accepts_load_and_cleanup_only_when_behavior_carries_on_state_change() {
6528 // Symmetry pin: the gate's pass arm doesn't depend on the
6529 // entry actually carrying a `:state-change` — if no
6530 // `:state-change` is declared, the gate is vacuous regardless
6531 // of the callback (an `:on-state-change` declared without a
6532 // matching per-version script is fine, the callback is the
6533 // runtime default for any *future* migration the author hasn't
6534 // yet added). Pins that a caixa author can declare the
6535 // callback ahead of any migration without the gate
6536 // complaining.
6537 let entries = vec![entry(
6538 "0.1.0",
6539 vec![
6540 UpgradeInstruction::LoadModule { module: "x".into() },
6541 UpgradeInstruction::SoftPurge {
6542 module: "x-old".into(),
6543 },
6544 ],
6545 )];
6546 let b = behavior_with_state_change_callback();
6547 validate_upgrade_from_against_behavior(&entries, Some(&b)).unwrap();
6548 }
6549
6550 #[test]
6551 fn validate_upgrade_from_against_behavior_projects_scripts_through_declared_path_accessor() {
6552 // Composition pin: [`validate_upgrade_from_against_behavior`]'s
6553 // per-instruction `StateChange`-arm script-path projection must
6554 // route through the sibling lifted
6555 // [`UpgradeInstruction::declared_path`] `Option<&PathBuf>`
6556 // accessor, not the raw
6557 // `if let UpgradeInstruction::StateChange { script } = instr`
6558 // open-coded pattern-match the cross-slot gate previously
6559 // carried at caixa-core/src/upgrade.rs:1365.
6560 //
6561 // Structurally: the gate's projection accept-set is the union
6562 // of every [`UpgradeInstruction`] variant for which
6563 // `declared_path().is_some()` — today exactly
6564 // [`UpgradeInstruction::StateChange`] per the sibling
6565 // `declared_path_only_for_state_change` pin, so a
6566 // `:state-change`-carrying entry without an `:on-state-change`
6567 // callback trips `StateChangeWithoutOnStateChangeCallback` and
6568 // a non-`StateChange` entry (load-only / cleanup-only /
6569 // restart-only / empty-`:instructions`) leaves the per-entry
6570 // walk continuing past every non-projecting instruction
6571 // byte-identical to the pattern-match shape.
6572 //
6573 // Byte-equal today (`declared_path` returns `Some(script)` iff
6574 // `StateChange`, byte-for-byte from the variant's own storage);
6575 // the pin catches any future accessor extension that promotes
6576 // an additional variant onto the `PathBuf`-carrying axis — the
6577 // gate then fires on scripts from that variant too, and the
6578 // cross-slot composition discipline the sibling per-
6579 // `UpgradeInstruction` consumers share on the `PathBuf`-
6580 // carrying axis extends to the promoted variant by
6581 // construction.
6582 //
6583 // Peer of the sibling four per-`UpgradeInstruction` consumers
6584 // ([`UpgradeInstruction::validate`]'s per-`StateChange`
6585 // sandbox-path fan-out, the layout-side per-`StateChange`
6586 // script-existence fan-out at
6587 // `caixa-core/src/layout.rs:1058`, the within-entry
6588 // [`UpgradeFromEntry::validate_state_change_singularity`]
6589 // (2bf3ce5) per-`StateChange` script-projection fan-out, the
6590 // peer [`UpgradeInstruction::declared_module`] `String`-axis
6591 // per-variant unifier) — the fourth (and last) per-
6592 // `UpgradeInstruction`-consumer of the `PathBuf`-carrying axis
6593 // to now route through the accessor. Same shape as the
6594 // sibling
6595 // `validate_state_change_singularity_projects_scripts_through_declared_path_accessor`
6596 // pin extended onto the cross-slot composition gate.
6597 //
6598 // Three-arm projective coverage:
6599 // (a) `StateChange` scripts project through `declared_path()`
6600 // byte-equal to the raw `script.clone()` field access
6601 // the diagnostic previously carried;
6602 // (b) a `:state-change`-carrying entry with `behavior: None`
6603 // trips the gate with `StateChangeWithoutOnStateChangeCallback`
6604 // carrying the offending script verbatim;
6605 // (c) a non-`StateChange`-only entry (`LoadModule` /
6606 // `SoftPurge` / `Purge` / `Restart`) leaves the gate
6607 // vacuous with `Ok(())` — the `declared_path().is_none()`
6608 // arm's fall-through pins.
6609 //
6610 // Fail-before-pass-after verified structurally: swapping the
6611 // production
6612 // `if let Some(script) = instr.declared_path() { … }`
6613 // back to
6614 // `if let UpgradeInstruction::StateChange { script } = instr { … }`
6615 // keeps arms (a)-(c) passing but silently detaches the gate
6616 // from the accessor's typed dispatch — any future
6617 // `declared_path` extension (promotion of an additional
6618 // variant onto the axis, an operator-side pre-resolved-path
6619 // cache the accessor materializes) would then silently
6620 // disagree between this cross-slot gate's raw pattern-match
6621 // and the peer four sibling consumers that route through the
6622 // accessor.
6623
6624 // (a) StateChange projection byte-equal via declared_path.
6625 let sc = UpgradeInstruction::StateChange {
6626 script: PathBuf::from("lib/m.lisp"),
6627 };
6628 assert_eq!(
6629 sc.declared_path().cloned(),
6630 Some(PathBuf::from("lib/m.lisp")),
6631 "declared_path() must project the StateChange :script byte-equal to the raw \
6632 field access — accessor divergence would silently detach this cross-slot \
6633 composition gate from the projection every peer per-`UpgradeInstruction` \
6634 consumer routes through"
6635 );
6636
6637 // (b) StateChange-carrying entry with behavior: None trips gate.
6638 let entries = vec![entry(
6639 "0.1.0",
6640 vec![
6641 UpgradeInstruction::LoadModule { module: "x".into() },
6642 UpgradeInstruction::StateChange {
6643 script: PathBuf::from("lib/m.lisp"),
6644 },
6645 ],
6646 )];
6647 assert_eq!(
6648 validate_upgrade_from_against_behavior(&entries, None),
6649 Err(UpgradeError::StateChangeWithoutOnStateChangeCallback {
6650 from: "0.1.0".into(),
6651 script: PathBuf::from("lib/m.lisp"),
6652 }),
6653 "a :state-change-carrying entry with behavior: None must trip the gate through \
6654 the declared_path accessor's Some(script) arm — carrying the offending script \
6655 verbatim byte-identical to the pattern-match shape"
6656 );
6657
6658 // (c) Non-StateChange-only inputs leave the gate vacuous.
6659 for instrs in [
6660 vec![UpgradeInstruction::LoadModule { module: "x".into() }],
6661 vec![
6662 UpgradeInstruction::LoadModule { module: "x".into() },
6663 UpgradeInstruction::SoftPurge {
6664 module: "x-old".into(),
6665 },
6666 ],
6667 vec![
6668 UpgradeInstruction::LoadModule { module: "x".into() },
6669 UpgradeInstruction::Purge {
6670 module: "x-old".into(),
6671 },
6672 ],
6673 vec![UpgradeInstruction::Restart],
6674 ] {
6675 for instr in &instrs {
6676 assert!(
6677 instr.declared_path().is_none(),
6678 "non-StateChange variants must project None through declared_path — \
6679 accessor divergence would let this cross-slot composition gate silently \
6680 fire on a module reference far from any :state-change site"
6681 );
6682 }
6683 let entries = vec![entry("0.1.0", instrs)];
6684 assert_eq!(
6685 validate_upgrade_from_against_behavior(&entries, None),
6686 Ok(()),
6687 "the cross-slot composition gate must return Ok(()) on an entry whose \
6688 instructions all project None through declared_path — the accessor's \
6689 None arm the pattern-match's implicit fall-through previously carried"
6690 );
6691 }
6692 }
6693
6694 #[test]
6695 fn validate_restart_exclusive_threads_through_validate_upgrade_from() {
6696 // Wiring pin: the within-entry restart-exclusivity gate fires
6697 // through [`validate_upgrade_from`] (which delegates to
6698 // [`UpgradeFromEntry::validate`] per entry) before the cross-
6699 // entry duplicate-`:from` gate would have a chance to run on
6700 // the malformed entry. Pinned here so a future refactor that
6701 // walks the cross-entry gate first doesn't accidentally
6702 // surface a DuplicateFrom over an entry that's also malformed
6703 // at the within-entry restart-exclusivity layer.
6704 let entries = vec![
6705 entry(
6706 "0.1.0",
6707 vec![
6708 UpgradeInstruction::LoadModule { module: "x".into() },
6709 UpgradeInstruction::Restart,
6710 ],
6711 ),
6712 entry("0.1.0", vec![UpgradeInstruction::Restart]),
6713 ];
6714 let err = validate_upgrade_from(&entries).unwrap_err();
6715 assert!(
6716 matches!(
6717 err,
6718 UpgradeError::RestartNotExclusive {
6719 restart_count: 1,
6720 ..
6721 }
6722 ),
6723 "within-entry restart-exclusivity diagnostic must surface before the cross-entry \
6724 duplicate-`:from` gate fires, got {err:?}"
6725 );
6726 }
6727
6728 // ── drift-detection: serde-derive-to-M2_UPGRADE_FROM_KEY_* identity ──
6729
6730 #[test]
6731 fn upgrade_from_entry_serde_keys_match_lifted_m2_upgrade_from_key_consts() {
6732 // Load-bearing invariant: the two `M2_UPGRADE_FROM_KEY_*` consts
6733 // (`M2_UPGRADE_FROM_KEY_FROM` / `M2_UPGRADE_FROM_KEY_INSTRUCTIONS`)
6734 // name the exact camelCase JSON keys the `#[serde(rename_all =
6735 // "camelCase")]` attribute on `UpgradeFromEntry` emits, and every
6736 // test-side probe across the caixa-core / caixa-flux renderer
6737 // test fixtures navigates into each element of the rendered
6738 // `:upgrade-from` overlay sequence by consulting one of these two
6739 // `&'static str`s. Serialize a fully-populated UpgradeFromEntry
6740 // and pin that each canonical byte-sequence appears verbatim in
6741 // the JSON — a future accidental `rename_all = "snake_case"` /
6742 // `"kebab-case"` / verbatim-field-name flip at the derive
6743 // attribute (any of which would silently break every test-side
6744 // probe that reaches for one of the two consts) surfaces here as
6745 // a build-time test failure at `upgrade.rs`, not as an apply-time
6746 // `.get(<stale-canonical-const>)` returning `None` far from the
6747 // derive-attr drift's commit. Same discipline the sibling
6748 // `limits_spec_serde_keys_match_lifted_m2_limits_key_consts`
6749 // (d8b8b4f) and
6750 // `behavior_spec_serde_keys_match_lifted_m2_behavior_key_consts`
6751 // (21fe462) pins established on the peer `:limits` / `:behavior`
6752 // sub-slot axes: one canonical byte-string per typed sub-key
6753 // axis, pinned to the load-bearing serde derivation at the type
6754 // itself.
6755 let e = UpgradeFromEntry {
6756 from: "0.1.0".into(),
6757 instructions: vec![UpgradeInstruction::LoadModule {
6758 module: "hello-rio".into(),
6759 }],
6760 };
6761 let json = serde_json::to_string(&e).unwrap();
6762 for key in [
6763 crate::render::M2_UPGRADE_FROM_KEY_FROM,
6764 crate::render::M2_UPGRADE_FROM_KEY_INSTRUCTIONS,
6765 ] {
6766 let quoted = format!("\"{key}\"");
6767 assert!(
6768 json.contains("ed),
6769 "serialized UpgradeFromEntry must carry the lifted \
6770 M2_UPGRADE_FROM_KEY_* byte-sequence {quoted} verbatim in \
6771 the JSON emission (got: {json})",
6772 );
6773 }
6774 }
6775
6776 #[test]
6777 fn m2_upgrade_from_key_consts_are_pairwise_distinct() {
6778 // Cross-axis drift-detection pin: a future collapse of the two
6779 // canonical sub-key byte-strings onto the same value (e.g. an
6780 // accidental copy-paste flip of `M2_UPGRADE_FROM_KEY_INSTRUCTIONS`
6781 // to also read `"from"`) would silently reroute every test-side
6782 // probe on one axis onto the sibling axis's per-entry field and
6783 // pass every propagation-probe test that expected only the stale
6784 // axis's value. Peer of `m2_limits_key_consts_are_pairwise_distinct`
6785 // (d8b8b4f) and `m2_behavior_key_consts_are_pairwise_distinct`
6786 // (21fe462) on the sibling `:limits` / `:behavior` sub-slot axes.
6787 let all = [
6788 crate::render::M2_UPGRADE_FROM_KEY_FROM,
6789 crate::render::M2_UPGRADE_FROM_KEY_INSTRUCTIONS,
6790 ];
6791 for (i, a) in all.iter().enumerate() {
6792 for b in all.iter().skip(i + 1) {
6793 assert_ne!(
6794 a, b,
6795 "M2_UPGRADE_FROM_KEY_* consts must be pairwise-distinct \
6796 canonical byte-sequences — got `{a}` == `{b}`",
6797 );
6798 }
6799 }
6800 }
6801
6802 #[test]
6803 fn upgrade_instruction_serde_tag_key_matches_lifted_m2_upgrade_instruction_key_kind_const() {
6804 // Load-bearing invariant on the M2 `:upgrade-from :instructions`
6805 // per-entry OTP-appup [`UpgradeInstruction`] enum's internally-
6806 // tagged variant-discriminator key axis: the
6807 // `M2_UPGRADE_INSTRUCTION_KEY_KIND` const names the exact tag-slot
6808 // JSON key the `#[serde(tag = "kind", rename_all = "kebab-case")]`
6809 // attribute on [`UpgradeInstruction`] emits, and every downstream
6810 // consumer that navigates the serialized instruction blob to
6811 // route by variant (the caixa-core reflection-vs-serde round-trip
6812 // check in `dispatcher_registration.rs` that probes
6813 // `v.get("kind")` against every variant's expected kebab-case
6814 // tag, the future M4 admission-webhook path, any wasm-operator
6815 // dispatch step consuming the serialized instruction blob) reads
6816 // through the same `&'static str`. Serialize every variant and
6817 // pin that the const's byte-sequence appears verbatim as the
6818 // tag-slot JSON key with the expected kebab-case value — a
6819 // future accidental `tag = "type"` / `tag = "op"` /
6820 // `tag = "instruction"` rebrand at the derive attribute (any of
6821 // which would silently break every consumer probe reaching for
6822 // the stale-tag-key const) surfaces here as a build-time test
6823 // failure at `upgrade.rs`, not as an apply-time
6824 // `.get(<stale-tag-key>)` returning `None` far from the derive-
6825 // attr drift's commit.
6826 //
6827 // Same "one canonical byte-string per typed axis" discipline the
6828 // sibling `upgrade_from_entry_serde_keys_match_lifted_m2_upgrade_from_key_consts`
6829 // pin (36ffe65) established on the peer `:upgrade-from` per-entry
6830 // outer-container axis — this pin extends the discipline one
6831 // altitude deeper onto the per-instruction *tag* axis inside
6832 // each element of the `:instructions` list, completing the
6833 // typed coverage of the `:upgrade-from :instructions` dual
6834 // (key = "kind" + five variant-value tags): the five
6835 // `M2_UPGRADE_INSTRUCTION_KIND_*` consts (56120ef) pin the
6836 // per-variant kebab-case *values*; this pin pins the tag *key*
6837 // above them.
6838 let samples: [(UpgradeInstruction, &'static str); 5] = [
6839 (
6840 UpgradeInstruction::LoadModule {
6841 module: "hello-rio".into(),
6842 },
6843 crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE.trim_start_matches(':'),
6844 ),
6845 (
6846 UpgradeInstruction::StateChange {
6847 script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
6848 },
6849 crate::render::M2_UPGRADE_INSTRUCTION_KIND_STATE_CHANGE.trim_start_matches(':'),
6850 ),
6851 (
6852 UpgradeInstruction::SoftPurge {
6853 module: "hello-rio-old".into(),
6854 },
6855 crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE.trim_start_matches(':'),
6856 ),
6857 (
6858 UpgradeInstruction::Purge {
6859 module: "hello-rio-old".into(),
6860 },
6861 crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE.trim_start_matches(':'),
6862 ),
6863 (
6864 UpgradeInstruction::Restart,
6865 crate::render::M2_UPGRADE_INSTRUCTION_KIND_RESTART.trim_start_matches(':'),
6866 ),
6867 ];
6868 for (sample, expected_value) in &samples {
6869 let v: serde_json::Value = serde_json::to_value(sample).unwrap();
6870 let got = v
6871 .get(crate::render::M2_UPGRADE_INSTRUCTION_KEY_KIND)
6872 .and_then(|k| k.as_str());
6873 assert_eq!(
6874 got,
6875 Some(*expected_value),
6876 "serialized {sample:?} must carry the lifted \
6877 M2_UPGRADE_INSTRUCTION_KEY_KIND byte-sequence \
6878 ({:?}) verbatim as the tag-slot JSON key, holding the \
6879 expected kebab-case value {expected_value:?} (got: {v})",
6880 crate::render::M2_UPGRADE_INSTRUCTION_KEY_KIND,
6881 );
6882 }
6883 }
6884
6885 #[test]
6886 fn m2_upgrade_instruction_key_kind_const_is_lower_camel_case_shape() {
6887 // Shape-pin: the `M2_UPGRADE_INSTRUCTION_KEY_KIND` const must be
6888 // a lowerCamelCase byte-sequence (non-empty, ASCII-lowercase
6889 // leader, ASCII-alphanumeric only — no `snake_case` underscores,
6890 // no `kebab-case` hyphens, no `PascalCase` leading capital, no
6891 // whitespace / colons / dots) — the canonical shape a serde
6892 // internally-tagged discriminator key takes across every peer
6893 // enum in this crate. A future flip to a non-camelCase byte at
6894 // the const surfaces here at build time. Peer of
6895 // `m2_upgrade_from_key_consts_are_lower_camel_case_shape` on the
6896 // sibling per-entry outer-container axis.
6897 let key = crate::render::M2_UPGRADE_INSTRUCTION_KEY_KIND;
6898 assert!(
6899 !key.is_empty(),
6900 "M2_UPGRADE_INSTRUCTION_KEY_KIND must be non-empty (got {key:?})"
6901 );
6902 let first = key.chars().next().unwrap();
6903 assert!(
6904 first.is_ascii_lowercase(),
6905 "M2_UPGRADE_INSTRUCTION_KEY_KIND must lead with an ASCII-lowercase \
6906 byte (got {key:?}, leads with {first:?})",
6907 );
6908 assert!(
6909 key.chars().all(|c| c.is_ascii_alphanumeric()),
6910 "M2_UPGRADE_INSTRUCTION_KEY_KIND must be ASCII-alphanumeric only \
6911 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
6912 );
6913 }
6914
6915 #[test]
6916 fn m2_upgrade_instruction_key_kind_const_disjoint_from_variant_data_keys() {
6917 // Cross-axis drift-detection pin: the tag-slot key
6918 // `M2_UPGRADE_INSTRUCTION_KEY_KIND` (`"kind"`) must be
6919 // disjoint from every per-variant data-field key the
6920 // internally-tagged serialization also emits (`"module"` for
6921 // LoadModule/SoftPurge/Purge, `"script"` for StateChange). A
6922 // future accidental rebrand that collapses `tag = "kind"` onto
6923 // one of the data-field names (e.g. `tag = "module"`) would
6924 // silently corrupt every serialized LoadModule blob (the
6925 // module string and the variant tag would collide on the same
6926 // JSON key) and every consumer probe would either misread the
6927 // tag or fail to distinguish variants. Pin the disjointness at
6928 // build time. Same cross-axis discipline the sibling
6929 // `m2_upgrade_from_key_consts_are_pairwise_distinct` pin
6930 // (36ffe65) established on the outer container's own
6931 // `from`/`instructions` pair.
6932 let key = crate::render::M2_UPGRADE_INSTRUCTION_KEY_KIND;
6933 // Enumerate every per-variant data-field key across all five
6934 // variants of [`UpgradeInstruction`], routing through the two
6935 // lifted `M2_UPGRADE_INSTRUCTION_FIELD_KEY_*` byte-string consts
6936 // that name the same per-variant data-field JSON keys the
6937 // `variant_fields` reflection in
6938 // `caixa-core/tests/dispatcher_registration.rs` surfaces. A future
6939 // per-variant struct-field rebrand (`module` → `component`,
6940 // `script` → `path`) lands as an edit to exactly one const and
6941 // reaches this disjointness pin by construction — the two axes
6942 // (tag-slot key on one side, per-variant data-field keys on the
6943 // other) share one source of truth per axis.
6944 for data_field in [
6945 crate::render::M2_UPGRADE_INSTRUCTION_FIELD_KEY_MODULE,
6946 crate::render::M2_UPGRADE_INSTRUCTION_FIELD_KEY_SCRIPT,
6947 ] {
6948 assert_ne!(
6949 key, data_field,
6950 "M2_UPGRADE_INSTRUCTION_KEY_KIND (the serde `tag` slot) \
6951 must be disjoint from every UpgradeInstruction per-variant \
6952 data-field key — got tag-key {key:?} colliding with \
6953 data-field {data_field:?}, which would silently corrupt \
6954 the internally-tagged serialization",
6955 );
6956 }
6957 }
6958
6959 #[test]
6960 fn upgrade_instruction_variant_data_field_keys_match_lifted_field_key_consts() {
6961 // Load-bearing invariant on the M2 `:upgrade-from :instructions`
6962 // per-entry OTP-appup [`UpgradeInstruction`] enum's per-variant
6963 // data-field JSON key axis: the two
6964 // `M2_UPGRADE_INSTRUCTION_FIELD_KEY_*` consts (`_MODULE`,
6965 // `_SCRIPT`) name the exact per-variant field JSON keys the
6966 // `#[serde(tag = "kind", rename_all = "kebab-case")]` attribute on
6967 // [`UpgradeInstruction`] emits alongside the tag-slot key from the
6968 // sibling [`crate::render::M2_UPGRADE_INSTRUCTION_KEY_KIND`]
6969 // const — the `module: String` struct-field on
6970 // `LoadModule`/`SoftPurge`/`Purge` and the `script: PathBuf`
6971 // struct-field on `StateChange` are promoted to sibling JSON keys
6972 // at the same nesting level as the tag by the internally-tagged
6973 // serialization, and every downstream consumer that navigates the
6974 // serialized instruction blob to reach the payload (the caixa-core
6975 // reflection round-trip in `dispatcher_registration.rs` that
6976 // consults `variant_fields`, the sibling disjointness pin below,
6977 // any future wasm-operator upgrade-dispatch step consuming the
6978 // serialized instruction blob to route the per-module load /
6979 // soft-purge / purge action or the per-script state-change action)
6980 // reads through the same `&'static str`. Serialize one Module-
6981 // bearing variant and one Script-bearing variant, then pin that
6982 // each const's byte-sequence appears verbatim in the JSON emission
6983 // — a future accidental struct-field rebrand (`module: String` →
6984 // `component: String`, `script: PathBuf` → `path: PathBuf`) at
6985 // either variant surfaces here as a build-time test failure at
6986 // `upgrade.rs`, not as an apply-time `.get(<stale-field-key>)`
6987 // returning `None` far from the field-name drift's commit.
6988 //
6989 // Same "one canonical byte-string per typed axis" discipline the
6990 // sibling `upgrade_instruction_serde_tag_key_matches_lifted_m2_upgrade_instruction_key_kind_const`
6991 // pin established on the peer tag-slot key axis on the same
6992 // enum — this pin extends the discipline onto the per-variant
6993 // data-field key axis, completing the `:upgrade-from :instructions`
6994 // variant-JSON dual (tag key + tag values + per-variant field keys)
6995 // fully into caixa-core.
6996 let module_sample = UpgradeInstruction::LoadModule {
6997 module: "hello-rio".into(),
6998 };
6999 let v: serde_json::Value = serde_json::to_value(&module_sample).unwrap();
7000 assert_eq!(
7001 v.get(crate::render::M2_UPGRADE_INSTRUCTION_FIELD_KEY_MODULE)
7002 .and_then(|k| k.as_str()),
7003 Some("hello-rio"),
7004 "serialized {module_sample:?} must carry the lifted \
7005 M2_UPGRADE_INSTRUCTION_FIELD_KEY_MODULE byte-sequence \
7006 ({:?}) verbatim as the data-field JSON key holding the \
7007 module string (got: {v})",
7008 crate::render::M2_UPGRADE_INSTRUCTION_FIELD_KEY_MODULE,
7009 );
7010
7011 let script_sample = UpgradeInstruction::StateChange {
7012 script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
7013 };
7014 let v: serde_json::Value = serde_json::to_value(&script_sample).unwrap();
7015 assert_eq!(
7016 v.get(crate::render::M2_UPGRADE_INSTRUCTION_FIELD_KEY_SCRIPT)
7017 .and_then(|k| k.as_str()),
7018 Some("lib/migrations/v01-to-v02.lisp"),
7019 "serialized {script_sample:?} must carry the lifted \
7020 M2_UPGRADE_INSTRUCTION_FIELD_KEY_SCRIPT byte-sequence \
7021 ({:?}) verbatim as the data-field JSON key holding the \
7022 script path (got: {v})",
7023 crate::render::M2_UPGRADE_INSTRUCTION_FIELD_KEY_SCRIPT,
7024 );
7025 }
7026
7027 #[test]
7028 fn m2_upgrade_instruction_field_key_consts_are_lower_camel_case_shape() {
7029 // Shape-pin: every `M2_UPGRADE_INSTRUCTION_FIELD_KEY_*` const must
7030 // be a lowerCamelCase byte-sequence (non-empty, ASCII-lowercase
7031 // leader, ASCII-alphanumeric only — no `snake_case` underscores,
7032 // no `kebab-case` hyphens, no `PascalCase` leading capital, no
7033 // whitespace / colons / dots) — the canonical shape a Rust
7034 // struct-field name promoted to a JSON key by serde takes on this
7035 // internally-tagged variant surface, matching the sibling
7036 // [`crate::render::M2_UPGRADE_INSTRUCTION_KEY_KIND`] tag-slot key
7037 // shape. A future flip to a non-camelCase byte at either const
7038 // (an accidental `rename_all` regime interleave, or a struct-
7039 // field flip like `module` → `module_name`) surfaces here at
7040 // build time. Peer of
7041 // `m2_upgrade_instruction_key_kind_const_is_lower_camel_case_shape`
7042 // and `m2_upgrade_from_key_consts_are_lower_camel_case_shape` on
7043 // the sibling wire-key axes.
7044 for key in [
7045 crate::render::M2_UPGRADE_INSTRUCTION_FIELD_KEY_MODULE,
7046 crate::render::M2_UPGRADE_INSTRUCTION_FIELD_KEY_SCRIPT,
7047 ] {
7048 assert!(
7049 !key.is_empty(),
7050 "M2_UPGRADE_INSTRUCTION_FIELD_KEY_* must be non-empty (got {key:?})"
7051 );
7052 let first = key.chars().next().unwrap();
7053 assert!(
7054 first.is_ascii_lowercase(),
7055 "M2_UPGRADE_INSTRUCTION_FIELD_KEY_* must lead with an ASCII-lowercase \
7056 byte (got {key:?}, leads with {first:?})",
7057 );
7058 assert!(
7059 key.chars().all(|c| c.is_ascii_alphanumeric()),
7060 "M2_UPGRADE_INSTRUCTION_FIELD_KEY_* must be ASCII-alphanumeric only \
7061 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
7062 );
7063 }
7064 }
7065
7066 #[test]
7067 fn m2_upgrade_instruction_field_key_consts_are_pairwise_distinct() {
7068 // Cross-axis drift-detection pin: a future collapse of the two
7069 // canonical per-variant data-field byte-strings onto the same
7070 // value (e.g. an accidental copy-paste flip of
7071 // `M2_UPGRADE_INSTRUCTION_FIELD_KEY_SCRIPT` to also read
7072 // `"module"`) would silently reroute every test-side probe on one
7073 // variant's payload onto the sibling variant's payload and pass
7074 // every propagation-probe test that expected only the stale
7075 // axis's value. Peer of `m2_upgrade_from_key_consts_are_pairwise_distinct`
7076 // on the sibling per-entry outer-container axis, and of
7077 // `m2_upgrade_instruction_key_kind_const_disjoint_from_variant_data_keys`
7078 // on the sibling tag-slot key ↔ per-variant data-field key axis.
7079 let all = [
7080 crate::render::M2_UPGRADE_INSTRUCTION_FIELD_KEY_MODULE,
7081 crate::render::M2_UPGRADE_INSTRUCTION_FIELD_KEY_SCRIPT,
7082 ];
7083 for (i, a) in all.iter().enumerate() {
7084 for b in all.iter().skip(i + 1) {
7085 assert_ne!(
7086 a, b,
7087 "M2_UPGRADE_INSTRUCTION_FIELD_KEY_* consts must be pairwise-distinct \
7088 canonical byte-sequences — got `{a}` == `{b}`",
7089 );
7090 }
7091 }
7092 }
7093
7094 #[test]
7095 fn m2_upgrade_from_key_consts_are_lower_camel_case_shape() {
7096 // Shape-pin: every `M2_UPGRADE_FROM_KEY_*` const must be a
7097 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
7098 // `kebab-case` hyphens, no `PascalCase` leading capital, no
7099 // whitespace / colons / dots) — the canonical shape the
7100 // `#[serde(rename_all = "camelCase")]` derive produces on
7101 // `UpgradeFromEntry`. A future flip to a non-camelCase attribute
7102 // at the derive surfaces both here (this test fails on the
7103 // stale-constant shape) and at
7104 // `upgrade_from_entry_serde_keys_match_lifted_m2_upgrade_from_key_consts`
7105 // (that test fails on the mismatch between const and derive).
7106 // Peer of `m2_limits_key_consts_are_lower_camel_case_shape`
7107 // (d8b8b4f) and `m2_behavior_key_consts_are_lower_camel_case_shape`
7108 // (21fe462) on the sibling `:limits` / `:behavior` sub-slot axes.
7109 for key in [
7110 crate::render::M2_UPGRADE_FROM_KEY_FROM,
7111 crate::render::M2_UPGRADE_FROM_KEY_INSTRUCTIONS,
7112 ] {
7113 assert!(
7114 !key.is_empty(),
7115 "M2_UPGRADE_FROM_KEY_* must be non-empty (got {key:?})"
7116 );
7117 let first = key.chars().next().unwrap();
7118 assert!(
7119 first.is_ascii_lowercase(),
7120 "M2_UPGRADE_FROM_KEY_* must lead with an ASCII-lowercase \
7121 byte (got {key:?}, leads with {first:?})",
7122 );
7123 assert!(
7124 key.chars().all(|c| c.is_ascii_alphanumeric()),
7125 "M2_UPGRADE_FROM_KEY_* must be ASCII-alphanumeric only \
7126 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
7127 );
7128 }
7129 }
7130
7131 #[test]
7132 fn m2_upgrade_instruction_kind_consts_pin_canonical_kebab_case_labels() {
7133 // Scalar-value pin on the M2 `:upgrade-from :instructions` per-entry
7134 // OTP-appup variant-tag axis: the five canonical author-facing
7135 // kebab-case labels (`:load-module` / `:state-change` /
7136 // `:soft-purge` / `:purge` / `:restart`) the substrate's
7137 // per-variant [`UpgradeInstruction::lisp_form`] dispatch reads
7138 // from and every downstream consumer probes for verbatim. Same
7139 // scalar-value discipline the peer
7140 // `contrato_author_key_consts_pin_canonical_kebab_case_labels`
7141 // (f50c875), `m3_top_level_author_key_consts_pin_canonical_kebab_case_labels`
7142 // (882f498), `m2_top_level_author_key_consts_pin_canonical_kebab_case_labels`
7143 // (f49c8b0), and `supervisor_top_level_author_key_consts_pin_canonical_kebab_case_labels`
7144 // (be40492) established for the sibling M2 / M3 / Supervisor
7145 // top-level and sub-slot author-facing-label axes. Fail-before-
7146 // pass-after locally verified by mutating
7147 // `M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE` to `":load"` — this
7148 // pin fires as expected; restoring passes.
7149 //
7150 // A future OTP-lineage per-variant rebrand (e.g.
7151 // `:load-module` → `:load` matching Erlang's abbreviated
7152 // `code:load_module` name, `:state-change` → `:code-change`
7153 // matching Erlang's verbatim `code_change/3` callback,
7154 // `:soft-purge` → `:drain` matching a hypothetical operator-side
7155 // vocabulary flip, `:purge` → `:discard` matching a hypothetical
7156 // Elixir/Phoenix hot-reload rebrand, `:restart` → `:reboot`
7157 // matching a supervisor-tree vocabulary alignment) lands as an
7158 // edit to exactly one const, and every consumer that reaches for
7159 // the label (the [`UpgradeInstruction::lisp_form`] dispatch, the
7160 // [`validate_cleanup_singularity`] per-variant `kind:` tagger,
7161 // every [`UpgradeError`] `kind:` / `kinds:` / `other_kinds:` /
7162 // `prior_cleanup_kind:` diagnostic field, the
7163 // [`LayoutError::UpgradeViolation`] `issue:` probe in
7164 // `layout.rs`) picks it up at build time rather than at runtime
7165 // as a downstream `kind: <stale-kebab-case>` diagnostic mismatch
7166 // far from the rename's commit.
7167 assert_eq!(
7168 crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE,
7169 ":load-module"
7170 );
7171 assert_eq!(
7172 crate::render::M2_UPGRADE_INSTRUCTION_KIND_STATE_CHANGE,
7173 ":state-change"
7174 );
7175 assert_eq!(
7176 crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
7177 ":soft-purge"
7178 );
7179 assert_eq!(crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE, ":purge");
7180 assert_eq!(
7181 crate::render::M2_UPGRADE_INSTRUCTION_KIND_RESTART,
7182 ":restart"
7183 );
7184 }
7185
7186 #[test]
7187 fn m2_upgrade_instruction_kind_consts_are_pairwise_distinct() {
7188 // Cross-arm drift-detection pin on the M2
7189 // [`crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE`] /
7190 // [`crate::render::M2_UPGRADE_INSTRUCTION_KIND_STATE_CHANGE`] /
7191 // [`crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE`] /
7192 // [`crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE`] /
7193 // [`crate::render::M2_UPGRADE_INSTRUCTION_KIND_RESTART`]
7194 // closed-set OTP-appup variant-tag pentad: a future collapse
7195 // of two canonical variant byte-strings onto the same value
7196 // (an accidental copy-paste flip of
7197 // [`crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE`]
7198 // to also read `":purge"`, a per-arm rebrand that lands one
7199 // const without touching its paired peer) would silently
7200 // reroute every downstream OTP-appup dispatcher's per-
7201 // instruction branch onto the sibling arm's runtime
7202 // behavior and pass every propagation-probe test that
7203 // expected only the stale arm's tag — a `:soft-purge`
7204 // instruction (drain-then-swap: existing callers finish
7205 // under the old module, new callers land on the new one)
7206 // would come up under the `:purge` reconcile branch
7207 // (drop-existing: every in-flight caller terminates
7208 // immediately) on every hot-upgrade cycle, so a rolling
7209 // module swap would silently downgrade to a hard cutover
7210 // against its declared appup discipline, with no field
7211 // naming the instruction-tag drift root cause. Every
7212 // [`crate::UpgradeError`] diagnostic that surfaces the tag
7213 // ([`crate::UpgradeError::ModuleEmpty`] with `kind:` field,
7214 // [`crate::UpgradeError::CleanupCollision`] with `kinds:`
7215 // slice, [`crate::UpgradeError::CleanupPrecedes`] with
7216 // `prior_cleanup_kind:` field, the
7217 // [`crate::LayoutError::UpgradeViolation`] `issue:` probe in
7218 // `layout.rs`) would emit the sibling arm's stale bytes at
7219 // the operator's console, far from the source rebrand
7220 // commit. Peer of the sibling
7221 // [`crate::supervisor::tests::supervisor_estrategia_consts_are_pairwise_distinct`]
7222 // (09ffb2d) /
7223 // [`crate::supervisor::tests::supervisor_child_restart_consts_are_pairwise_distinct`]
7224 // (ccdf955) /
7225 // [`crate::kind::tests::caixa_kind_label_consts_are_pairwise_distinct`]
7226 // (d739850) distinctness pins on the sibling OTP-shape /
7227 // caixa-kind closed-set typed-enum discriminator axes —
7228 // the fifth closed-set OTP-appup / typed-enum axis to
7229 // converge on the same
7230 // "pairwise-distinct-by-construction" discipline, and the
7231 // canonical companion to the peer
7232 // [`m2_upgrade_instruction_field_key_consts_are_pairwise_distinct`]
7233 // (ff980bb) distinctness pin on the sibling internally-
7234 // tagged-JSON per-variant data-field-key axis (the tag axis
7235 // this pin covers vs. the data-field-key axis its peer
7236 // covers — two paired axes on the same
7237 // [`crate::UpgradeInstruction`] typed enum surface).
7238 //
7239 // Fail-before-pass-after locally verified by mutating
7240 // [`crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE`]
7241 // to also read `":purge"` — this pin fires as expected;
7242 // restoring passes.
7243 let all = [
7244 crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE,
7245 crate::render::M2_UPGRADE_INSTRUCTION_KIND_STATE_CHANGE,
7246 crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
7247 crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
7248 crate::render::M2_UPGRADE_INSTRUCTION_KIND_RESTART,
7249 ];
7250 for (i, a) in all.iter().enumerate() {
7251 for (j, b) in all.iter().enumerate() {
7252 if i != j {
7253 assert_ne!(
7254 a, b,
7255 "M2_UPGRADE_INSTRUCTION_KIND_* consts must be pairwise \
7256 distinct — got duplicate {a:?} at indices {i} and {j}",
7257 );
7258 }
7259 }
7260 }
7261 }
7262
7263 #[test]
7264 fn upgrade_instruction_lisp_form_routes_through_lifted_kind_consts() {
7265 // Production-through-const pin: the five per-variant labels
7266 // [`UpgradeInstruction::lisp_form`] returns route through the
7267 // lifted [`crate::render::M2_UPGRADE_INSTRUCTION_KIND_*`] consts,
7268 // so a future rebrand that reaches the const but not the
7269 // dispatch (or vice versa) surfaces here at build time rather
7270 // than at runtime as a downstream
7271 // [`UpgradeError::ModuleEmpty`] `kind: <stale-kebab-case>`
7272 // diagnostic drift far from the rename's commit. Mirror of the
7273 // peer `contrato_shape_gate_routes_through_lifted_contrato_author_key_consts`
7274 // (f50c875), `declared_mesh_slots_route_through_lifted_m3_author_key_consts`
7275 // (882f498), and `declared_servico_slots_route_through_lifted_m2_author_key_consts`
7276 // (f49c8b0) production-through-const pins on the sibling M3 /
7277 // M2 top-level slot axes.
7278 //
7279 // Fail-before-pass-after locally verified by mutating
7280 // `UpgradeInstruction::lisp_form`'s `Self::Purge` arm to return
7281 // `":purge-drift"` — this pin fires as expected; restoring
7282 // passes.
7283 let cases: &[(UpgradeInstruction, &'static str)] = &[
7284 (
7285 UpgradeInstruction::LoadModule { module: "x".into() },
7286 crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE,
7287 ),
7288 (
7289 UpgradeInstruction::StateChange {
7290 script: PathBuf::from("lib/m.lisp"),
7291 },
7292 crate::render::M2_UPGRADE_INSTRUCTION_KIND_STATE_CHANGE,
7293 ),
7294 (
7295 UpgradeInstruction::SoftPurge {
7296 module: "x-old".into(),
7297 },
7298 crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
7299 ),
7300 (
7301 UpgradeInstruction::Purge {
7302 module: "x-old".into(),
7303 },
7304 crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
7305 ),
7306 (
7307 UpgradeInstruction::Restart,
7308 crate::render::M2_UPGRADE_INSTRUCTION_KIND_RESTART,
7309 ),
7310 ];
7311 for (instr, expected) in cases {
7312 assert_eq!(
7313 instr.lisp_form(),
7314 *expected,
7315 "UpgradeInstruction::lisp_form on {instr:?} must route through the lifted \
7316 const (expected {expected:?})",
7317 );
7318 }
7319 }
7320
7321 #[test]
7322 fn upgrade_from_entry_instructions_returns_instructions_slice_byte_equal_across_permutations() {
7323 // The canonical per-`:upgrade-from :instructions` OTP-appup
7324 // migration-instruction-list slice-shape pin:
7325 // [`UpgradeFromEntry::instructions`] must return the
7326 // `:instructions` typed `Vec<UpgradeInstruction>` verbatim as
7327 // a `&[UpgradeInstruction]` slice-view over the same backing
7328 // buffer the raw `self.instructions.as_slice()` field access
7329 // borrows from, byte-equal across every representative fixture
7330 // in the accept-set — the empty slice (the "no-op upgrade" /
7331 // metadata-only sentinel the [`UpgradeFromEntry::instructions`]
7332 // field's own docstring names), the singleton slice on every
7333 // variant of the [`UpgradeInstruction`] arm-space
7334 // (`LoadModule` / `StateChange` / `SoftPurge` / `Purge` /
7335 // `Restart` — the five OTP-appup runtime-primitive variants),
7336 // and multi-instruction cohorts (the canonical
7337 // `LoadModule → StateChange → SoftPurge` OTP two-phase code-
7338 // load + state-migration triad the module doc names as the
7339 // "runs the instructions in order" example).
7340 //
7341 // Pins against a future silent detour that returned
7342 // `&Vec<UpgradeInstruction>` (which would type-check but leak
7343 // the storage-side `Vec`'s grow/push/reserve surface no
7344 // consumer of the typed view reaches for), a fresh-allocated
7345 // `Vec<UpgradeInstruction>` copy (which would type-check via
7346 // a coercion but silently break every downstream caller that
7347 // relied on the slice sharing the backing buffer's identity),
7348 // or an out-of-order or length-drifted projection (which
7349 // would silently split the paired within-entry cross-
7350 // instruction ordering gates' inputs from the peer per-
7351 // instruction shape-check loop's input, one seven-gate cohort
7352 // silently drifting from the peer gate's actual traversal
7353 // input).
7354 //
7355 // Peer of the sibling
7356 // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations`
7357 // (0dcc926) `&[WitContract]` byte-equal pin on the M3 per-
7358 // `:contratos` edge-list axis, extended onto the M2 per-
7359 // `:upgrade-from :instructions` migration-instruction-list
7360 // axis — the fifth `&[T]`-return byte-equal pin, closing the
7361 // last unlifted `Vec`-carry axis on any M2 or M3 typed slot.
7362 let fixtures: Vec<Vec<UpgradeInstruction>> = vec![
7363 Vec::new(),
7364 vec![UpgradeInstruction::LoadModule { module: "x".into() }],
7365 vec![UpgradeInstruction::StateChange {
7366 script: PathBuf::from("lib/m.lisp"),
7367 }],
7368 vec![UpgradeInstruction::SoftPurge {
7369 module: "x-old".into(),
7370 }],
7371 vec![UpgradeInstruction::Purge {
7372 module: "x-old".into(),
7373 }],
7374 vec![UpgradeInstruction::Restart],
7375 vec![
7376 UpgradeInstruction::LoadModule { module: "x".into() },
7377 UpgradeInstruction::StateChange {
7378 script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
7379 },
7380 UpgradeInstruction::SoftPurge {
7381 module: "x-old".into(),
7382 },
7383 ],
7384 ];
7385 for instructions in fixtures {
7386 let e = UpgradeFromEntry {
7387 from: "0.1.0".into(),
7388 instructions: instructions.clone(),
7389 };
7390 assert_eq!(
7391 e.instructions(),
7392 e.instructions.as_slice(),
7393 "UpgradeFromEntry::instructions must project the raw \
7394 `:instructions` `Vec<UpgradeInstruction>` verbatim as a \
7395 `&[UpgradeInstruction]` slice-view over the same backing buffer \
7396 (fixture: {instructions:?})",
7397 );
7398 assert_eq!(
7399 e.instructions().len(),
7400 instructions.len(),
7401 "UpgradeFromEntry::instructions length must match the raw \
7402 `:instructions` `Vec<UpgradeInstruction>` length (fixture: {instructions:?})",
7403 );
7404 }
7405 }
7406
7407 #[test]
7408 fn validate_reads_through_lifted_instructions_accessor() {
7409 // Three-consumer coherence pin on the lifted
7410 // [`UpgradeFromEntry::instructions`] slice-return accessor:
7411 // exercises three of the nine paired production consumers of
7412 // the per-`:upgrade-from :instructions` OTP-appup migration-
7413 // instruction-list surface through end-to-end validate() paths
7414 // that require the accessor to reach each of the fixture's
7415 // instructions.
7416 //
7417 // (1) The per-instruction shape-check fan-out
7418 // ([`UpgradeFromEntry::validate`]'s `for instr in
7419 // self.instructions()` loop): pass the well-formed load →
7420 // state-change → soft-purge triad — `validate()` must accept
7421 // it, which requires the accessor to project every entry so
7422 // each `instr.validate()` fires.
7423 //
7424 // (2) The within-entry state-change-ordering gate
7425 // ([`Self::validate_state_change_ordering`]): pass a
7426 // `((:state-change …))` singleton — `validate()` must return
7427 // [`UpgradeError::StateChangeWithoutPriorLoad`], which
7428 // requires the accessor to reach the state-change so the
7429 // no-prior-load probe fires.
7430 //
7431 // (3) The within-entry per-module cleanup-singularity gate
7432 // ([`Self::validate_cleanup_singularity`]): pass a
7433 // `((:load-module "x") (:soft-purge "x-old") (:soft-purge
7434 // "x-old"))` cohort — `validate()` must return
7435 // [`UpgradeError::DuplicateCleanup`], which requires the
7436 // accessor to iterate the whole list so the second `SoftPurge`
7437 // matches the first via the `seen` set.
7438 //
7439 // Peer of the sibling
7440 // `validate_reads_through_lifted_contratos_accessor` (0dcc926)
7441 // three-consumer coherence pin on the M3 per-`:contratos`
7442 // edge-list axis, extended onto the M2 per-`:upgrade-from
7443 // :instructions` migration-instruction-list axis.
7444
7445 // (1) accept the well-formed OTP two-phase code-load triad
7446 let well_formed = entry(
7447 "0.1.0",
7448 vec![
7449 UpgradeInstruction::LoadModule { module: "x".into() },
7450 UpgradeInstruction::StateChange {
7451 script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
7452 },
7453 UpgradeInstruction::SoftPurge {
7454 module: "x-old".into(),
7455 },
7456 ],
7457 );
7458 assert!(
7459 well_formed.validate().is_ok(),
7460 "well-formed `LoadModule → StateChange → SoftPurge` triad must accept — \
7461 the per-instruction shape-check fan-out requires the accessor to reach every entry"
7462 );
7463
7464 // (2) refuse a `((:state-change …))` singleton — the
7465 // state-change-without-prior-load gate must fire, which
7466 // requires the accessor to reach the single instruction.
7467 let no_prior_load = entry(
7468 "0.1.0",
7469 vec![UpgradeInstruction::StateChange {
7470 script: PathBuf::from("lib/m.lisp"),
7471 }],
7472 );
7473 match no_prior_load.validate() {
7474 Err(UpgradeError::StateChangeWithoutPriorLoad { .. }) => {}
7475 other => panic!(
7476 "expected StateChangeWithoutPriorLoad on a `((:state-change …))` singleton \
7477 — the within-entry state-change-ordering gate must reach the single \
7478 instruction through the lifted accessor; got: {other:?}"
7479 ),
7480 }
7481
7482 // (3) refuse a `((:load-module "x") (:soft-purge "x-old")
7483 // (:soft-purge "x-old"))` cohort — the per-module cleanup-
7484 // singularity gate must fire on the second `SoftPurge`, which
7485 // requires the accessor to iterate the whole list.
7486 let duplicate_cleanup = entry(
7487 "0.1.0",
7488 vec![
7489 UpgradeInstruction::LoadModule { module: "x".into() },
7490 UpgradeInstruction::SoftPurge {
7491 module: "x-old".into(),
7492 },
7493 UpgradeInstruction::SoftPurge {
7494 module: "x-old".into(),
7495 },
7496 ],
7497 );
7498 match duplicate_cleanup.validate() {
7499 Err(UpgradeError::DuplicateCleanup { module, .. }) => {
7500 assert_eq!(
7501 module, "x-old",
7502 "DuplicateCleanup must name the colliding module `x-old` — the per-module \
7503 cleanup-singularity gate must iterate through the lifted accessor to \
7504 match the second SoftPurge against the first via the `seen` set"
7505 );
7506 }
7507 other => panic!(
7508 "expected DuplicateCleanup on `((:load-module x) (:soft-purge x-old) \
7509 (:soft-purge x-old))` — the within-entry cleanup-singularity gate must \
7510 iterate the whole list through the lifted accessor; got: {other:?}"
7511 ),
7512 }
7513
7514 // Path::new suppresses the unused-import warning if the
7515 // outer module trims `use std::path::Path;` in a future edit.
7516 let _ = Path::new("lib/m.lisp");
7517 }
7518}