Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 82 additions & 7 deletions pkgs/id/src/currency_poc/intent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};

Expand Down Expand Up @@ -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<Option<IntentRecord>>;
/// 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<Vec<IntentRecord>>;
/// 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<UnreadableIntent> {
Vec::new()
}
}

/// In-memory store for tests and demos.
Expand Down Expand Up @@ -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<Vec<UnreadableIntent>>,
}

impl FileIntentStore {
pub fn open(dir: PathBuf) -> io::Result<Self> {
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 {
Expand Down Expand Up @@ -163,19 +205,52 @@ impl IntentStore for FileIntentStore {
}

fn unresolved(&self) -> io::Result<Vec<IntentRecord>> {
// 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<UnreadableIntent> {
self.unreadable.borrow().clone()
}
}
13 changes: 12 additions & 1 deletion pkgs/id/src/currency_poc/recovery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,18 @@ pub fn reconcile<B: LedgerBackend, S: IntentStore>(
policy: RecoveryPolicy,
) -> Result<Vec<(u128, ReconcileOutcome)>> {
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
Expand Down
65 changes: 65 additions & 0 deletions pkgs/id/src/currency_poc/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Loading