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(wpt): run crashtests with their readiness protocol
ldm011f8e9668b3a
diff --git a/moli-benchmark/README.md b/moli-benchmark/README.mdindex c8939b2cf..29d858f1b 100644--- a/moli-benchmark/README.md+++ b/moli-benchmark/README.md@@ -63,6 +63,14 @@ uv run python -m moli_benchmark.wpt_cross \Use `--mode cdp` to check the same cases through CDP. Unsupported formatsremain failures in the report; they are not filtered out of this suite.+HTML crashtests, identified by WPT's `-crash` filename flag or a `crashtests`+directory, are also included within the semantic profile's existing filters.+Runs containing crashtests use CDP in `--mode auto`; explicit CLI mode rejects+them. The runner waits for load, fonts, two animation frames, and removal of+`test-wait`, dispatching `TestRendered` when needed. Reports record these as+`crashtest` with zero subtests. An outstanding wait remains a timeout, and a+renderer crash is reported even when the browser process stays alive.+### Cross-engine layout WPTThe standalone cross-engine runner has separate layout profiles, so itsdiff --git a/moli-benchmark/moli_benchmark/wpt_cross/__main__.py b/moli-benchmark/moli_benchmark/wpt_cross/__main__.pyindex e915449ba..552ccddde 100644--- a/moli-benchmark/moli_benchmark/wpt_cross/__main__.py+++ b/moli-benchmark/moli_benchmark/wpt_cross/__main__.py@@ -14,8 +14,8 @@ The runner:profile from ``--wpt-root``.2. Starts a single fixture server (loopback + optional global IPv6 for Obscura).3. For each engine, launches it via :class:`EngineDriver`, runs every case- through the testharness bridge or the CDP screenshot reftest path, and- writes per-engine JSON results.+ through the testharness bridge, crashtest readiness, or the CDP screenshot+ reftest path, and writes per-engine JSON results.4. Emits ``matrix.json`` with the cross-engine pass/fail/timeout/crash table."""@@ -42,6 +42,8 @@ from .cli_runner import run_engine_on_cases_clifrom .engine import ENGINES, build_driverfrom .audit import audit_matrix, load_known_failure_manifestfrom .runner import (+ CaseRun,+ CrashtestRun,LAYOUT_VIEWPORT,MAX_RECORDED_FAILURES,ReftestReferenceRun,@@ -580,8 +582,10 @@ def _cdp_case_run(*,external: bool,timeout_seconds: float,-) -> tuple[str, str, float] | ReftestRun:+) -> CaseRun:url = _url_for_case_origin(server, case.case_path, external=external)+ if case.test_type == "crashtest":+ return CrashtestRun(case.case_path, url, timeout_seconds)if case.test_type != "reftest":return case.case_path, url, timeout_secondsreturn ReftestRun(@@ -604,8 +608,8 @@ def _cdp_case_run()-def _run_case_path(case: tuple[str, str, float] | ReftestRun) -> str:- return case.case_path if isinstance(case, ReftestRun) else case[0]+def _run_case_path(case: CaseRun) -> str:+ return case.case_path if isinstance(case, (ReftestRun, CrashtestRun)) else case[0]def main(argv: list[str] | None = None) -> int:@@ -655,7 +659,12 @@ def main(argv: list[str] | None = None) -> int:return 2has_reftests = any(case.test_type == "reftest" for case in cases)+ has_crashtests = any(case.test_type == "crashtest" for case in cases)fixed_layout_viewport = _is_layout_profile(args.profile) or has_reftests+ if has_crashtests and args.mode == "cli":+ print("error: crashtests require CDP mode to observe readiness and crashes", file=sys.stderr)+ return 4+ requires_cdp = fixed_layout_viewport or has_crashtestsif fixed_layout_viewport and args.mode == "cli":print("error: layout profiles and reftests require CDP mode for fixed viewport screenshots",@@ -704,7 +713,7 @@ def main(argv: list[str] | None = None) -> int:for engine in args.engine:driver = build_driver(engine)external = engine == "obscura"- mode_for_check = "cdp" if fixed_layout_viewport else args.mode+ mode_for_check = "cdp" if requires_cdp else args.modeif mode_for_check == "auto":mode_for_check = "cli" if driver.cli_fetch_command is not None else "cdp"if external and mode_for_check == "cdp" and server.external_base_url is None:@@ -741,7 +750,7 @@ def main(argv: list[str] | None = None) -> int:for case in scheduled_cases]- mode = "cdp" if fixed_layout_viewport else args.mode+ mode = "cdp" if requires_cdp else args.modeif mode == "auto":mode = "cli" if driver.cli_fetch_command is not None else "cdp"elif mode == "cli" and driver.cli_fetch_command is None:diff --git a/moli-benchmark/moli_benchmark/wpt_cross/case_set.py b/moli-benchmark/moli_benchmark/wpt_cross/case_set.pyindex cf50cc8e4..da1865673 100644--- a/moli-benchmark/moli_benchmark/wpt_cross/case_set.py+++ b/moli-benchmark/moli_benchmark/wpt_cross/case_set.py@@ -1,6 +1,8 @@"""Enumerate WPT cases that the cross-engine runner can execute.-The default semantic profile selects testharness cases. Layout profiles add a+The default semantic profile selects testharness cases and HTML crashtests.+Crashtests use WPT's ``-crash`` filename flag or ``crashtests`` directory and+do not require testharness.js. Layout profiles add adeterministic static subset and read upstream ``MANIFEST.json`` for reftestURLs, ``==`` / ``!=`` references, timeout metadata, and fuzzy bounds.@@ -27,8 +29,8 @@ A testharness case is selectable if:``.https.``, ``.sub.``, and ``.serviceworker.`` cases because the fixtureserver has local HTTP substitutions for those WPT features.-The default set is blacklist-based: start from all upstream WPT HTML-testharness cases the v1 static fixture server can serve, then drop areas+The default set is blacklist-based: start from upstream WPT HTML testharness+cases and crashtests the v1 static fixture server can serve, then drop areasthat require a real layout, paint, compositor, media timeline, or canvasrasterizer. This keeps the baseline broad without letting rendering-only gapsdominate the signal.@@ -938,6 +940,17 @@ def _any_js_allows_worker(meta: AnyJsMeta) -> bool:return not meta.globals or bool(meta.globals & {"worker", "dedicatedworker"})+def _is_crashtest_path(rel: str) -> bool:+ """Match WPT SourceFile.name_is_crashtest, including markup-only scope."""+ path = Path(rel)+ if path.suffix not in {".html", ".htm", ".xhtml", ".xht", ".xml", ".svg"}:+ return False+ type_flag = (+ path.stem.rsplit("-", 1)[1].split(".", 1)[0] if "-" in path.stem else None+ )+ return type_flag == "crash" or "crashtests" in path.parts[:-1]++def enumerate_cases(wpt_root: Path,*,@@ -995,7 +1008,8 @@ def enumerate_cases(include_tentative=include_tentative,):continue- if "/resources/testharness.js" not in head:+ crashtest = _is_crashtest_path(rel)+ if not crashtest and "/resources/testharness.js" not in head:continueif "/resources/testdriver" in head:continue@@ -1006,8 +1020,12 @@ def enumerate_cases(continuetimeout_multiplier = LONG_TIMEOUT_MULTIPLIER if parser.long_timeout else 1.0found.extend(- WptCase(case_path=case_path, timeout_multiplier=timeout_multiplier)- for case_path in _case_paths_for_variants(rel, parser)+ WptCase(+ case_path=case_path,+ timeout_multiplier=timeout_multiplier,+ test_type="crashtest" if crashtest else "testharness",+ )+ for case_path in ([rel] if crashtest else _case_paths_for_variants(rel, parser)))for path in base.rglob("*.any.js"):if not path.is_file():@@ -1553,4 +1571,8 @@ def explicit_case(wpt_root: Path, case_path: str) -> WptCase:else:parser = _parse_case_html(source)timeout_multiplier = LONG_TIMEOUT_MULTIPLIER if parser.long_timeout else 1.0- return WptCase(case_path=normalized_case_path, timeout_multiplier=timeout_multiplier)+ return WptCase(+ case_path=normalized_case_path,+ timeout_multiplier=timeout_multiplier,+ test_type="crashtest" if _is_crashtest_path(source_case_path) else "testharness",+ )diff --git a/moli-benchmark/moli_benchmark/wpt_cross/crashtest_ready.js b/moli-benchmark/moli_benchmark/wpt_cross/crashtest_ready.jsnew file mode 100644index 000000000..2375c9050--- /dev/null+++ b/moli-benchmark/moli_benchmark/wpt_cross/crashtest_ready.js@@ -0,0 +1,32 @@+async function(expectedURL) {+ if (location.href !== new URL(expectedURL, location.href).href) {+ throw new Error('crashtest document changed before readiness check');+ }+ // Follow wptrunner's test-wait.js: load, fonts, two animation frames,+ // then test-wait removal. TestRendered is dispatched once after observing.+ const root = document.documentElement;+ if (document.readyState !== 'complete') {+ await new Promise(resolve => addEventListener('load', resolve, {once: true}));+ }+ if (Object.prototype.hasOwnProperty.call(Document.prototype, 'fonts')) {+ await document.fonts.ready;+ }+ await new Promise(resolve => {+ let observer = null;+ const paints = () => requestAnimationFrame(() => requestAnimationFrame(ready));+ const ready = () => {+ if (root && root.classList.contains('test-wait')) {+ if (observer === null) {+ observer = new MutationObserver(paints);+ observer.observe(root, {attributes: true});+ root.dispatchEvent(new Event('TestRendered', {bubbles: true}));+ }+ return;+ }+ if (observer !== null) observer.disconnect();+ resolve();+ };+ paints();+ });+ return {complete: true};+}diff --git a/moli-benchmark/moli_benchmark/wpt_cross/runner.py b/moli-benchmark/moli_benchmark/wpt_cross/runner.pyindex 1d84c7e9a..7d6303358 100644--- a/moli-benchmark/moli_benchmark/wpt_cross/runner.py+++ b/moli-benchmark/moli_benchmark/wpt_cross/runner.py@@ -1,8 +1,8 @@"""Per-engine WPT case runner.-Connects to a launched :class:`EngineDriver` and executes either testharness-cases (through ``window.__bench_wpt__``) or manifest-backed screenshot-reftests at a fixed viewport.+Connects to a launched :class:`EngineDriver` and executes testharness cases+(through ``window.__bench_wpt__``), crashtests (through WPT readiness and crash+signals), or manifest-backed screenshot reftests at a fixed viewport.Classifies each result as ``pass`` / ``fail`` / ``timeout`` / ``crash`` /``error`` so that the cross-engine matrix can be built without rewriting raw@@ -60,7 +60,14 @@ class ReftestRun:references: tuple[ReftestReferenceRun, ...]-CaseRun = tuple[str, str] | tuple[str, str, float] | ReftestRun+@dataclass(frozen=True)+class CrashtestRun:+ case_path: str+ url: str+ timeout_seconds: float+++CaseRun = tuple[str, str] | tuple[str, str, float] | ReftestRun | CrashtestRun# WPT testharness.js status constants (testharness.js: TestsStatus)@@ -691,6 +698,97 @@ async def _run_one_case()+_CRASHTEST_READY_SCRIPT = Path(__file__).with_name("crashtest_ready.js").read_text(encoding="utf-8")+++async def _run_one_crashtest(+ *,+ client: RawCdpClient,+ session_id: str,+ target_id: str,+ case: CrashtestRun,+) -> CaseResult:+ started = time.perf_counter()+ deadline = started + case.timeout_seconds+ seen: list[dict[str, Any]] = []++ def result(status: str, error: str | None = None) -> CaseResult:+ console_errors, js_exceptions = _count_traces(seen)+ return CaseResult(+ case_path=case.case_path,+ url=case.url,+ status=status,+ duration_ms=(time.perf_counter() - started) * 1000.0,+ error=error,+ console_errors=console_errors,+ js_exceptions=js_exceptions,+ test_type="crashtest",+ payload_source="crashtest-ready" if status == "pass" else None,+ )++ async def command(method: str, params: dict[str, Any] | None = None) -> dict[str, Any]:+ command_id = await client.send(method, params, session_id=session_id)+ while True:+ remaining = deadline - time.perf_counter()+ if remaining <= 0:+ raise asyncio.TimeoutError()+ message = await asyncio.wait_for(client.recv(), timeout=remaining)+ seen.append(message)+ # A renderer crash need not terminate the browser process or reply+ # to the outstanding command. Observe it as soon as it arrives.+ if (+ message.get("method") == "Inspector.targetCrashed"+ and message.get("sessionId") == session_id+ ) or (+ message.get("method") == "Target.targetCrashed"+ and (message.get("params") or {}).get("targetId") == target_id+ ):+ raise _PageSessionUnusable(result("crash", "crashtest target crashed"))+ if message.get("id") == command_id:+ if "error" in message:+ raise RawCdpError(f"{method} failed: {message['error']}")+ return message++ try:+ await command("Inspector.enable")+ response = await command("Page.navigate", {"url": case.url})+ identity = _navigation_identity(response, session_id=session_id, expected_url=case.url)+ location_expression = "({href: location.href})"+ while True:+ response = await command(+ "Runtime.evaluate", {"expression": location_expression, "returnByValue": True}+ )+ committed_url = _navigation_commit_url(seen, identity)+ commit_error = _navigation_commit_error(identity, committed_url)+ if commit_error is not None:+ return result("error", commit_error)+ value = _remote_object_value(response)+ if (+ committed_url is not None+ and isinstance(value, dict)+ and isinstance(value.get("href"), str)+ and _normalized_navigation_url(value["href"]) == _normalized_navigation_url(case.url)+ ):+ break+ await asyncio.sleep(min(0.025, max(0.0, deadline - time.perf_counter())))+ response = await command(+ "Runtime.evaluate",+ {+ "expression": f"({_CRASHTEST_READY_SCRIPT})({json.dumps(case.url)})",+ "returnByValue": True,+ "awaitPromise": True,+ },+ )+ value = _remote_object_value(response)+ if not isinstance(value, dict) or value.get("complete") is not True:+ return result("error", f"crashtest readiness script failed: {response}")+ return result("pass")+ except asyncio.TimeoutError as error:+ raise _PageSessionUnusable(result("timeout", "crashtest did not become ready within timeout")) from error+ except RawCdpError as error:+ raise _PageSessionUnusable(result("error", f"crashtest command failed: {error}")) from error++_REFTEST_LOCATION_EXPRESSION = """(function(expectedUrl) {return {@@ -1466,6 +1564,13 @@ async def _run_async(artifact_output_dir=artifact_output_dir,reference_cache=reference_cache,)+ elif isinstance(case, CrashtestRun):+ case_result = await _run_one_crashtest(+ client=client,+ session_id=page.session_id,+ target_id=page.target_id,+ case=case,+ )else:case_result = await _run_one_case(client=client,@@ -1683,7 +1788,7 @@ async def _wait_then_retry_launch(def _case_parts(case: CaseRun, default_timeout: float) -> tuple[str, str, float]:- if isinstance(case, ReftestRun):+ if isinstance(case, (ReftestRun, CrashtestRun)):return case.case_path, case.url, case.timeout_secondsif len(case) == 3:return case[0], case[1], case[2]@@ -1691,6 +1796,8 @@ def _case_parts(case: CaseRun, default_timeout: float) -> tuple[str, str, float]def _case_test_type(case: CaseRun) -> str:+ if isinstance(case, CrashtestRun):+ return "crashtest"return "reftest" if isinstance(case, ReftestRun) else "testharness"diff --git a/moli-benchmark/tests/test_wpt_crashtests.py b/moli-benchmark/tests/test_wpt_crashtests.pynew file mode 100644index 000000000..3f58b9d22--- /dev/null+++ b/moli-benchmark/tests/test_wpt_crashtests.py@@ -0,0 +1,207 @@+from __future__ import annotations++import asyncio+from collections import deque+from contextlib import redirect_stderr+from io import StringIO+from pathlib import Path+from types import SimpleNamespace+import tempfile+import unittest++from moli_benchmark.wpt_cross.__main__ import _cdp_case_run, _run_case_path, main+from moli_benchmark.wpt_cross.case_set import enumerate_cases, explicit_case+from moli_benchmark.wpt_cross.runner import (+ CrashtestRun,+ _PageSessionUnusable,+ _case_parts,+ _case_test_type,+ _run_one_crashtest,+ case_result_to_dict,+)+++URL = "http://localhost/dom/example-crash.html"+CASE = CrashtestRun("dom/example-crash.html", URL, 0.5)+++def commit(url: str = URL, loader: str = "loader") -> dict:+ return {+ "method": "Page.frameNavigated",+ "sessionId": "session",+ "params": {"frame": {"id": "frame", "loaderId": loader, "url": url}},+ }+++def value(payload: dict) -> dict:+ return {"result": {"result": {"value": payload}}}+++class FakeClient:+ def __init__(self, phases: list[list[dict | BaseException]]):+ self.phases = deque(phases)+ self.pending: deque[dict | BaseException] = deque()+ self.commands: list[tuple[str, dict | None]] = []++ async def send(self, method: str, params: dict | None = None, *, session_id: str) -> int:+ self.commands.append((method, params))+ command_id = len(self.commands)+ for message in self.phases.popleft():+ if isinstance(message, dict) and "method" not in message:+ message = {**message, "id": command_id}+ self.pending.append(message)+ return command_id++ async def recv(self) -> dict:+ message = self.pending.popleft()+ if isinstance(message, BaseException):+ raise message+ return message+++def phases() -> list[list[dict | BaseException]]:+ return [+ [{"result": {}}],+ [commit(), {"result": {"frameId": "frame", "loaderId": "loader"}}],+ [value({"href": URL})],+ [value({"complete": True})],+ ]+++class CrashtestTests(unittest.TestCase):+ def run_case(self, replies: list[list[dict | BaseException]]):+ client = FakeClient(replies)+ try:+ result = asyncio.run(_run_one_crashtest(+ client=client, session_id="session", target_id="target", case=CASE,+ ))+ except _PageSessionUnusable as error:+ result = error.case_result+ return result, client++ def test_name_rules_distinguish_markup_from_script_harnesses(self):+ with tempfile.TemporaryDirectory() as temp:+ root = Path(temp)+ expected = {+ "dom/example-crash.html": "crashtest",+ "dom/example-crash.sub.html": "crashtest",+ "dom/crashtests/example.htm": "crashtest",+ "dom/crashtests/example.svg": "crashtest",+ "dom/crashtests/example.xhtml": "crashtest",+ "dom/crashtests/example.any.js": "testharness",+ "dom/crashtests/example.window.js": "testharness",+ "dom/crash.html": "testharness",+ "dom/example-crash-other.html": "testharness",+ "dom/example.html?mode=-crash": "testharness",+ }+ for name, test_type in expected.items():+ path = root / name.split("?", 1)[0]+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text("<!doctype html>")+ with self.subTest(name=name):+ self.assertEqual(explicit_case(root, name).test_type, test_type)++ def test_discovery_applies_support_filters_and_crashtest_precedence(self):+ with tempfile.TemporaryDirectory() as temp:+ root = Path(temp)+ for name, source in {+ "dom/example-crash.html": '<meta name="variant" content="?ignored">',+ "dom/crashtests/also-harness.html": '<script src="/resources/testharness.js"></script>',+ "dom/ordinary.html": "<!doctype html>",+ "dom/resources/support-crash.html": "<!doctype html>",+ "css/css-flexbox/layout-crash.html": "<!doctype html>",+ }.items():+ path = root / name+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(source)+ cases = enumerate_cases(root)+ self.assertEqual([(case.case_path, case.test_type) for case in cases], [+ ("dom/crashtests/also-harness.html", "crashtest"),+ ("dom/example-crash.html", "crashtest"),+ ])++ def test_run_metadata_and_cli_mode_do_not_treat_crashtests_as_harnesses(self):+ with tempfile.TemporaryDirectory() as temp:+ root = Path(temp)+ (root / "example-crash.html").write_text("<!doctype html>")+ case = explicit_case(root, "example-crash.html")+ server = SimpleNamespace(url_for_case=lambda path, **_: "http://localhost/" + path)+ run = _cdp_case_run(server, case, external=False, timeout_seconds=9)+ self.assertIsInstance(run, CrashtestRun)+ self.assertEqual(_case_parts(run, 1), (case.case_path, "http://localhost/example-crash.html", 9))+ self.assertEqual(_case_test_type(run), "crashtest")+ self.assertEqual(_run_case_path(run), case.case_path)+ errors = StringIO()+ with redirect_stderr(errors):+ code = main(["--wpt-root", str(root), "--engine", "moli", "--mode", "cli",+ "--case", case.case_path, "--output-dir", str(root / "out")])+ self.assertEqual(code, 4)+ self.assertIn("crashtests require CDP", errors.getvalue())++ def test_completion_reports_no_invented_subtests(self):+ result, client = self.run_case(phases())+ self.assertEqual(result.status, "pass")+ self.assertEqual(result.test_type, "crashtest")+ self.assertEqual(result.payload_source, "crashtest-ready")+ self.assertEqual(case_result_to_dict(result)["subtests"]["total"], 0)+ self.assertTrue(client.commands[-1][1]["awaitPromise"])++ def test_waiting_page_times_out_without_a_completion_signal(self):+ replies = phases()+ replies[-1] = [asyncio.TimeoutError()]+ result, _ = self.run_case(replies)+ self.assertEqual(result.status, "timeout")+ self.assertIsNone(result.payload_source)++ def test_renderer_crash_is_observed_before_command_response(self):+ for crash in [+ {"method": "Inspector.targetCrashed", "sessionId": "session"},+ {"method": "Target.targetCrashed", "params": {"targetId": "target"}},+ ]:+ with self.subTest(crash=crash):+ replies = phases()+ replies[-1] = [crash]+ result, _ = self.run_case(replies)+ self.assertEqual(result.status, "crash")++ def test_other_targets_crashing_do_not_impersonate_this_target(self):+ replies = phases()+ replies[-1][:0] = [+ {"method": "Inspector.targetCrashed", "sessionId": "other"},+ {"method": "Target.targetCrashed", "params": {"targetId": "other"}},+ ]+ result, _ = self.run_case(replies)+ self.assertEqual(result.status, "pass")++ def test_wrong_navigation_cannot_report_pass(self):+ replies = phases()+ replies[1][0] = commit("http://localhost/other.html")+ result, client = self.run_case(replies)+ self.assertEqual(result.status, "error")+ self.assertIn("unexpected URL", result.error)+ self.assertEqual(len(client.commands), 3)++ def test_stale_loader_is_ignored_before_wait_script_runs(self):+ replies = phases()+ replies[1][0] = commit(loader="previous-loader")+ replies.insert(3, [commit(), value({"href": URL})])+ result, client = self.run_case(replies)+ self.assertEqual(result.status, "pass")+ self.assertEqual(len(client.commands), 5)++ def test_script_and_protocol_errors_are_not_completion(self):+ for reply in [+ {"result": {"exceptionDetails": {"text": "readiness failed"}}},+ {"error": {"message": "session closed"}},+ value({"complete": False}),+ ]:+ with self.subTest(reply=reply):+ replies = phases()+ replies[-1] = [reply]+ result, _ = self.run_case(replies)+ self.assertEqual(result.status, "error")+ self.assertIsNone(result.payload_source)+++if __name__ == "__main__":+ unittest.main()