Unverified Commit 0090db22 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

turbo-tasks: add hashed cell mode for hash-based change detection without cell data (#91576)

## Summary

### Core: hash-based cell change detection

- Adds `cell_data_hash: AutoMap<CellId, [u8; 16]>` to the storage schema
(`category = "data"`) so the backend can persist a hash of transient
cell data across evictions
- Stored as `[u8; 16]` (little-endian bytes of a u128) rather than
`u128` to keep the 1-byte alignment out of `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
- Adds `content_hash: Option<u128>` to `UpdateCellOperation::run` and
threads it through the full call chain: `CurrentCellRef` →
`TurboTasksCallApi::update_own_task_cell` → `Backend::update_task_cell`
→ operation
- **New invalidation logic** in `UpdateCellOperation::run` for the
`assume_unchanged = false` path:
  - Old content available → real equality compare (unchanged)
- Old content evicted, hashes match → write new content but **skip
dependent invalidation**
- Old content evicted, hashes differ (or missing) → write + invalidate
as before
- `cell_data_hash` is updated whenever content is written (skipped if
hash is unchanged; always updated for non-serializable cells regardless
of `assume_unchanged`)
- Adds `hashed_compare_and_update` /
`hashed_compare_and_update_with_shared_reference` methods to
`CurrentCellRef` (require `T: PartialEq + DeterministicHash`); hash is
computed lazily (only after equality check fails when old value is
available)
- Adds `VcCellHashedCompareMode<T>` in `cell_mode.rs` which implements
`VcCellMode<T>` for `T: VcValueType + PartialEq + DeterministicHash`

### Macro: `serialization = "hash"` and `hash = "manual"`

- **`serialization = "hash"`** — behaves like `serialization = "none"`
(no disk serialization, transient) but uses `VcCellHashedCompareMode` so
the stored hash prevents spurious downstream invalidation when transient
data is evicted and re-executed
- Valid only with `cell = "compare"` (the default); combining with `cell
= "new"` or `cell = "keyed"` is a compile error
  - Automatically derives `DeterministicHash` on the annotated type
- **`hash = "manual"`** — opt-out of the auto-derive when a custom
`DeterministicHash` impl is needed (analogous to `eq = "manual"`); using
`hash = "manual"` without `serialization = "hash"` is a compile error

### turbo-tasks-fs: `PersistedFileContent`

- Adds `PersistedFileContent` — a mirror of `FileContent` that is
returned by `Vc<FileContent>::persist()`, storing the same data but
obtained through the persistent cache path
- `FileContent` is switched to `serialization = "hash"` so the macro
auto-derives `DeterministicHash`
- `DiskFileSystem::write()` now calls `.persist().await?` before
emitting the write effect, using `PersistedFileContent` for the file
comparison and write — this ensures full content is in the persistent
cache on restore, avoiding spurious downstream invalidation
- `WriteContent::File` in `invalidator_map.rs` is updated to hold
`ReadRef<PersistedFileContent>`

### turbopack-core: `Code` with hash-based serialization

- Adds `DeterministicHash` impls for `SmallVec<[T; N]>` and `()` in
`turbo-tasks-hash`
- Switches `Code` to `serialization = "hash"` so module factory code
cells use hash-based change detection
- Calls `.persist()` on module factory code cells in
`turbopack-ecmascript`

### next-core: duplicate asset detection and parallel emit

- `emit_assets` now emits node and client assets concurrently via
`try_join!`
- Detects duplicate assets (same output path, different content) and
returns a hard error with a diff summary — previously the last writer
silently won

## Macro syntax

```rust
#[turbo_tasks::value(serialization = "hash")]
struct MyTransientType { ... }

// opt out of auto-derived DeterministicHash when you need a custom impl:
#[turbo_tasks::value(serialization = "hash", hash = "manual")]
struct MyTransientType { ... }
```

## Test plan

- [x] Integration tests in
`turbopack/crates/turbo-tasks-backend/tests/hashed_cell_mode.rs`:
- `test_hashed_cell_mode_change_triggers_invalidation` — value change
triggers consumer re-execution
- `test_hashed_cell_mode_equal_value_no_invalidation` — same hash
prevents consumer re-execution
- [x] `cargo test -p turbo-tasks-macros-tests` passes
- [x] `cargo test -p turbo-tasks-backend --test hashed_cell_mode` passes
- [x] `cargo check --workspace` passes

---------
Co-authored-by: 's avatarTobias Koppers <sokra@users.noreply.github.com>
Co-authored-by: 's avatarClaude <noreply@anthropic.com>
Co-authored-by: 's avatarVercel <vercel[bot]@users.noreply.github.com>
parent 548fbca6
......@@ -9725,6 +9725,7 @@ dependencies = [
"bincode 2.0.1",
"data-encoding",
"sha2",
"smallvec",
"turbo-tasks-macros",
"xxhash-rust",
]
......
use anyhow::Result;
use tracing::Instrument;
use turbo_tasks::{TryFlatJoinIterExt, Vc};
use turbo_tasks_fs::{FileSystemPath, rebase};
use anyhow::{Ok, Result, bail};
use futures::try_join;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{
FxIndexMap, ResolvedVc, TryFlatJoinIterExt, TryJoinIterExt, ValueToStringRef, Vc,
};
use turbo_tasks_fs::{FileContent, FileSystemPath, rebase};
use turbopack_core::{
asset::Asset,
asset::{Asset, AssetContent},
output::{ExpandedOutputAssets, OutputAsset, OutputAssets},
reference::all_assets_from_entries,
};
......@@ -43,40 +46,90 @@ pub async fn emit_assets(
client_relative_path: FileSystemPath,
client_output_path: FileSystemPath,
) -> Result<()> {
let _: Vec<()> = assets
enum Location {
Node,
Client,
}
let assets = assets
.await?
.iter()
.copied()
.map(|asset| {
let node_root = node_root.clone();
let client_relative_path = client_relative_path.clone();
let client_output_path = client_output_path.clone();
async move {
let path = asset.path().owned().await?;
let span = tracing::info_span!("emit asset", name = %path.value_to_string().await?);
async move {
Ok(if path.is_inside_ref(&node_root) {
Some(emit(*asset).as_side_effect().await?)
} else if path.is_inside_ref(&client_relative_path) {
// Client assets are emitted to the client output path, which is prefixed
// with _next. We need to rebase them to remove that
// prefix.
Some(
emit_rebase(*asset, client_relative_path, client_output_path)
.as_side_effect()
.await?,
)
} else {
None
})
}
.instrument(span)
.await
}
.map(async |asset| {
let path = asset.path().owned().await?;
let location = if path.is_inside_ref(&node_root) {
Location::Node
} else if path.is_inside_ref(&client_relative_path) {
Location::Client
} else {
return Ok(None);
};
Ok(Some((location, path, asset)))
})
.try_flat_join()
.await?;
let mut node_assets_by_path = FxIndexMap::default();
let mut client_assets_by_path = FxIndexMap::default();
for (location, path, asset) in assets {
match location {
Location::Node => {
node_assets_by_path
.entry(path)
.or_insert_with(Vec::new)
.push(asset);
}
Location::Client => {
client_assets_by_path
.entry(path)
.or_insert_with(Vec::new)
.push(asset);
}
}
}
async fn check_duplicates(
path: &FileSystemPath,
assets: Vec<ResolvedVc<Box<dyn OutputAsset>>>,
) -> Result<ResolvedVc<Box<dyn OutputAsset>>> {
let mut iter = assets.into_iter();
let first = iter.next().unwrap();
for next in iter {
if let Some(diff) = assets_diff(*next, *first).owned().await? {
bail!(
"Duplicate asset with different content: {}\n{}",
path.to_string_ref().await?,
diff
);
}
}
Ok(first)
}
try_join!(
node_assets_by_path
.into_iter()
.map(async |(path, assets)| {
let asset = check_duplicates(&path, assets).await?;
emit(*asset).as_side_effect().await
})
.try_join(),
client_assets_by_path
.into_iter()
.map(async |(path, assets)| {
let asset = check_duplicates(&path, assets).await?;
// Client assets are emitted to the client output path, which is prefixed
// with _next. We need to rebase them to remove that
// prefix.
emit_rebase(
*asset,
client_relative_path.clone(),
client_output_path.clone(),
)
.as_side_effect()
.await
})
.try_join(),
)?;
Ok(())
}
......@@ -110,3 +163,52 @@ async fn emit_rebase(
.await?;
Ok(())
}
#[turbo_tasks::function]
async fn assets_diff(
assets1: Vc<Box<dyn OutputAsset>>,
assets2: Vc<Box<dyn OutputAsset>>,
) -> Result<Vc<Option<RcStr>>> {
let content1 = assets1.content().await?;
let content2 = assets2.content().await?;
match (&*content1, &*content2) {
(AssetContent::File(content1), AssetContent::File(content2)) => {
let content1 = content1.await?;
let content2 = content2.await?;
match (&*content1, &*content2) {
(FileContent::NotFound, FileContent::NotFound) => Ok(Vc::cell(None)),
(FileContent::Content(content1), FileContent::Content(content2)) => {
if content1 == content2 {
Ok(Vc::cell(None))
} else {
// TODO: Produce an actual diff, e.g. write both versions to
// scratch space under `.next/` and run a text diff on them.
Ok(Vc::cell(Some(rcstr!("file content differs"))))
}
}
_ => Ok(Vc::cell(Some(rcstr!("file content type differs")))),
}
}
(
AssetContent::Redirect {
target: target1,
link_type: link_type1,
},
AssetContent::Redirect {
target: target2,
link_type: link_type2,
},
) => {
if target1 == target2 && link_type1 == link_type2 {
Ok(Vc::cell(None))
} else {
Ok(Vc::cell(Some(
format!("redirect differs: {} vs {}", target1, target2).into(),
)))
}
}
_ => Ok(Vc::cell(Some(rcstr!("asset content type differs")))),
}
}
......@@ -3047,6 +3047,7 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> {
is_serializable_cell_content: bool,
content: CellContent,
updated_key_hashes: Option<SmallVec<[u64; 2]>>,
content_hash: Option<[u8; 16]>,
verification_mode: VerificationMode,
turbo_tasks: &dyn TurboTasksBackendApi<TurboTasksBackend<B>>,
) {
......@@ -3056,6 +3057,7 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> {
content,
is_serializable_cell_content,
updated_key_hashes,
content_hash,
verification_mode,
self.execute_context(turbo_tasks),
);
......@@ -3609,6 +3611,7 @@ impl<B: BackingStorage> Backend for TurboTasksBackend<B> {
is_serializable_cell_content: bool,
content: CellContent,
updated_key_hashes: Option<SmallVec<[u64; 2]>>,
content_hash: Option<[u8; 16]>,
verification_mode: VerificationMode,
turbo_tasks: &dyn TurboTasksBackendApi<Self>,
) {
......@@ -3618,6 +3621,7 @@ impl<B: BackingStorage> Backend for TurboTasksBackend<B> {
is_serializable_cell_content,
content,
updated_key_hashes,
content_hash,
verification_mode,
turbo_tasks,
);
......
......@@ -56,10 +56,17 @@ impl UpdateCellOperation {
content: CellContent,
is_serializable_cell_content: bool,
updated_key_hashes: Option<SmallVec<[u64; 2]>>,
content_hash: Option<[u8; 16]>,
#[cfg(feature = "verify_determinism")] verification_mode: VerificationMode,
#[cfg(not(feature = "verify_determinism"))] _verification_mode: VerificationMode,
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 {
Some(new_content.into_typed(cell.type_id))
} else {
......@@ -107,27 +114,46 @@ impl UpdateCellOperation {
// When not recomputing, we need to notify dependent tasks if the content actually
// 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")]
let has_updated_key_hashes = updated_key_hashes.is_some();
let updated_key_hashes_set = updated_key_hashes.map(|updated_key_hashes| {
Lazy::new(|| updated_key_hashes.into_iter().collect::<FxHashSet<u64>>())
});
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))
});
// Collect dependent tasks only when not skipping invalidation.
// The iterator borrows from `task`, so it must be scoped to drop before
// we mutably borrow `task` again in the fast path.
let mut dependent_tasks: FxIndexMap<TaskId, SmallVec<[Option<u64>; 2]>> =
FxIndexMap::default();
for (task, key) in tasks_with_keys {
dependent_tasks.entry(task).or_default().push(key);
if !skip_invalidation {
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() {
......@@ -146,6 +172,18 @@ impl UpdateCellOperation {
let old_content = task.remove_cell_data(is_serializable_cell_content, cell);
// Update cell_data_hash before dropping the task lock
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);
}
}
}
drop(task);
drop(old_content);
......@@ -181,6 +219,18 @@ impl UpdateCellOperation {
task.remove_cell_data(is_serializable_cell_content, cell)
};
// Update cell_data_hash for non-serializable cells when not recomputing.
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);
}
}
}
let in_progress_cell = task.remove_in_progress_cells(&cell);
drop(task);
......
......@@ -275,6 +275,16 @@ struct TaskStorageSchema {
#[field(storage = "auto_map", category = "transient", shrink_on_completion)]
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, [u8; 16]>,
/// Maximum cell index per cell type.
#[field(storage = "auto_map", category = "data", shrink_on_completion)]
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 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!();
/// 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 = rand::random::<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 = rand::random::<u32>();
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;
use rustc_hash::FxHashMap;
use turbo_tasks::{Invalidator, ReadRef};
use crate::{FileContent, LinkContent};
use crate::{LinkContent, PersistedFileContent};
#[derive(PartialEq, Eq)]
pub enum WriteContent {
File(ReadRef<FileContent>),
File(ReadRef<PersistedFileContent>),
Link(ReadRef<LinkContent>),
}
......
......@@ -971,7 +971,12 @@ impl FileSystem for DiskFileSystem {
}
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 invalidator = turbo_tasks::get_invalidator();
......@@ -981,7 +986,7 @@ impl FileSystem for DiskFileSystem {
full_path: PathBuf,
inner: Arc<DiskFileSystemInner>,
invalidator: Option<Invalidator>,
content: ReadRef<FileContent>,
content: ReadRef<PersistedFileContent>,
}
impl Effect for WriteEffect {
......@@ -1030,7 +1035,7 @@ impl FileSystem for DiskFileSystem {
}
match &*self.content {
FileContent::Content(..) => {
PersistedFileContent::Content(..) => {
let create_directory = compare == FileComparison::Create;
if create_directory && let Some(parent) = full_path.parent() {
self.inner.create_directory(parent).await.with_context(|| {
......@@ -1044,7 +1049,7 @@ impl FileSystem for DiskFileSystem {
let content = self.content.clone();
retry_blocking(|| {
let mut f = std::fs::File::create(&full_path)?;
let FileContent::Content(file) = &*content else {
let PersistedFileContent::Content(file) = &*content else {
unreachable!()
};
std::io::copy(&mut file.read(), &mut f)?;
......@@ -1079,7 +1084,7 @@ impl FileSystem for DiskFileSystem {
.await
.with_context(|| format!("failed to write to {full_path:?}"))?;
}
FileContent::NotFound => {
PersistedFileContent::NotFound => {
retry_blocking(|| std::fs::remove_file(&full_path))
.instrument(tracing::info_span!("remove file", name = ?full_path))
.concurrency_limited(&self.inner.write_semaphore)
......@@ -1971,8 +1976,8 @@ impl From<std::fs::Permissions> for Permissions {
}
}
#[turbo_tasks::value(shared)]
#[derive(Clone, Debug, DeterministicHash, PartialOrd, Ord)]
#[turbo_tasks::value(shared, serialization = "hash")]
#[derive(Clone, Debug, PartialOrd, Ord)]
pub enum FileContent {
Content(File),
NotFound,
......@@ -1984,35 +1989,39 @@ impl From<File> for FileContent {
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
enum FileComparison {
Create,
Equal,
NotEqual,
/// A persisted version of [`FileContent`] that stores the full file content in the task cache.
///
/// [`FileContent`] uses `serialization = "hash"`, so only a hash is kept in the persistent cache.
/// When reading the file content back from the cache, the hash is compared to detect changes, but
/// 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 {
/// Performs a comparison of self's data against a disk file's streamed
/// read.
impl PersistedFileContent {
/// Performs a comparison of self's data against a disk file's streamed read.
async fn streaming_compare(&self, path: &Path) -> Result<FileComparison> {
let old_file =
extract_disk_access(retry_blocking(|| std::fs::File::open(path)).await, path)?;
let Some(old_file) = old_file else {
return Ok(match self {
FileContent::NotFound => FileComparison::Equal,
PersistedFileContent::NotFound => FileComparison::Equal,
_ => FileComparison::Create,
});
};
// 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);
};
let old_meta = extract_disk_access(retry_blocking(|| old_file.metadata()).await, path)?;
let Some(old_meta) = old_meta else {
// 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
// existed.
// handle open. In which case, we just pretend the file never existed.
return Ok(FileComparison::Create);
};
// If the meta is different, we need to rewrite the file to update it.
......@@ -2049,6 +2058,13 @@ impl FileContent {
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
enum FileComparison {
Create,
Equal,
NotEqual,
}
bitflags! {
#[derive(
Default,
......@@ -2416,6 +2432,18 @@ impl FileContent {
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 nothing
/// else. If there is no file content, it returns `None`.
#[turbo_tasks::function]
......
......@@ -15,6 +15,7 @@ workspace = true
[dependencies]
bincode = { workspace = true }
data-encoding = { workspace = true }
smallvec = { workspace = true }
sha2 = { workspace = true }
turbo-tasks-macros = { workspace = true }
xxhash-rust = { workspace = true }
use std::mem::Discriminant;
use smallvec::SmallVec;
pub use turbo_tasks_macros::DeterministicHash;
macro_rules! deterministic_hash_number {
......@@ -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 {
( $( $name:ident )+ ) => {
impl<$($name: DeterministicHash),+> DeterministicHash for ($($name,)+)
......
......@@ -5,10 +5,10 @@ use xxhash_rust::xxh3::Xxh3Default;
use crate::{DeterministicHash, DeterministicHasher};
/// 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();
input.deterministic_hash(&mut hasher);
hasher.finish()
hasher.finish_bytes()
}
/// Xxh3Hash128 hasher.
......@@ -32,7 +32,12 @@ impl Xxh3Hash128Hasher {
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_ne_bytes()
}
/// Finish the hash computation and return the digest as u128.
pub fn finish(&self) -> u128 {
self.0.digest128()
}
......
......@@ -45,6 +45,10 @@ impl TryFrom<LitStr> for CellMode {
enum SerializationMode {
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,
Custom,
}
......@@ -62,11 +66,12 @@ impl TryFrom<LitStr> for SerializationMode {
fn try_from(lit: LitStr) -> Result<Self, Self::Error> {
match lit.value().as_str() {
"none" => Ok(SerializationMode::None),
"hash" => Ok(SerializationMode::Hash),
"auto" => Ok(SerializationMode::Auto),
"custom" => Ok(SerializationMode::Custom),
_ => Err(Error::new_spanned(
&lit,
"expected \"none\", \"auto\", or \"custom\"",
"expected \"none\", \"hash\", \"auto\", or \"custom\"",
)),
}
}
......@@ -77,6 +82,7 @@ struct ValueArguments {
shared: bool,
cell_mode: CellMode,
manual_eq: bool,
manual_hash: bool,
transparent: bool,
/// Should we `#[derive(turbo_tasks::OperationValue)]`?
operation: Option<Span>,
......@@ -89,6 +95,7 @@ impl Parse for ValueArguments {
shared: false,
cell_mode: CellMode::Compare,
manual_eq: false,
manual_hash: false,
transparent: false,
operation: None,
};
......@@ -145,6 +152,22 @@ impl Parse for ValueArguments {
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(_)) => {
result.transparent = true;
}
......@@ -156,7 +179,7 @@ impl Parse for ValueArguments {
&meta,
format!(
"unexpected {meta:?}, expected \"shared\", \"into\", \
\"serialization\", \"cell\", \"eq\", \"transparent\", or \
\"serialization\", \"cell\", \"eq\", \"hash\", \"transparent\", or \
\"operation\""
),
));
......@@ -175,10 +198,33 @@ pub fn value(args: TokenStream, input: TokenStream) -> TokenStream {
shared,
cell_mode,
manual_eq,
manual_hash,
transparent,
operation,
} = 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! {
#[derive(
turbo_tasks::ShrinkToFit,
......@@ -277,6 +323,9 @@ pub fn value(args: TokenStream, input: TokenStream) -> TokenStream {
CellMode::New => quote! {
turbo_tasks::VcCellNewMode<#ident>
},
CellMode::Compare if matches!(serialization_mode, SerializationMode::Hash) => quote! {
turbo_tasks::VcCellHashedCompareMode<#ident>
},
CellMode::Compare => quote! {
turbo_tasks::VcCellCompareMode<#ident>
},
......@@ -314,7 +363,7 @@ pub fn value(args: TokenStream, input: TokenStream) -> TokenStream {
#[bincode(crate = "turbo_tasks::macro_helpers::bincode")]
});
}
SerializationMode::None | SerializationMode::Custom => {}
SerializationMode::None | SerializationMode::Hash | SerializationMode::Custom => {}
};
if inner_type.is_some() {
// Transparent structs have their own manual `ValueDebug` implementation.
......@@ -334,6 +383,11 @@ pub fn value(args: TokenStream, input: TokenStream) -> TokenStream {
#[derive(PartialEq, Eq)]
});
}
if matches!(serialization_mode, SerializationMode::Hash) && !manual_hash {
struct_attributes.push(quote! {
#[derive(turbo_tasks::DeterministicHash)]
});
}
if let Some(span) = operation {
struct_attributes.push(quote_spanned! {
span =>
......@@ -343,7 +397,7 @@ pub fn value(args: TokenStream, input: TokenStream) -> TokenStream {
let name = global_name_for_type(ident);
let new_value_type = match serialization_mode {
SerializationMode::None => quote! {
SerializationMode::None | SerializationMode::Hash => quote! {
turbo_tasks::ValueType::new::<#ident>(#name)
},
SerializationMode::Auto | SerializationMode::Custom => {
......@@ -353,7 +407,7 @@ pub fn value(args: TokenStream, input: TokenStream) -> TokenStream {
}
};
let has_serialization = match serialization_mode {
SerializationMode::None => quote! { false },
SerializationMode::None | SerializationMode::Hash => quote! { false },
SerializationMode::Auto | SerializationMode::Custom => quote! { true },
};
......
......@@ -279,6 +279,7 @@ impl TurboTasksApi for VcStorage {
_is_serializable_cell_content: bool,
content: CellContent,
_updated_key_hashes: Option<SmallVec<[u64; 2]>>,
_content_hash: Option<[u8; 16]>,
_verification_mode: VerificationMode,
) {
let mut map = self.cells.lock().unwrap();
......
......@@ -591,6 +591,7 @@ pub trait Backend: Sync + Send {
is_serializable_cell_content: bool,
content: CellContent,
updated_key_hashes: Option<SmallVec<[u64; 2]>>,
content_hash: Option<[u8; 16]>,
verification_mode: VerificationMode,
turbo_tasks: &dyn TurboTasksBackendApi<Self>,
);
......
......@@ -71,7 +71,7 @@ pub use anyhow::{Error, Result};
use auto_hash_map::AutoSet;
use rustc_hash::FxHasher;
pub use shrink_to_fit::ShrinkToFit;
pub use turbo_tasks_macros::{turbobail, turbofmt};
pub use turbo_tasks_macros::{DeterministicHash, turbobail, turbofmt};
pub use crate::{
capture_future::TurboTasksPanic,
......@@ -115,9 +115,9 @@ pub use crate::{
value_type::{TraitMethod, TraitType, ValueType},
vc::{
Dynamic, NonLocalValue, OperationValue, OperationVc, OptionVcExt, ReadVcFuture, ResolvedVc,
Upcast, UpcastStrict, ValueDefault, Vc, VcCast, VcCellCompareMode, VcCellKeyedCompareMode,
VcCellNewMode, VcDefaultRead, VcRead, VcTransparentRead, VcValueTrait, VcValueTraitCast,
VcValueType, VcValueTypeCast,
Upcast, UpcastStrict, ValueDefault, Vc, VcCast, VcCellCompareMode, VcCellHashedCompareMode,
VcCellKeyedCompareMode, VcCellNewMode, VcDefaultRead, VcRead, VcTransparentRead,
VcValueTrait, VcValueTraitCast, VcValueType, VcValueTypeCast,
},
};
......@@ -192,6 +192,7 @@ pub use turbo_tasks_macros::function;
/// - **`"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.
/// 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
/// depend on this cell's value.
......@@ -215,8 +216,21 @@ pub use turbo_tasks_macros::function;
/// - **`"auto"` *(default)*:** Derives the bincode traits and enables serialization.
/// - **`"custom"`:** Prevents deriving the bincode traits, but still enables serialization
/// (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.
///
/// ## `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`
///
/// This flag makes the macro-generated `.cell()` method public so everyone can use it.
......
......@@ -22,6 +22,7 @@ use serde::{Deserialize, Serialize};
use smallvec::SmallVec;
use tokio::{select, sync::mpsc::Receiver, task_local};
use tracing::{Instrument, Span, instrument};
use turbo_tasks_hash::{DeterministicHash, hash_xxh3_hash128};
use crate::{
Completion, InvalidationReason, InvalidationReasonSet, OutputContent, ReadCellOptions,
......@@ -174,6 +175,7 @@ pub trait TurboTasksApi: TurboTasksCallApi + Sync + Send {
is_serializable_cell_content: bool,
content: CellContent,
updated_key_hashes: Option<SmallVec<[u64; 2]>>,
content_hash: Option<[u8; 16]>,
verification_mode: VerificationMode,
);
fn mark_own_task_as_finished(&self, task: TaskId);
......@@ -1570,6 +1572,7 @@ impl<B: Backend + 'static> TurboTasksApi for TurboTasks<B> {
is_serializable_cell_content: bool,
content: CellContent,
updated_key_hashes: Option<SmallVec<[u64; 2]>>,
content_hash: Option<[u8; 16]>,
verification_mode: VerificationMode,
) {
self.backend.update_task_cell(
......@@ -1578,6 +1581,7 @@ impl<B: Backend + 'static> TurboTasksApi for TurboTasks<B> {
is_serializable_cell_content,
content,
updated_key_hashes,
content_hash,
verification_mode,
self,
);
......@@ -2029,16 +2033,17 @@ impl CurrentCellRef {
/// Updates the cell if the given `functor` returns a value.
fn conditional_update<T>(
&self,
functor: impl FnOnce(Option<&T>) -> Option<(T, Option<SmallVec<[u64; 2]>>)>,
functor: impl FnOnce(Option<&T>) -> Option<(T, Option<SmallVec<[u64; 2]>>, Option<[u8; 16]>)>,
) where
T: VcValueType,
{
self.conditional_update_with_shared_reference(|old_shared_reference| {
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((
SharedReference::new(triomphe::Arc::new(new_value)),
updated_key_hashes,
content_hash,
))
})
}
......@@ -2048,7 +2053,11 @@ impl CurrentCellRef {
&self,
functor: impl FnOnce(
Option<&SharedReference>,
) -> Option<(SharedReference, Option<SmallVec<[u64; 2]>>)>,
) -> Option<(
SharedReference,
Option<SmallVec<[u64; 2]>>,
Option<[u8; 16]>,
)>,
) {
let tt = turbo_tasks();
let cell_content = tt
......@@ -2064,13 +2073,14 @@ impl CurrentCellRef {
)
.ok();
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(
self.current_task,
self.index,
self.is_serializable_cell_content,
CellContent(Some(update)),
updated_key_hashes,
content_hash,
VerificationMode::EqualityCheck,
)
}
......@@ -2119,7 +2129,7 @@ impl CurrentCellRef {
{
return None;
}
Some((new_value, None))
Some((new_value, None, None))
});
}
......@@ -2142,7 +2152,54 @@ impl CurrentCellRef {
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)))
});
}
......@@ -2155,7 +2212,7 @@ impl CurrentCellRef {
{
self.conditional_update(|old_value| {
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 new_value_ref = <T as VcValueType>::Read::value_to_target_ref(&new_value);
......@@ -2168,7 +2225,7 @@ impl CurrentCellRef {
.into_iter()
.map(|key| FxBuildHasher.hash_one(key))
.collect();
Some((new_value, Some(updated_key_hashes)))
Some((new_value, Some(updated_key_hashes), None))
});
}
......@@ -2184,7 +2241,7 @@ impl CurrentCellRef {
{
self.conditional_update_with_shared_reference(|old_sr| {
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 = <T as VcValueType>::Read::value_to_target_ref(old_value);
......@@ -2199,7 +2256,7 @@ impl CurrentCellRef {
.into_iter()
.map(|key| FxBuildHasher.hash_one(key))
.collect();
Some((new_shared_reference, Some(updated_key_hashes)))
Some((new_shared_reference, Some(updated_key_hashes), None))
});
}
......@@ -2215,6 +2272,7 @@ impl CurrentCellRef {
self.is_serializable_cell_content,
CellContent(Some(SharedReference::new(triomphe::Arc::new(new_value)))),
None,
None,
verification_mode,
)
}
......@@ -2261,6 +2319,7 @@ impl CurrentCellRef {
self.is_serializable_cell_content,
CellContent(Some(shared_ref)),
None,
None,
verification_mode,
)
}
......
use std::{any::type_name, marker::PhantomData};
use turbo_tasks_hash::DeterministicHash;
use super::{read::VcRead, traits::VcValueType};
use crate::{
RawVc, Vc, backend::VerificationMode, keyed::KeyedEq, manager::find_cell_by_type,
......@@ -120,3 +122,31 @@ fn debug_assert_type<T: VcValueType>(content: &TypedSharedReference) {
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()
}
}
......@@ -23,7 +23,10 @@ use shrink_to_fit::ShrinkToFit;
pub use self::{
cast::{VcCast, VcValueTraitCast, VcValueTypeCast},
cell_mode::{VcCellCompareMode, VcCellKeyedCompareMode, VcCellMode, VcCellNewMode},
cell_mode::{
VcCellCompareMode, VcCellHashedCompareMode, VcCellKeyedCompareMode, VcCellMode,
VcCellNewMode,
},
default::ValueDefault,
local::NonLocalValue,
operation::{OperationValue, OperationVc},
......
......@@ -5,6 +5,7 @@ use std::{
};
use anyhow::Result;
use bincode::{Decode, Encode};
use tracing::instrument;
use turbo_rcstr::RcStr;
use turbo_tasks::{ResolvedVc, Vc};
......@@ -25,14 +26,18 @@ use crate::{
pub type Mapping = (usize, Option<Rope>);
/// Code stores combined output code and the source map of that output code.
#[turbo_tasks::value(shared)]
#[derive(Debug, Clone)]
#[turbo_tasks::value(shared, serialization = "hash")]
#[derive(Debug, Clone, Encode, Decode)]
pub struct Code {
code: Rope,
mappings: Vec<Mapping>,
should_generate_debug_id: bool,
}
#[turbo_tasks::value(transparent)]
#[derive(Debug, Clone)]
pub struct PersistedCode(Code);
impl Code {
pub fn source_code(&self) -> &Rope {
&self.code
......@@ -285,6 +290,16 @@ impl Code {
None
})
}
#[turbo_tasks::function]
pub async fn persisted(self: Vc<Self>) -> Result<Vc<Code>> {
Ok(self.persisted_internal().owned().await?.cell())
}
#[turbo_tasks::function]
fn persisted_internal(&self) -> Vc<PersistedCode> {
Vc::cell(self.clone())
}
}
impl Code {
......
......@@ -298,7 +298,7 @@ async fn module_factory_with_code_generation_issue(
code += "(() => {{\n\n";
writeln!(code, "throw new Error({error});", error = &js_error_message)?;
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