Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
refactor(emulation): notify isolate owners without environment generations
ldm019e5667fe340
diff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/process_environment.py b/moli-cdp-smoke/moli_cdp_smoke/groups/process_environment.pyindex df3c08102..8af57423f 100644--- a/moli-cdp-smoke/moli_cdp_smoke/groups/process_environment.py+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/process_environment.py@@ -51,12 +51,15 @@ async def _install_workers(page: Any) -> None:environmentShared.port.start();globalThis.environmentDate = Date;globalThis.environmentIntl = Intl.DateTimeFormat;+ globalThis.environmentExistingDate = new Date('2024-01-01T00:00:00Z');+ environmentExistingDate.getTimezoneOffset();}""", READ_DEFAULTS)-async def _override_while_peer_paused(control: Any, peer: Any) -> None:+async def _override_while_peer_paused(control: Any, peer: Any, baseline: list[Any]) -> None:# A paused isolate cannot drain its ordinary foreground notification. The- # nested Inspector command must see the new default before JS is resumed.+ # explicit owner notification must run before the next nested Inspector+ # command, without a generation check or resuming page JavaScript.await peer.send("Debugger.enable")paused = asyncio.get_running_loop().create_future()@@ -70,16 +73,24 @@ async def _override_while_peer_paused(control: Any, peer: Any) -> None:}))try:event = await asyncio.wait_for(paused, timeout=10)- await control.send("Emulation.setLocaleOverride", {"locale": "fr_FR"})- await control.send("Emulation.setTimezoneOverride", {"timezoneId": "Europe/Paris"})- result = await peer.send("Debugger.evaluateOnCallFrame", {- "callFrameId": event["callFrames"][0]["callFrameId"],- "expression": f"({READ_DEFAULTS})()",- "returnByValue": True,- })- assert_equal(result.get("result", {}).get("value"),- ["fr-FR", "Europe/Paris", -60, -120],- "paused isolate observes process defaults without resuming")+ transitions = [+ ("fr_FR", "Europe/Paris", ["fr-FR", "Europe/Paris", -60, -120]),+ ("de_DE", "Asia/Shanghai", ["de-DE", "Asia/Shanghai", -480, -480]),+ ("", "", baseline),+ ("fr_FR", "Europe/Paris", ["fr-FR", "Europe/Paris", -60, -120]),+ ]+ for locale, timezone, expected in transitions:+ await control.send("Emulation.setLocaleOverride", {"locale": locale})+ await control.send("Emulation.setTimezoneOverride", {"timezoneId": timezone})+ # No sleep, retry, resume, or unrelated command to drive delivery.+ result = await peer.send("Debugger.evaluateOnCallFrame", {+ "callFrameId": event["callFrames"][0]["callFrameId"],+ "expression": f"[({READ_DEFAULTS})(), environmentExistingDate.getTimezoneOffset()]",+ "returnByValue": True,+ })+ assert_equal(result.get("result", {}).get("value"),+ [expected, expected[2]],+ f"paused isolate and existing Date observe {locale}/{timezone}")finally:peer.remove_listener("Debugger.paused", on_paused)with contextlib.suppress(Exception):@@ -114,8 +125,8 @@ async def run_process_environment_group(assert_equal(await _worker_defaults(peer), [baseline, baseline], "worker baseline")record(results, "process_environment_workers_before_override")- await _override_while_peer_paused(control, other)- record(results, "process_environment_paused_inspector_refresh")+ await _override_while_peer_paused(control, other, baseline)+ record(results, "process_environment_paused_change_replace_restore")expected = ["fr-FR", "Europe/Paris", -60, -120]assert_equal(await peer.evaluate(READ_DEFAULTS), expected, "existing peer isolate")assert_equal(await _worker_defaults(peer), [expected, expected], "existing worker isolates")diff --git a/moli-protocol/src/domains/tracing/tests.rs b/moli-protocol/src/domains/tracing/tests.rsindex fc900cb34..0ff6d7091 100644--- a/moli-protocol/src/domains/tracing/tests.rs+++ b/moli-protocol/src/domains/tracing/tests.rs@@ -322,6 +322,7 @@ async fn owner_cleanup_waits_for_cpu_trace_release_before_replacement_start() {moli_v8_platform::V8ForegroundTaskWake::queued(move |task| {let _ = owner_task_tx.send(task);}),+ |_| {},);let mut ctx = context_with_page_sessions();@@ -567,6 +568,7 @@ async fn cpu_trace_start_response_waits_for_existing_isolate_ack() {moli_v8_platform::V8ForegroundTaskWake::queued(move |task| {let _ = owner_task_tx.send(task);}),+ |_| {},);let mut ctx = context_with_page_sessions();@@ -633,6 +635,7 @@ async fn cpu_trace_start_reports_chromium_error_when_stopped_before_ack() {moli_v8_platform::V8ForegroundTaskWake::queued(move |task| {let _ = owner_task_tx.send(task);}),+ |_| {},);let mut ctx = context_with_page_sessions();diff --git a/moli-renderer-v8/src/devtools/ingress/io.rs b/moli-renderer-v8/src/devtools/ingress/io.rsindex bc2a5d563..b1edee15b 100644--- a/moli-renderer-v8/src/devtools/ingress/io.rs+++ b/moli-renderer-v8/src/devtools/ingress/io.rs@@ -8,6 +8,7 @@ use std::{};use moli_page_types::{DevToolsSessionKey, RendererDevToolsAgentToken};+use moli_v8_platform::ProcessEnvironmentChange;use parking_lot::Mutex;use crate::{@@ -242,6 +243,9 @@ impl RendererInspectorIoOwnerWake {struct RendererInspectorIoState {commands: VecDeque<RendererInspectorIoCommand>,+ // Isolate-owned notifications, not session commands. They remain eligible+ // during session detach and an active command's nested debugger pause.+ environment_changes: VecDeque<ProcessEnvironmentChange>,active_command_id: Option<u64>,// One count per lane is enough: every detach guard completes at most once,// and commands stay blocked until all outstanding guards have completed.@@ -252,6 +256,10 @@ struct RendererInspectorIoState {impl RendererInspectorIoState {fn has_ready(&self) -> bool {+ !self.closed && (!self.environment_changes.is_empty() || self.has_ready_command())+ }++ fn has_ready_command(&self) -> bool {!self.closed&& self.active_command_id.is_none()&& self.commands.iter().any(|command| {@@ -373,6 +381,7 @@ impl RendererInspectorIoIngress {shared: Arc::new(RendererInspectorIoShared {state: Mutex::new(RendererInspectorIoState {commands: VecDeque::new(),+ environment_changes: VecDeque::new(),active_command_id: None,session_detaches: BTreeMap::new(),closed: false,@@ -399,6 +408,24 @@ impl RendererInspectorIoIngress {.map(|route| route.target.route_id())}+ /// The process controller publishes before returning to its caller. Reuse+ /// this owner's idle wake, active-JS interrupt and nested-pause wake; a+ /// normal Page foreground task cannot run while the debugger is paused.+ pub(crate) fn enqueue_environment_change(&self, change: ProcessEnvironmentChange) {+ {+ let mut state = self.shared.state.lock();+ if state.closed {+ return;+ }+ state.environment_changes.push_back(change);+ }+ self.notify_execution_opportunities();+ }++ pub(crate) fn claim_environment_change(&self) -> Option<ProcessEnvironmentChange> {+ self.shared.state.lock().environment_changes.pop_front()+ }+/// Breaks an active V8 call so target teardown can reach the Page owner.////// Closing the ingress prevents queued IO work from being claimed, but@@ -509,7 +536,7 @@ impl RendererInspectorIoIngress {consumer: RendererInspectorIoCommandConsumer,) -> Option<RendererInspectorIoCommand> {let mut state = self.shared.state.lock();- if !state.has_ready() {+ if !state.has_ready_command() {return None;}let position = state@@ -634,6 +661,7 @@ impl RendererInspectorIoIngress {let commands = {let mut state = self.shared.state.lock();state.closed = true;+ state.environment_changes.clear();state.commands.drain(..).collect::<Vec<_>>()};self.shared.pause_wake.notify_all();@@ -719,6 +747,10 @@ impl std::fmt::Debug for RendererInspectorIoIngress {.debug_struct("RendererInspectorIoIngress").field("route_id", &self.route_id()).field("queued_tasks", &state.commands.len())+ .field(+ "environment_notifications",+ &state.environment_changes.len(),+ ).field("active_command_id", &state.active_command_id).field("interrupt_armed",@@ -784,6 +816,42 @@ mod tests {)}+ #[test]+ fn environment_notifications_are_isolate_owned_and_survive_session_detach() {+ let ingress = ingress();+ let agent = RendererDevToolsAgentToken::allocate();+ let _route = enqueue(&ingress, agent, Some("session-a"), "active");+ let mut command = ingress.claim_for_owner().unwrap();+ let guard = ingress.first_dispatch_guard(&mut command);+ ingress.begin_session_detach(agent, command.ticket().session());+ ingress.enqueue_environment_change(ProcessEnvironmentChange::LocaleChanged);+ ingress.enqueue_environment_change(ProcessEnvironmentChange::TimezoneChanged);+ // A nested pause can receive these without releasing the active+ // command slot or creating another Inspector session.+ assert!(ingress.claim_for_pause().is_none());+ assert_eq!(+ ingress.claim_environment_change(),+ Some(ProcessEnvironmentChange::LocaleChanged)+ );+ assert_eq!(+ ingress.claim_environment_change(),+ Some(ProcessEnvironmentChange::TimezoneChanged)+ );+ assert_eq!(ingress.claim_environment_change(), None);+ drop(guard);+ ingress.finish_session_detach(agent, command.ticket().session());+ }++ #[test]+ fn closed_isolate_discards_queued_and_late_environment_notifications() {+ let ingress = ingress();+ ingress.enqueue_environment_change(ProcessEnvironmentChange::LocaleChanged);+ ingress.close("isolate disposed");+ ingress.enqueue_environment_change(ProcessEnvironmentChange::TimezoneChanged);+ assert_eq!(ingress.claim_environment_change(), None);+ assert!(!ingress.shared.state.lock().has_ready());+ }+fn session_response_output(call_id: i32,result: serde_json::Value,diff --git a/moli-renderer-v8/src/script_vm/document_isolate.rs b/moli-renderer-v8/src/script_vm/document_isolate.rsindex 33315a4e3..bc0ac94a9 100644--- a/moli-renderer-v8/src/script_vm/document_isolate.rs+++ b/moli-renderer-v8/src/script_vm/document_isolate.rs@@ -579,9 +579,14 @@ impl RendererDocumentIsolateHolder {isolate.set_promise_reject_callback(promise_reject_callback);isolate.set_failed_access_check_callback_function(failed_access_check_callback);+ let inspector_start = timing_enabled.then(std::time::Instant::now);+ let inspector_backend = RendererInspectorIsolateBackend::new(&mut isolate);+ let inspector_elapsed = inspector_start.map(|start| start.elapsed());+ let environment_ingress = inspector_backend.devtools_target().io_ref().clone();let platform_registration = V8PlatformIsolateRegistration::register(&mut isolate,foreground_wake.into_platform_wake(),+ move |change| environment_ingress.enqueue_environment_change(change),);let isolate_ptr = unsafe { isolate.as_raw_isolate_ptr() };let isolate_bootstrap;@@ -621,8 +626,6 @@ impl RendererDocumentIsolateHolder {}}- let inspector_start = timing_enabled.then(std::time::Instant::now);- let inspector_backend = RendererInspectorIsolateBackend::new(&mut isolate);let devtools_target_shutdown_registration = devtools_target_shutdown_registry.map(|registry| registry.register(inspector_backend.devtools_target())).transpose()@@ -631,7 +634,7 @@ impl RendererDocumentIsolateHolder {tracing::info!(target: "moli_cdp_nav_timing",stage = "inspector_backend_new",- elapsed_ms = inspector_start.unwrap().elapsed().as_secs_f64() * 1000.0,+ elapsed_ms = inspector_elapsed.unwrap().as_secs_f64() * 1000.0,"RendererInspectorIsolateBackend::new");tracing::info!(@@ -710,7 +713,6 @@ fn with_entered_owned_isolate<T>(isolate.enter();}let _guard = EnteredIsolateGuard(isolate);- moli_v8_platform::refresh_process_environment(isolate);op(isolate)}diff --git a/moli-renderer-v8/src/script_vm/inspector/v8_backend.rs b/moli-renderer-v8/src/script_vm/inspector/v8_backend.rsindex 46ad8f74f..9c611a45d 100644--- a/moli-renderer-v8/src/script_vm/inspector/v8_backend.rs+++ b/moli-renderer-v8/src/script_vm/inspector/v8_backend.rs@@ -73,6 +73,7 @@ struct RendererInspectorSessionExecutorLocal {}enum RendererInspectorNestedCommand {+ Environment(moli_v8_platform::ProcessEnvironmentChange),Main(RendererInspectorMainCommand),Io(RendererInspectorIoCommand),}@@ -171,6 +172,12 @@ impl RendererInspectorSessionExecutorLocal {};let mut prefer_main = true;while let Some(command) = self.target.pause_ref().wait_for_pause_work(|| {+ // These are actual posted owner tasks, not an environment-version+ // check. Service them in both pause modes, before a following+ // Inspector observation; they never execute page JavaScript.+ if let Some(change) = self.target.io_ref().claim_environment_change() {+ return Some(RendererInspectorNestedCommand::Environment(change));+ }let command = match pause_loop_policy {crate::devtools::pause::RendererInspectorPauseLoopPolicy::IoOnly => self.target@@ -211,13 +218,12 @@ impl RendererInspectorSessionExecutorLocal {}command}) {- // Pause-loop work bypasses normal isolate entry and foreground- // notifications. Refresh for each nested command, not just when- // entering the pause: process defaults may change while waiting.- let isolate = unsafe { &mut *self.isolate.get() };- let isolate = unsafe { v8::Isolate::ref_from_raw_isolate_ptr_mut(isolate) };- moli_v8_platform::refresh_process_environment(isolate);match command {+ RendererInspectorNestedCommand::Environment(change) => {+ let isolate = unsafe { &mut *self.isolate.get() };+ let isolate = unsafe { v8::Isolate::ref_from_raw_isolate_ptr_mut(isolate) };+ change.notify_isolate(isolate);+ }RendererInspectorNestedCommand::Main(command) => {self.dispatch_main_command(context_group_id, command);}diff --git a/moli-renderer-v8/src/script_vm/inspector/v8_backend/interrupt.rs b/moli-renderer-v8/src/script_vm/inspector/v8_backend/interrupt.rsindex 4b7f13456..fa84ffaec 100644--- a/moli-renderer-v8/src/script_vm/inspector/v8_backend/interrupt.rs+++ b/moli-renderer-v8/src/script_vm/inspector/v8_backend/interrupt.rs@@ -92,9 +92,7 @@ pub(super) unsafe extern "C" fn dispatch_inspector_interrupt(};let mut isolate_ptr = isolate;let isolate = unsafe { v8::Isolate::ref_from_raw_isolate_ptr_mut(&mut isolate_ptr) };- // Running JavaScript has not returned to the owner loop to consume the- // foreground notification. An Inspector interrupt is also an observation.- moli_v8_platform::refresh_process_environment(isolate);+ dispatch_environment_notifications(&session_executor, isolate);with_scoped_inspector_microtasks(isolate, || {session_executor.dispatch_next_io_command_from_interrupt();});@@ -118,7 +116,7 @@ pub(crate) fn dispatch_inspector_io_owner_wake(wake: RendererInspectorIoOwnerWakisolate.enter();}let _entered_isolate = EnteredOwnerWakeIsolateGuard(isolate);- moli_v8_platform::refresh_process_environment(isolate);+ dispatch_environment_notifications(&session_executor, isolate);let scope = pin!(v8::HandleScope::new(isolate));let scope = &mut scope.init();with_scoped_inspector_microtasks(scope, || {@@ -129,6 +127,26 @@ pub(crate) fn dispatch_inspector_io_owner_wake(wake: RendererInspectorIoOwnerWakpub(crate) fn dispatch_inspector_main_owner_wake(wake: RendererInspectorMainOwnerWake,) -> Option<RendererInspectorMainOwnerDispatch> {- session_executor(wake.route_id())- .and_then(|session_executor| session_executor.claim_next_main_command_from_owner())+ let session_executor = session_executor(wake.route_id())?;+ // Main and IO have separate owner wake channels. Do not let selection of+ // a Main wake overtake an environment notification already in IO ingress.+ // Only enter V8 when there is concrete notification work to execute.+ if let Some(change) = session_executor.target.io_ref().claim_environment_change() {+ let isolate = unsafe { &mut *session_executor.isolate.get() };+ let isolate = unsafe { v8::Isolate::ref_from_raw_isolate_ptr_mut(isolate) };+ unsafe { isolate.enter() };+ let _entered_isolate = EnteredOwnerWakeIsolateGuard(isolate);+ change.notify_isolate(isolate);+ dispatch_environment_notifications(&session_executor, isolate);+ }+ session_executor.claim_next_main_command_from_owner()+}++fn dispatch_environment_notifications(+ session_executor: &RendererInspectorSessionExecutorLocal,+ isolate: &mut v8::Isolate,+) {+ while let Some(change) = session_executor.target.io_ref().claim_environment_change() {+ change.notify_isolate(isolate);+ }}diff --git a/moli-renderer-v8/src/worker/inspector_task_runner.rs b/moli-renderer-v8/src/worker/inspector_task_runner.rsindex 4a2c07959..f1dd147b8 100644--- a/moli-renderer-v8/src/worker/inspector_task_runner.rs+++ b/moli-renderer-v8/src/worker/inspector_task_runner.rs@@ -78,6 +78,7 @@ unsafe extern "C" fn dispatch_worker_inspector_interrupt(pub(crate) type WorkerInspectorTaskMode = CdpInspectorTaskMode;pub(crate) enum WorkerInspectorTask {+ EnvironmentChanged(moli_v8_platform::ProcessEnvironmentChange),DispatchProtocolMessage {inspector_session_id: Option<String>,raw_json: String,@@ -175,6 +176,18 @@ impl WorkerInspectorTaskRunner {self.shared.interrupt_target.route_id}+ /// An isolate notification shares the existing owner/interrupt/pause task+ /// route, but has no Inspector session and invokes no page script.+ pub(crate) fn append_environment_change(+ &self,+ change: moli_v8_platform::ProcessEnvironmentChange,+ ) {+ self.append(+ WorkerInspectorTaskMode::Interrupt,+ WorkerInspectorTask::EnvironmentChanged(change),+ );+ }+pub(crate) fn append_protocol_message(&self,inspector_session_id: Option<String>,@@ -561,6 +574,35 @@ mod tests {));}+ #[test]+ fn environment_notifications_share_interrupt_fifo_and_are_discarded_on_disposal() {+ use moli_v8_platform::ProcessEnvironmentChange::{LocaleChanged, TimezoneChanged};++ let (runner, _wake_rx) = runner();+ runner.append_environment_change(LocaleChanged);+ let _command = append_protocol(&runner, 1, "Debugger.resume");+ runner.append_environment_change(TimezoneChanged);+ assert!(runner.begin_pause_loop());+ // The nested pause uses this same interrupting FIFO. No session or+ // ordinary Worker-loop turn is required to receive a notification.+ assert!(matches!(+ runner.claim_task(WorkerInspectorTaskMode::Interrupt),+ Some(WorkerInspectorTask::EnvironmentChanged(LocaleChanged))+ ));+ assert!(matches!(+ runner.claim_task(WorkerInspectorTaskMode::Interrupt),+ Some(WorkerInspectorTask::DispatchProtocolMessage { .. })+ ));+ runner.dispose("worker teardown");+ runner.append_environment_change(LocaleChanged);+ assert!(+ runner+ .claim_task(WorkerInspectorTaskMode::Interrupt)+ .is_none()+ );+ assert!(runner.wait_for_pause_task().is_none());+ }+#[test]fn dispose_rejects_queued_and_late_protocol_tasks() {let (runner, _wake_rx) = runner();diff --git a/moli-renderer-v8/src/worker/thread/isolate.rs b/moli-renderer-v8/src/worker/thread/isolate.rsindex 18af5fcc5..590ddce5d 100644--- a/moli-renderer-v8/src/worker/thread/isolate.rs+++ b/moli-renderer-v8/src/worker/thread/isolate.rs@@ -47,13 +47,14 @@ impl WorkerIsolateState {);let runtime_inspector = WorkerRuntimeInspector::new(&mut isolate,- inspector_task_runner,+ inspector_task_runner.clone(),parent_tx,shared_worker,);let platform_registration = V8PlatformIsolateRegistration::register(&mut isolate,platform_wake.into_platform_wake(),+ move |change| inspector_task_runner.append_environment_change(change),);Self {@@ -64,7 +65,6 @@ impl WorkerIsolateState {}pub(super) fn worker_isolate_mut(&mut self) -> &mut v8::OwnedIsolate {- moli_v8_platform::refresh_process_environment(&mut self.isolate);&mut self.isolate}@@ -75,7 +75,6 @@ impl WorkerIsolateState {pub(super) fn worker_isolate_and_runtime_inspector(&mut self,) -> (&mut v8::OwnedIsolate, Rc<WorkerRuntimeInspector>) {- moli_v8_platform::refresh_process_environment(&mut self.isolate);(&mut self.isolate, Rc::clone(&self.runtime_inspector))}diff --git a/moli-renderer-v8/src/worker/thread/runtime_inspector.rs b/moli-renderer-v8/src/worker/thread/runtime_inspector.rsindex c74a96405..c328f35c1 100644--- a/moli-renderer-v8/src/worker/thread/runtime_inspector.rs+++ b/moli-renderer-v8/src/worker/thread/runtime_inspector.rs@@ -565,11 +565,8 @@ impl WorkerRuntimeInspector {}pub(super) fn execute_task(&self, isolate: &mut v8::Isolate, task: WorkerInspectorTask) {- // This common entry also serves active-JS interrupts and nested pauses,- // where neither ordinary Worker entry nor foreground tasks can refresh- // V8's cached locale/timezone before the next Inspector observation.- moli_v8_platform::refresh_process_environment(isolate);match task {+ WorkerInspectorTask::EnvironmentChanged(change) => change.notify_isolate(isolate),WorkerInspectorTask::DispatchProtocolMessage {inspector_session_id,raw_json,@@ -805,12 +802,25 @@ mod tests {rv.set(v8::Boolean::new(scope, inspector_policy_is_scoped).into());}- #[test]- fn worker_inspector_observes_environment_without_an_owner_loop_turn() {+ #[tokio::test]+ async fn worker_environment_notifications_precede_inspector_work_without_an_owner_loop_turn() {crate::ensure_v8_for_test();let mut isolate = v8::Isolate::new(Default::default());isolate.set_microtasks_policy(v8::MicrotasksPolicy::Explicit);- let inspector = WorkerRuntimeInspector::new_for_test(&mut isolate);+ let (wake_tx, _wake_rx) = mpsc::unbounded_channel();+ let (parent_tx, _parent_rx) = mpsc::unbounded_channel();+ let task_runner = WorkerInspectorTaskRunner::new(+ wake_tx,+ std::sync::Arc::new(parking_lot::Mutex::new(Some(isolate.thread_safe_handle()))),+ );+ let inspector =+ WorkerRuntimeInspector::new(&mut isolate, task_runner.clone(), parent_tx, false);+ let notifications = task_runner.clone();+ let registration = moli_v8_platform::V8PlatformIsolateRegistration::register(+ &mut isolate,+ moli_v8_platform::V8ForegroundTaskWake::queued(|_| {}),+ move |change| notifications.append_environment_change(change),+ );{let scope = pin!(v8::HandleScope::new(&mut isolate));let scope = &mut scope.init();@@ -823,24 +833,30 @@ mod tests {}let read_defaults = |isolate: &mut v8::Isolate| {let (response_tx, mut response_rx) = tokio::sync::oneshot::channel();- // Interrupts and nested pauses enter execute_task directly, without- // WorkerIsolateState or a foreground task refreshing the isolate.- inspector.execute_task(- isolate,- WorkerInspectorTask::DispatchProtocolMessage {- inspector_session_id: None,- raw_json: json!({+ assert!(task_runner.append_protocol_message(+ None,+ json!({"id": 1,- "method": "Runtime.evaluate",+ "method": "Runtime.callFunctionOn","params": {- "expression": "[new Intl.NumberFormat().resolvedOptions().locale, new Intl.DateTimeFormat().resolvedOptions().timeZone, new Date('2024-01-01T00:00:00Z').getTimezoneOffset()]",+ "functionDeclaration": "function() { return [new Intl.NumberFormat().resolvedOptions().locale, new Intl.DateTimeFormat().resolvedOptions().timeZone, new Date('2024-01-01T00:00:00Z').getTimezoneOffset()]; }",+ "executionContextId": inspector.default_execution_context_id.get().unwrap(),"returnByValue": true,},- }).to_string(),- deferred_response: None,- response_tx,- },- );+ }).to_string(),+ None,+ response_tx,+ ));+ // Pump explicit owner notifications before the non-interrupting+ // evaluation. No global-version check or normal Worker entry is+ // involved, and a nested pause can consume these same notifications.+ while let Some(task) = task_runner.claim_task(WorkerInspectorTaskMode::Interrupt) {+ inspector.execute_task(isolate, task);+ }+ let task = task_runner+ .claim_task(WorkerInspectorTaskMode::DontInterrupt)+ .unwrap();+ inspector.execute_task(isolate, task);let messages = response_rx.try_recv().unwrap().unwrap();let response = protocol_response(&messages, 1);assert!(response.get("error").is_none(), "{response:#?}");@@ -856,6 +872,8 @@ mod tests {);owner.release();assert_eq!(read_defaults(&mut isolate), baseline);+ registration.unregister();+ task_runner.dispose("test complete");}#[test]diff --git a/moli-v8-platform/src/cpu_tracing.rs b/moli-v8-platform/src/cpu_tracing.rsindex b889a959d..747500b37 100644--- a/moli-v8-platform/src/cpu_tracing.rs+++ b/moli-v8-platform/src/cpu_tracing.rs@@ -703,6 +703,7 @@ mod tests {V8ForegroundTaskWake::queued(move |task| {let _ = owner_task_tx.send(task);}),+ |_| {},);let session = start_v8_cpu_trace(V8CpuTraceConfiguration {diff --git a/moli-v8-platform/src/environment.rs b/moli-v8-platform/src/environment.rsindex 1e22917ce..de0455bea 100644--- a/moli-v8-platform/src/environment.rs+++ b/moli-v8-platform/src/environment.rs@@ -12,13 +12,32 @@ use std::sync::{use parking_lot::Mutex;-use super::{- dispatch_isolate_owner_callback, registered_isolate_owners, unsafe_raw_isolate_ptr_from_addr,-};+use super::registered_isolate_owners;-static GENERATION: AtomicU64 = AtomicU64::new(1);static ENVIRONMENT: OnceLock<Mutex<Environment>> = OnceLock::new();+/// A committed change to the renderer-process defaults, delivered as owner+/// work rather than checked at every V8 entry. Delivery must enqueue the+/// notification; only the isolate's owner may apply it, including in a nested+/// Inspector pause loop. It carries no isolate pointer or configuration lease.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum ProcessEnvironmentChange {+ LocaleChanged,+ TimezoneChanged,+}++impl ProcessEnvironmentChange {+ /// Notify native V8 caches on the entered isolate's owner thread. Locale+ /// changes also invalidate cached Date locale formatters, as in Blink.+ pub fn notify_isolate(self, isolate: &mut v8::Isolate) {+ if self == Self::LocaleChanged {+ isolate.locale_configuration_change_notification();+ }+ // Redetect would overwrite the emulated ICU timezone with the host zone.+ isolate.date_time_configuration_change_notification(v8::TimeZoneDetection::Skip);+ }+}+fn environment() -> &'static Mutex<Environment> {ENVIRONMENT.get_or_init(|| {Mutex::new(Environment {@@ -92,7 +111,7 @@ impl ProcessEnvironmentOwner {owner: self.id,value: value.to_owned(),});- publish_change(state);+ publish_change(state, ProcessEnvironmentChange::LocaleChanged);Ok(())}@@ -125,7 +144,7 @@ impl ProcessEnvironmentOwner {owner: self.id,value: value.to_owned(),});- publish_change(state);+ publish_change(state, ProcessEnvironmentChange::TimezoneChanged);Ok(())}@@ -198,49 +217,29 @@ fn release(owner: EnvironmentOwnerId) {debug_assert!(restored, "the original ICU timezone must be restorable");state.timezone = None;}- publish_change(state);+ publish_change(+ state,+ if locale {+ ProcessEnvironmentChange::LocaleChanged+ } else {+ ProcessEnvironmentChange::TimezoneChanged+ },+ );}-/// Publish only a successfully committed ICU change. Advance the generation-/// under the configuration lock, but enqueue owner work after unlocking: an-/// isolate refresh must never run while holding the process configuration lock.-fn publish_change(state: parking_lot::MutexGuard<'_, Environment>) {- GENERATION.fetch_add(1, Ordering::Release);- drop(state);- // Reuse the platform's exact-generation routes: no second isolate registry,- // no timer/polling, and queued work is cancelled before isolate disposal.+/// Keep ICU updates and notification publication serialized, as in Blink's+/// controllers. Dispatchers only enqueue owner work, never enter V8 or acquire+/// this configuration lock. Publication finishes before the setter returns,+/// so a subsequent command cannot be enqueued ahead of its notification.+fn publish_change(+ _state: parking_lot::MutexGuard<'_, Environment>,+ change: ProcessEnvironmentChange,+) {for owner in registered_isolate_owners() {- let address = owner.isolate_addr;- dispatch_isolate_owner_callback(owner, move || {- // SAFETY: the platform invokes this on the registered owner thread- // while its exact generation is live. Page owners enter the isolate- // before running foreground tasks; Worker isolates remain entered.- let mut isolate = unsafe {- v8::Isolate::from_raw_isolate_ptr(unsafe_raw_isolate_ptr_from_addr(address))- };- refresh_process_environment(&mut isolate);- });- }-}--#[derive(Clone, Copy)]-struct ObservedEnvironment(u64);--/// Call at isolate entry as well as on the foreground notification. The entry-/// check prevents a command from overtaking a queued notification. No clean-/// operation resets V8 caches; changes within a turn coalesce by generation.-pub fn refresh_process_environment(isolate: &mut v8::Isolate) {- let generation = GENERATION.load(Ordering::Acquire);- if isolate- .get_slot::<ObservedEnvironment>()- .is_some_and(|seen| seen.0 == generation)- {- return;+ if owner.registration.generation.is_active() {+ (owner.registration.environment_changed)(change);+ }}- isolate.locale_configuration_change_notification();- // Redetect would overwrite the emulated ICU timezone with the host zone.- isolate.date_time_configuration_change_notification(v8::TimeZoneDetection::Skip);- isolate.set_slot(ObservedEnvironment(generation));}#[cfg(test)]@@ -287,55 +286,55 @@ mod tests {}#[test]- fn environment_notifications_use_exact_owner_generation_and_cancel_on_disposal() {+ fn environment_changes_are_published_before_return_without_polling_or_redundant_work() {moli_v8_init::ensure_v8_initialized(crate::create_platform);let runtime = tokio::runtime::Builder::new_current_thread().enable_time().build().unwrap();runtime.block_on(async {- let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();+ let (tx, rx) = std::sync::mpsc::channel();let mut isolate = v8::Isolate::new(Default::default());let registration = crate::V8PlatformIsolateRegistration::register(&mut isolate,- crate::V8ForegroundTaskWake::queued(move |task| {- let _ = tx.send(task);- }),+ crate::V8ForegroundTaskWake::queued(|_| {}),+ move |change| tx.send(change).unwrap(),);let owner = ProcessEnvironmentOwner::default();- let before = isolate.get_slot::<ObservedEnvironment>().unwrap().0;owner.set_locale(Some("fr_FR")).unwrap();- let task = tokio::time::timeout(std::time::Duration::from_secs(5), rx.recv())- .await- .expect("locale notification timed out")- .expect("locale update must notify the registered isolate");- assert_eq!(isolate.get_slot::<ObservedEnvironment>().unwrap().0, before);- assert!(task.run());- let after = isolate.get_slot::<ObservedEnvironment>().unwrap().0;- assert!(after > before);- // A clean entry and a repeated same-owner setting allocate no work.- refresh_process_environment(&mut isolate);+ owner.set_timezone(Some("Europe/Paris")).unwrap();+ // No runtime yield or isolate entry: publication is synchronous,+ // ordered, and application belongs to the receiving owner.+ assert_eq!(+ rx.try_recv().unwrap(),+ ProcessEnvironmentChange::LocaleChanged+ );+ assert_eq!(+ rx.try_recv().unwrap(),+ ProcessEnvironmentChange::TimezoneChanged+ );owner.set_locale(Some("fr_FR")).unwrap();- assert_eq!(GENERATION.load(Ordering::Acquire), after);- assert!(rx.try_recv().is_err());-owner.set_timezone(Some("Europe/Paris")).unwrap();- let stale = tokio::time::timeout(std::time::Duration::from_secs(5), rx.recv())- .await- .expect("timezone notification timed out")- .expect("timezone update must notify the isolate");- // A command can overtake the notification without observing old caches.- refresh_process_environment(&mut isolate);+ assert!(owner.set_timezone(Some("Invalid/Zone")).is_err());+ let peer = ProcessEnvironmentOwner::default();+ assert!(peer.set_locale(Some("de_DE")).is_err());+ peer.set_timezone(Some("Europe/Paris")).unwrap();+ peer.set_timezone(None).unwrap();+ assert!(rx.try_recv().is_err());+ owner.release();assert_eq!(- isolate.get_slot::<ObservedEnvironment>().unwrap().0,- GENERATION.load(Ordering::Acquire)+ rx.try_recv().unwrap(),+ ProcessEnvironmentChange::LocaleChanged);+ owner.release();+ assert!(rx.try_recv().is_err());registration.unregister();drop(registration);drop(isolate);+ owner.set_locale(Some("de_DE")).unwrap();assert!(- !stale.run(),- "queued notification must not touch a disposed isolate"+ rx.try_recv().is_err(),+ "retired owners receive no notification");});}diff --git a/moli-v8-platform/src/lib.rs b/moli-v8-platform/src/lib.rsindex b1e1b7502..f9e0c5c2d 100644--- a/moli-v8-platform/src/lib.rs+++ b/moli-v8-platform/src/lib.rs@@ -24,7 +24,7 @@ const MAX_V8_BACKGROUND_WORKER_THREADS: usize = 8;mod cpu_tracing;mod environment;-pub use environment::{ProcessEnvironmentOwner, refresh_process_environment};+pub use environment::{ProcessEnvironmentChange, ProcessEnvironmentOwner};pub use cpu_tracing::{PendingV8CpuTraceStart, PendingV8CpuTraceStop, V8CpuProfileSegment, V8CpuTraceConfiguration,@@ -137,6 +137,7 @@ struct IsolateRuntimeRegistration {handle: tokio::runtime::Handle,wake: V8ForegroundTaskWake,generation: IsolateRegistrationGeneration,+ environment_changed: Arc<dyn Fn(ProcessEnvironmentChange) + Send + Sync>,}#[derive(Clone)]@@ -255,6 +256,7 @@ fn dispatch_isolate_owner_callback(handle,wake,generation,+ ..},} = owner;handle.spawn(async move {@@ -277,6 +279,7 @@ fn dispatch_isolate_owner_callback(fn register_isolate_with_wake(isolate_ptr: v8::UnsafeRawIsolatePtr,wake: V8ForegroundTaskWake,+ environment_changed: impl Fn(ProcessEnvironmentChange) + Send + Sync + 'static,) -> IsolateRegistrationGeneration {let isolate_key = unsafe_raw_isolate_addr(isolate_ptr);let Ok(handle) = tokio::runtime::Handle::try_current() else {@@ -290,6 +293,7 @@ fn register_isolate_with_wake(handle,wake,generation: generation.clone(),+ environment_changed: Arc::new(environment_changed),},) {// A raw isolate address may be reused after disposal. Invalidate queued@@ -314,13 +318,23 @@ pub struct V8PlatformIsolateRegistration {}impl V8PlatformIsolateRegistration {- pub fn register(isolate: &mut v8::OwnedIsolate, wake: V8ForegroundTaskWake) -> Self {- refresh_process_environment(isolate);+ /// Register an isolate and its owner task routes. `environment_changed`+ /// must enqueue a notification on that exact owner, including while paused;+ /// it must not synchronously enter V8. Closing the owner rejects late work.+ pub fn register(+ isolate: &mut v8::OwnedIsolate,+ wake: V8ForegroundTaskWake,+ environment_changed: impl Fn(ProcessEnvironmentChange) + Send + Sync + 'static,+ ) -> Self {// SAFETY: `OwnedIsolate::as_raw_isolate_ptr` returns the V8 isolate// pointer used by platform foreground-task callbacks. Ownership remains// with `OwnedIsolate`; this registration stores only the address value.let isolate_ptr = unsafe { isolate.as_raw_isolate_ptr() };- let generation = register_isolate_with_wake(isolate_ptr, wake);+ let generation = register_isolate_with_wake(isolate_ptr, wake, environment_changed);+ // Bootstrap may have primed caches before registration. Register first,+ // then reset once: changes before registration are read from ICU, and+ // changes racing this reset already have an owner notification queued.+ ProcessEnvironmentChange::LocaleChanged.notify_isolate(isolate);Self {isolate_ptr: AtomicCell::new(isolate_ptr),generation,@@ -377,6 +391,7 @@ impl v8::PlatformImpl for MoliPlatformImpl {handle,wake,generation,+ ..} = registration;handle.spawn(async move {if !generation.is_active() {@@ -417,6 +432,7 @@ impl v8::PlatformImpl for MoliPlatformImpl {handle,wake,generation,+ ..} = registration;let delay = Duration::from_secs_f64(delay_in_seconds);handle.spawn(async move {@@ -454,6 +470,7 @@ impl v8::PlatformImpl for MoliPlatformImpl {handle,wake,generation,+ ..} = registration;handle.spawn(async move {if !generation.is_active() {@@ -537,6 +554,7 @@ mod tests {let _ = register_isolate_with_wake(v8::UnsafeRawIsolatePtr::null(),V8ForegroundTaskWake::new(|| {}),+ |_| {},);}@@ -552,7 +570,7 @@ mod tests {runtime.block_on(async {let generation =- register_isolate_with_wake(isolate_ptr, V8ForegroundTaskWake::new(|| {}));+ register_isolate_with_wake(isolate_ptr, V8ForegroundTaskWake::new(|| {}), |_| {});let registration = lookup_registration(raw).expect("registered isolate should expose its runtime registration");let owner = V8PlatformIsolateRegistration {@@ -582,14 +600,14 @@ mod tests {runtime.block_on(async {let first_generation =- register_isolate_with_wake(isolate_ptr, V8ForegroundTaskWake::new(|| {}));+ register_isolate_with_wake(isolate_ptr, V8ForegroundTaskWake::new(|| {}), |_| {});let first = V8PlatformIsolateRegistration {isolate_ptr: AtomicCell::new(isolate_ptr),generation: first_generation.clone(),};let second_generation =- register_isolate_with_wake(isolate_ptr, V8ForegroundTaskWake::new(|| {}));+ register_isolate_with_wake(isolate_ptr, V8ForegroundTaskWake::new(|| {}), |_| {});let second = V8PlatformIsolateRegistration {isolate_ptr: AtomicCell::new(isolate_ptr),generation: second_generation.clone(),