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 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
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 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
26 changed files with 2080 additions and 111 deletions

No files matched your search

@@ -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
+18 -4
View File
@@ -6,9 +6,20 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
## [Unreleased]
## [0.52.1] - 2026-11-14
## [0.52.1] - 2026-11-15
Same pin as 0.52.0 (invisible-core 64.71.0).
### 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)
@@ -18,8 +29,11 @@ Same pin as 0.52.0 (invisible-core 64.71.0).
- 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)
### Changed
- 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)
### 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
+3 -3
View File
@@ -7,9 +7,9 @@
{"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": 249, "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"], "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": 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.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": 17, "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 and the CPU of a window, and the shape of the committed Windows reference."}
{"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."}
]
+1 -1
View File
@@ -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==64.71.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
+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])
@@ -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", "")
+56 -7
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,6 +103,10 @@ 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 ──────────────────────────────────
@@ -131,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()
@@ -138,23 +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)
async def wait_until_stopped(self) -> None:
await self._stopped_future
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
await off_the_loop(self._join_workers)
def send(self, message: Dict) -> None:
"""⛔ ENQUEUE ONLY. Running the operation here would run it on the
+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]
+19 -2
View File
@@ -37,8 +37,25 @@ def delta_by_type(start: Dict[int, Tuple[str, float]], last: Dict[int, Tuple[str
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 named firefox below `root_pid`, now."""
"""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]] = {}
@@ -48,7 +65,7 @@ def engine_processes(root_pid: int) -> Dict[int, Tuple[str, float]]:
return out
for proc in below:
try:
if not proc.name().lower().startswith("firefox"):
if not is_engine(proc):
continue
times = proc.cpu_times()
out[proc.pid] = (classify(proc.cmdline()), times.user + times.system)
+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:
+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:
+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"
}
}
}
+87 -6
View File
@@ -1,6 +1,6 @@
{
"os": "windows",
"source": "GitHub Actions run 43652292533 (workflow 'cpu render path hunt vm', job on windows-2022), arm `ours` = the published engine firefox-64_159.0_20261114003728 with the core the branch installed from the index (before the declaration of software compositing), seed 42, locale en-US, timezone Europe/Rome, headless=True; launched twice, and the arm `ours_vmretail` (the VM decisions of the new core) twice more: every key below is equal in the four launches. `pngs`: the PNG keys, whose bytes differ in a 16-byte chunk `deBG` in every launch; their length, and the pixels they decode to where the hunt kept the bytes (a data URL longer than 3000 characters was kept as hash and length only: those five entries have no `sha256` and are written by the first run of tests/test_the_bytes_a_page_reads_do_not_change_e2e.py on the engine of the reference). The keys of c2d.scale.*, c2d.gradtext.*, gpu.webgpu.features and gpu.webgpu.limits were added to the probe after that run (in it the WebGPU read threw `Xray wrapping of iterators not supported`, key gpu.webgpu.error, dropped here) and are in no reference yet.",
"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",
@@ -14,6 +14,10 @@
"h": "182ab2238ae6c0",
"n": 5431
},
"c2d.gradtext.getImageData": {
"h": "42edf4d4d5394",
"n": 352800
},
"c2d.image.getImageData": {
"h": "8218d41a1794c",
"n": 76800
@@ -34,6 +38,22 @@
"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
@@ -259,9 +279,15 @@
"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]}"
}
@@ -281,8 +307,19 @@
"ct": 6,
"sha256": "fb585f18240eb1a787a5b146d6332a0376dae76f8c8716e99f68fbbf9eff905e"
},
"c2d.gradtext.png": {
"n": 55210,
"w": 420,
"h": 210,
"ct": 6,
"sha256": "1ce15c9ea557be69b62b4893b148345a694a93222c721b1bbb21cdcedebba5a0"
},
"c2d.image.png": {
"n": 19502
"n": 19502,
"w": 160,
"h": 120,
"ct": 6,
"sha256": "51bc3789f2e238dfbf8899eb7a965a4f04d3e0e7f2246b1bd3cfdc9597bd2a77"
},
"c2d.image.toBlob": {
"n": 14610,
@@ -298,8 +335,40 @@
"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
"n": 19226,
"w": 256,
"h": 160,
"ct": 6,
"sha256": "89ee57c100f4682099bd3a5f2de56c5b31091dae253bd7e3db4f254fb8b9e6a3"
},
"c2d.shapes.toBlob": {
"n": 14402,
@@ -309,7 +378,11 @@
"sha256": "89ee57c100f4682099bd3a5f2de56c5b31091dae253bd7e3db4f254fb8b9e6a3"
},
"c2d.text.png": {
"n": 42670
"n": 42670,
"w": 520,
"h": 412,
"ct": 6,
"sha256": "93d6fc37d2263e52e7b1b46f77c65d9e607faf577eb7c255dc38cbce8b7d7602"
},
"c2d.text.toBlob": {
"n": 31986,
@@ -319,10 +392,18 @@
"sha256": "93d6fc37d2263e52e7b1b46f77c65d9e607faf577eb7c255dc38cbce8b7d7602"
},
"gl1.triangle.toDataURL": {
"n": 7474
"n": 7474,
"w": 96,
"h": 96,
"ct": 6,
"sha256": "9989d00c92e8ae035dede9b81b1c9942223799c0ccc4d4875c8eca9efaca776c"
},
"gl2.triangle.toDataURL": {
"n": 7474
"n": 7474,
"w": 96,
"h": 96,
"ct": 6,
"sha256": "9989d00c92e8ae035dede9b81b1c9942223799c0ccc4d4875c8eca9efaca776c"
}
}
}
@@ -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"
@@ -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"]
-6
View File
@@ -171,12 +171,6 @@ def no_geo_lookup(monkeypatch):
lambda tz, proxy, locale, **_kw: SessionGeo(
"America/New_York", "198.51.100.4",
locale=decide_session_locale("en-US")))
# And the lifetime guard. `bind` waits for the browser tree to APPEAR -
# correct on a real launch, and here Playwright is a MagicMock so no process
# ever comes, and each of these four tests sat out the whole 10s deadline.
# The guard has its own tests in the core (test_process_guard.py); these
# assert which Playwright call the launcher makes.
monkeypatch.setattr(InvisiblePlaywright, "_bind_process_tree", lambda self: None)
@pytest.mark.unit
@@ -202,11 +202,15 @@ window.__ready = (async () => {
#: the runner's sake stays under it, and the hardware WebRender, which keeps the GPU process busy for every frame, does not.
#: This test starts ONE browser, which the GPU process has to itself, so it is at most what a browser used when four shared the runner.
#:
#: LINUX: there is no measurement of the GPU process on the Linux runner yet, and there may be no GPU process at all (software
#: WebRender on Linux can run in the parent). The test asserts on what exists: if a GPU process exists its CPU is held to the same bound,
#: and the parent's and the tab's CPU are printed with it. It does not assert that one exists. A first run on Linux says what the numbers
#: are; the bound for it is to be tightened from them, not guessed.
GPU_CPU_LIMIT_S = {"windows": 1.5, "linux": 1.5}
#: LINUX: THERE IS NO GPU PROCESS. Software WebRender composites in the parent, and the engine's tree on Linux is the parent, the
#: forkserver, the content processes (`tab`), the socket, the RDD and utility processes (WSL, firefox-64, /proc read; e2e Linux run
#: 43701692047 saw the same). The test says so, and holds the PARENT, where the compositing runs, to a bound measured on the Linux
#: runner: PARENT_CPU_LIMIT_LINUX_S below.
GPU_CPU_LIMIT_S = {"windows": 1.5}
#: CPU seconds the parent may use for the 10 scenes of ONE browser on the ubuntu-latest runner: 3.5 s. Measured there with this test,
#: 20 runs on two runners (run 43707494271): parent 2.11 to 2.46 s, median 2.31 s; tab 0.41 to 0.54 s; no GPU process in any run.
#: 3.5 s is 1.4 times the most a run used: a slow runner stays under it, and a parent that composites at half again its cost does not.
PARENT_CPU_LIMIT_LINUX_S = 3.5
def test_the_gpu_process_is_idle_on_a_fixed_scene(firefox_binary, capsys):
@@ -238,9 +242,15 @@ def test_the_gpu_process_is_idle_on_a_fixed_scene(firefox_binary, capsys):
assert states == ["complete"] * ROUNDS, "the scene did not run %d times to its end: %r" % (ROUNDS, states)
assert "parent" in seen and "tab" in seen, \
"no parent and content process of the engine below the test process (seen: %r): the process tree is cut and the CPU is not the browser's" % (seen,)
if OS_NAME == "linux":
assert "gpu" not in seen, "the Linux engine has a GPU process (seen: %r): software WebRender was measured without one" % (seen,)
assert cpu["parent"] < PARENT_CPU_LIMIT_LINUX_S, (
"the parent, where software WebRender composites on Linux, used %.2f s of CPU for %d scenes of one browser, the bound is "
"%.1f s (all types: %s)" % (cpu["parent"], ROUNDS, PARENT_CPU_LIMIT_LINUX_S,
json.dumps({k: round(v, 2) for k, v in cpu.items() if v})))
return
limit = GPU_CPU_LIMIT_S[OS_NAME]
if OS_NAME == "windows":
assert "gpu" in seen, "the Windows engine has no GPU process (seen: %r); the measurement of the bound had one" % (seen,)
assert "gpu" in seen, "the Windows engine has no GPU process (seen: %r); the measurement of the bound had one" % (seen,)
if "gpu" in seen:
assert cpu["gpu"] < limit, (
"the GPU process used %.2f s of CPU for %d scenes of one browser on %s, the bound is %.1f s (all types: %s). With the compositing "
@@ -0,0 +1,130 @@
"""A launch scans no process of the machine, and the engine's tree still dies with its launcher.
THE KNOWN-BAD INPUT, measured with py-spy on a Windows runner: at every launch `InvisiblePlaywright._bind_process_tree` called the
core's `JobObjectGuard.bind`, which read the environment of EVERY process of the machine (`psutil.process_iter` and
`Process.environ`, under the GIL on Windows), slept a quarter of a second and scanned again until a second passed with nothing new,
up to ten, synchronously on the caller's thread or event loop: 12-29% of the main thread's time and most of the GIL samples.
The core now creates the engine inside the process's job object (`invisible_core.process.engine_job`, used by the spawn in
`juggler.connection`), so its whole tree, late children included, is in the job by construction, and the wrapper no longer binds
anything. Three tests, on the real engine:
1. a launch (`__enter__`, a page, up to the moment before `__exit__`) makes no call to `psutil.process_iter` and none to
`psutil.Process.environ`. Red on the old wrapper on Windows, where the guard is the job guard;
2. after `browser.close()` no process of the session is left, the late children (the pingsender) included;
3. a client that launches and is ended with TerminateProcess leaves no engine process: the job closes them.
Windows is where the job exists; the first two run on Linux too, where they hold for the same reason in a different way (nothing
scans, `close()` ends the tree).
"""
from __future__ import annotations
import subprocess
import sys
import textwrap
import threading
import traceback
import pytest
pytestmark = pytest.mark.e2e
WINDOWS = sys.platform == "win32"
def _token_value(session) -> str:
return session._session_token.value
def test_a_launch_scans_no_process_of_the_machine(firefox_binary, monkeypatch):
import psutil
from invisible_playwright import InvisiblePlaywright
calls = []
real_iter, real_environ = psutil.process_iter, psutil.Process.environ
def watched_iter(*a, **k):
calls.append(("process_iter", "".join(traceback.format_stack(limit=6))))
return real_iter(*a, **k)
def watched_environ(self):
calls.append(("environ", "".join(traceback.format_stack(limit=6))))
return real_environ(self)
monkeypatch.setattr(psutil, "process_iter", watched_iter)
monkeypatch.setattr(psutil.Process, "environ", watched_environ)
session = InvisiblePlaywright(seed=7101, binary_path=firefox_binary,
humanize=False, headless=True)
with session as browser:
page = browser.new_page()
page.set_content("<p>born in the job</p>")
seen = list(calls)
assert not seen, (
"the launch read the machine's processes %d times; the first from:\n%s"
% (len(seen), seen[0][1]))
def test_after_close_no_process_of_the_session_is_left(firefox_binary):
from invisible_core.process import find_processes, wait_until_gone, SessionToken
from invisible_playwright import InvisiblePlaywright
session = InvisiblePlaywright(seed=7102, binary_path=firefox_binary,
humanize=False, headless=True)
with session as browser:
page = browser.new_page()
page.set_content("<p>one page, so a content process exists</p>")
token = SessionToken(_token_value(session))
assert len(find_processes(token)) >= 2, "no tree to leave behind"
browser.close()
left = [] if wait_until_gone(token, timeout=30) else find_processes(token)
assert not left, "processes of the session after close(): %s" % [
(p.pid, p.name()) for p in left]
_CLIENT = textwrap.dedent("""
import sys, time
from invisible_playwright import InvisiblePlaywright
session = InvisiblePlaywright(seed=7103, binary_path=sys.argv[1],
humanize=False, headless=True)
browser = session.__enter__()
page = browser.new_page()
page.set_content("<p>a page, so a content process exists</p>")
print("TOKEN", session._session_token.value, flush=True)
time.sleep(300)
""")
@pytest.mark.skipif(not WINDOWS, reason="the job object is Windows; Linux has no equivalent here")
def test_when_the_client_is_killed_no_engine_process_is_left(firefox_binary, tmp_path):
import psutil
from invisible_core.process import SessionToken, find_processes, terminate
script = tmp_path / "client.py"
script.write_text(_CLIENT, encoding="utf-8")
client = subprocess.Popen([sys.executable, str(script), firefox_binary],
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
lines = []
def read():
for raw in iter(client.stdout.readline, b""):
lines.append(raw.decode("utf-8", "replace").strip())
if lines[-1].startswith("TOKEN "):
return
reader = threading.Thread(target=read, daemon=True)
reader.start()
reader.join(240)
token = SessionToken(next((x.split()[1] for x in lines if x.startswith("TOKEN ")), ""))
assert token, "the client never launched: %r" % lines
try:
tree = find_processes(token)
assert len(tree) >= 2, "the engine's tree was not there to be killed"
client.kill() # TerminateProcess: no teardown runs
_, alive = psutil.wait_procs(tree, timeout=30)
assert not alive, "survivors of the killed client: %s" % [
(p.pid, p.name()) for p in alive]
finally:
client.kill()
terminate(find_processes(token))
@@ -171,6 +171,63 @@ def test_the_type_of_a_process_is_the_last_argument_of_contentproc():
assert cpu.classify(["firefox.exe", "-contentproc", "weird"]) == "other"
class _Proc:
"""A process as psutil gives it: the name it gave itself, its executable, its command line, its CPU."""
def __init__(self, pid, name, exe, cmdline, cpu_s=1.0):
self.pid, self._name, self._exe, self._cmdline, self._cpu = pid, name, exe, cmdline, cpu_s
def name(self):
return self._name
def exe(self):
return self._exe
def cmdline(self):
return self._cmdline
def cpu_times(self):
import collections
return collections.namedtuple("t", "user system")(self._cpu, 0.0)
def _below(monkeypatch, children):
import psutil
class _Root:
def __init__(self, pid):
pass
def children(self, recursive=False):
return children
monkeypatch.setattr(psutil, "Process", _Root)
def test_a_linux_child_that_names_itself_after_its_role_is_still_the_engine(monkeypatch):
"""The process tree of a Linux engine as /proc shows it (WSL, firefox-64): every child runs the firefox executable and names itself
after its role. Counted by name, only the parent was seen and the content processes were lost (e2e Linux, run 43701692047)."""
ff = "/opt/engine/firefox-64/firefox"
_below(monkeypatch, [
_Proc(1, "firefox", ff, [ff, "-profile", "p"]),
_Proc(2, "forkserver", ff, [ff, "-contentproc", "forkserver"]),
_Proc(3, "Isolated Web Co", ff, [ff, "-contentproc", "-isForBrowser", "tab"]),
_Proc(4, "Web Content", ff, [ff, "-contentproc", "tab"]),
_Proc(5, "Socket Process", ff, [ff, "-contentproc", "socket"]),
])
kinds = sorted(kind for kind, _cpu in cpu.engine_processes(0).values())
assert kinds == ["forkserver", "parent", "socket", "tab", "tab"], kinds
def test_a_process_that_does_not_run_the_firefox_executable_is_not_the_engine(monkeypatch):
_below(monkeypatch, [
_Proc(1, "firefox.exe", r"C:\e\firefox.exe", [r"C:\e\firefox.exe", "-contentproc", "gpu"]),
_Proc(2, "python3", "/usr/bin/python3", ["/usr/bin/python3", "-c", "x"]),
_Proc(3, "Xvfb", "/usr/bin/Xvfb", ["Xvfb", ":99"]),
])
assert sorted(kind for kind, _cpu in cpu.engine_processes(0).values()) == ["gpu"]
def test_the_cpu_of_a_window_is_the_last_value_minus_the_first_and_a_new_process_counts_whole():
start = {1: ("parent", 10.0), 2: ("gpu", 1.0)}
last = {1: ("parent", 12.5), 2: ("gpu", 1.25), 3: ("gpu", 0.5), 4: ("tab", 2.0)}
@@ -0,0 +1,188 @@
"""The UDP bench (``_socks_servers``) does not die of what a loaded Windows machine does to its sockets, and the verdict of a
failed UDP test says what the bench saw.
Three things made the red of ``test_a_gateway_that_is_far_away_still_gives_the_page_a_srflx_born_through_its_relay`` unreadable:
* the fake STUN server read with a socket that still reported ICMP "port unreachable" (``SIO_UDP_CONNRESET``): the next ``recvfrom``
raised ``ConnectionResetError`` and the ``except OSError: return`` ended the thread that answers, in silence, for every client after;
* the relay's ``inbound`` thread asked the exit socket for its port at every datagram, and at the teardown that socket was already
closed (``OSError`` WinError 10038, an unhandled exception of a thread);
* the verdict of the test said nothing of the gateway's send errors, CONNECTs and associations, nor of what the core had declared
for the proxy: a measurement of the core that ended past its budget looked like a page that never took the relay.
No browser, loopback only. The ICMP of Windows is simulated by a socket that raises the same error, so the tests fail on the old code
on any system.
"""
from __future__ import annotations
import socket
import struct
import threading
import time
import pytest
from _socks_servers import MEASURE_NUMBER, STUN_PORT, FakeStun, coherent
from _udp_line import bench_report, declared_udp_or_absent, udp_measure_sentence
pytestmark = pytest.mark.unit
_REAL_SOCKET = socket.socket
_BINDING = b"\x00\x01\x00\x00" + b"\x21\x12\xa4\x42" + b"0123456789ab"
def _flaky_socket(fail_recv: int = 0, fail_send: int = 0):
"""A socket class whose first ``fail_recv`` recvfrom raise ConnectionResetError (the ICMP of Windows) and whose first
``fail_send`` sendto raise ConnectionResetError, then behave as real ones."""
state = {"recv": fail_recv, "send": fail_send}
class Flaky(_REAL_SOCKET):
def recvfrom(self, *args):
if state["recv"] > 0:
state["recv"] -= 1
raise ConnectionResetError(10054, "an existing connection was forcibly closed")
return super().recvfrom(*args)
def sendto(self, *args):
if state["send"] > 0:
state["send"] -= 1
raise ConnectionResetError(10054, "an existing connection was forcibly closed")
return super().sendto(*args)
return Flaky
def _fake_stun(monkeypatch, **flaky) -> FakeStun:
with monkeypatch.context() as patch:
patch.setattr(socket, "socket", _flaky_socket(**flaky))
return FakeStun("203.0.113.7")
def _ask(stun: FakeStun) -> bytes:
client = _REAL_SOCKET(socket.AF_INET, socket.SOCK_DGRAM)
try:
client.settimeout(2)
client.sendto(_BINDING, stun.address)
return client.recvfrom(2048)[0]
finally:
client.close()
def test_the_fake_stun_answers_after_a_recvfrom_that_raised_connection_reset(monkeypatch):
stun = _fake_stun(monkeypatch, fail_recv=1)
try:
assert _ask(stun)[:2] == b"\x01\x01", "the server ended its thread at the reset and answered nobody after it"
assert stun.requests == 1
finally:
stun.close()
def test_the_fake_stun_answers_the_next_client_after_a_sendto_that_failed(monkeypatch):
stun = _fake_stun(monkeypatch, fail_send=1)
try:
client = _REAL_SOCKET(socket.AF_INET, socket.SOCK_DGRAM)
client.settimeout(0.3)
client.sendto(_BINDING, stun.address) # its answer fails to be sent: nobody is told
with pytest.raises(socket.timeout):
client.recvfrom(2048)
client.close()
assert _ask(stun)[:2] == b"\x01\x01", "a failed send ended the server for every client after it"
assert stun.requests == 2
finally:
stun.close()
def test_a_closed_fake_stun_ends_its_thread(monkeypatch):
stun = _fake_stun(monkeypatch)
stun.close()
stun._thread.join(timeout=2)
assert not stun._thread.is_alive()
def _associate(gateway):
"""The SOCKS5 handshake and a UDP ASSOCIATE; the control connection and the address of the relay."""
control = _REAL_SOCKET(socket.AF_INET, socket.SOCK_STREAM)
control.settimeout(3)
control.connect(("127.0.0.1", gateway.port))
control.sendall(b"\x05\x01\x00")
assert control.recv(2) == b"\x05\x00"
control.sendall(b"\x05\x03\x00\x01" + b"\x00" * 4 + b"\x00\x00")
reply = b""
while len(reply) < 10:
reply += control.recv(10 - len(reply))
assert reply[1] == 0, reply
return control, (socket.inet_ntoa(reply[4:8]), struct.unpack("!H", reply[8:10])[0])
def _wait(condition, seconds=3.0):
end = time.monotonic() + seconds
while time.monotonic() < end:
if condition():
return True
time.sleep(0.01)
return False
def test_the_inbound_thread_of_an_association_ends_clean_when_its_exit_socket_is_closed(monkeypatch):
created = []
class Recording(_REAL_SOCKET):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
created.append(self)
raised = []
monkeypatch.setattr(threading, "excepthook", lambda args: raised.append(args))
datagram = b"\x00\x00\x00\x01" + socket.inet_aton("198.51.100.77") + struct.pack("!H", 9) + b"payload"
with coherent() as gateway:
gateway.forward_only_to = set() # nothing leaves the machine
monkeypatch.setattr(socket, "socket", Recording)
control, relay = _associate(gateway)
monkeypatch.setattr(socket, "socket", _REAL_SOCKET)
client = _REAL_SOCKET(socket.AF_INET, socket.SOCK_DGRAM)
try:
client.sendto(datagram, relay)
assert _wait(lambda: len(gateway.datagram_log) == 1), "the relay never carried the first datagram"
out = [s for s in created if s.type == socket.SOCK_DGRAM and s.fileno() != -1
and s.getsockname()[1] == gateway.exit_ports[0]]
assert len(out) == 1
out[0].close() # the teardown closes the exit socket before the thread has seen it
client.sendto(datagram, relay)
assert _wait(lambda: len(gateway.datagram_log) == 2), "the relay stopped at the closed exit socket"
time.sleep(0.3) # the time a thread needs to raise what it raises
finally:
client.close()
control.close()
assert not raised, "the inbound thread raised: %s" % [repr(args.exc_value) for args in raised]
class _Gateway:
"""What a report reads of a gateway, set by hand."""
datagram_log = [(MEASURE_NUMBER, STUN_PORT, 1, 0.5), ("198.51.100.5", STUN_PORT, 1, 1.25)]
send_errors = ["the datagram to 198.51.100.4:5: OSError [WinError 10051] unreachable"]
connects = [("api.ipify.org", 80)]
accepted = [0.1, 0.2, 0.3]
associations = [[0.4, 1.0], [2.0, None]]
def test_the_report_of_a_bench_says_what_the_gateway_saw():
text = bench_report(_Gateway, 900, "coherent")
for piece in ("WinError 10051", "api.ipify.org", "TCP connections it accepted: 3", "[0.4, 1.0]", "[2.0, None]",
"%s:%d atyp=1 t=0.500s" % (MEASURE_NUMBER, STUN_PORT), "198.51.100.5:%d atyp=1 t=1.250s" % STUN_PORT,
"declared for this proxy: coherent"):
assert piece in text, (piece, text)
assert "did not finish" not in text
@pytest.mark.parametrize("declared", [None, "unmeasured", "no"])
def test_a_core_measure_that_is_not_coherent_is_said_outright_with_the_round_trip(declared):
sentence = udp_measure_sentence(declared, 900)
assert "did not finish" in sentence and "rtt 900 ms" in sentence, sentence
assert "did not finish" in bench_report(_Gateway, 900, declared)
if declared:
assert declared in sentence
def test_what_the_core_declared_is_absent_not_an_error_when_it_measured_nothing():
assert declared_udp_or_absent({"server": "socks5://127.0.0.1:1"}, ["198.51.100.6:19302"]) is None
@@ -0,0 +1,177 @@
"""Starting the hidden display must not block the event loop of an async user.
`headless=True` starts a virtual display (an Xvfb on Linux) before the browser
launches. The start is a blocking call (it spawns the server and waits for it
to report ready, ~75 ms measured, far more on a loaded host), and `__aenter__`
made it ON the user's loop: four browsers in one process each froze the other
three for that long. The async path awaits it in a worker thread; the sync path
has no other browser on its thread and stays as it was.
The display is still started - the hidden-headed surface is what the product
promises (`core-10-superficie-nascosta-headed`) - only the thread changes.
"""
from __future__ import annotations
import asyncio
import threading
import time
import types
import pytest
from invisible_core import SessionLocale
from invisible_core.launch import FontManifestMismatch
from invisible_playwright import _session, async_api
START_SECONDS = 0.5
class SlowDisplay:
"""Stand-in for a display whose start takes 500 ms."""
def __init__(self) -> None:
self.started_on = None
self.stopped = 0
self.release = None
def start(self) -> None:
self.started_on = threading.get_ident()
time.sleep(START_SECONDS)
def stop(self) -> None:
self.stopped += 1
def launch_env(self):
return {}
@pytest.fixture
def slow(monkeypatch):
vd = SlowDisplay()
geo = types.SimpleNamespace(timezone="Europe/Rome",
locale=SessionLocale.of("it-IT"),
egress_ip=None,
geolocation_override=lambda: None)
def refuse(**_kw):
raise FontManifestMismatch("stop here: the launch is not the subject")
monkeypatch.delenv(_session.TRUE_HEADLESS_ENV, raising=False)
monkeypatch.setattr(_session, "make_virtual_display", lambda: vd)
monkeypatch.setattr(_session, "build_env", refuse)
# Composing the prefs is its own ~100 ms of CPU on a cold process and is not
# the subject: the test measures the display start alone.
monkeypatch.setattr(async_api.InvisiblePlaywright, "_build_prefs", lambda _s: {})
# Nor is the teardown's process scan (~100 ms on a host with many
# processes): a stand-in that does only what this test checks, stop the display.
async def teardown(self):
vd, self._virtual_display = self._virtual_display, None
if vd is not None:
vd.stop()
monkeypatch.setattr(async_api.InvisiblePlaywright, "_teardown", teardown)
monkeypatch.setattr(async_api, "prepare_session_geo", lambda *_a, **_k: geo)
monkeypatch.setattr(async_api, "resolve_executable", lambda _p: "firefox")
return vd
def test_a_second_browser_is_served_while_the_first_starts_its_display(slow):
gaps = []
async def second_browser():
# Another browser on this loop asks for a reply every 10 ms while the
# first one launches. A reply later than 100 ms means the loop was held.
last = time.perf_counter()
while True:
await asyncio.sleep(0.01)
now = time.perf_counter()
gaps.append(now - last)
last = now
async def run():
first = async_api.InvisiblePlaywright(seed=7, headless=True)
other = asyncio.ensure_future(second_browser())
await asyncio.sleep(0.05)
launch = asyncio.ensure_future(first.__aenter__())
with pytest.raises(FontManifestMismatch):
await launch
await asyncio.sleep(0.05) # let the ticker record the last gap
other.cancel()
return first
first = asyncio.run(run())
assert len(gaps) > 5 and max(gaps) < 0.1, (
"the second browser waited %.0f ms for a reply: the display start ran "
"on the loop" % (max(gaps) * 1000))
assert slow.started_on is not None
assert slow.started_on != threading.get_ident(), "the start ran on the loop thread"
# The surface is still created, and still stopped by a failed launch.
assert slow.stopped == 1
assert first._virtual_display is None
def test_a_launch_cancelled_during_the_display_start_leaves_no_display(slow):
async def run():
first = async_api.InvisiblePlaywright(seed=7, headless=True)
launch = asyncio.ensure_future(first.__aenter__())
await asyncio.sleep(0.1) # the start is in its worker
launch.cancel()
with pytest.raises(asyncio.CancelledError):
await launch
await asyncio.sleep(START_SECONDS + 0.3) # the worker finishes
return first
asyncio.run(run())
assert slow.stopped == 1, "a display started for a cancelled launch was left running"
# -- one decision for both APIs ----------------------------------------------
class QuickDisplay:
def __init__(self) -> None:
self.started = 0
def start(self) -> None:
self.started += 1
def stop(self) -> None:
pass
@pytest.mark.parametrize("headless", [False, True])
@pytest.mark.parametrize("true_headless", [False, True])
@pytest.mark.parametrize("platform_has_display", [True, False])
def test_sync_and_async_make_the_same_decision(monkeypatch, headless, true_headless,
platform_has_display):
"""The same inputs give the same answer, the same display and the same
started/recorded facts on both paths: the decision lives in one function."""
from invisible_playwright import launcher
if true_headless:
monkeypatch.setenv(_session.TRUE_HEADLESS_ENV, "1")
else:
monkeypatch.delenv(_session.TRUE_HEADLESS_ENV, raising=False)
monkeypatch.setattr(
_session, "make_virtual_display",
lambda: QuickDisplay() if platform_has_display else None)
def outcome(session, result):
vd = session._virtual_display
return (result, vd is not None, vd.started if vd is not None else None)
sync = launcher.InvisiblePlaywright(seed=7, headless=headless)
got_sync = outcome(sync, sync._resolve_headless())
use = async_api.InvisiblePlaywright(seed=7, headless=headless)
got_async = outcome(use, asyncio.run(use._resolve_headless_async()))
assert got_sync == got_async
# And the decision itself, for the record.
if not headless:
assert got_sync == (False, False, None)
elif true_headless:
assert got_sync == (True, False, None)
elif platform_has_display:
assert got_sync == (False, True, 1)
else:
assert got_sync == (False, False, None)
+5 -2
View File
@@ -32,7 +32,7 @@ import pytest
from _host_address import this_host_address
from _socks_servers import MEASURE_NUMBER, STUN_PORT, Socks5TcpOnly
from _udp_line import declared_udp, egress_by_proxy, measure_servers
from _udp_line import bench_report, declared_udp, declared_udp_or_absent, egress_by_proxy, measure_servers
# ──────────────────────────────────────────────────────────────────────────
# Pure SDP / ICE-candidate helpers (no I/O) - the heart of the sentinels.
@@ -438,11 +438,14 @@ def _gather_behind_a_coherent_gateway(monkeypatch, credentials, ice_prefs, rtt_m
carried = [(host, port) for host, port, _payload in gateway.datagrams]
stun_requests = gateway.stun.requests
associates = gateway.associates
# What the bench saw, taken before the gateway closes: its send errors, CONNECTs, accepted connections, associations and the
# datagrams with their times, and what the core declared for this proxy (absent when its measure never finished).
bench = bench_report(gateway, rtt_ms, declared_udp_or_absent(gateway.proxy, measure_servers(gateway)))
srflx = [c for c in srflx_candidates(candidates(res["candidates"])) if c["address"] == exit_ip]
verdict = (f"srflx with the gateway's exit {exit_ip}: {srflx}; candidates: {res['candidates']}; "
f"ICE errors: {res['errors']}; gather timings (ms from the offer): {res['at_ms']}; "
f"datagrams the relay carried: {carried}; STUN requests the server answered: {stun_requests}; "
f"UDP ASSOCIATEs the gateway saw: {associates}; round trip to the gateway: {rtt_ms} ms")
f"UDP ASSOCIATEs the gateway saw: {associates}; round trip to the gateway: {rtt_ms} ms; {bench}")
return bool(srflx) and (STUN_NUMBER, STUN_PORT) in carried, verdict, res["at_ms"]
+111
View File
@@ -0,0 +1,111 @@
"""The back-forward-cache test writes down what it knows BEFORE it asserts, and the lab holds the host's two inputs of the cache still. No browser.
A red of tests/test_a_worker_comes_back_with_its_page_from_the_cache_e2e.py used to be the single sentence "the page was loaded again instead of
restored from the back-forward cache" (hunt of 2026-11-12, one run of 15, [top-other-site-goto]) and nothing else was left of the run, so nobody could say whether the
engine had announced a restore, or Firefox had refused or evicted the page. These tests hold what that red now carries, and that the lab no
longer lets the memory of the machine decide whether the cache holds.
"""
import _bfcache_evidence as bfc
import pytest
pytestmark = pytest.mark.unit
RESTORED = [("Page.navigationStarted", {"navigationId": "nav-bfcache-1"}),
("Page.navigationCommitted", {"navigationId": "nav-bfcache-1", "url": "http://a.test:1/top-worker"}),
("Runtime.executionContextsCleared", {}),
("Page.frameDocumentRestored", {"frameId": "f1"}),
("Page.workerCreated", {"workerId": "w1"}),
("Page.eventFired", {"name": "pageshow"})]
LOADED_AGAIN = [("Page.navigationStarted", {"navigationId": "nav-7"}),
("Page.navigationCommitted", {"navigationId": "nav-7", "url": "http://a.test:1/top-worker"}),
("Runtime.executionContextsCleared", {}),
("Page.eventFired", {"name": "load"}),
("Page.workerCreated", {"workerId": "w2"})]
class _Page:
def __init__(self, shown, entry="back_forward", state="complete"):
self._answers = [shown, entry, state]
def evaluate(self, expression):
return self._answers.pop(0)
def test_the_evidence_is_read_from_the_page_and_the_events_since_go_back():
prefix = [("Page.workerCreated", {"workerId": "old"})] # before go_back: not part of the evidence
ev = bfc.read_after_go_back(_Page([False, True]), prefix + RESTORED, len(prefix))
assert ev.restored and ev.engine_announced_a_restore
assert ev.navigation_type == "back_forward" and ev.ready_state == "complete"
assert ev.events == ["Page.navigationStarted nav-bfcache-1",
"Page.navigationCommitted nav-bfcache-1 http://a.test:1/top-worker",
"Runtime.executionContextsCleared", "Page.frameDocumentRestored f1", "Page.workerCreated w1",
"Page.eventFired pageshow"]
def test_a_red_writes_the_evidence_down_before_it_asserts_and_the_message_carries_it():
written = []
ev = bfc.read_after_go_back(_Page([False]), LOADED_AGAIN, 0)
with pytest.raises(AssertionError) as red:
bfc.decide_outcome(ev, False, written.append)
assert len(written) == 1, "the evidence was not written before the assertion"
assert "__shown=[False]" in written[0] and "the engine announced a restore: no" in written[0] and "outcome: failed" in written[0]
assert "Page.eventFired load" in written[0] and "nav-7" in written[0]
assert "built again instead of restored" in str(red.value) and ev.text() in str(red.value) and written[0].startswith(ev.text())
def test_a_restore_the_engine_announced_but_the_page_did_not_see_is_a_defect_even_where_a_reload_is_accepted():
ev = bfc.read_after_go_back(_Page([False]), RESTORED, 0)
assert ev.engine_announced_a_restore and not ev.restored
for may_reload in (False, True):
with pytest.raises(AssertionError) as red:
bfc.decide_outcome(ev, may_reload, lambda _line: None)
assert "the engine announced a restore" in str(red.value) and "pageshow with persisted" in str(red.value)
def test_a_restored_page_is_said_restored_and_written_down_too():
written = []
assert bfc.decide_outcome(bfc.read_after_go_back(_Page([False, True]), RESTORED, 0), False, written.append) == "restored"
assert len(written) == 1 and "__shown=[False, True]" in written[0] and "outcome: restored" in written[0]
assert bfc.decide_outcome(bfc.read_after_go_back(_Page([False, True]), RESTORED, 0), True, lambda _l: None) == "restored"
def test_a_document_built_again_is_said_reloaded_only_where_firefox_may_refuse_the_cache():
written = []
ev = bfc.read_after_go_back(_Page([False]), LOADED_AGAIN, 0)
assert bfc.decide_outcome(ev, True, written.append) == "reloaded"
assert "outcome: reloaded" in written[0]
with pytest.raises(AssertionError):
bfc.decide_outcome(ev, False, lambda _l: None)
def test_the_lab_holds_the_two_host_inputs_of_the_cache_still():
import test_a_worker_comes_back_with_its_page_from_the_cache_e2e as e2e
prefs = e2e.LAB_PREFS
assert prefs["browser.sessionhistory.max_total_viewers"] == 8
assert prefs["browser.low_commit_space_threshold_percent"] == 0 and prefs["browser.low_commit_space_threshold_mb"] == 0
assert all(prefs[k] == v for k, v in e2e.STRATEGY_1.items()), "the lab's prefs are the strategy's plus the two"
def test_the_test_has_no_repeat_no_skip_and_asks_for_the_evidence_and_the_cacheable_page():
import pathlib
source = (pathlib.Path(__file__).resolve().parent.parent / "test_a_worker_comes_back_with_its_page_from_the_cache_e2e.py").read_text("utf-8")
for word in ("ATTEMPTS", "REFUSALS", "_NotRestored", "pytest.skip", "pytest.xfail", "reruns", "flaky"):
assert word not in source, "%s: a refusal of the cache is a red with its evidence, never a repeat or a skip" % word
assert "extra_prefs=LAB_PREFS" in source
assert source.index("wait_cacheable(page)") < source.index("page.go_back("), "the page must be cacheable before the test leaves it"
assert source.index("decide_outcome(") < source.index("Page.workerCreated", source.index("decide_outcome(")), \
"the evidence is read and written before anything is asserted about the worker"
assert 'may_reload=(how == "goto")' in source, "a reload is accepted for a navigation the parent starts (goto) and for nothing else"
def test_the_commit_order_of_a_worker_is_asserted_only_on_an_engine_that_promises_it(monkeypatch):
import types
import invisible_core.seal as seal
import test_a_worker_comes_back_with_its_page_from_the_cache_e2e as e2e
for tag, promised in (("firefox-62", False), ("firefox-63-candidate", True), ("firefox-64", True), ("local", False)):
monkeypatch.setattr(seal, "active_seal", lambda tag=tag: types.SimpleNamespace(tag=tag))
assert e2e._commit_order_is_promised() is promised, tag