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): clarify environment invalidation contracts
ldm03a5cf7f1239b
diff --git a/moli-renderer-v8/src/devtools/ingress/io.rs b/moli-renderer-v8/src/devtools/ingress/io.rsindex b6aee6607..d19809300 100644--- a/moli-renderer-v8/src/devtools/ingress/io.rs+++ b/moli-renderer-v8/src/devtools/ingress/io.rs@@ -9,7 +9,7 @@ use std::{use moli_page_types::{DevToolsSessionKey, RendererDevToolsAgentToken};use moli_v8_platform::{- ProcessEnvironmentChange, ProcessEnvironmentNotifications, ProcessEnvironmentNotifier,+ ProcessEnvironmentInvalidation, ProcessEnvironmentNotifications, ProcessEnvironmentNotifier,};use parking_lot::Mutex;@@ -423,7 +423,7 @@ impl RendererInspectorIoIngress {})}- pub(crate) fn claim_environment_change(&self) -> Option<ProcessEnvironmentChange> {+ pub(crate) fn claim_environment_invalidation(&self) -> Option<ProcessEnvironmentInvalidation> {self.shared.state.lock().environment_notifications.take()}@@ -827,17 +827,17 @@ mod tests {ingress.begin_session_detach(agent, command.ticket().session());let notifier = ingress.environment_notifier();for _ in 0..1_000 {- notifier.notify(ProcessEnvironmentChange::LocaleChanged);- notifier.notify(ProcessEnvironmentChange::TimezoneChanged);+ notifier.notify(ProcessEnvironmentInvalidation::LocaleAndDateTime);+ notifier.notify(ProcessEnvironmentInvalidation::DateTime);}// 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)+ ingress.claim_environment_invalidation(),+ Some(ProcessEnvironmentInvalidation::LocaleAndDateTime));- assert_eq!(ingress.claim_environment_change(), None);+ assert_eq!(ingress.claim_environment_invalidation(), None);drop(guard);ingress.finish_session_detach(agent, command.ticket().session());}@@ -846,10 +846,10 @@ mod tests {fn closed_isolate_discards_queued_and_late_environment_notifications() {let ingress = ingress();let notifier = ingress.environment_notifier();- notifier.notify(ProcessEnvironmentChange::LocaleChanged);+ notifier.notify(ProcessEnvironmentInvalidation::LocaleAndDateTime);ingress.close("isolate disposed");- notifier.notify(ProcessEnvironmentChange::TimezoneChanged);- assert_eq!(ingress.claim_environment_change(), None);+ notifier.notify(ProcessEnvironmentInvalidation::DateTime);+ assert_eq!(ingress.claim_environment_invalidation(), None);assert!(!ingress.shared.state.lock().has_ready());}diff --git a/moli-renderer-v8/src/script_vm/inspector/v8_backend.rs b/moli-renderer-v8/src/script_vm/inspector/v8_backend.rsindex 9c611a45d..ed5490bc5 100644--- a/moli-renderer-v8/src/script_vm/inspector/v8_backend.rs+++ b/moli-renderer-v8/src/script_vm/inspector/v8_backend.rs@@ -73,7 +73,7 @@ struct RendererInspectorSessionExecutorLocal {}enum RendererInspectorNestedCommand {- Environment(moli_v8_platform::ProcessEnvironmentChange),+ EnvironmentInvalidation(moli_v8_platform::ProcessEnvironmentInvalidation),Main(RendererInspectorMainCommand),Io(RendererInspectorIoCommand),}@@ -175,8 +175,10 @@ impl RendererInspectorSessionExecutorLocal {// 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));+ if let Some(invalidation) = self.target.io_ref().claim_environment_invalidation() {+ return Some(RendererInspectorNestedCommand::EnvironmentInvalidation(+ invalidation,+ ));}let command = match pause_loop_policy {crate::devtools::pause::RendererInspectorPauseLoopPolicy::IoOnly => self@@ -219,10 +221,10 @@ impl RendererInspectorSessionExecutorLocal {command}) {match command {- RendererInspectorNestedCommand::Environment(change) => {+ RendererInspectorNestedCommand::EnvironmentInvalidation(invalidation) => {let isolate = unsafe { &mut *self.isolate.get() };let isolate = unsafe { v8::Isolate::ref_from_raw_isolate_ptr_mut(isolate) };- change.notify_isolate(isolate);+ invalidation.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 c47d6ee70..2cc12c91a 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@@ -131,12 +131,16 @@ pub(crate) fn dispatch_inspector_main_owner_wake(// 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() {+ if let Some(invalidation) = session_executor+ .target+ .io_ref()+ .claim_environment_invalidation()+ {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);+ invalidation.notify_isolate(isolate);}session_executor.claim_next_main_command_from_owner()}@@ -147,7 +151,11 @@ fn dispatch_environment_notifications() {// Consume one merged batch. A publication racing application retains its// own wake instead of making this callback drain an unbounded producer.- if let Some(change) = session_executor.target.io_ref().claim_environment_change() {- change.notify_isolate(isolate);+ if let Some(invalidation) = session_executor+ .target+ .io_ref()+ .claim_environment_invalidation()+ {+ invalidation.notify_isolate(isolate);}}diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/date_locale.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/date_locale.rsindex f3565af02..e39d13792 100644--- a/moli-renderer-v8/src/script_vm/tests/browser_api/date_locale.rs+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/date_locale.rs@@ -203,7 +203,7 @@ fn emulation_locale_fallback_preserves_native_observation_order() {#[test]fn process_environment_defaults_do_not_read_array_prototype() {let environment = moli_v8_platform::ProcessEnvironmentOwner::default();- let mut vm = new_storage_test_vm("https://intl-private-arguments.test/");+ let mut vm = new_storage_test_vm("https://intl-array-prototype.test/");environment.set_locale(Some("fr_FR")).unwrap();environment.set_timezone(Some("Europe/Paris")).unwrap();assert_eq!(@@ -230,46 +230,6 @@ fn process_environment_defaults_do_not_read_array_prototype() {);}-#[test]-fn process_environment_preserves_native_primitive_options_and_defaults() {- let environment = moli_v8_platform::ProcessEnvironmentOwner::default();- let mut vm = new_storage_test_vm("https://intl-primitive-options.test/");- environment.set_timezone(Some("Europe/Paris")).unwrap();- assert_eq!(vm.eval(r#"JSON.stringify((() => {- const date = new Date('2024-01-01T00:00:00Z');- const options = [42, true, '', Symbol(), 1n];- const zones = options.every(value =>- new Intl.DateTimeFormat('en-US', value).resolvedOptions().timeZone === 'Europe/Paris');- const dates = ['toLocaleString', 'toLocaleDateString', 'toLocaleTimeString'].every(method =>- options.every(value => date[method]('en-US', value) === date[method]('en-US', {timeZone: 'Europe/Paris'})));- let nullRejected = false;- try {new Intl.DateTimeFormat('en-US', null);} catch (error) {nullRejected = error instanceof TypeError;}- return [zones, dates, nullRejected];- })())"#).unwrap(), "[true,true,true]");-}--#[test]-fn emulation_date_time_first_legacy_hyphens_are_not_timezone_offsets() {- let environment = moli_v8_platform::ProcessEnvironmentOwner::default();- let mut vm = new_storage_test_vm("https://date-time-first.test/");- for timezone in ["Europe/Paris", "America/New_York", "Asia/Shanghai"] {- environment.set_timezone(Some(timezone)).unwrap();- assert_eq!(- vm.eval(- r#"JSON.stringify([- '00:00:00 Jan-01-2024', '00:00:00 01-01-2024',- '00:00 Jan-01-2024', '00:00:00.000 Jan-01-2024',- '00:00:00 January-01-2024', '00:00:00 Jan-01-2024 (PST)'- ].map(input => [Date.parse(input) === +new Date(2024, 0, 1),- +new Date(input) === +new Date(2024, 0, 1)]))"#- )- .unwrap(),- "[[true,true],[true,true],[true,true],[true,true],[true,true],[true,true]]",- "{timezone}"- );- }-}-#[test]fn date_and_intl_native_method_descriptors_are_unchanged() {let environment = moli_v8_platform::ProcessEnvironmentOwner::default();@@ -357,9 +317,9 @@ fn process_environment_preserves_native_date_and_intl_coercion() {}#[test]-fn process_environment_preserves_native_options_with_inherited_setters() {+fn process_environment_preserves_native_datetime_options() {let environment = moli_v8_platform::ProcessEnvironmentOwner::default();- let mut vm = new_storage_test_vm("https://date-intl-inherited-options.test/");+ let mut vm = new_storage_test_vm("https://native-datetime-options.test/");environment.set_timezone(Some("Europe/Paris")).unwrap();let result = vm.eval(@@ -367,22 +327,39 @@ fn process_environment_preserves_native_options_with_inherited_setters() {const keys = ['get', 'timeZone'];const before = keys.map(key => Object.getOwnPropertyDescriptor(Object.prototype, key));const sentinel = {};- // Changing native defaults must not add observable property writes to- // option handling, including frozen options and inherited accessors.+ const date = new Date('2024-01-01T00:00:00Z');+ const methods = ['toLocaleString', 'toLocaleDateString', 'toLocaleTimeString'];+ const frozen = Object.freeze({timeZone: undefined});+ const noGetter = Object.defineProperty({}, 'timeZone', {get: undefined});+ const receivers = [];+ const accessor = Object.freeze({get timeZone() {+ receivers.push(this === accessor); return undefined;+ }});+ const cases = [+ ['undefined', undefined], ['empty-object', {}], ['number', 42],+ ['boolean', true], ['string', ''], ['symbol', Symbol()], ['bigint', 1n],+ ['frozen', frozen], ['getterless', noGetter], ['accessor', accessor],+ ['inherited-setter', Object.create({set timeZone(value) { throw sentinel; }})],+ ['explicit', {timeZone: 'UTC'}, 'UTC'],+ ['frozen-explicit', Object.freeze({timeZone: 'UTC'}), 'UTC']+ ];try {+ // Native option reads must not introduce writes through inherited setters.for (const key of keys) Object.defineProperty(Object.prototype, key, {set() { throw sentinel; }, configurable: true});- const date = new Date('2024-01-01T00:00:00Z');- const frozen = Object.freeze({timeZone: undefined});- const explicit = {timeZone: 'Europe/Paris'};- return [- new Intl.DateTimeFormat('en-US').resolvedOptions().timeZone,- new Intl.DateTimeFormat('en-US', frozen).resolvedOptions().timeZone,- ...['toLocaleString', 'toLocaleDateString', 'toLocaleTimeString'].map(method =>- date[method]('en-US') === date[method]('en-US', explicit) &&- date[method]('en-US', frozen) === date[method]('en-US', explicit))- ];+ const rows = cases.map(([name, options, zone = 'Europe/Paris']) => [name, [+ new Intl.DateTimeFormat('en-US', options).resolvedOptions().timeZone === zone,+ ...methods.map(method =>+ date[method]('en-US', options) === date[method]('en-US', {timeZone: zone}))+ ]]);+ let nullRejected = false;+ try {new Intl.DateTimeFormat('en-US', null);}+ catch (error) {nullRejected = error instanceof TypeError;}+ rows.push(['null-rejected', [nullRejected]],+ ['getter-receivers', [receivers.length > 0 && receivers.every(value => value)]],+ ['frozen-unmodified', [frozen.timeZone === undefined]]);+ return rows;} finally {keys.forEach((key, index) => {if (before[index]) Object.defineProperty(Object.prototype, key, before[index]);@@ -392,7 +369,14 @@ fn process_environment_preserves_native_options_with_inherited_setters() {})())"#,).unwrap();- assert_eq!(result, r#"["Europe/Paris","Europe/Paris",true,true,true]"#);+ let rows: Vec<(String, Vec<bool>)> = serde_json::from_str(&result).unwrap();+ assert_eq!(rows.len(), 16);+ for (name, checks) in rows {+ assert!(+ !checks.is_empty() && checks.iter().all(|passed| *passed),+ "native options case {name}: {checks:?}"+ );+ }}#[test]@@ -459,6 +443,9 @@ fn emulation_date_local_grammar_and_coercion_preserve_native_contracts() {.eval(r#"(() => {const inputs = [+ ['00:00:00 Jan-01-2024', 1], ['00:00:00 01-01-2024', 1],+ ['00:00 Jan-01-2024', 1], ['00:00:00.000 Jan-01-2024', 1],+ ['00:00:00 January-01-2024', 1], ['00:00:00 Jan-01-2024 (PST)', 1],['Tue Jan 02 2024 00:00:00', 2], ['Thu Jan 04 2024 00:00:00', 4],['Sat Jan 06 2024 00:00:00', 6], ['Jan 02 2024 (PST)', 2],['Jan 02 2024 (PST (ignored)', 2], [' 2024-01-02 ', 2],@@ -531,34 +518,6 @@ fn emulation_timezone_does_not_change_option_get_order_or_exceptions() {assert_eq!(vm.eval(probe).unwrap(), baseline);}-#[test]-fn emulation_timezone_preserves_frozen_options_and_original_getter_receivers() {- let environment = moli_v8_platform::ProcessEnvironmentOwner::default();- let mut vm = new_storage_test_vm("https://frozen-intl-options.test/");- environment.set_timezone(Some("Europe/Paris")).unwrap();- let result = vm.eval(r#"(() => {- const date = new Date('2024-01-01T00:00:00Z');- const frozen = Object.freeze({timeZone: undefined});- const noGetter = Object.defineProperty({}, 'timeZone', {get: undefined});- let receiver;- const accessor = Object.freeze({get timeZone() { receiver = this; return undefined; }});- const methods = ['toLocaleString', 'toLocaleDateString', 'toLocaleTimeString'];- return JSON.stringify([- new Intl.DateTimeFormat('en-US', frozen).resolvedOptions().timeZone,- new Intl.DateTimeFormat('en-US', noGetter).resolvedOptions().timeZone,- new Intl.DateTimeFormat('en-US', accessor).resolvedOptions().timeZone,- receiver === accessor,- ...methods.map(method => date[method]('en-US', frozen) === date[method]('en-US', {timeZone: 'Europe/Paris'})),- new Intl.DateTimeFormat('en-US', Object.freeze({timeZone: 'UTC'})).resolvedOptions().timeZone,- frozen.timeZone === undefined- ]);- })()"#).unwrap();- assert_eq!(- result,- r#"["Europe/Paris","Europe/Paris","Europe/Paris",true,true,true,true,"UTC",true]"#- );-}-#[test]fn emulation_date_parsing_preserves_native_explicit_legacy_timezones() {let environment = moli_v8_platform::ProcessEnvironmentOwner::default();diff --git a/moli-renderer-v8/src/worker/inspector_task_runner.rs b/moli-renderer-v8/src/worker/inspector_task_runner.rsindex f95ffc143..bc2d444a0 100644--- a/moli-renderer-v8/src/worker/inspector_task_runner.rs+++ b/moli-renderer-v8/src/worker/inspector_task_runner.rs@@ -79,7 +79,7 @@ unsafe extern "C" fn dispatch_worker_inspector_interrupt(pub(crate) type WorkerInspectorTaskMode = CdpInspectorTaskMode;pub(crate) enum WorkerInspectorTask {- EnvironmentChanged(moli_v8_platform::ProcessEnvironmentChange),+ EnvironmentInvalidation(moli_v8_platform::ProcessEnvironmentInvalidation),DispatchProtocolMessage {inspector_session_id: Option<String>,raw_json: String,@@ -131,8 +131,10 @@ struct WorkerInspectorTaskRunnerState {struct WorkerInspectorTaskRunnerShared {state: Mutex<WorkerInspectorTaskRunnerState>,environment_notifications: ProcessEnvironmentNotifications,- // Interrupt/pause consumption must not clear this bit: a fallback owner- // message can still be in the channel while JS processes many interrupts.+ // Tracks an outstanding fallback WorkerMessage::RunEnvironmentNotification,+ // not whether the mailbox contains an invalidation. Only consumption of+ // that owner message disarms it; interrupt/pause consumption must not,+ // otherwise repeated interrupts can flood the ordinary Worker channel.environment_owner_wake_armed: AtomicBool,pause_work: Condvar,wake_tx: mpsc::UnboundedSender<WorkerMessage>,@@ -213,23 +215,25 @@ impl WorkerInspectorTaskRunner {self.shared.pause_work.notify_one();}+ /// Called only when consuming the fallback owner message. Disarm before+ /// taking the mailbox so a racing publication can arm the next owner wake.pub(crate) fn claim_environment_for_owner(&self,- ) -> Option<moli_v8_platform::ProcessEnvironmentChange> {+ ) -> Option<moli_v8_platform::ProcessEnvironmentInvalidation> {self.shared.environment_owner_wake_armed.store(false, Ordering::Release);- self.claim_environment_change()+ self.claim_environment_invalidation()}fn claim_environment_task(&self) -> Option<WorkerInspectorTask> {- self.claim_environment_change()- .map(WorkerInspectorTask::EnvironmentChanged)+ self.claim_environment_invalidation()+ .map(WorkerInspectorTask::EnvironmentInvalidation)}- pub(crate) fn claim_environment_change(+ pub(crate) fn claim_environment_invalidation(&self,- ) -> Option<moli_v8_platform::ProcessEnvironmentChange> {+ ) -> Option<moli_v8_platform::ProcessEnvironmentInvalidation> {self.shared.environment_notifications.take()}@@ -636,13 +640,13 @@ mod tests {#[test]fn environment_bursts_and_interrupt_consumption_keep_the_owner_wake_bounded() {- use moli_v8_platform::ProcessEnvironmentChange::{LocaleChanged, TimezoneChanged};+ use moli_v8_platform::ProcessEnvironmentInvalidation::{DateTime, LocaleAndDateTime};let (runner, mut wake_rx) = runner();let notifier = runner.environment_notifier();for _ in 0..10_000 {- notifier.notify(TimezoneChanged);- notifier.notify(LocaleChanged);+ notifier.notify(DateTime);+ notifier.notify(LocaleAndDateTime);}assert!(matches!(wake_rx.try_recv(),@@ -654,32 +658,34 @@ mod tests {// Simulate JS repeatedly accepting V8 interrupts while the ordinary// owner loop has not handled the already-posted fallback wake.for _ in 0..1_000 {- notifier.notify(LocaleChanged);+ notifier.notify(LocaleAndDateTime);assert!(matches!(runner.claim_interrupt_task(),- Some(WorkerInspectorTask::EnvironmentChanged(LocaleChanged))+ Some(WorkerInspectorTask::EnvironmentInvalidation(+ LocaleAndDateTime+ ))));}assert!(wake_rx.try_recv().is_err());assert!(runner.claim_environment_for_owner().is_none());- notifier.notify(TimezoneChanged);+ notifier.notify(DateTime);assert!(matches!(wake_rx.try_recv(),Ok(super::WorkerMessage::RunEnvironmentNotification)));assert!(matches!(runner.claim_environment_for_owner(),- Some(TimezoneChanged)+ Some(DateTime)));assert!(wake_rx.try_recv().is_err());}#[test]fn pending_environment_does_not_consume_an_ordinary_command_wake() {- use moli_v8_platform::ProcessEnvironmentChange::LocaleChanged;+ use moli_v8_platform::ProcessEnvironmentInvalidation::LocaleAndDateTime;let (runner, mut wake_rx) = runner();let _command = append_protocol(&runner, 1, "Debugger.resume");- runner.environment_notifier().notify(LocaleChanged);+ runner.environment_notifier().notify(LocaleAndDateTime);assert!(matches!(wake_rx.try_recv(),Ok(super::WorkerMessage::RunInspectorTask(@@ -694,26 +700,31 @@ mod tests {wake_rx.try_recv(),Ok(super::WorkerMessage::RunEnvironmentNotification)));- assert_eq!(runner.claim_environment_for_owner(), Some(LocaleChanged));+ assert_eq!(+ runner.claim_environment_for_owner(),+ Some(LocaleAndDateTime)+ );assert!(wake_rx.try_recv().is_err());}#[test]fn environment_notifications_merge_before_pause_commands_and_are_discarded_on_disposal() {- use moli_v8_platform::ProcessEnvironmentChange::{LocaleChanged, TimezoneChanged};+ use moli_v8_platform::ProcessEnvironmentInvalidation::{DateTime, LocaleAndDateTime};let (runner, _wake_rx) = runner();let notifier = runner.environment_notifier();let _first = append_protocol(&runner, 1, "Debugger.pause");- notifier.notify(LocaleChanged);+ notifier.notify(LocaleAndDateTime);let _second = append_protocol(&runner, 2, "Debugger.resume");- notifier.notify(TimezoneChanged);+ notifier.notify(DateTime);assert!(runner.begin_pause_loop());// The pause claims one merged invalidation ahead of queued commands,// without a session or ordinary Worker-loop turn.assert!(matches!(runner.wait_for_pause_task(),- Some(WorkerInspectorTask::EnvironmentChanged(LocaleChanged))+ Some(WorkerInspectorTask::EnvironmentInvalidation(+ LocaleAndDateTime+ ))));assert!(matches!(runner.wait_for_pause_task(),@@ -723,9 +734,9 @@ mod tests {assert!(matches!(runner.wait_for_pause_task(),Some(WorkerInspectorTask::DispatchProtocolMessage { raw_json, .. })if raw_json.contains("Debugger.resume")));- notifier.notify(TimezoneChanged);+ notifier.notify(DateTime);runner.dispose("worker teardown");- notifier.notify(LocaleChanged);+ notifier.notify(LocaleAndDateTime);assert!(runner.claim_task(WorkerInspectorTaskMode::Interrupt)diff --git a/moli-renderer-v8/src/worker/thread/mod.rs b/moli-renderer-v8/src/worker/thread/mod.rsindex c8e9ac3f1..b381814ff 100644--- a/moli-renderer-v8/src/worker/thread/mod.rs+++ b/moli-renderer-v8/src/worker/thread/mod.rs@@ -1011,10 +1011,10 @@ async fn run_worker_pre_bootstrap_debugger_pause(}match rx.recv().await {Some(WorkerMessage::RunEnvironmentNotification) => {- if let Some(change) = inspector_task_runner.claim_environment_for_owner() {+ if let Some(invalidation) = inspector_task_runner.claim_environment_for_owner() {// Cache invalidation is control work, not a JS turn or a// reason to run microtasks while bootstrap is paused.- change.notify_isolate(worker_isolate.worker_isolate_mut());+ invalidation.notify_isolate(worker_isolate.worker_isolate_mut());}}Some(WorkerMessage::RunInspectorTask(mode)) => {@@ -2677,8 +2677,8 @@ async fn worker_main(}}WorkerLoopWake::Message(Some(WorkerMessage::RunEnvironmentNotification)) => {- if let Some(change) = inspector_task_runner.claim_environment_for_owner() {- change.notify_isolate(worker_isolate.worker_isolate_mut());+ if let Some(invalidation) = inspector_task_runner.claim_environment_for_owner() {+ invalidation.notify_isolate(worker_isolate.worker_isolate_mut());}}WorkerLoopWake::Message(Some(WorkerMessage::RunInspectorTask(mode))) => {diff --git a/moli-renderer-v8/src/worker/thread/runtime_inspector.rs b/moli-renderer-v8/src/worker/thread/runtime_inspector.rsindex cfea65f30..7ab3f9efc 100644--- a/moli-renderer-v8/src/worker/thread/runtime_inspector.rs+++ b/moli-renderer-v8/src/worker/thread/runtime_inspector.rs@@ -564,13 +564,15 @@ impl WorkerRuntimeInspector {// Owner messages for the two Inspector modes use separate queues. An// already-published notification must also precede DontInterrupt work// if that wake is selected before the environment fallback message.- if !matches!(task, WorkerInspectorTask::EnvironmentChanged(_))- && let Some(change) = self.task_runner.claim_environment_change()+ if !matches!(task, WorkerInspectorTask::EnvironmentInvalidation(_))+ && let Some(invalidation) = self.task_runner.claim_environment_invalidation(){- change.notify_isolate(isolate);+ invalidation.notify_isolate(isolate);}match task {- WorkerInspectorTask::EnvironmentChanged(change) => change.notify_isolate(isolate),+ WorkerInspectorTask::EnvironmentInvalidation(invalidation) => {+ invalidation.notify_isolate(isolate)+ }WorkerInspectorTask::DispatchProtocolMessage {inspector_session_id,raw_json,diff --git a/moli-v8-platform/src/environment.rs b/moli-v8-platform/src/environment.rsindex 3523b5415..b9cb294e5 100644--- a/moli-v8-platform/src/environment.rs+++ b/moli-v8-platform/src/environment.rs@@ -19,21 +19,24 @@ pub use notifications::{ProcessEnvironmentNotifications, ProcessEnvironmentNotifstatic 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. Unconsumed changes are merged;-/// only the isolate's owner may apply them, including in a nested-/// Inspector pause loop. It carries no isolate pointer or configuration lease.+/// Which native V8 caches must be refreshed against the current ICU defaults.+/// This carries no configuration value or chronological change record: pending+/// invalidations can be merged because ICU already holds the latest defaults.+/// 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,+pub enum ProcessEnvironmentInvalidation {+ /// Refresh locale-dependent caches as well as Date/Intl date-time caches.+ LocaleAndDateTime,+ /// Refresh Date/Intl date-time caches without resetting the default locale.+ DateTime,}-impl ProcessEnvironmentChange {+impl ProcessEnvironmentInvalidation {/// 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 {+ if self == Self::LocaleAndDateTime {isolate.locale_configuration_change_notification();}// Redetect would overwrite the emulated ICU timezone with the host zone.@@ -114,7 +117,7 @@ impl ProcessEnvironmentOwner {owner: self.id,value: value.to_owned(),});- publish_change(state, ProcessEnvironmentChange::LocaleChanged);+ publish_invalidation(state, ProcessEnvironmentInvalidation::LocaleAndDateTime);Ok(())}@@ -147,7 +150,7 @@ impl ProcessEnvironmentOwner {owner: self.id,value: value.to_owned(),});- publish_change(state, ProcessEnvironmentChange::TimezoneChanged);+ publish_invalidation(state, ProcessEnvironmentInvalidation::DateTime);Ok(())}@@ -220,12 +223,12 @@ fn release(owner: EnvironmentOwnerId) {debug_assert!(restored, "the original ICU timezone must be restorable");state.timezone = None;}- publish_change(+ publish_invalidation(state,if locale {- ProcessEnvironmentChange::LocaleChanged+ ProcessEnvironmentInvalidation::LocaleAndDateTime} else {- ProcessEnvironmentChange::TimezoneChanged+ ProcessEnvironmentInvalidation::DateTime},);}@@ -240,15 +243,18 @@ fn release(owner: EnvironmentOwnerId) {/// Owner observation boundaries consume pending work first; already-running JS/// may use old caches until the next notification/interrupt opportunity, as with/// Blink's asynchronous Worker notifications.-fn publish_change(+fn publish_invalidation(state: parking_lot::MutexGuard<'_, Environment>,- change: ProcessEnvironmentChange,+ invalidation: ProcessEnvironmentInvalidation,) {let owners: Vec<_> = registered_isolate_owners().into_iter().map(|owner| {let wake = owner.registration.generation.is_active()- && owner.registration.environment_notifications.publish(change);+ && owner+ .registration+ .environment_notifications+ .publish(invalidation);(owner, wake)}).collect();@@ -340,7 +346,7 @@ mod tests {assert!(rx.try_recv().is_err());assert_eq!(notifications.take(),- Some(ProcessEnvironmentChange::LocaleChanged)+ Some(ProcessEnvironmentInvalidation::LocaleAndDateTime));owner.set_locale(Some("fr_FR")).unwrap();owner.set_timezone(Some("Europe/Paris")).unwrap();@@ -355,7 +361,7 @@ mod tests {rx.try_recv().unwrap();assert_eq!(notifications.take(),- Some(ProcessEnvironmentChange::LocaleChanged)+ Some(ProcessEnvironmentInvalidation::LocaleAndDateTime));owner.release();assert!(rx.try_recv().is_err());diff --git a/moli-v8-platform/src/environment/notifications.rs b/moli-v8-platform/src/environment/notifications.rsindex 9799064ee..8194c99cb 100644--- a/moli-v8-platform/src/environment/notifications.rs+++ b/moli-v8-platform/src/environment/notifications.rs@@ -3,9 +3,9 @@ use std::sync::{atomic::{AtomicU8, Ordering},};-use super::ProcessEnvironmentChange;+use super::ProcessEnvironmentInvalidation;-const TIMEZONE: u8 = 1;+const DATE_TIME: u8 = 1;const LOCALE: u8 = 2;const CLOSED: u8 = 4;@@ -26,18 +26,18 @@ impl ProcessEnvironmentNotifications {}pub fn has_pending(&self) -> bool {- self.pending.load(Ordering::Acquire) & (LOCALE | TIMEZONE) != 0+ self.pending.load(Ordering::Acquire) & (LOCALE | DATE_TIME) != 0}/// Claim only the work published so far. A concurrent publication either/// joins this batch or remains pending for the next owner turn; it cannot/// be cleared by finishing the current notification.- pub fn take(&self) -> Option<ProcessEnvironmentChange> {+ pub fn take(&self) -> Option<ProcessEnvironmentInvalidation> {let pending = self.pending.fetch_and(CLOSED, Ordering::AcqRel);if pending & LOCALE != 0 {- Some(ProcessEnvironmentChange::LocaleChanged)- } else if pending & TIMEZONE != 0 {- Some(ProcessEnvironmentChange::TimezoneChanged)+ Some(ProcessEnvironmentInvalidation::LocaleAndDateTime)+ } else if pending & DATE_TIME != 0 {+ Some(ProcessEnvironmentInvalidation::DateTime)} else {None}@@ -49,10 +49,10 @@ impl ProcessEnvironmentNotifications {self.pending.store(CLOSED, Ordering::Release);}- fn publish(&self, change: ProcessEnvironmentChange) -> bool {- let bits = match change {- ProcessEnvironmentChange::LocaleChanged => LOCALE | TIMEZONE,- ProcessEnvironmentChange::TimezoneChanged => TIMEZONE,+ fn publish(&self, invalidation: ProcessEnvironmentInvalidation) -> bool {+ let bits = match invalidation {+ ProcessEnvironmentInvalidation::LocaleAndDateTime => LOCALE | DATE_TIME,+ ProcessEnvironmentInvalidation::DateTime => DATE_TIME,};self.pending.fetch_update(Ordering::AcqRel, Ordering::Acquire, |pending| {@@ -74,14 +74,14 @@ pub struct ProcessEnvironmentNotifier {impl ProcessEnvironmentNotifier {/// Post a cache invalidation outside a process configuration transaction./// A burst schedules a wake only on the idle-to-pending transition.- pub fn notify(&self, change: ProcessEnvironmentChange) {- if self.publish(change) {+ pub fn notify(&self, invalidation: ProcessEnvironmentInvalidation) {+ if self.publish(invalidation) {self.wake();}}- pub(super) fn publish(&self, change: ProcessEnvironmentChange) -> bool {- self.notifications.publish(change)+ pub(super) fn publish(&self, invalidation: ProcessEnvironmentInvalidation) -> bool {+ self.notifications.publish(invalidation)}pub(super) fn wake(&self) {@@ -98,7 +98,7 @@ impl ProcessEnvironmentNotifier {#[cfg(test)]mod tests {use super::*;- use ProcessEnvironmentChange::{LocaleChanged, TimezoneChanged};+ use ProcessEnvironmentInvalidation::{DateTime, LocaleAndDateTime};use std::sync::atomic::AtomicUsize;#[test]@@ -110,15 +110,15 @@ mod tests {count.fetch_add(1, Ordering::Relaxed);});for _ in 0..10_000 {- notifier.notify(TimezoneChanged);- notifier.notify(LocaleChanged);+ notifier.notify(DateTime);+ notifier.notify(LocaleAndDateTime);}assert_eq!(wakes.load(Ordering::Relaxed), 1);- assert_eq!(notifications.take(), Some(LocaleChanged));+ assert_eq!(notifications.take(), Some(LocaleAndDateTime));assert_eq!(notifications.take(), None);- notifier.notify(TimezoneChanged);+ notifier.notify(DateTime);assert_eq!(wakes.load(Ordering::Relaxed), 2);- assert_eq!(notifications.take(), Some(TimezoneChanged));+ assert_eq!(notifications.take(), Some(DateTime));}#[test]@@ -126,19 +126,19 @@ mod tests {let notifications = ProcessEnvironmentNotifications::default();let (wake_tx, wake_rx) = std::sync::mpsc::channel();let notifier = notifications.notifier(move || wake_tx.send(()).unwrap());- notifier.notify(LocaleChanged);+ notifier.notify(LocaleAndDateTime);wake_rx.try_recv().unwrap();let applying = notifications.take().unwrap();// The first invalidation has been claimed but has not finished applying.- notifier.notify(TimezoneChanged);- assert_eq!(applying, LocaleChanged);+ notifier.notify(DateTime);+ assert_eq!(applying, LocaleAndDateTime);wake_rx.try_recv().unwrap();- assert_eq!(notifications.take(), Some(TimezoneChanged));+ assert_eq!(notifications.take(), Some(DateTime));assert_eq!(notifications.take(), None);}#[test]- fn concurrent_publication_and_claim_never_lose_either_axis() {+ fn concurrent_publication_and_claim_never_lose_either_invalidation_class() {let notifications = ProcessEnvironmentNotifications::default();let barrier = std::sync::Barrier::new(2);let mut outcomes = Vec::new();@@ -146,12 +146,12 @@ mod tests {scope.spawn(|| {for _ in 0..1_000 {barrier.wait();- notifications.publish(LocaleChanged);+ notifications.publish(LocaleAndDateTime);barrier.wait();}});for _ in 0..1_000 {- notifications.publish(TimezoneChanged);+ notifications.publish(DateTime);barrier.wait();let first = notifications.take();barrier.wait();@@ -162,10 +162,10 @@ mod tests {// Check after both threads finish so a regression cannot strand the// producer at a barrier while the assertion unwinds the consumer.for (first, second, pending) in outcomes {- assert!(first == Some(LocaleChanged) || second == Some(LocaleChanged));+ assert!(first == Some(LocaleAndDateTime) || second == Some(LocaleAndDateTime));assert!(first.is_some(),- "the earlier timezone must also be consumed"+ "the earlier date-time invalidation must also be consumed");assert!(!pending);}@@ -176,14 +176,14 @@ mod tests {let notifications = ProcessEnvironmentNotifications::default();let (wake_tx, wake_rx) = std::sync::mpsc::channel();let notifier = notifications.notifier(move || wake_tx.send(()).unwrap());- assert!(notifier.publish(TimezoneChanged));- assert!(!notifier.publish(LocaleChanged));+ assert!(notifier.publish(DateTime));+ assert!(!notifier.publish(LocaleAndDateTime));notifier.wake();wake_rx.try_recv().unwrap();- assert_eq!(notifications.take(), Some(LocaleChanged));- notifier.notify(TimezoneChanged);+ assert_eq!(notifications.take(), Some(LocaleAndDateTime));+ notifier.notify(DateTime);wake_rx.try_recv().unwrap();- assert_eq!(notifications.take(), Some(TimezoneChanged));+ assert_eq!(notifications.take(), Some(DateTime));notifier.wake(); // An old delayed wake carries no configuration value.assert!(wake_rx.try_recv().is_err());}@@ -198,7 +198,7 @@ mod tests {scope.spawn(|| {for mailbox in ¬ifications {barrier.wait();- mailbox.publish(LocaleChanged);+ mailbox.publish(LocaleAndDateTime);barrier.wait();}});@@ -210,7 +210,7 @@ mod tests {});for mailbox in notifications {assert_eq!(mailbox.take(), None);- assert!(!mailbox.publish(TimezoneChanged));+ assert!(!mailbox.publish(DateTime));assert_eq!(mailbox.take(), None);}}@@ -219,12 +219,12 @@ mod tests {fn disposal_cancels_delayed_wakes_and_cannot_be_reopened() {let notifications = ProcessEnvironmentNotifications::default();let notifier = notifications.notifier(|| panic!("closed mailbox woke its owner"));- assert!(notifier.publish(LocaleChanged));+ assert!(notifier.publish(LocaleAndDateTime));let delayed = notifier.clone();notifications.close();delayed.wake();- for change in [LocaleChanged, TimezoneChanged] {- delayed.notify(change);+ for invalidation in [LocaleAndDateTime, DateTime] {+ delayed.notify(invalidation);}assert_eq!(notifications.take(), None);assert!(!notifications.has_pending());diff --git a/moli-v8-platform/src/lib.rs b/moli-v8-platform/src/lib.rsindex 82b3e980e..576c83f02 100644--- a/moli-v8-platform/src/lib.rs+++ b/moli-v8-platform/src/lib.rs@@ -25,7 +25,7 @@ mod cpu_tracing;mod environment;pub use environment::{- ProcessEnvironmentChange, ProcessEnvironmentNotifications, ProcessEnvironmentNotifier,+ ProcessEnvironmentInvalidation, ProcessEnvironmentNotifications, ProcessEnvironmentNotifier,ProcessEnvironmentOwner,};@@ -338,7 +338,7 @@ impl V8PlatformIsolateRegistration {// 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);+ ProcessEnvironmentInvalidation::LocaleAndDateTime.notify_isolate(isolate);Self {isolate_ptr: AtomicCell::new(isolate_ptr),generation,@@ -589,7 +589,7 @@ mod tests {};owner.unregister();- notifier.notify(ProcessEnvironmentChange::LocaleChanged);+ notifier.notify(ProcessEnvironmentInvalidation::LocaleAndDateTime);assert_eq!(notifications.take(),None,