Преглед изворни кода

Fail loudly when the loader under-fetches balances for validation

The load/validate seam guarded the "loader fetched every balance key
validation reads" invariant with a debug_assert, which is stripped in
release. But the failure it catches is silent and financial: a missing
balance key defaults to zero in validate_and_plan and can approve an
overdraft, creating value. That must hold in the shipped binary, not
just debug builds.

Promote it to a real runtime check. Add LedgerError::UnderFetchedState
carrying the missing (account, asset) key, and have plan() return it
when required_state names a balance the loader did not fetch. The cost
is one key-set re-derivation per commit, negligible next to the IO load
already did.
Cesar Rodas пре 3 месеци
родитељ
комит
bbe52aac3c
2 измењених фајлова са 53 додато и 11 уклоњено
  1. 14 0
      crates/kuatia/src/error.rs
  2. 39 11
      crates/kuatia/src/ledger/commit.rs

+ 14 - 0
crates/kuatia/src/error.rs

@@ -72,6 +72,16 @@ pub enum LedgerError {
     InflightSelfMovement(AccountId),
     /// Monetary arithmetic overflow.
     Overflow,
+    /// The loader under-fetched: a balance key `validate_and_plan` reads was not
+    /// loaded. Validation would read the missing key as zero and could approve an
+    /// overdraft, so this is failed loudly instead. A load/validate seam bug, not
+    /// a user error. Carries the missing key.
+    UnderFetchedState {
+        /// Account whose balance was not loaded.
+        account: AccountId,
+        /// Asset whose balance was not loaded.
+        asset: AssetId,
+    },
     /// A saga step failed and its compensation also failed.
     CompensationFailed {
         /// The error that triggered compensation.
@@ -114,6 +124,10 @@ impl fmt::Display for LedgerError {
                 write!(f, "inflight movement must have distinct from/to: {id:?}")
             }
             Self::Overflow => write!(f, "monetary amount overflow"),
+            Self::UnderFetchedState { account, asset } => write!(
+                f,
+                "loader under-fetched balance for account {account:?} asset {asset:?}"
+            ),
             Self::CompensationFailed {
                 original,
                 compensation,

+ 39 - 11
crates/kuatia/src/ledger/commit.rs

@@ -89,17 +89,18 @@ impl Ledger {
 
     /// Run pure validation over the loaded state and produce a plan.
     fn plan(&self, envelope: &Envelope, loaded: &LoadedState) -> Result<Plan, LedgerError> {
-        // The loader must have fetched every balance key validation reads.
-        // `compute_balance` never omits a key (an empty account is zero), so a
-        // gap here means `load` under-fetched — a silent write-skew, not a
-        // missing row. Fail loudly instead of validating against zero.
-        debug_assert!(
-            required_state(envelope, &loaded.consumed_postings)
-                .balances
-                .iter()
-                .all(|key| loaded.balances.contains_key(key)),
-            "load under-fetched balances required by validation",
-        );
+        // The loader must have fetched every balance key validation reads. A gap
+        // means `load` under-fetched: validation would read the missing key as
+        // zero and could approve an overdraft, silently creating value. This
+        // crosses the async-loader / pure-core seam, so guard it in every build,
+        // not just debug.
+        if let Some((account, asset)) = required_state(envelope, &loaded.consumed_postings)
+            .balances
+            .into_iter()
+            .find(|key| !loaded.balances.contains_key(key))
+        {
+            return Err(LedgerError::UnderFetchedState { account, asset });
+        }
 
         let input = PlanInput {
             envelope,
@@ -1060,4 +1061,31 @@ mod recovery_tests {
         assert!(ledger.store().list_pending_sagas().await?.is_empty());
         Ok(())
     }
+
+    /// If the loader under-fetches a balance key validation reads, `plan` fails
+    /// loudly rather than letting the missing key default to zero and silently
+    /// approve an overdraft. This guards the async-loader / pure-core seam in
+    /// every build, not just debug.
+    #[tokio::test]
+    async fn plan_rejects_under_fetched_balance() -> Result<(), LedgerError> {
+        let ledger = funded_ledger().await;
+        let envelope = ledger.resolve(&pay_transfer()).await?;
+        let mut loaded = ledger.load(&envelope).await?;
+
+        // Drop a key the loader correctly fetched; validation still reads it.
+        let dropped = *loaded
+            .balances
+            .keys()
+            .next()
+            .expect("pay transfer reads at least one balance");
+        loaded.balances.remove(&dropped);
+
+        match ledger.plan(&envelope, &loaded) {
+            Err(LedgerError::UnderFetchedState { account, asset }) => {
+                assert_eq!((account, asset), dropped);
+            }
+            other => panic!("expected UnderFetchedState, got {other:?}"),
+        }
+        Ok(())
+    }
 }