diff --git a/moli-renderer-v8/src/context_bootstrap/worker_host/dispatch.rs b/moli-renderer-v8/src/context_bootstrap/worker_host/dispatch.rs index 888ac55b5d8..c9445b1c8b3 100644 --- a/moli-renderer-v8/src/context_bootstrap/worker_host/dispatch.rs +++ b/moli-renderer-v8/src/context_bootstrap/worker_host/dispatch.rs @@ -229,6 +229,7 @@ pub(crate) fn dispatch_worker_error_event_with_kind<'s>( fn worker_error_microtask_checkpoint(scope: &mut v8::PinScope<'_, '_>) { // Blink observes cancellation after microtasks queued by error listeners. + let _checkpoint_scope = crate::script_cleanup::MicrotaskCheckpointScope::enter(scope); scope.perform_microtask_checkpoint(); crate::context_bootstrap::run_end_of_microtask_checkpoint_tasks(scope); } diff --git a/moli-renderer-v8/src/script_cleanup.rs b/moli-renderer-v8/src/script_cleanup.rs index e230114fac6..fdecd6888b0 100644 --- a/moli-renderer-v8/src/script_cleanup.rs +++ b/moli-renderer-v8/src/script_cleanup.rs @@ -39,7 +39,10 @@ struct MicrotaskCheckpointState(Rc>); /// HTML's performing-a-microtask-checkpoint flag also covers rejection /// notification and checkpoint-end cleanup after V8 finishes draining jobs. -pub(crate) struct MicrotaskCheckpointScope(Rc>); +pub(crate) struct MicrotaskCheckpointScope { + active: Rc>, + _timer_nesting: Option, +} impl MicrotaskCheckpointScope { pub(crate) fn enter(scope: &mut v8::PinScope<'_, '_>) -> Option { @@ -61,13 +64,17 @@ impl MicrotaskCheckpointScope { if active.replace(true) { return None; } - Some(Self(active)) + Some(Self { + active, + _timer_nesting: + crate::timer_nesting::TimerNestingScope::suspend_for_microtask_checkpoint(scope), + }) } } impl Drop for MicrotaskCheckpointScope { fn drop(&mut self) { - self.0.set(false); + self.active.set(false); } } diff --git a/moli-renderer-v8/src/script_vm/tests/timer_nesting.rs b/moli-renderer-v8/src/script_vm/tests/timer_nesting.rs index 528533f8774..0770e1c2267 100644 --- a/moli-renderer-v8/src/script_vm/tests/timer_nesting.rs +++ b/moli-renderer-v8/src/script_vm/tests/timer_nesting.rs @@ -90,7 +90,7 @@ fn timer_nesting_clamps_string_chains_after_six_callbacks() { } #[test] -fn timer_nesting_survives_the_callback_microtask_checkpoint() { +fn timer_nesting_resets_inside_callback_microtask_checkpoint() { let mut vm = new_storage_test_vm("https://timer-nesting.test/"); vm.eval( "globalThis.fired = 0; function step() { ++fired; queueMicrotask(() => setTimeout(step, 0)); } setTimeout(step, 0)", @@ -99,7 +99,105 @@ fn timer_nesting_survives_the_callback_microtask_checkpoint() { run_first_six_callbacks(&mut vm); assert_eq!( vm.document_runtime.take_next_timeout_delay_for_test(), - Some(4) + Some(0) + ); +} + +#[test] +fn timer_microtask_timeout_keeps_requested_delay_after_a_nested_callback() { + for schedule in [ + "queueMicrotask", + "callback => Promise.resolve().then(callback)", + ] { + let mut vm = new_storage_test_vm("https://timer-microtask.test/"); + vm.eval(&format!( + r#" +globalThis.fired = 0; +const scheduleMicrotask = {schedule}; +function step() {{ + if (++fired < 6) {{ + setTimeout(step, 0); + return; + }} + setTimeout(() => {{}}, 1); + scheduleMicrotask(() => setTimeout(() => {{}}, 1)); +}} +setTimeout(step, 0); +"#, + )) + .unwrap(); + run_first_six_callbacks(&mut vm); + let mut delays = [ + vm.document_runtime.take_next_timeout_delay_for_test(), + vm.document_runtime.take_next_timeout_delay_for_test(), + ]; + delays.sort(); + assert_eq!(delays, [Some(1), Some(4)], "{schedule}"); + } +} + +#[test] +fn timer_microtask_timeout_does_not_reset_the_interval_rearm_level() { + let mut vm = new_storage_test_vm("https://timer-microtask-interval.test/"); + vm.eval( + r#" +globalThis.fired = 0; +setInterval(() => { + if (++fired === 6) queueMicrotask(() => setTimeout(() => {}, 1)); +}, 0); +"#, + ) + .unwrap(); + run_first_six_callbacks(&mut vm); + let mut delays = [ + vm.document_runtime.take_next_timeout_delay_for_test(), + vm.document_runtime.take_next_timeout_delay_for_test(), + ]; + delays.sort(); + assert_eq!(delays, [Some(1), Some(4)]); +} + +#[test] +fn timer_microtask_checkpoint_suspends_worker_level_and_restores_outer_task() { + use crate::timer_nesting::{TimerNestingLevel, TimerNestingOwner, TimerNestingScope}; + + crate::ensure_v8_for_test(); + let mut isolate = v8::Isolate::new(Default::default()); + let scope = std::pin::pin!(v8::HandleScope::new(&mut isolate)); + let scope = &mut scope.init(); + let context = v8::Context::new(scope, Default::default()); + let scope = &mut v8::ContextScope::new(scope, context); + let task = TimerNestingScope::enter(scope.as_mut()); + let owner = TimerNestingOwner::Worker; + let mut level = TimerNestingLevel::default(); + for _ in 0..6 { + level = level.next(); + } + level.activate(scope, owner); + assert_eq!( + TimerNestingLevel::for_new_timer(scope, owner).clamp_delay_ms(1), + 4 + ); + let checkpoint = crate::script_cleanup::MicrotaskCheckpointScope::enter(scope) + .expect("the agent checkpoint should start"); + assert_eq!( + TimerNestingLevel::for_new_timer(scope, owner).clamp_delay_ms(1), + 1 + ); + assert!(crate::script_cleanup::MicrotaskCheckpointScope::enter(scope).is_none()); + assert_eq!( + TimerNestingLevel::for_new_timer(scope, owner).clamp_delay_ms(1), + 1 + ); + drop(checkpoint); + assert_eq!( + TimerNestingLevel::for_new_timer(scope, owner).clamp_delay_ms(1), + 4 + ); + drop(task); + assert_eq!( + TimerNestingLevel::for_new_timer(scope, owner).clamp_delay_ms(1), + 1 ); } diff --git a/moli-renderer-v8/src/timer_nesting.rs b/moli-renderer-v8/src/timer_nesting.rs index f66f69f98a7..5d6cade353c 100644 --- a/moli-renderer-v8/src/timer_nesting.rs +++ b/moli-renderer-v8/src/timer_nesting.rs @@ -66,9 +66,9 @@ struct TimerNestingState { scope_depth: Cell, } -/// Keep an ExecutionContext's timer level through its callback checkpoint. -/// Consume this guard after the checkpoint, before asynchronous runtime -/// follow-up. Drop also restores it when a callback or checkpoint fails. +/// Preserve a timer task's level until its callback turn is finished. +/// Microtask checkpoints temporarily suspend this state because their jobs +/// are separate tasks. Drop also restores it on callback or checkpoint failure. pub(crate) struct TimerNestingScope { state: Rc, previous: TimerLevels, @@ -99,6 +99,24 @@ impl TimerNestingScope { } } + /// A microtask is the currently running task while its checkpoint drains. + /// Preserve the outer task's metadata for reentry and interval bookkeeping, + /// without letting newly scheduled timers inherit it from microtasks. + pub(crate) fn suspend_for_microtask_checkpoint(isolate: &v8::Isolate) -> Option { + let state = isolate.get_slot::>()?.clone(); + if state.levels.borrow().is_empty() { + return None; + } + let previous = std::mem::take(&mut *state.levels.borrow_mut()); + let previous_depth = state.scope_depth.get(); + state.scope_depth.set(previous_depth + 1); + Some(Self { + state, + previous, + previous_depth, + }) + } + /// Body-only execution has no checkpoint. Complete-task entrypoints keep /// an outer scope through the checkpoint as well. pub(crate) fn enter_if_absent(isolate: &mut v8::Isolate) -> Option { diff --git a/moli-renderer-v8/src/worker/global_scope/import_scripts.rs b/moli-renderer-v8/src/worker/global_scope/import_scripts.rs index be4cbdc24c9..47c267b9b14 100644 --- a/moli-renderer-v8/src/worker/global_scope/import_scripts.rs +++ b/moli-renderer-v8/src/worker/global_scope/import_scripts.rs @@ -584,8 +584,11 @@ fn evaluate_worker_script( }); return Err(error); } - scope.perform_microtask_checkpoint(); - crate::context_bootstrap::run_end_of_microtask_checkpoint_tasks(&mut scope); + { + let _checkpoint_scope = crate::script_cleanup::MicrotaskCheckpointScope::enter(&mut scope); + scope.perform_microtask_checkpoint(); + crate::context_bootstrap::run_end_of_microtask_checkpoint_tasks(&mut scope); + } Ok(()) } diff --git a/moli-renderer-v8/src/worker/module_runtime.rs b/moli-renderer-v8/src/worker/module_runtime.rs index d4194aaf01b..e7cd1ff3318 100644 --- a/moli-renderer-v8/src/worker/module_runtime.rs +++ b/moli-renderer-v8/src/worker/module_runtime.rs @@ -699,8 +699,11 @@ fn finish_worker_module_bootstrap( // The host reports evaluation failures as errors, not unhandled rejections. promise.mark_as_handled(); } - scope.perform_microtask_checkpoint(); - crate::context_bootstrap::run_end_of_microtask_checkpoint_tasks(scope); + { + let _checkpoint_scope = crate::script_cleanup::MicrotaskCheckpointScope::enter(scope); + scope.perform_microtask_checkpoint(); + crate::context_bootstrap::run_end_of_microtask_checkpoint_tasks(scope); + } if root_module.get_status() == v8::ModuleStatus::Errored { return Err(WorkerModuleBootstrapFailure::evaluation( worker_bootstrap_value_error( @@ -1382,8 +1385,11 @@ fn finish_worker_dynamic_module_import_evaluation( if let Some(promise) = evaluation_promise { promise.mark_as_handled(); } - scope.perform_microtask_checkpoint(); - crate::context_bootstrap::run_end_of_microtask_checkpoint_tasks(scope); + { + let _checkpoint_scope = crate::script_cleanup::MicrotaskCheckpointScope::enter(scope); + scope.perform_microtask_checkpoint(); + crate::context_bootstrap::run_end_of_microtask_checkpoint_tasks(scope); + } if root_module.get_status() == v8::ModuleStatus::Errored { return Err(WorkerDynamicModuleImportError::evaluation_rejection_value( scope, @@ -1504,8 +1510,11 @@ fn resolve_single_worker_dynamic_module_import( return; }; let _ = resolver.resolve(scope, resolved_value); - scope.perform_microtask_checkpoint(); - crate::context_bootstrap::run_end_of_microtask_checkpoint_tasks(scope); + { + let _checkpoint_scope = crate::script_cleanup::MicrotaskCheckpointScope::enter(scope); + scope.perform_microtask_checkpoint(); + crate::context_bootstrap::run_end_of_microtask_checkpoint_tasks(scope); + } } fn take_worker_dynamic_module_imports_joined_to_root( @@ -1546,8 +1555,11 @@ fn reject_worker_dynamic_module_import( .unwrap_or_else(|| v8::undefined(scope).into()), }; let _ = resolver.reject(scope, rejection); - scope.perform_microtask_checkpoint(); - crate::context_bootstrap::run_end_of_microtask_checkpoint_tasks(scope); + { + let _checkpoint_scope = crate::script_cleanup::MicrotaskCheckpointScope::enter(scope); + scope.perform_microtask_checkpoint(); + crate::context_bootstrap::run_end_of_microtask_checkpoint_tasks(scope); + } } fn finish_failed_worker_dynamic_module_import(