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(benchmark): isolate WPT CDP case execution
ldm092c1722f0f79
diff --git a/moli-benchmark/moli_benchmark/wpt_cross/__main__.py b/moli-benchmark/moli_benchmark/wpt_cross/__main__.pyindex 8539d3aa2..e8e0442e9 100644--- a/moli-benchmark/moli_benchmark/wpt_cross/__main__.py+++ b/moli-benchmark/moli_benchmark/wpt_cross/__main__.py@@ -54,7 +54,7 @@ from ..config import clear_current_proxy_envREPO_CASE_LIST_DIR = Path(__file__).resolve().parents[2] / "wpt-cross-current"WPT_CROSS_CASE_TIMEOUT_SECONDS = 120.0-WPT_CROSS_PARALLELISM = 100+WPT_CROSS_PARALLELISM = 50WPT_CROSS_PROFILES = ("default","layout-testharness",@@ -81,6 +81,16 @@ NON_TRUSTWORTHY_ORIGIN_CASES = frozenset()+def _positive_parallelism(value: str) -> int:+ try:+ parsed = int(value)+ except ValueError as error:+ raise argparse.ArgumentTypeError("parallelism must be an integer") from error+ if parsed <= 0:+ raise argparse.ArgumentTypeError("parallelism must be positive")+ return parsed++def _case_requires_trustworthy_origin(case_path: str) -> bool:file_part = case_path.split("?", 1)[0].split("#", 1)[0]return ".https." in file_part or file_part.endswith(".https.html")@@ -197,6 +207,15 @@ def _build_parser() -> argparse.ArgumentParser:default=30.0,help="Per-engine launch (CDP ready) timeout in seconds.",)+ parser.add_argument(+ "--parallelism",+ type=_positive_parallelism,+ default=WPT_CROSS_PARALLELISM,+ help=(+ "Maximum concurrent engine workers for WPT cases "+ f"(default: {WPT_CROSS_PARALLELISM})."+ ),+ )parser.add_argument("--moli-bin",type=str,@@ -789,14 +808,14 @@ def main(argv: list[str] | None = None) -> int:execution_cases=scheduled_cases_for_engine_cli,binary_override=_binary_override_for(engine, args),case_timeout_seconds=engine_case_timeout,- parallelism=WPT_CROSS_PARALLELISM,+ parallelism=args.parallelism,)else:print(f"[wpt-cross] running {engine} (CDP mode) on {len(cases_for_engine)} cases via fixture origins",file=sys.stderr,)- cdp_par = WPT_CROSS_PARALLELISM+ cdp_par = args.parallelismif cdp_par == 1 or len(cases_for_engine) <= 1:result = run_engine_on_cases(driver=driver,diff --git a/moli-benchmark/moli_benchmark/wpt_cross/runner.py b/moli-benchmark/moli_benchmark/wpt_cross/runner.pyindex c058fb346..1d84c7e9a 100644--- a/moli-benchmark/moli_benchmark/wpt_cross/runner.py+++ b/moli-benchmark/moli_benchmark/wpt_cross/runner.py@@ -21,6 +21,7 @@ import timefrom dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Any+from urllib.parse import quote, urlsplit, urlunsplitfrom PIL import Image, ImageChops@@ -140,6 +141,22 @@ class _PageSessionUnusable(RuntimeError):super().__init__(case_result.error or "page session became unusable")+@dataclass(frozen=True)+class _AttachedPage:+ browser_context_id: str | None+ target_id: str+ session_id: str+ baseline_target_ids: frozenset[str] | None+++@dataclass(frozen=True)+class _NavigationIdentity:+ session_id: str+ frame_id: str+ loader_id: str+ expected_url: str++_TRACE_METHODS = {"Runtime.consoleAPICalled", "Runtime.exceptionThrown", "Log.entryAdded"}@@ -212,101 +229,323 @@ def _failure_names(tests: Any) -> list[str]:return names+def _exception_text(error: BaseException) -> str:+ return str(error) or type(error).__name__+++async def _target_infos(client: RawCdpClient) -> list[dict[str, Any]]:+ command_id = await client.send("Target.getTargets")+ response, _ = await client.recv_until_id(command_id, timeout=5)+ infos = (response.get("result") or {}).get("targetInfos")+ if not isinstance(infos, list):+ raise RawCdpError(f"Target.getTargets returned invalid targetInfos: {response}")+ return [info for info in infos if isinstance(info, dict)]+++def _target_ids(infos: list[dict[str, Any]]) -> frozenset[str]:+ return frozenset(+ target_id+ for info in infos+ if isinstance((target_id := info.get("targetId")), str) and target_id+ )+++async def _close_target(client: RawCdpClient, target_id: str) -> None:+ command_id = await client.send("Target.closeTarget", {"targetId": target_id})+ response, _ = await client.recv_until_id(command_id, timeout=5)+ success = (response.get("result") or {}).get("success")+ if success is False:+ raise RawCdpError(f"Target.closeTarget rejected target {target_id}")+++async def _close_page(client: RawCdpClient, page: _AttachedPage) -> None:+ """Dispose one case's storage context and every target created inside it."""++ try:+ before = await _target_infos(client)+ except (RawCdpError, asyncio.TimeoutError):+ before = []++ if page.browser_context_id is not None:+ command_id = await client.send(+ "Target.disposeBrowserContext",+ {"browserContextId": page.browser_context_id},+ )+ await client.recv_until_id(command_id, timeout=10)+ else:+ owned_ids = {+ target_id+ for info in before+ if isinstance((target_id := info.get("targetId")), str)+ and target_id+ and (+ target_id == page.target_id+ or (+ page.baseline_target_ids is not None+ and target_id not in page.baseline_target_ids+ )+ )+ }+ owned_ids.add(page.target_id)+ for target_id in sorted(owned_ids):+ await _close_target(client, target_id)++ try:+ after = await _target_infos(client)+ except (RawCdpError, asyncio.TimeoutError):+ return++ residual_ids = {+ target_id+ for info in after+ if isinstance((target_id := info.get("targetId")), str)+ and target_id+ and (+ (+ page.browser_context_id is not None+ and info.get("browserContextId") == page.browser_context_id+ )+ or (+ page.browser_context_id is None+ and (+ target_id == page.target_id+ or (+ page.baseline_target_ids is not None+ and target_id not in page.baseline_target_ids+ )+ )+ )+ )+ }+ for target_id in sorted(residual_ids):+ await _close_target(client, target_id)++ if residual_ids:+ remaining = _target_ids(await _target_infos(client))+ leaked = residual_ids & remaining+ if leaked:+ raise RawCdpError(+ f"case cleanup left auxiliary targets alive: {sorted(leaked)}"+ )++async def _attach_page(client: RawCdpClient,*,viewport: Viewport | None = None,-) -> str:- """Create a fresh BrowserContext + Target and return its sessionId.+) -> _AttachedPage:+ """Create an isolated BrowserContext + Target for exactly one WPT case."""- Falls back to the default target if Target.createBrowserContext is not- supported. Enables Runtime/Page/Log so we can collect harness results- and console errors.- """+ try:+ baseline_target_ids: frozenset[str] | None = _target_ids(+ await _target_infos(client)+ )+ except (RawCdpError, asyncio.TimeoutError):+ baseline_target_ids = Nonebrowser_context_id: str | None = None+ target: str | None = Nonetry:- ctx_id = await client.send("Target.createBrowserContext")- ctx_resp, _ = await client.recv_until_id(ctx_id, timeout=5)- value = (ctx_resp.get("result") or {}).get("browserContextId")- if isinstance(value, str) and value:- browser_context_id = value- except RawCdpError:- browser_context_id = None- except asyncio.TimeoutError:- browser_context_id = None-- target_params: dict[str, Any] = {"url": "about:blank"}- if browser_context_id:- target_params["browserContextId"] = browser_context_id- target_id = await client.send("Target.createTarget", target_params)- target_resp, _ = await client.recv_until_id(target_id, timeout=10)- target = (target_resp.get("result") or {}).get("targetId")- if not isinstance(target, str) or not target:- raise RuntimeError(f"missing targetId in createTarget response: {target_resp}")-- attach_id = await client.send("Target.attachToTarget", {"targetId": target, "flatten": True})- attach_resp, _ = await client.recv_until_id(attach_id, timeout=5)- session_id = (attach_resp.get("result") or {}).get("sessionId")- if not isinstance(session_id, str) or not session_id:- raise RuntimeError(f"missing sessionId in attachToTarget response: {attach_resp}")-- for method in ("Runtime.enable", "Page.enable"):- cmd_id = await client.send(method, session_id=session_id)- await client.recv_until_id(cmd_id, timeout=5)- if viewport is not None:- cmd_id = await client.send(- "Emulation.setDeviceMetricsOverride",- {- "width": viewport.width,- "height": viewport.height,- "deviceScaleFactor": viewport.device_scale_factor,- "mobile": False,- },- session_id=session_id,+ try:+ ctx_id = await client.send("Target.createBrowserContext")+ ctx_resp, _ = await client.recv_until_id(ctx_id, timeout=5)+ value = (ctx_resp.get("result") or {}).get("browserContextId")+ if isinstance(value, str) and value:+ browser_context_id = value+ except (RawCdpError, asyncio.TimeoutError):+ browser_context_id = None++ target_params: dict[str, Any] = {"url": "about:blank"}+ if browser_context_id:+ target_params["browserContextId"] = browser_context_id+ target_id = await client.send("Target.createTarget", target_params)+ target_resp, _ = await client.recv_until_id(target_id, timeout=10)+ target = (target_resp.get("result") or {}).get("targetId")+ if not isinstance(target, str) or not target:+ raise RuntimeError(f"missing targetId in createTarget response: {target_resp}")++ attach_id = await client.send(+ "Target.attachToTarget", {"targetId": target, "flatten": True})- await client.recv_until_id(cmd_id, timeout=5)- for method in ("Log.enable",):+ attach_resp, _ = await client.recv_until_id(attach_id, timeout=5)+ session_id = (attach_resp.get("result") or {}).get("sessionId")+ if not isinstance(session_id, str) or not session_id:+ raise RuntimeError(f"missing sessionId in attachToTarget response: {attach_resp}")++ for method, params in (+ ("Runtime.enable", None),+ ("Page.enable", None),+ ("Page.setLifecycleEventsEnabled", {"enabled": True}),+ ):+ cmd_id = await client.send(method, params, session_id=session_id)+ await client.recv_until_id(cmd_id, timeout=5)+ if viewport is not None:+ cmd_id = await client.send(+ "Emulation.setDeviceMetricsOverride",+ {+ "width": viewport.width,+ "height": viewport.height,+ "deviceScaleFactor": viewport.device_scale_factor,+ "mobile": False,+ },+ session_id=session_id,+ )+ await client.recv_until_id(cmd_id, timeout=5)try:- cmd_id = await client.send(method, session_id=session_id)+ cmd_id = await client.send("Log.enable", session_id=session_id)await client.recv_until_id(cmd_id, timeout=3)except (RawCdpError, asyncio.TimeoutError):pass- return session_id+ return _AttachedPage(+ browser_context_id=browser_context_id,+ target_id=target,+ session_id=session_id,+ baseline_target_ids=baseline_target_ids,+ )+ except BaseException:+ if target is not None:+ try:+ await _close_page(+ client,+ _AttachedPage(+ browser_context_id=browser_context_id,+ target_id=target,+ session_id="",+ baseline_target_ids=baseline_target_ids,+ ),+ )+ except BaseException:+ pass+ elif browser_context_id is not None:+ try:+ command_id = await client.send(+ "Target.disposeBrowserContext",+ {"browserContextId": browser_context_id},+ )+ await client.recv_until_id(command_id, timeout=5)+ except BaseException:+ pass+ raise_HARNESS_PROBE_EXPRESSION = """(function() {- if (typeof window === 'undefined') return null;- if (typeof window.__bench_wpt__ === 'undefined') return null;- return window.__bench_wpt__;-})()-"""--_BRIDGE_INSTALLED_EXPRESSION = """-(function() {- var t = (typeof window !== 'undefined') ? window.__bench_wpt_trace__ : null;- if (!Array.isArray(t)) return false;- for (var i = 0; i < t.length; i++) {- if (t[i] && t[i].installing === true) return true;+ if (typeof window === 'undefined' || typeof location === 'undefined') return null;+ var trace = window.__bench_wpt_trace__;+ var bridgeInstalled = false;+ if (Array.isArray(trace)) {+ for (var i = 0; i < trace.length; i++) {+ if (trace[i] && trace[i].installing === true) {+ bridgeInstalled = true;+ break;+ }+ }}- return false;+ return {+ bridgeInstalled: bridgeInstalled,+ payload: typeof window.__bench_wpt__ === 'undefined' ? null : window.__bench_wpt__+ };})()"""-async def _bridge_installed(client: RawCdpClient, session_id: str) -> bool:- try:- eval_id = await client.send(- "Runtime.evaluate",- {"expression": _BRIDGE_INSTALLED_EXPRESSION, "returnByValue": True},- session_id=session_id,+def _normalized_case_path(value: str) -> str:+ parts = urlsplit(value)+ path = quote(parts.path.lstrip("/"), safe="/%:@!$&'()*+,;=-._~")+ query = quote(parts.query, safe="=&?/%:@!$'()*+,;[-]._~")+ return urlunsplit(("", "", path, query, ""))+++def _normalized_navigation_url(value: str) -> str:+ parts = urlsplit(value)+ path = quote(parts.path or "/", safe="/%:@!$&'()*+,;=-._~")+ query = quote(parts.query, safe="=&?/%:@!$'()*+,;[-]._~")+ return urlunsplit(+ (+ parts.scheme.lower(),+ parts.netloc.lower(),+ path,+ query,+ "",)- response, _ = await client.recv_until_id(eval_id, timeout=5)- except (RawCdpError, asyncio.TimeoutError):- return False- return bool(((response.get("result") or {}).get("result") or {}).get("value"))+ )+++def _navigation_identity(+ response: dict[str, Any],+ *,+ session_id: str,+ expected_url: str,+) -> _NavigationIdentity:+ response_session = response.get("sessionId")+ if response_session is not None and response_session != session_id:+ raise RawCdpError(+ f"Page.navigate response belonged to session {response_session!r}, "+ f"expected {session_id!r}"+ )+ result = response.get("result")+ if not isinstance(result, dict):+ raise RawCdpError(f"Page.navigate returned no result: {response}")+ error_text = result.get("errorText")+ if isinstance(error_text, str) and error_text:+ raise RawCdpError(f"Page.navigate failed for `{expected_url}`: {error_text}")+ if result.get("isDownload") is True:+ raise RawCdpError(f"Page.navigate produced a download for `{expected_url}`")+ frame_id = result.get("frameId")+ loader_id = result.get("loaderId")+ if not isinstance(frame_id, str) or not frame_id:+ raise RawCdpError(f"Page.navigate returned no frameId: {response}")+ if not isinstance(loader_id, str) or not loader_id:+ raise RawCdpError(f"Page.navigate returned no loaderId: {response}")+ return _NavigationIdentity(+ session_id=session_id,+ frame_id=frame_id,+ loader_id=loader_id,+ expected_url=expected_url,+ )+++def _navigation_commit_url(+ messages: list[dict[str, Any]], identity: _NavigationIdentity+) -> str | None:+ for message in messages:+ if message.get("sessionId") != identity.session_id:+ continue+ if message.get("method") != "Page.frameNavigated":+ continue+ frame = (message.get("params") or {}).get("frame") or {}+ if (+ frame.get("id") == identity.frame_id+ and frame.get("loaderId") == identity.loader_id+ and isinstance(frame.get("url"), str)+ ):+ return frame["url"]+ return None+++def _has_navigation_evidence(+ messages: list[dict[str, Any]], identity: _NavigationIdentity+) -> bool:+ committed_url = _navigation_commit_url(messages, identity)+ return committed_url is not None and (+ _normalized_navigation_url(committed_url)+ == _normalized_navigation_url(identity.expected_url)+ )+++def _navigation_commit_error(+ identity: _NavigationIdentity, committed_url: str | None+) -> str | None:+ if committed_url is None or (+ _normalized_navigation_url(committed_url)+ == _normalized_navigation_url(identity.expected_url)+ ):+ return None+ return (+ f"Page.navigate committed loader {identity.loader_id} to unexpected URL "+ f"`{committed_url}`; expected `{identity.expected_url}`"+ )async def _run_one_case(@@ -318,11 +557,20 @@ async def _run_one_case(timeout_seconds: float,) -> CaseResult:started = time.perf_counter()+ deadline = started + timeout_secondsseen_messages: list[dict[str, Any]] = []try:nav_id = await client.send("Page.navigate", {"url": url}, session_id=session_id)- _, nav_seen = await client.recv_until_id(nav_id, timeout=timeout_seconds)+ nav_response, nav_seen = await client.recv_until_id(+ nav_id,+ timeout=max(0.01, deadline - time.perf_counter()),+ )seen_messages.extend(nav_seen)+ identity = _navigation_identity(+ nav_response,+ session_id=session_id,+ expected_url=url,+ )except (RawCdpError, asyncio.TimeoutError) as error:raise _PageSessionUnusable(CaseResult(@@ -330,12 +578,25 @@ async def _run_one_case(url=url,status="error",duration_ms=(time.perf_counter() - started) * 1000.0,- error=f"navigate failed: {error}",+ error=f"navigate failed: {_exception_text(error)}",)) from error- deadline = time.perf_counter() + timeout_secondspayload: Any = None+ bridge_installed = False+ committed_url = _navigation_commit_url(seen_messages, identity)+ commit_error = _navigation_commit_error(identity, committed_url)+ if commit_error is not None:+ return CaseResult(+ case_path=case_path,+ url=url,+ status="error",+ duration_ms=(time.perf_counter() - started) * 1000.0,+ error=commit_error,+ )+ navigation_observed = committed_url is not None+ expected_case_path = _normalized_case_path(case_path)+ last_payload_case_path: str | None = Nonewhile time.perf_counter() < deadline:try:eval_id = await client.send(@@ -347,7 +608,10 @@ async def _run_one_case(},session_id=session_id,)- response, eval_seen = await client.recv_until_id(eval_id, timeout=5)+ response, eval_seen = await client.recv_until_id(+ eval_id,+ timeout=max(0.01, min(5.0, deadline - time.perf_counter())),+ )seen_messages.extend(eval_seen)except (RawCdpError, asyncio.TimeoutError) as error:raise _PageSessionUnusable(@@ -356,25 +620,65 @@ async def _run_one_case(url=url,status="error",duration_ms=(time.perf_counter() - started) * 1000.0,- error=f"evaluate failed: {error}",+ error=f"evaluate failed: {_exception_text(error)}",)) from error+ if committed_url is None:+ committed_url = _navigation_commit_url(eval_seen, identity)+ commit_error = _navigation_commit_error(identity, committed_url)+ if commit_error is not None:+ return CaseResult(+ case_path=case_path,+ url=url,+ status="error",+ duration_ms=(time.perf_counter() - started) * 1000.0,+ error=commit_error,+ )+ navigation_observed = committed_url is not Noneresult = ((response.get("result") or {}).get("result") or {})value = result.get("value")if isinstance(value, dict):- source = value.get("source") if isinstance(value.get("source"), str) else None- payload = value- if source in FINAL_PAYLOAD_SOURCES:- break+ if navigation_observed:+ bridge_installed = bridge_installed or value.get("bridgeInstalled") is True+ candidate = value.get("payload")+ if isinstance(candidate, dict):+ # A bridge payload is stronger evidence than the optional+ # trace array: some pages replace or mutate the trace after+ # the bridge has already published its terminal snapshot.+ bridge_installed = True+ candidate_case_path = candidate.get("case_path")+ if isinstance(candidate_case_path, str):+ last_payload_case_path = candidate_case_path+ if (+ isinstance(candidate_case_path, str)+ and _normalized_case_path(candidate_case_path)+ == expected_case_path+ ):+ source = (+ candidate.get("source")+ if isinstance(candidate.get("source"), str)+ else None+ )+ payload = candidate+ if source in FINAL_PAYLOAD_SOURCES:+ breakawait asyncio.sleep(0.05)duration_ms = (time.perf_counter() - started) * 1000.0console_errors, js_exceptions = _count_traces(seen_messages)- # Distinguish "bridge never installed" (engine couldn't load- # testharness.js at all) from "bridge installed but testharness never- # produced results" (engine-side completion bug). A non-final payload also- # proves the bridge was installed, but it is not enough to pass the case.- bridge_installed = payload is not None or await _bridge_installed(client, session_id)+ error: str | None = None+ if not navigation_observed:+ error = (+ "Page.navigate returned loader/frame identity but no matching "+ "navigation event was observed"+ )+ elif last_payload_case_path is not None and (+ _normalized_case_path(last_payload_case_path) != expected_case_path+ ):+ error = (+ f"ignored harness payload for `{last_payload_case_path}` while "+ f"waiting for `{case_path}`"+ )return classify_payload(payload=payload if isinstance(payload, dict) else None,case_path=case_path,@@ -383,6 +687,7 @@ async def _run_one_case(bridge_installed=bridge_installed,console_errors=console_errors,js_exceptions=js_exceptions,+ error=error,)@@ -486,6 +791,8 @@ async def _wait_for_reftest_ready(session_id: str,url: str,timeout_seconds: float,+ identity: _NavigationIdentity,+ navigation_observed: bool,) -> tuple[dict[str, Any], list[dict[str, Any]]]:deadline = time.perf_counter() + timeout_secondsseen_messages: list[dict[str, Any]] = []@@ -504,6 +811,9 @@ async def _wait_for_reftest_ready(timeout=max(0.01, min(5.0, remaining)),)seen_messages.extend(messages)+ navigation_observed = navigation_observed or _has_navigation_evidence(+ messages, identity+ )except (RawCdpError, asyncio.TimeoutError):await asyncio.sleep(0.025)continue@@ -511,6 +821,7 @@ async def _wait_for_reftest_ready(if (isinstance(value, dict)and value.get("href") == value.get("expectedHref")+ and navigation_observed):breakawait asyncio.sleep(0.025)@@ -531,9 +842,24 @@ async def _wait_for_reftest_ready()response, messages = await client.recv_until_id(eval_id, timeout=remaining)seen_messages.extend(messages)+ navigation_observed = navigation_observed or _has_navigation_evidence(+ messages, identity+ )value = _remote_object_value(response)if not isinstance(value, dict):raise RuntimeError(f"reftest readiness script failed for {url}: {response}")+ if not navigation_observed:+ raise RuntimeError(+ f"reftest observed no navigation event for frame={identity.frame_id} "+ f"loader={identity.loader_id}"+ )+ href = value.get("href")+ if not isinstance(href, str) or (+ _normalized_navigation_url(href) != _normalized_navigation_url(url)+ ):+ raise RuntimeError(+ f"reftest committed to unexpected URL {href!r}; expected {url!r}"+ )return value, seen_messages@@ -549,15 +875,19 @@ async def _navigate_and_capture_reftest(nav_id = await client.send("Page.navigate", {"url": url}, session_id=session_id)nav_response, nav_seen = await client.recv_until_id(nav_id, timeout=timeout_seconds)seen_messages.extend(nav_seen)- nav_result = nav_response.get("result") or {}- if nav_result.get("errorText"):- raise RuntimeError(f"navigation failed for {url}: {nav_result['errorText']}")+ identity = _navigation_identity(+ nav_response,+ session_id=session_id,+ expected_url=url,+ )ready, ready_seen = await _wait_for_reftest_ready(client,session_id,url,timeout_seconds,+ identity,+ _has_navigation_evidence(nav_seen, identity),)seen_messages.extend(ready_seen)actual_viewport = (ready.get("width"), ready.get("height"))@@ -1059,7 +1389,7 @@ async def _run_async(effective_viewport = LAYOUT_VIEWPORTtry:- session_id = await _attach_page(client, viewport=effective_viewport)+ page = await _attach_page(client, viewport=effective_viewport)except Exception as error:result.setup_error = f"attach failed: {error}"try:@@ -1113,13 +1443,13 @@ async def _run_async(continueconsecutive_relaunch_failures = 0relaunch_count += 1- # swap in new handle/client/session+ # Swap in a fresh engine and the isolated page for its next case.try:await client.websocket.close()except Exception:passdriver.shutdown(handle) # ensure old handle fully reaped- handle, client, session_id = relaunched+ handle, client, page = relaunchedreference_cache.clear()continue@@ -1129,7 +1459,7 @@ async def _run_async(raise RuntimeError("reftest requires a fixed viewport")case_result = await _run_one_reftest(client=client,- session_id=session_id,+ session_id=page.session_id,case=case,viewport=effective_viewport,engine=driver.name,@@ -1139,7 +1469,7 @@ async def _run_async(else:case_result = await _run_one_case(client=client,- session_id=session_id,+ session_id=page.session_id,case_path=case_path,url=url,timeout_seconds=timeout_seconds,@@ -1177,6 +1507,7 @@ async def _run_async(except Exception:passdriver.shutdown(handle)+ page = Nonerelaunched = await _try_relaunch(driver=driver,binary_override=binary_override,@@ -1199,7 +1530,7 @@ async def _run_async(break# client/handle are dead; fabricate placeholders that will fail# the poll() check next iteration -> retry relaunch path.- handle, client, session_id = await _wait_then_retry_launch(+ handle, client, page = await _wait_then_retry_launch(driver,binary_override,launch_timeout_seconds,@@ -1216,13 +1547,59 @@ async def _run_async(consecutive_relaunch_failures = 0relaunch_count += 1if relaunched is not None:- handle, client, session_id = relaunched+ handle, client, page = relaunchedreference_cache.clear()continueconsecutive_relaunch_failures = 0result.cases.append(case_result)+ if case_index + 1 < len(cases):+ try:+ await _close_page(client, page)+ page = await _attach_page(client, viewport=effective_viewport)+ except Exception:+ # The completed case keeps its result, but no later case may+ # inherit an incompletely disposed context or target set.+ try:+ await client.websocket.close()+ except Exception:+ pass+ driver.shutdown(handle)+ page = None+ relaunched = await _try_relaunch(+ driver=driver,+ binary_override=binary_override,+ launch_timeout_seconds=launch_timeout_seconds,+ viewport=effective_viewport,+ )+ relaunch_count += 1+ if relaunched is None:+ for remaining in cases[case_index + 1:]:+ rp, ru, _ = _case_parts(+ remaining, case_timeout_seconds+ )+ result.cases.append(+ CaseResult(+ case_path=rp,+ url=ru,+ status="crash",+ duration_ms=None,+ error=(+ "fresh page setup failed after case cleanup; "+ "engine relaunch also failed"+ ),+ test_type=_case_test_type(remaining),+ )+ )+ break+ handle, client, page = relaunched+ reference_cache.clear()finally:+ if page is not None:+ try:+ await _close_page(client, page)+ except Exception:+ passtry:await client.websocket.close()except Exception:@@ -1240,7 +1617,7 @@ async def _try_relaunch(binary_override: str | None,launch_timeout_seconds: float,viewport: Viewport | None,-) -> tuple[EngineDriverHandle, RawCdpClient, str] | None:+) -> tuple[EngineDriverHandle, RawCdpClient, _AttachedPage] | None:"""Relaunch engine + reconnect CDP + reattach. Returns None on failure."""try:@@ -1259,7 +1636,7 @@ async def _try_relaunch(passreturn Nonetry:- new_session_id = await _attach_page(new_client, viewport=viewport)+ new_page = await _attach_page(new_client, viewport=viewport)except Exception:try:await new_client.websocket.close()@@ -1270,7 +1647,7 @@ async def _try_relaunch(except Exception:passreturn None- return new_handle, new_client, new_session_id+ return new_handle, new_client, new_pageasync def _wait_then_retry_launch(@@ -1282,7 +1659,7 @@ async def _wait_then_retry_launch(case_index: int,case_timeout_seconds: float,viewport: Viewport | None,-) -> tuple[EngineDriverHandle | None, RawCdpClient | None, str | None]:+) -> tuple[EngineDriverHandle | None, RawCdpClient | None, _AttachedPage | None]:await asyncio.sleep(1.0)relaunched = await _try_relaunch(driver=driver,diff --git a/moli-benchmark/moli_benchmark/wpt_cross/server.py b/moli-benchmark/moli_benchmark/wpt_cross/server.pyindex 63e4e6165..159a448a1 100644--- a/moli-benchmark/moli_benchmark/wpt_cross/server.py+++ b/moli-benchmark/moli_benchmark/wpt_cross/server.py@@ -31,6 +31,7 @@ import mimetypesimport reimport socketimport subprocess+import sysimport threadingimport timeimport uuid@@ -1432,7 +1433,18 @@ def _wpt_cookie_websocket_set_cookie(query: str) -> str | None:return None-class _Ipv6ThreadingHTTPServer(ThreadingHTTPServer):+class _FixtureThreadingHTTPServer(ThreadingHTTPServer):+ def handle_error(self, request: object, client_address: object) -> None:+ # Disposing a case BrowserContext intentionally cancels any auxiliary+ # requests that outlive the harness result. The stdlib server prints a+ # full traceback for those routine disconnects, obscuring real fixture+ # failures during parallel runs.+ if isinstance(sys.exc_info()[1], (BrokenPipeError, ConnectionResetError)):+ return+ super().handle_error(request, client_address)+++class _Ipv6ThreadingHTTPServer(_FixtureThreadingHTTPServer):address_family = socket.AF_INET6@@ -2542,9 +2554,11 @@ class WptFixtureServer:self.results = ResultsStore()self.csp_reports = CspReportStore()handler_cls = _make_handler(self.wpt_root, self.results, self.csp_reports)- self.httpd = ThreadingHTTPServer(("127.0.0.1", 0), handler_cls)+ self.httpd = _FixtureThreadingHTTPServer(("127.0.0.1", 0), handler_cls)self.port = int(self.httpd.server_address[1])- self.alternate_httpd = ThreadingHTTPServer(("127.0.0.1", 0), handler_cls)+ self.alternate_httpd = _FixtureThreadingHTTPServer(+ ("127.0.0.1", 0), handler_cls+ )self.alternate_port = int(self.alternate_httpd.server_address[1])for httpd in (self.httpd, self.alternate_httpd):self._configure_httpd_defaults(diff --git a/moli-benchmark/tests/test_wpt_cross.py b/moli-benchmark/tests/test_wpt_cross.pyindex 0bafd342d..d886fe48f 100644--- a/moli-benchmark/tests/test_wpt_cross.py+++ b/moli-benchmark/tests/test_wpt_cross.py@@ -19,6 +19,7 @@ from urllib.request import Request, urlopenfrom PIL import Imagefrom moli_benchmark.config import clear_current_proxy_env+from moli_benchmark.raw_cdp import RawCdpErrorfrom moli_benchmark.wpt_cross.__main__ import (CASE_LIST_FILES,WPT_CROSS_CASE_TIMEOUT_SECONDS,@@ -79,8 +80,14 @@ from moli_benchmark.wpt_cross.any_js import ()from moli_benchmark.wpt_cross.render_html import render_htmlfrom moli_benchmark.wpt_cross.runner import (+ _AttachedPage,_PageSessionUnusable,_ReftestEvidence,+ _close_page,+ _has_navigation_evidence,+ _navigation_identity,+ _normalized_case_path,+ _normalized_navigation_url,_run_async,_run_one_case,_write_reftest_failure_artifacts,@@ -145,9 +152,23 @@ clear_current_proxy_env()class WptCrossTests(unittest.TestCase):def test_cdp_command_failure_marks_page_session_unusable(self) -> None:+ navigation_response = {+ "result": {"frameId": "FRAME-1", "loaderId": "LOADER-1"},+ "sessionId": "SESSION-1",+ }+ navigation_event = {+ "method": "Page.frameNavigated",+ "sessionId": "SESSION-1",+ "params": {+ "frame": {"id": "FRAME-1", "loaderId": "LOADER-1"}+ },+ }for receive_effect, error_prefix in ((asyncio.TimeoutError(), "navigate failed:"),- ([({"result": {}}, []), asyncio.TimeoutError()], "evaluate failed:"),+ (+ [(navigation_response, [navigation_event]), asyncio.TimeoutError()],+ "evaluate failed:",+ ),):with self.subTest(error_prefix=error_prefix):client = SimpleNamespace(@@ -168,6 +189,315 @@ class WptCrossTests(unittest.TestCase):case_result = raised.exception.case_resultself.assertEqual(case_result.status, "error")self.assertTrue((case_result.error or "").startswith(error_prefix))+ self.assertIn("TimeoutError", case_result.error or "")++ def test_navigation_identity_rejects_failed_or_unbound_navigation(self) -> None:+ with self.assertRaisesRegex(RawCdpError, "ERR_NAME_NOT_RESOLVED"):+ _navigation_identity(+ {+ "sessionId": "SESSION-1",+ "result": {+ "frameId": "FRAME-1",+ "errorText": "net::ERR_NAME_NOT_RESOLVED",+ },+ },+ session_id="SESSION-1",+ expected_url="http://localhost/case.html",+ )+ with self.assertRaisesRegex(RawCdpError, "produced a download"):+ _navigation_identity(+ {+ "sessionId": "SESSION-1",+ "result": {+ "frameId": "FRAME-1",+ "loaderId": "LOADER-1",+ "isDownload": True,+ },+ },+ session_id="SESSION-1",+ expected_url="http://localhost/case.html",+ )+ with self.assertRaisesRegex(RawCdpError, "no loaderId"):+ _navigation_identity(+ {+ "sessionId": "SESSION-1",+ "result": {"frameId": "FRAME-1"},+ },+ session_id="SESSION-1",+ expected_url="http://localhost/case.html",+ )++ def test_navigation_evidence_requires_exact_session_frame_and_loader(self) -> None:+ identity = _navigation_identity(+ {+ "sessionId": "SESSION-1",+ "result": {"frameId": "FRAME-1", "loaderId": "LOADER-1"},+ },+ session_id="SESSION-1",+ expected_url="http://localhost/case.html",+ )+ stale = {+ "method": "Page.lifecycleEvent",+ "sessionId": "SESSION-1",+ "params": {"frameId": "FRAME-1", "loaderId": "LOADER-OLD"},+ }+ wrong_session = {+ "method": "Page.frameNavigated",+ "sessionId": "SESSION-OLD",+ "params": {+ "frame": {"id": "FRAME-1", "loaderId": "LOADER-1"}+ },+ }+ current = {+ "method": "Page.frameNavigated",+ "sessionId": "SESSION-1",+ "params": {+ "frame": {+ "id": "FRAME-1",+ "loaderId": "LOADER-1",+ "url": "http://localhost/case.html",+ }+ },+ }+ wrong_url = {+ "method": "Page.frameNavigated",+ "sessionId": "SESSION-1",+ "params": {+ "frame": {+ "id": "FRAME-1",+ "loaderId": "LOADER-1",+ "url": "http://localhost/other.html",+ }+ },+ }++ self.assertFalse(_has_navigation_evidence([stale, wrong_session], identity))+ self.assertFalse(_has_navigation_evidence([wrong_url], identity))+ self.assertTrue(+ _has_navigation_evidence([stale, wrong_session, current], identity)+ )++ def test_case_path_and_url_normalization_ignore_leading_slash_and_fragment(self) -> None:+ self.assertEqual(+ _normalized_case_path("/dom/case.html?variant=1#ignored"),+ "dom/case.html?variant=1",+ )+ self.assertEqual(+ _normalized_navigation_url(+ "HTTP://LOCALHOST:8000/dom/case.html?variant=1#ignored"+ ),+ "http://localhost:8000/dom/case.html?variant=1",+ )+ self.assertEqual(+ _normalized_navigation_url(+ "http://localhost:8000/xhr/case.html?load fires normally"+ ),+ "http://localhost:8000/xhr/case.html?load%20fires%20normally",+ )++ def test_run_one_case_rejects_wrong_initial_commit_url(self) -> None:+ client = SimpleNamespace(+ send=AsyncMock(return_value=1),+ recv_until_id=AsyncMock(+ return_value=(+ {+ "sessionId": "SESSION-1",+ "result": {"frameId": "FRAME-1", "loaderId": "LOADER-1"},+ },+ [+ {+ "method": "Page.frameNavigated",+ "sessionId": "SESSION-1",+ "params": {+ "frame": {+ "id": "FRAME-1",+ "loaderId": "LOADER-1",+ "url": "http://localhost/wrong.html",+ }+ },+ }+ ],+ )+ ),+ )++ result = asyncio.run(+ _run_one_case(+ client=client, # type: ignore[arg-type]+ session_id="SESSION-1",+ case_path="expected.html",+ url="http://localhost/expected.html",+ timeout_seconds=1.0,+ )+ )++ self.assertEqual(result.status, "error")+ self.assertIn("unexpected URL", result.error or "")+ self.assertEqual(client.send.await_count, 1)++ def test_run_one_case_ignores_stale_payload_until_navigation_is_bound(self) -> None:+ class FakeClient:+ def __init__(self) -> None:+ self.commands: list[tuple[str, dict | None, str | None]] = []++ async def send(+ self,+ method: str,+ params: dict | None = None,+ *,+ session_id: str | None = None,+ ) -> int:+ self.commands.append((method, params, session_id))+ return len(self.commands)++ async def recv_until_id(+ self, command_id: int, *, timeout: float+ ) -> tuple[dict, list[dict]]:+ method = self.commands[command_id - 1][0]+ if method == "Page.navigate":+ return (+ {+ "sessionId": "SESSION-1",+ "result": {+ "frameId": "FRAME-1",+ "loaderId": "LOADER-1",+ },+ },+ [+ {+ "method": "Page.lifecycleEvent",+ "sessionId": "SESSION-1",+ "params": {+ "frameId": "FRAME-1",+ "loaderId": "LOADER-OLD",+ },+ }+ ],+ )+ evaluation_count = sum(+ command[0] == "Runtime.evaluate"+ for command in self.commands[:command_id]+ )+ payload_case = (+ "/old-case.html" if evaluation_count == 1 else "/new-case.html"+ )+ payload = {+ "case_path": payload_case,+ "source": "completion-callback",+ "harness": {"status": 0},+ "tests": [{"name": "current result", "status": 0}],+ }+ events = []+ if evaluation_count == 2:+ events.append(+ {+ "method": "Page.frameNavigated",+ "sessionId": "SESSION-1",+ "params": {+ "frame": {+ "id": "FRAME-1",+ "loaderId": "LOADER-1",+ "url": "http://localhost/new-case.html",+ }+ },+ }+ )+ return (+ {+ "result": {+ "result": {+ "value": {+ # The test may legitimately change its live+ # URL after the initial loader committed.+ "href": "http://localhost/after-push-state",+ "casePath": "/after-push-state",+ "bridgeInstalled": True,+ "payload": payload,+ }+ }+ }+ },+ events,+ )++ client = FakeClient()+ result = asyncio.run(+ _run_one_case(+ client=client, # type: ignore[arg-type]+ session_id="SESSION-1",+ case_path="new-case.html",+ url="http://localhost/new-case.html",+ timeout_seconds=1.0,+ )+ )++ self.assertEqual(result.status, "pass")+ self.assertEqual(result.subtests_pass, 1)+ self.assertEqual(+ sum(command[0] == "Runtime.evaluate" for command in client.commands),+ 2,+ )++ def test_close_page_disposes_context_with_all_auxiliary_targets(self) -> None:+ class FakeClient:+ def __init__(self) -> None:+ self.commands: list[tuple[str, dict | None]] = []+ self.get_targets_count = 0++ async def send(+ self,+ method: str,+ params: dict | None = None,+ *,+ session_id: str | None = None,+ ) -> int:+ self.commands.append((method, params))+ return len(self.commands)++ async def recv_until_id(+ self, command_id: int, *, timeout: float+ ) -> tuple[dict, list[dict]]:+ method = self.commands[command_id - 1][0]+ if method == "Target.getTargets":+ self.get_targets_count += 1+ infos = (+ [+ {+ "targetId": "TARGET-1",+ "browserContextId": "CONTEXT-1",+ },+ {+ "targetId": "POPUP-1",+ "browserContextId": "CONTEXT-1",+ },+ ]+ if self.get_targets_count == 1+ else []+ )+ return ({"result": {"targetInfos": infos}}, [])+ return ({"result": {}}, [])++ client = FakeClient()+ asyncio.run(+ _close_page(+ client, # type: ignore[arg-type]+ _AttachedPage(+ "CONTEXT-1",+ "TARGET-1",+ "SESSION-1",+ frozenset({"PREWARM"}),+ ),+ )+ )++ self.assertIn(+ (+ "Target.disposeBrowserContext",+ {"browserContextId": "CONTEXT-1"},+ ),+ client.commands,+ )+ self.assertNotIn("Target.closeTarget", [method for method, _ in client.commands])def test_unusable_page_session_preserves_case_result_and_relaunches(self) -> None:def handle(name: str) -> SimpleNamespace:@@ -203,6 +533,9 @@ class WptCrossTests(unittest.TestCase):duration_ms=1.0,)+ first_page = _AttachedPage("CONTEXT-1", "TARGET-1", "SESSION-1", frozenset())+ second_page = _AttachedPage("CONTEXT-2", "TARGET-2", "SESSION-2", frozenset())+with (patch("moli_benchmark.wpt_cross.runner.connect_raw_cdp",@@ -210,7 +543,7 @@ class WptCrossTests(unittest.TestCase):),patch("moli_benchmark.wpt_cross.runner._attach_page",- new=AsyncMock(return_value="SESSION-1"),+ new=AsyncMock(return_value=first_page),),patch("moli_benchmark.wpt_cross.runner._run_one_case",@@ -221,9 +554,13 @@ class WptCrossTests(unittest.TestCase):patch("moli_benchmark.wpt_cross.runner._try_relaunch",new=AsyncMock(- return_value=(second_handle, second_client, "SESSION-2")+ return_value=(second_handle, second_client, second_page)),),+ patch(+ "moli_benchmark.wpt_cross.runner._close_page",+ new=AsyncMock(),+ ),):result = asyncio.run(_run_async(@@ -244,6 +581,82 @@ class WptCrossTests(unittest.TestCase):self.assertIs(result.cases[1], passed_case)self.assertEqual(driver.shutdown.call_count, 2)+ def test_successful_cases_rotate_isolated_page_contexts(self) -> None:+ handle = SimpleNamespace(+ process=SimpleNamespace(poll=lambda: None),+ binary=None,+ binary_sha256=None,+ binary_version=None,+ endpoint="http://engine",+ ready_ms=1.0,+ )+ client = SimpleNamespace(websocket=SimpleNamespace(close=AsyncMock()))+ driver = SimpleNamespace(+ name="moli",+ launch=Mock(return_value=handle),+ shutdown=Mock(return_value={"stopped": True}),+ )+ first_page = _AttachedPage(+ "CONTEXT-1", "TARGET-1", "SESSION-1", frozenset()+ )+ second_page = _AttachedPage(+ "CONTEXT-2", "TARGET-2", "SESSION-2", frozenset()+ )+ first_result = CaseResult(+ "first.html", "http://localhost/first.html", "pass", 1.0+ )+ second_result = CaseResult(+ "second.html", "http://localhost/second.html", "pass", 1.0+ )+ attach = AsyncMock(side_effect=[first_page, second_page])+ close = AsyncMock()+ run_case = AsyncMock(side_effect=[first_result, second_result])++ with (+ patch(+ "moli_benchmark.wpt_cross.runner.connect_raw_cdp",+ new=AsyncMock(return_value=client),+ ),+ patch(+ "moli_benchmark.wpt_cross.runner._attach_page",+ new=attach,+ ),+ patch(+ "moli_benchmark.wpt_cross.runner._close_page",+ new=close,+ ),+ patch(+ "moli_benchmark.wpt_cross.runner._run_one_case",+ new=run_case,+ ),+ ):+ result = asyncio.run(+ _run_async(+ driver=driver, # type: ignore[arg-type]+ binary_override=None,+ cases=[+ ("first.html", "http://localhost/first.html"),+ ("second.html", "http://localhost/second.html"),+ ],+ case_timeout_seconds=1.0,+ launch_timeout_seconds=1.0,+ viewport=None,+ artifact_output_dir=None,+ )+ )++ self.assertEqual(result.cases, [first_result, second_result])+ self.assertEqual(+ [call.kwargs["session_id"] for call in run_case.await_args_list],+ ["SESSION-1", "SESSION-2"],+ )+ self.assertEqual(+ [call.args[1] for call in close.await_args_list],+ [first_page, second_page],+ )+ self.assertEqual(attach.await_count, 2)+ self.assertEqual(driver.launch.call_count, 1)+def test_moli_wpt_commands_enable_layout_and_resources(self) -> None:self.assertEqual(_moli_command(Path("/bin/moli"), 9222, None),@@ -291,18 +704,31 @@ class WptCrossTests(unittest.TestCase):self.assertNotIn("--wait_ms", command)self.assertNotIn("--http_timeout", command)- def test_parser_hides_fixed_timeout_and_parallelism_knobs(self) -> None:+ def test_parser_exposes_configurable_parallelism_with_stable_timeout(self) -> None:parser = _build_parser()help_text = parser.format_help()self.assertEqual(WPT_CROSS_CASE_TIMEOUT_SECONDS, 120.0)- self.assertEqual(WPT_CROSS_PARALLELISM, 100)+ self.assertEqual(WPT_CROSS_PARALLELISM, 50)self.assertNotIn("--case-timeout", help_text)self.assertNotIn("--case-timeout-engine", help_text)- self.assertNotIn("--parallelism", help_text)+ self.assertIn("--parallelism", help_text)self.assertNotIn("--cdp-parallelism", help_text)self.assertNotIn("--run-order", parser.format_help())self.assertNotIn("--shuffle-seed", parser.format_help())+ required = [+ "--wpt-root",+ "/tmp/wpt",+ "--engine",+ "moli",+ "--output-dir",+ "/tmp/out",+ ]+ self.assertEqual(parser.parse_args(required).parallelism, 50)+ self.assertEqual(+ parser.parse_args([*required, "--parallelism", "7"]).parallelism,+ 7,+ )def test_layout_profiles_are_explicit_and_keep_fixed_parallelism(self) -> None:parser = _build_parser()@@ -334,7 +760,7 @@ class WptCrossTests(unittest.TestCase):(800, 600),)self.assertEqual(LAYOUT_VIEWPORT.device_scale_factor, 1.0)- self.assertEqual(WPT_CROSS_PARALLELISM, 100)+ self.assertEqual(WPT_CROSS_PARALLELISM, 50)def test_all_profile_matrix_deduplicates_default_and_layout_cases(self) -> None:semantic = WptCase("css/cssom-view/shared.html")@@ -1323,7 +1749,7 @@ class WptCrossTests(unittest.TestCase):self.assertEqual(captured["case_timeout_seconds"], WPT_CROSS_CASE_TIMEOUT_SECONDS)self.assertEqual(captured["parallelism"], WPT_CROSS_PARALLELISM)- def test_main_uses_fixed_parallelism_for_cdp_runner(self) -> None:+ def test_main_uses_requested_parallelism_for_cdp_runner(self) -> None:calls: list[dict[str, object]] = []class FakeServer:@@ -1422,14 +1848,16 @@ class WptCrossTests(unittest.TestCase):str(output_dir),"--mode","cdp",+ "--parallelism",+ "2",])self.assertEqual(code, 0)- self.assertEqual(len(calls), len(cases))+ self.assertEqual(len(calls), 2)self.assertTrue(all(call["case_timeout_seconds"] == WPT_CROSS_CASE_TIMEOUT_SECONDS for call in calls))self.assertEqual(- sorted(call["cases"][0][0] for call in calls),+ sorted(case[0] for call in calls for case in call["cases"]),[case.case_path for case in cases],)@@ -1633,7 +2061,7 @@ class WptCrossTests(unittest.TestCase):self.assertEqual(_harness_timeout_multiplier(30.0, 10.0, case.case_path), 1.0)- def test_parser_rejects_removed_timeout_and_parallelism_flags(self) -> None:+ def test_parser_rejects_removed_timeout_flags_and_legacy_parallelism(self) -> None:parser = _build_parser()base = ["--wpt-root",@@ -1646,12 +2074,19 @@ class WptCrossTests(unittest.TestCase):for removed_flag in ("--case-timeout","--case-timeout-engine",- "--parallelism","--cdp-parallelism",):with self.subTest(removed_flag=removed_flag), self.assertRaises(SystemExit):parser.parse_args([*base, removed_flag, "1"])+ for invalid_parallelism in ("0", "-1", "not-an-integer"):+ with self.subTest(invalid_parallelism=invalid_parallelism), self.assertRaises(+ SystemExit+ ):+ parser.parse_args(+ [*base, "--parallelism", invalid_parallelism]+ )+def test_main_matrix_preserves_harness_message(self) -> None:with tempfile.TemporaryDirectory() as temp_dir:root = Path(temp_dir)