From 2516bc0b7b5c4e906b51cea82f6424fd7975d610 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 2 Nov 2026 12:31:20 -0600 Subject: [PATCH] fix(id): recovery skips unreadable intent entries instead of aborting (#4125) FileIntentStore::unresolved aborted on the first unreadable or unparseable *.json entry, so one corrupt or foreign file (or a *.json subdirectory) froze recovery for every pending conversion. The listing now skips such entries, never deletes them, and reports them via the new IntentStore::unreadable_entries (the trait contract documents the skip semantics); reconcile logs each skipped entry distinctly and reconciles everything readable. Tests cover a corrupt sibling file and a *.json subdirectory alongside a valid Recorded intent. --- pkgs/id/src/currency_poc/intent.rs | 89 +++++++++++++++++++++++++--- pkgs/id/src/currency_poc/recovery.rs | 13 +++- pkgs/id/src/currency_poc/tests.rs | 65 ++++++++++++++++++++ 3 files changed, 159 insertions(+), 8 deletions(-) diff --git a/pkgs/id/src/currency_poc/intent.rs b/pkgs/id/src/currency_poc/intent.rs index 9904fa8f9e..0d7cc781cb 100644 --- a/pkgs/id/src/currency_poc/intent.rs +++ b/pkgs/id/src/currency_poc/intent.rs @@ -10,10 +10,11 @@ //! (TigerBeetle transfer creation is idempotent by ID) or the record //! abandoned. +use std::cell::RefCell; use std::collections::HashMap; use std::fs; use std::io; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use serde::{Deserialize, Serialize}; @@ -71,13 +72,41 @@ impl IntentRecord { } } +/// A stored entry that a listing skipped because it could not be +/// read or parsed (#4125). Skipped entries are never deleted by the +/// store or the recovery scanner: the path stays on disk so an +/// operator can inspect, repair, or remove it deliberately. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct UnreadableIntent { + pub path: PathBuf, + pub reason: String, +} + /// Persistence seam for intent records. pub trait IntentStore { /// Insert or replace a record. Must be durable before returning: /// the write-ahead guarantee depends on it. fn put(&mut self, record: &IntentRecord) -> io::Result<()>; fn get(&self, conversion_id: u128) -> io::Result>; + /// List every unresolved record in the store. + /// + /// Listing contract (#4125): one unreadable or unparseable entry + /// must NOT abort the listing \u2014 the store directory is a + /// long-lived recovery surface that has to survive schema + /// evolution, operator handling, and foreign files. An + /// implementation therefore skips such an entry, leaves it in + /// place, and reports it through + /// [`IntentStore::unreadable_entries`]; only a failure to + /// enumerate the store itself is an `Err`. The in-memory store + /// holds already-parsed records, so it never skips. fn unresolved(&self) -> io::Result>; + /// Entries skipped by the most recent [`IntentStore::unresolved`] + /// call because they could not be read or parsed, in path order. + /// Empty when the last listing skipped nothing (or for stores + /// that cannot hold unreadable entries). + fn unreadable_entries(&self) -> Vec { + Vec::new() + } } /// In-memory store for tests and demos. @@ -117,12 +146,25 @@ impl IntentStore for InMemoryIntentStore { /// never leaves a torn record behind. pub struct FileIntentStore { dir: PathBuf, + /// Entries skipped by the most recent `unresolved` listing + /// (#4125); behind a `RefCell` because listing takes `&self`. + unreadable: RefCell>, } impl FileIntentStore { pub fn open(dir: PathBuf) -> io::Result { fs::create_dir_all(&dir)?; - Ok(Self { dir }) + Ok(Self { + dir, + unreadable: RefCell::new(Vec::new()), + }) + } + + fn note_unreadable(&self, path: &Path, reason: String) { + self.unreadable.borrow_mut().push(UnreadableIntent { + path: path.to_path_buf(), + reason, + }); } fn path_for(&self, conversion_id: u128) -> PathBuf { @@ -163,19 +205,52 @@ impl IntentStore for FileIntentStore { } fn unresolved(&self) -> io::Result> { + // A failure to enumerate the directory itself is fatal (the + // store is unreachable); anything wrong with one entry inside + // it is not (#4125). + let entries = fs::read_dir(&self.dir)?; + self.unreadable.borrow_mut().clear(); let mut records = Vec::new(); - for entry in fs::read_dir(&self.dir)? { - let path = entry?.path(); + for entry in entries { + let entry = match entry { + Ok(entry) => entry, + Err(error) => { + self.note_unreadable(&self.dir, format!("directory entry: {error}")); + continue; + } + }; + let path = entry.path(); if path.extension().and_then(|ext| ext.to_str()) != Some("json") { continue; } - let bytes = fs::read(&path)?; - let record: IntentRecord = serde_json::from_slice(&bytes) - .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?; + // fs::read also fails for a subdirectory named *.json; + // serde parsing fails for foreign or schema-drifted + // content. Both skip-and-report, never abort, never delete. + let bytes = match fs::read(&path) { + Ok(bytes) => bytes, + Err(error) => { + self.note_unreadable(&path, format!("read: {error}")); + continue; + } + }; + let record: IntentRecord = match serde_json::from_slice(&bytes) { + Ok(record) => record, + Err(error) => { + self.note_unreadable(&path, format!("parse: {error}")); + continue; + } + }; if record.state.is_unresolved() { records.push(record); } } + self.unreadable + .borrow_mut() + .sort_by(|a, b| a.path.cmp(&b.path)); Ok(records) } + + fn unreadable_entries(&self) -> Vec { + self.unreadable.borrow().clone() + } } diff --git a/pkgs/id/src/currency_poc/recovery.rs b/pkgs/id/src/currency_poc/recovery.rs index 84c13232b9..6526f43c80 100644 --- a/pkgs/id/src/currency_poc/recovery.rs +++ b/pkgs/id/src/currency_poc/recovery.rs @@ -59,7 +59,18 @@ pub fn reconcile( policy: RecoveryPolicy, ) -> Result> { let mut outcomes = Vec::new(); - for mut record in store.unresolved().context("listing unresolved intents")? { + let records = store.unresolved().context("listing unresolved intents")?; + // Entries the listing skipped (#4125) stay on disk for an + // operator; surface each one distinctly here instead of letting + // it pass silently, and reconcile everything readable regardless. + for unreadable in store.unreadable_entries() { + eprintln!( + "[recovery] skipping unreadable intent entry {}: {}", + unreadable.path.display(), + unreadable.reason + ); + } + for mut record in records { // A leg vector is the scanner's only statement of what must // be in the ledger, so it must name at least one transfer and // each transfer at most once (#4133): an empty vector would diff --git a/pkgs/id/src/currency_poc/tests.rs b/pkgs/id/src/currency_poc/tests.rs index f04c7f8eac..59dcd04bb8 100644 --- a/pkgs/id/src/currency_poc/tests.rs +++ b/pkgs/id/src/currency_poc/tests.rs @@ -572,3 +572,68 @@ fn recovery_rejects_duplicate_leg_ids_backed_by_one_transfer() { "a duplicate-leg record stays unresolved" ); } + +// --- #4125: one corrupt or foreign entry must not abort recovery --- + +/// Seed a file store holding the standard Recorded intent (777) the +/// way the write-ahead test does, in a fresh temp directory. +fn file_store_with_recorded_intent( + tag: &str, +) -> (PathBufForTests, FileIntentStore, InMemoryLedger) { + let dir = std::env::temp_dir().join(format!( + "id-currency-poc-intents-{tag}-{}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&dir); + let store = FileIntentStore::open(dir.clone()).expect("open store"); + let mut executor = ConversionExecutor::new(funded_ledger(), store); + let record = executor.prepare(&request()).expect("intent prepared"); + assert_eq!(record.state, IntentState::Recorded); + let backend = funded_ledger(); + let store = executor.store; + (dir, store, backend) +} + +type PathBufForTests = std::path::PathBuf; + +#[test] +fn recovery_continues_past_a_corrupt_sibling_file() { + let (dir, mut store, mut backend) = file_store_with_recorded_intent("corrupt"); + let corrupt = dir.join("deadbeef.json"); + std::fs::write(&corrupt, b"{not json").expect("write corrupt sibling"); + + // The listing itself no longer aborts, and reports the bad entry. + let listed = store.unresolved().expect("listing skips the corrupt file"); + assert_eq!(listed.len(), 1); + assert_eq!(listed[0].conversion_id, 777); + let unreadable = store.unreadable_entries(); + assert_eq!(unreadable.len(), 1); + assert_eq!(unreadable[0].path, corrupt); + + let outcomes = reconcile(&mut backend, &mut store, RecoveryPolicy::Resubmit) + .expect("reconcile past the corrupt sibling"); + assert_eq!(outcomes, vec![(777, ReconcileOutcome::Resubmitted)]); + assert_eq!(backend.transfers_with_user_data_128(777).len(), 3); + assert!( + corrupt.exists(), + "the scanner must not delete the corrupt entry an operator still needs to see" + ); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn recovery_continues_past_a_json_named_subdirectory() { + let (dir, mut store, mut backend) = file_store_with_recorded_intent("subdir"); + let subdir = dir.join("cafe.json"); + std::fs::create_dir(&subdir).expect("create *.json subdirectory"); + + let outcomes = reconcile(&mut backend, &mut store, RecoveryPolicy::Resubmit) + .expect("reconcile past the *.json subdirectory"); + assert_eq!(outcomes, vec![(777, ReconcileOutcome::Resubmitted)]); + assert_eq!(backend.transfers_with_user_data_128(777).len(), 3); + let unreadable = store.unreadable_entries(); + assert_eq!(unreadable.len(), 1); + assert_eq!(unreadable[0].path, subdir); + assert!(subdir.is_dir(), "the subdirectory stays in place"); + let _ = std::fs::remove_dir_all(&dir); +}