Unverified Commit 8db9a752 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

turbo-tasks: fix hashed cell mode crash on task error (re-land #91576) (#92108)

### What?

Re-lands #91576 ("turbo-tasks: add hashed cell mode for hash-based
change detection without cell data"), which was reverted in #92103 due
to a `FATAL` crash in the `filesystem-cache` test suite.

Includes a bug fix on top: in `task_execution_completed_prepare`, skip
updating `cell_type_max_index` when the task completed with an error.

Also adds a `CellHash = [u8; 16]` type alias (requested in review) used
throughout the hash pipeline.

### Why?

**The original feature** (`serialization = "hash"` on `FileContent` and
`Code`) stores a hash of the cell data instead of the full serialized
value. On session restore, the hash is used to detect whether cell
content has changed without needing the full data in memory. This avoids
a large persistent cache size increase.

**The bug** that caused the revert: When a task fails partway through
re-execution (before recreating all the cells from its previous run),
`cell_counters` only reflects the partially-executed state. The old code
used those partial counters to update `cell_type_max_index`, removing
entries for cell types that were not yet created at the point of
failure. This caused downstream tasks that still held cell dependencies
from the previous successful run to hit a hard "Cell no longer exists"
error.

**Concrete failure path** in `filesystem-cache rename app page` test:

1. `get_app_page_entry` runs for `/remove-me/page`, creating two
`FileContent` cells (indices 0 and 1). `cell_type_max_index[FileContent]
= 2` is persisted.
2. The folder is renamed (`app/remove-me` → `app/add-me`), dirtying the
task.
3. On re-execution, `get_app_page_entry` fails at `config.await?` (the
loader tree errors because the directory is gone) — before any
`FileContent::cell()` calls.
4. `cell_counters` has no `FileContent` entry → old code removed
`cell_type_max_index[FileContent]`.
5. The `parse` task tries to read `FileContent` cell 1 from
`get_app_page_entry` → `cell_type_max_index` is `None` → **"Cell no
longer exists" panic → FATAL error**.

**Why it didn't crash before** `serialization = "hash"`: `FileContent`
was previously serializable, so `parse` read stale cell data directly
from `persistent_cell_data`, which `task_execution_completed_cleanup`
already preserves on error. With `serialization = "hash"`, data is
transient — readers fall back to `cell_type_max_index` for range
validation, where a stale `None` caused the crash.

### How?

#### Core feature: `serialization = "hash"` cell mode

- New `SerializationMode::Hash` variant in `turbo-tasks-macros` — marks
a value type as non-serializable but stores a `DeterministicHash` of the
cell data for change detection.
- `VcCellHashedCompareMode<T>` cell mode: compares values via
`PartialEq` when available, falls back to hash comparison when transient
data has been evicted.
- `hashed_compare_and_update` /
`hashed_compare_and_update_with_shared_reference` on `CurrentCellRef`
compute and pass content hashes through the update pipeline.
- Backend `update_cell` uses hash-based comparison to skip invalidation
when the old cell data is unavailable but the hash matches.
- `cell_data_hash: AutoMap<CellId, CellHash>` field in task storage
persists hashes across sessions.
- Stale `cell_data_hash` entries are cleaned up in
`task_execution_completed_cleanup` alongside cell data removal.
- `CellHash = [u8; 16]` type alias keeps alignment at 1 byte to avoid
padding growth in `AutoMap`/`LazyField` enum variants.
- Hash bytes use little-endian encoding (`to_le_bytes`) for
cross-platform cache portability.

#### Bug fix: preserve `cell_type_max_index` on task error

In `task_execution_completed_prepare`, guard the `cell_type_max_index`
update block with `if result.is_ok()`. This mirrors the existing
`task_execution_completed_cleanup` behavior that already skips cell data
removal when `is_error` is true, keeping `cell_type_max_index`
consistent with the preserved transient cell data.

#### Applied to `FileContent` and `Code`

- `FileContent` uses `serialization = "hash"` — full content is
persisted via a separate `PersistedFileContent` type when needed (e.g.,
in `DiskFileSystem::write`).
- `Code` uses `serialization = "hash"` with `Arc<Vec<Mapping>>` for
cheap cloning. `Code::cell_persisted()` creates a `PersistedCode` cell
directly and returns `Vc<Code>` via `PersistedCode::to_code()`, avoiding
an intermediate hash-mode cell.

#### Other improvements

- `DeterministicHash` impls for `SmallVec` and `()`.
- `Xxh3Hash128Hasher::finish_bytes()` method returning `[u8; 16]`.
- `hash = "manual"` option on `#[turbo_tasks::value]` to opt out of
auto-deriving `DeterministicHash`.

**Note:** The shutdown hang and cache poisoning fixes that were
previously on this branch have been merged separately via #92254.

### Test plan

- [x] `test/e2e/filesystem-cache/filesystem-cache.test.ts` passes (all
17 tests)
- [x] New
`turbopack/crates/turbo-tasks-backend/tests/hashed_cell_mode.rs`
integration test verifies hash-based change detection: value changes
trigger invalidation, equal values (same hash) do not
- [x] `cargo check` passes for `turbo-tasks`, `turbo-tasks-backend`,
`turbo-tasks-fs`, `turbopack-core`, `turbopack-ecmascript`
- [x] CI green (attempt 2)

<!-- NEXT_JS_LLM_PR -->

---------
Co-authored-by: 's avatarTobias Koppers <sokra@users.noreply.github.com>
Co-authored-by: 's avatarClaude <noreply@anthropic.com>
parent 98539441
...@@ -9717,6 +9717,7 @@ dependencies = [ ...@@ -9717,6 +9717,7 @@ dependencies = [
"bincode 2.0.1", "bincode 2.0.1",
"data-encoding", "data-encoding",
"sha2", "sha2",
"smallvec",
"turbo-tasks-macros", "turbo-tasks-macros",
"xxhash-rust", "xxhash-rust",
] ]
......
...@@ -31,7 +31,7 @@ use turbo_tasks::{ ...@@ -31,7 +31,7 @@ use turbo_tasks::{
ReadOutputOptions, ReadTracking, SharedReference, TRANSIENT_TASK_BIT, TaskExecutionReason, ReadOutputOptions, ReadTracking, SharedReference, TRANSIENT_TASK_BIT, TaskExecutionReason,
TaskId, TaskPriority, TraitTypeId, TurboTasksBackendApi, TurboTasksPanic, ValueTypeId, TaskId, TaskPriority, TraitTypeId, TurboTasksBackendApi, TurboTasksPanic, ValueTypeId,
backend::{ backend::{
Backend, CachedTaskType, CellContent, TaskExecutionSpec, TransientTaskType, Backend, CachedTaskType, CellContent, CellHash, TaskExecutionSpec, TransientTaskType,
TurboTaskContextError, TurboTaskLocalContextError, TurboTasksError, TurboTaskContextError, TurboTaskLocalContextError, TurboTasksError,
TurboTasksExecutionError, TurboTasksExecutionErrorMessage, TypedCellContent, TurboTasksExecutionError, TurboTasksExecutionErrorMessage, TypedCellContent,
VerificationMode, VerificationMode,
...@@ -2732,6 +2732,19 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> { ...@@ -2732,6 +2732,19 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> {
removed_cell_data.push(data); removed_cell_data.push(data);
} }
} }
// Remove cell_data_hash entries for cells that no longer exist
let to_remove_hash: Vec<_> = task
.iter_cell_data_hash()
.filter_map(|(cell, _)| {
cell_counters
.get(&cell.type_id)
.is_none_or(|start_index| cell.index >= *start_index)
.then_some(*cell)
})
.collect();
for cell in to_remove_hash {
task.remove_cell_data_hash(&cell);
}
} }
// Clean up task storage after execution: // Clean up task storage after execution:
...@@ -3022,6 +3035,7 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> { ...@@ -3022,6 +3035,7 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> {
is_serializable_cell_content: bool, is_serializable_cell_content: bool,
content: CellContent, content: CellContent,
updated_key_hashes: Option<SmallVec<[u64; 2]>>, updated_key_hashes: Option<SmallVec<[u64; 2]>>,
content_hash: Option<CellHash>,
verification_mode: VerificationMode, verification_mode: VerificationMode,
turbo_tasks: &dyn TurboTasksBackendApi<TurboTasksBackend<B>>, turbo_tasks: &dyn TurboTasksBackendApi<TurboTasksBackend<B>>,
) { ) {
...@@ -3031,6 +3045,7 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> { ...@@ -3031,6 +3045,7 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> {
content, content,
is_serializable_cell_content, is_serializable_cell_content,
updated_key_hashes, updated_key_hashes,
content_hash,
verification_mode, verification_mode,
self.execute_context(turbo_tasks), self.execute_context(turbo_tasks),
); );
...@@ -3584,6 +3599,7 @@ impl<B: BackingStorage> Backend for TurboTasksBackend<B> { ...@@ -3584,6 +3599,7 @@ impl<B: BackingStorage> Backend for TurboTasksBackend<B> {
is_serializable_cell_content: bool, is_serializable_cell_content: bool,
content: CellContent, content: CellContent,
updated_key_hashes: Option<SmallVec<[u64; 2]>>, updated_key_hashes: Option<SmallVec<[u64; 2]>>,
content_hash: Option<CellHash>,
verification_mode: VerificationMode, verification_mode: VerificationMode,
turbo_tasks: &dyn TurboTasksBackendApi<Self>, turbo_tasks: &dyn TurboTasksBackendApi<Self>,
) { ) {
...@@ -3593,6 +3609,7 @@ impl<B: BackingStorage> Backend for TurboTasksBackend<B> { ...@@ -3593,6 +3609,7 @@ impl<B: BackingStorage> Backend for TurboTasksBackend<B> {
is_serializable_cell_content, is_serializable_cell_content,
content, content,
updated_key_hashes, updated_key_hashes,
content_hash,
verification_mode, verification_mode,
turbo_tasks, turbo_tasks,
); );
......
...@@ -6,7 +6,7 @@ use rustc_hash::FxHashSet; ...@@ -6,7 +6,7 @@ use rustc_hash::FxHashSet;
use smallvec::SmallVec; use smallvec::SmallVec;
use turbo_tasks::{ use turbo_tasks::{
CellId, FxIndexMap, TaskId, TypedSharedReference, CellId, FxIndexMap, TaskId, TypedSharedReference,
backend::{CellContent, VerificationMode}, backend::{CellContent, CellHash, VerificationMode},
}; };
#[cfg(feature = "trace_task_dirty")] #[cfg(feature = "trace_task_dirty")]
...@@ -56,10 +56,17 @@ impl UpdateCellOperation { ...@@ -56,10 +56,17 @@ impl UpdateCellOperation {
content: CellContent, content: CellContent,
is_serializable_cell_content: bool, is_serializable_cell_content: bool,
updated_key_hashes: Option<SmallVec<[u64; 2]>>, updated_key_hashes: Option<SmallVec<[u64; 2]>>,
content_hash: Option<CellHash>,
#[cfg(feature = "verify_determinism")] verification_mode: VerificationMode, #[cfg(feature = "verify_determinism")] verification_mode: VerificationMode,
#[cfg(not(feature = "verify_determinism"))] _verification_mode: VerificationMode, #[cfg(not(feature = "verify_determinism"))] _verification_mode: VerificationMode,
mut ctx: impl ExecuteContext<'_>, mut ctx: impl ExecuteContext<'_>,
) { ) {
// content_hash is only meaningful for transient (non-serializable) cells
debug_assert!(
!is_serializable_cell_content || content_hash.is_none(),
"content_hash must be None for serializable cell content"
);
let content = if let CellContent(Some(new_content)) = content { let content = if let CellContent(Some(new_content)) = content {
Some(new_content.into_typed(cell.type_id)) Some(new_content.into_typed(cell.type_id))
} else { } else {
...@@ -107,27 +114,46 @@ impl UpdateCellOperation { ...@@ -107,27 +114,46 @@ impl UpdateCellOperation {
// When not recomputing, we need to notify dependent tasks if the content actually // When not recomputing, we need to notify dependent tasks if the content actually
// changes. // changes.
// For transient cells without available content, use hash-based comparison to
// detect whether the value actually changed—avoiding unnecessary invalidation.
let skip_invalidation = !is_serializable_cell_content && {
let has_old_content = task.has_cell_data(false, cell);
if !has_old_content {
match (content_hash, task.get_cell_data_hash(&cell)) {
(Some(new_hash), Some(old_hash)) => new_hash == *old_hash,
_ => false,
}
} else {
false
}
};
#[cfg(feature = "trace_task_dirty")] #[cfg(feature = "trace_task_dirty")]
let has_updated_key_hashes = updated_key_hashes.is_some(); let has_updated_key_hashes = updated_key_hashes.is_some();
let updated_key_hashes_set = updated_key_hashes.map(|updated_key_hashes| { let updated_key_hashes_set = updated_key_hashes.map(|updated_key_hashes| {
Lazy::new(|| updated_key_hashes.into_iter().collect::<FxHashSet<u64>>()) Lazy::new(|| updated_key_hashes.into_iter().collect::<FxHashSet<u64>>())
}); });
let tasks_with_keys = // Collect dependent tasks only when not skipping invalidation.
task.iter_cell_dependents() // The iterator borrows from `task`, so it must be scoped to drop before
.filter_map(|(dependent_cell, key, task)| { // we mutably borrow `task` again in the fast path.
(dependent_cell == cell
&& key.is_none_or(|key_hash| {
updated_key_hashes_set
.as_ref()
.is_none_or(|set| set.contains(&key_hash))
}))
.then_some((task, key))
});
let mut dependent_tasks: FxIndexMap<TaskId, SmallVec<[Option<u64>; 2]>> = let mut dependent_tasks: FxIndexMap<TaskId, SmallVec<[Option<u64>; 2]>> =
FxIndexMap::default(); FxIndexMap::default();
for (task, key) in tasks_with_keys { if !skip_invalidation {
dependent_tasks.entry(task).or_default().push(key); let tasks_with_keys =
task.iter_cell_dependents()
.filter_map(|(dependent_cell, key, task)| {
(dependent_cell == cell
&& key.is_none_or(|key_hash| {
updated_key_hashes_set
.as_ref()
.is_none_or(|set| set.contains(&key_hash))
}))
.then_some((task, key))
});
for (task, key) in tasks_with_keys {
dependent_tasks.entry(task).or_default().push(key);
}
} }
if !dependent_tasks.is_empty() { if !dependent_tasks.is_empty() {
...@@ -146,6 +172,9 @@ impl UpdateCellOperation { ...@@ -146,6 +172,9 @@ impl UpdateCellOperation {
let old_content = task.remove_cell_data(is_serializable_cell_content, cell); let old_content = task.remove_cell_data(is_serializable_cell_content, cell);
// Update cell_data_hash before dropping the task lock
update_cell_data_hash(&mut task, &cell, is_serializable_cell_content, content_hash);
drop(task); drop(task);
drop(old_content); drop(old_content);
...@@ -181,6 +210,9 @@ impl UpdateCellOperation { ...@@ -181,6 +210,9 @@ impl UpdateCellOperation {
task.remove_cell_data(is_serializable_cell_content, cell) task.remove_cell_data(is_serializable_cell_content, cell)
}; };
// Update cell_data_hash for non-serializable cells.
update_cell_data_hash(&mut task, &cell, is_serializable_cell_content, content_hash);
let in_progress_cell = task.remove_in_progress_cells(&cell); let in_progress_cell = task.remove_in_progress_cells(&cell);
drop(task); drop(task);
...@@ -207,6 +239,26 @@ impl UpdateCellOperation { ...@@ -207,6 +239,26 @@ impl UpdateCellOperation {
} }
} }
/// Updates the stored cell_data_hash for a non-serializable cell.
/// Skips the update if the hash hasn't changed to avoid unnecessary writes.
fn update_cell_data_hash(
task: &mut impl TaskGuard,
cell: &CellId,
is_serializable_cell_content: bool,
content_hash: Option<CellHash>,
) {
if !is_serializable_cell_content {
let old_hash = task.get_cell_data_hash(cell).copied();
if old_hash != content_hash {
if let Some(hash) = content_hash {
task.insert_cell_data_hash(*cell, hash);
} else {
task.remove_cell_data_hash(cell);
}
}
}
}
impl Operation for UpdateCellOperation { impl Operation for UpdateCellOperation {
fn execute(mut self, ctx: &mut impl ExecuteContext<'_>) { fn execute(mut self, ctx: &mut impl ExecuteContext<'_>) {
loop { loop {
......
...@@ -23,7 +23,7 @@ use parking_lot::Mutex; ...@@ -23,7 +23,7 @@ use parking_lot::Mutex;
use turbo_tasks::{ use turbo_tasks::{
CellId, SharedReference, TaskExecutionReason, TaskId, TraitTypeId, TypedSharedReference, CellId, SharedReference, TaskExecutionReason, TaskId, TraitTypeId, TypedSharedReference,
ValueTypeId, ValueTypeId,
backend::{CachedTaskType, TransientTaskType}, backend::{CachedTaskType, CellHash, TransientTaskType},
event::Event, event::Event,
task_storage, task_storage,
}; };
...@@ -275,6 +275,16 @@ struct TaskStorageSchema { ...@@ -275,6 +275,16 @@ struct TaskStorageSchema {
#[field(storage = "auto_map", category = "transient", shrink_on_completion)] #[field(storage = "auto_map", category = "transient", shrink_on_completion)]
transient_cell_data: AutoMap<CellId, SharedReference>, transient_cell_data: AutoMap<CellId, SharedReference>,
/// Hash of transient cell data, persisted for hash-based change detection when
/// transient data has been evicted from memory.
///
/// Stored as `[u8; 16]` (little-endian bytes of a u128) rather than `u128` to keep
/// the 1-byte alignment out of the `AutoMap` and therefore out of the `LazyField`
/// enum; a bare `u128` would grow the enum from 56 to 64 bytes due to its 16-byte
/// alignment requirement.
#[field(storage = "auto_map", category = "data", shrink_on_completion)]
cell_data_hash: AutoMap<CellId, CellHash>,
/// Maximum cell index per cell type. /// Maximum cell index per cell type.
#[field(storage = "auto_map", category = "data", shrink_on_completion)] #[field(storage = "auto_map", category = "data", shrink_on_completion)]
cell_type_max_index: AutoMap<ValueTypeId, u32>, cell_type_max_index: AutoMap<ValueTypeId, u32>,
......
#![feature(arbitrary_self_types)]
#![feature(arbitrary_self_types_pointers)]
#![allow(clippy::needless_return)] // tokio macro-generated code doesn't respect this
use std::sync::atomic::{AtomicU32, Ordering};
use anyhow::Result;
use turbo_tasks::{ResolvedVc, State, Vc};
use turbo_tasks_hash::{DeterministicHash, DeterministicHasher};
use turbo_tasks_testing::{Registration, register, run};
static REGISTRATION: Registration = register!();
static EXECUTION_COUNTER: AtomicU32 = AtomicU32::new(0);
/// A value type using `serialization = "hash"` mode.
/// Only `value` participates in DeterministicHash/Eq; `noise` does not.
#[turbo_tasks::value(serialization = "hash", eq = "manual", hash = "manual")]
#[derive(Debug)]
struct HashedValue {
value: u32,
noise: u64,
}
impl DeterministicHash for HashedValue {
fn deterministic_hash<H: DeterministicHasher>(&self, state: &mut H) {
self.value.deterministic_hash(state);
}
}
impl PartialEq for HashedValue {
fn eq(&self, other: &Self) -> bool {
self.value == other.value
}
}
impl Eq for HashedValue {}
#[turbo_tasks::value(transparent)]
struct Step(State<u32>);
#[turbo_tasks::value]
struct ConsumeResult {
value: u32,
random: u32,
}
#[turbo_tasks::function(operation)]
fn create_state_operation() -> Vc<Step> {
Step(State::new(0)).cell()
}
/// Produces a HashedValue from a state. The noise field changes each execution
/// but does not affect hash or equality.
#[turbo_tasks::function(operation)]
async fn produce_hashed(input: ResolvedVc<Step>) -> Result<Vc<HashedValue>> {
let value = *input.await?.get();
let noise = EXECUTION_COUNTER.fetch_add(1, Ordering::Relaxed) as u64;
Ok(HashedValue { value, noise }.cell())
}
/// Consumes the HashedValue and records a random number to detect re-execution.
#[turbo_tasks::function(operation)]
async fn consume_hashed(input: ResolvedVc<Step>) -> Result<Vc<ConsumeResult>> {
let hashed = produce_hashed(input).connect();
let v = hashed.await?;
let value = v.value;
let random = EXECUTION_COUNTER.fetch_add(1, Ordering::Relaxed);
Ok(ConsumeResult { value, random }.cell())
}
/// Test 1: When the value changes, the consumer SHOULD be invalidated and re-execute.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_hashed_cell_mode_change_triggers_invalidation() {
run(&REGISTRATION, || async {
let state_op = create_state_operation();
let state_vc = state_op.resolve().strongly_consistent().await?;
let state = state_op.read_strongly_consistent().await?;
state.set(42);
let consumer = consume_hashed(state_vc);
let result1 = consumer.read_strongly_consistent().await?;
assert_eq!(result1.value, 42);
// Change the value — this should invalidate the consumer.
state.set(99);
let result2 = consumer.read_strongly_consistent().await?;
assert_eq!(result2.value, 99);
// Consumer must have re-executed (different random).
assert_ne!(
result1.random, result2.random,
"consumer should re-execute when value changes"
);
anyhow::Ok(())
})
.await
.unwrap();
}
/// Test 2: When the value stays the same, the consumer should NOT be invalidated.
/// The producer re-runs (state.set triggers it) but produces an equal HashedValue.
/// With `serialization = "hash"`, the consumer should not be re-executed.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_hashed_cell_mode_equal_value_no_invalidation() {
run(&REGISTRATION, || async {
let state_op = create_state_operation();
let state_vc = state_op.resolve().strongly_consistent().await?;
let state = state_op.read_strongly_consistent().await?;
state.set(42);
let consumer = consume_hashed(state_vc);
let result1 = consumer.read_strongly_consistent().await?;
assert_eq!(result1.value, 42);
// Re-trigger the producer with the same value.
// State::set unconditionally invalidates, so the producer re-runs.
// But it produces an equal HashedValue (same `value`, different `noise`).
// Since DeterministicHash and PartialEq only check `value`, the consumer should NOT
// re-execute.
state.set(42);
let result2 = consumer.read_strongly_consistent().await?;
assert_eq!(result2.value, 42);
assert_eq!(
result1.random, result2.random,
"consumer should not re-execute when value (and hash) are the same"
);
anyhow::Ok(())
})
.await
.unwrap();
}
...@@ -8,11 +8,11 @@ use concurrent_queue::ConcurrentQueue; ...@@ -8,11 +8,11 @@ use concurrent_queue::ConcurrentQueue;
use rustc_hash::FxHashMap; use rustc_hash::FxHashMap;
use turbo_tasks::{Invalidator, ReadRef}; use turbo_tasks::{Invalidator, ReadRef};
use crate::{FileContent, LinkContent}; use crate::{LinkContent, PersistedFileContent};
#[derive(PartialEq, Eq)] #[derive(PartialEq, Eq)]
pub enum WriteContent { pub enum WriteContent {
File(ReadRef<FileContent>), File(ReadRef<PersistedFileContent>),
Link(ReadRef<LinkContent>), Link(ReadRef<LinkContent>),
} }
......
...@@ -969,7 +969,12 @@ impl FileSystem for DiskFileSystem { ...@@ -969,7 +969,12 @@ impl FileSystem for DiskFileSystem {
} }
let full_path = self.to_sys_path(&fs_path); let full_path = self.to_sys_path(&fs_path);
let content = content.await?; // Persist the file content so it is stored in the persistent cache.
// Since FileContent uses serialization = "hash", persisting it here ensures the full
// content is available in the persistent cache (via PersistedFileContent) and does not
// require recomputing the content on cache restore — avoiding unnecessary downstream
// recomputation.
let content = content.persist().await?;
let inner = self.inner.clone(); let inner = self.inner.clone();
let invalidator = turbo_tasks::get_invalidator(); let invalidator = turbo_tasks::get_invalidator();
...@@ -979,7 +984,7 @@ impl FileSystem for DiskFileSystem { ...@@ -979,7 +984,7 @@ impl FileSystem for DiskFileSystem {
full_path: PathBuf, full_path: PathBuf,
inner: Arc<DiskFileSystemInner>, inner: Arc<DiskFileSystemInner>,
invalidator: Option<Invalidator>, invalidator: Option<Invalidator>,
content: ReadRef<FileContent>, content: ReadRef<PersistedFileContent>,
} }
impl Effect for WriteEffect { impl Effect for WriteEffect {
...@@ -1028,7 +1033,7 @@ impl FileSystem for DiskFileSystem { ...@@ -1028,7 +1033,7 @@ impl FileSystem for DiskFileSystem {
} }
match &*self.content { match &*self.content {
FileContent::Content(..) => { PersistedFileContent::Content(..) => {
let create_directory = compare == FileComparison::Create; let create_directory = compare == FileComparison::Create;
if create_directory && let Some(parent) = full_path.parent() { if create_directory && let Some(parent) = full_path.parent() {
self.inner.create_directory(parent).await.with_context(|| { self.inner.create_directory(parent).await.with_context(|| {
...@@ -1042,7 +1047,7 @@ impl FileSystem for DiskFileSystem { ...@@ -1042,7 +1047,7 @@ impl FileSystem for DiskFileSystem {
let content = self.content.clone(); let content = self.content.clone();
retry_blocking(|| { retry_blocking(|| {
let mut f = std::fs::File::create(&full_path)?; let mut f = std::fs::File::create(&full_path)?;
let FileContent::Content(file) = &*content else { let PersistedFileContent::Content(file) = &*content else {
unreachable!() unreachable!()
}; };
std::io::copy(&mut file.read(), &mut f)?; std::io::copy(&mut file.read(), &mut f)?;
...@@ -1077,7 +1082,7 @@ impl FileSystem for DiskFileSystem { ...@@ -1077,7 +1082,7 @@ impl FileSystem for DiskFileSystem {
.await .await
.with_context(|| format!("failed to write to {full_path:?}"))?; .with_context(|| format!("failed to write to {full_path:?}"))?;
} }
FileContent::NotFound => { PersistedFileContent::NotFound => {
retry_blocking(|| std::fs::remove_file(&full_path)) retry_blocking(|| std::fs::remove_file(&full_path))
.instrument(tracing::info_span!("remove file", name = ?full_path)) .instrument(tracing::info_span!("remove file", name = ?full_path))
.concurrency_limited(&self.inner.write_semaphore) .concurrency_limited(&self.inner.write_semaphore)
...@@ -1958,8 +1963,8 @@ impl From<std::fs::Permissions> for Permissions { ...@@ -1958,8 +1963,8 @@ impl From<std::fs::Permissions> for Permissions {
} }
} }
#[turbo_tasks::value(shared)] #[turbo_tasks::value(shared, serialization = "hash")]
#[derive(Clone, Debug, DeterministicHash, PartialOrd, Ord)] #[derive(Clone, Debug, PartialOrd, Ord)]
pub enum FileContent { pub enum FileContent {
Content(File), Content(File),
NotFound, NotFound,
...@@ -1971,35 +1976,39 @@ impl From<File> for FileContent { ...@@ -1971,35 +1976,39 @@ impl From<File> for FileContent {
} }
} }
#[derive(Clone, Debug, Eq, PartialEq)] /// A persisted version of [`FileContent`] that stores the full file content in the task cache.
enum FileComparison { ///
Create, /// [`FileContent`] uses `serialization = "hash"`, so only a hash is kept in the persistent cache.
Equal, /// When reading the file content back from the cache, the hash is compared to detect changes, but
NotEqual, /// the actual data is not available. `PersistedFileContent` provides the full data so that
/// [`DiskFileSystem::write`] can retrieve it without re-reading from disk.
#[turbo_tasks::value(shared)]
#[derive(Clone, Debug, DeterministicHash, PartialOrd, Ord)]
pub enum PersistedFileContent {
Content(File),
NotFound,
} }
impl FileContent { impl PersistedFileContent {
/// Performs a comparison of self's data against a disk file's streamed /// Performs a comparison of self's data against a disk file's streamed read.
/// read.
async fn streaming_compare(&self, path: &Path) -> Result<FileComparison> { async fn streaming_compare(&self, path: &Path) -> Result<FileComparison> {
let old_file = let old_file =
extract_disk_access(retry_blocking(|| std::fs::File::open(path)).await, path)?; extract_disk_access(retry_blocking(|| std::fs::File::open(path)).await, path)?;
let Some(old_file) = old_file else { let Some(old_file) = old_file else {
return Ok(match self { return Ok(match self {
FileContent::NotFound => FileComparison::Equal, PersistedFileContent::NotFound => FileComparison::Equal,
_ => FileComparison::Create, _ => FileComparison::Create,
}); });
}; };
// We know old file exists, does the new file? // We know old file exists, does the new file?
let FileContent::Content(new_file) = self else { let PersistedFileContent::Content(new_file) = self else {
return Ok(FileComparison::NotEqual); return Ok(FileComparison::NotEqual);
}; };
let old_meta = extract_disk_access(retry_blocking(|| old_file.metadata()).await, path)?; let old_meta = extract_disk_access(retry_blocking(|| old_file.metadata()).await, path)?;
let Some(old_meta) = old_meta else { let Some(old_meta) = old_meta else {
// If we failed to get meta, then the old file has been deleted between the // If we failed to get meta, then the old file has been deleted between the
// handle open. In which case, we just pretend the file never // handle open. In which case, we just pretend the file never existed.
// existed.
return Ok(FileComparison::Create); return Ok(FileComparison::Create);
}; };
// If the meta is different, we need to rewrite the file to update it. // If the meta is different, we need to rewrite the file to update it.
...@@ -2036,6 +2045,13 @@ impl FileContent { ...@@ -2036,6 +2045,13 @@ impl FileContent {
} }
} }
#[derive(Clone, Debug, Eq, PartialEq)]
enum FileComparison {
Create,
Equal,
NotEqual,
}
bitflags! { bitflags! {
#[derive( #[derive(
Default, Default,
...@@ -2403,6 +2419,18 @@ impl FileContent { ...@@ -2403,6 +2419,18 @@ impl FileContent {
Ok(Vc::cell(hash_xxh3_hash64(self))) Ok(Vc::cell(hash_xxh3_hash64(self)))
} }
/// Converts this [`FileContent`] into a [`PersistedFileContent`] by cloning.
///
/// Use this in contexts where the full file content must be serialized to the persistent
/// task cache (e.g., in [`DiskFileSystem::write`]).
#[turbo_tasks::function]
pub fn persist(&self) -> Vc<PersistedFileContent> {
match self {
FileContent::Content(file) => PersistedFileContent::Content(file.clone()).cell(),
FileContent::NotFound => PersistedFileContent::NotFound.cell(),
}
}
/// Compared to [FileContent::hash], this hashes only the bytes of the file content and /// Compared to [FileContent::hash], this hashes only the bytes of the file content and
/// nothing else, returning `None` if the file does not exist. /// nothing else, returning `None` if the file does not exist.
/// ///
......
...@@ -15,6 +15,7 @@ workspace = true ...@@ -15,6 +15,7 @@ workspace = true
[dependencies] [dependencies]
bincode = { workspace = true } bincode = { workspace = true }
data-encoding = { workspace = true } data-encoding = { workspace = true }
smallvec = { workspace = true }
sha2 = { workspace = true } sha2 = { workspace = true }
turbo-tasks-macros = { workspace = true } turbo-tasks-macros = { workspace = true }
xxhash-rust = { workspace = true } xxhash-rust = { workspace = true }
use std::mem::Discriminant; use std::mem::Discriminant;
use smallvec::SmallVec;
pub use turbo_tasks_macros::DeterministicHash; pub use turbo_tasks_macros::DeterministicHash;
macro_rules! deterministic_hash_number { macro_rules! deterministic_hash_number {
...@@ -152,6 +153,19 @@ impl<T: DeterministicHash> DeterministicHash for Vec<T> { ...@@ -152,6 +153,19 @@ impl<T: DeterministicHash> DeterministicHash for Vec<T> {
} }
} }
impl<T: DeterministicHash, const N: usize> DeterministicHash for SmallVec<[T; N]> {
fn deterministic_hash<H: DeterministicHasher>(&self, state: &mut H) {
state.write_usize(self.len());
for v in self {
v.deterministic_hash(state);
}
}
}
impl DeterministicHash for () {
fn deterministic_hash<H: DeterministicHasher>(&self, _state: &mut H) {}
}
macro_rules! tuple_impls { macro_rules! tuple_impls {
( $( $name:ident )+ ) => { ( $( $name:ident )+ ) => {
impl<$($name: DeterministicHash),+> DeterministicHash for ($($name,)+) impl<$($name: DeterministicHash),+> DeterministicHash for ($($name,)+)
......
...@@ -5,10 +5,10 @@ use xxhash_rust::xxh3::Xxh3Default; ...@@ -5,10 +5,10 @@ use xxhash_rust::xxh3::Xxh3Default;
use crate::{DeterministicHash, DeterministicHasher}; use crate::{DeterministicHash, DeterministicHasher};
/// Hash some content with the Xxh3Hash128 non-cryptographic hash function. /// Hash some content with the Xxh3Hash128 non-cryptographic hash function.
pub fn hash_xxh3_hash128<T: DeterministicHash>(input: T) -> u128 { pub fn hash_xxh3_hash128<T: DeterministicHash>(input: T) -> [u8; 16] {
let mut hasher = Xxh3Hash128Hasher::new(); let mut hasher = Xxh3Hash128Hasher::new();
input.deterministic_hash(&mut hasher); input.deterministic_hash(&mut hasher);
hasher.finish() hasher.finish_bytes()
} }
/// Xxh3Hash128 hasher. /// Xxh3Hash128 hasher.
...@@ -32,7 +32,12 @@ impl Xxh3Hash128Hasher { ...@@ -32,7 +32,12 @@ impl Xxh3Hash128Hasher {
input.deterministic_hash(self); input.deterministic_hash(self);
} }
/// Finish the hash computation and return the digest. /// Finish the hash computation and return the digest as bytes.
pub fn finish_bytes(&self) -> [u8; 16] {
self.0.digest128().to_le_bytes()
}
/// Finish the hash computation and return the digest as u128.
pub fn finish(&self) -> u128 { pub fn finish(&self) -> u128 {
self.0.digest128() self.0.digest128()
} }
......
...@@ -45,6 +45,10 @@ impl TryFrom<LitStr> for CellMode { ...@@ -45,6 +45,10 @@ impl TryFrom<LitStr> for CellMode {
enum SerializationMode { enum SerializationMode {
None, None,
/// Like `None` (no bincode serialization), but also stores a hash of the cell value so that
/// changes can be detected even when the transient cell data has been evicted from memory.
/// Only valid with `cell = "compare"` (or the default).
Hash,
Auto, Auto,
Custom, Custom,
} }
...@@ -62,11 +66,12 @@ impl TryFrom<LitStr> for SerializationMode { ...@@ -62,11 +66,12 @@ impl TryFrom<LitStr> for SerializationMode {
fn try_from(lit: LitStr) -> Result<Self, Self::Error> { fn try_from(lit: LitStr) -> Result<Self, Self::Error> {
match lit.value().as_str() { match lit.value().as_str() {
"none" => Ok(SerializationMode::None), "none" => Ok(SerializationMode::None),
"hash" => Ok(SerializationMode::Hash),
"auto" => Ok(SerializationMode::Auto), "auto" => Ok(SerializationMode::Auto),
"custom" => Ok(SerializationMode::Custom), "custom" => Ok(SerializationMode::Custom),
_ => Err(Error::new_spanned( _ => Err(Error::new_spanned(
&lit, &lit,
"expected \"none\", \"auto\", or \"custom\"", "expected \"none\", \"hash\", \"auto\", or \"custom\"",
)), )),
} }
} }
...@@ -77,6 +82,7 @@ struct ValueArguments { ...@@ -77,6 +82,7 @@ struct ValueArguments {
shared: bool, shared: bool,
cell_mode: CellMode, cell_mode: CellMode,
manual_eq: bool, manual_eq: bool,
manual_hash: bool,
transparent: bool, transparent: bool,
/// Should we `#[derive(turbo_tasks::OperationValue)]`? /// Should we `#[derive(turbo_tasks::OperationValue)]`?
operation: Option<Span>, operation: Option<Span>,
...@@ -89,6 +95,7 @@ impl Parse for ValueArguments { ...@@ -89,6 +95,7 @@ impl Parse for ValueArguments {
shared: false, shared: false,
cell_mode: CellMode::Compare, cell_mode: CellMode::Compare,
manual_eq: false, manual_eq: false,
manual_hash: false,
transparent: false, transparent: false,
operation: None, operation: None,
}; };
...@@ -145,6 +152,22 @@ impl Parse for ValueArguments { ...@@ -145,6 +152,22 @@ impl Parse for ValueArguments {
return Err(Error::new_spanned(&str, "expected \"manual\"")); return Err(Error::new_spanned(&str, "expected \"manual\""));
}; };
} }
(
"hash",
Meta::NameValue(MetaNameValue {
value:
Expr::Lit(ExprLit {
lit: Lit::Str(str), ..
}),
..
}),
) => {
result.manual_hash = if str.value() == "manual" {
true
} else {
return Err(Error::new_spanned(&str, "expected \"manual\""));
};
}
("transparent", Meta::Path(_)) => { ("transparent", Meta::Path(_)) => {
result.transparent = true; result.transparent = true;
} }
...@@ -156,7 +179,7 @@ impl Parse for ValueArguments { ...@@ -156,7 +179,7 @@ impl Parse for ValueArguments {
&meta, &meta,
format!( format!(
"unexpected {meta:?}, expected \"shared\", \"into\", \ "unexpected {meta:?}, expected \"shared\", \"into\", \
\"serialization\", \"cell\", \"eq\", \"transparent\", or \ \"serialization\", \"cell\", \"eq\", \"hash\", \"transparent\", or \
\"operation\"" \"operation\""
), ),
)); ));
...@@ -175,10 +198,33 @@ pub fn value(args: TokenStream, input: TokenStream) -> TokenStream { ...@@ -175,10 +198,33 @@ pub fn value(args: TokenStream, input: TokenStream) -> TokenStream {
shared, shared,
cell_mode, cell_mode,
manual_eq, manual_eq,
manual_hash,
transparent, transparent,
operation, operation,
} = parse_macro_input!(args as ValueArguments); } = parse_macro_input!(args as ValueArguments);
// `serialization = "hash"` only makes sense with `cell = "compare"` (the default).
if matches!(serialization_mode, SerializationMode::Hash)
&& !matches!(cell_mode, CellMode::Compare)
{
return syn::Error::new(
proc_macro2::Span::call_site(),
"serialization = \"hash\" only makes sense with cell = \"compare\" (or default)",
)
.to_compile_error()
.into();
}
// `hash = "manual"` only makes sense with `serialization = "hash"`.
if manual_hash && !matches!(serialization_mode, SerializationMode::Hash) {
return syn::Error::new(
proc_macro2::Span::call_site(),
"hash = \"manual\" only makes sense with serialization = \"hash\"",
)
.to_compile_error()
.into();
}
let mut struct_attributes = vec![quote! { let mut struct_attributes = vec![quote! {
#[derive( #[derive(
turbo_tasks::ShrinkToFit, turbo_tasks::ShrinkToFit,
...@@ -277,6 +323,9 @@ pub fn value(args: TokenStream, input: TokenStream) -> TokenStream { ...@@ -277,6 +323,9 @@ pub fn value(args: TokenStream, input: TokenStream) -> TokenStream {
CellMode::New => quote! { CellMode::New => quote! {
turbo_tasks::VcCellNewMode<#ident> turbo_tasks::VcCellNewMode<#ident>
}, },
CellMode::Compare if matches!(serialization_mode, SerializationMode::Hash) => quote! {
turbo_tasks::VcCellHashedCompareMode<#ident>
},
CellMode::Compare => quote! { CellMode::Compare => quote! {
turbo_tasks::VcCellCompareMode<#ident> turbo_tasks::VcCellCompareMode<#ident>
}, },
...@@ -314,7 +363,7 @@ pub fn value(args: TokenStream, input: TokenStream) -> TokenStream { ...@@ -314,7 +363,7 @@ pub fn value(args: TokenStream, input: TokenStream) -> TokenStream {
#[bincode(crate = "turbo_tasks::macro_helpers::bincode")] #[bincode(crate = "turbo_tasks::macro_helpers::bincode")]
}); });
} }
SerializationMode::None | SerializationMode::Custom => {} SerializationMode::None | SerializationMode::Hash | SerializationMode::Custom => {}
}; };
if inner_type.is_some() { if inner_type.is_some() {
// Transparent structs have their own manual `ValueDebug` implementation. // Transparent structs have their own manual `ValueDebug` implementation.
...@@ -334,6 +383,11 @@ pub fn value(args: TokenStream, input: TokenStream) -> TokenStream { ...@@ -334,6 +383,11 @@ pub fn value(args: TokenStream, input: TokenStream) -> TokenStream {
#[derive(PartialEq, Eq)] #[derive(PartialEq, Eq)]
}); });
} }
if matches!(serialization_mode, SerializationMode::Hash) && !manual_hash {
struct_attributes.push(quote! {
#[derive(turbo_tasks::DeterministicHash)]
});
}
if let Some(span) = operation { if let Some(span) = operation {
struct_attributes.push(quote_spanned! { struct_attributes.push(quote_spanned! {
span => span =>
...@@ -343,7 +397,7 @@ pub fn value(args: TokenStream, input: TokenStream) -> TokenStream { ...@@ -343,7 +397,7 @@ pub fn value(args: TokenStream, input: TokenStream) -> TokenStream {
let name = global_name_for_type(ident); let name = global_name_for_type(ident);
let new_value_type = match serialization_mode { let new_value_type = match serialization_mode {
SerializationMode::None => quote! { SerializationMode::None | SerializationMode::Hash => quote! {
turbo_tasks::ValueType::new::<#ident>(#name) turbo_tasks::ValueType::new::<#ident>(#name)
}, },
SerializationMode::Auto | SerializationMode::Custom => { SerializationMode::Auto | SerializationMode::Custom => {
...@@ -353,7 +407,7 @@ pub fn value(args: TokenStream, input: TokenStream) -> TokenStream { ...@@ -353,7 +407,7 @@ pub fn value(args: TokenStream, input: TokenStream) -> TokenStream {
} }
}; };
let has_serialization = match serialization_mode { let has_serialization = match serialization_mode {
SerializationMode::None => quote! { false }, SerializationMode::None | SerializationMode::Hash => quote! { false },
SerializationMode::Auto | SerializationMode::Custom => quote! { true }, SerializationMode::Auto | SerializationMode::Custom => quote! { true },
}; };
......
...@@ -279,6 +279,7 @@ impl TurboTasksApi for VcStorage { ...@@ -279,6 +279,7 @@ impl TurboTasksApi for VcStorage {
_is_serializable_cell_content: bool, _is_serializable_cell_content: bool,
content: CellContent, content: CellContent,
_updated_key_hashes: Option<SmallVec<[u64; 2]>>, _updated_key_hashes: Option<SmallVec<[u64; 2]>>,
_content_hash: Option<[u8; 16]>,
_verification_mode: VerificationMode, _verification_mode: VerificationMode,
) { ) {
let mut map = self.cells.lock().unwrap(); let mut map = self.cells.lock().unwrap();
......
...@@ -288,6 +288,13 @@ impl TryFrom<CellContent> for SharedReference { ...@@ -288,6 +288,13 @@ impl TryFrom<CellContent> for SharedReference {
pub type TaskCollectiblesMap = AutoMap<RawVc, i32, BuildHasherDefault<FxHasher>, 1>; pub type TaskCollectiblesMap = AutoMap<RawVc, i32, BuildHasherDefault<FxHasher>, 1>;
/// A 128-bit content hash stored as little-endian bytes.
///
/// Using a byte array rather than `u128` keeps the alignment at 1 byte, which avoids padding
/// in structures such as `AutoMap`/`LazyField` enums that would otherwise grow to accommodate
/// `u128`'s 16-byte alignment requirement.
pub type CellHash = [u8; 16];
// Structurally and functionally similar to Cow<&'static, str> but explicitly notes the importance // Structurally and functionally similar to Cow<&'static, str> but explicitly notes the importance
// of non-static strings potentially containing PII (Personal Identifiable Information). // of non-static strings potentially containing PII (Personal Identifiable Information).
#[derive(Debug, Clone, Encode, Decode, PartialEq, Eq)] #[derive(Debug, Clone, Encode, Decode, PartialEq, Eq)]
...@@ -591,6 +598,7 @@ pub trait Backend: Sync + Send { ...@@ -591,6 +598,7 @@ pub trait Backend: Sync + Send {
is_serializable_cell_content: bool, is_serializable_cell_content: bool,
content: CellContent, content: CellContent,
updated_key_hashes: Option<SmallVec<[u64; 2]>>, updated_key_hashes: Option<SmallVec<[u64; 2]>>,
content_hash: Option<CellHash>,
verification_mode: VerificationMode, verification_mode: VerificationMode,
turbo_tasks: &dyn TurboTasksBackendApi<Self>, turbo_tasks: &dyn TurboTasksBackendApi<Self>,
); );
......
...@@ -69,7 +69,7 @@ pub use anyhow::{Error, Result}; ...@@ -69,7 +69,7 @@ pub use anyhow::{Error, Result};
use auto_hash_map::AutoSet; use auto_hash_map::AutoSet;
use rustc_hash::FxHasher; use rustc_hash::FxHasher;
pub use shrink_to_fit::ShrinkToFit; pub use shrink_to_fit::ShrinkToFit;
pub use turbo_tasks_macros::{turbobail, turbofmt}; pub use turbo_tasks_macros::{DeterministicHash, turbobail, turbofmt};
pub use crate::{ pub use crate::{
capture_future::TurboTasksPanic, capture_future::TurboTasksPanic,
...@@ -112,9 +112,9 @@ pub use crate::{ ...@@ -112,9 +112,9 @@ pub use crate::{
vc::{ vc::{
Dynamic, NonLocalValue, OperationValue, OperationVc, OptionVcExt, ReadVcFuture, Dynamic, NonLocalValue, OperationValue, OperationVc, OptionVcExt, ReadVcFuture,
ResolveOperationVcFuture, ResolveVcFuture, ResolvedVc, ToResolvedVcFuture, Upcast, ResolveOperationVcFuture, ResolveVcFuture, ResolvedVc, ToResolvedVcFuture, Upcast,
UpcastStrict, ValueDefault, Vc, VcCast, VcCellCompareMode, VcCellKeyedCompareMode, UpcastStrict, ValueDefault, Vc, VcCast, VcCellCompareMode, VcCellHashedCompareMode,
VcCellNewMode, VcDefaultRead, VcRead, VcTransparentRead, VcValueTrait, VcValueTraitCast, VcCellKeyedCompareMode, VcCellNewMode, VcDefaultRead, VcRead, VcTransparentRead,
VcValueType, VcValueTypeCast, VcValueTrait, VcValueTraitCast, VcValueType, VcValueTypeCast,
}, },
}; };
...@@ -189,6 +189,7 @@ pub use turbo_tasks_macros::function; ...@@ -189,6 +189,7 @@ pub use turbo_tasks_macros::function;
/// - **`"new"`:** Always overrides the value in the cell, invalidating all dependent tasks. /// - **`"new"`:** Always overrides the value in the cell, invalidating all dependent tasks.
/// - **`"compare"` *(default)*:** Compares with the existing value in the cell, before overriding it. /// - **`"compare"` *(default)*:** Compares with the existing value in the cell, before overriding it.
/// Requires the value to implement [`Eq`]. /// Requires the value to implement [`Eq`].
/// - **`"keyed"`:** Like `"compare"`, but uses per-key invalidation for transparent map types.
/// ///
/// Avoiding unnecessary invalidation is important to reduce downstream recomputation of tasks that /// Avoiding unnecessary invalidation is important to reduce downstream recomputation of tasks that
/// depend on this cell's value. /// depend on this cell's value.
...@@ -212,8 +213,21 @@ pub use turbo_tasks_macros::function; ...@@ -212,8 +213,21 @@ pub use turbo_tasks_macros::function;
/// - **`"auto"` *(default)*:** Derives the bincode traits and enables serialization. /// - **`"auto"` *(default)*:** Derives the bincode traits and enables serialization.
/// - **`"custom"`:** Prevents deriving the bincode traits, but still enables serialization /// - **`"custom"`:** Prevents deriving the bincode traits, but still enables serialization
/// (you must manually implement [`bincode::Encode`] and [`bincode::Decode`]). /// (you must manually implement [`bincode::Encode`] and [`bincode::Decode`]).
/// - **`"hash"`:** Like `"none"` (no bincode serialization), but instead stores a hash of the cell
/// value so that changes can be detected even when the transient cell data has been evicted
/// from memory or was never stored in the cache—avoiding unnecessary downstream invalidation.
/// Only valid with `cell = "compare"`.
/// Requires the value to implement both [`Eq`] and [`DeterministicHash`][turbo_tasks_hash::DeterministicHash].
/// - **`"none"`:** Disables serialization and prevents deriving the traits. /// - **`"none"`:** Disables serialization and prevents deriving the traits.
/// ///
/// ## `hash = "..."`
///
/// By default, when using `serialization = "hash"`, we `#[derive(DeterministicHash)]`. This argument allows
/// overriding that default implementation behavior.
///
/// - **`"manual"`:** Prevents deriving [`DeterministicHash`][turbo_tasks_hash::DeterministicHash] so you can do it manually.
/// Only valid with `serialization = "hash"`.
///
/// ## `shared` /// ## `shared`
/// ///
/// This flag makes the macro-generated `.cell()` method public so everyone can use it. /// This flag makes the macro-generated `.cell()` method public so everyone can use it.
......
...@@ -22,13 +22,14 @@ use serde::{Deserialize, Serialize}; ...@@ -22,13 +22,14 @@ use serde::{Deserialize, Serialize};
use smallvec::SmallVec; use smallvec::SmallVec;
use tokio::{select, sync::mpsc::Receiver, task_local}; use tokio::{select, sync::mpsc::Receiver, task_local};
use tracing::{Instrument, Span, instrument}; use tracing::{Instrument, Span, instrument};
use turbo_tasks_hash::{DeterministicHash, hash_xxh3_hash128};
use crate::{ use crate::{
Completion, InvalidationReason, InvalidationReasonSet, OutputContent, ReadCellOptions, Completion, InvalidationReason, InvalidationReasonSet, OutputContent, ReadCellOptions,
ReadOutputOptions, ResolvedVc, SharedReference, TaskId, TraitMethod, ValueTypeId, Vc, VcRead, ReadOutputOptions, ResolvedVc, SharedReference, TaskId, TraitMethod, ValueTypeId, Vc, VcRead,
VcValueTrait, VcValueType, VcValueTrait, VcValueType,
backend::{ backend::{
Backend, CachedTaskType, CellContent, TaskCollectiblesMap, TaskExecutionSpec, Backend, CachedTaskType, CellContent, CellHash, TaskCollectiblesMap, TaskExecutionSpec,
TransientTaskType, TurboTasksExecutionError, TypedCellContent, VerificationMode, TransientTaskType, TurboTasksExecutionError, TypedCellContent, VerificationMode,
}, },
capture_future::CaptureFuture, capture_future::CaptureFuture,
...@@ -174,6 +175,7 @@ pub trait TurboTasksApi: TurboTasksCallApi + Sync + Send { ...@@ -174,6 +175,7 @@ pub trait TurboTasksApi: TurboTasksCallApi + Sync + Send {
is_serializable_cell_content: bool, is_serializable_cell_content: bool,
content: CellContent, content: CellContent,
updated_key_hashes: Option<SmallVec<[u64; 2]>>, updated_key_hashes: Option<SmallVec<[u64; 2]>>,
content_hash: Option<CellHash>,
verification_mode: VerificationMode, verification_mode: VerificationMode,
); );
fn mark_own_task_as_finished(&self, task: TaskId); fn mark_own_task_as_finished(&self, task: TaskId);
...@@ -1572,6 +1574,7 @@ impl<B: Backend + 'static> TurboTasksApi for TurboTasks<B> { ...@@ -1572,6 +1574,7 @@ impl<B: Backend + 'static> TurboTasksApi for TurboTasks<B> {
is_serializable_cell_content: bool, is_serializable_cell_content: bool,
content: CellContent, content: CellContent,
updated_key_hashes: Option<SmallVec<[u64; 2]>>, updated_key_hashes: Option<SmallVec<[u64; 2]>>,
content_hash: Option<CellHash>,
verification_mode: VerificationMode, verification_mode: VerificationMode,
) { ) {
self.backend.update_task_cell( self.backend.update_task_cell(
...@@ -1580,6 +1583,7 @@ impl<B: Backend + 'static> TurboTasksApi for TurboTasks<B> { ...@@ -1580,6 +1583,7 @@ impl<B: Backend + 'static> TurboTasksApi for TurboTasks<B> {
is_serializable_cell_content, is_serializable_cell_content,
content, content,
updated_key_hashes, updated_key_hashes,
content_hash,
verification_mode, verification_mode,
self, self,
); );
...@@ -2047,16 +2051,17 @@ impl CurrentCellRef { ...@@ -2047,16 +2051,17 @@ impl CurrentCellRef {
/// Updates the cell if the given `functor` returns a value. /// Updates the cell if the given `functor` returns a value.
fn conditional_update<T>( fn conditional_update<T>(
&self, &self,
functor: impl FnOnce(Option<&T>) -> Option<(T, Option<SmallVec<[u64; 2]>>)>, functor: impl FnOnce(Option<&T>) -> Option<(T, Option<SmallVec<[u64; 2]>>, Option<CellHash>)>,
) where ) where
T: VcValueType, T: VcValueType,
{ {
self.conditional_update_with_shared_reference(|old_shared_reference| { self.conditional_update_with_shared_reference(|old_shared_reference| {
let old_ref = old_shared_reference.and_then(|sr| sr.0.downcast_ref::<T>()); let old_ref = old_shared_reference.and_then(|sr| sr.0.downcast_ref::<T>());
let (new_value, updated_key_hashes) = functor(old_ref)?; let (new_value, updated_key_hashes, content_hash) = functor(old_ref)?;
Some(( Some((
SharedReference::new(triomphe::Arc::new(new_value)), SharedReference::new(triomphe::Arc::new(new_value)),
updated_key_hashes, updated_key_hashes,
content_hash,
)) ))
}) })
} }
...@@ -2066,7 +2071,11 @@ impl CurrentCellRef { ...@@ -2066,7 +2071,11 @@ impl CurrentCellRef {
&self, &self,
functor: impl FnOnce( functor: impl FnOnce(
Option<&SharedReference>, Option<&SharedReference>,
) -> Option<(SharedReference, Option<SmallVec<[u64; 2]>>)>, ) -> Option<(
SharedReference,
Option<SmallVec<[u64; 2]>>,
Option<CellHash>,
)>,
) { ) {
let tt = turbo_tasks(); let tt = turbo_tasks();
let cell_content = tt let cell_content = tt
...@@ -2082,13 +2091,14 @@ impl CurrentCellRef { ...@@ -2082,13 +2091,14 @@ impl CurrentCellRef {
) )
.ok(); .ok();
let update = functor(cell_content.as_ref().and_then(|cc| cc.1.0.as_ref())); let update = functor(cell_content.as_ref().and_then(|cc| cc.1.0.as_ref()));
if let Some((update, updated_key_hashes)) = update { if let Some((update, updated_key_hashes, content_hash)) = update {
tt.update_own_task_cell( tt.update_own_task_cell(
self.current_task, self.current_task,
self.index, self.index,
self.is_serializable_cell_content, self.is_serializable_cell_content,
CellContent(Some(update)), CellContent(Some(update)),
updated_key_hashes, updated_key_hashes,
content_hash,
VerificationMode::EqualityCheck, VerificationMode::EqualityCheck,
) )
} }
...@@ -2137,7 +2147,7 @@ impl CurrentCellRef { ...@@ -2137,7 +2147,7 @@ impl CurrentCellRef {
{ {
return None; return None;
} }
Some((new_value, None)) Some((new_value, None, None))
}); });
} }
...@@ -2160,7 +2170,54 @@ impl CurrentCellRef { ...@@ -2160,7 +2170,54 @@ impl CurrentCellRef {
return None; return None;
} }
} }
Some((new_shared_reference, None)) Some((new_shared_reference, None, None))
});
}
/// Replace the current cell's content if the new value is different.
///
/// Like [`Self::compare_and_update`], but also computes and stores a hash of the value.
/// When the cell's transient data is evicted, the stored hash enables the backend to detect
/// whether the value actually changed without re-comparing values—avoiding unnecessary
/// downstream invalidation.
///
/// Requires `T: DeterministicHash` in addition to `T: PartialEq`.
pub fn hashed_compare_and_update<T>(&self, new_value: T)
where
T: PartialEq + DeterministicHash + VcValueType,
{
self.conditional_update(|old_value| {
if let Some(old_value) = old_value
&& old_value == &new_value
{
return None;
}
let content_hash = hash_xxh3_hash128(&new_value);
Some((new_value, None, Some(content_hash)))
});
}
/// Replace the current cell's content if the new value (from a pre-existing
/// [`SharedReference`]) is different.
///
/// Like [`Self::compare_and_update_with_shared_reference`], but also passes a hash
/// for hash-based change detection when transient data has been evicted.
pub fn hashed_compare_and_update_with_shared_reference<T>(
&self,
new_shared_reference: SharedReference,
) where
T: VcValueType + PartialEq + DeterministicHash,
{
self.conditional_update_with_shared_reference(move |old_sr| {
if let Some(old_sr) = old_sr {
let old_value = extract_sr_value::<T>(old_sr);
let new_value = extract_sr_value::<T>(&new_shared_reference);
if old_value == new_value {
return None;
}
}
let content_hash = hash_xxh3_hash128(extract_sr_value::<T>(&new_shared_reference));
Some((new_shared_reference, None, Some(content_hash)))
}); });
} }
...@@ -2173,7 +2230,7 @@ impl CurrentCellRef { ...@@ -2173,7 +2230,7 @@ impl CurrentCellRef {
{ {
self.conditional_update(|old_value| { self.conditional_update(|old_value| {
let Some(old_value) = old_value else { let Some(old_value) = old_value else {
return Some((new_value, None)); return Some((new_value, None, None));
}; };
let old_value = <T as VcValueType>::Read::value_to_target_ref(old_value); let old_value = <T as VcValueType>::Read::value_to_target_ref(old_value);
let new_value_ref = <T as VcValueType>::Read::value_to_target_ref(&new_value); let new_value_ref = <T as VcValueType>::Read::value_to_target_ref(&new_value);
...@@ -2186,7 +2243,7 @@ impl CurrentCellRef { ...@@ -2186,7 +2243,7 @@ impl CurrentCellRef {
.into_iter() .into_iter()
.map(|key| FxBuildHasher.hash_one(key)) .map(|key| FxBuildHasher.hash_one(key))
.collect(); .collect();
Some((new_value, Some(updated_key_hashes))) Some((new_value, Some(updated_key_hashes), None))
}); });
} }
...@@ -2202,7 +2259,7 @@ impl CurrentCellRef { ...@@ -2202,7 +2259,7 @@ impl CurrentCellRef {
{ {
self.conditional_update_with_shared_reference(|old_sr| { self.conditional_update_with_shared_reference(|old_sr| {
let Some(old_sr) = old_sr else { let Some(old_sr) = old_sr else {
return Some((new_shared_reference, None)); return Some((new_shared_reference, None, None));
}; };
let old_value = extract_sr_value::<T>(old_sr); let old_value = extract_sr_value::<T>(old_sr);
let old_value = <T as VcValueType>::Read::value_to_target_ref(old_value); let old_value = <T as VcValueType>::Read::value_to_target_ref(old_value);
...@@ -2217,7 +2274,7 @@ impl CurrentCellRef { ...@@ -2217,7 +2274,7 @@ impl CurrentCellRef {
.into_iter() .into_iter()
.map(|key| FxBuildHasher.hash_one(key)) .map(|key| FxBuildHasher.hash_one(key))
.collect(); .collect();
Some((new_shared_reference, Some(updated_key_hashes))) Some((new_shared_reference, Some(updated_key_hashes), None))
}); });
} }
...@@ -2233,6 +2290,7 @@ impl CurrentCellRef { ...@@ -2233,6 +2290,7 @@ impl CurrentCellRef {
self.is_serializable_cell_content, self.is_serializable_cell_content,
CellContent(Some(SharedReference::new(triomphe::Arc::new(new_value)))), CellContent(Some(SharedReference::new(triomphe::Arc::new(new_value)))),
None, None,
None,
verification_mode, verification_mode,
) )
} }
...@@ -2279,6 +2337,7 @@ impl CurrentCellRef { ...@@ -2279,6 +2337,7 @@ impl CurrentCellRef {
self.is_serializable_cell_content, self.is_serializable_cell_content,
CellContent(Some(shared_ref)), CellContent(Some(shared_ref)),
None, None,
None,
verification_mode, verification_mode,
) )
} }
......
use std::{any::type_name, marker::PhantomData}; use std::{any::type_name, marker::PhantomData};
use turbo_tasks_hash::DeterministicHash;
use super::{read::VcRead, traits::VcValueType}; use super::{read::VcRead, traits::VcValueType};
use crate::{ use crate::{
RawVc, Vc, backend::VerificationMode, keyed::KeyedEq, manager::find_cell_by_type, RawVc, Vc, backend::VerificationMode, keyed::KeyedEq, manager::find_cell_by_type,
...@@ -120,3 +122,31 @@ fn debug_assert_type<T: VcValueType>(content: &TypedSharedReference) { ...@@ -120,3 +122,31 @@ fn debug_assert_type<T: VcValueType>(content: &TypedSharedReference) {
type_name::<T>(), type_name::<T>(),
); );
} }
/// Mode that compares the cell's content with the new value and only updates
/// if the new value is different, using both PartialEq (when old content is available)
/// and a stored hash (when old content has been evicted from memory) for comparison.
pub struct VcCellHashedCompareMode<T> {
_phantom: PhantomData<T>,
}
impl<T> VcCellMode<T> for VcCellHashedCompareMode<T>
where
T: VcValueType + PartialEq + DeterministicHash,
{
fn cell(inner: VcReadTarget<T>) -> Vc<T> {
let cell = find_cell_by_type::<T>();
cell.hashed_compare_and_update(<T::Read as VcRead<T>>::target_to_value(inner));
Vc {
node: cell.into(),
_t: PhantomData,
}
}
fn raw_cell(content: TypedSharedReference) -> RawVc {
debug_assert_type::<T>(&content);
let cell = find_cell_by_type::<T>();
cell.hashed_compare_and_update_with_shared_reference::<T>(content.reference);
cell.into()
}
}
...@@ -25,7 +25,10 @@ use shrink_to_fit::ShrinkToFit; ...@@ -25,7 +25,10 @@ use shrink_to_fit::ShrinkToFit;
pub use self::{ pub use self::{
cast::{VcCast, VcValueTraitCast, VcValueTypeCast}, cast::{VcCast, VcValueTraitCast, VcValueTypeCast},
cell_mode::{VcCellCompareMode, VcCellKeyedCompareMode, VcCellMode, VcCellNewMode}, cell_mode::{
VcCellCompareMode, VcCellHashedCompareMode, VcCellKeyedCompareMode, VcCellMode,
VcCellNewMode,
},
default::ValueDefault, default::ValueDefault,
local::NonLocalValue, local::NonLocalValue,
operation::{OperationValue, OperationVc, ResolveOperationVcFuture}, operation::{OperationValue, OperationVc, ResolveOperationVcFuture},
......
...@@ -2,9 +2,11 @@ use std::{ ...@@ -2,9 +2,11 @@ use std::{
cmp::min, cmp::min,
io::{BufRead, Result as IoResult, Write}, io::{BufRead, Result as IoResult, Write},
ops, ops,
sync::Arc,
}; };
use anyhow::Result; use anyhow::Result;
use bincode::{Decode, Encode};
use tracing::instrument; use tracing::instrument;
use turbo_rcstr::RcStr; use turbo_rcstr::RcStr;
use turbo_tasks::{ResolvedVc, Vc}; use turbo_tasks::{ResolvedVc, Vc};
...@@ -25,14 +27,27 @@ use crate::{ ...@@ -25,14 +27,27 @@ use crate::{
pub type Mapping = (usize, Option<Rope>); pub type Mapping = (usize, Option<Rope>);
/// Code stores combined output code and the source map of that output code. /// Code stores combined output code and the source map of that output code.
#[turbo_tasks::value(shared)] #[turbo_tasks::value(shared, serialization = "hash")]
#[derive(Debug, Clone)] #[derive(Debug, Clone, Encode, Decode)]
pub struct Code { pub struct Code {
code: Rope, code: Rope,
mappings: Vec<Mapping>, mappings: Arc<Vec<Mapping>>,
should_generate_debug_id: bool, should_generate_debug_id: bool,
} }
#[turbo_tasks::value(transparent)]
#[derive(Debug, Clone)]
pub struct PersistedCode(Code);
#[turbo_tasks::value_impl]
impl PersistedCode {
#[turbo_tasks::function]
async fn to_code(self: Vc<Self>) -> Result<Vc<Code>> {
// PersistedCode is transparent over Code; owned() yields Code directly.
Ok(self.owned().await?.cell())
}
}
impl Code { impl Code {
pub fn source_code(&self) -> &Rope { pub fn source_code(&self) -> &Rope {
&self.code &self.code
...@@ -52,6 +67,12 @@ impl Code { ...@@ -52,6 +67,12 @@ impl Code {
self.code self.code
} }
/// Stores this `Code` as a [`PersistedCode`] (fully serialized) and returns a `Vc<Code>`
/// backed by the persisted version, avoiding an intermediate hash-mode `Code` cell.
pub fn cell_persisted(self) -> Vc<Code> {
PersistedCode::to_code(PersistedCode(self).cell())
}
// Formats the code with the source map and debug id comments as // Formats the code with the source map and debug id comments as
pub async fn to_rope_with_magic_comments( pub async fn to_rope_with_magic_comments(
self: Vc<Self>, self: Vc<Self>,
...@@ -210,7 +231,7 @@ impl CodeBuilder { ...@@ -210,7 +231,7 @@ impl CodeBuilder {
pub fn build(self) -> Code { pub fn build(self) -> Code {
Code { Code {
code: self.code.build(), code: self.code.build(),
mappings: self.mappings.unwrap_or_default(), mappings: Arc::new(self.mappings.unwrap_or_default()),
should_generate_debug_id: self.should_generate_debug_id, should_generate_debug_id: self.should_generate_debug_id,
} }
} }
...@@ -302,7 +323,7 @@ impl Code { ...@@ -302,7 +323,7 @@ impl Code {
let mut sections = Vec::with_capacity(self.mappings.len()); let mut sections = Vec::with_capacity(self.mappings.len());
let mut read = self.code.read(); let mut read = self.code.read();
for (byte_pos, map) in &self.mappings { for (byte_pos, map) in self.mappings.iter() {
let mut want = byte_pos - last_byte_pos; let mut want = byte_pos - last_byte_pos;
while want > 0 { while want > 0 {
// `fill_buf` never returns an error. // `fill_buf` never returns an error.
......
...@@ -327,7 +327,7 @@ async fn module_factory_with_code_generation_issue( ...@@ -327,7 +327,7 @@ async fn module_factory_with_code_generation_issue(
code += "(() => {{\n\n"; code += "(() => {{\n\n";
writeln!(code, "throw new Error({error});", error = &js_error_message)?; writeln!(code, "throw new Error({error});", error = &js_error_message)?;
code += "\n}})"; code += "\n}})";
code.build().cell() code.build().cell_persisted()
} }
}) })
} }
......
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