Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

fix(renderer): reclaim collected child surface cache entries

ldm0622beac0894e
diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/document.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/document.rs
index 11699b2b3..ebc6b9c77 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/document.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/document.rs
@@ -197,6 +197,17 @@ impl JsContextHost {
.set_detached_content_window(scope, handle, window);
}
+ #[cfg(test)]
+ pub(crate) fn detached_content_surface_cache_counts_for_test(&self) -> [usize; 6] {
+ self.child_window_proxy_records
+ .detached_content_surface_cache_counts_for_test()
+ }
+
+ pub(crate) fn prune_collected_iframe_content_surfaces(&mut self) {
+ self.child_window_proxy_records
+ .prune_collected_detached_content_surfaces();
+ }
+
pub(crate) fn clear_cached_detached_iframe_content_surfaces(&mut self, handle: DomHandle) {
self.child_window_proxy_records
.clear_detached_content_surfaces(handle);
diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window.rs
index 4d6d5d825..54e4a7c45 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window.rs
@@ -396,6 +396,47 @@ impl ChildWindowProxyRecords {
.insert(handle, v8::Weak::new(scope, window));
}
+ pub(in crate::native_bridge::context_host) fn prune_collected_detached_content_surfaces(
+ &mut self,
+ ) {
+ for cache in [
+ &mut self.detached_content_window_wrappers,
+ &mut self.detached_content_document_wrappers,
+ ] {
+ // Run after V8 returns, without a Host borrow spanning GC. Empty
+ // Weak handles still own native control blocks until they drop.
+ cache.retain(|_, wrapper| !wrapper.is_empty());
+ if cache.is_empty() {
+ *cache = HashMap::new();
+ } else if cache.len() <= cache.capacity() / 4 {
+ // Keep author-reachable identities; only rehash sparse maps.
+ cache.shrink_to_fit();
+ }
+ }
+ }
+
+ #[cfg(test)]
+ pub(in crate::native_bridge::context_host) fn detached_content_surface_cache_counts_for_test(
+ &self,
+ ) -> [usize; 6] {
+ // Window entries/dead targets, Document entries/dead targets, then map capacities.
+ // is_empty() neither creates V8 locals nor makes an author-unreachable target live.
+ [
+ self.detached_content_window_wrappers.len(),
+ self.detached_content_window_wrappers
+ .values()
+ .filter(|wrapper| wrapper.is_empty())
+ .count(),
+ self.detached_content_document_wrappers.len(),
+ self.detached_content_document_wrappers
+ .values()
+ .filter(|wrapper| wrapper.is_empty())
+ .count(),
+ self.detached_content_window_wrappers.capacity(),
+ self.detached_content_document_wrappers.capacity(),
+ ]
+ }
+
pub(in crate::native_bridge::context_host) fn clear_detached_content_surfaces(
&mut self,
handle: DomHandle,
diff --git a/moli-renderer-v8/src/script_vm/runtime_observability.rs b/moli-renderer-v8/src/script_vm/runtime_observability.rs
index 839399edd..d16e06097 100644
--- a/moli-renderer-v8/src/script_vm/runtime_observability.rs
+++ b/moli-renderer-v8/src/script_vm/runtime_observability.rs
@@ -457,7 +457,11 @@ impl ScriptVm {
isolate.memory_pressure_notification(v8::MemoryPressureLevel::Critical);
isolate.low_memory_notification();
Ok(())
- })
+ })?;
+ self._context_host
+ .borrow_mut()
+ .prune_collected_iframe_content_surfaces();
+ Ok(())
}
pub(super) fn notify_renderer_document_isolate_memory_pressure(&mut self) -> Result<()> {
@@ -479,7 +483,11 @@ impl ScriptVm {
isolate.memory_pressure_notification(v8::MemoryPressureLevel::Moderate);
}
Ok(())
- })
+ })?;
+ self._context_host
+ .borrow_mut()
+ .prune_collected_iframe_content_surfaces();
+ Ok(())
}
pub(super) fn snapshot_console_messages_in_context(
diff --git a/moli-renderer-v8/src/script_vm/tests/extracted/child_realm_retention.rs b/moli-renderer-v8/src/script_vm/tests/extracted/child_realm_retention.rs
index c2e2d7ff7..e50a2e36a 100644
--- a/moli-renderer-v8/src/script_vm/tests/extracted/child_realm_retention.rs
+++ b/moli-renderer-v8/src/script_vm/tests/extracted/child_realm_retention.rs
@@ -192,7 +192,11 @@ fn detached_iframe_projection_keeps_its_cached_surfaces_across_gc() {
"#,
)
.unwrap();
- collected_native_context_count(&mut vm);
+ for _ in 0..2 {
+ vm.collect_renderer_document_isolate_garbage().unwrap();
+ }
+ vm.notify_renderer_document_isolate_memory_pressure()
+ .unwrap();
assert_eq!(
vm.eval(
r#"
@@ -208,3 +212,131 @@ fn detached_iframe_projection_keeps_its_cached_surfaces_across_gc() {
r#"[42,43,true,"kept"]"#
);
}
+
+fn churn_child_content_surfaces_for_inventory(vm: &mut StandaloneScriptVmHarness, count: usize) {
+ for _ in 0..count {
+ vm.eval(
+ r#"
+ (() => {
+ const frame = document.createElement('iframe');
+ document.body.append(frame);
+ const child = frame.contentDocument;
+ child.body.textContent = 'retire this child';
+ if (frame.contentWindow.document !== child) throw new Error('identity');
+ frame.remove();
+ return 'removed';
+ })()
+ "#,
+ )
+ .expect("create, expose and normally detach child content surfaces");
+ vm.prune_stale_child_default_execution_contexts();
+ }
+}
+
+fn detached_content_surface_inventory(vm: &StandaloneScriptVmHarness) -> [usize; 6] {
+ vm._context_host
+ .borrow()
+ .detached_content_surface_cache_counts_for_test()
+}
+
+#[test]
+fn collected_child_content_surface_caches_release_entries_and_capacity() {
+ for policy in [LayoutPolicy::Mock, LayoutPolicy::OnDemand] {
+ let mut vm = new_parsed_test_vm(
+ "https://weak-content-inventory.test/",
+ "<!doctype html><body></body>",
+ );
+ vm.set_layout_policy(policy);
+ let baseline_contexts = collected_native_context_count(&mut vm);
+ assert_eq!(detached_content_surface_inventory(&vm), [0; 6]);
+ for _ in 0..2 {
+ churn_child_content_surfaces_for_inventory(&mut vm, 4);
+ assert_eq!(vm.child_frame_realm_store.len(), 0, "{policy:?}");
+ assert_eq!(
+ collected_native_context_count(&mut vm),
+ baseline_contexts,
+ "{policy:?}: a dead Weak entry is not a live Realm"
+ );
+ vm.collect_renderer_document_isolate_garbage()
+ .expect("explicit collection also cleans native child surface caches");
+ assert_eq!(
+ detached_content_surface_inventory(&vm),
+ [0; 6],
+ "{policy:?}: release dead Weak control blocks and empty backing storage"
+ );
+ }
+ }
+}
+
+#[test]
+fn child_content_surface_maintenance_preserves_author_identity() {
+ for policy in [LayoutPolicy::Mock, LayoutPolicy::OnDemand] {
+ let mut vm = new_parsed_test_vm(
+ "https://weak-content-author-identity.test/",
+ "<!doctype html><body></body>",
+ );
+ vm.set_layout_policy(policy);
+ let baseline_contexts = collected_native_context_count(&mut vm);
+ assert_eq!(
+ detached_content_surface_inventory(&vm),
+ [0; 6],
+ "fresh fixture has no child surface cache"
+ );
+ vm.eval(
+ r#"
+ (() => {
+ const frame = document.createElement('iframe');
+ document.body.append(frame);
+ const child = frame.contentDocument;
+ child.body.innerHTML = '<p id="kept">before</p>';
+ child.authorMarker = 42;
+ globalThis.savedChildDocument = child;
+ globalThis.savedChildWindow = frame.contentWindow;
+ savedChildWindow.authorMarker = 43;
+ globalThis.savedChildNode = child.getElementById('kept');
+ frame.remove();
+ return 'retained';
+ })()
+ "#,
+ )
+ .expect("hold author-owned content surfaces across normal child detachment");
+ vm.prune_stale_child_default_execution_contexts();
+ churn_child_content_surfaces_for_inventory(&mut vm, 4);
+ assert!(collected_native_context_count(&mut vm) > baseline_contexts);
+ vm.notify_renderer_document_isolate_memory_pressure()
+ .expect("existing owner maintenance prunes already collected targets");
+ assert_eq!(
+ detached_content_surface_inventory(&vm)[..4],
+ [1, 0, 1, 0],
+ "{policy:?}: keep only the author-held Window and Document identities"
+ );
+ assert_eq!(
+ vm.eval(
+ r#"
+ savedChildNode.textContent = 'after';
+ JSON.stringify([
+ savedChildDocument.authorMarker,
+ savedChildWindow.authorMarker,
+ savedChildDocument.getElementById('kept') === savedChildNode,
+ savedChildNode.ownerDocument === savedChildDocument,
+ savedChildWindow.document === savedChildDocument,
+ savedChildDocument.body.textContent
+ ])
+ "#,
+ )
+ .expect("GC of unrelated children preserves author-held identity and state"),
+ r#"[42,43,true,true,true,"after"]"#,
+ "{policy:?}"
+ );
+ vm.eval("savedChildDocument = savedChildWindow = savedChildNode = undefined; 'released'")
+ .expect("release the remaining author references");
+ assert_eq!(collected_native_context_count(&mut vm), baseline_contexts);
+ vm.notify_renderer_document_isolate_memory_pressure()
+ .expect("reclaim native cache storage after the last author reference");
+ assert_eq!(
+ detached_content_surface_inventory(&vm),
+ [0; 6],
+ "{policy:?}: maintenance releases dead entries and backing storage"
+ );
+ }
+}