Compare commits

...
Author SHA1 Message Date
feder-cr 65fab67ec4 hunt: the text bytes of the idwr candidate engine on windows-2022, windows-2025 and ubuntu 2026-11-15 17:52:54 +01:00
feder-cr 0d34e6cc99 hunt: the bytes a page reads with one seed on windows-2022, windows-2025 and windows-2022 with one font more 2026-11-15 14:14:55 +01:00
Federico Elia 1d3d149cb6 Merge pull request #496 from oss-invisible/release/0.52.1
Release 0.52.1
2026-11-15 13:00:30 +01:00
Federico Elia 5ee935268a Merge pull request #505 from oss-invisible/fix/linux-e2e-close-and-compositing
Linux: the virtual display stops off the loop, and an engine process is known by its executable
2026-11-15 12:27:28 +01:00
feder-cr 4416b088d7 Linux: the virtual display stops off the loop, and an engine process is known by its executable
Two red tests of the e2e Linux leg on release/0.52.1 (run 43701692047), each a real defect:

1. The async close called `time.sleep` on the loop's own thread: `_teardown` stopped the virtual display
   inline, and the stop waits for the Xvfb to exit (`Popen.wait`, a loop of sleeps on POSIX). Windows has
   no Xvfb, so only Linux saw it. The stop now goes off the loop like the start, through `_take_display`,
   the counterpart of `_plan_headless`, used by both teardowns (sync inline, async with `off_the_loop`).

2. The GPU-process test counted only the parent on Linux: `_cpu_by_type` kept processes NAMED firefox, and
   a Linux child names itself after its role ("Web Content", "Isolated Web Co", "forkserver", from
   /proc/<pid>/comm) while its executable is the firefox binary (WSL, firefox-64). An engine process is now
   known by its executable. Linux has no GPU process (software WebRender composites in the parent): the
   test says so and holds the parent to 3.5 s, from 20 runs on the ubuntu-latest runner (run 43707494271:
   parent 2.11 to 2.46 s, median 2.31; no GPU process in any run).

Red on the old code and green here, in WSL with the e2e: the loop test (['sleep'] on the loop's thread) and
the GPU test (seen: ['parent']). Two unit tests for the engine processes (19 in wrapper.unit.compositing,
was 17); the Linux child test is red on the old code.
2026-11-15 12:12:46 +01:00
Federico Elia 8516470e95 Merge pull request #504 from oss-invisible/tests/udp-bench-linux-close
tests: a closed fake STUN server wakes and ends its thread on Linux too
2026-11-15 11:34:25 +01:00
feder-cr f0c60c0f0c tests: a closed fake STUN server wakes and ends its thread on Linux too 2026-11-15 11:06:06 +01:00
Federico Elia 5994a6cfd8 Merge pull request #502 from oss-invisible/tests/udp-bench-robust
tests: the UDP bench survives a loaded Windows machine and its verdict says what it saw
2026-11-15 10:57:01 +01:00
feder-cr e7f1c85225 Merge remote-tracking branch 'origin/release/0.52.1' into tests/udp-bench-robust
# Conflicts:
#	ci/required-suites.json
2026-11-15 10:52:24 +01:00
Federico Elia 5d3ac3bc7c Merge pull request #501 from oss-invisible/tests/software-compositing-declared
tests: software compositing is declared (compositor, GPU-process CPU, page-readable bytes against a recorded reference)
2026-11-15 10:51:59 +01:00
feder-cr 39128592a4 Merge remote-tracking branch 'origin/release/0.52.1' into tests/software-compositing-declared
# Conflicts:
#	ci/required-suites.json
2026-11-15 10:45:27 +01:00
Federico Elia a973088192 Merge pull request #503 from oss-invisible/perf/close-off-the-loop
perf: the async close of an in-process browser does not hold the user's event loop
2026-11-15 10:44:29 +01:00
Federico Elia b2d424925a Merge pull request #498 from oss-invisible/perf/engine-born-in-the-job
A launch no longer scans the machine to bind the engine's tree: the core creates the engine inside its job
2026-11-15 10:44:19 +01:00
Federico Elia c489db7937 Merge pull request #499 from oss-invisible/perf/virtual-display-off-the-loop
perf: the virtual display of headless=True starts off the event loop
2026-11-15 10:44:09 +01:00
Federico Elia 0706164f58 Merge pull request #481 from oss-invisible/tests/bfcache-worker-contract-both-outcomes
tests: the worker/back-forward-cache test writes down what happened before it asserts and asserts the worker's contract for both outcomes of a goto
2026-11-15 10:44:04 +01:00
feder-cr a09233152c changelog: the close off the loop is #503 2026-11-15 10:20:22 +01:00
feder-cr 7cd92712ab perf: the async close of an in-process browser does not hold the user's event loop
Closing one of four browsers in one process stopped the loop that serves the
other three for as long as the close waited. Three waits ran on it:
`InProcessTransport.request_stop` ran `server.shutdown()` (the hooks that wait for
the engine's tree, and the removal of its directories), `wait_until_stopped`
joined the workers, and `_teardown` reaped the session's token.

Now the shutdown runs on a non-daemon thread ("juggler-shutdown") that settles the
stop when it ends; the joins and the reap go through the core's `off_the_loop`
(invisible-core 64.72.0). The sync path is unchanged. `BrowserDispatcher.op_close`
stays on its worker: the four workers belong to the server of one
InvisiblePlaywright, so its wait holds no other session's calls (the test shows the
other three answering).

Test: four real engines in one async process, one closes; the loop is held less
than 50 ms by the clock of its own thread (the instrument of the core's test), no
blocking step runs on its thread, the other three keep answering. Registered in
wrapper.e2e.page (115 -> 120).
2026-11-15 10:15:50 +01:00
feder-cr 2be9b6046a Pin invisible-core 64.73.0 for 0.52.1: software compositing declared, the engine born in its job, a close off the loop 2026-11-15 10:10:53 +01:00
feder-cr c43d787ce9 tests: the UDP bench survives a loaded Windows machine and its verdict says what it saw
The red of the far-gateway srflx test was unreadable under CPU saturation:

- FakeStun read with a socket that still reported ICMP port-unreachable (SIO_UDP_CONNRESET): the next recvfrom raised ConnectionResetError and `except OSError: return` ended the thread that answers, silently. It now turns the ioctl off, continues on a reset, and continues (not returns) on a failed sendto unless it is closing.
- The relay's inbound thread read out.getsockname() at every datagram, which fell on a closed socket at the teardown (WinError 10038, an unhandled thread exception). The port is read once and an OSError of the body ends the thread cleanly.
- The verdict of _gather_behind_a_coherent_gateway now carries the gateway's send errors, CONNECTs, accepted connections, associations, the datagram log with times and the UDP verdict the core declared for the proxy; a measure that is not coherent is said outright with the round trip. The outcome of the test is unchanged.

Each fix has a unit test that fails on the old code (registered in wrapper.unit.udp, 249 -> 258).
2026-11-15 09:53:43 +01:00
feder-cr f094102fab tests: the page-bytes reference of the core 64.71.0 on Linux and Windows, recorded by run 43661728392 (97 keys, all stable in 2 launches) 2026-11-15 02:11:53 +01:00
feder-cr aa53d6ea06 tests: the page-bytes probe reads WebGPU features and limits by name
Array.from(adapter.features) and for-in over adapter.limits threw "Xray wrapping of iterators not
supported" in the page (run 43652292533), so the reference held an error string instead of the
adapter. Both are read by the names of the WebGPU specification (has, a property read). The
Windows reference drops gpu.webgpu.error; features and limits are recorded with the rest.
2026-11-15 01:54:44 +01:00
feder-cr 4b2fb63fe6 tests: software compositing is declared: the compositor, the GPU process CPU and the bytes a page reads
The core now declares software compositing on every machine (the compositing entries of the
feature-status table carry the VM decision; on Windows gfx.webrender.software=true and
gfx.webrender.software.d3d11=false). One e2e file, three tests, Linux and Windows:

1. windowUtils.layerManagerType of the engine's windows, read in chrome scope through Marionette,
   is "WebRender (Software)" (Troubleshoot.snapshot().graphics throws on this engine, so the
   provider's own two properties are read), and the declared table and prefs say so;
2. the GPU process uses under 1.5 s of CPU on the fixed 10-scene loop of one browser (Windows
   runner: 0.32 s declared, 2.7-4.2 s not; runs 43652292533 and 43642744101);
3. the 86 keys of the page-bytes probe plus canvas 2D scenes added for the canvas blocklist
   (drawImage scaled with smoothing off/low/medium/high, text with linear/radial/conic gradients)
   equal tests/data/page_bytes_<os>.json, PNGs compared on decoded pixels (every PNG carries a
   per-launch deBG chunk).

The Windows reference is taken from run 43652292533 (75 stable keys, 6 of the 11 PNG keys); what it
lacks is recorded by the first run on the engine of the reference, whose failure prints the entries.
Registered as wrapper.e2e.compositing (G2, both systems, 3 tests) and wrapper.unit.compositing (G1,
17 tests, the helpers on known inputs).
2026-11-15 01:53:32 +01:00
Federico Elia 83afc6c8d5 tests: the leak census imports nothing of the package (#500)
The census answers from sys.modules, so the jobs that install pytest alone (version) do not import the core.
2026-11-15 00:39:24 +01:00
feder-cr 163315c114 tests: the leak census imports nothing when no starter could have been built, so it runs in jobs without invisible_core 2026-11-15 00:26:20 +01:00
feder-cr 578763389d headless: one decision for the sync and the async start of the hidden display
`_resolve_headless` and `_resolve_headless_async` each carried a copy of the
decision (headless off, true headless, which display to build). `_plan_headless`
now makes it once and returns (pw_headless, display to start); the sync client
starts the display inline, the async one in a worker thread.

Test: the same inputs (headless False/True, INVPW_TRUE_HEADLESS set or not, a
platform with or without a display) give the same decision on both paths.
2026-11-15 00:19:45 +01:00
feder-cr 3a97b05708 async: the hidden display starts in a worker thread, not on the user's loop
`__aenter__` started the virtual display (an Xvfb on Linux: spawn, wait for
-displayfd) synchronously on the caller's event loop, with headless=True. Four
browsers in one process each froze the other three for ~75 ms per launch, far
more on a loaded host. The display is still created before the prefs are
composed (it is the hidden-headed surface the product promises); the async
path now awaits its start in a worker. A launch cancelled while the worker runs
releases the display when the worker ends. The sync path is unchanged.

Test: a stand-in display whose start takes 500 ms; a second browser on the same
loop is served within 100 ms (522 ms before), and a cancelled launch leaves no
display behind.
2026-11-15 00:08:14 +01:00
Federico Elia 91e69710eb perf: connect() starts no thread on the event loop (#497)
The four workers of a connection are built on the loop and started by the connection's one thread starter, the same one the engine's reader uses.
2026-11-15 00:07:27 +01:00
feder-cr cf328bf481 perf: one ThreadStarter per connection, owned by the server
The previous commit gave each browser two starter threads (the
BrowserDispatcher's for the reader, the transport's for the workers). Now the
connection's server (dispatcher.Server) owns a single ThreadStarter, built on
first use (Server.thread_starter) and stopped once, in Server.shutdown, which
the transport's request_stop already calls.

The transport starts its four workers through it (start_built, with a
per-thread failure callback that ends the transport). BrowserDispatcher holds
a ThreadStarterLease on it instead of building a starter: start() while the
browser's connection lives, nothing after the connection's close listener ran,
the same semantics the browser's own starter had. A browser that never needs a
thread makes none.

Remote: remote._SharedServer is a Server, so the shared server owns the one
starter (one browser per served launch; contexts and clients come and go under
it, shutdown ends it). Several browsers launched under one local server share
the one thread, which is why the lease, not the starter, ends with a browser's
connection.

Measured, live threads per browser right after a launch (transport.connect, a
BrowserDispatcher over the unit fixture's engine, one adoption started):
65b7a3c: 6 (invpw-thread-starter x2, juggler x4); now: 5 (starter x1,
juggler x4). Same at 4 browsers: 24 -> 20. All gone after close.

Tests that built a Server and only closed the connection now shut the server
down; the fake servers of the transport tests derive from Server.
2026-11-14 23:54:52 +01:00
feder-cr 65b7a3c3bc tests: the census counts a ThreadStarter from its construction, not from its thread
ThreadStarter now begins its own thread without waiting for it
(_thread.start_new_thread running Thread.start), so right after the constructor
the starter can be in no threading.enumerate(). The census of live
"invpw-thread-starter" threads then saw 0 leaks where a module built 2 (Linux
runner, 3 of 3 jobs: the inner pytest passed). Not a rename, not a wrong
count: a census of threads cannot see a thread that has not begun.

Fix at the source of the count: ThreadStarter keeps the set of starters built
and not yet ended (open_starters()), and the census counts that. The "no
Thread.start on the caller" guarantee is untouched.

Test, red on the old census (Thread.start slowed to 300 ms: the census sees 0
right after the constructor, expected 1): the census counts a starter whose
thread has not begun.
2026-11-14 23:30:58 +01:00
feder-cr 5fda215266 A launch no longer binds the engine's tree: the core creates the engine inside the job
InvisiblePlaywright._bind_process_tree called the core's JobObjectGuard.bind at
every launch (every process of the machine scanned, environment read, until a
second passes with nothing new: 12-29% of the launching thread on Windows). The
core now creates the engine inside the process's job object, so the tree is in
the job by construction and there is nothing to adopt. The method and its five
call sites are removed.

Needs the core release that carries engine_job / adopt_and_resume (the exact
invisible-core pin of the release that ships this). Tests, e2e on the real
engine: a launch makes no psutil.process_iter / Process.environ call; after
close() no process of the session is left; a client killed with TerminateProcess
leaves no engine process.
2026-11-14 23:13:46 +01:00
feder-cr 05190ed5e9 comment: the starter is called ThreadStarter now 2026-11-14 22:52:58 +01:00
feder-cr cfbf1889a8 perf: one ThreadStarter, shared, for the reader and for the transport's workers
Replaces the second bootstrapper (_thread.start_new_thread running a loop that
starts the workers) with the ThreadStarter the engine's reader already uses, so
one mechanism lives in one place: src/invisible_playwright/_juggler/_threads.py,
imported by server.py and transport.py.

ThreadStarter's own construction no longer calls Thread.start on its caller
either: its thread is begun by _thread.start_new_thread running Thread.start, so
the wait for the starter to run happens on that raw thread. It is still a
threading.Thread named invpw-thread-starter (alive a moment after the
constructor returns). connect() builds the four juggler-N threads, queues them
with start_built() and returns; request_stop stops the starter; a start that
fails ends the transport.

Tests: the connect() test stays red on origin/main (1202 ms against the 50 ms
bound) and a new one covers building the starter with Thread.start slowed to
300 ms. The two tests that import the starter now import it from _threads.
2026-11-14 22:52:50 +01:00
feder-cr 2d2204898e perf: InProcessTransport.connect starts no thread on the event loop
connect() is a coroutine of the user's loop and Thread.start() blocks until
the new thread runs. Measured on Windows CI (py-spy, 4 browsers in one
process under CPU load), the 4 "juggler-N" starts held the loop ~200 ms per
launch, 4.4% of the main thread's wall time.

Shape: connect() only BUILDS the 4 Thread objects (so request_stop still
puts one sentinel per worker) and begins one bootstrapper with
_thread.start_new_thread, which returns once the OS made the thread and
waits for nothing. A threading.Thread for the bootstrapper would be one more
Thread.start on the loop, so it is not used. The bootstrapper starts the
workers. Messages sent before a worker runs wait in the queue, as send()
already relied on; replies are matched by id, so no ordering is lost.

Workers are not reduced: a blocking operation must not hold up the others,
and nothing in the code or tests proves fewer suffice. A start that fails
stops the transport instead of leaving calls waiting; wait_until_stopped
joins only workers that were started.

Test (red on old code: connect took 1202 ms vs the 50 ms bound with
Thread.start slowed to 300 ms): tests/test_connect_does_not_start_threads_on_the_loop.py.
2026-11-14 22:52:35 +01:00
feder-cr 384351d4a3 Release 0.52.1: expose_function/expose_binding, element screenshot, init script once, CORS preflight not reported 2026-11-14 21:23:50 +01:00
feder-cr a14da2127e Merge #468 into release/0.52.1 2026-11-14 21:23:24 +01:00
feder-cr b60b5c5e8c Merge #471 into release/0.52.1
# Conflicts:
#	CHANGELOG.md
2026-11-14 21:23:24 +01:00
feder-cr 252036e2fc Merge #470 into release/0.52.1
# Conflicts:
#	CHANGELOG.md
2026-11-14 21:23:23 +01:00
feder-cr 0f7a9a2905 Merge #469 into release/0.52.1
# Conflicts:
#	CHANGELOG.md
2026-11-14 21:23:22 +01:00
feder-cr 112467f5ad Merge #467 into release/0.52.1
# Conflicts:
#	CHANGELOG.md
2026-11-14 21:23:21 +01:00
feder-cr 22d8abc9ba Merge #458 into release/0.52.1 2026-11-14 21:23:12 +01:00
feder-cr a743dbbbf7 tests: the relay page waits for the frame it writes to
The two sibling frames load in two processes, in no fixed order. The top page
relayed the first frame's message at once, and when the second frame's document
was not there yet the message was lost, as it would be in any browser: one CI
run in three never saw the answer. The top now holds a message until the load
event of the frame it is for.
2026-11-14 21:23:11 +01:00
feder-cr f7873501e2 tests: the cross-site iframe proof reads the frame after the page's load, not its domcontentloaded
The domcontentloaded of a page says nothing about its frames: the url of a frame of another site is
the url of its navigation, which commits in the frame's own process, usually after it. Read straight
after a domcontentloaded goto the url was empty in 26 of 30 reads on firefox-62 and in 5 of 21 runs of
the test; after the load of the page it was there 30 of 30, on stock Firefox too. The test now goes to
the page with the default load and asserts the url with no wait.
2026-11-14 21:23:11 +01:00
feder-cr bcf47c7dde tests: the frame of B reads its own partition, not an empty one
The reverse half of the partition test expected an empty cookie string in the
frame of B inside A. The frame has its own partition, and the two cookies it
wrote earlier in the test are in it: what must be absent is what B wrote as a
top page. The first CI run showed it; the first half already passed there.
2026-11-14 21:23:11 +01:00
feder-cr fcfbed215e tests: site B's storage is partitioned between a frame of A and B as a top page (retail outcome)
The reference for what a page reads is retail Firefox, which partitions cookies and storage by
top-level site; Playwright's own Firefox has that off. The test now asserts that B opened as a top
page sees an empty document.cookie and a null localStorage item for what B wrote inside a frame of A
(context.cookies() still lists B's cookies), and the reverse.
2026-11-14 21:23:11 +01:00
feder-cr b0b4f02d7c tests: end-to-end tests for iframes under Fission, and a cross-site harness for the cross-origin file
New files hold the gaps of the frame tests, each with a proof that the frame is in another
process: the frame tree A > B > A > C, typing and waits, clicks under a transform and after
scrolling, screenshots; routes, exposed functions, init scripts, postMessage; dialogs,
downloads and popups started in a frame; workers, storage and special frames; history and
processes left behind by a closed context. tests/_fission_frames.py holds the three sites
(127.0.0.1, localhost, 127.0.0.2) and the process proof they share.

test_cross_origin_iframe.py now serves its iframes from localhost while the page stays on
127.0.0.1 (two ports of one host are one site and never crossed a process), and proves it.
2026-11-14 21:23:11 +01:00
feder-cr d842a35ffa page.expose_function / expose_binding and context.expose_function / expose_binding
All four were refused ("not wired", "no method 'exposeBinding'"). The page calls a Python function and gets a promise: the value, a
rejection when the Python function raised, an await when it is async.

The page sees the function and nothing else. One engine binding per exposed name (Browser.addBinding for a context, Page.addBinding for
a page), under a native name chosen per session. The engine puts the native function on the window of every document, present and future,
in every process, before any script of the page, and runs the binding's script. The script takes the native function off the window, keeps
it in a closure, defines the function (an ordinary function; its source says nothing of what it is for) and hands the engine the function
that answers a call. Answers go through Runtime.callFunction on it. No init script, no controller, nothing run by this server in the
documents.

An engine without Page.addBinding and the binding that hands its end over is refused with a clear sentence: there is no fallback to a name
on the window. The engine is read from its own files (protocol schema and Runtime).

Calls are announced to the client in order by one worker per page, started by the browser's thread starter (never on the reader), and not
before the client has been told the address of the document that called: a script that calls the function in its first lines ran before the
commit reached the client and named a frame with an empty url. A name nobody exposed here is answered with an error instead of leaving the
page's promise waiting.

Limit: arguments and results cross as JSON (undefined, functions and NaN arrive as null).

Tests: e2e (before the load and across a navigation, after the load, async and a Python error, source page/frame, not on another page, on
the context for a page that exists, a page to come and their frames, disposed; the window of a page with an exposed function has its name
more and no symbol more, in the top, in a frame of another site, in a nested one, after a navigation and after document.open(); name, length,
own properties, descriptor, prototype and place among the keys are those of a function the page defined; neither its source nor the stack of an
error raised from it names the driver; a worker gets nothing) and the refusal of an engine that lacks what the functions need.
2026-11-14 20:07:15 +01:00
feder-cr 1832ea6323 Locator.screenshot / ElementHandle.screenshot: a picture of the element
The wrapper had no `screenshot` on an element handle ("ElementHandle has no method 'screenshot'"). The element is scrolled in, its box is
read from the engine's content quads (the main frame's viewport space, whatever frame the element is in, across processes), the main
frame's scroll is added to reach document coordinates, and the page's own screenshot takes that rectangle, so the type, the quality and
the scale have one path. An element with no layout box (display: none, detached) answers "Element is not visible".

Tests: an element in view, one far below the fold, one inside a frame below that frame's fold, and the <iframe> element itself; the
element that is not there. The Fission frame tests for a frame of another site, a nested one and the <iframe> element (draft #468) pass:
4 of 4 (3 were red on main).
2026-11-14 20:07:12 +01:00
feder-cr b3eb6c3733 tests: the worker/back-forward-cache test asks for the commit order of a worker only of an engine that promises it (firefox-63)
Juggler f284ca703e (PageHandler._commitNow ends the workers below the frame before it announces the commit) is in firefox-63; the published firefox-62 does
not promise it, and main's e2e runs on both: run 43193233155 had Page.navigationCommitted before Page.workerDestroyed for [top-same-site-goto] on the published engine.
On an engine that does not promise the order the test still requires the worker to be told ended (it waits for it), and asserts the order where it is promised.
2026-11-14 19:34:09 +01:00
feder-cr 1d7204ffe6 tests: the worker/back-forward-cache test writes down what happened before it asserts, holds the cache's two host inputs still, and asserts the worker's contract for the outcome of a goto (restored, or built again)
The e2e of the hunt of 2026-11-12 was red once in 30 runs for [top-other-site-goto] with only 'the page was loaded again'. With the evidence
written before the assertion and the SHIPBFCache log, the cause is Firefox's: for a navigation the PARENT starts (goto, to the same site or another)
the parent's CanonicalBrowsingContext::AllowedInBFCache can find the navigation's own DocumentChannel as the single request of the old document's
loadgroup ('* requests in the loadgroup'): 15 of 56 goto sessions in a container on the candidate, never for the page's own navigation (location).

* the page must be cacheable before the test leaves it (every document has had its pageshow), and the lab fixes browser.sessionhistory.max_total_viewers and
  the low-commit-space thresholds so that the memory of the runner does not decide whether the cache holds;
* the evidence (__shown, the type of the navigation entry, the readyState, the protocol events since go_back) is written before the assertion;
* for a goto the test says which outcome happened and asserts the contract of THAT outcome whole: restored (same worker id once, no workerDestroyed, the page's
  count), or built again (the old worker ended once before the new commit, exactly one new worker with a new id, the only live one, answering 1);
  a restore the engine announced that the page did not see fails in both; the page's own navigation must restore. No repeat, no skip.

Unit tests (no browser): the evidence is written before the assertion and carried by the message, a reload is accepted only for a goto, the lab holds the
two host inputs, the test file has no repeat or skip.
2026-11-14 19:34:08 +01:00
Federico Elia b14d1deacd docs: canvas page says what holds across OSes, not byte-identical hashes (#452) 2026-11-14 18:31:06 +01:00
Federico Elia 0aae7f73f1 e2e: the dot() vectors reach the page as float bits, so the zeros keep their signs (#434)
The vendored client sends every Python 0.0 as -0 (value == float('-0') is true for both zeros), so the 64 rows of zeros of both signs reached the page with the wrong signs and the Windows gate failed on those lanes only (dot2 21, dot3 10, dot4 6 of 4096, all at indices >= 4032; the random lanes all matched the chain).
2026-11-14 18:31:00 +01:00
feder-cr 1b974cd964 A context init script added after a page exists runs once, not twice
op_context_init_script registered the script on both sides: in the browser (Browser.setInitScripts, which the engine applies to every
page of the context, the pages already open included) and again in the own list of each open page. The comment said the open pages
do not re-read the context's list; they do. A page that existed when the script was added ran it twice in every later document; a
page opened afterwards ran it once, so any test that adds the script first passed. Found by the Fission frame tests (the document of
the top page saw ["init","init"]).

The script is registered once, in the browser, and removed from there. Test (e2e, hermetic): a page that exists before the script and
one opened after it each see ["init"], in the first document and in the next one. Red on the old code (['init', 'init']).
2026-11-14 16:06:13 +01:00
feder-cr 2c8bfa12da A CORS preflight is not a request the client hears of, as on stock Firefox
Playwright's own server drops an OPTIONS request that no route holds before the client can see it (ffNetworkManager
_onRequestWillBeSent: `if (event.method === "OPTIONS" && !event.isIntercepted) return;`). Ours reported it: a page with
preflighted fetches showed more requests than on stock Firefox, 10 OPTIONS a page on cnbc.com and 18 on scmp.com (three
pairs, our engine and Playwright's Firefox side by side), in page.on("request"), in a route and in any request counter.

The server drops the same requests now, at the place where the event is turned into a request of the client; the response and the
end of a dropped request find no request and are dropped with it.

Test (e2e): a page at one origin fetches another with a header that needs a preflight; the client hears the document and the two
fetches and no OPTIONS, with and without a context route. Red before.
2026-11-14 16:06:13 +01:00
feder-cr 8d48c4a472 Remove scripts that no test round runs
- scripts/check_unresolved_names.py: replaced by the ruff F821/F811/F601 step in .github/workflows/tests.yml.
- scripts/bench_transport.py: one-off measurement that asserts nothing.
- scripts/diff_protocol.py: needs the Node driver arm, which was removed.
- scripts/judge_both_transports.py: needs the Node driver arm, which was removed.
- tests/gates/prefs_byte_parity.py: compares with the removed driver's prefs writer.
- tests/gates/driver_prefs_rules.json: frozen rules for that comparison, nothing else reads it.

References to these files in comments, docstrings and THIRD_PARTY_FORK.md are reworded.
2026-11-14 16:00:58 +01:00
Federico Elia 9d217c4911 tests: the census counts its own server, and a module that leaves a browser open fails (#493)
* tests: the census of a closed context counts only its own server's objects

* tests: a module that leaves a browser open fails, and the unit tests that leaked close theirs

A BrowserDispatcher starts the thread "invpw-thread-starter" and stops it only when its connection's close listeners fire. A unit test that
builds one on a fake connection and never closes it left the thread alive, and with it the connection, the browser and every context for the
rest of the worker (23 files, 635 threads in one of them).

- tests/_browser_census.py, registered in conftest.py: a module-scoped autouse check. When the last test of a module has torn down, the live
  starters must be back to what they were before it (a short join: stop is asynchronous), else the module errors with "left N browser(s)
  open: close their connection". Module level, so a module-scoped browser is fine.
- tests/test_a_module_that_leaves_a_browser_open_fails.py: red on a module that leaks, green on one that closes and on one that shares a
  browser through a module fixture.
- the fake connections of the leaking files register themselves with closes_with_the_test(self) in their __init__; an autouse fixture ends
  them when the test ends with announce_closed(), the real path: it fires the close listeners the dispatcher registered. Nothing intercepts
  the starter, so a test that builds a browser on a connection it did not register still leaves the thread and the module check says so.
2026-11-14 14:25:14 +01:00
Federico Elia 45c7450b3e tests: the fake installer of the index wait counts its calls atomically (#495) 2026-11-14 14:00:41 +01:00
Federico Elia 9699a52df9 record 0.52.0 as published (#494) 2026-11-14 13:59:59 +01:00
Federico Elia 77d97d894d egress gate: OCSP of a context goes through its proxy; the Windows native sink is the engine log (#492)
* tests: the egress sink reads the engine log on Windows too, and the OCSP request of a trusted page is held to the proxy of its context

The native-lookup sink is the engine's own log on both systems (the getaddrinfo lines are in the parent process file under the sandbox of Windows and
Linux, run 43574494194): the Windows DNS-Client event-log sink is gone, a blind log raises BlindSink instead of answering nothing, and the suite
wrapper.e2e.context.sink now runs on Linux and Windows.

OCSP: a lab CA the engine trusts (put in the profile by the engine's xpcshell, no ignore_https_errors), a TLS page whose leaf names its OCSP responder by
a name and by an IP, a context behind the gateway that loads it (the request must go through the gateway and never be looked up natively, in user
context 0, or reach the responder), a no-proxy control that is asked of the responder, and an untrusted-issuer control that makes no OCSP request.
Expected red on firefox-63, green on firefox-64.

* tests: the OCSP cases let the engine trust the DoH of the context through the lab CA, so the page name resolves without ignore_https_errors

Run 43584815874: both OCSP cases behind the gateway failed with NS_ERROR_UNKNOWN_HOST before any handshake. The other cases accept the FakeDoh's self-signed
certificate with ignore_https_errors on the context; the OCSP cases cannot (it switches off the chain check, so no OCSP), so the DoH handshake was refused
(SSLV3_ALERT_BAD_CERTIFICATE at the gateway) and the name never resolved. FakeDoh.use_certificate lets the case serve a leaf of the lab CA for the DoH host,
which the profile trusts. Line endings of the touched files are back to those of main.

* required suites: wrapper.unit.udp is 249 (the DoH serving a lab-CA leaf)
2026-11-14 13:30:37 +01:00
Federico Elia e986a0b859 screencast: a frame that arrives while the start is being answered is held and acknowledged, not dropped (#491)
* screencast: a frame that arrives while the start is being answered is held and acknowledged, not dropped

The engine keeps one screencast frame in flight until the wrapper
acknowledges it (kMaxFramesInFlight is 1, and its heartbeat only repeats a
frame when none is in flight), so a frame the wrapper drops without an ack is
the last frame of the stream.

op_screencast_start stored the screencast id AFTER send("Page.startScreencast")
returned. The reader thread wakes the caller on the reply and goes straight on
to the next message, so a frame right behind the reply was handled while the
id was still None: dropped, never acknowledged, stream dead with start()
already returned.

The id, a "start in progress" flag and the frame that came in meanwhile are now
one state under a lock; the held frame is handed up and acknowledged once the
id is in. The ack uses the id the frame was accepted under, read once, and the
check-then-set in start/stop/detach is taken under the same lock.

tests/test_screencast_ack_race.py drives the engine's own flow control through
a reader thread shaped like Connection: 200 start cycles in 4 threads with
random gaps between reply and frame (84 of 200 stall on the old code, 0 on the
fix), stop in the middle of a frame, a refused start, and a page closed with a
running screencast.

Not reproduced in a real engine: 0 dead streams in about 1300 start cycles on
the old code, because the first frame comes at least 46 ms after the reply and
the window is only the time the caller thread takes to wake.

* tests: the hidden-desktop test serves its own page and says what the engine printed when no frame comes

It loaded https://example.com in both sessions; a gate does not use a real site,
so the page is served from 127.0.0.1 by the test. The checks are the same.

When no screencast frame arrives in 15 s, the assertion message now carries the
browser's lines that start with "screencast:" (the core keeps the last 200 lines
of the browser's output, Connection.output), so a failed run says whether the
engine could not start the capture or the frames did not reach the wrapper.

* tests: a screencast e2e that gets no frame says what the engine printed and how long each stream waited

The helper that reads the engine's "screencast:" lines out of the browser's
output moves to tests/_screencast_evidence.py, with a small Stream that keeps a
stream's frames and the time from the start reply to the first frame. The two
e2e in test_screencast.py (the JPEG of the whole window, and the higher rate
delivering more frames) and the hidden-desktop test now put both in the
assertion message when a stream delivers nothing.

A unit test covers the helper: only "screencast:" lines are kept, a lookup that
fails says so, and a stream with no frame says "never arrived".

* changelog: the screencast frame held during the start (0.52.0)
2026-11-14 12:31:30 +01:00
Federico Elia 64d86b4e8a Release 0.52.0: engine firefox-64 through invisible-core 64.69.0 (#490)
* tests: nothing of a context leaves but through its proxy (witness, engine log and nonce as the sink)

A context with a proxy and a session with none, one probe per road a page can
start: fetch, WebSocket, stun, turn over UDP, turn and turns over TCP, each by
name, by IP and by a .local name, behind SOCKS5 and behind an HTTP proxy. The
sink is a witness at an address of this host (no proxy forwards to it), the
watcher, the engine's own resolver log and the resolver trap where it runs.
The Windows second sink is one function that raises until it is written.

Taken unchanged from the minimal-engine port: the page work of the proxied
context and the TURN-by-name reproducer (its engine gate removed: red on
firefox-63, as it is).

* tests: a PeerConnection of a torn-down window leaves only through the proxy of its context (B3)

A PeerConnection built from the window of a detached iframe or of a closed
popup had no proxy config on the engine firefox-63: direct UDP and TCP from
the host, ICE server names looked up in the default context. Four cases (both
windows, behind SOCKS5 and behind an HTTP proxy) build one with a STUN and a
TURN-over-TCP server by name and judge it with the sinks of the suite; two
controls build the same PeerConnection from an attached iframe. A dead window
that refuses the constructor or never gathers passes the egress assertions and
says so (printed, recorded as dead_window_outcome).

Expected red on firefox-63, green on firefox-64.

* tests: the isolated page moves on when the test says so, not 500 ms after its load

On a loaded Windows runner more than 500 ms passed between domcontentloaded and the first read, which then met the second page or the
move itself (2 rounds in 20 under four workers, runs 43435932449 and 43439508625). The page now moves right after the read on it, by its
own location.replace. Still red on the release before the fix: 0.42.0 with firefox-52 answers 'Cannot find object with id = id-10' in
5 of 5 runs on Linux and Windows, green on 0.51.1 (run 43451615354).

* tests: two contexts alive at once resolve their TURN names each through its own proxy and DoH

Two contexts of one browser, each with its own proxy and its own FakeDoh (a
zone that does not know the other's name), each with a PeerConnection kept
open whose TURN server over TCP has a different name. The port of a CONNECT
(one witness per context, same address) says which context it came from.
Each name must reach only the DoH of its own context through its own proxy,
none the machine's resolver, no CONNECT the other proxy, nothing a witness
direct. Behind SOCKS5 red on firefox-63 and green on firefox-64; behind an
HTTP proxy green on both.

* server: no thread is started on the engine connection's reader; one long-lived starter does it

Thread.start waits until the new thread runs, and the reader is the thread every event of the engine waits behind. Browser.attachedToTarget
(one thread per adoption, _spawn_adoption) and Page.fileChooserOpened (one thread to announce the chooser) started a thread from the
reader. They now hand a Thread that is only built there to the browser's _ThreadStarter, one daemon thread made with the browser, which
starts it. The starter starts threads and does not run the work: an adoption waits for the engine without a limit, and a worker that ran
it would hold every later adoption (and new_page) behind a slow popup. The adoption keeps its own thread and its name.

Test: the real dispatchers over a scripted connection, events delivered from a thread of their own, Thread.start recorded; red on the old
code (two starts from the reader). The Page.eventFired(load) case is skipped with a core that still starts a Timer for networkidle.

* tests: a session without a proxy declares the DoH provider and builtin-excluded-domains = localhost

The core declares network.trr.builtin-excluded-domains = "localhost" (core #261: behind a proxy a *.local name goes to DoH
through the proxy, not to the host's resolver). The unit test pinned the old set of two keys and was red in the engine
candidate 43471799366, which runs the core of main.

* tests: the load case of the reader rule lives in the core, where its fix is; the wrapper keeps its two cases, no skip

* tests: the first browser run of the two context suites, test errors fixed

wrapper.e2e.context.sink: every probe by name behind SOCKS5 (and the TURN names of
the window and two-context cases) never connected, because the lab answers every
name with the address of this host, an RFC 1918 one on a runner, and the engine's
DoH client drops such an answer unless network.trr.allow-rfc1918 is true. The lab
now declares it. turns: by IP is refused by the browser itself ("TLS requires
FQDN, not IP address"), so that case shows no CONNECT and keeps every egress
assertion. The firefox-64 expectations of the three *.local probes were stale
(green in the run).

wrapper.e2e.context.egress: the push case waits for the page to leave pending
(30 s) and says the step it reached (registering, registered, ready,
subscription-read). The direct DoH connection of closing-context_only is an
engine behaviour and its assertion is unchanged.

unit.udp min_tests 233 -> 236 (three new unit tests of the lab).

* tests: the push page asks for its subscription again until the parent's push service answers

The parent process listens for the push requests of a content process only once its
PushServiceParent exists, which a first-window idle task creates (BrowserGlue
PushService.ensureReady); a request sent earlier is dropped, not queued. The page
of the push case now repeats getSubscription every 2 s (up to 15 times) and the
message says how many asks it took. The assertion is unchanged.

* tests: revert the retry of getSubscription and the longer wait (a page that retries hides a request that is never answered); keep the stage diagnostics

* Revert "tests: revert the retry of getSubscription and the longer wait (a page that retries hides a request that is never answered); keep the stage diagnostics"

This reverts commit fbd376c4c4.

* tests: say why the push page asks again (silent start-up, lost Push:Registration, same in stock Playwright), with file:line and the bounded wait

* tests: a process that reads no seccomp filter while it starts is read again before it is judged

Firefox pre-launches content processes and a child installs its filter only after its
own start-up, so a process sampled during start-up reads Seccomp 0 (run 43523960399:
the newest tab process). A pid that does not read 2 is now read again for up to 10 s;
none is dropped, and one that is still 0 fails with the same message. Two unit tests
hold it (a late filter is accepted, a process that stays unfiltered is not);
unit.udp min_tests 236 -> 238.

* Release 0.52.0: pins invisible-core 64.69.0 (engine firefox-64)

* server: say nothing about the launch counter (core 64.69.0 has no pref for it)

From invisible-core 64.69.0 (engine firefox-64) the launch counter has no pref: the engine's address is built in and the
counter is mandatory, so the core has no USAGE_PING_* constants. The server imported them at every launch to refuse the
two prefs, which raises ImportError with core 64. The refusal and its test go; a new test asserts that a launch composes
no launch-counter pref and that the server has no refusal (red on the old server). wrapper.unit.udp: 238 -> 228 tests.

* tests: the keyboard rhythm tests run on a clock that moves with each sleep

invisible-core 64.69.0 sends each key at its planned time measured from the start of the action. The rhythm tests replaced
time.sleep with a recorder and left the clock still, so every later wait carried the earlier ones (13 waits for "hello"
instead of 9, the caller's 120 ms gap never seen). The fixture now stands a clock in the keyboard's place that advances by
each sleep, as the core's own test does; every assertion is unchanged.

* tests: the tests of the shelved line wait for firefox-65

Fifteen e2e files are gated on engine_at_least("firefox-64"), set on 11/11 when firefox-64 was the name of the shelved line
(canvas text and ICC from DirectWrite/ucrt work, ucrt Math and calc, the NVIDIA fma chain, WebGL blending, system fonts and
colours, WebCodecs H.264, no host fontconfig/Mesa/libavcodec). The engine released today as firefox-64 is the context/UDP
line and carries none of that work (nor does core 64.x carry its core half), so the gates opened and the tests failed. The
shelved line is now firefox-65; the gates follow it, as they did at 0.50.0.

* Release 0.52.0: pins invisible-core 64.70.0 (64.69.0 refused a page built on the connection's reader)

* memprobe: stamp and write a row under one lock so the file stays in time order

The tick thread and the thread that closes a context both call write().
The row was stamped in sample() before the lock was taken, so a slow
sample (USS on Windows, a big gc) let a later row be written first.
Adds a test that holds the first sample after its stamp and lets a second
writer overtake it.

* Release 0.52.0: pins invisible-core 64.71.0 (a key never reaches the page closer than the plan allows)
2026-11-14 11:08:43 +01:00
Federico Elia c3e0570e6d record 0.51.1 as published (#487) 2026-11-13 15:19:08 +01:00
Federico EliaandClaude Opus 5.5 fcacd9c33d Release 0.51.1 (#486)
* juggler: a popup's page is handed from its buffer to its dispatcher in one step, so no commit or load between the snapshot and the hook is lost (DRAFT)

What the client is told of a frame comes from the initializer (a snapshot of what the lifecycle knew when the frame dispatcher was made)
and from the lifecycle's announcements through a hook that the page installs at the end of its construction. An event the lifecycle heard
after the snapshot and before the hook was told to nobody: the commit of a popup's destination left the client's frame at about:blank for
good, and the DOMContentLoaded/load held in the same period were dropped with every held event that is not a Network.* one. Measured on
Windows with the in-process client and no route on the context: the popup "is at about:blank", or wait_for_load_state("load") times out.

_hear_lifecycle installs the hook and reconciles the frames in one step with the lifecycle's lock held: frames born or gone, the document a
frame committed, its load states; each difference is said once (a frame dispatcher now remembers the load states the client was told). A
commit also drops the load states said before the announcement for the document it replaces, so the replay after the `page` event is the
destination's and not the blank page's.

Tests: test_a_commit_at_any_point_of_the_hand_over_reaches_the_client_once (the destination's commit, DOMContentLoaded and load at every
placement among four points of the passage: 16 of 20 orders red on the code as it was; and the commit before or during the announcement:
2 of 2 red), green on this change. The fixtures of two white-box tests get the attributes the page now keeps.

* juggler: the hand-over of a popup's page gives back EVERY event held while it was built, in the order it arrived (DRAFT, 0.51.1)

The page's own listener holds the events of the period between its construction and the end of _install_events, and the hand-over gave
back only the Network.* ones: a console message, a pageError, a dialog, a crash or any other event that came in that period was dropped.
A dialog is the worst: alert() blocks the page until the client accepts it, and a client never told of it cannot. Every held event is now
delivered, whatever its kind, in the order it arrived and once (the events the lifecycle owns are also reconciled, which is idempotent).

Tests: one event of each family (console, pageError, dialog, crash) in this order at every placement among four points of the passage,
35 orders, 34 red on the hand-over as it was; each is told once and in order, the dialog is known to the page and the console message is in
its log; and accepting a dialog opened during the passage sends the engine the answer that unblocks the page (3 points).

* juggler: an event beyond the cap of the hold is counted and said once; a file chooser opened during the hand-over reaches the client; CHANGELOG (DRAFT, 0.51.1)

The hold of a page being built keeps at most HELD_CAP events (it bounds the memory of a page that never finishes building). The events beyond
it are counted and, when the hold ends, said once with their count in a RuntimeWarning, instead of vanishing.

Tests: the cap (a loss said once, with its count), and a file chooser opened at each of four points of the hand-over reaches the client with
the handle of its input element and its isMultiple (the scripted engine answers the three commands the chooser needs). The fixture of
test_a_closed_page_says_nothing gets the counter the page now keeps. CHANGELOG: Fixed, for 0.51.1.

* ci: every leg launches with a GeoIP database made by the repository (same bytes every run, no download, no licensed data); the release alone looks at the real one

scripts/ci_lab_geoip.py writes a MaxMind DB with the six networks of the realness exits and the fields the core reads (an ip_version 6 tree, the types libmaxminddb checks),
refuses to go on when its bytes are not the sha256 of ci/geoip.json, exports STEALTHFOX_GEOIP_MMDB to the job, and says in 'evidence' which file a launch ran with;
scripts/ci_verdict.py judge --geoip --geoip-pin turns a leg that ran without it, or with another, red. tests.yml, e2e.yml and webrtc-e2e.yml make it before pytest;
user-install.yml is left alone. publish.yml (the release) runs scripts/ci_real_geoip_check.py before the upload: the product's own download road, the lab database against the real
one for the six exits, every time_zone of the real database known to the runner.

* tests: the two white-box fixtures that build a PageDispatcher by hand get the attributes the hand-over now keeps

test_navigation_response.py and test_same_document_navigation.py build a PageDispatcher with object.__new__ and set by hand the
attributes the code under test touches; the hook of the lifecycle (_on_lifecycle commit, _hear_lifecycle) now reads _announce_lock,
_announced, _said_before_announcement, _frames and _told_attached, and the frame stubs need frame_id and told_states. They are not marked
unit, so the first full run (-m unit) did not reach them; the run without the e2e marker does. No assertion is touched.

* tests: ONE picker for 'the same number on TCP and UDP', used by the HTTP/3 server, the witness and the resolver trap (for 0.51.1)

tests/_ports.py has the sequence of numbers (the system's own pick, then numbers drawn below the ephemeral range, 200 tries) and the picker that keeps every refusal with its code. The HTTP/3 server
calls it (repos-2e's own copy of the loop is gone), the witness walks the same sequence instead of its own, and so does the resolver trap when its port is 0; a port asked for (53 on the root leg)
is tried once per address as before. The test that holds a port for the trap picks it with the picker too: its own system pick fell in a refused UDP block on a work machine (WinError 10013).
Unit tests with a fake socket layer that refuses a contiguous block of 200 UDP ports, for the server, the witness and the trap.

* tests: the hand-over of a popup under concurrency, five sequences (RED on 7d934a6: a load told twice, an event that overtakes the held ones, a frame created after the page's dispose, a frame made twice, a same-address commit not told)

Test only. A-D go green with the changes listed in the review (E not tried).

* juggler: the hand-over of a popup holds under concurrency (a load told once, the held events keep their order, a document at the same address is told, a closed page is not given frames or announced, one dispatcher per frame) (DRAFT, 0.51.1)

From the concurrency review of 7d934a6 (five sequences, tests/test_the_hand_over_of_a_popup_holds_under_concurrency.py):
- FrameDispatcher.emit tells a load state once; the replay after the announcement keeps one entry per (frame, state) even when the
  client knows it from the snapshot, and says it again on purpose.
- the hold ends only when a round finds it empty; the rounds are delivered outside the lock, so a live event never overtakes a held one.
- the reconciliation compares the place of the last commit, not only (url, name).
- _hear_lifecycle and _reconcile_frames do nothing on a closed page; announce() does not say `page` for a page closed before it.
- frame_for checks and creates under a recursive lock.
The five files of the hand-over are in wrapper.unit.page (62).

* juggler: the hold gives back in at most four rounds outside the lock, then the rest with the lock held (a page that prints in a tight loop cannot keep it open) (DRAFT, 0.51.1)

* juggler: a live event of the engine never overtakes the replay of the events a new page missed (the cause of the popups left at about:blank on engine 63) (DRAFT, 0.51.1)

The browser buffers the events of a session nobody reads yet and `PageDispatcher` is handed them (`replay`) after it subscribed its
lifecycle and injected script. The replay ran on the adoption thread while the engine's reader went on delivering live events to the same
subscribers: the destination's commit (live) fell into the middle of the replay of the popup's first events and the replay then brought
older ones after it - the initial about:blank (no id) and the navigationStarted of the same navigation. The lifecycle ended at about:blank
(a popup at about:blank), or had its navigation pending again (Execution context was destroyed). The second Page.frameAttached of every popup
in the traces of the proof is the replay: the engine sends each event once.

The reader takes a gate for each event of a session; the page takes it for "subscribe, then replay" as one step (BrowserDispatcher.events_gate),
with a bounded wait for the reader (5 s) so a holder that never lets go cannot stop the engine's stream.

Test: tests/test_a_live_event_does_not_overtake_the_replay_of_a_new_page.py, five stops of the replay, RED on the old code (the lifecycle
ends at about:blank), green with the gate. wrapper.unit.page 62 -> 67.

* juggler: the gate of the events belongs to the connection, looks the delivery up at each event, and bounds the hold, not each event (DRAFT, 0.51.1)

From the review of 80bc478:
- the wrapper froze the bound `dispatch_event` of the connection: a patch of the class made after the browser was built (the e2e fixtures that
  record the events) was bypassed. It looks the delivery up at each event, as the reader did.
- the 5 s bound was per event: a holder that never lets go made the reader pay 5 s for every event. After one timeout the reader delivers ungated
  for 30 s, and the connection records it (`handler_errors`).
- the gate is kept on the connection, so a second dispatcher over the same connection shares the one the wrapper takes.
Tests: a utility context created while the replay goes on is not undone by an older event (the injected script half), the class patch, the
hold bound; wrapper.unit.page 67 -> 71.

* juggler: a page that is being built waits at most 30 s for the gate of the events, and says it when it does not get it (DRAFT, 0.51.1)

From the reading of 15d1891 by repos-6b: the construction of a page waited for the gate with no bound, a new dependency on the reader. It now
builds without the gate after 30 s and warns. wrapper.unit.page 71 -> 72.

* tests: the 17 CodeQL alerts of PR 483 are fixed in the test code (TLS floor, exact host, own address, header from the dict's key, MD5 declared not for security)

py/insecure-protocol x11 (23-33): every client TLS context the fake servers' tests make sets minimum_version = TLS 1.2 (test_the_fake_doh_answers x7,
test_the_fake_doh_delays_and_refuses, test_the_h3_line_helpers, test_the_http_proxy_helper_asks_for_credentials, test_the_udp_chain_helper).
py/bind-socket-all-network-interfaces (37): the TURN stand-in listens on the address the browser is told to connect to, not on 0.0.0.0.
py/http-response-splitting (39): the Content-Disposition name is the dict's own key, found by comparison, nothing of the request is written back.
py/incomplete-url-substring-sanitization (38): the trap's description is compared whole, not searched for a host name.
py/weak-sensitive-data-hashing x3 (34, 35, 36): the TURN long-term credential key IS MD5(user:realm:password) (RFC 5389 15.4); the stand-in and its test
compute it with usedforsecurity=False. Whether CodeQL accepts that is seen on the next scan; no setting touched, no alert closed.

* tests: Control+A selects all in an input and a textarea, in-process and served to the stock client (e2e, red on the keyboard that held Shift for the capital A)

* ci: e2e.yml runs the Control+A e2e on Windows, on the published engine, as a job of its own (dispatchable alone with only=windows-control-a)

tests/test_control_a_selects_all_in_a_field_e2e.py (5 ways to press the shortcut x an <input> and a <textarea>, in-process and served to the stock
client) is red on the keyboard that held Shift for the capital A and was measured on Linux; the keyboard of a user is Windows. The new job
installs the wrapper (which pins the core of the release), fetches the published engine and runs that file on windows-latest with bash as the
shell, behind the same core-on-index gate as the Linux job: skipped with the reason in the summary until the core is on the index. The
workflow_dispatch input `only` lets it run alone (`windows-control-a`) without the 40 minutes of the Linux job.

* ci(install): the wait for the index asks both installers of the job (pip and uv), three rounds in a row, and a call that does not answer is a no

The job installs with two tools: the upgrade test with pip, the release test with uv (the README's way in). The wait asked only pip, so a green wait said nothing
about the page uv would be served, and one yes proves one request, not the next. Each round now asks `pip download` AND `uv pip compile` of
`invisible-playwright==X` (no cache, nothing installed); the job goes on after three rounds in a row in which both said yes (INDEX_WAIT_CONFIRMATIONS), 15 s apart,
a no starts the count again, a call that does not answer in 120 s (INDEX_WAIT_CALL_SECONDS) is a no; the bound of ten minutes is the same and the error says
which installer said no. The harness environment gets `uv` (a PyPI package: `python -m uv`), independent of the uv the release test installs in its own home.

Test: the script of the step runs with a pip and a uv that answer as plans say; red on the step of 299fc9f (8 of 10). The same remedy as invisible_core 2089b48.

* tests: the GeoIP check of e2e.yml anchors on the step's name on main ("..., without the root ones")

The rebase of the 0.51.1 stack over main (c70a396d, 3be9c0b) met the e2e step renamed by 0.51.0's root step; the database is
still made before it and verified after the root step.

* tests: the raw juggler e2e wait for Page.ready and the main frame, not a fixed 0.4-0.5 s

The Windows census of all the e2e (run 43307193708) and the recheck on 87a4e3b (run 43313222398) had 6-7 of these tests red
with "no frame: the page has not announced its main frame yet": on a Windows runner the page is announced after the sleep.
The page is the caller's when the engine says Page.ready, as Playwright hands it over (Lifecycle.wait_for_page_ready), and
then its main frame is there (wait_for_main_frame).

* ci: the sandbox e2e runs in a step that turns user namespaces on; the consecutive-port tests run serially; CHANGELOG for 0.51.1

The sandbox e2e (tests/test_the_socket_process_is_sandboxed_e2e.py) fails on a runner whose AppArmor refuses
user namespaces to a normal user. e2e.yml now leaves it out of the normal run by name (SANDBOX_FILES) and runs
it, after the run and the root step, in a step of its own that sets
kernel.apparmor_restrict_unprivileged_userns=0 first and refuses anything but exactly one passed test.

The two tests of test_declared_host_network_e2e.py that read a consecutive pair of host ports (N, N+1) carry
the wall_clock marker: the e2e run gives them the machine alone, so no other worker can take port N+1.

Each has a unit test that is red on the previous tree. CHANGELOG: the measured popup and Control+A results,
the test fixes, and the known issue this release fixes is removed.

* tests: no address is written out in the GeoIP lab table and its tests (built from numbers, as tests/_realness_support.py does); ci/geoip.json drops its unused network list

* tests: a DoH handshake the client dropped is not a refused certificate (Windows: ConnectionAbortedError 10053)

Windows census of 12/11 (run 43333574229): test_resolver_race_e2e[context_without_proxy_beside_a_proxied_one] read a
ConnectionAbortedError [WinError 10053], through the gateway of a context that HAS the certificate exception, as "a context
without the FakeDoh certificate exception used the DoH". A connection the browser drops before the handshake ends says
nothing about the certificate; only a TLS alert from the client (unknown CA, bad certificate) does. FakeDoh.certificate_refusals()
keeps those; the four e2e that judged every failed handshake (resolver race x2, context-only proxy, DoH under stress) judge the
refusals and still print every failure. Unit test red on the old FakeDoh (no certificate_refusals), green now.

* tests: the GeoIP lab database answers every public address that is not reserved with one declared record

A launch with no proxy asks the database for the runner's egress address, which is not known in advance (any provider, any region). With the six
exits alone the lab database ended those launches in 'egress IP not present in the geoip database' (run 43351424907: 495 errors of this one cause in
the e2e job, and 3 tests of the unit legs). The reserved ranges stay absent, as in the real database. Test red on the six-network database.

* tests: the two gather tests that compare a near and a far duration run alone, in the serial group

Run 43353896238 (Linux e2e, four workers): 765 passed, one failed with (350 - 84) <= 100, the host candidate of the far gather 266 ms after the
near one. The verdict is a difference of two wall-clock measures, which the e2e run gives the machine alone (wall_clock). A unit test reads the file and
refuses any test that compares a near and a far timing without the marker; it is red on the file as it was.

* tests: every suite of the gate and the e2e and unit tests of a pull request run on Linux and Windows, or say why not

Federico, 12/11: a test seen only on Linux proves nothing about the system the product imitates; where Windows behaves
differently the test adapts. A row of ci/required-suites.json names both systems, or a windows_twin, or a linux_only reason;
the jobs of e2e.yml that run scripts/run_e2e.py cover both runners between them; the unit job of tests.yml runs on both.
wrapper.e2e.udp.exit and wrapper.e2e.udp.sandbox are declared linux_only with their reason (the lab's exit address cannot
be held on the runner's adapter without taking the runner off the network; the sandbox twin needs a retail measurement).
Known-bad: the files of 12/11 (two Linux-only rows without a reason, e2e on ubuntu only) -> problems names each.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ci: e2e.yml runs the e2e on Windows too, in four parts, without the linux_only suites

Before this, 562 of the 808 e2e had never run on Windows in any round (census of 12/11, run 43307193708, ~50 minutes in one
job). Four jobs "e2e (windows, part N)" on windows-2022, the published engine, scripts/run_e2e.py as on Linux; the sorted e2e
files split every fourth; the suites ci/required-suites.json declares linux_only are left out by reading the file, not by a
skip. scripts/e2e_is_green.py already reads every e2e check-run of the commit, so the release waits for the Windows parts too.
The root-step test finds the Linux run by its xvfb-run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ci: the unit tests run on Windows at both ends of the Python range (3.11 and 3.14), not on 3.12 alone

Federico, 12/11: every test on Linux AND Windows. Ubuntu keeps the whole range.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ci: webrtc-e2e.yml goes (dispatch only, Linux only); its file runs in e2e.yml on Linux and Windows and in the gate

Its one test file, tests/test_webrtc_realness.py, is e2e: e2e.yml collects it on every pull request on both systems, and the
gate's wrapper.e2e.udp lists its UDP-line tests. A workflow that only a person can start is not a round; it is deleted, not
left off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ci: the Windows parts of e2e.yml launch with the repository's GeoIP database and verify it, as the Linux run does

tests/test_ci_workflows_build_the_geoip_database.py judges each leg of e2e.yml on its own (the Linux job, the Windows parts)
and no longer names webrtc-e2e.yml, which is gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* tests: the raw juggler e2e subscribe the page's Lifecycle and injected script on the attach, not after it

Windows CI of 13/11 (run 43373058301, e2e windows part 2): test_juggler_actions [engine-approach] waited 30 s and "the
engine never said Page.ready (frames seen: [])". The connection hands each event to the listeners of that moment
(EventListeners.dispatch_event copies the list); these tests built the Lifecycle from the test thread after polling for the
attach, so the page's first frameAttached and Page.ready, delivered in between, reached no one. Built in the attach
listener, on the reader thread, they are subscribed before the next event of the session.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* tests: the fake HTTP/3 server closes its event loop on its own thread (a loop left to the garbage collector hung Windows runs)

PR #486, e2e windows part 1, twice; the Windows hunt of 13/11 (run 43377799126) three runs of fifteen: a test of
test_http3_through_the_proxy_e2e.py stood for minutes and was killed by the timeout. The server had answered every call;
the test thread was in base_events.__del__ -> proactor_events.close -> windows_events.close -> _poll in all three dumps.
H3Server.close() stopped its loop and never closed it, so BaseEventLoop.__del__ closed it later on whatever thread the
garbage collector ran in, and the Windows proactor waited for ever for the UDP receive still pending on it. The loop is now
closed on its own thread after the QUIC server, and close() joins the thread. Unit test red on the old server, green now;
wrapper.unit.udp counts 222.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* tests: the late element is scheduled by the test, and the cross-origin button is waited for before it is counted

Windows CI of 13/11 (PR #486, run 43383366904), two reds of the tests themselves:
- test_juggler_transport::test_the_public_API_WAITS_for_an_element_that_arrives_late: the page's timer (800 ms from its
  load) had already added the element when the test first read it ("the element was already there"); the test now empties
  it and schedules it itself, 800 ms from its own read.
- test_cross_origin_iframe::test_cross_origin_iframe_frame_locator_resolves_button: Locator.count() does not wait, and the
  cross-origin document of the iframe, in its own process, loaded after the count (0 elements); the button is waited for first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Pin invisible-core 63.68.0 (the font-manifest cache on Windows, host environment, GeoIP once a day)

* tests: core 63.68.0 no longer declares gfx.webrender.all (a pref that does nothing)

* tests: a move with a button held carries buttons=1 and pressure 0.5 (core 63.68.0); the timed typing test runs in the serial group

* tests: the first-STUN-datagram timing runs in the serial group (419 ms under four parallel browsers on Windows)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 13:26:47 +01:00
177 changed files with 15059 additions and 1986 deletions

No files matched your search

+165 -5
View File
@@ -6,8 +6,7 @@
# launched Firefox in true HEADLESS mode, which is content-process unstable on
# the hosted runners (eval-CSP / context-destroyed). The stealth wrapper instead
# launches Firefox HEADED on a real display; under `xvfb-run` (a virtual X
# server) that's exactly what we get on a headless CI box - stable, and the same
# thing webrtc-e2e.yml already relies on.
# server) that's exactly what we get on a headless CI box - stable.
#
# Secret-free, so it's safe in public CI: the binary is the PUBLIC firefox-9
# release (no token), and the webrtc e2e fake a local TCP-only SOCKS. The proxy
@@ -34,6 +33,15 @@ on:
- 'docs/**'
- 'LICENSE'
workflow_dispatch:
inputs:
only:
description: "Which job. `windows-control-a` runs only the Windows job of the keyboard shortcut (after the core of a release is on the index and its engine is published); `all` runs the whole workflow."
required: false
default: "all"
type: choice
options:
- all
- windows-control-a
permissions:
contents: read
@@ -75,7 +83,7 @@ jobs:
e2e:
name: e2e (linux, xvfb)
needs: core-on-index
if: needs.core-on-index.outputs.available == 'true'
if: needs.core-on-index.outputs.available == 'true' && inputs.only != 'windows-control-a'
runs-on: ubuntu-24.04
timeout-minutes: 40
steps:
@@ -116,6 +124,13 @@ jobs:
# The generator moved into the core with the module it writes (0.30.0),
# so the check runs against the core this package installs.
run: python -m invisible_core.juggler._gen_protocol --check --binary "$(dirname "$FF")"
# The GeoIP database is made by the repository (scripts/ci_lab_geoip.py: the same bytes on every run, the sha256 in ci/geoip.json), never a
# site and never a licensed file: without STEALTHFOX_GEOIP_MMDB the core asks GitHub which database is the latest on every call
# (run 43211837926). The variable reaches every later step of the job.
- name: The GeoIP database (made by the repository, same bytes every run)
shell: bash
run: python scripts/ci_lab_geoip.py build
- name: Run the full e2e suite under a virtual display, without the root ones
# PYTHONUNBUFFERED, and it is not a nicety. Without it Python block-buffers
# stdout when it is a pipe, and this step printed NOTHING for 39 minutes
@@ -134,9 +149,11 @@ jobs:
INVPW_TEST_WATCHDOG_FILE: ${{ runner.temp }}/e2e-watchdog.log
ROOT_FILES: tests/test_a_proxy_that_cannot_carry_udp_leaks_nothing_direct_e2e.py
ROOT_NODES: tests/test_the_whole_udp_chain_by_name_e2e.py::test_a_turn_srflx_by_name_arrives_through_the_relay_before_the_tick
# The root ones are left out by name and run in the step below, as root: here, as the runner user, they errored.
SANDBOX_FILES: tests/test_the_socket_process_is_sandboxed_e2e.py
# The root ones are left out by name and run in the step below, as root: here, as the runner user, they errored. The sandbox one is left out
# by name too and runs in its own step after them: it is red on a runner whose AppArmor refuses user namespaces to a normal user.
run: |
IGNORE=(); for f in $ROOT_FILES; do IGNORE+=("--ignore=$f"); done
IGNORE=(); for f in $ROOT_FILES $SANDBOX_FILES; do IGNORE+=("--ignore=$f"); done
DESELECT=(); for n in $ROOT_NODES; do DESELECT+=("--deselect=$n"); done
xvfb-run -a python -u scripts/run_e2e.py "$FF" "${IGNORE[@]}" "${DESELECT[@]}"
@@ -175,6 +192,32 @@ jobs:
if counts["tests"] != int(os.environ["ROOT_TESTS"]) or counts["failures"] or counts["errors"] or counts["skipped"]:
sys.exit("the root e2e must be exactly %s tests, all passed: %s" % (os.environ["ROOT_TESTS"], counts))
PY
# THE SANDBOX E2E (wrapper.e2e.udp.sandbox), as the gate runs its first file: the browser WITH its sandbox, run by the runner user. On this runner AppArmor
# refuses user namespaces to a normal user (kernel.apparmor_restrict_unprivileged_userns=1), so the browser of every other step starts WITHOUT the sandbox
# of its socket and content processes, and tests/test_the_socket_process_is_sandboxed_e2e.py (which fails unless both have a seccomp filter) can only
# be green after the restriction is turned off. It is left out of the run above by name (SANDBOX_FILES) so that it cannot fail on a runner without the
# sysctl, and it runs here, after the run and the root step (whatever the sysctl changes cannot reach a launch of the run), as the runner user. Nothing
# is skipped silently: the step reads its own junit and refuses anything but exactly that many tests, all passed.
# tests/test_the_sandbox_e2e_runs_where_user_namespaces_are_on.py holds this step, the exclusion above and the order.
- name: The sandbox e2e (wrapper.e2e.udp.sandbox), with unprivileged user namespaces on
if: success() || failure()
env:
PYTHONUNBUFFERED: "1"
SANDBOX_FILES: tests/test_the_socket_process_is_sandboxed_e2e.py
SANDBOX_TESTS: "1"
run: |
sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0
JUNIT="${RUNNER_TEMP}/sandbox-e2e.xml"
xvfb-run -a env -u PYTEST_ADDOPTS INVPW_BINARY_PATH="$FF" STEALTHFOX_E2E_BINARY="$FF" python -m pytest $SANDBOX_FILES -m e2e -o addopts='' -o junit_family=xunit2 -q -p no:cacheprovider -p no:rerunfailures -rs --junitxml="$JUNIT" || true
python - <<'PY'
import os, sys, xml.etree.ElementTree as ET
root = ET.parse(os.path.join(os.environ["RUNNER_TEMP"], "sandbox-e2e.xml")).getroot()
suite = root if root.tag == "testsuite" else root.find("testsuite")
counts = {k: int(suite.get(k, 0)) for k in ("tests", "failures", "errors", "skipped")}
print("sandbox e2e:", counts)
if counts["tests"] != int(os.environ["SANDBOX_TESTS"]) or counts["failures"] or counts["errors"] or counts["skipped"]:
sys.exit("the sandbox e2e must be exactly %s tests, all passed: %s" % (os.environ["SANDBOX_TESTS"], counts))
PY
- name: What the root step left behind (diagnostic, decides nothing)
if: always()
run: |
@@ -182,6 +225,15 @@ jobs:
echo "-- /etc/resolv.conf"; cat /etc/resolv.conf || true
echo "-- lo"; ip -4 addr show lo || true
# The leg ran with the pinned database, and the core never went past it to GitHub (tests/geoip_used.py wrote what it did).
- name: The leg ran with the pinned GeoIP database
if: always()
shell: bash
run: |
python scripts/ci_lab_geoip.py evidence --out "$(dirname "$GEOIP_USED_OUT")/geoip-evidence.json" > /dev/null
python scripts/ci_lab_geoip.py verify --evidence "$(dirname "$GEOIP_USED_OUT")/geoip-evidence.json" --used "$GEOIP_USED_OUT"
# Runs ONLY if the full run above fails, and before 2026-08-13 it could not
# exist: the hang was killed by the 40-minute ceiling, so the job came out
# `cancelled` and the following steps did not start at all. With
@@ -219,3 +271,111 @@ jobs:
path: ${{ runner.temp }}/e2e-watchdog.log
if-no-files-found: warn
retention-days: 14
# ``Control+A`` selects all in a field, on the PUBLISHED engine and the core this package pins, on Windows, where the keyboard of a real
# user is: the shortcut letter used to reach the browser as Control+Shift+A (invisible-core 63.66.0 fixes it). The e2e is red on the
# keyboard that held Shift for the capital A (tests/test_control_a_selects_all_in_a_field_e2e.py: 5 ways to press it x an <input> and a
# <textarea>, in-process and served to the stock Playwright client). Same gate as the Linux job: it is SKIPPED, with the reason in the
# summary, until the core is on the index, and it runs unchanged after; `workflow_dispatch` with `only: windows-control-a` runs it alone.
e2e-windows-control-a:
name: e2e (windows, Control+A)
needs: core-on-index
if: needs.core-on-index.outputs.available == 'true'
runs-on: windows-latest
timeout-minutes: 20
# `run:` blocks are PowerShell on Windows unless said otherwise (e2e-hunt.yml had a ParserError on its first launch there).
defaults:
run:
shell: bash
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
with: { fetch-depth: 1 }
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
with: { python-version: '3.11' }
- name: Install wrapper + test deps (the stock client is in the dev extra)
run: |
python -m pip install --upgrade pip
python -m pip install ".[dev]"
- name: Fetch the published firefox binary
run: echo "FF=$(python -m invisible_playwright fetch | tail -1)" >> "$GITHUB_ENV"
- name: The keyboard shortcut selects all (the browser opens on the runner's desktop, as in e2e-hunt.yml)
env:
PYTHONUNBUFFERED: "1"
run: INVPW_BINARY_PATH="$FF" python -u -m pytest -m e2e -p no:cacheprovider -v tests/test_control_a_selects_all_in_a_field_e2e.py
# THE SAME e2e ON WINDOWS (Federico, 12/11: every test of the product runs on Linux AND Windows; where Windows behaves
# differently the test adapts to the system). Before this, 562 of the 808 e2e had never run on Windows in any round. The census
# of 12/11 (run 43307193708) took ~50 minutes in one job, so the files are split in four parts (the sorted list, every fourth
# file: a split that does not move when a file is added elsewhere). Left out, by name, are the suites ci/required-suites.json
# declares `linux_only` (the reason is on the row); tests/test_every_suite_runs_on_linux_and_windows.py holds both together.
e2e-windows:
name: e2e (windows, part ${{ matrix.part }})
needs: core-on-index
if: needs.core-on-index.outputs.available == 'true' && inputs.only != 'windows-control-a'
runs-on: windows-2022
timeout-minutes: 40
strategy:
fail-fast: false
matrix:
part: [1, 2, 3, 4]
defaults:
run:
shell: bash
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
with: { fetch-depth: 1 }
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
with: { python-version: '3.11' }
- name: Install wrapper + test deps (+ Playwright ONLY as a system tool)
run: |
python -m pip install --upgrade pip
python -m pip install ".[dev]"
python -m pip install "playwright==$(cat scripts/playwright_pin.txt)"
- name: Fetch the published firefox binary
run: echo "FF=$(cd "$RUNNER_TEMP" && python -m invisible_playwright fetch | tail -1)" >> "$GITHUB_ENV"
# The GeoIP database made by the repository, as on the Linux run (no download, the same bytes every run).
- name: The GeoIP database (made by the repository, same bytes every run)
run: python scripts/ci_lab_geoip.py build
- name: The files of this part, without the linux_only suites
run: |
set -e
python -m pytest --collect-only -q -m e2e -o addopts= -p no:cacheprovider 2>/dev/null | grep "::" | cut -d: -f1 | sort -u > "$RUNNER_TEMP/e2e_files.txt"
python - "${{ matrix.part }}" "$RUNNER_TEMP" <<'PY'
import json, os, sys
part, tmp = int(sys.argv[1]), sys.argv[2]
rows = json.load(open("ci/required-suites.json", encoding="utf-8"))
left_out = [t for r in rows if r.get("linux_only") for t in r["tests"]]
files = [l.strip() for l in open(os.path.join(tmp, "e2e_files.txt")) if l.strip()]
files = [f for f in files if f not in left_out]
mine = [f for i, f in enumerate(files) if i % 4 == part - 1]
nodes = [t for t in left_out if "::" in t and t.split("::")[0] in mine]
open(os.path.join(tmp, "e2e_args.txt"), "w").write("\n".join(mine + ["--deselect=" + n for n in nodes]) + "\n")
print("%d e2e files, %d left out as linux_only, %d in part %d, %d node(s) deselected"
% (len(files) + len([t for t in left_out if "::" not in t]), len(left_out), len(mine), part, len(nodes)))
PY
- name: Run this part of the e2e
env:
PYTHONUNBUFFERED: "1"
INVPW_TEST_WATCHDOG_FILE: ${{ runner.temp }}/e2e-watchdog.log
run: |
mapfile -t ARGS < <(tr -d '\r' < "$RUNNER_TEMP/e2e_args.txt")
python -u scripts/run_e2e.py "$FF" "${ARGS[@]}"
- name: The leg ran with the pinned GeoIP database
if: always()
run: |
python scripts/ci_lab_geoip.py evidence --out "$(dirname "$GEOIP_USED_OUT")/geoip-evidence.json" > /dev/null
python scripts/ci_lab_geoip.py verify --evidence "$(dirname "$GEOIP_USED_OUT")/geoip-evidence.json" --used "$GEOIP_USED_OUT"
- name: Close every Firefox left
if: always()
shell: pwsh
run: |
Get-Process firefox -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue
"left: " + @(Get-Process firefox -ErrorAction SilentlyContinue).Count
- name: Upload the hang evidence
if: always()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: e2e-watchdog-windows-${{ matrix.part }}-${{ github.run_id }}-${{ github.run_attempt }}
path: ${{ runner.temp }}/e2e-watchdog.log
if-no-files-found: warn
retention-days: 14
+20 -1
View File
@@ -196,8 +196,27 @@ jobs:
# code no job has run.
run: python -m pytest -q
# The three checks on the REAL GeoIP database, and only here (the release): the legs of the pull requests and of the gates launch with the database that
# scripts/ci_lab_geoip.py makes (a few networks, the same bytes every run, no download), so what only the real one can show is looked at once per release:
# the product's own road (no variable, cold cache, the latest database downloaded), the lab database against it for the six exits, and every
# time_zone of the database known to the runner's tz database. See the docstring of scripts/ci_real_geoip_check.py.
real-geoip-database:
needs: already-published
if: needs.already-published.outputs.present != 'yes'
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: Install the wrapper (its core comes from the index)
run: python -m pip install -e . maxminddb
- name: The real GeoIP database - the product's road, the lab database against it, every zone known
run: python scripts/ci_real_geoip_check.py
upload:
needs: [already-published, gate]
needs: [already-published, gate, real-geoip-database]
if: needs.already-published.outputs.present != 'yes'
runs-on: ubuntu-latest
environment: pypi # the trust relationship lives HERE, behind the gate
+22 -7
View File
@@ -173,15 +173,15 @@ jobs:
# untested until 2026-08-01, and the user who opened issue #51 was on
# 3.14. test_marker_vocabulary.py compares this list to the floor.
python: ["3.11", "3.12", "3.13", "3.14"]
# Windows runners are the scarce, 2x-cost, slow-to-schedule ones, and a
# burst of pushes queues them for a long time. Run the FULL Python range
# on ubuntu (cheap, fast) and cover Windows on 3.12 only - this is a
# pure-Python package, the OS-specific surface is tiny. The python LIST
# above stays complete so test_marker_vocabulary still sees every version.
# The FULL Python range on ubuntu; Windows on the two ends of the range,
# 3.11 and 3.14 (Federico, 12/11: every test on Linux AND Windows; the
# ends are where a version-specific difference shows first). The runners
# are free for this public repository; the account runs 20 jobs at once.
# The python LIST above stays complete so test_marker_vocabulary still
# sees every version.
exclude:
- { os: windows-latest, python: "3.11" }
- { os: windows-latest, python: "3.12" }
- { os: windows-latest, python: "3.13" }
- { os: windows-latest, python: "3.14" }
steps:
- uses: actions/checkout@v4
@@ -222,12 +222,27 @@ jobs:
run: |
python -m ruff check --select F821,F811,F601 --no-cache --output-format concise .
# The GeoIP database is made by the repository (scripts/ci_lab_geoip.py: the same bytes on every run, the sha256 in ci/geoip.json), never a
# site and never a licensed file: without STEALTHFOX_GEOIP_MMDB the core asks GitHub which database is the latest on every call
# (run 43211837926). The variable reaches every later step of the job.
- name: The GeoIP database (made by the repository, same bytes every run)
shell: bash
run: python scripts/ci_lab_geoip.py build
- name: Run pytest
shell: bash
run: |
set -o pipefail # or tee would swallow pytest's exit code
pytest tests/ -v --tb=short -rs | tee tests-report.txt
# The leg ran with the pinned database, and the core never went past it to GitHub (tests/geoip_used.py wrote what it did).
- name: The leg ran with the pinned GeoIP database
if: always()
shell: bash
run: |
python scripts/ci_lab_geoip.py evidence --out "$(dirname "$GEOIP_USED_OUT")/geoip-evidence.json" > /dev/null
python scripts/ci_lab_geoip.py verify --evidence "$(dirname "$GEOIP_USED_OUT")/geoip-evidence.json" --used "$GEOIP_USED_OUT"
# This repo has the largest suite of the three and was the only one with
# no floor. pytest's exit code cannot distinguish "everything passed"
# from "the marker expression deselected everything", and `addopts`
@@ -0,0 +1,97 @@
name: text bytes host hunt (idwr candidate)
on:
push:
branches: [hunt/text-bytes-host]
paths: [scripts/hunt_text_bytes.py, .github/workflows/text-bytes-host-hunt.yml]
env:
GITHUB_TOKEN: ${{ github.token }}
concurrency:
group: text-bytes-host-hunt
cancel-in-progress: true
jobs:
hunt:
strategy:
fail-fast: false
max-parallel: 3
matrix:
include:
- {leg: w2022, runner: windows-2022, extra: none, asset: asset-win-x86_64}
- {leg: w2025, runner: windows-2025, extra: none, asset: asset-win-x86_64}
- {leg: ubuntu, runner: ubuntu-24.04, extra: none, asset: asset-linux-x86_64}
runs-on: ${{ matrix.runner }}
timeout-minutes: 40
defaults:
run:
shell: bash
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
with: { fetch-depth: 1 }
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
with: { python-version: '3.12' }
- name: Install
run: |
python -m pip install --upgrade pip
python -m pip install ".[dev]"
- name: Linux display and runtime libraries
if: runner.os == 'Linux'
run: |
python -m pip install "playwright==$(cat scripts/playwright_pin.txt)"
sudo apt-get update -q && sudo apt-get install -y -q xvfb
sudo "$(which python)" -m playwright install-deps firefox
- name: The engine of the idwr candidate (artifact of feder-cr/firefox_antidetect_patch run 43728338511), sealed
env:
GH_TOKEN: ${{ github.token }}
run: |
mkdir -p "$RUNNER_TEMP/eng" && cd "$RUNNER_TEMP/eng"
gh run download 43728338511 -R feder-cr/firefox_antidetect_patch -n ${{ matrix.asset }} -D .
ls -la
if [ "$RUNNER_OS" = "Windows" ]; then unzip -q ./*.zip -d ff && FF="$(cd ff && pwd -W)/firefox.exe"; else mkdir ff && tar -xzf ./*.tar.gz -C ff && FF="$(find "$PWD/ff" -maxdepth 2 -name firefox -type f | head -1)"; fi
echo "FF=$FF" >> "$GITHUB_ENV"
cd "$GITHUB_WORKSPACE"
python -m invisible_core seal --binary "$FF" --tag firefox-65-candidate -o "$RUNNER_TEMP/seal.json"
echo "INVISIBLE_SEAL_FILE=$RUNNER_TEMP/seal.json" >> "$GITHUB_ENV"
- name: One system font more (DejaVu Sans, installed for all users)
if: matrix.extra == 'dejavu'
shell: pwsh
run: |
python -m pip install matplotlib
$src = python -c "import matplotlib, os; print(os.path.join(os.path.dirname(matplotlib.__file__), 'mpl-data', 'fonts', 'ttf', 'DejaVuSans.ttf'))"
Copy-Item $src "C:\Windows\Fonts\DejaVuSans.ttf"
New-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts" -Name "DejaVu Sans (TrueType)" -Value "DejaVuSans.ttf" -PropertyType String -Force | Out-Null
"installed: " + (Get-Item "C:\Windows\Fonts\DejaVuSans.ttf").Length
- name: The host (Windows build, DirectWrite, the font files the probe names)
if: runner.os == 'Windows'
shell: pwsh
run: |
$cv = Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion"
$out = [ordered]@{ build = "$($cv.CurrentBuild).$($cv.UBR)"; product = $cv.ProductName }
foreach ($dll in "DWrite.dll", "d2d1.dll", "gdi32full.dll", "fontsub.dll") {
$p = "C:\Windows\System32\$dll"
if (Test-Path $p) { $out[$dll] = "$((Get-Item $p).VersionInfo.FileVersion) $((Get-FileHash $p -Algorithm SHA256).Hash.Substring(0,16))" }
}
$reg = Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts"
$out["registry_fonts"] = @($reg.PSObject.Properties | Where-Object { $_.Name -notlike "PS*" }).Count
$out["fonts_dir_files"] = @(Get-ChildItem C:\Windows\Fonts -File).Count
foreach ($f in "arial.ttf","arialbd.ttf","times.ttf","segoeui.ttf","segoeuii.ttf","calibri.ttf","consola.ttf","verdana.ttf","tahoma.ttf","georgia.ttf","seguiemj.ttf","msyh.ttc","YuGothR.ttc","cour.ttf","timesi.ttf") {
$p = "C:\Windows\Fonts\$f"
$out["font:$f"] = if (Test-Path $p) { "$((Get-Item $p).VersionInfo.FileVersion) $((Get-FileHash $p -Algorithm SHA256).Hash.Substring(0,16))" } else { "absent" }
}
$out | ConvertTo-Json | Tee-Object "$env:RUNNER_TEMP\host.json"
- name: Two runs of the probe, seed 42
env:
MOZ_CRASHREPORTER_DISABLE: "1"
run: |
mkdir -p "$RUNNER_TEMP/out"
if [ -f "$RUNNER_TEMP/host.json" ]; then cp "$RUNNER_TEMP/host.json" "$RUNNER_TEMP/out/host.json"; else
python -c "import json, platform, sys; json.dump({'os': platform.platform()}, open(sys.argv[1], 'w'))" "$RUNNER_TEMP/out/host.json"; fi
python -c "import json, sys; json.dump({'engine': 'idwr candidate, feder-cr/firefox_antidetect_patch run 43728338511', 'asset': sys.argv[1]}, open(sys.argv[2], 'w'))" "${{ matrix.asset }}" "$RUNNER_TEMP/out/engine.json"
if [ "$RUNNER_OS" = "Linux" ]; then RUN="xvfb-run -a"; else RUN=""; fi
for i in 1 2; do $RUN python scripts/hunt_text_bytes.py "$FF" "$RUNNER_TEMP/out/probe-$i.json"; done
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with: { name: "text-bytes-${{ matrix.leg }}", path: "${{ runner.temp }}/out" }
- name: Close every Firefox left
if: always()
shell: pwsh
run: |
Get-Process firefox -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue
"left: " + @(Get-Process firefox -ErrorAction SilentlyContinue).Count
+34 -13
View File
@@ -94,12 +94,12 @@ jobs:
- uses: actions/setup-python@v5
with: { python-version: '3.11' }
# Only what the TEST needs. The package under test is installed by the
# Only what the TEST needs (and `uv`, for the wait below to ask uv, which the release test installs the package with). The package under test is installed by the
# test itself, into a venv it creates, from the index - installing it
# here as well would put a second copy on the path and the assertions
# would be reading the wrong one.
- name: Test harness only
run: python -m pip install --upgrade pip pytest packaging
run: python -m pip install --upgrade pip pytest packaging uv
# PyPI does not serve a new version to pip the instant twine finishes, and
# this workflow runs on the ledger pull request, which the publish run
@@ -115,9 +115,11 @@ jobs:
# started later, was green). Those are three different pages of the index, and
# the job only needs the one pip installs from.
#
# So the question asked here is pip's own: `pip download invisible-playwright==X`,
# the same client, the same index, no cache. Bounded at ten minutes: a forgotten
# publish still fails, and it fails HERE, saying that the index does not have the
# So the question asked here is the INSTALLERS' own, both: the upgrade test installs with pip, the release test with uv (the README's
# way in), so each round asks `pip download invisible-playwright==X` AND `uv pip compile` of it (no cache, nothing installed), and the
# job goes on only after three rounds in a row in which both said yes, 15 s apart (one yes proves that one request saw the version, not
# that the next is served by the same node of the index); a no restarts the count and a call that does not answer in two minutes is
# a no. Bounded at ten minutes: a forgotten publish still fails, and it fails HERE, saying that the index does not have the
# version, instead of three steps later as a test that compares two versions.
#
# Only on the ledger pull request. A scheduled or dispatched run is not
@@ -134,21 +136,40 @@ jobs:
deadline = time.monotonic() + 600
deadline = min(deadline, time.monotonic() + float(os.environ.get("INDEX_WAIT_SECONDS", "600")))
poll = float(os.environ.get("INDEX_WAIT_POLL", "15"))
n = 0
need = int(os.environ.get("INDEX_WAIT_CONFIRMATIONS", "3"))
call_limit = float(os.environ.get("INDEX_WAIT_CALL_SECONDS", "120"))
asks = [
("pip", [sys.executable, "-m", "pip", "download", "--no-deps", "--no-cache-dir", "--disable-pip-version-check", "--quiet",
"-d", tempfile.mkdtemp(), f"{dist}=={version}"], None),
("uv", [sys.executable, "-m", "uv", "pip", "compile", "-", "--no-deps", "--no-cache", "--quiet"], f"{dist}=={version}\n"),
]
def round_says():
"""An empty string when every installer resolves the version, else what the first that did not said."""
for tool, command, stdin in asks:
try:
r = subprocess.run(command, input=stdin, capture_output=True, text=True, timeout=call_limit)
except subprocess.TimeoutExpired:
return f"{tool} did not answer within {call_limit:.0f} s"
if r.returncode != 0:
return f"{tool} said: " + ((r.stderr.strip().splitlines() or [""])[-1])
return ""
n = streak = 0
said = ""
while True:
n += 1
r = subprocess.run([sys.executable, "-m", "pip", "download", "--no-deps", "--no-cache-dir",
"--disable-pip-version-check", "--quiet", "-d", tempfile.mkdtemp(),
f"{dist}=={version}"], capture_output=True, text=True)
if r.returncode == 0:
print(f"::notice::pip downloads {dist} {version} from the index (attempt {n})")
said = round_says()
streak = 0 if said else streak + 1
if streak >= need:
print(f"::notice::pip and uv resolve {dist} {version} from the index, {need} rounds in a row (attempt {n})")
sys.exit(0)
said = (r.stderr.strip().splitlines() or [""])[-1]
if time.monotonic() >= deadline:
minutes = int(float(os.environ.get("INDEX_WAIT_SECONDS", "600")) // 60) or 1
print(f"::error::the index does not have {dist} {version} yet, after {minutes} minutes "
f"and {n} attempts (pip said: {said})")
f"and {n} attempts, {streak} of {need} rounds in a row ({said})")
sys.exit(1)
time.sleep(poll)
PY
-111
View File
@@ -1,111 +0,0 @@
name: webrtc-e2e
# Live WebRTC realness check against the shipped patched binary.
#
# Manual (workflow_dispatch) on purpose: it needs a firefox-N binary that
# carries the WebRTC fixes (synthetic srflx in genuine nICEr form + the
# default-route fallback behind a proxy). Run it after publishing such a
# binary - it is the release gate for "WebRTC looks real behind a proxy".
# On this Linux runner an engine older than firefox-35 never gets the synthetic
# srflx behind a SOCKS proxy (the wildcard default-route probe, fixed in
# firefox-35): test_not_blocked_behind_tcp_only_socks skips on it, naming that
# defect, and the floor below turns the skip red. From firefox-35 on, a
# missing srflx fails the test itself.
#
# No external proxy provider, no credentials: the "behind a proxy" condition is faked by an
# in-process TCP-only SOCKS5 server (refuses UDP ASSOCIATE) and the egress IP
# is injected as an RFC 5737 TEST-NET address. Fully self-contained.
on:
workflow_dispatch:
permissions:
contents: read
# Engine and GeoIP downloads go through the release API with this token.
# Anonymous requests share a 60-an-hour limit per runner address and are the
# ones GitHub drops first when it is degraded (2026-11-08: timeouts for
# unauthenticated users failed the gates three times). user-install.yml stays
# anonymous on purpose: it is the user's path.
env:
GITHUB_TOKEN: ${{ github.token }}
jobs:
# `pip install -e ".[dev]"` below resolves `invisible-core==N.M.0` from the
# package index, and the core is published BEFORE this package. This gate
# answers whether it is there yet; during that window the realness job is
# SKIPPED with the reason in the run summary rather than faked green, and
# once the core is up it runs unchanged. See
# .github/workflows/core-on-index.yml.
core-on-index:
uses: ./.github/workflows/core-on-index.yml
webrtc-e2e:
name: webrtc realness (ubuntu, py3.12)
needs: core-on-index
if: needs.core-on-index.outputs.available == 'true'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Python 3.12
uses: actions/setup-python@v5
with:
python-version: "3.12"
cache: pip
- name: Install package + dev extras
run: |
python -m pip install --upgrade pip
pip install -e ".[dev]"
- name: Fetch the patched Firefox binary and expose its path
shell: bash
run: |
# NOT `echo "VAR=$(cmd)" >> $GITHUB_ENV`. echo exits 0 whatever the
# substitution did, so `set -e` never sees a failure and an EMPTY
# value lands in the environment. Both tests below then hit
# `pytest.skip("no patched binary")`, pytest exits 0, and the job is
# green having verified nothing - which is exactly what run #1 did.
set -euo pipefail
FETCH_OUTPUT="$(python -m invisible_playwright fetch)"
printf '%s\n' "$FETCH_OUTPUT"
BIN="$(printf '%s\n' "$FETCH_OUTPUT" | tail -n 1)"
if [ -z "$BIN" ] || [ ! -e "$BIN" ]; then
echo "invisible_playwright fetch returned '$BIN', which is not a" >&2
echo "file. Refusing to run a suite that would skip itself green." >&2
exit 1
fi
echo "STEALTHFOX_E2E_BINARY=$BIN" >> "$GITHUB_ENV"
- name: Run WebRTC realness e2e (xvfb for the headless Firefox)
run: |
set -o pipefail
sudo apt-get update && sudo apt-get install -y xvfb
xvfb-run -a pytest tests/test_webrtc_realness.py -m e2e -o addopts="" -v -rs | tee webrtc-report.txt
# Run #1 was GREEN with the headline assertion skipped: "1 passed, 1
# skipped", and the skipped one is the test this workflow's own header
# calls the point of the gate. pytest's exit code cannot tell that from a
# pass, and this file was the only one of four without a floor.
- name: Refuse a run whose main assertion did not execute
shell: bash
run: |
python - <<'PY'
import pathlib, re, sys
text = pathlib.Path("webrtc-report.txt").read_text(encoding="utf-8", errors="ignore")
passed = int((re.search(r"(\d+) passed", text) or [0, 0])[1] or 0)
skipped = int((re.search(r"(\d+) skipped", text) or [0, 0])[1] or 0)
if skipped:
print("these tests SKIPPED, so the gate verified less than it "
"claims:", file=sys.stderr)
for line in text.splitlines():
if line.startswith("SKIPPED"):
print(" " + line, file=sys.stderr)
if passed < 2 or skipped:
print(f"{passed} passed / {skipped} skipped - this gate exists for "
f"the synthetic-srflx assertion; a run that skips it is not "
f"a pass.", file=sys.stderr)
sys.exit(1)
print(f"{passed} tests ran, none skipped")
PY
+87 -11
View File
@@ -6,11 +6,98 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
## [Unreleased]
## [0.52.1] - 2026-11-15
### Changed
- Pins invisible-core 64.73.0 (same engine, firefox-64). The compositor is now declared in software on every machine, as a
retail Firefox reports on a machine without a usable GPU, and never read from the host. Before, the hardware compositor
was declared over a software adapter, which cost about 6x the CPU in the GPU process.
- Windows: the engine is created inside a job of its own, so a launch no longer scans every process of the machine to bind
the engine's tree. (#498)
- Several browsers in one async program no longer slow one another down:
- `connect()` starts no thread on the event loop (#497).
- The virtual display of `headless=True` starts off the event loop (#499).
- Closing a browser waits for its processes and removes its profile without holding the loop that serves the others:
with four browsers in one process the loop was held for up to about 0.5 s per close, and is not held now (#503).
- Comments, the fork notes and one test message no longer point at scripts that were deleted (the transport comparison scripts and the prefs byte-parity gate: no round ran them). No behaviour changes. (#458)
### Added
- `page.expose_function`, `page.expose_binding`, `context.expose_function` and `context.expose_binding`, as in Playwright: the page calls a Python function and gets a promise (the value, a rejection when the function raised, an await when it is async). The page sees the function and nothing else (no name of ours on the window, no init script); an engine without `Page.addBinding` is refused with a clear sentence. Arguments and results cross as JSON. (#471)
- `Locator.screenshot()` and `ElementHandle.screenshot()`: a picture of the element, as in Playwright, in the page, in a frame of another site and in a frame nested in it. (#470)
### Fixed
- A context init script added after a page exists runs once in it, not twice. (#469)
- A CORS preflight (an OPTIONS request that no route holds) is no longer reported to the client, as in Playwright's own server: `page.on("request")`, `route` and a request counter hear of one request fewer for each preflighted fetch of the page. (#467)
### Tests
- Every test module is checked to leave no browser open (a census of the connection threads, which needs no package to run). (#497, #500)
- Software compositing is declared: the compositor in use, the CPU of the GPU process, and the bytes a page reads compared
against a recorded reference, on Linux and Windows. (#501)
- The UDP bench survives a loaded Windows machine, and its verdict says what it saw. (#502)
## [0.52.0] - 2026-11-14
### Changed
- Pins invisible-core 64.71.0 and with it the engine firefox-64. A request a page causes now leaves in the context of that
page, by that context's proxy and resolver: the name of a TURN server over TCP, the OCSP request of a certificate, the TLS
over a tunnel, the Safe Browsing completion of a page load. Nothing of a context with a proxy goes out DIRECT when a proxy
lookup fails or the context has just closed. On Linux the profile lock no longer looks up the machine's host name.
- Typing: each key is sent at its planned time measured from the start of the action, so a late reply no longer shifts the
keys after it, and the engine delivers each key at once with its event born the declared latency in the past. Measured
against stock Playwright Firefox, 20 runs per cell, slip of the last key against the plan (median): Windows 635 ms before,
6 ms now (stock 122); Linux 554 ms before, -5 ms now (stock 91).
### Fixed
- Screencast: a frame that arrives while the start of the screencast is being answered is held and acknowledged,
not dropped, so the stream no longer dies from its first frame (the engine keeps one frame in flight and waits for its
acknowledgement).
- No thread is started on the engine connection's reader any more (the adoption of a new page and the file chooser hand
their work to one long-lived starter). On Windows under load a Thread.start there held every event behind it; without
instrumentation, goto(..., wait_until="networkidle") on pages that replace themselves missed 1 in 1200 instead of 4.
### Tests
- The suites "nothing of a context leaves but through its proxy" (a witness of every direct arrival, the engine's resolver
log as the sink of native lookups), on Linux and Windows, including two contexts with their own proxies at once and a
PeerConnection of a torn-down window.
- Windows: the isolated-page test moves the page when the test says so instead of on a 500 ms timer; the sandbox test
reads again a process that is still starting.
## [0.51.1] - 2026-11-13
### Changed
- Pins invisible-core 63.68.0 (core fixes on the same firefox-63 engine: two sessions starting together on Windows no longer fail on the shared font-manifest cache; no MOZ_*, GL or toolkit variable of the host reaches the engine; GitHub is asked for the latest GeoIP database once a day, not on every launch; mouse moves carry the pressed buttons; a CORS preflight does not count for networkidle).
- The project moved to the oss-invisible GitHub organization: every GitHub link, the issue templates and the package URLs point to github.com/oss-invisible/playwright. The PyPI name and the import name do not change; the old addresses redirect.
### Fixed
- A popup (a `window.open` or a `target=_blank` link) could be handed to the client at `about:blank`, with the blank page's `load`, when it
was opened with no route on the context: the commit of its address, or its `DOMContentLoaded` and `load`, arrived while the page was being
handed from its buffer to its dispatcher and was told to nobody (`page.url` stayed `about:blank`, or `wait_for_load_state("load")` timed
out). Measured on Windows with the library's client in the same process, `test_popups_reach_the_client_e2e.py` x20 on 4 workers: 3 runs
red with the published firefox-62 engine and 11 with firefox-63. The page is now handed over in one step: what the client was not told is
said once, in order, and nothing the engine sent in that period is lost.
- The same hand-over dropped every event that is not a request: a `console` message, a `pageError`, a `dialog` (an `alert()` that opened
while the popup was being built blocked its page for good, because no client had been told of it and none could answer it), a `crash`, a file chooser. All
of them are given back now, in the order they arrived. The only bound left is the memory of the buffer (512 events): an event beyond it is
lost and a `RuntimeWarning` says how many, once per page.
- The hand-over holds when the engine's reader, the adoption and a close run at the same time: a `load` is told to the client once (not twice,
so `page.on("load")` runs once); an event the engine sends while the held ones are being given back waits for them (a response is never handled
before its request); a document committed at the same address as the previous one is told; a page closed while it was being adopted is not given
frames, and is not announced, after its `__dispose__`; one frame never gets two dispatchers.
- A popup could still be handed to the client at `about:blank` (or with its navigation pending again, and "Execution context was destroyed" in its
first evaluate) when the destination committed while the events the page had missed were being replayed to it: the engine's reader went on
delivering the live events to the lifecycle, and the replay then brought older ones after them. The page now subscribes its readers and is
handed the missed events in one step, with the delivery of the sessions' events held, so a live event never overtakes the replay.
With the three corrections together, on Windows with the library's client in the same process, under load: 680/680 and 256/256 popup cases
green (run 43261858525).
- `Control+A` selects all in an `<input>` and a `<textarea>` on Windows, on the published engine and the core this package pins: a new end-to-end
test (five ways to press the shortcut, in-process and served to the stock client), run by `e2e.yml` on Windows, 20/20 green (run 43262320744).
- Tests only: the e2e tests of the test servers take their ports from one sequence (no two servers draw the same one); the two tests that read a
consecutive pair of host ports run alone, after the parallel tests; the sandbox e2e (the browser's seccomp filter) runs in a step of its own that
turns unprivileged user namespaces on, and is left out of the normal run; every leg launches with a GeoIP database the repository builds (same
bytes every run, no download); the CodeQL alerts of the test code are fixed; the install job waits for the package index through both installers;
the raw Juggler tests wait for `Page.ready` and the main frame instead of a fixed time.
## [0.51.0] - 2026-11-12
### Changed
@@ -62,17 +149,6 @@ comparison run is saved). The result of a `window.open` (`null` or a window) is
`extra_prefs={"dom.disable_open_during_load": False}` for the session, knowing that a page then sees a browser that differs from a
retail Firefox.
### Known issues
- **A popup opened without a route can be announced while it is still on `about:blank`.** A popup opened with no route on the context
(a `target=_blank` link, or `window.open` from a click) can be announced to the client while it is still on `about:blank`; its `url`
then stays `about:blank`, or its `load` never arrives. Seen on a Windows runner with the library's client in the same process and four
workers running the popup tests in parallel (`test_popups_reach_the_client_e2e.py`, 20 runs): with the firefox-63 engine 17 cases of 640
in 12 of 20 runs; with the published firefox-62 engine (so also with 0.50.1) 15 cases of 640. Both causes found are in the wrapper: the hand-over of
a new page to the client, and the replay of a new page's events while live ones are being delivered. The correction of the first alone,
not in this release, lowers the red cases over 20 runs from 15 to 2 with engine 62 and from 17 to 13 with engine 63; the correction of the
second is under test. On Linux no run was red (0 of 20). Not measured: a served
launch with numbers of its own, other machines, a run without parallel workers, macOS.
## [0.50.1] - 2026-11-12
0.50.0 was tagged and never published: its end-to-end gate was red on two tests that counted processes.
+1191
View File
File diff suppressed because it is too large. Load diff
+7
View File
@@ -0,0 +1,7 @@
{
"comment": "The GeoIP database every CI leg launches with (STEALTHFOX_GEOIP_MMDB): made by scripts/ci_lab_geoip.py, the same bytes on every run, no download and no licensed data. One record answers every public address that is not one of the lab's networks and not reserved (the runner's own egress address is not known in advance). To change it (a network, a field): change the table of the script and mmdb_sha256 here in one commit; `build` refuses to go on when they differ.",
"generator": "scripts/ci_lab_geoip.py",
"mmdb": "geoip-aio-all.mmdb",
"mmdb_sha256": "d02825fd0336afa72ad7b7573769f1d9efddea447133f99ae3008c56d5308929",
"mmdb_bytes": 2706
}
+9 -5
View File
@@ -1,11 +1,15 @@
[
{"id": "wrapper.e2e.udp", "giro": "G2", "os": ["linux", "windows"], "min_tests": 43, "exact": true, "tests": ["tests/test_preload_newtab_turns_the_privileged_about_process_off_e2e.py", "tests/test_the_association_is_ready_when_the_peerconnection_is_born_e2e.py", "tests/test_turn_over_tcp_is_tried_for_real_e2e.py", "tests/test_webrtc_realness.py::test_the_gather_is_real_without_a_proxy", "tests/test_the_whole_udp_chain_by_name_e2e.py::test_a_turn_srflx_by_name_arrives_through_the_relay_when_the_exit_of_the_lab_is_loopback", "tests/test_declared_host_network_e2e.py", "tests/test_a_page_over_ipv6_gathers_on_a_machine_declared_without_it_e2e.py", "tests/test_webrtc_realness.py::test_a_gateway_with_coherent_udp_gives_the_page_a_srflx_born_through_its_relay", "tests/test_webrtc_realness.py::test_a_host_with_ipv6_addresses_gathers_through_an_ipv4_relay", "tests/test_webrtc_realness.py::test_a_gateway_that_is_far_away_still_gives_the_page_a_srflx_born_through_its_relay", "tests/test_webrtc_realness.py::test_the_first_candidate_of_a_gather_does_not_wait_for_a_gateway_that_is_far_away", "tests/test_webrtc_realness.py::test_a_gather_after_the_page_loaded_through_the_gateway_costs_only_the_road_to_the_server", "tests/test_webrtc_realness.py::test_two_contexts_with_two_proxies_each_gets_the_srflx_of_its_own", "tests/test_webrtc_realness.py::test_the_turn_over_tcp_of_a_context_goes_through_the_proxy_of_that_context", "tests/test_webrtc_realness.py::test_a_proxy_that_does_not_relay_udp_gives_no_srflx_at_all", "tests/test_webrtc_realness.py::test_a_proxy_whose_udp_leaves_from_another_address_gives_no_srflx_at_all", "tests/test_webrtc_realness.py::test_a_proxy_whose_relay_never_answers_gives_no_srflx_at_all"], "marker": "e2e", "needs_root": false, "note": "Needs the candidate binary (STEALTHFOX_E2E_BINARY) and the engine that carries the UDP line. 57 = 1+7+6+1+21 from the five files + 21 from the 10 UDP-line tests of test_webrtc_realness.py (parametrized). The chain by name is here in its variant with the lab's exit on loopback (127.0.0.2) and the pref `media.peerconnection.ice.loopback`, on Linux and Windows: the exit of the lab is loopback, and a loopback mapped address is thrown away by nICEr unless the ICE context allows it. The variant without the pref (an exit that is not loopback) is the suite wrapper.e2e.udp.exit, Linux only; the address added to the interface of the Windows runner is work of the release after firefox-63. The preload_newtab test (2) is here: seen green on Linux as root (Docker) and on Windows 10 runs of 10 (windows-2022, round 5 engine); it reads the engine's own process log."},
{"id": "wrapper.e2e.udp.exit", "giro": "G2", "os": ["linux"], "min_tests": 7, "exact": true, "tests": ["tests/test_the_whole_udp_chain_by_name_e2e.py::test_a_turn_srflx_by_name_arrives_through_the_relay_before_the_tick", "tests/test_a_proxy_that_cannot_carry_udp_leaks_nothing_direct_e2e.py"], "marker": "e2e", "needs_root": ["linux"], "note": "Linux only, and not collected on Windows: the exit of the lab is a documentation address (198.51.100.9) added to lo with `ip addr add`, which needs root and iproute2; a mapped address in 127/8 would be thrown away by nICEr as bogus (stun_client_ctx.cpp nr_stun_transport_addr_check) and the pref that allows it is off in a product. The page reads a srflx equal to the gateway exit and the relay of the TURN server, the TURN name resolved by the DoH through the proxy, in the tick of 2 s. On the Windows runner of GitHub (administrator, the network of the runner) it could run too: not yet. A skipped test would turn the verdict red, hence a suite of its own. Its twin with the lab's exit on loopback and the pref stays in wrapper.e2e.udp on both systems, so that Windows keeps the walk of the chain by name."},
{"id": "wrapper.e2e.udp.sandbox", "giro": "G2", "os": ["linux"], "min_tests": 13, "exact": true, "tests": ["tests/test_the_socket_process_is_sandboxed_e2e.py", "tests/test_webrtc_realness.py::test_the_gather_is_real_without_a_proxy", "tests/test_webrtc_realness.py::test_a_gateway_with_coherent_udp_gives_the_page_a_srflx_born_through_its_relay", "tests/test_ice_names_by_the_context_proxy_e2e.py::test_a_gateway_without_udp_resolves_the_ice_name_then_ends_in_701"], "marker": "e2e", "needs_root": false, "note": "The browser WITH its sandbox, run by a normal user, as on any Linux that allows user namespaces. On the Ubuntu 24.04 runner AppArmor refuses them to a user, so every other non-root suite runs a browser WITHOUT the sandbox of its socket and content processes; the gate turns the restriction off for this leg (sysctl kernel.apparmor_restrict_unprivileged_userns=0) and the first test fails unless the socket and a tab process have a seccomp filter (Seccomp: 2). The three situations of the UDP line: A (a proxy that carries UDP: the srflx born through the relay), B (no proxy: the gather is real), C (a proxy with no UDP: the ICE server name goes by DoH through the proxy and the gather ends in 701). No root and no resolver trap needed."},
{"id": "wrapper.e2e.udp.exit", "giro": "G2", "os": ["linux"], "min_tests": 7, "exact": true, "tests": ["tests/test_the_whole_udp_chain_by_name_e2e.py::test_a_turn_srflx_by_name_arrives_through_the_relay_before_the_tick", "tests/test_a_proxy_that_cannot_carry_udp_leaks_nothing_direct_e2e.py"], "marker": "e2e", "needs_root": ["linux"], "note": "Linux only, and not collected on Windows: the exit of the lab is a documentation address (198.51.100.9) added to lo with `ip addr add`, which needs root and iproute2; a mapped address in 127/8 would be thrown away by nICEr as bogus (stun_client_ctx.cpp nr_stun_transport_addr_check) and the pref that allows it is off in a product. The page reads a srflx equal to the gateway exit and the relay of the TURN server, the TURN name resolved by the DoH through the proxy, in the tick of 2 s. On the Windows runner of GitHub (administrator, the network of the runner) it could run too: not yet. A skipped test would turn the verdict red, hence a suite of its own. Its twin with the lab's exit on loopback and the pref stays in wrapper.e2e.udp on both systems, so that Windows keeps the walk of the chain by name.", "linux_only": "The lab's exit is a documentation address the host must hold besides its loopback (nICEr throws away a mapped address in 127/8). Linux holds it on lo as root; Windows takes no extra address on its loopback pseudo-interface, and adding it to the runner's adapter took the runner off the network (runs 43314251547 and 43334169682 died in the test step). A Windows twin waits for a way that leaves the runner's network alone."},
{"id": "wrapper.e2e.udp.sandbox", "giro": "G2", "os": ["linux"], "min_tests": 13, "exact": true, "tests": ["tests/test_the_socket_process_is_sandboxed_e2e.py", "tests/test_webrtc_realness.py::test_the_gather_is_real_without_a_proxy", "tests/test_webrtc_realness.py::test_a_gateway_with_coherent_udp_gives_the_page_a_srflx_born_through_its_relay", "tests/test_ice_names_by_the_context_proxy_e2e.py::test_a_gateway_without_udp_resolves_the_ice_name_then_ends_in_701"], "marker": "e2e", "needs_root": false, "note": "The browser WITH its sandbox, run by a normal user, as on any Linux that allows user namespaces. On the Ubuntu 24.04 runner AppArmor refuses them to a user, so every other non-root suite runs a browser WITHOUT the sandbox of its socket and content processes; the gate turns the restriction off for this leg (sysctl kernel.apparmor_restrict_unprivileged_userns=0) and the first test fails unless the socket and a tab process have a seccomp filter (Seccomp: 2). The three situations of the UDP line: A (a proxy that carries UDP: the srflx born through the relay), B (no proxy: the gather is real), C (a proxy with no UDP: the ICE server name goes by DoH through the proxy and the gather ends in 701). No root and no resolver trap needed.", "linux_only": "It reads the seccomp filter of the socket and tab processes in /proc. The Windows twin reads the sandbox token of the same processes (integrity level, restrictions) and needs a measurement of the retail Firefox's tokens first; until then Linux only."},
{"id": "wrapper.e2e.web", "giro": "G2", "os": ["linux", "windows"], "min_tests": 27, "exact": true, "tests": ["tests/test_networkidle_through_a_served_browser_with_routes_e2e.py", "tests/test_http3_through_the_proxy_e2e.py"], "marker": "e2e", "needs_root": false, "note": "The networkidle e2e with routes and the HTTP/3 e2e, split from wrapper.e2e.udp (about 260 s of 500 on Linux; the whole suite did not fit the 15 minutes of Windows)."},
{"id": "wrapper.e2e.doh", "giro": "G2", "os": ["linux", "windows"], "min_tests": 19, "exact": true, "tests": ["tests/test_the_hosts_file_of_the_host_is_never_read_e2e.py", "tests/test_resolver_race_e2e.py", "tests/test_doh_under_stress_e2e.py", "tests/test_context_proxy_only_resolves_by_doh_e2e.py", "tests/test_doh_through_the_proxy_e2e.py", "tests/test_ice_names_by_the_context_proxy_e2e.py"], "marker": "e2e", "needs_root": ["linux"], "note": "Linux needs root: the resolver trap of the file (ResolverTrap) points /etc/resolv.conf at a counting resolver on port 53. Su Windows il resolver trap non gira: l'asserzione sul resolver di sistema è l'unica omessa. Run it without xdist (port 53 is one per host). On the Linux leg the gate exports INVPW_REQUIRE_TRAP=1: a trap that cannot run or bind port 53 is a failure, not a skipped assertion."},
{"id": "wrapper.e2e.context.egress", "giro": "G2", "os": ["linux", "windows"], "min_tests": 14, "exact": true, "tests": ["tests/test_nothing_leaves_but_the_proxy_e2e.py", "tests/test_a_turn_name_over_tcp_goes_through_the_proxy_of_the_context_e2e.py"], "marker": "e2e", "needs_root": ["linux"], "note": "Taken from the minimal-engine port (branch tests/minimal-port) unchanged but for the removed engine gate: 12 = 6 kinds of page work (hints, image/fetch/WebSocket/EventSource, WebRTC STUN and TURN-udp by name, geolocation, a service worker with push, a page still loading when its context closes) x 2 schemes (no proxy at launch and a gateway on the context; a launch gateway and a different one on the context), and 2 = the TURN server named over TCP in those two schemes. EXPECTED RED on the published firefox-63: the 2 TURN-by-name cases (the lookup of the TCP socket takes user context 0; fixed by commits ac0214bff4 and 058edd6cc6 of firefox-64). The 12 have not run on any engine yet. Like wrapper.e2e.doh: the Linux leg runs as root for the resolver trap (INVPW_REQUIRE_TRAP=1); on Windows the DoH log and the gateway's CONNECTs are the sink."},
{"id": "wrapper.e2e.context.sink", "giro": "G2", "os": ["linux", "windows"], "min_tests": 35, "exact": true, "tests": ["tests/test_nothing_of_a_context_leaves_but_through_its_proxy_e2e.py"], "marker": "e2e", "needs_root": ["linux"], "note": "The behavioural half of the class gate 'nothing of a context leaves but through its proxy', with a witness at an address of this host (no root, no address on lo) and the engine's own resolver log as the native-lookup sink. 35 = 31 + the 4 OCSP cases; the 31 are 19 probes (fetch, WebSocket, stun, turn over UDP, turn and turns over TCP, each by name, by IP and by a .local name, behind SOCKS5 and behind an HTTP proxy where the road differs) + 3 controls (the same probe by IP with no proxy IS heard by the witness) + 1 control of the native sink. + 4 PeerConnections built from a torn-down window (a detached iframe, a closed popup; behind SOCKS5 and behind HTTP; defect B3: EXPECTED RED on firefox-63, green on firefox-64) + 2 controls of them (the same PeerConnection from an attached iframe, green on both). + 2 cases of two contexts alive at once (each with its own proxy and DoH, a TURN server over TCP by a different name in each; behind SOCKS5 EXPECTED RED on firefox-63 like turn_tcp-name-socks5, behind HTTP green on both). EXPECTED RED on firefox-63: turn_tcp-name-socks5, turns_tcp-name-socks5 (user context 0, fixed in firefox-64) and the three .local cases fetch-local-socks5, stun-local-socks5, stun-local-http (audit B4, also red on firefox-64 until decided). The Linux leg runs as root so the resolver trap is a second sink. Windows reads the same engine log (its getaddrinfo lines are in the parent process file under the sandbox: run 43574494194), with the no-proxy native control as its positive control. THE OCSP CASES (4): a TLS page whose leaf, signed by a lab CA the engine trusts (put in the profile by the engine's xpcshell, no ignore_https_errors), names its OCSP responder by a NAME (ocsp-<nonce>.lab.test) and by an IP; a context behind the gateway loads it and the request must go through the gateway, never be looked up natively, in user context 0, or reach the responder (2 cases, EXPECTED RED on firefox-63, green on firefox-64); the same page in a context with no proxy IS asked of the responder (control); a page of an issuer the engine does not trust makes no OCSP request (negative control)."},
{"id": "wrapper.e2e.realness", "giro": "G2", "os": ["linux", "windows"], "min_tests": 32, "exact": true, "tests": ["tests/test_realness_behind_a_declared_exit_e2e.py"], "marker": "e2e", "needs_root": ["linux"], "note": "The realness check without a real proxy: six declared exits, the values a page reads, and the roads. Linux runs as root without xdist like the DoH suite (the resolver trap); on Windows the trap does not exist and the assertion on the system resolver is the only one omitted."},
{"id": "wrapper.unit.udp", "giro": "G1", "os": ["linux", "windows"], "min_tests": 221, "exact": true, "tests": ["tests/test_a_served_launch_cannot_turn_the_launch_counter_off.py", "tests/test_the_witness_picks_a_port_both_sockets_bind.py", "tests/test_preload_newtab_reaches_the_core_only_when_asked.py", "tests/test_the_resolver_trap_counts_its_own_users.py", "tests/test_the_doh_e2e_launch_on_a_virtual_display.py", "tests/test_the_realness_helpers.py", "tests/test_the_h3_line_helpers.py", "tests/test_the_fake_doh_delays_and_refuses.py", "tests/test_the_host_address_helper.py", "tests/test_the_udp_chain_helper.py", "tests/test_the_fake_doh_answers.py", "tests/test_doh_session_prefs_unit.py", "tests/test_the_leak_watcher_sees_a_direct_connection.py", "tests/test_the_http_proxy_helper_asks_for_credentials.py", "tests/test_every_route_command_is_answered_may_fail.py", "tests/test_the_network_declaration_reaches_the_engine.py", "tests/test_the_resolver_trap_is_required_by_the_gate.py", "tests/test_the_exit_of_a_context_is_discovered_through_its_own_gateway.py", "tests/test_the_witness_hears_a_direct_send.py"], "marker": "unit", "needs_root": false, "note": "92 = 6+32+21+7+8+3+9+6. The leak watcher file defines exactly one of its two resolver-trap tests per host (7 everywhere), so no test is skipped. `exact`: min_tests is raised by hand when a test is added."},
{"id": "wrapper.e2e.page", "giro": "G2", "os": ["linux", "windows"], "min_tests": 115, "exact": true, "tests": ["tests/test_a_tiny_download_on_a_served_browser_is_saved_e2e.py", "tests/test_a_page_that_moves_on_e2e.py", "tests/test_a_popup_is_reported_when_the_engine_says_it_is_ready_as_playwright_does_e2e.py", "tests/test_a_popup_of_a_link_reaches_the_client_e2e.py", "tests/test_popup_destinations_e2e.py", "tests/test_popups_reach_the_client_e2e.py", "tests/test_route_superseded_e2e.py"], "marker": "e2e", "needs_root": false, "note": "114 = 100 + the 14 of test_a_page_that_moves_on_e2e.py (a navigation the page overtook with location.replace ends; the engine fix 860ef8a6d9 is proved by it). 100 counted at the collection; was 96 = 10+32+16+34+4 before the popup tests of 6200bc2). A page is handed over when the engine says Page.ready; a popup reaches the client (link, noopener, window.open; own site and another; with and without a route; in-process and over launch_server) as Playwright's does; a superseded route. Needs the candidate binary, and the stock Playwright client of the dev extra."},
{"id": "wrapper.unit.page", "giro": "G1", "os": ["linux", "windows"], "min_tests": 44, "exact": true, "tests": ["tests/test_a_download_finished_before_it_was_announced_is_finished.py", "tests/test_every_order_of_the_events_of_a_popup_gives_one_page_event.py", "tests/test_ci_drive_gate_goes_through_the_core.py", "tests/test_a_page_is_handed_over_only_when_the_engine_says_it_is_ready.py", "tests/test_a_new_page_waits_for_the_engine.py", "tests/test_page_number_follows_the_call.py"], "marker": "unit", "needs_root": false, "note": "24 (counted at the collection; was 20 = 3+8+1+8 before 6200bc2). The page dispatcher's wait for Page.ready and what it hands over; the drive gate goes through the core (the engine waits for the session's road)."}
{"id": "wrapper.unit.udp", "giro": "G1", "os": ["linux", "windows"], "min_tests": 258, "exact": true, "tests": ["tests/test_the_server_says_nothing_about_the_launch_counter.py", "tests/test_the_witness_picks_a_port_both_sockets_bind.py", "tests/test_preload_newtab_reaches_the_core_only_when_asked.py", "tests/test_the_resolver_trap_counts_its_own_users.py", "tests/test_the_doh_e2e_launch_on_a_virtual_display.py", "tests/test_the_realness_helpers.py", "tests/test_the_h3_line_helpers.py", "tests/test_the_fake_doh_delays_and_refuses.py", "tests/test_the_host_address_helper.py", "tests/test_the_udp_chain_helper.py", "tests/test_the_fake_doh_answers.py", "tests/test_doh_session_prefs_unit.py", "tests/test_the_leak_watcher_sees_a_direct_connection.py", "tests/test_the_http_proxy_helper_asks_for_credentials.py", "tests/test_every_route_command_is_answered_may_fail.py", "tests/test_the_network_declaration_reaches_the_engine.py", "tests/test_the_resolver_trap_is_required_by_the_gate.py", "tests/test_the_exit_of_a_context_is_discovered_through_its_own_gateway.py", "tests/test_the_witness_hears_a_direct_send.py", "tests/test_the_egress_sink_helpers.py", "tests/test_the_lab_ca_and_its_ocsp_leaf.py", "tests/test_the_udp_bench_survives_what_a_loaded_machine_does_to_it.py"], "marker": "unit", "needs_root": false, "note": "92 = 6+32+21+7+8+3+9+6. The leak watcher file defines exactly one of its two resolver-trap tests per host (7 everywhere), so no test is skipped. `exact`: min_tests is raised by hand when a test is added. The sink of the egress gate (tests/test_the_egress_sink_helpers.py, 20): the engine's log (the same on Linux and Windows) and the witness read on known inputs, and a blind log that must raise, never answer 'nothing'. The lab CA of its OCSP case (tests/test_the_lab_ca_and_its_ocsp_leaf.py, 17; tests/test_the_fake_doh_answers.py +1, the DoH serving a lab-CA leaf): the leaf's AIA, trusted and untrusted issuers, the responder, the xpcshell step."},
{"id": "wrapper.e2e.page", "giro": "G2", "os": ["linux", "windows"], "min_tests": 120, "exact": true, "tests": ["tests/test_a_tiny_download_on_a_served_browser_is_saved_e2e.py", "tests/test_a_page_that_moves_on_e2e.py", "tests/test_a_popup_is_reported_when_the_engine_says_it_is_ready_as_playwright_does_e2e.py", "tests/test_a_popup_of_a_link_reaches_the_client_e2e.py", "tests/test_popup_destinations_e2e.py", "tests/test_popups_reach_the_client_e2e.py", "tests/test_route_superseded_e2e.py", "tests/test_closing_one_of_four_browsers_does_not_hold_the_loop_e2e.py"], "marker": "e2e", "needs_root": false, "note": "114 + the 5 of test_closing_one_of_four_browsers_does_not_hold_the_loop_e2e.py (four browsers in one process, one closes: the loop is held less than 50 ms by the clock of its own thread, the other three keep answering; the control holds the loop on purpose). 114 = 100 + the 14 of test_a_page_that_moves_on_e2e.py (a navigation the page overtook with location.replace ends; the engine fix 860ef8a6d9 is proved by it). 100 counted at the collection; was 96 = 10+32+16+34+4 before the popup tests of 6200bc2). A page is handed over when the engine says Page.ready; a popup reaches the client (link, noopener, window.open; own site and another; with and without a route; in-process and over launch_server) as Playwright's does; a superseded route. Needs the candidate binary, and the stock Playwright client of the dev extra."},
{"id": "wrapper.unit.page", "giro": "G1", "os": ["linux", "windows"], "min_tests": 72, "exact": true, "tests": ["tests/test_a_download_finished_before_it_was_announced_is_finished.py", "tests/test_every_order_of_the_events_of_a_popup_gives_one_page_event.py", "tests/test_ci_drive_gate_goes_through_the_core.py", "tests/test_a_page_is_handed_over_only_when_the_engine_says_it_is_ready.py", "tests/test_a_new_page_waits_for_the_engine.py", "tests/test_page_number_follows_the_call.py", "tests/test_a_commit_at_any_point_of_the_hand_over_reaches_the_client_once.py", "tests/test_no_event_of_any_family_is_lost_by_the_hand_over.py", "tests/test_the_hand_over_of_a_popup_holds_under_concurrency.py", "tests/test_a_page_closed_before_its_announcement_is_not_announced.py", "tests/test_a_live_event_does_not_overtake_the_replay_of_a_new_page.py"], "marker": "unit", "needs_root": false, "note": "72 = 44 + 3+9+5+1+10 of the popup hand-over (24 counted at the collection before; was 20 = 3+8+1+8 before 6200bc2). The page dispatcher's wait for Page.ready and what it hands over; the drive gate goes through the core (the engine waits for the session's road)."},
{"id": "wrapper.e2e.compositing", "giro": "G2", "os": ["linux", "windows"], "min_tests": 3, "exact": true, "tests": ["tests/test_software_compositing_is_declared_e2e.py"], "marker": "e2e", "needs_root": false, "note": "The engine DECLARES software compositing on every machine (core: the compositing entries of zoom.stealth.gfx.feature_status carry the VM decision, and on Windows gfx.webrender.software=true, gfx.webrender.software.d3d11=false). 3 = (1) the compositor read from a privileged context is 'WebRender (Software)' on Windows and on Linux (windowUtils.layerManagerType of each window: Troubleshoot.snapshot().graphics throws on this engine, `ext is null`, so it is not the route); (2) the GPU process uses under 1.5 s of CPU on the fixed 10-scene loop of one browser (Windows runner: 0.32 s declared, 2.7-4.2 s not, runs 43652292533 and 43642744101; on Linux it is held to the bound if a GPU process exists); (3) the 86 keys of the page-bytes probe plus the canvas 2D scenes (drawImage scaled with smoothing off/low/medium/high, text with linear/radial/conic gradients) equal tests/data/page_bytes_<os>.json, PNGs on decoded pixels. EXPECTED RED on the core 64.71.0 (tests 1 and 2 on Windows). The reference of Windows holds the 75 stable keys and 6 of the 11 PNG keys of run 43652292533; the five other PNG keys and the new canvas keys, and all of Linux, are written from the first run on the engine of the reference (the failure of test 3 prints RECORD-BEGIN ... RECORD-END with the entries to merge): a reference that is not complete is red, never skipped."},
{"id": "wrapper.unit.compositing", "giro": "G1", "os": ["linux", "windows"], "min_tests": 19, "exact": true, "tests": ["tests/test_the_page_bytes_reference_compares_decoded_pixels.py"], "marker": "unit", "needs_root": false, "note": "The helpers of wrapper.e2e.compositing on known inputs, no browser: the PNG compared on decoded pixels (another deBG chunk and compression are the same, one pixel is not, every scanline filter), the comparison with a reference (changed, missing and extra keys named, the entry to record), the type of an engine process, an engine process known by its executable and not by the name it gives itself (Linux), and the CPU of a window, and the shape of the committed Windows reference."}
]
+23 -19
View File
@@ -1,17 +1,20 @@
---
title: "Canvas and WebGL fingerprints, identical across OSes"
description: "Canvas and WebGL fingerprints identical across Windows and Linux: intercept readback, not the render, so one seed produces a byte-identical hash on every OS."
title: "Canvas and WebGL fingerprints across OSes"
description: "Canvas and WebGL fingerprints across Windows and Linux: 2D canvas is drawn on the CPU, noise is projected only when WebGL and WebGPU pixels are read back, and it depends only on the seed."
parent: "Canvas, WebGL, Fonts and Audio"
grand_parent: "Guides"
nav_order: 9
---
# Canvas and WebGL fingerprints, identical across OSes
# Canvas and WebGL fingerprints across OSes
A GPU-backed render surface can't be read from or written to directly and safely, so
the fix intercepts the one place JavaScript can actually see the result instead - the
same seed then produces a byte-identical canvas and WebGL hash on Windows and Linux.
same seed then gives the same noise on Windows and Linux. 2D canvas is drawn on the CPU, so it
does not depend on the GPU; the noise is projected only when WebGL and WebGPU pixels are read back.
Text and GPU raster can still differ slightly between the two OSes, and the PNG container is left
as a stock Firefox writes it.
[Why headless browsers render different fonts](headless-fonts-differ.md) and
[how to make Linux and macOS report real Windows fonts](bundled-fonts-cross-platform.md)
@@ -92,17 +95,18 @@ for the same reason: nothing about it resembles noise added on top of a real sig
| Additive per-call noise | Perturbs a fraction of pixels on top of the real render | Two reads in one page differ; the real render's font/GPU signature still shows through; the noise has a high-frequency shape a single read can flag |
| Full substitution | Replaces pixels with a pure function of the seed and the pixel position, with zero input from the render underneath | Must leave low-entropy buffers untouched so it does not break legitimate canvas reads |
## The proof: byte-identical hashes, not just "looks similar"
## What was checked, and what was not
Rendered the same seed's canvas (text plus a gradient) and WebGL scene (a
high-entropy draw) on Windows and on Linux, hashed both in-page. The hashes matched
byte for byte on both platforms. Run against a commercial fingerprint scanner across
multiple seeds, zero failures on either OS.
high-entropy draw) on Windows and on Linux, hashed both in-page, and ran a commercial
fingerprint scanner across multiple seeds. What holds: the noise is a pure function of
the seed and of the pixels it is applied to, so two reads of the same bytes give the same
result, and the 2D path does not depend on the GPU.
That is a stronger claim than "produces a plausible fingerprint." It's the same
identity, provably, regardless of which OS is actually running underneath - which is
what makes a seed a real, portable identity instead of a value that happens to look
right on the machine it was tested on.
What is not claimed: that every byte matches between a Windows and a Linux host. Text
pixels follow the host's rasteriser on Linux, and GPU raster can differ by one level
between drivers. Whether two profiles with the same font can be linked by the way they
rasterise has not been measured.
## What this generalises to, and where the edges still are
@@ -121,8 +125,8 @@ a fact that becomes true once and stays true.
The render was never the reachable surface. Content only ever sees a canvas or a
WebGL scene through a handful of readback calls, and putting the substitution there
instead of in the renderer is what makes a seed portable: the same identity produces
the same bytes on Windows and on Linux, because nothing about either host's actual
rendering pipeline reaches the output.
the same noise on Windows and on Linux, because the noise comes from the seed and not from
the host's rendering pipeline.
The tradeoff is honest rather than free - the fix covers only the readback paths it
enumerates, and a masking-safe design still has to leave genuinely low-entropy canvas
@@ -131,10 +135,10 @@ fingerprinting.
## Short answers to the questions that lead here
**Can canvas and WebGL fingerprints be made identical across operating systems?** Yes,
if the interception happens at every point content can read the result rather
than at the render itself, which is the part that can't be touched directly on a
GPU-backed surface.
**Can canvas and WebGL fingerprints be made the same across operating systems?** The
noise can: it is applied where content can read the result, from the seed, rather than at
the render itself, which can't be touched directly on a GPU-backed surface. The pixels
underneath still differ slightly between hosts for text and GPU raster.
**Why substitution instead of adding noise to the real render?** Noise on top of a
real image still carries the host's own rendering signature underneath it.
@@ -162,7 +166,7 @@ content can observe, not at the source - applied to a different surface.
retrieved 2026-08-28, the enumerable set of readback calls this page's interception
point covers.
- This project's own render-readback interception work and its cross-platform
validation (same-seed byte-identical hashes on Windows and Linux, multi-seed
validation (same-seed hashes on Windows and Linux, multi-seed
results against a commercial fingerprint scanner).
**See also:** [canvas fingerprint noise](canvas-fingerprint-noise.md), for why
+2 -2
View File
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "invisible_playwright"
version = "0.51.1"
version = "0.52.1"
description = "Playwright wrapper for a patched Firefox with deterministic stealth profile."
readme = "README.md"
requires-python = ">=3.11"
@@ -69,7 +69,7 @@ dependencies = [
# metadata; nothing in src/ hardcodes a second copy (tests/test_core_pin.py
# fails if one appears). What stays invisible to install-time machinery is the
# --no-deps / lockfile residue, and _pin.py is the only layer that sees it.
"invisible_core==63.67.0",
"invisible_core==64.73.0",
# ⛔ playwright is NO LONGER a dependency: since the full fork, the Python
# client lives in src/invisible_playwright/_pw/ and its server in
# src/invisible_playwright/_juggler/ (no Node driver). Reintroducing it would not visibly
-132
View File
@@ -1,132 +0,0 @@
"""How much does answering the protocol IN PROCESS actually cost?
⛔ THE QUESTION IS NARROW ON PURPOSE. Not "is the Python path faster than the
Node driver" - that comparison is dominated by the browser and would answer a
different question. This measures ONLY the machinery this package adds between
`Channel.send` and the code that talks to Juggler: building the message dict,
the queue, the worker-thread hop, the reply, and `call_soon_threadsafe` back
onto the loop.
That is the thing the owner asked about on 2026-08-28: inside one process,
serialising to yourself looks like waste. Whether it IS waste depends on how it
compares to the round trip it wraps, and this project decides that kind of
question with a number.
⛔ NO BROWSER, and that is what makes this trustworthy. A fake server answers
instantly, so what is left in the measurement is the transport and nothing
else. It also means the result does not depend on the machine being quiet in
the way a browser measurement does - though a loaded machine still widens the
tail, which is why the median is reported next to the mean.
python scripts/bench_transport.py
python scripts/bench_transport.py --giri 20000
"""
from __future__ import annotations
import argparse
import asyncio
import pathlib
import statistics
import sys
import time
ROOT = pathlib.Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT / "src"))
#: What a real Juggler round trip costs, measured on 2026-08-27 with the
#: shipped binary. It is the denominator: the transport's cost only means
#: something as a fraction of the work it wraps.
#: ⛔ `Runtime.evaluate("1")` and NOT `Heap.collectGarbage`, which was used once
#: as a "bare command" and actually collects garbage - 26,8 ms of browser work
#: attributed to the transport.
JUGGLER_ROUND_TRIP_MS = 2.4
class FakeServer:
"""Answers instantly, so only the transport is being timed."""
def __init__(self) -> None:
self.transport = None
def attach(self, transport) -> None:
self.transport = transport
def shutdown(self) -> None:
pass
def handle(self, message):
return {"value": message["params"].get("n")}
async def run(rounds: int) -> int:
from invisible_playwright._juggler.transport import InProcessTransport
loop = asyncio.get_running_loop()
transport = InProcessTransport(loop, FakeServer())
await transport.connect()
pending = {}
def on_message(message):
future = pending.pop(message.get("id"), None)
if future is not None and not future.done():
future.set_result(message)
transport.on_message = on_message
async def one(index: int):
future = loop.create_future()
pending[index] = future
transport.send({"id": index, "guid": "x", "method": "noop",
"params": {"n": index},
"metadata": {"apiName": "bench"}})
return await future
# ⛔ A warm-up that is DISCARDED: the first calls pay for thread start-up
# and for the first allocation of every structure, and folding those into
# the average is how a microbenchmark reports a number nobody can reproduce.
for i in range(200):
await one(i)
samples = []
for i in range(rounds):
start = time.perf_counter()
await one(200 + i)
samples.append((time.perf_counter() - start) * 1000.0)
transport.request_stop()
await transport.wait_until_stopped()
samples.sort()
media = statistics.fmean(samples)
mediana = samples[len(samples) // 2]
p95 = samples[int(len(samples) * 0.95)]
print("giri utili %d" % len(samples))
print("media %.4f ms" % media)
print("mediana %.4f ms" % mediana)
print("p95 %.4f ms" % p95)
print("p99 %.4f ms" % samples[int(len(samples) * 0.99)])
print()
print("un giro Juggler vero %.2f ms (misurato 2026-08-27)"
% JUGGLER_ROUND_TRIP_MS)
quota = 100.0 * mediana / JUGGLER_ROUND_TRIP_MS
print("il transport pesa %.1f%% di una chiamata vera" % quota)
print()
if quota < 10:
print("VERDETTO: il transport NON e' il costo. Togliere thread e coda "
"andrebbe fatto per semplicita', se mai, non per velocita'.")
else:
print("VERDETTO: il transport pesa abbastanza da giustificare il "
"refactor asincrono.")
return 0
def main() -> int:
p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
p.add_argument("--giri", type=int, default=5000)
a = p.parse_args()
return asyncio.run(run(a.giri))
if __name__ == "__main__":
sys.exit(main())
+2 -2
View File
@@ -100,8 +100,8 @@ def _classes(tree: ast.AST) -> dict:
#: next step. The failure it would cause is silent and backwards: an `async
#: def` operation is absent from `_methods`, so `reachable` returns an EMPTY
#: known-set for it, and every field that operation legitimately reads gets
#: reported as ignored. Same tuple as `check_unresolved_names.py`'s
#: `_FUNCTIONS`, for the same reason.
#: reported as ignored. Both function kinds are listed for the same reason as in any
#: AST walk over operations.
_FUNCTIONS = (ast.FunctionDef, ast.AsyncFunctionDef)
-243
View File
@@ -1,243 +0,0 @@
"""A method that uses a name it never has: the NameError nobody ran into yet.
⛔ IT CAUGHT TWO REAL DEFECTS THE MOMENT IT WAS WRITTEN, both of the same shape
and both invisible to every other check in this repo:
* `Actions._set_checked` passed `frame_id` to its retry loop without ever
taking it as a parameter, while `check()` and `uncheck()` accepted the
argument and dropped it. Every `page.check()` on the Python transport died
with `Page.check: name 'frame_id' is not defined` - and the transport judge
reported it as an ENGINE defect, because the test that exercises it pins the
transport itself and therefore fails identically on both arms.
* `Actions.drag_and_drop` did the same thing twice in one function.
⛔ WHY THE SUITE DID NOT SEE IT. A `NameError` inside a method is not a syntax
error and not an import error: the module loads, the class builds, the name
resolves at CALL time. So the whole file is green until somebody calls that one
method, and the two above sat in a package with 500 passing tests.
**What it does NOT do.** It does not type-check, it does not follow
`globals()`, `exec`, or a name injected by a decorator, and it deliberately
treats every module-level assignment and import as available. The question it
asks is the narrowest one that catches this: *does this function use a bare
name that is neither its parameter, nor assigned in it, nor defined at module
level?*
python scripts/check_unresolved_names.py
python scripts/check_unresolved_names.py --selftest
"""
from __future__ import annotations
import argparse
import ast
import builtins
import pathlib
import sys
ROOT = pathlib.Path(__file__).resolve().parent.parent
#: ⛔ `scripts/` IS IN THE PERIMETER SINCE 2026-08-29, and leaving it out was
#: not a scoping decision - it was a hole this gate exists to close. On that
#: date `upstream_baseline.py:_per_file` was found returning `1 if morti else
#: 0` with `morti` assigned nowhere: a guaranteed NameError, sitting in the
#: repository, while this gate reported "none in 102 file(s)". Pointed at that
#: one file by hand it named the fault correctly, so the LOGIC was never
#: wrong; only the perimeter was.
#:
#: And the argument for scanning `scripts/` is STRONGER than for the package,
#: not weaker. The reason this class of defect survives is that a NameError
#: inside a function is invisible until someone calls it - and the package has
#: 529 unit tests calling into it, while these scripts have none. `_per_file`
#: is reached only by `--per-file`, on the async arm, forty minutes into a run
#: nobody makes twice.
#:
#: Measured before widening: 22 files, zero findings besides the real one - so
#: this costs no false positives to keep.
SCANNED = [ROOT / "src" / "invisible_playwright", ROOT / "scripts"]
sys.stdout.reconfigure(encoding="utf-8")
_FUNCTIONS = (ast.FunctionDef, ast.AsyncFunctionDef)
def _module_names(tree: ast.AST) -> set:
known = {n.name for n in ast.walk(tree)
if isinstance(n, _FUNCTIONS + (ast.ClassDef,))}
known |= {t.id for n in ast.walk(tree) if isinstance(n, ast.Assign)
for t in n.targets if isinstance(t, ast.Name)}
known |= {n.target.id for n in ast.walk(tree)
if isinstance(n, ast.AnnAssign) and isinstance(n.target, ast.Name)}
known |= {a.asname or a.name.split(".")[0]
for n in ast.walk(tree) if isinstance(n, (ast.Import, ast.ImportFrom))
for a in n.names}
# ⛔ THE MODULE DUNDERS, which are not builtins and are not imports:
# Python puts them in the module namespace itself. They only became
# reachable when this gate started walking module-level functions, and
# `__file__` in a plain function is the commonest of them by far - it was
# the first false positive the widening produced.
known |= {"__file__", "__name__", "__doc__", "__package__", "__spec__",
"__loader__", "__builtins__", "__path__"}
return known | set(dir(builtins))
def _bound_in(fn: ast.AST) -> set:
"""Every name that exists inside this function by the time it runs.
⛔ Nested functions and lambdas contribute their PARAMETERS, because the
outer body legitimately refers to them; comprehension targets and `except
... as` names too. Leaving any of those out turns ordinary code into a
fault, and a check that cries wolf is switched off after the third time.
"""
args = fn.args
bound = {a.arg for a in list(args.args) + list(args.kwonlyargs)
+ list(getattr(args, "posonlyargs", []))}
if args.vararg:
bound.add(args.vararg.arg)
if args.kwarg:
bound.add(args.kwarg.arg)
for n in ast.walk(fn):
if isinstance(n, ast.Name) and isinstance(n.ctx, ast.Store):
bound.add(n.id)
elif isinstance(n, _FUNCTIONS + (ast.Lambda,)) and n is not fn:
inner = n.args
for a in (list(inner.args) + list(inner.kwonlyargs)
+ list(getattr(inner, "posonlyargs", []))):
bound.add(a.arg)
# ⛔ `*args` and `**kw` OF THE NESTED FUNCTION TOO. Leaving these
# out is not a small gap: the first run of this checker over the
# real package reported 10 faults and every one of them was this -
# `def patched(**kw)` inside a wrapper, which is the single most
# common shape in the file it was scanning. A checker that is
# wrong ten times out of ten teaches people to ignore it, and the
# two REAL defects it had just found would have been ignored with
# the rest.
if inner.vararg:
bound.add(inner.vararg.arg)
if inner.kwarg:
bound.add(inner.kwarg.arg)
if not isinstance(n, ast.Lambda):
bound.add(n.name)
elif isinstance(n, ast.comprehension):
for t in ast.walk(n.target):
if isinstance(t, ast.Name):
bound.add(t.id)
elif isinstance(n, ast.ExceptHandler) and n.name:
bound.add(n.name)
elif isinstance(n, ast.Global):
bound.update(n.names)
elif isinstance(n, ast.Nonlocal):
bound.update(n.names)
return bound
def unresolved(source: str, where: str = "<source>") -> list:
tree = ast.parse(source)
known = _module_names(tree)
out = []
def scan(fn, owner):
bound = _bound_in(fn)
for n in ast.walk(fn):
if isinstance(n, ast.Name) and isinstance(n.ctx, ast.Load):
if n.id not in bound and n.id not in known:
out.append((where, owner, fn.name, n.id, n.lineno))
for cls in [n for n in ast.walk(tree) if isinstance(n, ast.ClassDef)]:
for fn in [n for n in cls.body if isinstance(n, _FUNCTIONS)]:
scan(fn, cls.name)
# ⛔ MODULE-LEVEL FUNCTIONS TOO, and they were invisible until
# 2026-08-29. This gate was written against a file of dispatcher classes,
# so it walked classes and nothing else; a plain function was never looked
# at. It cost a real defect the day a refactor moved seventeen leaf helpers
# into two new modules with no classes at all: one of them used `json`
# without importing it, this gate reported "none in 103 files", and the
# failure surfaced as a NameError out of one test - which is the exact
# shape it exists to catch before a caller does.
for fn in [n for n in tree.body if isinstance(n, _FUNCTIONS)]:
scan(fn, "<module>")
return out
SELFTEST = [
("the defect itself: used, never taken",
"class A:\n def op(self, x):\n return self.go(frame_id)\n", 1),
("a parameter is not a fault",
"class A:\n def op(self, frame_id):\n return frame_id\n", 0),
("a keyword-only parameter is not a fault",
"class A:\n def op(self, *, frame_id=None):\n return frame_id\n", 0),
("something assigned in the body is not a fault",
"class A:\n def op(self):\n v = 1\n return v\n", 0),
("a module-level name is not a fault",
"H = 1\nclass A:\n def op(self):\n return H\n", 0),
("a MODULE-LEVEL FUNCTION using a name nobody imported",
"def helper(x):\n return json.dumps(x)\n", 1),
("the same module-level function with the import present",
"import json\ndef helper(x):\n return json.dumps(x)\n", 0),
("__file__ in a module-level function is not a fault",
"def where():\n return __file__\n", 0),
("an import is not a fault",
"import json\nclass A:\n def op(self):\n return json\n", 0),
("a builtin is not a fault",
"class A:\n def op(self):\n return len([])\n", 0),
("a nested function's parameter is not a fault",
"class A:\n def op(self):\n def run(p):\n return p\n"
" return run\n", 0),
("a comprehension target is not a fault",
"class A:\n def op(self):\n return [i for i in range(3)]\n", 0),
("an except-as name is not a fault",
"class A:\n def op(self):\n try:\n pass\n"
" except ValueError as e:\n return e\n", 0),
("two in one function are both reported",
"class A:\n def op(self):\n return (a_missing, b_missing)\n", 2),
# ⛔ The two below are the shape that produced 10 false alarms on the first
# real run. They are here so the next person who tightens `_bound_in` finds
# out immediately instead of from a wall of noise.
("a nested function's **kwargs is not a fault",
"class A:\n def op(self):\n def patched(**kw):\n"
" return kw\n return patched\n", 0),
("a lambda's *args is not a fault",
"class A:\n def op(self):\n return lambda *args: args\n", 0),
]
def selftest() -> int:
bad = 0
for name, source, expected in SELFTEST:
got = len(unresolved(source))
ok = got == expected
bad += 0 if ok else 1
print(" %-48s %s (%d, expected %d)"
% (name, "ok" if ok else "BROKEN", got, expected))
print("selftest: %d cases, %d broken" % (len(SELFTEST), bad))
return 1 if bad else 0
def main() -> int:
p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
p.add_argument("--selftest", action="store_true")
p.add_argument("paths", nargs="*",
help="default: the package's own source, plus scripts/")
a = p.parse_args()
if a.selftest:
return selftest()
files = ([pathlib.Path(x) for x in a.paths]
or sorted(f for root in SCANNED for f in root.rglob("*.py")))
faults = []
for f in files:
try:
faults += unresolved(f.read_text(encoding="utf-8"), str(f))
except SyntaxError as bad:
print(" %s: cannot be parsed (%s)" % (f, bad))
return 2
for where, cls, fn, name, line in faults:
print(" %s :: %s.%s uses %r at line %d and never has it"
% (pathlib.Path(where).name, cls, fn, name, line))
if faults:
print("UNRESOLVED NAMES: %d. Each one is a NameError waiting for the "
"first caller of that method." % len(faults))
return 1
print("UNRESOLVED NAMES: none in %d file(s)." % len(files))
return 0
if __name__ == "__main__":
sys.exit(main())
+354
View File
@@ -0,0 +1,354 @@
"""The GeoIP database of a CI leg: written by this file, the same bytes on every run, and the proof that the leg launched with it.
python scripts/ci_lab_geoip.py build [--pin ci/geoip.json] [--dest DIR] # writes DIR/geoip-aio-all.mmdb, exports STEALTHFOX_GEOIP_MMDB
python scripts/ci_lab_geoip.py evidence [--out result/geoip.json] # what the environment of THIS command says
python scripts/ci_lab_geoip.py verify [--pin ci/geoip.json] --evidence FILE [--used FILE] # exit 1: the leg did not run with the pinned database
Why this exists (run 43211837926, the root legs of the realness suite): without ``STEALTHFOX_GEOIP_MMDB`` the core asked GitHub which GeoIP
database is the latest on every call, from the python of the test, and a resolver trap counted those names (github.com, api.github.com) as the
browser's. A CI leg reaches no site for its data and uses no licensed one: the database is made here, from the table below, with nothing but the
standard library. It holds the networks the tests look up (the six exits of tests/_realness_support.py EXITS) and the fields the core reads
(``country.iso_code``, ``location.latitude`` / ``longitude`` / ``time_zone``); an address that is not in it (the documentation ranges the lab uses,
loopback, any IPv6) is "not in the database", as in the real one. ``ci/geoip.json`` holds the sha256 of the file: ``build`` refuses to go on when
what it wrote is not that, ``evidence`` says which file a launch ran with, and ``scripts/ci_verdict.py judge --geoip`` turns a leg that ran with
anything else red. The real database is looked at only by the release (scripts/ci_real_geoip_check.py).
The format is MaxMind DB 2.0 (https://maxmind.github.io/MaxMind-DB/): a binary search tree of node_count nodes of two records of 24 bits, 16 zero
bytes, the data section, the marker and the metadata map. The tree is an ip_version 6 tree with the IPv4 space under ::/96, as in the real database,
so that a lookup of an IPv6 address answers "not found" instead of raising. The metadata integers have the types libmaxminddb checks.
``build`` writes ``STEALTHFOX_GEOIP_MMDB=<path>`` to ``$GITHUB_ENV`` (every later step of the job sees it, ``sudo -E`` carries it to a root leg) and to
stdout.
"""
from __future__ import annotations
import argparse
import hashlib
import ipaddress
import json
import os
import struct
import sys
from pathlib import Path
ENV = "STEALTHFOX_GEOIP_MMDB"
FILE_NAME = "geoip-aio-all.mmdb"
MARKER = b"\xab\xcd\xefMaxMind.com"
RECORD_BITS = 24
BUILD_EPOCH = 1793790075 # fixed: the same bytes on every run
def addr(*octets: int) -> str:
"""A dotted address from its numbers (no address is written out as text in this repository: the tests and this table build theirs)."""
return ".".join(str(o) for o in octets)
def net(a: int, b: int, c: int) -> str:
"""The /24 of a.b.c."""
return addr(a, b, c, 0) + "/24"
#: The six exits of tests/_realness_support.py EXITS (each test declares the .5 of its /24) and what the core reads of them: country, IANA zone,
#: and the coordinates of the city centre (public geography). The tests ask the database for their truth at test time, so any coherent values do.
NETWORKS = {
net(1, 178, 10): ("DE", "Europe/Berlin", 50.1109, 8.6821), # germany
net(1, 0, 16): ("JP", "Asia/Tokyo", 35.6895, 139.6917), # japan
net(1, 6, 0): ("IN", "Asia/Kolkata", 12.9716, 77.5946), # india
net(1, 0, 4): ("AU", "Australia/Melbourne", -37.8136, 144.9631), # australia
net(1, 178, 32): ("BR", "America/Sao_Paulo", -23.5505, -46.6333), # brazil
net(1, 32, 239): ("US", "America/Los_Angeles", 34.0522, -118.2437), # united_states
}
class Refused(Exception):
pass
class U16(int):
"""A uint16 of the metadata: not the smallest type that holds it, libmaxminddb checks the type of each key."""
class U32(int):
pass
class U64(int):
pass
def _control(kind: int, size: int) -> bytes:
"""The control byte(s) of a value of type `kind` (1..15) and `size`."""
if kind <= 7:
first, ext = kind << 5, b""
else:
first, ext = 0, bytes([kind - 7])
if size < 29:
return bytes([first | size]) + ext
if size < 285:
return bytes([first | 29]) + ext + bytes([size - 29])
if size < 65821:
return bytes([first | 30]) + ext + struct.pack(">H", size - 285)
return bytes([first | 31]) + ext + struct.pack(">I", size - 65821)[1:]
def _unsigned(kind: int, value: int, width: int) -> bytes:
raw = value.to_bytes(width, "big").lstrip(bytes([0])) # MaxMind DB integers drop their leading zero bytes
return _control(kind, len(raw)) + raw
def encode(value) -> bytes:
if isinstance(value, U16):
return _unsigned(5, int(value), 2)
if isinstance(value, U32):
return _unsigned(6, int(value), 4)
if isinstance(value, U64):
return _unsigned(9, int(value), 8)
if isinstance(value, str):
raw = value.encode("utf-8")
return _control(2, len(raw)) + raw
if isinstance(value, float):
return _control(3, 8) + struct.pack(">d", value)
if isinstance(value, dict):
out = _control(7, len(value))
for key in sorted(value): # sorted: the same bytes whatever the order of the table
out += encode(key) + encode(value[key])
return out
if isinstance(value, (list, tuple)):
return _control(11, len(value)) + b"".join(encode(v) for v in value)
raise TypeError("cannot encode %r" % (value,))
#: Every address that is not reserved (RFC 6890: this network, private, shared, loopback, link-local, protocol assignments, documentation,
#: benchmarking, multicast, the rest of class E) and is not one of the six exits above answers ONE record: the egress address of the machine that
#: runs a test is not known in advance (a runner of any provider, any region) and a launch with no proxy asks the database for it. Without this
#: record such a launch ends in "egress IP not present in the geoip database" (run 43351424907 of PR 486: 495 errors of one cause). The record is
#: declared here, so it is the same on every machine, which a download of the real database is not. The reserved ranges stay "not in the
#: database", as in the real one: the lab's own exits (the documentation addresses) must not resolve to anything.
FALLBACK = ("US", "America/New_York", 40.7128, -74.006)
RESERVED = tuple(ipaddress.ip_network(n) for n in (
addr(0, 0, 0, 0) + "/8", addr(10, 0, 0, 0) + "/8", addr(100, 64, 0, 0) + "/10", addr(127, 0, 0, 0) + "/8", addr(169, 254, 0, 0) + "/16",
addr(172, 16, 0, 0) + "/12", addr(192, 0, 0, 0) + "/24", addr(192, 0, 2, 0) + "/24", addr(192, 88, 99, 0) + "/24", addr(192, 168, 0, 0) + "/16",
addr(198, 18, 0, 0) + "/15", addr(198, 51, 100, 0) + "/24", addr(203, 0, 113, 0) + "/24", addr(224, 0, 0, 0) + "/4", addr(240, 0, 0, 0) + "/4"))
def fallback_networks() -> list:
"""The public space minus the reserved ranges minus the networks of the table: disjoint CIDRs (the writer takes no overlap)."""
if FALLBACK is None: # a test builds the database without it, to stand for one that has no answer for an address
return []
left = [ipaddress.ip_network("0.0.0.0/0")]
for hole in list(RESERVED) + [ipaddress.ip_network(c) for c in NETWORKS]:
nxt = []
for net in left:
if net.overlaps(hole):
nxt.extend(net.address_exclude(hole) if net.supernet_of(hole) else [])
else:
nxt.append(net)
left = nxt
return sorted(left, key=lambda n: (int(n.network_address), n.prefixlen))
def records() -> dict:
def one(country, zone, lat, lon):
return {"country": {"iso_code": country}, "location": {"latitude": lat, "longitude": lon, "time_zone": zone}}
table = {cidr: one(*row) for cidr, row in NETWORKS.items()}
table.update({str(net): one(*FALLBACK) for net in fallback_networks()})
return table
def build_bytes() -> bytes:
"""The database: the same bytes on every call."""
data = bytearray()
offsets: dict = {}
leaves = []
table = records()
for cidr in sorted(table, key=lambda c: (int(ipaddress.ip_network(c).network_address), ipaddress.ip_network(c).prefixlen)):
blob = encode(table[cidr])
if blob not in offsets:
offsets[blob] = len(data)
data += blob
leaves.append((ipaddress.ip_network(cidr), offsets[blob]))
# the trie: nodes are [left, right]; a child is None (no data), ("node", index) or ("data", offset)
nodes = [[None, None]]
for net, offset in leaves:
if net.version != 4:
raise ValueError("this writer takes IPv4 networks: %s" % net)
bits = int(net.network_address)
prefix = 96 + net.prefixlen # the IPv4 space sits under ::/96
index = 0
for depth in range(prefix):
bit = (bits >> (127 - depth)) & 1
if depth == prefix - 1:
nodes[index][bit] = ("data", offset)
else:
child = nodes[index][bit]
if child is None:
nodes.append([None, None])
child = ("node", len(nodes) - 1)
nodes[index][bit] = child
elif child[0] != "node":
raise ValueError("%s sits inside a network that already has data" % net)
index = child[1]
count = len(nodes)
def record(child) -> int:
if child is None:
return count
return child[1] if child[0] == "node" else count + 16 + child[1]
tree = bytearray()
for left, right in nodes:
for child in (left, right):
value = record(child)
if value >= 1 << RECORD_BITS:
raise ValueError("a record does not fit in %d bits" % RECORD_BITS)
tree += value.to_bytes(RECORD_BITS // 8, "big")
metadata = {
"binary_format_major_version": U16(2),
"binary_format_minor_version": U16(0),
"build_epoch": U64(BUILD_EPOCH),
"database_type": "GeoIP2-City",
"description": {"en": "invisible CI lab database: the networks the tests look up, and one record for every other public address"},
"ip_version": U16(6),
"languages": ["en"],
"node_count": U32(count),
"record_size": U16(RECORD_BITS),
}
return bytes(tree) + bytes(16) + bytes(data) + MARKER + encode(metadata)
def sha256_of_bytes(blob: bytes) -> str:
return hashlib.sha256(blob).hexdigest()
def sha256_of(path) -> str:
h = hashlib.sha256()
with open(path, "rb") as f:
for block in iter(lambda: f.read(1 << 20), b""):
h.update(block)
return h.hexdigest()
def load_pin(path) -> dict:
try:
pin = json.loads(Path(path).read_text(encoding="utf-8"))
except (OSError, ValueError) as exc:
raise Refused("the pin %s cannot be read: %s" % (path, exc))
sha = pin.get("mmdb_sha256") if isinstance(pin, dict) else None
if not isinstance(sha, str) or len(sha) != 64 or any(c not in "0123456789abcdef" for c in sha):
raise Refused("the pin %s has no mmdb_sha256 that is a sha256" % path)
return pin
def build(pin: dict, dest: Path) -> Path:
"""Write the database to DEST and check it against the pin: a writer that no longer makes the pinned bytes is red."""
blob = build_bytes()
got = sha256_of_bytes(blob)
if got != pin["mmdb_sha256"]:
raise Refused("the lab database made by scripts/ci_lab_geoip.py has sha256 %s, the pin (ci/geoip.json) says %s: change both in one commit"
% (got, pin["mmdb_sha256"]))
dest.mkdir(parents=True, exist_ok=True)
target = dest / FILE_NAME
target.write_bytes(blob)
return target
def evidence(environ=None) -> dict:
"""What the environment of this command says about the database: the value of the variable, whether it is a file, its sha256."""
environ = os.environ if environ is None else environ
value = environ.get(ENV, "")
out = {"env": value, "exists": False, "sha256": None}
if value and os.path.isfile(value):
out["exists"] = True
out["sha256"] = sha256_of(value)
return out
def verify(pin: dict, evidence_file, used_file=None) -> list:
"""The reasons a leg did not run with the pinned database ([] = it did). The same reading as the judge's (scripts/ci_verdict.py), and
independent of it: a step of the workflow runs this, so that a judge that does not know the evidence yet (the first merge to main ends that)
is not the only thing standing between a leg with no database and a green run.
``evidence_file``: what the environment said BEFORE pytest was launched (the ``evidence`` command). ``used_file``: what the process of the
tests used (tests/geoip_used.py, written when pytest ends): the variable at the end, the sha256 of that file, and how many times the core went
to GitHub for a database, which has to be none."""
problems = []
def read(path, what):
try:
data = json.loads(Path(path).read_text(encoding="utf-8"))
if not isinstance(data, dict):
raise ValueError("not a JSON object")
return data
except (OSError, ValueError) as exc:
problems.append("the %s %s cannot be read: %s" % (what, path, exc))
return None
for what, path in (("evidence", evidence_file), ("record of use", used_file)):
if path is None:
continue
data = read(path, what)
if data is None:
continue
if not data.get("env"):
problems.append("the %s says STEALTHFOX_GEOIP_MMDB was not set" % what)
elif not data.get("exists") or not data.get("sha256"):
problems.append("the %s says STEALTHFOX_GEOIP_MMDB=%s is not a file" % (what, data.get("env")))
elif data["sha256"] != pin["mmdb_sha256"]:
problems.append("the %s says the database has sha256 %s, the pin says %s" % (what, data["sha256"], pin["mmdb_sha256"]))
if what == "record of use" and data.get("asked_github"):
problems.append("the core asked GitHub for a database %s time(s) during the run: it went past STEALTHFOX_GEOIP_MMDB" % data["asked_github"])
return problems
def main(argv=None) -> int:
ap = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0])
sub = ap.add_subparsers(dest="cmd", required=True)
b = sub.add_parser("build")
b.add_argument("--pin", default="ci/geoip.json")
b.add_argument("--dest", default=None, help="default: $RUNNER_TEMP/geoip, or ./.geoip")
e = sub.add_parser("evidence")
e.add_argument("--out", default=None)
v = sub.add_parser("verify")
v.add_argument("--pin", default="ci/geoip.json")
v.add_argument("--evidence", required=True)
v.add_argument("--used", default=None)
ns = ap.parse_args(argv)
if ns.cmd == "build":
try:
dest = Path(ns.dest or os.path.join(os.environ.get("RUNNER_TEMP", "."), "geoip" if os.environ.get("RUNNER_TEMP") else ".geoip"))
path = build(load_pin(ns.pin), dest.resolve())
except Refused as exc:
print("ci_lab_geoip: %s" % exc, file=sys.stderr)
return 1
# Where the process of the tests writes what the core did about the database (tests/geoip_used.py, read by `verify`).
used = path.parent / "geoip-used.json"
print("%s=%s" % (ENV, path))
print("GEOIP_USED_OUT=%s" % used)
env_file = os.environ.get("GITHUB_ENV")
if env_file:
with open(env_file, "a", encoding="utf-8") as fh:
fh.write("%s=%s\n" % (ENV, path))
fh.write("GEOIP_USED_OUT=%s\n" % used)
return 0
if ns.cmd == "verify":
try:
problems = verify(load_pin(ns.pin), ns.evidence, ns.used)
except Refused as exc:
print("ci_lab_geoip: %s" % exc, file=sys.stderr)
return 1
for problem in problems:
print("ci_lab_geoip: FAIL: %s" % problem, file=sys.stderr)
print("the leg ran with the pinned GeoIP database" if not problems else "%d problem(s)" % len(problems))
return 1 if problems else 0
data = evidence()
text = json.dumps(data, indent=1)
if ns.out:
Path(ns.out).parent.mkdir(parents=True, exist_ok=True)
Path(ns.out).write_text(text, encoding="utf-8")
print(text)
return 0
if __name__ == "__main__":
sys.exit(main())
+131
View File
@@ -0,0 +1,131 @@
"""The three checks on the REAL GeoIP database: the only place a CI run touches it, and only in the release (publish.yml, job `real-geoip-database`).
The legs of the gates and of the pull requests launch with the database made by scripts/ci_lab_geoip.py (a few networks, the same bytes every run, no
download). What it cannot prove is proved here, once per release, against the database a user gets:
1. THE PRODUCT'S OWN ROAD. With STEALTHFOX_GEOIP_MMDB unset and a cold cache the core downloads the latest database (``ensure_geoip_mmdb``), the file
opens with the reader the core uses (MODE_MMAP) and answers for an address.
2. THE LAB DATABASE AGREES. For the exit of each network of the lab database the real one gives the same country and the same IANA zone: if it does
not, the lab table is stale (the tests ask their truth of the database at test time, so a stale table does not break them; it says the lab no longer
looks like the world).
3. EVERY ZONE IS KNOWN. Each distinct ``location.time_zone`` of the real database is a zone this runner's tz database knows (``ip_to_timezone``
validates with ZoneInfo: a name the database has and the runner has not is a launch that fails for the user).
python scripts/ci_real_geoip_check.py # exit 0: all three hold; 1: one does not (said); 2: wrong use; 3: no database came (the network)
"""
from __future__ import annotations
import os
import sys
import tempfile
from pathlib import Path
from zoneinfo import ZoneInfo
sys.path.insert(0, str(Path(__file__).resolve().parent))
import ci_lab_geoip as lab # noqa: E402
#: The database did not come: not a finding about it (see main).
EXIT_NO_DATABASE = 3
def exit_of(cidr: str) -> str:
"""The address each test declares in a lab network: the .5 of its /24 (tests/_realness_support.py EXITS)."""
base = cidr.split("/")[0].rsplit(".", 1)[0]
return "%s.5" % base
def check_open_and_answer(path: Path) -> list:
import maxminddb
try:
with maxminddb.open_database(str(path), mode=maxminddb.MODE_MMAP) as reader:
record = reader.get("8.8.8.8")
except (OSError, ValueError, getattr(maxminddb, "InvalidDatabaseError", ValueError)) as exc:
return ["the database %s does not open with the reader of the core: %s" % (path, exc)]
code = ((record or {}).get("country") or {}).get("iso_code")
return [] if code else ["the database %s has no country for 8.8.8.8: %r" % (path, record)]
def check_lab_agrees(real: Path, lab_path: Path) -> list:
from invisible_core._geo import GeoTimezoneError, ip_to_country, ip_to_timezone
problems = []
for cidr in sorted(lab.NETWORKS):
ip = exit_of(cidr)
try:
ours = (ip_to_country(ip, lab_path), ip_to_timezone(ip, lab_path))
theirs = (ip_to_country(ip, real), ip_to_timezone(ip, real))
except GeoTimezoneError as exc:
problems.append("%s (%s): %s" % (cidr, ip, exc))
continue
if ours != theirs:
problems.append("%s (%s): the lab database says %s, the real one %s" % (cidr, ip, ours, theirs))
return problems
def zones_of(path: Path) -> set:
import maxminddb
zones = set()
with maxminddb.open_database(str(path), mode=maxminddb.MODE_MMAP_EXT if hasattr(maxminddb, "MODE_MMAP_EXT") else maxminddb.MODE_MMAP) as reader:
for _network, record in reader:
zone = (record.get("location") or {}).get("time_zone") if isinstance(record, dict) else None
if zone:
zones.add(zone)
return zones
def check_zones(path: Path) -> list:
problems = []
zones = zones_of(path)
if not zones:
return ["the database %s has no time_zone at all" % path]
for zone in sorted(zones):
try:
ZoneInfo(zone)
except Exception as exc: # noqa: BLE001 - ZoneInfoNotFoundError, ValueError, OSError: all the same finding
problems.append("the zone %r of the database is not known to the tz database of this runner: %s" % (zone, exc))
print("%d distinct zones in %s" % (len(zones), path))
return problems
def product_download(cache: Path) -> Path:
"""The core's own road: no variable, a cold cache."""
os.environ.pop(lab.ENV, None)
os.environ["INVISIBLE_PLAYWRIGHT_CACHE_DIR"] = str(cache)
from invisible_core.download import ensure_geoip_mmdb
return Path(ensure_geoip_mmdb())
def main(argv=None) -> int:
if len(argv if argv is not None else sys.argv[1:]):
print(__doc__)
return 2
problems = []
with tempfile.TemporaryDirectory() as td:
td = Path(td)
try:
real = product_download(td / "cache")
except Exception as exc: # noqa: BLE001
# Exit 3: the database did not come (the network, GitHub, the download), which says nothing about the database. The release
# waits for a rerun; it is not a defect of the product and not one of the three checks.
print("1. the product's own road: NO DATABASE (%s: %s): exit 3, run it again" % (type(exc).__name__, exc))
return EXIT_NO_DATABASE
print("1. the product's road gave %s: tag %s, %d bytes, sha256 %s" % (real, real.parent.name, real.stat().st_size, lab.sha256_of(real)))
results = []
for label, found in (
("1. it opens with the reader of the core and answers for an address", check_open_and_answer(real)),
("2. the lab database agrees with it on the six exits (country, zone)",
check_lab_agrees(real, lab.build(lab.load_pin(Path(__file__).resolve().parents[1] / "ci" / "geoip.json"), td / "lab"))),
("3. every time_zone of it is known to the tz database of this runner", check_zones(real))):
print("%s: %s" % (label, "ok" if not found else "FAILED (%d)" % len(found)))
problems += found
for p in problems:
print("FAIL: %s" % p)
print("real GeoIP database: %s" % ("all three checks hold" if not problems else "%d problem(s)" % len(problems)))
return 1 if problems else 0
if __name__ == "__main__":
sys.exit(main())
+35
View File
@@ -307,6 +307,37 @@ def _seal_problems(path, result):
return []
def _geoip_problems(path, pin_path, result):
"""A leg launched with the GeoIP database of the pin, or it is red.
``path`` is the evidence the leg wrote with ``scripts/ci_lab_geoip.py evidence``, run in the very environment pytest was started in
(``sudo -E`` included): the value of STEALTHFOX_GEOIP_MMDB, whether it is a file, its sha256. Without the variable the core asks GitHub which
database is the latest on every call, from the python of the test (run 43211837926: a resolver trap counted github.com and api.github.com as
the browser's), and a leg that reaches a site for its data is not a leg of the gate.
"""
try:
evidence = json.loads(Path(path).read_text(encoding="utf-8"))
if not isinstance(evidence, dict):
raise ValueError("not a JSON object")
except (OSError, ValueError) as exc:
result["geoip_sha256"] = "unreadable"
return ["the GeoIP evidence %s cannot be read: %s: the leg did not say which database it ran with" % (path, exc)]
result["geoip_sha256"] = evidence.get("sha256")
if not evidence.get("env"):
return ["the leg launched without STEALTHFOX_GEOIP_MMDB: the core would ask GitHub for its database on every call (the database of "
"the gate is ci/geoip.json, made by scripts/ci_lab_geoip.py)"]
if not evidence.get("exists") or not evidence.get("sha256"):
return ["STEALTHFOX_GEOIP_MMDB=%s is not a file: the leg ran without a database" % evidence.get("env")]
try:
pin = json.loads(Path(pin_path).read_text(encoding="utf-8")) if pin_path else None
expected = pin["mmdb_sha256"]
except (OSError, ValueError, KeyError, TypeError) as exc:
return ["the pin of the GeoIP database %s cannot be read: %s" % (pin_path, exc)]
if evidence["sha256"] != expected:
return ["the leg ran with a GeoIP database of sha256 %s, the pin (%s) says %s" % (evidence["sha256"], pin_path, expected)]
return []
def cmd_judge(ns):
problems = []
result = {"suite": ns.suite, "os": ns.os, "commit": commit_sha(ns.commit), "binary_sha256": sha256_of(ns.binary),
@@ -329,6 +360,8 @@ def cmd_judge(ns):
problems.append("the binary %s does not exist: a result with no hash of the engine is not a result" % ns.binary)
if ns.seal:
problems += _seal_problems(ns.seal, result)
if ns.geoip:
problems += _geoip_problems(ns.geoip, ns.geoip_pin, result)
counts = {"passed": 0, "failed": 0, "skipped": 0, "errors": 0}
cases = []
@@ -476,6 +509,8 @@ def main(argv=None):
j.add_argument("--binary")
j.add_argument("--commit")
j.add_argument("--seal")
j.add_argument("--geoip", help="the evidence of the leg (scripts/ci_lab_geoip.py evidence): a leg launched without the database is red")
j.add_argument("--geoip-pin", help="ci/geoip.json: the sha256 of the database the leg has to have run with (main's, when main has it)")
j.add_argument("--out")
j.add_argument("--main-required")
j.add_argument("--main-has-no-list", action="store_true",
-318
View File
@@ -1,318 +0,0 @@
"""Do the two servers receive the same thing, and answer the same thing?
⛔ THIS IS THE QUESTION THAT DECIDES WHETHER THE NODE DRIVER CAN BE DELETED, and
it is not the same question `judge_both_transports.py` answers. That one runs
tests and reports which arm goes red - a behavioural check, and a coarse one: a
field the client does not happen to read today is missing in complete silence,
and shows up as a bug months later in a code path nobody exercised. This one
compares the WIRE.
**What it compares, and why at this level.**
* **input**: every method the client SENDS, and the set of PARAMETER NAMES it
sends with each. Both servers must accept the same vocabulary. A method
present on one side and absent on the other is a hole; a method present on
both but reached with different fields means the client is being driven
differently, which makes the rest of the comparison meaningless.
* **output**: every object TYPE the server creates, and the set of INITIALIZER
FIELD NAMES for each; plus every EVENT name the server emits, per type. This
is the half that reading `_impl` cannot give you: it tells you which fields
are CONSUMED today, never which are SENT, and the difference is exactly the
set a future code path will want.
⛔ **FIELD NAMES, NOT VALUES.** guids are allocated by whoever allocates them,
ports are ephemeral, versions and build ids differ by construction. Comparing
values would drown the real differences in noise that is not a difference at
all. Where a VALUE matters it belongs in a test, not here.
⛔ **AND IT RUNS THE SAME SESSION TWICE, IN TWO SUBPROCESSES.** The transport is
chosen once, at import time, from the environment: two transports in one process
would mean one of the two arms was not the thing it claims to be.
python scripts/diff_protocol.py <firefox-binary>
python scripts/diff_protocol.py <firefox-binary> --keep (leave the traces)
"""
from __future__ import annotations
import argparse
import json
import os
import pathlib
import subprocess
import sys
import tempfile
ROOT = pathlib.Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT / "src"))
sys.stdout.reconfigure(encoding="utf-8")
#: Fields whose ABSENCE on one side is not a finding, because the two paths
#: legitimately disagree about them. Kept short and each one argued: a long
#: list here is how a comparison stops comparing.
EXPECTED_DIFFERENCES = {
# The driver reports the bundled Playwright's version string; we report the
# engine's. Neither is wrong and no client behaviour depends on the text.
("Playwright", "initializer", "preLaunchedBrowser"),
# ⛔ `previewUpdated` is a REAL gap, listed here because it is argued and
# not because it is small. The driver pushes a new preview string every
# time a handle's value changes, and `_js_handle.py` does listen for it -
# so on this server `repr(handle)` keeps the preview it was born with.
# That is the whole consequence: it reaches error messages and the REPL,
# never a page, never a decision, never a byte on the wire. Implementing it
# would mean re-serialising every handle after every evaluation, which is
# protocol traffic and parent-process work for a string a human reads.
# If it ever stops being cosmetic - a client that BRANCHES on the preview -
# this line is where to start.
("ElementHandle", "event", "previewUpdated"),
("JSHandle", "event", "previewUpdated"),
}
#: A checkout that still carries the Node driver, for the day this one does not.
#: Same contract and same reason as in `judge_both_transports.py`: a worktree,
#: not an installed release, because a published wrapper pins a published core
#: and a sealed engine and cannot drive a locally built binary.
#:
#: git worktree add /tmp/judge <the last commit that carried _driver/>
#: INVPW_DRIVER_TREE=/tmp/judge python scripts/diff_protocol.py <binary>
DRIVER_TREE_ENV = "INVPW_DRIVER_TREE"
def capture(binary: str, transport: str, out: pathlib.Path) -> None:
"""Run the scripted session under one transport, writing its trace."""
env = dict(os.environ)
env["INVPW_TRANSPORT"] = transport
env["INVPW_TRACE_OUT"] = str(out)
tree = os.environ.get(DRIVER_TREE_ENV)
if transport == "driver" and tree:
# ⛔ The driver comes from the older tree; the RECORDER does not. The
# capture script has to be this one, or the two traces are produced by
# two different instruments and every difference between them measures
# the instruments - which is the mistake this whole comparison exists
# to avoid.
src = str(pathlib.Path(tree) / "src")
env["PYTHONPATH"] = os.pathsep.join(
[src] + ([env["PYTHONPATH"]] if env.get("PYTHONPATH") else []))
script = ROOT / "scripts" / "capture_protocol.py"
r = subprocess.run([sys.executable, str(script), binary, "-o", str(out)],
env=env, capture_output=True, text=True)
if r.returncode != 0 or not out.exists():
raise RuntimeError("the %s arm did not produce a trace:\n%s\n%s"
% (transport, r.stdout[-2000:], r.stderr[-2000:]))
def sent_vocabulary(trace: list) -> dict:
"""method -> the set of parameter names ever sent with it."""
out: dict = {}
for entry in trace:
if entry["dir"] != "send":
continue
message = entry["msg"]
method = message.get("method")
if not method:
continue
params = message.get("params") or {}
out.setdefault(method, set()).update(params.keys())
return out
def created_shapes(trace: list) -> dict:
"""type -> the set of initializer field names ever seen for it."""
out: dict = {}
for entry in trace:
if entry["dir"] != "recv":
continue
message = entry["msg"]
if message.get("method") != "__create__":
continue
params = message.get("params") or {}
kind = params.get("type")
if not kind:
continue
out.setdefault(kind, set()).update(
(params.get("initializer") or {}).keys())
return out
def events_by_owner(trace: list, shapes_of_guid: dict) -> dict:
"""type -> the set of event names the server emitted on objects of it."""
out: dict = {}
for entry in trace:
if entry["dir"] != "recv":
continue
message = entry["msg"]
method = message.get("method")
if not method or method.startswith("__"):
continue
kind = shapes_of_guid.get(message.get("guid"), "?")
out.setdefault(kind, set()).add(method)
return out
def parentage(trace: list, types: dict) -> dict:
"""child TYPE -> the set of parent TYPES it was ever created under.
⛔ A FOURTH DIMENSION, ADDED BECAUSE ITS ABSENCE LET A REAL DEFECT
THROUGH. This server created `ElementHandle` as a child of `Page`; the
driver creates it under `Frame`. Types matched, initializer fields matched,
events matched - and every call that reads a timeout off the handle's frame
died with `'Page' object has no attribute '_timeout'`, because
`_element_handle.py` learns its frame from the guid TREE and from nothing
else. Parentage is protocol, not bookkeeping.
"""
out: dict = {}
for entry in trace:
if entry["dir"] != "recv":
continue
message = entry["msg"]
if message.get("method") != "__create__":
continue
params = message.get("params") or {}
kind = params.get("type")
if not kind:
continue
out.setdefault(kind, set()).add(types.get(message.get("guid"), "root"))
return out
def disposed_types(trace: list, types: dict) -> dict:
"""type -> whether an object of it was ever disposed ("yes" or nothing).
⛔ A FIFTH DIMENSION, AND THE FOUR ABOVE ARE BLIND TO IT BY CONSTRUCTION:
`events_by_owner` skips every method starting with `__`, so `__dispose__`
was invisible to this comparison no matter how far the two servers drifted.
It is not bookkeeping either - the client ACTS on it, dropping the object
from its registry - so a server that never disposes anything grows the
client's registry for the life of the browser, and a server that disposes
something the client still holds hands back a dead reference.
It was added on 2026-08-28 to answer a question the PARITY verdict could
not: this server never disposed a closed page, and the count of live
objects grew by one per page (9 at page 0, 508 at page 499). Whether that
is a defect or a difference depends entirely on what the driver does, and
nothing here could see it.
The value is a one-element set rather than a bool so `report` can compare
it like every other dimension.
"""
out: dict = {}
for entry in trace:
if entry["dir"] != "recv":
continue
message = entry["msg"]
if message.get("method") != "__dispose__":
continue
kind = types.get(message.get("guid"))
if kind:
out.setdefault(kind, set()).add("disposed")
return out
def guid_types(trace: list) -> dict:
"""guid -> its type, so an event can be attributed to a KIND of object."""
out: dict = {}
for entry in trace:
if entry["dir"] != "recv":
continue
message = entry["msg"]
if message.get("method") != "__create__":
continue
params = message.get("params") or {}
if params.get("guid"):
out[params["guid"]] = params.get("type")
return out
def report(label: str, ours: dict, theirs: dict, kind: str) -> list:
"""Differences in one dimension, as lines. Empty means parity."""
faults = []
def kept(name, fields):
"""⛔ The argued differences are filtered HERE TOO, and they were not.
A field can be missing two ways: the key exists on both sides and one
set is short, or the key is absent entirely. The first version only
filtered the first, so an event type that appears on the driver and
nowhere on ours stayed red forever no matter what was written about
it - and a gate with a permanent red is a gate people stop reading."""
return sorted(f for f in fields
if (name, kind, f) not in EXPECTED_DIFFERENCES)
for name in sorted(set(theirs) - set(ours)):
rest = kept(name, theirs[name])
if rest:
faults.append("%s %r reaches the DRIVER and not us: %s"
% (label, name, rest))
for name in sorted(set(ours) - set(theirs)):
rest = kept(name, ours[name])
if rest:
faults.append("%s %r reaches US and not the driver: %s"
% (label, name, rest))
for name in sorted(set(ours) & set(theirs)):
missing = theirs[name] - ours[name]
extra = ours[name] - theirs[name]
missing = {f for f in missing
if (name, kind, f) not in EXPECTED_DIFFERENCES}
extra = {f for f in extra
if (name, kind, f) not in EXPECTED_DIFFERENCES}
if missing:
faults.append("%s %r: the driver carries %s and we do not"
% (label, name, sorted(missing)))
if extra:
faults.append("%s %r: we carry %s and the driver does not"
% (label, name, sorted(extra)))
return faults
def main() -> int:
p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
p.add_argument("binary")
p.add_argument("--keep", action="store_true",
help="leave the two traces on disk for inspection")
a = p.parse_args()
work = pathlib.Path(tempfile.mkdtemp(prefix="protocol_diff_"))
driver_trace = work / "driver.json"
ours_trace = work / "juggler.json"
print("recording the DRIVER arm ...", flush=True)
capture(a.binary, "driver", driver_trace)
print("recording the PYTHON arm ...", flush=True)
capture(a.binary, "juggler", ours_trace)
driver = json.loads(driver_trace.read_text(encoding="utf-8"))
ours = json.loads(ours_trace.read_text(encoding="utf-8"))
print()
print(" driver: %d messages python: %d messages"
% (len(driver), len(ours)))
faults = []
faults += report("method", sent_vocabulary(ours), sent_vocabulary(driver),
"params")
faults += report("object", created_shapes(ours), created_shapes(driver),
"initializer")
faults += report("events on", events_by_owner(ours, guid_types(ours)),
events_by_owner(driver, guid_types(driver)), "event")
faults += report("parent of", parentage(ours, guid_types(ours)),
parentage(driver, guid_types(driver)), "parent")
faults += report("disposal of", disposed_types(ours, guid_types(ours)),
disposed_types(driver, guid_types(driver)), "dispose")
print()
for line in faults:
print(" " + line)
if a.keep or faults:
print()
print(" traces: %s" % work)
if faults:
print("PROTOCOL DIFF: %d difference(s). The Node driver cannot be "
"deleted while any of these stand, or a caller who reaches one "
"gets silence instead of a browser." % len(faults))
return 1
print("PROTOCOL DIFF: PARITY - same methods with the same parameters in, "
"same object types with the same initializer fields, the same "
"events, the same parentage and the same disposals out.")
return 0
if __name__ == "__main__":
sys.exit(main())
+75
View File
@@ -0,0 +1,75 @@
"""Hunt only: the bytes a page reads, one seed, on this machine; and each probe font drawn alone, to tell which one differs.
python scripts/hunt_text_bytes.py <binary> <out.json>
"""
import json
import sys
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "tests"))
import _page_bytes # noqa: E402
from invisible_playwright import InvisiblePlaywright # noqa: E402
LAUNCH = dict(seed=42, headless=True, locale="en-US", timezone="Europe/Rome")
PROBE = (Path(__file__).resolve().parent.parent / "tests" / "page_bytes_probe.js").read_text(encoding="utf-8")
EACH_FONT = r"""async () => {
const FONTS = ["16px sans-serif", "20px serif", "18px monospace", "bold 16px Arial", "italic 15px 'Segoe UI'", "16px 'Times New Roman'",
"16px Calibri", "14px Consolas", "16px Verdana", "16px Tahoma", "17px Georgia", "16px 'Segoe UI Emoji'", "16px 'Microsoft YaHei'",
"16px 'Yu Gothic'", "bold 40px sans-serif", "italic 34px serif", "28px monospace", "bold 44px Arial", "36px 'Times New Roman'", "30px 'Segoe UI'"];
const TEXTS = {latin: "Hamburgefonstiv 0123456789 Ag", cjk: "日本語のテキスト 漢字", emoji: "😀🚀👍🏽", arabic: "مرحبا بالعالم"};
async function digest(data) {
const h = await crypto.subtle.digest("SHA-256", data);
return Array.from(new Uint8Array(h)).slice(0, 8).map((b) => b.toString(16).padStart(2, "0")).join("");
}
const out = [];
for (const f of FONTS) {
for (const [name, t] of Object.entries(TEXTS)) {
const c = document.createElement("canvas"); c.width = 640; c.height = 64;
const g = c.getContext("2d"); g.fillStyle = "#fff"; g.fillRect(0, 0, 640, 64);
g.font = f; g.fillStyle = "#101820"; g.textBaseline = "alphabetic"; g.fillText(t, 4, 44);
const m = g.measureText(t);
const px = g.getImageData(0, 0, 640, 64).data;
let ink = 0; for (let i = 0; i < px.length; i += 4) if (px[i] < 250) ink++;
out.push({font: f, text: name, raster: await digest(px), ink, width: m.width, asc: m.actualBoundingBoxAscent,
desc: m.actualBoundingBoxDescent, fasc: m.fontBoundingBoxAscent, fdesc: m.fontBoundingBoxDescent,
check: document.fonts.check(f)});
}
}
return out;
}"""
class Page(BaseHTTPRequestHandler):
def log_message(self, *a):
pass
def do_GET(self):
body = b"<!doctype html><meta charset=utf-8><title>probe</title><body></body>"
self.send_response(200); self.send_header("Content-Type", "text/html"); self.send_header("Content-Length", str(len(body)))
self.end_headers(); self.wfile.write(body)
def main(binary, out):
server = ThreadingHTTPServer(("127.0.0.1", 0), Page)
threading.Thread(target=server.serve_forever, daemon=True).start()
url = "http://127.0.0.1:%d/" % server.server_address[1]
try:
with InvisiblePlaywright(binary_path=binary, **LAUNCH) as browser:
page = browser.new_page()
page.goto(url, wait_until="load", timeout=60000)
measured = page.evaluate(PROBE)
page.goto(url, wait_until="load", timeout=60000)
each = page.evaluate(EACH_FONT)
finally:
server.shutdown()
entries = {k: _page_bytes.entry_of(k, v) for k, v in measured.items()}
raw_strings = {k: v["s"] for k, v in measured.items() if "s" in v}
Path(out).write_text(json.dumps({"entries": entries, "strings": raw_strings, "each_font": each}, indent=1), encoding="utf-8")
print("HUNT wrote %d keys and %d single-font draws" % (len(entries), len(each)))
if __name__ == "__main__":
main(sys.argv[1], sys.argv[2])
-195
View File
@@ -1,195 +0,0 @@
"""Run the same e2e through BOTH transports and compare, test by test.
⛔ THIS IS THE JUDGEMENT ITEM 8 WAITS FOR. The Node driver and the Python
server answer the same protocol, so the only honest way to know the second one
is correct is to run the same session through both and compare the results
name by name. Deleting the driver before this has run leaves the new path with
nothing to be measured against - a build that agrees with itself.
⛔ AND A DIFFERENCE IS NOT AUTOMATICALLY OURS. In two days this comparison has
already answered in both directions: `go_back` fails identically on both arms,
so it is the engine ([B185]); an unanswered dialog failed only on ours, so it
was ours. The table below keeps them apart instead of counting failures.
python scripts/judge_both_transports.py <firefox-binary>
python scripts/judge_both_transports.py <binary> -k juggler # a subset
⛔ THE MACHINE MUST BE QUIET. Both arms launch real browsers, and this project
has three recorded cases of measuring under load and reading the noise as a
product defect. The script refuses to start if a firefox is already alive.
⛔ AND THE ARMS RUN INTERLEAVED PER FILE, never all-of-A then all-of-B. Machine
load and disk cache drift over minutes; running one arm to completion first
puts every one of its tests in a different window from the other's, which turns
"this arm is worse" and "that minute was worse" into the same measurement.
"""
from __future__ import annotations
import argparse
import pathlib
import re
import subprocess
import sys
ROOT = pathlib.Path(__file__).resolve().parent.parent
#: The files worth running on both. ⛔ NOT the whole suite: most of it never
#: touches a transport, so running it twice would double the time and add no
#: information. These are the ones that drive a browser through the seam.
FILES = [
"tests/test_juggler_transport.py",
"tests/test_hidden_desktop.py",
"tests/test_new_page_defaults.py",
"tests/test_cross_origin_iframe.py",
"tests/test_file_chooser.py",
]
ESITO = re.compile(r"^(tests[^\s:]+)::(\S+)\s+(PASSED|FAILED|ERROR|XFAIL|XPASS|SKIPPED)",
re.M)
def quiet_machine() -> int:
r = subprocess.run(
["powershell", "-NoProfile", "-Command",
"(Get-Process firefox -ErrorAction SilentlyContinue | Measure-Object).Count"],
capture_output=True, text=True)
try:
return int((r.stdout or "0").strip() or 0)
except ValueError:
return -1
#: A checkout that still carries the Node driver, for the day this one does not.
#:
#: ⛔ THIS GATE EXISTS ONLY WHILE THERE ARE TWO ARMS, and the driver is on its
#: way out of the tree. When it goes, the second arm comes from a git worktree
#: at the last commit that carried it:
#:
#: git worktree add /tmp/judge <that commit>
#: INVPW_DRIVER_TREE=/tmp/judge python scripts/judge_both_transports.py <bin>
#:
#: A worktree rather than an installed release, because a published wrapper
#: pins a published core and a sealed engine and therefore cannot drive a
#: locally built binary - which is the only kind worth judging.
DRIVER_TREE_ENV = "INVPW_DRIVER_TREE"
def run_one(transport: str, binary: str, path: str, extra: list) -> dict:
import os
env = dict(os.environ)
env["INVPW_TRANSPORT"] = transport
env["INVPW_BINARY_PATH"] = binary
tree = os.environ.get(DRIVER_TREE_ENV)
if transport == "driver" and tree:
# ⛔ PREPENDED, so the older tree's package wins the import. The TESTS
# still come from this checkout: what is being borrowed is the driver,
# not the suite, and running the old suite would compare two different
# sets of assertions and call it a transport difference.
src = str(pathlib.Path(tree) / "src")
env["PYTHONPATH"] = os.pathsep.join(
[src] + ([env["PYTHONPATH"]] if env.get("PYTHONPATH") else []))
r = subprocess.run(
[sys.executable, "-m", "pytest", path, "-o", "addopts=", "-v",
"-p", "no:cacheprovider"] + extra,
cwd=ROOT, env=env, capture_output=True, text=True, timeout=3600)
return {name: verdict
for _, name, verdict in ESITO.findall(r.stdout + r.stderr)}
def main() -> int:
p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
p.add_argument("binary")
p.add_argument("-k", dest="selection", default=None)
p.add_argument("--allow-busy", action="store_true",
help="run even with a browser already alive. ⛔ The result "
"is then not a measurement, and the report says so.")
a = p.parse_args()
alive = quiet_machine()
if alive and not a.allow_busy:
print("REFUSING: %d firefox processes are already alive. A run under "
"load is not a measurement - this project has three recorded "
"cases of reading that noise as a product defect. Close them, or "
"pass --allow-busy and read the result as indicative." % alive)
return 2
if alive:
print("WARNING: %d firefox alive, the result is INDICATIVE" % alive)
extra = ["-k", a.selection] if a.selection else []
driver, juggler = {}, {}
for path in FILES:
if not (ROOT / path).exists():
print(" (skipped, absent: %s)" % path)
continue
print("running %s ..." % path, flush=True)
# ⛔ Interleaved per file: see the module docstring.
driver.update(run_one("driver", a.binary, path, extra))
juggler.update(run_one("juggler", a.binary, path, extra))
names = sorted(set(driver) | set(juggler))
ok = both_fail = only_ours = only_theirs = not_run = 0
rows = []
for name in names:
d = driver.get(name, "ABSENT")
j = juggler.get(name, "ABSENT")
good = ("PASSED", "XFAIL", "SKIPPED")
# ⛔ A TEST THE OTHER ARM NEVER RAN IS NOT A TEST THE OTHER ARM
# FAILED, and folding the two was making this gate lie in the
# comfortable direction. The driver arm imports an OLD `src/`, so any
# test file naming something added since that commit fails to COLLECT
# there and every test in it comes back ABSENT. Counted as "only the
# driver fails", they printed under "ours is BETTER here" - measured
# 2026-08-28 at 32 of them, essentially all of that kind. The number
# grows on its own as this tree moves, which is the property that
# turns a gate into decoration.
if "ABSENT" in (d, j) and not (d in good and j in good):
not_run += 1
rows.append(("NOT RUN", name, d, j))
elif d in good and j in good:
ok += 1
elif d not in good and j not in good:
both_fail += 1
rows.append(("ENGINE?", name, d, j))
elif d in good:
only_ours += 1
rows.append(("OURS", name, d, j))
else:
only_theirs += 1
rows.append(("DRIVER", name, d, j))
print()
print("=" * 78)
print("%-8s %-46s %-10s %s" % ("verdict", "test", "driver", "juggler"))
print("-" * 78)
for kind, name, d, j in rows:
print("%-8s %-46s %-10s %s" % (kind, name[:46], d, j))
print("-" * 78)
print("both green %d" % ok)
print("BOTH fail -> the ENGINE %d" % both_fail)
print("only OURS fails %d <- the ones that are ours to fix"
% only_ours)
print("only the DRIVER fails %d <- ours is BETTER here, verify why"
% only_theirs)
print("never ran on one arm %d <- NOT a comparison: the old arm "
"could not collect these" % not_run)
if not_run:
print()
print(" WARNING: %d of the rows above were never compared at all. The driver "
"arm's `src/` is a worktree that ages: a test naming anything "
"added since it was cut fails to collect there. When this number "
"approaches the total, this gate has stopped answering its own "
"question and the worktree needs re-cutting." % not_run)
print()
if only_ours:
print("VERDICT: not ready to delete the driver. %d tests pass through "
"it and fail through us." % only_ours)
return 1
print("VERDICT: no test passes on the driver and fails on us.")
if both_fail:
print(" (%d fail on BOTH: engine defects, not a reason to wait)"
% both_fail)
return 0
if __name__ == "__main__":
sys.exit(main())
+1 -1
View File
@@ -7,7 +7,7 @@ against anything of ours: its `conftest.py` imports the real `playwright`
package, so it has only ever measured Microsoft's client.
The plan it serves: replacing the channel between our client and our server
removes the boundary `diff_protocol.py` compares across, so the judgement has to
removes the boundary the old protocol comparison compared across, so the judgement has to
move up a level, from the PROTOCOL to the CONTRACT. This suite is that judge -
but only if we know, before touching anything, which of those 2173 pass TODAY.
A baseline taken afterwards proves nothing: every failure would be arguable.
+6 -6
View File
@@ -52,14 +52,14 @@ did so on evidence rather than on the code looking finished:
regenerating them. `injected.js` (the selector engines, actionability and
`expect` that run in the page), `keylayout.py` (both in `invisible_core.juggler`
since 0.30.0, with their extractors in the core's `scripts/`), and the four rules
`prefs_byte_parity.py` compares our `user.js` writer against - now frozen in
`tests/gates/driver_prefs_rules.json` with the sha of the bundle and of the
exact window they came from.
- ⛔ And the second arm. `judge_both_transports.py` and `diff_protocol.py` exist
only while there are two implementations to compare. To get one back:
the `user.js` writer was compared against (the comparison script and the frozen
rules file were later deleted; they are in git history).
- ⛔ And the second arm. A comparison between the two transports only exists
while there are two implementations to compare, and the scripts that did it
were deleted with the driver arm. To get one back:
git worktree add /tmp/judge <the last commit that carried _driver/>
INVPW_DRIVER_TREE=/tmp/judge python scripts/judge_both_transports.py <bin>
INVPW_DRIVER_TREE=/tmp/judge python scripts/capture_protocol.py <bin>
A worktree rather than an installed release, because a published wrapper pins
a published core and a sealed engine and therefore cannot drive a locally
@@ -0,0 +1,88 @@
"""`expose_binding` / `expose_function`: the script a page runs, and the way a call is read and answered.
THE RULE: THE PAGE SEES `foo` AND NOTHING ELSE. A page can list the names on its window, so a transport left there ("a binding
function", a controller) is the driver's signature. Nothing is left:
* One engine binding PER EXPOSED NAME (`Browser.addBinding` for a context, `Page.addBinding` for a page), under a native name chosen
for the session. The engine puts the native function on the window of every document of the page or context, present and future,
in every process, BEFORE any script of the page, and then runs the script below.
* The script takes the native function off the window at once and keeps it in a closure; defines `foo` (an ordinary function whose
source says nothing of what it is for); and hands the engine, through the native function, the function that answers a call
(the engine keeps it as an object of that context and reports its id: `payload.bindingEnd`).
* A call travels as a JSON string through the native function; the answer is `Runtime.callFunction` on the kept function.
LIMIT, SAID HERE. Arguments and results cross as JSON: `undefined`, functions and `NaN` arrive as `null`, and a `Date` as its ISO
string. A caller who needs one passes it as a string. Workers do not get the function (the engine installs bindings in the frames
of a page, as Playwright's does).
"""
from __future__ import annotations
import functools
import json
def install_script(native: str, name: str) -> str:
"""Run by the engine in each document, after it exports the native function `native` on the window."""
return (
"(() => {"
" const send = globalThis[%(native)s];"
" try { delete globalThis[%(native)s]; } catch (e) {}"
" if (typeof send !== 'function') return;"
" const text = JSON.stringify, waiting = new Map();"
" let last = 0;"
" const ask = (name, args) => new Promise((resolve, reject) => {"
" const id = ++last; waiting.set(id, [resolve, reject]);"
" try { send(text({ name, seq: id, args })); } catch (e) { waiting.delete(id); reject(e); } });"
" const f = { [%(name)s]: function (...args) { return ask(%(name)s, args); } }[%(name)s];"
" Object.defineProperty(globalThis, %(name)s,"
" { value: f, writable: true, configurable: true, enumerable: true });"
" send(function (id, ok, value) {"
" const w = waiting.get(id); if (!w) return; waiting.delete(id);"
" if (ok) w[0](value); else w[1](new Error(value)); });"
" })()") % {"native": json.dumps(native), "name": json.dumps(name)}
def remove_script(native: str, name: str) -> str:
"""The same binding again, as the engine runs the last one it was given for a native name: it takes the native function
off the window and the exposed function with it. A document that exists loses `foo`; one to come never gets it."""
return ("(() => { try { delete globalThis[%s]; } catch (e) {}"
" try { delete globalThis[%s]; } catch (e) {} })()") % (json.dumps(native), json.dumps(name))
#: `Runtime.callFunction` with the kept function as the first argument.
DELIVER = "(end, seq, ok, value) => end(seq, ok, value)"
def read_call(payload) -> tuple:
"""`(name, seq, args)` of a `Page.bindingCalled` payload, or `None` if it is not a call."""
try:
data = json.loads(payload) if isinstance(payload, str) else payload
return str(data["name"]), int(data["seq"]), list(data.get("args") or [])
except (TypeError, ValueError, KeyError):
return None
@functools.lru_cache(maxsize=16)
def engine_supports(engine_dir: str) -> bool:
"""Whether the engine in `engine_dir` has `Page.addBinding` and the binding that hands its end over.
Read from the engine's own files (the schema of its protocol, and its Runtime), so an engine without them is known BEFORE a
function is exposed: there is no fallback to a name on the window, and a clear refusal is the answer. An engine that cannot
be read is treated as one that cannot."""
if not engine_dir:
return False
try:
import os
from invisible_core.juggler._gen_protocol import protocol_source
_label, text = protocol_source(engine_dir)
if text.count("'addBinding'") < 2:
return False
omni = os.path.join(engine_dir, "omni.ja")
if os.path.isfile(omni):
from invisible_core.jar import open_jar
jar = open_jar(omni)
return b"bindingEnd" in jar.read("modules/juggler/content/Runtime.js")
return True
except BaseException:
return False
@@ -0,0 +1,126 @@
"""The one way this package starts a thread from a place that must not wait for it.
`Thread.start` does not return until the new thread is running (`self._started.wait()`), and on Windows under load that wait is
milliseconds long. Two places in the package cannot afford it: the engine connection's reader (an event is measured late by every
millisecond the reader is late) and the user's event loop (`InProcessTransport.connect`: four worker starts held the loop ~200 ms per
launch with four browsers in one process). Both hand the thread to `ThreadStarter`.
"""
from __future__ import annotations
import _thread as _raw_thread
import queue
import threading
from typing import Any, Callable, Optional
class ThreadStarter:
"""The ONE long-lived thread that starts the other threads it is handed.
⛔ NO `Thread.start` ON THE CALLER, AND THAT INCLUDES BUILDING THE STARTER. `start` and `start_built` only queue (a `Thread` that is
only BUILT waits for nothing); this thread starts what is queued. The starter's own thread is begun with `_thread.start_new_thread`
running `Thread.start`: the OS makes a thread and the caller returns at once, and the wait for the starter to run happens on that
raw thread, not on the caller. The starter is still a `threading.Thread` named `invpw-thread-starter` (it is alive a moment after
the constructor returns, not before).
It starts threads and does not run the work itself, on purpose: an adoption waits for the engine as long as the engine takes (a popup
whose destination never answers is waited for without a limit), and a worker that ran it would hold every later adoption behind it,
`new_page()` included. Each piece of work keeps the thread of its own and the name it always had.
"""
#: Every starter built and not yet ended (from the constructor, which returns before its thread runs, to the end of that thread).
#: Without it a starter whose thread has not begun yet is in no `threading.enumerate()` and nobody can count it: the census of
#: tests/_browser_census.py missed the leaked starters on a machine where the raw thread was late to run.
_open: "set" = set()
_open_lock = threading.Lock()
@classmethod
def open_starters(cls) -> list:
with cls._open_lock:
return list(cls._open)
def __init__(self, on_error: Callable[[str], None]) -> None:
with ThreadStarter._open_lock:
ThreadStarter._open.add(self)
self._queue: "queue.SimpleQueue" = queue.SimpleQueue()
self._on_error = on_error
self._stopped = False
self._thread = threading.Thread(target=self._run, daemon=True, name="invpw-thread-starter")
_raw_thread.start_new_thread(self._begin, ())
def _begin(self) -> None:
try:
self._thread.start()
except BaseException as failure:
self._ended()
self._report("%s could not be started: %s" % (self._thread.name, failure))
def _ended(self) -> None:
with ThreadStarter._open_lock:
ThreadStarter._open.discard(self)
def start(self, **thread_arguments: Any) -> None:
"""Called from any thread, the reader's and the loop's included: builds a daemon thread and queues it. Never waits."""
if self._stopped:
return
self._queue.put((threading.Thread(daemon=True, **thread_arguments), None))
def start_built(self, thread: threading.Thread, on_failure: Optional[Callable[[str], None]] = None) -> None:
"""Queue a thread the caller built (its name, its daemon flag, its target). Never waits.
`on_failure(why)` runs on the starter if this thread cannot be started, besides the starter's own report."""
if self._stopped:
return
self._queue.put((thread, on_failure))
def stop(self) -> None:
self._stopped = True
self._queue.put(None)
def _report(self, why: str) -> None:
try:
self._on_error(why)
except Exception:
pass
def _run(self) -> None:
try:
self._loop()
finally:
self._ended()
def _loop(self) -> None:
while True:
item = self._queue.get()
if item is None:
return
thread, on_failure = item
try:
thread.start()
except Exception as failure:
why = "%s could not be started: %s" % (thread.name, failure)
self._report(why)
if on_failure is not None:
try:
on_failure(why)
except Exception:
pass
class ThreadStarterLease:
"""One browser's use of the connection's starter: `start` while the browser's connection lives, nothing after it.
The starter is the SERVER's (one thread per connection, however many browsers it launches, `Server.thread_starter`) and ends with
the server. A browser's connection ends earlier than that: from then on a thread its events ask for must not start, which is
what `stop` on the browser's own starter used to give. The starter is asked for on the first `start`, so a browser that never
needs a thread makes none."""
def __init__(self, get_starter: Callable[[], ThreadStarter]) -> None:
self._get_starter = get_starter
self._stopped = False
def start(self, **thread_arguments: Any) -> None:
if not self._stopped:
self._get_starter().start(**thread_arguments)
def stop(self) -> None:
self._stopped = True
@@ -39,6 +39,7 @@ import time
from typing import Any, Callable, Dict, List, Optional
from . import perimeter, variants
from ._threads import ThreadStarter
# One class for a target that is gone, raised here for a disposed object and
# by the connection for a closed pipe. Defined there, the lower layer.
from invisible_core.juggler.connection import TargetClosedError # noqa: F401 - re-exported on purpose
@@ -274,8 +275,30 @@ class Server:
self._on_shutdown: list = []
#: What `shutdown` runs after every hook. See `after_shutdown`.
self._after_shutdown: list = []
self._starter: Optional[ThreadStarter] = None
self._starter_lock = threading.Lock()
self._is_shut_down = False
#: Why a thread the starter was handed could not be started (the last few).
self.start_errors: list = []
# ── plumbing ────────────────────────────────────────────────────────────
@property
def thread_starter(self) -> ThreadStarter:
"""The ONE thread that starts threads for this connection: the transport's workers and every browser's reader hand theirs to it.
Built on first use, ended by `shutdown`. Served by several clients (`remote._SharedServer`) it is the same one: the server
is the connection's owner there too, and its browser's contexts come and go under it."""
with self._starter_lock:
if self._starter is None:
self._starter = ThreadStarter(self._start_failed)
if self._is_shut_down:
self._starter.stop()
return self._starter
def _start_failed(self, why: str) -> None:
if len(self.start_errors) < 32:
self.start_errors.append(why)
def attach(self, transport: Any) -> None:
self._transport = transport
@@ -436,6 +459,11 @@ class Server:
except Exception:
pass
self._after_shutdown.clear()
with self._starter_lock:
self._is_shut_down = True
starter = self._starter
if starter is not None:
starter.stop()
# ── the entry point ─────────────────────────────────────────────────────
def handle(self, message: Dict) -> Any:
@@ -155,10 +155,15 @@ class MemProbe:
}
def write(self, event: str) -> None:
# The row is stamped (`t` in `sample`) and written under ONE lock: the tick thread and
# the thread that closes a context both come here, and a row stamped before the lock
# can be written after a later one (slow sample, e.g. USS on Windows), which puts the
# file out of time order.
try:
line = json.dumps(self.sample(event))
with self._lock, open(self.path, "a", encoding="utf-8") as out:
out.write(line + "\n")
with self._lock:
line = json.dumps(self.sample(event))
with open(self.path, "a", encoding="utf-8") as out:
out.write(line + "\n")
except Exception:
pass # a probe never takes the server down
@@ -169,13 +169,6 @@ FIXED_AT_BUILD = {
#: Our debt, plainly. Nothing external blocks these: they are not written yet.
#: This set is the honest list of what "100% compatible" does not cover today.
NOT_WIRED_YET = {
"exposeBinding",
# ⛔ `reject` shares its handler with `resolve`, and that is how it stayed
# invisible: the first scan keyed the method table by python name, so the
# second operation routed to `op_binding_reply` overwrote the first. Two
# operations, one handler, one of them unaccounted for.
"reject",
"resolve",
"setExtraHTTPHeaders",
}
@@ -837,7 +837,6 @@ def launch_server(host: str = DEFAULT_HOST, port: int = 0, *,
LocalUtilsDispatcher(server)
browser = server.object(
browser_type.op_launch(params)["browser"]["guid"])
session._bind_process_tree()
class _Reported: # what assert_wire_version reads off a Browser
version = browser.initializer.get("version", "")
File diff suppressed because it is too large. Load diff
+79 -14
View File
@@ -43,6 +43,7 @@ names the guid it creates, and that is the dispatcher's job, not the pool's.
"""
from __future__ import annotations
import _thread as _raw_thread
import asyncio
import os
import queue
@@ -50,6 +51,7 @@ import threading
import traceback
from typing import Any, Dict, Optional
from invisible_core._offloop import off_the_loop
from invisible_playwright._pw._impl._helper import parse_error
from invisible_playwright._pw._impl._transport import Transport
@@ -101,15 +103,33 @@ class InProcessTransport(Transport):
self._stopped = threading.Event()
self._stopped_future: asyncio.Future = loop.create_future()
self._threads: list = []
#: The thread that runs the server's shutdown (see `request_stop`); None until the stop is requested.
self._shutdown_thread: Optional[threading.Thread] = None
#: Set once the raw thread has begun (or failed to begin) the shutdown thread, so the join below knows whether to wait.
self._shutdown_begun = threading.Event()
server.attach(self)
# ── the five methods the seam declares ──────────────────────────────────
async def connect(self) -> None:
for i in range(self.WORKERS):
t = threading.Thread(target=self._work, name="juggler-%d" % i,
daemon=True)
t.start()
self._threads.append(t)
"""⛔ NO `Thread.start` ON THE LOOP, NOT EVEN ONE. `connect` is a coroutine of the caller's event loop, and
`Thread.start` does not return until the new thread is running (`self._started.wait()`): measured with four
browsers in one process under CPU load on Windows, the four starts held the loop ~200 ms per launch (4.4% of the
main thread's wall time), the same wait the engine's reader is spared by the same starter.
The four `Thread` objects are only BUILT here (building waits for nothing), so `request_stop` still knows how many
sentinels the pool needs, and the server's one starter (`Server.thread_starter`, shared with every browser's reader) starts them. Messages sent before a worker runs wait in the queue and are
answered when it does, which is what `send` always relied on."""
self._threads = [
threading.Thread(target=self._work, name="juggler-%d" % i, daemon=True)
for i in range(self.WORKERS)]
server_starter = self._server.thread_starter
for t in self._threads:
server_starter.start_built(t, self._workers_could_not_start)
def _workers_could_not_start(self, why: str) -> None:
"""No worker may ever answer a queued message, so the session cannot go on: end it, the way a transport that lost
its other end ends, instead of leaving every call to wait for a reply that cannot come."""
self.request_stop()
async def run(self) -> None:
"""⛔ Must not return until the transport is stopped: `Connection.run`
@@ -117,6 +137,14 @@ class InProcessTransport(Transport):
await self._stopped_future
def request_stop(self) -> None:
"""⛔ THE SERVER'S SHUTDOWN IS NOT RUN BY THE CALLER, and the caller is usually the user's event loop. `server.shutdown()` runs the
hooks of the session (the engine's `conn.close`, which waits for its processes to exit) and then the removal of its directories:
seconds of waiting, and on the loop they stopped every other browser of the process for as long as they took (measured with
four browsers in one process). It runs on a thread of its own, NOT a daemon: a close that the interpreter's exit could cut short
is a browser left half closed, a leak. `wait_until_stopped` is where it is waited for, and off the loop too.
The thread is begun by a raw thread, as the server's starter is: `Thread.start` does not return until the new thread runs, and
that wait on a loaded machine is the loop's own (see `connect`)."""
if self._stopped.is_set():
return
self._stopped.set()
@@ -124,21 +152,58 @@ class InProcessTransport(Transport):
# a flag.
for _ in self._threads:
self._queue.put(None)
def shutdown() -> None:
try:
self._server.shutdown()
except Exception:
pass
finally:
# The stop is settled when the shutdown has ended, as it always was: `run` returns after the hooks.
try:
self._loop.call_soon_threadsafe(self._settle)
except RuntimeError:
pass # the loop is closed: nobody waits for the stop any more
thread = threading.Thread(target=shutdown, name="juggler-shutdown")
self._shutdown_thread = thread
# Not through the server's `ThreadStarter`: `Server.shutdown` stops it, and a starter that has stopped drops what it is handed,
# which here would be the shutdown itself. A raw thread begins this one (the caller returns at once).
try:
self._server.shutdown()
except Exception:
pass
if not self._stopped_future.done():
self._loop.call_soon_threadsafe(self._settle)
_raw_thread.start_new_thread(self._begin, (thread, shutdown))
except RuntimeError:
self._shutdown_begun.set()
shutdown() # no thread can be made: the shutdown still has to happen, as it did before
def _begin(self, thread: threading.Thread, shutdown: Any) -> None:
try:
thread.start()
except BaseException:
self._shutdown_begun.set()
shutdown() # on this raw thread, which is not the loop's
else:
self._shutdown_begun.set()
def _settle(self) -> None:
if not self._stopped_future.done():
self._stopped_future.set_result(None)
def _join_workers(self) -> None:
"""What `wait_until_stopped` waits for besides the stop itself: the workers (and the shutdown thread, which has settled the stop
and is ending). Blocking, so never on the loop."""
for t in self._threads:
# A worker the starter never started (the transport stopped first) has nothing to join.
if t.is_alive():
t.join(timeout=5)
shutdown = self._shutdown_thread
if shutdown is not None:
self._shutdown_begun.wait(5) # the raw thread that begins it may be a moment late
if shutdown.is_alive():
shutdown.join(timeout=5)
async def wait_until_stopped(self) -> None:
await self._stopped_future
for t in self._threads:
t.join(timeout=5)
await off_the_loop(self._join_workers)
def send(self, message: Dict) -> None:
"""⛔ ENQUEUE ONLY. Running the operation here would run it on the
@@ -282,8 +347,8 @@ def make_transport(loop: asyncio.AbstractEventLoop) -> "InProcessTransport":
"only transport - unset %s and it runs. To get the old arm back "
"for a COMPARISON (the only thing it was still for): check out "
"the last commit that carried it into a git worktree and point "
"INVPW_DRIVER_TREE at it. Both `judge_both_transports.py` and "
"`diff_protocol.py` read that variable." % CHOICE_ENV)
"INVPW_DRIVER_TREE at it, which `scripts/capture_protocol.py` "
"reads." % CHOICE_ENV)
from .server import JugglerServer
if (os.environ.get(WIRE_ENV) or "").strip().lower() == "json":
return JsonWireTransport(loop, JugglerServer())
@@ -26,7 +26,7 @@ What each 1.62 addition becomes here:
target into view first, which is `auto`; `none` asks to act on the element
where it is, and honouring it needs an action path that does not scroll,
which does not exist. The action still happens, scrolled.
* `noGlobal` on exposeBinding: moot, `exposeBinding` is refused as a whole.
* `noGlobal` on exposeBinding: not read. The function is always defined on the page's `window`, as `expose_function` documents.
* `type` "webp" on screenshot: REFUSED. The engine captures PNG and JPEG, and
answering a webp request with PNG bytes would hand the caller a file that
is not the format it asked for.
@@ -102,5 +102,5 @@ class Transport(ABC):
#
# ⛔ To get the old arm back for a comparison - which is the only thing it
# was still for - check out the last commit that carried it into a git
# worktree and point `INVPW_DRIVER_TREE` at it. `judge_both_transports.py`
# and `diff_protocol.py` both read that variable.
# worktree and point `INVPW_DRIVER_TREE` at it. `scripts/capture_protocol.py`
# reads that variable.
+61 -28
View File
@@ -20,6 +20,7 @@ the two classes is `await`, and nothing else belongs in this file.
"""
from __future__ import annotations
import asyncio
import os
from ._cursor import (ENGINE_BINARY,
ENGINE_PYTHON,
@@ -436,19 +437,72 @@ class CommonLaunch:
``self._virtual_display`` is the fact ``_build_prefs`` reads to decide
whether the desktop workarounds apply (B172).
"""
pw_headless, vd = self._plan_headless()
if vd is not None:
vd.start()
self._virtual_display = vd
return pw_headless
def _plan_headless(self) -> "tuple[bool, Any]":
"""THE decision, made once for both APIs: ``(pw_headless, display)``.
``pw_headless`` is what Playwright is told; ``display`` is the hidden
surface the caller must START (and then record in
``self._virtual_display``, which `_build_prefs` reads), or None when
none is wanted: headless off, true headless asked for, or a platform
with no display to make. The two callers only decide WHERE the start
runs - inline in the sync client, in a worker in the async one - so
the decision cannot drift between them (B172 was one such drift).
"""
if not self._headless:
return False
return False, None
# Opt-in TRUE headless, shared with the async class. It existed on the
# async API ONLY until 2026-07-27: a documented env var that worked
# depending on which entry point the caller happened to pick, which is
# the same drift that shipped the process-leak fix to half the users.
if true_headless_requested():
return True
vd = make_virtual_display()
if vd is not None:
vd.start()
self._virtual_display = vd
return False
return True, None
return False, make_virtual_display()
async def _resolve_headless_async(self) -> bool:
"""`_resolve_headless` for the async API: the display starts in a worker.
Starting the surface is a blocking call - on Linux it spawns an Xvfb
and waits for it to report ready (~75 ms measured, seconds on a loaded
host) - and `__aenter__` made it on the user's loop, so every other
browser of the process stood still for that long, `headless=True`
or not. The surface is the same and is still created before the prefs
are composed; only the thread changes. The sync API keeps the direct
call: nothing else runs on its thread.
"""
pw_headless, vd = self._plan_headless()
if vd is None:
return pw_headless
started = asyncio.ensure_future(asyncio.to_thread(vd.start))
try:
await asyncio.shield(started)
except asyncio.CancelledError:
# The worker cannot be interrupted and may yet create the surface
# for a launch nobody is waiting for: release it when it ends.
loop = asyncio.get_running_loop()
def release(done: "asyncio.Future") -> None:
if not done.cancelled() and done.exception() is None:
loop.run_in_executor(None, vd.stop)
started.add_done_callback(release)
raise
self._virtual_display = vd
return pw_headless
def _take_display(self) -> Any:
"""THE release, made once for both APIs: the hidden surface this session started, taken out of it (None when there is none).
The counterpart of `_plan_headless`: the two teardowns only decide WHERE the stop runs - inline in the sync client, off the
loop in the async one. Stopping waits for the Xvfb to exit (`Popen.wait`, a loop of sleeps on POSIX), and on the user's loop
that wait held every other browser of the process (e2e Linux, run 43701692047)."""
display, self._virtual_display = self._virtual_display, None
return display
def _default_context_kwargs(self) -> Dict[str, Any]:
# The screen and viewport in CSS pixels, derived once in the core:
@@ -546,24 +600,3 @@ class CommonLaunch:
_enable_cursor_engine(
owner, seed=self.seed, max_seconds=_cursor_max_seconds(self._humanize)
)
def _bind_process_tree(self) -> None:
"""Tie the browser tree to this process's lifetime, at the OS level.
MEASURED before being written, because the first attempt at this fixed
a path that was not broken: an exception out of the `with` block does
NOT leak - __exit__ runs and Playwright cleans up, zero survivors over
an interleaved A/B. The leak is the killed-runner path, where __exit__
never executes at all: launch, kill the runner, and eight processes
were still alive; twelve on the second attempt. Nothing written inside
_teardown can reach that, so the guarantee comes from a Windows job
object that the kernel empties when this process's handle closes,
however this process ends.
Best-effort by construction: a failure here leaves the pre-existing
behaviour rather than breaking a launch that is otherwise fine.
"""
try:
self._lifetime_guard.bind(self._session_token)
except Exception:
pass
+11 -12
View File
@@ -15,6 +15,7 @@ from invisible_core._fpforge import Profile, generate_profile
from invisible_core import SessionLocale, persona_cookies, prepare_session_geo, record_session_seed, resolve_session_seed
from ._engine import assert_wire_version, resolve_executable
from invisible_core import configure_proxy as _configure_proxy_shared
from invisible_core._offloop import off_the_loop
from ._reaper import SessionToken, guard_for
@@ -129,7 +130,7 @@ class InvisiblePlaywright(_session.CommonLaunch):
# the REAL result of _resolve_headless (did it create an
# alternate desktop or not?) must be known BEFORE composing the
# prefs, not after: B172, 2026-08-24.
pw_headless = self._resolve_headless()
pw_headless = await self._resolve_headless_async()
prefs = self._build_prefs()
playwright_proxy = _configure_proxy_shared(self._proxy, prefs)
self._session_token = SessionToken.mint()
@@ -153,7 +154,6 @@ class InvisiblePlaywright(_session.CommonLaunch):
env=env,
**self._default_context_kwargs(),
)
self._bind_process_tree()
self._arm_cursor_engine(self._persistent_context)
return self._persistent_context
self._browser = await self._pw.firefox.launch(
@@ -167,7 +167,6 @@ class InvisiblePlaywright(_session.CommonLaunch):
# See the sync launcher: browser.version comes from the connection
# initializer, costs no round trip, and cannot be spoofed by a pref.
assert_wire_version(self._browser)
self._bind_process_tree()
except BaseException:
await self._teardown()
raise
@@ -351,18 +350,18 @@ class InvisiblePlaywright(_session.CommonLaunch):
if self._pw is not None:
await close(self._pw.stop())
self._pw = None
if self._virtual_display is not None:
# Synchronous, so it cannot be cancelled mid-call the way the
# three awaits above can.
try:
self._virtual_display.stop()
except Exception:
pass
self._virtual_display = None
display = self._take_display()
if display is not None:
# Off the loop like its start (`_resolve_headless_async`): a cancellation stops the waiting, not the stop.
await close(off_the_loop(display.stop))
finally:
if self._session_token:
# ⛔ NOT ON THE LOOP: `reap` waits for the tree of the session to be gone. It runs in a thread of its own
# (`off_the_loop`); a cancellation of this task stops the waiting and not the reaping, which runs to its end.
try:
self._lifetime_guard.reap(self._session_token)
await off_the_loop(self._lifetime_guard.reap, self._session_token)
except asyncio.CancelledError as stop:
cancelled = stop
except Exception:
pass
self._session_token = SessionToken()
+3 -5
View File
@@ -358,7 +358,6 @@ class InvisiblePlaywright(_session.CommonLaunch):
env=env,
**self._persistent_context_kwargs(),
)
self._bind_process_tree()
self._arm_cursor_engine(self._persistent_context)
return self._persistent_context
self._browser = self._pw.firefox.launch(
@@ -374,7 +373,6 @@ class InvisiblePlaywright(_session.CommonLaunch):
# pref can spoof it. Inside the try so a refusal tears the browser
# down instead of leaking the process we just refused.
assert_wire_version(self._browser)
self._bind_process_tree()
except BaseException:
# Python doesn't call __exit__ when __enter__ raises - clean up
# the virtual display + Playwright manually so we don't leak Xvfb
@@ -571,12 +569,12 @@ class InvisiblePlaywright(_session.CommonLaunch):
except Exception:
pass
self._pw = None
if self._virtual_display is not None:
display = self._take_display()
if display is not None:
try:
self._virtual_display.stop()
display.stop()
except Exception:
pass
self._virtual_display = None
# Last, and unconditionally: whatever Playwright's close() did or did
# not manage, nothing carrying this session's token may outlive it. Each
# step above is individually wrapped in `except: pass`, so before this
+114
View File
@@ -0,0 +1,114 @@
"""What a test that expects a page back from the back-forward cache writes down BEFORE it asserts anything, and the wait that leaves it
a page the cache can take.
The test used to read `window.__shown` after `go_back()` and assert on it with nothing else saved: a red said "the page was loaded again" and
nobody could tell whether the engine had announced a restore (and the page was loaded again anyway), or Firefox had refused or evicted the page.
`read_after_go_back` takes, in one place and before any assertion, what tells them apart:
* `__shown`: `[False, True]` is a `pageshow` with `persisted` after the first one; `[False]` alone is a document that was built again;
* the type of the navigation entry and the `readyState` of the document that answers;
* the protocol events since `go_back()`: a restore is announced by the engine with a navigation id that starts with `nav-bfcache-` (and
`Page.frameDocumentRestored`); a document that loaded again comes with a `Page.eventFired` `load` and new execution contexts.
`decide_outcome` writes that down FIRST (stdout, which pytest prints with the failure) and then says which of the two outcomes happened:
the page was `restored` from the cache, or the document was built again (`reloaded`). The second is accepted ONLY where Firefox itself may
not use the cache: a navigation the PARENT starts (`Page.navigate`, `goto`, to the same site or to another) is checked by the parent against the
requests in the old document's loadgroup, and the navigation's own DocumentChannel may still be there when the check runs (measured 2026-11-12,
SHIPBFCache log: `AllowedInBFCache` found "requests in the loadgroup" in 15 of 56 goto sessions, never after the page's own navigation). The test then asserts the worker's contract for the outcome that happened, whole, and says which it was.
"""
from __future__ import annotations
import time
from dataclasses import dataclass, field
from typing import Callable, List
#: The navigation id of a restore: Juggler's FrameTree.announceRestoredDocument gives it `nav-bfcache-<n>`; a document loaded again has the id of its load.
RESTORE_PREFIX = "nav-bfcache-"
#: The protocol events that say what the engine did with the document, and the one parameter that names each.
_SAID = {
"Page.navigationStarted": "navigationId",
"Page.navigationCommitted": "navigationId",
"Page.eventFired": "name",
"Page.frameDocumentRestored": "frameId",
"Runtime.executionContextsCleared": None,
"Runtime.executionContextCreated": None,
"Page.workerCreated": "workerId",
"Page.workerDestroyed": "workerId",
}
@dataclass
class Evidence:
shown: object
navigation_type: object
ready_state: object
events: List[str] = field(default_factory=list)
@property
def restored(self) -> bool:
return self.shown == [False, True]
@property
def engine_announced_a_restore(self) -> bool:
return any(e.startswith("Page.navigationCommitted " + RESTORE_PREFIX) for e in self.events)
def text(self) -> str:
return ("[bfcache] after go_back: __shown=%r navigation entry type=%r readyState=%r; the engine announced a restore: %s; events: %s"
% (self.shown, self.navigation_type, self.ready_state, "yes" if self.engine_announced_a_restore else "no",
self.events))
def why_not(self) -> str:
if self.engine_announced_a_restore:
return ("the engine announced a restore (%s...) but the page did not run a pageshow with persisted after its first one"
% RESTORE_PREFIX)
return ("the page was built again instead of restored from the back-forward cache (no restore was announced by the engine), "
"so this test proves nothing")
def summarize_events(events, start: int) -> List[str]:
"""The events since ``start`` that say what became of the document, one short string each, in order."""
said = []
for method, params in events[start:]:
if method not in _SAID:
continue
key = _SAID[method]
said.append(method if key is None else "%s %s" % (method, params.get(key)) + (
" %s" % params.get("url") if method == "Page.navigationCommitted" else ""))
return said
def read_after_go_back(page, events, start: int) -> Evidence:
"""Everything the test knows right after ``go_back()``, taken before any assertion."""
return Evidence(
shown=page.evaluate("window.__shown"),
navigation_type=page.evaluate("() => { const e = performance.getEntriesByType('navigation')[0]; return e ? e.type : null; }"),
ready_state=page.evaluate("document.readyState"),
events=summarize_events(events, start),
)
def decide_outcome(evidence: Evidence, may_reload: bool, write: Callable[[str], None] = print) -> str:
"""Write the evidence down (always, first), then say what happened: ``"restored"``, or ``"reloaded"`` when the document was built again
and ``may_reload`` (the case where Firefox may refuse the cache); anything else fails, naming why and carrying the evidence. A restore
the engine announced that the page did not see fails even where a reload is accepted: that is a defect of ours, not of the cache."""
outcome = "restored" if evidence.restored else (
"reloaded" if may_reload and not evidence.engine_announced_a_restore else "failed")
write(evidence.text() + " => outcome: " + outcome)
assert outcome != "failed", "%s: %s" % (evidence.why_not(), evidence.text())
return outcome
def wait_cacheable(page, seconds: float = 10.0) -> None:
"""Until every document of the page that records `pageshow` has had it. A document whose `pageshow` has not run is still marked as
loading and Firefox will not cache it (Document::OnPageShow clears the mark): the lab does not leave before that, however slow the
machine is. The worker has started and answered before this: the callers asked it twice."""
def shown() -> bool:
return all(frame.evaluate("(window.__shown || [0]).length >= 1") for frame in page.frames)
end = time.monotonic() + seconds
while time.monotonic() < end:
if shown():
return
time.sleep(0.1)
assert shown(), "a document of the page never ran its pageshow: %r" % [f.url for f in page.frames]
+78
View File
@@ -0,0 +1,78 @@
"""The check that no test module leaves a browser open.
A connection's server owns ONE daemon thread, "invpw-thread-starter" (`Server.thread_starter`, made when the first thread is asked of it), and
stops it only on `shutdown`. A unit test that builds a dispatcher on a server and never shuts the server down leaves that thread alive, and the thread keeps the connection,
the browser and every context alive for the rest of the worker (a gc census of a closed context once found 7 of them, and one file alone
left 635). So the number of live starters, counted when the last test of a module has torn down, must be what it was before the module.
Module level and not per test: a module-scoped browser (the e2e ones) is legitimately open between its tests and closed at the end.
"""
import sys
import time
import pytest
STARTER_NAME = "invpw-thread-starter"
_THREADS_MODULE = "invisible_playwright._juggler._threads"
# `stop` is asynchronous: it queues a None and the thread leaves on its next turn. A moment, not a wait for a leak that will not leave.
_JOIN_SECONDS = 5.0
def starters_alive():
"""The starters built and not ended, counted from their construction: `ThreadStarter` begins its thread without waiting for it, so
one that has not run yet is in no `threading.enumerate()` (a census of live threads missed 2 leaks on a Linux runner).
NO IMPORT HERE. A module that never loaded `_threads` cannot have built a starter, so the answer is empty without importing anything:
the census runs from conftest in every job, including ones that install pytest alone and have no `invisible_core` (the `version`
job failed on `invisible_playwright._pin` when this function imported the package)."""
threads = sys.modules.get(_THREADS_MODULE)
if threads is None:
return []
return threads.ThreadStarter.open_starters()
def wait_until_back_to(before, seconds=_JOIN_SECONDS):
"""The starters still open after `seconds` beyond the `before` that were there already (0 when the module closed everything)."""
deadline = time.monotonic() + seconds
while True:
extra = len(starters_alive()) - before
if extra <= 0 or time.monotonic() >= deadline:
return max(extra, 0)
time.sleep(0.05)
@pytest.fixture(scope="module", autouse=True)
def _a_module_leaves_no_browser_open(request):
before = len(starters_alive())
yield
left = wait_until_back_to(before)
if left:
pytest.fail(
"%s left %d browser(s) open: close their connection (fire its close listeners) or shut the server down, in a "
"finally or a fixture teardown. Each one keeps a thread named %r alive, and with it the connection, the browser "
"and every context, for the rest of the worker." % (request.module.__name__, left, STARTER_NAME),
pytrace=False,
)
_made = []
def closes_with_the_test(connection):
"""Register a fake connection a test builds: when the test ends it is closed the way a real one ends, `announce_closed()`, which fires
its close listeners (a `BrowserDispatcher` registered `_starter.stop` on them). Returns the connection, so it goes inline:
`conn = closes_with_the_test(Engine())`, or from the `__init__` of a fake class so that every instance is covered.
Nothing intercepts the starter: a test that builds a browser on a connection it did not register still leaves the thread open, and the
module check above says so.
"""
_made.append(connection)
return connection
@pytest.fixture(autouse=True)
def _the_connections_a_test_made_are_closed_with_it():
yield
made, _made[:] = list(_made), []
for connection in reversed(made):
connection.announce_closed()
+106
View File
@@ -0,0 +1,106 @@
"""The CPU the engine's processes use, by type of process, read from the processes of this test.
A Firefox browser is a tree: the parent, content processes (`tab`), and, where there are any, a GPU process (`gpu`), a socket process,
a media process (`rdd`) and utility processes. Every one but the parent is started with `-contentproc ... <type>` as the last argument
of its command line, so the type is read from there; no `-contentproc` is the parent.
`CpuSampler` reads the cumulative CPU time (user + kernel) of every engine process below the process that runs the test, every
`period` seconds, from a thread. A process that ends inside the window keeps the last value read before its end (at most one period of
its end is lost). The CPU of a type in a window is the sum, over its processes, of the last value minus the value at the start of the
window (zero for a process born after it).
The process of a test is the root: the browser a test starts is its descendant, and so is nothing else of the engine (an e2e run opens
several browsers at once, in several workers, each in its own process tree).
"""
from __future__ import annotations
import threading
import time
from typing import Dict, List, Tuple
TYPES = ("parent", "tab", "gpu", "socket", "rdd", "utility", "forkserver", "other")
def classify(cmdline: List[str]) -> str:
"""parent = no `-contentproc`; otherwise the last argument (tab, gpu, socket, rdd, utility, forkserver), `other` for any other."""
if "-contentproc" not in cmdline:
return "parent"
last = str(cmdline[-1]).strip('"').lower() if cmdline else "?"
return last if last in TYPES else "other"
def delta_by_type(start: Dict[int, Tuple[str, float]], last: Dict[int, Tuple[str, float]]) -> Dict[str, float]:
"""CPU seconds per type over a window: `start` and `last` map pid -> (type, cumulative CPU seconds)."""
out = {t: 0.0 for t in TYPES}
for pid, (kind, cpu) in last.items():
out[kind] = out.get(kind, 0.0) + max(0.0, cpu - start.get(pid, (kind, 0.0))[1])
return out
def is_engine(proc) -> bool:
"""True when the process runs the firefox executable (its file name, whatever name the process gave itself)."""
import psutil
try:
exe = proc.exe()
except (psutil.Error, OSError):
exe = ""
# Either separator: the file name of the executable, whichever system wrote the path.
return (exe or proc.name()).replace("\\", "/").rsplit("/", 1)[-1].lower().startswith("firefox")
def engine_processes(root_pid: int) -> Dict[int, Tuple[str, float]]:
"""pid -> (type, cumulative CPU seconds) of every process of the engine below `root_pid`, now.
⛔ AN ENGINE PROCESS IS KNOWN BY ITS EXECUTABLE, NOT BY ITS NAME. On Linux a child names itself after its role ("Web Content",
"Isolated Web Co", "forkserver", "Socket Process", read from /proc/<pid>/comm) while its executable stays the firefox binary, so a
filter on the name kept the parent alone and the content processes were never counted (e2e Linux, run 43701692047). On Windows the
name and the executable are the same file."""
import psutil
out: Dict[int, Tuple[str, float]] = {}
try:
below = psutil.Process(root_pid).children(recursive=True)
except psutil.Error:
return out
for proc in below:
try:
if not is_engine(proc):
continue
times = proc.cpu_times()
out[proc.pid] = (classify(proc.cmdline()), times.user + times.system)
except psutil.Error:
continue
return out
class CpuSampler:
def __init__(self, root_pid: int, period: float = 0.25) -> None:
self.root_pid = root_pid
self.period = period
self.last: Dict[int, Tuple[str, float]] = {}
self.start: Dict[int, Tuple[str, float]] = {}
self._halt = threading.Event()
self._thread = threading.Thread(target=self._run, name="cpu-sampler", daemon=True)
def _take(self) -> None:
self.last.update(engine_processes(self.root_pid))
def _run(self) -> None:
while not self._halt.is_set():
self._take()
self._halt.wait(self.period)
def begin(self) -> None:
"""Mark the start of the window (what every process has used until now is not counted) and start sampling."""
self._take()
self.start = dict(self.last)
self._thread.start()
def end(self) -> Dict[str, float]:
"""Stop, take one more sample, and return the CPU seconds of the window by type."""
self._halt.set()
self._thread.join(timeout=10)
time.sleep(0.3)
self._take()
return delta_by_type(self.start, self.last)
+19
View File
@@ -265,6 +265,12 @@ class FakeDoh:
self._closed = False
threading.Thread(target=self._accept, daemon=True).start()
def use_certificate(self, certificate: Path, key: Path) -> None:
"""Serve this certificate from now on (new connections): a test whose session must TRUST the DoH by its profile, not through
``ignore_https_errors`` (which would also switch off the check the test is about), has a CA of its own sign it."""
self._context.load_cert_chain(str(certificate), str(key))
self.certificate_path, self._key_path = Path(certificate), Path(key)
# --- what a test reads ------------------------------------------------------------------------------------
def queries_for(self, name: str, qtype: Optional[int] = None) -> List[DohQuery]:
name = name.lower().rstrip(".")
@@ -280,6 +286,19 @@ class FakeDoh:
with self._lock:
return [a for a in self.answers if a.name == name and (qtype is None or a.qtype == qtype)]
def certificate_refusals(self) -> List[Tuple[str, str]]:
"""The failed handshakes in which the client REFUSED the certificate: a TLS alert (unknown CA, bad certificate...).
Not every failed handshake is one. A client that drops a connection before the handshake ends (a speculative or a
duplicate DoH connection the browser abandons) fails it too, and says nothing about the certificate: on Windows as
ConnectionAbortedError [WinError 10053], elsewhere as a reset or an end of file. Only a refusal means that a lookup
of a context without the certificate exception reached the DoH. Windows census of 12/11 (run 43333574229): a
ConnectionAbortedError through the gateway of a context that HAS the exception was read as such a lookup.
"""
with self._lock:
return [(via, error) for via, error in self.tls_failures
if "ALERT" in error.upper() or "CERTIFICATE" in error.upper()]
def seen_names(self) -> List[str]:
with self._lock:
return sorted({q.name for q in self.queries})
+162
View File
@@ -0,0 +1,162 @@
"""The sink of "nothing of a context leaves but through its proxy": what a test reads to know that a request went AROUND the proxy (no pytest in here).
A context with a proxy and a session with none: the default context is then the machine's own network, so "everything that leaves" cannot be
judged (the browser's own background resolves and connects there, and may). What a test judges is what ITS probe made the browser do: every
name of a probe carries a nonce (``fetch-name-3fa91c.test``) and every address a probe uses is the one of a WITNESS no proxy of the test
forwards to (the gateways refuse a CONNECT past loopback and relay no datagram), so whatever arrives at the witness arrived direct. The sink
has four parts, each of which a test proves is not blind:
* the WITNESS (``_witness.Witness``) at an address of this host: a TCP connection or a datagram that reaches it came from the browser, direct;
* the WATCHER (``_leaks.Watcher``): a connection of a browser process to that address, seen in ``/proc`` or the connection table;
* the NATIVE LOOKUPS of the probe's names: ``native_lookup_names`` is the ONE function a test calls. On Linux and on Windows alike it is the
engine's own log (``nsHostResolver.cpp`` writes ``DNS resolve task - Calling getaddrinfo for host [<name>]`` before every native lookup; on
Windows that is the call into the system resolver too) and, where the resolver trap runs (Linux, root), the trap's questions. The lines are
in the PARENT process's file (``moz--main.<pid>.log.moz_log``); the child files are empty, under the sandbox of both systems (measured on a
runner of each, run 43574494194). A log that holds no resolver start is blind and ``native_lookup_names`` raises ``BlindSink``: it never
answers "nothing" for a sink that cannot see;
* the LOOKUPS IN USER CONTEXT 0: the same log says in which context each name was asked (``Resolving host [<name>]<^userContextId=N>``): a
probe name asked with no ``userContextId`` is a lookup that lost the context of its page, whichever road it then took.
The log is the engine's, not a hook of the test: ``MOZ_LOG=sync,nsHostResolver:5`` and ``MOZ_LOG_FILE=<dir>/moz-%PID.log`` give one file per
process (``moz-<pid>.log`` and ``moz-<pid>.log.child-<n>``), as ``test_the_hosts_file_of_the_host_is_never_read_e2e.py`` reads it.
"""
from __future__ import annotations
import glob
import os
import re
import secrets
import sys
from typing import Callable, Dict, Iterable, List, Optional, Sequence
MOZ_LOG = "sync,nsHostResolver:5"
LOG_FILE_NAME = "moz-%PID.log"
_NATIVE = re.compile(r"Calling getaddrinfo for host \[([^\]]+)\]")
_RESOLVING = re.compile(r"Resolving host \[([^\]]+)\]<([^>]*)>")
_STARTED = "nsHostResolver::Init"
def new_nonce() -> str:
"""Six hex digits: unique in a run, and a legal label."""
return secrets.token_hex(3)
def log_files(directory) -> List[str]:
return sorted(glob.glob(os.path.join(str(directory), "moz-*.log*")))
def _lines(directory) -> Iterable[str]:
for path in log_files(directory):
with open(path, "rb") as handle:
for raw in handle:
yield raw.decode("utf-8", "replace")
def engine_log_native_lookups(directory, nonce: Optional[str] = None) -> List[str]:
"""The names the engine looked up with the machine's resolver (``getaddrinfo``), in the order it did, only those with ``nonce`` when given."""
out = []
for line in _lines(directory):
found = _NATIVE.search(line)
if found and (nonce is None or nonce in found.group(1)):
out.append(found.group(1))
return out
def engine_log_context_zero_lookups(directory, nonce: Optional[str] = None) -> List[str]:
"""The names asked of the resolver in a request with NO user context (user context 0: the suffix has no ``userContextId``)."""
out = []
for line in _lines(directory):
found = _RESOLVING.search(line)
if found and "userContextId" not in found.group(2) and (nonce is None or nonce in found.group(1)):
out.append(found.group(1))
return out
def engine_log_is_alive(directory) -> bool:
"""The control of the log sink: some process logged the start of its resolver. A log with no such line says nothing."""
return any(_STARTED in line for line in _lines(directory))
class BlindSink(RuntimeError):
"""The engine's log cannot say anything: no file, or no process logged the start of its resolver."""
def native_lookup_names(directory, nonce: str, trap=None, platform: Optional[str] = None) -> List[str]:
"""Every name with ``nonce`` that the machine's resolver was asked for by the browser: the ONE function every test calls, on every system.
The engine's log on Linux and on Windows; plus ``trap`` (a ``_leaks.ResolverTrap``, Linux and root) when given. Raises ``BlindSink`` when
the log is empty or holds no resolver start. ``platform`` is for the unit test of this function."""
platform = platform or sys.platform
if not log_files(directory):
raise BlindSink("the engine wrote no log in %s: the native-lookup sink is blind" % directory)
if not engine_log_is_alive(directory):
raise BlindSink("no process of the browser logged the start of its resolver (%r) in %s: the native-lookup sink is blind" % (_STARTED, directory))
names = set(engine_log_native_lookups(directory, nonce))
if trap is not None and platform.startswith("linux"):
names |= {n for n in trap.names() if nonce in n}
return sorted(names)
class EgressSink:
"""What a probe of one case left behind, and the verdicts the test makes of it.
``witness`` is the ``_witness.Witness`` of the case, ``watcher`` the ``_leaks.Watcher`` (stopped), ``directory`` the folder of the engine's
log, ``nonce`` the one of the probe's names, ``trap`` the resolver trap or None."""
def __init__(self, witness, watcher, directory, nonce: str, trap=None, native: Callable[..., List[str]] = native_lookup_names):
self.witness, self.watcher, self.directory, self.nonce, self.trap = witness, watcher, directory, nonce, trap
self._native = native
def arrivals(self) -> Dict[str, list]:
"""Everything the witness heard: nothing is forwarded to it by any proxy of the tests, so each one is a send around the proxy."""
return self.witness.heard()
def direct_connections(self) -> list:
return [c for c in self.watcher.direct if c.remote.rsplit(":", 1)[0] == self.witness.address]
def native_lookups(self) -> List[str]:
return self._native(self.directory, self.nonce, self.trap)
def context_zero_lookups(self) -> List[str]:
return engine_log_context_zero_lookups(self.directory, self.nonce)
def blind_problems(self) -> List[str]:
"""The reasons this sink cannot be trusted: a green over a sink that sees nothing proves nothing."""
out = []
if not self.watcher.watched_pids:
out.append("the watcher never saw a browser process (it saw: %s)" % self.watcher.process_names)
if not log_files(self.directory):
out.append("the engine wrote no log in %s: the native-lookup sink is blind (MOZ_LOG / MOZ_LOG_FILE did not reach it)" % self.directory)
elif not engine_log_is_alive(self.directory):
out.append("no process of the browser logged the start of its resolver (%r): the native-lookup sink is blind" % _STARTED)
return out
def leak_problems(self) -> List[str]:
"""The sentences of every leak the sink saw, empty when the probe stayed home."""
out = []
heard = self.arrivals()
if heard["tcp"] or heard["udp"]:
out.append("the witness at %s was reached direct: %d TCP connection(s) from %s, %d datagram(s) from %s"
% (self.witness.address, len(heard["tcp"]), sorted({h[0] for h in heard["tcp"]}), len(heard["udp"]),
sorted({h[0] for h in heard["udp"]})))
seen = self.direct_connections()
if seen:
out.append("the watcher saw the browser connect to %s without the proxy: %s"
% (self.witness.address, "; ".join("%s %s -> %s %s" % (c.process, c.protocol, c.remote, c.status) for c in seen)))
try:
native = self.native_lookups()
except BlindSink as exc:
out.append(str(exc))
native = []
if native:
out.append("the machine's resolver was asked for %s (a lookup of a proxied context took the native road)" % native)
zero = self.context_zero_lookups()
if zero:
out.append("%s was looked up in user context 0, not in the context of its page" % sorted(set(zero)))
return out
def named_connects(gateway_connects: Sequence, is_address: Callable[[str], bool], allowed_names: Sequence[str] = ()) -> List[tuple]:
"""The CONNECTs of a SOCKS5 gateway that carry a NAME (the browser must resolve and connect by address), except ``allowed_names``."""
return [(h, p) for h, p in gateway_connects if not is_address(h) and h not in allowed_names]
+243
View File
@@ -0,0 +1,243 @@
"""What the Fission frame tests (`test_fission_frames_*_e2e.py`) share: three sites, and a proof of a process.
Three SITES on one machine, told apart by HOST and never by port (`127.0.0.1:1` and `127.0.0.1:2` are one site,
so a frame served from the other port stays in the process of its page):
A 127.0.0.1 the top page, and the A inside A > B > A > C
B localhost the iframe of another site
C 127.0.0.2 the third site
The wrapper runs Fission the way retail Firefox does (strategy 1, one content process per site), so with no pref a
frame of B inside a page of A runs in another process.
`assert_other_process` is how a test proves that, from inside the pages and with no help from the driver: the
frame spins for 600 ms and the observer frame times a 10 ms timer, which stalls only when the two share a process.
A test file calls it at least once, so the suite cannot silently turn into a same-process suite.
"""
from __future__ import annotations
import json
import struct
import threading
import zlib
import time
from http.server import BaseHTTPRequestHandler
from urllib.parse import parse_qs, urlsplit
from _servers import LocalServer
HOSTS = {"A": "127.0.0.1", "B": "localhost", "C": "127.0.0.2"}
#: How long the frame keeps its main thread busy, and the longest gap of the observer's timer that still means
#: "another process" (a process shared with the frame is stalled for about the whole spin).
SPIN_MS = 600
OWN_PROCESS_GAP_MS = 300
HTML = "text/html; charset=utf-8"
class Sites:
"""Three local servers, one per site, and the routes they serve.
``route(site, path, body, ...)`` registers a page; ``body`` is a string or bytes, or a function of the request
that returns the same (the request is the handler: ``.headers``, ``.query``). ``requests`` lists what arrived,
as dicts with ``site``, ``path``, ``query``, ``method`` and ``headers``.
"""
def __init__(self):
self._routes = {}
self.requests = []
self.servers = {}
self.origin = {}
sites = self
class Handler(BaseHTTPRequestHandler):
timeout = 10
def log_message(self, *args):
pass
def _answer(self):
url = urlsplit(self.path)
self.query = parse_qs(url.query)
site = self.server.site
length = int(self.headers.get("Content-Length") or 0)
self.body = self.rfile.read(length) if length else b""
sites.requests.append({"site": site, "path": url.path, "query": self.query,
"method": self.command, "headers": dict(self.headers)})
spec = sites._routes.get((site, url.path))
if spec is None:
self.send_response(404)
self.send_header("Content-Length", "0")
self.end_headers()
return
body = spec["body"](self) if callable(spec["body"]) else spec["body"]
if isinstance(body, str):
body = body.encode("utf-8")
if spec["delay"]:
time.sleep(spec["delay"])
try:
self.send_response(spec["status"])
self.send_header("Content-Type", spec["ctype"])
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-store")
for name, value in spec["headers"]:
self.send_header(name, value)
self.end_headers()
self.wfile.write(body)
except OSError:
pass
do_GET = _answer
do_POST = _answer
self._handler = Handler
def __enter__(self):
for site, host in HOSTS.items():
server = LocalServer((host if host != "localhost" else "127.0.0.1", 0), self._handler)
server.site = site
threading.Thread(target=server.serve_forever, daemon=True).start()
self.servers[site] = server
self.origin[site] = "http://%s:%d" % (host, server.server_address[1])
return self
def __exit__(self, *exc):
for server in self.servers.values():
server.shutdown()
server.server_close()
def url(self, site, path=""):
return self.origin[site] + path
def route(self, site, path, body, ctype=HTML, status=200, headers=(), delay=0):
self._routes[(site, path)] = {"body": body, "ctype": ctype, "status": status,
"headers": list(headers), "delay": delay}
def seen(self, site, path):
return [r for r in self.requests if r["site"] == site and r["path"] == path]
def wait_for(page, predicate, seconds=10.0):
"""Until ``predicate()``, with the client's events being read (the sync client takes the engine's events only
inside its own calls, so a plain sleep would never see a frame arrive)."""
end = time.monotonic() + seconds
while time.monotonic() < end:
if predicate():
return True
page.wait_for_timeout(100)
return bool(predicate())
def frame_of(page, origin, path=None):
"""The frame of ``page`` whose url starts with ``origin`` (and ``path``), or None."""
prefix = origin + (path or "")
for frame in page.frames:
if frame.url.startswith(prefix):
return frame
return None
def wait_frame(page, origin, path=None, seconds=10.0):
wait_for(page, lambda: frame_of(page, origin, path) is not None, seconds)
frame = frame_of(page, origin, path)
assert frame is not None, "no frame at %s%s; page.frames = %r" % (origin, path or "", [f.url for f in page.frames])
return frame
def launch(binary, humanize=False, **kwargs):
"""The browser of every test here: seed 42, headless, no humanizing unless asked."""
from invisible_playwright import InvisiblePlaywright
return InvisiblePlaywright(seed=42, binary_path=binary, humanize=humanize, headless=True, **kwargs)
def new_page(browser, **context_kwargs):
context = browser.new_context(**context_kwargs)
page = context.new_page()
page.set_default_timeout(8000)
page.set_default_navigation_timeout(30000)
return context, page
def longest_timer_gap(observer, frame, spin_ms=SPIN_MS):
"""Make ``frame`` spin for ``spin_ms`` and return the longest gap (ms) between two ticks of a 10 ms timer that
``observer`` (a frame) runs meanwhile."""
observer.evaluate("""() => {
window.__gap = 0;
let last = performance.now();
window.__tick = setInterval(() => {
const now = performance.now();
window.__gap = Math.max(window.__gap, now - last);
last = now;
}, 10);
}""")
frame.evaluate("""(ms) => { setTimeout(() => {
const end = performance.now() + ms;
while (performance.now() < end) { /* spin */ }
}, 50); }""", spin_ms)
observer.page.wait_for_timeout(spin_ms + 800)
return observer.evaluate("() => { clearInterval(window.__tick); return window.__gap; }")
def assert_other_process(observer, frame):
"""``frame`` runs in a process of its own, not the one of ``observer``: a spin in it does not stall the timer."""
gap = longest_timer_gap(observer, frame)
assert gap < OWN_PROCESS_GAP_MS, (
"the frame at %s shares the process of the observer at %s: a %d ms spin stalled the observer's timer for "
"%.0f ms" % (frame.url, observer.url, SPIN_MS, gap))
def js(value):
"""``value`` as a JavaScript literal, for a page built from a template."""
return json.dumps(value)
def decode_png(data):
"""``(width, height, pixel)`` of a PNG made by the browser (8 bits, no interlace); ``pixel(x, y)`` is the
``(r, g, b)`` tuple. Enough to ask what colour a screenshot has at a point, with no imaging library."""
assert data[:8] == bytes([137, 80, 78, 71, 13, 10, 26, 10]), "not a PNG"
pos, idat, width = 8, b"", None
while pos < len(data):
(length,) = struct.unpack(">I", data[pos:pos + 4])
kind, body = data[pos + 4:pos + 8], data[pos + 8:pos + 8 + length]
if kind == b"IHDR":
width, height, depth, color, _, _, interlace = struct.unpack(">IIBBBBB", body)
assert depth == 8 and interlace == 0 and color in (2, 6), (depth, color, interlace)
channels = 3 if color == 2 else 4
elif kind == b"IDAT":
idat += body
pos += 12 + length
raw = zlib.decompress(idat)
stride = width * channels
rows, previous = [], bytearray(stride)
for y in range(height):
start = y * (stride + 1)
filter_type, line = raw[start], bytearray(raw[start + 1:start + 1 + stride])
for i in range(stride):
left = line[i - channels] if i >= channels else 0
up = previous[i]
upleft = previous[i - channels] if i >= channels else 0
if filter_type == 1:
line[i] = (line[i] + left) & 255
elif filter_type == 2:
line[i] = (line[i] + up) & 255
elif filter_type == 3:
line[i] = (line[i] + (left + up) // 2) & 255
elif filter_type == 4:
estimate = left + up - upleft
pa, pb, pc = abs(estimate - left), abs(estimate - up), abs(estimate - upleft)
line[i] = (line[i] + (left if pa <= pb and pa <= pc else up if pb <= pc else upleft)) & 255
rows.append(line)
previous = line
def pixel(x, y):
offset = x * channels
return tuple(rows[y][offset:offset + 3])
return width, height, pixel
def near(color, expected, tolerance=3):
"""``color`` is ``expected`` give or take ``tolerance`` per channel."""
return all(abs(a - b) <= tolerance for a, b in zip(color, expected))
+27 -38
View File
@@ -14,15 +14,17 @@ from __future__ import annotations
import asyncio
import datetime
import ipaddress
import random
import socket
import socketserver
import ssl
import sys
import tempfile
import threading
from pathlib import Path
from typing import List, Tuple
from _ports import bind_tcp_and_probe_udp
def _certificate(address: str, directory: Path):
from cryptography import x509
@@ -48,44 +50,19 @@ def _certificate(address: str, directory: Path):
#: The one document every path answers, over TCP and over QUIC.
PAGE = b"<!doctype html><meta charset=utf-8><title>h3</title><p>ok</p>"
# How many port numbers are tried, and where the ones after the system's own pick are drawn from: the same as the witness's.
from _witness import DRAW_FROM as _WITNESS_DRAW_FROM, TRIES as _WITNESS_TRIES # noqa: E402
class _TcpServer(socketserver.ThreadingTCPServer):
allow_reuse_address = True
# On Windows SO_REUSEADDR is "share the port": with a number the picker drew (tests/_ports.py) it would bind over a listener that is there.
allow_reuse_address = sys.platform != "win32"
daemon_threads = True
def _tcp_server_on_a_port_udp_binds(address: str):
"""A TCP server on a port number that UDP can bind too, as ``(server, port)``.
The first try is the system's own pick (port 0); the others are drawn at random below the dynamic range. Windows hands out
ephemeral TCP ports in sequence and keeps excluded ranges of a hundred ports for UDP inside the same zone, so asking the
system again lands in the same refused range again and again (run 43230437094, ``wrapper.e2e.web`` on Windows: fifty
consecutive picks refused, three tests red; the witness had the same defect and the same remedy,
``test_the_witness_picks_a_port_both_sockets_bind.py``)."""
draw = random.Random()
refusals: List[str] = []
for attempt in range(_WITNESS_TRIES):
wanted = 0 if attempt == 0 else draw.randint(*_WITNESS_DRAW_FROM)
try:
tcp = _TcpServer((address, wanted), _TcpHandler)
except OSError as exc:
refusals.append("%s: %s" % (wanted or "system pick", exc))
continue
port = tcp.server_address[1]
probe = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
probe.bind((address, port))
return tcp, port
except OSError as exc:
refusals.append("%s: %s" % (port, exc))
tcp.server_close()
finally:
probe.close()
raise RuntimeError("no port free for both TCP and UDP on %s after %d tries; the last refusals: %s"
% (address, _WITNESS_TRIES, "; ".join(refusals[-3:])))
"""A TCP server on a port number that UDP can bind too, as ``(server, port)``: the one picker of the harness (tests/_ports.py), which the
witness and the resolver trap walk the same sequence of. The first try is the system's own pick (port 0); the others are drawn at random
below the dynamic range, because Windows hands out ephemeral TCP ports in sequence and keeps excluded ranges of a hundred ports for UDP
inside the same zone (run 43230437094, ``wrapper.e2e.web`` on Windows: fifty consecutive picks refused, three tests red). Every refusal is
kept with its code and the last three are in the error."""
return bind_tcp_and_probe_udp(address, lambda host, number: _TcpServer((host, number), _TcpHandler), socket_module=socket)
class _TcpHandler(socketserver.BaseRequestHandler):
@@ -235,9 +212,20 @@ class H3Server:
self._quic = self._loop.run_until_complete(
serve(address, port, configuration=configuration, create_protocol=Protocol))
started.set()
self._loop.run_forever()
try:
self._loop.run_forever()
finally:
# ⛔ THE LOOP IS CLOSED HERE, ON ITS OWN THREAD, after the QUIC server. A loop that is only stopped is closed later by
# BaseEventLoop.__del__ on whatever thread the garbage collector runs in, and on Windows the proactor's close then
# waits for the UDP receive still pending on it, for ever: the HTTP/3 e2e hung inside a later test's goto or
# new_page, the test thread in base_events.__del__ -> proactor close -> _poll (Windows hunt of 13/11, run
# 43377799126, 3 runs of 15; PR #486 part 1 twice).
self._quic.close()
self._loop.run_until_complete(asyncio.sleep(0.05))
self._loop.close()
threading.Thread(target=run, daemon=True).start()
self._thread = threading.Thread(target=run, daemon=True)
self._thread.start()
if not started.wait(10):
raise RuntimeError("the QUIC server did not start")
@@ -248,8 +236,9 @@ class H3Server:
def close(self) -> None:
self._tcp.shutdown()
self._tcp.server_close()
self._quic.close()
self._loop.call_soon_threadsafe(self._loop.stop)
if not self._loop.is_closed():
self._loop.call_soon_threadsafe(self._loop.stop)
self._thread.join(10)
self._dir.cleanup()
def __enter__(self) -> "H3Server":
+319
View File
@@ -0,0 +1,319 @@
"""A lab certificate authority the ENGINE trusts, leaves that name an OCSP responder, and the servers that stand behind them (no pytest in here).
Why. A revocation check is asked only for a chain that builds to a trusted root: with an issuer the engine does not trust the handshake fails
first and no OCSP request is ever made, so a page served with ``ignore_https_errors`` (which switches every check off) says nothing about the
road of an OCSP request. The lab therefore makes a CA, puts it in the NSS database of the profile BEFORE the launch, and serves a leaf signed
by it whose Authority Information Access names an OCSP URL (by a NAME, or by an IP).
How the CA gets into the profile. The engine's own ``-xpcshell`` (the same code on every system, no OS store, no root) runs
``x509certdb.addCertFromBase64(pem, "C,,")`` on the profile directory the session is then launched with (``profile_dir=``); first shown on a
runner of each system (run 43574494194): the page loads trusted with no ``ignore_https_errors`` and a listener at the OCSP URL gets
``POST application/ocsp-request``. The prefs the session needs for it are ``OCSP_PREFS``.
The script prints ``JavaScript error: ... uncaught exception: 2147500037`` for its own lines 25 and 26 (and, on Linux, for a line of
``nsAsyncShutdown.sys.mjs``): an observer of ``profile-do-change`` / ``profile-after-change`` throws NS_ERROR_FAILURE in a shell with no application.
It changes nothing: the verdict is the result file the script writes after ``addCertFromBase64`` returned, and the trust read back with
``isCertTrusted``, never the exit code or the text.
"""
from __future__ import annotations
import base64
import datetime
import ipaddress
import json
import os
import ssl
import subprocess
import threading
from pathlib import Path
from typing import Dict, List, NamedTuple, Optional, Sequence, Tuple
from _servers import LocalServer
#: ``security.pki.crlite_mode`` 0 takes CRLite out of the answer (the lab's issuer is in no filter anyway); ``security.OCSP.enabled`` 1 asks;
#: ``require`` false makes a missing answer a soft failure, so the page still loads and the test reads the road, not the page.
OCSP_PREFS = {"security.OCSP.enabled": 1, "security.OCSP.require": False, "security.pki.crlite_mode": 0}
XPCSHELL_JS = r"""
"use strict";
const result = Services.env.get("LAB_RESULT");
const out = { steps: [] };
let done = false;
function finish(ok) {
out.ok = ok;
IOUtils.writeUTF8(result, JSON.stringify(out)).then(() => { done = true; }, e => { dump("write failed " + e + "\n"); done = true; });
}
try {
const profd = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
profd.initWithPath(Services.env.get("LAB_PROFILE"));
const provider = {
getFile(prop, persistent) {
persistent.value = true;
if (prop == "ProfD" || prop == "ProfLD" || prop == "ProfDS" || prop == "UpdRootD") {
return profd.clone();
}
throw Cr.NS_ERROR_FAILURE;
},
QueryInterface: ChromeUtils.generateQI(["nsIDirectoryServiceProvider"]),
};
Services.dirsvc.QueryInterface(Ci.nsIDirectoryService).registerProvider(provider);
out.steps.push("profile provider registered");
Services.obs.notifyObservers(null, "profile-do-change", "xpcshell-do-get-profile");
Services.obs.notifyObservers(null, "profile-after-change", "xpcshell-do-get-profile");
out.steps.push("profile notified");
const certdb = Cc["@mozilla.org/security/x509certdb;1"].getService(Ci.nsIX509CertDB);
out.steps.push("x509certdb service obtained");
const cert = certdb.addCertFromBase64(Services.env.get("LAB_CERT_B64"), "C,,");
out.steps.push("addCertFromBase64 returned");
try { out.subject = cert.subjectName; } catch (e) { out.subject_error = String(e); }
try {
out.trusted_ssl = certdb.isCertTrusted(cert, Ci.nsIX509Cert.CA_CERT, Ci.nsIX509CertDB.TRUSTED_SSL);
} catch (e) { out.trusted_error = String(e); }
finish(true);
} catch (e) {
out.error = String(e);
out.stack = e && e.stack ? String(e.stack) : "";
finish(false);
}
Services.tm.spinEventLoopUntil("lab-ca-xpcshell", () => done);
quit(0);
"""
class LabCa:
"""A CA made for one test: the key stays here, the certificate goes to the profile (``ca_b64``) or nowhere (an untrusted issuer)."""
def __init__(self, directory: Path, label: str = "lab egress CA"):
from cryptography import x509
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.x509.oid import NameOID
self.directory = Path(directory)
self.label = label
now = datetime.datetime.now(datetime.timezone.utc)
self._key = ec.generate_private_key(ec.SECP256R1())
self._name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, label)])
self._cert = (x509.CertificateBuilder().subject_name(self._name).issuer_name(self._name).public_key(self._key.public_key())
.serial_number(x509.random_serial_number()).not_valid_before(now - datetime.timedelta(days=1))
.not_valid_after(now + datetime.timedelta(days=90))
.add_extension(x509.BasicConstraints(ca=True, path_length=0), critical=True)
.add_extension(_usage(digital_signature=True, key_cert_sign=True, crl_sign=True), critical=True)
.add_extension(x509.SubjectKeyIdentifier.from_public_key(self._key.public_key()), critical=False)
.sign(self._key, hashes.SHA256()))
self.ca_pem = self.directory / ("%s.pem" % label.replace(" ", "-"))
self.ca_pem.write_bytes(self._cert.public_bytes(serialization.Encoding.PEM))
#: What ``addCertFromBase64`` takes: the DER, base64.
self.ca_b64 = base64.b64encode(self._cert.public_bytes(serialization.Encoding.DER)).decode("ascii")
def leaf(self, tag: str, dns_names: Sequence[str], ip_addresses: Sequence[str], ocsp_url: Optional[str]) -> Tuple[Path, Path]:
"""A leaf for ``dns_names`` and ``ip_addresses`` whose AIA names ``ocsp_url`` (none: no AIA). Returns (certificate, key), both PEM."""
from cryptography import x509
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.x509.oid import AuthorityInformationAccessOID, ExtendedKeyUsageOID, NameOID
now = datetime.datetime.now(datetime.timezone.utc)
key = ec.generate_private_key(ec.SECP256R1())
san = [x509.DNSName(n) for n in dns_names] + [x509.IPAddress(ipaddress.ip_address(a)) for a in ip_addresses]
builder = (x509.CertificateBuilder()
.subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, (list(dns_names) + list(ip_addresses))[0])]))
.issuer_name(self._name).public_key(key.public_key())
.serial_number(x509.random_serial_number()).not_valid_before(now - datetime.timedelta(days=1))
.not_valid_after(now + datetime.timedelta(days=60))
.add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True)
.add_extension(_usage(digital_signature=True), critical=True)
.add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH]), critical=False)
.add_extension(x509.SubjectAlternativeName(san), critical=False)
.add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(self._key.public_key()), critical=False))
if ocsp_url:
builder = builder.add_extension(
x509.AuthorityInformationAccess([x509.AccessDescription(AuthorityInformationAccessOID.OCSP,
x509.UniformResourceIdentifier(ocsp_url))]), critical=False)
leaf = builder.sign(self._key, hashes.SHA256())
cert_path, key_path = self.directory / ("leaf-%s.pem" % tag), self.directory / ("leaf-%s-key.pem" % tag)
cert_path.write_bytes(leaf.public_bytes(serialization.Encoding.PEM))
key_path.write_bytes(key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption()))
return cert_path, key_path
def _usage(**given):
from cryptography import x509
base = dict(digital_signature=False, content_commitment=False, key_encipherment=False, data_encipherment=False, key_agreement=False,
key_cert_sign=False, crl_sign=False, encipher_only=False, decipher_only=False)
base.update(given)
return x509.KeyUsage(**base)
def aia_ocsp_urls(leaf_pem: Path) -> List[str]:
"""The OCSP URLs a leaf names (for the unit test of the lab and for the message of a failed case)."""
from cryptography import x509
from cryptography.x509.oid import AuthorityInformationAccessOID, ExtensionOID
cert = x509.load_pem_x509_certificate(Path(leaf_pem).read_bytes())
try:
aia = cert.extensions.get_extension_for_oid(ExtensionOID.AUTHORITY_INFORMATION_ACCESS).value
except x509.ExtensionNotFound:
return []
return [d.access_location.value for d in aia if d.access_method == AuthorityInformationAccessOID.OCSP]
class OcspRequest(NamedTuple):
method: str
path: str
content_type: str
length: int
class OcspResponder:
"""What the OCSP URL of a leaf points at: it records every request and answers 503 (a soft failure), so the page still loads.
Bound at ``address`` (an address of this host that no proxy of the tests forwards to): a request that arrives here came from the browser, direct."""
def __init__(self, address: str = "127.0.0.1"):
import http.server
outer = self
self.address = address
self.requests: List[OcspRequest] = []
class Handler(http.server.BaseHTTPRequestHandler):
def _answer(self):
length = int(self.headers.get("Content-Length") or 0)
if length:
self.rfile.read(length)
outer.requests.append(OcspRequest(self.command, self.path[:80], self.headers.get("Content-Type", ""), length))
self.send_response(503)
self.send_header("Content-Length", "0")
self.end_headers()
do_GET = do_POST = _answer # noqa: N815
def log_message(self, *args):
pass
self._server = LocalServer((address, 0), Handler)
self.port = self._server.server_address[1]
threading.Thread(target=self._server.serve_forever, daemon=True).start()
@property
def asked(self) -> List[OcspRequest]:
"""The requests that are OCSP ones (``POST application/ocsp-request``, or a GET of the base64 form)."""
return [r for r in self.requests if r.content_type == "application/ocsp-request" or r.method == "GET"]
def url_by_address(self) -> str:
return "http://%s:%d/" % (self.address, self.port)
def close(self) -> None:
self._server.shutdown()
self._server.server_close()
class TlsPage:
"""A page over TLS at ``address`` with the given leaf. The handshake is made in the thread of the connection, not in the accept loop."""
def __init__(self, leaf: Path, key: Path, body: str, address: str = "127.0.0.1"):
import http.server
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain(str(leaf), str(key))
self.handshakes: List[str] = []
self.body = body
outer = self
class Handler(http.server.BaseHTTPRequestHandler):
def setup(self):
try:
self.request = context.wrap_socket(self.request, server_side=True)
outer.handshakes.append("ok")
except (ssl.SSLError, OSError) as exc:
outer.handshakes.append("failed: %s" % exc)
raise
super().setup()
def do_GET(self): # noqa: N802
payload = ("<!doctype html><title>lab</title><body>%s</body>" % outer.body).encode()
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(payload)))
self.end_headers()
self.wfile.write(payload)
def log_message(self, *args):
pass
class Server(LocalServer):
def handle_error(self, request, client_address):
pass
self._server = Server((address, 0), Handler)
self.port = self._server.server_address[1]
threading.Thread(target=self._server.serve_forever, daemon=True).start()
def close(self) -> None:
self._server.shutdown()
self._server.server_close()
# ------------------------------------------------------------------------------------------------------- the profile
def xpcshell_commands(binary: str) -> List[Tuple[str, List[str]]]:
"""The ways to start the engine's xpcshell, the plain one first (the one that worked on both systems)."""
exe = str(Path(binary).resolve())
gre = str(Path(exe).parent)
return [("plain", [exe, "-xpcshell"]), ("with -g and -a", [exe, "-xpcshell", "-g", gre, "-a", gre])]
def _kill_tree(proc: subprocess.Popen) -> None:
try:
import psutil
parent = psutil.Process(proc.pid)
for child in parent.children(recursive=True):
child.kill()
parent.kill()
except Exception: # noqa: BLE001 - the process may be gone already
proc.kill()
def _run(argv: List[str], env: Dict[str, str], timeout: float, cwd: str) -> Tuple[Optional[int], str]:
proc = subprocess.Popen(argv, env=env, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL)
try:
out, _ = proc.communicate(timeout=timeout)
return proc.returncode, out.decode("utf-8", "replace")
except subprocess.TimeoutExpired:
_kill_tree(proc)
out, _ = proc.communicate()
return None, "TIMEOUT after %ss\n%s" % (timeout, out.decode("utf-8", "replace"))
def trusted_by_the_script(result: Optional[dict]) -> bool:
"""The verdict of one run of ``XPCSHELL_JS`` from the file it wrote: the call returned AND the NSS database says the root is trusted for TLS."""
return bool(result) and result.get("ok") is True and result.get("trusted_ssl") is True
def add_ca_to_profile(binary: str, profile: Path, ca_b64: str, work: Path, timeout: float = 120) -> List[str]:
"""Trust ``ca_b64`` in the NSS database of ``profile`` with the engine's own xpcshell. Returns the evidence lines; raises ``RuntimeError`` with
them when no way to start the shell ended with the root trusted. The profile directory is the one the session is launched with afterwards."""
profile, work = Path(profile), Path(work)
profile.mkdir(parents=True, exist_ok=True)
work.mkdir(parents=True, exist_ok=True)
script = work / "add_ca.js"
script.write_text(XPCSHELL_JS, encoding="utf-8")
evidence: List[str] = []
for label, head in xpcshell_commands(binary):
result_file = work / ("xpcshell-result-%s.json" % label.replace(" ", "_"))
env = dict(os.environ, LAB_PROFILE=str(profile), LAB_CERT_B64=ca_b64, LAB_RESULT=str(result_file), MOZ_LAUNCHER_PROCESS="0",
MOZ_CRASHREPORTER_DISABLE="1")
code, output = _run(head + [str(script)], env, timeout, str(Path(binary).resolve().parent))
body = None
if result_file.exists():
try:
body = json.loads(result_file.read_text(encoding="utf-8"))
except ValueError:
body = {"unreadable": result_file.read_text(encoding="utf-8", errors="replace")[:300]}
evidence.append("xpcshell [%s] exit=%s result=%s" % (label, code, json.dumps(body) if body is not None else "(no result file)"))
evidence.append("xpcshell [%s] output: %s" % (label, output.strip()[:600].replace("\n", " | ") or "(empty)"))
if trusted_by_the_script(body):
return evidence
raise RuntimeError("the engine's xpcshell could not trust the lab CA in %s:\n %s" % (profile, "\n ".join(evidence)))
+10 -20
View File
@@ -31,6 +31,8 @@ from pathlib import Path
from typing import Dict, Iterable, List, NamedTuple, Optional, Set, Tuple
from _doh_servers import RCODE_REFUSED, DohQuery, answer_for, build_response, parse_query
from _ports import candidates
from _ports import who_holds as _who_holds
RESOLV_CONF = Path("/etc/resolv.conf")
@@ -172,19 +174,6 @@ def _trap_capability() -> Tuple[bool, str]:
TRAP_ADDRESSES = ("127.0.0.1", "127.0.0.2", "127.0.0.3", "127.0.0.4", "127.0.0.5", "127.0.0.6", "127.0.0.7", "127.0.0.8")
def _who_holds(port: int) -> str:
"""What the machine says about the sockets of `port` (Linux: ss), for the message of a trap that could not bind."""
import subprocess
for command in (["ss", "-H", "-lntup"], ["netstat", "-lntup"]):
try:
done = subprocess.run(command, capture_output=True, text=True, timeout=10)
except (OSError, subprocess.SubprocessError):
continue
lines = [line for line in done.stdout.splitlines() if (":%d " % port) in line]
return "; held by: " + (" | ".join(lines) if lines else "nothing listed by %s" % command[0])
return "; no ss or netstat to say who holds it"
class Asker(NamedTuple):
"""Who sent a question to the trap: the user, the process (None when its socket could not be traced) and its command."""
uid: int
@@ -435,12 +424,12 @@ class ResolverTrap:
try:
addresses = TRAP_ADDRESSES if self.port != 0 else TRAP_ADDRESSES[:1]
for address in addresses:
for attempt in range(200):
made = self._bind_once(discarded, address)
# A port asked for (53) is tried once per address; with 0 the numbers are the harness's sequence (tests/_ports.py): the
# system's own pick, then numbers drawn below the ephemeral range, where Windows' excluded UDP blocks are not.
for wanted in ([self.port] if self.port != 0 else candidates(200)):
made = self._bind_once(discarded, address, wanted)
if made:
break
if self.port != 0:
break
if made:
self.address = address
break
@@ -458,10 +447,11 @@ class ResolverTrap:
self._threads.append(t)
t.start()
def _bind_once(self, discarded: List[socket.socket], address: str = "127.0.0.1") -> List[socket.socket]:
"""One attempt: the sockets bound, or [] after putting what it opened in ``discarded``."""
def _bind_once(self, discarded: List[socket.socket], address: str = "127.0.0.1", wanted: Optional[int] = None) -> List[socket.socket]:
"""One attempt, on the number ``wanted`` (the trap's own port when None, 0 for the system's pick): the sockets bound, or [] after
putting what it opened in ``discarded``."""
made: List[socket.socket] = []
port = self.port
port = self.port if wanted is None else wanted
for family, host, required in ((socket.AF_INET, address, True), (socket.AF_INET6, "::1", False)):
pair: List[socket.socket] = [] # this family's TCP and UDP, kept or dropped together
try:
+216
View File
@@ -0,0 +1,216 @@
"""What the page-bytes e2e needs, apart from the browser: the probe's values, the PNG comparison on decoded pixels, and the
comparison with a reference committed per operating system (tests/data/page_bytes_<os>.json).
The probe (tests/page_bytes_probe.js) resolves to a flat object {key: value} where a value is
{"s": "a short string"} a string of at most 3000 characters, or
{"h": ..., "n": ..., "s0": ...} a longer string: the hash of its bytes (cyrb53), its length, its first 200 characters, or
{"h": ..., "n": ..., "w": ..., "b64": ...} bytes: hash, length, pixels per row, the bytes themselves when at most 400 KiB.
A PNG that the page reads (toDataURL, toBlob, convertToBlob) also carries `b64`: the bytes of the file.
Two kinds of key in the reference:
"keys" stable values, equal in every launch: compared as they are (the string, or the hash and the length);
"pngs" the keys that are PNG files. A PNG the engine writes holds a 16-byte ancillary chunk, `deBG`, that differs in every
launch (measured on the Windows runner, run 43652292533: the same arm launched twice differs in that chunk and
nowhere else, the length is the same). So its bytes are not compared: its length, and the pixels it decodes to
(width, height, colour type, and the sha256 of the unfiltered scanlines).
No value here is made up: an entry the reference does not hold is a problem (the test is red), and the problem carries the
entry the run measured, in the form the reference file takes, so that a run on the engine of the day writes it down.
"""
from __future__ import annotations
import base64
import hashlib
import json
import struct
import zlib
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
DATA_PREFIX = "data:image/png;base64,"
#: the end of a key that is a PNG file (the jpeg and webp encodings are stable and are compared as they are)
PNG_KEY_ENDS = (".png", ".toBlob", ".convertToBlob", ".toDataURL")
DATA_DIR = Path(__file__).resolve().parent / "data"
# ------------------------------------------------------------------------------------------------------------------ PNG
class NotAPng(ValueError):
pass
def png_chunks(png: bytes) -> List[Tuple[bytes, bytes]]:
if not png.startswith(PNG_SIGNATURE):
raise NotAPng("no PNG signature")
out, i = [], len(PNG_SIGNATURE)
while i + 12 <= len(png):
size = struct.unpack(">I", png[i:i + 4])[0]
tag, data = png[i + 4:i + 8], png[i + 8:i + 8 + size]
if len(data) != size:
raise NotAPng("a chunk is cut")
out.append((tag, data))
i += 12 + size
return out
def _paeth(a: int, b: int, c: int) -> int:
p = a + b - c
pa, pb, pc = abs(p - a), abs(p - b), abs(p - c)
return a if pa <= pb and pa <= pc else (b if pb <= pc else c)
def decode_png(png: bytes) -> Dict[str, Any]:
"""{w, h, ct, sha256} of a non-interlaced 8-bit PNG (grey, RGB, grey+alpha, RGBA): the sha256 is over the unfiltered
scanlines, so two files with the same pixels and different ancillary chunks or compression give the same answer."""
chunks = png_chunks(png)
head = [d for t, d in chunks if t == b"IHDR"]
if not head:
raise NotAPng("no IHDR")
w, h, depth, ct, _comp, _filt, interlace = struct.unpack(">IIBBBBB", head[0])
channels = {0: 1, 2: 3, 4: 2, 6: 4}.get(ct)
if depth != 8 or interlace != 0 or channels is None:
raise NotAPng("only 8-bit, non-interlaced, non-palette PNG is decoded here (bit depth %d, colour type %d, interlace %d)"
% (depth, ct, interlace))
raw = zlib.decompress(b"".join(d for t, d in chunks if t == b"IDAT"))
stride = w * channels
if len(raw) != h * (stride + 1):
raise NotAPng("the scanlines are %d bytes, %d expected" % (len(raw), h * (stride + 1)))
out = bytearray()
prev = bytearray(stride)
pos = 0
for _ in range(h):
ftype = raw[pos]
line = bytearray(raw[pos + 1:pos + 1 + stride])
pos += 1 + stride
if ftype == 1:
for i in range(channels, stride):
line[i] = (line[i] + line[i - channels]) & 255
elif ftype == 2:
for i in range(stride):
line[i] = (line[i] + prev[i]) & 255
elif ftype == 3:
for i in range(stride):
left = line[i - channels] if i >= channels else 0
line[i] = (line[i] + ((left + prev[i]) >> 1)) & 255
elif ftype == 4:
for i in range(stride):
left = line[i - channels] if i >= channels else 0
upleft = prev[i - channels] if i >= channels else 0
line[i] = (line[i] + _paeth(left, prev[i], upleft)) & 255
elif ftype != 0:
raise NotAPng("filter type %d" % ftype)
out += line
prev = line
return {"w": w, "h": h, "ct": ct, "sha256": hashlib.sha256(bytes(out)).hexdigest()}
def png_bytes_of(value: Dict[str, Any]) -> Optional[bytes]:
"""The PNG file a probe value holds, or None when the probe did not keep its bytes."""
if "b64" in value:
return base64.b64decode(value["b64"])
text = value.get("s")
if isinstance(text, str) and text.startswith(DATA_PREFIX):
return base64.b64decode(text[len(DATA_PREFIX):])
return None
def is_png_key(key: str) -> bool:
return key.endswith(PNG_KEY_ENDS)
# --------------------------------------------------------------------------------------------------------- the reference
def ident(value: Dict[str, Any]) -> Dict[str, Any]:
"""What identifies a stable value: its string, or the hash and the length of its bytes."""
if "s" in value:
return {"s": value["s"]}
return {"h": value.get("h"), "n": value.get("n")}
def png_entry(value: Dict[str, Any]) -> Dict[str, Any]:
"""The entry of a PNG key: its length and, when the bytes were kept, the pixels they decode to."""
# n: the length of the string for a data URL, of the file for bytes
entry: Dict[str, Any] = {"n": value["n"] if "n" in value else len(value.get("s", ""))}
data = png_bytes_of(value)
if data is None:
return entry
try:
entry.update(decode_png(data))
except (NotAPng, zlib.error) as exc:
entry["undecodable"] = str(exc)
return entry
def entry_of(key: str, value: Dict[str, Any]) -> Dict[str, Any]:
return png_entry(value) if is_png_key(key) else ident(value)
def reference_path(os_name: str) -> Path:
return DATA_DIR / ("page_bytes_%s.json" % os_name)
def load_reference(os_name: str) -> Dict[str, Any]:
"""The reference of an operating system; an empty one when the file does not exist yet (every key is then a problem
that carries its own entry, which is how the first reference is written)."""
path = reference_path(os_name)
if not path.is_file():
return {"keys": {}, "pngs": {}}
return json.loads(path.read_text(encoding="utf-8"))
def compare(reference: Dict[str, Any], measured: Dict[str, Dict[str, Any]]) -> Tuple[List[str], Dict[str, Dict[str, Any]]]:
"""(problems, record). `problems` is empty when every key the probe returned is in the reference with the same value
and the reference holds no key the probe did not return. `record` is the entry the run measured for every key that is
missing from the reference or incomplete in it (a PNG with no decoded pixels), in the form the reference file takes."""
problems: List[str] = []
record: Dict[str, Dict[str, Any]] = {}
stable, pngs = reference.get("keys", {}), reference.get("pngs", {})
for key in sorted(measured):
mine = entry_of(key, measured[key])
if is_png_key(key):
if "undecodable" in mine:
problems.append("%s: the PNG the page read does not decode (%s)" % (key, mine["undecodable"]))
continue
if "sha256" not in mine:
problems.append("%s: the probe did not keep the bytes of this PNG" % key)
continue
ref = pngs.get(key)
if ref is None:
problems.append("%s: not in the reference" % key)
record[key] = mine
elif ref.get("n") != mine.get("n"):
problems.append("%s: the PNG is %s bytes, the reference says %s" % (key, mine.get("n"), ref.get("n")))
elif "sha256" not in ref:
problems.append("%s: the reference has the length of this PNG and not yet its decoded pixels" % key)
record[key] = mine
elif (ref["w"], ref["h"], ref["ct"], ref["sha256"]) != (mine["w"], mine["h"], mine["ct"], mine["sha256"]):
problems.append("%s: the decoded pixels differ (%sx%s ct %s %s, the reference %sx%s ct %s %s)"
% (key, mine["w"], mine["h"], mine["ct"], mine["sha256"][:12],
ref["w"], ref["h"], ref["ct"], ref["sha256"][:12]))
else:
ref = stable.get(key)
if ref is None:
problems.append("%s: not in the reference" % key)
record[key] = mine
elif ref != mine:
problems.append("%s: %s, the reference %s" % (key, _short(mine), _short(ref)))
for key in sorted((set(stable) | set(pngs)) - set(measured)):
problems.append("%s: in the reference and not read by the probe" % key)
return problems, record
def _short(entry: Dict[str, Any], limit: int = 120) -> str:
return json.dumps(entry, sort_keys=True)[:limit]
def message(os_name: str, problems: List[str], record: Dict[str, Dict[str, Any]]) -> str:
"""The failure text: the problems, and the entries to add to tests/data/page_bytes_<os>.json."""
text = "%d problem(s) in the bytes a page reads on %s against %s:\n %s" % (
len(problems), os_name, reference_path(os_name).name, "\n ".join(problems[:60]))
if record:
keys = {k: v for k, v in record.items() if not is_png_key(k)}
pngs = {k: v for k, v in record.items() if is_png_key(k)}
text += ("\nTO RECORD (merge into tests/data/page_bytes_%s.json, from a run on the engine whose bytes are the reference):\n"
"RECORD-BEGIN %s\n%s\nRECORD-END" % (os_name, os_name, json.dumps({"keys": keys, "pngs": pngs}, sort_keys=True)))
return text
+137
View File
@@ -0,0 +1,137 @@
"""The page work of the "nothing leaves but the proxy" e2e: the names, the pages and the server (no pytest in here).
A page can make a browser do much more than load a document: hints (``dns-prefetch``, ``preconnect``, ``prefetch``, ``preload``), an
image, a ``fetch``, a WebSocket, an EventSource, a WebRTC gather with a STUN and a TURN server, a geolocation request, a service worker
with push, and a page still loading when its context is closed. Each of them is tried in a context of its own behind a SOCKS5 gateway,
and what the test asks is where the browser went: no question to the resolver of the machine, no direct connection, every name asked
to the DoH THROUGH the gateway of the context, every CONNECT by an ADDRESS.
The names are the zone of a ``FakeDoh``. The pages are served from 127.0.0.1 and reached by a name (``<case>-site.test``) that points
there. Every name the page work uses points at a DOCUMENTATION address (RFC 5737, 198.51.100.0/24), never at loopback, for two reasons:
a connection a browser opens straight to it is seen by the leak watcher (a loopback one never is), and the gateway of the tests refuses
a CONNECT to a non-loopback address and lists it, which is how a test sees that the browser CONNECTed by the address the DoH gave.
"""
from __future__ import annotations
import http.server
import threading
from typing import Dict, List, Optional
from _servers import LocalServer
#: The zone of the page work: name -> the documentation address a lookup of it answers.
ROUTABLE: Dict[str, str] = {
"prefetch-a.test": "198.51.100.21", "preconnect-b.test": "198.51.100.22", "prefetch-c.test": "198.51.100.23",
"preload-d.test": "198.51.100.24",
"img-e.test": "198.51.100.25", "fetch-f.test": "198.51.100.26", "ws-g.test": "198.51.100.27", "es-h.test": "198.51.100.28",
"stun-i.test": "198.51.100.29", "turn-j.test": "198.51.100.30",
}
#: The pages' own names: they point at the local server. ``push`` is served by its address (a service worker needs a secure
#: context, and ``.test`` is not one; 127.0.0.1 is).
SITES: Dict[str, str] = {"hints-site.test": "127.0.0.1", "subresources-site.test": "127.0.0.1", "webrtc-site.test": "127.0.0.1",
"geolocation-site.test": "127.0.0.1", "closing-site.test": "127.0.0.1"}
ZONE: Dict[str, str] = {**SITES, **ROUTABLE}
#: What each case's page does. ``%`` is not used: the names are written out, the page of a case is a constant.
CASES: Dict[str, str] = {
"hints": '<link rel=dns-prefetch href="//prefetch-a.test"><link rel=preconnect href="http://preconnect-b.test">'
'<link rel=prefetch href="http://prefetch-c.test/x"><link rel=preload as=image href="http://preload-d.test/i.png">',
"subresources": '<img src="http://img-e.test/i.png"><script>fetch("http://fetch-f.test/x").catch(() => {});'
'try { new WebSocket("ws://ws-g.test/s").onerror = () => {}; } catch (e) {}'
'try { new EventSource("http://es-h.test/s").onerror = function () { this.close(); }; } catch (e) {}</script>',
"webrtc": '<script>(async () => { const pc = new RTCPeerConnection({iceServers: [{urls: "stun:stun-i.test:3478"},'
'{urls: "turn:turn-j.test:3478", username: "u", credential: "p"}]});'
'pc.createDataChannel("d"); await pc.setLocalDescription(await pc.createOffer()); })().catch(() => {});</script>',
"geolocation": '<script>try { navigator.geolocation.getCurrentPosition(() => {}, () => {}, {timeout: 4000}); } catch (e) {}</script>',
# a page still loading when its context is closed: requests made between the close and the death of its processes. These names
# are in no zone: the DoH answers NXDOMAIN, and what is asked is where the question goes.
"closing": '<script>let n = 0; setInterval(() => { for (let k = 0; k < 3; k++) fetch("http://late-" + (n++) + ".test/x")'
'.catch(() => {}); }, 5);</script>',
# `__pushStage` says how far the page got (registering, registered, ready, subscription-read): a page that stays `pending` names the step it
# is stuck in.
"push": '<script>window.__push = "pending"; window.__pushStage = "start"; (async () => { if (!navigator.serviceWorker) { window.__push = "no-service-worker"; return; }'
'window.__pushStage = "registering"; const r = await navigator.serviceWorker.register("/sw.js"); window.__pushStage = "registered";'
'await navigator.serviceWorker.ready; window.__pushStage = "ready";'
# WHY THE PAGE ASKS AGAIN (run 43501478312: Linux, both schemes, stage `ready`, `pending` for 30 s; Windows passes). The launch has `-silent`
# (invisible_core/juggler/connection.py:1245), which means NO window at start-up (browser/components/BrowserContentHandler.sys.mjs:626,
# preventDefault) and Juggler declares the browser started at once (juggler/components/Juggler.js:86-88) instead of waiting for
# `browser-idle-startup-tasks-finished` (Juggler.js:93). The first window is made by the first new page; only then does
# `sessionstore-windows-restored` (browser/components/sessionstore/SessionStore.sys.mjs:1865) schedule BrowserGlue's idle tasks
# (browser/components/BrowserGlue.sys.mjs:828-885), among them `PushService.ensureReady` (BrowserGlue.sys.mjs:984-1000), which is the first
# thing that creates the parent's PushServiceParent. Its message listeners are registered in the constructor (dom/push/PushComponents.sys.mjs:49-52),
# so a `Push:Registration` sent by the content process before that (PushComponents.sys.mjs:425-430) is lost, not queued: `getSubscription()` never
# settles. This is Mozilla/Juggler behaviour, not ours: stock Playwright 1.61 also starts a non-persistent Firefox with `-silent` (driver
# coreBundle.js, defaultArgs: `if (isPersistent) firefoxArguments.push("about:blank"); else firefoxArguments.push("-silent");`). A page
# that asks early is a property of this lab, so the page asks again every 2 s as a page would, bounded: 15 asks, 30 s, then it stays
# `pending` and the test fails with the stage. How long the push service takes to exist is UNMEASURED (the only runs are the red ones, where
# it had not existed 30 s after the page was loaded; no run has a number for a green Linux leg).
'let sub; for (let i = 1; i <= 15 && sub === undefined; i++) { window.__pushTries = i; sub = await Promise.race([r.pushManager.getSubscription(),'
' new Promise(res => setTimeout(() => res(undefined), 2000))]); }'
'if (sub === undefined) return; window.__push = "sub:" + JSON.stringify(sub); window.__pushStage = "subscription-read";'
'await r.pushManager.subscribe({userVisibleOnly: true, applicationServerKey: new Uint8Array(65).fill(4)});'
'})().catch(e => { window.__push = String(window.__push).startsWith("sub:") ? window.__push : "error:" + e.name; });</script>',
}
#: The names the DoH must be asked for, by case, when the work is done (a hint is speculative: the browser may skip it, so none is demanded).
ASKED: Dict[str, List[str]] = {
"hints": [], "subresources": ["img-e.test", "fetch-f.test", "ws-g.test", "es-h.test"], "webrtc": ["stun-i.test", "turn-j.test"],
"geolocation": [], "closing": ["late-0.test"], "push": [],
}
#: How long the page is left to work before the context is closed, in seconds: a case that does little is closed sooner.
SETTLE_SECONDS: Dict[str, float] = {"hints": 6.0, "subresources": 6.0, "webrtc": 6.0, "geolocation": 6.0, "closing": 1.5, "push": 6.0}
SW = b"self.addEventListener('push', () => {});"
def site_name(case: str) -> Optional[str]:
"""The name a case's page is reached by, or None for the one reached by its address."""
name = "%s-site.test" % case
return name if name in SITES else None
def is_documentation_address(address: str) -> bool:
"""True for an address of 198.51.100.0/24 (TEST-NET-2)."""
return address.startswith("198.51.100.")
class CaseSite:
"""A local HTTP server: ``/<case>`` answers the page of that case, ``/sw.js`` a service worker with a push listener."""
def __init__(self):
outer = self
self.hits: List[tuple] = []
class Handler(http.server.BaseHTTPRequestHandler):
def do_GET(self): # noqa: N802
path = self.path.split("?", 1)[0]
outer.hits.append((self.headers.get("Host", ""), path))
if path == "/sw.js":
body, kind = SW, "application/javascript"
elif path.lstrip("/") in CASES:
body, kind = ("<!doctype html><meta charset=utf-8><title>%s</title>%s" % (path.lstrip("/"), CASES[path.lstrip("/")])
).encode(), "text/html; charset=utf-8"
else:
body, kind = b"", "text/plain"
self.send_response(200)
self.send_header("Content-Type", kind)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
self._server = LocalServer(("127.0.0.1", 0), Handler)
self.port = self._server.server_address[1]
threading.Thread(target=self._server.serve_forever, daemon=True).start()
def url(self, case: str) -> str:
name = site_name(case)
return "http://%s:%d/%s" % (name or "127.0.0.1", self.port, case)
def close(self) -> None:
self._server.shutdown()
self._server.server_close()
+67
View File
@@ -0,0 +1,67 @@
"""One port number that TCP and UDP both bind on an address, found the way the witness finds it (tests/_witness.py), and said when it is not found.
Windows hands out ephemeral TCP ports in sequence and keeps excluded ranges of a hundred ports for UDP in the same zone, so asking the system for
fifty TCP ports in a row can give fifty consecutive numbers inside one range UDP may not bind: the first try is the system's own pick, the others
are drawn at random below the ephemeral range (run 43230437094, wrapper.e2e.web on Windows: ``H3Server`` found "no port free for both TCP and UDP"
three times, and the refusals it had swallowed were never read). Every refusal is kept, with its code, and the last ones are in the message.
"""
from __future__ import annotations
import random
import socket
import subprocess
from typing import Any, Callable, List, Tuple
TRIES = 200
#: Below Linux's ephemeral range (32768): a number drawn here is not the next of a sequence the system hands out.
DRAW_FROM = (20000, 32767)
def who_holds(port: int) -> str:
"""What the machine says about the sockets of `port` (ss, or netstat), for the message of a picker or a trap that found no number."""
for command in (["ss", "-H", "-lntup"], ["netstat", "-lntup"]):
try:
done = subprocess.run(command, capture_output=True, text=True, timeout=10)
except (OSError, subprocess.SubprocessError):
continue
lines = [line for line in done.stdout.splitlines() if (":%d " % port) in line]
return "; held by: " + (" | ".join(lines) if lines else "nothing listed by %s" % command[0])
return "; no ss or netstat to say who holds it"
def candidates(tries: int = TRIES, draw: Any = None):
"""The port numbers to try, in order: 0 (the system's own pick) first, then numbers drawn at random below the ephemeral range. The ONE
sequence of the harness for "the same number on TCP and UDP": the HTTP/3 server, the witness and the resolver trap all walk it."""
draw = draw or random.Random()
for attempt in range(tries):
yield 0 if attempt == 0 else draw.randint(*DRAW_FROM)
def bind_tcp_and_probe_udp(address: str, make_tcp: Callable[[str, int], Any], tries: int = TRIES, socket_module: Any = None,
draw: Any = None) -> Tuple[Any, int]:
"""``make_tcp(address, port)`` makes the TCP server (it binds, with port 0 for the system's pick; it has ``server_address`` and
``server_close``). Returns ``(that server, its port)`` once UDP binds the same number too (the probe is closed again: whoever needs the UDP
socket binds it next). Raises RuntimeError saying how many tries were made and the last refusals, codes included."""
sock = socket_module or socket
refusals: List[str] = []
last = 0
for wanted in candidates(tries, draw):
tcp = None
try:
tcp = make_tcp(address, wanted)
port = tcp.server_address[1]
probe = sock.socket(sock.AF_INET, sock.SOCK_DGRAM)
try:
probe.bind((address, port))
finally:
probe.close()
return tcp, port
except OSError as exc:
refusals.append("%s: %s" % (wanted or "system pick", exc))
if tcp is not None:
last = tcp.server_address[1]
tcp.server_close()
else:
last = wanted
raise RuntimeError("no port free for both TCP and UDP on %s, after %d tries (the last number tried: %s)%s; the last refusals: %s"
% (address, tries, last or "the system's pick", who_holds(last) if last else "", "; ".join(refusals[-3:])))
+68
View File
@@ -0,0 +1,68 @@
"""What a test of the screencast needs to say when a stream delivers nothing.
A dead stream is silent on the wrapper side (the engine keeps one frame in
flight and sends no error), so the only account of why is the engine's own
output and the clock: the lines it printed that start with ``screencast:`` and,
per stream, how long after the start reply the first frame came (if one did).
Shared by `test_screencast.py` and `test_hidden_desktop.py`.
"""
from __future__ import annotations
import time
def engine_screencast_lines(page):
"""The lines the engine printed that start with ``screencast:``, from the
browser's own stdout/stderr (the core keeps the last 200 lines of the
pipe for the whole life of the process, `ProcessOutput`). Where the
engine has no line for it the answer says so, so a failure message never
comes out empty. Read while the browser is still up."""
try:
impl = page._impl_obj
server = impl._connection._transport._server
output = server.object(impl._guid).conn.output
lines = output.tail(output.KEEP)
except Exception as failure: # the message is the point, not the lookup
return "(the engine output could not be read: %r)" % (failure,)
mine = [l for l in lines if l.lstrip().startswith("screencast:")]
return "\n".join(mine) if mine else "(the engine printed no line starting with 'screencast:')"
class Stream:
"""One screencast's frames and the clock around them.
`on_frame` is a plain function held in an attribute, not a bound method:
the sync client tags the handler with an attribute, which a bound method
cannot carry.
"""
def __init__(self, name="stream"):
self.name = name
self.frames = []
self.started = None # when `start()` returned, i.e. the reply was handled
self.first = None # when the first frame reached the handler
def on_frame(frame):
if self.first is None:
self.first = time.monotonic()
self.frames.append(frame)
self.on_frame = on_frame
def start(self, page, **kwargs):
page.screencast.start(on_frame=self.on_frame, **kwargs)
self.started = time.monotonic()
def first_after_start(self):
"""Seconds from the start reply to the first frame, or None. Negative
when the frame was handed to the handler before `start()` returned."""
if self.first is None or self.started is None:
return None
return self.first - self.started
def describe(self):
delay = self.first_after_start()
return "%s: %d frame(s), first frame %s" % (
self.name, len(self.frames),
"never arrived" if delay is None else
"%+.3f s after the start reply" % delay)
+57 -23
View File
@@ -97,6 +97,11 @@ class FakeStun:
# On the address the relay sends from: Windows sends neither from an address of the host to loopback (WinError 10049) nor
# from loopback to an address of the host (10051), so a relay that leaves from the host's address needs its STUN there too.
self._sock.bind((bind_host, 0))
self._closing = False
if hasattr(socket, "SIO_UDP_CONNRESET"):
# Windows: an ICMP "port unreachable" to an answer (a client that already closed its socket) makes the NEXT recvfrom raise
# WinError 10054; left on, the server that reads would end there and answer nobody afterwards. Off, as a real server has it.
self._sock.ioctl(socket.SIO_UDP_CONNRESET, False)
self.address: Tuple[str, int] = self._sock.getsockname()
self._thread = threading.Thread(target=self._serve, daemon=True)
self._thread.start()
@@ -105,8 +110,12 @@ class FakeStun:
while True:
try:
data, peer = self._sock.recvfrom(2048)
except ConnectionResetError:
continue # an earlier answer found nobody: that is that client's business, not the server's end
except OSError:
return
if self._closing:
return # the datagram `close` sent to wake this thread, or one that came after it
if len(data) < 20 or data[0:2] != b"\x00\x01":
continue
self.requests += 1
@@ -118,9 +127,25 @@ class FakeStun:
try:
self._sock.sendto(resp, peer)
except OSError:
return
if self._closing:
return
continue # a send that failed (the peer is gone) does not end the server for the next client
def close(self) -> None:
"""Ends the server and its thread. Closing the socket wakes a `recvfrom` blocked in another thread on Windows, not on Linux,
where the thread would stay blocked for the rest of the process: so the server first sends itself one datagram, which wakes the
thread to see `_closing`, waits for the thread, and only then closes the socket."""
self._closing = True
try:
waker = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
waker.sendto(b"", self.address)
finally:
waker.close()
except OSError:
pass
if self._thread is not threading.current_thread():
self._thread.join(timeout=2)
self._sock.close()
@@ -433,6 +458,12 @@ class Gateway:
self._deliver(relay, client[0], host, port, data)
def inbound() -> None: # client -> world
# The port of the exit socket is read ONCE: asked at every datagram it fell on a socket the teardown had already closed
# (OSError WinError 10038 in a thread nobody joins). An OSError of the body is the association ending, not a failure.
try:
out_port = out.getsockname()[1]
except OSError:
return
while True:
try:
d, peer = relay.recvfrom(65536)
@@ -440,28 +471,31 @@ class Gateway:
continue
except OSError:
return
if len(d) < 10 or d[2] != 0:
continue
client[0] = peer
atyp, i = d[3], 4
if atyp == 1:
host, i = socket.inet_ntoa(d[i:i + 4]), i + 4
elif atyp == 3:
n = d[i]
host, i = d[i + 1:i + 1 + n].decode(), i + 1 + n
else:
host, i = socket.inet_ntop(socket.AF_INET6, d[i:i + 16]), i + 16
dport = struct.unpack("!H", d[i:i + 2])[0]
payload = d[i + 2:]
self.datagrams.append((host, dport, payload))
self.datagram_log.append((host, dport, atyp, time.monotonic() - self.t0))
routed = self._route(host, dport, atyp, payload, out.getsockname()[1], answer)
if routed is None:
continue
target, reported = routed
if reported is not None:
asked_at[target] = reported
self._later(lambda p=payload, t=target: out.sendto(p, t), "the datagram to %s:%d" % target)
try:
if len(d) < 10 or d[2] != 0:
continue
client[0] = peer
atyp, i = d[3], 4
if atyp == 1:
host, i = socket.inet_ntoa(d[i:i + 4]), i + 4
elif atyp == 3:
n = d[i]
host, i = d[i + 1:i + 1 + n].decode(), i + 1 + n
else:
host, i = socket.inet_ntop(socket.AF_INET6, d[i:i + 16]), i + 16
dport = struct.unpack("!H", d[i:i + 2])[0]
payload = d[i + 2:]
self.datagrams.append((host, dport, payload))
self.datagram_log.append((host, dport, atyp, time.monotonic() - self.t0))
routed = self._route(host, dport, atyp, payload, out_port, answer)
if routed is None:
continue
target, reported = routed
if reported is not None:
asked_at[target] = reported
self._later(lambda p=payload, t=target: out.sendto(p, t), "the datagram to %s:%d" % target)
except OSError:
return
def outbound() -> None: # world -> client
while True:
+2 -2
View File
@@ -143,14 +143,14 @@ class TurnServer:
self.sock.sendto(_message(0x0113, tid, err), src)
continue
user = attrs[0x0006].decode(errors="replace")
key = hashlib.md5(("%s:%s:%s" % (user, REALM, PASSWORD)).encode()).digest()
key = hashlib.md5(("%s:%s:%s" % (user, REALM, PASSWORD)).encode(), usedforsecurity=False).digest()
body = (_attr(0x0016, _xor_addr(*RELAYED)) + _attr(0x0020, _xor_addr(src[0], src[1])) +
_attr(0x000D, struct.pack("!I", 600)))
self.allocations.append((src[0], src[1], user, time.monotonic()))
self.sock.sendto(_message(0x0103, tid, body, key), src)
elif mtype in (0x0004, 0x0008, 0x0009): # Refresh, CreatePermission, ChannelBind
user = attrs.get(0x0006, b"").decode(errors="replace")
key = hashlib.md5(("%s:%s:%s" % (user, REALM, PASSWORD)).encode()).digest()
key = hashlib.md5(("%s:%s:%s" % (user, REALM, PASSWORD)).encode(), usedforsecurity=False).digest()
body = _attr(0x000D, struct.pack("!I", 600)) if mtype == 0x0004 else b""
self.sock.sendto(_message(mtype | 0x0100, tid, body, key), src)
+33
View File
@@ -88,6 +88,39 @@ def declared_udp(proxy: Dict[str, Any], servers: Sequence[str]) -> str:
return entry[1]
def declared_udp_or_absent(proxy: Dict[str, Any], servers: Sequence[str]) -> Optional[str]:
""":func:`declared_udp`, or None when the launch measured nothing for ``proxy`` (a report must say that, not raise)."""
try:
return declared_udp(proxy, servers)
except AssertionError:
return None
def udp_measure_sentence(declared: Optional[str], rtt_ms: int) -> str:
"""What the core declared for the proxy of a bench, as a sentence of the verdict of a failed test. A measurement that is
not ``coherent`` is said outright: the engine then never sends the page's UDP to the relay, and the test fails for a reason
that is the measurement's (the budget of the core against the round trip of the gateway), not the page's."""
if declared == "coherent":
return "UDP verdict the core declared for this proxy: coherent"
if declared is None:
return ("the core measured nothing for this proxy: the UDP measure of the core did not finish in its budget "
"with rtt %d ms (no verdict was declared)" % rtt_ms)
return ("the UDP measure of the core did not finish coherent in its budget with rtt %d ms: it declared %r for this proxy, "
"so the engine had no relay to use" % (rtt_ms, declared))
def bench_report(gateway: Any, rtt_ms: int, declared: Optional[str]) -> str:
"""What the bench saw, as one string for the verdict of a failed test: the datagrams the relay carried with their times
(seconds from the start of the gateway), the sends that failed, the CONNECTs, the TCP connections accepted, the UDP
ASSOCIATEs and their start and end, and what the core declared for the proxy. Nothing here changes an outcome."""
log = ["%s:%d atyp=%d t=%.3fs" % (host, port, atyp, at) for host, port, atyp, at in list(gateway.datagram_log)]
associations = [[None if x is None else round(x, 3) for x in record] for record in list(gateway.associations)]
return ("%s; gateway send errors: %s; CONNECTs the gateway saw: %s; TCP connections it accepted: %d; "
"associations (start, end in s from its start): %s; datagram log with times: %s"
% (udp_measure_sentence(declared, rtt_ms), list(gateway.send_errors), list(gateway.connects),
len(gateway.accepted), associations, log))
def visits_for(road: str) -> int:
"""How many times the page is visited on ``road``: three with no proxy, :data:`PROXY_VISITS` behind any proxy."""
if road == _DIRECT_ROAD:
+6 -9
View File
@@ -10,7 +10,6 @@ saw, so a road that works also gives the page a server-reflexive candidate.
"""
from __future__ import annotations
import random
import socket
import sys
import struct
@@ -19,11 +18,11 @@ from typing import Dict, Iterable, List, Tuple
_MAGIC = b"\x21\x12\xa4\x42"
#: How many port numbers the witness tries before it gives up, and where it draws them from after the system's own pick.
TRIES = 200
#: Below the start of Windows' dynamic range (49152), where its excluded ranges are reserved in blocks of a hundred, and
#: below Linux's ephemeral range (32768): a number drawn here is not the next of a sequence the system hands out.
DRAW_FROM = (20000, 32767)
#: How many port numbers the witness tries before it gives up, and where it draws them from after the system's own pick: the sequence of
#: tests/_ports.py, which the HTTP/3 server and the resolver trap walk too. Below the start of Windows' dynamic range (49152), where its excluded
#: ranges are reserved in blocks of a hundred, and below Linux's ephemeral range (32768): a number drawn there is not the next of a sequence the
#: system hands out.
from _ports import DRAW_FROM, TRIES, candidates # noqa: E402
class Witness:
@@ -45,9 +44,7 @@ class Witness:
@staticmethod
def _bind_both(address: str, port: int):
refusals: List[str] = []
draw = random.Random()
for attempt in range(1 if port else TRIES):
wanted = port if port else (0 if attempt == 0 else draw.randint(*DRAW_FROM))
for wanted in ([port] if port else candidates(TRIES)):
tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
udp = None
try:
+8 -1
View File
@@ -11,6 +11,7 @@ from pathlib import Path
import pytest
from _servers import LocalServer
from _browser_census import _a_module_leaves_no_browser_open, _the_connections_a_test_made_are_closed_with_it # noqa: F401 (autouse)
# ── The watchdog that says WHERE it is stuck, while it is still stuck ─────────
#
@@ -73,6 +74,12 @@ def pytest_configure(config):
# The run stops at the first refusal of the engine (tests/engine_refusal.py).
from engine_refusal import StopAtTheFirstRefusal
config.pluginmanager.register(StopAtTheFirstRefusal(config), "engine-refusal-stop")
# What the core did about the GeoIP database during the run, for scripts/ci_lab_geoip.py verify (the CI legs set GEOIP_USED_OUT).
if os.environ.get("GEOIP_USED_OUT"):
from geoip_used import GeoipUsedRecorder
recorder = GeoipUsedRecorder(os.environ["GEOIP_USED_OUT"])
recorder.start()
config.pluginmanager.register(recorder, "geoip-used")
def pytest_runtest_setup(item):
@@ -244,7 +251,7 @@ def _skip_unless_engine_at_least(minimum, tag):
@pytest.fixture(scope="session")
def engine_at_least():
"""``engine_at_least("firefox-64")``: skip the test unless the engine in
"""``engine_at_least("firefox-65")``: skip the test unless the engine in
use is that release or a later one (see above for how it is read). A seal
whose tag has no number (``local``, anything but firefox-N or
firefox-N-candidate) makes the test FAIL, saying so: it neither skips nor
+409
View File
@@ -0,0 +1,409 @@
{
"os": "linux",
"source": "GitHub Actions run 43661728392 (workflow page-bytes-reference-hunt, runner image ubuntu24 20261111.370.1), wrapper commit 455d5619e5, invisible-core 64.71.0, engine firefox-64_159.0_20261114003728, seed 42, locale en-US, timezone Europe/Rome, headless=True; 2 launches, every key below is equal in all of them. `pngs`: the PNG keys, compared on their length and decoded pixels because every PNG carries a per-launch chunk.",
"keys": {
"c2d.composite.getImageData": {
"h": "df65ebe03bf31",
"n": 131072
},
"c2d.composite.jpeg": {
"h": "1c1b75006c5984",
"n": 11535
},
"c2d.composite.webp": {
"h": "182ab2238ae6c0",
"n": 5431
},
"c2d.gradtext.getImageData": {
"h": "ba9fb4487cdea",
"n": 352800
},
"c2d.image.getImageData": {
"h": "8218d41a1794c",
"n": 76800
},
"c2d.image.jpeg": {
"h": "125de65c968e30",
"n": 7315
},
"c2d.image.webp": {
"h": "26ea5dc80f98c",
"n": 5659
},
"c2d.measure": {
"h": "14a71ef40cb01c",
"n": 9488
},
"c2d.offscreen.getImageData": {
"h": "5a93b1c32ab60",
"n": 51200
},
"c2d.scale.high.getImageData": {
"h": "10d3beda5ba224",
"n": 114400
},
"c2d.scale.low.getImageData": {
"h": "10d3beda5ba224",
"n": 114400
},
"c2d.scale.medium.getImageData": {
"h": "10d3beda5ba224",
"n": 114400
},
"c2d.scale.off.getImageData": {
"h": "c673134829639",
"n": 114400
},
"c2d.shapes.getImageData": {
"h": "18fe9a0f7336da",
"n": 163840
},
"c2d.shapes.jpeg": {
"h": "18d82802030ab3",
"n": 6975
},
"c2d.shapes.webp": {
"h": "1ec9fa4e39f8de",
"n": 3287
},
"c2d.text.getImageData": {
"h": "e141df45718e",
"n": 856960
},
"c2d.text.jpeg": {
"h": "23b24c30781ee",
"n": 41751
},
"c2d.text.webp": {
"h": "1b0cc3c21c4f0f",
"n": 26215
},
"dom.fonts_check": {
"s": "[[\"16px sans-serif\",true],[\"20px serif\",true],[\"18px monospace\",true],[\"bold 16px Arial\",true],[\"italic 15px 'Segoe UI'\",true],[\"16px 'Times New Roman'\",true],[\"16px Calibri\",true],[\"14px Consolas\",true],[\"16px Verdana\",true],[\"16px Tahoma\",true],[\"17px Georgia\",true],[\"16px 'Segoe UI Emoji'\",true],[\"16px 'Microsoft YaHei'\",true],[\"16px 'Yu Gothic'\",true]]"
},
"dom.paragraphs": {
"s": "[[\"16px sans-serif\",200,21],[\"15px 'Times New Roman'\",200,20],[\"14px Consolas\",200,19]]"
},
"dom.span_boxes": {
"h": "1435dcc5a321d6",
"n": 5864
},
"dom.system_colors": {
"s": "[[\"Canvas\",\"rgb(255, 255, 255)\"],[\"CanvasText\",\"rgb(0, 0, 0)\"],[\"ButtonFace\",\"rgb(233, 233, 237)\"],[\"ButtonText\",\"rgb(0, 0, 0)\"],[\"ButtonBorder\",\"rgb(129, 127, 132)\"],[\"Field\",\"rgb(255, 255, 255)\"],[\"FieldText\",\"rgb(0, 0, 0)\"],[\"Highlight\",\"rgb(0, 120, 215)\"],[\"HighlightText\",\"rgb(255, 255, 255)\"],[\"GrayText\",\"rgb(109, 109, 109)\"],[\"LinkText\",\"rgb(0, 0, 238)\"],[\"VisitedText\",\"rgb(85, 26, 139)\"],[\"ActiveText\",\"rgb(238, 0, 0)\"],[\"Mark\",\"rgb(255, 255, 0)\"],[\"MarkText\",\"rgb(0, 0, 0)\"],[\"AccentColor\",\"rgb(0, 96, 223)\"],[\"AccentColorText\",\"rgb(255, 255, 255)\"],[\"SelectedItem\",\"rgb(0, 120, 215)\"],[\"SelectedItemText\",\"rgb(255, 255, 255)\"]]"
},
"env.dpr": {
"s": "1"
},
"env.hw": {
"s": "8"
},
"env.lang": {
"s": "[\"en-US\",\"en\"]"
},
"env.mq": {
"s": "[true,false,false,false,false,false,false]"
},
"env.oscpu": {
"s": "Windows NT 10.0; Win64; x64"
},
"env.platform": {
"s": "Win32"
},
"env.screen": {
"s": "[1920,1080,1920,1032,24,24]"
},
"env.ua": {
"s": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:159.0) Gecko/20100101 Firefox/159.0"
},
"gl1.anisotropy": {
"s": "16"
},
"gl1.antialias.false.readPixels": {
"h": "abed055e93fb8",
"n": 36864
},
"gl1.antialias.false.samples": {
"s": "0"
},
"gl1.antialias.true.readPixels": {
"h": "155744fc8af4b9",
"n": 36864
},
"gl1.antialias.true.samples": {
"s": "4"
},
"gl1.attributes": {
"s": "{\"alpha\":true,\"antialias\":true,\"depth\":true,\"failIfMajorPerformanceCaveat\":false,\"powerPreference\":\"default\",\"premultipliedAlpha\":true,\"preserveDrawingBuffer\":true,\"stencil\":false}"
},
"gl1.blend.readPixels": {
"h": "cfef8e9072c0c",
"n": 16384
},
"gl1.depth_stencil.readPixels": {
"h": "eaa3d5d41cfb",
"n": 16384
},
"gl1.extension_objects": {
"s": "[[\"ANGLE_instanced_arrays\",4],[\"EXT_blend_minmax\",2],[\"EXT_clip_control\",7],[\"EXT_color_buffer_half_float\",4],[\"EXT_depth_clamp\",1],[\"EXT_float_blend\",0],[\"EXT_frag_depth\",0],[\"EXT_polygon_offset_clamp\",2],[\"EXT_shader_texture_lod\",0],[\"EXT_sRGB\",4],[\"EXT_texture_compression_bptc\",4],[\"EXT_texture_compression_rgtc\",4],[\"EXT_texture_filter_anisotropic\",2],[\"EXT_texture_mirror_clamp_to_edge\",1],[\"OES_element_index_uint\",0],[\"OES_fbo_render_mipmap\",0],[\"OES_standard_derivatives\",1],[\"OES_texture_float\",0],[\"OES_texture_float_linear\",0],[\"OES_texture_half_float\",1],[\"OES_texture_half_float_linear\",0],[\"OES_vertex_array_object\",5],[\"WEBGL_color_buffer_float\",4],[\"WEBGL_compressed_texture_s3tc\",4],[\"WEBGL_compressed_texture_s3tc_srgb\",4],[\"WEBGL_debug_renderer_info\",2],[\"WEBGL_debug_shaders\",1],[\"WEBGL_depth_texture\",1],[\"WEBGL_draw_buffers\",35],[\"WEBGL_lose_context\",2],[\"WEBGL_provoking_vertex\",4]]"
},
"gl1.extensions": {
"s": "[\"ANGLE_instanced_arrays\",\"EXT_blend_minmax\",\"EXT_clip_control\",\"EXT_color_buffer_half_float\",\"EXT_depth_clamp\",\"EXT_float_blend\",\"EXT_frag_depth\",\"EXT_polygon_offset_clamp\",\"EXT_shader_texture_lod\",\"EXT_sRGB\",\"EXT_texture_compression_bptc\",\"EXT_texture_compression_rgtc\",\"EXT_texture_filter_anisotropic\",\"EXT_texture_mirror_clamp_to_edge\",\"OES_element_index_uint\",\"OES_fbo_render_mipmap\",\"OES_standard_derivatives\",\"OES_texture_float\",\"OES_texture_float_linear\",\"OES_texture_half_float\",\"OES_texture_half_float_linear\",\"OES_vertex_array_object\",\"WEBGL_color_buffer_float\",\"WEBGL_compressed_texture_s3tc\",\"WEBGL_compressed_texture_s3tc_srgb\",\"WEBGL_debug_renderer_info\",\"WEBGL_debug_shaders\",\"WEBGL_depth_texture\",\"WEBGL_draw_buffers\",\"WEBGL_lose_context\",\"WEBGL_provoking_vertex\"]"
},
"gl1.lines_points.readPixels": {
"h": "1841f80a258941",
"n": 16384
},
"gl1.math.highp.readPixels": {
"h": "14f93cecd95f86",
"n": 16384
},
"gl1.math.mediump.readPixels": {
"h": "14f93cecd95f86",
"n": 16384
},
"gl1.params": {
"s": "{\"VERSION\":\"WebGL 1.0\",\"SHADING_LANGUAGE_VERSION\":\"WebGL GLSL ES 1.0\",\"VENDOR\":\"Mozilla\",\"RENDERER\":\"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0), or similar\",\"MAX_TEXTURE_SIZE\":16384,\"MAX_CUBE_MAP_TEXTURE_SIZE\":16384,\"MAX_RENDERBUFFER_SIZE\":16384,\"MAX_VIEWPORT_DIMS\":[32767,32767],\"ALIASED_LINE_WIDTH_RANGE\":[1,1],\"ALIASED_POINT_SIZE_RANGE\":[1,1024],\"MAX_VERTEX_ATTRIBS\":16,\"MAX_VARYING_VECTORS\":30,\"MAX_COMBINED_TEXTURE_IMAGE_UNITS\":32,\"MAX_VERTEX_TEXTURE_IMAGE_UNITS\":16,\"MAX_TEXTURE_IMAGE_UNITS\":16,\"MAX_VERTEX_UNIFORM_VECTORS\":4096,\"MAX_FRAGMENT_UNIFORM_VECTORS\":1024,\"RED_BITS\":8,\"GREEN_BITS\":8,\"BLUE_BITS\":8,\"ALPHA_BITS\":8,\"DEPTH_BITS\":24,\"STENCIL_BITS\":0,\"SAMPLES\":4,\"SAMPLE_BUFFERS\":1,\"SUBPIXEL_BITS\":4}"
},
"gl1.precision": {
"s": "[[\"VERTEX_SHADER\",\"LOW_FLOAT\",127,127,23],[\"VERTEX_SHADER\",\"MEDIUM_FLOAT\",127,127,23],[\"VERTEX_SHADER\",\"HIGH_FLOAT\",127,127,23],[\"VERTEX_SHADER\",\"LOW_INT\",31,30,0],[\"VERTEX_SHADER\",\"MEDIUM_INT\",31,30,0],[\"VERTEX_SHADER\",\"HIGH_INT\",31,30,0],[\"FRAGMENT_SHADER\",\"LOW_FLOAT\",127,127,23],[\"FRAGMENT_SHADER\",\"MEDIUM_FLOAT\",127,127,23],[\"FRAGMENT_SHADER\",\"HIGH_FLOAT\",127,127,23],[\"FRAGMENT_SHADER\",\"LOW_INT\",31,30,0],[\"FRAGMENT_SHADER\",\"MEDIUM_INT\",31,30,0],[\"FRAGMENT_SHADER\",\"HIGH_INT\",31,30,0]]"
},
"gl1.texture.linear.readPixels": {
"h": "5fdcdb999f3e0",
"n": 16384
},
"gl1.texture.mip.readPixels": {
"h": "5fdcdb999f3e0",
"n": 16384
},
"gl1.texture.nearest.readPixels": {
"h": "160f810aa6835f",
"n": 16384
},
"gl1.triangle.drawImage": {
"h": "81a61d733e561",
"n": 36864
},
"gl1.triangle.readPixels": {
"h": "12bb7ce7d2f21",
"n": 36864
},
"gl1.triangle.toDataURL_jpeg": {
"s": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCABgAGADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDxKiiivTPOCiiigAopDwOaro5MpfnB7e1enl+V1ceqjp/ZV/V9vnqJuyuWaKKK81pp2YwooopAFFFFABRRRQAUUUUAMlPy4HU0RR05U3NmrMUdfdZXbBYZR6vV/wBeR1VaHJTV9yMxHZkdqjrTijqre25hYMPuN+h9K8LOKMZT9vT67/5/5nl0qtpezl8itRRRXhHUFFFFABRRRQAUqjJxSVYt4+MnvW+GipVE3sjvy7CvE1kui1YsUdW4o6WKOrcUdevUx3mehjqe4kUdWTbrLEyOPlYYp8UdW4o64KuNvofG46DTujj7y3a1uGifnHIOOoqGu01LTRfW2wELIpyjEd/Q+1cYysjFXBVgcEEYINeepxk9DfB4pV42fxLf/MSiiimdgUUUUAOiQu4UfjWpFHjFQafD8pc9+BWnFHWM8Uqd0j7zJsv9hg1Vkvenr8un+fzEijq3FHSxR1bijriqY7zPPx1PcSKOrcUdLFHVuKOuCpjvM+Nx1PcSKOsHxdpDPF9ugUl0GJVUD7v978On0+ldTFHVuKOuVZk6U1JHys608LVVWHT8Txyit/xboR0m7WSBXNnL91jyEb+7n9Rn9cGsCvp6FeFeCqU3dM+qoV4YimqlN6MKdGhkdUXqTim1p6PAGLSnnHyipxNdYek6jPaybLpZljIYdbPf0W/9dy/DEFAAHAGBVuKOlijqYyQQsFmmjRsZwzAGvk54yU3Zas/VsfCFOOtkvuJIo6txR1SbUrCDbvuYzn+5838s0kniHT4du1pJc9didPzxWXLiqnwU2/kz4jH1qKuudfebMUdW4o65iTxbaogMFtM755DkKMfUZqGbxpNsAtrKNHzyZHLjH0GKn+zsfU2hb1a/zufI4tRn8LO4ijq3FHXmsvjPU3iKRrbRMejohJH5kj9KpzeKNZmiaNr5wp6lFVD+YAIprh/HVPicV83+iPncRldSts0j1e+02HUrCW0uQxilGDtOCOcgj6ECvHdb0yfSNSmtLhWBU/IxGN654YfX/wCt2ok1fUpI2jk1C8eNgVZWnYgg9QRmqNe7lGWYjAOSnUTi+luve9/0Ncsy6rgpSvO8X0t17hUiTyooVJZFA7BiKjor25RUlaSue3TqzpO9OTT8tB0kjyHMjs5xjLHNNooppJKyJlJzfNJ3YUUUUCCiiigAooooAKKKKAP/2Q=="
},
"gl1.unmasked": {
"s": "[\"Google Inc. (Intel)\",\"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0), or similar\"]"
},
"gl2.anisotropy": {
"s": "16"
},
"gl2.antialias.false.readPixels": {
"h": "abed055e93fb8",
"n": 36864
},
"gl2.antialias.false.samples": {
"s": "0"
},
"gl2.antialias.true.readPixels": {
"h": "155744fc8af4b9",
"n": 36864
},
"gl2.antialias.true.samples": {
"s": "4"
},
"gl2.attributes": {
"s": "{\"alpha\":true,\"antialias\":true,\"depth\":true,\"failIfMajorPerformanceCaveat\":false,\"powerPreference\":\"default\",\"premultipliedAlpha\":true,\"preserveDrawingBuffer\":true,\"stencil\":false}"
},
"gl2.blend.readPixels": {
"h": "cfef8e9072c0c",
"n": 16384
},
"gl2.depth_stencil.readPixels": {
"h": "eaa3d5d41cfb",
"n": 16384
},
"gl2.extension_objects": {
"s": "[[\"EXT_clip_control\",7],[\"EXT_color_buffer_float\",0],[\"EXT_depth_clamp\",1],[\"EXT_float_blend\",0],[\"EXT_polygon_offset_clamp\",2],[\"EXT_texture_compression_bptc\",4],[\"EXT_texture_compression_rgtc\",4],[\"EXT_texture_filter_anisotropic\",2],[\"EXT_texture_mirror_clamp_to_edge\",1],[\"EXT_texture_norm16\",8],[\"OES_draw_buffers_indexed\",7],[\"OES_texture_float_linear\",0],[\"OVR_multiview2\",5],[\"WEBGL_compressed_texture_s3tc\",4],[\"WEBGL_compressed_texture_s3tc_srgb\",4],[\"WEBGL_debug_renderer_info\",2],[\"WEBGL_debug_shaders\",1],[\"WEBGL_lose_context\",2],[\"WEBGL_provoking_vertex\",4]]"
},
"gl2.extensions": {
"s": "[\"EXT_clip_control\",\"EXT_color_buffer_float\",\"EXT_depth_clamp\",\"EXT_float_blend\",\"EXT_polygon_offset_clamp\",\"EXT_texture_compression_bptc\",\"EXT_texture_compression_rgtc\",\"EXT_texture_filter_anisotropic\",\"EXT_texture_mirror_clamp_to_edge\",\"EXT_texture_norm16\",\"OES_draw_buffers_indexed\",\"OES_texture_float_linear\",\"OVR_multiview2\",\"WEBGL_compressed_texture_s3tc\",\"WEBGL_compressed_texture_s3tc_srgb\",\"WEBGL_debug_renderer_info\",\"WEBGL_debug_shaders\",\"WEBGL_lose_context\",\"WEBGL_provoking_vertex\"]"
},
"gl2.float_target.readPixels": {
"h": "1ba8f4b0bbe2d8",
"n": 16384
},
"gl2.lines_points.readPixels": {
"h": "1841f80a258941",
"n": 16384
},
"gl2.math.highp.readPixels": {
"h": "14f93cecd95f86",
"n": 16384
},
"gl2.math.mediump.readPixels": {
"h": "14f93cecd95f86",
"n": 16384
},
"gl2.msaa_resolve.readPixels": {
"h": "1a2cbef856e591",
"n": 16384
},
"gl2.params": {
"s": "{\"VERSION\":\"WebGL 2.0\",\"SHADING_LANGUAGE_VERSION\":\"WebGL GLSL ES 3.00\",\"VENDOR\":\"Mozilla\",\"RENDERER\":\"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0), or similar\",\"MAX_TEXTURE_SIZE\":16384,\"MAX_CUBE_MAP_TEXTURE_SIZE\":16384,\"MAX_RENDERBUFFER_SIZE\":16384,\"MAX_VIEWPORT_DIMS\":[32767,32767],\"ALIASED_LINE_WIDTH_RANGE\":[1,1],\"ALIASED_POINT_SIZE_RANGE\":[1,1024],\"MAX_VERTEX_ATTRIBS\":16,\"MAX_VARYING_VECTORS\":30,\"MAX_COMBINED_TEXTURE_IMAGE_UNITS\":32,\"MAX_VERTEX_TEXTURE_IMAGE_UNITS\":16,\"MAX_TEXTURE_IMAGE_UNITS\":16,\"MAX_VERTEX_UNIFORM_VECTORS\":4096,\"MAX_FRAGMENT_UNIFORM_VECTORS\":1024,\"RED_BITS\":8,\"GREEN_BITS\":8,\"BLUE_BITS\":8,\"ALPHA_BITS\":8,\"DEPTH_BITS\":24,\"STENCIL_BITS\":0,\"SAMPLES\":4,\"SAMPLE_BUFFERS\":1,\"SUBPIXEL_BITS\":4,\"MAX_3D_TEXTURE_SIZE\":2048,\"MAX_ARRAY_TEXTURE_LAYERS\":2048,\"MAX_COLOR_ATTACHMENTS\":8,\"MAX_DRAW_BUFFERS\":8,\"MAX_ELEMENTS_INDICES\":2147483647,\"MAX_ELEMENTS_VERTICES\":2147483647,\"MAX_FRAGMENT_INPUT_COMPONENTS\":120,\"MAX_FRAGMENT_UNIFORM_BLOCKS\":12,\"MAX_FRAGMENT_UNIFORM_COMPONENTS\":4096,\"MAX_PROGRAM_TEXEL_OFFSET\":7,\"MAX_SAMPLES\":8,\"MAX_SERVER_WAIT_TIMEOUT\":0,\"MAX_TEXTURE_LOD_BIAS\":2,\"MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS\":120,\"MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS\":4,\"MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS\":4,\"MAX_UNIFORM_BLOCK_SIZE\":65536,\"MAX_UNIFORM_BUFFER_BINDINGS\":24,\"MAX_VARYING_COMPONENTS\":120,\"MAX_VERTEX_OUTPUT_COMPONENTS\":120,\"MAX_VERTEX_UNIFORM_BLOCKS\":12,\"MAX_VERTEX_UNIFORM_COMPONENTS\":16384,\"MIN_PROGRAM_TEXEL_OFFSET\":-8,\"MAX_COMBINED_UNIFORM_BLOCKS\":24,\"MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS\":200704,\"MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS\":212992,\"UNIFORM_BUFFER_OFFSET_ALIGNMENT\":256}"
},
"gl2.precision": {
"s": "[[\"VERTEX_SHADER\",\"LOW_FLOAT\",127,127,23],[\"VERTEX_SHADER\",\"MEDIUM_FLOAT\",127,127,23],[\"VERTEX_SHADER\",\"HIGH_FLOAT\",127,127,23],[\"VERTEX_SHADER\",\"LOW_INT\",31,30,0],[\"VERTEX_SHADER\",\"MEDIUM_INT\",31,30,0],[\"VERTEX_SHADER\",\"HIGH_INT\",31,30,0],[\"FRAGMENT_SHADER\",\"LOW_FLOAT\",127,127,23],[\"FRAGMENT_SHADER\",\"MEDIUM_FLOAT\",127,127,23],[\"FRAGMENT_SHADER\",\"HIGH_FLOAT\",127,127,23],[\"FRAGMENT_SHADER\",\"LOW_INT\",31,30,0],[\"FRAGMENT_SHADER\",\"MEDIUM_INT\",31,30,0],[\"FRAGMENT_SHADER\",\"HIGH_INT\",31,30,0]]"
},
"gl2.texture.linear.readPixels": {
"h": "5fdcdb999f3e0",
"n": 16384
},
"gl2.texture.mip.readPixels": {
"h": "5fdcdb999f3e0",
"n": 16384
},
"gl2.texture.nearest.readPixels": {
"h": "160f810aa6835f",
"n": 16384
},
"gl2.triangle.drawImage": {
"h": "81a61d733e561",
"n": 36864
},
"gl2.triangle.readPixels": {
"h": "12bb7ce7d2f21",
"n": 36864
},
"gl2.triangle.toDataURL_jpeg": {
"s": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCABgAGADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDxKiiivTPOCiiigAopDwOaro5MpfnB7e1enl+V1ceqjp/ZV/V9vnqJuyuWaKKK81pp2YwooopAFFFFABRRRQAUUUUAMlPy4HU0RR05U3NmrMUdfdZXbBYZR6vV/wBeR1VaHJTV9yMxHZkdqjrTijqre25hYMPuN+h9K8LOKMZT9vT67/5/5nl0qtpezl8itRRRXhHUFFFFABRRRQAUqjJxSVYt4+MnvW+GipVE3sjvy7CvE1kui1YsUdW4o6WKOrcUdevUx3mehjqe4kUdWTbrLEyOPlYYp8UdW4o64KuNvofG46DTujj7y3a1uGifnHIOOoqGu01LTRfW2wELIpyjEd/Q+1cYysjFXBVgcEEYINeepxk9DfB4pV42fxLf/MSiiimdgUUUUAOiQu4UfjWpFHjFQafD8pc9+BWnFHWM8Uqd0j7zJsv9hg1Vkvenr8un+fzEijq3FHSxR1bijriqY7zPPx1PcSKOrcUdLFHVuKOuCpjvM+Nx1PcSKOsHxdpDPF9ugUl0GJVUD7v978On0+ldTFHVuKOuVZk6U1JHys608LVVWHT8Txyit/xboR0m7WSBXNnL91jyEb+7n9Rn9cGsCvp6FeFeCqU3dM+qoV4YimqlN6MKdGhkdUXqTim1p6PAGLSnnHyipxNdYek6jPaybLpZljIYdbPf0W/9dy/DEFAAHAGBVuKOlijqYyQQsFmmjRsZwzAGvk54yU3Zas/VsfCFOOtkvuJIo6txR1SbUrCDbvuYzn+5838s0kniHT4du1pJc9didPzxWXLiqnwU2/kz4jH1qKuudfebMUdW4o65iTxbaogMFtM755DkKMfUZqGbxpNsAtrKNHzyZHLjH0GKn+zsfU2hb1a/zufI4tRn8LO4ijq3FHXmsvjPU3iKRrbRMejohJH5kj9KpzeKNZmiaNr5wp6lFVD+YAIprh/HVPicV83+iPncRldSts0j1e+02HUrCW0uQxilGDtOCOcgj6ECvHdb0yfSNSmtLhWBU/IxGN654YfX/wCt2ok1fUpI2jk1C8eNgVZWnYgg9QRmqNe7lGWYjAOSnUTi+luve9/0Ncsy6rgpSvO8X0t17hUiTyooVJZFA7BiKjor25RUlaSue3TqzpO9OTT8tB0kjyHMjs5xjLHNNooppJKyJlJzfNJ3YUUUUCCiiigAooooAKKKKAP/2Q=="
},
"gl2.unmasked": {
"s": "[\"Google Inc. (Intel)\",\"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0), or similar\"]"
},
"gpu.webgpu.features": {
"s": "{\"depth-clip-control\":true,\"depth32float-stencil8\":true,\"texture-compression-bc\":true,\"texture-compression-bc-sliced-3d\":true,\"texture-compression-etc2\":false,\"texture-compression-astc\":false,\"texture-compression-astc-sliced-3d\":false,\"timestamp-query\":true,\"indirect-first-instance\":true,\"shader-f16\":true,\"rg11b10ufloat-renderable\":true,\"bgra8unorm-storage\":true,\"float32-filterable\":true,\"float32-blendable\":true,\"clip-distances\":false,\"dual-source-blending\":true,\"subgroups\":false}"
},
"gpu.webgpu.info": {
"s": "{\"vendor\":\"\",\"architecture\":\"\",\"device\":\"\",\"description\":\"\"}"
},
"gpu.webgpu.limits": {
"s": "{\"maxTextureDimension1D\":16384,\"maxTextureDimension2D\":16384,\"maxTextureDimension3D\":2048,\"maxTextureArrayLayers\":2048,\"maxBindGroups\":8,\"maxBindGroupsPlusVertexBuffers\":24,\"maxBindingsPerBindGroup\":4294967295,\"maxDynamicUniformBuffersPerPipelineLayout\":8,\"maxDynamicStorageBuffersPerPipelineLayout\":4,\"maxSampledTexturesPerShaderStage\":64,\"maxSamplersPerShaderStage\":64,\"maxStorageBuffersPerShaderStage\":64,\"maxStorageTexturesPerShaderStage\":64,\"maxUniformBuffersPerShaderStage\":64,\"maxUniformBufferBindingSize\":65536,\"maxStorageBufferBindingSize\":2147483644,\"minUniformBufferOffsetAlignment\":256,\"minStorageBufferOffsetAlignment\":32,\"maxVertexBuffers\":16,\"maxBufferSize\":2147483644,\"maxVertexAttributes\":30,\"maxVertexBufferArrayStride\":2048,\"maxInterStageShaderVariables\":31,\"maxColorAttachments\":8,\"maxColorAttachmentBytesPerSample\":128,\"maxComputeWorkgroupStorageSize\":32768,\"maxComputeInvocationsPerWorkgroup\":1024,\"maxComputeWorkgroupSizeX\":1024,\"maxComputeWorkgroupSizeY\":1024,\"maxComputeWorkgroupSizeZ\":64,\"maxComputeWorkgroupsPerDimension\":65535}"
},
"worker.webgl": {
"s": "{\"vendor\":\"Mozilla\",\"renderer\":\"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0), or similar\",\"unmasked\":[\"Google Inc. (Intel)\",\"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0), or similar\"],\"exts\":[\"ANGLE_instanced_arrays\",\"EXT_blend_minmax\",\"EXT_clip_control\",\"EXT_color_buffer_half_float\",\"EXT_depth_clamp\",\"EXT_float_blend\",\"EXT_frag_depth\",\"EXT_polygon_offset_clamp\",\"EXT_shader_texture_lod\",\"EXT_sRGB\",\"EXT_texture_compression_bptc\",\"EXT_texture_compression_rgtc\",\"EXT_texture_filter_anisotropic\",\"EXT_texture_mirror_clamp_to_edge\",\"OES_element_index_uint\",\"OES_fbo_render_mipmap\",\"OES_standard_derivatives\",\"OES_texture_float\",\"OES_texture_float_linear\",\"OES_texture_half_float\",\"OES_texture_half_float_linear\",\"OES_vertex_array_object\",\"WEBGL_color_buffer_float\",\"WEBGL_compressed_texture_s3tc\",\"WEBGL_compressed_texture_s3tc_srgb\",\"WEBGL_debug_renderer_info\",\"WEBGL_debug_shaders\",\"WEBGL_depth_texture\",\"WEBGL_draw_buffers\",\"WEBGL_lose_context\",\"WEBGL_provoking_vertex\"],\"px\":[64,128,191,255,64,128,191,255,64,128,191,255,64,128,191,255]}"
}
},
"pngs": {
"c2d.composite.png": {
"n": 2414,
"w": 256,
"h": 128,
"ct": 6,
"sha256": "fb585f18240eb1a787a5b146d6332a0376dae76f8c8716e99f68fbbf9eff905e"
},
"c2d.composite.toBlob": {
"n": 1794,
"w": 256,
"h": 128,
"ct": 6,
"sha256": "fb585f18240eb1a787a5b146d6332a0376dae76f8c8716e99f68fbbf9eff905e"
},
"c2d.gradtext.png": {
"n": 56850,
"w": 420,
"h": 210,
"ct": 6,
"sha256": "a294763c6eca0c9178d09052cfaa5ac92932d8cf32909f31bbb387810d473310"
},
"c2d.image.png": {
"n": 19502,
"w": 160,
"h": 120,
"ct": 6,
"sha256": "51bc3789f2e238dfbf8899eb7a965a4f04d3e0e7f2246b1bd3cfdc9597bd2a77"
},
"c2d.image.toBlob": {
"n": 14610,
"w": 160,
"h": 120,
"ct": 6,
"sha256": "51bc3789f2e238dfbf8899eb7a965a4f04d3e0e7f2246b1bd3cfdc9597bd2a77"
},
"c2d.offscreen.convertToBlob": {
"n": 2687,
"w": 160,
"h": 80,
"ct": 6,
"sha256": "38b7fa4aa1d61a5bae5b92e8b9216ff61ce4d4a8d15cc0fa6d8a8c8441a3fdb8"
},
"c2d.scale.high.png": {
"n": 47314,
"w": 220,
"h": 130,
"ct": 6,
"sha256": "8672b8676f90d662b4809e56c55da58e05be4e72b2f7c543b33da4bdafb0ce21"
},
"c2d.scale.low.png": {
"n": 47314,
"w": 220,
"h": 130,
"ct": 6,
"sha256": "8672b8676f90d662b4809e56c55da58e05be4e72b2f7c543b33da4bdafb0ce21"
},
"c2d.scale.medium.png": {
"n": 47314,
"w": 220,
"h": 130,
"ct": 6,
"sha256": "8672b8676f90d662b4809e56c55da58e05be4e72b2f7c543b33da4bdafb0ce21"
},
"c2d.scale.off.png": {
"n": 20890,
"w": 220,
"h": 130,
"ct": 6,
"sha256": "c28700e28636d69dfe9bf293fadebae1fdf970949ac90147836ab1837065f46d"
},
"c2d.shapes.png": {
"n": 19226,
"w": 256,
"h": 160,
"ct": 6,
"sha256": "89ee57c100f4682099bd3a5f2de56c5b31091dae253bd7e3db4f254fb8b9e6a3"
},
"c2d.shapes.toBlob": {
"n": 14402,
"w": 256,
"h": 160,
"ct": 6,
"sha256": "89ee57c100f4682099bd3a5f2de56c5b31091dae253bd7e3db4f254fb8b9e6a3"
},
"c2d.text.png": {
"n": 51610,
"w": 520,
"h": 412,
"ct": 6,
"sha256": "1c56511f78721be0423bbcef100bf7b52e9997da498bd1f771d0d8348a791d3b"
},
"c2d.text.toBlob": {
"n": 38691,
"w": 520,
"h": 412,
"ct": 6,
"sha256": "1c56511f78721be0423bbcef100bf7b52e9997da498bd1f771d0d8348a791d3b"
},
"gl1.triangle.toDataURL": {
"n": 7470,
"w": 96,
"h": 96,
"ct": 6,
"sha256": "3f24afcf21a411e18ef9256e558a30ec589bbb51923fedf485cd0e6a2dcd9919"
},
"gl2.triangle.toDataURL": {
"n": 7470,
"w": 96,
"h": 96,
"ct": 6,
"sha256": "3f24afcf21a411e18ef9256e558a30ec589bbb51923fedf485cd0e6a2dcd9919"
}
}
}
+409
View File
@@ -0,0 +1,409 @@
{
"os": "windows",
"source": "GitHub Actions run 43661728392 (workflow page-bytes-reference-hunt, runner image win22 20261112.366.7), wrapper commit 455d5619e5, invisible-core 64.71.0, engine firefox-64_159.0_20261114003728, seed 42, locale en-US, timezone Europe/Rome, headless=True; 2 launches, every key below is equal in all of them. `pngs`: the PNG keys, compared on their length and decoded pixels because every PNG carries a per-launch chunk.",
"keys": {
"c2d.composite.getImageData": {
"h": "df65ebe03bf31",
"n": 131072
},
"c2d.composite.jpeg": {
"h": "1c1b75006c5984",
"n": 11535
},
"c2d.composite.webp": {
"h": "182ab2238ae6c0",
"n": 5431
},
"c2d.gradtext.getImageData": {
"h": "42edf4d4d5394",
"n": 352800
},
"c2d.image.getImageData": {
"h": "8218d41a1794c",
"n": 76800
},
"c2d.image.jpeg": {
"h": "125de65c968e30",
"n": 7315
},
"c2d.image.webp": {
"h": "26ea5dc80f98c",
"n": 5659
},
"c2d.measure": {
"h": "a731f7d3287e2",
"n": 9495
},
"c2d.offscreen.getImageData": {
"h": "1d9666b372acb1",
"n": 51200
},
"c2d.scale.high.getImageData": {
"h": "10d3beda5ba224",
"n": 114400
},
"c2d.scale.low.getImageData": {
"h": "10d3beda5ba224",
"n": 114400
},
"c2d.scale.medium.getImageData": {
"h": "10d3beda5ba224",
"n": 114400
},
"c2d.scale.off.getImageData": {
"h": "c673134829639",
"n": 114400
},
"c2d.shapes.getImageData": {
"h": "18fe9a0f7336da",
"n": 163840
},
"c2d.shapes.jpeg": {
"h": "18d82802030ab3",
"n": 6975
},
"c2d.shapes.webp": {
"h": "1ec9fa4e39f8de",
"n": 3287
},
"c2d.text.getImageData": {
"h": "11041652732d2c",
"n": 856960
},
"c2d.text.jpeg": {
"h": "15a47ca2d73ab",
"n": 43163
},
"c2d.text.webp": {
"h": "59e03617b84b1",
"n": 26943
},
"dom.fonts_check": {
"s": "[[\"16px sans-serif\",true],[\"20px serif\",true],[\"18px monospace\",true],[\"bold 16px Arial\",true],[\"italic 15px 'Segoe UI'\",true],[\"16px 'Times New Roman'\",true],[\"16px Calibri\",true],[\"14px Consolas\",true],[\"16px Verdana\",true],[\"16px Tahoma\",true],[\"17px Georgia\",true],[\"16px 'Segoe UI Emoji'\",true],[\"16px 'Microsoft YaHei'\",true],[\"16px 'Yu Gothic'\",true]]"
},
"dom.paragraphs": {
"s": "[[\"16px sans-serif\",200,21],[\"15px 'Times New Roman'\",200,20],[\"14px Consolas\",200,19]]"
},
"dom.span_boxes": {
"h": "157207c863aeec",
"n": 5863
},
"dom.system_colors": {
"s": "[[\"Canvas\",\"rgb(255, 255, 255)\"],[\"CanvasText\",\"rgb(0, 0, 0)\"],[\"ButtonFace\",\"rgb(233, 233, 237)\"],[\"ButtonText\",\"rgb(0, 0, 0)\"],[\"ButtonBorder\",\"rgb(129, 127, 132)\"],[\"Field\",\"rgb(255, 255, 255)\"],[\"FieldText\",\"rgb(0, 0, 0)\"],[\"Highlight\",\"rgb(0, 120, 215)\"],[\"HighlightText\",\"rgb(255, 255, 255)\"],[\"GrayText\",\"rgb(109, 109, 109)\"],[\"LinkText\",\"rgb(0, 0, 238)\"],[\"VisitedText\",\"rgb(85, 26, 139)\"],[\"ActiveText\",\"rgb(238, 0, 0)\"],[\"Mark\",\"rgb(255, 255, 0)\"],[\"MarkText\",\"rgb(0, 0, 0)\"],[\"AccentColor\",\"rgb(0, 96, 223)\"],[\"AccentColorText\",\"rgb(255, 255, 255)\"],[\"SelectedItem\",\"rgb(0, 120, 215)\"],[\"SelectedItemText\",\"rgb(255, 255, 255)\"]]"
},
"env.dpr": {
"s": "1"
},
"env.hw": {
"s": "8"
},
"env.lang": {
"s": "[\"en-US\",\"en\"]"
},
"env.mq": {
"s": "[true,false,false,false,false,false,false]"
},
"env.oscpu": {
"s": "Windows NT 10.0; Win64; x64"
},
"env.platform": {
"s": "Win32"
},
"env.screen": {
"s": "[1920,1080,1920,1032,24,24]"
},
"env.ua": {
"s": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:159.0) Gecko/20100101 Firefox/159.0"
},
"gl1.anisotropy": {
"s": "16"
},
"gl1.antialias.false.readPixels": {
"h": "abed055e93fb8",
"n": 36864
},
"gl1.antialias.false.samples": {
"s": "0"
},
"gl1.antialias.true.readPixels": {
"h": "155744fc8af4b9",
"n": 36864
},
"gl1.antialias.true.samples": {
"s": "4"
},
"gl1.attributes": {
"s": "{\"alpha\":true,\"antialias\":true,\"depth\":true,\"failIfMajorPerformanceCaveat\":false,\"powerPreference\":\"default\",\"premultipliedAlpha\":true,\"preserveDrawingBuffer\":true,\"stencil\":false}"
},
"gl1.blend.readPixels": {
"h": "1e61b0c76b34d",
"n": 16384
},
"gl1.depth_stencil.readPixels": {
"h": "eaa3d5d41cfb",
"n": 16384
},
"gl1.extension_objects": {
"s": "[[\"ANGLE_instanced_arrays\",4],[\"EXT_blend_minmax\",2],[\"EXT_clip_control\",7],[\"EXT_color_buffer_half_float\",4],[\"EXT_depth_clamp\",1],[\"EXT_float_blend\",0],[\"EXT_frag_depth\",0],[\"EXT_polygon_offset_clamp\",2],[\"EXT_shader_texture_lod\",0],[\"EXT_sRGB\",4],[\"EXT_texture_compression_bptc\",4],[\"EXT_texture_compression_rgtc\",4],[\"EXT_texture_filter_anisotropic\",2],[\"EXT_texture_mirror_clamp_to_edge\",1],[\"OES_element_index_uint\",0],[\"OES_fbo_render_mipmap\",0],[\"OES_standard_derivatives\",1],[\"OES_texture_float\",0],[\"OES_texture_float_linear\",0],[\"OES_texture_half_float\",1],[\"OES_texture_half_float_linear\",0],[\"OES_vertex_array_object\",5],[\"WEBGL_color_buffer_float\",4],[\"WEBGL_compressed_texture_s3tc\",4],[\"WEBGL_compressed_texture_s3tc_srgb\",4],[\"WEBGL_debug_renderer_info\",2],[\"WEBGL_debug_shaders\",1],[\"WEBGL_depth_texture\",1],[\"WEBGL_draw_buffers\",35],[\"WEBGL_lose_context\",2],[\"WEBGL_provoking_vertex\",4]]"
},
"gl1.extensions": {
"s": "[\"ANGLE_instanced_arrays\",\"EXT_blend_minmax\",\"EXT_clip_control\",\"EXT_color_buffer_half_float\",\"EXT_depth_clamp\",\"EXT_float_blend\",\"EXT_frag_depth\",\"EXT_polygon_offset_clamp\",\"EXT_shader_texture_lod\",\"EXT_sRGB\",\"EXT_texture_compression_bptc\",\"EXT_texture_compression_rgtc\",\"EXT_texture_filter_anisotropic\",\"EXT_texture_mirror_clamp_to_edge\",\"OES_element_index_uint\",\"OES_fbo_render_mipmap\",\"OES_standard_derivatives\",\"OES_texture_float\",\"OES_texture_float_linear\",\"OES_texture_half_float\",\"OES_texture_half_float_linear\",\"OES_vertex_array_object\",\"WEBGL_color_buffer_float\",\"WEBGL_compressed_texture_s3tc\",\"WEBGL_compressed_texture_s3tc_srgb\",\"WEBGL_debug_renderer_info\",\"WEBGL_debug_shaders\",\"WEBGL_depth_texture\",\"WEBGL_draw_buffers\",\"WEBGL_lose_context\",\"WEBGL_provoking_vertex\"]"
},
"gl1.lines_points.readPixels": {
"h": "1841f80a258941",
"n": 16384
},
"gl1.math.highp.readPixels": {
"h": "85fe168c6de19",
"n": 16384
},
"gl1.math.mediump.readPixels": {
"h": "85fe168c6de19",
"n": 16384
},
"gl1.params": {
"s": "{\"VERSION\":\"WebGL 1.0\",\"SHADING_LANGUAGE_VERSION\":\"WebGL GLSL ES 1.0\",\"VENDOR\":\"Mozilla\",\"RENDERER\":\"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0), or similar\",\"MAX_TEXTURE_SIZE\":16384,\"MAX_CUBE_MAP_TEXTURE_SIZE\":16384,\"MAX_RENDERBUFFER_SIZE\":16384,\"MAX_VIEWPORT_DIMS\":[32767,32767],\"ALIASED_LINE_WIDTH_RANGE\":[1,1],\"ALIASED_POINT_SIZE_RANGE\":[1,1024],\"MAX_VERTEX_ATTRIBS\":16,\"MAX_VARYING_VECTORS\":30,\"MAX_COMBINED_TEXTURE_IMAGE_UNITS\":32,\"MAX_VERTEX_TEXTURE_IMAGE_UNITS\":16,\"MAX_TEXTURE_IMAGE_UNITS\":16,\"MAX_VERTEX_UNIFORM_VECTORS\":4096,\"MAX_FRAGMENT_UNIFORM_VECTORS\":1024,\"RED_BITS\":8,\"GREEN_BITS\":8,\"BLUE_BITS\":8,\"ALPHA_BITS\":8,\"DEPTH_BITS\":24,\"STENCIL_BITS\":0,\"SAMPLES\":4,\"SAMPLE_BUFFERS\":1,\"SUBPIXEL_BITS\":4}"
},
"gl1.precision": {
"s": "[[\"VERTEX_SHADER\",\"LOW_FLOAT\",127,127,23],[\"VERTEX_SHADER\",\"MEDIUM_FLOAT\",127,127,23],[\"VERTEX_SHADER\",\"HIGH_FLOAT\",127,127,23],[\"VERTEX_SHADER\",\"LOW_INT\",31,30,0],[\"VERTEX_SHADER\",\"MEDIUM_INT\",31,30,0],[\"VERTEX_SHADER\",\"HIGH_INT\",31,30,0],[\"FRAGMENT_SHADER\",\"LOW_FLOAT\",127,127,23],[\"FRAGMENT_SHADER\",\"MEDIUM_FLOAT\",127,127,23],[\"FRAGMENT_SHADER\",\"HIGH_FLOAT\",127,127,23],[\"FRAGMENT_SHADER\",\"LOW_INT\",31,30,0],[\"FRAGMENT_SHADER\",\"MEDIUM_INT\",31,30,0],[\"FRAGMENT_SHADER\",\"HIGH_INT\",31,30,0]]"
},
"gl1.texture.linear.readPixels": {
"h": "12a052fdb7d89f",
"n": 16384
},
"gl1.texture.mip.readPixels": {
"h": "12a052fdb7d89f",
"n": 16384
},
"gl1.texture.nearest.readPixels": {
"h": "160f810aa6835f",
"n": 16384
},
"gl1.triangle.drawImage": {
"h": "1f2476721e653d",
"n": 36864
},
"gl1.triangle.readPixels": {
"h": "e35b6ac5b7d59",
"n": 36864
},
"gl1.triangle.toDataURL_jpeg": {
"s": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCABgAGADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDxKiiivTPOCiiigAopDwOaro5MpfnB7e1enl+V1ceqjp/ZV/V9vnqJuyuWaKKK81pp2YwooopAFFFFABRRRQAUUUUAMlPy4HU0RR05U3NmrMUdfdZXbBYZR6vV/wBeR1VaHJTV9yMxHZkdqjrTijqre25hYMPuN+h9K8LOKMZT9vDrv/n/AJnl0qtpezl8itRRRXhHUFFFFABRRRQAUqjJxSVYt4+MnvW+GipVE3sjvy7CvE1kui1YsUdW4o6WKOrcUdevUx3mehjqe4kUdWTbrLEyOPlYYp8UdW4o64KuNvofG46DTujj7y3a1uGifnHIOOoqGu01LTRfW2wELIpyjEd/Q+1cYysjFXBVgcEEYINeepxk9DfB4pV42fxLf/MSiiimdgUUUUAOiQu4UfjWpFHjFQafD8pc9+BWnFHWM8Uqd0j7zJsv9hg1Vkvenr8un+fzEijq3FHSxR1bijriqY7zPPx1PcSKOrcUdLFHVuKOuCpjvM+Nx1PcSKOsHxdpDPF9ugUl0GJVUD7v978On0+ldTFHVuKOuVZk6U1JHys608LVVWHT8Txyit/xboR0m7WSBXNnL91jyEb+7n9Rn9cGsCvp6FeFeCqU3dM+qoV4YimqlN6MKdGhkdUXqTim1p6PAGLSnnHyipxNdYek6jPaybLpZljIYdbPf0W/9dy/DEFAAHAGBVuKOlijqYyQQsFmmjRsZwzAGvk54yU3Zas/VsfCFOOtkvuJIo6txR1SbUrCDbvuYzn+5838s0kniHT4du1pJc9didPzxWXLiqnwU2/kz4jH1qKuudfebMUdW4o65iTxbaogMFtM755DkKMfUZqGbxpNsAtrKNHzyZHLjH0GKn+zsfU2hb1a/wA7nyOLUZ/CzuIo6txR15rL4z1N4ika20THo6ISR+ZI/Sqc3ijWZomja+cKepRVQ/mACKa4fx1T4nFfN/oj53EZXUrbNI9XvtNh1KwltLkMYpRg7TgjnII+hArx3W9Mn0jUprS4VgVPyMRjeueGH1/+t2ok1fUpI2jk1C8eNgVZWnYgg9QRmqNe7lGWYjAOSnUTi+luve9/0Ncsy6rgpSvO8X0t17hUiTyooVJZFA7BiKjor25RUlaSue3TqzpO9OTT8tB0kjyHMjs5xjLHNNooppJKyJlJzfNJ3YUUUUCCiiigAooooAKKKKAP/9k="
},
"gl1.unmasked": {
"s": "[\"Google Inc. (Intel)\",\"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0), or similar\"]"
},
"gl2.anisotropy": {
"s": "16"
},
"gl2.antialias.false.readPixels": {
"h": "abed055e93fb8",
"n": 36864
},
"gl2.antialias.false.samples": {
"s": "0"
},
"gl2.antialias.true.readPixels": {
"h": "155744fc8af4b9",
"n": 36864
},
"gl2.antialias.true.samples": {
"s": "4"
},
"gl2.attributes": {
"s": "{\"alpha\":true,\"antialias\":true,\"depth\":true,\"failIfMajorPerformanceCaveat\":false,\"powerPreference\":\"default\",\"premultipliedAlpha\":true,\"preserveDrawingBuffer\":true,\"stencil\":false}"
},
"gl2.blend.readPixels": {
"h": "1e61b0c76b34d",
"n": 16384
},
"gl2.depth_stencil.readPixels": {
"h": "eaa3d5d41cfb",
"n": 16384
},
"gl2.extension_objects": {
"s": "[[\"EXT_clip_control\",7],[\"EXT_color_buffer_float\",0],[\"EXT_depth_clamp\",1],[\"EXT_float_blend\",0],[\"EXT_polygon_offset_clamp\",2],[\"EXT_texture_compression_bptc\",4],[\"EXT_texture_compression_rgtc\",4],[\"EXT_texture_filter_anisotropic\",2],[\"EXT_texture_mirror_clamp_to_edge\",1],[\"EXT_texture_norm16\",8],[\"OES_draw_buffers_indexed\",7],[\"OES_texture_float_linear\",0],[\"OVR_multiview2\",5],[\"WEBGL_compressed_texture_s3tc\",4],[\"WEBGL_compressed_texture_s3tc_srgb\",4],[\"WEBGL_debug_renderer_info\",2],[\"WEBGL_debug_shaders\",1],[\"WEBGL_lose_context\",2],[\"WEBGL_provoking_vertex\",4]]"
},
"gl2.extensions": {
"s": "[\"EXT_clip_control\",\"EXT_color_buffer_float\",\"EXT_depth_clamp\",\"EXT_float_blend\",\"EXT_polygon_offset_clamp\",\"EXT_texture_compression_bptc\",\"EXT_texture_compression_rgtc\",\"EXT_texture_filter_anisotropic\",\"EXT_texture_mirror_clamp_to_edge\",\"EXT_texture_norm16\",\"OES_draw_buffers_indexed\",\"OES_texture_float_linear\",\"OVR_multiview2\",\"WEBGL_compressed_texture_s3tc\",\"WEBGL_compressed_texture_s3tc_srgb\",\"WEBGL_debug_renderer_info\",\"WEBGL_debug_shaders\",\"WEBGL_lose_context\",\"WEBGL_provoking_vertex\"]"
},
"gl2.float_target.readPixels": {
"h": "4036e3357974d",
"n": 16384
},
"gl2.lines_points.readPixels": {
"h": "1841f80a258941",
"n": 16384
},
"gl2.math.highp.readPixels": {
"h": "85fe168c6de19",
"n": 16384
},
"gl2.math.mediump.readPixels": {
"h": "85fe168c6de19",
"n": 16384
},
"gl2.msaa_resolve.readPixels": {
"h": "1a2cbef856e591",
"n": 16384
},
"gl2.params": {
"s": "{\"VERSION\":\"WebGL 2.0\",\"SHADING_LANGUAGE_VERSION\":\"WebGL GLSL ES 3.00\",\"VENDOR\":\"Mozilla\",\"RENDERER\":\"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0), or similar\",\"MAX_TEXTURE_SIZE\":16384,\"MAX_CUBE_MAP_TEXTURE_SIZE\":16384,\"MAX_RENDERBUFFER_SIZE\":16384,\"MAX_VIEWPORT_DIMS\":[32767,32767],\"ALIASED_LINE_WIDTH_RANGE\":[1,1],\"ALIASED_POINT_SIZE_RANGE\":[1,1024],\"MAX_VERTEX_ATTRIBS\":16,\"MAX_VARYING_VECTORS\":30,\"MAX_COMBINED_TEXTURE_IMAGE_UNITS\":32,\"MAX_VERTEX_TEXTURE_IMAGE_UNITS\":16,\"MAX_TEXTURE_IMAGE_UNITS\":16,\"MAX_VERTEX_UNIFORM_VECTORS\":4096,\"MAX_FRAGMENT_UNIFORM_VECTORS\":1024,\"RED_BITS\":8,\"GREEN_BITS\":8,\"BLUE_BITS\":8,\"ALPHA_BITS\":8,\"DEPTH_BITS\":24,\"STENCIL_BITS\":0,\"SAMPLES\":4,\"SAMPLE_BUFFERS\":1,\"SUBPIXEL_BITS\":4,\"MAX_3D_TEXTURE_SIZE\":2048,\"MAX_ARRAY_TEXTURE_LAYERS\":2048,\"MAX_COLOR_ATTACHMENTS\":8,\"MAX_DRAW_BUFFERS\":8,\"MAX_ELEMENTS_INDICES\":2147483647,\"MAX_ELEMENTS_VERTICES\":2147483647,\"MAX_FRAGMENT_INPUT_COMPONENTS\":120,\"MAX_FRAGMENT_UNIFORM_BLOCKS\":12,\"MAX_FRAGMENT_UNIFORM_COMPONENTS\":4096,\"MAX_PROGRAM_TEXEL_OFFSET\":7,\"MAX_SAMPLES\":8,\"MAX_SERVER_WAIT_TIMEOUT\":0,\"MAX_TEXTURE_LOD_BIAS\":2,\"MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS\":120,\"MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS\":4,\"MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS\":4,\"MAX_UNIFORM_BLOCK_SIZE\":65536,\"MAX_UNIFORM_BUFFER_BINDINGS\":24,\"MAX_VARYING_COMPONENTS\":120,\"MAX_VERTEX_OUTPUT_COMPONENTS\":120,\"MAX_VERTEX_UNIFORM_BLOCKS\":12,\"MAX_VERTEX_UNIFORM_COMPONENTS\":16384,\"MIN_PROGRAM_TEXEL_OFFSET\":-8,\"MAX_COMBINED_UNIFORM_BLOCKS\":24,\"MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS\":200704,\"MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS\":212992,\"UNIFORM_BUFFER_OFFSET_ALIGNMENT\":256}"
},
"gl2.precision": {
"s": "[[\"VERTEX_SHADER\",\"LOW_FLOAT\",127,127,23],[\"VERTEX_SHADER\",\"MEDIUM_FLOAT\",127,127,23],[\"VERTEX_SHADER\",\"HIGH_FLOAT\",127,127,23],[\"VERTEX_SHADER\",\"LOW_INT\",31,30,0],[\"VERTEX_SHADER\",\"MEDIUM_INT\",31,30,0],[\"VERTEX_SHADER\",\"HIGH_INT\",31,30,0],[\"FRAGMENT_SHADER\",\"LOW_FLOAT\",127,127,23],[\"FRAGMENT_SHADER\",\"MEDIUM_FLOAT\",127,127,23],[\"FRAGMENT_SHADER\",\"HIGH_FLOAT\",127,127,23],[\"FRAGMENT_SHADER\",\"LOW_INT\",31,30,0],[\"FRAGMENT_SHADER\",\"MEDIUM_INT\",31,30,0],[\"FRAGMENT_SHADER\",\"HIGH_INT\",31,30,0]]"
},
"gl2.texture.linear.readPixels": {
"h": "12a052fdb7d89f",
"n": 16384
},
"gl2.texture.mip.readPixels": {
"h": "12a052fdb7d89f",
"n": 16384
},
"gl2.texture.nearest.readPixels": {
"h": "160f810aa6835f",
"n": 16384
},
"gl2.triangle.drawImage": {
"h": "1f2476721e653d",
"n": 36864
},
"gl2.triangle.readPixels": {
"h": "e35b6ac5b7d59",
"n": 36864
},
"gl2.triangle.toDataURL_jpeg": {
"s": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCABgAGADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDxKiiivTPOCiiigAopDwOaro5MpfnB7e1enl+V1ceqjp/ZV/V9vnqJuyuWaKKK81pp2YwooopAFFFFABRRRQAUUUUAMlPy4HU0RR05U3NmrMUdfdZXbBYZR6vV/wBeR1VaHJTV9yMxHZkdqjrTijqre25hYMPuN+h9K8LOKMZT9vDrv/n/AJnl0qtpezl8itRRRXhHUFFFFABRRRQAUqjJxSVYt4+MnvW+GipVE3sjvy7CvE1kui1YsUdW4o6WKOrcUdevUx3mehjqe4kUdWTbrLEyOPlYYp8UdW4o64KuNvofG46DTujj7y3a1uGifnHIOOoqGu01LTRfW2wELIpyjEd/Q+1cYysjFXBVgcEEYINeepxk9DfB4pV42fxLf/MSiiimdgUUUUAOiQu4UfjWpFHjFQafD8pc9+BWnFHWM8Uqd0j7zJsv9hg1Vkvenr8un+fzEijq3FHSxR1bijriqY7zPPx1PcSKOrcUdLFHVuKOuCpjvM+Nx1PcSKOsHxdpDPF9ugUl0GJVUD7v978On0+ldTFHVuKOuVZk6U1JHys608LVVWHT8Txyit/xboR0m7WSBXNnL91jyEb+7n9Rn9cGsCvp6FeFeCqU3dM+qoV4YimqlN6MKdGhkdUXqTim1p6PAGLSnnHyipxNdYek6jPaybLpZljIYdbPf0W/9dy/DEFAAHAGBVuKOlijqYyQQsFmmjRsZwzAGvk54yU3Zas/VsfCFOOtkvuJIo6txR1SbUrCDbvuYzn+5838s0kniHT4du1pJc9didPzxWXLiqnwU2/kz4jH1qKuudfebMUdW4o65iTxbaogMFtM755DkKMfUZqGbxpNsAtrKNHzyZHLjH0GKn+zsfU2hb1a/wA7nyOLUZ/CzuIo6txR15rL4z1N4ika20THo6ISR+ZI/Sqc3ijWZomja+cKepRVQ/mACKa4fx1T4nFfN/oj53EZXUrbNI9XvtNh1KwltLkMYpRg7TgjnII+hArx3W9Mn0jUprS4VgVPyMRjeueGH1/+t2ok1fUpI2jk1C8eNgVZWnYgg9QRmqNe7lGWYjAOSnUTi+luve9/0Ncsy6rgpSvO8X0t17hUiTyooVJZFA7BiKjor25RUlaSue3TqzpO9OTT8tB0kjyHMjs5xjLHNNooppJKyJlJzfNJ3YUUUUCCiiigAooooAKKKKAP/9k="
},
"gl2.unmasked": {
"s": "[\"Google Inc. (Intel)\",\"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0), or similar\"]"
},
"gpu.webgpu.features": {
"s": "{\"depth-clip-control\":true,\"depth32float-stencil8\":true,\"texture-compression-bc\":true,\"texture-compression-bc-sliced-3d\":true,\"texture-compression-etc2\":false,\"texture-compression-astc\":false,\"texture-compression-astc-sliced-3d\":false,\"timestamp-query\":true,\"indirect-first-instance\":true,\"shader-f16\":true,\"rg11b10ufloat-renderable\":true,\"bgra8unorm-storage\":true,\"float32-filterable\":true,\"float32-blendable\":true,\"clip-distances\":false,\"dual-source-blending\":true,\"subgroups\":false}"
},
"gpu.webgpu.info": {
"s": "{\"vendor\":\"\",\"architecture\":\"\",\"device\":\"\",\"description\":\"\"}"
},
"gpu.webgpu.limits": {
"s": "{\"maxTextureDimension1D\":16384,\"maxTextureDimension2D\":16384,\"maxTextureDimension3D\":2048,\"maxTextureArrayLayers\":2048,\"maxBindGroups\":8,\"maxBindGroupsPlusVertexBuffers\":24,\"maxBindingsPerBindGroup\":4294967295,\"maxDynamicUniformBuffersPerPipelineLayout\":8,\"maxDynamicStorageBuffersPerPipelineLayout\":4,\"maxSampledTexturesPerShaderStage\":64,\"maxSamplersPerShaderStage\":64,\"maxStorageBuffersPerShaderStage\":64,\"maxStorageTexturesPerShaderStage\":64,\"maxUniformBuffersPerShaderStage\":64,\"maxUniformBufferBindingSize\":65536,\"maxStorageBufferBindingSize\":2147483644,\"minUniformBufferOffsetAlignment\":256,\"minStorageBufferOffsetAlignment\":32,\"maxVertexBuffers\":16,\"maxBufferSize\":2147483644,\"maxVertexAttributes\":30,\"maxVertexBufferArrayStride\":2048,\"maxInterStageShaderVariables\":31,\"maxColorAttachments\":8,\"maxColorAttachmentBytesPerSample\":128,\"maxComputeWorkgroupStorageSize\":32768,\"maxComputeInvocationsPerWorkgroup\":1024,\"maxComputeWorkgroupSizeX\":1024,\"maxComputeWorkgroupSizeY\":1024,\"maxComputeWorkgroupSizeZ\":64,\"maxComputeWorkgroupsPerDimension\":65535}"
},
"worker.webgl": {
"s": "{\"vendor\":\"Mozilla\",\"renderer\":\"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0), or similar\",\"unmasked\":[\"Google Inc. (Intel)\",\"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0), or similar\"],\"exts\":[\"ANGLE_instanced_arrays\",\"EXT_blend_minmax\",\"EXT_clip_control\",\"EXT_color_buffer_half_float\",\"EXT_depth_clamp\",\"EXT_float_blend\",\"EXT_frag_depth\",\"EXT_polygon_offset_clamp\",\"EXT_shader_texture_lod\",\"EXT_sRGB\",\"EXT_texture_compression_bptc\",\"EXT_texture_compression_rgtc\",\"EXT_texture_filter_anisotropic\",\"EXT_texture_mirror_clamp_to_edge\",\"OES_element_index_uint\",\"OES_fbo_render_mipmap\",\"OES_standard_derivatives\",\"OES_texture_float\",\"OES_texture_float_linear\",\"OES_texture_half_float\",\"OES_texture_half_float_linear\",\"OES_vertex_array_object\",\"WEBGL_color_buffer_float\",\"WEBGL_compressed_texture_s3tc\",\"WEBGL_compressed_texture_s3tc_srgb\",\"WEBGL_debug_renderer_info\",\"WEBGL_debug_shaders\",\"WEBGL_depth_texture\",\"WEBGL_draw_buffers\",\"WEBGL_lose_context\",\"WEBGL_provoking_vertex\"],\"px\":[64,128,191,255,64,128,191,255,64,128,191,255,64,128,191,255]}"
}
},
"pngs": {
"c2d.composite.png": {
"n": 2414,
"w": 256,
"h": 128,
"ct": 6,
"sha256": "fb585f18240eb1a787a5b146d6332a0376dae76f8c8716e99f68fbbf9eff905e"
},
"c2d.composite.toBlob": {
"n": 1794,
"w": 256,
"h": 128,
"ct": 6,
"sha256": "fb585f18240eb1a787a5b146d6332a0376dae76f8c8716e99f68fbbf9eff905e"
},
"c2d.gradtext.png": {
"n": 55210,
"w": 420,
"h": 210,
"ct": 6,
"sha256": "1ce15c9ea557be69b62b4893b148345a694a93222c721b1bbb21cdcedebba5a0"
},
"c2d.image.png": {
"n": 19502,
"w": 160,
"h": 120,
"ct": 6,
"sha256": "51bc3789f2e238dfbf8899eb7a965a4f04d3e0e7f2246b1bd3cfdc9597bd2a77"
},
"c2d.image.toBlob": {
"n": 14610,
"w": 160,
"h": 120,
"ct": 6,
"sha256": "51bc3789f2e238dfbf8899eb7a965a4f04d3e0e7f2246b1bd3cfdc9597bd2a77"
},
"c2d.offscreen.convertToBlob": {
"n": 2251,
"w": 160,
"h": 80,
"ct": 6,
"sha256": "55b4c78cd7b05627e9b2767477d61063b6849a7636c5be2ce0a62c6a2c6c9cc4"
},
"c2d.scale.high.png": {
"n": 47314,
"w": 220,
"h": 130,
"ct": 6,
"sha256": "8672b8676f90d662b4809e56c55da58e05be4e72b2f7c543b33da4bdafb0ce21"
},
"c2d.scale.low.png": {
"n": 47314,
"w": 220,
"h": 130,
"ct": 6,
"sha256": "8672b8676f90d662b4809e56c55da58e05be4e72b2f7c543b33da4bdafb0ce21"
},
"c2d.scale.medium.png": {
"n": 47314,
"w": 220,
"h": 130,
"ct": 6,
"sha256": "8672b8676f90d662b4809e56c55da58e05be4e72b2f7c543b33da4bdafb0ce21"
},
"c2d.scale.off.png": {
"n": 20890,
"w": 220,
"h": 130,
"ct": 6,
"sha256": "c28700e28636d69dfe9bf293fadebae1fdf970949ac90147836ab1837065f46d"
},
"c2d.shapes.png": {
"n": 19226,
"w": 256,
"h": 160,
"ct": 6,
"sha256": "89ee57c100f4682099bd3a5f2de56c5b31091dae253bd7e3db4f254fb8b9e6a3"
},
"c2d.shapes.toBlob": {
"n": 14402,
"w": 256,
"h": 160,
"ct": 6,
"sha256": "89ee57c100f4682099bd3a5f2de56c5b31091dae253bd7e3db4f254fb8b9e6a3"
},
"c2d.text.png": {
"n": 42670,
"w": 520,
"h": 412,
"ct": 6,
"sha256": "93d6fc37d2263e52e7b1b46f77c65d9e607faf577eb7c255dc38cbce8b7d7602"
},
"c2d.text.toBlob": {
"n": 31986,
"w": 520,
"h": 412,
"ct": 6,
"sha256": "93d6fc37d2263e52e7b1b46f77c65d9e607faf577eb7c255dc38cbce8b7d7602"
},
"gl1.triangle.toDataURL": {
"n": 7474,
"w": 96,
"h": 96,
"ct": 6,
"sha256": "9989d00c92e8ae035dede9b81b1c9942223799c0ccc4d4875c8eca9efaca776c"
},
"gl2.triangle.toDataURL": {
"n": 7474,
"w": 96,
"h": 96,
"ct": 6,
"sha256": "9989d00c92e8ae035dede9b81b1c9942223799c0ccc4d4875c8eca9efaca776c"
}
}
}
-21
View File
@@ -1,21 +0,0 @@
{
"_why": "The four rules the Node driver's user.js writer follows, FROZEN. Until 2026-08-28 prefs_byte_parity.py read them out of src/invisible_playwright/_driver/package/lib/coreBundle.js on every run, deliberately, so that an upstream change moved the gate with it instead of leaving it comparing against a stale transcription. The bundle is being deleted with the Node driver, so the derived fact becomes a recorded one - and this file exists to make that visible rather than silent.",
"_how_to_verify": "While a bundle is still reachable, prefs_byte_parity.py re-extracts and compares against these values, and FAILS on a mismatch. To reach one after the deletion: git worktree add <dir> <the last commit that carried _driver/>, then point the gate at it with INVPW_DRIVER_BUNDLE=<dir>/src/invisible_playwright/_driver/package/lib/coreBundle.js.",
"_what_a_stale_copy_would_cost": "The gate would compare our writer against our own idea of the driver, which always agrees. That is the failure mode the run-time read existed to prevent, and it is why the provenance below is recorded to the byte instead of just being dated.",
"rules": {
"sorts": false,
"header": false,
"separator": true,
"integer_bare": true
},
"provenance": {
"frozen_on": "2026-08-28",
"file": "src/invisible_playwright/_driver/package/lib/coreBundle.js",
"bundle_bytes": 2780363,
"bundle_sha256_16": "97d55ec7f856966d",
"marker": "__ipwLit",
"marker_offset": 1775227,
"window_bytes": 1200,
"window_sha256_16": "4891de086d6625f6"
}
}
-243
View File
@@ -1,243 +0,0 @@
"""The two writers must produce the SAME `user.js`, byte for byte.
⛔ THIS IS THE CRITERION ITEM 1 WAS WRITTEN WITH, and it is stricter than
"both work" on purpose. Two prefs files can each be valid, each configure the
browser, and differ - a header comment, a different order, an integer written
as a string. Every one of those differences is invisible in a running browser
and every one of them means the Python path is configuring a browser the Node
path never configured. The whole point of keeping the driver as a judge is that
this comparison is possible; a looser check throws that away.
⛔ AND IT NEEDS NO BROWSER. Both writers are pure functions of the prefs dict:
the driver's is a JavaScript literal builder inside `coreBundle.js`, ours is
`invisible_core.launch.write_user_js`, the one writer since 0.30.0. The driver's rules are re-implemented here FROM ITS SOURCE,
read at run time rather than copied - so if upstream's writer changes, this gate
changes with it instead of silently comparing against a stale transcription.
python tests/gates/prefs_byte_parity.py
python tests/gates/prefs_byte_parity.py --selftest # 6 mutations, 3 that must not fire
"""
from __future__ import annotations
import argparse
import json
import os
import pathlib
import re
import sys
import tempfile
ROOT = pathlib.Path(__file__).resolve().parent.parent.parent
sys.path.insert(0, str(ROOT / "src"))
BUNDLE = ROOT / "src/invisible_playwright/_driver/package/lib/coreBundle.js"
#: A prefs dict shaped like a real one: the four value kinds that matter, a
#: name with a character JSON has to escape, and a deliberately unsorted order.
#: ⛔ THE ORDER IS PART OF THE FIXTURE. The driver uses `Object.keys()`, so a
#: writer that sorts produces a file that is equally correct and not identical,
#: and that is precisely the class of difference this gate exists to catch.
SAMPLE = {
"zoom.stealth.screen.width": 1920,
"app.update.auto": False,
"layout.css.devPixelsPerPx": "1.25",
"ui.textScaleFactor": 1.0,
"general.useragent.override": 'Mozilla/5.0 "quoted" \\ backslash',
"browser.startup.homepage": "about:blank",
}
class DriverRulesMissing(RuntimeError):
pass
#: The frozen copy, with its provenance. See the file itself for why.
FROZEN = pathlib.Path(__file__).resolve().parent / "driver_prefs_rules.json"
#: Where to find a bundle after the deletion: a git worktree at the last commit
#: that carried `_driver/`. Named here so the gate can say it out loud instead
#: of leaving the reader to work it out.
BUNDLE_ENV = "INVPW_DRIVER_BUNDLE"
def _bundle():
"""A reachable bundle, or None. Never raises: absence is a state."""
named = os.environ.get(BUNDLE_ENV)
if named:
candidate = pathlib.Path(named)
return candidate if candidate.exists() else None
return BUNDLE if BUNDLE.exists() else None
def driver_rules() -> dict:
"""The driver's literal rules: frozen, and re-checked whenever possible.
⛔ IT USED TO READ THE BUNDLE ON EVERY RUN, deliberately, so an upstream
change moved this gate with it instead of leaving it comparing against a
stale transcription. The bundle goes with the Node driver, so the rules are
now RECORDED - in `driver_prefs_rules.json`, with the sha of the bundle and
of the exact 1200-byte window they came from.
⛔ AND THE RE-CHECK IS THE WHOLE POINT OF FREEZING THEM THIS WAY. Whenever a
bundle IS reachable - still in the tree, or named by `INVPW_DRIVER_BUNDLE`
from a git worktree - the rules are extracted again and compared against the
frozen copy, and a mismatch FAILS. A recorded fact nobody can re-derive is a
transcription, and a transcription this gate cannot check is exactly what
the original design refused to have.
"""
frozen = json.loads(FROZEN.read_text(encoding="utf-8"))["rules"]
bundle = _bundle()
if bundle is None:
return frozen
live = _extract(bundle.read_text(encoding="utf-8", errors="replace"))
if live != frozen:
raise DriverRulesMissing(
"the frozen driver rules disagree with the bundle at %s.\n"
" frozen: %s\n bundle: %s\n"
"The frozen copy is stale: re-freeze it with the new provenance, "
"rather than loosening this comparison." % (bundle, frozen, live))
return frozen
def _extract(text: str) -> dict:
start = text.find("__ipwLit")
if start < 0:
raise DriverRulesMissing(
"the driver's pref writer is not in the bundle: it was renamed or "
"removed, and this gate cannot compare against something it "
"cannot read")
window = text[start:start + 1200]
return {
"sorts": "sort()" in window,
"header": bool(re.search(r'"//[^"]*"\s*\+', window)),
"separator": "String.fromCharCode(10)" in window or "\\n" in window,
"integer_bare": "Number.isInteger" in window,
}
def driver_user_js(prefs: dict) -> str:
"""What the driver writes, in Python, following the rules read above."""
rules = driver_rules()
names = sorted(prefs) if rules["sorts"] else list(prefs)
lines = []
for name in names:
value = prefs[name]
if isinstance(value, bool):
literal = "true" if value else "false"
elif isinstance(value, int):
literal = str(value)
elif isinstance(value, float):
# ⛔ Not an integer, so the driver quotes it: Gecko has no float
# pref type, and a bare fraction makes the parser fail and IGNORE
# EVERY LINE AFTER IT.
literal = json.dumps(str(value))
else:
literal = json.dumps(str(value))
lines.append("user_pref(%s, %s);" % (json.dumps(name), literal))
head = "// header\n" if rules["header"] else ""
return head + "\n".join(lines) + "\n"
def ours(prefs: dict) -> str:
from invisible_core.launch import write_user_js
directory = tempfile.mkdtemp(prefix="prefs_parity_")
write_user_js(directory, prefs)
return (pathlib.Path(directory) / "user.js").read_bytes().decode("utf-8")
def compare(prefs: dict) -> list:
theirs = driver_user_js(prefs)
mine = ours(prefs)
if theirs == mine:
return []
faults = []
a, b = theirs.splitlines(), mine.splitlines()
if len(a) != len(b):
faults.append("line count: driver %d, ours %d" % (len(a), len(b)))
for i, (x, y) in enumerate(zip(a, b)):
if x != y:
faults.append("line %d:\n driver: %s\n ours : %s"
% (i + 1, x, y))
if not faults:
faults.append("same lines, different bytes: trailing newline or "
"encoding")
return faults
# ── the selftest ────────────────────────────────────────────────────────────
def selftest() -> int:
bad = 0
def expect(name, produce, should_fire):
nonlocal bad
theirs = driver_user_js(SAMPLE)
mine = produce(theirs)
differs = theirs != mine
if differs != should_fire:
print(" %s: %s" % ("SURVIVED" if should_fire else "FALSE POSITIVE",
name))
bad += 1
else:
print(" %s: %s" % ("killed" if should_fire else "silent", name))
print("--- mutations that MUST fire ---")
expect("a header comment is added",
lambda t: "// written by us\n" + t, True)
expect("the lines are sorted",
lambda t: "\n".join(sorted(t.splitlines())) + "\n", True)
expect("an integer is quoted",
lambda t: t.replace("user_pref(\"zoom.stealth.screen.width\", 1920)",
"user_pref(\"zoom.stealth.screen.width\", \"1920\")"),
True)
expect("a boolean becomes a string",
lambda t: t.replace(", false)", ", \"false\")"), True)
expect("the trailing newline is dropped",
lambda t: t.rstrip("\n"), True)
expect("one pref goes missing",
lambda t: "\n".join(t.splitlines()[1:]) + "\n", True)
print("--- cases that must NOT fire ---")
expect("the same text", lambda t: t, False)
expect("the same text built twice", lambda t: driver_user_js(SAMPLE), False)
expect("a float stays quoted",
lambda t: t.replace('"1.0"', '"1.0"'), False)
print()
print("selftest: %s" % ("ALL GOOD" if not bad else "%d PROBLEMS" % bad))
return 1 if bad else 0
def main() -> int:
p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
p.add_argument("--selftest", action="store_true")
a = p.parse_args()
if a.selftest:
return selftest()
try:
rules = driver_rules()
except DriverRulesMissing as failure:
print("NOT COMPARABLE: %s" % failure)
return 2
# ⛔ IT SAYS WHICH SOURCE IT USED. The line used to read "driver rules read
# from the bundle" unconditionally, and after the freeze that sentence was
# simply false half the time - a gate that misreports where its own
# reference came from is worse than one with no message, because the reader
# stops looking.
bundle = _bundle()
print("driver rules %s: %s"
% ("re-checked against %s" % bundle if bundle
else "from the FROZEN copy (%s) - no bundle reachable, so nothing "
"re-derived them this run" % FROZEN.name,
", ".join("%s=%s" % kv for kv in sorted(rules.items()))))
faults = compare(SAMPLE)
if not faults:
print("PREFS BYTE PARITY: identical (%d prefs)" % len(SAMPLE))
return 0
print("the two writers DISAGREE:")
for f in faults:
print(" " + f)
return 1
if __name__ == "__main__":
sys.exit(main())
+54
View File
@@ -0,0 +1,54 @@
"""What the core did about the GeoIP database during a pytest run, written when the run ends.
Registered by tests/conftest.py when ``GEOIP_USED_OUT`` names a file (the CI legs set it; a developer's run does not). ``scripts/ci_lab_geoip.py
verify`` reads the file: the proof of a leg is not only the environment it was LAUNCHED in (``evidence``, written before pytest) but what the
process of the tests used: the value of ``STEALTHFOX_GEOIP_MMDB`` when the run ended, the sha256 of that file, and how many times the core went
past the override to ask GitHub for the latest database (``_resolve_latest_geoip_tag``) or to download one (``_download_geoip_tag``): none, in a leg
with the database of the pin. A test that removes the variable on purpose (the user-path e2e files do, in a throwaway environment of their own)
runs in another process and is not counted here.
"""
from __future__ import annotations
import hashlib
import json
import os
from pathlib import Path
class GeoipUsedRecorder:
def __init__(self, path: str) -> None:
self.path = Path(path)
self.asked_github = 0
self._undo = []
def start(self) -> None:
try:
from invisible_core import _geoip_db
except ImportError: # a run without the core installed: the file says so
return
for name in ("_resolve_latest_geoip_tag", "_download_geoip_tag"):
original = getattr(_geoip_db, name, None)
if original is None:
continue
def counted(*args, __original=original, **kwargs):
self.asked_github += 1
return __original(*args, **kwargs)
setattr(_geoip_db, name, counted)
self._undo.append((_geoip_db, name, original))
def stop(self) -> None:
for module, name, original in reversed(self._undo):
setattr(module, name, original)
self._undo = []
def pytest_sessionfinish(self, session, exitstatus) -> None: # noqa: ARG002
value = os.environ.get("STEALTHFOX_GEOIP_MMDB", "")
digest = None
if value and os.path.isfile(value):
digest = hashlib.sha256(Path(value).read_bytes()).hexdigest()
data = {"env": value, "exists": digest is not None, "sha256": digest, "asked_github": self.asked_github}
self.path.parent.mkdir(parents=True, exist_ok=True)
self.path.write_text(json.dumps(data, indent=1), encoding="utf-8")
self.stop()
+475
View File
@@ -0,0 +1,475 @@
// The probe of tests/test_the_bytes_a_page_reads_do_not_change_e2e.py: one expression that resolves to a flat object
// {key: {s: "a short string"} | {h, n, s0} | {h, n, w, b64}} of everything a page can read about drawing and text:
// c2d.* canvas 2D: getImageData bytes, toDataURL (png, jpeg, webp), toBlob, OffscreenCanvas.convertToBlob, measureText; drawImage scaled up
// and down with imageSmoothing off and on at every imageSmoothingQuality (c2d.scale.*); gradients (linear, radial, conic) filling and
// stroking text (c2d.gradtext)
// gl1.* WebGL 1 and gl2.* WebGL 2: strings, extensions, limits, precision formats, readPixels bytes of several scenes, toDataURL, drawImage of the canvas
// worker.* an OffscreenCanvas WebGL context in a worker
// gpu.* the WebGPU adapter
// dom.* text layout: the boxes of spans in many fonts, wrapped paragraphs, system colours
// env.* the values the persona declares around it
// A PNG the page reads (toDataURL, toBlob, convertToBlob) keeps its bytes in `b64`: the test compares the pixels it decodes to, because the engine
// writes a per-launch ancillary chunk into every PNG (tests/_page_bytes.py). Every scene is wrapped: an exception becomes `<scene>.error` and is
// compared like any other value, so every launch gives the same keys.
// Taken from the hunt that measured the Windows reference (scripts/hunt_page_bytes_probe.js of run 43652292533), with its encoding mode removed.
(async () => {
const out = {};
const enc = new TextEncoder();
function hashBytes(u8) { // cyrb53 over bytes: no crypto.subtle (it needs a secure context)
let h1 = 0xdeadbeef ^ u8.length, h2 = 0x41c6ce57 ^ u8.length;
for (let i = 0; i < u8.length; i++) { const ch = u8[i]; h1 = Math.imul(h1 ^ ch, 2654435761); h2 = Math.imul(h2 ^ ch, 1597334677); }
h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(16);
}
function b64(u8) {
let s = "";
for (let i = 0; i < u8.length; i += 0x8000) s += String.fromCharCode.apply(null, u8.subarray(i, i + 0x8000));
return btoa(s);
}
function put(k, v, w) {
if (ArrayBuffer.isView(v) || v instanceof ArrayBuffer) {
const u8 = v instanceof ArrayBuffer ? new Uint8Array(v) : new Uint8Array(v.buffer, v.byteOffset, v.byteLength);
out[k] = { h: hashBytes(u8), n: u8.length };
if (w) { out[k].w = w; out[k].bpp = 4 * (v.BYTES_PER_ELEMENT || 1); } // pixels per row, bytes per pixel (RGBA)
if (u8.length <= 400 * 1024) out[k].b64 = b64(u8);
} else {
const s = typeof v === "string" ? v : JSON.stringify(v);
out[k] = s.length <= 3000 ? { s } : { h: hashBytes(enc.encode(s)), n: s.length, s0: s.slice(0, 200) };
if (s.length > 3000 && s.startsWith("data:image/png;base64,") && s.length <= 600 * 1024) out[k].b64 = s.slice(22);
}
}
async function scene(k, fn) {
try { await fn(); } catch (e) { put(k + ".error", String((e && e.message) || e)); }
}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
// ------------------------------------------------------------------------------------------------------------ env
await scene("env", async () => {
put("env.ua", navigator.userAgent);
put("env.platform", navigator.platform);
put("env.oscpu", navigator.oscpu || "");
put("env.hw", navigator.hardwareConcurrency);
put("env.lang", navigator.languages);
put("env.dpr", window.devicePixelRatio);
put("env.screen", [screen.width, screen.height, screen.availWidth, screen.availHeight, screen.colorDepth, screen.pixelDepth]);
put("env.mq", ["(color-gamut: srgb)", "(color-gamut: p3)", "(dynamic-range: high)", "(prefers-color-scheme: dark)", "(prefers-reduced-motion: reduce)",
"(forced-colors: active)", "(inverted-colors: inverted)"].map((q) => matchMedia(q).matches));
});
// ---------------------------------------------------------------------------------------------------- canvas 2D
function c2d(w, h) { const c = document.createElement("canvas"); c.width = w; c.height = h; return [c, c.getContext("2d")]; }
function dataUrlBytes(url) {
const bin = atob(url.split(",")[1]);
const u = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) u[i] = bin.charCodeAt(i);
return u;
}
async function read2d(k, c, g) {
put(k + ".getImageData", g.getImageData(0, 0, c.width, c.height).data, c.width);
put(k + ".png", c.toDataURL());
put(k + ".jpeg", c.toDataURL("image/jpeg", 0.8));
put(k + ".webp", c.toDataURL("image/webp", 0.8));
const blob = await new Promise((r) => c.toBlob(r));
put(k + ".toBlob", blob ? new Uint8Array(await blob.arrayBuffer()) : "null");
}
await scene("c2d.shapes", async () => {
const [c, g] = c2d(256, 160);
g.fillStyle = "#fff"; g.fillRect(0, 0, 256, 160);
const lg = g.createLinearGradient(0, 0, 256, 0);
lg.addColorStop(0, "#f00"); lg.addColorStop(0.5, "rgba(0,200,0,.5)"); lg.addColorStop(1, "#00f");
g.fillStyle = lg; g.fillRect(8, 8, 240, 40);
const rg = g.createRadialGradient(60, 100, 4, 60, 100, 50);
rg.addColorStop(0, "#ff0"); rg.addColorStop(1, "rgba(255,0,255,.2)");
g.fillStyle = rg; g.beginPath(); g.arc(60, 100, 50, 0, Math.PI * 2); g.fill();
g.strokeStyle = "#123"; g.lineWidth = 1.5; g.beginPath(); g.moveTo(130, 60); g.bezierCurveTo(160, 20, 200, 140, 240, 70); g.stroke();
g.lineWidth = 0.7; g.beginPath(); g.ellipse(190, 110, 40, 20, 0.5, 0, Math.PI * 2); g.stroke();
g.save(); g.shadowColor = "rgba(0,0,0,.6)"; g.shadowBlur = 6; g.shadowOffsetX = 3; g.shadowOffsetY = 3; g.fillStyle = "#38c"; g.fillRect(120, 100, 50, 30); g.restore();
g.save(); g.translate(30, 140); g.rotate(0.3); g.scale(1.3, 0.8); g.fillStyle = "#a40"; g.fillRect(0, 0, 40, 20); g.restore();
if (g.createConicGradient) {
const cg = g.createConicGradient(0.5, 215, 140);
cg.addColorStop(0, "#f80"); cg.addColorStop(0.5, "#08f"); cg.addColorStop(1, "#f80");
g.fillStyle = cg; g.fillRect(190, 120, 60, 36);
}
await read2d("c2d.shapes", c, g);
});
await scene("c2d.composite", async () => {
const ops = ["source-over", "source-in", "source-out", "source-atop", "destination-over", "destination-in", "destination-out", "destination-atop",
"lighter", "copy", "xor", "multiply", "screen", "overlay", "darken", "lighten", "color-dodge", "color-burn", "hard-light", "soft-light",
"difference", "exclusion", "hue", "saturation", "color", "luminosity"];
const [c, g] = c2d(8 * 32, 4 * 32);
ops.forEach((op, i) => {
const x = (i % 8) * 32, y = Math.floor(i / 8) * 32;
g.save(); g.beginPath(); g.rect(x, y, 32, 32); g.clip();
g.globalCompositeOperation = "source-over";
g.fillStyle = "rgba(200,60,40,.8)"; g.fillRect(x + 2, y + 2, 20, 20);
g.globalCompositeOperation = op;
g.fillStyle = "rgba(30,90,220,.6)"; g.fillRect(x + 10, y + 10, 20, 20);
g.restore();
});
await read2d("c2d.composite", c, g);
});
await scene("c2d.filter_draw_image", async () => {
const [c, g] = c2d(160, 120);
const [s, sg] = c2d(10, 10);
for (let i = 0; i < 100; i++) { sg.fillStyle = "hsl(" + ((i * 37) % 360) + ",70%,50%)"; sg.fillRect(i % 10, Math.floor(i / 10), 1, 1); }
g.imageSmoothingEnabled = true; g.imageSmoothingQuality = "high";
g.drawImage(s, 0, 0, 10, 10, 5.5, 5.5, 70.3, 70.3);
g.imageSmoothingEnabled = false; g.drawImage(s, 80, 5, 60, 60);
if ("filter" in g) { g.filter = "blur(2px) saturate(1.4)"; g.drawImage(s, 5, 70, 40, 40); g.filter = "none"; }
const p = g.createPattern(s, "repeat"); g.fillStyle = p; g.fillRect(60, 70, 90, 40);
const d = g.getImageData(0, 0, 40, 40); g.putImageData(d, 100, 80);
await read2d("c2d.image", c, g);
});
const FONTS = ["16px sans-serif", "20px serif", "18px monospace", "bold 16px Arial", "italic 15px 'Segoe UI'", "16px 'Times New Roman'", "16px Calibri",
"14px Consolas", "16px Verdana", "16px Tahoma", "17px Georgia", "16px 'Segoe UI Emoji'", "16px 'Microsoft YaHei'", "16px 'Yu Gothic'"];
const TEXTS = ["Hamburgefonstiv 0123456789", "The quick brown fox jumps over the lazy dog", "ÀÉÎÕÜ ß fi fl ffl", "日本語のテキスト 漢字", "😀🚀👍🏽", "مرحبا بالعالم"];
await scene("c2d.text", async () => {
const [c, g] = c2d(520, FONTS.length * 28 + 20);
g.fillStyle = "#fff"; g.fillRect(0, 0, c.width, c.height);
FONTS.forEach((f, i) => {
g.font = f; g.fillStyle = "#101820"; g.textBaseline = "alphabetic";
g.fillText(TEXTS[i % TEXTS.length], 6, 22 + i * 28);
g.strokeStyle = "rgba(200,0,0,.8)"; g.lineWidth = 0.6; g.strokeText("Ag", 470, 22 + i * 28);
});
await read2d("c2d.text", c, g);
const m = [];
for (const f of FONTS) {
g.font = f;
for (const t of TEXTS) {
const r = g.measureText(t);
m.push([f, t, r.width, r.actualBoundingBoxLeft, r.actualBoundingBoxRight, r.actualBoundingBoxAscent, r.actualBoundingBoxDescent,
r.fontBoundingBoxAscent, r.fontBoundingBoxDescent]);
}
}
put("c2d.measure", m);
});
await scene("c2d.offscreen", async () => {
if (typeof OffscreenCanvas === "undefined") { put("c2d.offscreen", "no OffscreenCanvas"); return; }
const oc = new OffscreenCanvas(160, 80), g = oc.getContext("2d");
g.fillStyle = "#fed"; g.fillRect(0, 0, 160, 80); g.fillStyle = "rgba(10,120,200,.7)"; g.beginPath(); g.arc(50, 40, 30, 0, 6.2); g.fill();
g.font = "bold 18px sans-serif"; g.fillStyle = "#222"; g.fillText("offscreen 2d", 70, 45);
put("c2d.offscreen.getImageData", g.getImageData(0, 0, 160, 80).data, 160);
const blob = await oc.convertToBlob();
put("c2d.offscreen.convertToBlob", new Uint8Array(await blob.arrayBuffer()));
});
// ----------------------------------------------------------------------------------------- drawImage scaled, smoothing and quality
// A 24x24 source with hard edges and a ramp, a 200x200 one (to scale down), each drawn up and down, rotated and not, with imageSmoothing off and
// on at low, medium and high. The pixels (getImageData) and the PNG of the same canvas, which the test compares decoded.
await scene("c2d.scale", async () => {
const [s1, sg1] = c2d(24, 24);
for (let y = 0; y < 24; y++) for (let x = 0; x < 24; x++) {
sg1.fillStyle = (x + y) % 5 === 0 ? "#000" : "hsl(" + ((x * 13 + y * 7) % 360) + "," + (40 + (y * 2)) + "%," + (30 + x) + "%)";
sg1.fillRect(x, y, 1, 1);
}
const [s2, sg2] = c2d(200, 200);
for (let i = 0; i < 40; i++) {
sg2.fillStyle = "hsl(" + (i * 9) + ",70%,50%)"; sg2.fillRect((i * 17) % 190, (i * 29) % 190, 23 + (i % 7), 11 + (i % 5));
sg2.strokeStyle = i % 2 ? "#fff" : "#111"; sg2.lineWidth = 1; sg2.beginPath(); sg2.moveTo(i * 5, 0); sg2.lineTo(200 - i * 4, 200); sg2.stroke();
}
const configs = [["off", false, "low"], ["low", true, "low"], ["medium", true, "medium"], ["high", true, "high"]];
for (const [name, on, quality] of configs) {
const [c, g] = c2d(220, 130);
g.fillStyle = "#fff"; g.fillRect(0, 0, 220, 130);
g.imageSmoothingEnabled = on; g.imageSmoothingQuality = quality;
g.drawImage(s1, 0, 0, 24, 24, 3.25, 3.25, 97.3, 97.3); // up, not an integer factor
g.drawImage(s2, 0, 0, 200, 200, 110.5, 4.5, 37, 37); // down, far
g.drawImage(s2, 20, 20, 120, 120, 150, 4, 61, 61); // down, near, a part of the source
g.drawImage(s1, 0, 0, 24, 24, 110, 50, 24, 24); // 1:1 at a whole pixel
g.save(); g.translate(180, 95); g.rotate(0.35); g.drawImage(s1, 0, 0, 24, 24, -20, -20, 40, 40); g.restore(); // rotated and scaled up
g.save(); g.translate(60, 118); g.scale(1.7, 0.45); g.drawImage(s2, 0, 0, 200, 200, 0, -20, 30, 30); g.restore(); // scaled by a transform
put("c2d.scale." + name + ".getImageData", g.getImageData(0, 0, 220, 130).data, 220);
put("c2d.scale." + name + ".png", c.toDataURL());
}
});
// Text filled and stroked with gradients of the three kinds, with a shadow and with a global alpha: the paths the canvas takes for a gradient
// over glyphs.
await scene("c2d.gradtext", async () => {
const [c, g] = c2d(420, 210);
g.fillStyle = "#fff"; g.fillRect(0, 0, 420, 210);
const lin = g.createLinearGradient(10, 0, 400, 0);
lin.addColorStop(0, "#d00"); lin.addColorStop(0.4, "#fc0"); lin.addColorStop(0.7, "rgba(0,160,60,.6)"); lin.addColorStop(1, "#04d");
const rad = g.createRadialGradient(100, 90, 4, 130, 100, 90);
rad.addColorStop(0, "#fff"); rad.addColorStop(0.5, "#c0c"); rad.addColorStop(1, "#036");
const rad2 = g.createRadialGradient(300, 60, 30, 340, 80, 8); // the focal circle outside the start circle
rad2.addColorStop(0, "#f60"); rad2.addColorStop(1, "#0af");
const con = g.createConicGradient ? g.createConicGradient(0.6, 210, 150) : lin;
con.addColorStop(0, "#f80"); con.addColorStop(0.33, "#0c8"); con.addColorStop(0.66, "#80f"); con.addColorStop(1, "#f80");
g.textBaseline = "alphabetic";
g.font = "bold 40px sans-serif"; g.fillStyle = lin; g.fillText("Gradient 0123", 10, 44);
g.font = "italic 34px serif"; g.fillStyle = rad; g.fillText("Hamburgefonstiv", 10, 90);
g.font = "28px monospace"; g.fillStyle = rad2; g.fillText("radial focal 1/2", 220, 40);
g.font = "bold 44px Arial"; g.strokeStyle = lin; g.lineWidth = 2.5; g.strokeText("Stroke", 10, 140);
g.font = "36px 'Times New Roman'"; g.fillStyle = con; g.fillText("Conic text", 150, 150);
g.save(); g.shadowColor = "rgba(0,0,0,.55)"; g.shadowBlur = 4; g.shadowOffsetX = 2; g.shadowOffsetY = 3; g.globalAlpha = 0.8;
g.font = "30px 'Segoe UI'"; g.fillStyle = lin; g.fillText("Shadow and alpha", 10, 190); g.restore();
g.font = "20px sans-serif"; g.fillStyle = con; g.fillRect(300, 150, 110, 50); g.fillStyle = "#fff"; g.fillText("on conic", 310, 180);
put("c2d.gradtext.getImageData", g.getImageData(0, 0, 420, 210).data, 420);
put("c2d.gradtext.png", c.toDataURL());
});
// ------------------------------------------------------------------------------------------------------------ WebGL
const P1 = ["VERSION", "SHADING_LANGUAGE_VERSION", "VENDOR", "RENDERER", "MAX_TEXTURE_SIZE", "MAX_CUBE_MAP_TEXTURE_SIZE", "MAX_RENDERBUFFER_SIZE",
"MAX_VIEWPORT_DIMS", "ALIASED_LINE_WIDTH_RANGE", "ALIASED_POINT_SIZE_RANGE", "MAX_VERTEX_ATTRIBS", "MAX_VARYING_VECTORS",
"MAX_COMBINED_TEXTURE_IMAGE_UNITS", "MAX_VERTEX_TEXTURE_IMAGE_UNITS", "MAX_TEXTURE_IMAGE_UNITS", "MAX_VERTEX_UNIFORM_VECTORS",
"MAX_FRAGMENT_UNIFORM_VECTORS", "RED_BITS", "GREEN_BITS", "BLUE_BITS", "ALPHA_BITS", "DEPTH_BITS", "STENCIL_BITS", "SAMPLES",
"SAMPLE_BUFFERS", "SUBPIXEL_BITS"];
const P2 = ["MAX_3D_TEXTURE_SIZE", "MAX_ARRAY_TEXTURE_LAYERS", "MAX_COLOR_ATTACHMENTS", "MAX_DRAW_BUFFERS", "MAX_ELEMENTS_INDICES", "MAX_ELEMENTS_VERTICES",
"MAX_FRAGMENT_INPUT_COMPONENTS", "MAX_FRAGMENT_UNIFORM_BLOCKS", "MAX_FRAGMENT_UNIFORM_COMPONENTS", "MAX_PROGRAM_TEXEL_OFFSET", "MAX_SAMPLES",
"MAX_SERVER_WAIT_TIMEOUT", "MAX_TEXTURE_LOD_BIAS", "MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS", "MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS",
"MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS", "MAX_UNIFORM_BLOCK_SIZE", "MAX_UNIFORM_BUFFER_BINDINGS", "MAX_VARYING_COMPONENTS",
"MAX_VERTEX_OUTPUT_COMPONENTS", "MAX_VERTEX_UNIFORM_BLOCKS", "MAX_VERTEX_UNIFORM_COMPONENTS", "MIN_PROGRAM_TEXEL_OFFSET",
"MAX_COMBINED_UNIFORM_BLOCKS", "MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS", "MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS", "UNIFORM_BUFFER_OFFSET_ALIGNMENT"];
function glInfo(p, gl, v2) {
const params = {};
for (const n of P1.concat(v2 ? P2 : [])) {
try { let v = gl.getParameter(gl[n]); if (ArrayBuffer.isView(v)) v = Array.from(v); params[n] = v; } catch (e) { params[n] = "ERR " + e.message; }
}
put(p + ".params", params);
const exts = gl.getSupportedExtensions() || [];
put(p + ".extensions", exts);
const eo = [];
for (const e of exts) {
try { const o = gl.getExtension(e); eo.push([e, o ? Object.keys(Object.getPrototypeOf(o)).length : -1]); } catch (er) { eo.push([e, "ERR"]); }
}
put(p + ".extension_objects", eo);
const dbg = gl.getExtension("WEBGL_debug_renderer_info");
put(p + ".unmasked", dbg ? [gl.getParameter(dbg.UNMASKED_VENDOR_WEBGL), gl.getParameter(dbg.UNMASKED_RENDERER_WEBGL)] : "no WEBGL_debug_renderer_info");
const an = gl.getExtension("EXT_texture_filter_anisotropic");
put(p + ".anisotropy", an ? gl.getParameter(an.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : "none");
const prec = [];
for (const sh of ["VERTEX_SHADER", "FRAGMENT_SHADER"]) for (const lv of ["LOW_FLOAT", "MEDIUM_FLOAT", "HIGH_FLOAT", "LOW_INT", "MEDIUM_INT", "HIGH_INT"]) {
const f = gl.getShaderPrecisionFormat(gl[sh], gl[lv]);
prec.push([sh, lv, f && f.rangeMin, f && f.rangeMax, f && f.precision]);
}
put(p + ".precision", prec);
put(p + ".attributes", gl.getContextAttributes());
}
function program(gl, vs, fs) {
const mk = (type, src) => {
const s = gl.createShader(type); gl.shaderSource(s, src); gl.compileShader(s);
if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) throw new Error("shader: " + gl.getShaderInfoLog(s));
return s;
};
const pr = gl.createProgram();
gl.attachShader(pr, mk(gl.VERTEX_SHADER, vs)); gl.attachShader(pr, mk(gl.FRAGMENT_SHADER, fs));
gl.bindAttribLocation(pr, 0, "p"); gl.bindAttribLocation(pr, 1, "c");
gl.linkProgram(pr);
if (!gl.getProgramParameter(pr, gl.LINK_STATUS)) throw new Error("link: " + gl.getProgramInfoLog(pr));
gl.useProgram(pr);
return pr;
}
function buffer(gl, loc, data, size) {
const b = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, b); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(data), gl.STATIC_DRAW);
gl.enableVertexAttribArray(loc); gl.vertexAttribPointer(loc, size, gl.FLOAT, false, 0, 0);
return b;
}
function pixels(gl, w, h) { const u = new Uint8Array(w * h * 4); gl.readPixels(0, 0, w, h, gl.RGBA, gl.UNSIGNED_BYTE, u); return u; }
const VS = "attribute vec2 p; attribute vec4 c; varying vec4 v; varying vec2 uv; void main(){ v=c; uv=p*0.5+0.5; gl_Position=vec4(p,0.,1.); gl_PointSize=7.5; }";
const FS_COLOR = "precision mediump float; varying vec4 v; void main(){ gl_FragColor=v; }";
const QUAD = [-1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, 1];
async function glScenes(p, v2) {
const kind = v2 ? "webgl2" : "webgl";
const mkctx = (w, h, attrs) => {
const c = document.createElement("canvas"); c.width = w; c.height = h;
return [c, c.getContext(kind, Object.assign({ preserveDrawingBuffer: true }, attrs || {}))];
};
let [c0, gl0] = mkctx(64, 64);
if (!gl0) { put(p + ".context", "null"); return; }
glInfo(p, gl0, v2);
await scene(p + ".triangle", async () => {
const [c, gl] = mkctx(96, 96, { antialias: false });
gl.viewport(0, 0, 96, 96); gl.clearColor(0.1, 0.2, 0.3, 0.4); gl.clear(gl.COLOR_BUFFER_BIT);
program(gl, VS, FS_COLOR);
buffer(gl, 0, [-0.8, -0.7, 0.9, -0.5, -0.1, 0.85], 2);
buffer(gl, 1, [1, 0, 0, 1, 0, 1, 0, 0.7, 0, 0, 1, 0.3], 4);
gl.drawArrays(gl.TRIANGLES, 0, 3);
put(p + ".triangle.readPixels", pixels(gl, 96, 96), 96);
put(p + ".triangle.toDataURL", c.toDataURL());
put(p + ".triangle.toDataURL_jpeg", c.toDataURL("image/jpeg", 0.8));
const [d, g2] = c2d(96, 96); g2.drawImage(c, 0, 0);
put(p + ".triangle.drawImage", g2.getImageData(0, 0, 96, 96).data, 96);
});
await scene(p + ".antialias", async () => {
for (const aa of [true, false]) {
const [c, gl] = mkctx(96, 96, { antialias: aa });
gl.viewport(0, 0, 96, 96); gl.clearColor(1, 1, 1, 1); gl.clear(gl.COLOR_BUFFER_BIT);
program(gl, VS, FS_COLOR);
buffer(gl, 0, [-0.83, -0.71, 0.77, -0.43, -0.1, 0.89, 0.3, 0.9, 0.9, 0.2, 0.6, 0.95], 2);
buffer(gl, 1, [0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0.8, 0, 0, 1, 0.8, 0, 0, 1, 0.8, 0, 0, 1], 4);
gl.drawArrays(gl.TRIANGLES, 0, 6);
put(p + ".antialias." + aa + ".samples", gl.getParameter(gl.SAMPLES));
put(p + ".antialias." + aa + ".readPixels", pixels(gl, 96, 96), 96);
}
});
for (const prec of ["highp", "mediump"]) await scene(p + ".math." + prec, async () => {
const [c, gl] = mkctx(64, 64, { antialias: false });
const fp = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT);
const use = prec === "highp" && !(fp && fp.precision) ? "mediump" : prec;
gl.viewport(0, 0, 64, 64);
program(gl, VS, "precision " + use + " float; varying vec2 uv;" +
"void main(){ float x=uv.x*6.0; gl_FragColor=vec4(fract(sin(x)*43758.5453), fract(exp(uv.y*3.0)), fract(pow(uv.x+0.5, 2.2+uv.y)), fract(sqrt(uv.x*uv.y)*17.0)); }");
buffer(gl, 0, QUAD, 2); gl.drawArrays(gl.TRIANGLES, 0, 6);
put(p + ".math." + prec + ".readPixels", pixels(gl, 64, 64), 64);
});
await scene(p + ".texture", async () => {
const [c, gl] = mkctx(64, 64, { antialias: false });
gl.viewport(0, 0, 64, 64);
program(gl, VS, "precision mediump float; varying vec2 uv; uniform sampler2D t; void main(){ gl_FragColor=texture2D(t, uv*0.9+0.03); }");
const tex = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, tex);
const d = new Uint8Array(32 * 32 * 4); let s = 12345;
for (let i = 0; i < d.length; i++) { s = (s * 1103515245 + 12345) & 0x7fffffff; d[i] = (s >> 16) & 255; }
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 32, 32, 0, gl.RGBA, gl.UNSIGNED_BYTE, d);
gl.generateMipmap(gl.TEXTURE_2D);
for (const [name, mag, min] of [["linear", gl.LINEAR, gl.LINEAR], ["mip", gl.LINEAR, gl.LINEAR_MIPMAP_LINEAR], ["nearest", gl.NEAREST, gl.NEAREST]]) {
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, mag); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, min);
gl.clear(gl.COLOR_BUFFER_BIT);
buffer(gl, 0, QUAD, 2); gl.drawArrays(gl.TRIANGLES, 0, 6);
put(p + ".texture." + name + ".readPixels", pixels(gl, 64, 64), 64);
}
});
await scene(p + ".blend", async () => {
const [c, gl] = mkctx(64, 64, { antialias: false, premultipliedAlpha: false });
gl.viewport(0, 0, 64, 64); gl.clearColor(0.2, 0.4, 0.6, 0.5); gl.clear(gl.COLOR_BUFFER_BIT);
program(gl, VS, FS_COLOR); gl.enable(gl.BLEND);
for (const [src, dst] of [[gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA], [gl.ONE, gl.ONE_MINUS_SRC_ALPHA], [gl.DST_COLOR, gl.ZERO]]) {
gl.blendFunc(src, dst);
buffer(gl, 0, [-0.9, -0.9, 0.3, -0.5, -0.3, 0.7], 2);
buffer(gl, 1, [0.9, 0.2, 0.1, 0.37, 0.1, 0.8, 0.3, 0.55, 0.2, 0.3, 0.9, 0.21], 4);
gl.drawArrays(gl.TRIANGLES, 0, 3);
}
put(p + ".blend.readPixels", pixels(gl, 64, 64), 64);
});
await scene(p + ".lines_points", async () => {
const [c, gl] = mkctx(64, 64, { antialias: false });
gl.viewport(0, 0, 64, 64); gl.clearColor(1, 1, 1, 1); gl.clear(gl.COLOR_BUFFER_BIT);
program(gl, VS, FS_COLOR);
buffer(gl, 1, [0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1], 4);
buffer(gl, 0, [-0.9, -0.3, 0.9, 0.5, -0.9, 0.6, 0.2, -0.9], 2);
gl.lineWidth(1); gl.drawArrays(gl.LINES, 0, 4);
gl.lineWidth(3); buffer(gl, 0, [-0.6, -0.8, 0.8, 0.9], 2); gl.drawArrays(gl.LINES, 0, 2);
buffer(gl, 0, [-0.5, 0.5, 0.4, -0.2], 2); gl.drawArrays(gl.POINTS, 0, 2);
put(p + ".lines_points.readPixels", pixels(gl, 64, 64), 64);
});
await scene(p + ".depth_stencil", async () => {
const [c, gl] = mkctx(64, 64, { antialias: false, depth: true, stencil: true });
gl.viewport(0, 0, 64, 64); gl.clearColor(0, 0, 0, 1); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);
program(gl, "attribute vec3 p; attribute vec4 c; varying vec4 v; void main(){ v=c; gl_Position=vec4(p,1.); }", FS_COLOR);
gl.enable(gl.DEPTH_TEST); gl.enable(gl.STENCIL_TEST); gl.stencilFunc(gl.ALWAYS, 1, 255); gl.stencilOp(gl.KEEP, gl.KEEP, gl.REPLACE);
buffer(gl, 0, [-0.9, -0.9, 0.2, 0.9, -0.5, -0.4, 0.0, 0.9, 0.6], 3);
buffer(gl, 1, [1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1], 4);
gl.drawArrays(gl.TRIANGLES, 0, 3);
buffer(gl, 0, [-0.9, 0.9, 0.0, 0.9, 0.9, 0.0, 0.0, -0.9, 0.5], 3);
buffer(gl, 1, [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1], 4);
gl.drawArrays(gl.TRIANGLES, 0, 3);
put(p + ".depth_stencil.readPixels", pixels(gl, 64, 64), 64);
});
if (v2) {
await scene(p + ".msaa_resolve", async () => {
const [c, gl] = mkctx(64, 64, { antialias: false });
const rb = gl.createRenderbuffer(); gl.bindRenderbuffer(gl.RENDERBUFFER, rb);
gl.renderbufferStorageMultisample(gl.RENDERBUFFER, 4, gl.RGBA8, 64, 64);
const fb = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, rb);
const tx = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, tx);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 64, 64, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
const fb2 = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, fb2);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tx, 0);
gl.bindFramebuffer(gl.FRAMEBUFFER, fb); gl.viewport(0, 0, 64, 64); gl.clearColor(1, 1, 1, 1); gl.clear(gl.COLOR_BUFFER_BIT);
program(gl, VS, FS_COLOR);
buffer(gl, 0, [-0.83, -0.71, 0.77, -0.43, -0.1, 0.89], 2);
buffer(gl, 1, [0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1], 4);
gl.drawArrays(gl.TRIANGLES, 0, 3);
gl.bindFramebuffer(gl.READ_FRAMEBUFFER, fb); gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, fb2);
gl.blitFramebuffer(0, 0, 64, 64, 0, 0, 64, 64, gl.COLOR_BUFFER_BIT, gl.NEAREST);
gl.bindFramebuffer(gl.FRAMEBUFFER, fb2);
put(p + ".msaa_resolve.readPixels", pixels(gl, 64, 64), 64);
});
await scene(p + ".float_target", async () => {
const [c, gl] = mkctx(32, 32, { antialias: false });
if (!gl.getExtension("EXT_color_buffer_float")) { put(p + ".float_target", "no EXT_color_buffer_float"); return; }
const tx = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, tx);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA32F, 32, 32, 0, gl.RGBA, gl.FLOAT, null);
const fb = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tx, 0);
gl.viewport(0, 0, 32, 32);
program(gl, VS, "precision highp float; varying vec2 uv; void main(){ gl_FragColor=vec4(sin(uv.x*9.0)*exp(uv.y), pow(uv.x+0.1, 1.7), sqrt(uv.y), uv.x/(uv.y+0.37)); }");
buffer(gl, 0, QUAD, 2); gl.drawArrays(gl.TRIANGLES, 0, 6);
const f = new Float32Array(32 * 32 * 4); gl.readPixels(0, 0, 32, 32, gl.RGBA, gl.FLOAT, f);
put(p + ".float_target.readPixels", f, 32);
});
}
}
await scene("gl1", () => glScenes("gl1", false));
await scene("gl2", () => glScenes("gl2", true));
await scene("worker.webgl", async () => {
if (typeof Worker === "undefined" || typeof OffscreenCanvas === "undefined") { put("worker.webgl", "no worker or OffscreenCanvas"); return; }
const src = "onmessage = () => { try { const c = new OffscreenCanvas(32, 32), gl = c.getContext('webgl'); if (!gl) { postMessage({err: 'no webgl'}); return; }" +
"const d = gl.getExtension('WEBGL_debug_renderer_info');" +
"gl.clearColor(0.25, 0.5, 0.75, 1); gl.clear(gl.COLOR_BUFFER_BIT); const u = new Uint8Array(32*32*4); gl.readPixels(0,0,32,32,gl.RGBA,gl.UNSIGNED_BYTE,u);" +
"postMessage({vendor: gl.getParameter(gl.VENDOR), renderer: gl.getParameter(gl.RENDERER), unmasked: d ? [gl.getParameter(d.UNMASKED_VENDOR_WEBGL), gl.getParameter(d.UNMASKED_RENDERER_WEBGL)] : null," +
"exts: gl.getSupportedExtensions(), px: Array.from(u.subarray(0, 16))}); } catch (e) { postMessage({err: String(e)}); } };";
const w = new Worker(URL.createObjectURL(new Blob([src])));
const r = await Promise.race([new Promise((res) => { w.onmessage = (e) => res(e.data); w.onerror = (e) => res({ err: "worker error " + e.message }); w.postMessage(1); }),
sleep(10000).then(() => ({ err: "timeout" }))]);
w.terminate();
put("worker.webgl", r);
});
await scene("gpu.webgpu", async () => {
if (!navigator.gpu) { put("gpu.webgpu", "no navigator.gpu"); return; }
const a = await Promise.race([navigator.gpu.requestAdapter(), sleep(10000).then(() => "timeout")]);
if (!a || a === "timeout") { put("gpu.webgpu", String(a)); return; }
const info = a.info || (a.requestAdapterInfo ? await a.requestAdapterInfo() : {});
// Features and limits are read by NAME, never by iterating them: the expression runs with the page's objects behind Xray wrappers, and
// `Array.from(a.features)` / `for (k in a.limits)` threw "Xray wrapping of iterators not supported" there (run 43652292533). `has` and a property
// read are plain calls. The names are those of the WebGPU specification (limits table and GPUFeatureName); one the engine does not know reads
// false / undefined, which is a value like any other.
const featureNames = ["depth-clip-control", "depth32float-stencil8", "texture-compression-bc", "texture-compression-bc-sliced-3d",
"texture-compression-etc2", "texture-compression-astc", "texture-compression-astc-sliced-3d", "timestamp-query", "indirect-first-instance",
"shader-f16", "rg11b10ufloat-renderable", "bgra8unorm-storage", "float32-filterable", "float32-blendable", "clip-distances",
"dual-source-blending", "subgroups"];
const limitNames = ["maxTextureDimension1D", "maxTextureDimension2D", "maxTextureDimension3D", "maxTextureArrayLayers", "maxBindGroups",
"maxBindGroupsPlusVertexBuffers", "maxBindingsPerBindGroup", "maxDynamicUniformBuffersPerPipelineLayout",
"maxDynamicStorageBuffersPerPipelineLayout", "maxSampledTexturesPerShaderStage", "maxSamplersPerShaderStage",
"maxStorageBuffersPerShaderStage", "maxStorageTexturesPerShaderStage", "maxUniformBuffersPerShaderStage", "maxUniformBufferBindingSize",
"maxStorageBufferBindingSize", "minUniformBufferOffsetAlignment", "minStorageBufferOffsetAlignment", "maxVertexBuffers", "maxBufferSize",
"maxVertexAttributes", "maxVertexBufferArrayStride", "maxInterStageShaderVariables", "maxColorAttachments",
"maxColorAttachmentBytesPerSample", "maxComputeWorkgroupStorageSize", "maxComputeInvocationsPerWorkgroup", "maxComputeWorkgroupSizeX",
"maxComputeWorkgroupSizeY", "maxComputeWorkgroupSizeZ", "maxComputeWorkgroupsPerDimension"];
const lim = {}, feat = {};
for (const k of limitNames) { try { lim[k] = a.limits[k]; } catch (e) { lim[k] = "ERR " + e.message; } }
for (const f of featureNames) { try { feat[f] = a.features.has(f); } catch (e) { feat[f] = "ERR " + e.message; } }
put("gpu.webgpu.info", { vendor: info.vendor, architecture: info.architecture, device: info.device, description: info.description });
put("gpu.webgpu.features", feat);
put("gpu.webgpu.limits", lim);
});
// ------------------------------------------------------------------------------------------------------------ DOM text
await scene("dom.text", async () => {
const box = document.createElement("div"); box.style.cssText = "position:absolute;left:0;top:0;white-space:nowrap";
document.body.appendChild(box);
const rows = [];
for (const f of FONTS) for (const t of TEXTS) {
const s = document.createElement("span"); s.style.font = f; s.textContent = t; box.appendChild(s);
const r = s.getBoundingClientRect();
rows.push([f, t, r.width, r.height, s.offsetWidth, s.offsetHeight]);
box.removeChild(s);
}
put("dom.span_boxes", rows);
const para = [];
for (const f of ["16px sans-serif", "15px 'Times New Roman'", "14px Consolas"]) {
const d = document.createElement("div"); d.style.cssText = "width:200px;font:" + f; d.textContent = TEXTS.join(" · ") + " " + TEXTS.join(" · ");
box.appendChild(d); const r = d.getBoundingClientRect(); para.push([f, r.width, r.height]); box.removeChild(d);
}
put("dom.paragraphs", para);
put("dom.fonts_check", FONTS.map((f) => [f, document.fonts.check(f)]));
const colors = ["Canvas", "CanvasText", "ButtonFace", "ButtonText", "ButtonBorder", "Field", "FieldText", "Highlight", "HighlightText", "GrayText", "LinkText",
"VisitedText", "ActiveText", "Mark", "MarkText", "AccentColor", "AccentColorText", "SelectedItem", "SelectedItemText"];
put("dom.system_colors", colors.map((c) => { const e = document.createElement("i"); e.style.color = c; box.appendChild(e); const v = getComputedStyle(e).color; box.removeChild(e); return [c, v]; }));
document.body.removeChild(box);
});
return out;
})()
@@ -34,6 +34,7 @@ from invisible_playwright._juggler.server import (
ArtifactDispatcher, BrowserContextDispatcher, BrowserDispatcher,
DebuggerDispatcher, JugglerServer, LocalUtilsDispatcher, PageDispatcher,
StreamDispatcher, TracingDispatcher)
from _browser_census import closes_with_the_test
pytestmark = pytest.mark.unit
@@ -44,6 +45,7 @@ class ScriptedJuggler(EventListeners):
def __init__(self):
super().__init__()
closes_with_the_test(self)
self._contexts = itertools.count(1)
self._targets = itertools.count(1)
self.sessions = {}
@@ -150,24 +152,47 @@ def test_the_browser_does_not_keep_the_contexts_it_closed(browser):
assert browser._buffered == {} and browser._live == set()
def _census(browser):
"""What this browser's server built and is still alive, after a collection.
Only ITS objects: another browser of the same process (an earlier test of the
same worker that left its contexts open) is not this server's census."""
kinds = (BrowserContextDispatcher, PageDispatcher, DebuggerDispatcher,
TracingDispatcher)
gc.collect()
return collections.Counter(type(o).__name__ for o in gc.get_objects()
if type(o) in kinds and o.server is browser.server)
def _assert_the_census_is_stable(browser):
for n in range(20):
_cycle(browser, n, close_page_first=n % 2 == 0)
first = _census(browser)
for n in range(20, 60):
_cycle(browser, n, close_page_first=n % 2 == 0)
assert _census(browser) == first
assert first.get("BrowserContextDispatcher", 0) == 0, first
def test_the_count_of_objects_is_stable_across_cycles(browser):
"""The census of what the server builds, after a collection, does not move
between 20 cycles and 60."""
kinds = (BrowserContextDispatcher, PageDispatcher, DebuggerDispatcher,
TracingDispatcher)
_assert_the_census_is_stable(browser)
def census():
gc.collect()
return collections.Counter(type(o).__name__ for o in gc.get_objects()
if type(o) in kinds)
for n in range(20):
_cycle(browser, n, close_page_first=n % 2 == 0)
first = census()
for n in range(20, 60):
_cycle(browser, n, close_page_first=n % 2 == 0)
assert census() == first
assert first.get("BrowserContextDispatcher", 0) == 0, first
def test_the_census_does_not_count_another_browsers_open_context(browser):
# The census counted every dispatcher of the process: run after a file that
# leaves its contexts open in the same worker, it saw 7 BrowserContextDispatcher
# that were not this server's (core #272, wrapper-on-this-core linux part 2).
server = remote._SharedServer()
other = remote.SharedBrowserDispatcher(server, remote.SharedBrowserType(server),
ScriptedJuggler(), "firefox/1")
left_open = server.object(server.handle(
{"guid": other.guid, "method": "newContext", "params": {}})["context"]["guid"])
try:
_assert_the_census_is_stable(browser)
assert left_open.guid in server._objects
finally:
server.shutdown()
def test_a_download_and_its_stream_are_let_go_with_their_context(browser):
+1
View File
@@ -57,6 +57,7 @@ def _page(handled):
page.disposed = False
page._held = None
page._held_lock = threading.Lock()
page._held_dropped = 0
page._detach_listeners = lambda: None
page._hear_lifecycle = lambda: None
page.context = types.SimpleNamespace(browser=types.SimpleNamespace(
@@ -0,0 +1,275 @@
"""The destination's commit of a popup, whenever it comes while the page is handed from the buffer to its dispatcher, reaches the client once.
NO BROWSER HERE (the real dispatchers over a scripted Juggler connection, as `test_every_order_of_the_events_of_a_popup_gives_one_page_event`).
A popup's page is built the moment the engine attaches its target, and what the client is told of its frame comes from two places: the
INITIALIZER (a snapshot of what the lifecycle knew when the frame dispatcher was made: url, name, load states) and the lifecycle's own
announcements (`navigated`, `loadstate`, a new frame), which go up through a hook (`Lifecycle.announce`) that the page installs at the
end of its construction (`_install_events` -> `_hear_lifecycle`). The page's own listener holds the events of the same period and
`_install_events` hands over only the `Network.*` ones. So an event that the lifecycle heard AFTER the snapshot and BEFORE the hook was
told to nobody: the commit of the destination left the client's frame at `about:blank` for good, and the `DOMContentLoaded`/`load` of
the destination was dropped with the held events (measured on Windows, `test_popups_reach_the_client_e2e.py` with no route on the context:
the popup "is at about:blank", or `wait_for_load_state("load")` times out).
The test parks the adoption thread at FOUR points of that passage - after the main frame is known (before the snapshot), as the main
frame's dispatcher is made (after the snapshot), as the events are installed (the hold is still on) and after they are installed (the hook
is in) - and delivers the destination's commit, `DOMContentLoaded` and `load` (in this order) at every placement of the three among the
four points, 20 cases, none sampled. (The hand-over itself, from the release of the hold to the hook, is one step with the lifecycle's lock
held: there is no point inside it to park at, which is the property that is wanted.) The page is then made ready and announced, and what the CLIENT was
told of the main frame (the initializer, then each `navigated` and `loadstate`, in order) must be what the lifecycle holds: the url of the
destination, the states commit/domcontentloaded/load, and the destination's url told exactly once.
Known-bad input: the code as it was -> the orders with an event between the snapshot and the hook are red.
"""
from __future__ import annotations
import itertools
import threading
import time
import pytest
from invisible_playwright._juggler import dispatcher as base
from invisible_playwright._juggler import remote
from invisible_playwright._juggler import server as server_mod
from invisible_playwright._juggler.server import LocalUtilsDispatcher
from test_every_order_of_the_events_of_a_popup_gives_one_page_event import Engine, FRAME, SESSION, TARGET, _thread, _wait
pytestmark = pytest.mark.unit
DEST = "http://dest.test/p"
POINTS = ["after_main_frame", "frame_dispatcher", "events_install", "events_installed"]
STATES = ("commit", "domcontentloaded", "load")
class PopupEngine(Engine):
def start(self):
self.dispatch_event("Page.navigationStarted", {"frameId": FRAME, "navigationId": "n2", "url": DEST}, SESSION)
def commit_dest(self):
self.dispatch_event("Page.navigationCommitted", {"frameId": FRAME, "navigationId": "n2", "url": DEST, "name": ""}, SESSION)
def dcl(self):
self.dispatch_event("Page.eventFired", {"frameId": FRAME, "name": "DOMContentLoaded"}, SESSION)
def load(self):
self.dispatch_event("Page.eventFired", {"frameId": FRAME, "name": "load"}, SESSION)
class Parking:
"""Stops the adoption thread of the popup at the four points of the passage, until the test lets it go on."""
def __init__(self):
self.reached = [threading.Event() for _ in POINTS]
self.release = [threading.Event() for _ in POINTS]
def pause(self, index):
if threading.current_thread().name != "invpw-adopt-%s" % TARGET or self.reached[index].is_set():
return
self.reached[index].set()
self.release[index].wait(10)
def open_all(self):
for event in self.release:
event.set()
def _install(mp, parking, told):
"""The parking points, and a record of what the client is told of the main frame of the popup."""
original_wait = server_mod.Lifecycle.wait_for_main_frame
def after_main_frame(self, *args, **kwargs):
result = original_wait(self, *args, **kwargs)
parking.pause(0)
return result
mp.setattr(server_mod.Lifecycle, "wait_for_main_frame", after_main_frame)
original_init = server_mod.FrameDispatcher.__init__
def frame_init(self, server, page, frame_id, url="about:blank", name="", load_states=None, parent_frame=None, told_commit=None):
if frame_id == FRAME and parent_frame is None:
parking.pause(1)
told["url"] = url
told["states"] = set(load_states or ["commit"])
told["navigated"] = []
told["ops"] = []
return original_init(self, server, page, frame_id, url=url, name=name, load_states=load_states, parent_frame=parent_frame, told_commit=told_commit)
mp.setattr(server_mod.FrameDispatcher, "__init__", frame_init)
original_install = server_mod.PageDispatcher._install_events
def install(self):
parking.pause(2)
result = original_install(self)
parking.pause(3)
return result
mp.setattr(server_mod.PageDispatcher, "_install_events", install)
original_emit = base.Dispatcher.emit
def spy(self, method, params=None):
if getattr(self, "TYPE", "") == "Frame" and getattr(self, "frame_id", None) == FRAME and "ops" in told:
if method == "navigated":
told["navigated"].append(params["url"])
told["ops"].append(("url", params["url"]))
elif method == "loadstate":
for key in ("add", "remove"):
if key in params:
told["ops"].append((key, params[key]))
return original_emit(self, method, params)
mp.setattr(base.Dispatcher, "emit", spy)
def _client_view(told):
url, states = told["url"], set(told["states"])
for op, value in told["ops"]:
if op == "url":
url = value
elif op == "add":
states.add(value)
elif op == "remove":
states.discard(value)
return url, states
def _run(placement):
"""One case: commit_dest, dcl and load delivered at the points in `placement` (one per event, in order)."""
parking, told, announced = Parking(), {}, []
with pytest.MonkeyPatch.context() as mp:
_install(mp, parking, told)
original_emit = base.Dispatcher.emit
def page_spy(self, method, params=None):
if method == "page" and getattr(self, "TYPE", "") == "BrowserContext":
announced.append(time.monotonic())
return original_emit(self, method, params)
mp.setattr(base.Dispatcher, "emit", page_spy)
server = remote._SharedServer()
browser_type = remote.SharedBrowserType(server)
LocalUtilsDispatcher(server)
conn = PopupEngine()
browser = remote.SharedBrowserDispatcher(server, browser_type, conn, "firefox/1")
try:
context = server.object(server.handle({"guid": browser.guid, "method": "newContext", "params": {}})["context"]["guid"])
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
opener_target = next(t for t in conn.sessions if t != TARGET)
del announced[:]
conn.attach(opener_target, context.context_id)
conn.frame()
conn.commit() # the initial about:blank
conn.start() # the navigation to the address starts
todo = list(zip(["commit_dest", "dcl", "load"], placement))
for i in range(len(POINTS)):
assert parking.reached[i].wait(5), "the adoption thread never reached %s" % POINTS[i]
for event, where in list(todo):
if where == i:
getattr(conn, event)()
todo.remove((event, where))
parking.release[i].set()
conn.ready()
assert _wait(lambda: announced), "the popup was never announced"
assert _wait(lambda: _thread() is None), "the adoption thread never ended"
page = browser._page_targets.get(TARGET)
frame = page.lifecycle.frames[FRAME]
return _client_view(told), (frame.url, {s for s in frame.states if s in STATES}), told
finally:
parking.open_all()
try:
server.shutdown()
except Exception:
pass
def test_the_commit_and_the_load_of_the_destination_reach_the_client_whenever_they_come_while_the_page_is_handed_over():
failures, count = [], 0
for combo in itertools.combinations_with_replacement(range(len(POINTS)), 3):
count += 1
(client_url, client_states), (url, states), told = _run(combo)
label = "commit_dest/dcl/load at %s" % [POINTS[i] for i in combo]
problems = []
if client_url != url:
problems.append("the client's frame is at %r, the lifecycle's at %r" % (client_url, url))
if {s for s in client_states if s in STATES} != states:
problems.append("the client has the states %s, the lifecycle %s" % (sorted(client_states & set(STATES)), sorted(states)))
told_dest = (1 if told["url"] == DEST else 0) + told["navigated"].count(DEST)
if told_dest != 1:
problems.append("the destination's address was told %d times" % told_dest)
if problems:
failures.append("%s: %s" % (label, "; ".join(problems)))
assert count == 20
assert not failures, "%d of %d orders lost or doubled an event, e.g.:\n %s" % (len(failures), count, "\n ".join(failures[:12]))
def _run_announcement(where):
"""The blank page loads, the page is made ready, and the destination's commit comes at `where`: before the ready, or WHILE the page is
announced (the adoption thread is parked inside the announcement, after the `page` event and before the replay of the states said
before it, and the commit is delivered by another thread, as the engine's reader would)."""
told, announced, inside = {}, [], threading.Event()
go = threading.Event()
with pytest.MonkeyPatch.context() as mp:
open_parking = Parking()
open_parking.open_all()
_install(mp, open_parking, told) # the record of what the client is told; its parking points are open
original_emit = base.Dispatcher.emit
def page_spy(self, method, params=None):
result = original_emit(self, method, params)
if method == "page" and getattr(self, "TYPE", "") == "BrowserContext" and threading.current_thread().name == "invpw-adopt-%s" % TARGET:
announced.append(True)
inside.set()
go.wait(10)
return result
mp.setattr(base.Dispatcher, "emit", page_spy)
server = remote._SharedServer()
browser_type = remote.SharedBrowserType(server)
LocalUtilsDispatcher(server)
conn = PopupEngine()
browser = remote.SharedBrowserDispatcher(server, browser_type, conn, "firefox/1")
try:
context = server.object(server.handle({"guid": browser.guid, "method": "newContext", "params": {}})["context"]["guid"])
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
opener_target = next(t for t in conn.sessions if t != TARGET)
del announced[:]
told.clear()
conn.attach(opener_target, context.context_id)
conn.frame()
conn.commit()
conn.start()
assert _wait(lambda: (browser._adoptions.get(TARGET) is not None and browser._adoptions[TARGET].state == "waiting")), \
"the adoption never waited for the ready"
conn.dcl() # the blank page's load, said live and kept for the replay
conn.load()
deliverer = None
if where == "before_ready":
conn.commit_dest()
conn.ready()
else:
conn.ready()
assert inside.wait(5), "the page was never announced"
deliverer = threading.Thread(target=conn.commit_dest, daemon=True)
deliverer.start()
time.sleep(0.2) # the commit is on its way while the announcement is not over
go.set()
if deliverer is not None:
deliverer.join(5)
assert _wait(lambda: _thread() is None), "the adoption thread never ended"
page = browser._page_targets.get(TARGET)
known = page.lifecycle.frames[FRAME]
return _client_view(told), (known.url, {s for s in known.states if s in STATES}), told
finally:
go.set()
try:
server.shutdown()
except Exception:
pass
@pytest.mark.parametrize("where", ["before_ready", "during_announcement"])
def test_a_commit_before_or_during_the_announcement_leaves_the_client_with_the_states_of_the_destination(where):
(client_url, client_states), (url, states), told = _run_announcement(where)
assert client_url == url == DEST
assert {s for s in client_states if s in STATES} == states == {"commit"}, (
"the client has the states %s of a destination that has only committed: the load of the blank page, said again after the "
"commit, is still on its frame" % sorted(client_states & set(STATES)))
assert (1 if told["url"] == DEST else 0) + told["navigated"].count(DEST) == 1
@@ -0,0 +1,31 @@
"""`context.add_init_script` added after a page exists runs once in each document, not twice.
The context-level script was registered on both sides: in the browser (`Browser.setInitScripts`, which the engine applies to every
page of the context, the ones already open included) and, for the pages already open, again in each page's own list. A page that
existed when the script was added ran it twice in every later document; a page opened afterwards ran it once, so the test that adds the
script first passed. Playwright runs a context script once in each document of each page.
"""
from __future__ import annotations
import pytest
pytestmark = pytest.mark.e2e
PAGE = ("<!doctype html><title>t</title><script>window.__seen = JSON.stringify(window.__o || []);</script>")
def test_a_context_script_added_after_the_page_exists_runs_once(firefox_binary, tmp_path):
from invisible_playwright import InvisiblePlaywright
(tmp_path / "p.html").write_text(PAGE, encoding="utf-8")
url = (tmp_path / "p.html").as_uri()
with InvisiblePlaywright(seed=4261, binary_path=firefox_binary, headless=True) as browser:
context = browser.new_context()
existing = context.new_page() # the page exists BEFORE the script
context.add_init_script("(window.__o = window.__o || []).push('init');")
later = context.new_page() # and a page opened AFTER it
for page in (existing, later):
page.goto(url, wait_until="load")
assert page.evaluate("window.__o") == ["init"], "the script ran %r" % page.evaluate("window.__o")
page.goto(url + "?again", wait_until="load") # the next document of the same page, too
assert page.evaluate("window.__o") == ["init"], "the second document ran %r" % page.evaluate("window.__o")
@@ -29,6 +29,7 @@ from invisible_core.juggler.connection import EventListeners
from invisible_playwright import _session
from invisible_playwright._juggler.server import (BrowserDispatcher, Server, UDP_STUN_PREF,
session_udp_stun_servers, take_session_motion)
from _browser_census import closes_with_the_test
pytestmark = pytest.mark.unit
@@ -39,6 +40,7 @@ STUN = ["%s:%d" % (STUN_NUMBER, STUN_PORT)]
class _Connection(EventListeners):
def __init__(self, gateways=()):
super().__init__()
closes_with_the_test(self)
self.sent = []
self.datagrams_before = {}
self._gateways = gateways
@@ -16,6 +16,7 @@ from invisible_core.juggler.connection import EventListeners
from invisible_playwright._juggler.server import (
BrowserContextDispatcher, BrowserDispatcher, Server,
)
from _browser_census import closes_with_the_test
class _Engine(EventListeners):
@@ -23,6 +24,7 @@ class _Engine(EventListeners):
def __init__(self):
super().__init__()
closes_with_the_test(self)
self.sent = []
def startup_send(self, method, params=None):
@@ -0,0 +1,99 @@
"""A CORS preflight is not a request the client hears of, as on stock Firefox.
A page at one origin fetches another origin with a header that needs a preflight: the browser sends an OPTIONS request first. Playwright's
own server drops an OPTIONS request that no route holds before the client can see it (ffNetworkManager `_onRequestWillBeSent`);
ours reported it, so a page with preflighted fetches showed more requests than on stock (measured on cnbc.com and scmp.com: 10 and
18 OPTIONS requests a page, none on stock). The test counts what the client hears: the document and the two fetches, no OPTIONS, with
and without a context route (a route that holds the request is another story and keeps it).
"""
from __future__ import annotations
import threading
from http.server import BaseHTTPRequestHandler
import pytest
from _servers import LocalServer
pytestmark = pytest.mark.e2e
class _Api(BaseHTTPRequestHandler):
hits: list = []
def log_message(self, *a):
pass
def _cors(self):
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Access-Control-Allow-Headers", "x-test")
self.send_header("Access-Control-Allow-Methods", "GET, OPTIONS")
def do_OPTIONS(self):
_Api.hits.append(("OPTIONS", self.path))
self.send_response(204)
self._cors()
self.end_headers()
def do_GET(self):
_Api.hits.append(("GET", self.path))
body = b'{"ok":1}'
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self._cors()
self.end_headers()
self.wfile.write(body)
def _page(api_origin):
return ("<!doctype html><title>preflight</title><script>"
"fetch('%s/one', {headers: {'x-test': '1'}}); fetch('%s/two', {headers: {'x-test': '2'}});"
"</script>" % (api_origin, api_origin)).encode()
@pytest.fixture
def two_origins():
_Api.hits = []
class Page(BaseHTTPRequestHandler):
def log_message(self, *a):
pass
def do_GET(self):
body = _page(self.server.api_origin)
self.send_response(200)
self.send_header("Content-Type", "text/html")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
api = LocalServer(("127.0.0.1", 0), _Api)
page = LocalServer(("127.0.0.1", 0), Page)
page.api_origin = "http://localhost:%d" % api.server_address[1]
for srv in (api, page):
threading.Thread(target=srv.serve_forever, daemon=True).start()
try:
yield "http://127.0.0.1:%d/" % page.server_address[1]
finally:
for srv in (api, page):
srv.shutdown()
srv.server_close()
@pytest.mark.parametrize("route", [False, True])
def test_the_client_hears_the_document_and_the_fetches_and_no_preflight(firefox_binary, two_origins, route):
from invisible_playwright import InvisiblePlaywright
heard = []
with InvisiblePlaywright(seed=4261, binary_path=firefox_binary, headless=True) as browser:
context = browser.new_context()
if route:
context.route("**/*", lambda r: r.continue_())
page = context.new_page()
page.on("request", lambda r: heard.append((r.method, r.url.rsplit("/", 1)[-1] or "page")))
page.goto(two_origins, wait_until="load")
page.wait_for_timeout(2000) # the events of a sync client are delivered while it calls the browser
assert ("OPTIONS", "/one") in _Api.hits or ("OPTIONS", "/two") in _Api.hits, "the browser made no preflight: %r" % _Api.hits
methods = sorted(m for m, _ in heard)
assert methods == ["GET", "GET", "GET"], "the client heard %r (the server saw %r)" % (heard, _Api.hits)
@@ -34,6 +34,8 @@ def page():
page.injected = Mock()
page.actions = Mock()
page._frames = {}
page._told_attached = set()
page._frames_lock = __import__("threading").RLock()
page._navigation_requests = {}
page._announced_closed = False
Dispatcher.__init__(page, server, context)
@@ -331,6 +331,7 @@ def _seed_whose_first_field_pause_is_longer_than(seconds):
@pytest.mark.e2e
@pytest.mark.wall_clock
@pytest.mark.parametrize("how", ["fill", "press_sequentially"])
def test_a_store_that_answers_the_focus_does_not_eat_the_text(firefox_binary, store_url, how):
"""Known-bad, measured on 0.25.8 before this change: the store's write at
+2
View File
@@ -24,6 +24,7 @@ from invisible_playwright._juggler.server import (
BrowserTypeDispatcher, JugglerServer)
from invisible_playwright._juggler.transport import _translate_exception
from invisible_playwright.sync_api import TimeoutError as PlaywrightTimeout
from _browser_census import closes_with_the_test
PROXY = {"server": "socks5://127.0.0.1:1080", "username": "u", "password": "p"}
@@ -34,6 +35,7 @@ class _Engine(EventListeners):
def __init__(self, silent=()):
EventListeners.__init__(self)
closes_with_the_test(self)
self.silent = set(silent)
self.bounds: dict = {}
self.startup: list = []
@@ -24,6 +24,7 @@ from invisible_playwright import _session
from invisible_playwright._juggler import server as module
from invisible_playwright._juggler.server import (SESSION_SEED_PREF, BrowserTypeDispatcher,
JugglerServer)
from _browser_census import closes_with_the_test
# Read with a default so that, on the code before the fix, the test fails on what the
# profile holds and not on an import.
@@ -35,6 +36,7 @@ _LINE = re.compile(r'^user_pref\("([^"]+)",\s*(.*)\);\s*$')
class _Engine(EventListeners):
def __init__(self):
EventListeners.__init__(self)
closes_with_the_test(self)
def send(self, method, params=None, session=None, timeout=30.0):
return {"browserContextId": "ctx-1", "targetId": "t-1"}
@@ -0,0 +1,190 @@
"""An event the engine sends LIVE while the events a new page missed are being replayed to it does not reach it before them.
NO BROWSER HERE (the real dispatchers over a scripted Juggler connection, as `test_the_hand_over_of_a_popup_holds_under_concurrency`).
The browser buffers the events of a session nobody reads yet, and `PageDispatcher` is handed them (`BrowserDispatcher.replay`) once its
lifecycle and its injected script are subscribed. The replay ran on the adoption thread while the engine's reader went on delivering the
live events to the same subscribers: a popup's destination committed (live) in the middle of the replay of its first events, and the
replay then went on with the OLDER ones - the initial `about:blank` (no navigation of ours) and the `navigationStarted` of the same
navigation. The lifecycle ended at `about:blank` for good (a popup "at about:blank": the client was never told of the destination), or
had the navigation pending again after its own commit ("Execution context was destroyed" in the first evaluate). Measured on Windows with
the engine's events traced (`POPUP-63-SECONDA-CAUSA.md`): the second `Page.frameAttached` of every popup in the traces IS the replay, and
the engine sends each event once - 13 reds in 20 runs of the popup file on engine 63 after the hand-over fix, none of them with a second
`frameAttached` from the engine (`PageHandler._onFrameAttached` answers nothing for a frame it holds live).
Sequence of the test: the first events of a popup are buffered (frame, blank commit, the destination's navigation started) -> the page is
built and the replay starts, stopped after its first event -> the engine's reader delivers the destination's commit -> the replay goes on.
Whatever the interleaving, the lifecycle must end at the destination, with the navigation committed and not pending, and the client's
frame must be told the destination.
Known-bad input: the replay as it was -> the lifecycle ends at `about:blank` and the navigation of the destination is pending again.
"""
from __future__ import annotations
import threading
import pytest
from invisible_playwright._juggler import server as server_mod
from test_a_commit_at_any_point_of_the_hand_over_reaches_the_client_once import DEST
from test_the_hand_over_of_a_popup_holds_under_concurrency import World, _finish
from test_every_order_of_the_events_of_a_popup_gives_one_page_event import FRAME, SESSION, TARGET, _thread, _wait
pytestmark = pytest.mark.unit
def _case(stop_after, scenario="commit"):
"""The replay is stopped after `stop_after` of its events; the live event of the scenario is delivered by another thread (the reader):
the destination's commit, or (`context`) the creation of a new utility context after the old one was destroyed."""
parked, go, delivered = threading.Event(), threading.Event(), []
with pytest.MonkeyPatch.context() as mp:
original = server_mod.BrowserDispatcher.replay
def replay(self, session, deliver):
if session != SESSION:
return original(self, session, deliver)
count = [0]
def slow(method, params, s):
deliver(method, params, s)
delivered.append(method)
count[0] += 1
if count[0] == stop_after:
parked.set()
go.wait(10)
return original(self, session, slow)
mp.setattr(server_mod.BrowserDispatcher, "replay", replay)
# the adoption thread is held before the page is built, so that the first events of the popup are buffered when it is
entered, begin = threading.Event(), threading.Event()
original_build = server_mod.BrowserDispatcher._enter_building
def enter_building(self, *args, **kwargs):
if threading.current_thread().name == "invpw-adopt-%s" % TARGET:
entered.set()
begin.wait(10)
return original_build(self, *args, **kwargs)
mp.setattr(server_mod.BrowserDispatcher, "_enter_building", enter_building)
world = World()
reader = None
try:
conn = world.conn
conn.attach(world.opener_target, world.context.context_id)
assert entered.wait(5), "the adoption never started"
conn.frame()
conn.commit() # the initial about:blank (navigation n1)
conn.start() # the navigation to the destination starts (n2)
if scenario == "context":
conn.dispatch_event("Runtime.executionContextDestroyed", {"executionContextId": "eutility"}, SESSION)
begin.set() # the page is built now, and the replay hands it those events
assert parked.wait(5), "the replay never delivered %d event(s): %s" % (stop_after, delivered)
live = conn.commit_dest if scenario == "commit" else (lambda: conn.dispatch_event("Runtime.executionContextCreated", {
"executionContextId": "eutility2", "auxData": {"frameId": FRAME, "name": "utility"}}, SESSION))
reader = threading.Thread(target=live, daemon=True, name="engine-reader")
reader.start()
reader.join(0.3) # with the replay ordered, the reader waits behind it; unordered, it is through
go.set()
reader.join(5)
assert not reader.is_alive(), "the reader never got through"
conn.ready()
assert _wait(lambda: _thread() is None), "the adoption thread never ended"
page = world.browser._page_targets.get(TARGET)
known = page.lifecycle.frames[FRAME]
if scenario == "context":
return page.injected.contexts.get((FRAME, "utility"))
return known.url, known.navigation, sorted(known.states), page.frame.url
finally:
begin.set()
go.set()
world.close()
@pytest.mark.parametrize("stop_after", [1, 2, 3, 4, 5])
def test_the_destination_commit_delivered_while_the_replay_goes_on_is_the_last_word(stop_after):
url, navigation, states, told = _case(stop_after)
assert url == DEST, "the lifecycle ended at %r: an older event of the replay came after the live commit" % url
assert navigation == "n2", "the frame's navigation is %r" % navigation
assert "commit" in states
assert told == DEST, "the client's frame is at %r" % told
@pytest.mark.parametrize("stop_after", [1, 2])
def test_a_context_created_while_the_replay_goes_on_is_not_undone_by_an_older_event(stop_after):
"""The same race for the injected script: the replay brings the creation of the utility context and its destruction, the engine creates a
new one meanwhile. The new one is the context the injected script must end with."""
context = _case(stop_after, "context")
assert context == "eutility2", "the injected script ended with the utility context %r" % (context,)
def test_a_patch_of_the_class_made_after_the_browser_was_built_still_sees_the_events():
"""The reader looked the delivery up on the class at each event; the gate keeps doing so (the e2e fixtures that record the events patch
`EventListeners.dispatch_event` after the browser exists)."""
from invisible_core.juggler.connection import EventListeners
world = World()
try:
seen = []
original = EventListeners.dispatch_event
with pytest.MonkeyPatch.context() as mp:
mp.setattr(EventListeners, "dispatch_event", lambda self, method, params, session: seen.append((method, session)))
world.conn.dispatch_event("Page.x", {}, "S-patched")
assert seen == [("Page.x", "S-patched")]
assert EventListeners.dispatch_event is original
finally:
world.close()
def test_a_gate_that_is_never_let_go_costs_the_reader_one_wait_and_is_said():
"""The bound is on the hold, not on each event: the first event waits GATE_WAIT_S, the next ones are delivered at once, and the
connection records it."""
import time
world = World()
held, release, got = threading.Event(), threading.Event(), []
try:
world.browser.GATE_WAIT_S = 0.2
def holder():
with world.browser.events_gate():
held.set()
release.wait(10)
t = threading.Thread(target=holder, daemon=True)
t.start()
assert held.wait(5)
world.conn.add_listener(lambda m, p, s: got.append(m) if s == "S-stuck" else None)
began = time.monotonic()
for n in range(3):
world.conn.dispatch_event("Page.e%d" % n, {}, "S-stuck")
took = time.monotonic() - began
assert got == ["Page.e0", "Page.e1", "Page.e2"], got
assert took < 1.0, "the reader waited %.2fs for three events: the bound is per event" % took
assert world.browser._gate_timeouts == 1
assert any("events gate" in str(e) for e in world.conn.handler_errors), world.conn.handler_errors
finally:
release.set()
world.close()
def test_a_page_built_while_the_reader_is_stuck_in_a_handler_is_built_all_the_same_and_it_is_said():
import warnings
world = World()
held, release = threading.Event(), threading.Event()
try:
world.browser.PAGE_GATE_WAIT_S = 0.2
def stuck_reader():
with world.browser.events_gate():
held.set()
release.wait(10)
t = threading.Thread(target=stuck_reader, daemon=True)
t.start()
assert held.wait(5)
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
with world.browser.events_gate():
pass
assert any("held for more than" in str(w.message) for w in caught), [str(w.message) for w in caught]
finally:
release.set()
world.close()
@@ -74,7 +74,7 @@ ON_WINDOWS = sys.platform == "win32"
@pytest.mark.skipif(ON_WINDOWS, reason="the system theme is declared, and its absence refused, on Linux only")
@pytest.mark.parametrize("pref", MISSING)
def test_a_missing_pref_refuses_the_launch(firefox_binary, engine_at_least, pref):
engine_at_least("firefox-64")
engine_at_least("firefox-65")
with pytest.raises(RuntimeError) as err:
c, profile_dir = _launch(firefox_binary, pref)
# Not reached when the engine refuses: close what must not be running.
@@ -88,7 +88,7 @@ def test_a_missing_pref_refuses_the_launch(firefox_binary, engine_at_least, pref
@pytest.mark.e2e
def test_every_pref_declared_the_launch_succeeds(firefox_binary, engine_at_least):
engine_at_least("firefox-64")
engine_at_least("firefox-65")
c, profile_dir = _launch(firefox_binary, None)
try:
assert c.ready_seen, "the browser did not announce the protocol"
@@ -0,0 +1,109 @@
"""The check of tests/_browser_census.py is red on a module that leaks a browser and green on one that closes it.
Each case is a module of its own in a fresh pytest (the check is module level and the leak would otherwise count against this file).
"""
import os
import subprocess
import sys
import textwrap
from pathlib import Path
TESTS = str(Path(__file__).resolve().parent)
_BUILD = """
from invisible_playwright._juggler._threads import ThreadStarter
def build():
return ThreadStarter(on_error=lambda message: None)
"""
def _run(tmp_path, body):
(tmp_path / "conftest.py").write_text("from _browser_census import _a_module_leaves_no_browser_open # noqa\n")
(tmp_path / "test_the_module.py").write_text(textwrap.dedent(_BUILD) + textwrap.dedent(body))
env = dict(os.environ, PYTHONPATH=TESTS + os.pathsep + os.environ.get("PYTHONPATH", ""))
return subprocess.run(
[sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider", "-o", "addopts=", str(tmp_path / "test_the_module.py")],
cwd=str(tmp_path), env=env, capture_output=True, text=True, timeout=120,
)
def test_a_module_that_never_closes_what_it_built_fails(tmp_path):
done = _run(tmp_path, """
def test_one():
build()
def test_two():
build()
""")
out = done.stdout + done.stderr
assert done.returncode != 0, out
assert "left 2 browser(s) open: close their connection" in out, out
assert "2 passed" in out and "1 error" in out, out # the tests pass; the module is the one that fails
def test_a_module_that_closes_what_it_built_passes(tmp_path):
done = _run(tmp_path, """
import pytest
@pytest.fixture
def starter():
built = build()
yield built
built.stop()
def test_one(starter):
pass
def test_two(starter):
pass
""")
out = done.stdout + done.stderr
assert done.returncode == 0, out
assert "2 passed" in out and "error" not in out, out
def test_a_browser_shared_by_the_tests_of_a_module_may_stay_open_until_the_module_ends(tmp_path):
done = _run(tmp_path, """
import pytest
@pytest.fixture(scope="module")
def shared():
built = build()
yield built
built.stop()
def test_one(shared):
pass
def test_two(shared):
pass
""")
out = done.stdout + done.stderr
assert done.returncode == 0, out
assert "2 passed" in out, out
def test_the_census_counts_a_starter_whose_thread_has_not_begun(monkeypatch):
"""The starter's thread is begun without waiting for it, so right after the constructor it can be in no `threading.enumerate()`:
the census must still count it (it missed both leaks of a module on a Linux runner, 3 of 3 jobs)."""
import threading
import time
sys.path.insert(0, TESTS)
import _browser_census as census
from invisible_playwright._juggler._threads import ThreadStarter
original = threading.Thread.start
def slow_start(self):
time.sleep(0.3)
return original(self)
monkeypatch.setattr(threading.Thread, "start", slow_start)
before = len(census.starters_alive())
starter = ThreadStarter(on_error=lambda message: None)
try:
assert len(census.starters_alive()) == before + 1
finally:
starter.stop()
assert census.wait_until_back_to(before) == 0
@@ -19,6 +19,7 @@ from invisible_playwright._juggler import server as srv
from invisible_playwright._juggler.server import (
BrowserContextDispatcher, BrowserDispatcher, Server,
)
from _browser_census import closes_with_the_test
#: How long this engine takes to answer `Browser.newPage`, in its own clock.
ANSWER_AFTER_S = 35.0
@@ -30,6 +31,7 @@ class _SlowEngine(EventListeners):
def __init__(self):
super().__init__()
closes_with_the_test(self)
self.browser = None
self.bounds = []
@@ -75,12 +77,16 @@ class _Page:
def test_a_page_the_engine_answers_after_35_s_is_still_a_page(monkeypatch):
monkeypatch.setattr(srv, "PageDispatcher", _Page)
engine = _SlowEngine()
browser = BrowserDispatcher(Server(), None, engine, "151.0", session_seed=1)
server = Server()
browser = BrowserDispatcher(server, None, engine, "151.0", session_seed=1)
engine.browser = browser
context = BrowserContextDispatcher(browser.server, browser, {}, "C1")
browser.contexts.append(context)
result = context.op_new_page({"pageNumber": 0})
try:
result = context.op_new_page({"pageNumber": 0})
finally:
server.shutdown() # the connection's one starter ends with its server
assert result == {"page": {"guid": "page-T0"}}
assert engine.bounds == [None], (
@@ -0,0 +1,60 @@
"""A popup's page that is closed (the caller closes the context or the browser) while it is being adopted is not announced to the client afterwards.
NO BROWSER HERE (the real dispatchers over a scripted Juggler connection, as `test_the_hand_over_of_a_popup_holds_under_concurrency`).
The page's guid exists for the client from the moment the page is built (its `__create__`), and the context's `page` event is what tells the client
to treat it as a page. A close that comes in between sends `close` and `__dispose__` for that guid; the adoption then said `page` for it, and the
client threw (an event naming an object it had dropped, the family of `'dict' object has no attribute '_object'`).
Sequence: the adoption thread is parked before the hook goes in -> the page is closed (`announce_closed`) -> the adoption thread goes on to
announce the page. Nothing may be sent for the page, or about it, after its `__dispose__`.
Known-bad input: 436f815 + the fixes of the concurrency review, without the guard in `announce` -> a `page` event after the `__dispose__`.
"""
from __future__ import annotations
import threading
import pytest
from test_the_hand_over_of_a_popup_holds_under_concurrency import World, _adopter, _wait, _thread, POINTS, Parking, _install
from invisible_playwright._juggler import server as server_mod
pytestmark = pytest.mark.unit
def test_a_page_closed_before_its_announcement_is_never_announced():
parking, told = Parking(), {}
sent, caught, at_hook, go = [], [], threading.Event(), threading.Event()
with pytest.MonkeyPatch.context() as mp:
_install(mp, parking, told)
original = server_mod.PageDispatcher._hear_lifecycle
def hear(self):
if _adopter() and not caught:
caught.append(self)
at_hook.set()
go.wait(10)
return original(self)
mp.setattr(server_mod.PageDispatcher, "_hear_lifecycle", hear)
world = World()
mp.setattr(world.server, "send_up", lambda message: sent.append(message))
try:
world.born()
for i in range(3):
assert parking.reached[i].wait(5), "the adoption thread never reached %s" % POINTS[i]
parking.release[i].set()
assert at_hook.wait(5), "the adoption thread never reached the hook"
page = caught[0]
page.announce_closed()
disposed_at = next(i for i, m in enumerate(sent) if m.get("method") == "__dispose__" and m.get("guid") == page.guid)
go.set()
parking.open_all()
assert _wait(lambda: _thread() is None), "the adoption thread never ended"
after = [m for m in sent[disposed_at + 1:] if m.get("method") in ("page", "__create__")
or m.get("params", {}).get("page", {}).get("guid") == page.guid]
assert not after, "told after the page's __dispose__: %s" % [(m.get("method"), m.get("guid")) for m in after]
finally:
go.set()
parking.open_all()
world.close()
@@ -1,50 +0,0 @@
"""A client of the server cannot turn the launch counter off or point it elsewhere (no browser).
The core refuses the two prefs of the counter in ``extra_prefs``; the server takes ``firefoxUserPrefs`` from a client and, for a launch
that names no session, puts them on top of the session it composes, and for a marked launch takes them as they come. Both roads are
closed here, at ``session_for_launch``, with the core's own refusal.
"""
from __future__ import annotations
import pytest
from invisible_core.prefs import USAGE_PING_PREFS, USAGE_PING_REFUSAL, USAGE_PING_URL
from invisible_playwright._juggler import server
pytestmark = pytest.mark.unit
ENABLED, URL = USAGE_PING_PREFS
@pytest.fixture(autouse=True)
def composed_session(monkeypatch):
"""The session the server composes for an unmarked launch, without composing one (that needs an engine)."""
import invisible_playwright._session as session
monkeypatch.setattr(session, "default_session", lambda executable, proxy=None: ({URL: USAGE_PING_URL, "x": 1}, {}))
@pytest.mark.parametrize("pref,value", [(ENABLED, False), (ENABLED, True), (ENABLED, None), (URL, "https://example.invalid/x"), (URL, None)])
@pytest.mark.parametrize("marked", [False, True], ids=["bare launch", "marked launch"])
def test_a_client_cannot_send_the_counter_prefs(pref, value, marked):
prefs = {pref: value}
if marked:
prefs[server.COMPOSED_PREF] = True
with pytest.raises(ValueError) as refused:
server.session_for_launch(prefs, "firefox")
assert pref in str(refused.value) and USAGE_PING_REFUSAL in str(refused.value)
def test_the_address_the_core_wrote_travels_in_a_marked_launch():
prefs, _env = server.session_for_launch({server.COMPOSED_PREF: True, URL: USAGE_PING_URL, "y": 2}, "firefox")
assert prefs[URL] == USAGE_PING_URL and prefs["y"] == 2 and ENABLED not in prefs
def test_a_bare_launch_gets_the_core_address_and_the_clients_other_prefs():
prefs, _env = server.session_for_launch({"z": 3}, "firefox")
assert prefs[URL] == USAGE_PING_URL and prefs["z"] == 3 and ENABLED not in prefs
def test_the_same_address_in_a_bare_launch_is_still_refused():
"""Only the address the CORE wrote, inside a composed launch, is let through: a bare client that names it is refused too."""
with pytest.raises(ValueError):
server.session_for_launch({URL: USAGE_PING_URL}, "firefox")
@@ -28,8 +28,10 @@ def _serve():
pass
def do_GET(self):
kind = self.path.strip("/").split("/")[0].split("?")[0]
if kind in BODIES:
asked = self.path.strip("/").split("/")[0].split("?")[0]
# the name that goes into the header is the dict's own key, found by comparison: nothing of the request is written back
kind = next((name for name in BODIES if name == asked), None)
if kind is not None:
body = BODIES[kind]
self.send_response(200)
self.send_header("content-type", "application/octet-stream")
@@ -0,0 +1,116 @@
"""E2E: a TURN server given by NAME, over TCP, in a context with a proxy, is resolved by the DoH through THAT proxy.
EXPECTED RED ON THE PUBLISHED ENGINE firefox-63, GREEN ON firefox-64 (the engine fix is commit ac0214bff4 with 058edd6cc6). The test is not gated and
not skipped: it runs on every engine, so the candidate of firefox-64 (this branch runs there as ``wrapper_ref``) is red when the fix is missing, and
firefox-63 is red because it does not have it.
The defect. A page asks for ``turn:<name>:3478?transport=tcp``. The TCP socket that talks to the TURN server (``WebrtcTCPSocket``) did not
carry the origin attributes of its PeerConnection, so its name lookup was made in the DEFAULT user context. In a session with no proxy at
launch and a proxy on the context (the scheme of ``test_context_proxy_only_resolves_by_doh_e2e.py``) the default context resolves natively:
the lookup went to the system resolver (a question for a name of a proxied page, and the DoH never saw it); with a proxy at launch AND a
different one on the context, the DoH request left by the proxy of the LAUNCH, the wrong exit. The STUN and the TURN-over-UDP names do not
have the defect (``test_ice_names_by_the_context_proxy_e2e.py``), and the TURN over TCP by an IP does not resolve at all
(``test_webrtc_realness.py::test_the_turn_over_tcp_of_a_context_goes_through_the_proxy_of_that_context``): no test of the main line made the
browser resolve a TURN name over TCP, so nothing showed it. Found by the minimal engine's matrix of page work behind a proxy.
What the page does and what is read (two schemes, as in ``test_nothing_leaves_but_the_proxy_e2e.py``):
* ``context_only``: no launch proxy, a context with a SOCKS5 gateway. The name must reach the DoH by that gateway, the resolver of the
machine must be asked nothing for it (the trap, Linux root), and the gateway must be handed the ADDRESS the DoH answered (198.51.100.7,
a documentation address nothing routes: the gateway refuses it and lists it);
* ``launch_and_context``: a launch gateway and a different one for the context. The name must reach the DoH by the gateway of the CONTEXT
and by no other, and nothing at all may go direct or ask the resolver.
Red on the defect: the DoH is never asked for the name (the lookup took the native road, or the default context's DoH request failed its
handshake by design), and on Linux the trap heard the name.
"""
from __future__ import annotations
import pytest
# The fixtures and the helpers of the DoH e2e (imported, not copied). `doh`, `gateway`, `pages`, `trap` and `watcher` are in conftest.py.
from test_doh_through_the_proxy_e2e import ( # noqa: F401 (the hermetic session is autouse and imported by name)
DOH_ADDRESSES, ZONE, _assert_every_connection_went_through_the_gateway, _direct_to_the_doh, _hermetic_session, _is_address, _launch,
_page_in, _why)
import _doh_servers as ds
from _doh_servers import DOH_HOST, QTYPE_A, FakeDoh
pytestmark = [pytest.mark.e2e]
#: A documentation address of its own (not the STUN one, 198.51.100.5, nor the core's measurement one, 198.51.100.6).
TURN_NUMBER = "198.51.100.7"
TURN_NAME = "turn-a.test"
TURN_PORT = 3478
TURN_ZONE = {**ZONE, TURN_NAME: TURN_NUMBER}
#: How long the page waits for the ICE agent to try the server, in milliseconds.
WAIT_MS = 6000
#: How long to wait for the DoH to be asked and for the gateway to be handed the address, in seconds.
ASKED_SECONDS = 25
_PROBE_JS = """async ([url, waitMs]) => {
const errors = [], found = [];
const pc = new RTCPeerConnection({iceServers: [{urls: url, username: 'u', credential: 'p'}]});
pc.createDataChannel('d');
pc.onicecandidateerror = (e) => errors.push(e.errorCode);
pc.onicecandidate = (e) => { if (e.candidate) found.push(e.candidate.candidate); };
await pc.setLocalDescription(await pc.createOffer());
await new Promise((resolve) => setTimeout(resolve, waitMs));
pc.close();
return {errors, candidates: found.length};
}"""
@pytest.fixture
def doh():
"""The FakeDoh with the TURN name pointing at a documentation address (overrides the one of conftest.py)."""
import h2 # noqa: F401 - the dev extra installs it: a missing one is a failure, never a skip
server = FakeDoh(TURN_ZONE)
yield server
server.close()
@pytest.mark.parametrize("scheme", ["context_only", "launch_and_context"])
def test_a_turn_server_named_over_tcp_is_resolved_by_the_doh_through_the_proxy_of_the_context(
scheme, firefox_binary, doh, pages, gateway, trap, watcher):
"""EXPECTED RED on the published firefox-63 (the defect), green with the engine fix of firefox-64."""
gw_context = gateway("gw-context")
gw_launch = gateway("gw-launch") if scheme == "launch_and_context" else None
gateways = [g for g in (gw_context, gw_launch) if g is not None]
with _launch(firefox_binary, gw_launch.proxy if gw_launch else None) as browser:
context, page = _page_in(browser, proxy=gw_context.proxy)
page.goto(pages.url("page-a.test"), wait_until="load", timeout=30000)
result = page.evaluate(_PROBE_JS, ["turn:%s:%d?transport=tcp" % (TURN_NAME, TURN_PORT), WAIT_MS])
asked = ds.wait_until(lambda: doh.queries_for(TURN_NAME, QTYPE_A), ASKED_SECONDS)
handed = ds.wait_until(lambda: (TURN_NUMBER, TURN_PORT) in gw_context.connects, ASKED_SECONDS)
context.close()
watcher.stop()
why = _why(doh, *gateways) + "\n the page: %s" % (result,)
assert asked, (
"the DoH was never asked for the TURN name %s over TCP: the lookup of the socket took the user context of no proxy (the "
"system resolver, or the default context's DoH request)" % TURN_NAME + why)
assert doh.vias_of(TURN_NAME, QTYPE_A) == {gw_context.name}, (
"%s (A) was not asked by the gateway of the context only: %s" % (TURN_NAME, sorted(doh.vias_of(TURN_NAME, QTYPE_A))) + why)
assert handed, "the gateway of the context was never handed the address %s:%d the DoH answered" % (TURN_NUMBER, TURN_PORT) + why
for gw in gateways:
named = [h for h, _p in gw.connects if not _is_address(h) and h != DOH_HOST]
assert named == [], "%s was sent a NAME in a CONNECT: %s" % (gw.name, named) + why
if gw_launch is not None:
assert (TURN_NUMBER, TURN_PORT) not in gw_launch.connects, "the TURN address was handed to the gateway of the LAUNCH" + why
assert [q for q in doh.queries if q.via == gw_launch.name and q.name == TURN_NAME] == [], (
"the name of the TURN server left by the gateway of the LAUNCH, not by the one of the context" + why)
_assert_every_connection_went_through_the_gateway(doh, *gateways)
assert watcher.watched_pids, "the watcher never saw a browser process (it saw: %s)" % watcher.process_names
assert _direct_to_the_doh(watcher) == [], (
"the browser reached a DoH (%s) or a DNS server (port 53) without the proxy: %s" % (", ".join(DOH_ADDRESSES), watcher.describe()))
assert [c for c in watcher.direct if c.remote.rsplit(":", 1)[0] == TURN_NUMBER] == [], (
"the browser connected straight to the TURN server, around the proxy: %s" % watcher.describe())
if gw_launch is not None:
assert watcher.direct == [], "the browser connected past the gateways, with every context proxied: %s" % watcher.describe()
if trap is not None:
assert not trap.asked(TURN_NAME), "the browser asked the resolver of the machine for the TURN name: %s" % trap.describe()
if gw_launch is not None:
assert trap.queries == [], "the browser asked the resolver of the machine, with every context proxied: %s" % trap.describe()
@@ -28,6 +28,7 @@ from http.server import BaseHTTPRequestHandler
import pytest
from _bfcache_evidence import decide_outcome, read_after_go_back, wait_cacheable
from _servers import LocalServer
STRATEGY_1 = {
@@ -37,6 +38,21 @@ STRATEGY_1 = {
"network.dns.localDomains": "a.test,b.test,c.test",
}
# The lab holds still the two things of the HOST that decide whether a page the cache took is still there when the test goes back, so that the
# memory of the runner does not decide whether the cache holds (a red then would say something about the machine, not about the engine):
# * how many pages the cache keeps: by default `nsSHistory` computes it from the PHYSICAL memory of the machine (at most 8; nsSHistory.cpp
# CalcMaxTotalViewers), here it is 8;
# * the low-memory watcher: on Linux Firefox reads /proc/meminfo every second and, when what is available is under 5% of the total or under 200 MB,
# sends memory-pressure, which evicts EVERY page of the cache (AvailableMemoryWatcherLinux.cpp, nsSHistory.cpp). Both thresholds at 0 here
# (they are static prefs; the percent one exists on Linux only and is ignored elsewhere).
# Nothing of this is in the product: a user's Firefox keeps both defaults, and so does ours.
LAB_PREFS = {
**STRATEGY_1,
"browser.sessionhistory.max_total_viewers": 8,
"browser.low_commit_space_threshold_percent": 0,
"browser.low_commit_space_threshold_mb": 0,
}
# What a document with a worker runs: the worker answers every message with its count.
OWNER = """<script>
window.__shown = [];
@@ -113,6 +129,16 @@ def events(monkeypatch):
return seen
def _commit_order_is_promised():
"""Whether the engine under test ends the workers of a document BEFORE it announces the commit that replaces it. Juggler f284ca703e
(PageHandler._commitNow ends the workers below the frame first) is in firefox-63; the published firefox-62 does not promise the order, and
main's e2e runs on both (run 43193233155: `Page.navigationCommitted` before `Page.workerDestroyed` on the published engine)."""
from conftest import _engine_number
from invisible_core.seal import active_seal
return (_engine_number(active_seal().tag) or 0) >= 63
def _wait(check, seconds=10.0):
end = time.monotonic() + seconds
while time.monotonic() < end:
@@ -144,7 +170,7 @@ def test_a_worker_leaves_with_its_page_for_the_cache_and_comes_back_the_same(fir
from invisible_playwright import InvisiblePlaywright
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, humanize=False,
headless=True, extra_prefs=STRATEGY_1) as browser:
headless=True, extra_prefs=LAB_PREFS) as browser:
page = browser.new_context().new_page()
page.set_default_timeout(10000)
page.goto(sites[where]["page"], wait_until="load")
@@ -159,6 +185,7 @@ def test_a_worker_leaves_with_its_page_for_the_cache_and_comes_back_the_same(fir
"the frame of the worker is not listed with its url: %r" % [f.url for f in page.frames])
assert _ask(page, where) == 1
assert _ask(page, where) == 2
wait_cacheable(page) # the cache takes a page only after the `pageshow` of every document of it, however slow the machine is
# 2. the top goes forward: the worker ends for the client, before the new page commits
forward = len(events)
@@ -169,15 +196,25 @@ def test_a_worker_leaves_with_its_page_for_the_cache_and_comes_back_the_same(fir
page.evaluate("url => { location.href = url; }", sites[away])
committed = _index(events, forward, "Page.navigationCommitted", lambda p: p.get("url", "").endswith("/other"))
assert committed is not None, "no commit of the new page was seen"
promised = _commit_order_is_promised()
if not promised: # an engine that does not promise the order still tells the worker ended, a moment later
_wait(lambda: _index(events, forward, "Page.workerDestroyed", lambda p: p["workerId"] == wid) is not None)
ended = _index(events, forward, "Page.workerDestroyed", lambda p: p["workerId"] == wid)
assert ended is not None, "the worker was not told ended when its page left: %r" % _methods(events, forward)
assert ended < committed, "the worker was told ended only after the new page committed: %r" % _methods(events, forward)
if promised:
assert ended < committed, "the worker was told ended only after the new page committed: %r" % _methods(events, forward)
# 3. back from the cache: the same worker, told once, after the restored document's contexts are cleared
back = len(events)
page.go_back(wait_until="load")
assert page.evaluate("window.__shown") == [False, True], (
"the page was loaded again instead of restored from the back-forward cache, so this test proves nothing")
# What it knows is written down BEFORE anything is asserted. A goto is started by the PARENT and Firefox may refuse the cache for it,
# to the same site or to another (measured: the navigation's own channel is still in the old document's loadgroup when the parent
# checks: SHIPBFCache log, CanonicalBrowsingContext::AllowedInBFCache); then the document is built again and the contract is the one
# of a new page, asserted whole. The page's own navigation (`location`) is never refused: a restore is required there.
outcome = decide_outcome(read_after_go_back(page, events, back), may_reload=(how == "goto"))
if outcome == "reloaded":
_assert_a_new_page_with_a_new_worker(page, events, where, wid, back)
return
if not _wait(lambda: _index(events, back, "Page.workerCreated", lambda p: p["workerId"] == wid) is not None):
other = [p["workerId"] for m, p in events[back:] if m == "Page.workerCreated"]
raise AssertionError(("the restored worker was announced under a NEW id %s, not %s: " % (other, wid)
@@ -213,3 +250,27 @@ def _methods(events, start):
for m, p in events[start:] if m.startswith(("Page.worker", "Page.navigationCommitted", "Page.frameDocument",
"Runtime.executionContextsCleared", "Page.frameDetached",
"Page.frameAttached"))]
def _assert_a_new_page_with_a_new_worker(page, events, where, old, back):
"""The document was built again after go_back (the cache was not used): the contract of a page that loads. The old worker has been told
ended once (asserted before), ONE new worker is announced with a NEW id, it is not told ended, it is the only live one, and it is a fresh
worker (it answers 1)."""
def created():
return [p["workerId"] for m, p in events[back:] if m == "Page.workerCreated" and p["url"].endswith("/worker.js")]
assert _wait(lambda: bool(created())), "the page built again did not announce its worker: %r" % _methods(events, back)
time.sleep(1.0) # what comes in excess comes now
new = created()
assert len(new) == 1 and new[0] != old, "expected one NEW worker, got %r (the old one was %s): %r" % (new, old, _methods(events, back))
assert not [p for m, p in events[back:] if m == "Page.workerDestroyed" and p["workerId"] == new[0]], (
"the new worker was told ended: %r" % _methods(events, back))
live = {}
for m, p in events:
if m == "Page.workerCreated":
live[p["workerId"]] = p
elif m == "Page.workerDestroyed":
live.pop(p["workerId"], None)
assert list(live) == [new[0]], "live workers after the page was built again: %r" % list(live.values())
assert _wait(lambda: where == "top" or any(f.url.endswith("/frame-worker") for f in page.frames)), "the frame of the new page is missing"
assert _ask(page, where) == 1, "the worker of the page built again is not a fresh worker"
@@ -18,6 +18,13 @@ Runtime.js) and the core drops every world on `executionContextsCleared`
Each round checks `crossOriginIsolated` on the first page: a round where the
engine did not isolate it would not have changed process, and would pass for
the wrong reason.
The page moves to the second one when the test says so, right after the read
on the first: it used to go on its own 500 ms after `load`, and on a loaded
Windows runner more than 500 ms can pass between `domcontentloaded` and the
first read, so that read met the second page or the move itself (2 rounds in 20
under four workers, runs 43435932449 and 43439508625: `crossOriginIsolated`
false, and "Execution context was destroyed").
"""
from __future__ import annotations
@@ -32,8 +39,8 @@ ROUNDS = 3
PAGES = {
"/isolated": (b"<!doctype html><html><body><p id=p>isolated</p><script>"
b"addEventListener('load', () => setTimeout(() => "
b"location.replace('/plain' + location.search), 500))"
b"window.moveOn = () => setTimeout(() => "
b"location.replace('/plain' + location.search), 0)"
b"</script></body></html>"),
"/plain": b"<!doctype html><html><body><p id=p>plain</p></body></html>",
}
@@ -82,7 +89,9 @@ def test_reads_after_the_isolated_page_answer(page, site):
"the engine did not isolate the page: this round tests nothing")
# The read on the isolated page is what builds the script that went
# stale; without it the bug never showed.
assert page.locator("#p").inner_text(timeout=10_000) in ("isolated", "plain")
assert page.locator("#p").inner_text(timeout=10_000) == "isolated"
# The page sends itself on, as a challenge page does: the move is its own location.replace, not a goto of ours.
page.evaluate("moveOn()")
page.wait_for_url("**/plain?i=%d" % i, timeout=10_000)
assert page.evaluate("self.crossOriginIsolated") is False
assert page.locator("#p").inner_text(timeout=10_000) == "plain"
@@ -113,7 +113,7 @@ def _serve(imgs, listing):
@pytest.mark.e2e
@pytest.mark.timeout(300, method="thread")
def test_tagged_images_read_back_as_retail_windows_reads_them(firefox_binary, engine_at_least):
engine_at_least("firefox-64")
engine_at_least("firefox-65")
refs_path = DATA / "refs.json"
if not refs_path.is_file():
pytest.fail("tests/data/canvas_icc_ref/refs.json is missing: it is the reference "
@@ -104,7 +104,7 @@ def _want(cases):
@pytest.mark.e2e
@pytest.mark.timeout(600, method="thread")
def test_coloured_text_is_what_retail_windows_draws(firefox_binary, engine_at_least):
engine_at_least("firefox-64")
engine_at_least("firefox-65")
refs = _refs()
assert refs["colors"]["count"] == len(refs["colors"]["cases"]) == 14
got = _launch(firefox_binary, refs, None, {})
@@ -128,7 +128,7 @@ def _keys():
@pytest.mark.parametrize("tag", _keys())
def test_text_under_a_cleartype_key_is_what_retail_windows_draws(
tag, firefox_binary, engine_at_least):
engine_at_least("firefox-64")
engine_at_least("firefox-65")
refs = _refs()
k = refs["keys"][tag]
want_black, want_colors = _want(k["black"]), _want(k["colors"])
+1 -1
View File
@@ -58,7 +58,7 @@ from invisible_playwright import InvisiblePlaywright
@pytest.mark.e2e
@pytest.mark.timeout(1800, method="thread")
def test_canvas_text_is_what_retail_windows_draws(firefox_binary, engine_at_least):
engine_at_least("firefox-64")
engine_at_least("firefox-65")
refs_path = DATA / "refs.json"
if not refs_path.is_file():
pytest.fail("tests/data/canvas_text_ref/refs.json is missing: it is the reference "
+128
View File
@@ -0,0 +1,128 @@
"""scripts/ci_lab_geoip.py: the GeoIP database of a CI leg is made by the repository, the same bytes on every run, and a leg says what it ran with."""
import importlib.util
import json
from pathlib import Path
import pytest
pytestmark = pytest.mark.unit
ROOT = Path(__file__).resolve().parents[1]
def _load():
spec = importlib.util.spec_from_file_location("ci_lab_geoip_under_test", ROOT / "scripts" / "ci_lab_geoip.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
lab = _load()
EXITS = {"germany": lab.addr(1, 178, 10, 5), "japan": lab.addr(1, 0, 16, 5), "india": lab.addr(1, 6, 0, 5), "australia": lab.addr(1, 0, 4, 5),
"brazil": lab.addr(1, 178, 32, 5), "united_states": lab.addr(1, 32, 239, 5)}
@pytest.fixture
def database(tmp_path):
path = tmp_path / lab.FILE_NAME
path.write_bytes(lab.build_bytes())
return path
def test_the_same_bytes_on_every_run_and_the_pin_is_their_hash():
first, second = lab.build_bytes(), lab.build_bytes()
assert first == second
pin = lab.load_pin(ROOT / "ci" / "geoip.json")
assert lab.sha256_of_bytes(first) == pin["mmdb_sha256"], "the table of scripts/ci_lab_geoip.py and ci/geoip.json changed apart"
assert len(first) == pin["mmdb_bytes"]
def test_the_exits_of_the_realness_suite_are_the_networks_of_the_database():
support = (ROOT / "tests" / "_realness_support.py").read_text(encoding="utf-8")
for label, address in EXITS.items():
assert '"%s": _address(%s)' % (label, ", ".join(address.split("."))) in support, "%s moved in tests/_realness_support.py" % label
net = ".".join(address.split(".")[:3]) + ".0/24"
assert net in lab.NETWORKS, "%s (%s) is not a network of the lab database" % (label, address)
@pytest.mark.parametrize("mode", ["MODE_MMAP_EXT", "MODE_MMAP", "MODE_FILE", "MODE_MEMORY"])
def test_every_reader_of_maxminddb_opens_it(database, mode):
maxminddb = pytest.importorskip("maxminddb")
if not hasattr(maxminddb, mode):
pytest.skip("no %s in this maxminddb" % mode)
with maxminddb.open_database(str(database), mode=getattr(maxminddb, mode)) as reader:
record = reader.get(EXITS["germany"])
assert record["country"]["iso_code"] == "DE" and record["location"]["time_zone"] == "Europe/Berlin"
def test_the_core_reads_what_it_reads_from_it(database):
from invisible_core._geo import ip_to_coordinates, ip_to_country, ip_to_timezone
for cidr, (country, zone, lat, lon) in lab.NETWORKS.items():
ip = cidr.split("/")[0].rsplit(".", 1)[0] + ".5"
assert ip_to_country(ip, database) == country
assert ip_to_timezone(ip, database) == zone
assert ip_to_coordinates(ip, database) == (lat, lon)
@pytest.mark.parametrize("address", ["198.51.100.4", "198.51.100.5", "198.51.100.6", "198.51.100.9", "203.0.113.7", "127.0.0.1",
"2001:db8::1", "::1"])
def test_an_address_that_is_not_in_it_is_not_in_the_database_and_never_an_error(database, address):
from invisible_core._geo import GeoTimezoneError, ip_to_country, ip_to_timezone
assert ip_to_country(address, database) is None
with pytest.raises(GeoTimezoneError) as caught:
ip_to_timezone(address, database)
assert caught.value.kind == "ip_not_in_db"
def test_a_writer_that_no_longer_makes_the_pinned_bytes_is_refused_and_exports_nothing(tmp_path, monkeypatch, capsys):
pin = tmp_path / "geoip.json"
pin.write_text(json.dumps({"mmdb_sha256": "0" * 64}), encoding="utf-8")
env_file = tmp_path / "github_env"
monkeypatch.setenv("GITHUB_ENV", str(env_file))
code = lab.main(["build", "--pin", str(pin), "--dest", str(tmp_path / "dest")])
assert code == 1 and not env_file.exists() and not (tmp_path / "dest" / lab.FILE_NAME).exists()
assert "change both in one commit" in capsys.readouterr().err
def test_a_pin_that_is_not_a_pin_is_refused(tmp_path):
bad = tmp_path / "geoip.json"
for text in ("not json", "{}", json.dumps({"mmdb_sha256": "xyz"})):
bad.write_text(text, encoding="utf-8")
with pytest.raises(lab.Refused):
lab.load_pin(bad)
def test_the_evidence_is_what_the_environment_says(tmp_path):
db = tmp_path / "db.mmdb"
db.write_bytes(b"x")
assert lab.evidence({lab.ENV: str(db)})["exists"] is True
assert lab.evidence({}) == {"env": "", "exists": False, "sha256": None}
assert lab.evidence({lab.ENV: str(tmp_path / "no")}) == {"env": str(tmp_path / "no"), "exists": False, "sha256": None}
def test_the_evidence_command_writes_the_file_the_judge_reads(tmp_path, monkeypatch):
out = tmp_path / "result" / "geoip.json"
monkeypatch.delenv(lab.ENV, raising=False)
assert lab.main(["evidence", "--out", str(out)]) == 0
assert json.loads(out.read_text(encoding="utf-8")) == {"env": "", "exists": False, "sha256": None}
@pytest.mark.parametrize("address", [lab.addr(20, 118, 230, 145), lab.addr(8, 8, 8, 8), lab.addr(1, 178, 11, 5), lab.addr(52, 0, 0, 1), lab.addr(223, 255, 255, 1)])
def test_a_public_address_that_is_not_a_lab_network_answers_the_declared_record(database, address):
"""A launch with no proxy asks the database for the egress address of the runner, which is not known in advance (run 43351424907 of PR 486: 495
errors "egress IP ... not present in the geoip database", every one from a test that launches without a proxy). One declared record answers it."""
from invisible_core._geo import ip_to_country, ip_to_timezone
country, zone, _lat, _lon = lab.FALLBACK
assert ip_to_country(address, database) == country and ip_to_timezone(address, database) == zone
def test_the_fallback_cuts_out_every_network_of_the_table_and_every_reserved_range():
import ipaddress
cut = lab.fallback_networks()
for net in [ipaddress.ip_network(c) for c in lab.NETWORKS] + list(lab.RESERVED):
assert not any(n.overlaps(net) for n in cut), "%s is covered by the fallback" % net
assert sum(n.num_addresses for n in cut) + sum(ipaddress.ip_network(c).num_addresses for c in lab.NETWORKS) + sum(n.num_addresses for n in lab.RESERVED) == 1 << 32
+71
View File
@@ -0,0 +1,71 @@
"""scripts/ci_lab_geoip.py verify: the leg ran with the pinned database and the core never went past it to GitHub; and `build` says where the record goes."""
import importlib.util
import json
from pathlib import Path
import pytest
pytestmark = pytest.mark.unit
ROOT = Path(__file__).resolve().parents[1]
def _load():
spec = importlib.util.spec_from_file_location("ci_lab_geoip_verify_under_test", ROOT / "scripts" / "ci_lab_geoip.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
lab = _load()
PIN = ROOT / "ci" / "geoip.json"
def _proof(tmp_path, name, **fields):
data = {"env": "/db/geoip-aio-all.mmdb", "exists": True, "sha256": lab.load_pin(PIN)["mmdb_sha256"]}
data.update(fields)
path = tmp_path / name
path.write_text(json.dumps(data), encoding="utf-8")
return path
def test_build_exports_the_variable_and_the_place_of_the_record_of_use(tmp_path, monkeypatch, capsys):
env_file = tmp_path / "github_env"
monkeypatch.setenv("GITHUB_ENV", str(env_file))
assert lab.main(["build", "--pin", str(PIN), "--dest", str(tmp_path / "dest")]) == 0
path = (tmp_path / "dest" / lab.FILE_NAME).resolve()
used = path.parent / "geoip-used.json"
assert env_file.read_text(encoding="utf-8") == "STEALTHFOX_GEOIP_MMDB=%s\nGEOIP_USED_OUT=%s\n" % (path, used)
assert "GEOIP_USED_OUT=%s" % used in capsys.readouterr().out
def test_a_leg_with_the_pinned_database_and_no_question_to_github_verifies(tmp_path):
evidence = _proof(tmp_path, "evidence.json")
used = _proof(tmp_path, "used.json", asked_github=0)
assert lab.verify(lab.load_pin(PIN), evidence, used) == []
assert lab.main(["verify", "--pin", str(PIN), "--evidence", str(evidence), "--used", str(used)]) == 0
@pytest.mark.parametrize("fields, said", [({"env": "", "exists": False, "sha256": None}, "was not set"),
({"exists": False, "sha256": None}, "is not a file"),
({"sha256": "d" * 64}, "the pin says")])
def test_evidence_of_a_leg_without_the_database_does_not_verify(tmp_path, fields, said):
problems = lab.verify(lab.load_pin(PIN), _proof(tmp_path, "evidence.json", **fields))
assert len(problems) == 1 and said in problems[0], problems
def test_a_core_that_went_past_the_variable_to_github_does_not_verify(tmp_path):
problems = lab.verify(lab.load_pin(PIN), _proof(tmp_path, "evidence.json"), _proof(tmp_path, "used.json", asked_github=3))
assert len(problems) == 1 and "asked GitHub" in problems[0] and "3 time" in problems[0]
def test_a_variable_gone_by_the_end_of_the_run_does_not_verify(tmp_path):
used = _proof(tmp_path, "used.json", env="", exists=False, sha256=None, asked_github=0)
problems = lab.verify(lab.load_pin(PIN), _proof(tmp_path, "evidence.json"), used)
assert len(problems) == 1 and "record of use" in problems[0]
def test_a_record_that_is_not_there_does_not_verify(tmp_path):
problems = lab.verify(lab.load_pin(PIN), _proof(tmp_path, "evidence.json"), tmp_path / "none.json")
assert len(problems) == 1 and "cannot be read" in problems[0]
assert lab.main(["verify", "--pin", str(PIN), "--evidence", str(tmp_path / "none.json")]) == 1
+109
View File
@@ -0,0 +1,109 @@
"""scripts/ci_real_geoip_check.py, the three checks on the REAL database that only the release runs: here against databases made on the spot."""
import importlib.util
import os
from pathlib import Path
import pytest
pytestmark = pytest.mark.unit
ROOT = Path(__file__).resolve().parents[1]
def _load(name):
spec = importlib.util.spec_from_file_location(name + "_under_test", ROOT / "scripts" / (name + ".py"))
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
check = _load("ci_real_geoip_check")
lab = check.lab
def _database(tmp_path, name, networks=None):
"""A database made like the lab one, from `networks` (the table of the script when None)."""
old = dict(lab.NETWORKS)
try:
if networks is not None:
lab.NETWORKS.clear()
lab.NETWORKS.update(networks)
path = tmp_path / name
path.write_bytes(lab.build_bytes())
return path
finally:
lab.NETWORKS.clear()
lab.NETWORKS.update(old)
def _database_without_fallback(tmp_path, name):
"""The lab table alone, with no record for the other public addresses: a database that has no answer for 8.8.8.8."""
old = lab.FALLBACK
lab.FALLBACK = None
try:
return _database(tmp_path, name)
finally:
lab.FALLBACK = old
def test_the_exit_of_a_network_is_the_dot_five_of_its_slash_24():
assert check.exit_of(lab.net(1, 178, 10)) == lab.addr(1, 178, 10, 5)
def test_a_database_that_agrees_passes_the_comparison_and_the_zones(tmp_path, capsys):
real = _database(tmp_path, "real.mmdb")
ours = _database(tmp_path, "lab.mmdb")
assert check.check_lab_agrees(real, ours) == []
assert check.check_zones(real) == []
assert "distinct zones" in capsys.readouterr().out
def test_a_zone_that_differs_is_said_with_the_network(tmp_path):
changed = dict(lab.NETWORKS)
changed[lab.net(1, 0, 16)] = ("JP", "Asia/Seoul", 35.0, 139.0)
real = _database(tmp_path, "real.mmdb", changed)
ours = _database(tmp_path, "lab.mmdb")
problems = check.check_lab_agrees(real, ours)
assert len(problems) == 1 and lab.net(1, 0, 16) in problems[0] and "Asia/Seoul" in problems[0]
def test_a_network_the_real_database_does_not_have_is_said(tmp_path):
real = _database(tmp_path, "real.mmdb", {lab.net(1, 178, 10): lab.NETWORKS[lab.net(1, 178, 10)]})
ours = _database(tmp_path, "lab.mmdb")
problems = check.check_lab_agrees(real, ours)
assert len(problems) == len(lab.NETWORKS) - 1
def test_a_zone_the_runner_does_not_know_is_a_finding(tmp_path):
odd = dict(lab.NETWORKS)
odd[lab.net(1, 6, 0)] = ("IN", "Mars/Olympus_Mons", 1.0, 1.0)
real = _database(tmp_path, "real.mmdb", odd)
problems = check.check_zones(real)
assert len(problems) == 1 and "Mars/Olympus_Mons" in problems[0]
def test_a_database_that_does_not_open_or_has_no_country_is_a_finding(tmp_path):
broken = tmp_path / "broken.mmdb"
broken.write_bytes(b"not a database")
assert check.check_open_and_answer(broken)
assert check.check_open_and_answer(_database_without_fallback(tmp_path, "lab.mmdb")) # no 8.8.8.8 in it: no country
def test_the_command_takes_no_argument():
assert check.main(["--something"]) == 2
def test_the_product_road_is_the_one_without_the_variable_and_with_a_cold_cache(tmp_path, monkeypatch):
seen = {}
def fake():
seen["variable"] = os.environ.get("STEALTHFOX_GEOIP_MMDB")
seen["cache"] = os.environ.get("INVISIBLE_PLAYWRIGHT_CACHE_DIR")
return tmp_path / "x.mmdb"
monkeypatch.setenv("STEALTHFOX_GEOIP_MMDB", "/somewhere")
monkeypatch.setenv("INVISIBLE_PLAYWRIGHT_CACHE_DIR", "/before")
import invisible_core.download as download
monkeypatch.setattr(download, "ensure_geoip_mmdb", fake)
assert check.product_download(tmp_path / "cold") == tmp_path / "x.mmdb"
assert seen == {"variable": None, "cache": str(tmp_path / "cold")}
+41
View File
@@ -0,0 +1,41 @@
"""scripts/ci_real_geoip_check.py exits 3 when no database came (the network): that says nothing about the database, and the release is run again."""
import importlib.util
from pathlib import Path
import pytest
pytestmark = pytest.mark.unit
ROOT = Path(__file__).resolve().parents[1]
def _load():
spec = importlib.util.spec_from_file_location("ci_real_geoip_exit_under_test", ROOT / "scripts" / "ci_real_geoip_check.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
check = _load()
def test_a_database_that_did_not_come_is_exit_3_and_not_a_finding(monkeypatch, capsys):
def no_network(cache):
raise OSError("name resolution failed")
monkeypatch.setattr(check, "product_download", no_network)
assert check.main([]) == check.EXIT_NO_DATABASE == 3
assert "NO DATABASE" in capsys.readouterr().out
def test_a_database_that_came_and_fails_a_check_is_exit_1_and_names_the_check(tmp_path, monkeypatch, capsys):
lab = check.lab
broken = tmp_path / "geoip-aio-all.mmdb"
with monkeypatch.context() as m:
m.setattr(lab, "FALLBACK", None) # no record for 8.8.8.8 in the lab database: the first check fails
broken.write_bytes(lab.build_bytes())
monkeypatch.setattr(check, "product_download", lambda cache: broken)
assert check.main([]) == 1
out = capsys.readouterr().out
assert "sha256 %s" % lab.sha256_of(broken) in out and "1. it opens with the reader of the core and answers for an address: FAILED" in out
assert "2. the lab database agrees" in out and "3. every time_zone" in out
+47
View File
@@ -316,6 +316,53 @@ def test_a_seal_that_cannot_be_read_is_red(tmp_path, capsys):
assert code == 1 and "cannot be read" in capsys.readouterr().out
# --- the GeoIP database of the leg ---------------------------------------------------------------------------------
MMDB_SHA = "c" * 64
def _geoip(tmp_path, **evidence):
pin = tmp_path / "geoip.json"
pin.write_text(json.dumps({"mmdb_sha256": MMDB_SHA}), encoding="utf-8")
proof = tmp_path / "geoip-evidence.json"
base = {"env": "/db/geoip-aio-all.mmdb", "exists": True, "sha256": MMDB_SHA}
base.update(evidence)
proof.write_text(json.dumps(base), encoding="utf-8")
return ["--geoip", str(proof), "--geoip-pin", str(pin)]
def test_a_leg_that_ran_with_the_database_of_the_pin_is_green(tmp_path):
code, result = _judge(tmp_path, GREEN, extra=_geoip(tmp_path))
assert code == 0 and result["geoip_sha256"] == MMDB_SHA
def test_a_leg_launched_without_the_variable_is_red(tmp_path, capsys):
code, result = _judge(tmp_path, GREEN, extra=_geoip(tmp_path, env="", exists=False, sha256=None))
out = capsys.readouterr().out
assert code == 1 and result["verdict"] == "red" and "without STEALTHFOX_GEOIP_MMDB" in out
def test_a_variable_that_names_no_file_is_red(tmp_path, capsys):
code, _r = _judge(tmp_path, GREEN, extra=_geoip(tmp_path, exists=False, sha256=None))
assert code == 1 and "is not a file" in capsys.readouterr().out
def test_a_database_that_is_not_the_one_of_the_pin_is_red(tmp_path, capsys):
code, _r = _judge(tmp_path, GREEN, extra=_geoip(tmp_path, sha256="d" * 64))
assert code == 1 and "the pin" in capsys.readouterr().out
def test_evidence_that_is_missing_or_unreadable_is_red(tmp_path, capsys):
code, _r = _judge(tmp_path, GREEN, extra=["--geoip", str(tmp_path / "none.json"), "--geoip-pin", str(tmp_path / "geoip.json")])
assert code == 1 and "did not say which database" in capsys.readouterr().out
def test_a_pin_that_cannot_be_read_is_red(tmp_path, capsys):
extra = _geoip(tmp_path)
(tmp_path / "geoip.json").write_text("not json", encoding="utf-8")
code, _r = _judge(tmp_path, GREEN, extra=extra)
assert code == 1 and "pin of the GeoIP database" in capsys.readouterr().out
# --- exact, every test of a file, xunit2 ---------------------------------------------------------------------------
def test_an_exact_suite_with_more_tests_than_min_tests_is_red(tmp_path, capsys):
cases = GREEN + [_case(FILE_B, "test_new")]
@@ -0,0 +1,67 @@
"""The workflows that run the wrapper's tests launch with the GeoIP database of ci/geoip.json; the release alone looks at the real one.
Without STEALTHFOX_GEOIP_MMDB the core asks GitHub which database is the latest on every call (run 43211837926). tests.yml and e2e.yml (its Linux run and its Windows parts) make
the database (scripts/ci_lab_geoip.py: the same bytes every run, no download) BEFORE the step that runs pytest. user-install.yml proves the installation a user
gets and is left as it is. publish.yml is the release: it runs the three checks on the REAL database (scripts/ci_real_geoip_check.py) before it uploads, and
nothing else touches it.
"""
from pathlib import Path
import pytest
pytestmark = pytest.mark.unit
WORKFLOWS = Path(__file__).resolve().parents[1] / ".github" / "workflows"
BUILD = "scripts/ci_lab_geoip.py build"
REAL = "scripts/ci_real_geoip_check.py"
RUNS_PYTEST = {
"tests.yml": " - name: Run pytest\n",
"e2e.yml": " - name: Run the full e2e suite under a virtual display, without the root ones\n",
"e2e.yml#windows": " - name: Run this part of the e2e\n",
}
def _scope(name):
"""The text of one workflow, or of one leg of it: `e2e.yml` is its Linux job, `e2e.yml#windows` its Windows parts."""
file, _, leg = name.partition("#")
text = (WORKFLOWS / file).read_text(encoding="utf-8")
if file != "e2e.yml":
return text
windows = text.index("\n e2e-windows:\n")
if leg == "windows":
return text[windows:]
ends = [i for i in (text.find("\n e2e-windows-control-a:\n"), windows) if i >= 0]
return text[:min(ends)]
@pytest.mark.parametrize("name, pytest_step", sorted(RUNS_PYTEST.items()))
def test_the_database_is_made_before_the_step_that_runs_the_tests(name, pytest_step):
text = _scope(name)
assert text.count(BUILD) == 1, "%s makes the GeoIP database %d times" % (name, text.count(BUILD))
assert pytest_step in text, "the step that runs the tests of %s moved: update this test with it" % name
assert text.index(BUILD) < text.index(pytest_step), "%s makes the database after the tests started" % name
assert REAL not in text, "the real database is the release's alone"
def test_the_workflow_that_proves_the_installation_is_left_alone():
text = (WORKFLOWS / "user-install.yml").read_text(encoding="utf-8")
assert BUILD not in text and REAL not in text
def test_the_release_checks_the_real_database_before_it_uploads_and_makes_no_lab_one():
text = (WORKFLOWS / "publish.yml").read_text(encoding="utf-8")
assert text.count("python " + REAL) == 1 and BUILD not in text
assert " real-geoip-database:\n" in text
assert "needs: [already-published, gate, real-geoip-database]" in text, "the upload does not wait for the real database"
# and no other workflow runs the real checks
for other in sorted(WORKFLOWS.glob("*.yml")):
if other.name != "publish.yml":
assert REAL not in other.read_text(encoding="utf-8"), "%s runs the checks of the release" % other.name
@pytest.mark.parametrize("name, pytest_step", sorted(RUNS_PYTEST.items()))
def test_the_leg_verifies_after_the_tests_that_it_ran_with_the_pinned_database(name, pytest_step):
text = _scope(name)
step = " - name: The leg ran with the pinned GeoIP database\n if: always()\n"
assert text.count(step) == 1 and "ci_lab_geoip.py verify" in text, name
assert text.index(pytest_step) < text.index(step), "%s verifies before the tests ran" % name
@@ -0,0 +1,286 @@
"""Closing one of four browsers in one process does not hold the event loop that serves the other three.
The close of a browser WAITS (for its processes to exit, for its profile to be removed): that is the contract, Playwright's `close()`
returns once the processes are gone. What was wrong was WHO waited. In the async API the user's own event loop did, three times:
* `InProcessTransport.request_stop` ran `server.shutdown()` (the hooks that close the engine's pipe and wait for its tree, and the
removal of the profile) on the loop that asked for the stop;
* `InProcessTransport.wait_until_stopped` joined the four `juggler-N` workers on the loop, up to 5 s each, and a worker is busy
for as long as the engine's `conn.close()` waits (`BrowserDispatcher.op_close`);
* `InvisiblePlaywright._teardown` reaped the session's token (`reap` waits for the tree) on the loop.
Measured with py-spy on four browsers in one Python process: closing one stopped the loop that serves the other three for as long as
it waited. Now the same waits run in threads of their own (`invisible_core._offloop.off_the_loop`, from invisible-core 64.72.0).
The test runs the real engine, four of them, in a client program of its own (the loop under test is that program's main thread). A
sentinel task asks to wake every 5 ms; a watcher thread notes how late it woke and where the main thread was: waiting in the
selector (the machine did not run the loop: on a loaded host an idle loop is 100 ms late now and then, which is not the close's
doing and is not counted) or INSIDE something (held). The instrument is the one of the core's
`tests/test_a_close_does_not_hold_the_loop.py`. A control with the same instrument holds the loop on purpose first, so a watcher
that could not see a held loop does not pass the test for nothing.
"""
from __future__ import annotations
import json
import os
import subprocess
import sys
import textwrap
import pytest
pytestmark = pytest.mark.e2e
#: The client. Four browsers by the async API, each with a page; one is closed while a sentinel measures the loop and one pinger per
#: other browser keeps asking its page a question. Prints one JSON line.
_CLIENT = textwrap.dedent("""
import asyncio, json, os, shutil, sys, threading, time, traceback
import psutil
from invisible_playwright.async_api import InvisiblePlaywright
BINARY = sys.argv[1]
main_id = threading.get_ident()
class Instrument:
\"\"\"A sentinel on the loop and a watcher thread. `held` is the longest wake that was late while the main thread was INSIDE
something, not idle in the loop's selector.\"\"\"
def __init__(self):
self.gaps, self.holes, self.held = [], [], 0.0
self.beat = [time.monotonic()]
self.stop = asyncio.Event()
self.over = threading.Event()
self.on_the_loop = []
self._real = {}
async def sentinel(self):
last = time.monotonic()
while not self.stop.is_set():
await asyncio.sleep(0.005)
now = time.monotonic()
self.gaps.append(now - last)
last = self.beat[0] = now
@staticmethod
def idle(frame):
# True when the main thread is waiting in the event loop's selector: it is not running anything of anybody's.
for _ in range(3):
if frame is None:
return False
code = frame.f_code
if code.co_name in ("_poll", "select") and code.co_filename.endswith(("windows_events.py", "selectors.py")):
return True
frame = frame.f_back
return False
def stacks(self):
frames = sys._current_frames()
names = {t.ident: t.name for t in threading.enumerate()}
return {
"main": "".join(traceback.format_stack(frames[main_id])[-6:]),
"others": {names.get(i, str(i)): "".join(traceback.format_stack(f)[-3:])
for i, f in frames.items() if i != main_id and i != threading.get_ident()}}
def watcher(self):
looked = 0
while not self.over.is_set():
time.sleep(0.003)
late = time.monotonic() - self.beat[0]
level = int(late / 0.03)
if late > 0.03 and not self.idle(sys._current_frames().get(main_id)):
self.held = max(self.held, late)
if level > looked:
self.holes.append({"late_ms": round(late * 1000), **self.stacks()})
looked = level
def watched(self, owner, name):
self._real[(owner, name)] = original = getattr(owner, name)
def call(*x, **k):
if threading.get_ident() == main_id and not self.over.is_set():
self.on_the_loop.append(name)
return original(*x, **k)
setattr(owner, name, call)
async def start(self):
self.watched(time, "sleep")
self.watched(shutil, "rmtree")
self.watched(psutil, "wait_procs")
self.watched(threading.Thread, "join")
threading.Thread(target=self.watcher, daemon=True, name="the-watcher").start()
self.task = asyncio.create_task(self.sentinel())
await asyncio.sleep(0.1)
async def finish(self):
self.stop.set()
await self.task
self.over.set()
for (owner, name), original in self._real.items():
setattr(owner, name, original)
self._real.clear()
def report(self):
return {"held": self.held, "gap": max(self.gaps), "holes": self.holes[:4], "on_the_loop": sorted(set(self.on_the_loop))}
def engines():
out = []
for child in psutil.Process().children(recursive=True):
try:
if "firefox" in child.name().lower():
out.append(child.pid)
except psutil.Error:
pass
return out
async def pinger(page, record, closing):
while not record["stop"]:
started = time.monotonic()
await page.evaluate("1 + 1")
took = time.monotonic() - started
if closing.is_set():
record["answers"] += 1
record["slowest"] = max(record["slowest"], took)
await asyncio.sleep(0.02)
async def main():
# The control: the same instrument on a loop that is held on purpose.
control = Instrument()
await control.start()
await asyncio.sleep(0.05)
time.sleep(0.4)
await asyncio.sleep(0.05)
await control.finish()
# A slow disk: removing a profile takes 150 ms more (a scanner of files at work, a spinning disk, a loaded runner). On a fast
# disk the removal of a profile is a few ms and a close made on the loop hides in the noise; with a disk that is slow the
# wait is what the loop pays, wherever it is made. Every thread pays it the same.
real_rmtree = shutil.rmtree
def slow_rmtree(*x, **k):
time.sleep(0.15)
return real_rmtree(*x, **k)
shutil.rmtree = slow_rmtree
sessions = [InvisiblePlaywright(seed=7100 + i, binary_path=BINARY, headless=True) for i in range(4)]
browsers = []
for session in sessions:
browsers.append(await session.__aenter__())
pages = [await b.new_page() for b in browsers]
for i, page in enumerate(pages):
await page.set_content("<p id=n>browser %d</p>" % i)
launched = len(engines())
closing, records = asyncio.Event(), []
tasks = []
for page in pages[1:]:
record = {"stop": False, "answers": 0, "slowest": 0.0}
records.append(record)
tasks.append(asyncio.create_task(pinger(page, record, closing)))
await asyncio.sleep(0.5)
instrument = Instrument()
await instrument.start()
closing.set()
started = time.monotonic()
await sessions[0].__aexit__(None, None, None)
took = time.monotonic() - started
closing.clear()
await instrument.finish()
report = instrument.report()
report.update({
"took": took, "launched": launched,
"control": control.report(),
"answers": [r["answers"] for r in records], "slowest": [r["slowest"] for r in records],
})
# The other three still work after it.
shutil.rmtree = real_rmtree
report["texts"] = [await p.text_content("#n") for p in pages[1:]]
for record in records:
record["stop"] = True
await asyncio.gather(*tasks)
for session in sessions[1:]:
await session.__aexit__(None, None, None)
time.sleep(0.5)
report["left"] = engines()
print("REPORT", json.dumps(report), flush=True)
try:
asyncio.run(asyncio.wait_for(main(), 240))
finally:
for pid in engines():
try:
psutil.Process(pid).kill()
except psutil.Error:
pass
""")
def _holes(report):
out = []
for hole in report.get("holes") or []:
out.append("--- the loop was %d ms late. MAIN THREAD:\n%s" % (hole["late_ms"], hole["main"]))
for name, stack in hole["others"].items():
out.append("--- thread %s:\n%s" % (name, stack))
return "\n".join(out) or "(no look was taken)"
@pytest.fixture(scope="module")
def report(firefox_binary, tmp_path_factory):
"""One run of the client: its numbers are asserted one claim at a time below."""
script = tmp_path_factory.mktemp("close-loop") / "client.py"
script.write_text(_CLIENT, encoding="utf-8")
import invisible_playwright
# The client imports the checkout under test, the one this run imported.
source = os.path.dirname(os.path.dirname(os.path.abspath(invisible_playwright.__file__)))
env = dict(os.environ, PYTHONPATH=os.pathsep.join([source, os.environ.get("PYTHONPATH", "")]).rstrip(os.pathsep))
done = subprocess.run([sys.executable, str(script), str(firefox_binary)], capture_output=True, text=True, timeout=300, env=env)
lines = [x for x in done.stdout.splitlines() if x.startswith("REPORT ")]
assert done.returncode == 0 and lines, (
"the client failed (%s):\n%s\n%s" % (done.returncode, done.stdout[-2000:], done.stderr[-4000:]))
return json.loads(lines[-1][len("REPORT "):])
@pytest.mark.wall_clock
def test_the_instrument_sees_a_loop_that_is_held(report):
"""The control: the loop held on purpose for 400 ms is seen as held. Without this, a watcher that could not tell a held loop from
a starved one would pass the test below for nothing."""
control = report["control"]
assert control["held"] > 0.3, (
"the watcher did not see a loop held for 400 ms: held %.0f ms" % (control["held"] * 1000))
assert "sleep" in control["on_the_loop"]
@pytest.mark.wall_clock
def test_closing_one_of_four_browsers_does_not_hold_the_loop(report):
"""Four browsers, one closes: the loop of the program is not held for 50 ms, counting only the time its thread is running."""
assert report["launched"] >= 4, "fewer than four engines were running before the close: %r" % report["launched"]
assert report["took"] > 0.3, "the close finished before the engine could have exited: nothing was waited for"
assert report["held"] < 0.05, (
"the loop was held for %.0f ms while one of four browsers closed (the close took %.0f ms; the longest wake was %.0f ms late; "
"calls made by the loop's own thread: %s). Where the threads were while it was late:\n%s"
% (report["held"] * 1000, report["took"] * 1000, report["gap"] * 1000, report["on_the_loop"], _holes(report)))
def test_no_blocking_step_of_the_close_runs_on_the_loop_s_thread(report):
"""The cause, asked directly and without the clock: `time.sleep`, `rmtree`, `psutil.wait_procs` and `Thread.join` are what a close
does while it waits and removes, and none of them may be called by the thread that runs the loop. Red on a close made on it."""
assert report["on_the_loop"] == [], "the loop's own thread made these calls while it awaited the close: %s" % report["on_the_loop"]
@pytest.mark.wall_clock
def test_the_other_three_keep_answering_during_the_close(report):
"""A call on each of the other three browsers is answered while the first one closes, and the three are alive after."""
assert len(report["answers"]) == 3
assert all(n >= 3 for n in report["answers"]), "the others stopped answering during the close: %r" % report["answers"]
assert max(report["slowest"]) < 2.0, "a call of another browser waited %.1f s during the close" % max(report["slowest"])
assert report["texts"] == ["browser 1", "browser 2", "browser 3"]
def test_every_engine_is_gone_when_the_four_have_closed(report):
assert report["left"] == [], "engine processes are left after every browser closed: %r" % report["left"]
@@ -0,0 +1,122 @@
"""`InProcessTransport.connect` returns without waiting for any thread to start.
`connect` is a coroutine of the user's event loop, and `Thread.start` does not return until the new thread is running. Measured with
four browsers in one process under CPU load on Windows, the four worker starts held the loop ~200 ms per launch (4.4% of the main
thread's wall time). The workers are now started by a bootstrapper that is not the loop (and is itself begun without a
`Thread.start`), and a message sent right after `connect` waits in the queue until a worker runs.
NO BROWSER HERE: a scripted server behind the real transport, with `Thread.start` slowed to 300 ms, the way a loaded machine slows it.
Known-bad input: workers started inside `connect` -> `connect` takes 4 x 300 ms and fails the 50 ms bound.
"""
from __future__ import annotations
import asyncio
import threading
import time
import pytest
from invisible_playwright._juggler.dispatcher import Server
from invisible_playwright._juggler.transport import InProcessTransport
pytestmark = pytest.mark.unit
START_DELAY_S = 0.3
class _Server(Server):
"""The registry's base class, whose `thread_starter` the transport starts its workers through, answering every call with its id."""
def handle(self, message):
return {"echo": message["id"]}
def test_connect_returns_before_any_worker_has_started_and_a_message_is_still_answered(monkeypatch):
original = threading.Thread.start
def slow_start(self):
time.sleep(START_DELAY_S)
return original(self)
monkeypatch.setattr(threading.Thread, "start", slow_start)
async def scenario():
loop = asyncio.get_running_loop()
transport = InProcessTransport(loop, _Server())
replies: "asyncio.Queue" = asyncio.Queue()
transport.on_message = replies.put_nowait
began = time.perf_counter()
await transport.connect()
took = time.perf_counter() - began
transport.send({"id": 7, "guid": "g", "method": "m", "params": {}})
reply = await asyncio.wait_for(replies.get(), 10)
transport.request_stop()
await asyncio.wait_for(transport.wait_until_stopped(), 10)
return took, reply
took, reply = asyncio.run(scenario())
assert took < 0.05, "connect() waited %.0f ms: a thread was started on the loop" % (took * 1000)
assert reply == {"id": 7, "result": {"echo": 7}}
def test_a_transport_stopped_before_its_workers_started_ends_without_error(monkeypatch):
original = threading.Thread.start
def slow_start(self):
time.sleep(START_DELAY_S)
return original(self)
monkeypatch.setattr(threading.Thread, "start", slow_start)
async def scenario():
transport = InProcessTransport(asyncio.get_running_loop(), _Server())
await transport.connect()
transport.request_stop()
await asyncio.wait_for(transport.wait_until_stopped(), 10)
asyncio.run(scenario())
def test_building_the_shared_starter_waits_for_no_thread_start(monkeypatch):
"""The starter every caller of `ThreadStarter` builds on its own thread must not itself cost a `Thread.start` there."""
from invisible_playwright._juggler._threads import ThreadStarter
original = threading.Thread.start
def slow_start(self):
time.sleep(START_DELAY_S)
return original(self)
monkeypatch.setattr(threading.Thread, "start", slow_start)
began = time.perf_counter()
starter = ThreadStarter(on_error=lambda why: None)
ran = threading.Event()
starter.start(target=ran.set, name="invpw-test-started")
took = time.perf_counter() - began
try:
assert took < 0.05, "building the starter and queueing a thread waited %.0f ms" % (took * 1000)
assert ran.wait(10), "the queued thread never ran"
finally:
starter.stop()
def test_a_browsers_reader_and_the_transports_workers_share_ONE_starter():
"""Each browser costs one starter thread, not two: the transport's workers and the browser's lease both go through the server's."""
from invisible_playwright._juggler._threads import ThreadStarter, ThreadStarterLease
async def scenario():
server = _Server()
transport = InProcessTransport(asyncio.get_running_loop(), server)
before = len(ThreadStarter.open_starters())
await transport.connect()
lease = ThreadStarterLease(lambda: server.thread_starter)
ran = threading.Event()
lease.start(target=ran.set, name="invpw-test-started")
assert ran.wait(10)
opened = len(ThreadStarter.open_starters()) - before
transport.request_stop()
await asyncio.wait_for(transport.wait_until_stopped(), 10)
return opened
assert asyncio.run(scenario()) == 1
+2
View File
@@ -22,6 +22,7 @@ import pytest
from invisible_core import SessionGeo, SessionLocale, decide_session_locale
from invisible_core.juggler.connection import EventListeners
from invisible_playwright._juggler.server import BrowserDispatcher, Server
from _browser_census import closes_with_the_test
_PKG_DIR = pathlib.Path(__file__).resolve().parent.parent / "src" / "invisible_playwright"
@@ -29,6 +30,7 @@ _PKG_DIR = pathlib.Path(__file__).resolve().parent.parent / "src" / "invisible_p
class _Connection(EventListeners):
def __init__(self):
super().__init__()
closes_with_the_test(self)
self.sent = []
def startup_send(self, method, params=None):
@@ -89,11 +89,11 @@ def test_a_context_that_is_the_only_proxy_resolves_its_names_by_doh_through_it(f
assert _asked_outside(doh, "page-a.test") == [], (
"the DoH was asked for a name that is not the proxied context's: the default context, which has no proxy, must "
"resolve natively and never use the DoH: %s" % _asked_outside(doh, "page-a.test") + why)
# A lookup of a context without `ignore_https_errors` (the default one) can only fail the handshake with the FakeDoh:
# a failed handshake is a lookup of the wrong context that reached the DoH through this gateway.
assert doh.tls_failures == [], (
"a DoH handshake failed: a context that does not accept the FakeDoh certificate (the default context, which has no "
"proxy) used the DoH: %s" % doh.tls_failures + why)
# A lookup of a context without `ignore_https_errors` (the default one) can only REFUSE the FakeDoh's certificate: a refusal
# is a lookup of the wrong context that reached the DoH through this gateway (a dropped connection is not one).
assert doh.certificate_refusals() == [], (
"a DoH handshake was refused: a context that does not accept the FakeDoh certificate (the default context, which has no "
"proxy) used the DoH: %s (every failed handshake: %s)" % (doh.certificate_refusals(), doh.tls_failures) + why)
assert watcher.watched_pids, ("the watcher never saw a browser process (it saw: %s): a watcher that cannot see proves "
"nothing" % watcher.process_names)
@@ -0,0 +1,44 @@
"""``Control+A`` selects all in an <input> and a <textarea>, in-process and served to the stock Playwright client, as it does on the stock Firefox.
Measured on the published wrapper 0.50.1 and on the engine of the giro 7 (Docker Linux, a field with 11 characters, focus, the selection collapsed
before each press): ``press("Control+A")``, ``press("ControlOrMeta+A")``, ``down("Control")`` + ``press("A")`` + ``up("Control")`` and
``locator.press("Control+A")`` left ``selectionStart == selectionEnd == 0``; ``press("Control+a")`` selected all (0, 11); the stock Firefox of
Playwright selected all with every one of them. Cause: the keyboard of invisible_core held Shift for the capital ``A`` (a character that only
exists with Shift), so the browser got Control+Shift+A, which is not the select-all command (juggler/keyboard.py, ``_shortcut_letter``).
What a page reads here is only ``selectionStart`` and ``selectionEnd`` after the shortcut: the same on every machine.
"""
from __future__ import annotations
import pytest
pytestmark = pytest.mark.e2e
_HTML = '<html><body><input id="i" value="hello world"><br><textarea id="t">hello world</textarea></body></html>'
_LENGTH = len("hello world")
_VARIANTS = ["Control+A", "Control+a", "ControlOrMeta+A", "separate", "locator.press"]
@pytest.mark.parametrize("variant", _VARIANTS)
@pytest.mark.parametrize("field", ["i", "t"])
def test_control_a_selects_all_in_the_field(browser, field, variant):
page = browser.new_page()
try:
page.set_content(_HTML)
page.evaluate("(id) => { const e = document.getElementById(id); e.focus(); e.setSelectionRange(0, 0); }", field)
if variant == "separate":
page.keyboard.down("Control")
page.keyboard.press("A")
page.keyboard.up("Control")
elif variant == "locator.press":
page.locator("#" + field).press("Control+A")
else:
page.keyboard.press(variant)
got = page.evaluate(
"(id) => { const e = document.getElementById(id); return [e.selectionStart, e.selectionEnd, document.activeElement.id]; }",
field)
finally:
page.close()
assert got == [0, _LENGTH, field], (
"%s in #%s: selection %r, expected (0, %d) in the same field" % (variant, field, got, _LENGTH))
+57 -19
View File
@@ -27,18 +27,22 @@ needs an ``invisible-core`` that declares them.
Layers:
* ``unit`` - ``_BASELINE`` contains the prefs with the right values. No browser.
* ``e2e`` - launch the real binary against a LOCAL HTTP harness on
``127.0.0.1`` and verify the four protocol operations that
regressed: frame URL tracking, ``handle.content_frame()``,
``frame.evaluate()``, and ``frame_locator(...).locator(...)``
element resolution. The harness uses two ports of one host,
which is one SITE: those iframes stay in the process of the
page even at strategy 1. The iframes that leave the process
(different hosts) are held by ``test_fission_strategy1_bench.py``.
* ``e2e`` - launch the real binary against a LOCAL HTTP harness and
verify the four protocol operations that regressed: frame URL
tracking, ``handle.content_frame()``, ``frame.evaluate()``, and
``frame_locator(...).locator(...)`` element resolution. The page
is served from ``127.0.0.1`` and its iframes from ``localhost``:
two hosts are two SITES, so at strategy 1 each iframe runs in a
content process of its own. (Two ports of one host would be one
site, and those iframes would stay in the process of the page.)
``test_the_iframe_runs_in_another_process`` proves it from
inside the pages, so this file cannot fall back to the process
of the page unnoticed. The bench with its own hosts and
process counts is ``test_fission_strategy1_bench.py``.
The e2e tests run entirely offline. They never call out to a real site;
the cross-origin shape is reproduced with two local HTTP servers on
random free ports.
the cross-site shape is reproduced with two local HTTP servers on random
free ports, reached by two names of the loopback interface.
"""
from __future__ import annotations
@@ -168,12 +172,13 @@ def _serve(payload: bytes) -> tuple[ThreadingHTTPServer, int]:
@pytest.fixture
def cross_origin_harness():
"""Spin up TWO local HTTP servers on different localhost ports.
"""Spin up TWO local HTTP servers: the page on ``127.0.0.1``, the iframes on ``localhost``.
Two ports = two distinct origins under SOP (same host, different port
→ different origin). The parent page on port A embeds an iframe with
src pointing at port B. Same cross-origin browsing-context shape as
a parent-page-plus-third-party-iframe layout, fully offline.
Two hosts = two SITES (and two origins under SOP). The parent page
embeds iframes with src pointing at the other host, which at strategy 1
puts them in another content process. Same cross-site browsing-context
shape as a parent-page-plus-third-party-iframe layout, fully offline.
The servers listen on 127.0.0.1 and the child is named ``localhost``.
"""
# The CHILD goes up first, because the parent's markup has to name the
# child's port and there is no longer a way to learn that number without
@@ -186,20 +191,49 @@ def cross_origin_harness():
sb, pb = _serve(child_html)
parent_html = f"""<!doctype html><html><head><title>parent</title></head><body>
<h1>parent</h1>
<iframe id="ifr_plain" src="http://127.0.0.1:{pb}/child" width="300" height="120"></iframe>
<iframe id="ifr_sandbox" src="http://127.0.0.1:{pb}/child" width="300" height="120"
<iframe id="ifr_plain" src="http://localhost:{pb}/child" width="300" height="120"></iframe>
<iframe id="ifr_sandbox" src="http://localhost:{pb}/child" width="300" height="120"
sandbox="allow-scripts allow-same-origin"></iframe>
<iframe id="ifr_titled" src="http://127.0.0.1:{pb}/child" width="300" height="120"
<iframe id="ifr_titled" src="http://localhost:{pb}/child" width="300" height="120"
title="cross-origin titled iframe"></iframe>
</body></html>""".encode("utf-8")
sa, pa = _serve(parent_html)
try:
yield {"parent_url": f"http://127.0.0.1:{pa}/", "child_origin": f"http://127.0.0.1:{pb}"}
yield {"parent_url": f"http://127.0.0.1:{pa}/", "child_origin": f"http://localhost:{pb}"}
finally:
sa.shutdown()
sb.shutdown()
@pytest.mark.e2e
def test_the_iframe_runs_in_another_process(firefox_binary, cross_origin_harness):
"""The harness of this file really crosses a process: a spin in the iframe does not stall the page.
The iframe spins for 600 ms and the page times a 10 ms timer; the timer
stalls only when both share a content process. Without this, a harness
that went back to two ports of one host would keep every test below green
while testing a same-process iframe.
"""
from _fission_frames import assert_other_process
from invisible_playwright import InvisiblePlaywright
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, humanize=False) as browser:
page = browser.new_context().new_page()
# ⛔ `load`, NOT `domcontentloaded`. The `domcontentloaded` of a page says nothing about its frames: the
# frame of another site is listed as soon as it is attached, and its url is the one of its navigation,
# which commits in the frame's own process, usually AFTER the page's domcontentloaded. Read straight after
# a `domcontentloaded` goto the url was empty in 26 reads of 30 on firefox-62 (stock Playwright Firefox,
# whose frames commit in the process of the page, had it 30 of 30). After the `load` of the page the url
# was there 30 of 30 on both, with no wait: that is what is asserted here, so a `goto` that returns
# with a cross-site frame still without its url fails this test.
page.goto(cross_origin_harness["parent_url"], wait_until="load", timeout=30_000)
page.wait_for_selector("iframe#ifr_plain", timeout=10_000)
frame = page.query_selector("iframe#ifr_plain").content_frame()
assert frame is not None and cross_origin_harness["child_origin"] in frame.url, (
f"after the load of the page the iframe of the other site has url {getattr(frame, 'url', None)!r}")
assert_other_process(page.main_frame, frame)
@pytest.mark.e2e
def test_cross_origin_iframe_url_appears_in_page_frames(firefox_binary, cross_origin_harness):
"""``page.frames`` must list the cross-origin iframe with its real URL.
@@ -314,6 +348,10 @@ def test_cross_origin_iframe_frame_locator_resolves_button(firefox_binary, cross
page.goto(cross_origin_harness["parent_url"], wait_until="domcontentloaded", timeout=30_000)
page.wait_for_selector("iframe#ifr_plain", timeout=10_000)
# count() does not wait (Playwright's own semantics): the iframe ELEMENT is in the parent, but its cross-origin document,
# in a process of its own, can load later on a loaded runner (Windows CI of 13/11, run 43383366904: 0 elements). Wait for
# the button first, as a script that counts it would.
page.frame_locator("iframe#ifr_plain").locator("button#ok").wait_for(timeout=10_000)
for selector in ("button#ok", "button.btn-primary"):
cnt = page.frame_locator("iframe#ifr_plain").locator(selector).count()
assert cnt == 1, f"locator({selector!r}) found {cnt} elements (expected 1)"
+1 -1
View File
@@ -73,7 +73,7 @@ def test_the_data_has_every_function_and_the_inputs_that_tell_the_libraries_apar
@pytest.mark.e2e
def test_css_calc_functions_are_ucrtbase_bytes(firefox_binary, engine_at_least):
engine_at_least("firefox-64")
engine_at_least("firefox-65")
from invisible_playwright import InvisiblePlaywright
cases = _cases()
+4
View File
@@ -32,6 +32,8 @@ import pytest
from test_webrtc_realness import _e2e_binary, _launch, candidates, decode_priority, host_candidates, is_mdns # noqa: F401
pytestmark = [pytest.mark.e2e, pytest.mark.usefixtures("the_udp_line")]
# The two tests that read a consecutive pair of ports (N, N+1) carry `wall_clock`: the e2e run gives them the machine alone, after the parallel tests,
# so that another worker's browser or test server cannot take port N+1 between the engine's draw and the bind (tests/test_the_consecutive_port_tests_run_serially.py).
NETWORK_ENV = "STEALTHFOX_WEBRTC_NETWORK"
# retail 159 on Windows. The interface rank is the position in the prioritizer's sort, starting at 127
@@ -158,6 +160,7 @@ def test_ipv6_without_the_exit_prefix_is_no_ipv6(local_https_page, socks5_tcp_on
assert _by_protocol(hosts) == {"UDP": [UDP_127], "TCP": [TCP_127]}, hosts
@pytest.mark.wall_clock
def test_the_host_ports_are_those_of_a_windows_machine(local_https_page, socks5_tcp_only, monkeypatch):
"""Retail on Windows (6 of 6 runs, ``captures/retail/firefox-159.0-win/direct-dualstack-srflx-ports``): the UDP host
ports are in the dynamic range 49152-65535 and, on one connection, the IPv4 port and the IPv6 port are consecutive
@@ -188,6 +191,7 @@ def _ports_of_two_connections(declaration, socks, page_url, monkeypatch, seed):
sorted(c["port"] for c in second if c["proto"] == "UDP"))
@pytest.mark.wall_clock
def test_two_connections_on_one_page_get_their_own_port_pair(local_https_page, socks5_tcp_only, monkeypatch):
"""Retail (``captures/retail/firefox-159.0-win/two-pc-port-sequence``, 6 of 6): each connection gets its own pair,
consecutive (N, N+1) in the range, and the second pair is unrelated to the first (not increasing)."""
+2 -1
View File
@@ -86,7 +86,8 @@ def test_the_bootstrap_address_is_a_public_address_and_not_the_proxy(compose):
def test_a_session_without_a_proxy_declares_the_provider_and_no_state(compose):
prefs = compose(None)
assert sorted(k for k in prefs if k.startswith("network.trr.")) == ["network.trr.bootstrapAddr", "network.trr.uri"]
assert sorted(k for k in prefs if k.startswith("network.trr.")) == ["network.trr.bootstrapAddr", "network.trr.builtin-excluded-domains", "network.trr.uri"]
assert prefs["network.trr.builtin-excluded-domains"] == "localhost", "only localhost stays off DoH: a *.local name behind a proxy is not read from the host"
assert prefs.get("network.proxy.allow_bypass") is not False, "no proxy, no closed fallback"
assert prefs["network.parental_controls_cached_state"] is False, "declared off with or without a proxy"
+4 -2
View File
@@ -96,9 +96,11 @@ def _only_the_doh_road_was_used(doh, gw, watcher):
"a CONNECT carried a name: the browser must resolve with the DoH and connect by address" + why)
assert "direct" not in {q.via for q in doh.queries}, "something reached the DoH without the proxy of the context" + why
_assert_every_connection_went_through_the_gateway(doh, gw)
# Context-only layout: the default context resolves natively and never uses the DoH, so a failed handshake (the lookup
# Context-only layout: the default context resolves natively and never uses the DoH, so a refused certificate (the lookup
# of a context that does not accept the FakeDoh certificate) is a lookup of the wrong context sent to the DoH.
assert doh.tls_failures == [], "a DoH handshake failed: the default context used the DoH: %s" % doh.tls_failures + why
assert doh.certificate_refusals() == [], (
"a DoH handshake was refused: the default context used the DoH: %s (every failed handshake: %s)"
% (doh.certificate_refusals(), doh.tls_failures) + why)
assert watcher.watched_pids, ("the watcher never saw a browser process (it saw: %s): a watcher that cannot see proves "
"nothing" % watcher.process_names)
assert _direct_to_the_doh(watcher) == [], (
Loaded 100 of 177 files, more files were not shown because too many files have changed in this diff. Show more