Unverified Commit b6920088 authored by vercel-fleet-prod[bot]'s avatar vercel-fleet-prod[bot] Committed by GitHub

Skip equal mutable cell updates

Co-authored-by: 's avatarLuke Sandberg <210140+lukesandberg@users.noreply.github.com>
parent 6cee07d9
......@@ -508,6 +508,14 @@ impl TurboTasksBackend {
ctx.task(task, TaskDataCategory::All).get_dirty().is_some()
}
/// Inspect payload persistence dirtying without restoring or executing a task.
#[doc(hidden)]
pub fn is_data_modified_for_testing(&self, task: TaskId) -> bool {
self.storage
.with_task(task, |t| t.flags.data_modified())
.expect("test task must be resident")
}
/// Observe reservation wait registrations without entering snapshot admission.
/// The count resets on release; callers must keep the writer held while inspecting.
#[doc(hidden)]
......@@ -3962,7 +3970,7 @@ impl Backend for TurboTasksBackend {
cell: CellId,
update: &mut dyn FnMut(
turbo_tasks::SharedReference,
) -> Result<turbo_tasks::SharedReference>,
) -> Result<Option<turbo_tasks::SharedReference>>,
tt: &TurboTasks<Self>,
) -> Result<()> {
self.mutate_mutable_cell_impl(task, cell, update, tt)
......
......@@ -173,7 +173,7 @@ impl TurboTasksBackend {
&self,
id: TaskId,
cell: CellId,
update: &mut dyn FnMut(SharedReference) -> Result<SharedReference>,
update: &mut dyn FnMut(SharedReference) -> Result<Option<SharedReference>>,
tt: &TurboTasks<Self>,
) -> Result<()> {
check_type(cell)?;
......@@ -189,7 +189,11 @@ impl TurboTasksBackend {
.cloned()
.ok_or_else(|| anyhow!("canonical mutable cell content is unavailable"))?;
drop(task);
let content = update(old)?;
let Some(content) = update(old)? else {
// Comparison ran under writer exclusion, but outside shard locks.
// An equal value is not a payload mutation or a dependency event.
return Ok(());
};
// The same owner reservation excludes initialization and completion, so
// slot retirement cannot occur between validation and publication.
let task = transaction.ctx.task(id, TaskDataCategory::All);
......
......@@ -118,7 +118,9 @@ async fn downstream(id: u32, state: MutableCell<Counter>, tracked: bool) -> Resu
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn tracked_untracked_and_immutable_snapshots() {
let (tt, _dir) = create_tt("mutable_snapshots");
let tt_test = tt.clone();
turbo_tasks::run_once(tt.clone(), async move {
let tt = tt_test;
let state = create_counter(0)
.read_strongly_consistent()
.await?
......@@ -154,28 +156,193 @@ async fn tracked_untracked_and_immutable_snapshots() {
);
assert_eq!(READER_RUNS[0].load(Ordering::SeqCst), expected_runs(2));
assert_eq!(READER_RUNS[1].load(Ordering::SeqCst), expected_runs(1));
tt.backend().snapshot_and_evict_for_testing(&tt);
let owner = create_counter(0).task_id();
let before_noop = state.get_untracked()?;
assert!(!tt.backend().is_data_modified_for_testing(owner));
state.set(Counter { value: 1 })?;
state.update(|_| {})?;
state.update(|value| {
value.value += 1;
value.value -= 1;
})?;
assert!(before_noop.ptr_eq(&state.get_untracked()?));
assert!(!tt.backend().is_data_modified_for_testing(owner));
assert_eq!(
*downstream(0, state, true)
.read_strongly_consistent()
.await?,
2
);
let equal_runs = READER_RUNS[0].load(Ordering::SeqCst);
assert!(
(expected_runs(2) + 1..=expected_runs(3)).contains(&equal_runs),
"equal-value commit must reexecute once (plus an optional verification rerun): \
{equal_runs}"
assert_eq!(
READER_RUNS[0].load(Ordering::SeqCst),
expected_runs(2),
"equal updates must neither replace storage nor invalidate readers"
);
assert_eq!(
OWNER_RUNS[0].load(Ordering::SeqCst),
expected_runs(1),
"external mutation does not rerun its owner"
);
state.update(|value| value.value += 1)?;
assert!(!before_noop.ptr_eq(&state.get_untracked()?));
assert!(tt.backend().is_data_modified_for_testing(owner));
assert_eq!(
*downstream(0, state, true)
.read_strongly_consistent()
.await?,
4
);
anyhow::Ok(())
})
.await
.unwrap();
tt.stop_and_wait().await;
}
#[turbo_tasks::value(cell = "mutable", operation, eq = "manual")]
#[derive(Clone)]
struct CustomEquality {
value: u32,
ignored: u32,
}
impl PartialEq for CustomEquality {
fn eq(&self, other: &Self) -> bool {
match other.ignored {
u32::MAX => panic!("deliberate equality panic"),
tag if tag == u32::MAX - 1 => {
let _ = Vc::<u32>::cell(1);
}
_ => {}
}
self.value == other.value
}
}
impl Drop for CustomEquality {
fn drop(&mut self) {
if self.ignored == u32::MAX - 2 {
// Rejected candidates must be dropped after the mutation callback.
// Calling the backend from their destructor is legal here.
let _ = Vc::<u32>::cell(1);
}
}
}
#[turbo_tasks::value]
struct CustomEqualityHandle {
cell: MutableCell<CustomEquality>,
}
#[turbo_tasks::function(operation, root)]
fn create_custom_equality() -> Vc<CustomEqualityHandle> {
CustomEqualityHandle {
cell: CustomEquality {
value: 0,
ignored: 0,
}
.mutable_cell(),
}
.cell()
}
static CUSTOM_EQUALITY_READS: AtomicU32 = AtomicU32::new(0);
#[turbo_tasks::function(operation, root)]
fn read_custom_equality(cell: MutableCell<CustomEquality>) -> Result<Vc<u32>> {
CUSTOM_EQUALITY_READS.fetch_add(1, Ordering::SeqCst);
Ok(Vc::cell(cell.get()?.value))
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn custom_equality_reentrancy_panic_and_candidate_drop_recovery() {
let (tt, _dir) = create_tt("mutable_custom_equality");
turbo_tasks::run_once(tt.clone(), async move {
let cell = create_custom_equality()
.read_strongly_consistent()
.await?
.cell;
let original = cell.get_untracked()?;
assert_eq!(
*read_custom_equality(cell)
.read_strongly_consistent()
.await?,
0
);
let reads = CUSTOM_EQUALITY_READS.load(Ordering::SeqCst);
cell.set(CustomEquality {
value: 0,
ignored: 1,
})?;
cell.update(|v| v.ignored = 2)?;
cell.set(CustomEquality {
value: 0,
ignored: u32::MAX - 2,
})?;
cell.update(|v| v.ignored = u32::MAX - 2)?;
assert!(original.ptr_eq(&cell.get_untracked()?));
assert_eq!(cell.get_untracked()?.ignored, 0);
assert_eq!(
*read_custom_equality(cell)
.read_strongly_consistent()
.await?,
0
);
assert_eq!(CUSTOM_EQUALITY_READS.load(Ordering::SeqCst), reads);
for tag in [u32::MAX, u32::MAX - 1] {
for update in [false, true] {
let panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
if update {
cell.update(|v| v.ignored = tag).unwrap();
} else {
cell.set(CustomEquality {
value: 0,
ignored: tag,
})
.unwrap();
}
}));
assert!(panic.is_err(), "equality panic/reentrancy must fail fast");
assert!(original.ptr_eq(&cell.get_untracked()?));
}
}
let panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
cell.update(|v| {
v.ignored = u32::MAX - 2;
panic!("candidate must drop after unwind releases reservation");
})
.unwrap();
}));
assert!(panic.is_err());
assert!(original.ptr_eq(&cell.get_untracked()?));
cell.set(CustomEquality {
value: 1,
ignored: 3,
})?;
assert_eq!(
*read_custom_equality(cell)
.read_strongly_consistent()
.await?,
1
);
assert!(CUSTOM_EQUALITY_READS.load(Ordering::SeqCst) > reads);
cell.update(|v| v.value += 1)?;
assert_eq!(
*read_custom_equality(cell)
.read_strongly_consistent()
.await?,
2
);
anyhow::Ok(())
})
.await
.unwrap();
assert!(
tt.backend()
.snapshot_and_evict_for_testing(&tt)
.had_new_data
);
tt.stop_and_wait().await;
}
......
#![feature(arbitrary_self_types)]
#![feature(arbitrary_self_types_pointers)]
#![allow(unexpected_cfgs)]
use turbo_tasks::MutableCell;
#[turbo_tasks::value(cell = "mutable", operation, eq = "manual")]
#[derive(Clone)]
struct NoEquality { value: u32 }
fn writes_require_equality(cell: MutableCell<NoEquality>) {
let _ = cell.set(NoEquality { value: 1 });
let _ = cell.update(|value| value.value += 1);
}
fn main() {}
error[E0277]: can't compare `NoEquality` with `NoEquality`
--> tests/value/fail_mutable_equality.rs:12:18
|
12 | let _ = cell.set(NoEquality { value: 1 });
| ^^^ ----------------------- `NoEquality` doesn't satisfy the trait bound
| |
| no implementation for `NoEquality == NoEquality`
|
= help: the trait `PartialEq` is not implemented for `NoEquality`
note: required by a bound in `MutableCell::<T>::set`
--> $WORKSPACE/turbopack/crates/turbo-tasks/src/mutable_cell.rs
|
| pub fn set(&self, value: T) -> Result<()>
| --- required by a bound in this associated function
| where
| T: PartialEq,
| ^^^^^^^^^ required by this bound in `MutableCell::<T>::set`
help: consider annotating `NoEquality` with `#[derive(PartialEq)]`
|
9 + #[derive(PartialEq)]
10 | struct NoEquality { value: u32 }
|
error[E0277]: can't compare `NoEquality` with `NoEquality`
--> tests/value/fail_mutable_equality.rs:13:18
|
13 | let _ = cell.update(|value| value.value += 1);
| ^^^^^^ no implementation for `NoEquality == NoEquality`
|
= help: the trait `PartialEq` is not implemented for `NoEquality`
note: required by a bound in `MutableCell::<T>::update`
--> $WORKSPACE/turbopack/crates/turbo-tasks/src/mutable_cell.rs
|
| pub fn update(&self, f: impl FnOnce(&mut T)) -> Result<()>
| ------ required by a bound in this associated function
| where
| T: PartialEq,
| ^^^^^^^^^ required by this bound in `MutableCell::<T>::update`
help: consider annotating `NoEquality` with `#[derive(PartialEq)]`
|
9 + #[derive(PartialEq)]
10 | struct NoEquality { value: u32 }
|
......@@ -20,4 +20,15 @@ fn check_api(value: MutableValue) -> anyhow::Result<()> {
state.update(|value| value.value += 1)?;
Ok(())
}
#[turbo_tasks::value(cell = "mutable", operation, eq = "manual")]
#[derive(Clone)]
struct NoEquality { value: u32 }
fn check_read_without_equality(value: NoEquality) -> anyhow::Result<()> {
let cell = value.mutable_cell();
let _: ReadRef<NoEquality> = cell.get()?;
let _: ReadRef<NoEquality> = cell.get_untracked()?;
Ok(())
}
fn main() { assert_handle::<MutableCell<MutableValue>>(); }
......@@ -49,9 +49,11 @@ for this mode. Existing values and `State<T>` users are unchanged.
- `get()` returns an immutable `ReadRef<T>` snapshot and tracks a normal cell dependency;
`get_untracked()` returns the same snapshot without an edge.
- `set(value)` replaces canonical backend content. `update(|value| ...)` serializes
writers, edits a private clone, and publishes only if the closure returns normally.
Every commit invalidates readers, even when the new value is equal.
- `set(value)` and `update(|value| ...)` require the payload's `PartialEq`, including
custom equality implementations. They serialize writers and publish only when
the final value differs. Equal results preserve canonical storage without reader
invalidation or payload persistence dirtying. `update` edits a private clone;
panicking callbacks leave canonical content unchanged.
- Construction is first-value-wins, including after eviction and persistence restore.
One persistent creator task owns the cell; transient/Once Tasks cannot own it.
Sharing handles never transfers ownership. Keep a
......@@ -61,9 +63,9 @@ for this mode. Existing values and `State<T>` users are unchanged.
handles through the creator after reopening a backend.
- Methods are synchronous and require a turbo-tasks context and a multi-threaded
Tokio runtime. The executing owner cannot call `set` or `update` on its own cell.
Update closures must be short, synchronous, and must not call turbo-tasks, nest
cell access, or spawn/wait for task work. Reentrant calls panic even in release
builds. Old read snapshots are unchanged after publication.
Cloning, custom equality, and update closures must be short and synchronous, and
must not call turbo-tasks, nest cell access, or spawn/wait for task work. Reentrant
calls panic even in release builds. Old read snapshots are unchanged after publication.
This is a bounded prototype, not a named state registry, schema-migration API,
mutable read guard, or multi-cell transaction facility.
......
......@@ -732,12 +732,13 @@ pub trait Backend: Sized + Sync + Send {
turbo_tasks: &TurboTasks<Self>,
) -> Result<SharedReference>;
/// Serialize clone/edit/publication as one backend operation. The callback runs once.
/// Serialize clone/edit/comparison/publication as one operation. The callback runs once;
/// `None` preserves existing content, dependencies, and payload persistence state.
fn mutate_mutable_cell(
&self,
task: TaskId,
cell: CellId,
update: &mut dyn FnMut(SharedReference) -> Result<SharedReference>,
update: &mut dyn FnMut(SharedReference) -> Result<Option<SharedReference>>,
turbo_tasks: &TurboTasks<Self>,
) -> Result<()>;
......
......@@ -213,7 +213,7 @@ pub trait TurboTasksApi: TurboTasksCallApi + Sync + Send {
&self,
task: TaskId,
cell: CellId,
update: &mut dyn FnMut(SharedReference) -> Result<SharedReference>,
update: &mut dyn FnMut(SharedReference) -> Result<Option<SharedReference>>,
) -> Result<()>;
fn read_own_task_cell(&self, task: TaskId, index: CellId) -> Result<TypedCellContent>;
......@@ -1986,7 +1986,7 @@ impl<B: Backend + 'static> TurboTasksApi for TurboTasks<B> {
&self,
task: TaskId,
cell: CellId,
update: &mut dyn FnMut(SharedReference) -> Result<SharedReference>,
update: &mut dyn FnMut(SharedReference) -> Result<Option<SharedReference>>,
) -> Result<()> {
crate::assert_not_in_mutable_update();
self.backend.mutate_mutable_cell(task, cell, update, self)
......
......@@ -28,7 +28,7 @@ pub fn assert_not_in_mutable_update() {
IN_UPDATE.with(|active| {
assert!(
!active.get(),
"turbo-tasks calls are forbidden inside MutableCell::update"
"turbo-tasks calls are forbidden inside MutableCell mutation callbacks"
)
});
}
......@@ -53,8 +53,8 @@ impl Drop for UpdateScope {
/// can construct these handles; transient/Once Tasks cannot own this prototype's state.
/// Initialization is first-value-wins, including after persistence restore. Identity
/// follows per-type construction order: use a fixed-layout creator. Reordering or
/// conditionally omitting allocations is not a state migration mechanism. Successful
/// omission retires a cell; reuse of a retired index is unsupported.
/// conditionally omitting allocations can change live cell identity across reruns.
/// Successful omission retires a cell; reuse of a retired index is unsupported.
///
/// Handles may be shared by multiple consumers, but never transfer cell ownership.
/// They do not pin their creator against GC. Keep the creator connected to an explicit
......@@ -64,8 +64,11 @@ impl Drop for UpdateScope {
///
/// All access is synchronous and requires a current turbo-tasks context and a
/// multi-threaded Tokio runtime. Reads return immutable snapshots; previously obtained
/// snapshots never refresh. Every committed write invalidates tracked readers,
/// including equal values. No equality comparison or physical interior mutation occurs.
/// snapshots never refresh. Writes compare using the payload's `PartialEq`, like
/// ordinary compare-mode cells. Equal results preserve canonical storage without
/// invalidating readers or marking payload data modified. Changed results publish
/// a new immutable allocation and invalidate tracked readers; no physical interior
/// mutation of read snapshots occurs.
#[derive(Serialize, Deserialize, Encode, Decode)]
#[bincode(bounds = "T: VcValueType")]
#[serde(bound = "")]
......@@ -131,37 +134,64 @@ impl<T: VcValueType + Clone + OperationValue> MutableCell<T> {
Ok(())
}
/// Replace the canonical value and invalidate readers. Writes by the currently
/// executing owner task are rejected; use the constructor for initialization.
pub fn set(&self, value: T) -> Result<()> {
/// Replace the canonical value and invalidate readers only if it is not equal.
/// Writes by the currently executing owner task are rejected; use the constructor
/// for initialization. Custom equality must obey the restrictions of `update`.
pub fn set(&self, value: T) -> Result<()>
where
T: PartialEq,
{
// Keep rejected candidates outside the callback so their destructors run
// after backend reservation/admission release, including on unwind.
let mut value = Some(value);
self.replace(&mut |_| {
Ok(SharedReference::new(triomphe::Arc::new(
self.replace(&mut |old| {
let _scope = UpdateScope::enter();
let old = old
.downcast_ref::<T>()
.ok_or_else(|| anyhow!("mutable cell type mismatch"))?;
if old == value.as_ref().expect("called once") {
return Ok(None);
}
Ok(Some(SharedReference::new(triomphe::Arc::new(
value.take().expect("called once"),
)))
))))
})
}
/// Serialize writers, clone the canonical value, edit it once, then publish.
/// Serialize writers, clone the canonical value, edit it once, then publish
/// only if the final value differs by `PartialEq`. Equal results are no-ops.
///
/// The closure must return promptly and must not call turbo-tasks, nest cell
/// access, perform async work, or spawn/wait for task work. Reentrant backend
/// calls panic in release builds too. A panicking closure discards its private
/// clone, leaves the published value unchanged, and releases its reservation.
pub fn update(&self, f: impl FnOnce(&mut T)) -> Result<()> {
/// The closure, cloning, and custom equality must return promptly and must not
/// call turbo-tasks, nest cell access, perform async work, or spawn/wait for task
/// work. Reentrant backend calls panic in release builds too. A panicking
/// callback discards its private candidate, leaves the published value unchanged,
/// and releases its reservation before the candidate is dropped.
pub fn update(&self, f: impl FnOnce(&mut T)) -> Result<()>
where
T: PartialEq,
{
let mut f = Some(f);
let mut value = None;
self.replace(&mut |old| {
let _scope = UpdateScope::enter();
let mut value = old
let old = old
.downcast_ref::<T>()
.ok_or_else(|| anyhow!("mutable cell type mismatch"))?
.clone();
f.take().expect("called once")(&mut value);
Ok(SharedReference::new(triomphe::Arc::new(value)))
.ok_or_else(|| anyhow!("mutable cell type mismatch"))?;
let candidate = value.insert(old.clone());
f.take().expect("called once")(candidate);
if old == candidate {
return Ok(None);
}
Ok(Some(SharedReference::new(triomphe::Arc::new(
value.take().expect("called once"),
))))
})
}
fn replace(&self, f: &mut dyn FnMut(SharedReference) -> Result<SharedReference>) -> Result<()> {
fn replace(
&self,
f: &mut dyn FnMut(SharedReference) -> Result<Option<SharedReference>>,
) -> Result<()> {
assert_not_in_mutable_update();
self.ensure_type()?;
let tt = try_turbo_tasks()
......
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