Эх сурвалжийг харах

Give the write-ahead saga keyspace a typed kind discriminator

Commit sagas and account transitions share one flat saga keyspace. They
were told apart only by an in-band enum tag inside the opaque blob, and
their keys avoided collision only because both drew from the reservation
generator, a fact a comment promised. The transition also masqueraded as
a reservation just to borrow that generator.

Make the kind a typed, first-class column. SagaStore stores and returns a
SagaKind, so recovery dispatches by type instead of decoding the blob;
the PendingRecord wrapper enum is gone and each payload is serialized
directly under its kind. A transition now mints a TransitionId (a
distinct type sharing the one saga-id generator, so ids stay globally
unique and get/delete still key by id alone). Adds migration 009 for the
kind column and a conformance test that a mixed keyspace lists each
record with its kind.
Cesar Rodas 3 сар өмнө
parent
commit
0a3bf0d938

+ 4 - 0
crates/kuatia-storage-sql/src/migrate.rs

@@ -48,6 +48,10 @@ impl SqlStore {
                 "008_live_postings",
                 include_str!("migrations/008_live_postings.sql"),
             ),
+            (
+                "009_saga_kind",
+                include_str!("migrations/009_saga_kind.sql"),
+            ),
         ];
 
         for (name, sql) in migrations {

+ 6 - 0
crates/kuatia-storage-sql/src/migrations/009_saga_kind.sql

@@ -0,0 +1,6 @@
+-- Typed discriminator for the write-ahead saga keyspace. Both commit sagas and
+-- account transitions share the sagas table, so kind records which a row is and
+-- recovery dispatches by a typed column instead of an in-band blob tag. The id
+-- stays the primary key (all ids come from one generator, so it is unique across
+-- kinds). The default keeps any surviving row valid as an envelope commit.
+ALTER TABLE sagas ADD COLUMN kind TEXT NOT NULL DEFAULT 'envelope';

+ 10 - 6
crates/kuatia-storage-sql/src/saga.rs

@@ -11,12 +11,13 @@ use crate::row::{from_hex, to_hex};
 
 #[async_trait]
 impl SagaStore for SqlStore {
-    async fn save_saga(&self, id: &i64, data: Vec<u8>) -> Result<(), StoreError> {
+    async fn save_saga(&self, kind: SagaKind, id: &i64, data: Vec<u8>) -> Result<(), StoreError> {
         sqlx::query(
-            "INSERT INTO sagas (id, data) VALUES ($1, $2) \
-             ON CONFLICT (id) DO UPDATE SET data = EXCLUDED.data",
+            "INSERT INTO sagas (id, kind, data) VALUES ($1, $2, $3) \
+             ON CONFLICT (id) DO UPDATE SET kind = EXCLUDED.kind, data = EXCLUDED.data",
         )
         .bind(*id)
+        .bind(kind.as_str())
         .bind(to_hex(&data))
         .execute(&self.pool)
         .await
@@ -24,8 +25,8 @@ impl SagaStore for SqlStore {
         Ok(())
     }
 
-    async fn list_pending_sagas(&self) -> Result<Vec<(i64, Vec<u8>)>, StoreError> {
-        let rows = sqlx::query("SELECT id, data FROM sagas")
+    async fn list_pending_sagas(&self) -> Result<Vec<(SagaKind, i64, Vec<u8>)>, StoreError> {
+        let rows = sqlx::query("SELECT id, kind, data FROM sagas")
             .fetch_all(&self.pool)
             .await
             .map_err(|e| StoreError::Internal(e.to_string()))?;
@@ -34,10 +35,13 @@ impl SagaStore for SqlStore {
             let id: i64 = row
                 .try_get("id")
                 .map_err(|e| StoreError::Internal(e.to_string()))?;
+            let kind: String = row
+                .try_get("kind")
+                .map_err(|e| StoreError::Internal(e.to_string()))?;
             let data_hex: String = row
                 .try_get("data")
                 .map_err(|e| StoreError::Internal(e.to_string()))?;
-            result.push((id, from_hex(&data_hex)?));
+            result.push((SagaKind::parse(&kind)?, id, from_hex(&data_hex)?));
         }
         Ok(result)
     }

+ 9 - 0
crates/kuatia-storage-sql/tests/sqlite.rs

@@ -152,6 +152,12 @@ async fn migration_upgrades_existing_rows_to_main_account() {
         .execute(&pool)
         .await
         .unwrap();
+    // The sagas table has existed since 001; seed it so the 009 ALTER (add the
+    // kind column) has a table to run against on this full-chain upgrade.
+    sqlx::query("CREATE TABLE sagas (id BIGINT PRIMARY KEY, data TEXT NOT NULL)")
+        .execute(&pool)
+        .await
+        .unwrap();
     // Legacy 001/002 schema carried a user_data JSON column; the 003 migration
     // drops it. Seed it with the value the old UserData type serialized to.
     let user_data = r#"{"d128":0,"d64":0,"d32":0}"#.to_string();
@@ -233,6 +239,7 @@ async fn migration_004_backfills_index_tables() {
         "006_drop_policy",
         "007_balance_projection",
         "008_live_postings",
+        "009_saga_kind",
     ] {
         sqlx::query("INSERT INTO _migrations (name) VALUES ($1)")
             .bind(m)
@@ -323,6 +330,7 @@ async fn migration_005_backfills_account_head() {
         "006_drop_policy",
         "007_balance_projection",
         "008_live_postings",
+        "009_saga_kind",
     ] {
         sqlx::query("INSERT INTO _migrations (name) VALUES ($1)")
             .bind(m)
@@ -393,6 +401,7 @@ async fn migration_008_merges_live_postings() {
         "005_account_head",
         "006_drop_policy",
         "007_balance_projection",
+        "009_saga_kind",
     ] {
         sqlx::query("INSERT INTO _migrations (name) VALUES ($1)")
             .bind(m)

+ 10 - 7
crates/kuatia-storage/src/mem_store.rs

@@ -18,7 +18,7 @@ use crate::events::{EventStore, LedgerEvent, event_dedup_key};
 use crate::query::{filter_transfers, paginate};
 use crate::store::{
     AccountStore, BalanceProjection, BalanceProjectionStore, BookStore, EnvelopeRecord, Page,
-    PostingStore, SagaStore, TransferQuery, TransferStore,
+    PostingStore, SagaKind, SagaStore, TransferQuery, TransferStore,
 };
 
 /// Postings held as an immutable record table plus two index maps that carry
@@ -44,7 +44,7 @@ pub struct InMemoryStore {
     /// `store_transfer`, mirroring the SQL `transfer_accounts` table so both
     /// backends resolve `get_transfers_for_account` from the same instruction.
     transfer_accounts: RwLock<HashMap<EnvelopeId, Vec<AccountId>>>,
-    sagas: RwLock<HashMap<i64, Vec<u8>>>,
+    sagas: RwLock<HashMap<i64, (SagaKind, Vec<u8>)>>,
     events: RwLock<Vec<LedgerEvent>>,
     books: RwLock<HashMap<BookId, Book>>,
     /// Append-only balance cache points keyed by `(account, asset)` (ADR-0019).
@@ -437,20 +437,23 @@ impl TransferStore for InMemoryStore {
 
 #[async_trait]
 impl SagaStore for InMemoryStore {
-    async fn save_saga(&self, id: &i64, data: Vec<u8>) -> Result<(), StoreError> {
+    async fn save_saga(&self, kind: SagaKind, id: &i64, data: Vec<u8>) -> Result<(), StoreError> {
         let mut sagas = self.sagas.write().await;
-        sagas.insert(*id, data);
+        sagas.insert(*id, (kind, data));
         Ok(())
     }
 
-    async fn list_pending_sagas(&self) -> Result<Vec<(i64, Vec<u8>)>, StoreError> {
+    async fn list_pending_sagas(&self) -> Result<Vec<(SagaKind, i64, Vec<u8>)>, StoreError> {
         let sagas = self.sagas.read().await;
-        Ok(sagas.iter().map(|(k, v)| (*k, v.clone())).collect())
+        Ok(sagas
+            .iter()
+            .map(|(id, (kind, data))| (*kind, *id, data.clone()))
+            .collect())
     }
 
     async fn get_saga(&self, id: &i64) -> Result<Option<Vec<u8>>, StoreError> {
         let sagas = self.sagas.read().await;
-        Ok(sagas.get(id).cloned())
+        Ok(sagas.get(id).map(|(_, data)| data.clone()))
     }
 
     async fn delete_saga(&self, id: &i64) -> Result<(), StoreError> {

+ 40 - 4
crates/kuatia-storage/src/store.rs

@@ -236,13 +236,49 @@ pub trait TransferStore: Send + Sync {
     ) -> Result<Page<EnvelopeRecord>, StoreError>;
 }
 
+/// Which kind of write-ahead record a saga row holds. A typed discriminator on
+/// the shared saga keyspace: the store stores and returns it so recovery can
+/// dispatch by type rather than by decoding the opaque blob to read an in-band
+/// tag. Persisted as its [`as_str`](SagaKind::as_str) TEXT form.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum SagaKind {
+    /// A two-step envelope commit saga (reserve → finalize).
+    Envelope,
+    /// A single account-version transition (append version + lifecycle event).
+    Transition,
+}
+
+impl SagaKind {
+    /// The stored TEXT form of this kind.
+    pub fn as_str(&self) -> &'static str {
+        match self {
+            Self::Envelope => "envelope",
+            Self::Transition => "transition",
+        }
+    }
+
+    /// Parse the stored TEXT form back into a kind.
+    pub fn parse(s: &str) -> Result<Self, StoreError> {
+        match s {
+            "envelope" => Ok(Self::Envelope),
+            "transition" => Ok(Self::Transition),
+            other => Err(StoreError::Internal(format!("unknown saga kind: {other}"))),
+        }
+    }
+}
+
 /// Saga state persistence for crash recovery.
+///
+/// One flat `id → (kind, bytes)` keyspace holds both write-ahead kinds. `id` is
+/// globally unique (all ids come from one generator), so `get`/`delete` locate a
+/// row by `id` alone; `kind` is carried so `list_pending_sagas` can hand recovery
+/// a typed discriminator instead of an in-band blob tag.
 #[async_trait]
 pub trait SagaStore: Send + Sync {
-    /// Persist a saga execution state.
-    async fn save_saga(&self, id: &i64, data: Vec<u8>) -> Result<(), StoreError>;
-    /// Load all pending (incomplete) saga states.
-    async fn list_pending_sagas(&self) -> Result<Vec<(i64, Vec<u8>)>, StoreError>;
+    /// Persist a saga execution state under `id`, tagged with its [`SagaKind`].
+    async fn save_saga(&self, kind: SagaKind, id: &i64, data: Vec<u8>) -> Result<(), StoreError>;
+    /// Load all pending (incomplete) saga states with their kind.
+    async fn list_pending_sagas(&self) -> Result<Vec<(SagaKind, i64, Vec<u8>)>, StoreError>;
     /// Load one saga state by id, or `None` if no record is stored under `id`.
     /// A keyed read so a caller checking a single in-flight saga does not scan
     /// every pending record.

+ 37 - 6
crates/kuatia-storage/src/store_tests.rs

@@ -1122,22 +1122,29 @@ pub async fn query_transfers_store_wide(store: &(impl Store + 'static)) {
 // SagaStore tests
 // ---------------------------------------------------------------------------
 
-/// Save saga state and list it.
+/// Save saga state and list it with its kind.
 pub async fn save_and_list_sagas(store: &(impl Store + 'static)) {
     let id: i64 = 42;
     let data = vec![1, 2, 3];
-    store.save_saga(&id, data.clone()).await.unwrap();
+    store
+        .save_saga(SagaKind::Envelope, &id, data.clone())
+        .await
+        .unwrap();
 
     let pending = store.list_pending_sagas().await.unwrap();
     assert_eq!(pending.len(), 1);
-    assert_eq!(pending[0].0, id);
-    assert_eq!(pending[0].1, data);
+    assert_eq!(pending[0].0, SagaKind::Envelope);
+    assert_eq!(pending[0].1, id);
+    assert_eq!(pending[0].2, data);
 }
 
 /// Delete a saga state.
 pub async fn delete_saga(store: &(impl Store + 'static)) {
     let id: i64 = 42;
-    store.save_saga(&id, vec![1, 2, 3]).await.unwrap();
+    store
+        .save_saga(SagaKind::Envelope, &id, vec![1, 2, 3])
+        .await
+        .unwrap();
     store.delete_saga(&id).await.unwrap();
 
     let pending = store.list_pending_sagas().await.unwrap();
@@ -1151,7 +1158,10 @@ pub async fn get_saga_by_id(store: &(impl Store + 'static)) {
     let data = vec![7, 8, 9];
     assert!(store.get_saga(&id).await.unwrap().is_none());
 
-    store.save_saga(&id, data.clone()).await.unwrap();
+    store
+        .save_saga(SagaKind::Envelope, &id, data.clone())
+        .await
+        .unwrap();
     assert_eq!(store.get_saga(&id).await.unwrap(), Some(data));
     // A different id is still absent while this one exists.
     assert!(store.get_saga(&99).await.unwrap().is_none());
@@ -1160,6 +1170,26 @@ pub async fn get_saga_by_id(store: &(impl Store + 'static)) {
     assert!(store.get_saga(&id).await.unwrap().is_none());
 }
 
+/// Both write-ahead kinds share one keyspace: `list_pending_sagas` returns each
+/// record with the kind it was saved under, so recovery can dispatch by type
+/// rather than by decoding the blob.
+pub async fn mixed_saga_kinds_list_with_their_kinds(store: &(impl Store + 'static)) {
+    store
+        .save_saga(SagaKind::Envelope, &1, vec![10])
+        .await
+        .unwrap();
+    store
+        .save_saga(SagaKind::Transition, &2, vec![20])
+        .await
+        .unwrap();
+
+    let mut pending = store.list_pending_sagas().await.unwrap();
+    pending.sort_by_key(|(_, id, _)| *id);
+    assert_eq!(pending.len(), 2);
+    assert_eq!(pending[0], (SagaKind::Envelope, 1, vec![10]));
+    assert_eq!(pending[1], (SagaKind::Transition, 2, vec![20]));
+}
+
 // ---------------------------------------------------------------------------
 // EventStore tests
 // ---------------------------------------------------------------------------
@@ -1405,6 +1435,7 @@ macro_rules! store_tests {
             save_and_list_sagas,
             get_saga_by_id,
             delete_saga,
+            mixed_saga_kinds_list_with_their_kinds,
             // EventStore
             append_and_query_events,
             events_sequence_ordering,

+ 38 - 7
crates/kuatia-types/src/ids.rs

@@ -78,6 +78,13 @@ pub struct BookId(pub i64);
 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
 pub struct ReservationId(pub i64);
 
+/// Identifies an account-version transition's write-ahead record. A distinct
+/// type from [`ReservationId`] so a transition does not masquerade as a
+/// reservation, but drawn from the same generator (see [`ReservationId::default`])
+/// so the two write-ahead kinds share one collision-free id space.
+#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
+pub struct TransitionId(pub i64);
+
 // ---------------------------------------------------------------------------
 // Debug impls for identifiers
 // ---------------------------------------------------------------------------
@@ -125,6 +132,12 @@ impl fmt::Debug for ReservationId {
     }
 }
 
+impl fmt::Debug for TransitionId {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        write!(f, "TransitionId({})", self.0)
+    }
+}
+
 fn hex(bytes: &[u8]) -> String {
     bytes.iter().map(|b| format!("{b:02x}")).collect()
 }
@@ -220,14 +233,32 @@ impl ReservationId {
     }
 }
 
+/// The one process-global id source behind every write-ahead saga key —
+/// reservation ids and transition ids alike. One atomic counter, not one per
+/// thread: a `thread_local` generator lets two sagas on different threads mint
+/// the same id within a millisecond, which collapses the reservation-ownership
+/// check and allows a double-spend under concurrency. Sharing it across both
+/// kinds is also what keeps their keys unique in the single saga keyspace.
+fn next_saga_id() -> i64 {
+    static GEN: AutoId = AutoId::new();
+    GEN.next()
+}
+
 impl Default for ReservationId {
     fn default() -> Self {
-        // One process-global generator, not one per thread: its atomic counter
-        // makes every reservation id unique across threads. A `thread_local`
-        // generator lets two sagas on different threads mint the same id within
-        // a millisecond, which collapses the reservation-ownership check and
-        // allows a double-spend under concurrency.
-        static GEN: AutoId = AutoId::new();
-        Self(GEN.next())
+        Self(next_saga_id())
+    }
+}
+
+impl TransitionId {
+    /// Create a `TransitionId` from an `i64`.
+    pub const fn new(id: i64) -> Self {
+        Self(id)
+    }
+}
+
+impl Default for TransitionId {
+    fn default() -> Self {
+        Self(next_saga_id())
     }
 }

+ 1 - 1
crates/kuatia-types/src/lib.rs

@@ -35,7 +35,7 @@ pub use book::{Book, BookBuilder, BookPolicy};
 pub use envelope::{Envelope, EnvelopeBuilder, Metadata};
 pub use ids::{
     AccountId, AccountSnapshotId, AssetId, BookId, DEFAULT_BOOK, EnvelopeId, PostingId,
-    ReservationId,
+    ReservationId, TransitionId,
 };
 pub use posting::{NewPosting, Posting, PostingFilter, PostingState};
 pub use transfer::{Movement, Receipt, Transfer, TransferBuilder};

+ 37 - 24
crates/kuatia/src/ledger/commit.rs

@@ -21,13 +21,13 @@ use kuatia_core::{
 
 use kuatia_storage::error::StoreError;
 use kuatia_storage::events::{LedgerEvent, LedgerEventKind};
-use kuatia_storage::store::EnvelopeRecord;
+use kuatia_storage::store::{EnvelopeRecord, SagaKind};
 
 use super::{Ledger, now_millis};
 use crate::error::LedgerError;
 use crate::saga::{apply_and_verify, consume_reserved, verify_postings};
 
-use super::pending::{PendingRecord, PendingSaga, SagaPhase};
+use super::pending::{PendingSaga, PendingTransition, SagaPhase};
 
 /// State loaded in phase 1, passed to the pure validation in phase 2.
 struct LoadedState {
@@ -284,20 +284,27 @@ impl Ledger {
     /// Complete every pending write-ahead record left by a crash. Call on
     /// startup; returns how many were processed.
     ///
-    /// Each record is decoded and driven to a terminal state by
-    /// `PendingRecord::complete` (in the `pending` module), which owns the
-    /// per-kind completion: a transition rolls forward; an envelope commit
-    /// branches on its persisted phase — a `Reserving` saga is re-run and
-    /// re-validated, a `Finalizing` saga is rolled forward through the verified
-    /// `finalize_envelope`.
+    /// Each record is dispatched on its stored [`SagaKind`] and driven to a
+    /// terminal state by the completion method in the `pending` module: a
+    /// transition rolls forward; an envelope commit branches on its persisted
+    /// phase — a `Reserving` saga is re-run and re-validated, a `Finalizing` saga
+    /// is rolled forward through the verified `finalize_envelope`.
     #[instrument(skip(self), name = "ledger.recover")]
     pub async fn recover(self: &Arc<Self>) -> Result<usize, LedgerError> {
         let pending = self.store.list_pending_sagas().await?;
         let count = pending.len();
-        for (saga_id, blob) in pending {
-            PendingRecord::decode(&blob)?
-                .complete(self, saga_id)
-                .await?;
+        for (kind, saga_id, blob) in pending {
+            // Dispatch on the store's typed kind, not an in-band blob tag. The
+            // commit lifecycle (phase rules, delete-safety) lives on `PendingSaga`;
+            // a transition rolls itself forward.
+            match kind {
+                SagaKind::Envelope => PendingSaga::decode(&blob)?.complete(self).await?,
+                SagaKind::Transition => {
+                    PendingTransition::decode(&blob)?
+                        .complete(self, saga_id)
+                        .await?
+                }
+            }
         }
         Ok(count)
     }
@@ -437,8 +444,10 @@ impl Ledger {
     /// (which has no phase). Used to decide whether a failed commit reached the
     /// point of no return.
     pub(super) async fn saga_phase(&self, saga_id: i64) -> Result<Option<SagaPhase>, LedgerError> {
+        // Only ever called with an envelope saga's key (its reservation id), so the
+        // record decodes as a `PendingSaga`; a transition never reaches here.
         match self.store.get_saga(&saga_id).await? {
-            Some(blob) => Ok(PendingRecord::decode(&blob)?.envelope_phase()),
+            Some(blob) => Ok(Some(PendingSaga::decode(&blob)?.phase)),
             None => Ok(None),
         }
     }
@@ -511,7 +520,7 @@ impl Ledger {
 mod recovery_tests {
     use super::super::pending::{PendingSaga, PendingTransition};
     use super::*;
-    use kuatia_core::{Account, AccountFlags, ReservationId, TransferBuilder};
+    use kuatia_core::{Account, AccountFlags, ReservationId, TransferBuilder, TransitionId};
     use kuatia_storage::mem_store::InMemoryStore;
     use std::collections::BTreeMap;
 
@@ -565,13 +574,17 @@ mod recovery_tests {
         rid: ReservationId,
         phase: SagaPhase,
     ) {
-        let blob = serde_json::to_vec(&PendingRecord::Envelope(PendingSaga {
+        let blob = serde_json::to_vec(&PendingSaga {
             envelope: envelope.clone(),
             reservation: rid,
             phase,
-        }))
+        })
         .unwrap();
-        ledger.store().save_saga(&rid.0, blob).await.unwrap();
+        ledger
+            .store()
+            .save_saga(SagaKind::Envelope, &rid.0, blob)
+            .await
+            .unwrap();
     }
 
     /// A commit interrupted right after its write-ahead record (phase Reserving,
@@ -858,13 +871,13 @@ mod recovery_tests {
         next: &Account,
         event: &LedgerEventKind,
     ) -> Result<i64, LedgerError> {
-        let saga_id = ReservationId::default().0;
-        let blob = serde_json::to_vec(&PendingRecord::Transition(PendingTransition {
-            next: next.clone(),
-            event: event.clone(),
-        }))
-        .map_err(|e| LedgerError::Store(StoreError::Internal(e.to_string())))?;
-        ledger.store().save_saga(&saga_id, blob).await?;
+        let saga_id = TransitionId::default().0;
+        let blob = serde_json::to_vec(&PendingTransition::new(next.clone(), event.clone()))
+            .map_err(|e| LedgerError::Store(StoreError::Internal(e.to_string())))?;
+        ledger
+            .store()
+            .save_saga(SagaKind::Transition, &saga_id, blob)
+            .await?;
         Ok(saga_id)
     }
 

+ 75 - 103
crates/kuatia/src/ledger/pending.rs

@@ -3,21 +3,24 @@
 //! A commit (reserve → finalize) and an account-version transition (append
 //! version → append event) are each more than one store write with no shared
 //! transaction, so a crash mid-sequence can leave a half-applied state. Before
-//! either mutates anything it persists a [`PendingRecord`] via `SagaStore`; on
-//! startup [`Ledger::recover`](super::Ledger::recover) loads every surviving
-//! record and drives it to a terminal state through [`PendingRecord::complete`].
+//! either mutates anything it persists a write-ahead record via `SagaStore`,
+//! tagged with its [`SagaKind`]; on startup
+//! [`Ledger::recover`](super::Ledger::recover) loads every surviving record and,
+//! dispatching on that kind, drives it to a terminal state.
 //!
 //! This module owns the whole write-ahead concept behind one seam: what a
-//! pending record *is*, how it is (de)serialized, how it is persisted, and how
-//! each kind completes. The completion primitives it calls (`finalize_envelope`,
-//! `reserve_and_finalize`) stay on [`Ledger`] because the live commit path shares
-//! them; this module sequences them for the recovery path.
+//! pending record *is* ([`PendingSaga`] / [`PendingTransition`]), how it is
+//! (de)serialized, how it is persisted, and how each kind completes. The
+//! completion primitives it calls (`finalize_envelope`, `reserve_and_finalize`)
+//! stay on [`Ledger`] because the live commit path shares them; this module
+//! sequences them for the recovery path.
 
 use std::sync::Arc;
 
 use kuatia_core::{Account, Envelope, Receipt, ReservationId, envelope_id};
 use kuatia_storage::error::StoreError;
 use kuatia_storage::events::{LedgerEvent, LedgerEventKind};
+use kuatia_storage::store::SagaKind;
 
 use super::{Ledger, now_millis};
 use crate::error::LedgerError;
@@ -59,68 +62,10 @@ pub(super) struct PendingTransition {
     pub(super) event: LedgerEventKind,
 }
 
-/// The two kinds of write-ahead record the [`SagaStore`] holds, tagged so
-/// recovery can tell an envelope commit saga from an account transition and
-/// complete each through its own path.
-#[derive(serde::Serialize, serde::Deserialize)]
-pub(super) enum PendingRecord {
-    /// A two-step envelope commit saga (reserve → finalize).
-    Envelope(PendingSaga),
-    /// A single account-version transition (append version + lifecycle event).
-    Transition(PendingTransition),
-}
-
-impl PendingRecord {
-    /// An account-transition write-ahead record.
-    pub(super) fn transition(next: Account, event: LedgerEventKind) -> Self {
-        Self::Transition(PendingTransition { next, event })
-    }
-
-    /// Decode a record from its stored bytes. The single decoder for the
-    /// write-ahead format, shared by `recover` and the keyed phase read.
-    pub(super) fn decode(blob: &[u8]) -> Result<Self, LedgerError> {
-        serde_json::from_slice(blob)
-            .map_err(|e| LedgerError::Store(StoreError::Internal(e.to_string())))
-    }
-
-    /// The commit phase of an envelope record; `None` for a transition record,
-    /// which has no phase.
-    pub(super) fn envelope_phase(&self) -> Option<SagaPhase> {
-        match self {
-            Self::Envelope(s) => Some(s.phase),
-            Self::Transition(_) => None,
-        }
-    }
-
-    /// Persist this record under `saga_id` (upsert on the id).
-    pub(super) async fn save(&self, ledger: &Ledger, saga_id: i64) -> Result<(), LedgerError> {
-        let blob = serde_json::to_vec(self)
-            .map_err(|e| LedgerError::Store(StoreError::Internal(e.to_string())))?;
-        ledger.store.save_saga(&saga_id, blob).await?;
-        Ok(())
-    }
-
-    /// Drive this record to a terminal state and clear it when safe. Called by
-    /// [`Ledger::recover`](super::Ledger::recover) for every surviving record.
-    ///
-    /// A transition rolls forward (any completion error propagates, so recovery
-    /// retries on the next run). An envelope commit branches on its phase, and
-    /// its drive/finalize failures are absorbed here (the record is kept for a
-    /// later run) rather than aborting recovery of the remaining records.
-    pub(super) async fn complete(
-        self,
-        ledger: &Arc<Ledger>,
-        saga_id: i64,
-    ) -> Result<(), LedgerError> {
-        match self {
-            Self::Transition(PendingTransition { next, event }) => {
-                complete_transition(ledger, saga_id, next, event).await
-            }
-            // The commit lifecycle (phase rules, delete-safety) lives on
-            // `PendingSaga`; recovery just hands the decoded record to it.
-            Self::Envelope(saga) => saga.complete(ledger).await,
-        }
-    }
+/// Map a JSON (de)serialization failure to a store error. The write-ahead format
+/// is a store implementation detail, so a codec failure surfaces as `Store`.
+fn json_err(e: serde_json::Error) -> LedgerError {
+    LedgerError::Store(StoreError::Internal(e.to_string()))
 }
 
 impl PendingSaga {
@@ -149,13 +94,21 @@ impl PendingSaga {
         self.reservation.0
     }
 
+    /// Decode an envelope commit record from its stored bytes.
+    pub(super) fn decode(blob: &[u8]) -> Result<Self, LedgerError> {
+        serde_json::from_slice(blob).map_err(json_err)
+    }
+
     /// Persist this record at its current phase (upsert). The single writer of a
     /// commit write-ahead record: the Reserving→Finalizing bump is just a persist
     /// of the [`finalizing`](Self::finalizing) variant.
     pub(super) async fn persist(&self, ledger: &Ledger) -> Result<(), LedgerError> {
-        PendingRecord::Envelope(self.clone())
-            .save(ledger, self.saga_id())
-            .await
+        let blob = serde_json::to_vec(self).map_err(json_err)?;
+        ledger
+            .store
+            .save_saga(SagaKind::Envelope, &self.saga_id(), blob)
+            .await?;
+        Ok(())
     }
 
     /// Run a fresh commit end to end: write-ahead at Reserving, reserve then
@@ -194,7 +147,7 @@ impl PendingSaga {
     /// Complete a crash-interrupted commit from its persisted phase, clearing the
     /// record when safe. The recovery counterpart of [`run`](Self::run): same
     /// lifecycle rules, entered from a decoded record instead of a fresh one.
-    async fn complete(self, ledger: &Arc<Ledger>) -> Result<(), LedgerError> {
+    pub(super) async fn complete(self, ledger: &Arc<Ledger>) -> Result<(), LedgerError> {
         // A full commit is the transfer row plus its committed event (appended
         // after store_transfer). If the row is present the commit reached the far
         // side; repair the possibly-missing event (idempotent) and clear.
@@ -231,35 +184,54 @@ impl PendingSaga {
     }
 }
 
-/// Roll a crash-interrupted transition forward and clear its write-ahead record.
-///
-/// Idempotent in every crash window: the version append runs only into an empty
-/// version slot (`append_account_version` requires `version == current + 1`, so a
-/// blind retry after it applied would fail), and the event carries its target
-/// version so re-appending it dedups to the original. The empty-slot guard also
-/// subsumes the forward path's is_closed check: a close always bumps the version,
-/// so a since-closed account sits at `version >= next.version` and is skipped.
-async fn complete_transition(
-    ledger: &Ledger,
-    saga_id: i64,
-    next: Account,
-    event: LedgerEventKind,
-) -> Result<(), LedgerError> {
-    // The account is guaranteed to exist here (its version was bumped, or is
-    // about to be), so a read failure is transient or a real invariant breach,
-    // not "not found": surface it verbatim so recovery retries.
-    let current = ledger.store.get_account(&next.id).await?;
-    if current.version < next.version {
-        ledger.store.append_account_version(next).await?;
+impl PendingTransition {
+    /// A transition write-ahead record for a version bump and its lifecycle event.
+    pub(super) fn new(next: Account, event: LedgerEventKind) -> Self {
+        Self { next, event }
+    }
+
+    /// Decode a transition record from its stored bytes.
+    pub(super) fn decode(blob: &[u8]) -> Result<Self, LedgerError> {
+        serde_json::from_slice(blob).map_err(json_err)
+    }
+
+    /// Persist this record under `saga_id` (upsert).
+    pub(super) async fn save(&self, ledger: &Ledger, saga_id: i64) -> Result<(), LedgerError> {
+        let blob = serde_json::to_vec(self).map_err(json_err)?;
+        ledger
+            .store
+            .save_saga(SagaKind::Transition, &saga_id, blob)
+            .await?;
+        Ok(())
+    }
+
+    /// Roll a crash-interrupted transition forward and clear its write-ahead
+    /// record.
+    ///
+    /// Idempotent in every crash window: the version append runs only into an
+    /// empty version slot (`append_account_version` requires `version == current +
+    /// 1`, so a blind retry after it applied would fail), and the event carries its
+    /// target version so re-appending it dedups to the original. The empty-slot
+    /// guard also subsumes the forward path's is_closed check: a close always bumps
+    /// the version, so a since-closed account sits at `version >= next.version` and
+    /// is skipped.
+    pub(super) async fn complete(self, ledger: &Ledger, saga_id: i64) -> Result<(), LedgerError> {
+        // The account is guaranteed to exist here (its version was bumped, or is
+        // about to be), so a read failure is transient or a real invariant breach,
+        // not "not found": surface it verbatim so recovery retries.
+        let current = ledger.store.get_account(&self.next.id).await?;
+        if current.version < self.next.version {
+            ledger.store.append_account_version(self.next).await?;
+        }
+        ledger
+            .store
+            .append_event(&LedgerEvent {
+                seq: 0,
+                timestamp: now_millis()?,
+                kind: self.event,
+            })
+            .await?;
+        ledger.store.delete_saga(&saga_id).await?;
+        Ok(())
     }
-    ledger
-        .store
-        .append_event(&LedgerEvent {
-            seq: 0,
-            timestamp: now_millis()?,
-            kind: event,
-        })
-        .await?;
-    ledger.store.delete_saga(&saga_id).await?;
-    Ok(())
 }

+ 7 - 6
crates/kuatia/src/ledger/transition.rs

@@ -15,10 +15,10 @@
 //! already present, and the event carries its target version so a second append
 //! dedups to the original.
 
-use kuatia_core::{AccountFlags, AccountId, ReservationId};
+use kuatia_core::{AccountFlags, AccountId, TransitionId};
 use kuatia_storage::events::{LedgerEvent, LedgerEventKind};
 
-use super::pending::PendingRecord;
+use super::pending::PendingTransition;
 use super::{Ledger, now_millis};
 use crate::error::LedgerError;
 
@@ -53,10 +53,11 @@ impl Ledger {
 
         // Write-ahead before either write. A crash between the version append and
         // the event append is then repaired by recover(), not left dangling. The
-        // key shares the reservation-id generator so it never collides with an
-        // in-flight commit saga's key.
-        let saga_id = ReservationId::default().0;
-        PendingRecord::transition(next.clone(), event.clone())
+        // record is tagged `Transition` in the store, and its id comes from the
+        // shared saga-id generator, so it lands in its own typed slot without
+        // colliding with an in-flight commit saga's key.
+        let saga_id = TransitionId::default().0;
+        PendingTransition::new(next.clone(), event.clone())
             .save(self, saga_id)
             .await?;