Skip to main content

type_bridge_schema_migration/
execution.rs

1//! Provider-neutral fenced migration journal and recovery contracts.
2
3use std::fmt;
4use std::future::Future;
5use std::pin::Pin;
6use std::sync::Arc;
7use std::sync::atomic::{AtomicBool, Ordering};
8use std::task::{Poll, Waker};
9use std::time::Instant;
10
11use type_bridge_contract::diagnostic::{Diagnostic, DiagnosticCategory, DiagnosticCode};
12use type_bridge_contract::fingerprint::Fingerprint;
13use type_bridge_contract::managed_scope::{ManagedScopeId, SemanticProfileFingerprint};
14use type_bridge_contract::migration::{
15    MigrationId, MigrationManifestDigest, MigrationPlanFingerprint,
16};
17use type_bridge_contract::schema_delta::ManagedSchemaState;
18use type_bridge_contract::schema_fingerprint::{
19    ManagedDeclaredIdentityFingerprint, ManagedSemanticSchemaFingerprint,
20};
21use type_bridge_contract::schema_lowering::SchemaLoweringProfileFingerprint;
22
23use crate::{
24    VerifiedMigrationApplyManifest, VerifiedMigrationApplyPlan, VerifiedMigrationRollbackManifest,
25    VerifiedMigrationRollbackPlan, VerifiedMigrationTransactionGroup,
26};
27
28const MAX_LEASE_HOLDER_BYTES: usize = 128;
29
30/// Shared maximum number of migration transaction groups in one invocation.
31pub const MAX_MIGRATION_EXECUTION_GROUPS: usize = 65_536;
32/// Shared maximum number of retained terminal backfill observations.
33pub const MAX_MIGRATION_BACKFILL_OBSERVATIONS: usize = 65_536;
34
35/// Cloneable, wakeable cancellation authority for migration operations.
36#[derive(Clone, Debug, Default)]
37pub struct MigrationCancellation {
38    inner: Arc<MigrationCancellationInner>,
39}
40
41#[derive(Debug, Default)]
42struct MigrationCancellationInner {
43    cancelled: AtomicBool,
44    waiters: std::sync::Mutex<Vec<Waker>>,
45}
46
47impl MigrationCancellation {
48    /// Request cancellation and wake every currently registered provider wait.
49    pub fn cancel(&self) {
50        if !self.inner.cancelled.swap(true, Ordering::AcqRel) {
51            let waiters = {
52                let mut waiters = self.inner.waiters.lock().expect("cancellation waiters");
53                std::mem::take(&mut *waiters)
54            };
55            for waiter in waiters {
56                waiter.wake();
57            }
58        }
59    }
60
61    /// Return whether cancellation has been requested.
62    #[must_use]
63    pub fn is_cancelled(&self) -> bool {
64        self.inner.cancelled.load(Ordering::Acquire)
65    }
66
67    /// Await cancellation without polling or spawning a worker thread.
68    pub async fn cancelled(&self) {
69        std::future::poll_fn(|context| {
70            if self.is_cancelled() {
71                return Poll::Ready(());
72            }
73            let mut waiters = self.inner.waiters.lock().expect("cancellation waiters");
74            if self.is_cancelled() {
75                return Poll::Ready(());
76            }
77            if !waiters
78                .iter()
79                .any(|waiter| waiter.will_wake(context.waker()))
80            {
81                waiters.push(context.waker().clone());
82            }
83            Poll::Pending
84        })
85        .await
86    }
87}
88
89/// Tighten-only bounded resources for one migration execution invocation.
90#[derive(Clone, Copy, Debug, Eq, PartialEq)]
91pub struct MigrationExecutionResourceLimits {
92    transaction_groups: usize,
93    backfill_observations: usize,
94}
95
96impl MigrationExecutionResourceLimits {
97    /// Construct limits clamped to the shared ceilings.
98    #[must_use]
99    pub const fn tightened(transaction_groups: usize, backfill_observations: usize) -> Self {
100        Self {
101            transaction_groups: if transaction_groups < MAX_MIGRATION_EXECUTION_GROUPS {
102                transaction_groups
103            } else {
104                MAX_MIGRATION_EXECUTION_GROUPS
105            },
106            backfill_observations: if backfill_observations < MAX_MIGRATION_BACKFILL_OBSERVATIONS {
107                backfill_observations
108            } else {
109                MAX_MIGRATION_BACKFILL_OBSERVATIONS
110            },
111        }
112    }
113
114    /// Return the maximum transaction groups admitted by this invocation.
115    pub const fn transaction_groups(self) -> usize {
116        self.transaction_groups
117    }
118
119    /// Return the maximum retained terminal backfill observations.
120    pub const fn backfill_observations(self) -> usize {
121        self.backfill_observations
122    }
123}
124
125impl Default for MigrationExecutionResourceLimits {
126    fn default() -> Self {
127        Self::tightened(
128            MAX_MIGRATION_EXECUTION_GROUPS,
129            MAX_MIGRATION_BACKFILL_OBSERVATIONS,
130        )
131    }
132}
133
134/// Immutable controls shared by apply and rollback execution.
135#[derive(Clone, Debug, Default)]
136pub struct MigrationExecutionControl {
137    cancellation: MigrationCancellation,
138    deadline: Option<Instant>,
139    resources: MigrationExecutionResourceLimits,
140}
141
142impl MigrationExecutionControl {
143    /// Bind cancellation, one absolute monotonic deadline, and tightened limits.
144    #[must_use]
145    pub const fn new(
146        cancellation: MigrationCancellation,
147        deadline: Option<Instant>,
148        resources: MigrationExecutionResourceLimits,
149    ) -> Self {
150        Self {
151            cancellation,
152            deadline,
153            resources,
154        }
155    }
156
157    /// Return the cancellation authority.
158    pub const fn cancellation(&self) -> &MigrationCancellation {
159        &self.cancellation
160    }
161
162    /// Return the absolute monotonic deadline, when bounded.
163    pub const fn deadline(&self) -> Option<Instant> {
164        self.deadline
165    }
166
167    /// Return caller-tightened resource limits.
168    pub const fn resources(&self) -> MigrationExecutionResourceLimits {
169        self.resources
170    }
171
172    /// Reject work at a safe coordinator boundary before another effect begins.
173    pub fn check(&self) -> Result<(), Diagnostic> {
174        if self.cancellation.is_cancelled() {
175            return Err(failure(
176                DiagnosticCategory::Cancelled,
177                "migration_execution_cancelled",
178                "migration execution was cancelled before the next effect",
179            ));
180        }
181        if self
182            .deadline
183            .is_some_and(|deadline| Instant::now() >= deadline)
184        {
185            return Err(failure(
186                DiagnosticCategory::ResourceLimit,
187                "migration_execution_deadline_exceeded",
188                "migration execution reached its absolute deadline before the next effect",
189            ));
190        }
191        Ok(())
192    }
193}
194
195/// Boxed future returned by provider-neutral execution stores.
196pub type ExecutionFuture<'a, T> = Pin<Box<dyn Future<Output = Result<T, Diagnostic>> + Send + 'a>>;
197
198/// A monotonically increasing store-issued migration fencing token.
199#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
200pub struct ExecutionFence(u64);
201
202impl ExecutionFence {
203    /// Construct a non-zero fence.
204    pub fn new(value: u64) -> Result<Self, Diagnostic> {
205        if value == 0 {
206            return Err(failure(
207                DiagnosticCategory::InvalidContract,
208                "migration_execution_zero_fence",
209                "migration execution fences must be non-zero",
210            ));
211        }
212        Ok(Self(value))
213    }
214
215    /// Return the numeric fence value.
216    pub const fn get(self) -> u64 {
217        self.0
218    }
219
220    /// Derive the next strictly greater fence without wrapping.
221    pub fn checked_successor(self) -> Result<Self, Diagnostic> {
222        let value = self.0.checked_add(1).ok_or_else(|| {
223            failure(
224                DiagnosticCategory::ResourceLimit,
225                "migration_execution_fence_exhausted",
226                "migration execution fence range is exhausted",
227            )
228        })?;
229        Self::new(value)
230    }
231}
232
233/// One durable managed migration scope.
234#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
235pub struct ExecutionScope(ManagedScopeId);
236
237impl ExecutionScope {
238    /// Bind execution to an existing managed-scope identity.
239    pub const fn new(scope: ManagedScopeId) -> Self {
240        Self(scope)
241    }
242
243    /// Return the managed-scope identity.
244    pub const fn managed_scope_id(&self) -> &ManagedScopeId {
245        &self.0
246    }
247}
248
249/// Caller-supplied lease holder identity with no machine-derived garnish.
250#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
251pub struct LeaseHolderId(String);
252
253impl LeaseHolderId {
254    /// Validate a bounded canonical holder label.
255    pub fn new(value: impl Into<String>) -> Result<Self, Diagnostic> {
256        let value = value.into();
257        if value.is_empty()
258            || value.len() > MAX_LEASE_HOLDER_BYTES
259            || !value
260                .bytes()
261                .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'))
262        {
263            return Err(failure(
264                DiagnosticCategory::InvalidContract,
265                "migration_execution_invalid_holder",
266                "lease holder must be bounded non-empty ASCII [A-Za-z0-9._-]",
267            ));
268        }
269        Ok(Self(value))
270    }
271
272    /// Return the canonical holder label.
273    pub fn as_str(&self) -> &str {
274        &self.0
275    }
276}
277
278/// Store-issued authority to mutate one migration scope.
279#[derive(Clone, Debug)]
280pub struct MigrationLease {
281    scope: ExecutionScope,
282    holder: LeaseHolderId,
283    fence: ExecutionFence,
284    local_binding: Option<ExecutionBindingToken>,
285}
286
287/// Opaque, process-local identity shared by one provider/store execution pair.
288///
289/// The token is deliberately absent from canonical and persisted migration
290/// records. Provider-neutral stores continue to issue unbound leases through
291/// [`MigrationLease::new`]; provider adapters that require local composition
292/// integrity can mint a token and use [`MigrationLease::new_bound`].
293#[doc(hidden)]
294#[derive(Clone)]
295pub struct ExecutionBindingToken(Arc<()>);
296
297impl ExecutionBindingToken {
298    /// Mint one fresh, unforgeable process-local identity.
299    #[doc(hidden)]
300    #[must_use]
301    pub fn fresh() -> Self {
302        Self(Arc::new(()))
303    }
304
305    fn matches(&self, other: &Self) -> bool {
306        Arc::ptr_eq(&self.0, &other.0)
307    }
308}
309
310impl fmt::Debug for ExecutionBindingToken {
311    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
312        formatter.write_str("ExecutionBindingToken([OPAQUE])")
313    }
314}
315
316impl MigrationLease {
317    /// Construct an unbound lease returned by a provider-neutral store.
318    pub const fn new(scope: ExecutionScope, holder: LeaseHolderId, fence: ExecutionFence) -> Self {
319        Self {
320            scope,
321            holder,
322            fence,
323            local_binding: None,
324        }
325    }
326
327    /// Construct a lease carrying one process-local provider/store binding.
328    #[doc(hidden)]
329    #[must_use]
330    pub fn new_bound(
331        scope: ExecutionScope,
332        holder: LeaseHolderId,
333        fence: ExecutionFence,
334        local_binding: ExecutionBindingToken,
335    ) -> Self {
336        Self {
337            scope,
338            holder,
339            fence,
340            local_binding: Some(local_binding),
341        }
342    }
343
344    /// Return whether this lease carries the exact supplied local binding.
345    #[doc(hidden)]
346    #[must_use]
347    pub fn is_bound_to(&self, expected: &ExecutionBindingToken) -> bool {
348        self.local_binding
349            .as_ref()
350            .is_some_and(|actual| actual.matches(expected))
351    }
352
353    /// Return the leased scope.
354    pub const fn scope(&self) -> &ExecutionScope {
355        &self.scope
356    }
357
358    /// Return the holder identity.
359    pub const fn holder(&self) -> &LeaseHolderId {
360        &self.holder
361    }
362
363    /// Return the store-issued fence.
364    pub const fn fence(&self) -> ExecutionFence {
365        self.fence
366    }
367}
368
369impl PartialEq for MigrationLease {
370    fn eq(&self, other: &Self) -> bool {
371        self.scope == other.scope
372            && self.holder == other.holder
373            && self.fence == other.fence
374            && match (&self.local_binding, &other.local_binding) {
375                (None, None) => true,
376                (Some(left), Some(right)) => left.matches(right),
377                (None, Some(_)) | (Some(_), None) => false,
378            }
379    }
380}
381
382impl Eq for MigrationLease {}
383
384/// Commit certainty owned by the migration journal layer.
385///
386/// Provider adapters must map absent certainty information to [`Self::Unknown`].
387/// Only an explicit provider proof that commit could not have occurred may map
388/// to [`Self::DefinitelyAborted`].
389#[derive(Clone, Copy, Debug, Eq, PartialEq)]
390pub enum GroupCommitCertainty {
391    /// The provider proves that the group transaction did not commit.
392    DefinitelyAborted,
393    /// The provider cannot determine whether the group transaction committed.
394    Unknown,
395}
396
397impl GroupCommitCertainty {
398    /// Convert certainty into its durable journal event.
399    pub const fn journal_event(self) -> GroupJournalEventKind {
400        match self {
401            Self::DefinitelyAborted => GroupJournalEventKind::DefinitelyAborted,
402            Self::Unknown => GroupJournalEventKind::CommitOutcomeUnknown,
403        }
404    }
405}
406
407/// Durable commit-boundary event vocabulary for one transaction group.
408#[derive(Clone, Copy, Debug, Eq, PartialEq)]
409pub enum GroupJournalEventKind {
410    /// The group statements completed and the commit call is about to begin.
411    BeforeCommit,
412    /// The provider commit succeeded and exact live target semantics were observed.
413    Committed,
414    /// The commit response cannot prove whether durability occurred.
415    CommitOutcomeUnknown,
416    /// The provider proves that the transaction did not commit.
417    DefinitelyAborted,
418    /// An empty formal-only group advanced without a provider transaction.
419    FormalOnlyAdvanced,
420}
421
422/// Optional live managed-semantic evidence used during recovery.
423#[derive(Clone, Debug, Eq, PartialEq)]
424pub enum GroupRecoveryObservation {
425    /// The provider cannot supply a trustworthy managed-semantic observation.
426    Unavailable,
427    /// Exact live managed semantics observed under the current fence.
428    ManagedSemantics(ManagedSemanticSchemaFingerprint),
429}
430
431/// Fail-closed recovery decision for one positional transaction group.
432#[derive(Clone, Copy, Debug, Eq, PartialEq)]
433pub enum GroupRecoveryDecision {
434    /// The group is proven absent and may execute under the current fence.
435    ExecuteNormally,
436    /// The target is proven reached and only the journal checkpoint needs repair.
437    RepairCheckpoint,
438    /// Evidence is ambiguous or contradictory and requires verified operator action.
439    RequiresExplicitRecovery,
440}
441
442/// Direction of one closed backfill program at execution time.
443#[derive(Clone, Copy, Debug, Eq, PartialEq)]
444pub enum BackfillExecutionDirection {
445    /// Execute the canonical forward data program.
446    Forward,
447    /// Execute its independently verified reverse program.
448    Reverse,
449}
450
451/// Bounded aggregate counts from a completely verified backfill execution.
452#[derive(Clone, Copy, Debug, Eq, PartialEq)]
453pub struct BackfillExecutionCounts {
454    matched: u64,
455    changed: u64,
456    skipped: u64,
457    transaction_groups: u32,
458}
459
460impl BackfillExecutionCounts {
461    /// Construct internally consistent terminal counts.
462    pub fn new(
463        matched: u64,
464        changed: u64,
465        skipped: u64,
466        transaction_groups: u32,
467    ) -> Result<Self, Diagnostic> {
468        if transaction_groups == 0 {
469            return Err(failure(
470                DiagnosticCategory::InvalidContract,
471                "migration_backfill_zero_transaction_groups",
472                "terminal backfill evidence must include at least one transaction group",
473            ));
474        }
475        if changed.checked_add(skipped) != Some(matched) {
476            return Err(failure(
477                DiagnosticCategory::InvalidContract,
478                "migration_backfill_count_mismatch",
479                "backfill matched count must equal changed plus skipped counts",
480            ));
481        }
482        Ok(Self {
483            matched,
484            changed,
485            skipped,
486            transaction_groups,
487        })
488    }
489
490    /// Return the number of source rows selected by the closed plan.
491    pub const fn matched(self) -> u64 {
492        self.matched
493    }
494
495    /// Return the number of destination rows changed.
496    pub const fn changed(self) -> u64 {
497        self.changed
498    }
499
500    /// Return the number of already-equal rows skipped idempotently.
501    pub const fn skipped(self) -> u64 {
502        self.skipped
503    }
504
505    /// Return the number of committed deterministic transaction groups.
506    pub const fn transaction_groups(self) -> u32 {
507        self.transaction_groups
508    }
509}
510
511/// Exact terminal proof that one closed backfill program satisfies its postcondition.
512#[derive(Clone, Debug, Eq, PartialEq)]
513pub struct BackfillCompletionEvidence {
514    plan_fingerprint: Fingerprint,
515    direction: BackfillExecutionDirection,
516    counts: BackfillExecutionCounts,
517}
518
519impl BackfillCompletionEvidence {
520    /// Bind terminal counts to one exact canonical plan and execution direction.
521    #[must_use]
522    pub const fn new(
523        plan_fingerprint: Fingerprint,
524        direction: BackfillExecutionDirection,
525        counts: BackfillExecutionCounts,
526    ) -> Self {
527        Self {
528            plan_fingerprint,
529            direction,
530            counts,
531        }
532    }
533
534    /// Return the exact canonical backfill-plan identity.
535    pub const fn plan_fingerprint(&self) -> &Fingerprint {
536        &self.plan_fingerprint
537    }
538
539    /// Return whether the forward or checked reverse program completed.
540    pub const fn direction(&self) -> BackfillExecutionDirection {
541        self.direction
542    }
543
544    /// Return internally consistent aggregate counts.
545    pub const fn counts(&self) -> BackfillExecutionCounts {
546        self.counts
547    }
548}
549
550/// Fresh provider observation of one exact backfill postcondition.
551#[derive(Clone, Debug, Eq, PartialEq)]
552pub enum BackfillRecoveryObservation {
553    /// No trustworthy data observation is available.
554    Unavailable,
555    /// The exact postcondition is not currently satisfied.
556    Incomplete,
557    /// The exact plan and direction have a verified terminal postcondition.
558    Complete(BackfillCompletionEvidence),
559}
560
561/// Decide whether a complete backfill may execute or only repair its checkpoint.
562///
563/// Unlike schema groups, an incomplete data observation after a before-commit
564/// or unknown-commit event cannot prove that no partition committed. Automatic
565/// replay therefore remains forbidden until partition checkpoints are present.
566/// With no prior event, both incomplete and already-complete postconditions are
567/// safe to execute: the journal proves that execution has never begun, and an
568/// already-complete closed backfill is a deterministic no-op.
569pub fn decide_backfill_recovery(
570    last_event: Option<GroupJournalEventKind>,
571    observation: &BackfillRecoveryObservation,
572    expected_plan: &Fingerprint,
573    expected_direction: BackfillExecutionDirection,
574) -> GroupRecoveryDecision {
575    let complete = matches!(
576        observation,
577        BackfillRecoveryObservation::Complete(evidence)
578            if evidence.plan_fingerprint() == expected_plan
579                && evidence.direction() == expected_direction
580    );
581    match last_event {
582        None if matches!(
583            observation,
584            BackfillRecoveryObservation::Incomplete | BackfillRecoveryObservation::Complete(_)
585        ) =>
586        {
587            GroupRecoveryDecision::ExecuteNormally
588        }
589        Some(GroupJournalEventKind::DefinitelyAborted)
590            if matches!(observation, BackfillRecoveryObservation::Incomplete) =>
591        {
592            GroupRecoveryDecision::ExecuteNormally
593        }
594        Some(
595            GroupJournalEventKind::BeforeCommit
596            | GroupJournalEventKind::CommitOutcomeUnknown
597            | GroupJournalEventKind::Committed,
598        ) if complete => GroupRecoveryDecision::RepairCheckpoint,
599        _ => GroupRecoveryDecision::RequiresExplicitRecovery,
600    }
601}
602
603/// Decide recovery from durable event and freshly observed managed semantics.
604///
605/// Equal source and target fingerprints are intentionally uninformative for
606/// unknown commit outcomes. They never authorize replay or checkpoint repair.
607pub fn decide_group_recovery(
608    last_event: Option<GroupJournalEventKind>,
609    observation: &GroupRecoveryObservation,
610    source: &ManagedSemanticSchemaFingerprint,
611    target: &ManagedSemanticSchemaFingerprint,
612) -> GroupRecoveryDecision {
613    let distinct = source != target;
614    let observed = match observation {
615        GroupRecoveryObservation::Unavailable => ObservedRelation::Unavailable,
616        GroupRecoveryObservation::ManagedSemantics(value) if value == source && value == target => {
617            ObservedRelation::Both
618        }
619        GroupRecoveryObservation::ManagedSemantics(value) if value == source => {
620            ObservedRelation::Source
621        }
622        GroupRecoveryObservation::ManagedSemantics(value) if value == target => {
623            ObservedRelation::Target
624        }
625        GroupRecoveryObservation::ManagedSemantics(_) => ObservedRelation::Neither,
626    };
627    match (last_event, distinct, observed) {
628        (None, true, ObservedRelation::Source)
629        | (Some(GroupJournalEventKind::DefinitelyAborted), true, ObservedRelation::Source)
630        | (None, false, ObservedRelation::Both)
631        | (Some(GroupJournalEventKind::DefinitelyAborted), false, ObservedRelation::Both) => {
632            GroupRecoveryDecision::ExecuteNormally
633        }
634        (
635            Some(GroupJournalEventKind::BeforeCommit | GroupJournalEventKind::CommitOutcomeUnknown),
636            true,
637            ObservedRelation::Source,
638        ) => GroupRecoveryDecision::ExecuteNormally,
639        (
640            Some(GroupJournalEventKind::BeforeCommit | GroupJournalEventKind::CommitOutcomeUnknown),
641            true,
642            ObservedRelation::Target,
643        )
644        | (Some(GroupJournalEventKind::Committed), true, ObservedRelation::Target)
645        | (
646            Some(GroupJournalEventKind::Committed | GroupJournalEventKind::FormalOnlyAdvanced),
647            false,
648            ObservedRelation::Both,
649        ) => GroupRecoveryDecision::RepairCheckpoint,
650        _ => GroupRecoveryDecision::RequiresExplicitRecovery,
651    }
652}
653
654#[derive(Clone, Copy, Debug, Eq, PartialEq)]
655enum ObservedRelation {
656    Source,
657    Target,
658    Both,
659    Neither,
660    Unavailable,
661}
662
663/// Store-assigned monotonic ordering identity for journal entries.
664#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
665pub struct JournalSequence(u64);
666
667impl JournalSequence {
668    /// Construct a non-zero journal sequence.
669    pub fn new(value: u64) -> Result<Self, Diagnostic> {
670        if value == 0 {
671            return Err(failure(
672                DiagnosticCategory::InvalidContract,
673                "migration_execution_zero_sequence",
674                "journal sequence numbers must be non-zero",
675            ));
676        }
677        Ok(Self(value))
678    }
679
680    /// Return the numeric sequence value.
681    pub const fn get(self) -> u64 {
682        self.0
683    }
684}
685
686/// One record after the store atomically assigns its ordering sequence.
687#[derive(Clone, Debug, Eq, PartialEq)]
688pub struct JournalEntry<T> {
689    sequence: JournalSequence,
690    record: T,
691}
692
693impl<T> JournalEntry<T> {
694    /// Attach a sequence allocated by the authoritative store.
695    pub const fn from_store(sequence: JournalSequence, record: T) -> Self {
696        Self { sequence, record }
697    }
698
699    /// Return the store ordering sequence.
700    pub const fn sequence(&self) -> JournalSequence {
701        self.sequence
702    }
703
704    /// Return the trusted record.
705    pub const fn record(&self) -> &T {
706        &self.record
707    }
708
709    /// Consume the envelope and return its record.
710    pub fn into_record(self) -> T {
711        self.record
712    }
713}
714
715/// One trusted, still-open plan and its ordered group events.
716#[derive(Clone, Debug, Eq, PartialEq)]
717pub struct OpenPlanRecord {
718    plan: JournalEntry<PlanRecord>,
719    events: Vec<JournalEntry<GroupEventRecord>>,
720    backfill_events: Vec<JournalEntry<BackfillEventRecord>>,
721}
722
723impl OpenPlanRecord {
724    /// Rebuild store output while checking sequence, scope, fence, and manifest binding.
725    ///
726    /// The plan retains its original fence while recovery events may be written
727    /// under later fences. Event fences therefore must be monotonic and no older
728    /// than the plan fence; requiring equality would hide durable recovery work
729    /// after the lease rolls forward.
730    pub fn from_store(
731        plan: JournalEntry<PlanRecord>,
732        events: Vec<JournalEntry<GroupEventRecord>>,
733    ) -> Result<Self, Diagnostic> {
734        Self::from_store_with_backfills(plan, events, Vec::new())
735    }
736
737    /// Rebuild store output including independently journaled data-step events.
738    pub fn from_store_with_backfills(
739        plan: JournalEntry<PlanRecord>,
740        events: Vec<JournalEntry<GroupEventRecord>>,
741        backfill_events: Vec<JournalEntry<BackfillEventRecord>>,
742    ) -> Result<Self, Diagnostic> {
743        let mut previous = plan.sequence();
744        let mut previous_fence = plan.record().fence();
745        let mut ordered: Vec<(
746            JournalSequence,
747            ExecutionFence,
748            &MigrationId,
749            MigrationManifestDigest,
750        )> = events
751            .iter()
752            .map(|event| {
753                (
754                    event.sequence(),
755                    event.record().fence(),
756                    event.record().migration_id(),
757                    event.record().manifest_digest(),
758                )
759            })
760            .chain(backfill_events.iter().map(|event| {
761                (
762                    event.sequence(),
763                    event.record().fence(),
764                    event.record().migration_id(),
765                    event.record().manifest_digest(),
766                )
767            }))
768            .collect();
769        ordered.sort_by_key(|event| event.0);
770        for (sequence, fence, migration_id, manifest_digest) in ordered {
771            let manifest_index = plan
772                .record()
773                .manifest_digests()
774                .iter()
775                .position(|digest| digest == &manifest_digest);
776            if sequence <= previous
777                || fence < previous_fence
778                || manifest_index.is_none_or(|index| {
779                    plan.record().migration_ids().get(index) != Some(migration_id)
780                })
781            {
782                return Err(failure(
783                    DiagnosticCategory::Integrity,
784                    "migration_execution_invalid_open_plan",
785                    "loaded open-plan events are not ordered and bound to the plan",
786                ));
787            }
788            previous = sequence;
789            previous_fence = fence;
790        }
791        if events
792            .iter()
793            .any(|event| event.record().scope() != plan.record().scope())
794            || backfill_events
795                .iter()
796                .any(|event| event.record().scope() != plan.record().scope())
797        {
798            return Err(failure(
799                DiagnosticCategory::Integrity,
800                "migration_execution_invalid_open_plan",
801                "loaded open-plan events are not bound to the plan scope",
802            ));
803        }
804        Ok(Self {
805            plan,
806            events,
807            backfill_events,
808        })
809    }
810
811    /// Return the sequenced plan record.
812    pub const fn plan(&self) -> &JournalEntry<PlanRecord> {
813        &self.plan
814    }
815
816    /// Return ordered sequenced group events.
817    pub fn events(&self) -> &[JournalEntry<GroupEventRecord>] {
818        &self.events
819    }
820
821    /// Return ordered sequenced backfill events.
822    pub fn backfill_events(&self) -> &[JournalEntry<BackfillEventRecord>] {
823        &self.backfill_events
824    }
825}
826
827/// Identity-only journal record for one complete verified apply plan.
828#[derive(Clone, Debug, Eq, PartialEq)]
829pub struct PlanRecord {
830    scope: ExecutionScope,
831    fence: ExecutionFence,
832    source_applied: Vec<MigrationId>,
833    source_frontier: Vec<MigrationId>,
834    target_frontier: Vec<MigrationId>,
835    migration_ids: Vec<MigrationId>,
836    manifest_digests: Vec<MigrationManifestDigest>,
837    manifest_plan_fingerprints: Vec<MigrationPlanFingerprint>,
838    source_declared: ManagedDeclaredIdentityFingerprint,
839    target_declared: ManagedDeclaredIdentityFingerprint,
840    source_semantics: ManagedSemanticSchemaFingerprint,
841    target_semantics: ManagedSemanticSchemaFingerprint,
842    semantic_profile: SemanticProfileFingerprint,
843    lowering_profile: SchemaLoweringProfileFingerprint,
844    observed_live_source: ManagedSemanticSchemaFingerprint,
845}
846
847impl PlanRecord {
848    /// Bind a fresh-lease ledger and live-state precondition to verified plan identities.
849    pub fn from_verified_plan(
850        lease: &MigrationLease,
851        plan: &VerifiedMigrationApplyPlan,
852        observed_applied_migrations: &[MigrationId],
853        observed_live_source: &ManagedSchemaState,
854    ) -> Result<Self, Diagnostic> {
855        let source = plan.source_state().ok_or_else(|| {
856            failure(
857                DiagnosticCategory::InvalidContract,
858                "migration_execution_empty_plan",
859                "an executable migration plan requires a source state",
860            )
861        })?;
862        let target = plan.target_state().ok_or_else(|| {
863            failure(
864                DiagnosticCategory::InvalidContract,
865                "migration_execution_empty_plan",
866                "an executable migration plan requires a target state",
867            )
868        })?;
869        let first = plan.migrations().first().ok_or_else(|| {
870            failure(
871                DiagnosticCategory::InvalidContract,
872                "migration_execution_empty_plan",
873                "an executable migration plan requires at least one manifest",
874            )
875        })?;
876        if observed_applied_migrations != plan.applied_migrations() {
877            return Err(failure(
878                DiagnosticCategory::Integrity,
879                "migration_execution_stale_applied_set",
880                "applied ledger changed after migration planning; rebuild the plan",
881            ));
882        }
883        if observed_live_source != source {
884            return Err(failure(
885                DiagnosticCategory::Integrity,
886                "migration_execution_stale_source_state",
887                "live managed state differs from the planned source; rebuild the plan",
888            ));
889        }
890        let scope = ExecutionScope::new(source.scope().id().clone());
891        if lease.scope() != &scope || target.scope() != source.scope() {
892            return Err(failure(
893                DiagnosticCategory::Integrity,
894                "migration_execution_scope_mismatch",
895                "lease, source, and target must bind the same managed scope",
896            ));
897        }
898        let semantic_profile = first.manifest().semantic_profile().fingerprint().clone();
899        let lowering_profile = first.manifest().lowering_profile().fingerprint().clone();
900        // The record binds the first manifest's profile. A plan replaying a
901        // bridged history crosses the profile only at the bridge, which moves
902        // from exactly the profile in force before it.
903        let mut current = (&semantic_profile, &lowering_profile);
904        for migration in plan.migrations() {
905            let manifest = migration.manifest();
906            if let Some(bridge) = manifest.profile_bridge()
907                && bridge.from_semantic_profile().fingerprint() == current.0
908                && bridge.from_lowering_profile().fingerprint() == current.1
909            {
910                current = (
911                    manifest.semantic_profile().fingerprint(),
912                    manifest.lowering_profile().fingerprint(),
913                );
914            }
915            if manifest.managed_scope().id() != scope.managed_scope_id()
916                || manifest.semantic_profile().fingerprint() != current.0
917                || manifest.lowering_profile().fingerprint() != current.1
918            {
919                return Err(failure(
920                    DiagnosticCategory::Integrity,
921                    "migration_execution_plan_binding_mismatch",
922                    "planned manifests do not share exact scope and profile bindings",
923                ));
924            }
925        }
926        Ok(Self {
927            scope,
928            fence: lease.fence(),
929            source_applied: plan.applied_migrations().to_vec(),
930            source_frontier: plan.applied_frontier().to_vec(),
931            target_frontier: plan.target_frontier().to_vec(),
932            migration_ids: plan
933                .migrations()
934                .iter()
935                .map(|migration| migration.manifest().id().clone())
936                .collect(),
937            manifest_digests: plan
938                .migrations()
939                .iter()
940                .map(VerifiedMigrationApplyManifest::digest)
941                .collect(),
942            manifest_plan_fingerprints: plan
943                .migrations()
944                .iter()
945                .map(|migration| migration.manifest().plan_fingerprint().clone())
946                .collect(),
947            source_declared: source.managed_declared_identity().clone(),
948            target_declared: target.managed_declared_identity().clone(),
949            source_semantics: source.managed_semantic_schema().clone(),
950            target_semantics: target.managed_semantic_schema().clone(),
951            semantic_profile,
952            lowering_profile,
953            observed_live_source: observed_live_source.managed_semantic_schema().clone(),
954        })
955    }
956
957    /// Return the execution scope.
958    pub const fn scope(&self) -> &ExecutionScope {
959        &self.scope
960    }
961    /// Return the fence bound into this record.
962    pub const fn fence(&self) -> ExecutionFence {
963        self.fence
964    }
965    /// Return the planned source frontier.
966    pub fn source_frontier(&self) -> &[MigrationId] {
967        &self.source_frontier
968    }
969    /// Return the complete canonically ordered source applied set.
970    pub fn source_applied(&self) -> &[MigrationId] {
971        &self.source_applied
972    }
973    /// Return the planned target frontier.
974    pub fn target_frontier(&self) -> &[MigrationId] {
975        &self.target_frontier
976    }
977    /// Return ordered migration identities.
978    pub fn migration_ids(&self) -> &[MigrationId] {
979        &self.migration_ids
980    }
981    /// Return ordered canonical manifest digests.
982    pub fn manifest_digests(&self) -> &[MigrationManifestDigest] {
983        &self.manifest_digests
984    }
985    /// Return ordered manifest plan fingerprints.
986    pub fn manifest_plan_fingerprints(&self) -> &[MigrationPlanFingerprint] {
987        &self.manifest_plan_fingerprints
988    }
989    /// Return planned source managed-declared identity.
990    pub const fn source_declared(&self) -> &ManagedDeclaredIdentityFingerprint {
991        &self.source_declared
992    }
993    /// Return planned target managed-declared identity.
994    pub const fn target_declared(&self) -> &ManagedDeclaredIdentityFingerprint {
995        &self.target_declared
996    }
997    /// Return planned source managed semantics.
998    pub const fn source_semantics(&self) -> &ManagedSemanticSchemaFingerprint {
999        &self.source_semantics
1000    }
1001    /// Return planned target managed semantics.
1002    pub const fn target_semantics(&self) -> &ManagedSemanticSchemaFingerprint {
1003        &self.target_semantics
1004    }
1005    /// Return semantic-profile content identity.
1006    pub const fn semantic_profile(&self) -> &SemanticProfileFingerprint {
1007        &self.semantic_profile
1008    }
1009    /// Return lowering-registry content identity.
1010    pub const fn lowering_profile(&self) -> &SchemaLoweringProfileFingerprint {
1011        &self.lowering_profile
1012    }
1013    /// Return the pre-mutation observed source semantics.
1014    pub const fn observed_live_source(&self) -> &ManagedSemanticSchemaFingerprint {
1015        &self.observed_live_source
1016    }
1017}
1018
1019/// Identity-only journal event for one verified transaction group.
1020#[derive(Clone, Debug, Eq, PartialEq)]
1021pub struct GroupEventRecord {
1022    scope: ExecutionScope,
1023    fence: ExecutionFence,
1024    manifest_digest: MigrationManifestDigest,
1025    migration_id: MigrationId,
1026    group_ordinal: u32,
1027    first_step_index: u32,
1028    schema_delta_step_index: u32,
1029    end_step_index: u32,
1030    kind: GroupJournalEventKind,
1031    observed_target: Option<ManagedSemanticSchemaFingerprint>,
1032}
1033
1034impl GroupEventRecord {
1035    /// Derive a positional event from exact verified apply evidence.
1036    pub fn new(
1037        lease: &MigrationLease,
1038        migration: &VerifiedMigrationApplyManifest,
1039        group: &VerifiedMigrationTransactionGroup,
1040        kind: GroupJournalEventKind,
1041        observed_target: Option<ManagedSemanticSchemaFingerprint>,
1042    ) -> Result<Self, Diagnostic> {
1043        if migration.transaction_groups().get(group.ordinal()) != Some(group) {
1044            return Err(failure(
1045                DiagnosticCategory::Integrity,
1046                "migration_execution_foreign_group",
1047                "transaction group does not belong to the supplied verified manifest",
1048            ));
1049        }
1050        let step = migration
1051            .steps()
1052            .get(group.schema_delta_step_index())
1053            .ok_or_else(|| {
1054                failure(
1055                    DiagnosticCategory::Integrity,
1056                    "migration_execution_group_position_mismatch",
1057                    "transaction group delta position is outside the verified manifest",
1058                )
1059            })?;
1060        let delta = step
1061            .step()
1062            .as_schema_delta()
1063            .ok_or_else(|| {
1064                failure(
1065                    DiagnosticCategory::Integrity,
1066                    "migration_execution_group_position_mismatch",
1067                    "transaction group does not terminate in a schema delta",
1068                )
1069            })?
1070            .delta();
1071        let lowering = step.lowering().ok_or_else(|| {
1072            failure(
1073                DiagnosticCategory::Integrity,
1074                "migration_execution_group_lowering_missing",
1075                "transaction group delta has no verified lowering",
1076            )
1077        })?;
1078        let scope = ExecutionScope::new(migration.manifest().managed_scope().id().clone());
1079        if lease.scope() != &scope {
1080            return Err(failure(
1081                DiagnosticCategory::Integrity,
1082                "migration_execution_scope_mismatch",
1083                "lease scope differs from the verified migration scope",
1084            ));
1085        }
1086        match kind {
1087            GroupJournalEventKind::Committed
1088                if observed_target.as_ref() == Some(delta.target().managed_semantic_schema()) => {}
1089            GroupJournalEventKind::Committed => {
1090                return Err(failure(
1091                    DiagnosticCategory::Integrity,
1092                    "migration_execution_commit_evidence_mismatch",
1093                    "committed event requires the exact observed target semantics",
1094                ));
1095            }
1096            GroupJournalEventKind::FormalOnlyAdvanced
1097                if observed_target.is_none()
1098                    && group.assertion_count() == 0
1099                    && lowering.units().is_empty()
1100                    && delta.source().managed_semantic_schema()
1101                        == delta.target().managed_semantic_schema() => {}
1102            GroupJournalEventKind::FormalOnlyAdvanced => {
1103                return Err(failure(
1104                    DiagnosticCategory::InvalidContract,
1105                    "migration_execution_invalid_formal_advance",
1106                    "formal-only advancement requires an assertion-free empty equal-semantic group",
1107                ));
1108            }
1109            _ if observed_target.is_none() => {}
1110            _ => {
1111                return Err(failure(
1112                    DiagnosticCategory::InvalidContract,
1113                    "migration_execution_unexpected_observation",
1114                    "only committed events may carry observed target semantics",
1115                ));
1116            }
1117        }
1118        Ok(Self {
1119            scope,
1120            fence: lease.fence(),
1121            manifest_digest: migration.digest(),
1122            migration_id: migration.manifest().id().clone(),
1123            group_ordinal: position(group.ordinal())?,
1124            first_step_index: position(group.first_step_index())?,
1125            schema_delta_step_index: position(group.schema_delta_step_index())?,
1126            end_step_index: position(group.end_step_index())?,
1127            kind,
1128            observed_target,
1129        })
1130    }
1131
1132    /// Return the execution scope.
1133    pub const fn scope(&self) -> &ExecutionScope {
1134        &self.scope
1135    }
1136    /// Return the event fence.
1137    pub const fn fence(&self) -> ExecutionFence {
1138        self.fence
1139    }
1140    /// Return the canonical manifest digest.
1141    pub const fn manifest_digest(&self) -> MigrationManifestDigest {
1142        self.manifest_digest
1143    }
1144    /// Return the migration identity.
1145    pub const fn migration_id(&self) -> &MigrationId {
1146        &self.migration_id
1147    }
1148    /// Return the group ordinal.
1149    pub const fn group_ordinal(&self) -> u32 {
1150        self.group_ordinal
1151    }
1152    /// Return the first group step index.
1153    pub const fn first_step_index(&self) -> u32 {
1154        self.first_step_index
1155    }
1156    /// Return the terminal delta step index.
1157    pub const fn schema_delta_step_index(&self) -> u32 {
1158        self.schema_delta_step_index
1159    }
1160    /// Return the exclusive group step end.
1161    pub const fn end_step_index(&self) -> u32 {
1162        self.end_step_index
1163    }
1164    /// Return the event kind.
1165    pub const fn kind(&self) -> GroupJournalEventKind {
1166        self.kind
1167    }
1168    /// Return exact target evidence carried only by committed events.
1169    pub const fn observed_target(&self) -> Option<&ManagedSemanticSchemaFingerprint> {
1170        self.observed_target.as_ref()
1171    }
1172}
1173
1174/// Durable positional event for one exact forward or reverse backfill step.
1175///
1176/// Data effects cannot be inferred from unchanged schema semantics. This
1177/// record therefore carries the canonical plan identity on every boundary and
1178/// admits terminal counts only when the provider has verified the complete
1179/// postcondition.
1180#[derive(Clone, Debug, Eq, PartialEq)]
1181pub struct BackfillEventRecord {
1182    scope: ExecutionScope,
1183    fence: ExecutionFence,
1184    manifest_digest: MigrationManifestDigest,
1185    migration_id: MigrationId,
1186    operation_ordinal: u32,
1187    manifest_step_index: u32,
1188    plan_fingerprint: Fingerprint,
1189    direction: BackfillExecutionDirection,
1190    kind: GroupJournalEventKind,
1191    completion: Option<BackfillCompletionEvidence>,
1192}
1193
1194impl BackfillEventRecord {
1195    /// Derive a forward event from one exact verified apply step position.
1196    pub fn new_apply(
1197        lease: &MigrationLease,
1198        migration: &VerifiedMigrationApplyManifest,
1199        step_index: usize,
1200        kind: GroupJournalEventKind,
1201        completion: Option<BackfillCompletionEvidence>,
1202    ) -> Result<Self, Diagnostic> {
1203        if lease.scope().managed_scope_id() != migration.manifest().managed_scope().id() {
1204            return Err(failure(
1205                DiagnosticCategory::Integrity,
1206                "migration_execution_scope_mismatch",
1207                "lease scope differs from the verified migration scope",
1208            ));
1209        }
1210        if !migration.backfill_step_indices().contains(&step_index) {
1211            return Err(failure(
1212                DiagnosticCategory::Integrity,
1213                "migration_execution_backfill_step_position",
1214                "backfill event position is outside the verified apply manifest",
1215            ));
1216        }
1217        let step = migration.steps().get(step_index).ok_or_else(|| {
1218            failure(
1219                DiagnosticCategory::Integrity,
1220                "migration_execution_backfill_step_position",
1221                "backfill event position is outside the verified apply manifest",
1222            )
1223        })?;
1224        let (contract, _) = step.step().as_backfill().ok_or_else(|| {
1225            failure(
1226                DiagnosticCategory::Integrity,
1227                "migration_execution_backfill_step_position",
1228                "verified backfill position does not contain a backfill step",
1229            )
1230        })?;
1231        Self::new_checked(
1232            lease,
1233            migration.digest(),
1234            migration.manifest().id().clone(),
1235            step_index,
1236            step_index,
1237            contract.plan_fingerprint().clone(),
1238            BackfillExecutionDirection::Forward,
1239            kind,
1240            completion,
1241        )
1242    }
1243
1244    /// Derive a reverse event from one exact mixed rollback operation position.
1245    pub fn new_rollback(
1246        lease: &MigrationLease,
1247        rollback: &VerifiedMigrationRollbackManifest,
1248        operation_index: usize,
1249        kind: GroupJournalEventKind,
1250        completion: Option<BackfillCompletionEvidence>,
1251    ) -> Result<Self, Diagnostic> {
1252        if lease.scope().managed_scope_id() != rollback.manifest().managed_scope().id() {
1253            return Err(failure(
1254                DiagnosticCategory::Integrity,
1255                "migration_execution_scope_mismatch",
1256                "lease scope differs from the verified rollback scope",
1257            ));
1258        }
1259        let backfill_index = match rollback.operations().get(operation_index) {
1260            Some(crate::VerifiedMigrationRollbackOperation::Backfill(index)) => *index,
1261            _ => {
1262                return Err(failure(
1263                    DiagnosticCategory::Integrity,
1264                    "migration_execution_backfill_step_position",
1265                    "backfill event position is outside the verified rollback operations",
1266                ));
1267            }
1268        };
1269        let step = rollback
1270            .backfills()
1271            .get(backfill_index)
1272            .ok_or_else(|| {
1273                failure(
1274                    DiagnosticCategory::Integrity,
1275                    "migration_execution_backfill_step_position",
1276                    "rollback backfill index is outside the verified reverse program",
1277                )
1278            })?
1279            .forward_step();
1280        let (contract, _) = step.as_backfill().ok_or_else(|| {
1281            failure(
1282                DiagnosticCategory::Integrity,
1283                "migration_execution_backfill_step_position",
1284                "verified rollback backfill does not contain a backfill step",
1285            )
1286        })?;
1287        let manifest_step_index = rollback
1288            .manifest()
1289            .steps()
1290            .iter()
1291            .position(|candidate| candidate == step)
1292            .ok_or_else(|| {
1293                failure(
1294                    DiagnosticCategory::Integrity,
1295                    "migration_execution_backfill_step_position",
1296                    "rollback backfill is absent from its verified manifest",
1297                )
1298            })?;
1299        Self::new_checked(
1300            lease,
1301            *rollback.digest(),
1302            rollback.manifest().id().clone(),
1303            operation_index,
1304            manifest_step_index,
1305            contract.plan_fingerprint().clone(),
1306            BackfillExecutionDirection::Reverse,
1307            kind,
1308            completion,
1309        )
1310    }
1311
1312    #[allow(clippy::too_many_arguments)]
1313    fn new_checked(
1314        lease: &MigrationLease,
1315        manifest_digest: MigrationManifestDigest,
1316        migration_id: MigrationId,
1317        operation_ordinal: usize,
1318        manifest_step_index: usize,
1319        plan_fingerprint: Fingerprint,
1320        direction: BackfillExecutionDirection,
1321        kind: GroupJournalEventKind,
1322        completion: Option<BackfillCompletionEvidence>,
1323    ) -> Result<Self, Diagnostic> {
1324        match kind {
1325            GroupJournalEventKind::Committed
1326                if completion.as_ref().is_some_and(|evidence| {
1327                    evidence.plan_fingerprint() == &plan_fingerprint
1328                        && evidence.direction() == direction
1329                }) => {}
1330            GroupJournalEventKind::Committed => {
1331                return Err(failure(
1332                    DiagnosticCategory::Integrity,
1333                    "migration_execution_backfill_completion_mismatch",
1334                    "committed backfill event requires exact terminal plan evidence",
1335                ));
1336            }
1337            GroupJournalEventKind::FormalOnlyAdvanced => {
1338                return Err(failure(
1339                    DiagnosticCategory::InvalidContract,
1340                    "migration_execution_backfill_formal_advance",
1341                    "a data backfill cannot advance as a formal-only operation",
1342                ));
1343            }
1344            _ if completion.is_none() => {}
1345            _ => {
1346                return Err(failure(
1347                    DiagnosticCategory::InvalidContract,
1348                    "migration_execution_unexpected_backfill_completion",
1349                    "only a committed backfill event may carry terminal evidence",
1350                ));
1351            }
1352        }
1353        Ok(Self {
1354            scope: lease.scope().clone(),
1355            fence: lease.fence(),
1356            manifest_digest,
1357            migration_id,
1358            operation_ordinal: position(operation_ordinal)?,
1359            manifest_step_index: position(manifest_step_index)?,
1360            plan_fingerprint,
1361            direction,
1362            kind,
1363            completion,
1364        })
1365    }
1366
1367    /// Return the execution scope.
1368    pub const fn scope(&self) -> &ExecutionScope {
1369        &self.scope
1370    }
1371
1372    /// Return the event fence.
1373    pub const fn fence(&self) -> ExecutionFence {
1374        self.fence
1375    }
1376
1377    /// Return the exact manifest digest.
1378    pub const fn manifest_digest(&self) -> MigrationManifestDigest {
1379        self.manifest_digest
1380    }
1381
1382    /// Return the migration identity.
1383    pub const fn migration_id(&self) -> &MigrationId {
1384        &self.migration_id
1385    }
1386
1387    /// Return the position in forward steps or mixed reverse operations.
1388    pub const fn operation_ordinal(&self) -> u32 {
1389        self.operation_ordinal
1390    }
1391
1392    /// Return the original canonical manifest step position.
1393    pub const fn manifest_step_index(&self) -> u32 {
1394        self.manifest_step_index
1395    }
1396
1397    /// Return the exact canonical backfill plan identity.
1398    pub const fn plan_fingerprint(&self) -> &Fingerprint {
1399        &self.plan_fingerprint
1400    }
1401
1402    /// Return the execution direction.
1403    pub const fn direction(&self) -> BackfillExecutionDirection {
1404        self.direction
1405    }
1406
1407    /// Return the commit-boundary event kind.
1408    pub const fn kind(&self) -> GroupJournalEventKind {
1409        self.kind
1410    }
1411
1412    /// Return terminal evidence carried only by committed events.
1413    pub const fn completion(&self) -> Option<&BackfillCompletionEvidence> {
1414        self.completion.as_ref()
1415    }
1416}
1417
1418/// Identity-only applied-ledger record for one verified manifest.
1419#[derive(Clone, Debug, Eq, PartialEq)]
1420pub struct AppliedRecord {
1421    scope: ExecutionScope,
1422    fence: ExecutionFence,
1423    migration_id: MigrationId,
1424    manifest_digest: MigrationManifestDigest,
1425    source_declared: ManagedDeclaredIdentityFingerprint,
1426    target_declared: ManagedDeclaredIdentityFingerprint,
1427    source_semantics: ManagedSemanticSchemaFingerprint,
1428    target_semantics: ManagedSemanticSchemaFingerprint,
1429}
1430
1431impl AppliedRecord {
1432    /// Derive an applied-ledger record from one exact verified manifest.
1433    pub fn from_verified_manifest(
1434        lease: &MigrationLease,
1435        migration: &VerifiedMigrationApplyManifest,
1436    ) -> Result<Self, Diagnostic> {
1437        Self::from_verified_manifest_contract(lease, migration.manifest())
1438    }
1439
1440    /// Derive an applied-ledger record from one verified manifest contract.
1441    ///
1442    /// This is the reconstruction seam for persistent stores. The manifest
1443    /// remains the trust anchor: its digest is recomputed from verified bytes,
1444    /// and no persisted record claim enters the trusted value.
1445    pub fn from_verified_manifest_contract(
1446        lease: &MigrationLease,
1447        manifest: &crate::VerifiedSchemaMigrationManifest,
1448    ) -> Result<Self, Diagnostic> {
1449        let source = manifest.source_state();
1450        let target = manifest.target_state();
1451        let scope = ExecutionScope::new(source.scope().id().clone());
1452        if lease.scope() != &scope || target.scope() != source.scope() {
1453            return Err(failure(
1454                DiagnosticCategory::Integrity,
1455                "migration_execution_scope_mismatch",
1456                "lease and manifest endpoints must bind the same managed scope",
1457            ));
1458        }
1459        Ok(Self {
1460            scope,
1461            fence: lease.fence(),
1462            migration_id: manifest.id().clone(),
1463            manifest_digest: crate::verified_manifest_digest(manifest)?,
1464            source_declared: source.managed_declared_identity().clone(),
1465            target_declared: target.managed_declared_identity().clone(),
1466            source_semantics: source.managed_semantic_schema().clone(),
1467            target_semantics: target.managed_semantic_schema().clone(),
1468        })
1469    }
1470
1471    /// Return the execution scope.
1472    pub const fn scope(&self) -> &ExecutionScope {
1473        &self.scope
1474    }
1475    /// Return the record fence.
1476    pub const fn fence(&self) -> ExecutionFence {
1477        self.fence
1478    }
1479    /// Return the migration identity.
1480    pub const fn migration_id(&self) -> &MigrationId {
1481        &self.migration_id
1482    }
1483    /// Return the canonical manifest digest.
1484    pub const fn manifest_digest(&self) -> MigrationManifestDigest {
1485        self.manifest_digest
1486    }
1487    /// Return source managed-declared identity.
1488    pub const fn source_declared(&self) -> &ManagedDeclaredIdentityFingerprint {
1489        &self.source_declared
1490    }
1491    /// Return target managed-declared identity.
1492    pub const fn target_declared(&self) -> &ManagedDeclaredIdentityFingerprint {
1493        &self.target_declared
1494    }
1495    /// Return source managed semantics.
1496    pub const fn source_semantics(&self) -> &ManagedSemanticSchemaFingerprint {
1497        &self.source_semantics
1498    }
1499    /// Return target managed semantics.
1500    pub const fn target_semantics(&self) -> &ManagedSemanticSchemaFingerprint {
1501        &self.target_semantics
1502    }
1503}
1504
1505/// Identity-only journal record for one complete verified rollback plan.
1506///
1507/// The record binds the exact reverse-topological order, manifest digests,
1508/// surviving applied set, and endpoint managed states the rollback executes
1509/// under. It is the rollback analogue of [`PlanRecord`].
1510#[derive(Clone, Debug, Eq, PartialEq)]
1511pub struct RollbackPlanRecord {
1512    scope: ExecutionScope,
1513    fence: ExecutionFence,
1514    source_applied: Vec<MigrationId>,
1515    rollback_ids: Vec<MigrationId>,
1516    manifest_digests: Vec<MigrationManifestDigest>,
1517    manifest_plan_fingerprints: Vec<MigrationPlanFingerprint>,
1518    remaining_applied: Vec<MigrationId>,
1519    source_declared: ManagedDeclaredIdentityFingerprint,
1520    target_declared: ManagedDeclaredIdentityFingerprint,
1521    source_semantics: ManagedSemanticSchemaFingerprint,
1522    target_semantics: ManagedSemanticSchemaFingerprint,
1523    semantic_profile: SemanticProfileFingerprint,
1524    lowering_profile: SchemaLoweringProfileFingerprint,
1525    observed_live_source: ManagedSemanticSchemaFingerprint,
1526}
1527
1528impl RollbackPlanRecord {
1529    /// Bind a fresh-lease rollback ledger and live-state precondition to
1530    /// verified rollback plan identities.
1531    pub fn from_verified_rollback_plan(
1532        lease: &MigrationLease,
1533        plan: &VerifiedMigrationRollbackPlan,
1534        observed_applied_migrations: &[MigrationId],
1535        observed_live_source: &ManagedSchemaState,
1536    ) -> Result<Self, Diagnostic> {
1537        let first = plan.rollbacks().first().ok_or_else(|| {
1538            failure(
1539                DiagnosticCategory::InvalidContract,
1540                "migration_execution_empty_plan",
1541                "an executable rollback plan requires at least one manifest",
1542            )
1543        })?;
1544        let basis: Vec<MigrationId> = plan.applied_basis().into_iter().collect();
1545        if observed_applied_migrations != basis {
1546            return Err(failure(
1547                DiagnosticCategory::Integrity,
1548                "migration_execution_stale_applied_set",
1549                "applied ledger changed after rollback planning; rebuild the plan",
1550            ));
1551        }
1552        if observed_live_source != plan.source_state() {
1553            return Err(failure(
1554                DiagnosticCategory::Integrity,
1555                "migration_execution_stale_source_state",
1556                "live managed state differs from the planned source; rebuild the plan",
1557            ));
1558        }
1559        let scope = ExecutionScope::new(plan.source_state().scope().id().clone());
1560        if lease.scope() != &scope || plan.target_state().scope() != plan.source_state().scope() {
1561            return Err(failure(
1562                DiagnosticCategory::Integrity,
1563                "migration_execution_scope_mismatch",
1564                "lease, source, and target must bind the same managed scope",
1565            ));
1566        }
1567        let semantic_profile = first.manifest().semantic_profile().fingerprint().clone();
1568        let lowering_profile = first.manifest().lowering_profile().fingerprint().clone();
1569        for rollback in plan.rollbacks() {
1570            if rollback.manifest().managed_scope().id() != scope.managed_scope_id()
1571                || rollback.manifest().semantic_profile().fingerprint() != &semantic_profile
1572                || rollback.manifest().lowering_profile().fingerprint() != &lowering_profile
1573            {
1574                return Err(failure(
1575                    DiagnosticCategory::Integrity,
1576                    "migration_execution_plan_binding_mismatch",
1577                    "planned rollbacks do not share exact scope and profile bindings",
1578                ));
1579            }
1580        }
1581        Ok(Self {
1582            scope,
1583            fence: lease.fence(),
1584            source_applied: basis,
1585            rollback_ids: plan
1586                .rollbacks()
1587                .iter()
1588                .map(|rollback| rollback.manifest().id().clone())
1589                .collect(),
1590            manifest_digests: plan
1591                .rollbacks()
1592                .iter()
1593                .map(|rollback| *rollback.digest())
1594                .collect(),
1595            manifest_plan_fingerprints: plan
1596                .rollbacks()
1597                .iter()
1598                .map(|rollback| rollback.manifest().plan_fingerprint().clone())
1599                .collect(),
1600            remaining_applied: plan.remaining_applied().to_vec(),
1601            source_declared: plan.source_state().managed_declared_identity().clone(),
1602            target_declared: plan.target_state().managed_declared_identity().clone(),
1603            source_semantics: plan.source_state().managed_semantic_schema().clone(),
1604            target_semantics: plan.target_state().managed_semantic_schema().clone(),
1605            semantic_profile,
1606            lowering_profile,
1607            observed_live_source: observed_live_source.managed_semantic_schema().clone(),
1608        })
1609    }
1610
1611    /// Return the execution scope.
1612    pub const fn scope(&self) -> &ExecutionScope {
1613        &self.scope
1614    }
1615    /// Return the fence bound into this record.
1616    pub const fn fence(&self) -> ExecutionFence {
1617        self.fence
1618    }
1619    /// Return the complete canonically ordered pre-rollback applied set.
1620    pub fn source_applied(&self) -> &[MigrationId] {
1621        &self.source_applied
1622    }
1623    /// Return rolled-back identities in reverse-topological execution order.
1624    pub fn rollback_ids(&self) -> &[MigrationId] {
1625        &self.rollback_ids
1626    }
1627    /// Return ordered canonical manifest digests.
1628    pub fn manifest_digests(&self) -> &[MigrationManifestDigest] {
1629        &self.manifest_digests
1630    }
1631    /// Return ordered manifest plan fingerprints.
1632    pub fn manifest_plan_fingerprints(&self) -> &[MigrationPlanFingerprint] {
1633        &self.manifest_plan_fingerprints
1634    }
1635    /// Return the applied identities that survive the rollback, in order.
1636    pub fn remaining_applied(&self) -> &[MigrationId] {
1637        &self.remaining_applied
1638    }
1639    /// Return planned pre-rollback managed-declared identity.
1640    pub const fn source_declared(&self) -> &ManagedDeclaredIdentityFingerprint {
1641        &self.source_declared
1642    }
1643    /// Return planned restored managed-declared identity.
1644    pub const fn target_declared(&self) -> &ManagedDeclaredIdentityFingerprint {
1645        &self.target_declared
1646    }
1647    /// Return planned pre-rollback managed semantics.
1648    pub const fn source_semantics(&self) -> &ManagedSemanticSchemaFingerprint {
1649        &self.source_semantics
1650    }
1651    /// Return planned restored managed semantics.
1652    pub const fn target_semantics(&self) -> &ManagedSemanticSchemaFingerprint {
1653        &self.target_semantics
1654    }
1655    /// Return semantic-profile content identity.
1656    pub const fn semantic_profile(&self) -> &SemanticProfileFingerprint {
1657        &self.semantic_profile
1658    }
1659    /// Return lowering-registry content identity.
1660    pub const fn lowering_profile(&self) -> &SchemaLoweringProfileFingerprint {
1661        &self.lowering_profile
1662    }
1663    /// Return the pre-mutation observed source semantics.
1664    pub const fn observed_live_source(&self) -> &ManagedSemanticSchemaFingerprint {
1665        &self.observed_live_source
1666    }
1667}
1668
1669/// Identity-only journal event for one verified rollback step transaction.
1670///
1671/// Each rollback step executes one recorded reverse program in its own
1672/// provider transaction, so the commit-boundary vocabulary and recovery
1673/// decision table are shared with forward [`GroupEventRecord`] events.
1674#[derive(Clone, Debug, Eq, PartialEq)]
1675pub struct RollbackStepEventRecord {
1676    scope: ExecutionScope,
1677    fence: ExecutionFence,
1678    manifest_digest: MigrationManifestDigest,
1679    migration_id: MigrationId,
1680    step_ordinal: u32,
1681    kind: GroupJournalEventKind,
1682    observed_target: Option<ManagedSemanticSchemaFingerprint>,
1683}
1684
1685impl RollbackStepEventRecord {
1686    /// Derive a positional event from exact verified rollback evidence.
1687    pub fn new(
1688        lease: &MigrationLease,
1689        rollback: &VerifiedMigrationRollbackManifest,
1690        step_index: usize,
1691        kind: GroupJournalEventKind,
1692        observed_target: Option<ManagedSemanticSchemaFingerprint>,
1693    ) -> Result<Self, Diagnostic> {
1694        let step = rollback.steps().get(step_index).ok_or_else(|| {
1695            failure(
1696                DiagnosticCategory::Integrity,
1697                "migration_execution_rollback_step_position",
1698                "rollback event position is outside the verified rollback manifest",
1699            )
1700        })?;
1701        let reverse = rollback.reverse_delta(step)?;
1702        let scope = ExecutionScope::new(rollback.manifest().managed_scope().id().clone());
1703        if lease.scope() != &scope {
1704            return Err(failure(
1705                DiagnosticCategory::Integrity,
1706                "migration_execution_scope_mismatch",
1707                "lease scope differs from the verified rollback scope",
1708            ));
1709        }
1710        match kind {
1711            GroupJournalEventKind::Committed
1712                if observed_target.as_ref() == Some(reverse.target().managed_semantic_schema()) => {
1713            }
1714            GroupJournalEventKind::Committed => {
1715                return Err(failure(
1716                    DiagnosticCategory::Integrity,
1717                    "migration_execution_commit_evidence_mismatch",
1718                    "committed event requires the exact observed target semantics",
1719                ));
1720            }
1721            GroupJournalEventKind::FormalOnlyAdvanced
1722                if observed_target.is_none()
1723                    && step.lowering().units().is_empty()
1724                    && reverse.source().managed_semantic_schema()
1725                        == reverse.target().managed_semantic_schema() => {}
1726            GroupJournalEventKind::FormalOnlyAdvanced => {
1727                return Err(failure(
1728                    DiagnosticCategory::InvalidContract,
1729                    "migration_execution_invalid_formal_advance",
1730                    "formal-only advancement requires an empty equal-semantic reverse program",
1731                ));
1732            }
1733            _ if observed_target.is_none() => {}
1734            _ => {
1735                return Err(failure(
1736                    DiagnosticCategory::InvalidContract,
1737                    "migration_execution_unexpected_observation",
1738                    "only committed events may carry observed target semantics",
1739                ));
1740            }
1741        }
1742        Ok(Self {
1743            scope,
1744            fence: lease.fence(),
1745            manifest_digest: *rollback.digest(),
1746            migration_id: rollback.manifest().id().clone(),
1747            step_ordinal: position(step_index)?,
1748            kind,
1749            observed_target,
1750        })
1751    }
1752
1753    /// Return the execution scope.
1754    pub const fn scope(&self) -> &ExecutionScope {
1755        &self.scope
1756    }
1757    /// Return the event fence.
1758    pub const fn fence(&self) -> ExecutionFence {
1759        self.fence
1760    }
1761    /// Return the canonical digest of the manifest being rolled back.
1762    pub const fn manifest_digest(&self) -> MigrationManifestDigest {
1763        self.manifest_digest
1764    }
1765    /// Return the migration identity.
1766    pub const fn migration_id(&self) -> &MigrationId {
1767        &self.migration_id
1768    }
1769    /// Return the rollback step position in execution order.
1770    pub const fn step_ordinal(&self) -> u32 {
1771        self.step_ordinal
1772    }
1773    /// Return the event kind.
1774    pub const fn kind(&self) -> GroupJournalEventKind {
1775        self.kind
1776    }
1777    /// Return exact target evidence carried only by committed events.
1778    pub const fn observed_target(&self) -> Option<&ManagedSemanticSchemaFingerprint> {
1779        self.observed_target.as_ref()
1780    }
1781}
1782
1783/// Identity-only retirement record for one rolled-back applied migration.
1784///
1785/// Retirement is append-only history: the applied record stays in the durable
1786/// journal, and this record marks it inactive. The states enter swapped
1787/// relative to [`AppliedRecord`] because rolling back moves the managed schema
1788/// from the manifest's target back to its source.
1789#[derive(Clone, Debug, Eq, PartialEq)]
1790pub struct RolledBackRecord {
1791    scope: ExecutionScope,
1792    fence: ExecutionFence,
1793    migration_id: MigrationId,
1794    manifest_digest: MigrationManifestDigest,
1795    source_declared: ManagedDeclaredIdentityFingerprint,
1796    target_declared: ManagedDeclaredIdentityFingerprint,
1797    source_semantics: ManagedSemanticSchemaFingerprint,
1798    target_semantics: ManagedSemanticSchemaFingerprint,
1799}
1800
1801impl RolledBackRecord {
1802    /// Derive a retirement record from one exact verified rollback manifest.
1803    pub fn from_verified_rollback(
1804        lease: &MigrationLease,
1805        rollback: &VerifiedMigrationRollbackManifest,
1806    ) -> Result<Self, Diagnostic> {
1807        Self::from_verified_manifest_contract(lease, rollback.manifest())
1808    }
1809
1810    /// Derive a retirement record from one verified manifest contract.
1811    ///
1812    /// This is the reconstruction seam for persistent stores, mirroring
1813    /// [`AppliedRecord::from_verified_manifest_contract`].
1814    pub fn from_verified_manifest_contract(
1815        lease: &MigrationLease,
1816        manifest: &crate::VerifiedSchemaMigrationManifest,
1817    ) -> Result<Self, Diagnostic> {
1818        let source = manifest.target_state();
1819        let target = manifest.source_state();
1820        let scope = ExecutionScope::new(source.scope().id().clone());
1821        if lease.scope() != &scope || target.scope() != source.scope() {
1822            return Err(failure(
1823                DiagnosticCategory::Integrity,
1824                "migration_execution_scope_mismatch",
1825                "lease and manifest endpoints must bind the same managed scope",
1826            ));
1827        }
1828        Ok(Self {
1829            scope,
1830            fence: lease.fence(),
1831            migration_id: manifest.id().clone(),
1832            manifest_digest: crate::verified_manifest_digest(manifest)?,
1833            source_declared: source.managed_declared_identity().clone(),
1834            target_declared: target.managed_declared_identity().clone(),
1835            source_semantics: source.managed_semantic_schema().clone(),
1836            target_semantics: target.managed_semantic_schema().clone(),
1837        })
1838    }
1839
1840    /// Return the execution scope.
1841    pub const fn scope(&self) -> &ExecutionScope {
1842        &self.scope
1843    }
1844    /// Return the record fence.
1845    pub const fn fence(&self) -> ExecutionFence {
1846        self.fence
1847    }
1848    /// Return the retired migration identity.
1849    pub const fn migration_id(&self) -> &MigrationId {
1850        &self.migration_id
1851    }
1852    /// Return the canonical manifest digest.
1853    pub const fn manifest_digest(&self) -> MigrationManifestDigest {
1854        self.manifest_digest
1855    }
1856    /// Return pre-rollback managed-declared identity.
1857    pub const fn source_declared(&self) -> &ManagedDeclaredIdentityFingerprint {
1858        &self.source_declared
1859    }
1860    /// Return restored managed-declared identity.
1861    pub const fn target_declared(&self) -> &ManagedDeclaredIdentityFingerprint {
1862        &self.target_declared
1863    }
1864    /// Return pre-rollback managed semantics.
1865    pub const fn source_semantics(&self) -> &ManagedSemanticSchemaFingerprint {
1866        &self.source_semantics
1867    }
1868    /// Return restored managed semantics.
1869    pub const fn target_semantics(&self) -> &ManagedSemanticSchemaFingerprint {
1870        &self.target_semantics
1871    }
1872}
1873
1874/// One trusted, still-open rollback plan and its ordered step events.
1875#[derive(Clone, Debug, Eq, PartialEq)]
1876pub struct OpenRollbackPlanRecord {
1877    plan: JournalEntry<RollbackPlanRecord>,
1878    events: Vec<JournalEntry<RollbackStepEventRecord>>,
1879    backfill_events: Vec<JournalEntry<BackfillEventRecord>>,
1880}
1881
1882impl OpenRollbackPlanRecord {
1883    /// Rebuild store output while checking sequence, scope, fence, and manifest binding.
1884    ///
1885    /// The same monotonic-fence rule as [`OpenPlanRecord::from_store`] applies:
1886    /// recovery events may be written under later fences than the plan itself.
1887    pub fn from_store(
1888        plan: JournalEntry<RollbackPlanRecord>,
1889        events: Vec<JournalEntry<RollbackStepEventRecord>>,
1890    ) -> Result<Self, Diagnostic> {
1891        Self::from_store_with_backfills(plan, events, Vec::new())
1892    }
1893
1894    /// Rebuild store output including independently journaled reverse data-step events.
1895    pub fn from_store_with_backfills(
1896        plan: JournalEntry<RollbackPlanRecord>,
1897        events: Vec<JournalEntry<RollbackStepEventRecord>>,
1898        backfill_events: Vec<JournalEntry<BackfillEventRecord>>,
1899    ) -> Result<Self, Diagnostic> {
1900        let mut previous = plan.sequence();
1901        let mut previous_fence = plan.record().fence();
1902        let mut ordered: Vec<(
1903            JournalSequence,
1904            ExecutionFence,
1905            &MigrationId,
1906            MigrationManifestDigest,
1907        )> = events
1908            .iter()
1909            .map(|event| {
1910                (
1911                    event.sequence(),
1912                    event.record().fence(),
1913                    event.record().migration_id(),
1914                    event.record().manifest_digest(),
1915                )
1916            })
1917            .chain(backfill_events.iter().map(|event| {
1918                (
1919                    event.sequence(),
1920                    event.record().fence(),
1921                    event.record().migration_id(),
1922                    event.record().manifest_digest(),
1923                )
1924            }))
1925            .collect();
1926        ordered.sort_by_key(|event| event.0);
1927        for (sequence, fence, migration_id, manifest_digest) in ordered {
1928            let manifest_index = plan
1929                .record()
1930                .manifest_digests()
1931                .iter()
1932                .position(|digest| digest == &manifest_digest);
1933            if sequence <= previous
1934                || fence < previous_fence
1935                || manifest_index.is_none_or(|index| {
1936                    plan.record().rollback_ids().get(index) != Some(migration_id)
1937                })
1938            {
1939                return Err(failure(
1940                    DiagnosticCategory::Integrity,
1941                    "migration_execution_invalid_open_plan",
1942                    "loaded open-rollback events are not ordered and bound to the plan",
1943                ));
1944            }
1945            previous = sequence;
1946            previous_fence = fence;
1947        }
1948        if events
1949            .iter()
1950            .any(|event| event.record().scope() != plan.record().scope())
1951            || backfill_events
1952                .iter()
1953                .any(|event| event.record().scope() != plan.record().scope())
1954        {
1955            return Err(failure(
1956                DiagnosticCategory::Integrity,
1957                "migration_execution_invalid_open_plan",
1958                "loaded open-rollback events are not bound to the plan scope",
1959            ));
1960        }
1961        Ok(Self {
1962            plan,
1963            events,
1964            backfill_events,
1965        })
1966    }
1967
1968    /// Return the sequenced rollback plan record.
1969    pub const fn plan(&self) -> &JournalEntry<RollbackPlanRecord> {
1970        &self.plan
1971    }
1972
1973    /// Return ordered sequenced rollback step events.
1974    pub fn events(&self) -> &[JournalEntry<RollbackStepEventRecord>] {
1975        &self.events
1976    }
1977
1978    /// Return ordered sequenced reverse backfill events.
1979    pub fn backfill_events(&self) -> &[JournalEntry<BackfillEventRecord>] {
1980        &self.backfill_events
1981    }
1982}
1983
1984/// Store-backed exclusive lease service.
1985pub trait MigrationLeaseStore: Send + Sync {
1986    /// Atomically acquire an available scope and issue a fence strictly greater
1987    /// than every fence previously issued for that scope.
1988    ///
1989    /// Lease expiry, liveness, and takeover policy are store-defined. Every
1990    /// takeover after release, expiry, or failure must issue a strictly greater
1991    /// fence so a surviving stale holder cannot mutate the journal.
1992    fn acquire<'a>(
1993        &'a self,
1994        scope: &'a ExecutionScope,
1995        holder: &'a LeaseHolderId,
1996    ) -> ExecutionFuture<'a, MigrationLease>;
1997
1998    /// Release only the exact currently active holder and fence.
1999    fn release<'a>(&'a self, lease: &'a MigrationLease) -> ExecutionFuture<'a, ()>;
2000}
2001
2002/// Durable applied ledger and open-plan journal.
2003///
2004/// Every write must atomically reject a lease that is not the current active
2005/// scope, holder, and fence. There is deliberately no advisory validate method.
2006pub trait MigrationExecutionJournal: Send + Sync {
2007    /// Begin one fully verified plan after stale-ledger and live-source checks.
2008    ///
2009    /// An open plan of either direction is exclusive: the store must reject a
2010    /// new apply plan while a rollback plan is open and vice versa.
2011    fn begin_plan<'a>(
2012        &'a self,
2013        lease: &'a MigrationLease,
2014        record: PlanRecord,
2015    ) -> ExecutionFuture<'a, JournalEntry<PlanRecord>>;
2016
2017    /// Append one positional commit-boundary event under the active fence.
2018    fn record_group_event<'a>(
2019        &'a self,
2020        lease: &'a MigrationLease,
2021        record: GroupEventRecord,
2022    ) -> ExecutionFuture<'a, JournalEntry<GroupEventRecord>>;
2023
2024    /// Append one exact forward or reverse backfill commit-boundary event.
2025    fn record_backfill_event<'a>(
2026        &'a self,
2027        lease: &'a MigrationLease,
2028        record: BackfillEventRecord,
2029    ) -> ExecutionFuture<'a, JournalEntry<BackfillEventRecord>>;
2030
2031    /// Add one exact verified manifest from the open plan to the applied ledger.
2032    ///
2033    /// The store must reject a new record whose migration identity and digest do
2034    /// not occur at the same position in the open plan. Importing an existing
2035    /// ledger is a separate concern and must not use this execution write. An
2036    /// exact retry is idempotent only under the same fence; seeing the same
2037    /// migration under a newer fence requires reloading the ledger rather than
2038    /// treating differently fenced evidence as equal.
2039    fn record_applied<'a>(
2040        &'a self,
2041        lease: &'a MigrationLease,
2042        record: AppliedRecord,
2043    ) -> ExecutionFuture<'a, JournalEntry<AppliedRecord>>;
2044
2045    /// Load ordered active applied records under the active fence.
2046    ///
2047    /// Retired records — applied records whose migration was rolled back by a
2048    /// later [`RolledBackRecord`] — are excluded. The full append-only history
2049    /// stays durable in the store; only the active ledger is the apply basis.
2050    fn load_applied<'a>(
2051        &'a self,
2052        lease: &'a MigrationLease,
2053    ) -> ExecutionFuture<'a, Vec<JournalEntry<AppliedRecord>>>;
2054
2055    /// Load the open plan and all ordered events written at its fence or later.
2056    fn load_open_plan<'a>(
2057        &'a self,
2058        lease: &'a MigrationLease,
2059    ) -> ExecutionFuture<'a, Option<OpenPlanRecord>>;
2060
2061    /// Begin one fully verified rollback plan after stale-ledger checks.
2062    ///
2063    /// Subject to the same open-plan exclusivity as [`Self::begin_plan`].
2064    fn begin_rollback_plan<'a>(
2065        &'a self,
2066        lease: &'a MigrationLease,
2067        record: RollbackPlanRecord,
2068    ) -> ExecutionFuture<'a, JournalEntry<RollbackPlanRecord>>;
2069
2070    /// Append one positional rollback commit-boundary event under the active fence.
2071    fn record_rollback_step_event<'a>(
2072        &'a self,
2073        lease: &'a MigrationLease,
2074        record: RollbackStepEventRecord,
2075    ) -> ExecutionFuture<'a, JournalEntry<RollbackStepEventRecord>>;
2076
2077    /// Retire one exact applied record from the open rollback plan.
2078    ///
2079    /// The store must reject a record whose migration identity and digest do
2080    /// not occur at the same position in the open rollback plan, or whose
2081    /// migration is not currently active in the applied ledger. Retirement is
2082    /// append-only: the applied record and this record both stay durable, and
2083    /// the migration merely leaves the active ledger. An exact retry is
2084    /// idempotent only under the same fence.
2085    fn record_rolled_back<'a>(
2086        &'a self,
2087        lease: &'a MigrationLease,
2088        record: RolledBackRecord,
2089    ) -> ExecutionFuture<'a, JournalEntry<RolledBackRecord>>;
2090
2091    /// Load ordered retirement records under the active fence.
2092    fn load_rolled_back<'a>(
2093        &'a self,
2094        lease: &'a MigrationLease,
2095    ) -> ExecutionFuture<'a, Vec<JournalEntry<RolledBackRecord>>>;
2096
2097    /// Load the open rollback plan and all ordered events at its fence or later.
2098    fn load_open_rollback_plan<'a>(
2099        &'a self,
2100        lease: &'a MigrationLease,
2101    ) -> ExecutionFuture<'a, Option<OpenRollbackPlanRecord>>;
2102}
2103
2104/// Filter an applied ledger down to its active records.
2105///
2106/// Each retirement record consumes the latest not-yet-retired applied record
2107/// with the same migration identity and manifest digest written before it.
2108/// A retirement that matches no applied record is corrupt history and fails
2109/// closed. Stores share this exact matching rule so every journal
2110/// implementation reports the same active basis.
2111pub fn active_applied_entries(
2112    applied: Vec<JournalEntry<AppliedRecord>>,
2113    rolled_back: &[JournalEntry<RolledBackRecord>],
2114) -> Result<Vec<JournalEntry<AppliedRecord>>, Diagnostic> {
2115    let mut retired = vec![false; applied.len()];
2116    for retirement in rolled_back {
2117        let matched = applied
2118            .iter()
2119            .enumerate()
2120            .filter(|(index, entry)| {
2121                !retired[*index]
2122                    && entry.sequence() < retirement.sequence()
2123                    && entry.record().migration_id() == retirement.record().migration_id()
2124                    && entry.record().manifest_digest() == retirement.record().manifest_digest()
2125            })
2126            .max_by_key(|(_, entry)| entry.sequence())
2127            .map(|(index, _)| index);
2128        let Some(index) = matched else {
2129            return Err(failure(
2130                DiagnosticCategory::Integrity,
2131                "migration_execution_unmatched_retirement",
2132                "retirement record matches no active applied record before it",
2133            ));
2134        };
2135        retired[index] = true;
2136    }
2137    Ok(applied
2138        .into_iter()
2139        .zip(retired)
2140        .filter_map(|(entry, retired)| (!retired).then_some(entry))
2141        .collect())
2142}
2143
2144fn position(value: usize) -> Result<u32, Diagnostic> {
2145    u32::try_from(value).map_err(|_| {
2146        failure(
2147            DiagnosticCategory::ResourceLimit,
2148            "migration_execution_position_limit",
2149            "migration transaction position exceeds the canonical u32 range",
2150        )
2151    })
2152}
2153
2154fn failure(category: DiagnosticCategory, code: &'static str, message: &'static str) -> Diagnostic {
2155    Diagnostic::new(
2156        category,
2157        DiagnosticCode::new(code).expect("static migration execution diagnostic code"),
2158        message,
2159    )
2160}
2161
2162#[cfg(test)]
2163mod tests {
2164    use std::collections::BTreeMap;
2165    use std::future::Future;
2166    use std::sync::Mutex;
2167    use std::task::{Context, Poll, Waker};
2168
2169    use type_bridge_contract::fingerprint::SemanticProfileId;
2170    use type_bridge_contract::managed_scope::{ManagedScopeId, SemanticProfileBinding};
2171    use type_bridge_contract::migration::{MigrationAppLabel, MigrationName};
2172
2173    use super::*;
2174
2175    #[test]
2176    fn migration_controls_cancel_and_only_tighten_shared_ceilings() {
2177        let cancellation = MigrationCancellation::default();
2178        let limits = MigrationExecutionResourceLimits::tightened(7, usize::MAX);
2179        let control = MigrationExecutionControl::new(cancellation.clone(), None, limits);
2180
2181        assert_eq!(control.resources().transaction_groups(), 7);
2182        assert_eq!(
2183            control.resources().backfill_observations(),
2184            MAX_MIGRATION_BACKFILL_OBSERVATIONS
2185        );
2186        assert!(control.check().is_ok());
2187
2188        cancellation.cancel();
2189        cancellation.cancel();
2190        let diagnostic = control.check().expect_err("cancelled control");
2191        assert_eq!(diagnostic.category(), DiagnosticCategory::Cancelled);
2192        assert_eq!(diagnostic.code().as_str(), "migration_execution_cancelled");
2193    }
2194
2195    #[test]
2196    fn migration_control_uses_one_absolute_deadline() {
2197        let control = MigrationExecutionControl::new(
2198            MigrationCancellation::default(),
2199            Some(Instant::now()),
2200            MigrationExecutionResourceLimits::default(),
2201        );
2202        let diagnostic = control.check().expect_err("expired deadline");
2203        assert_eq!(diagnostic.category(), DiagnosticCategory::ResourceLimit);
2204        assert_eq!(
2205            diagnostic.code().as_str(),
2206            "migration_execution_deadline_exceeded"
2207        );
2208    }
2209    use crate::schema_lowering_profile_binding;
2210
2211    #[derive(Default)]
2212    struct ScopeState {
2213        highest_fence: u64,
2214        active_lease: Option<MigrationLease>,
2215        next_sequence: u64,
2216        applied: Vec<JournalEntry<AppliedRecord>>,
2217        rolled_back: Vec<JournalEntry<RolledBackRecord>>,
2218        open_plan: Option<JournalEntry<PlanRecord>>,
2219        events: Vec<JournalEntry<GroupEventRecord>>,
2220        backfill_events: Vec<JournalEntry<BackfillEventRecord>>,
2221        open_rollback_plan: Option<JournalEntry<RollbackPlanRecord>>,
2222        rollback_events: Vec<JournalEntry<RollbackStepEventRecord>>,
2223    }
2224
2225    #[derive(Default)]
2226    struct InMemoryStore {
2227        scopes: Mutex<BTreeMap<ExecutionScope, ScopeState>>,
2228    }
2229
2230    impl InMemoryStore {
2231        fn check_lease<'a>(
2232            state: &'a mut ScopeState,
2233            lease: &MigrationLease,
2234        ) -> Result<&'a mut ScopeState, Diagnostic> {
2235            if state.active_lease.as_ref() != Some(lease) {
2236                return Err(failure(
2237                    DiagnosticCategory::Integrity,
2238                    "migration_execution_stale_fence",
2239                    "journal write does not carry the current active lease and fence",
2240                ));
2241            }
2242            Ok(state)
2243        }
2244
2245        fn sequence(state: &mut ScopeState) -> Result<JournalSequence, Diagnostic> {
2246            state.next_sequence = state.next_sequence.checked_add(1).ok_or_else(|| {
2247                failure(
2248                    DiagnosticCategory::ResourceLimit,
2249                    "migration_execution_sequence_exhausted",
2250                    "journal sequence range is exhausted",
2251                )
2252            })?;
2253            JournalSequence::new(state.next_sequence)
2254        }
2255    }
2256
2257    impl MigrationLeaseStore for InMemoryStore {
2258        fn acquire<'a>(
2259            &'a self,
2260            scope: &'a ExecutionScope,
2261            holder: &'a LeaseHolderId,
2262        ) -> ExecutionFuture<'a, MigrationLease> {
2263            Box::pin(async move {
2264                let mut scopes = self.scopes.lock().expect("store mutex");
2265                let state = scopes.entry(scope.clone()).or_default();
2266                if state.active_lease.is_some() {
2267                    return Err(failure(
2268                        DiagnosticCategory::InvalidContract,
2269                        "migration_execution_lease_contended",
2270                        "migration scope already has an active lease",
2271                    ));
2272                }
2273                let fence = if state.highest_fence == 0 {
2274                    ExecutionFence::new(1)?
2275                } else {
2276                    ExecutionFence::new(state.highest_fence)?.checked_successor()?
2277                };
2278                state.highest_fence = fence.get();
2279                let lease = MigrationLease::new(scope.clone(), holder.clone(), fence);
2280                state.active_lease = Some(lease.clone());
2281                Ok(lease)
2282            })
2283        }
2284
2285        fn release<'a>(&'a self, lease: &'a MigrationLease) -> ExecutionFuture<'a, ()> {
2286            Box::pin(async move {
2287                let mut scopes = self.scopes.lock().expect("store mutex");
2288                let state = scopes.get_mut(lease.scope()).ok_or_else(|| {
2289                    failure(
2290                        DiagnosticCategory::Integrity,
2291                        "migration_execution_stale_fence",
2292                        "lease scope is not active",
2293                    )
2294                })?;
2295                Self::check_lease(state, lease)?;
2296                state.active_lease = None;
2297                Ok(())
2298            })
2299        }
2300    }
2301
2302    impl MigrationExecutionJournal for InMemoryStore {
2303        fn begin_plan<'a>(
2304            &'a self,
2305            lease: &'a MigrationLease,
2306            record: PlanRecord,
2307        ) -> ExecutionFuture<'a, JournalEntry<PlanRecord>> {
2308            Box::pin(async move {
2309                let mut scopes = self.scopes.lock().expect("store mutex");
2310                let state = scopes.get_mut(lease.scope()).ok_or_else(stale_fence)?;
2311                Self::check_lease(state, lease)?;
2312                if record.scope() != lease.scope() || record.fence() != lease.fence() {
2313                    return Err(stale_fence());
2314                }
2315                if state.open_plan.is_some() || state.open_rollback_plan.is_some() {
2316                    return Err(failure(
2317                        DiagnosticCategory::InvalidContract,
2318                        "migration_execution_plan_already_open",
2319                        "migration scope already has an open plan",
2320                    ));
2321                }
2322                let entry = JournalEntry::from_store(Self::sequence(state)?, record);
2323                state.open_plan = Some(entry.clone());
2324                Ok(entry)
2325            })
2326        }
2327
2328        fn record_group_event<'a>(
2329            &'a self,
2330            lease: &'a MigrationLease,
2331            record: GroupEventRecord,
2332        ) -> ExecutionFuture<'a, JournalEntry<GroupEventRecord>> {
2333            Box::pin(async move {
2334                let mut scopes = self.scopes.lock().expect("store mutex");
2335                let state = scopes.get_mut(lease.scope()).ok_or_else(stale_fence)?;
2336                Self::check_lease(state, lease)?;
2337                if record.scope() != lease.scope() || record.fence() != lease.fence() {
2338                    return Err(stale_fence());
2339                }
2340                let plan = state.open_plan.as_ref().ok_or_else(|| {
2341                    failure(
2342                        DiagnosticCategory::InvalidContract,
2343                        "migration_execution_no_open_plan",
2344                        "group event requires an open migration plan",
2345                    )
2346                })?;
2347                if !plan
2348                    .record()
2349                    .manifest_digests()
2350                    .contains(&record.manifest_digest())
2351                {
2352                    return Err(failure(
2353                        DiagnosticCategory::Integrity,
2354                        "migration_execution_foreign_event",
2355                        "group event manifest is absent from the open plan",
2356                    ));
2357                }
2358                let entry = JournalEntry::from_store(Self::sequence(state)?, record);
2359                state.events.push(entry.clone());
2360                Ok(entry)
2361            })
2362        }
2363
2364        fn record_backfill_event<'a>(
2365            &'a self,
2366            lease: &'a MigrationLease,
2367            record: BackfillEventRecord,
2368        ) -> ExecutionFuture<'a, JournalEntry<BackfillEventRecord>> {
2369            Box::pin(async move {
2370                let mut scopes = self.scopes.lock().expect("store mutex");
2371                let state = scopes.get_mut(lease.scope()).ok_or_else(stale_fence)?;
2372                Self::check_lease(state, lease)?;
2373                if record.scope() != lease.scope() || record.fence() != lease.fence() {
2374                    return Err(stale_fence());
2375                }
2376                let member = state.open_plan.as_ref().is_some_and(|plan| {
2377                    plan.record()
2378                        .manifest_digests()
2379                        .contains(&record.manifest_digest())
2380                }) || state.open_rollback_plan.as_ref().is_some_and(|plan| {
2381                    plan.record()
2382                        .manifest_digests()
2383                        .contains(&record.manifest_digest())
2384                });
2385                if !member {
2386                    return Err(failure(
2387                        DiagnosticCategory::Integrity,
2388                        "migration_execution_foreign_event",
2389                        "backfill event manifest is absent from the open plan",
2390                    ));
2391                }
2392                let entry = JournalEntry::from_store(Self::sequence(state)?, record);
2393                state.backfill_events.push(entry.clone());
2394                Ok(entry)
2395            })
2396        }
2397
2398        fn record_applied<'a>(
2399            &'a self,
2400            lease: &'a MigrationLease,
2401            record: AppliedRecord,
2402        ) -> ExecutionFuture<'a, JournalEntry<AppliedRecord>> {
2403            Box::pin(async move {
2404                let mut scopes = self.scopes.lock().expect("store mutex");
2405                let state = scopes.get_mut(lease.scope()).ok_or_else(stale_fence)?;
2406                Self::check_lease(state, lease)?;
2407                if record.scope() != lease.scope() || record.fence() != lease.fence() {
2408                    return Err(stale_fence());
2409                }
2410                let active = active_applied_entries(state.applied.clone(), &state.rolled_back)?;
2411                if let Some(existing) = active
2412                    .iter()
2413                    .find(|entry| entry.record().migration_id() == record.migration_id())
2414                {
2415                    return if existing.record() == &record {
2416                        Ok(existing.clone())
2417                    } else {
2418                        Err(failure(
2419                            DiagnosticCategory::Integrity,
2420                            "migration_execution_applied_identity_conflict",
2421                            "applied migration identity has different evidence",
2422                        ))
2423                    };
2424                }
2425                let plan = state.open_plan.as_ref().ok_or_else(|| {
2426                    failure(
2427                        DiagnosticCategory::InvalidContract,
2428                        "migration_execution_no_open_plan",
2429                        "applied migration requires an open migration plan",
2430                    )
2431                })?;
2432                let manifest_index = plan
2433                    .record()
2434                    .migration_ids()
2435                    .iter()
2436                    .position(|id| id == record.migration_id());
2437                if manifest_index.is_none_or(|index| {
2438                    plan.record().manifest_digests().get(index) != Some(&record.manifest_digest())
2439                }) {
2440                    return Err(failure(
2441                        DiagnosticCategory::Integrity,
2442                        "migration_execution_foreign_applied_record",
2443                        "applied migration identity and digest are absent from the open plan",
2444                    ));
2445                }
2446                let entry = JournalEntry::from_store(Self::sequence(state)?, record);
2447                state.applied.push(entry.clone());
2448                let active = active_applied_entries(state.applied.clone(), &state.rolled_back)?;
2449                let complete = state.open_plan.as_ref().is_some_and(|plan| {
2450                    plan.record().migration_ids().iter().all(|id| {
2451                        active
2452                            .iter()
2453                            .any(|applied| applied.record().migration_id() == id)
2454                    })
2455                });
2456                if complete {
2457                    state.open_plan = None;
2458                    state.events.clear();
2459                    state.backfill_events.clear();
2460                }
2461                Ok(entry)
2462            })
2463        }
2464
2465        fn load_applied<'a>(
2466            &'a self,
2467            lease: &'a MigrationLease,
2468        ) -> ExecutionFuture<'a, Vec<JournalEntry<AppliedRecord>>> {
2469            Box::pin(async move {
2470                let mut scopes = self.scopes.lock().expect("store mutex");
2471                let state = scopes.get_mut(lease.scope()).ok_or_else(stale_fence)?;
2472                Self::check_lease(state, lease)?;
2473                active_applied_entries(state.applied.clone(), &state.rolled_back)
2474            })
2475        }
2476
2477        fn load_open_plan<'a>(
2478            &'a self,
2479            lease: &'a MigrationLease,
2480        ) -> ExecutionFuture<'a, Option<OpenPlanRecord>> {
2481            Box::pin(async move {
2482                let mut scopes = self.scopes.lock().expect("store mutex");
2483                let state = scopes.get_mut(lease.scope()).ok_or_else(stale_fence)?;
2484                Self::check_lease(state, lease)?;
2485                let Some(plan) = state.open_plan.clone() else {
2486                    return Ok(None);
2487                };
2488                Ok(Some(OpenPlanRecord::from_store_with_backfills(
2489                    plan,
2490                    state.events.clone(),
2491                    state
2492                        .backfill_events
2493                        .iter()
2494                        .filter(|event| {
2495                            event.record().direction() == BackfillExecutionDirection::Forward
2496                        })
2497                        .cloned()
2498                        .collect(),
2499                )?))
2500            })
2501        }
2502
2503        fn begin_rollback_plan<'a>(
2504            &'a self,
2505            lease: &'a MigrationLease,
2506            record: RollbackPlanRecord,
2507        ) -> ExecutionFuture<'a, JournalEntry<RollbackPlanRecord>> {
2508            Box::pin(async move {
2509                let mut scopes = self.scopes.lock().expect("store mutex");
2510                let state = scopes.get_mut(lease.scope()).ok_or_else(stale_fence)?;
2511                Self::check_lease(state, lease)?;
2512                if record.scope() != lease.scope() || record.fence() != lease.fence() {
2513                    return Err(stale_fence());
2514                }
2515                if state.open_plan.is_some() || state.open_rollback_plan.is_some() {
2516                    return Err(failure(
2517                        DiagnosticCategory::InvalidContract,
2518                        "migration_execution_plan_already_open",
2519                        "migration scope already has an open plan",
2520                    ));
2521                }
2522                let entry = JournalEntry::from_store(Self::sequence(state)?, record);
2523                state.open_rollback_plan = Some(entry.clone());
2524                Ok(entry)
2525            })
2526        }
2527
2528        fn record_rollback_step_event<'a>(
2529            &'a self,
2530            lease: &'a MigrationLease,
2531            record: RollbackStepEventRecord,
2532        ) -> ExecutionFuture<'a, JournalEntry<RollbackStepEventRecord>> {
2533            Box::pin(async move {
2534                let mut scopes = self.scopes.lock().expect("store mutex");
2535                let state = scopes.get_mut(lease.scope()).ok_or_else(stale_fence)?;
2536                Self::check_lease(state, lease)?;
2537                if record.scope() != lease.scope() || record.fence() != lease.fence() {
2538                    return Err(stale_fence());
2539                }
2540                let plan = state.open_rollback_plan.as_ref().ok_or_else(|| {
2541                    failure(
2542                        DiagnosticCategory::InvalidContract,
2543                        "migration_execution_no_open_plan",
2544                        "rollback event requires an open rollback plan",
2545                    )
2546                })?;
2547                if !plan
2548                    .record()
2549                    .manifest_digests()
2550                    .contains(&record.manifest_digest())
2551                {
2552                    return Err(failure(
2553                        DiagnosticCategory::Integrity,
2554                        "migration_execution_foreign_event",
2555                        "rollback event manifest is absent from the open plan",
2556                    ));
2557                }
2558                let entry = JournalEntry::from_store(Self::sequence(state)?, record);
2559                state.rollback_events.push(entry.clone());
2560                Ok(entry)
2561            })
2562        }
2563
2564        fn record_rolled_back<'a>(
2565            &'a self,
2566            lease: &'a MigrationLease,
2567            record: RolledBackRecord,
2568        ) -> ExecutionFuture<'a, JournalEntry<RolledBackRecord>> {
2569            Box::pin(async move {
2570                let mut scopes = self.scopes.lock().expect("store mutex");
2571                let state = scopes.get_mut(lease.scope()).ok_or_else(stale_fence)?;
2572                Self::check_lease(state, lease)?;
2573                if record.scope() != lease.scope() || record.fence() != lease.fence() {
2574                    return Err(stale_fence());
2575                }
2576                let active = active_applied_entries(state.applied.clone(), &state.rolled_back)?;
2577                let is_active = active.iter().any(|entry| {
2578                    entry.record().migration_id() == record.migration_id()
2579                        && entry.record().manifest_digest() == record.manifest_digest()
2580                });
2581                if !is_active {
2582                    if let Some(existing) = state.rolled_back.iter().find(|entry| {
2583                        entry.record() == &record && entry.record().fence() == lease.fence()
2584                    }) {
2585                        return Ok(existing.clone());
2586                    }
2587                    return Err(failure(
2588                        DiagnosticCategory::Integrity,
2589                        "migration_execution_retirement_conflict",
2590                        "retirement target is not active in the applied ledger",
2591                    ));
2592                }
2593                let plan = state.open_rollback_plan.as_ref().ok_or_else(|| {
2594                    failure(
2595                        DiagnosticCategory::InvalidContract,
2596                        "migration_execution_no_open_plan",
2597                        "retirement requires an open rollback plan",
2598                    )
2599                })?;
2600                let manifest_index = plan
2601                    .record()
2602                    .rollback_ids()
2603                    .iter()
2604                    .position(|id| id == record.migration_id());
2605                if manifest_index.is_none_or(|index| {
2606                    plan.record().manifest_digests().get(index) != Some(&record.manifest_digest())
2607                }) {
2608                    return Err(failure(
2609                        DiagnosticCategory::Integrity,
2610                        "migration_execution_foreign_applied_record",
2611                        "retirement identity and digest are absent from the open plan",
2612                    ));
2613                }
2614                let entry = JournalEntry::from_store(Self::sequence(state)?, record);
2615                state.rolled_back.push(entry.clone());
2616                let active = active_applied_entries(state.applied.clone(), &state.rolled_back)?;
2617                let complete = state.open_rollback_plan.as_ref().is_some_and(|plan| {
2618                    plan.record().rollback_ids().iter().all(|id| {
2619                        !active
2620                            .iter()
2621                            .any(|applied| applied.record().migration_id() == id)
2622                    })
2623                });
2624                if complete {
2625                    state.open_rollback_plan = None;
2626                    state.rollback_events.clear();
2627                    state.backfill_events.clear();
2628                }
2629                Ok(entry)
2630            })
2631        }
2632
2633        fn load_rolled_back<'a>(
2634            &'a self,
2635            lease: &'a MigrationLease,
2636        ) -> ExecutionFuture<'a, Vec<JournalEntry<RolledBackRecord>>> {
2637            Box::pin(async move {
2638                let mut scopes = self.scopes.lock().expect("store mutex");
2639                let state = scopes.get_mut(lease.scope()).ok_or_else(stale_fence)?;
2640                Self::check_lease(state, lease)?;
2641                Ok(state.rolled_back.clone())
2642            })
2643        }
2644
2645        fn load_open_rollback_plan<'a>(
2646            &'a self,
2647            lease: &'a MigrationLease,
2648        ) -> ExecutionFuture<'a, Option<OpenRollbackPlanRecord>> {
2649            Box::pin(async move {
2650                let mut scopes = self.scopes.lock().expect("store mutex");
2651                let state = scopes.get_mut(lease.scope()).ok_or_else(stale_fence)?;
2652                Self::check_lease(state, lease)?;
2653                let Some(plan) = state.open_rollback_plan.clone() else {
2654                    return Ok(None);
2655                };
2656                Ok(Some(OpenRollbackPlanRecord::from_store_with_backfills(
2657                    plan,
2658                    state.rollback_events.clone(),
2659                    state
2660                        .backfill_events
2661                        .iter()
2662                        .filter(|event| {
2663                            event.record().direction() == BackfillExecutionDirection::Reverse
2664                        })
2665                        .cloned()
2666                        .collect(),
2667                )?))
2668            })
2669        }
2670    }
2671
2672    fn stale_fence() -> Diagnostic {
2673        failure(
2674            DiagnosticCategory::Integrity,
2675            "migration_execution_stale_fence",
2676            "journal write does not carry the current active lease and fence",
2677        )
2678    }
2679
2680    fn scope() -> ExecutionScope {
2681        ExecutionScope::new(ManagedScopeId::new("journal-test").expect("scope"))
2682    }
2683
2684    fn migration_id() -> MigrationId {
2685        MigrationId::from_components(
2686            MigrationAppLabel::new("example").expect("app"),
2687            MigrationName::new("0001_initial").expect("name"),
2688        )
2689    }
2690
2691    fn semantic_fingerprint(bytes: &[u8]) -> ManagedSemanticSchemaFingerprint {
2692        ManagedSemanticSchemaFingerprint::compute(
2693            SemanticProfileId::new("typedb-3.12.1/v1").expect("profile"),
2694            bytes,
2695        )
2696        .expect("semantic fingerprint")
2697    }
2698
2699    fn fake_plan(lease: &MigrationLease) -> PlanRecord {
2700        let id = migration_id();
2701        let semantic = SemanticProfileBinding::resolve(
2702            SemanticProfileId::new("typedb-3.12.1/v1").expect("profile"),
2703        )
2704        .expect("semantic binding");
2705        PlanRecord {
2706            scope: lease.scope().clone(),
2707            fence: lease.fence(),
2708            source_applied: Vec::new(),
2709            source_frontier: Vec::new(),
2710            target_frontier: vec![id.clone()],
2711            migration_ids: vec![id],
2712            manifest_digests: vec![MigrationManifestDigest::compute(b"manifest")],
2713            manifest_plan_fingerprints: vec![
2714                MigrationPlanFingerprint::compute(&[]).expect("plan fingerprint"),
2715            ],
2716            source_declared: ManagedDeclaredIdentityFingerprint::compute(b"source")
2717                .expect("source declared"),
2718            target_declared: ManagedDeclaredIdentityFingerprint::compute(b"target")
2719                .expect("target declared"),
2720            source_semantics: semantic_fingerprint(b"source"),
2721            target_semantics: semantic_fingerprint(b"target"),
2722            semantic_profile: semantic.fingerprint().clone(),
2723            lowering_profile: schema_lowering_profile_binding()
2724                .expect("lowering binding")
2725                .fingerprint()
2726                .clone(),
2727            observed_live_source: semantic_fingerprint(b"source"),
2728        }
2729    }
2730
2731    fn fake_event(lease: &MigrationLease, plan: &PlanRecord) -> GroupEventRecord {
2732        GroupEventRecord {
2733            scope: lease.scope().clone(),
2734            fence: lease.fence(),
2735            manifest_digest: plan.manifest_digests()[0],
2736            migration_id: plan.migration_ids()[0].clone(),
2737            group_ordinal: 0,
2738            first_step_index: 0,
2739            schema_delta_step_index: 0,
2740            end_step_index: 1,
2741            kind: GroupJournalEventKind::BeforeCommit,
2742            observed_target: None,
2743        }
2744    }
2745
2746    fn fake_applied(lease: &MigrationLease, plan: &PlanRecord) -> AppliedRecord {
2747        AppliedRecord {
2748            scope: lease.scope().clone(),
2749            fence: lease.fence(),
2750            migration_id: plan.migration_ids()[0].clone(),
2751            manifest_digest: plan.manifest_digests()[0],
2752            source_declared: plan.source_declared().clone(),
2753            target_declared: plan.target_declared().clone(),
2754            source_semantics: plan.source_semantics().clone(),
2755            target_semantics: plan.target_semantics().clone(),
2756        }
2757    }
2758
2759    #[test]
2760    fn bound_lease_equality_includes_process_local_binding_identity() {
2761        let scope = scope();
2762        let holder = LeaseHolderId::new("owner").expect("holder");
2763        let fence = ExecutionFence::new(1).expect("fence");
2764        let token = ExecutionBindingToken::fresh();
2765        let same = MigrationLease::new_bound(scope.clone(), holder.clone(), fence, token.clone());
2766        let clone = same.clone();
2767        let foreign = MigrationLease::new_bound(
2768            scope.clone(),
2769            holder.clone(),
2770            fence,
2771            ExecutionBindingToken::fresh(),
2772        );
2773        let unbound = MigrationLease::new(scope.clone(), holder.clone(), fence);
2774        let same_unbound = MigrationLease::new(scope, holder, fence);
2775
2776        assert_eq!(same, clone);
2777        assert_ne!(same, foreign);
2778        assert_ne!(same, unbound);
2779        assert_eq!(unbound, same_unbound);
2780    }
2781
2782    #[test]
2783    fn store_assigns_monotonic_sequences_and_rejects_every_stale_fence_write() {
2784        let store = InMemoryStore::default();
2785        let scope = scope();
2786        let holder_a = LeaseHolderId::new("owner-a").expect("holder");
2787        let holder_b = LeaseHolderId::new("owner-b").expect("holder");
2788        let lease_a = block_on(store.acquire(&scope, &holder_a)).expect("lease a");
2789        assert!(block_on(store.acquire(&scope, &holder_b)).is_err());
2790        let plan_a = fake_plan(&lease_a);
2791        let plan_entry = block_on(store.begin_plan(&lease_a, plan_a.clone())).expect("plan");
2792        let event_entry =
2793            block_on(store.record_group_event(&lease_a, fake_event(&lease_a, &plan_a)))
2794                .expect("event");
2795        assert_eq!(plan_entry.sequence().get(), 1);
2796        assert_eq!(event_entry.sequence().get(), 2);
2797        block_on(store.release(&lease_a)).expect("release a");
2798        let lease_b = block_on(store.acquire(&scope, &holder_b)).expect("lease b");
2799        assert!(lease_b.fence() > lease_a.fence());
2800        assert!(block_on(store.begin_plan(&lease_a, plan_a.clone())).is_err());
2801        assert!(
2802            block_on(store.record_group_event(&lease_a, fake_event(&lease_a, &plan_a),)).is_err()
2803        );
2804        assert!(
2805            block_on(store.record_applied(&lease_a, fake_applied(&lease_a, &plan_a),)).is_err()
2806        );
2807        assert!(block_on(store.release(&lease_a)).is_err());
2808        let recovery_event =
2809            block_on(store.record_group_event(&lease_b, fake_event(&lease_b, &plan_a)))
2810                .expect("recovery event");
2811        assert_eq!(recovery_event.sequence().get(), 3);
2812        block_on(store.release(&lease_b)).expect("release recovery lease");
2813        let holder_c = LeaseHolderId::new("owner-c").expect("holder");
2814        let lease_c = block_on(store.acquire(&scope, &holder_c)).expect("lease c");
2815        assert!(lease_c.fence() > lease_b.fence());
2816        let open = block_on(store.load_open_plan(&lease_c))
2817            .expect("open plan")
2818            .expect("plan remains open after recovery crash");
2819        assert_eq!(open.events().len(), 2);
2820        assert_eq!(open.events()[0].record().fence(), lease_a.fence());
2821        assert_eq!(open.events()[1].record().fence(), lease_b.fence());
2822    }
2823
2824    #[test]
2825    fn applied_records_are_plan_bound_idempotent_and_close_the_completed_plan() {
2826        let store = InMemoryStore::default();
2827        let scope = scope();
2828        let holder = LeaseHolderId::new("applied-owner").expect("holder");
2829        let lease = block_on(store.acquire(&scope, &holder)).expect("lease");
2830        let plan = fake_plan(&lease);
2831        let applied = fake_applied(&lease, &plan);
2832
2833        assert!(block_on(store.record_applied(&lease, applied.clone())).is_err());
2834        block_on(store.begin_plan(&lease, plan.clone())).expect("open plan");
2835
2836        let mut foreign = applied.clone();
2837        foreign.manifest_digest = MigrationManifestDigest::compute(b"foreign");
2838        assert!(block_on(store.record_applied(&lease, foreign)).is_err());
2839
2840        let first = block_on(store.record_applied(&lease, applied.clone()))
2841            .expect("apply planned manifest");
2842        let duplicate = block_on(store.record_applied(&lease, applied))
2843            .expect("same-fence duplicate is idempotent");
2844        assert_eq!(duplicate, first);
2845        assert!(
2846            block_on(store.load_open_plan(&lease))
2847                .expect("load completed plan")
2848                .is_none()
2849        );
2850        assert_eq!(
2851            block_on(store.load_applied(&lease)).expect("load applied ledger"),
2852            vec![first],
2853        );
2854    }
2855
2856    fn fake_rollback_plan(lease: &MigrationLease, plan: &PlanRecord) -> RollbackPlanRecord {
2857        RollbackPlanRecord {
2858            scope: lease.scope().clone(),
2859            fence: lease.fence(),
2860            source_applied: plan.migration_ids().to_vec(),
2861            rollback_ids: plan.migration_ids().to_vec(),
2862            manifest_digests: plan.manifest_digests().to_vec(),
2863            manifest_plan_fingerprints: plan.manifest_plan_fingerprints().to_vec(),
2864            remaining_applied: Vec::new(),
2865            source_declared: plan.target_declared().clone(),
2866            target_declared: plan.source_declared().clone(),
2867            source_semantics: plan.target_semantics().clone(),
2868            target_semantics: plan.source_semantics().clone(),
2869            semantic_profile: plan.semantic_profile().clone(),
2870            lowering_profile: plan.lowering_profile().clone(),
2871            observed_live_source: plan.target_semantics().clone(),
2872        }
2873    }
2874
2875    fn fake_rolled_back(lease: &MigrationLease, plan: &PlanRecord) -> RolledBackRecord {
2876        RolledBackRecord {
2877            scope: lease.scope().clone(),
2878            fence: lease.fence(),
2879            migration_id: plan.migration_ids()[0].clone(),
2880            manifest_digest: plan.manifest_digests()[0],
2881            source_declared: plan.target_declared().clone(),
2882            target_declared: plan.source_declared().clone(),
2883            source_semantics: plan.target_semantics().clone(),
2884            target_semantics: plan.source_semantics().clone(),
2885        }
2886    }
2887
2888    #[test]
2889    fn retirement_is_append_only_exclusive_and_reopens_the_identity() {
2890        let store = InMemoryStore::default();
2891        let scope = scope();
2892        let holder = LeaseHolderId::new("retirement-owner").expect("holder");
2893        let lease = block_on(store.acquire(&scope, &holder)).expect("lease");
2894        let plan = fake_plan(&lease);
2895        let rollback_plan = fake_rollback_plan(&lease, &plan);
2896        let retirement = fake_rolled_back(&lease, &plan);
2897
2898        // Apply the migration through an ordinary forward plan.
2899        block_on(store.begin_plan(&lease, plan.clone())).expect("open plan");
2900        assert!(
2901            block_on(store.begin_rollback_plan(&lease, rollback_plan.clone())).is_err(),
2902            "open plans of either direction must be exclusive"
2903        );
2904        block_on(store.record_applied(&lease, fake_applied(&lease, &plan)))
2905            .expect("apply planned manifest");
2906        assert_eq!(
2907            block_on(store.load_applied(&lease)).expect("active").len(),
2908            1
2909        );
2910
2911        // Retiring outside an open rollback plan fails closed.
2912        assert!(block_on(store.record_rolled_back(&lease, retirement.clone())).is_err());
2913        block_on(store.begin_rollback_plan(&lease, rollback_plan)).expect("open rollback plan");
2914        assert!(
2915            block_on(store.begin_plan(&lease, plan.clone())).is_err(),
2916            "an open rollback plan must block a new apply plan"
2917        );
2918        let first = block_on(store.record_rolled_back(&lease, retirement.clone()))
2919            .expect("retire applied migration");
2920        let duplicate = block_on(store.record_rolled_back(&lease, retirement))
2921            .expect("same-fence duplicate retirement is idempotent");
2922        assert_eq!(duplicate, first);
2923        assert!(
2924            block_on(store.load_open_rollback_plan(&lease))
2925                .expect("closed rollback plan")
2926                .is_none()
2927        );
2928        assert!(
2929            block_on(store.load_applied(&lease))
2930                .expect("active")
2931                .is_empty()
2932        );
2933        assert_eq!(
2934            block_on(store.load_rolled_back(&lease))
2935                .expect("retired")
2936                .len(),
2937            1,
2938        );
2939
2940        // The identity is free again: a fresh forward plan re-applies it.
2941        block_on(store.begin_plan(&lease, plan.clone())).expect("reopen plan");
2942        block_on(store.record_applied(&lease, fake_applied(&lease, &plan)))
2943            .expect("re-apply retired migration");
2944        assert_eq!(
2945            block_on(store.load_applied(&lease)).expect("active").len(),
2946            1
2947        );
2948    }
2949
2950    #[test]
2951    fn unmatched_retirements_are_corrupt_history() {
2952        let store = InMemoryStore::default();
2953        let scope = scope();
2954        let holder = LeaseHolderId::new("orphan-owner").expect("holder");
2955        let lease = block_on(store.acquire(&scope, &holder)).expect("lease");
2956        let plan = fake_plan(&lease);
2957        let orphan = JournalEntry::from_store(
2958            JournalSequence::new(7).expect("sequence"),
2959            fake_rolled_back(&lease, &plan),
2960        );
2961        let error = active_applied_entries(Vec::new(), &[orphan])
2962            .expect_err("a retirement without its applied record is corrupt");
2963        assert_eq!(
2964            error.code().as_str(),
2965            "migration_execution_unmatched_retirement"
2966        );
2967    }
2968
2969    #[test]
2970    fn recovery_decision_table_is_exhaustive_for_distinct_and_equal_semantics() {
2971        let source = semantic_fingerprint(b"source");
2972        let target = semantic_fingerprint(b"target");
2973        let neither = semantic_fingerprint(b"neither");
2974        let events = [
2975            None,
2976            Some(GroupJournalEventKind::BeforeCommit),
2977            Some(GroupJournalEventKind::Committed),
2978            Some(GroupJournalEventKind::CommitOutcomeUnknown),
2979            Some(GroupJournalEventKind::DefinitelyAborted),
2980            Some(GroupJournalEventKind::FormalOnlyAdvanced),
2981        ];
2982        let observations = [
2983            GroupRecoveryObservation::ManagedSemantics(source.clone()),
2984            GroupRecoveryObservation::ManagedSemantics(target.clone()),
2985            GroupRecoveryObservation::ManagedSemantics(neither.clone()),
2986            GroupRecoveryObservation::Unavailable,
2987        ];
2988        for event in events {
2989            for observation in &observations {
2990                let expected = expected_distinct(event, observation, &source, &target);
2991                assert_eq!(
2992                    decide_group_recovery(event, observation, &source, &target),
2993                    expected,
2994                    "distinct case {event:?} {observation:?}",
2995                );
2996            }
2997        }
2998        let equal_observations = [
2999            GroupRecoveryObservation::ManagedSemantics(source.clone()),
3000            GroupRecoveryObservation::ManagedSemantics(neither),
3001            GroupRecoveryObservation::Unavailable,
3002        ];
3003        for event in events {
3004            for observation in &equal_observations {
3005                let expected = expected_equal(event, observation, &source);
3006                assert_eq!(
3007                    decide_group_recovery(event, observation, &source, &source),
3008                    expected,
3009                    "equal case {event:?} {observation:?}",
3010                );
3011            }
3012        }
3013    }
3014
3015    #[test]
3016    fn backfill_counts_and_recovery_fail_closed_without_exact_completion() {
3017        assert_eq!(
3018            BackfillExecutionCounts::new(5, 3, 1, 1)
3019                .expect_err("inconsistent counts reject")
3020                .code()
3021                .as_str(),
3022            "migration_backfill_count_mismatch"
3023        );
3024        assert_eq!(
3025            BackfillExecutionCounts::new(0, 0, 0, 0)
3026                .expect_err("zero transaction groups reject")
3027                .code()
3028                .as_str(),
3029            "migration_backfill_zero_transaction_groups"
3030        );
3031
3032        let plan = semantic_fingerprint(b"backfill-plan")
3033            .as_fingerprint()
3034            .clone();
3035        let foreign = semantic_fingerprint(b"foreign-backfill-plan")
3036            .as_fingerprint()
3037            .clone();
3038        let counts = BackfillExecutionCounts::new(5, 3, 2, 2).expect("valid counts");
3039        let complete = BackfillRecoveryObservation::Complete(BackfillCompletionEvidence::new(
3040            plan.clone(),
3041            BackfillExecutionDirection::Forward,
3042            counts,
3043        ));
3044
3045        assert_eq!(
3046            decide_backfill_recovery(
3047                None,
3048                &BackfillRecoveryObservation::Incomplete,
3049                &plan,
3050                BackfillExecutionDirection::Forward,
3051            ),
3052            GroupRecoveryDecision::ExecuteNormally
3053        );
3054        assert_eq!(
3055            decide_backfill_recovery(None, &complete, &plan, BackfillExecutionDirection::Forward,),
3056            GroupRecoveryDecision::ExecuteNormally
3057        );
3058        assert_eq!(
3059            decide_backfill_recovery(
3060                Some(GroupJournalEventKind::BeforeCommit),
3061                &BackfillRecoveryObservation::Incomplete,
3062                &plan,
3063                BackfillExecutionDirection::Forward,
3064            ),
3065            GroupRecoveryDecision::RequiresExplicitRecovery
3066        );
3067        assert_eq!(
3068            decide_backfill_recovery(
3069                Some(GroupJournalEventKind::CommitOutcomeUnknown),
3070                &complete,
3071                &plan,
3072                BackfillExecutionDirection::Forward,
3073            ),
3074            GroupRecoveryDecision::RepairCheckpoint
3075        );
3076        assert_eq!(
3077            decide_backfill_recovery(
3078                Some(GroupJournalEventKind::Committed),
3079                &complete,
3080                &foreign,
3081                BackfillExecutionDirection::Forward,
3082            ),
3083            GroupRecoveryDecision::RequiresExplicitRecovery
3084        );
3085        assert_eq!(
3086            decide_backfill_recovery(
3087                Some(GroupJournalEventKind::Committed),
3088                &complete,
3089                &plan,
3090                BackfillExecutionDirection::Reverse,
3091            ),
3092            GroupRecoveryDecision::RequiresExplicitRecovery
3093        );
3094    }
3095
3096    fn expected_distinct(
3097        event: Option<GroupJournalEventKind>,
3098        observation: &GroupRecoveryObservation,
3099        source: &ManagedSemanticSchemaFingerprint,
3100        target: &ManagedSemanticSchemaFingerprint,
3101    ) -> GroupRecoveryDecision {
3102        let source_seen = matches!(observation, GroupRecoveryObservation::ManagedSemantics(value) if value == source);
3103        let target_seen = matches!(observation, GroupRecoveryObservation::ManagedSemantics(value) if value == target);
3104        match event {
3105            None | Some(GroupJournalEventKind::DefinitelyAborted) if source_seen => {
3106                GroupRecoveryDecision::ExecuteNormally
3107            }
3108            Some(
3109                GroupJournalEventKind::BeforeCommit | GroupJournalEventKind::CommitOutcomeUnknown,
3110            ) if source_seen => GroupRecoveryDecision::ExecuteNormally,
3111            Some(
3112                GroupJournalEventKind::BeforeCommit
3113                | GroupJournalEventKind::CommitOutcomeUnknown
3114                | GroupJournalEventKind::Committed,
3115            ) if target_seen => GroupRecoveryDecision::RepairCheckpoint,
3116            _ => GroupRecoveryDecision::RequiresExplicitRecovery,
3117        }
3118    }
3119
3120    fn expected_equal(
3121        event: Option<GroupJournalEventKind>,
3122        observation: &GroupRecoveryObservation,
3123        both: &ManagedSemanticSchemaFingerprint,
3124    ) -> GroupRecoveryDecision {
3125        let both_seen = matches!(observation, GroupRecoveryObservation::ManagedSemantics(value) if value == both);
3126        if !both_seen {
3127            return GroupRecoveryDecision::RequiresExplicitRecovery;
3128        }
3129        match event {
3130            None | Some(GroupJournalEventKind::DefinitelyAborted) => {
3131                GroupRecoveryDecision::ExecuteNormally
3132            }
3133            Some(GroupJournalEventKind::Committed | GroupJournalEventKind::FormalOnlyAdvanced) => {
3134                GroupRecoveryDecision::RepairCheckpoint
3135            }
3136            _ => GroupRecoveryDecision::RequiresExplicitRecovery,
3137        }
3138    }
3139
3140    fn block_on<F: Future>(future: F) -> F::Output {
3141        let mut context = Context::from_waker(Waker::noop());
3142        let mut future = Box::pin(future);
3143        loop {
3144            match future.as_mut().poll(&mut context) {
3145                Poll::Ready(output) => return output,
3146                Poll::Pending => std::thread::yield_now(),
3147            }
3148        }
3149    }
3150}