Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
fix(performance): preserve receiver timeline across borrowed methods
ldm01ef06b739227
diff --git a/moli-renderer-v8/src/common_runtime.rs b/moli-renderer-v8/src/common_runtime.rsindex fadd6a2f4..faaa08f23 100644--- a/moli-renderer-v8/src/common_runtime.rs+++ b/moli-renderer-v8/src/common_runtime.rs@@ -41,7 +41,12 @@ impl CommonRuntimeState {/// host. Retained backing state and callback execution permission remain/// separate: asynchronous callbacks must still revalidate their identities.pub(crate) fn from_scope(scope: &mut v8::PinScope<'_, '_>) -> Option<Rc<Self>> {- let context = scope.get_current_context();+ Self::from_context(scope.get_current_context())+ }++ /// Native components for an explicit target Realm. Borrowed methods must+ /// resolve the receiver's owner rather than the method's current Context.+ pub(crate) fn from_context(context: v8::Local<'_, v8::Context>) -> Option<Rc<Self>> {let binding = context.get_slot::<CommonRuntimeBinding>()?;let (runtime, _) = binding.resolve_owner(context)?;Some(runtime)@@ -278,9 +283,14 @@ mod tests {let scope = &mut v8::ContextScope::new(scope, other);let (binding, _) = CommonRuntimeBinding::from_scope(scope).unwrap();assert!(!Rc::ptr_eq(&binding.runtime().unwrap(), &common));+ assert!(Rc::ptr_eq(+ &CommonRuntimeState::from_context(first).unwrap(),+ &common+ ));other_lifecycle.set(ContextHostLifecycle::Destroyed);assert!(CommonRuntimeBinding::from_scope(scope).is_none());assert!(CommonRuntimeState::from_scope(scope).is_none());+ assert!(CommonRuntimeState::from_context(other).is_none());// A previously resolved owner is not a cached execution permit.assert!(binding.callback_execution_context(scope).is_none());}diff --git a/moli-renderer-v8/src/common_runtime/callback_registry.rs b/moli-renderer-v8/src/common_runtime/callback_registry.rsindex bd0acc744..7e87808f6 100644--- a/moli-renderer-v8/src/common_runtime/callback_registry.rs+++ b/moli-renderer-v8/src/common_runtime/callback_registry.rs@@ -354,13 +354,13 @@ impl CallbackRegistry {pub(crate) fn active_performance_observers<'s>(&self,scope: &mut v8::PinScope<'s, '_>,+ timeline_context: v8::Local<'s, v8::Context>,) -> Vec<v8::Local<'s, v8::Object>> {let roots: Vec<_> = self.state.borrow().active.values().map(Rc::clone).collect();- let context = scope.get_current_context();roots.iter().map(|root| v8::Local::new(scope, root.as_ref()))- .filter(|observer| observer.get_creation_context(scope) == Some(context))+ .filter(|observer| observer.get_creation_context(scope) == Some(timeline_context)).collect()}diff --git a/moli-renderer-v8/src/context_bootstrap/performance_observer_runtime/delivery.rs b/moli-renderer-v8/src/context_bootstrap/performance_observer_runtime/delivery.rsindex d391113b3..5a118d323 100644--- a/moli-renderer-v8/src/context_bootstrap/performance_observer_runtime/delivery.rs+++ b/moli-renderer-v8/src/context_bootstrap/performance_observer_runtime/delivery.rs@@ -65,13 +65,9 @@ fn performance_observer_flush_callback<'s>(pub(super) fn enqueue_buffered_performance_entries<'s>(scope: &mut v8::PinScope<'s, '_>,+ performance: v8::Local<'s, v8::Object>,observer: v8::Local<'s, v8::Object>,) {- let Some(performance) =- super::super::performance_runtime::ensure_current_performance_for_api(scope)- else {- return;- };let Some(entries) = performance_slot_array(scope, performance, PERFORMANCE_ENTRIES_SLOT) else {return;};@@ -94,10 +90,15 @@ pub(super) fn enqueue_buffered_performance_entries<'s>(pub(in crate::context_bootstrap) fn queue_matching_performance_observers<'s>(scope: &mut v8::PinScope<'s, '_>,+ performance: v8::Local<'s, v8::Object>,entry: v8::Local<'s, v8::Object>,entry_type: &str,) {- for observer in active_performance_observers(scope) {+ let Some(timeline_context) = performance.get_creation_context(scope) else {+ return;+ };+ let scope = &mut v8::ContextScope::new(scope, timeline_context);+ for observer in active_performance_observers(scope, timeline_context) {if !performance_observer_callback_is_current(scope, observer) {let pending = v8::Array::new(scope, 0);set_performance_observer_pending(scope, observer, pending);@@ -121,6 +122,13 @@ pub(super) fn queue_performance_observer_delivery<'s>(scope: &mut v8::PinScope<'s, '_>,observer: v8::Local<'s, v8::Object>,) {+ let Some(context) = observer.get_creation_context(scope) else {+ return;+ };+ // The queue and native flush trampoline belong to the observer's global,+ // even when observe() was borrowed from another Realm. Callback Realm+ // entry remains the shared Web IDL execution layer's responsibility.+ let scope = &mut v8::ContextScope::new(scope, context);if performance_observer_scheduled(scope, observer) {return;}diff --git a/moli-renderer-v8/src/context_bootstrap/performance_observer_runtime/observer.rs b/moli-renderer-v8/src/context_bootstrap/performance_observer_runtime/observer.rsindex c6dde5aaa..31b69b21d 100644--- a/moli-renderer-v8/src/context_bootstrap/performance_observer_runtime/observer.rs+++ b/moli-renderer-v8/src/context_bootstrap/performance_observer_runtime/observer.rs@@ -199,6 +199,12 @@ pub(in crate::context_bootstrap) fn performance_observer_observe_callback<'s>(rv.set_undefined();return;}+ let Some(context) = args.this().get_creation_context(scope) else {+ return;+ };+ // Web IDL conversion and option validation above use the method Realm.+ // Registration, buffered records and delivery use the observer's global.+ let scope = &mut v8::ContextScope::new(scope, context);let performance = super::super::performance_runtime::ensure_current_performance_for_api(scope);let observes_navigation = (0..observed_entry_types.length()).any(|index| {observed_entry_types@@ -212,15 +218,13 @@ pub(in crate::context_bootstrap) fn performance_observer_observe_callback<'s>(performance,);}- set_performance_observer_type(- scope,- args.this(),- init.observed_type- .as_deref()- .and_then(|value| v8_string(scope, value))- .map(|value| value.into())- .unwrap_or_else(|| v8::null(scope).into()),- );+ let observed_type = init+ .observed_type+ .as_deref()+ .and_then(|value| v8_string(scope, value))+ .map(|value| value.into())+ .unwrap_or_else(|| v8::null(scope).into());+ set_performance_observer_type(scope, args.this(), observed_type);set_performance_observer_entry_types(scope, args.this(), observed_entry_types);let activated = PerformanceObserverRegistration::from_observer(scope, args.this()).is_some_and(|registration| registration.activate(scope));@@ -233,7 +237,9 @@ pub(in crate::context_bootstrap) fn performance_observer_observe_callback<'s>(}set_performance_observer_active(scope, args.this(), true);if init.buffered.unwrap_or(false) && has_type_member {- enqueue_buffered_performance_entries(scope, args.this());+ if let Some(performance) = performance {+ enqueue_buffered_performance_entries(scope, performance, args.this());+ }queue_performance_observer_delivery(scope, args.this());}rv.set_undefined();diff --git a/moli-renderer-v8/src/context_bootstrap/performance_observer_runtime/registration.rs b/moli-renderer-v8/src/context_bootstrap/performance_observer_runtime/registration.rsindex 86252cb27..350cde7b7 100644--- a/moli-renderer-v8/src/context_bootstrap/performance_observer_runtime/registration.rs+++ b/moli-renderer-v8/src/context_bootstrap/performance_observer_runtime/registration.rs@@ -49,10 +49,11 @@ impl<'s> PerformanceObserverRegistration<'s> {) -> Option<Self> {let id = get_private_value(scope, observer, PERFORMANCE_OBSERVER_CALLBACK_ID_SLOT)?.number_value(scope)?;+ let context = observer.get_creation_context(scope)?;Some(Self {observer,id: CallbackRegistrationId::from_number(id)?,- common: CommonRuntimeState::from_scope(scope)?,+ common: CommonRuntimeState::from_context(context)?,})}@@ -108,8 +109,13 @@ pub(super) fn performance_observer_callback_is_current<'s>(pub(super) fn active_performance_observers<'s>(scope: &mut v8::PinScope<'s, '_>,+ timeline_context: v8::Local<'s, v8::Context>,) -> Vec<v8::Local<'s, v8::Object>> {- CommonRuntimeState::from_scope(scope)- .map(|common| common.callbacks.active_performance_observers(scope))+ CommonRuntimeState::from_context(timeline_context)+ .map(|common| {+ common+ .callbacks+ .active_performance_observers(scope, timeline_context)+ }).unwrap_or_default()}diff --git a/moli-renderer-v8/src/context_bootstrap/performance_runtime.rs b/moli-renderer-v8/src/context_bootstrap/performance_runtime.rsindex a0d322c8e..90c589eb8 100644--- a/moli-renderer-v8/src/context_bootstrap/performance_runtime.rs+++ b/moli-renderer-v8/src/context_bootstrap/performance_runtime.rs@@ -402,8 +402,15 @@ fn append_resource_performance_entry<'s>() {let start_time = entry.start_unix_millis.unwrap_or_else(unix_epoch_millis)- performance_slot_number(scope, performance, PERFORMANCE_TIME_ORIGIN_SLOT).unwrap_or(0.0);- let resource =- entries::create_performance_entry(scope, "resource", &entry.name, start_time, 0.0, None);+ let resource = entries::create_performance_entry(+ scope,+ performance,+ "resource",+ &entry.name,+ start_time,+ 0.0,+ None,+ );initialize_resource_timing_slots(scope,resource,diff --git a/moli-renderer-v8/src/context_bootstrap/performance_runtime/entries.rs b/moli-renderer-v8/src/context_bootstrap/performance_runtime/entries.rsindex 67dfb76bc..cf8af2545 100644--- a/moli-renderer-v8/src/context_bootstrap/performance_runtime/entries.rs+++ b/moli-renderer-v8/src/context_bootstrap/performance_runtime/entries.rs@@ -785,12 +785,17 @@ pub(super) fn find_latest_performance_mark_start<'s>(pub(super) fn create_performance_entry<'s>(scope: &mut v8::PinScope<'s, '_>,+ performance: v8::Local<'s, v8::Object>,entry_type: &str,name: &str,start_time: f64,duration: f64,detail: Option<v8::Local<'s, v8::Value>>,) -> v8::Local<'s, v8::Object> {+ let context = performance+ .get_creation_context(scope)+ .expect("native Performance must retain its relevant Realm");+ let scope = &mut v8::ContextScope::new(scope, context);let detail = detail.unwrap_or_else(|| v8::null(scope).into());let entry = PerformanceEntryObjectDeclaration {id: 0.0,@@ -848,6 +853,10 @@ pub(super) fn push_performance_entry<'s>(performance: v8::Local<'s, v8::Object>,entry: v8::Local<'s, v8::Object>,) {+ let Some(context) = performance.get_creation_context(scope) else {+ return;+ };+ let scope = &mut v8::ContextScope::new(scope, context);if super::install::is_window_performance(scope, performance) {super::install::ensure_navigation_performance_entry(scope, performance);}@@ -855,12 +864,12 @@ pub(super) fn push_performance_entry<'s>(let entry_type = performance_entry_slot_string(scope, entry, PERFORMANCE_ENTRY_TYPE_SLOT).unwrap_or_default();if entry_type == "resource" {- queue_matching_performance_observers(scope, entry, &entry_type);+ queue_matching_performance_observers(scope, performance, entry, &entry_type);super::resource_buffer::add_resource_timing_entry(scope, performance, entry);return;}append_performance_entry(scope, performance, entry);- queue_matching_performance_observers(scope, entry, &entry_type);+ queue_matching_performance_observers(scope, performance, entry, &entry_type);}pub(super) fn assign_navigation_performance_entry_identity<'s>(diff --git a/moli-renderer-v8/src/context_bootstrap/performance_runtime/install.rs b/moli-renderer-v8/src/context_bootstrap/performance_runtime/install.rsindex a916ff403..938af359c 100644--- a/moli-renderer-v8/src/context_bootstrap/performance_runtime/install.rs+++ b/moli-renderer-v8/src/context_bootstrap/performance_runtime/install.rs@@ -685,10 +685,11 @@ fn performance_navigation_entry_name<'s>(fn create_navigation_performance_entry<'s>(scope: &mut v8::PinScope<'s, '_>,+ performance: v8::Local<'s, v8::Object>,navigation_type: &str,name: &str,) -> v8::Local<'s, v8::Object> {- let entry = create_performance_entry(scope, "navigation", name, 0.0, 0.0, None);+ let entry = create_performance_entry(scope, performance, "navigation", name, 0.0, 0.0, None);super::entries::initialize_resource_timing_slots(scope,entry,@@ -829,7 +830,7 @@ fn apply_load_end<'s>(// PerformanceNavigationTiming.duration is loadEventEnd relative to timeOrigin.set_performance_entry_slot_number(scope, entry, PERFORMANCE_ENTRY_DURATION_SLOT, timestamp);if notify_observers {- queue_matching_performance_observers(scope, entry, "navigation");+ queue_matching_performance_observers(scope, performance, entry, "navigation");}}}@@ -896,7 +897,7 @@ pub(super) fn ensure_navigation_performance_entry<'s>(.and_then(|value| value.to_string(scope)).map(|value| value.to_rust_string_lossy(scope)).unwrap_or_else(|| "document".to_owned());- let entry = create_navigation_performance_entry(scope, &navigation_type, &name);+ let entry = create_navigation_performance_entry(scope, performance, &navigation_type, &name);super::entries::assign_navigation_performance_entry_identity(scope, performance, entry);set_private_value(scope,diff --git a/moli-renderer-v8/src/context_bootstrap/performance_runtime/marks_measures.rs b/moli-renderer-v8/src/context_bootstrap/performance_runtime/marks_measures.rsindex 1a2b690b5..b47b7dbc5 100644--- a/moli-renderer-v8/src/context_bootstrap/performance_runtime/marks_measures.rs+++ b/moli-renderer-v8/src/context_bootstrap/performance_runtime/marks_measures.rs@@ -3,7 +3,7 @@ use super::entries::{initialize_performance_entry_slots,};use super::*;-use crate::context_bootstrap::structured_clone_value;+use crate::context_bootstrap::{structured_deserialize_value, structured_serialize_value};use crate::util::serialize_v8_iter_array;use crate::webidl;@@ -95,7 +95,15 @@ pub(in crate::context_bootstrap) fn performance_mark_callback<'s>(else {return;};- let entry = create_performance_entry(scope, "mark", &parsed.name, start_time, 0.0, detail);+ let entry = create_performance_entry(+ scope,+ performance,+ "mark",+ &parsed.name,+ start_time,+ 0.0,+ detail,+ );push_performance_entry(scope, performance, entry);rv.set(entry.into());}@@ -196,7 +204,7 @@ fn prepare_performance_mark<'s>();return None;}- clone_user_timing_detail(scope, options.detail).map(|detail| (start_time, detail))+ clone_user_timing_detail(scope, performance, options.detail).map(|detail| (start_time, detail))}pub(in crate::context_bootstrap) fn performance_clear_marks_callback<'s>(@@ -275,12 +283,13 @@ pub(in crate::context_bootstrap) fn performance_measure_callback<'s>(Some(duration) => (start, start + duration),None => (start, end),};- let detail = match clone_user_timing_detail(scope, parsed_measure.detail) {+ let detail = match clone_user_timing_detail(scope, performance, parsed_measure.detail) {Some(detail) => detail,None => return,};let entry = create_performance_entry(scope,+ performance,"measure",&parsed.name,start_time,@@ -571,10 +580,19 @@ fn resolve_named_measure_boundary<'s>(fn clone_user_timing_detail<'s>(scope: &mut v8::PinScope<'s, '_>,+ performance: v8::Local<'s, v8::Object>,detail: Option<v8::Local<'s, v8::Value>>,) -> Option<Option<v8::Local<'s, v8::Value>>> {match detail {- Some(detail) => structured_clone_value(scope, detail).map(Some),+ Some(detail) => {+ // Serialization can invoke getters or throw DataCloneError. Keep+ // those exceptions in the method Realm; only the clone's native+ // objects and prototypes are created in the receiver's Realm.+ let payload = structured_serialize_value(scope, detail)?;+ let context = performance.get_creation_context(scope)?;+ let scope = &mut v8::ContextScope::new(scope, context);+ structured_deserialize_value(scope, &payload).map(Some)+ }None => Some(None),}}diff --git a/moli-renderer-v8/src/script_vm/tests/observer_callbacks.rs b/moli-renderer-v8/src/script_vm/tests/observer_callbacks.rsindex 158bb272d..435cae282 100644--- a/moli-renderer-v8/src/script_vm/tests/observer_callbacks.rs+++ b/moli-renderer-v8/src/script_vm/tests/observer_callbacks.rs@@ -20,6 +20,74 @@ fn observer_callback_test_vm(url: &str) -> StandaloneScriptVmHarness {vm}+#[test]+fn borrowed_performance_methods_use_receiver_timeline_and_entry_realms() {+ let mut vm = observer_callback_test_vm("https://performance-borrowed-method-realms.test/");+ let source = format!(+ "({})(window, __observerCallbackFrame.contentWindow).then(result => globalThis.__borrowedTimeline = result, error => globalThis.__borrowedTimeline = {{ error: String(error) }});",+ include_str!("performance_timeline_borrowed_methods.js"),+ );+ vm.eval(&source)+ .expect("queue borrowed mark and measure deliveries");+ assert_eq!(+ vm.eval("JSON.stringify(__borrowedTimeline)").unwrap(),+ r#"{"received":{"parent":["parent-mark","parent-measure"],"child":["child-mark","child-measure"]},"failures":[]}"#,+ );+}++#[test]+fn borrowed_performance_observe_reads_and_delivers_the_observers_own_buffer() {+ let mut vm = observer_callback_test_vm("https://performance-borrowed-buffered-observe.test/");+ vm.eval(+ r#"+(() => {+ const child = __observerCallbackFrame.contentWindow;+ globalThis.__borrowedBuffered = { parent: [], child: [] };+ performance.mark('parent-buffered');+ child.performance.mark('child-buffered');+ const parentObserver = new PerformanceObserver(list => {+ __borrowedBuffered.parent.push(...list.getEntries().map(entry => entry.name));+ });+ const childObserver = new child.PerformanceObserver(list => {+ __borrowedBuffered.child.push(...list.getEntries().map(entry => entry.name));+ });+ child.PerformanceObserver.prototype.observe.call(parentObserver, { type: 'mark', buffered: true });+ PerformanceObserver.prototype.observe.call(childObserver, { type: 'mark', buffered: true });+})()+"#,+ )+ .expect("subscribe to buffers using the other Realm's observe method");+ assert_eq!(+ vm.eval("JSON.stringify(__borrowedBuffered)").unwrap(),+ r#"{"parent":["parent-buffered"],"child":["child-buffered"]}"#,+ );+}++#[test]+fn borrowed_performance_delivery_survives_retirement_of_the_method_realm() {+ let mut vm = observer_callback_test_vm("https://performance-method-realm-retirement.test/");+ vm.eval(+ r#"+(() => {+ const child = __observerCallbackFrame.contentWindow;+ globalThis.__survivingTimeline = [];+ new PerformanceObserver(list => {+ __survivingTimeline.push(...list.getEntries().map(entry => entry.name));+ }).observe({ type: 'mark' });+ const mark = child.Performance.prototype.mark;+ mark.call(performance, 'before-method-realm-retirement');+ __observerCallbackFrame.remove();+ mark.call(performance, 'after-method-realm-retirement');+})()+"#,+ )+ .expect("retire the method Realm after queuing to the surviving timeline");+ assert_eq!(+ vm.eval("JSON.stringify(__survivingTimeline)").unwrap(),+ r#"["before-method-realm-retirement","after-method-realm-retirement"]"#,+ );+}+#[test]fn common_callback_registry_keeps_active_observers_until_owner_teardown() {let mut vm = new_storage_test_vm("https://performance-observer-active-root.test/");diff --git a/moli-renderer-v8/src/script_vm/tests/performance_timeline_borrowed_methods.js b/moli-renderer-v8/src/script_vm/tests/performance_timeline_borrowed_methods.jsnew file mode 100644index 000000000..ff41bbd04--- /dev/null+++ b/moli-renderer-v8/src/script_vm/tests/performance_timeline_borrowed_methods.js@@ -0,0 +1,62 @@+(async (parent, child) => {+ const result = { received: { parent: [], child: [] }, failures: [] };+ const check = (name, condition) => {+ if (!condition) result.failures.push(name);+ };+ let acknowledge;+ let delivered = 0;+ const delivery = new Promise(resolve => acknowledge = resolve);+ const observers = [parent, child].map((owner, index) => {+ const label = index ? 'child' : 'parent';+ const accept = (list, localList) => {+ check(label + '/delivery-list-realm', localList);+ result.received[label].push(...list.getEntries().map(entry => entry.name).sort());+ if (++delivered === 2) acknowledge();+ };+ const callback = owner.Function('accept', `return function(list) {+ accept(list, list instanceof PerformanceObserverEntryList);+ };`)(accept);+ const observer = new owner.PerformanceObserver(callback);+ observer.observe({ entryTypes: ['mark', 'measure'] });+ return observer;+ });+ for (const [callee, owner, label] of [[parent, child, 'child'], [child, parent, 'parent']]) {+ const markMethod = callee.Performance.prototype.mark;+ const measureMethod = callee.Performance.prototype.measure;+ const detail = { nested: [] };+ const mark = markMethod.call(owner.performance, label + '-mark', { startTime: 10, detail });+ const measure = measureMethod.call(owner.performance, label + '-measure', {+ start: label + '-mark', end: 20, detail+ });+ for (const [kind, entry] of [['mark', mark], ['measure', measure]]) {+ const type = kind === 'mark' ? 'PerformanceMark' : 'PerformanceMeasure';+ check(label + '/' + kind + '/prototype', Object.getPrototypeOf(entry) === owner[type].prototype);+ check(label + '/' + kind + '/detail-realm', entry.detail instanceof owner.Object);+ check(label + '/' + kind + '/nested-realm', entry.detail.nested instanceof owner.Array);+ check(label + '/' + kind + '/cloned-detail', entry.detail !== detail && entry.detail.nested !== detail.nested);+ check(label + '/' + kind + '/buffer-identity', owner.performance.getEntriesByName(entry.name)[0] === entry);+ }+ check(label + '/measure-boundaries', measure.startTime === 10 && measure.duration === 10);+ for (const [kind, name, invoke] of [+ ['negative-mark', 'TypeError', () => markMethod.call(owner.performance, 'negative', { startTime: -1 })],+ ['nonfinite-mark', 'TypeError', () => markMethod.call(owner.performance, 'nonfinite', { startTime: NaN })],+ ['invalid-measure', 'TypeError', () => measureMethod.call(owner.performance, 'invalid', { duration: 1 })],+ ['clone-mark', 'DataCloneError', () => markMethod.call(owner.performance, 'clone', { detail: () => {} })],+ ['clone-measure', 'DataCloneError', () => measureMethod.call(owner.performance, 'clone', { start: 0, end: 1, detail: () => {} })],+ ]) {+ let error;+ try { invoke(); } catch (caught) { error = caught; }+ check(label + '/' + kind + '/error-realm', error && error.name === name &&+ error instanceof callee[name === 'TypeError' ? 'TypeError' : 'DOMException']);+ }+ const sentinel = new callee.Error('detail getter');+ let caught;+ try {+ markMethod.call(owner.performance, 'getter', { detail: { get value() { throw sentinel; } } });+ } catch (error) { caught = error; }+ check(label + '/detail-getter-exception-identity', caught === sentinel);+ }+ await delivery;+ for (const observer of observers) observer.disconnect();+ return result;+})