Skip to content

Commit 0309bd0

Browse files
authored
Report a Playwright driver that never starts as one line, not a traceback (#725)
1 parent 74693ce commit 0309bd0

5 files changed

Lines changed: 276 additions & 42 deletions

File tree

‎skills/leaf/scripts/leaf/exporting.py‎

Lines changed: 25 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,12 @@
3131
)
3232
from leaf.render_gate.browser import (
3333
EXPORT_FLOOR,
34+
DriverNotStarted,
3435
below_export_floor,
3536
browser_hint,
37+
driver_hint,
3638
launch_browser,
39+
playwright_driver,
3740
)
3841
from leaf.render_gate.preview import preview_server
3942
from leaf.revision_artifact import (
@@ -581,7 +584,6 @@ def cmd_export(page_dir: Path, out: Path, version, *, interactive: bool = False)
581584
copy packages the captured inputs so that same drawing happens when the file opens;
582585
its embedded authoritative reading has no host command or transport capability."""
583586
from playwright.sync_api import Error as PlaywrightError
584-
from playwright.sync_api import sync_playwright
585587

586588
events = read_events(page_dir)
587589
published = published_versions(page_dir, events)
@@ -619,22 +621,28 @@ def cmd_export(page_dir: Path, out: Path, version, *, interactive: bool = False)
619621
artifact, state, snapshot.data, revision, version
620622
)
621623
else:
622-
with (
623-
preview_server(page_dir, document, revision, version=version) as url,
624-
sync_playwright() as p,
625-
):
626-
try:
627-
browser, _ = launch_browser(p)
628-
except PlaywrightError as e:
629-
sys.exit(
630-
"export needs a browser, and none launched "
631-
f"({str(e).strip().splitlines()[0]}). A copy is the drawn page, so "
632-
f"there is nothing to write without one. {browser_hint()}"
633-
)
634-
try:
635-
html = export_page(browser, url, page_dir, name)
636-
finally:
637-
browser.close()
624+
try:
625+
with (
626+
preview_server(page_dir, document, revision, version=version) as url,
627+
playwright_driver() as p,
628+
):
629+
try:
630+
browser, _ = launch_browser(p)
631+
except PlaywrightError as e:
632+
sys.exit(
633+
"export needs a browser, and none launched "
634+
f"({str(e).strip().splitlines()[0]}). A copy is the drawn page, "
635+
f"so there is nothing to write without one. {browser_hint()}"
636+
)
637+
try:
638+
html = export_page(browser, url, page_dir, name)
639+
finally:
640+
browser.close()
641+
except DriverNotStarted as error:
642+
sys.exit(
643+
f"export needs a browser, and Playwright's driver did not start "
644+
f"({error}), so none was ever asked for. {driver_hint()}"
645+
)
638646

639647
out.parent.mkdir(parents=True, exist_ok=True)
640648
out.write_text(html, encoding="utf-8")

‎skills/leaf/scripts/leaf/render_gate/browser.py‎

Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,15 +30,27 @@
3030
3131
The variables carry a path and nothing else: the launch takes no other argument
3232
from the host.
33+
34+
Under every one of those readings sits Playwright's driver, a Node process that
35+
leaf neither names nor sees. Where that process ends at startup, or never runs
36+
at all, no launch is reached, so `playwright_driver()` reports it beside the
37+
failures above rather than through them.
3338
"""
3439

3540
import os
3641
import re
3742
import shutil
43+
from contextlib import contextmanager
44+
from pathlib import Path
3845

3946
VARIABLE = "LEAF_BROWSER_EXECUTABLE"
4047
VARIABLES = (VARIABLE, "CHROME_PATH", "CHROME_BIN")
4148

49+
# Playwright runs its driver under Node, and reads this for the executable. It is
50+
# not leaf's namespace, but it is the only knob over the process whose failure
51+
# `playwright_driver()` reports, so the message that reports one names it.
52+
DRIVER_VARIABLE = "PLAYWRIGHT_NODEJS_PATH"
53+
4254
# Chrome first, so discovery reaching a host that also has a Chrome would land
4355
# where the channel already does.
4456
COMMANDS = (
@@ -75,6 +87,108 @@ def discovered_executable() -> str | None:
7587
return None
7688

7789

90+
class DriverNotStarted(Exception):
91+
"""Playwright's driver ended before it answered the connection, so no browser
92+
was ever asked for. Carries that connection's own first line, which each gate
93+
reports in its own words as it does a failed launch."""
94+
95+
96+
def driver_node() -> str:
97+
"""The Node that Playwright runs its driver under: whichever DRIVER_VARIABLE
98+
names, else the one bundled in the installed wheel.
99+
100+
Both readings are Playwright's, made here from the package's own location
101+
rather than through `playwright._impl._driver`: this runs only on the path
102+
where the driver already failed, and a private that moved would put the
103+
traceback back."""
104+
if named := os.environ.get(DRIVER_VARIABLE):
105+
return named
106+
import playwright
107+
108+
return str(Path(playwright.__file__).parent / "driver" / "node")
109+
110+
111+
def driver_hint() -> str:
112+
"""The line each gate appends when the driver never started.
113+
114+
The two hosts this reaches are a glibc older than the bundled Node needs and a
115+
DRIVER_VARIABLE naming a Node older than the driver bundle needs. The first
116+
fails in the loader naming the binary, the second inside the bundle naming
117+
nothing, and neither says which Node ran or what chooses it — so the hint says
118+
both."""
119+
node = driver_node()
120+
if os.environ.get(DRIVER_VARIABLE):
121+
return f"{DRIVER_VARIABLE} named {node}."
122+
return f"Playwright ran its bundled {node}; {DRIVER_VARIABLE} names another."
123+
124+
125+
@contextmanager
126+
def playwright_driver():
127+
"""Playwright, with a driver that never started raised as DriverNotStarted
128+
rather than as a Playwright private.
129+
130+
`sync_playwright().__enter__` returns `self._playwright`, which the connection
131+
callback assigns. A driver that exits at startup never runs that callback, so
132+
the context entry dies on an AttributeError naming that attribute while the
133+
real cause sits on the connection's init task — printed afterwards, out of
134+
order, as asyncio's `Task exception was never retrieved`. Reading that task is
135+
what both names the cause and keeps the second traceback from being printed at
136+
all.
137+
138+
A driver the host named but does not have fails one step earlier, in the spawn,
139+
and that OSError names the file. It reads as the same DriverNotStarted, so both
140+
hosts get one line — but its manager is left unentered and unexited, which is
141+
what `with` did too: Playwright's stop asserts a transport handle the failed
142+
spawn never assigned, so exiting a failed entry replaces the reason with a
143+
private of its own."""
144+
from playwright.sync_api import sync_playwright
145+
146+
manager = sync_playwright()
147+
try:
148+
playwright = manager.start()
149+
except AttributeError as error:
150+
# The driver ran and stayed silent, so the connection stands: its reason is
151+
# readable, and stopping it is what reaps the process and the loop.
152+
reason = _driver_failure(manager)
153+
manager.__exit__()
154+
raise DriverNotStarted(reason) from error
155+
except OSError as error:
156+
raise DriverNotStarted(_spawn_failure(manager, error)) from error
157+
try:
158+
yield playwright
159+
finally:
160+
manager.__exit__()
161+
162+
163+
def _spawn_failure(manager, error: OSError) -> str:
164+
"""Why the driver never ran, in one line.
165+
166+
The spawn's own error says it. Reading the transport's error future as well is
167+
what keeps asyncio from printing that same error a second time as an
168+
unretrieved future, the way reading the init task does for a driver that ran."""
169+
transport = getattr(getattr(manager, "_connection", None), "_transport", None)
170+
future = getattr(transport, "on_error_future", None)
171+
if future is not None and future.done() and not future.cancelled():
172+
future.exception()
173+
return str(error).strip().splitlines()[0]
174+
175+
176+
def _driver_failure(manager) -> str:
177+
"""Why the connection ended, in one line.
178+
179+
The reason is an exception on the connection's init task, reachable only
180+
through Playwright privates. Every reading is optional here and a plain
181+
sentence stands in for a missing one, because this runs on the path whose
182+
whole point is that an attribute error stops being what the reader sees."""
183+
task = getattr(getattr(manager, "_connection", None), "_init_task", None)
184+
if task is None or not task.done() or task.cancelled():
185+
return "the driver ended before answering"
186+
error = task.exception()
187+
if error is None:
188+
return "the driver ended before answering"
189+
return str(error).strip().splitlines()[0]
190+
191+
78192
def launch_browser(p):
79193
"""The host's browser, and what to call it in a message that reports
80194
success: whichever executable a browser variable names, else the installed

‎skills/leaf/scripts/leaf/render_gate/command.py‎

Lines changed: 38 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,13 @@
66
from leaf.revision_artifact import RevisionArtifact
77
from leaf.structure import SourceDocument
88

9-
from .browser import browser_hint, launch_browser
9+
from .browser import (
10+
DriverNotStarted,
11+
browser_hint,
12+
driver_hint,
13+
launch_browser,
14+
playwright_driver,
15+
)
1016
from .preview import preview_server
1117
from .version import RENDER_VIEWPORTS, render_version
1218

@@ -23,31 +29,38 @@ def render_check(
2329
invariants on it. A browser is part of this gate: if it cannot launch, the
2430
gate fails."""
2531
from playwright.sync_api import Error as PlaywrightError
26-
from playwright.sync_api import sync_playwright
2732

28-
with (
29-
preview_server(
30-
page_dir,
31-
document,
32-
revision,
33-
transition_held=transition_held,
34-
artifact=artifact,
35-
) as url,
36-
sync_playwright() as p,
37-
):
38-
try:
39-
browser, browser_name = launch_browser(p)
40-
except PlaywrightError as error:
41-
print(
42-
"✗ render check failed — no browser launched: "
43-
f"{str(error).strip().splitlines()[0]}. {browser_hint()}",
44-
file=sys.stderr,
45-
)
46-
return 1
47-
try:
48-
failures = render_version(browser, url)
49-
finally:
50-
browser.close()
33+
try:
34+
with (
35+
preview_server(
36+
page_dir,
37+
document,
38+
revision,
39+
transition_held=transition_held,
40+
artifact=artifact,
41+
) as url,
42+
playwright_driver() as p,
43+
):
44+
try:
45+
browser, browser_name = launch_browser(p)
46+
except PlaywrightError as error:
47+
print(
48+
"✗ render check failed — no browser launched: "
49+
f"{str(error).strip().splitlines()[0]}. {browser_hint()}",
50+
file=sys.stderr,
51+
)
52+
return 1
53+
try:
54+
failures = render_version(browser, url)
55+
finally:
56+
browser.close()
57+
except DriverNotStarted as error:
58+
print(
59+
f"✗ render check failed — Playwright's driver did not start: {error}. "
60+
f"{driver_hint()}",
61+
file=sys.stderr,
62+
)
63+
return 1
5164
if failures:
5265
print(
5366
f"✗ index.html: renders broken — {len(failures)} issue(s)",

‎skills/leaf/scripts/leaf/validation.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,12 @@ end-to-end render-check tests run the launches used here — the installed Chrom
5454
channel, and the headless shell handed over under each variable that names one —
5555
and a unit reading covers the PATH search, which is only reached where the channel
5656
misses. `version export` launches through the same helper, so the two move together.
57+
Under every one of those launches sits Playwright's driver, a Node process the
58+
wheel bundles and `PLAYWRIGHT_NODEJS_PATH` replaces. Where that process ends at
59+
startup, or never runs at all, no launch is reached, so both gates report it as
60+
one line of their own — why the driver stopped, the Node that ran, and the
61+
variable that chooses one — rather than letting Playwright's context entry, or
62+
its cleanup after one, raise a private attribute.
5763

5864
The browser's authored-state conflict check considers only surviving reader actions
5965
made before the revision being checked. Actions made on that revision already saw

0 commit comments

Comments
 (0)