Unverified Commit 8a473f45 authored by Luke Sandberg's avatar Luke Sandberg Committed by GitHub

turbo-tasks-backend: add persistence delete/tombstone plumbing for GC (#95975)

## What

The persistence-layer mechanism to tombstone (delete) tasks from the
on-disk cache. A GC-collected task is represented as a
`SnapshotItem::Delete` that rides the same streaming iterator
`save_snapshot` already consumes for puts, so tombstones are applied in
the same commit/batch as the snapshot with no side-channel.

- `SnapshotItem` becomes an enum: `Put { … }` (the existing path) and
`Delete(TaskDeletion)`.
- `TurboWriteBatch::delete/value_delete` passthrough to
`turbo_persistence`.
- `save_snapshot` applies deletes inline in the parallel put phase


## Note

`SnapshotItem::Delete` is `#[allow(dead_code)]` here: this PR lands the
persistence-side *handling* and its tests, but nothing *emits* a
`Delete` yet. The GC pass that soft-deletes tasks and serializes them to
`Delete` lands in the next PR in the stack. So this PR is a no-op at
runtime.

---------
Co-authored-by: 's avatarClaude Opus 4.8 (1M context) <noreply@anthropic.com>
parent 863a0ada
...@@ -1244,7 +1244,7 @@ impl TurboTasksBackend { ...@@ -1244,7 +1244,7 @@ impl TurboTasksBackend {
None None
}; };
SnapshotItem { SnapshotItem::Put {
task_id, task_id,
meta, meta,
data, data,
......
...@@ -1044,7 +1044,7 @@ mod tests { ...@@ -1044,7 +1044,7 @@ mod tests {
_: &super::TaskStorage, _: &super::TaskStorage,
_: &mut TurboBincodeBuffer, _: &mut TurboBincodeBuffer,
) -> SnapshotItem { ) -> SnapshotItem {
SnapshotItem { SnapshotItem::Put {
task_id, task_id,
meta: Some(TurboBincodeBuffer::default()), meta: Some(TurboBincodeBuffer::default()),
data: None, data: None,
...@@ -1112,7 +1112,7 @@ mod tests { ...@@ -1112,7 +1112,7 @@ mod tests {
// The pre-snapshot snapshot copy should have been encoded and returned. // The pre-snapshot snapshot copy should have been encoded and returned.
assert_eq!(items.len(), 1); assert_eq!(items.len(), 1);
assert_eq!(items[0].task_id, task_id); assert_eq!(items[0].task_id(), task_id);
{ {
let guard = storage.access_mut(task_id); let guard = storage.access_mut(task_id);
...@@ -1179,7 +1179,7 @@ mod tests { ...@@ -1179,7 +1179,7 @@ mod tests {
.collect(); .collect();
assert_eq!(items.len(), 1); assert_eq!(items.len(), 1);
assert_eq!(items[0].task_id, task_id); assert_eq!(items[0].task_id(), task_id);
{ {
let guard = storage.access_mut(task_id); let guard = storage.access_mut(task_id);
...@@ -1227,7 +1227,7 @@ mod tests { ...@@ -1227,7 +1227,7 @@ mod tests {
.collect(); .collect();
assert_eq!(items.len(), 1); assert_eq!(items.len(), 1);
assert_eq!(items[0].task_id, task_id); assert_eq!(items[0].task_id(), task_id);
// The entry must be gone from the map now that it has been persisted. // The entry must be gone from the map now that it has been persisted.
assert!( assert!(
...@@ -1324,7 +1324,7 @@ mod tests { ...@@ -1324,7 +1324,7 @@ mod tests {
.flat_map(|shard| shard.into_iter()) .flat_map(|shard| shard.into_iter())
.collect(); .collect();
assert_eq!(items.len(), 1); assert_eq!(items.len(), 1);
assert_eq!(items[0].task_id, modified_id); assert_eq!(items[0].task_id(), modified_id);
} }
#[tokio::test(flavor = "multi_thread")] #[tokio::test(flavor = "multi_thread")]
......
...@@ -8,15 +8,40 @@ use turbo_tasks_hash::Xxh3Hash64Hasher; ...@@ -8,15 +8,40 @@ use turbo_tasks_hash::Xxh3Hash64Hasher;
pub type TaskTypeHash = [u8; 8]; pub type TaskTypeHash = [u8; 8];
/// A single item yielded by the snapshot iterator during persistence. /// A single item yielded by the snapshot iterator during persistence: either a put (persist a
pub struct SnapshotItem { /// modified task's meta/data + optionally register a new task's type) or a delete (tombstone a
pub task_id: TaskId, /// GC-collected task's on-disk copy). Both ride the one iterator `save_snapshot` consumes, so
/// tombstones are applied in the same commit and batch as the puts.
pub enum SnapshotItem {
Put {
task_id: TaskId,
/// Serialized task meta data, if modified /// Serialized task meta data, if modified
pub meta: Option<TurboBincodeBuffer>, meta: Option<TurboBincodeBuffer>,
/// Serialized task data, if modified /// Serialized task data, if modified
pub data: Option<TurboBincodeBuffer>, data: Option<TurboBincodeBuffer>,
/// Task type for new tasks that need to be added to the task cache /// Task type for new tasks that need to be added to the task cache
pub task_type_hash: Option<TaskTypeHash>, task_type_hash: Option<TaskTypeHash>,
},
// Constructed by the GC pass that emits `Delete` for soft-deleted tasks, which lands in a
// later PR in the stack.
#[allow(dead_code)]
Delete {
task_id: TaskId,
/// The deleted task's `TaskCache` key. Always present: only persistent tasks are
/// collected, and those always have a task type.
task_type_hash: TaskTypeHash,
},
}
impl SnapshotItem {
/// The task this item persists or tombstones. (Currently only used by tests, which assert on
/// the id of items yielded by the snapshot iterator.)
#[cfg(test)]
pub fn task_id(&self) -> TaskId {
match self {
SnapshotItem::Put { task_id, .. } | SnapshotItem::Delete { task_id, .. } => *task_id,
}
}
} }
/// Computes a deterministic 64-bit hash of a CachedTaskType for use as a TaskCache key. /// Computes a deterministic 64-bit hash of a CachedTaskType for use as a TaskCache key.
......
...@@ -234,6 +234,25 @@ impl<'a> TurboWriteBatch<'a> { ...@@ -234,6 +234,25 @@ impl<'a> TurboWriteBatch<'a> {
.put(key_space as u32, key.into_static(), value.into()) .put(key_space as u32, key.into_static(), value.into())
} }
/// Writes a delete (tombstone) for `key` into the write batch.
///
/// Use [`Self::delete_value`] to remove a single mapping from a MultiValue KeySpace
pub fn delete(&self, key_space: KeySpace, key: WriteBuffer<'_>) -> Result<()> {
self.batch.delete(key_space as u32, key.into_static())
}
/// Writes a tombstone for a single `key` -> `value` mapping, leaving other values under `key`
/// intact. Only valid for `MultiValue` families (`TaskCache`).
pub fn delete_value(
&self,
key_space: KeySpace,
key: WriteBuffer<'_>,
value: WriteBuffer<'_>,
) -> Result<()> {
self.batch
.delete_value(key_space as u32, key.into_static(), value.into())
}
/// Flushes a key space of the write batch, reducing the amount of buffered memory used. /// Flushes a key space of the write batch, reducing the amount of buffered memory used.
/// Does not commit any data persistently. /// Does not commit any data persistently.
/// ///
......
...@@ -236,20 +236,22 @@ impl TurboBackingStorage { ...@@ -236,20 +236,22 @@ impl TurboBackingStorage {
let batch = self.inner.database.write_batch()?; let batch = self.inner.database.write_batch()?;
{ {
let _span = tracing::trace_span!("update task data").entered(); let span = tracing::trace_span!("update task data");
let mut snapshot_meta = let mut snapshot_meta =
parallel::map_collect_owned::<_, _, Result<Vec<_>>>(snapshots, |shard: I| { parallel::map_collect_owned::<_, _, Result<Vec<_>>>(snapshots, |shard: I| {
let _span = span.clone().entered();
let mut max_new_task_id = 0; let mut max_new_task_id = 0;
let mut data_items = 0; let mut data_items = 0;
let mut meta_items = 0; let mut meta_items = 0;
let mut task_cache_items = 0; let mut task_cache_items = 0;
for SnapshotItem { for item in shard {
match item {
SnapshotItem::Put {
task_id, task_id,
meta, meta,
data, data,
task_type_hash, task_type_hash,
} in shard } => {
{
let key = IntKey::new(*task_id); let key = IntKey::new(*task_id);
let key = key.as_ref(); let key = key.as_ref();
if let Some(meta) = meta { if let Some(meta) = meta {
...@@ -268,7 +270,7 @@ impl TurboBackingStorage { ...@@ -268,7 +270,7 @@ impl TurboBackingStorage {
)?; )?;
data_items += 1; data_items += 1;
} }
// Write task cache entry inline if this is a new task // Register the task type only for new tasks.
if let Some(task_type_hash) = task_type_hash { if let Some(task_type_hash) = task_type_hash {
batch.put( batch.put(
KeySpace::TaskCache, KeySpace::TaskCache,
...@@ -279,12 +281,29 @@ impl TurboBackingStorage { ...@@ -279,12 +281,29 @@ impl TurboBackingStorage {
max_new_task_id = max_new_task_id.max(*task_id); max_new_task_id = max_new_task_id.max(*task_id);
} }
} }
SnapshotItem::Delete {
task_id,
task_type_hash,
} => {
let key = IntKey::new(*task_id);
let key = key.as_ref();
batch.delete(KeySpace::TaskMeta, WriteBuffer::Borrowed(key))?;
batch.delete(KeySpace::TaskData, WriteBuffer::Borrowed(key))?;
// TaskCache is MultiValue, delete just this id from the bucket.
batch.delete_value(
KeySpace::TaskCache,
WriteBuffer::Borrowed(&task_type_hash[..]),
WriteBuffer::Borrowed(key),
)?;
}
}
}
Ok(SnapshotMeta { Ok(SnapshotMeta {
data_items, data_items,
meta_items, meta_items,
task_cache_items, task_cache_items,
// The on-disk byte totals aren't known until the batch is committed below; // The on-disk byte totals aren't known until the batch is committed
// they're filled in from `CommitStats` after `batch.commit()`. // below; they're filled in from `CommitStats` after `batch.commit()`.
bytes_written: 0, bytes_written: 0,
bytes_deleted: 0, bytes_deleted: 0,
max_next_task_id: max_new_task_id, max_next_task_id: max_new_task_id,
...@@ -294,13 +313,13 @@ impl TurboBackingStorage { ...@@ -294,13 +313,13 @@ impl TurboBackingStorage {
.reduce(|t1, t2| t1.merge(t2)) .reduce(|t1, t2| t1.merge(t2))
.unwrap_or_default(); .unwrap_or_default();
let span = tracing::trace_span!("flush task data").entered(); let span = tracing::trace_span!("flush task data");
parallel::try_for_each( parallel::try_for_each(
&[KeySpace::TaskMeta, KeySpace::TaskData, KeySpace::TaskCache], &[KeySpace::TaskMeta, KeySpace::TaskData, KeySpace::TaskCache],
|&key_space| { |&key_space| {
let _span = span.clone().entered(); let _span = span.clone().entered();
// Safety: `map_collect_owned` has returned, so no concurrent `put` or // Safety: `map_collect_owned` has returned, so no concurrent `put` or `delete`
// `delete` on these key spaces are in-flight. // on these key spaces are in-flight.
unsafe { batch.flush(key_space) } unsafe { batch.flush(key_space) }
}, },
)?; )?;
...@@ -484,6 +503,20 @@ mod tests { ...@@ -484,6 +503,20 @@ mod tests {
Ok(()) Ok(())
} }
/// Reads the TaskIds stored under `hash` in `TaskCache`, sorted for stable comparison.
fn task_cache_ids(db: &TurboKeyValueDatabase, hash: u64) -> Result<Vec<TaskId>> {
let mut ids: Vec<TaskId> = db
.get_multiple(KeySpace::TaskCache, &hash.to_le_bytes())?
.iter()
.map(|bytes| {
let bytes: [u8; 4] = Borrow::<[u8]>::borrow(bytes).try_into().unwrap();
TaskId::try_from(u32::from_le_bytes(bytes)).unwrap()
})
.collect();
ids.sort_by_key(|id| **id);
Ok(ids)
}
/// Tests that `get_multiple` correctly returns multiple TaskIds when the same hash key /// Tests that `get_multiple` correctly returns multiple TaskIds when the same hash key
/// is used (simulating a hash collision scenario). /// is used (simulating a hash collision scenario).
/// ///
...@@ -511,26 +544,12 @@ mod tests { ...@@ -511,26 +544,12 @@ mod tests {
write_task_cache_entry(&db, collision_hash, task_id_3)?; write_task_cache_entry(&db, collision_hash, task_id_3)?;
// Now query using get_multiple - should return all three TaskIds // Now query using get_multiple - should return all three TaskIds
let results = db.get_multiple(KeySpace::TaskCache, &collision_hash.to_le_bytes())?;
assert_eq!( assert_eq!(
results.len(), task_cache_ids(&db, collision_hash)?,
3, vec![task_id_1, task_id_2, task_id_3],
"Should return all 3 task IDs for the colliding hash" "Should return all 3 task IDs for the colliding hash"
); );
// Convert results to TaskIds and verify all three are present
let mut found_ids: Vec<TaskId> = results
.iter()
.map(|bytes| {
let bytes: [u8; 4] = Borrow::<[u8]>::borrow(bytes).try_into().unwrap();
TaskId::try_from(u32::from_le_bytes(bytes)).unwrap()
})
.collect();
found_ids.sort_by_key(|id| **id);
assert_eq!(found_ids, vec![task_id_1, task_id_2, task_id_3]);
db.shutdown()?; db.shutdown()?;
Ok(()) Ok(())
} }
...@@ -589,4 +608,78 @@ mod tests { ...@@ -589,4 +608,78 @@ mod tests {
Ok(()) Ok(())
} }
/// `save_snapshot` delete path: a `Delete` item must erase the task's `TaskMeta` and
/// `TaskData` (`SingleValue`) entries and remove *only* that id from its `TaskCache`
/// (`MultiValue`) bucket.
///
/// The colliding survivor is never read or rewritten — the key-value tombstone names the
/// single id it deletes, so anything else in the bucket is untouched whether or not this
/// commit knows about it.
#[tokio::test(flavor = "multi_thread")]
async fn test_save_snapshot_delete_tombstones_task() -> Result<()> {
let tempdir = tempfile::tempdir()?;
let path = tempdir.path();
let collision_hash: u64 = 0xC0FFEE;
let deleted_id = TaskId::try_from(111u32).unwrap();
let survivor_id = TaskId::try_from(222u32).unwrap();
let deleted_key = (*deleted_id).to_le_bytes();
let db = TurboKeyValueDatabase::new(path.to_path_buf(), false, true, false)?;
// Both ids collide in one TaskCache bucket, purely on disk; the deleted task also has
// meta and data entries.
write_task_cache_entry(&db, collision_hash, deleted_id)?;
write_task_cache_entry(&db, collision_hash, survivor_id)?;
let batch = db.write_batch()?;
batch.put(
KeySpace::TaskMeta,
WriteBuffer::Borrowed(&deleted_key),
WriteBuffer::Borrowed(b"meta-bytes"),
)?;
batch.put(
KeySpace::TaskData,
WriteBuffer::Borrowed(&deleted_key),
WriteBuffer::Borrowed(b"data-bytes"),
)?;
batch.commit()?;
// Sanity: everything is present before the delete.
assert!(db.get(KeySpace::TaskMeta, &deleted_key)?.is_some());
assert!(db.get(KeySpace::TaskData, &deleted_key)?.is_some());
assert_eq!(
task_cache_ids(&db, collision_hash)?,
vec![deleted_id, survivor_id],
);
let storage = TurboBackingStorage::new_in_memory(db);
// Snapshot with no task data, just the one deletion.
storage.save_snapshot(
Vec::new(),
vec![vec![SnapshotItem::Delete {
task_id: deleted_id,
task_type_hash: collision_hash.to_le_bytes(),
}]],
)?;
let db = &storage.inner.database;
assert!(
db.get(KeySpace::TaskMeta, &deleted_key)?.is_none(),
"TaskMeta should be tombstoned"
);
assert!(
db.get(KeySpace::TaskData, &deleted_key)?.is_none(),
"TaskData should be tombstoned"
);
assert_eq!(
task_cache_ids(db, collision_hash)?,
vec![survivor_id],
"save_snapshot should delete only the named id from the bucket"
);
db.shutdown()?;
Ok(())
}
} }
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