Unverified Commit fff4a4d9 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

turbo-persistence: stop background persisting after unrecoverable failure (#92106)

### What?

When a persist or compaction operation fails in `turbo-persistence`, the
database now:
- Rolls back cleanly (deletes orphan files, restores CURRENT)
- Stops the background persisting process for the session
- Keeps in-memory state consistent with on-disk state at all times
- Deletes superseded files safely (with Windows fallback for open memory
maps)

### Why?

Previously, a failed write operation (e.g. disk full, I/O error) would
leave the database in a broken state:

1. **Misleading error loop** — The `active_write_operation` `AtomicBool`
was left set to `true` after failure, so every subsequent snapshot cycle
printed _"another write operation is already in progress"_ forever,
hiding the real error.

2. **In-memory corruption** — `commit()` mutated `inner.meta_files` and
`inner.current_sequence_number` *before* writing the CURRENT file to
disk. If a disk error occurred between those two steps, the in-memory
state was inconsistent with disk and the rollback had no way to fix it.

3. **Rollback could corrupt committed data** — If `commit()` failed
*after* writing CURRENT (e.g. during old-file deletion or LOG writing),
the rollback would delete the *newly committed* files, corrupting the
database.

4. **Task graph corruption** — `save_snapshot` consumes task cache log
entries. If it failed, those entries were lost, but the background loop
would continue trying to persist — silently skipping those tasks and
corrupting the task graph in storage.

5. **Partially written CURRENT** — If the failure happened mid-write to
the CURRENT file, it could be left with partial/corrupt content, but
nothing restored it.

### How?

**`WriteOperationGuard` RAII (db.rs)**

A new `WriteOperationGuard<'a>` replaces the `AtomicBool` + manual
`try_recover_after_failed_write()` pattern. The guard holds:
- `&'a Mutex<Option<ActiveWriteState>>` — the write slot (`None` = idle,
`Some(Active("write batch"))` = in progress, `Some(Error)` = permanently
disabled)
- `path: &'a Path` — database directory for rollback
- `seq_before: u32` — sequence number at operation start
- `succeeded: bool` — set by `guard.success()`

On `drop`, if not succeeded:
1. Writes `seq_before` back to CURRENT (repairs a partially-written
CURRENT)
2. Deletes all files with `seq > seq_before` (orphans from the failed
operation)
3. Sets the slot to `None` (success) or `Some(Error)` (if cleanup itself
failed)

The `Active` variant carries a `&'static str` name (e.g. `"write
batch"`, `"compaction"`) used in error messages.

**Three-phase `commit()` (db.rs)**

`commit()` is restructured so `inner` is completely unmodified before
the point of no return:

| Phase | What happens | `inner` state | On failure |
|-------|-------------|---------------|------------|
| **A** | Compute `meta_seq_numbers_to_delete` via `sst_filter`. Uses
`apply_filter_collect` (read-only) to update filter state and collect
per-meta-file removal sets without modifying any MetaFile. Only a read
lock on `inner` is needed. | Unchanged | Guard deletes orphan files +
restores CURRENT; `inner` is intact |
| **B** | Write `.del` file and CURRENT to disk. | Unchanged | Same as
above |
| **C** | Apply deferred `retain_entries` (from A's removal sets),
append new metas, remove obsolete metas, bump `current_sequence_number`.
Try to delete superseded files; defer failures. | Updated | CURRENT is
already durable; commit is irreversible |

After CURRENT is written (point of no return), LOG writing errors are
caught and reported via `eprintln!` — they must not propagate because
the `WriteOperationGuard` would then run its rollback and delete the
*newly committed* files.

**`SstFilter::apply_filter_collect` (sst_filter.rs)**

A new read-only variant of `apply_filter` that updates the filter state
and returns a `FxHashSet<u32>` of SST entry sequence numbers to remove
from each meta file, without calling `retain_entries`. The original
`apply_filter` (which mutates the MetaFile) is still used by
`load_directory` and during new-meta-file construction where immediate
mutation is appropriate.

**Deferred file deletion (db.rs)**

Superseded `.sst`/`.meta`/`.blob` files are deleted immediately after
Phase C (once `inner` is updated). On Linux/macOS this always succeeds,
even if concurrent readers have the files memory-mapped. On Windows,
open memory maps prevent deletion — any file that fails is stored as a
`DeferredDeletion` enum (`Sst(u32)` / `Meta(u32)` / `Blob(u32)`) and
retried on the next commit or at shutdown. The `.del` file written
during Phase B ensures crash recovery via `load_directory` regardless.

**Background loop error handling (backend/mod.rs)**

- `snapshot_and_persist()` returns `Result<(Instant, bool),
anyhow::Error>` instead of `Option`. When `save_snapshot` fails, the
error propagates with `?`.
- The background loop matches on the `Result`: on `Err`, it logs the
error and a message that persisting is disabled for this session, then
returns (permanently stopping the background job).
- `has_unrecoverable_write_error()` checks the `ActiveWriteState::Error`
variant to detect permanent failure after compaction errors.

<!-- NEXT_JS_LLM_PR -->

---------
Co-authored-by: 's avatarTobias Koppers <sokra@users.noreply.github.com>
Co-authored-by: 's avatarClaude <noreply@anthropic.com>
parent d4b051d9
......@@ -106,6 +106,107 @@ struct TrackedStats {
miss_global: std::sync::atomic::AtomicU64,
}
/// State of the active write slot.
enum ActiveWriteState {
/// A write operation or compaction is in progress.
/// The string is a human-readable name used in error messages.
Active(&'static str),
/// A previous write or compaction failed and recovery also failed.
/// No further writes are possible.
Error,
}
/// A single superseded file whose deletion failed and is being retried.
///
/// On Linux/macOS, deleting a memory-mapped file is safe and this list is
/// normally empty. On Windows, open memory maps prevent deletion; failed files
/// are collected here and retried on the next commit or shutdown.
enum DeferredDeletion {
Sst(u32),
Meta(u32),
Blob(u32),
}
/// RAII guard for an active write operation.
///
/// When dropped without [`WriteOperationGuard::success`] being called first, the guard rolls back
/// the operation by deleting any files whose sequence number exceeds `seq_before` (the sequence
/// number at the time the operation started). If rollback itself fails the write slot is set to
/// [`ActiveWriteState::Error`], permanently disabling further writes.
pub(crate) struct WriteOperationGuard<'a> {
/// Reference to the active-write-operation slot, so we can clear or error it on drop.
active: &'a Mutex<Option<ActiveWriteState>>,
/// Database directory path, needed for orphan-file deletion during rollback.
path: &'a Path,
/// Sequence number at the time the operation started (= the last committed seq on disk).
/// Files with seq > this were created by the current operation and must be deleted on
/// rollback.
seq_before: u32,
/// Set to `true` by [`WriteOperationGuard::success`] to skip rollback on drop.
succeeded: bool,
}
impl WriteOperationGuard<'_> {
/// Mark the operation as successfully completed.
///
/// After this call the guard's `Drop` impl will release the write slot without rolling back.
pub(crate) fn success(&mut self) {
self.succeeded = true;
}
}
/// Deletes all files in `path` whose numeric stem is greater than `seq_before`.
///
/// Called on rollback to clean up any SST, meta, blob, or del files written during a
/// failed write operation or compaction.
fn delete_orphan_files(path: &Path, seq_before: u32) -> Result<()> {
// Restore CURRENT to seq_before first. The failure may have happened mid-write
// to CURRENT, leaving it partially written. Writing seq_before makes the
// on-disk state consistent before we start deleting orphan files.
let mut current_file = OpenOptions::new()
.write(true)
.truncate(false)
.read(false)
.open(path.join("CURRENT"))?;
current_file.write_u32::<BE>(seq_before)?;
current_file.sync_all()?;
for entry in fs::read_dir(path)? {
let entry = entry?;
let path = entry.path();
if let Some(ext) = path.extension().and_then(|s| s.to_str())
&& let Some(seq) = path
.file_stem()
.and_then(|s| s.to_str())
.and_then(|s| s.parse::<u32>().ok())
&& seq > seq_before
{
match ext {
"sst" | "meta" | "blob" | "del" => fs::remove_file(&path)?,
_ => {}
}
}
}
Ok(())
}
impl Drop for WriteOperationGuard<'_> {
fn drop(&mut self) {
if self.succeeded {
// Happy path: just release the slot.
*self.active.lock() = None;
return;
}
// Unhappy path: the operation failed (or was dropped without commit).
// Delete every file that was created during this operation (seq > seq_before).
match delete_orphan_files(self.path, self.seq_before) {
Ok(()) => *self.active.lock() = None,
Err(_) => *self.active.lock() = Some(ActiveWriteState::Error),
}
}
}
/// TurboPersistence is a persistent key-value store. It is limited to a single writer at a time
/// using a single write batch. It allows for concurrent reads.
pub struct TurboPersistence<S: ParallelScheduler, const FAMILIES: usize> {
......@@ -120,9 +221,13 @@ pub struct TurboPersistence<S: ParallelScheduler, const FAMILIES: usize> {
/// A flag to indicate if the database is empty (no meta files). This is an atomic mirror of
/// `inner.meta_files.is_empty()` to avoid taking a lock on the hot path.
is_empty: AtomicBool,
/// A flag to indicate if a write operation is currently active. Prevents multiple concurrent
/// write operations.
active_write_operation: AtomicBool,
/// Tracks whether a write operation is in progress or has permanently failed.
/// `None` = idle, `Some(Active)` = in progress, `Some(Error)` = permanently disabled.
active_write_operation: Mutex<Option<ActiveWriteState>>,
/// Files from superseded commits whose deletion failed (e.g. on Windows due to open memory
/// maps) and will be retried on the next commit or at shutdown.
/// Protected by `active_write_operation` (only mutated inside a write operation).
deferred_deletions: Mutex<Vec<DeferredDeletion>>,
/// A cache for decompressed key blocks.
key_block_cache: BlockCache,
/// A cache for decompressed value blocks.
......@@ -195,7 +300,8 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
.map(|_| DashSet::with_hasher(BuildNoHashHasher::default())),
}),
is_empty: AtomicBool::new(true),
active_write_operation: AtomicBool::new(false),
active_write_operation: Mutex::new(None),
deferred_deletions: Mutex::new(Vec::new()),
key_block_cache: BlockCache::with(
KEY_BLOCK_CACHE_SIZE as usize / KEY_BLOCK_AVG_SIZE,
KEY_BLOCK_CACHE_SIZE,
......@@ -451,26 +557,59 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
self.is_empty.load(Ordering::Relaxed)
}
/// Returns `true` if a previous write or compaction left the database in an unrecoverable error
/// state, permanently disabling further writes.
pub fn has_unrecoverable_write_error(&self) -> bool {
matches!(
*self.active_write_operation.lock(),
Some(ActiveWriteState::Error)
)
}
/// Acquires the write-operation slot, returning an RAII guard that rolls back and releases it
/// on drop. Only one write operation (write batch or compaction) is allowed at a time.
/// `name` is a short human-readable label used in error messages (e.g. `"write batch"`).
fn acquire_write_operation(&self, name: &'static str) -> Result<WriteOperationGuard<'_>> {
if self.read_only {
bail!("Cannot perform write operations on a read-only database");
}
let mut slot = self.active_write_operation.lock();
match &*slot {
Some(ActiveWriteState::Active(active_name)) => {
bail!(
"Another {active_name} is already active (only a single write operation is \
allowed at a time)"
);
}
Some(ActiveWriteState::Error) => {
bail!(
"A previous write operation failed with an unrecoverable error; no further \
writes are possible"
);
}
None => {}
}
*slot = Some(ActiveWriteState::Active(name));
drop(slot); // release before acquiring inner read lock
let seq_before = self.inner.read().current_sequence_number;
Ok(WriteOperationGuard {
active: &self.active_write_operation,
path: &self.path,
seq_before,
succeeded: false,
})
}
/// Starts a new WriteBatch for the database. Only a single write operation is allowed at a
/// time. The WriteBatch need to be committed with [`TurboPersistence::commit_write_batch`].
/// Note that the WriteBatch might start writing data to disk while it's filled up with data.
/// This data will only become visible after the WriteBatch is committed.
pub fn write_batch<K: StoreKey + Send + Sync>(&self) -> Result<WriteBatch<K, S, FAMILIES>> {
if self.read_only {
bail!("Cannot write to a read-only database");
}
if self
.active_write_operation
.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
.is_err()
{
bail!(
"Another write batch or compaction is already active (Only a single write \
operations is allowed at a time)"
);
}
let current = self.inner.read().current_sequence_number;
pub fn write_batch<K: StoreKey + Send + Sync>(&self) -> Result<WriteBatch<'_, K, S, FAMILIES>> {
let guard = self.acquire_write_operation("write batch")?;
// seq_before is already the current sequence number, no second read needed.
let current = guard.seq_before;
Ok(WriteBatch::new(
guard,
self.path.clone(),
current,
self.parallel_scheduler.clone(),
......@@ -517,7 +656,7 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
/// visible to readers.
pub fn commit_write_batch<K: StoreKey + Send + Sync>(
&self,
mut write_batch: WriteBatch<K, S, FAMILIES>,
mut write_batch: WriteBatch<'_, K, S, FAMILIES>,
) -> Result<()> {
if self.read_only {
unreachable!("It's not possible to create a write batch for a read-only database");
......@@ -563,7 +702,8 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
sequence_number,
keys_written,
})?;
self.active_write_operation.store(false, Ordering::Release);
// Mark the guard inside the write batch as succeeded so it skips the rollback on drop.
write_batch.mark_succeeded();
Ok(())
}
......@@ -672,35 +812,61 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
})
.collect::<Vec<_>>();
// ── Phase A: compute what will change without modifying inner. ──
//
// We need `meta_seq_numbers_to_delete` and `has_delete_file` to write
// the .del file BEFORE writing CURRENT. We must not modify `inner` at
// all — if a disk error occurs before CURRENT is durable, the
// WriteOperationGuard rollback can only clean up orphan files, not undo
// in-memory mutations. The MetaFile in-memory optimization
// (retain_entries) is deferred to Phase C.
let has_delete_file;
let mut meta_seq_numbers_to_delete = Vec::new();
let entries_to_remove;
{
let mut inner = self.inner.write();
for meta_file in inner.meta_files.iter_mut().rev() {
sst_filter.apply_filter(meta_file);
let inner = self.inner.read();
// (A1) Run the SST filter on existing meta files. This only
// updates the SstFilter state — the MetaFile in-memory layout is
// not modified yet (that happens in Phase C via retain_entries).
// Collects the set of SST entry sequence numbers to remove from
// each meta file, keyed by position in `inner.meta_files`.
entries_to_remove = inner
.meta_files
.iter()
.rev()
.map(|meta_file| sst_filter.apply_filter_collect(meta_file))
.collect::<Vec<_>>();
// (A2) Determine which meta files are fully obsolete by running
// `apply_and_get_remove` in newest-first order. Process new metas
// first (they are newer than existing ones) to advance the filter
// state, then existing ones. New metas are never candidates for
// removal (just created), so only their filter-state side-effects
// matter.
for meta_file in new_meta_files.iter().rev() {
let should_remove = sst_filter.apply_and_get_remove(meta_file);
debug_assert!(
!should_remove,
"newly created meta file should never be a candidate for removal"
);
}
inner.meta_files.append(&mut new_meta_files);
// apply_and_get_remove need to run in reverse order
inner.meta_files.reverse();
inner.meta_files.retain(|meta| {
if sst_filter.apply_and_get_remove(meta) {
meta_seq_numbers_to_delete.push(meta.sequence_number());
false
} else {
true
for i in (0..inner.meta_files.len()).rev() {
if sst_filter.apply_and_get_remove(&inner.meta_files[i]) {
meta_seq_numbers_to_delete.push(inner.meta_files[i].sequence_number());
}
});
inner.meta_files.reverse();
self.is_empty
.store(inner.meta_files.is_empty(), Ordering::Relaxed);
}
// (A3) Compute the final sequence number that will be written to
// CURRENT. A .del file is created only when there are files to
// delete, which consumes one extra sequence number.
has_delete_file = !sst_seq_numbers_to_delete.is_empty()
|| !blob_seq_numbers_to_delete.is_empty()
|| !meta_seq_numbers_to_delete.is_empty();
if has_delete_file {
seq += 1;
}
inner.current_sequence_number = seq;
}
if has_delete_file {
seq += 1;
}
self.parallel_scheduler.block_in_place(|| {
......@@ -737,17 +903,24 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
current_file.write_u32::<BE>(seq)?;
current_file.sync_data()?;
for seq in sst_seq_numbers_to_delete.iter() {
fs::remove_file(self.path.join(format!("{seq:08}.sst")))?;
}
for seq in meta_seq_numbers_to_delete.iter() {
fs::remove_file(self.path.join(format!("{seq:08}.meta")))?;
}
for seq in blob_seq_numbers_to_delete.iter() {
fs::remove_file(self.path.join(format!("{seq:08}.blob")))?;
}
{
// ── Point of no return ──────────────────────────────────────────
//
// CURRENT has been durably updated. The commit is now visible to
// future readers (including after a crash/restart via
// `load_directory`). Everything below is best-effort cleanup:
//
// • Writing the LOG is purely informational.
//
// • Superseded files are NOT deleted here — Phase C handles that
// after `inner` is updated. On Linux/macOS they are deleted
// immediately; on Windows (where open memory maps prevent
// deletion) they are retried on the next commit or shutdown.
//
// Errors here must NOT propagate, because the WriteOperationGuard
// would then run its rollback and delete the *newly committed*
// files, corrupting the database.
if let Err(e) = (|| {
let mut log = self.open_log()?;
writeln!(log, "Time {time}")?;
let span = time.until(Timestamp::now())?;
......@@ -772,16 +945,12 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
}
}
fn write_seq_numbers<W: std::io::Write, T, I>(
fn write_seq_numbers<W: std::io::Write, T>(
log: &mut W,
items: I,
items: &[T],
label: &str,
extract_seq: fn(&T) -> u32,
) -> std::io::Result<()>
where
I: IntoIterator<Item = T>,
{
let items: Vec<T> = items.into_iter().collect();
) -> std::io::Result<()> {
for chunk in items.chunks(15) {
write!(log, " | |")?;
for item in chunk {
......@@ -793,53 +962,122 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
}
new_blob_files.sort_unstable_by_key(|(seq, _)| *seq);
write_seq_numbers(&mut log, new_blob_files, "NEW BLOB", |&(seq, _)| seq)?;
write_seq_numbers(&mut log, &new_blob_files, "NEW BLOB", |&(seq, _)| seq)?;
write_seq_numbers(
&mut log,
blob_seq_numbers_to_delete,
&blob_seq_numbers_to_delete,
"BLOB DELETED",
|&seq| seq,
)?;
write_seq_numbers(&mut log, sst_seq_numbers_to_delete, "SST DELETED", |&seq| {
seq
})?;
write_seq_numbers(
&mut log,
meta_seq_numbers_to_delete,
&sst_seq_numbers_to_delete,
"SST DELETED",
|&seq| seq,
)?;
write_seq_numbers(
&mut log,
&meta_seq_numbers_to_delete,
"META DELETED",
|&seq| seq,
)?;
#[cfg(feature = "verbose_log")]
{
writeln!(log, "New database state:")?;
writeln!(log, "FAM | META SEQ | SST SEQ FLAGS | RANGE")?;
let inner = self.inner.read();
let families = inner.meta_files.iter().map(|meta| meta.family()).filter({
let mut set = HashSet::new();
move |family| set.insert(*family)
});
for family in families {
for meta in inner.meta_files.iter() {
if meta.family() != family {
continue;
}
let meta_seq = meta.sequence_number();
for entry in meta.entries().iter() {
let seq = entry.sequence_number();
let range = entry.range();
writeln!(
log,
"{family:3} | {meta_seq:08} | {seq:08} {:>6} | {}",
entry.flags(),
range_to_str(range.min_hash, range.max_hash)
)?;
}
}
}
}
anyhow::Ok(())
})() {
eprintln!("turbo-persistence: failed to write LOG after commit {seq:08}: {e:#}");
}
anyhow::Ok(())
})?;
// ── Phase C: structurally update inner (CURRENT is already durable). ──
//
// Between Phase A's read-lock drop and this point no other writer can
// run (WriteOperationGuard ensures exclusivity) and readers never mutate
// inner, so the snapshot from Phase A is still valid.
{
let mut inner = self.inner.write();
// Apply the deferred MetaFile mutations from Phase A1. apply_filter
// was called read-only earlier; now we actually move superseded
// entries from active to obsolete inside each MetaFile.
// entries_to_remove was collected in reverse order, so iterate it
// in reverse to match the forward order of inner.meta_files.
for (meta_file, to_remove) in inner
.meta_files
.iter_mut()
.zip(entries_to_remove.into_iter().rev())
{
if !to_remove.is_empty() {
meta_file.retain_entries(|seq| !to_remove.contains(&seq));
}
}
inner.meta_files.append(&mut new_meta_files);
if !meta_seq_numbers_to_delete.is_empty() {
let to_delete: HashSet<u32> = meta_seq_numbers_to_delete.iter().copied().collect();
inner
.meta_files
.retain(|meta| !to_delete.contains(&meta.sequence_number()));
}
inner.current_sequence_number = seq;
self.is_empty
.store(inner.meta_files.is_empty(), Ordering::Relaxed);
}
// Try to delete superseded files immediately. On Linux/macOS this always
// works even if readers have the files memory-mapped. On Windows, open
// memory maps prevent deletion; any file that fails is kept in
// `deferred_deletions` and retried on the next commit or at shutdown.
self.deferred_deletions.lock().extend(
Self::try_delete_files(&self.path, &sst_seq_numbers_to_delete, "sst")
.map(DeferredDeletion::Sst)
.chain(
Self::try_delete_files(&self.path, &meta_seq_numbers_to_delete, "meta")
.map(DeferredDeletion::Meta),
)
.chain(
Self::try_delete_files(&self.path, &blob_seq_numbers_to_delete, "blob")
.map(DeferredDeletion::Blob),
),
);
// Retry any deletions that failed in earlier commits.
self.retry_deferred_deletions();
// Best-effort verbose log of the new database state after Phase C.
#[cfg(feature = "verbose_log")]
{
let _: Result<(), _> = (|| -> anyhow::Result<()> {
let mut log = self.open_log()?;
writeln!(log, "New database state:")?;
writeln!(log, "FAM | META SEQ | SST SEQ FLAGS | RANGE")?;
let inner = self.inner.read();
let families = inner.meta_files.iter().map(|meta| meta.family()).filter({
let mut set = HashSet::new();
move |family| set.insert(*family)
});
for family in families {
for meta in inner.meta_files.iter() {
if meta.family() != family {
continue;
}
let meta_seq = meta.sequence_number();
for entry in meta.entries().iter() {
let seq = entry.sequence_number();
let range = entry.range();
writeln!(
log,
"{family:3} | {meta_seq:08} | {seq:08} {:>6} | {}",
entry.flags(),
range_to_str(range.min_hash, range.max_hash)
)?;
}
}
}
Ok(())
})();
}
Ok(())
}
......@@ -863,19 +1101,7 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
/// need to be read to find a key. It also limits the maximum number of SST files that are
/// merged at once, which is the main factor for the runtime of the compaction.
pub fn compact(&self, compact_config: &CompactConfig) -> Result<bool> {
if self.read_only {
bail!("Compaction is not allowed on a read only database");
}
if self
.active_write_operation
.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
.is_err()
{
bail!(
"Another write batch or compaction is already active (Only a single write \
operations is allowed at a time)"
);
}
let mut guard = self.acquire_write_operation("compaction")?;
// Free block caches and SST mmaps before compaction. The block caches
// are not used during compaction (we iterate uncached), and any cached
......@@ -920,8 +1146,7 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
.context("Failed to commit the database compaction")?;
}
self.active_write_operation.store(false, Ordering::Release);
guard.success();
Ok(has_changes)
}
......@@ -1778,11 +2003,42 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
}
/// Shuts down the database. This will print statistics if the `print_stats` feature is enabled.
/// Retries deletion of all previously-deferred files and clears successfully deleted batches.
pub fn shutdown(&self) -> Result<()> {
#[cfg(feature = "print_stats")]
println!("{:#?}", self.statistics());
self.retry_deferred_deletions();
Ok(())
}
/// Attempts to delete files with the given extension, returning an iterator of sequence
/// numbers for files that could not be deleted (e.g. due to open memory maps on Windows).
fn try_delete_files<'a>(
dir: &'a Path,
seqs: &'a [u32],
ext: &'a str,
) -> impl Iterator<Item = u32> + 'a {
seqs.iter()
.copied()
.filter(move |&seq| fs::remove_file(dir.join(format!("{seq:08}.{ext}"))).is_err())
}
/// Retries deletion of files that previously failed (typically due to open memory maps on
/// Windows). Any file that still fails is kept for the next retry.
/// Best-effort: persistent failures are acceptable because `load_directory` cleans up
/// any leftover files on the next open via the `.del` file.
fn retry_deferred_deletions(&self) {
let mut deferred = self.deferred_deletions.lock();
deferred.retain(|entry| {
let (seq, ext) = match *entry {
DeferredDeletion::Sst(seq) => (seq, "sst"),
DeferredDeletion::Meta(seq) => (seq, "meta"),
DeferredDeletion::Blob(seq) => (seq, "blob"),
};
// Keep the entry only if deletion still fails.
fs::remove_file(self.path.join(format!("{seq:08}.{ext}"))).is_err()
});
}
}
fn range_to_str(min: u64, max: u64) -> String {
......
use std::collections::hash_map::Entry;
use rustc_hash::FxHashMap;
use rustc_hash::{FxHashMap, FxHashSet};
use crate::meta_file::MetaFile;
......@@ -47,6 +47,42 @@ impl SstFilter {
}
}
/// Like [`apply_filter`](Self::apply_filter) but only updates the filter state without
/// modifying the MetaFile. Returns the set of SST sequence numbers that should be removed
/// from this meta file's entries (they are superseded by a newer meta). Call
/// `meta.retain_entries(|seq| !obsolete.contains(&seq))` later to apply.
pub fn apply_filter_collect(&mut self, meta: &MetaFile) -> FxHashSet<u32> {
let mut to_remove = FxHashSet::default();
// Already obsolete entries need to be considered for usage computation
for seq in meta.obsolete_entries() {
if let Some(state) = self.0.get_mut(seq)
&& matches!(state, SstState::UnusedObsolete)
{
// the obsolete state is used now
*state = SstState::Obsolete;
}
}
for entry in meta.entries() {
let seq = entry.sequence_number();
match self.0.entry(seq) {
Entry::Occupied(mut e) => {
let state = e.get_mut();
if matches!(state, SstState::UnusedObsolete) {
*state = SstState::Obsolete;
}
to_remove.insert(seq);
}
Entry::Vacant(e) => {
e.insert(SstState::Active);
}
}
}
for seq in meta.obsolete_sst_files() {
self.0.entry(*seq).or_insert(SstState::UnusedObsolete);
}
to_remove
}
/// Phase 2: Check if the meta file can be removed based on the filter state after phase 1.
/// Updates the filter state for the next meta file. Returns true if the meta file can be
/// removed.
......
......@@ -2023,18 +2023,19 @@ fn compaction_deletes_superseded_blob() -> Result<()> {
// Compact — the old blob entry is superseded by the newer small value
db.full_compact()?;
// After compaction, the old blob file should be deleted
// The new value should still be readable
let result = db.get(0, &vec![1u8])?;
assert_eq!(result.as_deref(), Some(&[99u8][..]));
// After compaction, the old blob file should be deleted immediately.
assert_eq!(
count_blob_files(path),
0,
"Old blob file should be deleted after compaction"
);
// The new value should still be readable
let result = db.get(0, &vec![1u8])?;
assert_eq!(result.as_deref(), Some(&[99u8][..]));
db.shutdown()?;
Ok(())
}
......@@ -2074,18 +2075,19 @@ fn compaction_deletes_blob_on_tombstone() -> Result<()> {
// Compact — tombstone supersedes the blob entry
db.full_compact()?;
// After compaction, the blob file should be deleted
// Key should not be found
let result = db.get(0, &vec![1u8])?;
assert!(result.is_none());
// After compaction, the blob file should be deleted immediately.
assert_eq!(
count_blob_files(path),
0,
"Blob file should be deleted after compaction"
);
// Key should not be found
let result = db.get(0, &vec![1u8])?;
assert!(result.is_none());
db.shutdown()?;
Ok(())
}
......@@ -2130,19 +2132,20 @@ fn compaction_deletes_blob_multi_value_tombstone() -> Result<()> {
// Compact — tombstone prunes the old blob entry
db.full_compact()?;
// After compaction, the old blob file should be deleted
// The new value should still be readable
let results = db.get_multiple(0, &vec![1u8].as_slice())?;
assert_eq!(results.len(), 1);
assert_eq!(results[0].as_ref(), &[99u8]);
// After compaction, the old blob file should be deleted immediately.
assert_eq!(
count_blob_files(path),
0,
"Blob file should be deleted after compaction"
);
// The new value should still be readable
let results = db.get_multiple(0, &vec![1u8].as_slice())?;
assert_eq!(results.len(), 1);
assert_eq!(results[0].as_ref(), &[99u8]);
db.shutdown()?;
Ok(())
}
......
......@@ -20,6 +20,7 @@ use crate::{
collector_entry::CollectorEntry,
compression::{checksum_block, compress_into_buffer},
constants::{MAX_MEDIUM_VALUE_SIZE, THREAD_LOCAL_SIZE_SHIFT},
db::WriteOperationGuard,
key::StoreKey,
meta_file::MetaEntryFlags,
meta_file_builder::MetaFileBuilder,
......@@ -66,7 +67,9 @@ enum GlobalCollectorState<K: StoreKey + Send> {
}
/// A write batch.
pub struct WriteBatch<K: StoreKey + Send, S: ParallelScheduler, const FAMILIES: usize> {
pub struct WriteBatch<'db, K: StoreKey + Send, S: ParallelScheduler, const FAMILIES: usize> {
/// RAII guard that releases the write-operation slot (and rolls back on failure) on drop.
_write_guard: WriteOperationGuard<'db>,
/// Parallel scheduler
parallel_scheduler: S,
/// The database path
......@@ -87,11 +90,12 @@ pub struct WriteBatch<K: StoreKey + Send, S: ParallelScheduler, const FAMILIES:
new_sst_files: Mutex<Vec<(u32, File)>>,
}
impl<K: StoreKey + Send + Sync, S: ParallelScheduler, const FAMILIES: usize>
WriteBatch<K, S, FAMILIES>
impl<'db, K: StoreKey + Send + Sync, S: ParallelScheduler, const FAMILIES: usize>
WriteBatch<'db, K, S, FAMILIES>
{
/// Creates a new write batch for a database with per-family configuration.
pub(crate) fn new(
write_guard: WriteOperationGuard<'db>,
path: PathBuf,
current: u32,
parallel_scheduler: S,
......@@ -101,6 +105,7 @@ impl<K: StoreKey + Send + Sync, S: ParallelScheduler, const FAMILIES: usize>
assert!(FAMILIES <= usize_from_u32(u32::MAX));
};
Self {
_write_guard: write_guard,
parallel_scheduler,
db_path: path,
family_configs,
......@@ -113,6 +118,14 @@ impl<K: StoreKey + Send + Sync, S: ParallelScheduler, const FAMILIES: usize>
}
}
/// Marks the write operation as successfully completed.
///
/// Must be called before dropping the `WriteBatch` to skip the rollback in the guard's `Drop`
/// impl. Typically called by `TurboPersistence::commit_write_batch` after a successful commit.
pub(crate) fn mark_succeeded(&mut self) {
self._write_guard.success();
}
/// Returns the thread local state for the current thread.
#[allow(clippy::mut_from_ref)]
fn thread_local_state(&self) -> &mut ThreadLocalState<K, FAMILIES> {
......
......@@ -989,7 +989,7 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> {
parent_span: Option<tracing::Id>,
reason: &str,
turbo_tasks: &dyn TurboTasksBackendApi<TurboTasksBackend<B>>,
) -> Option<(Instant, bool)> {
) -> Result<(Instant, bool), anyhow::Error> {
let snapshot_span =
tracing::trace_span!(parent: parent_span.clone(), "snapshot", reason = reason)
.entered();
......@@ -1036,7 +1036,7 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> {
// No tasks modified since the last snapshot — drop the guard (which
// calls end_snapshot) and skip the expensive O(N) scan.
drop(snapshot_guard);
return Some((start, false));
return Ok((start, false));
}
#[cfg(feature = "print_cache_item_size")]
......@@ -1298,19 +1298,17 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> {
// This should be impossible — if we got here, modified_count was nonzero, and every
// modification that increments the count also failed during encoding.
std::hint::cold_path();
return Some((snapshot_time, false));
return Ok((snapshot_time, false));
}
let persist_start = Instant::now();
let _span = tracing::info_span!(parent: parent_span, "persist", reason = reason).entered();
{
if let Err(err) = self
.backing_storage
.save_snapshot(suspended_operations, task_snapshots)
{
eprintln!("Persisting failed: {err:?}");
return None;
}
// Tasks were already consumed by take_snapshot, so a future snapshot
// would not re-persist them — returning an error signals to the caller
// that further persist attempts would corrupt the task graph in storage.
self.backing_storage
.save_snapshot(suspended_operations, task_snapshots)?;
#[cfg(feature = "print_cache_item_size")]
{
let mut task_cache_stats = task_cache_stats
......@@ -1421,7 +1419,7 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> {
],
)));
Some((snapshot_time, true))
Ok((snapshot_time, true))
}
fn startup(&self, turbo_tasks: &dyn TurboTasksBackendApi<TurboTasksBackend<B>>) {
......@@ -1463,8 +1461,10 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> {
self.is_idle.store(false, Ordering::Release);
self.verify_aggregation_graph(turbo_tasks, false);
}
if self.should_persist() {
self.snapshot_and_persist(Span::current().into(), "stop", turbo_tasks);
if self.should_persist()
&& let Err(err) = self.snapshot_and_persist(Span::current().into(), "stop", turbo_tasks)
{
eprintln!("Persisting failed during shutdown: {err:?}");
}
drop_contents(&self.task_cache);
self.storage.drop_contents();
......@@ -2777,6 +2777,15 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> {
removed_cell_data
}
/// Prints the standard message emitted when the background persisting process stops due to an
/// unrecoverable write error. The caller is responsible for returning from the background job.
fn log_unrecoverable_persist_error() {
eprintln!(
"Persisting is disabled for this session due to an unrecoverable error. Stopping the \
background persisting process."
);
}
fn run_backend_job<'a>(
self: &'a Arc<Self>,
job: TurboTasksBackendJob,
......@@ -2820,7 +2829,6 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> {
return;
},
_ = &mut idle_start_listener => {
fresh_idle = true;
idle_time = Instant::now() + idle_timeout;
idle_start_listener = self.idle_start_event.listen()
},
......@@ -2847,62 +2855,74 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> {
// grouped together in trace viewers.
let background_span =
tracing::info_span!(parent: None, "background snapshot");
let snapshot =
this.snapshot_and_persist(background_span.id(), reason, turbo_tasks);
if let Some((snapshot_start, new_data)) = snapshot {
last_snapshot = snapshot_start;
// Compact while idle (up to limit), regardless of
// whether the snapshot had new data.
// `background_span` is not entered here because
// `EnteredSpan` is `!Send` and would prevent the
// future from being sent across threads when it
// suspends at the `select!` await below.
const MAX_IDLE_COMPACTION_PASSES: usize = 10;
for _ in 0..MAX_IDLE_COMPACTION_PASSES {
let idle_ended = tokio::select! {
biased;
_ = &mut idle_end_listener => {
idle_end_listener = self.idle_end_event.listen();
true
},
_ = std::future::ready(()) => false,
};
if idle_ended {
break;
}
// Enter the span only around the synchronous
// compact() call so we never hold an
// `EnteredSpan` across an await point.
let _compact_span = tracing::info_span!(
parent: background_span.id(),
"compact database"
)
.entered();
match self.backing_storage.compact() {
Ok(true) => {}
Ok(false) => break,
Err(err) => {
eprintln!("Compaction failed: {err:?}");
match this.snapshot_and_persist(background_span.id(), reason, turbo_tasks) {
Err(err) => {
// save_snapshot consumed persisted_task_cache_log entries;
// further snapshots would corrupt the task graph.
eprintln!("Persisting failed: {err:?}");
Self::log_unrecoverable_persist_error();
return;
}
Ok((snapshot_start, new_data)) => {
last_snapshot = snapshot_start;
// Compact while idle (up to limit), regardless of
// whether the snapshot had new data.
// `background_span` is not entered here because
// `EnteredSpan` is `!Send` and would prevent the
// future from being sent across threads when it
// suspends at the `select!` await below.
const MAX_IDLE_COMPACTION_PASSES: usize = 10;
for _ in 0..MAX_IDLE_COMPACTION_PASSES {
let idle_ended = tokio::select! {
biased;
_ = &mut idle_end_listener => {
idle_end_listener = self.idle_end_event.listen();
true
},
_ = std::future::ready(()) => false,
};
if idle_ended {
break;
}
// Enter the span only around the synchronous
// compact() call so we never hold an
// `EnteredSpan` across an await point.
let _compact_span = tracing::info_span!(
parent: background_span.id(),
"compact database"
)
.entered();
match self.backing_storage.compact() {
Ok(true) => {}
Ok(false) => break,
Err(err) => {
eprintln!("Compaction failed: {err:?}");
if self.backing_storage.has_unrecoverable_write_error()
{
Self::log_unrecoverable_persist_error();
return;
}
break;
}
}
}
}
if !new_data {
fresh_idle = false;
continue;
if !new_data {
fresh_idle = false;
continue;
}
let last_snapshot = last_snapshot.duration_since(self.start_time);
self.last_snapshot.store(
last_snapshot.as_millis().try_into().unwrap(),
Ordering::Relaxed,
);
turbo_tasks.schedule_backend_background_job(
TurboTasksBackendJob::FollowUpSnapshot,
);
return;
}
let last_snapshot = last_snapshot.duration_since(self.start_time);
self.last_snapshot.store(
last_snapshot.as_millis().try_into().unwrap(),
Ordering::Relaxed,
);
turbo_tasks.schedule_backend_background_job(
TurboTasksBackendJob::FollowUpSnapshot,
);
return;
}
}
}
......
......@@ -108,6 +108,12 @@ pub trait BackingStorageSealed: 'static + Send + Sync {
fn shutdown(&self) -> Result<()> {
Ok(())
}
/// Returns true if the database is in an unrecoverable error state where a previous write or
/// compaction failed and the rollback also failed, permanently disabling further writes.
fn has_unrecoverable_write_error(&self) -> bool {
false
}
}
impl<L, R> BackingStorage for Either<L, R>
......@@ -171,4 +177,8 @@ where
fn shutdown(&self) -> Result<()> {
either::for_both!(self, this => this.shutdown())
}
fn has_unrecoverable_write_error(&self) -> bool {
either::for_both!(self, this => this.has_unrecoverable_write_error())
}
}
......@@ -119,4 +119,10 @@ pub trait KeyValueDatabase {
fn shutdown(&self) -> Result<()> {
Ok(())
}
/// Returns true if the database is in an unrecoverable error state where a previous write or
/// compaction failed and the rollback also failed, permanently disabling further writes.
fn has_unrecoverable_write_error(&self) -> bool {
false
}
}
......@@ -137,6 +137,10 @@ impl KeyValueDatabase for TurboKeyValueDatabase {
)
}
fn has_unrecoverable_write_error(&self) -> bool {
self.db.has_unrecoverable_write_error()
}
fn shutdown(&self) -> Result<()> {
// Compact the database on shutdown
// (Avoid compacting a fresh database since we don't have any usage info yet)
......@@ -195,8 +199,12 @@ fn do_compact(
}
pub struct TurboWriteBatch<'a> {
batch:
turbo_persistence::WriteBatch<WriteBuffer<'static>, TurboTasksParallelScheduler, FAMILIES>,
batch: turbo_persistence::WriteBatch<
'a,
WriteBuffer<'static>,
TurboTasksParallelScheduler,
FAMILIES,
>,
db: &'a Arc<TurboPersistence<TurboTasksParallelScheduler, FAMILIES>>,
}
......
......@@ -381,6 +381,10 @@ impl<T: KeyValueDatabase + Send + Sync + 'static> BackingStorageSealed
fn shutdown(&self) -> Result<()> {
self.inner.database.shutdown()
}
fn has_unrecoverable_write_error(&self) -> bool {
self.inner.database.has_unrecoverable_write_error()
}
}
fn get_next_free_task_id<'a>(batch: &impl ConcurrentWriteBatch<'a>) -> Result<u32, anyhow::Error> {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment