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(cdp-smoke): retain debugger-wait load events during Runtime.enable
ldm0f702d9a65dc6
diff --git a/moli-cdp-smoke/README.md b/moli-cdp-smoke/README.mdindex 1e22f9639..8d8a016cd 100644--- a/moli-cdp-smoke/README.md+++ b/moli-cdp-smoke/README.md@@ -337,6 +337,21 @@ Chromium source revision `a03603fe9af6` was also inspected to explain theaccess-mode and auto-attach machinery; the executable probe remains thebehavioral authority.+The real-URL debugger-wait lifecycle contract was checked again on 2026-10-20+against Playwright 1.58.0's Chrome for Testing 145.0.7632.6, matching CI.+The probe creates the script-free `/semantic-frames?debugger-wait=1` target+under `waitForDebuggerOnStart`, enables Page lifecycle events and Runtime, and+then sends `Runtime.runIfWaitingForDebugger`. Chromium can emit the requested+main document's `load` before replying to `Runtime.enable`; the attach event's+`waitingForDebugger=true` does not guarantee that this HTML load waits for the+explicit resume. Retain events from both Runtime commands and require the+owning session, main frame, and the committed frame tree's loader. The initial+document load check and child document checks still apply. With four browsers+restricted to two CPUs, discarding the Runtime-enable batch caused 3/300+timeouts; retaining it passed 300/300, including three loads from that batch.+Repeat the whole group with+`--browser chromium --group target-semantics --repeat 30 --jobs 4`.+The expanded `multi-page` group was calibrated again on 2026-08-31 againstDebian `/usr/bin/chromium` 145.0.7632.116 and local Chromium source revision`a03603fe9af6`. Five new executable contracts cover target-local Debuggerdiff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/target_semantics.py b/moli-cdp-smoke/moli_cdp_smoke/groups/target_semantics.pyindex 6f881cdfe..4849a683a 100644--- a/moli-cdp-smoke/moli_cdp_smoke/groups/target_semantics.py+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/target_semantics.py@@ -76,7 +76,7 @@ def _raw_semantic_contracts() -> tuple[RawSemanticContract, ...]:),RawSemanticContract("raw_cdp_contract_created_target_debugger_wait_lifecycle",- "A real-URL target created under waitForDebuggerOnStart does not expose an internal about:blank load; after Runtime.runIfWaitingForDebugger, the requested main-frame load includes its child-frame document.",+ "A real-URL target created under waitForDebuggerOnStart does not expose an internal about:blank load; after Runtime.runIfWaitingForDebugger, its requested document and child frames are loaded, including when the main load arrives during Runtime.enable.","Chromium behavior and CDP Target/Page lifecycle ordering",["Target.setAutoAttach",@@ -325,8 +325,15 @@ async def _raw_wait_for_event(while True:remaining = deadline - asyncio.get_running_loop().time()if remaining <= 0:- raise SmokeError(f"timed out waiting for {method}; seen={seen[-20:]}")- message = await asyncio.wait_for(client.recv(), timeout=remaining)+ raise SmokeError(+ f"timed out waiting for {method} session={session_id}; seen={seen[-20:]}"+ )+ try:+ message = await asyncio.wait_for(client.recv(), timeout=remaining)+ except TimeoutError as error:+ raise SmokeError(+ f"timed out waiting for {method} session={session_id}; seen={seen[-20:]}"+ ) from errorseen.append(message)if matches(message):return message@@ -1095,18 +1102,21 @@ async def _created_target_debugger_wait_lifecycle()stage = "resume requested document"- await _raw_command(client, "Runtime.enable", session_id=session_id)+ _, runtime_seen = await _raw_command(client, "Runtime.enable", session_id=session_id)_, resume_seen = await _raw_command(client,"Runtime.runIfWaitingForDebugger",session_id=session_id,)+ # Chromium can finish loading this script-free page during Runtime.enable.+ # Keep its interleaved events even when they precede the explicit resume.main_load = await _raw_wait_for_event(client,"Page.lifecycleEvent",lambda params: params.get("frameId") == target_idand params.get("name") == "load",- resume_seen,+ [*runtime_seen, *resume_seen],+ session_id=session_id,)stage = "read committed frame tree"@@ -1117,6 +1127,11 @@ async def _created_target_debugger_wait_lifecycle()root = frame_tree.get("frameTree", {})assert_equal(root.get("frame", {}).get("url"), target_url, "main frame URL")+ assert_equal(+ main_load["params"].get("loaderId"),+ root.get("frame", {}).get("loaderId"),+ "main load loader",+ )child_urls = [child.get("frame", {}).get("url")for child in root.get("childFrames", [])@@ -1150,6 +1165,7 @@ async def _created_target_debugger_wait_lifecycle(return {"preResumeMainLoadCount": len(premature_main_loads),"mainLoadLoaderId": main_load["params"].get("loaderId"),+ "loadObservedDuringRuntimeEnable": main_load in runtime_seen,"childUrls": child_urls,"childTexts": child_texts,}diff --git a/moli-cdp-smoke/tests/test_target_semantics.py b/moli-cdp-smoke/tests/test_target_semantics.pynew file mode 100644index 000000000..4f3951130--- /dev/null+++ b/moli-cdp-smoke/tests/test_target_semantics.py@@ -0,0 +1,170 @@+from __future__ import annotations++import asyncio+import json+import unittest+from typing import Any+from unittest.mock import AsyncMock, patch++from moli_cdp_smoke.assertions import SmokeError+from moli_cdp_smoke.groups import target_semantics+from moli_cdp_smoke.raw_cdp import RawCdpClient+++FIXTURE = "http://fixture.test"+SESSION = "page-session"+TARGET = "page-target"+LOADER = "requested-loader"+++def lifecycle(frame: str = TARGET, loader: str = LOADER, session: str = SESSION) -> dict[str, Any]:+ return {+ "method": "Page.lifecycleEvent",+ "sessionId": session,+ "params": {"frameId": frame, "loaderId": loader, "name": "load"},+ }+++class _TargetSocket:+ def __init__(+ self,+ phase: str,+ *,+ loader: str = LOADER,+ foreign_loads: bool = False,+ child_texts: list[str | None] | None = None,+ ) -> None:+ self.phase = phase+ self.loader = loader+ self.foreign_loads = foreign_loads+ self.child_texts = child_texts if child_texts is not None else ["child first", "child second"]+ self.messages: asyncio.Queue[str] = asyncio.Queue()+ self.commands: list[dict[str, Any]] = []+ self.closed = False++ async def send(self, raw: str) -> None:+ command = json.loads(raw)+ self.commands.append(command)+ method = command["method"]+ before: list[dict[str, Any]] = []+ after: list[dict[str, Any]] = []+ result: dict[str, Any] = {}+ if method == "Target.createBrowserContext":+ result = {"browserContextId": "context"}+ elif method == "Target.createTarget":+ result = {"targetId": TARGET}+ before.append({+ "method": "Target.attachedToTarget",+ "params": {+ "sessionId": SESSION,+ "waitingForDebugger": True,+ "targetInfo": {+ "targetId": TARGET,+ "url": f"{FIXTURE}/semantic-frames?debugger-wait=1",+ },+ },+ })+ elif method == "Page.setLifecycleEventsEnabled" and self.phase == "initial-document":+ before.append(lifecycle(loader="initial-about-blank-loader"))+ elif method == "Runtime.enable":+ if self.foreign_loads:+ before.extend([lifecycle(frame="child-frame"), lifecycle(session="other-session")])+ if self.phase == "runtime-enable":+ # Chromium's actual failure order: requested main load before+ # the Runtime.enable response, followed by a normal resume ACK.+ before.append(lifecycle(loader=self.loader))+ elif method == "Runtime.runIfWaitingForDebugger":+ if self.phase == "resume-before-reply":+ before.append(lifecycle(loader=self.loader))+ elif self.phase == "resume-after-reply":+ after.append(lifecycle(loader=self.loader))+ elif method == "Page.getFrameTree":+ result = {+ "frameTree": {+ "frame": {+ "id": TARGET,+ "loaderId": LOADER,+ "url": f"{FIXTURE}/semantic-frames?debugger-wait=1",+ },+ "childFrames": [+ {"frame": {+ "url": f"{FIXTURE}/semantic-frame-child?child=first&nested=1",+ }},+ {"frame": {"url": f"{FIXTURE}/semantic-frame-child?child=second"}},+ ],+ },+ }+ elif method == "Runtime.evaluate":+ result = {"result": {"value": self.child_texts}}+ response: dict[str, Any] = {"id": command["id"], "result": result}+ if "sessionId" in command:+ response["sessionId"] = command["sessionId"]+ for message in [*before, response, *after]:+ self.messages.put_nowait(json.dumps(message))++ async def recv(self) -> str:+ return await self.messages.get()++ async def close(self) -> None:+ self.closed = True+++class CreatedTargetLifecycleTests(unittest.IsolatedAsyncioTestCase):+ async def run_scenario(self, socket: _TargetSocket) -> dict[str, Any]:+ client = RawCdpClient(websocket=socket) # type: ignore[arg-type]+ wait_for_event = target_semantics._raw_wait_for_event++ async def bounded_wait(*args: Any, **kwargs: Any) -> dict[str, Any]:+ return await wait_for_event(*args, **kwargs, timeout=0.01)++ with (+ patch.object(target_semantics, "connect_raw_cdp", AsyncMock(return_value=client)),+ patch.object(target_semantics, "_raw_wait_for_event", bounded_wait),+ ):+ return await target_semantics._created_target_debugger_wait_lifecycle("http://browser", FIXTURE)++ async def test_main_load_is_retained_across_command_response_boundaries(self) -> None:+ for phase in ["runtime-enable", "resume-before-reply", "resume-after-reply"]:+ with self.subTest(phase=phase):+ socket = _TargetSocket(phase)+ observed = await self.run_scenario(socket)+ self.assertEqual(observed["mainLoadLoaderId"], LOADER)+ self.assertEqual(observed["childTexts"], ["child first", "child second"])+ self.assertEqual(observed["loadObservedDuringRuntimeEnable"], phase == "runtime-enable")+ self.assertIn("Runtime.runIfWaitingForDebugger", [c["method"] for c in socket.commands])+ self.assertTrue(socket.closed)++ async def test_child_and_foreign_session_loads_do_not_satisfy_main_load(self) -> None:+ socket = _TargetSocket("resume-after-reply", foreign_loads=True)+ observed = await self.run_scenario(socket)+ self.assertEqual(observed["mainLoadLoaderId"], LOADER)+ self.assertFalse(observed["loadObservedDuringRuntimeEnable"])++ async def test_a_different_loader_does_not_satisfy_the_requested_navigation(self) -> None:+ socket = _TargetSocket("runtime-enable", loader="stale-loader")+ with self.assertRaisesRegex(SmokeError, "main load loader"):+ await self.run_scenario(socket)+ self.assertTrue(socket.closed)++ async def test_initial_placeholder_load_is_still_rejected(self) -> None:+ socket = _TargetSocket("initial-document")+ with self.assertRaisesRegex(SmokeError, "internal initial document"):+ await self.run_scenario(socket)+ self.assertNotIn("Runtime.runIfWaitingForDebugger", [c["method"] for c in socket.commands])+ self.assertTrue(socket.closed)++ async def test_missing_load_reports_the_expected_event_and_session(self) -> None:+ socket = _TargetSocket("missing", foreign_loads=True)+ with self.assertRaisesRegex(SmokeError, "Page.lifecycleEvent.*page-session"):+ await self.run_scenario(socket)+ self.assertTrue(socket.closed)++ async def test_child_documents_must_still_be_loaded(self) -> None:+ socket = _TargetSocket("resume-after-reply", child_texts=["child first", None])+ with self.assertRaisesRegex(SmokeError, "child frame documents"):+ await self.run_scenario(socket)+ self.assertTrue(socket.closed)+++if __name__ == "__main__":+ unittest.main()