Compare commits

..
Author SHA1 Message Date
feder-cr 1968b61fab hunt: why a 1024x1024 WebGL readPixels costs 250 ms in ours: readback cost per content (flat to per-pixel ramp), 2D control, arm ours_noproj (read-time canvas projection off), the diagonal-edge scene against retail, and a symbolicated profile of the reading process 2026-11-15 01:36:16 +01:00
feder-cr ae10391340 hunt: does our forced multisample make readPixels slow, and does MSAA change the pixels a page reads (arm ours_nomsaa, readPixels with antialias true and false in the same browser, a scene with diagonal edges, the byte diff) 2026-11-15 01:05:45 +01:00
feder-cr bf4d2a10f9 hunt: what a page reads of the compositor (rAF, CSS and WebGL animation, smooth scroll, readback timings, matchMedia, timer resolution) in ours, ours_vmretail, stockheaded and retail 159 launched by hand, with Troubleshoot's monitors and the OS refresh rate 2026-11-15 00:47:44 +01:00
feder-cr 21c6c878d5 hunt: hunt_encoding.py lists the real PNG chunks and checks them against the specification; the 'deBG' chunk is Mozilla's, not a parser error
The parser was right and the table was misleading: "chunks differ (IHDR,deBG,IEND)" meant that the ancillary chunk deBG differs, with IDAT left out of the names. deBG is upstream Mozilla's nsPNGEncoder::MaybeAddCustomMetadata (the four letters are set one by one, so git grep deBG finds nothing): 16 hex characters keyed by the session's fingerprinting randomization key.

- parse_png reads length/type/data/CRC as ISO/IEC 15948, checks every CRC, IHDR first and 13 bytes, IDATs consecutive, IEND last and empty, no trailing bytes.
- compare_png compares chunk by chunk and says only the deBG chunk differs / deflate only / filter only / pixels; byte_report gives the offsets and the chunk and field each falls in; the table prints the deBG text of every launch.
- selftest: a known 1x1 PNG (IHDR crc 1f15c489, IEND crc ae426082), a deBG layout, deBG-only, deflate-only, bad CRC, no IDAT, truncated; run first in the workflow.
- client retail: Mozilla's 159.0 launched by hand, to answer whether retail writes deBG with a different value in every launch.
2026-11-15 00:26:52 +01:00
feder-cr 4c3fdeaba4 hunt: the first 80 s of a new profile, retail against ours (CPU slices, threads, files, network), and what a page reads of it (EME, MediaCapabilities, WebRTC codecs) in fresh and used profiles 2026-11-15 00:21:19 +01:00
feder-cr 4de5f69ec7 hunt: same seed same bytes (PNG stability, 2 runners, PyPI 0.52.0, stock), ours_vmretail (retail's VM decisions), GPU process profile with no thread filter
- encoding-stability-hunt.yml + scripts/hunt_encoding.py: the 11 PNG keys that were not stable between two launches. The probe's new encoding mode puts the pixels of the draw, three toDataURL and three toBlob of one canvas in one page and the pixels the browser decodes; the script reads the PNG chunks, inflates and unfilters the IDATs and prints per arm and key whether pixels or only the encoding differ, per runner, per page, across a 2-leg matrix (windows-2022, max-parallel 2), for ours, invisible-playwright 0.52.0 from PyPI, stock headed and headless.
- scripts/hunt_vmretail.py + cpu-render-path-hunt-vm.yml: arm ours_vmretail = the declared feature table with the compositing features replaced by stock's own decision on the runner, gfx.webrender.software=true, gfx.webrender.software.d3d11=false, webgl.angle.force-warp=true, all through extra_prefs. Table printed per feature; support reads the prefs and Troubleshoot (windowLayerManagerType/Remote) back; baseline gains stockheaded, ours_swwr, ours_vmretail and says where compositing runs (parent or GPU process); byte diff and suites as for ours_swwr.
- profile --gpu --filters '*': every thread of the GPU process; the summary gets --thread-table (one line per thread with its self weight by module, the unnamed threads together, the sampler's CPU of the pid for coverage).
- cpu-render-path-hunt.yml is dispatch only now: its scripts are shared with the two new workflows.
2026-11-15 00:10:22 +01:00
feder-cr 88958a778b hunt: parent baseline (retail by hand, ours, ours reused), ours_swwr arm and a page-bytes diff, readable GPU-process profile, command lines of the short-lived processes
- scripts/hunt_cpu_baseline.py: one browser, 20 s; arms retail (Mozilla's installer unpacked with 7-Zip, subprocess, -no-remote, fresh profile, no automation; falls back to Playwright's firefox and says so), ours, ours_reused (profile_dir twice, the second launch measured). CPU per process type and per thread name.
- ours_swwr (gfx.webrender.software=true through extra_prefs, from the hunt only) in hunt_cpu_per_browser.py and in `support`.
- scripts/hunt_page_bytes.py + hunt_page_bytes_probe.js: canvas 2D, WebGL 1/2, text and strings read in both arms and diffed; hunt_extra_prefs_plugin.py runs the wrapper's byte suites under both arms.
- profile --gpu: thread filter limited to the GPU process, small buffer, short loop, waits for the processes to exit and checks each file is valid JSON; summary gains a process-wide module table.
- print_processes lists the command line of every process without a -contentproc type and groups the other short-lived ones.
2026-11-14 23:26:12 +01:00
feder-cr f6329cd1d0 hunt: quote the job name of cpu-render-path-hunt.yml (an unquoted 'headed: about:support' is not valid YAML) 2026-11-14 22:46:32 +01:00
feder-cr 731e4d8540 hunt: why our Firefox uses ~6x the CPU of stock with a window (about:support and prefs diff, CPU by process type, Gecko profiles of parent and GPU process) 2026-11-14 22:40:12 +01:00
90 changed files with 9196 additions and 6651 deletions

No files matched your search

@@ -0,0 +1,206 @@
# ─────────────────────────────────────────────────────────────────────────────
# compositor-visible-hunt.yml - HUNT ONLY, never merged. Nothing of the product is changed. Starts on its own paths only (the hunts running on this branch are
# not restarted by it, and it is not restarted by them).
#
# Can a PAGE tell software compositing ("WebRender (Software)") from our hardware path? Earlier rAF data showed 60 fps in one arm and 50-53 in another: why?
# Four arms, one browser each, ~20 s each, windows-2022, two rounds (alternating, so a drift of the runner is seen): ours, ours_vmretail (the prefs of
# hunt_vmretail.py build: retail's VM decisions), stockheaded, and retail 159.0 launched by hand (Mozilla's installer, checked against SHA256SUMS; the page runs
# the probe and posts its result to the local server). In the page (scripts/hunt_compositor_probe.js): requestAnimationFrame alone (interval p5/p50/p95, fps,
# dropped frames), with a CSS animation, with a WebGL animation; a smooth scrollTo of a long page (scroll events per second, time to finish); canvas 2D getImageData
# on 1024x1024 after drawing and WebGL readPixels timings; matchMedia (update: fast), screen refresh hints, the resolution of performance.now().
# `facts` reads, per arm, what Troubleshoot exposes (graphics.monitors[].refreshRate, the layer manager, layout.frame_rate, gfx.vsync.*) and PowerShell's
# Win32_VideoController.CurrentRefreshRate. The table marks every difference between ours / ours_vmretail and retail as TIMING-ONLY or VALUE.
# The code that decides the rAF rate: gfx/thebes/gfxWindowsPlatform.cpp D3DVsyncSource (rate from DwmGetCompositionTimingInfo, loop on WaitForVBlank, software
# vsync when it returns in under 1 ms or fails) and gfx/thebes/gfxPlatform.cpp:3462-3516 (layout.frame_rate, 60 Hz default): see the docstring of
# scripts/hunt_compositor_visible.py.
# Every step is continue-on-error: a hunt must give whatever it got.
# ─────────────────────────────────────────────────────────────────────────────
name: compositor visible hunt
on:
push:
branches: [hunt/cpu-render-path]
paths:
- scripts/hunt_compositor_visible.py
- scripts/hunt_compositor_probe.js
- .github/workflows/compositor-visible-hunt.yml
workflow_dispatch:
permissions:
contents: read
concurrency:
group: compositor-visible-hunt-${{ github.ref }}
cancel-in-progress: true
env:
GITHUB_TOKEN: ${{ github.token }}
jobs:
hunt:
name: "hunt (windows-2022, what a page reads of the compositor: ours, ours_vmretail, stockheaded, retail)"
runs-on: windows-2022
timeout-minutes: 90
defaults:
run:
shell: bash
env:
PYTHONUNBUFFERED: "1"
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
with: { fetch-depth: 1 }
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
with: { python-version: '3.11' }
- name: Install the wrapper, psutil, and stock Playwright with its firefox
run: |
python -m pip install --upgrade pip
python -m pip install ".[dev]" psutil
python -m pip install "playwright==$(cat scripts/playwright_pin.txt)"
python -m playwright install firefox
- name: Fetch the published firefox binary
run: echo "FF=$(cd "$RUNNER_TEMP" && python -m invisible_playwright fetch | tail -1)" >> "$GITHUB_ENV"
- name: The GeoIP database (made by the repository, same bytes every run)
run: python scripts/ci_lab_geoip.py build
- name: Where the prefs of ours_vmretail are written
run: echo "HUNT_VMRETAIL_PREFS=$RUNNER_TEMP/cv/vmretail/prefs.json" >> "$GITHUB_ENV"
- name: "Retail Firefox 159.0 (Mozilla's installer, checked against SHA256SUMS, unpacked with 7-Zip)"
continue-on-error: true
run: python -u scripts/hunt_first_run.py fetch-retail --out "$RUNNER_TEMP/cv/retail"
- name: "Build ours_vmretail (the declared table of ours, the decisions of stock, the prefs)"
continue-on-error: true
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_vmretail.py build --binary "$FF" --out "$RUNNER_TEMP/cv/vmretail" | tee "$RUNNER_TEMP/cv/vmretail-build.txt"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
# ---------------------------------------------------------------------------------------- the facts (once per arm)
- name: "Facts, arm ours (Troubleshoot, effective prefs)"
if: always()
continue-on-error: true
timeout-minutes: 5
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_compositor_visible.py facts --arm ours --binary "$FF" --out "$RUNNER_TEMP/cv/r0"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "Facts, arm ours_vmretail (Troubleshoot, effective prefs)"
if: always()
continue-on-error: true
timeout-minutes: 5
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_compositor_visible.py facts --arm ours_vmretail --binary "$FF" --out "$RUNNER_TEMP/cv/r0"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "Facts, arm stockheaded (Troubleshoot, effective prefs)"
if: always()
continue-on-error: true
timeout-minutes: 5
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_compositor_visible.py facts --arm stockheaded --out "$RUNNER_TEMP/cv/r0"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "Facts, arm retail (Troubleshoot, effective prefs)"
if: always()
continue-on-error: true
timeout-minutes: 5
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_compositor_visible.py facts --arm retail --retail-from "$RUNNER_TEMP/cv/retail" --out "$RUNNER_TEMP/cv/r0"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
# ---------------------------------------------------------------------------------------- the measurement, two rounds
- name: "Round 1, arm ours (one browser, ~20 s in the page)"
if: always()
continue-on-error: true
timeout-minutes: 6
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_compositor_visible.py run --arm ours --binary "$FF" --out "$RUNNER_TEMP/cv/r1"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "Round 1, arm retail (one browser, ~20 s in the page)"
if: always()
continue-on-error: true
timeout-minutes: 6
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_compositor_visible.py run --arm retail --retail-from "$RUNNER_TEMP/cv/retail" --out "$RUNNER_TEMP/cv/r1"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "Round 1, arm ours_vmretail (one browser, ~20 s in the page)"
if: always()
continue-on-error: true
timeout-minutes: 6
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_compositor_visible.py run --arm ours_vmretail --binary "$FF" --out "$RUNNER_TEMP/cv/r1"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "Round 1, arm stockheaded (one browser, ~20 s in the page)"
if: always()
continue-on-error: true
timeout-minutes: 6
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_compositor_visible.py run --arm stockheaded --out "$RUNNER_TEMP/cv/r1"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "Round 1: table, what differs between ours / ours_vmretail and retail"
if: always()
continue-on-error: true
run: |
cp -r "$RUNNER_TEMP/cv/r0/"*-facts "$RUNNER_TEMP/cv/r1/" 2>/dev/null || true
python -u scripts/hunt_compositor_visible.py table "$RUNNER_TEMP/cv/r1" | tee "$RUNNER_TEMP/cv/r1/table.txt"
- name: "Round 2, arm stockheaded (one browser, ~20 s in the page)"
if: always()
continue-on-error: true
timeout-minutes: 6
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_compositor_visible.py run --arm stockheaded --out "$RUNNER_TEMP/cv/r2"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "Round 2, arm ours_vmretail (one browser, ~20 s in the page)"
if: always()
continue-on-error: true
timeout-minutes: 6
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_compositor_visible.py run --arm ours_vmretail --binary "$FF" --out "$RUNNER_TEMP/cv/r2"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "Round 2, arm retail (one browser, ~20 s in the page)"
if: always()
continue-on-error: true
timeout-minutes: 6
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_compositor_visible.py run --arm retail --retail-from "$RUNNER_TEMP/cv/retail" --out "$RUNNER_TEMP/cv/r2"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "Round 2, arm ours (one browser, ~20 s in the page)"
if: always()
continue-on-error: true
timeout-minutes: 6
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_compositor_visible.py run --arm ours --binary "$FF" --out "$RUNNER_TEMP/cv/r2"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "Round 2: table, what differs between ours / ours_vmretail and retail"
if: always()
continue-on-error: true
run: |
cp -r "$RUNNER_TEMP/cv/r0/"*-facts "$RUNNER_TEMP/cv/r2/" 2>/dev/null || true
python -u scripts/hunt_compositor_visible.py table "$RUNNER_TEMP/cv/r2" | tee "$RUNNER_TEMP/cv/r2/table.txt"
- name: Close every Firefox left
if: always()
shell: pwsh
run: |
Get-Process firefox -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue
"left: " + @(Get-Process firefox -ErrorAction SilentlyContinue).Count
- name: Upload the results
if: always()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: compositor-visible-hunt-${{ github.run_id }}-${{ github.run_attempt }}
path: |
${{ runner.temp }}/cv/r0
${{ runner.temp }}/cv/r1
${{ runner.temp }}/cv/r2
${{ runner.temp }}/cv/vmretail
${{ runner.temp }}/cv/vmretail-build.txt
if-no-files-found: warn
retention-days: 14
@@ -0,0 +1,312 @@
# ─────────────────────────────────────────────────────────────────────────────
# cpu-render-path-hunt-vm.yml - HUNT ONLY, never merged: second round of cpu-render-path-hunt.yml. Nothing of the product is changed: every pref goes
# through the hunt scripts (extra_prefs, the pytest plugin) and this workflow.
#
# What the first round found: on the Windows VM runner (adapter Microsoft Hyper-V Video) stock Firefox's GfxInfo blocks D3D11 compositing and WebRender
# with FEATURE_FAILURE_VM_VENDOR and falls back to WebRender (Software); ours declares OK for those features (the core's declaration, answered by
# the engine before any blocklist) and takes the hardware path: a GPU process, D3D11 compositing, and ~6x the CPU.
#
# This round, one windows-2022 job, in this order:
# 0. scripts/hunt_vmretail.py build: the arm `ours_vmretail` = ours made to take retail's VM decisions. It reads ours's DECLARED table
# (zoom.stealth.gfx.feature_status) and stock's own decision for every feature (nsIGfxInfo.getFeatureStatusStr), prints both side by side for
# every feature, and writes the extra_prefs: the declared table with only the compositing features replaced by stock's decision, plus
# gfx.webrender.software=true, gfx.webrender.software.d3d11=false (WebRender (Software), not Software D3D11) and webgl.angle.force-warp=true (WebGL on
# ANGLE with an explicit WARP device). The WebGL, media and every other feature keep what the persona declares: renderer, vendor and extensions stay
# as declared. The list is printed there, and read back from the effective prefs and Troubleshoot by the next steps.
# 1. `support` for ours, stockheaded and ours_vmretail: effective prefs, feature decisions, Troubleshoot's windowLayerManagerType and
# windowLayerManagerRemote, WebRender/D3D11/WARP lines. Did the prefs take effect?
# 2. scripts/hunt_cpu_baseline.py: one browser, 20 s, arms stockheaded, ours, ours_swwr, ours_vmretail: CPU per process type and per thread name, and
# WHERE COMPOSITING RUNS (the Compositor, Renderer, RenderBackend, WRWorker ... threads: in the parent or in the GPU process).
# 3. scripts/hunt_page_bytes.py: every page-readable value (canvas 2D, WebGL 1/2, text, strings; 2 launches per arm), ours against ours_vmretail.
# 4. The CPU per process type of the 4-browser, 10-scene loop (hunt_cpu_per_browser.py): ours, stockheaded, ours_vmretail, 2 rounds, alternating.
# 5. A profile of OUR GPU process with NO thread filter (MOZ_PROFILER_STARTUP_FILTERS=*), small buffer, 3 rounds: every thread of the GPU process with
# its self weight by module, and the weight of the unnamed threads by module (are they d3d10warp.dll?).
# 6. The wrapper's own byte suites (canvas_*, webgl_*, ...) under ours and under ours_vmretail (scripts/hunt_extra_prefs_plugin.py), outcome per test.
# Every step is continue-on-error: a hunt must give whatever it got.
# ─────────────────────────────────────────────────────────────────────────────
name: cpu render path hunt vm
on:
push:
branches: [hunt/cpu-render-path]
paths:
- scripts/hunt_vmretail.py
- scripts/hunt_cpu_render_path.py
- scripts/hunt_cpu_per_browser.py
- scripts/hunt_cpu_baseline.py
- scripts/hunt_page_bytes.py
- scripts/hunt_page_bytes_probe.js
- scripts/hunt_extra_prefs_plugin.py
- scripts/hunt_profile_summary.py
- scripts/hunt_fetch_symbols.py
- .github/workflows/cpu-render-path-hunt-vm.yml
workflow_dispatch:
inputs:
symbols_run:
description: "Run id of the engine's release.yml whose symbols-win-x86_64 artifact matches the binary (empty: look through the recent runs)"
required: false
default: ""
permissions:
contents: read
concurrency:
group: cpu-render-path-hunt-vm-${{ github.ref }}
cancel-in-progress: true
env:
GITHUB_TOKEN: ${{ github.token }}
jobs:
hunt:
name: "hunt (windows-2022, ours_vmretail - retail's VM decisions, where compositing runs, page bytes, GPU process profile)"
runs-on: windows-2022
timeout-minutes: 200
defaults:
run:
shell: bash
env:
PYTHONUNBUFFERED: "1"
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
with: { fetch-depth: 1 }
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
with: { python-version: '3.11' }
- name: Install the wrapper, psutil, and stock Playwright with its firefox
run: |
python -m pip install --upgrade pip
python -m pip install ".[dev]" psutil
python -m pip install "playwright==$(cat scripts/playwright_pin.txt)"
python -m playwright install firefox
- name: Fetch the published firefox binary
run: echo "FF=$(cd "$RUNNER_TEMP" && python -m invisible_playwright fetch | tail -1)" >> "$GITHUB_ENV"
- name: The GeoIP database (made by the repository, same bytes every run)
run: python scripts/ci_lab_geoip.py build
- name: Where the prefs of ours_vmretail are written
run: echo "HUNT_VMRETAIL_PREFS=$RUNNER_TEMP/vm/vmretail/prefs.json" >> "$GITHUB_ENV"
# ------------------------------------------------------------------------------------------------ 0. the arm ours_vmretail
- name: "0. Build ours_vmretail (the declared table of ours, the decisions of stock, the prefs)"
continue-on-error: true
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_vmretail.py build --binary "$FF" --out "$RUNNER_TEMP/vm/vmretail" | tee "$RUNNER_TEMP/vm/vmretail-build.txt"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
# ------------------------------------------------------------------------------------------------ 1. did the prefs take effect, where does it composite
- name: "1. Compositing facts, arm ours"
if: always()
continue-on-error: true
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_cpu_render_path.py support --arm ours --binary "$FF" --out "$RUNNER_TEMP/vm/support"
- name: "1. Compositing facts, arm stockheaded"
if: always()
continue-on-error: true
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_cpu_render_path.py support --arm stockheaded --out "$RUNNER_TEMP/vm/support"
- name: "1. Compositing facts, arm ours_vmretail (the prefs read back)"
if: always()
continue-on-error: true
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_cpu_render_path.py support --arm ours_vmretail --binary "$FF" --out "$RUNNER_TEMP/vm/support"
- name: "1. Graphics diff, ours_vmretail against stockheaded (is it the same compositing as stock now?)"
if: always()
continue-on-error: true
run: |
mkdir -p "$RUNNER_TEMP/vm/support-vm"
rm -rf "$RUNNER_TEMP/vm/support-vm/ours" "$RUNNER_TEMP/vm/support-vm/stockheaded"
cp -r "$RUNNER_TEMP/vm/support/ours_vmretail" "$RUNNER_TEMP/vm/support-vm/ours"
cp -r "$RUNNER_TEMP/vm/support/stockheaded" "$RUNNER_TEMP/vm/support-vm/stockheaded"
python -u scripts/hunt_cpu_render_path.py diff "$RUNNER_TEMP/vm/support-vm" | tee "$RUNNER_TEMP/vm/support-vm/diff.txt"
# ------------------------------------------------------------------------------------------------ 2. one browser, 20 s: CPU by process and thread
- name: "2. Baseline, arm stockheaded"
if: always()
continue-on-error: true
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_cpu_baseline.py --arm stockheaded --out "$RUNNER_TEMP/vm/baseline"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "2. Baseline, arm ours"
if: always()
continue-on-error: true
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_cpu_baseline.py --arm ours --binary "$FF" --out "$RUNNER_TEMP/vm/baseline"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "2. Baseline, arm ours_vmretail"
if: always()
continue-on-error: true
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_cpu_baseline.py --arm ours_vmretail --binary "$FF" --out "$RUNNER_TEMP/vm/baseline"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "2. Baseline, arm ours_swwr"
if: always()
continue-on-error: true
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_cpu_baseline.py --arm ours_swwr --binary "$FF" --out "$RUNNER_TEMP/vm/baseline"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "2. Baseline comparison and where compositing runs"
if: always()
continue-on-error: true
run: python scripts/hunt_cpu_baseline.py --compare "$RUNNER_TEMP/vm/baseline" | tee "$RUNNER_TEMP/vm/baseline/compare.txt"
# ------------------------------------------------------------------------------------------------ 3. page-readable bytes
- name: "3. Page-readable bytes, arm ours (2 launches)"
if: always()
continue-on-error: true
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_page_bytes.py collect --arm ours --binary "$FF" --launches 2 --out "$RUNNER_TEMP/vm/pagebytes"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "3. Page-readable bytes, arm ours_vmretail (2 launches)"
if: always()
continue-on-error: true
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_page_bytes.py collect --arm ours_vmretail --binary "$FF" --launches 2 --out "$RUNNER_TEMP/vm/pagebytes"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "3. Page-readable bytes, ours against ours_vmretail"
if: always()
continue-on-error: true
run: python -u scripts/hunt_page_bytes.py diff "$RUNNER_TEMP/vm/pagebytes" --a ours --b ours_vmretail | tee "$RUNNER_TEMP/vm/pagebytes/diff.txt"
# ------------------------------------------------------------------------------------------------ 4. CPU of the 4-browser loop
- name: "4. CPU by process type, ours, round 1"
if: always()
continue-on-error: true
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_cpu_per_browser.py --arm ours --binary "$FF" --round 1 --out "$RUNNER_TEMP/vm/cpu/ours-1.json"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "4. CPU by process type, stockheaded, round 1"
if: always()
continue-on-error: true
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_cpu_per_browser.py --arm stockheaded --round 1 --out "$RUNNER_TEMP/vm/cpu/stockheaded-1.json"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "4. CPU by process type, ours_vmretail, round 1"
if: always()
continue-on-error: true
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_cpu_per_browser.py --arm ours_vmretail --binary "$FF" --round 1 --out "$RUNNER_TEMP/vm/cpu/ours_vmretail-1.json"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "4. CPU by process type, ours, round 2"
if: always()
continue-on-error: true
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_cpu_per_browser.py --arm ours --binary "$FF" --round 2 --out "$RUNNER_TEMP/vm/cpu/ours-2.json"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "4. CPU by process type, stockheaded, round 2"
if: always()
continue-on-error: true
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_cpu_per_browser.py --arm stockheaded --round 2 --out "$RUNNER_TEMP/vm/cpu/stockheaded-2.json"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "4. CPU by process type, ours_vmretail, round 2"
if: always()
continue-on-error: true
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_cpu_per_browser.py --arm ours_vmretail --binary "$FF" --round 2 --out "$RUNNER_TEMP/vm/cpu/ours_vmretail-2.json"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "4. Comparison table"
if: always()
continue-on-error: true
run: python scripts/hunt_cpu_per_browser.py --compare "$RUNNER_TEMP/vm/cpu" | tee "$RUNNER_TEMP/vm/cpu/compare.txt"
# ------------------------------------------------------------------------------------------------ 5. our GPU process, every thread
- name: "5. Gecko profile of our GPU process, NO thread filter (MOZ_PROFILER_STARTUP_FILTERS=*), small buffer, 3 rounds"
if: always()
continue-on-error: true
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_cpu_render_path.py profile --arm ours --binary "$FF" --gpu --filters '*' --out "$RUNNER_TEMP/vm/profiles-gpu-all"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "5. Symbols of our engine (artifact symbols-win-x86_64 of the engine's release.yml)"
if: always()
continue-on-error: true
env:
GH_TOKEN: ${{ github.token }}
run: |
P="$RUNNER_TEMP/vm/profiles-gpu-all"
ID="$(python scripts/hunt_profile_summary.py "$P/ours" --ids | awk '$3=="xul.dll"{print $2}' | head -1)"
echo "breakpad id of our xul.dll in the profile: '$ID'"
if [ -z "$ID" ]; then echo "SYMBOLS: none (no id: no parent profile of ours)"; exit 0; fi
python scripts/hunt_fetch_symbols.py --id "$ID" --run "${{ inputs.symbols_run }}" --out "$RUNNER_TEMP/vm/symbols" | tee "$RUNNER_TEMP/vm/symbols.log"
- name: "5. Summary of the GPU process: every thread, its self weight by module, the unnamed threads, the top functions"
if: always()
continue-on-error: true
run: |
P="$RUNNER_TEMP/vm/profiles-gpu-all/ours"
SYM=$(ls "$RUNNER_TEMP"/vm/symbols/symbols-*.zip 2>/dev/null | head -1 || true)
python -u scripts/hunt_profile_summary.py "$P" ${SYM:+--symbols "$SYM"} --only gpu --detail 2 --thread-table --threads 8 --top 20 | tee "$P/summary-gpu-all.txt"
# ------------------------------------------------------------------------------------------------ 6. the wrapper's byte suites
- name: "6. The wrapper's byte suites, arm ours"
if: always()
continue-on-error: true
timeout-minutes: 35
env:
PYTHONPATH: ${{ github.workspace }}/scripts
INVPW_BINARY_PATH: ${{ env.FF }}
INVPW_TEST_WATCHDOG_FILE: ${{ runner.temp }}/e2e-watchdog-suites.log
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
D="$RUNNER_TEMP/vm/suites"; mkdir -p "$D"
FILES=$(ls tests/test_canvas_*.py tests/test_webgl_*.py tests/test_a_declared_webgl_extension_survives_its_use_e2e.py \
tests/test_fingerprint_surface.py tests/test_fingerprint_consistency.py tests/test_system_fonts_and_colors_are_windows_e2e.py \
tests/test_css_calc_is_windows_e2e.py tests/test_screenshot_of_text_returns_linux_e2e.py | sort -u)
echo "$FILES" > "$D/files.txt"; echo "$FILES" | wc -l
python -u -m pytest $FILES -o addopts= -p no:cacheprovider -p hunt_extra_prefs_plugin -q -rs --junitxml="$D/ours.xml" 2>&1 | tee "$D/ours.log" | tail -60
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "6. The wrapper's byte suites, arm ours_vmretail (HUNT_EXTRA_PREFS = the prefs of hunt_vmretail.py build)"
if: always()
continue-on-error: true
timeout-minutes: 35
env:
PYTHONPATH: ${{ github.workspace }}/scripts
INVPW_BINARY_PATH: ${{ env.FF }}
INVPW_TEST_WATCHDOG_FILE: ${{ runner.temp }}/e2e-watchdog-suites.log
HUNT_EXTRA_PREFS_LOG: ${{ runner.temp }}/vm/suites/ours_vmretail-prefs.log
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
D="$RUNNER_TEMP/vm/suites"; mkdir -p "$D"
export HUNT_EXTRA_PREFS="$(python scripts/hunt_vmretail.py prefs-json "$HUNT_VMRETAIL_PREFS")"
echo "HUNT_EXTRA_PREFS has $(echo -n "$HUNT_EXTRA_PREFS" | wc -c) characters"
FILES=$(cat "$D/files.txt" 2>/dev/null || true)
[ -n "$FILES" ] || FILES=$(ls tests/test_canvas_*.py tests/test_webgl_*.py)
python -u -m pytest $FILES -o addopts= -p no:cacheprovider -p hunt_extra_prefs_plugin -q -rs --junitxml="$D/ours_vmretail.xml" 2>&1 | tee "$D/ours_vmretail.log" | tail -60
echo "browsers constructed with the prefs: $(wc -l < "$D/ours_vmretail-prefs.log" 2>/dev/null || echo 0)"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "6. The wrapper's byte suites, outcome per test in both arms"
if: always()
continue-on-error: true
run: |
D="$RUNNER_TEMP/vm/suites"
python scripts/hunt_page_bytes.py suites "$D/ours.xml" "$D/ours_vmretail.xml" --b-name ours_vmretail | tee "$D/suites-diff.txt"
- name: Close every Firefox left
if: always()
shell: pwsh
run: |
Get-Process firefox -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue
"left: " + @(Get-Process firefox -ErrorAction SilentlyContinue).Count
- name: Upload the results
if: always()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: cpu-render-path-hunt-vm-${{ github.run_id }}-${{ github.run_attempt }}
path: |
${{ runner.temp }}/vm
if-no-files-found: warn
retention-days: 14
+330
View File
@@ -0,0 +1,330 @@
# ─────────────────────────────────────────────────────────────────────────────
# cpu-render-path-hunt.yml - HUNT ONLY, never merged: why does our Firefox use ~6x the CPU of stock Firefox 159 with a window, on Windows?
# (measured per browser: parent 8.8 s against 1.7, GPU process 4.9 against 0.03, tab 0.84 against 0.58.) Nothing of the product is changed.
#
# Two arms, as in cpu-per-browser-hunt: `ours` = invisible_playwright, headless=True (on Windows: headed Firefox on a hidden desktop) and
# `stockheaded` = stock Playwright, firefox.launch(headless=False). One job, windows-2022, in this order:
# 1. scripts/hunt_cpu_render_path.py support, then diff: the full about:support text of each browser (page.goto("about:support") through
# the wire; if that is refused, Troubleshoot.snapshot() through Marionette in chrome scope, and the job says which route worked), the
# effective prefs, the profile's prefs.js and user.js, the parent's environment, and the diff of the Graphics section (compositing,
# WebRender hardware/software, D3D11/WARP, GPU process, the feature decisions and their reasons, the differing gfx.* / layers.* prefs).
# 3. the CPU by process type of hunt_cpu_per_browser.py, ours and stockheaded, 2 rounds each, alternating (the sanity check).
# 2. scripts/hunt_cpu_render_path.py profile: the same 4-browser, 10-scene loop with the Gecko profiler on from startup in every process
# (MOZ_PROFILER_STARTUP, STARTUP_FEATURES, MOZ_PROFILER_SHUTDOWN=<dir>/profile-%p.json: one file per process). It runs AFTER the CPU
# rounds because the profiler slows the browsers. scripts/hunt_profile_summary.py prints, for the busiest parent and GPU process of each
# arm, the CPU by thread, by module and by function. Symbols: for ours, the Breakpad symbols of the artifact symbols-win-x86_64 of a
# recent release.yml run of the engine's repository, if one still exists and its xul.pdb id matches the binary (scripts/
# hunt_fetch_symbols.py; a candidate's are kept 2 days, a release's 14); for every module the zips do not have, Mozilla's symbol server.
# Where a module cannot be symbolicated the summary says so and prints module+offset; the raw profiles are always in the artifact.
# 4. (second round of the hunt) the baseline of the parent: scripts/hunt_cpu_baseline.py, ONE browser for 20 s, three arms: `retail` (Mozilla's own
# Firefox installer of the stable release, unpacked with 7-Zip and launched by hand with subprocess, -no-remote, a fresh profile, the scene
# URL, no automation, no Playwright; if it cannot be had the step falls back to Playwright's firefox-1572 and says so), `ours`, and
# `ours_reused` (ours twice on the same persistent profile, profile_dir=). CPU per process type (the sampler) and per thread name (psutil
# threads + GetThreadDescription) in the whole window and in its last 10 s; the command line of every short-lived process.
# 5. `ours_swwr` = ours with gfx.webrender.software=true, passed ONLY by the hunt through extra_prefs: its compositing facts (support), its CPU
# per process type next to ours and stockheaded (step 3 gains two rounds of it), and whether ANY byte a page reads differs from ours:
# scripts/hunt_page_bytes.py (canvas 2D, WebGL 1/2, text, strings, in both arms, launched twice each, diffed) and the wrapper's own byte
# suites (canvas_*, webgl_*, canvas text, fingerprint_*, system fonts, css calc) under both arms through scripts/hunt_extra_prefs_plugin.py.
# 6. A readable profile of OUR GPU process only (profile --gpu): the profiler's thread filter limited to the GPU process's threads, a small buffer,
# 3 rounds, and the run waits for every process to exit before reading the files (the first GPU profile came back truncated).
# Every step is continue-on-error: a hunt must give whatever it got.
# ─────────────────────────────────────────────────────────────────────────────
name: cpu render path hunt
# Dispatch only since the second round: its scripts are shared with cpu-render-path-hunt-vm.yml and encoding-stability-hunt.yml, which start on push
# to this branch, and a 2 h Windows run must not start again on every push that touches a shared script.
on:
workflow_dispatch:
inputs:
symbols_run:
description: "Run id of the engine's release.yml whose symbols-win-x86_64 artifact matches the binary (empty: look through the recent runs)"
required: false
default: ""
permissions:
contents: read
concurrency:
group: cpu-render-path-hunt-${{ github.ref }}
cancel-in-progress: true
# Engine and GeoIP downloads go through the release API with this token (as in e2e.yml).
env:
GITHUB_TOKEN: ${{ github.token }}
jobs:
hunt:
name: "hunt (windows-2022, ours vs stock headed vs retail - about:support, CPU by process type, baseline, software WebRender, Gecko profiles)"
runs-on: windows-2022
timeout-minutes: 170
defaults:
run:
shell: bash
env:
PYTHONUNBUFFERED: "1"
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
with: { fetch-depth: 1 }
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
with: { python-version: '3.11' }
- name: Install the wrapper, psutil, and stock Playwright with its firefox
run: |
python -m pip install --upgrade pip
python -m pip install ".[dev]" psutil
python -m pip install "playwright==$(cat scripts/playwright_pin.txt)"
python -m playwright install firefox
- name: Fetch the published firefox binary
run: echo "FF=$(cd "$RUNNER_TEMP" && python -m invisible_playwright fetch | tail -1)" >> "$GITHUB_ENV"
- name: The GeoIP database (made by the repository, same bytes every run)
run: python scripts/ci_lab_geoip.py build
# ------------------------------------------------------------------------------------------------- 1. about:support
- name: "1. about:support, prefs and environment, arm ours"
continue-on-error: true
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_cpu_render_path.py support --arm ours --binary "$FF" --out "$RUNNER_TEMP/render-hunt/support"
- name: "1. about:support, prefs and environment, arm stockheaded"
continue-on-error: true
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_cpu_render_path.py support --arm stockheaded --out "$RUNNER_TEMP/render-hunt/support"
- name: "1. Graphics diff, ours against stockheaded"
if: always()
continue-on-error: true
run: python -u scripts/hunt_cpu_render_path.py diff "$RUNNER_TEMP/render-hunt/support" | tee "$RUNNER_TEMP/render-hunt/support/diff.txt"
- name: "5. Compositing facts of ours_swwr (does gfx.webrender.software=true from the hunt really take effect?)"
if: always()
continue-on-error: true
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_cpu_render_path.py support --arm ours_swwr --binary "$FF" --out "$RUNNER_TEMP/render-hunt/support"
# --------------------------------------------------------------------------------- 4. the baseline of the parent (one browser, 20 s)
- name: "4. Baseline, arm retail (Mozilla's Firefox, launched by hand, no automation)"
if: always()
continue-on-error: true
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_cpu_baseline.py --arm retail --out "$RUNNER_TEMP/render-hunt/baseline"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "4. Baseline, arm ours (fresh temporary profile)"
if: always()
continue-on-error: true
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_cpu_baseline.py --arm ours --binary "$FF" --out "$RUNNER_TEMP/render-hunt/baseline"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "4. Baseline, arm ours_reused (the same persistent profile twice; the second launch is measured)"
if: always()
continue-on-error: true
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_cpu_baseline.py --arm ours_reused --binary "$FF" --out "$RUNNER_TEMP/render-hunt/baseline"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "4. Baseline comparison table"
if: always()
continue-on-error: true
run: python scripts/hunt_cpu_baseline.py --compare "$RUNNER_TEMP/render-hunt/baseline" | tee "$RUNNER_TEMP/render-hunt/baseline/compare.txt"
# ------------------------------------------------------------------------------------- 3. CPU by process type (sanity)
- name: "3. CPU by process type, ours, round 1"
if: always()
continue-on-error: true
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_cpu_per_browser.py --arm ours --binary "$FF" --round 1 --out "$RUNNER_TEMP/render-hunt/cpu/ours-1.json"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "3. CPU by process type, stockheaded, round 1"
if: always()
continue-on-error: true
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_cpu_per_browser.py --arm stockheaded --round 1 --out "$RUNNER_TEMP/render-hunt/cpu/stockheaded-1.json"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "3. CPU by process type, ours_swwr, round 1"
if: always()
continue-on-error: true
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_cpu_per_browser.py --arm ours_swwr --binary "$FF" --round 1 --out "$RUNNER_TEMP/render-hunt/cpu/ours_swwr-1.json"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "3. CPU by process type, ours, round 2"
if: always()
continue-on-error: true
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_cpu_per_browser.py --arm ours --binary "$FF" --round 2 --out "$RUNNER_TEMP/render-hunt/cpu/ours-2.json"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "3. CPU by process type, stockheaded, round 2"
if: always()
continue-on-error: true
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_cpu_per_browser.py --arm stockheaded --round 2 --out "$RUNNER_TEMP/render-hunt/cpu/stockheaded-2.json"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "3. CPU by process type, ours_swwr, round 2"
if: always()
continue-on-error: true
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_cpu_per_browser.py --arm ours_swwr --binary "$FF" --round 2 --out "$RUNNER_TEMP/render-hunt/cpu/ours_swwr-2.json"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "3. Comparison table"
if: always()
continue-on-error: true
run: python scripts/hunt_cpu_per_browser.py --compare "$RUNNER_TEMP/render-hunt/cpu" | tee "$RUNNER_TEMP/render-hunt/cpu/compare.txt"
# ------------------------------------------------------------------------- 5. does any byte a page reads change with software WebRender?
- name: "5. Page-readable bytes, arm ours (canvas 2D, WebGL 1/2, text, strings; 2 launches)"
if: always()
continue-on-error: true
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_page_bytes.py collect --arm ours --binary "$FF" --launches 2 --out "$RUNNER_TEMP/render-hunt/pagebytes"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "5. Page-readable bytes, arm ours_swwr (2 launches)"
if: always()
continue-on-error: true
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_page_bytes.py collect --arm ours_swwr --binary "$FF" --launches 2 --out "$RUNNER_TEMP/render-hunt/pagebytes"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "5. Page-readable bytes, ours against ours_swwr"
if: always()
continue-on-error: true
run: python -u scripts/hunt_page_bytes.py diff "$RUNNER_TEMP/render-hunt/pagebytes" | tee "$RUNNER_TEMP/render-hunt/pagebytes/diff.txt"
# -------------------------------------------------------------------------------------------- 2. the Gecko profiles
- name: "2. Gecko profiles of the 10-scene loop, arm ours"
if: always()
continue-on-error: true
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_cpu_render_path.py profile --arm ours --binary "$FF" --out "$RUNNER_TEMP/render-hunt/profiles"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "2. Gecko profiles of the 10-scene loop, arm stockheaded"
if: always()
continue-on-error: true
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_cpu_render_path.py profile --arm stockheaded --out "$RUNNER_TEMP/render-hunt/profiles"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "2. Symbols of our engine (artifact symbols-win-x86_64 of the engine's release.yml)"
if: always()
continue-on-error: true
env:
GH_TOKEN: ${{ github.token }}
run: |
P="$RUNNER_TEMP/render-hunt/profiles"
ID="$(python scripts/hunt_profile_summary.py "$P/ours" --ids | awk '$3=="xul.dll"{print $2}' | head -1)"
echo "breakpad id of our xul.dll in the profile: '$ID'"
if [ -z "$ID" ]; then echo "SYMBOLS: none (no id: no parent profile of ours)"; exit 0; fi
python scripts/hunt_fetch_symbols.py --id "$ID" --run "${{ inputs.symbols_run }}" --out "$RUNNER_TEMP/render-hunt/symbols" | tee "$RUNNER_TEMP/render-hunt/symbols.log"
- name: "2. Profile summary, ours"
if: always()
continue-on-error: true
run: |
P="$RUNNER_TEMP/render-hunt/profiles"
SYM=$(ls "$RUNNER_TEMP"/render-hunt/symbols/symbols-*.zip 2>/dev/null | head -1 || true)
python -u scripts/hunt_profile_summary.py "$P/ours" ${SYM:+--symbols "$SYM"} | tee "$P/summary-ours.txt"
- name: "2. Profile summary, stockheaded"
if: always()
continue-on-error: true
run: |
P="$RUNNER_TEMP/render-hunt/profiles"
python -u scripts/hunt_profile_summary.py "$P/stockheaded" | tee "$P/summary-stockheaded.txt"
# ----------------------------------------------------------------------------------------- 6. a readable profile of OUR GPU process
- name: "6. Gecko profile of our GPU process only (filtered threads, small buffer, 3 rounds)"
if: always()
continue-on-error: true
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_cpu_render_path.py profile --arm ours --binary "$FF" --gpu --out "$RUNNER_TEMP/render-hunt/profiles-gpu"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "6. Summary of the GPU process: self time by module and the top functions"
if: always()
continue-on-error: true
env:
GH_TOKEN: ${{ github.token }}
run: |
P="$RUNNER_TEMP/render-hunt/profiles-gpu/ours"
SYM=$(ls "$RUNNER_TEMP"/render-hunt/symbols/symbols-*.zip 2>/dev/null | head -1 || true)
if [ -z "$SYM" ]; then
ID="$(python scripts/hunt_profile_summary.py "$P" --ids | awk '$3=="xul.dll"{print $2}' | head -1)"
echo "no symbols from step 2; breakpad id of our xul.dll in the GPU run: '$ID'"
if [ -n "$ID" ]; then python scripts/hunt_fetch_symbols.py --id "$ID" --run "${{ inputs.symbols_run }}" --out "$RUNNER_TEMP/render-hunt/symbols" | tee "$RUNNER_TEMP/render-hunt/symbols-gpu.log"; fi
SYM=$(ls "$RUNNER_TEMP"/render-hunt/symbols/symbols-*.zip 2>/dev/null | head -1 || true)
fi
python -u scripts/hunt_profile_summary.py "$P" ${SYM:+--symbols "$SYM"} --only gpu --detail 2 --threads 6 --top 20 | tee "$P/summary-gpu.txt"
# ----------------------------------------------------- 5b. the wrapper's own byte suites under both arms (the pref goes in through a plugin)
- name: "5. The wrapper's byte suites, arm ours"
if: always()
continue-on-error: true
timeout-minutes: 30
env:
PYTHONUNBUFFERED: "1"
PYTHONPATH: ${{ github.workspace }}/scripts
INVPW_BINARY_PATH: ${{ env.FF }}
INVPW_TEST_WATCHDOG_FILE: ${{ runner.temp }}/e2e-watchdog-suites.log
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
D="$RUNNER_TEMP/render-hunt/suites"; mkdir -p "$D"
FILES=$(ls tests/test_canvas_*.py tests/test_webgl_*.py tests/test_a_declared_webgl_extension_survives_its_use_e2e.py \
tests/test_fingerprint_surface.py tests/test_fingerprint_consistency.py tests/test_system_fonts_and_colors_are_windows_e2e.py \
tests/test_css_calc_is_windows_e2e.py tests/test_screenshot_of_text_returns_linux_e2e.py | sort -u)
echo "$FILES" > "$D/files.txt"; echo "$FILES" | wc -l
python -u -m pytest $FILES -o addopts= -p no:cacheprovider -p hunt_extra_prefs_plugin -q -rs --junitxml="$D/ours.xml" 2>&1 | tee "$D/ours.log" | tail -60
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "5. The wrapper's byte suites, arm ours_swwr (HUNT_EXTRA_PREFS gfx.webrender.software=true)"
if: always()
continue-on-error: true
timeout-minutes: 30
env:
PYTHONUNBUFFERED: "1"
PYTHONPATH: ${{ github.workspace }}/scripts
INVPW_BINARY_PATH: ${{ env.FF }}
INVPW_TEST_WATCHDOG_FILE: ${{ runner.temp }}/e2e-watchdog-suites.log
HUNT_EXTRA_PREFS: '{"gfx.webrender.software": true}'
HUNT_EXTRA_PREFS_LOG: ${{ runner.temp }}/render-hunt/suites/ours_swwr-prefs.log
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
D="$RUNNER_TEMP/render-hunt/suites"; mkdir -p "$D"
FILES=$(cat "$D/files.txt" 2>/dev/null || true)
[ -n "$FILES" ] || FILES=$(ls tests/test_canvas_*.py tests/test_webgl_*.py)
python -u -m pytest $FILES -o addopts= -p no:cacheprovider -p hunt_extra_prefs_plugin -q -rs --junitxml="$D/ours_swwr.xml" 2>&1 | tee "$D/ours_swwr.log" | tail -60
echo "browsers constructed with the pref: $(wc -l < "$D/ours_swwr-prefs.log" 2>/dev/null || echo 0)"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "5. The wrapper's byte suites, outcome per test in both arms"
if: always()
continue-on-error: true
run: |
D="$RUNNER_TEMP/render-hunt/suites"
python scripts/hunt_page_bytes.py suites "$D/ours.xml" "$D/ours_swwr.xml" | tee "$D/suites-diff.txt"
- name: Close every Firefox left
if: always()
shell: pwsh
run: |
Get-Process firefox -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue
"left: " + @(Get-Process firefox -ErrorAction SilentlyContinue).Count
- name: Upload the results (about:support, prefs, CPU numbers, summaries, raw gzipped profiles)
if: always()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: cpu-render-path-hunt-${{ github.run_id }}-${{ github.run_attempt }}
path: |
${{ runner.temp }}/render-hunt/support
${{ runner.temp }}/render-hunt/cpu
${{ runner.temp }}/render-hunt/profiles
${{ runner.temp }}/render-hunt/profiles-gpu
${{ runner.temp }}/render-hunt/baseline
${{ runner.temp }}/render-hunt/pagebytes
${{ runner.temp }}/render-hunt/suites
${{ runner.temp }}/render-hunt/symbols.log
if-no-files-found: warn
retention-days: 14
@@ -0,0 +1,177 @@
# ─────────────────────────────────────────────────────────────────────────────
# encoding-stability-hunt.yml - HUNT ONLY, never merged: "same seed, same bytes" for the PNG of the canvas. Nothing of the product is changed.
#
# In scripts/hunt_page_bytes.py (seed 42, two launches of the same arm) 11 keys were not stable: the PNG (toDataURL, toBlob, convertToBlob) of the 2D
# scenes shapes, composite, image and text, of the OffscreenCanvas and of the WebGL 1 and 2 triangle. Their pixels (getImageData, readPixels), JPEG and
# WebP were stable. Questions, per key:
# - do the PIXELS differ, or only the encoding? (the probe's ENCODING MODE puts the pixels of the draw, the raw bytes of three toDataURL and three toBlob
# in one page, and the pixels the browser decodes from the first PNG; scripts/hunt_encoding.py reads the PNG chunks, inflates and unfilters the IDATs)
# - is the difference between two launches on one runner, and also between two runners? (a 2-leg matrix, windows-2022, max-parallel 2; the job
# `compare` reads both legs)
# - does it happen with the published invisible-playwright 0.52.0 (its own venv, its own binary), and with stock Playwright's firefox (headed and
# headless)?
# - is the probe at fault? (anything time-, random- or order-dependent in what it draws: three calls on the same canvas in the same page say so)
# The arms: ours (this checkout's wrapper with the published binary of the job), ours_pypi052, stockheaded, stockheadless and, from the second run,
# `retail` (Mozilla's Firefox 159.0 installer, checked against its SHA256SUMS, launched by hand: subprocess, -no-remote, a fresh profile, no automation);
# two launches each.
#
# FINDING OF THE FIRST RUN (43652292507), read again with a parser that checks the PNG against the specification: the pixels, the filter and the deflate
# stream of every PNG are identical between two launches, between two runners, in every arm. The ONE difference is a 16-byte ancillary chunk `deBG` after the
# IDATs (16 hex characters, plus its CRC): upstream Mozilla's nsPNGEncoder::MaybeAddCustomMetadata (image/encoders/png/nsPNGEncoder.cpp, the four letters
# are set one by one, which is why `git grep deBG` finds nothing), keyed by the session's fingerprinting randomization key. The core turns
# privacy.baselineFingerprintingProtection on to match retail 151 (invisible_core/prefs.py). What this run adds: does retail 159 write it, and with a
# different value in every launch?
# ─────────────────────────────────────────────────────────────────────────────
name: encoding stability hunt
on:
push:
branches: [hunt/cpu-render-path]
paths:
- scripts/hunt_encoding.py
- scripts/hunt_page_bytes_probe.js
- .github/workflows/encoding-stability-hunt.yml
workflow_dispatch:
permissions:
contents: read
actions: read
concurrency:
group: encoding-stability-hunt-${{ github.ref }}
cancel-in-progress: true
env:
GITHUB_TOKEN: ${{ github.token }}
jobs:
hunt:
name: "hunt (windows-2022, leg ${{ matrix.leg }} - PNG stability: ours, PyPI 0.52.0, stock headed and headless)"
runs-on: windows-2022
timeout-minutes: 40
strategy:
fail-fast: false
max-parallel: 2
matrix:
leg: [A, B]
defaults:
run:
shell: bash
env:
PYTHONUNBUFFERED: "1"
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
with: { fetch-depth: 1 }
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
with: { python-version: '3.11' }
- name: Install the wrapper of this checkout, and stock Playwright with its firefox
run: |
python -m pip install --upgrade pip
python -m pip install ".[dev]" psutil
python -m pip install "playwright==$(cat scripts/playwright_pin.txt)"
python -m playwright install firefox
- name: Fetch the published firefox binary
run: echo "FF=$(cd "$RUNNER_TEMP" && python -m invisible_playwright fetch | tail -1)" >> "$GITHUB_ENV"
- name: The GeoIP database (made by the repository, same bytes every run)
run: python scripts/ci_lab_geoip.py build
- name: The PNG parser against PNGs whose chunks are known
run: python scripts/hunt_encoding.py selftest
- name: "Retail Firefox 159.0 (Mozilla's installer, checked against SHA256SUMS, unpacked with 7-Zip)"
continue-on-error: true
run: python -u scripts/hunt_first_run.py fetch-retail --out "$RUNNER_TEMP/retail"
- name: Install the PUBLISHED invisible-playwright 0.52.0 in its own venv, and fetch its own binary
continue-on-error: true
run: |
python -m venv "$RUNNER_TEMP/pypi052"
"$RUNNER_TEMP/pypi052/Scripts/python" -m pip install --upgrade pip
"$RUNNER_TEMP/pypi052/Scripts/python" -m pip install "invisible-playwright==0.52.0"
"$RUNNER_TEMP/pypi052/Scripts/python" -m pip list 2>/dev/null | grep -i -E "invisible|playwright"
echo "FF052=$(cd "$RUNNER_TEMP" && "$RUNNER_TEMP/pypi052/Scripts/python" -m invisible_playwright fetch | tail -1)" >> "$GITHUB_ENV"
- name: "Arm ours (this checkout's wrapper, the job's binary), 2 launches"
if: always()
continue-on-error: true
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_encoding.py collect --client ours --label ours --binary "$FF" --out "$RUNNER_TEMP/enc/${{ matrix.leg }}"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "Arm ours_pypi052 (invisible-playwright 0.52.0 from PyPI, its own binary), 2 launches"
if: always()
continue-on-error: true
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
echo "binary of 0.52.0: ${FF052:-<none>}"
"$RUNNER_TEMP/pypi052/Scripts/python" -u scripts/hunt_encoding.py collect --client ours --label ours_pypi052 ${FF052:+--binary "$FF052"} --out "$RUNNER_TEMP/enc/${{ matrix.leg }}"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "Arm stockheaded (stock Playwright firefox, headless=False), 2 launches"
if: always()
continue-on-error: true
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_encoding.py collect --client stock --label stockheaded --out "$RUNNER_TEMP/enc/${{ matrix.leg }}"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "Arm stockheadless (stock Playwright firefox, headless=True), 2 launches"
if: always()
continue-on-error: true
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_encoding.py collect --client stock --label stockheadless --headless --out "$RUNNER_TEMP/enc/${{ matrix.leg }}"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "Arm retail (Mozilla's Firefox 159.0 launched by hand, no automation), 2 launches"
if: always()
continue-on-error: true
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_encoding.py collect --client retail --label retail --retail-from "$RUNNER_TEMP/retail" --out "$RUNNER_TEMP/enc/${{ matrix.leg }}"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "Per-key table of this runner (two launches, three calls in one page)"
if: always()
continue-on-error: true
run: python -u scripts/hunt_encoding.py table "$RUNNER_TEMP/enc/${{ matrix.leg }}" | tee "$RUNNER_TEMP/enc/${{ matrix.leg }}/table.txt"
- name: Close every Firefox left
if: always()
shell: pwsh
run: |
Get-Process firefox -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue
"left: " + @(Get-Process firefox -ErrorAction SilentlyContinue).Count
- name: Upload the raw probe results of this runner
if: always()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: encoding-stability-${{ matrix.leg }}
path: ${{ runner.temp }}/enc/${{ matrix.leg }}
if-no-files-found: warn
retention-days: 14
compare:
name: "hunt (compare the two runners)"
needs: hunt
if: always()
runs-on: ubuntu-24.04
timeout-minutes: 15
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
with: { fetch-depth: 1 }
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
with: { python-version: '3.11' }
- name: The PNG parser against PNGs whose chunks are known
run: python scripts/hunt_encoding.py selftest
- name: Download both legs
continue-on-error: true
env:
GH_TOKEN: ${{ github.token }}
run: |
for leg in A B; do
gh run download "${{ github.run_id }}" --repo "${{ github.repository }}" -n "encoding-stability-$leg" -D "enc/$leg" || echo "leg $leg: no artifact"
done
ls -R enc | head -40
- name: "Per-key table: same runner and across the two runners"
continue-on-error: true
run: python -u scripts/hunt_encoding.py table enc/A enc/B | tee enc/table-two-runners.txt
- name: Upload the table
if: always()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: encoding-stability-table
path: enc/table-two-runners.txt
if-no-files-found: warn
retention-days: 14
+175
View File
@@ -0,0 +1,175 @@
# ─────────────────────────────────────────────────────────────────────────────
# first-run-hunt.yml - HUNT ONLY, never merged. Nothing of the product is changed. Starts on its own paths only: the two other hunts running on this
# branch (cpu-render-path-hunt-vm.yml, encoding-stability-hunt.yml) are not restarted by it, and it is not restarted by them.
#
# In ours with a fresh profile the parent shows a ~15 s CPU burst between +8 and +50 s after the launch, with these downloads: remote settings 18.9 MB,
# CRLite 6 MB, safebrowsing 8.5 MB, Widevine 23 MB, the newtab xpi; after that it drops to zero.
# Part 1 (scripts/hunt_first_run.py census): does retail Firefox 159.0 (Mozilla's installer, verified against its SHA256SUMS, launched by hand with
# subprocess: -no-remote, a fresh profile, an idle local page, no automation, no Playwright) show the same burst, with the same duration and the
# same downloads? 80 s, slices of 10 s: the parent's CPU, the parent's CPU per thread name, the files written in the profile (path and size; the
# directories gmp-*, security_state, safebrowsing, settings, features listed), the bytes the network interfaces received and sent. Ours (fresh
# profile) in the same table.
# Part 2 (scripts/hunt_first_run.py probe): what can a PAGE read of that state? ours with a fresh profile, ours with a used one, retail fresh, retail
# used (launched a second time on the profile of part 1), probed at +5, +20, +40 and +90 s: requestMediaKeySystemAccess for Widevine, ClearKey and
# PlayReady (outcome, time to resolve, the configuration returned), MediaCapabilities for encrypted and WebRTC H.264 configurations, the WebRTC codec
# lists (OpenH264 is a downloaded GMP), canPlayType, mediaDevices, plugins, permissions, storage, and whether three hosts are reachable/blocked.
# Each arm runs twice: `seq` (the four moments in one launch) and `late` (only +90 s: asking early may start a download).
# Every step is continue-on-error: a hunt must give whatever it got.
# ─────────────────────────────────────────────────────────────────────────────
name: first run hunt
on:
push:
branches: [hunt/cpu-render-path]
paths:
- scripts/hunt_first_run.py
- scripts/hunt_first_run_probe.js
- .github/workflows/first-run-hunt.yml
workflow_dispatch:
permissions:
contents: read
concurrency:
group: first-run-hunt-${{ github.ref }}
cancel-in-progress: true
env:
GITHUB_TOKEN: ${{ github.token }}
jobs:
hunt:
name: "hunt (windows-2022, first 80 s of a new profile: retail against ours; what a page reads of it)"
runs-on: windows-2022
timeout-minutes: 150
defaults:
run:
shell: bash
env:
PYTHONUNBUFFERED: "1"
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
with: { fetch-depth: 1 }
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
with: { python-version: '3.11' }
- name: Install the wrapper and psutil
run: |
python -m pip install --upgrade pip
python -m pip install ".[dev]" psutil
- name: Fetch the published firefox binary
run: echo "FF=$(cd "$RUNNER_TEMP" && python -m invisible_playwright fetch | tail -1)" >> "$GITHUB_ENV"
- name: The GeoIP database (made by the repository, same bytes every run)
run: python scripts/ci_lab_geoip.py build
- name: "Retail Firefox 159.0 (Mozilla's installer, checked against SHA256SUMS, unpacked with 7-Zip), once"
continue-on-error: true
run: python -u scripts/hunt_first_run.py fetch-retail --out "$RUNNER_TEMP/fr/retail"
# ----------------------------------------------------------------------------------------------- part 1: the first 80 s of a new profile
- name: "1. Census, retail (fresh profile, 80 s; the profile is kept for part 2)"
if: always()
continue-on-error: true
timeout-minutes: 8
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_first_run.py census --arm retail --retail-from "$RUNNER_TEMP/fr/retail" --keep-profile "$RUNNER_TEMP/fr/profile-retail" --out "$RUNNER_TEMP/fr/census"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "1. Census, ours (fresh profile, 80 s)"
if: always()
continue-on-error: true
timeout-minutes: 8
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_first_run.py census --arm ours --binary "$FF" --out "$RUNNER_TEMP/fr/census"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "1. Table: retail and ours, slice by slice"
if: always()
continue-on-error: true
run: python -u scripts/hunt_first_run.py census-table "$RUNNER_TEMP/fr/census" | tee "$RUNNER_TEMP/fr/census/table.txt"
# ----------------------------------------------------------------------------------------------- part 2: what a page reads
- name: "2. Probe, ours_fresh, seq"
if: always()
continue-on-error: true
timeout-minutes: 12
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_first_run.py probe --arm ours_fresh --mode seq --binary "$FF" --out "$RUNNER_TEMP/fr/probe"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "2. Probe, ours_fresh, late"
if: always()
continue-on-error: true
timeout-minutes: 12
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_first_run.py probe --arm ours_fresh --mode late --binary "$FF" --out "$RUNNER_TEMP/fr/probe"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "2. Probe, ours_used, seq"
if: always()
continue-on-error: true
timeout-minutes: 12
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_first_run.py probe --arm ours_used --mode seq --binary "$FF" --out "$RUNNER_TEMP/fr/probe"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "2. Probe, ours_used, late"
if: always()
continue-on-error: true
timeout-minutes: 12
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_first_run.py probe --arm ours_used --mode late --binary "$FF" --out "$RUNNER_TEMP/fr/probe"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "2. Probe, retail_fresh, seq"
if: always()
continue-on-error: true
timeout-minutes: 12
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_first_run.py probe --arm retail_fresh --mode seq --retail-from "$RUNNER_TEMP/fr/retail" --out "$RUNNER_TEMP/fr/probe"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "2. Probe, retail_fresh, late"
if: always()
continue-on-error: true
timeout-minutes: 12
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_first_run.py probe --arm retail_fresh --mode late --retail-from "$RUNNER_TEMP/fr/retail" --out "$RUNNER_TEMP/fr/probe"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "2. Probe, retail_used, seq"
if: always()
continue-on-error: true
timeout-minutes: 12
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_first_run.py probe --arm retail_used --mode seq --retail-from "$RUNNER_TEMP/fr/retail" --profile "$RUNNER_TEMP/fr/profile-retail" --out "$RUNNER_TEMP/fr/probe"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "2. Probe, retail_used, late"
if: always()
continue-on-error: true
timeout-minutes: 12
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_first_run.py probe --arm retail_used --mode late --retail-from "$RUNNER_TEMP/fr/retail" --profile "$RUNNER_TEMP/fr/profile-retail" --out "$RUNNER_TEMP/fr/probe"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "2. Tables: per probe and moment, fresh against used, ours and retail"
if: always()
continue-on-error: true
run: python -u scripts/hunt_first_run.py probe-table "$RUNNER_TEMP/fr/probe" | tee "$RUNNER_TEMP/fr/probe/table.txt"
- name: Close every Firefox left
if: always()
shell: pwsh
run: |
Get-Process firefox -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue
"left: " + @(Get-Process firefox -ErrorAction SilentlyContinue).Count
- name: Upload the results
if: always()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: first-run-hunt-${{ github.run_id }}-${{ github.run_attempt }}
path: |
${{ runner.temp }}/fr/census
${{ runner.temp }}/fr/probe
${{ runner.temp }}/fr/retail/retail.json
if-no-files-found: warn
retention-days: 14
+213
View File
@@ -0,0 +1,213 @@
# ─────────────────────────────────────────────────────────────────────────────
# msaa-hunt.yml - HUNT ONLY, never merged. Nothing of the product is changed: the prefs of the arm ours_nomsaa go through extra_prefs, from the hunt.
# Starts on its own paths only (the hunts running on this branch are not restarted by it, and it is not restarted by them).
#
# Measured: WebGL readPixels of 1024x1024 takes ~400 ms (p50) in ours and in ours_vmretail against ~89 ms in stock and in retail 159.
# Hypothesis: the multisample we force. GLContext.cpp:783-787 marks framebuffer_multisample unsupported on the Microsoft Basic Render Driver; the engine's hook at
# GLContext.cpp:799 (StealthDeclaredMultisample) turns it back on when webgl.msaa-samples > 0; the core sets webgl.msaa-samples=4 and webgl.msaa-force=true on Windows
# (invisible_core/prefs.py:1263-1264); so every readPixels of the default framebuffer resolves MSAA in software.
# Arms: ours, ours_nomsaa (webgl.msaa-samples=0, webgl.msaa-force=false from the hunt), stockheaded, retail 159.0 launched by hand (Mozilla's installer, checked against
# SHA256SUMS). Measured in each browser, in the page (scripts/hunt_msaa_probe.js): readPixels 1024x1024 (first, repeat p50, draw then 1 pixel) and toDataURL with
# antialias:true AND antialias:false in the same browser; a 256x256 scene with diagonal edges read back with readPixels and toDataURL, the edge pixels hashed apart from the
# interior ones, the antialiased pixels counted; getContextAttributes().antialias, SAMPLES, SAMPLE_BUFFERS, MAX_SAMPLES. Two rounds in reversed order. `facts` reads the
# multisample prefs back. Then the page-readable bytes of scripts/hunt_page_bytes.py (the 86-key diff), ours against ours_nomsaa.
# What retail does, from the sources, is in the docstring of scripts/hunt_msaa.py.
# Every step is continue-on-error: a hunt must give whatever it got.
# ─────────────────────────────────────────────────────────────────────────────
name: msaa hunt
on:
push:
branches: [hunt/cpu-render-path]
paths:
- scripts/hunt_msaa.py
- scripts/hunt_msaa_probe.js
- .github/workflows/msaa-hunt.yml
workflow_dispatch:
permissions:
contents: read
concurrency:
group: msaa-hunt-${{ github.ref }}
cancel-in-progress: true
env:
GITHUB_TOKEN: ${{ github.token }}
jobs:
hunt:
name: "hunt (windows-2022, MSAA and readPixels: ours, ours_nomsaa, stockheaded, retail)"
runs-on: windows-2022
timeout-minutes: 60
defaults:
run:
shell: bash
env:
PYTHONUNBUFFERED: "1"
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
with: { fetch-depth: 1 }
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
with: { python-version: '3.11' }
- name: Install the wrapper, psutil, and stock Playwright with its firefox
run: |
python -m pip install --upgrade pip
python -m pip install ".[dev]" psutil
python -m pip install "playwright==$(cat scripts/playwright_pin.txt)"
python -m playwright install firefox
- name: Fetch the published firefox binary
run: echo "FF=$(cd "$RUNNER_TEMP" && python -m invisible_playwright fetch | tail -1)" >> "$GITHUB_ENV"
- name: The GeoIP database (made by the repository, same bytes every run)
run: python scripts/ci_lab_geoip.py build
- name: "Retail Firefox 159.0 (Mozilla's installer, checked against SHA256SUMS, unpacked with 7-Zip)"
continue-on-error: true
run: python -u scripts/hunt_first_run.py fetch-retail --out "$RUNNER_TEMP/ms/retail"
# ------------------------------------------------------------------------------------------ the multisample prefs, read back (once per arm)
- name: "Facts, arm ours (effective webgl.msaa-* prefs, Troubleshoot)"
if: always()
continue-on-error: true
timeout-minutes: 5
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_msaa.py facts --arm ours --binary "$FF" --out "$RUNNER_TEMP/ms/r0"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "Facts, arm ours_nomsaa (effective webgl.msaa-* prefs, Troubleshoot)"
if: always()
continue-on-error: true
timeout-minutes: 5
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_msaa.py facts --arm ours_nomsaa --binary "$FF" --out "$RUNNER_TEMP/ms/r0"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "Facts, arm stockheaded (effective webgl.msaa-* prefs, Troubleshoot)"
if: always()
continue-on-error: true
timeout-minutes: 5
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_msaa.py facts --arm stockheaded --out "$RUNNER_TEMP/ms/r0"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "Facts, arm retail (effective webgl.msaa-* prefs, Troubleshoot)"
if: always()
continue-on-error: true
timeout-minutes: 5
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_msaa.py facts --arm retail --retail-from "$RUNNER_TEMP/ms/retail" --out "$RUNNER_TEMP/ms/r0"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
# ------------------------------------------------------------------------------------------ readPixels timing and the edges, two rounds
- name: "Round 1, arm ours"
if: always()
continue-on-error: true
timeout-minutes: 6
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_msaa.py run --arm ours --binary "$FF" --out "$RUNNER_TEMP/ms/r1"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "Round 1, arm retail"
if: always()
continue-on-error: true
timeout-minutes: 6
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_msaa.py run --arm retail --retail-from "$RUNNER_TEMP/ms/retail" --out "$RUNNER_TEMP/ms/r1"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "Round 1, arm ours_nomsaa"
if: always()
continue-on-error: true
timeout-minutes: 6
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_msaa.py run --arm ours_nomsaa --binary "$FF" --out "$RUNNER_TEMP/ms/r1"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "Round 1, arm stockheaded"
if: always()
continue-on-error: true
timeout-minutes: 6
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_msaa.py run --arm stockheaded --out "$RUNNER_TEMP/ms/r1"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "Round 2, arm stockheaded"
if: always()
continue-on-error: true
timeout-minutes: 6
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_msaa.py run --arm stockheaded --out "$RUNNER_TEMP/ms/r2"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "Round 2, arm ours_nomsaa"
if: always()
continue-on-error: true
timeout-minutes: 6
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_msaa.py run --arm ours_nomsaa --binary "$FF" --out "$RUNNER_TEMP/ms/r2"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "Round 2, arm retail"
if: always()
continue-on-error: true
timeout-minutes: 6
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_msaa.py run --arm retail --retail-from "$RUNNER_TEMP/ms/retail" --out "$RUNNER_TEMP/ms/r2"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "Round 2, arm ours"
if: always()
continue-on-error: true
timeout-minutes: 6
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_msaa.py run --arm ours --binary "$FF" --out "$RUNNER_TEMP/ms/r2"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "Table: timing, values, the edges pixel by pixel, what differs"
if: always()
continue-on-error: true
run: |
cp -r "$RUNNER_TEMP/ms/r0/"*-facts "$RUNNER_TEMP/ms/r1/" 2>/dev/null || true
python -u scripts/hunt_msaa.py table "$RUNNER_TEMP/ms/r1" "$RUNNER_TEMP/ms/r2" | tee "$RUNNER_TEMP/ms/table.txt"
# ------------------------------------------------------------------------------------------ the page-readable bytes, ours against ours_nomsaa
- name: "Page-readable bytes, arm ours (2 launches)"
if: always()
continue-on-error: true
timeout-minutes: 8
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_page_bytes.py collect --arm ours --binary "$FF" --launches 2 --out "$RUNNER_TEMP/ms/pagebytes"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "Page-readable bytes, arm ours_nomsaa (2 launches)"
if: always()
continue-on-error: true
timeout-minutes: 8
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_page_bytes.py collect --arm ours_nomsaa --binary "$FF" --launches 2 --out "$RUNNER_TEMP/ms/pagebytes"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "Page-readable bytes, ours against ours_nomsaa"
if: always()
continue-on-error: true
run: python -u scripts/hunt_page_bytes.py diff "$RUNNER_TEMP/ms/pagebytes" --a ours --b ours_nomsaa | tee "$RUNNER_TEMP/ms/pagebytes/diff.txt"
- name: Close every Firefox left
if: always()
shell: pwsh
run: |
Get-Process firefox -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue
"left: " + @(Get-Process firefox -ErrorAction SilentlyContinue).Count
- name: Upload the results
if: always()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: msaa-hunt-${{ github.run_id }}-${{ github.run_attempt }}
path: |
${{ runner.temp }}/ms/r0
${{ runner.temp }}/ms/r1
${{ runner.temp }}/ms/r2
${{ runner.temp }}/ms/table.txt
${{ runner.temp }}/ms/pagebytes
if-no-files-found: warn
retention-days: 14
+224
View File
@@ -0,0 +1,224 @@
# ─────────────────────────────────────────────────────────────────────────────
# readback-hunt.yml - HUNT ONLY, never merged. Nothing of the product is changed: the pref of the arm ours_noproj goes through extra_prefs, from the hunt.
# Starts on its own paths only (the hunts running on this branch are not restarted by it, and it is not restarted by them).
#
# Measured (43656857973): WebGL readPixels 1024x1024 repeat p50 is ~250-290 ms in ours, with or without MSAA, against 5-9 ms in stock and retail 159; toDataURL 1024 ~140-170 ms
# against 12-18. MSAA is not the cause. Suspect: the read-time canvas projection of the engine (the engine source tree): gfx/2d/StealthCanvasProjection.cpp StealthProjectPixels, applied to WebGL and
# WebGPU reads only (never to a 2D canvas), on when zoom.stealth.fpp.hw_seed > 0 and zoom.stealth.canvas.substitute_pixels is true (gfx/thebes/StealthDeclarationGate.h:54-62). Its cost is
# data-dependent: a pixel with a differing 4-neighbour builds a 3x3 neighbourhood and runs OnOneSegment (StealthCanvasProjection.cpp:89-129); the probes so far drew a ramp in which EVERY pixel is such an edge.
# Arms: ours, ours_noproj (zoom.stealth.canvas.substitute_pixels=false from the hunt), stockheaded, retail 159.0 launched by hand (Mozilla's installer, checked against SHA256SUMS).
# - timing, per content (flat, halves, triangle, gradient, noise), 1024x1024, antialias:false: WebGL readPixels and toDataURL, canvas 2D getImageData and toDataURL (the 2D canvas is never
# projected: if it is slow too, the cause is elsewhere); ms per MB; a hash of the bytes; two rounds in reversed order;
# - the 256x256 diagonal-edge scene with antialias:false, pixel by pixel: is the 1-level difference of ours against retail the projection (ours_noproj against retail)?
# - a Gecko profile with symbols of EVERY process and thread (MOZ_PROFILER_STARTUP_FILTERS=*) during 20 readPixels and 20 toDataURL of the gradient canvas, for ours and for ours_noproj:
# which process reads (content or GPU) and the top functions by self time (hunt_profile_summary.py, symbols as in hunt_fetch_symbols.py).
# Every step is continue-on-error: a hunt must give whatever it got.
# ─────────────────────────────────────────────────────────────────────────────
name: readback hunt
on:
push:
branches: [hunt/cpu-render-path]
paths:
- scripts/hunt_readback.py
- scripts/hunt_readback_probe.js
- .github/workflows/readback-hunt.yml
workflow_dispatch:
inputs:
symbols_run:
description: "Run id of the engine's release.yml whose symbols-win-x86_64 artifact matches the binary (empty: look through the recent runs)"
required: false
default: ""
permissions:
contents: read
concurrency:
group: readback-hunt-${{ github.ref }}
cancel-in-progress: true
env:
GITHUB_TOKEN: ${{ github.token }}
jobs:
hunt:
name: "hunt (windows-2022, readPixels and toDataURL cost: ours, ours_noproj, stockheaded, retail; profile with symbols)"
runs-on: windows-2022
timeout-minutes: 60
defaults:
run:
shell: bash
env:
PYTHONUNBUFFERED: "1"
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
with: { fetch-depth: 1 }
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
with: { python-version: '3.11' }
- name: Install the wrapper, psutil, and stock Playwright with its firefox
run: |
python -m pip install --upgrade pip
python -m pip install ".[dev]" psutil
python -m pip install "playwright==$(cat scripts/playwright_pin.txt)"
python -m playwright install firefox
- name: Fetch the published firefox binary
run: echo "FF=$(cd "$RUNNER_TEMP" && python -m invisible_playwright fetch | tail -1)" >> "$GITHUB_ENV"
- name: The GeoIP database (made by the repository, same bytes every run)
run: python scripts/ci_lab_geoip.py build
- name: "Retail Firefox 159.0 (Mozilla's installer, checked against SHA256SUMS, unpacked with 7-Zip)"
continue-on-error: true
run: python -u scripts/hunt_first_run.py fetch-retail --out "$RUNNER_TEMP/rb/retail"
# ------------------------------------------------------------------------------------------ the prefs, read back
- name: "Facts, arm ours (effective zoom.stealth.canvas.* and fpp.hw_seed)"
if: always()
continue-on-error: true
timeout-minutes: 5
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_readback.py facts --arm ours --binary "$FF" --out "$RUNNER_TEMP/rb/r0"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "Facts, arm ours_noproj (effective zoom.stealth.canvas.* and fpp.hw_seed)"
if: always()
continue-on-error: true
timeout-minutes: 5
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_readback.py facts --arm ours_noproj --binary "$FF" --out "$RUNNER_TEMP/rb/r0"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
# ------------------------------------------------------------------------------------------ timing per content, two rounds
- name: "Round 1, arm ours"
if: always()
continue-on-error: true
timeout-minutes: 8
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_readback.py run --arm ours --binary "$FF" --out "$RUNNER_TEMP/rb/r1"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "Round 1, arm retail"
if: always()
continue-on-error: true
timeout-minutes: 8
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_readback.py run --arm retail --retail-from "$RUNNER_TEMP/rb/retail" --out "$RUNNER_TEMP/rb/r1"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "Round 1, arm ours_noproj"
if: always()
continue-on-error: true
timeout-minutes: 8
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_readback.py run --arm ours_noproj --binary "$FF" --out "$RUNNER_TEMP/rb/r1"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "Round 1, arm stockheaded"
if: always()
continue-on-error: true
timeout-minutes: 8
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_readback.py run --arm stockheaded --out "$RUNNER_TEMP/rb/r1"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "Round 2, arm stockheaded"
if: always()
continue-on-error: true
timeout-minutes: 8
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_readback.py run --arm stockheaded --out "$RUNNER_TEMP/rb/r2"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "Round 2, arm ours_noproj"
if: always()
continue-on-error: true
timeout-minutes: 8
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_readback.py run --arm ours_noproj --binary "$FF" --out "$RUNNER_TEMP/rb/r2"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "Round 2, arm retail"
if: always()
continue-on-error: true
timeout-minutes: 8
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_readback.py run --arm retail --retail-from "$RUNNER_TEMP/rb/retail" --out "$RUNNER_TEMP/rb/r2"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "Round 2, arm ours"
if: always()
continue-on-error: true
timeout-minutes: 8
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_readback.py run --arm ours --binary "$FF" --out "$RUNNER_TEMP/rb/r2"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "Table: cost per content and per MB, the 2D control, the bytes, the edge scene"
if: always()
continue-on-error: true
run: |
cp -r "$RUNNER_TEMP/rb/r0/"*-facts "$RUNNER_TEMP/rb/r1/" 2>/dev/null || true
python -u scripts/hunt_readback.py table "$RUNNER_TEMP/rb/r1" "$RUNNER_TEMP/rb/r2" | tee "$RUNNER_TEMP/rb/table.txt"
# ------------------------------------------------------------------------------------------ the Gecko profile, with symbols
- name: "Profile, arm ours (20 readPixels + 20 toDataURL of the gradient canvas, every process and thread)"
if: always()
continue-on-error: true
timeout-minutes: 8
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_readback.py profile --arm ours --binary "$FF" --out "$RUNNER_TEMP/rb/profiles"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "Profile, arm ours_noproj (the same, projection off)"
if: always()
continue-on-error: true
timeout-minutes: 8
run: |
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
python -u scripts/hunt_readback.py profile --arm ours_noproj --binary "$FF" --out "$RUNNER_TEMP/rb/profiles"
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
- name: "Symbols of our engine (artifact symbols-win-x86_64 of the engine's release.yml)"
if: always()
continue-on-error: true
env:
GH_TOKEN: ${{ github.token }}
run: |
P="$RUNNER_TEMP/rb/profiles"
ID="$(python scripts/hunt_profile_summary.py "$P/ours" --ids | awk '$3=="xul.dll"{print $2}' | head -1)"
echo "breakpad id of our xul.dll in the profile: '$ID'"
if [ -z "$ID" ]; then echo "SYMBOLS: none (no id: no parent profile of ours)"; exit 0; fi
python scripts/hunt_fetch_symbols.py --id "$ID" --run "${{ inputs.symbols_run }}" --out "$RUNNER_TEMP/rb/symbols" | tee "$RUNNER_TEMP/rb/symbols.log"
- name: "Profile summary, ours: which process reads, top 20 functions by self time (content and GPU processes, every thread)"
if: always()
continue-on-error: true
run: |
P="$RUNNER_TEMP/rb/profiles/ours"
SYM=$(ls "$RUNNER_TEMP"/rb/symbols/symbols-*.zip 2>/dev/null | head -1 || true)
python -u scripts/hunt_profile_summary.py "$P" ${SYM:+--symbols "$SYM"} --only tab,gpu --detail 3 --thread-table --threads 3 --top 20 | tee "$P/summary.txt"
- name: "Profile summary, ours_noproj (what is left when the projection is off)"
if: always()
continue-on-error: true
run: |
P="$RUNNER_TEMP/rb/profiles/ours_noproj"
SYM=$(ls "$RUNNER_TEMP"/rb/symbols/symbols-*.zip 2>/dev/null | head -1 || true)
python -u scripts/hunt_profile_summary.py "$P" ${SYM:+--symbols "$SYM"} --only tab,gpu --detail 3 --threads 3 --top 20 | tee "$P/summary.txt"
- name: Close every Firefox left
if: always()
shell: pwsh
run: |
Get-Process firefox -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue
"left: " + @(Get-Process firefox -ErrorAction SilentlyContinue).Count
- name: Upload the results
if: always()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: readback-hunt-${{ github.run_id }}-${{ github.run_attempt }}
path: |
${{ runner.temp }}/rb/r0
${{ runner.temp }}/rb/r1
${{ runner.temp }}/rb/r2
${{ runner.temp }}/rb/table.txt
${{ runner.temp }}/rb/profiles
${{ runner.temp }}/rb/symbols.log
if-no-files-found: warn
retention-days: 14
@@ -1,97 +0,0 @@
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
-29
View File
@@ -6,35 +6,6 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
## [Unreleased]
## [0.52.1] - 2026-11-15
### Changed
- Pins invisible-core 64.73.0 (same engine, firefox-64). The compositor is now declared in software on every machine, as a
retail Firefox reports on a machine without a usable GPU, and never read from the host. Before, the hardware compositor
was declared over a software adapter, which cost about 6x the CPU in the GPU process.
- Windows: the engine is created inside a job of its own, so a launch no longer scans every process of the machine to bind
the engine's tree. (#498)
- Several browsers in one async program no longer slow one another down:
- `connect()` starts no thread on the event loop (#497).
- The virtual display of `headless=True` starts off the event loop (#499).
- Closing a browser waits for its processes and removes its profile without holding the loop that serves the others:
with four browsers in one process the loop was held for up to about 0.5 s per close, and is not held now (#503).
- Comments, the fork notes and one test message no longer point at scripts that were deleted (the transport comparison scripts and the prefs byte-parity gate: no round ran them). No behaviour changes. (#458)
### Added
- `page.expose_function`, `page.expose_binding`, `context.expose_function` and `context.expose_binding`, as in Playwright: the page calls a Python function and gets a promise (the value, a rejection when the function raised, an await when it is async). The page sees the function and nothing else (no name of ours on the window, no init script); an engine without `Page.addBinding` is refused with a clear sentence. Arguments and results cross as JSON. (#471)
- `Locator.screenshot()` and `ElementHandle.screenshot()`: a picture of the element, as in Playwright, in the page, in a frame of another site and in a frame nested in it. (#470)
### Fixed
- A context init script added after a page exists runs once in it, not twice. (#469)
- A CORS preflight (an OPTIONS request that no route holds) is no longer reported to the client, as in Playwright's own server: `page.on("request")`, `route` and a request counter hear of one request fewer for each preflighted fetch of the page. (#467)
### Tests
- Every test module is checked to leave no browser open (a census of the connection threads, which needs no package to run). (#497, #500)
- Software compositing is declared: the compositor in use, the CPU of the GPU process, and the bytes a page reads compared
against a recorded reference, on Linux and Windows. (#501)
- The UDP bench survives a loaded Windows machine, and its verdict says what it saw. (#502)
## [0.52.0] - 2026-11-14
### Changed
+3 -5
View File
@@ -7,9 +7,7 @@
{"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": 258, "exact": true, "tests": ["tests/test_the_server_says_nothing_about_the_launch_counter.py", "tests/test_the_witness_picks_a_port_both_sockets_bind.py", "tests/test_preload_newtab_reaches_the_core_only_when_asked.py", "tests/test_the_resolver_trap_counts_its_own_users.py", "tests/test_the_doh_e2e_launch_on_a_virtual_display.py", "tests/test_the_realness_helpers.py", "tests/test_the_h3_line_helpers.py", "tests/test_the_fake_doh_delays_and_refuses.py", "tests/test_the_host_address_helper.py", "tests/test_the_udp_chain_helper.py", "tests/test_the_fake_doh_answers.py", "tests/test_doh_session_prefs_unit.py", "tests/test_the_leak_watcher_sees_a_direct_connection.py", "tests/test_the_http_proxy_helper_asks_for_credentials.py", "tests/test_every_route_command_is_answered_may_fail.py", "tests/test_the_network_declaration_reaches_the_engine.py", "tests/test_the_resolver_trap_is_required_by_the_gate.py", "tests/test_the_exit_of_a_context_is_discovered_through_its_own_gateway.py", "tests/test_the_witness_hears_a_direct_send.py", "tests/test_the_egress_sink_helpers.py", "tests/test_the_lab_ca_and_its_ocsp_leaf.py", "tests/test_the_udp_bench_survives_what_a_loaded_machine_does_to_it.py"], "marker": "unit", "needs_root": false, "note": "92 = 6+32+21+7+8+3+9+6. The leak watcher file defines exactly one of its two resolver-trap tests per host (7 everywhere), so no test is skipped. `exact`: min_tests is raised by hand when a test is added. The sink of the egress gate (tests/test_the_egress_sink_helpers.py, 20): the engine's log (the same on Linux and Windows) and the witness read on known inputs, and a blind log that must raise, never answer 'nothing'. The lab CA of its OCSP case (tests/test_the_lab_ca_and_its_ocsp_leaf.py, 17; tests/test_the_fake_doh_answers.py +1, the DoH serving a lab-CA leaf): the leaf's AIA, trusted and untrusted issuers, the responder, the xpcshell step."},
{"id": "wrapper.e2e.page", "giro": "G2", "os": ["linux", "windows"], "min_tests": 120, "exact": true, "tests": ["tests/test_a_tiny_download_on_a_served_browser_is_saved_e2e.py", "tests/test_a_page_that_moves_on_e2e.py", "tests/test_a_popup_is_reported_when_the_engine_says_it_is_ready_as_playwright_does_e2e.py", "tests/test_a_popup_of_a_link_reaches_the_client_e2e.py", "tests/test_popup_destinations_e2e.py", "tests/test_popups_reach_the_client_e2e.py", "tests/test_route_superseded_e2e.py", "tests/test_closing_one_of_four_browsers_does_not_hold_the_loop_e2e.py"], "marker": "e2e", "needs_root": false, "note": "114 + the 5 of test_closing_one_of_four_browsers_does_not_hold_the_loop_e2e.py (four browsers in one process, one closes: the loop is held less than 50 ms by the clock of its own thread, the other three keep answering; the control holds the loop on purpose). 114 = 100 + the 14 of test_a_page_that_moves_on_e2e.py (a navigation the page overtook with location.replace ends; the engine fix 860ef8a6d9 is proved by it). 100 counted at the collection; was 96 = 10+32+16+34+4 before the popup tests of 6200bc2). A page is handed over when the engine says Page.ready; a popup reaches the client (link, noopener, window.open; own site and another; with and without a route; in-process and over launch_server) as Playwright's does; a superseded route. Needs the candidate binary, and the stock Playwright client of the dev extra."},
{"id": "wrapper.unit.page", "giro": "G1", "os": ["linux", "windows"], "min_tests": 72, "exact": true, "tests": ["tests/test_a_download_finished_before_it_was_announced_is_finished.py", "tests/test_every_order_of_the_events_of_a_popup_gives_one_page_event.py", "tests/test_ci_drive_gate_goes_through_the_core.py", "tests/test_a_page_is_handed_over_only_when_the_engine_says_it_is_ready.py", "tests/test_a_new_page_waits_for_the_engine.py", "tests/test_page_number_follows_the_call.py", "tests/test_a_commit_at_any_point_of_the_hand_over_reaches_the_client_once.py", "tests/test_no_event_of_any_family_is_lost_by_the_hand_over.py", "tests/test_the_hand_over_of_a_popup_holds_under_concurrency.py", "tests/test_a_page_closed_before_its_announcement_is_not_announced.py", "tests/test_a_live_event_does_not_overtake_the_replay_of_a_new_page.py"], "marker": "unit", "needs_root": false, "note": "72 = 44 + 3+9+5+1+10 of the popup hand-over (24 counted at the collection before; was 20 = 3+8+1+8 before 6200bc2). The page dispatcher's wait for Page.ready and what it hands over; the drive gate goes through the core (the engine waits for the session's road)."},
{"id": "wrapper.e2e.compositing", "giro": "G2", "os": ["linux", "windows"], "min_tests": 3, "exact": true, "tests": ["tests/test_software_compositing_is_declared_e2e.py"], "marker": "e2e", "needs_root": false, "note": "The engine DECLARES software compositing on every machine (core: the compositing entries of zoom.stealth.gfx.feature_status carry the VM decision, and on Windows gfx.webrender.software=true, gfx.webrender.software.d3d11=false). 3 = (1) the compositor read from a privileged context is 'WebRender (Software)' on Windows and on Linux (windowUtils.layerManagerType of each window: Troubleshoot.snapshot().graphics throws on this engine, `ext is null`, so it is not the route); (2) the GPU process uses under 1.5 s of CPU on the fixed 10-scene loop of one browser (Windows runner: 0.32 s declared, 2.7-4.2 s not, runs 43652292533 and 43642744101; on Linux it is held to the bound if a GPU process exists); (3) the 86 keys of the page-bytes probe plus the canvas 2D scenes (drawImage scaled with smoothing off/low/medium/high, text with linear/radial/conic gradients) equal tests/data/page_bytes_<os>.json, PNGs on decoded pixels. EXPECTED RED on the core 64.71.0 (tests 1 and 2 on Windows). The reference of Windows holds the 75 stable keys and 6 of the 11 PNG keys of run 43652292533; the five other PNG keys and the new canvas keys, and all of Linux, are written from the first run on the engine of the reference (the failure of test 3 prints RECORD-BEGIN ... RECORD-END with the entries to merge): a reference that is not complete is red, never skipped."},
{"id": "wrapper.unit.compositing", "giro": "G1", "os": ["linux", "windows"], "min_tests": 19, "exact": true, "tests": ["tests/test_the_page_bytes_reference_compares_decoded_pixels.py"], "marker": "unit", "needs_root": false, "note": "The helpers of wrapper.e2e.compositing on known inputs, no browser: the PNG compared on decoded pixels (another deBG chunk and compression are the same, one pixel is not, every scanline filter), the comparison with a reference (changed, missing and extra keys named, the entry to record), the type of an engine process, an engine process known by its executable and not by the name it gives itself (Linux), and the CPU of a window, and the shape of the committed Windows reference."}
{"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.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)."}
]
+2 -2
View File
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "invisible_playwright"
version = "0.52.1"
version = "0.52.0"
description = "Playwright wrapper for a patched Firefox with deterministic stealth profile."
readme = "README.md"
requires-python = ">=3.11"
@@ -69,7 +69,7 @@ dependencies = [
# metadata; nothing in src/ hardcodes a second copy (tests/test_core_pin.py
# fails if one appears). What stays invisible to install-time machinery is the
# --no-deps / lockfile residue, and _pin.py is the only layer that sees it.
"invisible_core==64.73.0",
"invisible_core==64.71.0",
# ⛔ playwright is NO LONGER a dependency: since the full fork, the Python
# client lives in src/invisible_playwright/_pw/ and its server in
# src/invisible_playwright/_juggler/ (no Node driver). Reintroducing it would not visibly
+132
View File
@@ -0,0 +1,132 @@
"""How much does answering the protocol IN PROCESS actually cost?
⛔ THE QUESTION IS NARROW ON PURPOSE. Not "is the Python path faster than the
Node driver" - that comparison is dominated by the browser and would answer a
different question. This measures ONLY the machinery this package adds between
`Channel.send` and the code that talks to Juggler: building the message dict,
the queue, the worker-thread hop, the reply, and `call_soon_threadsafe` back
onto the loop.
That is the thing the owner asked about on 2026-08-28: inside one process,
serialising to yourself looks like waste. Whether it IS waste depends on how it
compares to the round trip it wraps, and this project decides that kind of
question with a number.
⛔ NO BROWSER, and that is what makes this trustworthy. A fake server answers
instantly, so what is left in the measurement is the transport and nothing
else. It also means the result does not depend on the machine being quiet in
the way a browser measurement does - though a loaded machine still widens the
tail, which is why the median is reported next to the mean.
python scripts/bench_transport.py
python scripts/bench_transport.py --giri 20000
"""
from __future__ import annotations
import argparse
import asyncio
import pathlib
import statistics
import sys
import time
ROOT = pathlib.Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT / "src"))
#: What a real Juggler round trip costs, measured on 2026-08-27 with the
#: shipped binary. It is the denominator: the transport's cost only means
#: something as a fraction of the work it wraps.
#: ⛔ `Runtime.evaluate("1")` and NOT `Heap.collectGarbage`, which was used once
#: as a "bare command" and actually collects garbage - 26,8 ms of browser work
#: attributed to the transport.
JUGGLER_ROUND_TRIP_MS = 2.4
class FakeServer:
"""Answers instantly, so only the transport is being timed."""
def __init__(self) -> None:
self.transport = None
def attach(self, transport) -> None:
self.transport = transport
def shutdown(self) -> None:
pass
def handle(self, message):
return {"value": message["params"].get("n")}
async def run(rounds: int) -> int:
from invisible_playwright._juggler.transport import InProcessTransport
loop = asyncio.get_running_loop()
transport = InProcessTransport(loop, FakeServer())
await transport.connect()
pending = {}
def on_message(message):
future = pending.pop(message.get("id"), None)
if future is not None and not future.done():
future.set_result(message)
transport.on_message = on_message
async def one(index: int):
future = loop.create_future()
pending[index] = future
transport.send({"id": index, "guid": "x", "method": "noop",
"params": {"n": index},
"metadata": {"apiName": "bench"}})
return await future
# ⛔ A warm-up that is DISCARDED: the first calls pay for thread start-up
# and for the first allocation of every structure, and folding those into
# the average is how a microbenchmark reports a number nobody can reproduce.
for i in range(200):
await one(i)
samples = []
for i in range(rounds):
start = time.perf_counter()
await one(200 + i)
samples.append((time.perf_counter() - start) * 1000.0)
transport.request_stop()
await transport.wait_until_stopped()
samples.sort()
media = statistics.fmean(samples)
mediana = samples[len(samples) // 2]
p95 = samples[int(len(samples) * 0.95)]
print("giri utili %d" % len(samples))
print("media %.4f ms" % media)
print("mediana %.4f ms" % mediana)
print("p95 %.4f ms" % p95)
print("p99 %.4f ms" % samples[int(len(samples) * 0.99)])
print()
print("un giro Juggler vero %.2f ms (misurato 2026-08-27)"
% JUGGLER_ROUND_TRIP_MS)
quota = 100.0 * mediana / JUGGLER_ROUND_TRIP_MS
print("il transport pesa %.1f%% di una chiamata vera" % quota)
print()
if quota < 10:
print("VERDETTO: il transport NON e' il costo. Togliere thread e coda "
"andrebbe fatto per semplicita', se mai, non per velocita'.")
else:
print("VERDETTO: il transport pesa abbastanza da giustificare il "
"refactor asincrono.")
return 0
def main() -> int:
p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
p.add_argument("--giri", type=int, default=5000)
a = p.parse_args()
return asyncio.run(run(a.giri))
if __name__ == "__main__":
sys.exit(main())
+2 -2
View File
@@ -100,8 +100,8 @@ def _classes(tree: ast.AST) -> dict:
#: next step. The failure it would cause is silent and backwards: an `async
#: def` operation is absent from `_methods`, so `reachable` returns an EMPTY
#: known-set for it, and every field that operation legitimately reads gets
#: reported as ignored. Both function kinds are listed for the same reason as in any
#: AST walk over operations.
#: reported as ignored. Same tuple as `check_unresolved_names.py`'s
#: `_FUNCTIONS`, for the same reason.
_FUNCTIONS = (ast.FunctionDef, ast.AsyncFunctionDef)
+243
View File
@@ -0,0 +1,243 @@
"""A method that uses a name it never has: the NameError nobody ran into yet.
⛔ IT CAUGHT TWO REAL DEFECTS THE MOMENT IT WAS WRITTEN, both of the same shape
and both invisible to every other check in this repo:
* `Actions._set_checked` passed `frame_id` to its retry loop without ever
taking it as a parameter, while `check()` and `uncheck()` accepted the
argument and dropped it. Every `page.check()` on the Python transport died
with `Page.check: name 'frame_id' is not defined` - and the transport judge
reported it as an ENGINE defect, because the test that exercises it pins the
transport itself and therefore fails identically on both arms.
* `Actions.drag_and_drop` did the same thing twice in one function.
⛔ WHY THE SUITE DID NOT SEE IT. A `NameError` inside a method is not a syntax
error and not an import error: the module loads, the class builds, the name
resolves at CALL time. So the whole file is green until somebody calls that one
method, and the two above sat in a package with 500 passing tests.
**What it does NOT do.** It does not type-check, it does not follow
`globals()`, `exec`, or a name injected by a decorator, and it deliberately
treats every module-level assignment and import as available. The question it
asks is the narrowest one that catches this: *does this function use a bare
name that is neither its parameter, nor assigned in it, nor defined at module
level?*
python scripts/check_unresolved_names.py
python scripts/check_unresolved_names.py --selftest
"""
from __future__ import annotations
import argparse
import ast
import builtins
import pathlib
import sys
ROOT = pathlib.Path(__file__).resolve().parent.parent
#: ⛔ `scripts/` IS IN THE PERIMETER SINCE 2026-08-29, and leaving it out was
#: not a scoping decision - it was a hole this gate exists to close. On that
#: date `upstream_baseline.py:_per_file` was found returning `1 if morti else
#: 0` with `morti` assigned nowhere: a guaranteed NameError, sitting in the
#: repository, while this gate reported "none in 102 file(s)". Pointed at that
#: one file by hand it named the fault correctly, so the LOGIC was never
#: wrong; only the perimeter was.
#:
#: And the argument for scanning `scripts/` is STRONGER than for the package,
#: not weaker. The reason this class of defect survives is that a NameError
#: inside a function is invisible until someone calls it - and the package has
#: 529 unit tests calling into it, while these scripts have none. `_per_file`
#: is reached only by `--per-file`, on the async arm, forty minutes into a run
#: nobody makes twice.
#:
#: Measured before widening: 22 files, zero findings besides the real one - so
#: this costs no false positives to keep.
SCANNED = [ROOT / "src" / "invisible_playwright", ROOT / "scripts"]
sys.stdout.reconfigure(encoding="utf-8")
_FUNCTIONS = (ast.FunctionDef, ast.AsyncFunctionDef)
def _module_names(tree: ast.AST) -> set:
known = {n.name for n in ast.walk(tree)
if isinstance(n, _FUNCTIONS + (ast.ClassDef,))}
known |= {t.id for n in ast.walk(tree) if isinstance(n, ast.Assign)
for t in n.targets if isinstance(t, ast.Name)}
known |= {n.target.id for n in ast.walk(tree)
if isinstance(n, ast.AnnAssign) and isinstance(n.target, ast.Name)}
known |= {a.asname or a.name.split(".")[0]
for n in ast.walk(tree) if isinstance(n, (ast.Import, ast.ImportFrom))
for a in n.names}
# ⛔ THE MODULE DUNDERS, which are not builtins and are not imports:
# Python puts them in the module namespace itself. They only became
# reachable when this gate started walking module-level functions, and
# `__file__` in a plain function is the commonest of them by far - it was
# the first false positive the widening produced.
known |= {"__file__", "__name__", "__doc__", "__package__", "__spec__",
"__loader__", "__builtins__", "__path__"}
return known | set(dir(builtins))
def _bound_in(fn: ast.AST) -> set:
"""Every name that exists inside this function by the time it runs.
⛔ Nested functions and lambdas contribute their PARAMETERS, because the
outer body legitimately refers to them; comprehension targets and `except
... as` names too. Leaving any of those out turns ordinary code into a
fault, and a check that cries wolf is switched off after the third time.
"""
args = fn.args
bound = {a.arg for a in list(args.args) + list(args.kwonlyargs)
+ list(getattr(args, "posonlyargs", []))}
if args.vararg:
bound.add(args.vararg.arg)
if args.kwarg:
bound.add(args.kwarg.arg)
for n in ast.walk(fn):
if isinstance(n, ast.Name) and isinstance(n.ctx, ast.Store):
bound.add(n.id)
elif isinstance(n, _FUNCTIONS + (ast.Lambda,)) and n is not fn:
inner = n.args
for a in (list(inner.args) + list(inner.kwonlyargs)
+ list(getattr(inner, "posonlyargs", []))):
bound.add(a.arg)
# ⛔ `*args` and `**kw` OF THE NESTED FUNCTION TOO. Leaving these
# out is not a small gap: the first run of this checker over the
# real package reported 10 faults and every one of them was this -
# `def patched(**kw)` inside a wrapper, which is the single most
# common shape in the file it was scanning. A checker that is
# wrong ten times out of ten teaches people to ignore it, and the
# two REAL defects it had just found would have been ignored with
# the rest.
if inner.vararg:
bound.add(inner.vararg.arg)
if inner.kwarg:
bound.add(inner.kwarg.arg)
if not isinstance(n, ast.Lambda):
bound.add(n.name)
elif isinstance(n, ast.comprehension):
for t in ast.walk(n.target):
if isinstance(t, ast.Name):
bound.add(t.id)
elif isinstance(n, ast.ExceptHandler) and n.name:
bound.add(n.name)
elif isinstance(n, ast.Global):
bound.update(n.names)
elif isinstance(n, ast.Nonlocal):
bound.update(n.names)
return bound
def unresolved(source: str, where: str = "<source>") -> list:
tree = ast.parse(source)
known = _module_names(tree)
out = []
def scan(fn, owner):
bound = _bound_in(fn)
for n in ast.walk(fn):
if isinstance(n, ast.Name) and isinstance(n.ctx, ast.Load):
if n.id not in bound and n.id not in known:
out.append((where, owner, fn.name, n.id, n.lineno))
for cls in [n for n in ast.walk(tree) if isinstance(n, ast.ClassDef)]:
for fn in [n for n in cls.body if isinstance(n, _FUNCTIONS)]:
scan(fn, cls.name)
# ⛔ MODULE-LEVEL FUNCTIONS TOO, and they were invisible until
# 2026-08-29. This gate was written against a file of dispatcher classes,
# so it walked classes and nothing else; a plain function was never looked
# at. It cost a real defect the day a refactor moved seventeen leaf helpers
# into two new modules with no classes at all: one of them used `json`
# without importing it, this gate reported "none in 103 files", and the
# failure surfaced as a NameError out of one test - which is the exact
# shape it exists to catch before a caller does.
for fn in [n for n in tree.body if isinstance(n, _FUNCTIONS)]:
scan(fn, "<module>")
return out
SELFTEST = [
("the defect itself: used, never taken",
"class A:\n def op(self, x):\n return self.go(frame_id)\n", 1),
("a parameter is not a fault",
"class A:\n def op(self, frame_id):\n return frame_id\n", 0),
("a keyword-only parameter is not a fault",
"class A:\n def op(self, *, frame_id=None):\n return frame_id\n", 0),
("something assigned in the body is not a fault",
"class A:\n def op(self):\n v = 1\n return v\n", 0),
("a module-level name is not a fault",
"H = 1\nclass A:\n def op(self):\n return H\n", 0),
("a MODULE-LEVEL FUNCTION using a name nobody imported",
"def helper(x):\n return json.dumps(x)\n", 1),
("the same module-level function with the import present",
"import json\ndef helper(x):\n return json.dumps(x)\n", 0),
("__file__ in a module-level function is not a fault",
"def where():\n return __file__\n", 0),
("an import is not a fault",
"import json\nclass A:\n def op(self):\n return json\n", 0),
("a builtin is not a fault",
"class A:\n def op(self):\n return len([])\n", 0),
("a nested function's parameter is not a fault",
"class A:\n def op(self):\n def run(p):\n return p\n"
" return run\n", 0),
("a comprehension target is not a fault",
"class A:\n def op(self):\n return [i for i in range(3)]\n", 0),
("an except-as name is not a fault",
"class A:\n def op(self):\n try:\n pass\n"
" except ValueError as e:\n return e\n", 0),
("two in one function are both reported",
"class A:\n def op(self):\n return (a_missing, b_missing)\n", 2),
# ⛔ The two below are the shape that produced 10 false alarms on the first
# real run. They are here so the next person who tightens `_bound_in` finds
# out immediately instead of from a wall of noise.
("a nested function's **kwargs is not a fault",
"class A:\n def op(self):\n def patched(**kw):\n"
" return kw\n return patched\n", 0),
("a lambda's *args is not a fault",
"class A:\n def op(self):\n return lambda *args: args\n", 0),
]
def selftest() -> int:
bad = 0
for name, source, expected in SELFTEST:
got = len(unresolved(source))
ok = got == expected
bad += 0 if ok else 1
print(" %-48s %s (%d, expected %d)"
% (name, "ok" if ok else "BROKEN", got, expected))
print("selftest: %d cases, %d broken" % (len(SELFTEST), bad))
return 1 if bad else 0
def main() -> int:
p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
p.add_argument("--selftest", action="store_true")
p.add_argument("paths", nargs="*",
help="default: the package's own source, plus scripts/")
a = p.parse_args()
if a.selftest:
return selftest()
files = ([pathlib.Path(x) for x in a.paths]
or sorted(f for root in SCANNED for f in root.rglob("*.py")))
faults = []
for f in files:
try:
faults += unresolved(f.read_text(encoding="utf-8"), str(f))
except SyntaxError as bad:
print(" %s: cannot be parsed (%s)" % (f, bad))
return 2
for where, cls, fn, name, line in faults:
print(" %s :: %s.%s uses %r at line %d and never has it"
% (pathlib.Path(where).name, cls, fn, name, line))
if faults:
print("UNRESOLVED NAMES: %d. Each one is a NameError waiting for the "
"first caller of that method." % len(faults))
return 1
print("UNRESOLVED NAMES: none in %d file(s)." % len(files))
return 0
if __name__ == "__main__":
sys.exit(main())
+318
View File
@@ -0,0 +1,318 @@
"""Do the two servers receive the same thing, and answer the same thing?
⛔ THIS IS THE QUESTION THAT DECIDES WHETHER THE NODE DRIVER CAN BE DELETED, and
it is not the same question `judge_both_transports.py` answers. That one runs
tests and reports which arm goes red - a behavioural check, and a coarse one: a
field the client does not happen to read today is missing in complete silence,
and shows up as a bug months later in a code path nobody exercised. This one
compares the WIRE.
**What it compares, and why at this level.**
* **input**: every method the client SENDS, and the set of PARAMETER NAMES it
sends with each. Both servers must accept the same vocabulary. A method
present on one side and absent on the other is a hole; a method present on
both but reached with different fields means the client is being driven
differently, which makes the rest of the comparison meaningless.
* **output**: every object TYPE the server creates, and the set of INITIALIZER
FIELD NAMES for each; plus every EVENT name the server emits, per type. This
is the half that reading `_impl` cannot give you: it tells you which fields
are CONSUMED today, never which are SENT, and the difference is exactly the
set a future code path will want.
⛔ **FIELD NAMES, NOT VALUES.** guids are allocated by whoever allocates them,
ports are ephemeral, versions and build ids differ by construction. Comparing
values would drown the real differences in noise that is not a difference at
all. Where a VALUE matters it belongs in a test, not here.
⛔ **AND IT RUNS THE SAME SESSION TWICE, IN TWO SUBPROCESSES.** The transport is
chosen once, at import time, from the environment: two transports in one process
would mean one of the two arms was not the thing it claims to be.
python scripts/diff_protocol.py <firefox-binary>
python scripts/diff_protocol.py <firefox-binary> --keep (leave the traces)
"""
from __future__ import annotations
import argparse
import json
import os
import pathlib
import subprocess
import sys
import tempfile
ROOT = pathlib.Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT / "src"))
sys.stdout.reconfigure(encoding="utf-8")
#: Fields whose ABSENCE on one side is not a finding, because the two paths
#: legitimately disagree about them. Kept short and each one argued: a long
#: list here is how a comparison stops comparing.
EXPECTED_DIFFERENCES = {
# The driver reports the bundled Playwright's version string; we report the
# engine's. Neither is wrong and no client behaviour depends on the text.
("Playwright", "initializer", "preLaunchedBrowser"),
# ⛔ `previewUpdated` is a REAL gap, listed here because it is argued and
# not because it is small. The driver pushes a new preview string every
# time a handle's value changes, and `_js_handle.py` does listen for it -
# so on this server `repr(handle)` keeps the preview it was born with.
# That is the whole consequence: it reaches error messages and the REPL,
# never a page, never a decision, never a byte on the wire. Implementing it
# would mean re-serialising every handle after every evaluation, which is
# protocol traffic and parent-process work for a string a human reads.
# If it ever stops being cosmetic - a client that BRANCHES on the preview -
# this line is where to start.
("ElementHandle", "event", "previewUpdated"),
("JSHandle", "event", "previewUpdated"),
}
#: A checkout that still carries the Node driver, for the day this one does not.
#: Same contract and same reason as in `judge_both_transports.py`: a worktree,
#: not an installed release, because a published wrapper pins a published core
#: and a sealed engine and cannot drive a locally built binary.
#:
#: git worktree add /tmp/judge <the last commit that carried _driver/>
#: INVPW_DRIVER_TREE=/tmp/judge python scripts/diff_protocol.py <binary>
DRIVER_TREE_ENV = "INVPW_DRIVER_TREE"
def capture(binary: str, transport: str, out: pathlib.Path) -> None:
"""Run the scripted session under one transport, writing its trace."""
env = dict(os.environ)
env["INVPW_TRANSPORT"] = transport
env["INVPW_TRACE_OUT"] = str(out)
tree = os.environ.get(DRIVER_TREE_ENV)
if transport == "driver" and tree:
# ⛔ The driver comes from the older tree; the RECORDER does not. The
# capture script has to be this one, or the two traces are produced by
# two different instruments and every difference between them measures
# the instruments - which is the mistake this whole comparison exists
# to avoid.
src = str(pathlib.Path(tree) / "src")
env["PYTHONPATH"] = os.pathsep.join(
[src] + ([env["PYTHONPATH"]] if env.get("PYTHONPATH") else []))
script = ROOT / "scripts" / "capture_protocol.py"
r = subprocess.run([sys.executable, str(script), binary, "-o", str(out)],
env=env, capture_output=True, text=True)
if r.returncode != 0 or not out.exists():
raise RuntimeError("the %s arm did not produce a trace:\n%s\n%s"
% (transport, r.stdout[-2000:], r.stderr[-2000:]))
def sent_vocabulary(trace: list) -> dict:
"""method -> the set of parameter names ever sent with it."""
out: dict = {}
for entry in trace:
if entry["dir"] != "send":
continue
message = entry["msg"]
method = message.get("method")
if not method:
continue
params = message.get("params") or {}
out.setdefault(method, set()).update(params.keys())
return out
def created_shapes(trace: list) -> dict:
"""type -> the set of initializer field names ever seen for it."""
out: dict = {}
for entry in trace:
if entry["dir"] != "recv":
continue
message = entry["msg"]
if message.get("method") != "__create__":
continue
params = message.get("params") or {}
kind = params.get("type")
if not kind:
continue
out.setdefault(kind, set()).update(
(params.get("initializer") or {}).keys())
return out
def events_by_owner(trace: list, shapes_of_guid: dict) -> dict:
"""type -> the set of event names the server emitted on objects of it."""
out: dict = {}
for entry in trace:
if entry["dir"] != "recv":
continue
message = entry["msg"]
method = message.get("method")
if not method or method.startswith("__"):
continue
kind = shapes_of_guid.get(message.get("guid"), "?")
out.setdefault(kind, set()).add(method)
return out
def parentage(trace: list, types: dict) -> dict:
"""child TYPE -> the set of parent TYPES it was ever created under.
⛔ A FOURTH DIMENSION, ADDED BECAUSE ITS ABSENCE LET A REAL DEFECT
THROUGH. This server created `ElementHandle` as a child of `Page`; the
driver creates it under `Frame`. Types matched, initializer fields matched,
events matched - and every call that reads a timeout off the handle's frame
died with `'Page' object has no attribute '_timeout'`, because
`_element_handle.py` learns its frame from the guid TREE and from nothing
else. Parentage is protocol, not bookkeeping.
"""
out: dict = {}
for entry in trace:
if entry["dir"] != "recv":
continue
message = entry["msg"]
if message.get("method") != "__create__":
continue
params = message.get("params") or {}
kind = params.get("type")
if not kind:
continue
out.setdefault(kind, set()).add(types.get(message.get("guid"), "root"))
return out
def disposed_types(trace: list, types: dict) -> dict:
"""type -> whether an object of it was ever disposed ("yes" or nothing).
⛔ A FIFTH DIMENSION, AND THE FOUR ABOVE ARE BLIND TO IT BY CONSTRUCTION:
`events_by_owner` skips every method starting with `__`, so `__dispose__`
was invisible to this comparison no matter how far the two servers drifted.
It is not bookkeeping either - the client ACTS on it, dropping the object
from its registry - so a server that never disposes anything grows the
client's registry for the life of the browser, and a server that disposes
something the client still holds hands back a dead reference.
It was added on 2026-08-28 to answer a question the PARITY verdict could
not: this server never disposed a closed page, and the count of live
objects grew by one per page (9 at page 0, 508 at page 499). Whether that
is a defect or a difference depends entirely on what the driver does, and
nothing here could see it.
The value is a one-element set rather than a bool so `report` can compare
it like every other dimension.
"""
out: dict = {}
for entry in trace:
if entry["dir"] != "recv":
continue
message = entry["msg"]
if message.get("method") != "__dispose__":
continue
kind = types.get(message.get("guid"))
if kind:
out.setdefault(kind, set()).add("disposed")
return out
def guid_types(trace: list) -> dict:
"""guid -> its type, so an event can be attributed to a KIND of object."""
out: dict = {}
for entry in trace:
if entry["dir"] != "recv":
continue
message = entry["msg"]
if message.get("method") != "__create__":
continue
params = message.get("params") or {}
if params.get("guid"):
out[params["guid"]] = params.get("type")
return out
def report(label: str, ours: dict, theirs: dict, kind: str) -> list:
"""Differences in one dimension, as lines. Empty means parity."""
faults = []
def kept(name, fields):
"""⛔ The argued differences are filtered HERE TOO, and they were not.
A field can be missing two ways: the key exists on both sides and one
set is short, or the key is absent entirely. The first version only
filtered the first, so an event type that appears on the driver and
nowhere on ours stayed red forever no matter what was written about
it - and a gate with a permanent red is a gate people stop reading."""
return sorted(f for f in fields
if (name, kind, f) not in EXPECTED_DIFFERENCES)
for name in sorted(set(theirs) - set(ours)):
rest = kept(name, theirs[name])
if rest:
faults.append("%s %r reaches the DRIVER and not us: %s"
% (label, name, rest))
for name in sorted(set(ours) - set(theirs)):
rest = kept(name, ours[name])
if rest:
faults.append("%s %r reaches US and not the driver: %s"
% (label, name, rest))
for name in sorted(set(ours) & set(theirs)):
missing = theirs[name] - ours[name]
extra = ours[name] - theirs[name]
missing = {f for f in missing
if (name, kind, f) not in EXPECTED_DIFFERENCES}
extra = {f for f in extra
if (name, kind, f) not in EXPECTED_DIFFERENCES}
if missing:
faults.append("%s %r: the driver carries %s and we do not"
% (label, name, sorted(missing)))
if extra:
faults.append("%s %r: we carry %s and the driver does not"
% (label, name, sorted(extra)))
return faults
def main() -> int:
p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
p.add_argument("binary")
p.add_argument("--keep", action="store_true",
help="leave the two traces on disk for inspection")
a = p.parse_args()
work = pathlib.Path(tempfile.mkdtemp(prefix="protocol_diff_"))
driver_trace = work / "driver.json"
ours_trace = work / "juggler.json"
print("recording the DRIVER arm ...", flush=True)
capture(a.binary, "driver", driver_trace)
print("recording the PYTHON arm ...", flush=True)
capture(a.binary, "juggler", ours_trace)
driver = json.loads(driver_trace.read_text(encoding="utf-8"))
ours = json.loads(ours_trace.read_text(encoding="utf-8"))
print()
print(" driver: %d messages python: %d messages"
% (len(driver), len(ours)))
faults = []
faults += report("method", sent_vocabulary(ours), sent_vocabulary(driver),
"params")
faults += report("object", created_shapes(ours), created_shapes(driver),
"initializer")
faults += report("events on", events_by_owner(ours, guid_types(ours)),
events_by_owner(driver, guid_types(driver)), "event")
faults += report("parent of", parentage(ours, guid_types(ours)),
parentage(driver, guid_types(driver)), "parent")
faults += report("disposal of", disposed_types(ours, guid_types(ours)),
disposed_types(driver, guid_types(driver)), "dispose")
print()
for line in faults:
print(" " + line)
if a.keep or faults:
print()
print(" traces: %s" % work)
if faults:
print("PROTOCOL DIFF: %d difference(s). The Node driver cannot be "
"deleted while any of these stand, or a caller who reaches one "
"gets silence instead of a browser." % len(faults))
return 1
print("PROTOCOL DIFF: PARITY - same methods with the same parameters in, "
"same object types with the same initializer fields, the same "
"events, the same parentage and the same disposals out.")
return 0
if __name__ == "__main__":
sys.exit(main())
+182
View File
@@ -0,0 +1,182 @@
// HUNT ONLY (branch hunt/cpu-render-path, never merged). Served by scripts/hunt_compositor_visible.py as /probe.js and run by every arm in a page of its own for
// about 20 s: what can a PAGE read of the compositor behind it? Each number is measured in the page, with the page's own clocks, and the whole result is POSTed to
// /result once, as one JSON object: {phases: {name: {...}}, values: {...}}. `kind` says what a difference between two browsers would be: "timing" (a measurement
// that varies from run to run and from machine to machine) or "value" (a declared or fixed property: it should be equal in every Firefox on the same machine).
(async () => {
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const now = () => performance.now();
const q = (a, p) => { if (!a.length) return null; const s = a.slice().sort((x, y) => x - y); return s[Math.min(s.length - 1, Math.floor(p * s.length))]; };
const r3 = (x) => (x === null || x === undefined ? null : Math.round(x * 1000) / 1000);
const result = { phases: {}, values: {}, errors: [], started_at: Date.now() };
// Frames: one rAF loop for `ms`, with the interval between callbacks and what the callback's timestamp says.
function frames(ms, each) {
return new Promise((resolve) => {
const t = [], skew = [], start = now();
let stop = false;
const guard = setTimeout(() => { stop = true; resolve({ t, skew, guard: true }); }, ms + 3000);
function tick(ts) {
if (stop) return;
const n = now();
t.push(n); skew.push(n - ts);
if (each) each(n);
if (n - start < ms) requestAnimationFrame(tick);
else { clearTimeout(guard); stop = true; resolve({ t, skew, guard: false }); }
}
requestAnimationFrame(tick);
});
}
function describe(f, ms) {
const iv = [];
for (let i = 1; i < f.t.length; i++) iv.push(f.t[i] - f.t[i - 1]);
const med = q(iv, 0.5);
const wall = f.t.length > 1 ? f.t[f.t.length - 1] - f.t[0] : ms;
let dropped = 0;
if (med) for (const x of iv) if (x > med * 1.5) dropped += Math.max(1, Math.round(x / med) - 1);
const buckets = { "<14": 0, "14-15.5": 0, "15.5-18": 0, "18-20": 0, "20-25": 0, ">25": 0 };
for (const x of iv) buckets[x < 14 ? "<14" : x < 15.5 ? "14-15.5" : x < 18 ? "15.5-18" : x < 20 ? "18-20" : x < 25 ? "20-25" : ">25"]++;
return { kind: "timing", frames: f.t.length, seconds: r3(wall / 1000), fps: r3(iv.length / (wall / 1000)), interval_ms_p5: r3(q(iv, 0.05)), interval_ms_p50: r3(med),
interval_ms_p95: r3(q(iv, 0.95)), interval_ms_max: r3(Math.max(0, ...iv)), dropped_frames: dropped, buckets, now_minus_timestamp_ms_p50: r3(q(f.skew, 0.5)),
watchdog: f.guard };
}
async function phase(name, fn) {
try { result.phases[name] = await fn(); } catch (e) { result.errors.push(name + ": " + ((e && e.message) || e)); }
}
// ------------------------------------------------------------------------------------------------------------------ values
result.values = {
kind: "value",
update_fast: matchMedia("(update: fast)").matches, update_slow: matchMedia("(update: slow)").matches, update_none: matchMedia("(update: none)").matches,
prefers_reduced_motion: matchMedia("(prefers-reduced-motion: reduce)").matches, hover: matchMedia("(hover: hover)").matches,
any_pointer_fine: matchMedia("(any-pointer: fine)").matches, dynamic_range_high: matchMedia("(dynamic-range: high)").matches,
color_gamut_p3: matchMedia("(color-gamut: p3)").matches, display_mode_browser: matchMedia("(display-mode: browser)").matches,
screen: [screen.width, screen.height, screen.availWidth, screen.availHeight, screen.colorDepth, screen.pixelDepth], dpr: window.devicePixelRatio,
visibility: document.visibilityState, hasFocus: document.hasFocus(), hidden: document.hidden,
scroll_behavior_supported: CSS.supports("scroll-behavior", "smooth"), scrollend_supported: "onscrollend" in window,
screen_refresh_property: ("refreshRate" in screen) ? screen.refreshRate : "absent", screen_keys_with_rate: Object.keys(Object.getPrototypeOf(screen)).filter((k) => /refresh|rate|hz/i.test(k)),
hardwareConcurrency: navigator.hardwareConcurrency,
};
// performance.now() resolution: the smallest positive step in 300000 calls, and the number of decimals seen
{
let min = Infinity, last = now(), decimals = 0;
for (let i = 0; i < 300000; i++) { const n = now(); const d = n - last; if (d > 0 && d < min) min = d; last = n; if (i < 2000) { const s = String(n); const dot = s.indexOf("."); if (dot >= 0) decimals = Math.max(decimals, s.length - dot - 1); } }
result.values.performance_now_min_step_ms = r3(min);
result.values.performance_now_decimals_seen = decimals;
let dmin = Infinity, dl = Date.now();
const s0 = now();
while (now() - s0 < 60 && dmin > 0.5) { const d = Date.now(); if (d > dl) { dmin = Math.min(dmin, d - dl); dl = d; } }
result.values.date_now_min_step_ms = dmin === Infinity ? null : dmin;
}
// ------------------------------------------------------------------------------------------------------------------ 1. rAF alone
await phase("raf_idle_5s", async () => describe(await frames(5000), 5000));
// ------------------------------------------------------------------------------------------------------------------ 2. CSS animation
await phase("raf_with_css_animation_4s", async () => {
const st = document.createElement("style");
st.textContent = "@keyframes hspin{from{transform:rotate(0)}to{transform:rotate(360deg)}}@keyframes hcol{from{box-shadow:0 0 0 0 #08f,inset 0 0 20px #f80}to{box-shadow:0 0 60px 20px #0a8,inset 0 0 90px #f08}}" +
".hb{position:fixed;left:20px;top:20px;width:300px;height:300px;background:linear-gradient(45deg,#f00,#00f);animation:hspin 2s linear infinite}" +
".hc{position:fixed;left:360px;top:20px;width:300px;height:300px;background:#444;animation:hcol 1s ease-in-out infinite alternate}";
document.head.appendChild(st);
const a = document.createElement("div"); a.className = "hb"; const b = document.createElement("div"); b.className = "hc";
document.body.append(a, b);
const running = document.getAnimations().length;
const f = await frames(4000);
a.remove(); b.remove(); st.remove();
return Object.assign(describe(f, 4000), { running_animations: running });
});
// ------------------------------------------------------------------------------------------------------------------ 3. WebGL animation (2 s free, 2 s with a sync readback every frame)
async function glCanvas(w, h) {
const c = document.createElement("canvas"); c.width = w; c.height = h; c.style.cssText = "position:fixed;left:0;top:0";
document.body.appendChild(c);
const gl = c.getContext("webgl", { preserveDrawingBuffer: false, antialias: true });
if (!gl) { c.remove(); throw new Error("no webgl"); }
const mk = (type, src) => { const s = gl.createShader(type); gl.shaderSource(s, src); gl.compileShader(s); return s; };
const p = gl.createProgram();
gl.attachShader(p, mk(gl.VERTEX_SHADER, "attribute vec2 p; varying vec2 uv; void main(){ uv=p*0.5+0.5; gl_Position=vec4(p,0.,1.); }"));
gl.attachShader(p, mk(gl.FRAGMENT_SHADER, "precision highp float; varying vec2 uv; uniform float t; void main(){ float a=0.; for(int i=0;i<48;i++){ a+=sin(uv.x*float(i)+t)*cos(uv.y*float(i)-t); } gl_FragColor=vec4(fract(a),uv.x,uv.y,1.); }"));
gl.linkProgram(p); gl.useProgram(p);
const b = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, b);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, 1]), gl.STATIC_DRAW);
gl.enableVertexAttribArray(0); gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);
return { c, gl, t: gl.getUniformLocation(p, "t") };
}
await phase("raf_with_webgl_animation_4s", async () => {
const { c, gl, t } = await glCanvas(512, 512);
const px = new Uint8Array(4), syncs = [];
const f1 = await frames(2000, (n) => { gl.uniform1f(t, n / 500); gl.drawArrays(gl.TRIANGLES, 0, 6); });
const f2 = await frames(2000, (n) => { gl.uniform1f(t, n / 500); gl.drawArrays(gl.TRIANGLES, 0, 6); const s = now(); gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, px); syncs.push(now() - s); });
c.remove();
return { free: describe(f1, 2000), with_sync_readback_every_frame: describe(f2, 2000), sync_readback_ms_p50: r3(q(syncs, 0.5)), sync_readback_ms_p95: r3(q(syncs, 0.95)), kind: "timing" };
});
// ------------------------------------------------------------------------------------------------------------------ 4. smooth scrolling of a long page
await phase("smooth_scroll", async () => {
const box = document.createElement("div");
box.style.cssText = "position:absolute;left:0;top:0;width:100%;height:30000px;background:repeating-linear-gradient(#fff,#fff 40px,#cde 40px,#cde 80px)";
for (let i = 0; i < 400; i++) { const d = document.createElement("div"); d.style.cssText = "position:absolute;left:" + ((i * 37) % 600) + "px;top:" + (i * 70) + "px;width:200px;height:50px;background:hsl(" + ((i * 11) % 360) + ",60%,60%);box-shadow:0 2px 8px #0008"; d.textContent = "row " + i; box.appendChild(d); }
document.body.appendChild(box);
window.scrollTo(0, 0);
await sleep(200);
const ev = [], target = 12000;
let ended = false, endAt = 0;
const onScroll = () => ev.push(now());
window.addEventListener("scroll", onScroll);
window.addEventListener("scrollend", () => { ended = true; endAt = now(); }, { once: true });
const t0 = now();
const frameLoop = frames(4500);
window.scrollTo({ top: target, behavior: "smooth" });
let doneAt = null;
while (now() - t0 < 4500) {
await sleep(25);
if (Math.abs(window.scrollY - target) < 1 && doneAt === null) doneAt = now();
if (ended || (doneAt !== null && now() - doneAt > 400)) break;
}
const f = await frameLoop;
window.removeEventListener("scroll", onScroll);
const y = window.scrollY;
window.scrollTo(0, 0); box.remove();
const lastEv = ev.length ? ev[ev.length - 1] : t0;
const dur = (ended ? endAt : (doneAt !== null ? doneAt : lastEv)) - t0;
return { kind: "timing", reached_target: Math.abs(y - target) < 1, final_scrollY: y, scroll_events: ev.length, time_to_finish_ms: r3(dur), scrollend_fired: ended,
scroll_events_per_second: r3(ev.length / Math.max(0.001, (lastEv - t0) / 1000)), first_event_after_ms: ev.length ? r3(ev[0] - t0) : null, frames_during: describe(f, 4500) };
});
// ------------------------------------------------------------------------------------------------------------------ 5. readback timings, 1024x1024
function hash(u8) { let h1 = 0xdeadbeef, h2 = 0x41c6ce57; for (let i = 0; i < u8.length; i += 7) { h1 = Math.imul(h1 ^ u8[i], 2654435761); h2 = Math.imul(h2 ^ u8[i], 1597334677); } return ((h2 >>> 0).toString(16) + (h1 >>> 0).toString(16)); }
await phase("canvas2d_getImageData_1024", async () => {
const times = [], first = {};
const c = document.createElement("canvas"); c.width = c.height = 1024;
const g = c.getContext("2d");
const draw = () => {
const lg = g.createLinearGradient(0, 0, 1024, 1024); lg.addColorStop(0, "#f40"); lg.addColorStop(1, "#04f");
g.fillStyle = lg; g.fillRect(0, 0, 1024, 1024);
for (let i = 0; i < 300; i++) { g.fillStyle = "hsla(" + (i * 13 % 360) + ",70%,50%,.5)"; g.beginPath(); g.arc((i * 97) % 1024, (i * 61) % 1024, 20 + (i % 40), 0, 6.283); g.fill(); }
g.font = "30px sans-serif"; g.fillStyle = "#000"; g.fillText("compositor-visible probe", 40, 500);
};
draw();
let d = null;
for (let i = 0; i < 6; i++) { const s = now(); d = g.getImageData(0, 0, 1024, 1024); times.push(now() - s); if (i === 0) first.ms = now() - s; }
const one = []; for (let i = 0; i < 6; i++) { draw(); const s = now(); g.getImageData(0, 0, 1, 1); one.push(now() - s); }
const s2 = now(); c.toDataURL("image/png"); const png = now() - s2;
return { kind: "timing", first_getImageData_ms: r3(first.ms), repeat_getImageData_ms_p50: r3(q(times.slice(1), 0.5)), draw_then_1x1_getImageData_ms_p50: r3(q(one, 0.5)),
toDataURL_png_ms: r3(png), bytes_hash_value: hash(d.data), willReadFrequently: g.getContextAttributes ? g.getContextAttributes().willReadFrequently : null };
});
await phase("webgl_readPixels_1024", async () => {
const { c, gl, t } = await glCanvas(1024, 1024);
const px = new Uint8Array(1024 * 1024 * 4), times = [], one = [];
gl.viewport(0, 0, 1024, 1024);
for (let i = 0; i < 6; i++) { gl.uniform1f(t, 1.5); gl.drawArrays(gl.TRIANGLES, 0, 6); const s = now(); gl.readPixels(0, 0, 1024, 1024, gl.RGBA, gl.UNSIGNED_BYTE, px); times.push(now() - s); }
const p1 = new Uint8Array(4);
for (let i = 0; i < 6; i++) { gl.drawArrays(gl.TRIANGLES, 0, 6); const s = now(); gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, p1); one.push(now() - s); }
const info = gl.getExtension("WEBGL_debug_renderer_info");
const out = { kind: "timing", first_readPixels_ms: r3(times[0]), repeat_readPixels_ms_p50: r3(q(times.slice(1), 0.5)), draw_then_1px_readPixels_ms_p50: r3(q(one, 0.5)), bytes_hash_value: hash(px),
renderer_value: info ? gl.getParameter(info.UNMASKED_RENDERER_WEBGL) : gl.getParameter(gl.RENDERER) };
c.remove();
return out;
});
result.finished_at = Date.now();
result.visibility_at_end = document.visibilityState;
await fetch("/result", { method: "POST", body: JSON.stringify(result) });
})().catch((e) => fetch("/result", { method: "POST", body: JSON.stringify({ fatal: String((e && e.message) || e) }) }));
+433
View File
@@ -0,0 +1,433 @@
"""HUNT ONLY (branch hunt/cpu-render-path, never merged): can a PAGE tell software compositing ("WebRender (Software)") from our hardware path?
python scripts/hunt_compositor_visible.py run --arm ours|ours_vmretail|stockheaded|retail [--binary B] [--retail-from DIR] --out DIR
python scripts/hunt_compositor_visible.py facts --arm ... (same) --out DIR # Troubleshoot, effective prefs, the OS's own refresh rate
python scripts/hunt_compositor_visible.py table DIR
Earlier rAF data showed 60 fps in one arm and 50-53 in another. What decides the rate of requestAnimationFrame on Windows (code of this tree):
- the vsync source is gfx/thebes/gfxWindowsPlatform.cpp D3DVsyncSource. Its RATE is read once from DwmGetCompositionTimingInfo (lines 1466-1480: the DWM's
rateRefresh, or 60 Hz if the call fails). Its LOOP (lines 1605-1646) waits on IDXGIOutput::WaitForVBlank; if that fails, or returns in under 1 ms ("vblank
might return instantly when running headless, monitor powering off"), it schedules a SOFTWARE vsync with that same rate (ScheduleSoftwareVsync, line 1520);
- layout.frame_rate > 0 forces SoftwareVsyncSource at that rate; -1 (default) is the hardware source, with 60 Hz only when the hardware source fails
(gfx/thebes/gfxPlatform.cpp:3462-3516, GetDefaultFrameRate() == 60);
- privacy.resistFingerprinting with RFPTarget::FrameRate makes layout.frame_rate read as 60 (gfxPlatform.cpp LayoutFrameRateFromPrefs).
So a browser whose vsync is the DWM/WaitForVBlank of a virtual display runs at that display's refresh rate and jitter, and one on the software fallback runs on an exact
60.00 Hz timer. `run` measures what the page sees; `facts` reads what the OS and Troubleshoot say (graphics.monitors[].refreshRate is Screen::GetRefreshRate, the OS rate;
the effective layout.frame_rate and gfx.vsync.* prefs; the layer manager) and PowerShell's Win32_VideoController.CurrentRefreshRate. Which vsync source Gecko picked is not exposed to
a page or to Troubleshoot: it is inferred from the interval distribution (an exact 16.667 ms with a tight p5..p95 is a timer; a hardware wait has the display's period and jitter).
`run` launches ONE browser of the arm, opens a page of this script's local server and lets it measure for about 20 s (scripts/hunt_compositor_probe.js): requestAnimationFrame
alone (5 s: interval p5/p50/p95, fps, dropped frames, the interval buckets, now - timestamp), with a CSS animation (4 s), with a WebGL animation (2 s free + 2 s with a synchronous
readback every frame), a smooth scrollTo of a long page (scroll events per second, time to finish, scrollend), canvas 2D getImageData on 1024x1024 after drawing, WebGL
readPixels of 1024x1024, matchMedia (update: fast), screen refresh hints, the resolution of performance.now(). The arms:
ours invisible_playwright, headless=True (on Windows a headed Firefox on a hidden desktop), the declared persona
ours_vmretail ours with the prefs of hunt_vmretail.py build (HUNT_VMRETAIL_PREFS): retail's VM decisions, WebRender software without D3D11, WebGL on WARP
stockheaded stock Playwright's firefox, headless=False
retail Mozilla's Firefox 159.0 launched by hand (hunt_first_run.py fetch-retail): subprocess, -no-remote, a fresh profile, no automation, the page posts its result
`table` prints, per arm, every measurement, then ours and ours_vmretail against retail (and the other pairs) with a DIFFERS mark. Each row says whether it is TIMING (a measurement:
a difference is a rate or a latency a page can time) or VALUE (a declared or fixed property: a difference is a different answer to the same question).
"""
from __future__ import annotations
import argparse
import asyncio
import contextlib
import json
import os
import shutil
import subprocess
import sys
import tempfile
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
import hunt_cpu_per_browser as hunt # noqa: E402
import hunt_cpu_render_path as rp # noqa: E402
ARMS = ["ours", "ours_vmretail", "stockheaded", "retail"]
WAIT_S = 90
class Page(BaseHTTPRequestHandler):
result: Optional[str] = None
def _send(self, body: bytes, ctype: str) -> None:
self.send_response(200)
self.send_header("Content-Type", ctype)
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(body)
def do_GET(self): # noqa: N802
if self.path.startswith("/probe.js"):
self._send((HERE / "hunt_compositor_probe.js").read_bytes(), "text/javascript; charset=utf-8")
else:
self._send(b'<!doctype html><meta charset=utf-8><title>compositor</title><body style="margin:0"><script src="/probe.js"></script></body>',
"text/html; charset=utf-8")
def do_POST(self): # noqa: N802
n = int(self.headers.get("Content-Length") or 0)
Page.result = self.rfile.read(n).decode("utf-8", "replace")
self._send(b"ok", "text/plain")
def log_message(self, *a): # noqa: D102
pass
def serve() -> Tuple[ThreadingHTTPServer, str]:
httpd = ThreadingHTTPServer(("127.0.0.1", 0), Page)
httpd.daemon_threads = True
threading.Thread(target=httpd.serve_forever, daemon=True).start()
return httpd, "http://127.0.0.1:%d/" % httpd.server_address[1]
def kill_firefox() -> None:
rp.kill_firefox()
def retail_exe(args) -> Tuple[Path, str]:
info = json.loads((Path(args.retail_from) / "retail.json").read_text(encoding="utf-8"))
return Path(info["exe"]), info["note"]
def os_facts() -> Dict[str, Any]:
"""What the machine itself says about its display (not through Firefox)."""
out: Dict[str, Any] = {}
if sys.platform == "win32":
cmd = ("Get-CimInstance Win32_VideoController | Select-Object Name,CurrentRefreshRate,MaxRefreshRate,MinRefreshRate,VideoModeDescription,"
"AdapterCompatibility,DriverVersion | ConvertTo-Json -Compress")
try:
r = subprocess.run(["powershell", "-NoProfile", "-NonInteractive", "-Command", cmd], capture_output=True, text=True, timeout=60)
out["Win32_VideoController"] = json.loads(r.stdout) if r.stdout.strip() else r.stderr[:300]
except Exception as exc: # noqa: BLE001
out["Win32_VideoController"] = "%s: %s" % (type(exc).__name__, exc)
try:
import ctypes
out["session_is_remote"] = bool(ctypes.windll.user32.GetSystemMetrics(0x1000)) # SM_REMOTESESSION
except Exception: # noqa: BLE001
pass
return out
# ----------------------------------------------------------------------------------------------------------------------------- run
async def ours_run(binary: str, url: str, prefs: Optional[dict]) -> None:
from invisible_playwright.async_api import InvisiblePlaywright
async with InvisiblePlaywright(seed=100, binary_path=binary, headless=True, locale="en-US", timezone="Europe/Rome", extra_prefs=prefs) as browser:
page = await browser.new_page()
await page.goto(url, wait_until="load", timeout=60000)
await wait_result()
async def stock_run(url: str) -> None:
import importlib
pw = await importlib.import_module("playwright.async_api").async_playwright().start() # by name: the fork's guard forbids a static import
browser = None
try:
browser = await pw.firefox.launch(headless=False, firefox_user_prefs={"fission.autostart": True})
page = await browser.new_page()
await page.goto(url, wait_until="load", timeout=60000)
await wait_result()
finally:
if browser is not None:
with contextlib.suppress(Exception):
await browser.close()
with contextlib.suppress(Exception):
await pw.stop()
async def wait_result() -> None:
end = time.time() + WAIT_S
while Page.result is None and time.time() < end:
await asyncio.sleep(0.5)
def run(args) -> int:
args.out.mkdir(parents=True, exist_ok=True)
httpd, url = serve()
Page.result = None
kill_firefox()
note, err = "", ""
t0 = time.time()
try:
if args.arm == "retail":
exe, note = retail_exe(args)
profile = Path(tempfile.mkdtemp(prefix="hunt-compositor-retail-"))
proc = subprocess.Popen([str(exe), "-no-remote", "-profile", str(profile), url], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
try:
end = time.time() + WAIT_S
while Page.result is None and time.time() < end:
time.sleep(0.5)
finally:
kill_firefox()
with contextlib.suppress(Exception):
proc.wait(timeout=10)
elif args.arm == "stockheaded":
asyncio.run(stock_run(url))
else:
asyncio.run(ours_run(args.binary, url, hunt.arm_prefs(args.arm)))
except BaseException as exc: # noqa: BLE001
err = "%s: %s" % (type(exc).__name__, str(exc)[:400])
kill_firefox()
httpd.shutdown()
data: Dict[str, Any] = {}
if Page.result:
try:
data = json.loads(Page.result)
except ValueError as exc:
err = err or "unreadable result: %s" % exc
else:
err = err or "the page posted nothing in %d s" % WAIT_S
doc = {"arm": args.arm, "note": note, "error": err, "wall_s": time.time() - t0, "probe": data, "os": os_facts()}
(args.out / ("%s.json" % args.arm)).write_text(json.dumps(doc, indent=1), encoding="utf-8")
print("arm %s: %s; probe took %.1f s of wall time%s" % (args.arm, "result received" if data else "NO RESULT", doc["wall_s"], ("; ERROR " + err) if err else ""))
if data.get("errors"):
print(" page errors: %s" % data["errors"])
print_arm(doc)
return 1 if err else 0
# -------------------------------------------------------------------------------------------------------------------------- facts
def facts(args) -> int:
out = args.out / ("%s-facts" % args.arm)
out.mkdir(parents=True, exist_ok=True)
kill_firefox()
report: Dict[str, Any] = {"arm": args.arm}
async def ours_like():
async with rp.launched(args.arm, args.binary or "", marionette=True) as browser:
page = await browser.new_page()
await page.goto("about:blank")
await asyncio.get_running_loop().run_in_executor(None, rp.privileged_route, out, report)
try:
if args.arm == "retail":
exe, note = retail_exe(args)
report["note"] = note
profile = Path(tempfile.mkdtemp(prefix="hunt-compositor-facts-"))
env = dict(os.environ, MOZ_REMOTE_ALLOW_SYSTEM_ACCESS="1")
proc = subprocess.Popen([str(exe), "-no-remote", "-marionette", "-remote-allow-system-access", "-profile", str(profile), "about:blank"], env=env,
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
try:
rp.privileged_route(out, report)
finally:
kill_firefox()
with contextlib.suppress(Exception):
proc.wait(timeout=10)
else:
asyncio.run(ours_like())
except BaseException as exc: # noqa: BLE001
report["error"] = "%s: %s" % (type(exc).__name__, str(exc)[:300])
kill_firefox()
(out / "report.json").write_text(json.dumps(report, indent=1, default=str), encoding="utf-8")
print_facts(args.arm, out)
return 0
def read_facts(out: Path) -> Dict[str, Any]:
d: Dict[str, Any] = {}
sf, pf = out / "troubleshoot.json", out / "effective_prefs.json"
if sf.is_file():
data = json.loads(sf.read_text(encoding="utf-8"))
g = data.get("graphics", {})
d["monitors"] = g.get("monitors")
d["layer_manager"] = (g.get("windowLayerManagerType"), g.get("windowLayerManagerRemote"))
d["window_protocol"] = g.get("windowProtocol")
d["adapter"] = g.get("adapterDescription")
d["features"] = {f.get("name"): f.get("status") for f in (g.get("features") or []) if isinstance(f, dict)}
if pf.is_file():
prefs = json.loads(pf.read_text(encoding="utf-8"))
d["prefs"] = {n: prefs[n][1] for n in prefs if n.startswith(("layout.frame_rate", "gfx.vsync", "gfx.webrender.software", "gfx.canvas", "layout.throttled", "dom.animations", "general.smoothScroll",
"apz.", "privacy.resistFingerprinting", "privacy.baselineFingerprintingProtection"))}
return d
def print_facts(arm: str, out: Path) -> None:
d = read_facts(out)
print("-" * 110)
print("FACTS of %s (Troubleshoot, effective prefs)" % arm)
if not d:
print(" nothing read (see report.json)")
return
print(" monitors (graphics.monitors, Screen::GetRefreshRate = the OS rate): %s" % json.dumps(d.get("monitors")))
print(" layer manager type / remote: %s; window protocol: %s; adapter: %s" % (d.get("layer_manager"), d.get("window_protocol"), d.get("adapter")))
for name in ("Compositing", "WebRender", "WebRender (Software)", "Direct3D 11 Compositing", "GPU Process"):
if name in (d.get("features") or {}):
print(" feature %-28s %s" % (name, d["features"][name]))
for n, v in sorted((d.get("prefs") or {}).items()):
print(" pref %s = %s" % (n, v))
# --------------------------------------------------------------------------------------------------------------------------- table
# (label, path, kind, comparison): comparison is ("rel", ratio) | ("abs", amount) | ("fps", ...) | ("eq",)
METRICS: List[Tuple[str, str, str, Tuple]] = [
("rAF idle: fps", "phases.raf_idle_5s.fps", "timing", ("fps",)),
("rAF idle: interval p5 ms", "phases.raf_idle_5s.interval_ms_p5", "timing", ("ms", 1.0, 0.15)),
("rAF idle: interval p50 ms", "phases.raf_idle_5s.interval_ms_p50", "timing", ("ms", 1.0, 0.15)),
("rAF idle: interval p95 ms", "phases.raf_idle_5s.interval_ms_p95", "timing", ("ms", 2.0, 0.25)),
("rAF idle: dropped frames", "phases.raf_idle_5s.dropped_frames", "timing", ("count",)),
("rAF idle: now - timestamp p50 ms", "phases.raf_idle_5s.now_minus_timestamp_ms_p50", "timing", ("ms", 1.0, 0.5)),
("rAF idle: intervals <14 / 14-15.5 / 15.5-18 / 18-20 / 20-25 / >25 ms", "phases.raf_idle_5s.buckets", "timing", ("buckets",)),
("rAF + CSS animation: fps", "phases.raf_with_css_animation_4s.fps", "timing", ("fps",)),
("rAF + CSS animation: interval p95 ms", "phases.raf_with_css_animation_4s.interval_ms_p95", "timing", ("ms", 2.0, 0.25)),
("rAF + CSS animation: dropped frames", "phases.raf_with_css_animation_4s.dropped_frames", "timing", ("count",)),
("rAF + CSS animation: animations running (value)", "phases.raf_with_css_animation_4s.running_animations", "value", ("eq",)),
("rAF + WebGL animation: fps", "phases.raf_with_webgl_animation_4s.free.fps", "timing", ("fps",)),
("rAF + WebGL animation: interval p95 ms", "phases.raf_with_webgl_animation_4s.free.interval_ms_p95", "timing", ("ms", 2.0, 0.25)),
("rAF + WebGL animation: dropped frames", "phases.raf_with_webgl_animation_4s.free.dropped_frames", "timing", ("count",)),
("WebGL animation + readback each frame: fps", "phases.raf_with_webgl_animation_4s.with_sync_readback_every_frame.fps", "timing", ("fps",)),
("WebGL 1-pixel sync readback per frame p50 ms", "phases.raf_with_webgl_animation_4s.sync_readback_ms_p50", "timing", ("ms", 2.0, 0.5)),
("smooth scroll: reached target (value)", "phases.smooth_scroll.reached_target", "value", ("eq",)),
("smooth scroll: scrollend fired (value)", "phases.smooth_scroll.scrollend_fired", "value", ("eq",)),
("smooth scroll: scroll events", "phases.smooth_scroll.scroll_events", "timing", ("count",)),
("smooth scroll: scroll events per second", "phases.smooth_scroll.scroll_events_per_second", "timing", ("rel", 0.3)),
("smooth scroll: time to finish ms", "phases.smooth_scroll.time_to_finish_ms", "timing", ("ms", 100.0, 0.3)),
("smooth scroll: rAF fps while it runs", "phases.smooth_scroll.frames_during.fps", "timing", ("fps",)),
("canvas2d 1024: first getImageData ms", "phases.canvas2d_getImageData_1024.first_getImageData_ms", "timing", ("ms", 3.0, 0.5)),
("canvas2d 1024: repeat getImageData p50 ms", "phases.canvas2d_getImageData_1024.repeat_getImageData_ms_p50", "timing", ("ms", 3.0, 0.5)),
("canvas2d 1024: draw then 1x1 getImageData p50 ms", "phases.canvas2d_getImageData_1024.draw_then_1x1_getImageData_ms_p50", "timing", ("ms", 3.0, 0.5)),
("canvas2d 1024: toDataURL png ms", "phases.canvas2d_getImageData_1024.toDataURL_png_ms", "timing", ("ms", 5.0, 0.5)),
("canvas2d 1024: pixels hash (value)", "phases.canvas2d_getImageData_1024.bytes_hash_value", "value", ("eq",)),
("webgl 1024: first readPixels ms", "phases.webgl_readPixels_1024.first_readPixels_ms", "timing", ("ms", 3.0, 0.5)),
("webgl 1024: repeat readPixels p50 ms", "phases.webgl_readPixels_1024.repeat_readPixels_ms_p50", "timing", ("ms", 3.0, 0.5)),
("webgl 1024: draw then 1px readPixels p50 ms", "phases.webgl_readPixels_1024.draw_then_1px_readPixels_ms_p50", "timing", ("ms", 2.0, 0.5)),
("webgl 1024: pixels hash (value)", "phases.webgl_readPixels_1024.bytes_hash_value", "value", ("eq",)),
("webgl: unmasked renderer (value)", "phases.webgl_readPixels_1024.renderer_value", "value", ("eq",)),
]
VALUE_KEYS = ["update_fast", "update_slow", "update_none", "prefers_reduced_motion", "hover", "any_pointer_fine", "dynamic_range_high", "color_gamut_p3", "display_mode_browser", "screen", "dpr",
"visibility", "hasFocus", "hidden", "scroll_behavior_supported", "scrollend_supported", "screen_refresh_property", "screen_keys_with_rate", "performance_now_min_step_ms",
"performance_now_decimals_seen", "date_now_min_step_ms", "hardwareConcurrency"]
def dig(doc: Dict[str, Any], path: str) -> Any:
cur: Any = doc.get("probe", {})
for part in path.split("."):
if not isinstance(cur, dict) or part not in cur:
return None
cur = cur[part]
return cur
def differs(spec: Tuple, a: Any, b: Any) -> bool:
if a is None or b is None:
return a != b
kind = spec[0]
if kind == "eq":
return a != b
if kind == "buckets":
ta, tb = sum(a.values()) or 1, sum(b.values()) or 1
return any(abs(a[k] / ta - b[k] / tb) > 0.25 for k in a)
if kind == "fps":
return abs(a - b) > max(2.0, 0.05 * max(a, b))
if kind == "count":
return abs(a - b) > max(3.0, 0.3 * max(a, b))
if kind == "rel":
lo, hi = min(a, b), max(a, b)
return hi > 0 and (lo == 0 or hi / lo > 1 + spec[1])
if kind == "ms":
floor, rel = spec[1], spec[2]
return abs(a - b) > max(floor, rel * max(abs(a), abs(b))) # above `floor` ms AND above `rel` of the larger value
return a != b
def fmt(v: Any) -> str:
if v is None:
return "-"
if isinstance(v, dict):
return "/".join(str(x) for x in v.values())
if isinstance(v, list):
return json.dumps(v)
return str(v)
def print_arm(doc: Dict[str, Any]) -> None:
print("-" * 110)
print("ARM %s%s" % (doc["arm"], (" (" + doc["note"][:100] + ")") if doc.get("note") else ""))
for label, path, kind, _spec in METRICS:
print(" %-9s %-64s %s" % (kind.upper(), label, fmt(dig(doc, path))))
vals = doc.get("probe", {}).get("values", {})
for k in VALUE_KEYS:
print(" %-9s %-64s %s" % ("VALUE", k, fmt(vals.get(k))))
print(" OS: %s" % json.dumps(doc.get("os"))[:400])
sys.stdout.flush()
def table(root: Path) -> int:
docs: Dict[str, Dict[str, Any]] = {}
for a in ARMS:
p = root / ("%s.json" % a)
if p.is_file():
docs[a] = json.loads(p.read_text(encoding="utf-8"))
if not docs:
print("no results in %s" % root)
return 1
arms = [a for a in ARMS if a in docs]
print("=" * 140)
print("WHAT A PAGE READS OF THE COMPOSITOR: %s" % ", ".join("%s%s" % (a, " (ERROR %s)" % docs[a]["error"][:60] if docs[a]["error"] else "") for a in arms))
for a in arms:
if docs[a].get("note"):
print(" %s: %s" % (a, docs[a]["note"][:200]))
print("=" * 140)
print("%-9s %-62s" % ("kind", "measurement") + "".join(" %-15s" % a for a in arms))
for label, path, kind, _spec in METRICS:
print("%-9s %-62s" % (kind.upper(), label[:62]) + "".join(" %-15s" % fmt(dig(docs[a], path))[:15] for a in arms))
for k in VALUE_KEYS:
print("%-9s %-62s" % ("VALUE", k) + "".join(" %-15s" % fmt(docs[a].get("probe", {}).get("values", {}).get(k))[:15] for a in arms))
for pair in (("ours", "retail"), ("ours_vmretail", "retail"), ("ours", "ours_vmretail"), ("stockheaded", "retail")):
if pair[0] not in docs or pair[1] not in docs:
continue
a, b = docs[pair[0]], docs[pair[1]]
print("=" * 140)
print("%s AGAINST %s: what differs" % (pair[0].upper(), pair[1].upper()))
n_t = n_v = 0
for label, path, kind, spec in METRICS:
va, vb = dig(a, path), dig(b, path)
if differs(spec, va, vb):
n_t += kind == "timing"
n_v += kind == "value"
print(" DIFFERS %-8s %-62s %s: %s | %s: %s" % ("TIMING-ONLY" if kind == "timing" else "VALUE", label[:62], pair[0], fmt(va), pair[1], fmt(vb)))
for k in VALUE_KEYS:
va, vb = a.get("probe", {}).get("values", {}).get(k), b.get("probe", {}).get("values", {}).get(k)
if va != vb:
n_v += 1
print(" DIFFERS %-8s %-62s %s: %s | %s: %s" % ("VALUE", k, pair[0], fmt(va), pair[1], fmt(vb)))
print(" -> %d timing measurement(s) differ (timing-only), %d value(s) differ" % (n_t, n_v))
# the facts, if collected
for a in arms:
f = root / ("%s-facts" % a)
if f.is_dir():
print_facts(a, f)
return 0
def main() -> int:
ap = argparse.ArgumentParser()
sub = ap.add_subparsers(dest="cmd", required=True)
for name in ("run", "facts"):
p = sub.add_parser(name)
p.add_argument("--arm", choices=ARMS, required=True)
p.add_argument("--binary", default=os.environ.get("INVPW_BINARY_PATH", ""))
p.add_argument("--retail-from", default="")
p.add_argument("--out", type=Path, required=True)
t = sub.add_parser("table")
t.add_argument("root", type=Path)
args = ap.parse_args()
if args.cmd == "table":
return table(args.root)
if args.arm.startswith("ours") and not args.binary:
ap.error("the ours arms need --binary (or INVPW_BINARY_PATH)")
if args.arm == "retail" and not args.retail_from:
ap.error("the arm retail needs --retail-from (hunt_first_run.py fetch-retail)")
return run(args) if args.cmd == "run" else facts(args)
if __name__ == "__main__":
sys.exit(main())
+599
View File
@@ -0,0 +1,599 @@
"""HUNT ONLY (branch hunt/cpu-render-path, never merged): the right baseline for the PARENT's CPU, one browser, 20 seconds, with a window.
python scripts/hunt_cpu_baseline.py --arm retail [--retail-binary firefox.exe] [--retail-version 159.0] --out DIR
python scripts/hunt_cpu_baseline.py --arm ours --binary "$FF" --out DIR
python scripts/hunt_cpu_baseline.py --arm ours_reused --binary "$FF" --out DIR
python scripts/hunt_cpu_baseline.py --compare DIR
The earlier hunt compared ours with stock PLAYWRIGHT's Firefox (a build with automation: Juggler, playwright.cfg, its own prefs), whose parent
might do less work for that very reason. Here the reference is a Firefox nobody drives:
retail Firefox retail, launched by hand: subprocess.Popen([firefox.exe, -no-remote, -profile <fresh dir>, <url of the scene>]), no automation
prefs, no Playwright, the environment untouched. The binary is Mozilla's own installer of the stable release
(https://archive.mozilla.org/pub/firefox/releases/<version>/win64/en-US/Firefox Setup <version>.exe, checked against the release's
SHA256SUMS, unpacked with 7-Zip: no install, nothing written outside the work dir). If that cannot be done the arm falls back to
the firefox-1572 that `playwright install firefox` put on the machine and SAYS SO on its first line: that one is not retail.
ours our binary, invisible_playwright, headless=True (on Windows a headed Firefox on a hidden desktop), a fresh temporary profile.
ours_reused ours twice on the SAME persistent profile (profile_dir=): launch 1 is a fresh profile (measured too: it answers "does profile_dir
itself cost anything?"), launch 2 is the same profile used again, and is the one this arm exists for.
The scene is the one of scripts/hunt_cpu_per_browser.py (an RTCPeerConnection gathering, 200 DOM elements, one 2D canvas frame) with one addition:
when it is done the page tells the server (/done/...) and, 300 ms later, navigates to the next copy (/p/<arm>/<n+1>), so a browser nobody drives
keeps the same load for the whole window. The server counts the scenes each arm completed: CPU per scene is the number to compare when the arms
turn the scene at different speeds.
THE WINDOW. t0 = just before the launch; the window is [t0, t0 + 20 s] for every arm (startup included: that is also what retail pays), and the
STEADY window is the last 10 s. The sampler is the one of hunt_cpu_per_browser.py (NtQuerySystemInformation every 250 ms, the command line of each
firefox pid read once at first sight). CPU per PROCESS TYPE comes from it. CPU per THREAD comes from a watcher thread of this script: every 0.5 s
psutil's Process.threads() of every firefox process that is not a tab (the parent, the GPU process, socket, rdd, utility) with the thread's NAME
(GetThreadDescription; Firefox names its threads) and cumulative user+kernel time; a thread's CPU in a window is read like a process's (the last
sample at or before each instant, 0 before it was first seen). Threads are grouped by name with a trailing number removed ("StyleThread#3" ->
"StyleThread"). A thread that lived and died between two polls is not seen: the report prints, per process type, the process CPU of the sampler, the
sum over its threads and the difference.
"""
from __future__ import annotations
import argparse
import asyncio
import bisect
import contextlib
import hashlib
import json
import os
import re
import shutil
import statistics
import subprocess
import sys
import tempfile
import threading
import time
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
import hunt_cpu_per_browser as hunt # noqa: E402
ARMS = ["retail", "ours", "ours_reused", "ours_swwr", "ours_vmretail", "stockheaded"]
WINDOW_S = 20.0
TYPES = hunt.TYPES
LOOP = """<script>
(async () => {
const m = location.pathname.match(/^\\/p\\/([^/]+)\\/(\\d+)$/);
if (!m) return;
let state = "error";
try { state = await window.__ready; } catch (e) { state = "error:" + e; }
try { await fetch("/done/" + m[1] + "/" + m[2] + "?" + encodeURIComponent(state), {cache: "no-store"}); } catch (e) {}
await new Promise(r => setTimeout(r, 300));
location.replace("/p/" + m[1] + "/" + (parseInt(m[2], 10) + 1));
})();
</script>
"""
PAGE = hunt.PAGE + LOOP
class Scene(BaseHTTPRequestHandler):
timeout = 10
done: Dict[str, List[str]] = {}
lock = threading.Lock()
def do_GET(self): # noqa: N802
if self.path.startswith("/done/"):
parts = self.path.split("?")[0].split("/")
state = self.path.split("?", 1)[1] if "?" in self.path else ""
with Scene.lock:
Scene.done.setdefault(parts[2] if len(parts) > 2 else "?", []).append(state)
self.send_response(204)
self.send_header("Cache-Control", "no-store")
self.end_headers()
return
if not self.path.startswith("/p/"):
self.send_response(404)
self.send_header("Content-Length", "0")
self.end_headers()
return
body = PAGE.encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(body)
def log_message(self, *a): # noqa: D102
pass
# ---------------------------------------------------------------------------------------------------------------- the threads
def thread_names_windows():
import ctypes
from ctypes import wintypes
k32 = ctypes.WinDLL("kernel32", use_last_error=True)
k32.OpenThread.restype = wintypes.HANDLE
k32.OpenThread.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
k32.GetThreadDescription.restype = ctypes.c_long
k32.GetThreadDescription.argtypes = [wintypes.HANDLE, ctypes.POINTER(ctypes.c_void_p)]
k32.CloseHandle.argtypes = [wintypes.HANDLE]
k32.LocalFree.argtypes = [ctypes.c_void_p]
def name_of(pid: int, tid: int) -> str:
h = k32.OpenThread(0x0800, False, tid) # THREAD_QUERY_LIMITED_INFORMATION
if not h:
return ""
try:
ptr = ctypes.c_void_p()
if k32.GetThreadDescription(h, ctypes.byref(ptr)) < 0 or not ptr.value:
return ""
try:
return ctypes.wstring_at(ptr.value)
finally:
k32.LocalFree(ptr)
finally:
k32.CloseHandle(h)
return name_of
def thread_names_linux():
def name_of(pid: int, tid: int) -> str:
try:
return Path("/proc/%d/task/%d/comm" % (pid, tid)).read_text().strip()
except OSError:
return ""
return name_of
def normalise(name: str) -> str:
return re.sub(r"[\s#]*\d+$", "", name) or "(unnamed)"
class Watcher(threading.Thread):
"""Per-thread cumulative CPU of every firefox process that is not a tab, every 0.5 s."""
def __init__(self) -> None:
super().__init__(daemon=True)
self.stop_flag = threading.Event()
self.kinds: Dict[int, str] = {}
self.series: Dict[Tuple[int, int], Dict[str, Any]] = {}
self.name_of = thread_names_windows() if sys.platform == "win32" else thread_names_linux()
self.error = ""
def poll(self) -> None:
import psutil
now = time.time()
for p in psutil.process_iter(["pid", "name"]):
if not (p.info.get("name") or "").lower().startswith("firefox"):
continue
pid = p.info["pid"]
if pid not in self.kinds:
try:
self.kinds[pid] = hunt.classify(p.cmdline())
except Exception: # noqa: BLE001
continue
if self.kinds[pid] == "tab":
continue
try:
threads = p.threads()
except Exception: # noqa: BLE001
continue
for th in threads:
key = (pid, th.id)
row = self.series.get(key)
if row is None:
row = self.series[key] = {"name": "", "kind": self.kinds[pid], "t": [], "c": []}
if not row["name"]:
row["name"] = self.name_of(pid, th.id)
row["t"].append(now)
row["c"].append(th.user_time + th.system_time)
def run(self) -> None:
while not self.stop_flag.is_set():
try:
self.poll()
except Exception as exc: # noqa: BLE001
self.error = "%s: %s" % (type(exc).__name__, exc)
self.stop_flag.wait(0.5)
def used(self, a: float, b: float) -> List[Dict[str, Any]]:
out = []
for (pid, tid), row in self.series.items():
def at(t, row=row):
i = bisect.bisect_right(row["t"], t)
return row["c"][i - 1] if i else 0.0
out.append({"pid": pid, "tid": tid, "kind": row["kind"], "name": row["name"] or "?", "cpu_s": max(0.0, at(b) - at(a))})
return out
# ------------------------------------------------------------------------------------------------------------ the retail binary
def sha256_of(path: Path) -> str:
h = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(1 << 20), b""):
h.update(chunk)
return h.hexdigest()
def fetch(url: str, dest: Path, timeout: int = 180) -> None:
req = urllib.request.Request(url, headers={"User-Agent": "invisible-hunt"})
with urllib.request.urlopen(req, timeout=timeout) as resp, open(dest, "wb") as f:
shutil.copyfileobj(resp, f, 1 << 20)
def retail_from_mozilla(version: str, work: Path) -> Tuple[Optional[Path], str]:
base = "https://archive.mozilla.org/pub/firefox/releases/%s" % version
name = "Firefox Setup %s.exe" % version
installer = work / "installer.exe"
try:
fetch("%s/win64/en-US/%s" % (base, name.replace(" ", "%20")), installer)
except Exception as exc: # noqa: BLE001
return None, "download failed: %s: %s" % (type(exc).__name__, str(exc)[:200])
digest = sha256_of(installer)
verdict = "sha256 %s, NOT checked (no SHA256SUMS)" % digest
try:
sums = work / "SHA256SUMS"
fetch(base + "/SHA256SUMS", sums, 60)
want = [l.split()[0] for l in sums.read_text(encoding="utf-8", errors="replace").splitlines()
if l.strip().endswith("win64/en-US/" + name)]
if want:
if want[0].lower() != digest:
return None, "SHA256 MISMATCH: installer %s, SHA256SUMS %s" % (digest, want[0])
verdict = "sha256 %s, equal to the release's SHA256SUMS" % digest
else:
verdict = "sha256 %s, its line not found in SHA256SUMS" % digest
except Exception as exc: # noqa: BLE001
verdict += " (SHA256SUMS: %s)" % type(exc).__name__
seven = shutil.which("7z") or next((p for p in (r"C:\Program Files\7-Zip\7z.exe", r"C:\Program Files (x86)\7-Zip\7z.exe") if os.path.isfile(p)), None)
if not seven:
return None, "7-Zip not found, %s" % verdict
target = work / "unpacked"
run = subprocess.run([seven, "x", "-y", "-o" + str(target), str(installer)], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=300)
exe = next(iter(sorted(target.rglob("firefox.exe"))), None)
if exe is None:
return None, "7z exit %d and no firefox.exe in the installer; %s" % (run.returncode, verdict)
return exe, "Mozilla's installer %s (%s)" % (name, verdict)
def retail_from_playwright() -> Tuple[Optional[Path], str]:
roots = [os.environ.get("PLAYWRIGHT_BROWSERS_PATH") or "", str(Path(os.environ.get("LOCALAPPDATA", "")) / "ms-playwright"),
str(Path.home() / ".cache" / "ms-playwright")]
for r in roots:
if r and Path(r).is_dir():
for exe in sorted(Path(r).glob("firefox-*/firefox/firefox.exe")) + sorted(Path(r).glob("firefox-*/firefox/firefox")):
return exe, "NOT RETAIL: Playwright's %s, launched by hand" % exe.parent.parent.name
return None, "no Playwright firefox found"
def application_ini(exe: Path) -> str:
ini = exe.parent / "application.ini"
if not ini.is_file():
return "no application.ini"
keys = {}
for line in ini.read_text(encoding="utf-8", errors="replace").splitlines():
if "=" in line and line.split("=")[0] in ("Version", "BuildID", "Name", "SourceStamp", "Vendor"):
keys[line.split("=")[0]] = line.split("=", 1)[1]
return ", ".join("%s=%s" % kv for kv in keys.items())
def find_retail(args, work: Path) -> Tuple[Optional[Path], str]:
if args.retail_binary:
return Path(args.retail_binary), "given: %s" % args.retail_binary
exe, why = retail_from_mozilla(args.retail_version, work)
if exe:
return exe, why
print("retail from Mozilla impossible (%s); falling back to Playwright's firefox" % why)
exe, why2 = retail_from_playwright()
return exe, "%s (Mozilla: %s)" % (why2, why)
# --------------------------------------------------------------------------------------------------------------------- launches
def kill_tree(pid: int) -> None:
if sys.platform == "win32":
subprocess.run(["taskkill", "/F", "/T", "/PID", str(pid)], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
else:
import psutil
with contextlib.suppress(Exception):
parent = psutil.Process(pid)
for c in parent.children(recursive=True):
c.kill()
parent.kill()
def kill_firefox() -> None:
import psutil
for p in psutil.process_iter(["name"]):
if (p.info.get("name") or "").lower().startswith("firefox"):
with contextlib.suppress(Exception):
p.kill()
time.sleep(1)
def launch_retail(exe: Path, base: str, profile: Path, t0: float) -> None:
profile.mkdir(parents=True, exist_ok=True)
proc = subprocess.Popen([str(exe), "-no-remote", "-profile", str(profile), "%s/p/retail/0" % base],
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
try:
time.sleep(max(0.0, t0 + WINDOW_S - time.time()))
finally:
kill_tree(proc.pid)
with contextlib.suppress(Exception):
proc.wait(timeout=15)
async def stock_session(base: str, label: str, t0: float) -> None:
"""Stock Playwright's firefox, headed (what stock does with a window), one browser, the same scene."""
import importlib
pw = await importlib.import_module("playwright.async_api").async_playwright().start() # by name: the fork's guard forbids a static import
browser = None
try:
browser = await pw.firefox.launch(headless=False, firefox_user_prefs={"fission.autostart": True})
page = await browser.new_page()
await page.goto("%s/p/%s/0" % (base, label), wait_until="load", timeout=60000)
await asyncio.sleep(max(0.0, t0 + WINDOW_S - time.time()))
finally:
if browser is not None:
with contextlib.suppress(Exception):
await browser.close()
with contextlib.suppress(Exception):
await pw.stop()
async def ours_session(base: str, binary: str, label: str, profile_dir: Optional[str], t0: float, extra_prefs: Optional[dict] = None) -> None:
from invisible_playwright.async_api import InvisiblePlaywright
kwargs: Dict[str, Any] = {}
if profile_dir:
kwargs["profile_dir"] = profile_dir
if extra_prefs:
kwargs["extra_prefs"] = extra_prefs
async with InvisiblePlaywright(seed=100, binary_path=binary, headless=True, locale="en-US", timezone="Europe/Rome", **kwargs) as browser:
page = await browser.new_page()
await page.goto("%s/p/%s/0" % (base, label), wait_until="load", timeout=60000)
await asyncio.sleep(max(0.0, t0 + WINDOW_S - time.time()))
# ------------------------------------------------------------------------------------------------------------------ measuring
def by_type(sampler: hunt.Sampler, a: float, b: float) -> Tuple[Dict[str, float], int]:
series = hunt.Series(sampler.samples)
where, roots = hunt.roots_and_kinds(sampler.info)
out = {t: 0.0 for t in TYPES}
for pid, (_root, kind) in where.items():
out[kind] += series.used(pid, a, b)
return out, len(roots)
def measure(label: str, arm: str, key: str, launch) -> Dict[str, Any]:
"""One window: sampler + watcher around launch(t0), which returns when the browser is closed. `key` is the scene path the server counts."""
with Scene.lock:
Scene.done.pop(key, None)
sampler = hunt.Sampler()
sampler.start()
watcher = Watcher()
watcher.start()
t0 = time.time()
err = ""
try:
launch(t0)
except BaseException as exc: # noqa: BLE001
err = "%s: %s" % (type(exc).__name__, str(exc)[:400])
t_end = time.time()
time.sleep(0.8)
watcher.stop_flag.set()
watcher.join(5)
sampler.stop()
kill_firefox()
mid = t0 + WINDOW_S / 2
end = t0 + WINDOW_S
full, roots = by_type(sampler, t0, end)
steady, _ = by_type(sampler, mid, end)
series = hunt.Series(sampler.samples)
client_full = sum(series.used(pid, t0, end) for pid, v in sampler.info.items() if v[0] in ("client", "client-child"))
threads_full, threads_steady = watcher.used(t0, end), watcher.used(mid, end)
steady_by = {(r["pid"], r["tid"]): r["cpu_s"] for r in threads_steady}
for r in threads_full:
r["steady_s"] = steady_by.get((r["pid"], r["tid"]), 0.0)
done = list(Scene.done.get(key, []))
return {
"label": label, "arm": arm, "error": err, "roots_seen": roots, "window_s": WINDOW_S, "lived_s": t_end - t0,
"scenes_completed": sum(1 for s in done if s == "complete"), "scenes_other": [s for s in done if s != "complete"][:10],
"full": full, "steady": steady, "client_cpu_s": client_full, "threads": threads_full, "watcher_error": watcher.error,
"processes": hunt.process_listing(sampler, t0),
"process_cpu": {k: {"full": full[k], "steady": steady[k]} for k in TYPES},
}
def print_result(r: Dict[str, Any], note: str = "") -> None:
print("=" * 100)
print("%s: window %.0f s from just before the launch (steady = the last %.0f s), %d browser root(s) seen%s%s"
% (r["label"], r["window_s"], r["window_s"] / 2, r["roots_seen"], "" if r["roots_seen"] == 1 else " <-- WARNING (1 expected)",
(" [" + note + "]") if note else ""))
if r["error"]:
print("ERROR: " + r["error"])
if r["watcher_error"]:
print("thread watcher: " + r["watcher_error"])
n = r["scenes_completed"]
tot_full, tot_steady = sum(r["full"].values()), sum(r["steady"].values())
print("scenes completed: %d%s; CPU per scene (whole window, all processes): %s s"
% (n, (" (not completed: %s)" % r["scenes_other"]) if r["scenes_other"] else "", ("%.3f" % (tot_full / n)) if n else "-"))
print(" CPU seconds by process type: %9s %9s" % ("full", "steady"))
for t in TYPES:
print(" %-8s %20.2f %9.2f" % (t, r["full"][t], r["steady"][t]))
print(" %-8s %20.2f %9.2f (client side, python: %.2f s)" % ("TOTAL", tot_full, tot_steady, r["client_cpu_s"]))
for kind in ("parent", "gpu"):
rows = [t for t in r["threads"] if t["kind"] == kind]
if not rows:
print(" no %s-process threads were read" % kind)
continue
groups: Dict[str, List[float]] = {}
for t in rows:
g = groups.setdefault(normalise(t["name"]), [0, 0.0, 0.0])
g[0] += 1
g[1] += t["cpu_s"]
g[2] += t["steady_s"]
seen_sum = sum(t["cpu_s"] for t in rows)
print(" threads of the %s process(es), grouped by name, by full-window CPU (the sum over the threads %.2f s, the sampler's process CPU %.2f s, "
"difference %.2f s = threads born and dead between two polls):" % (kind, seen_sum, r["full"][kind], r["full"][kind] - seen_sum))
print(" %-34s %7s %9s %9s" % ("thread", "threads", "full s", "steady s"))
for name, (cnt, f, s) in sorted(groups.items(), key=lambda kv: -kv[1][1])[:18]:
print(" %-34s %7d %9.2f %9.2f" % (name[:34], cnt, f, s))
print_compositing_where(r)
hunt.print_processes(r["processes"])
sys.stdout.flush()
COMPOSITING_THREADS = re.compile(r"(?i)^(compositor|renderer|renderbackend|scenebuilder|wrworker|canvasrenderer|swcomposite|paintthread|compositorbridge)")
def compositing_by_kind(r: Dict[str, Any]) -> Dict[str, Dict[str, List[float]]]:
"""{process kind: {thread name: [threads, full s, steady s]}} for the threads that do the compositing and the drawing for it."""
out: Dict[str, Dict[str, List[float]]] = {}
for t in r["threads"]:
if COMPOSITING_THREADS.match(t["name"] or ""):
g = out.setdefault(t["kind"], {}).setdefault(normalise(t["name"]), [0, 0.0, 0.0])
g[0] += 1
g[1] += t["cpu_s"]
g[2] += t["steady_s"]
return out
def where_compositing_runs(r: Dict[str, Any]) -> str:
by = compositing_by_kind(r)
cpu = {k: sum(v[1] for v in g.values()) for k, g in by.items()}
if not cpu or sum(cpu.values()) <= 0:
return "no compositing thread (Compositor, Renderer, RenderBackend, WRWorker, ...) was seen with CPU in the parent or the GPU process"
best = max(cpu, key=cpu.get)
return "compositing threads: %s; they run mostly in the %s process" % (", ".join("%s process %.2f s" % (k, v) for k, v in sorted(cpu.items())), best)
def print_compositing_where(r: Dict[str, Any]) -> None:
print(" WHERE COMPOSITING RUNS (threads named Compositor, Renderer, RenderBackend, SceneBuilder, WRWorker, CanvasRenderer, ... by process):")
by = compositing_by_kind(r)
for kind, g in sorted(by.items()):
for name, (cnt, f, st) in sorted(g.items(), key=lambda kv: -kv[1][1]):
print(" %-8s %-26s %3d thread(s) %8.2f s full %8.2f s steady" % (kind, name[:26], cnt, f, st))
print(" -> " + where_compositing_runs(r))
def run_arm(args) -> int:
Scene.done = {}
httpd = ThreadingHTTPServer(("127.0.0.1", 0), Scene)
httpd.daemon_threads = True
threading.Thread(target=httpd.serve_forever, daemon=True).start()
base = "http://127.0.0.1:%d" % httpd.server_address[1]
work = Path(tempfile.mkdtemp(prefix="hunt-baseline-"))
out: Path = args.out
out.mkdir(parents=True, exist_ok=True)
rc = 0
try:
kill_firefox()
if args.arm == "retail":
exe, why = find_retail(args, work)
if exe is None:
print("retail: no binary (%s)" % why)
return 1
note = "%s; %s" % (why, application_ini(exe))
print("RETAIL BINARY: %s" % note)
r = measure("retail", "retail", "retail", lambda t0: launch_retail(exe, base, work / "profile-retail", t0))
print_result(r, note)
(out / "retail.json").write_text(json.dumps(r, indent=1), encoding="utf-8")
rc = 1 if r["error"] else 0
elif args.arm == "stockheaded":
r = measure("stockheaded", "stockheaded", "stockheaded", lambda t0: asyncio.run(stock_session(base, "stockheaded", t0)))
print_result(r, "stock Playwright firefox, headless=False, fresh profile")
(out / "stockheaded.json").write_text(json.dumps(r, indent=1), encoding="utf-8")
rc = 1 if r["error"] else 0
elif args.arm in ("ours", "ours_swwr", "ours_vmretail"):
prefs = hunt.arm_prefs(args.arm)
r = measure(args.arm, args.arm, args.arm, lambda t0: asyncio.run(ours_session(base, args.binary, args.arm, None, t0, prefs)))
print_result(r, "fresh temporary profile%s" % (("; extra_prefs from the hunt: %s" % sorted(prefs)) if prefs else ""))
(out / ("%s.json" % args.arm)).write_text(json.dumps(r, indent=1), encoding="utf-8")
rc = 1 if r["error"] else 0
else:
persistent = str(work / "profile-reused")
for n in (1, 2):
label = "ours_reused/%d" % n
r = measure(label, "ours_reused", "ours_reused%d" % n,
lambda t0, n=n: asyncio.run(ours_session(base, args.binary, "ours_reused%d" % n, persistent, t0)))
r["launch"] = n
print_result(r, "profile_dir=%s, launch %d of 2 on it (%s)" % ("<persistent>", n, "fresh profile" if n == 1 else "SECOND launch: the measured one"))
(out / ("ours_reused-%d.json" % n)).write_text(json.dumps(r, indent=1), encoding="utf-8")
rc = rc or (1 if r["error"] else 0)
kill_firefox()
finally:
httpd.shutdown()
kill_firefox()
shutil.rmtree(work, ignore_errors=True)
return rc
# -------------------------------------------------------------------------------------------------------------------- compare
def compare(root: Path) -> int:
files = [("retail", "retail.json"), ("stockheaded", "stockheaded.json"), ("ours", "ours.json"), ("ours_swwr", "ours_swwr.json"),
("ours_vmretail", "ours_vmretail.json"), ("reused #1 fresh", "ours_reused-1.json"), ("reused #2 REUSED", "ours_reused-2.json")]
runs = []
for title, name in files:
p = root / name
if p.is_file():
runs.append((title, json.loads(p.read_text(encoding="utf-8"))))
if not runs:
print("no results in %s" % root)
return 1
print("=" * 100)
print("BASELINE FOR THE PARENT: one browser, %.0f s from the launch (full) and the last %.0f s (steady); %s"
% (WINDOW_S, WINDOW_S / 2, ", ".join(t + (" (ERROR)" if r["error"] else "") for t, r in runs)))
for window in ("full", "steady"):
print("-" * 100)
print("CPU seconds by process type, %s window" % window)
print(" %-24s" % "" + "".join("%17s" % t for t, _ in runs))
for kind in TYPES:
print(" %-24s" % kind + "".join("%17.2f" % r[window][kind] for _, r in runs))
print(" %-24s" % "TOTAL" + "".join("%17.2f" % sum(r[window].values()) for _, r in runs))
print(" %-24s" % "scenes completed" + "".join("%17d" % r["scenes_completed"] for _, r in runs))
print(" %-24s" % "CPU s per scene (full)" + "".join("%17s" % (("%.3f" % (sum(r["full"].values()) / r["scenes_completed"])) if r["scenes_completed"] else "-")
for _, r in runs))
for kind in ("parent", "gpu"):
names: Dict[str, Dict[str, float]] = {}
for title, r in runs:
for t in r["threads"]:
if t["kind"] == kind:
names.setdefault(normalise(t["name"]), {}).setdefault(title, 0.0)
names[normalise(t["name"])][title] += t["steady_s"]
order = sorted(names, key=lambda n: -max(names[n].values()))[:20]
print("-" * 100)
print("CPU seconds by thread name of the %s process, STEADY window (largest first)" % kind)
print(" %-30s" % "" + "".join("%17s" % t for t, _ in runs))
for n in order:
print(" %-30s" % n[:30] + "".join("%17.2f" % names[n].get(t, 0.0) for t, _ in runs))
print("-" * 100)
print("WHERE COMPOSITING RUNS, per arm (CPU of the Compositor/Renderer/RenderBackend/SceneBuilder/WRWorker/CanvasRenderer threads, full window)")
for title, r in runs:
print(" %-18s %s" % (title, where_compositing_runs(r)))
return 0
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--arm", choices=ARMS)
ap.add_argument("--binary", default=os.environ.get("INVPW_BINARY_PATH", ""))
ap.add_argument("--retail-binary", default="")
ap.add_argument("--retail-version", default="159.0")
ap.add_argument("--out", type=Path)
ap.add_argument("--compare", type=Path)
args = ap.parse_args()
if args.compare:
return compare(args.compare)
if not args.arm or not args.out:
ap.error("--arm and --out, or --compare")
if args.arm.startswith("ours") and not args.binary:
ap.error("the arms ours and ours_reused need --binary (or INVPW_BINARY_PATH)")
return run_arm(args)
if __name__ == "__main__":
sys.exit(main())
+556
View File
@@ -0,0 +1,556 @@
"""HUNT ONLY (branch hunt/cpu-render-path, never merged; copied from hunt/udp-chain-post at 5cb46f6): under the same load, does OUR Firefox use more CPU per browser than stock Firefox?
python scripts/hunt_cpu_per_browser.py --arm ours --binary "$FF" --out DIR/ours-1.json
python scripts/hunt_cpu_per_browser.py --arm ours_swwr --binary "$FF" --out DIR/ours_swwr-1.json
python scripts/hunt_cpu_per_browser.py --arm stock --out DIR/stock-1.json
python scripts/hunt_cpu_per_browser.py --arm stockheaded --out DIR/stockheaded-1.json
python scripts/hunt_cpu_per_browser.py --compare DIR
An arm runs 4 browsers at once in ONE client process, each headless with 1 page, and each page loops 10 times over the same scenario,
served by an http server inside the client process:
1. load a page that builds an RTCPeerConnection with no ICE servers, createDataChannel, createOffer, setLocalDescription and waits for
iceGatheringState "complete";
2. draw 200 DOM elements and one 2D canvas frame;
3. navigate to the next copy of that page (/p/<browser>/<n>).
ours invisible_playwright.async_api.InvisiblePlaywright (the in-process client, our binary), headless=True
stock stock Playwright's async client (its node driver) and the firefox-1572 it installed, headless=True, with
firefox_user_prefs {"fission.autostart": true}. Stock's playwright.cfg forces webContentIsolationStrategy 0 by autoconfig, so the
pref does not change the isolation the cfg picked; it is passed so that both arms are launched with Fission asked for.
ours_swwr ours with gfx.webrender.software=true passed ONLY here, through extra_prefs (a hunt-side switch, the product is untouched):
would software WebRender on the VM cost as little as stock's fallback does?
ours_nomsaa ours with webgl.msaa-samples=0 and webgl.msaa-force=false passed ONLY here (scripts/hunt_msaa.py): without the forced multisample.
ours_noproj ours with zoom.stealth.canvas.substitute_pixels=false passed ONLY here (scripts/hunt_readback.py): the read-time canvas noise off.
ours_vmretail ours made to take the retail decisions of the VM: the feature-status declaration of the core with the compositing features
replaced by what stock decides on this runner, gfx.webrender.software=true, gfx.webrender.software.d3d11=false, webgl.angle.force-warp=true
(scripts/hunt_vmretail.py; the list is printed there and in `support`).
stockheaded the same as stock with headless=False: a headed Firefox, which is what ours is on Windows (headless=True there creates a hidden
desktop and runs headed Firefox on it), so that the comparison with ours is not headed against --headless.
THE CPU. A tiny separate process (SAMPLER_CODE) reads NtQuerySystemInformation(SystemProcessInformation) every 250 ms (psutil elsewhere): one
call that holds name, ppid and user+kernel time of every process. It keeps, per sample, the cumulative CPU of every firefox process and of
the client side (the client pid and its non-firefox descendants: the python client, stock's node driver).
THE ATTRIBUTION PER BROWSER. The command line is read ONCE per pid, and only for processes whose image name is firefox (the first time the
sampler sees them, whatever CPU they have used, so a short-lived process is not missed for lack of it). The type comes from it:
no `-contentproc` = "parent", otherwise the last token of the command line (tab = content, gpu, socket, rdd, utility, ...). The browser of a
process comes from the table of ppid: walk up through the firefox processes while the parent is a firefox process; the topmost one is the
browser (so a Windows launcher process, should one stay, is the root and the real parent is its child, both counted as "parent"). Four
roots are expected; any other number is printed as a warning.
CPU of a process in a window = its cumulative CPU at the end minus at the start (the last sample at or before each instant; 0 before the
process was first seen), so a process that dies inside the window still counts up to its last sample (at most 250 ms of its end is lost).
The loop window is from the moment all four pages exist to the moment the last page finished its tenth round; the whole-arm window is
from before the first launch to after the last close.
"""
from __future__ import annotations
import argparse
import asyncio
import bisect
import contextlib
import importlib
import json
import os
import statistics
import subprocess
import sys
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
BROWSERS = int(os.environ.get("HUNT_BROWSERS", "4")) # only the hunt's GPU-process profile shortens the loop; every other step leaves these alone
ROUNDS = int(os.environ.get("HUNT_ROUNDS", "10"))
ARMS = ["ours", "ours_swwr", "ours_vmretail", "ours_nomsaa", "ours_noproj", "stock", "stockheaded"]
#: prefs an arm passes through extra_prefs: the only place they are added, the hunt and never the product
ARM_PREFS = {"ours_swwr": {"gfx.webrender.software": True},
# ours_nomsaa: the multisample the core forces (webgl.msaa-samples=4, webgl.msaa-force=true) switched off, by the hunt only
"ours_nomsaa": {"webgl.msaa-samples": 0, "webgl.msaa-force": False},
# ours_noproj: the read-time canvas noise of the engine (gfx::StealthProjectPixels, gfx/thebes/StealthDeclarationGate.h:54-62) declared off, by the hunt only
"ours_noproj": {"zoom.stealth.canvas.substitute_pixels": False}}
#: ours_vmretail: the prefs are BUILT in the run (scripts/hunt_vmretail.py build reads the retail decisions of the VM from stock and writes this file)
VMRETAIL_FILE = os.environ.get("HUNT_VMRETAIL_PREFS", "")
def arm_prefs(arm: str) -> dict | None:
"""The extra_prefs of an arm (None for ours and the stock arms). ours_vmretail reads the file hunt_vmretail.py build wrote and says so if it is missing."""
if arm == "ours_vmretail":
path = os.environ.get("HUNT_VMRETAIL_PREFS", VMRETAIL_FILE)
if not path or not os.path.isfile(path):
raise RuntimeError("the arm ours_vmretail needs HUNT_VMRETAIL_PREFS=<prefs.json of scripts/hunt_vmretail.py build>; %r is not a file" % path)
with open(path, encoding="utf-8") as f:
return json.load(f)["prefs"]
return ARM_PREFS.get(arm)
def is_ours(arm: str) -> bool:
return arm.startswith("ours")
TYPES = ["parent", "tab", "gpu", "socket", "rdd", "utility", "other"]
ICE_WAIT_MS = 15000
SCENARIO_TIMEOUT_S = 60
PAGE = """<!doctype html><meta charset=utf-8><title>scenario</title>
<body><div id=root></div><canvas id=c width=320 height=200></canvas>
<script>
window.__ready = (async () => {
const pc = new RTCPeerConnection({iceServers: []});
pc.createDataChannel("x");
const done = new Promise(res => {
const t = setTimeout(() => res("timeout:" + pc.iceGatheringState), %(ice_wait)d);
pc.addEventListener("icegatheringstatechange", () => {
if (pc.iceGatheringState === "complete") { clearTimeout(t); res("complete"); }
});
});
await pc.setLocalDescription(await pc.createOffer());
const state = pc.iceGatheringState === "complete" ? "complete" : await done;
const root = document.getElementById("root");
for (let i = 0; i < 200; i++) {
const d = document.createElement("div");
d.textContent = "element " + i;
d.style.cssText = "display:inline-block;width:40px;height:16px;margin:1px;background:hsl(" + (i * 7 %% 360) + ",60%%,60%%)";
root.appendChild(d);
}
const g = document.getElementById("c").getContext("2d");
for (let i = 0; i < 40; i++) {
g.fillStyle = "hsl(" + (i * 9) + ",70%%,50%%)";
g.fillRect(i * 8, (i * 5) %% 160, 60, 30);
}
g.font = "16px sans-serif";
g.fillText("a frame of the scenario", 10, 100);
g.getImageData(0, 0, 1, 1);
pc.close();
return state;
})();
</script>
""" % {"ice_wait": ICE_WAIT_MS}
class Handler(BaseHTTPRequestHandler):
timeout = 10
def do_GET(self): # noqa: N802
body = PAGE.encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(body)
def log_message(self, *a): # noqa: D102
pass
# --------------------------------------------------------------------------------------------------------------- the sampler
SAMPLER_CODE = r"""
import json, os, sys, threading, time
halt = threading.Event()
threading.Thread(target=lambda: (sys.stdin.read(), halt.set()), daemon=True).start()
client = int(sys.argv[1])
info, samples = {}, [] # info: pid -> [kind, ppid, name, cmdline-or-None]; samples: [t, {pid: cumulative cpu seconds}]
def table():
# {pid: (name, cpu seconds user+kernel, ppid)} of every process, in ONE call (psutil's cpu_times opens every process: far slower).
out = {}
if sys.platform == "win32":
import ctypes, struct
ntdll = ctypes.windll.ntdll
size = 1 << 20
while True:
buf = ctypes.create_string_buffer(size)
need = ctypes.c_ulong(0)
status = ntdll.NtQuerySystemInformation(5, buf, size, ctypes.byref(need)) & 0xFFFFFFFF
if status == 0xC0000004:
size = max(size * 2, need.value + 65536)
continue
if status != 0:
raise OSError("NtQuerySystemInformation %#x" % status)
break
base, raw, off = ctypes.addressof(buf), buf.raw, 0
while True:
nxt = struct.unpack_from("<I", raw, off)[0]
user, kernel = struct.unpack_from("<qq", raw, off + 40)
length = struct.unpack_from("<H", raw, off + 56)[0]
pointer = struct.unpack_from("<Q", raw, off + 64)[0]
pid, ppid = struct.unpack_from("<QQ", raw, off + 80)
name = raw[pointer - base:pointer - base + length].decode("utf-16-le", "replace") if pointer and length else "?"
if pid != 0:
out[pid] = (name, (user + kernel) / 1e7, ppid)
if nxt == 0:
break
off += nxt
return out
import psutil
for p in psutil.process_iter(["pid", "name", "cpu_times", "ppid"]):
ct = p.info.get("cpu_times")
if ct is not None:
out[p.info["pid"]] = (p.info.get("name") or "?", ct.user + ct.system, p.info.get("ppid") or -1)
return out
def cmdline_of(pid):
try:
import psutil
return psutil.Process(pid).cmdline()
except Exception as exc:
return ["?", "%s: %s" % (type(exc).__name__, exc)]
def is_firefox(name):
return name.lower().startswith("firefox")
def sample():
now = time.time()
tab = table()
tracked = {client}
grew = True
while grew: # the client side: the client pid and its descendants that are not firefox (a node driver, helpers)
grew = False
for pid, (name, _, ppid) in tab.items():
if pid not in tracked and ppid in tracked and not is_firefox(name):
tracked.add(pid)
grew = True
cpu = {}
for pid, (name, c, ppid) in tab.items():
if is_firefox(name):
if pid not in info: # the command line: once per pid, only for firefox, at first sight
info[pid] = ["firefox", ppid, name, cmdline_of(pid)]
cpu[pid] = c
elif pid in tracked:
if pid not in info:
info[pid] = ["client" if pid == client else "client-child", ppid, name, None]
cpu[pid] = c
samples.append([now, cpu])
print("ready", flush=True)
while not halt.is_set():
try:
sample()
except Exception as exc:
info[-1] = ["error", -1, "%s: %s" % (type(exc).__name__, exc), None]
halt.wait(0.25)
print(json.dumps({"info": info, "samples": samples}), flush=True)
"""
class Sampler:
def __init__(self) -> None:
self.info: dict = {}
self.samples: list = []
self.note = ""
self._proc = None
def start(self) -> None:
self._proc = subprocess.Popen([sys.executable, "-I", "-c", SAMPLER_CODE, str(os.getpid())], stdin=subprocess.PIPE,
stdout=subprocess.PIPE, text=True)
ready = self._proc.stdout.readline()
if "ready" not in ready:
raise RuntimeError("the sampler said %r instead of ready" % ready)
def stop(self) -> None:
proc, self._proc = self._proc, None
if proc is None:
return
try:
proc.stdin.close()
data = json.loads(proc.stdout.readline())
self.info = {int(k): v for k, v in data["info"].items()}
self.samples = data["samples"]
finally:
try:
proc.wait(timeout=10)
except Exception: # noqa: BLE001
proc.kill()
# ------------------------------------------------------------------------------------------------------------------ the attribution
def classify(cmd: list) -> str:
"""parent = no -contentproc; otherwise the last token of the command line (tab, gpu, socket, rdd, utility, ...)."""
if "-contentproc" not in cmd:
return "parent"
last = str(cmd[-1]).strip('"').lower()
return last if last in TYPES else "other"
def roots_and_kinds(info: dict) -> tuple:
"""{pid: (root pid, type)} for every firefox process, and the list of roots."""
firefox = {p: v for p, v in info.items() if v[0] == "firefox"}
out, roots = {}, set()
for pid, v in firefox.items():
top, seen = pid, {pid}
while firefox.get(top) is not None and firefox[top][1] in firefox and firefox[top][1] not in seen:
top = firefox[top][1]
seen.add(top)
out[pid] = (top, classify(v[3]))
roots.add(top)
return out, sorted(roots)
class Series:
"""cumulative CPU of every tracked pid over time: cpu_at(pid, t) = the last sample at or before t, 0 before the pid's first sample."""
def __init__(self, samples: list) -> None:
self.t: dict = {}
self.c: dict = {}
for ts, cpu in samples:
for pid, c in cpu.items():
pid = int(pid)
self.t.setdefault(pid, []).append(ts)
self.c.setdefault(pid, []).append(c)
def at(self, pid: int, t: float) -> float:
i = bisect.bisect_right(self.t.get(pid, []), t)
return self.c[pid][i - 1] if i else 0.0
def used(self, pid: int, a: float, b: float) -> float:
return max(0.0, self.at(pid, b) - self.at(pid, a))
def per_browser(sampler: Sampler, a: float, b: float) -> tuple:
"""([ {type: cpu s} per browser ], roots, client-side cpu s) over the window [a, b]."""
series = Series(sampler.samples)
where, roots = roots_and_kinds(sampler.info)
rows = {r: {t: 0.0 for t in TYPES} for r in roots}
for pid, (root, kind) in where.items():
rows[root][kind] += series.used(pid, a, b)
client = sum(series.used(pid, a, b) for pid, v in sampler.info.items() if v[0] in ("client", "client-child"))
return [rows[r] for r in roots], roots, client
def process_listing(sampler: "Sampler", t0: float) -> list:
"""Every firefox process the sampler saw: pid, parent, browser root, type, first/last sample (s from t0), lifetime, CPU used in all, command line."""
series = Series(sampler.samples)
where, _ = roots_and_kinds(sampler.info)
out = []
for pid, (root, kind) in sorted(where.items()):
ts, cs = series.t.get(pid, []), series.c.get(pid, [])
if not ts:
continue
cmd = sampler.info[pid][3] or []
out.append({"pid": pid, "ppid": sampler.info[pid][1], "root": root, "kind": kind, "first_s": round(ts[0] - t0, 2),
"last_s": round(ts[-1] - t0, 2), "life_s": round(ts[-1] - ts[0], 2), "cpu_s": round(cs[-1], 3),
"cmd": " ".join(str(x) for x in cmd)})
return out
SHORT_S = 5.0
def print_processes(listing: list) -> None:
"""What the short-lived processes are. `default` = a firefox process with no recognised -contentproc type (parent or other here)."""
import re
print(" processes seen by the sampler (every 250 ms: one that lives less is not seen): %d in all" % len(listing))
kinds: dict = {}
for r in listing:
kinds.setdefault(r["kind"], []).append(r)
for k, rs in sorted(kinds.items()):
shorts = [r for r in rs if r["life_s"] < SHORT_S]
print(" %-8s %3d process(es), %3d shorter than %.0f s, lifetime median %.1f s, CPU of all of them %.2f s"
% (k, len(rs), len(shorts), SHORT_S, statistics.median([r["life_s"] for r in rs]), sum(r["cpu_s"] for r in rs)))
defaults = [r for r in listing if r["kind"] in ("parent", "other")]
print(" every firefox process WITHOUT a recognised -contentproc type (`default` in a Gecko profile), %d:" % len(defaults))
for r in defaults[:80]:
print(" pid %-6s ppid %-6s root %-6s first %6.1f s life %6.1f s cpu %6.2f s %s"
% (r["pid"], r["ppid"], r["root"], r["first_s"], r["life_s"], r["cpu_s"], r["cmd"][:500]))
groups: dict = {}
for r in listing:
if r["life_s"] < SHORT_S and r["kind"] not in ("parent", "other"):
groups.setdefault((r["kind"], re.sub(r"\d+", "N", r["cmd"])), []).append(r)
print(" the other short-lived processes (< %.0f s), grouped by type and command line with the numbers blanked:" % SHORT_S)
for (kind, _norm), rs in sorted(groups.items(), key=lambda kv: -len(kv[1]))[:20]:
print(" %3d x %-8s median life %.1f s, CPU %.2f s: %s" % (len(rs), kind, statistics.median([r["life_s"] for r in rs]),
sum(r["cpu_s"] for r in rs), rs[0]["cmd"][:400]))
sys.stdout.flush()
def summarise(rows: list) -> dict:
med = {t: (statistics.median([r[t] for r in rows]) if rows else 0.0) for t in TYPES}
totals = [sum(r.values()) for r in rows]
return {"median_by_type": med, "median_total": statistics.median(totals) if totals else 0.0, "total_all": sum(totals)}
# ----------------------------------------------------------------------------------------------------------------------- the arms
async def loop_one(page, base: str, index: int, outcome: dict) -> None:
for n in range(ROUNDS):
t = time.perf_counter()
try:
await page.goto("%s/p/%d/%d" % (base, index, n), wait_until="load", timeout=SCENARIO_TIMEOUT_S * 1000)
state = await asyncio.wait_for(page.evaluate("window.__ready"), SCENARIO_TIMEOUT_S)
except Exception as exc: # noqa: BLE001
outcome["failed"].append("browser %d round %d: %s: %s" % (index, n, type(exc).__name__, str(exc)[:200]))
continue
if state == "complete":
outcome["completed"] += 1
else:
outcome["incomplete"].append("browser %d round %d: ice %s" % (index, n, state))
outcome["ms"].append((time.perf_counter() - t) * 1000)
async def run_scenarios(pages: list, base: str) -> tuple:
outcome = {"completed": 0, "incomplete": [], "failed": [], "ms": []}
t0 = time.time()
await asyncio.gather(*(loop_one(p, base, i, outcome) for i, p in enumerate(pages)))
return t0, time.time(), outcome
async def arm_ours(base: str, binary: str, extra_prefs: dict | None = None):
from invisible_playwright.async_api import InvisiblePlaywright
async with contextlib.AsyncExitStack() as stack:
browsers = await asyncio.gather(*(stack.enter_async_context(
InvisiblePlaywright(seed=100 + i, binary_path=binary, headless=True, locale="en-US", timezone="Europe/Rome",
extra_prefs=extra_prefs))
for i in range(BROWSERS)))
pages = await asyncio.gather(*(b.new_page() for b in browsers))
return await run_scenarios(pages, base)
async def arm_stock(base: str, binary: str, headless: bool = True):
async_playwright = importlib.import_module("playwright.async_api").async_playwright # by name: the fork's guard forbids a static import
pw = await async_playwright().start()
browsers = []
try:
browsers = await asyncio.gather(*(pw.firefox.launch(headless=headless, firefox_user_prefs={"fission.autostart": True})
for _ in range(BROWSERS)))
pages = await asyncio.gather(*(b.new_page() for b in browsers))
return await run_scenarios(pages, base)
finally:
for b in browsers:
with contextlib.suppress(Exception):
await b.close()
with contextlib.suppress(Exception):
await pw.stop()
def run_arm(arm: str, binary: str, rnd: int) -> dict:
httpd = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
httpd.daemon_threads = True
threading.Thread(target=httpd.serve_forever, daemon=True).start()
base = "http://127.0.0.1:%d" % httpd.server_address[1]
sampler = Sampler()
sampler.start()
whole_a = time.time()
err = ""
loop_a = loop_b = whole_a
outcome = {"completed": 0, "incomplete": [], "failed": [], "ms": []}
try:
if is_ours(arm):
coro = arm_ours(base, binary, arm_prefs(arm))
else:
coro = arm_stock(base, binary, headless=(arm == "stock"))
loop_a, loop_b, outcome = asyncio.run(coro)
except BaseException as exc: # noqa: BLE001
err = "%s: %s" % (type(exc).__name__, exc)
time.sleep(0.6) # two more samples after the last close
whole_b = time.time()
sampler.stop()
httpd.shutdown()
rows, roots, client = per_browser(sampler, loop_a, loop_b)
whole_rows, _, whole_client = per_browser(sampler, whole_a, whole_b)
loop = summarise(rows)
result = {
"arm": arm, "round": rnd, "error": err, "browsers_seen": len(roots), "wall_s": loop_b - loop_a,
"completed": outcome["completed"], "incomplete": outcome["incomplete"], "failed": outcome["failed"],
"median_scenario_ms": statistics.median(outcome["ms"]) if outcome["ms"] else None,
"loop": loop, "client_cpu_s": client,
"cpu_per_scenario_s": (loop["total_all"] / outcome["completed"]) if outcome["completed"] else None,
"whole": summarise(whole_rows), "whole_client_cpu_s": whole_client, "whole_wall_s": whole_b - whole_a,
"processes": process_listing(sampler, whole_a),
}
return result
def print_arm(r: dict) -> None:
print("=" * 100)
print("arm %s, round %s: %s completed of %d scenarios, wall time of the loop %.1f s, %d browser(s) seen (4 expected)%s"
% (r["arm"], r["round"], r["completed"], BROWSERS * ROUNDS, r["wall_s"], r["browsers_seen"],
"" if r["browsers_seen"] == BROWSERS else " <-- WARNING"))
if r["error"]:
print("ERROR: " + r["error"])
for line in (r["incomplete"] + r["failed"])[:10]:
print(" not completed: " + line)
print(" CPU seconds per browser, median of the browsers, LOOP window:")
for t in TYPES:
print(" %-8s %8.2f" % (t, r["loop"]["median_by_type"][t]))
print(" %-8s %8.2f (median per browser; all browsers together %.2f)" % ("TOTAL", r["loop"]["median_total"], r["loop"]["total_all"]))
print(" client side (python client, node driver): %.2f s" % r["client_cpu_s"])
if r["cpu_per_scenario_s"] is not None:
print(" CPU per completed scenario (all browsers): %.3f s; median scenario time %.0f ms"
% (r["cpu_per_scenario_s"], r["median_scenario_ms"] or 0))
print(" whole arm (launch to close, %.1f s): median total per browser %.2f s, all %.2f s, client side %.2f s"
% (r["whole_wall_s"], r["whole"]["median_total"], r["whole"]["total_all"], r["whole_client_cpu_s"]))
print_processes(r.get("processes") or [])
sys.stdout.flush()
# ----------------------------------------------------------------------------------------------------------------------- compare
def compare(directory: Path) -> int:
results = [json.loads(p.read_text(encoding="utf-8")) for p in sorted(directory.glob("*.json"))]
arms = {a: [r for r in results if r["arm"] == a and not r["error"]] for a in ARMS}
for a, rs in arms.items():
print("%s: %d good run(s) (%s)" % (a, len(rs), ", ".join("round %s" % r["round"] for r in rs)))
if not arms["ours"] or not (arms["stock"] or arms["stockheaded"]):
print("no comparison: ours or every stock arm has no good run")
return 1
def mean(a, f):
values = [f(r) for r in arms[a] if f(r) is not None]
return sum(values) / len(values) if values else float("nan")
rows = [("%s CPU s per browser (median of 4)" % t, lambda r, t=t: r["loop"]["median_by_type"][t]) for t in TYPES]
rows += [
("TOTAL CPU s per browser (median of 4)", lambda r: r["loop"]["median_total"]),
("total CPU s, all browsers", lambda r: r["loop"]["total_all"]),
("client side CPU s", lambda r: r["client_cpu_s"]),
("wall time of the loop, s", lambda r: r["wall_s"]),
("completed scenarios (of %d)" % (BROWSERS * ROUNDS), lambda r: r["completed"]),
("CPU s per completed scenario", lambda r: r["cpu_per_scenario_s"]),
("whole arm, total CPU s per browser", lambda r: r["whole"]["median_total"]),
]
def ratio(a, b):
return ("%.2f" % (a / b)) if b and b == b else "-"
print()
print("%-52s %9s %9s %9s %9s %11s %11s %13s %12s %12s" % ("loop window, mean over the rounds", "ours", "ours_swwr", "ours_vmret", "stock",
"stockheaded", "ours/stock", "ours/stockhd", "swwr/stockhd", "vmret/stockhd"))
for label, f in rows:
o, w, v, s, h = mean("ours", f), mean("ours_swwr", f), mean("ours_vmretail", f), mean("stock", f), mean("stockheaded", f)
print("%-52s %9.3f %9.3f %9.3f %9.3f %11.3f %11s %13s %12s %12s" % (label, o, w, v, s, h, ratio(o, s), ratio(o, h), ratio(w, h), ratio(v, h)))
print()
for a in ARMS:
print("%s per round: " % a + "; ".join("r%s total/browser %.2f s, wall %.1f s" % (r["round"], r["loop"]["median_total"], r["wall_s"])
for r in arms[a]))
return 0
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--arm", choices=ARMS)
ap.add_argument("--binary", default=os.environ.get("INVPW_BINARY_PATH", ""))
ap.add_argument("--round", type=int, default=1)
ap.add_argument("--out", type=Path)
ap.add_argument("--compare", type=Path)
args = ap.parse_args()
if args.compare:
return compare(args.compare)
if not args.arm:
ap.error("--arm or --compare")
if is_ours(args.arm) and not args.binary:
ap.error("the ours arms need --binary (or INVPW_BINARY_PATH)")
result = run_arm(args.arm, args.binary, args.round)
print_arm(result)
if args.out:
args.out.parent.mkdir(parents=True, exist_ok=True)
args.out.write_text(json.dumps(result, indent=1), encoding="utf-8")
return 1 if result["error"] else 0
if __name__ == "__main__":
sys.exit(main())
+654
View File
@@ -0,0 +1,654 @@
"""HUNT ONLY (branch hunt/cpu-render-path, never merged): why does our Firefox use ~6x the CPU of stock Firefox 159 with a window?
Nothing of the product is changed: this script only launches the two arms the way scripts/hunt_cpu_per_browser.py does and looks.
python scripts/hunt_cpu_render_path.py support --arm ours --binary "$FF" --out DIR # 1. about:support, prefs, env
python scripts/hunt_cpu_render_path.py support --arm stockheaded --out DIR
python scripts/hunt_cpu_render_path.py diff DIR # the Graphics diff
python scripts/hunt_cpu_render_path.py profile --arm ours --binary "$FF" --out DIR # 2. Gecko profiles of the 10-scene loop
python scripts/hunt_cpu_render_path.py profile --arm stockheaded --out DIR
python scripts/hunt_cpu_render_path.py profile --arm ours --binary "$FF" --gpu --out DIR # 4. a readable profile of OUR GPU process
python scripts/hunt_cpu_render_path.py support --arm ours_swwr --binary "$FF" --out DIR # compositing facts of the swwr arm
ARMS (as in hunt_cpu_per_browser.py)
ours invisible_playwright, headless=True (on Windows: headed Firefox on a hidden desktop)
ours_swwr ours with gfx.webrender.software=true through extra_prefs (hunt only); `support` then proves the pref took effect
stockheaded stock Playwright's firefox, firefox.launch(headless=False)
1. `support` launches the arm TWICE, alone:
A. clean launch (nothing added). Route "juggler": page.goto("about:support") in a page of the browser and save document.body.innerText.
Then, while the browser is alive, the parent's command line, its environment (MOZ_*, STEALTH*, GFX*, ... only) and the profile's
prefs.js and user.js are copied (the profile directory comes from `-profile` in the command line), and the process types are counted
(is there a GPU process?).
B. launch with `-marionette -remote-allow-system-access` and MOZ_REMOTE_ALLOW_SYSTEM_ACCESS=1 (the route tests/webfont_probe.py uses),
and in chrome scope: Troubleshoot.snapshot() (the data about:support is made of) and the EFFECTIVE prefs (every pref with a user value,
plus the whole gfx.*, layers.*, webgl.*, widget.*, media.*, dom.ipc.*, ... family). This is the route "troubleshoot". It is needed even
when the juggler route works, because in our product the prefs travel over the wire and never reach prefs.js or user.js.
The report says which route worked, and `diff` prints the Graphics section of both routes side by side, the lines that decide
compositing (WebRender hardware/software, D3D11/WARP, GPU process, the feature decisions and their reasons) and the differing prefs.
2. `profile` runs the arm of hunt_cpu_per_browser.py (4 browsers at once, 10 rounds of the same scenario each) with the Gecko profiler on
from startup in EVERY process:
MOZ_PROFILER_STARTUP=1 MOZ_PROFILER_STARTUP_FEATURES=js,stackwalk,cpu,threads,processcpu MOZ_PROFILER_STARTUP_FILTERS=*
MOZ_PROFILER_STARTUP_INTERVAL=2 MOZ_PROFILER_SHUTDOWN=<out>/profile-%p.json
`threads` and `processcpu` are added to the three features asked for: without `threads` only the main thread of each process is sampled
and the GPU process's cost is on the Compositor and Renderer threads; STARTUP_FILTERS=* keeps every thread of the parent.
The profiler slows the browsers: the CPU numbers of this run are printed but are NOT the comparison; part 3 is.
Our product removes every MOZ_* variable that is not on its pass list from the engine's environment (invisible_core._engine_env.
without_the_hosts), so MOZ_PROFILER_* would never reach our binary. This script lets MOZ_PROFILER_* through by wrapping that function in
this process only (a hunt-side switch, not a change of the product); the profile run says whether the variables arrived by counting the
profile files it got.
The profiles are written when each process shuts down cleanly; the files are gzipped and left in <out> for the artifact.
`--gpu` is the same run narrowed to the GPU process: MOZ_PROFILER_STARTUP_FILTERS=Compositor,Renderer,RenderBackend,WRWorker,CanvasRenderer,
GeckoMain (read by every process: the parent and the tabs keep only their GeckoMain), MOZ_PROFILER_STARTUP_ENTRIES=1048576 (8 MiB instead of
the default), no `js`, 3 rounds. The run waits (up to 90 s) for every firefox process to exit before it looks at the files, and says for each
file whether it is valid JSON: the first GPU profile (pid 10492) was truncated.
"""
from __future__ import annotations
import argparse
import asyncio
import contextlib
import difflib
import gzip
import importlib
import json
import os
import re
import shutil
import sys
import time
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
from hunt_cpu_per_browser import arm_prefs, is_ours # noqa: E402 (the one place the hunt's prefs are declared)
MARIONETTE_PORTS = (28431, 2828)
ENV_INTERESTING = re.compile(r"^(MOZ_|STEALTH|INVPW|GFX|WEBRENDER|DXGI|D3D|LIBGL|MESA|GDK_|GTK_|DISPLAY|USERNAME$|SESSIONNAME$)", re.I)
#: the prefs families whose EFFECTIVE value is read (a pref with a user value is read whatever its name)
PREF_FAMILIES = (r"gfx\.|layers\.|webgl\.|widget\.|media\.(hardware|rdd|gpu|ffvpx|wmf|utility)|dom\.ipc\.|dom\.webgpu|fission|browser\.tabs\.remote|"
r"apz\.|general\.smoothScroll|privacy\.resistFingerprinting|nglayout\.|security\.sandbox\.(gpu|content)|"
r"layout\.(frame_rate|css\.devPixelsPerPx)|toolkit\.cosmeticAnimations|"
r"accessibility\.|stealth|juggler|zoom\.|webrender|canvas|gpu|headless|remote\.")
GRAPHICS_KEYS = ("graphics", "features", "processes", "modifiedPreferences", "environmentVariables", "userJS", "experimentalFeatures",
"lockedPreferences")
KEY_LINE = re.compile(r"(?i)compositing|webrender|d3d11|d3d9|warp|direct2d|d2d|gpu process|hardware|software|decision|blocklist|blocked|disabled|"
r"unavailable|failed|angle|renderer|adapter|driver|device|window protocol|display|advanced layers|opengl|vulkan|"
r"remote process|process type|acceler|basic|force|fallback|status|reason|gfx\.|layers\.")
# --------------------------------------------------------------------------------------------------- the profiler switch
def let_profiler_env_through() -> str:
"""Wrap invisible_core._engine_env.without_the_hosts so that MOZ_PROFILER_* (and nothing else) survives. This process only."""
try:
eng = importlib.import_module("invisible_core._engine_env")
except Exception as exc: # noqa: BLE001
return "invisible_core._engine_env not importable (%s: %s): our binary will not see MOZ_PROFILER_*" % (type(exc).__name__, exc)
original = eng.without_the_hosts
def wrapped(env):
kept = original(env)
for k, v in env.items():
if k.upper().startswith("MOZ_PROFILER_"):
kept[k] = v
return kept
eng.without_the_hosts = wrapped
return "without_the_hosts wrapped: MOZ_PROFILER_* passes"
# ------------------------------------------------------------------------------------------------------------- process facts
def firefox_processes() -> List[Dict[str, Any]]:
import psutil
out = []
for p in psutil.process_iter(["pid", "ppid", "name"]):
if not (p.info.get("name") or "").lower().startswith("firefox"):
continue
try:
cmd = p.cmdline()
except Exception: # noqa: BLE001
cmd = []
kind = "parent"
if "-contentproc" in cmd:
last = str(cmd[-1]).strip('"').lower() if cmd else "?"
kind = last if last in ("tab", "gpu", "socket", "rdd", "utility", "forkserver") else "other"
out.append({"pid": p.info["pid"], "ppid": p.info["ppid"], "kind": kind, "cmd": cmd, "proc": p})
return out
def parent_facts() -> Dict[str, Any]:
"""The facts of the running parent: command line, profile dir, interesting environment, the types of every firefox process."""
procs = firefox_processes()
kinds: Dict[str, int] = {}
for p in procs:
kinds[p["kind"]] = kinds.get(p["kind"], 0) + 1
parents = [p for p in procs if p["kind"] == "parent" and "-profile" in p["cmd"]] or [p for p in procs if p["kind"] == "parent"]
facts: Dict[str, Any] = {"process_kinds": kinds, "parents": len(parents)}
if not parents:
return facts
parent = parents[0]
cmd = parent["cmd"]
facts["cmdline"] = cmd
if "-profile" in cmd:
facts["profile_dir"] = cmd[cmd.index("-profile") + 1]
try:
env = parent["proc"].environ()
facts["env"] = {k: v for k, v in sorted(env.items()) if ENV_INTERESTING.match(k)}
except Exception as exc: # noqa: BLE001
facts["env_error"] = "%s: %s" % (type(exc).__name__, exc)
return facts
def copy_profile_files(facts: Dict[str, Any], out: Path) -> None:
profile = facts.get("profile_dir")
if not profile:
return
for name in ("user.js", "prefs.js"):
src = Path(profile) / name
try:
if src.is_file():
shutil.copyfile(src, out / name)
facts[name + "_bytes"] = src.stat().st_size
else:
facts[name + "_bytes"] = None
except Exception as exc: # noqa: BLE001
facts[name + "_error"] = "%s: %s" % (type(exc).__name__, exc)
# ---------------------------------------------------------------------------------------------------------------- Marionette
class Marionette:
def __init__(self, timeout: float = 60.0):
import socket
self.n = 0
self.port = 0
end = time.time() + timeout
last: Optional[BaseException] = None
while time.time() < end:
for port in MARIONETTE_PORTS:
try:
self.sock = socket.create_connection(("127.0.0.1", port), timeout=3)
self.sock.settimeout(120)
self._read()
self.port = port
return
except (OSError, ValueError) as exc:
last = exc
time.sleep(1)
raise OSError("no Marionette on %s: %s" % (MARIONETTE_PORTS, last))
def _read(self):
head = b""
while not head.endswith(b":"):
c = self.sock.recv(1)
if not c:
raise OSError("closed")
head += c
size = int(head[:-1])
data = b""
while len(data) < size:
data += self.sock.recv(size - len(data))
return json.loads(data)
def call(self, name: str, params: Optional[dict] = None):
self.n += 1
body = json.dumps([0, self.n, name, params or {}]).encode()
self.sock.sendall(str(len(body)).encode() + b":" + body)
while True:
msg = self._read()
if msg[0] == 1 and msg[1] == self.n:
if msg[2]:
raise RuntimeError("%s: %s" % (msg[2].get("error"), str(msg[2].get("message"))[:300]))
return msg[3]
def close(self):
with contextlib.suppress(Exception):
self.sock.close()
TROUBLESHOOT_JS = """
let cb = arguments[arguments.length - 1];
let mod;
try { mod = ChromeUtils.importESModule("resource://gre/modules/Troubleshoot.sys.mjs"); }
catch (e) { try { mod = ChromeUtils.import("resource://gre/modules/Troubleshoot.jsm"); } catch (e2) { cb(JSON.stringify({error: String(e) + " / " + String(e2)})); return; } }
Promise.resolve(mod.Troubleshoot.snapshot()).then(s => cb(JSON.stringify(s)), e => cb(JSON.stringify({error: String(e)})));
"""
PREFS_JS = """
let cb = arguments[arguments.length - 1];
let rel = new RegExp("^(" + arguments[0] + ")", "i");
let out = {};
for (let n of Services.prefs.getChildList("")) {
let user = Services.prefs.prefHasUserValue(n);
if (!user && !rel.test(n)) continue;
let v = null;
try {
switch (Services.prefs.getPrefType(n)) {
case 32: v = Services.prefs.getStringPref(n); break;
case 64: v = Services.prefs.getIntPref(n); break;
case 128: v = Services.prefs.getBoolPref(n); break;
}
} catch (e) { v = "<unreadable: " + e + ">"; }
out[n] = [user, v];
}
cb(JSON.stringify(out));
"""
def marionette_value(res):
return res.get("value") if isinstance(res, dict) and "value" in res else res
def privileged_route(out: Path, report: Dict[str, Any]) -> None:
"""Troubleshoot.snapshot() and the effective prefs, through Marionette in chrome scope."""
m = None
try:
m = Marionette()
report["marionette_port"] = m.port
m.call("WebDriver:NewSession", {"capabilities": {"alwaysMatch": {}}})
m.call("WebDriver:SetTimeouts", {"script": 120000})
m.call("Marionette:SetContext", {"value": "chrome"})
snap = marionette_value(m.call("WebDriver:ExecuteAsyncScript", {"script": TROUBLESHOOT_JS, "args": []}))
(out / "troubleshoot.json").write_text(snap if isinstance(snap, str) else json.dumps(snap), encoding="utf-8")
report["troubleshoot"] = "ok, %d bytes" % len(snap)
prefs = marionette_value(m.call("WebDriver:ExecuteAsyncScript", {"script": PREFS_JS, "args": [PREF_FAMILIES]}))
(out / "effective_prefs.json").write_text(prefs if isinstance(prefs, str) else json.dumps(prefs), encoding="utf-8")
report["effective_prefs"] = "ok, %d bytes" % len(prefs)
except Exception as exc: # noqa: BLE001
report["privileged_error"] = "%s: %s" % (type(exc).__name__, str(exc)[:400])
finally:
if m is not None:
m.close()
# ------------------------------------------------------------------------------------------------------------- the launches
@contextlib.asynccontextmanager
async def launched(arm: str, binary: str, marionette: bool):
"""Yield one browser of the arm, alone."""
extra_args = ["-marionette", "-remote-allow-system-access"] if marionette else []
if marionette:
os.environ["MOZ_REMOTE_ALLOW_SYSTEM_ACCESS"] = "1"
if is_ours(arm):
from invisible_playwright.async_api import InvisiblePlaywright
prefs = dict(arm_prefs(arm) or {}) # ours_swwr / ours_vmretail: from the hunt only
if marionette:
prefs["marionette.port"] = MARIONETTE_PORTS[0]
prefs = prefs or None
async with InvisiblePlaywright(seed=100, binary_path=binary, headless=True, locale="en-US", timezone="Europe/Rome",
extra_args=extra_args, extra_prefs=prefs) as browser:
yield browser
return
async_playwright = importlib.import_module("playwright.async_api").async_playwright # by name: the fork's guard forbids a static import
pw = await async_playwright().start()
browser = None
try:
prefs = {"fission.autostart": True}
if marionette:
prefs["marionette.port"] = MARIONETTE_PORTS[0]
browser = await pw.firefox.launch(headless=False, args=extra_args, firefox_user_prefs=prefs)
yield browser
finally:
if browser is not None:
with contextlib.suppress(Exception):
await browser.close()
with contextlib.suppress(Exception):
await pw.stop()
async def juggler_route(browser, out: Path, report: Dict[str, Any]) -> None:
page = None
try:
page = await browser.new_page()
await page.goto("about:support", wait_until="load", timeout=30000)
with contextlib.suppress(Exception):
await page.wait_for_function(
"(() => { const e = document.getElementById('graphics-tbody'); return !!e && e.children.length > 0; })()", timeout=20000)
await asyncio.sleep(2) # the page fills its sections one by one
text = await page.evaluate("document.body.innerText")
(out / "about_support.txt").write_text(text, encoding="utf-8")
report["juggler_route"] = "ok, %d chars, %d lines" % (len(text), text.count("\n") + 1)
except Exception as exc: # noqa: BLE001
report["juggler_route"] = "FAILED: %s: %s" % (type(exc).__name__, str(exc)[:400])
finally:
if page is not None:
with contextlib.suppress(Exception):
await page.close()
async def support_arm(arm: str, binary: str, out: Path) -> Dict[str, Any]:
out.mkdir(parents=True, exist_ok=True)
report: Dict[str, Any] = {"arm": arm}
kill_firefox()
try: # A: the clean launch
async with launched(arm, binary, marionette=False) as browser:
report["version"] = getattr(browser, "version", None)
await juggler_route(browser, out, report)
report["launch_A"] = parent_facts()
copy_profile_files(report["launch_A"], out)
except BaseException as exc: # noqa: BLE001
report["launch_A_error"] = "%s: %s" % (type(exc).__name__, str(exc)[:400])
kill_firefox()
try: # B: the privileged route
async with launched(arm, binary, marionette=True) as browser:
page = await browser.new_page() # a window exists, as in launch A
await page.goto("about:blank")
report["launch_B"] = parent_facts()
await asyncio.get_running_loop().run_in_executor(None, privileged_route, out, report)
except BaseException as exc: # noqa: BLE001
report["launch_B_error"] = "%s: %s" % (type(exc).__name__, str(exc)[:400])
kill_firefox()
(out / "support_report.json").write_text(json.dumps(report, indent=1, default=str), encoding="utf-8")
return report
def kill_firefox() -> None:
for p in firefox_processes():
with contextlib.suppress(Exception):
p["proc"].kill()
time.sleep(1)
def print_support(report: Dict[str, Any]) -> None:
print("=" * 100)
print("support, arm %s (browser version %s)" % (report["arm"], report.get("version")))
print(" route juggler (page.goto about:support, document.body.innerText): %s" % report.get("juggler_route", "not tried"))
print(" route troubleshoot (Marionette, chrome scope, Troubleshoot.snapshot): %s"
% (report.get("troubleshoot") or report.get("privileged_error") or report.get("launch_B_error") or "not tried"))
print(" effective prefs (Services.prefs): %s" % report.get("effective_prefs", "none"))
for key in ("launch_A", "launch_B"):
f = report.get(key) or {}
print(" %s: process kinds %s, parents %s, profile dir %s, user.js %s bytes, prefs.js %s bytes"
% (key, f.get("process_kinds"), f.get("parents"), f.get("profile_dir"), f.get("user.js_bytes"), f.get("prefs.js_bytes")))
if f.get("cmdline"):
print(" command line: %s" % " ".join(str(x) for x in f["cmdline"])[:600])
for k, v in (f.get("env") or {}).items():
print(" env %s=%s" % (k, str(v)[:120]))
if f.get("env_error"):
print(" env: %s" % f["env_error"])
for key in ("launch_A_error", "launch_B_error"):
if report.get(key):
print(" %s: %s" % (key, report[key]))
sys.stdout.flush()
def print_compositing(arm_dir: Path) -> None:
"""What decided compositing in this arm, and WHERE it runs: the prefs the hunt passed (as read back), the feature decisions, the layer manager."""
print("-" * 100)
print("compositing facts of %s:" % arm_dir.name)
pf = arm_dir / "effective_prefs.json"
if pf.is_file():
prefs = json.loads(pf.read_text(encoding="utf-8"))
for n in sorted(prefs):
if n.startswith(("gfx.webrender.", "gfx.canvas.", "layers.gpu-process", "layers.d3d11", "webgl.angle.", "webgl.disable-angle", "gfx.direct")):
print(" pref %s = %s (user-set: %s)" % (n, prefs[n][1], prefs[n][0]))
decl = prefs.get("zoom.stealth.gfx.feature_status")
if decl and isinstance(decl[1], str):
entries = [e for e in decl[1].split(",") if e]
odd = [e for e in entries if e.split("|")[1:2] != ["1"]]
print(" pref zoom.stealth.gfx.feature_status: %d features declared, the ones that are not OK (|1): %s"
% (len(entries), "; ".join(odd) if odd else "none"))
comp = [e for e in entries if re.match(r"(DIRECT3D_11_LAYERS|GPU_PROCESS|WEBRENDER[A-Z_]*|D3D11_KEYED_MUTEX|DX_INTEROP2|CANVAS2D_ACCELERATION|"
r"ACCELERATED_CANVAS2D|DIRECT3D_11_ANGLE|WEBGL_ANGLE|WEBGL_USE_HARDWARE)\|", e)]
print(" the compositing/WebGL ones: " + "; ".join(comp))
else:
print(" effective_prefs.json missing")
sf = arm_dir / "troubleshoot.json"
if sf.is_file():
data = json.loads(sf.read_text(encoding="utf-8"))
g = data.get("graphics", {})
print(" Troubleshoot graphics.windowLayerManagerType = %s, windowLayerManagerRemote = %s, windowProtocol = %s"
% (g.get("windowLayerManagerType"), g.get("windowLayerManagerRemote"), g.get("windowProtocol")))
lines: List[str] = []
flatten("", g, lines)
for l in lines:
key = l.split(" = ")[0]
if re.search(r"(?i)compositing|webrender|d3d11|warp|gpu.?process|description|adapter|failure|blocklist|layermanager", key) or re.search(r"(?i)FEATURE_|WebRender|D3D11|WARP", l):
print(" " + l[:240])
else:
print(" troubleshoot.json missing")
sys.stdout.flush()
# ---------------------------------------------------------------------------------------------------------------- the diff
def graphics_section(text: str) -> List[str]:
"""The lines of the Graphics section of about:support's innerText (from the heading to the next known heading)."""
lines = [re.sub(r"[ \t]+", " ", l).strip() for l in text.splitlines()]
lines = [l for l in lines if l]
stops = {"media", "audio", "internationalization & localization", "accessibility", "library versions", "experimental features",
"sandbox", "safe mode", "startup cache", "winsock lsps", "remote processes", "environment variables", "normandy",
"mozilla crash reports", "javascript", "place database", "extensions", "security software", "user javascript settings"}
start = next((i for i, l in enumerate(lines) if l.lower() == "graphics"), None)
if start is None:
return ["<no 'Graphics' heading found in about:support>"]
out = []
for l in lines[start:]:
if out and l.lower() in stops:
break
out.append(l)
return out
def flatten(prefix: str, value: Any, out: List[str]) -> None:
if isinstance(value, dict):
for k in sorted(value):
flatten("%s.%s" % (prefix, k) if prefix else str(k), value[k], out)
elif isinstance(value, list):
for i, v in enumerate(value):
flatten("%s[%d]" % (prefix, i), v, out)
else:
out.append("%s = %s" % (prefix, value))
def snapshot_lines(path: Path, keys: Tuple[str, ...]) -> Dict[str, List[str]]:
data = json.loads(path.read_text(encoding="utf-8"))
return {k: (lambda o: (flatten("", data[k], o), o)[1])([]) for k in keys if k in data}
def side(title: str, a: List[str], b: List[str], limit: int = 400) -> None:
diff = [l for l in difflib.unified_diff(a, b, "ours", "stockheaded", lineterm="", n=0) if not l.startswith(("---", "+++", "@@"))]
print("-" * 100)
print("%s: %d lines (ours), %d lines (stockheaded), %d differing lines (- ours only, + stockheaded only)" % (title, len(a), len(b), len(diff)))
for l in diff[:limit]:
print(l[:300])
if len(diff) > limit:
print("... %d more" % (len(diff) - limit))
def read_prefs_js(path: Path) -> Dict[str, str]:
out: Dict[str, str] = {}
if path.is_file():
for m in re.finditer(r'user_pref\("([^"]+)",\s*(.*?)\);\s*$', path.read_text(encoding="utf-8", errors="replace"), re.M):
out[m.group(1)] = m.group(2)
return out
def diff_dir(root: Path) -> int:
ours, stock = root / "ours", root / "stockheaded"
print("=" * 100)
print("GRAPHICS DIFF, ours (-) against stockheaded (+)")
for a in (ours, stock):
r = a / "support_report.json"
if r.is_file():
rep = json.loads(r.read_text(encoding="utf-8"))
print("%s: juggler route: %s; troubleshoot route: %s" % (a.name, rep.get("juggler_route"),
rep.get("troubleshoot") or rep.get("privileged_error") or rep.get("launch_B_error")))
# about:support innerText, Graphics section
ta, tb = ours / "about_support.txt", stock / "about_support.txt"
if ta.is_file() and tb.is_file():
ga, gb = graphics_section(ta.read_text(encoding="utf-8")), graphics_section(tb.read_text(encoding="utf-8"))
side("about:support innerText, Graphics section", ga, gb)
for name, g in (("ours", ga), ("stockheaded", gb)):
print("-" * 100)
print("key lines of the Graphics section, %s:" % name)
for l in g:
if KEY_LINE.search(l):
print(" " + l[:240])
# the rest of the page, for what is not in Graphics (Remote Processes, Environment Variables, Important Modified Preferences ...)
fa = [re.sub(r"[ \t]+", " ", l).strip() for l in ta.read_text(encoding="utf-8").splitlines() if l.strip()]
fb = [re.sub(r"[ \t]+", " ", l).strip() for l in tb.read_text(encoding="utf-8").splitlines() if l.strip()]
side("about:support innerText, WHOLE page", fa, fb, limit=300)
else:
print("about:support innerText missing for: %s" % ", ".join(n for n, p in (("ours", ta), ("stockheaded", tb)) if not p.is_file()))
# Troubleshoot data
sa, sb = ours / "troubleshoot.json", stock / "troubleshoot.json"
if sa.is_file() and sb.is_file():
la, lb = snapshot_lines(sa, GRAPHICS_KEYS), snapshot_lines(sb, GRAPHICS_KEYS)
for key in GRAPHICS_KEYS:
if key in la or key in lb:
side("Troubleshoot.snapshot().%s" % key, la.get(key, []), lb.get(key, []))
for name, lines in (("ours", la.get("graphics", [])), ("stockheaded", lb.get("graphics", []))):
print("-" * 100)
print("key lines of Troubleshoot graphics, %s:" % name)
for l in lines:
if KEY_LINE.search(l):
print(" " + l[:240])
else:
print("troubleshoot.json missing for: %s" % ", ".join(n for n, p in (("ours", sa), ("stockheaded", sb)) if not p.is_file()))
# effective prefs
pa, pb = ours / "effective_prefs.json", stock / "effective_prefs.json"
if pa.is_file() and pb.is_file():
ea, eb = json.loads(pa.read_text(encoding="utf-8")), json.loads(pb.read_text(encoding="utf-8"))
names = sorted(set(ea) | set(eb))
rows = [(n, ea.get(n), eb.get(n)) for n in names if ea.get(n) != eb.get(n)]
print("-" * 100)
print("EFFECTIVE prefs that differ (name: ours [user-set, value] | stockheaded [user-set, value]); %d of %d read" % (len(rows), len(names)))
for family in ("gfx.", "layers.", "webgl.", "widget.", "media.", "dom.", "other"):
sel = [r for r in rows if (r[0].startswith(family) if family != "other" else not r[0].startswith(
("gfx.", "layers.", "webgl.", "widget.", "media.", "dom.")))]
if sel:
print(" [%s*] %d" % (family, len(sel)))
for n, x, y in sel[:250]:
print(" %s: %s | %s" % (n, json.dumps(x)[:90] if x is not None else "-", json.dumps(y)[:90] if y is not None else "-"))
else:
print("effective_prefs.json missing for: %s" % ", ".join(n for n, p in (("ours", pa), ("stockheaded", pb)) if not p.is_file()))
# the profile's own files
for fname in ("user.js", "prefs.js"):
da, db = read_prefs_js(ours / fname), read_prefs_js(stock / fname)
rows = [(n, da.get(n), db.get(n)) for n in sorted(set(da) | set(db)) if da.get(n) != db.get(n)]
rel = [r for r in rows if re.match(PREF_FAMILIES, r[0])]
print("-" * 100)
print("%s of the profile: %d prefs in ours, %d in stockheaded, %d differ (%d in the gfx/layers/... families)"
% (fname, len(da), len(db), len(rows), len(rel)))
for n, x, y in rel[:200]:
print(" %s: %s | %s" % (n, x if x is not None else "-", y if y is not None else "-"))
return 0
# ------------------------------------------------------------------------------------------------------------- the profile
GPU_THREADS = "Compositor,Renderer,RenderBackend,WRWorker,CanvasRenderer,GeckoMain"
def wait_until_no_firefox(timeout: float) -> str:
"""The profiles are written when each process shuts down: let them finish (the first GPU profile came back truncated)."""
end = time.time() + timeout
left = firefox_processes()
while left and time.time() < end:
time.sleep(1)
left = firefox_processes()
return "firefox processes left after %.0f s: %d%s" % (timeout - max(0.0, end - time.time()), len(left),
(" (%s)" % ", ".join("%s %s" % (p["pid"], p["kind"]) for p in left)) if left else "")
def profile_run(arm: str, binary: str, out: Path, rnd: int, gpu: bool = False, rounds: int = 0, browsers: int = 0, filters: str = "") -> int:
import hunt_cpu_per_browser as hunt
out.mkdir(parents=True, exist_ok=True)
pattern = str(out / "profile-%p.json")
if gpu:
# ONE question: where does the GPU process spend its CPU. Only the threads that matter there are sampled (the filter is read by
# EVERY process, so the parent and the tabs keep their GeckoMain too, which is cheap), a small buffer (1 Mi entries, 8 MiB: the
# first run's file was truncated) and a short loop. No `js`: nothing in the GPU process runs JS.
os.environ.update({
"MOZ_PROFILER_STARTUP": "1",
"MOZ_PROFILER_STARTUP_FEATURES": "stackwalk,cpu,threads,processcpu",
"MOZ_PROFILER_STARTUP_FILTERS": filters or GPU_THREADS,
"MOZ_PROFILER_STARTUP_ENTRIES": "1048576",
"MOZ_PROFILER_STARTUP_INTERVAL": "2",
"MOZ_PROFILER_SHUTDOWN": pattern,
})
hunt.ROUNDS = rounds or 3
hunt.BROWSERS = browsers or hunt.BROWSERS
else:
os.environ.update({
"MOZ_PROFILER_STARTUP": "1",
"MOZ_PROFILER_STARTUP_FEATURES": "js,stackwalk,cpu,threads,processcpu",
"MOZ_PROFILER_STARTUP_FILTERS": "*",
"MOZ_PROFILER_STARTUP_INTERVAL": "2",
"MOZ_PROFILER_SHUTDOWN": pattern,
})
if rounds:
hunt.ROUNDS = rounds
if browsers:
hunt.BROWSERS = browsers
print("profile arm %s%s: %s; %d browsers x %d rounds" % (arm, " (GPU-process profile)" if gpu else "", pattern, hunt.BROWSERS, hunt.ROUNDS))
print("profiler environment: " + ", ".join("%s=%s" % (k, v) for k, v in sorted(os.environ.items()) if k.startswith("MOZ_PROFILER_")))
if is_ours(arm):
print(let_profiler_env_through())
kill_firefox()
result = hunt.run_arm(arm, binary, rnd)
hunt.print_arm(result)
print(wait_until_no_firefox(90))
kill_firefox()
time.sleep(3)
files = sorted(out.glob("profile-*.json"))
total = 0
for f in files:
raw = f.read_bytes()
total += len(raw)
try:
json.loads(raw.decode("utf-8", "replace"))
state = "valid JSON"
except ValueError as exc:
state = "NOT VALID JSON (%s), ends with %r" % (str(exc)[:100], raw[-80:])
print(" %s: %.1f MB, %s" % (f.name, len(raw) / 2 ** 20, state))
with gzip.open(str(f) + ".gz", "wb", 6) as g:
g.write(raw)
f.unlink()
print("profile files written by the processes: %d (%.1f MB raw), gzipped in %s" % (len(files), total / 2 ** 20, out))
if not files:
print("NO PROFILE FILES: the variables did not arrive, the profiler is not in this build, or the processes were killed instead of closed")
(out / "cpu_profiled.json").write_text(json.dumps(result, indent=1), encoding="utf-8")
return 0
def main() -> int:
ap = argparse.ArgumentParser()
sub = ap.add_subparsers(dest="cmd", required=True)
for name in ("support", "profile"):
p = sub.add_parser(name)
p.add_argument("--arm", choices=("ours", "ours_swwr", "ours_vmretail", "stockheaded"), required=True)
p.add_argument("--binary", default=os.environ.get("INVPW_BINARY_PATH", ""))
p.add_argument("--out", type=Path, required=True, help="the root; the arm's files go in <out>/<arm>/")
p.add_argument("--round", type=int, default=1)
if name == "profile":
p.add_argument("--gpu", action="store_true", help="the GPU-process profile: filtered threads, small buffer, short loop")
p.add_argument("--rounds", type=int, default=0, help="scenes per browser (default 10, 3 with --gpu)")
p.add_argument("--browsers", type=int, default=0)
p.add_argument("--filters", default="", help="MOZ_PROFILER_STARTUP_FILTERS for --gpu (default: the six GPU-process threads; '*' = every thread)")
d = sub.add_parser("diff")
d.add_argument("root", type=Path)
args = ap.parse_args()
if args.cmd == "diff":
return diff_dir(args.root)
if is_ours(args.arm) and not args.binary:
ap.error("the ours arms need --binary (or INVPW_BINARY_PATH)")
arm_dir = args.out / args.arm
if args.cmd == "support":
report = asyncio.run(support_arm(args.arm, args.binary, arm_dir))
print_support(report)
print_compositing(arm_dir)
return 0
return profile_run(args.arm, args.binary, arm_dir, args.round, gpu=args.gpu, rounds=args.rounds, browsers=args.browsers,
filters=args.filters)
if __name__ == "__main__":
sys.exit(main())
+585
View File
@@ -0,0 +1,585 @@
"""HUNT ONLY (branch hunt/cpu-render-path, never merged): "same seed, same bytes" - why are the PNG outputs of the canvas not the same between two launches?
python scripts/hunt_encoding.py collect --client ours --label ours --binary "$FF" --out DIR [--launches 2]
python scripts/hunt_encoding.py collect --client ours --label ours_pypi052 [--binary B] --out DIR # run by the venv python that has invisible-playwright==0.52.0
python scripts/hunt_encoding.py collect --client stock --label stockheaded [--headless] --out DIR
python scripts/hunt_encoding.py collect --client retail --label retail --retail-from DIR --out DIR # Mozilla's retail, launched by hand (hunt_first_run.py fetch-retail)
python scripts/hunt_encoding.py table DIR [DIR ...]
python scripts/hunt_encoding.py selftest # the PNG parser against PNGs whose chunks are known
The 11 keys that were not stable inside an arm (seed 42, two launches) in scripts/hunt_page_bytes.py: the PNG (toDataURL, toBlob, convertToBlob) of the
2D scenes shapes, composite, image, text, of the OffscreenCanvas and of the WebGL 1 and 2 triangle; their pixels (getImageData, readPixels), their
JPEG and WebP were stable.
collect launches the client `--launches` times and evaluates scripts/hunt_page_bytes_probe.js in ENCODING MODE (see its header): for each of those scenes
the pixels of the draw, the raw bytes of three toDataURL and three toBlob on the same canvas in the same page, and the pixels the browser decodes
from the first PNG. One gzipped JSON per launch: DIR/<label>-<n>.json.gz. This file imports nothing of this repository: it runs in the venv of the
published wrapper as well as in the checkout's, and with stock Playwright (the client `stock`, imported by name).
table reads one or more DIRs (one per runner) and prints, per arm and per key: whether the DRAW is the same (pixels), whether the PNGs are the same
between two launches on the same runner, inside one page (three calls), between two runners, and for every pair of PNGs that differ WHAT differs:
a chunk other than IDAT, only the deflate stream (same inflated data), only the filter choice (same pixels), or the pixels themselves.
PNG chunks are read here as the PNG specification lays them out (length, type, data, CRC-32; each CRC checked, IHDR first, IDATs consecutive, IEND last),
the IDATs inflated and unfiltered, so that nothing is guessed from a hash. For every pair that differs the table prints WHICH BYTES (runs of offsets, and
the chunk and field each falls in), whether the inflated IDAT data is identical, and the 16-character `deBG` text of every launch.
WHAT THE `deBG` CHUNK IS (found in the run of 2026-11-14): upstream Mozilla's image/encoders/png/nsPNGEncoder.cpp, MaybeAddCustomMetadata, writes it with the
letters 'd','e','B','G' set one by one (so `git grep deBG` finds nothing): 16 hex characters of a hash of the session's fingerprinting randomization key and the
image, after the IDATs, when canvas extraction is in the EfficientRandomize mode (privacy.baselineFingerprintingProtection, which the core turns on to match retail
151; invisible_core/prefs.py). The key is random per browsing session: the pixels are the same, the chunk is not. `collect --client retail` asks whether Mozilla's
own retail 159 writes it too.
"""
from __future__ import annotations
import argparse
import base64
import gzip
import hashlib
import importlib
import json
import re
import struct
import sys
import threading
import zlib
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
HERE = Path(__file__).resolve().parent
SEED = 42
class Blank(BaseHTTPRequestHandler):
def do_GET(self): # noqa: N802
body = b"<!doctype html><meta charset=utf-8><title>probe</title><body></body>"
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *a): # noqa: D102
pass
def probe_expression() -> str:
return "globalThis.__ENCODING_MODE = true;\n" + (HERE / "hunt_page_bytes_probe.js").read_text(encoding="utf-8")
class Retail(BaseHTTPRequestHandler):
"""The page of the client `retail`: runs the probe and posts its result back (nothing drives the browser)."""
result: Optional[str] = None
def _send(self, body: bytes, ctype: str) -> None:
self.send_response(200)
self.send_header("Content-Type", ctype)
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(body)
def do_GET(self): # noqa: N802
if self.path.startswith("/probe.js"):
self._send((HERE / "hunt_page_bytes_probe.js").read_bytes(), "text/javascript; charset=utf-8")
else:
self._send(b"<!doctype html><meta charset=utf-8><title>probe</title><body><script>globalThis.__ENCODING_MODE = true;"
b"fetch('/probe.js').then(r => r.text()).then(src => (0, eval)(src))"
b".then(o => fetch('/result', {method: 'POST', body: JSON.stringify(o)}))"
b".catch(e => fetch('/result', {method: 'POST', body: JSON.stringify({error: String(e)})}));</script></body>", "text/html; charset=utf-8")
def do_POST(self): # noqa: N802
n = int(self.headers.get("Content-Length") or 0)
Retail.result = self.rfile.read(n).decode("utf-8")
self._send(b"ok", "text/plain")
def log_message(self, *a): # noqa: D102
pass
def collect_retail(exe: str) -> Dict[str, Any]:
import subprocess
import tempfile
import time
Retail.result = None
httpd = ThreadingHTTPServer(("127.0.0.1", 0), Retail)
httpd.daemon_threads = True
threading.Thread(target=httpd.serve_forever, daemon=True).start()
url = "http://127.0.0.1:%d/" % httpd.server_address[1]
profile = Path(tempfile.mkdtemp(prefix="hunt-retail-profile-"))
proc = subprocess.Popen([exe, "-no-remote", "-profile", str(profile), url], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
try:
end = time.time() + 90
while Retail.result is None and time.time() < end:
time.sleep(0.5)
if Retail.result is None:
raise RuntimeError("retail answered nothing in 90 s")
data = json.loads(Retail.result)
if "error" in data and len(data) == 1:
raise RuntimeError("the probe failed in the page: %s" % data["error"])
return data
finally:
if sys.platform == "win32":
subprocess.run(["taskkill", "/F", "/T", "/PID", str(proc.pid)], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
subprocess.run(["taskkill", "/F", "/IM", "firefox.exe", "/T"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
else:
proc.kill()
httpd.shutdown()
def collect_once(client: str, binary: str, headless: bool) -> Dict[str, Any]:
if client == "retail":
return collect_retail(binary)
httpd = ThreadingHTTPServer(("127.0.0.1", 0), Blank)
httpd.daemon_threads = True
threading.Thread(target=httpd.serve_forever, daemon=True).start()
url = "http://127.0.0.1:%d/" % httpd.server_address[1]
try:
if client == "ours":
from invisible_playwright import InvisiblePlaywright
kwargs: Dict[str, Any] = {"seed": SEED, "headless": True, "locale": "en-US", "timezone": "Europe/Rome"}
if binary:
kwargs["binary_path"] = binary
try:
browser_cm = InvisiblePlaywright(**kwargs)
except TypeError as exc: # an older wrapper without one of the keywords
print(" InvisiblePlaywright(%s) refused (%s): launching with seed, headless and binary only" % (sorted(kwargs), exc))
kwargs = {k: v for k, v in kwargs.items() if k in ("seed", "headless", "binary_path")}
browser_cm = InvisiblePlaywright(**kwargs)
with browser_cm as browser:
page = browser.new_page()
page.goto(url, wait_until="load", timeout=60000)
return page.evaluate(probe_expression())
sync_playwright = importlib.import_module("playwright.sync_api").sync_playwright # by name: the fork's guard forbids a static import
with sync_playwright() as pw:
browser = pw.firefox.launch(headless=headless, firefox_user_prefs={"fission.autostart": True})
try:
page = browser.new_page()
page.goto(url, wait_until="load", timeout=60000)
return page.evaluate(probe_expression())
finally:
browser.close()
finally:
httpd.shutdown()
def collect(args) -> int:
args.out.mkdir(parents=True, exist_ok=True)
try:
import invisible_playwright
version = getattr(invisible_playwright, "__version__", "?")
except Exception: # noqa: BLE001
version = "not importable"
print("collect: client %s, label %s, invisible_playwright %s, binary %s" % (args.client, args.label, version, args.binary or "(the wrapper's own)"))
rc = 0
for n in range(1, args.launches + 1):
try:
data = collect_once(args.client, args.binary, args.headless)
except BaseException as exc: # noqa: BLE001
print(" launch %d FAILED: %s: %s" % (n, type(exc).__name__, str(exc)[:400]))
rc = 1
continue
path = args.out / ("%s-%d.json.gz" % (args.label, n))
with gzip.open(path, "wt", encoding="utf-8") as f:
json.dump(data, f)
print(" launch %d: %d keys -> %s; ua %s" % (n, len(data), path, (data.get("env.ua") or {}).get("s")))
sys.stdout.flush()
return rc
# ------------------------------------------------------------------------------------------------------------------- the PNG
SIGNATURE = b"\x89PNG\r\n\x1a\n"
def sha(b: bytes) -> str:
return hashlib.sha1(b).hexdigest()[:12]
def parse_png(data: bytes) -> Dict[str, Any]:
"""Chunks of a PNG, read as the PNG specification (ISO/IEC 15948) lays them out and CHECKED against it.
Each chunk is: length (4 bytes, big endian, of the data only) + type (4 ASCII letters) + data + CRC-32 (4 bytes, big endian, of type + data).
Returns {"chunks": [{type, offset, length, crc, crc_ok, data_offset}], "problems": [...], "idat": bytes}. Offsets are absolute, from the first byte of the file.
A problem is anything the specification forbids: a bad signature, a wrong CRC, a chunk running past the end, IHDR not first or not 13 bytes, no IDAT, IDAT chunks
that are not consecutive, IEND not last or not empty, a type that is not four letters, bytes after IEND.
"""
problems: List[str] = []
chunks: List[Dict[str, Any]] = []
if data[:8] != SIGNATURE:
return {"chunks": [], "problems": ["bad signature %r" % data[:8]], "idat": b""}
pos = 8
while pos < len(data):
if pos + 12 > len(data):
problems.append("%d trailing byte(s) too short for a chunk at offset %d" % (len(data) - pos, pos))
break
length = struct.unpack(">I", data[pos:pos + 4])[0]
ctype = data[pos + 4:pos + 8]
if length > 0x7FFFFFFF or pos + 12 + length > len(data):
problems.append("chunk %r at offset %d claims %d data bytes, the file ends at %d" % (ctype, pos, length, len(data)))
break
body = data[pos + 8:pos + 8 + length]
crc = struct.unpack(">I", data[pos + 8 + length:pos + 12 + length])[0]
ok = (zlib.crc32(ctype + body) & 0xFFFFFFFF) == crc
if not re.fullmatch(rb"[A-Za-z]{4}", ctype):
problems.append("chunk type %r at offset %d is not four letters" % (ctype, pos))
if not ok:
problems.append("CRC of %r at offset %d is %08x, computed %08x" % (ctype, pos, crc, zlib.crc32(ctype + body) & 0xFFFFFFFF))
chunks.append({"type": ctype.decode("latin1"), "offset": pos, "length": length, "crc": crc, "crc_ok": ok, "data_offset": pos + 8})
pos += 12 + length
if ctype == b"IEND":
if pos != len(data):
problems.append("%d byte(s) after IEND" % (len(data) - pos))
break
types = [c["type"] for c in chunks]
if not types or types[0] != "IHDR":
problems.append("the first chunk is %s, not IHDR" % (types[0] if types else "missing"))
elif chunks[0]["length"] != 13:
problems.append("IHDR has %d data bytes, not 13" % chunks[0]["length"])
if "IDAT" not in types:
problems.append("no IDAT")
else:
idx = [i for i, t in enumerate(types) if t == "IDAT"]
if idx != list(range(idx[0], idx[-1] + 1)):
problems.append("the IDAT chunks are not consecutive")
if not types or types[-1] != "IEND":
problems.append("the last chunk is %s, not IEND" % (types[-1] if types else "missing"))
elif chunks[-1]["length"] != 0:
problems.append("IEND has data")
idat = b"".join(data[c["data_offset"]:c["data_offset"] + c["length"]] for c in chunks if c["type"] == "IDAT")
return {"chunks": chunks, "problems": problems, "idat": idat}
def unfilter(raw: bytes, w: int, h: int, bpp: int) -> Tuple[bytes, List[int]]:
stride = w * bpp
out = bytearray()
prev = bytearray(stride)
pos = 0
filters: List[int] = []
for _ in range(h):
ft = raw[pos]
pos += 1
row = bytearray(raw[pos:pos + stride])
pos += stride
filters.append(ft)
if ft == 1:
for i in range(bpp, stride):
row[i] = (row[i] + row[i - bpp]) & 255
elif ft == 2:
for i in range(stride):
row[i] = (row[i] + prev[i]) & 255
elif ft == 3:
for i in range(stride):
left = row[i - bpp] if i >= bpp else 0
row[i] = (row[i] + ((left + prev[i]) >> 1)) & 255
elif ft == 4:
for i in range(stride):
a = row[i - bpp] if i >= bpp else 0
b = prev[i]
c = prev[i - bpp] if i >= bpp else 0
p = a + b - c
pa, pb, pc = abs(p - a), abs(p - b), abs(p - c)
pr = a if (pa <= pb and pa <= pc) else (b if pb <= pc else c)
row[i] = (row[i] + pr) & 255
out += row
prev = row
return bytes(out), filters
_cache: Dict[str, Dict[str, Any]] = {}
def png_facts(data: bytes) -> Dict[str, Any]:
key = sha(data)
if key in _cache:
return _cache[key]
p = parse_png(data)
f: Dict[str, Any] = {"sha": key, "size": len(data), "chunks": p["chunks"], "problems": p["problems"]}
if p["chunks"] and p["chunks"][0]["type"] == "IHDR" and p["chunks"][0]["length"] == 13:
o = p["chunks"][0]["data_offset"]
w, h, depth, ctype, _comp, _filt, interlace = struct.unpack(">IIBBBBB", data[o:o + 13])
f["ihdr"] = {"w": w, "h": h, "depth": depth, "color_type": ctype, "interlace": interlace}
try:
raw = zlib.decompress(p["idat"])
f["raw_sha"] = sha(raw)
channels = {0: 1, 2: 3, 4: 2, 6: 4}.get(ctype)
if channels and depth == 8 and interlace == 0 and len(raw) == h * (w * channels + 1):
pixels, filters = unfilter(raw, w, h, channels)
f["pixels"], f["pixel_sha"], f["channels"] = pixels, sha(pixels), channels
f["filters"] = {t: filters.count(t) for t in sorted(set(filters))}
else:
f["pixel_note"] = "not unfiltered (type %d depth %d interlace %d, inflated %d bytes for %dx%d)" % (ctype, depth, interlace, len(raw), w, h)
except zlib.error as exc:
f["problems"] = f["problems"] + ["inflate: %s" % exc]
_cache[key] = f
return f
def chunk_summary(data: bytes) -> str:
"""`IHDR 13 crc e319b23c | IDAT 8192 ... | deBG 16 ...` - the real chunks, in order."""
f = png_facts(data)
return " | ".join("%s %d crc %08x%s" % (c["type"], c["length"], c["crc"], "" if c["crc_ok"] else " BAD") for c in f["chunks"]) or "(no chunk)"
def field_of(chunks: List[Dict[str, Any]], offset: int) -> str:
for c in chunks:
if c["offset"] <= offset < c["offset"] + 12 + c["length"]:
rel = offset - c["offset"]
part = "length" if rel < 4 else ("type" if rel < 8 else ("data" if rel < 8 + c["length"] else "CRC"))
return "%s %s" % (c["type"], part)
return "outside every chunk"
def byte_report(a: bytes, b: bytes) -> str:
"""WHICH BYTES differ: runs of offsets, and for each the chunk and the field (length, type, data, CRC) it falls in."""
if a == b:
return "identical"
if len(a) != len(b):
return "lengths differ (%d against %d bytes)" % (len(a), len(b))
ca = png_facts(a)["chunks"]
runs: List[Tuple[int, int]] = []
for i, (x, y) in enumerate(zip(a, b)):
if x != y:
if runs and runs[-1][1] == i - 1:
runs[-1] = (runs[-1][0], i)
else:
runs.append((i, i))
total = sum(e - s + 1 for s, e in runs)
where = []
for s, e in runs[:8]:
fields = {field_of(ca, i) for i in range(s, e + 1)}
where.append("%d..%d (%d byte%s: %s)" % (s, e, e - s + 1, "" if e == s else "s", ", ".join(sorted(fields))))
return "%d of %d bytes differ in %d run(s): %s%s" % (total, len(a), len(runs), "; ".join(where), "; ..." if len(runs) > 8 else "")
def compare_png(a: bytes, b: bytes) -> str:
"""Short word for what differs between two PNGs; the chunks are compared one by one, the IDATs inflated and unfiltered."""
if a == b:
return "same"
fa, fb = png_facts(a), png_facts(b)
if fa["problems"] or fb["problems"]:
return "INVALID PNG (%s | %s)" % ("; ".join(fa["problems"][:2]) or "ok", "; ".join(fb["problems"][:2]) or "ok")
ta = [(c["type"], c["length"]) for c in fa["chunks"]]
tb = [(c["type"], c["length"]) for c in fb["chunks"]]
differing = []
if [t for t, _ in ta] == [t for t, _ in tb]:
# same chunk list: which chunks have different data or CRC
for i, (ca, cb) in enumerate(zip(fa["chunks"], fb["chunks"])):
if (ca["length"], ca["crc"]) != (cb["length"], cb["crc"]) or a[ca["data_offset"]:ca["data_offset"] + ca["length"]] != b[cb["data_offset"]:cb["data_offset"] + cb["length"]]:
differing.append(ca["type"])
else:
return "chunk list differs (%s | %s)" % (",".join(t for t, _ in ta), ",".join(t for t, _ in tb))
non_idat = sorted(set(t for t in differing if t != "IDAT"))
idat_state = ""
if "IDAT" in differing:
if fa.get("raw_sha") == fb.get("raw_sha"):
idat_state = "IDAT: same inflated data, only the deflate stream differs (%d / %d bytes)" % (len(png_facts(a)["chunks"]), len(png_facts(b)["chunks"]))
idat_state = "IDAT: same inflated data, only the deflate stream differs"
elif "pixels" in fa and "pixels" in fb and fa["pixel_sha"] == fb["pixel_sha"]:
idat_state = "IDAT: same pixels, other filter choice"
elif "pixels" in fa and "pixels" in fb and len(fa["pixels"]) == len(fb["pixels"]):
x, y = fa["pixels"], fb["pixels"]
diff = [i for i in range(len(x)) if x[i] != y[i]]
px = diff[0] // fa["channels"]
idat_state = "IDAT: PIXELS differ (%d of %d bytes, largest delta %d, first at (%d, %d))" % (
len(diff), len(x), max(abs(x[i] - y[i]) for i in diff), px % fa["ihdr"]["w"], px // fa["ihdr"]["w"])
else:
idat_state = "IDAT: inflated data differs"
elif fa.get("raw_sha") == fb.get("raw_sha") and fa.get("pixel_sha") == fb.get("pixel_sha"):
idat_state = "IDAT identical, pixels identical"
parts = []
if non_idat:
parts.append("only the %s chunk%s differ%s" % ("+".join(non_idat), "" if len(non_idat) == 1 else "s", "s" if len(non_idat) == 1 else "") if not idat_state.startswith("IDAT:") else
"the %s chunk%s and IDAT differ" % ("+".join(non_idat), "" if len(non_idat) == 1 else "s"))
return "; ".join(parts + [idat_state]) if parts else idat_state
def deBG_text(data: bytes) -> str:
f = png_facts(data)
for c in f["chunks"]:
if c["type"] == "deBG":
return data[c["data_offset"]:c["data_offset"] + c["length"]].decode("latin1")
return "-"
def selftest() -> int:
"""The parser against PNGs whose chunks are known."""
def chunk(t: bytes, body: bytes, bad: bool = False) -> bytes:
crc = zlib.crc32(t + body) & 0xFFFFFFFF
return struct.pack(">I", len(body)) + t + body + struct.pack(">I", crc ^ (1 if bad else 0))
# 1. a known 1x1 RGBA PNG (the smallest one browsers produce); its IHDR and IEND CRCs are known.
one = base64.b64decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==")
p = parse_png(one)
got = [(c["type"], c["length"], "%08x" % c["crc"], c["crc_ok"]) for c in p["chunks"]]
assert p["problems"] == [], p["problems"]
assert [(t, n, ok) for t, n, _c, ok in got] == [("IHDR", 13, True), ("IDAT", 13, True), ("IEND", 0, True)], got
assert got[0][2] == "1f15c489" and got[2][2] == "ae426082", got # the CRCs of this IHDR and of every IEND: known from any PNG tool
f = png_facts(one)
assert (f["ihdr"]["w"], f["ihdr"]["h"], f["ihdr"]["depth"], f["ihdr"]["color_type"]) == (1, 1, 8, 6), f["ihdr"]
assert len(f["pixels"]) == 4, f
# 2. a PNG built here with an ancillary chunk after IDAT, as nsPNGEncoder writes deBG
ihdr = struct.pack(">IIBBBBB", 2, 2, 8, 6, 0, 0, 0)
raw = b"".join(b"\x00" + bytes([i, 0, 0, 255, 0, i, 0, 255]) for i in (10, 20))
img = SIGNATURE + chunk(b"IHDR", ihdr) + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"deBG", b"B78D4FA4CD83BABE") + chunk(b"IEND", b"")
p2 = parse_png(img)
assert p2["problems"] == [] and [c["type"] for c in p2["chunks"]] == ["IHDR", "IDAT", "deBG", "IEND"], p2
assert deBG_text(img) == "B78D4FA4CD83BABE"
other = SIGNATURE + chunk(b"IHDR", ihdr) + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"deBG", b"0123456789ABCDEF") + chunk(b"IEND", b"")
assert compare_png(img, other).startswith("only the deBG chunk differs"), compare_png(img, other)
assert "IDAT identical" in compare_png(img, other)
assert "12 of" not in byte_report(img, other) and "deBG data" in byte_report(img, other), byte_report(img, other)
recompressed = SIGNATURE + chunk(b"IHDR", ihdr) + chunk(b"IDAT", zlib.compress(raw, 0)) + chunk(b"deBG", b"B78D4FA4CD83BABE") + chunk(b"IEND", b"")
assert "same inflated data" in compare_png(img, recompressed), compare_png(img, recompressed)
# 3. what the parser must refuse
bad_crc = SIGNATURE + chunk(b"IHDR", ihdr) + chunk(b"IDAT", zlib.compress(raw), bad=True) + chunk(b"IEND", b"")
assert any("CRC" in x for x in parse_png(bad_crc)["problems"])
no_idat = SIGNATURE + chunk(b"IHDR", ihdr) + chunk(b"IEND", b"")
assert "no IDAT" in parse_png(no_idat)["problems"]
assert parse_png(b"not a png")["problems"][0].startswith("bad signature")
cut = img[:-7]
assert parse_png(cut)["problems"], "a truncated file must have a problem"
print("selftest: the PNG parser reads the known 1x1 PNG (IHDR crc 1f15c489, IEND crc ae426082), the deBG layout, tells deBG-only, deflate-only and bad files apart: ok")
return 0
# ------------------------------------------------------------------------------------------------------------------ the table
def load(dirs: List[Path]) -> Dict[str, Dict[str, List[Dict[str, Any]]]]:
"""{arm label: {runner dir name: [launch data...]}}"""
out: Dict[str, Dict[str, List[Dict[str, Any]]]] = {}
for d in dirs:
for f in sorted(d.glob("*-*.json.gz")):
label = f.name.rsplit("-", 1)[0]
with gzip.open(f, "rt", encoding="utf-8") as g:
out.setdefault(label, {}).setdefault(d.name, []).append(json.load(g))
return out
def raw(run: Dict[str, Any], key: str) -> Optional[bytes]:
v = run.get(key)
return base64.b64decode(v["b64"]) if v and "b64" in v else None
def scenes_of(run: Dict[str, Any]) -> List[str]:
return sorted({k[:-len(".getImageData")] for k in run if k.endswith(".getImageData")})
def pair_word(a: Optional[bytes], b: Optional[bytes]) -> str:
if a is None or b is None:
return "missing"
return compare_png(a, b)
def table(dirs: List[Path]) -> int:
data = load(dirs)
if not data:
print("no data in %s" % ", ".join(map(str, dirs)))
return 1
runners = [d.name for d in dirs]
print("=" * 120)
print("SAME SEED, SAME BYTES? seed %d; runners (legs): %s; arms: %s" % (SEED, ", ".join(runners), ", ".join(sorted(data))))
summary: List[str] = []
for arm in sorted(data):
legs = data[arm]
names = sorted(legs)
print("=" * 120)
print("ARM %s: %s" % (arm, ", ".join("runner %s %d launch(es)" % (r, len(l)) for r, l in sorted(legs.items()))))
ua = next(iter(next(iter(legs.values()))), {}).get("env.ua", {}).get("s")
print(" user agent: %s" % ua)
first = next(iter(legs.values()))[0]
scenes = scenes_of(first)
sample = raw(first, scenes[0] + ".png1") if scenes else None
if sample:
print(" the chunks of one PNG (type length crc, in file order; CRCs checked): %s" % chunk_summary(sample))
for sc in scenes:
print(" " + "-" * 116)
print(" %s" % sc)
px = {r: [raw(run, sc + ".getImageData") for run in l] for r, l in legs.items()}
all_px = {x for v in px.values() for x in v}
draw = "same in every launch of every runner" if len(all_px) == 1 else (
"DIFFERS inside a runner" if any(len(set(v)) > 1 for v in px.values()) else "differs across runners")
print(" draw (getImageData): %s" % draw)
valid, png_eq_px, dec_eq = [], [], []
inpage, blob_eq_png = set(), set()
for r, l in legs.items():
for run in l:
a1 = raw(run, sc + ".png1")
if a1 is None:
continue
f = png_facts(a1)
valid.append(not f["problems"])
g = raw(run, sc + ".getImageData")
if f.get("pixels") is not None and g is not None and f.get("channels") == 4:
png_eq_px.append(f["pixels"] == g)
d = raw(run, sc + ".png.decoded")
if d is not None and g is not None:
dec_eq.append(d == g)
p = [raw(run, sc + ".png%d" % i) for i in (1, 2, 3)]
inpage.add("identical" if p[0] == p[1] == p[2] else "DIFFER")
bl = [raw(run, sc + ".blob%d" % i) for i in (1, 2, 3)]
if bl[0] is not None:
inpage.add("toBlob x3 " + ("identical" if bl[0] == bl[1] == bl[2] else "DIFFER"))
blob_eq_png.add(bl[0] == a1)
print(" PNG valid against the specification (CRCs, order, IHDR/IDAT/IEND): %s" % ("all %d" % len(valid) if valid and all(valid) else "NO: " + ", ".join(
"; ".join(png_facts(raw(run, sc + '.png1'))['problems']) for l in legs.values() for run in l if png_facts(raw(run, sc + '.png1'))['problems'])))
print(" PNG pixels (IDAT inflated and unfiltered) == getImageData: %s; the pixels the browser decodes from the PNG == getImageData: %s" % (
"always" if png_eq_px and all(png_eq_px) else ("NOT always" if png_eq_px else "n/a"), "always" if dec_eq and all(dec_eq) else ("NOT always" if dec_eq else "n/a")))
print(" inside one page, three calls: %s; toBlob == toDataURL: %s" % ("toDataURL x3 " + "/".join(sorted(x for x in inpage if not x.startswith("toBlob"))) +
("; " + "/".join(sorted(x for x in inpage if x.startswith("toBlob"))) if any(x.startswith("toBlob") for x in inpage) else ""),
"yes" if blob_eq_png == {True} else ("no" if blob_eq_png else "n/a")))
deb = []
pair_words: List[str] = []
for r in names:
l = legs[r]
deb.append("%s: %s" % (r, ", ".join(deBG_text(raw(run, sc + ".png1") or b"") for run in l)))
if len(l) >= 2:
a, b = raw(l[0], sc + ".png1"), raw(l[1], sc + ".png1")
word = pair_word(a, b)
pair_words.append("%s: %s" % (r, word))
print(" launch 1 against launch 2, runner %s: %s" % (r, word))
if a is not None and b is not None and a != b:
print(" bytes: %s" % byte_report(a, b))
cross = ""
if len(names) >= 2:
a, b = raw(legs[names[0]][0], sc + ".png1"), raw(legs[names[1]][0], sc + ".png1")
cross = pair_word(a, b)
print(" runner %s launch 1 against runner %s launch 1: %s" % (names[0], names[1], cross))
if a is not None and b is not None and a != b:
print(" bytes: %s" % byte_report(a, b))
print(" deBG chunk data (16 ASCII hex characters) per launch: %s" % "; ".join(deb))
summary.append("%-14s %-24s | draw %s | PNG pixels == getImageData %s | launch~launch %s | cross-runner %s" % (
arm, sc, "same" if len(all_px) == 1 else "DIFF", "yes" if png_eq_px and all(png_eq_px) else "NO", " ; ".join(pair_words) or "-", cross or "-"))
print("=" * 120)
print("ONE LINE PER ARM AND KEY")
for line in summary:
print(" " + line)
return 0
def main() -> int:
ap = argparse.ArgumentParser()
sub = ap.add_subparsers(dest="cmd", required=True)
c = sub.add_parser("collect")
c.add_argument("--client", choices=("ours", "stock", "retail"), required=True)
c.add_argument("--retail-from", default="", help="retail: the --out of hunt_first_run.py fetch-retail (its retail.json names firefox.exe)")
c.add_argument("--label", required=True)
c.add_argument("--binary", default="")
c.add_argument("--headless", action="store_true", help="stock only: headless=True (default headed)")
c.add_argument("--out", type=Path, required=True)
c.add_argument("--launches", type=int, default=2)
sub.add_parser("selftest")
t = sub.add_parser("table")
t.add_argument("dirs", type=Path, nargs="+")
args = ap.parse_args()
if args.cmd == "selftest":
return selftest()
if args.cmd == "collect":
if args.client == "retail":
if not args.retail_from:
ap.error("--client retail needs --retail-from")
args.binary = json.loads((Path(args.retail_from) / "retail.json").read_text(encoding="utf-8"))["exe"]
return collect(args)
return table(args.dirs)
if __name__ == "__main__":
sys.exit(main())
+48
View File
@@ -0,0 +1,48 @@
"""HUNT ONLY (branch hunt/cpu-render-path, never merged): a pytest plugin that adds prefs to every browser the wrapper's own tests launch.
PYTHONPATH=scripts HUNT_EXTRA_PREFS='{"gfx.webrender.software": true}' python -m pytest -p hunt_extra_prefs_plugin tests/test_...py
The tests construct `InvisiblePlaywright(...)` (the sync class, tests/test_canvas_text_is_windows_e2e.py and others) or its async twin and
some of them pass `extra_prefs=` of their own. Nothing of the product and nothing of the tests is edited: this plugin wraps the two
`__init__` in place, in this process only, and merges HUNT_EXTRA_PREFS over the test's own extra_prefs (the hunt's value wins; the
test's other prefs stay). Without HUNT_EXTRA_PREFS the plugin does nothing, so the same command line runs the arm `ours`.
It prints one line per construction to a file (HUNT_EXTRA_PREFS_LOG, default <tmp>/hunt-extra-prefs.log) so that the run can say how many
browsers got the pref: a suite that launches its browser some other way would otherwise pass "with the pref" without having had it.
"""
from __future__ import annotations
import json
import os
import tempfile
_PREFS = json.loads(os.environ.get("HUNT_EXTRA_PREFS") or "{}")
_LOG = os.environ.get("HUNT_EXTRA_PREFS_LOG") or os.path.join(tempfile.gettempdir(), "hunt-extra-prefs.log")
def _wrap(cls) -> None:
original = cls.__init__
def __init__(self, *args, **kwargs): # noqa: N807
merged = dict(kwargs.get("extra_prefs") or {})
merged.update(_PREFS)
kwargs["extra_prefs"] = merged
try:
with open(_LOG, "a", encoding="utf-8") as f:
f.write("%s.%s seed=%s extra_prefs=%s\n" % (cls.__module__, cls.__name__, kwargs.get("seed"), json.dumps(merged, sort_keys=True)))
except OSError:
pass
original(self, *args, **kwargs)
__init__.__wrapped__ = original
cls.__init__ = __init__
def pytest_configure(config): # noqa: D103
if not _PREFS:
return
from invisible_playwright.async_api import InvisiblePlaywright as Async
from invisible_playwright.launcher import InvisiblePlaywright as Sync
_wrap(Sync)
_wrap(Async)
print("[hunt] extra_prefs %s added to every InvisiblePlaywright construction, logged to %s" % (json.dumps(_PREFS), _LOG))
+92
View File
@@ -0,0 +1,92 @@
"""HUNT ONLY (branch hunt/cpu-render-path, never merged): find the Breakpad symbols of our engine's xul.dll among the recent runs of the
engine's release.yml (artifact symbols-win-x86_64), and keep the zip whose xul.pdb/<breakpad id>/ matches the binary that was profiled.
python scripts/hunt_fetch_symbols.py --id ABC123... --out DIR [--run 123] [--repo oss-invisible/firefox_antidetect_patch]
The artifact of a candidate is kept 2 days, that of a release 14; the one that matches may have expired. At most MAX_DOWNLOADS artifacts
(about 400 MB each) are downloaded, newest first, unless --run names one. It needs `gh` and GH_TOKEN. Whatever happens, the exit code is 0
and the last line says `SYMBOLS: <path>` or `SYMBOLS: none (<why>)`.
"""
from __future__ import annotations
import argparse
import json
import shutil
import subprocess
import sys
import zipfile
from pathlib import Path
MAX_DOWNLOADS = 4
ARTIFACT = "symbols-win-x86_64"
def gh(*args: str, timeout: int = 900) -> str:
done = subprocess.run(["gh", *args], capture_output=True, text=True, timeout=timeout)
if done.returncode:
raise RuntimeError("gh %s: %s" % (" ".join(args[:3]), (done.stderr or done.stdout)[:300]))
return done.stdout
def candidates(repo: str, run: str) -> list:
if run:
return [run]
runs = json.loads(gh("run", "list", "-R", repo, "--workflow", "release.yml", "-L", "40", "--json", "databaseId,conclusion,createdAt"))
out = []
for r in runs:
try:
arts = json.loads(gh("api", "repos/%s/actions/runs/%s/artifacts?name=%s" % (repo, r["databaseId"], ARTIFACT)))["artifacts"]
except Exception as exc: # noqa: BLE001
print("run %s: %s" % (r["databaseId"], exc))
continue
if any(not a["expired"] for a in arts):
print("run %s (%s, %s): %s available" % (r["databaseId"], r["createdAt"], r["conclusion"], ARTIFACT))
out.append(str(r["databaseId"]))
return out
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--id", required=True, help="breakpad id of xul.dll in the profile")
ap.add_argument("--out", type=Path, required=True)
ap.add_argument("--run", default="")
ap.add_argument("--repo", default="oss-invisible/firefox_antidetect_patch")
args = ap.parse_args()
args.out.mkdir(parents=True, exist_ok=True)
try:
runs = candidates(args.repo, args.run)
except Exception as exc: # noqa: BLE001
print("SYMBOLS: none (listing the runs failed: %s)" % exc)
return 0
if not runs:
print("SYMBOLS: none (no run of release.yml has an unexpired %s)" % ARTIFACT)
return 0
for run in runs[:MAX_DOWNLOADS]:
tmp = args.out / ("dl-" + run)
try:
gh("run", "download", run, "-R", args.repo, "-n", ARTIFACT, "-D", str(tmp))
except Exception as exc: # noqa: BLE001
print("run %s: download failed: %s" % (run, exc))
shutil.rmtree(tmp, ignore_errors=True)
continue
for z in sorted(tmp.rglob("*.zip")):
try:
names = zipfile.ZipFile(z).namelist()
except Exception as exc: # noqa: BLE001
print("run %s: %s unreadable: %s" % (run, z.name, exc))
continue
pdbs = sorted({n.split("/")[1] for n in names if n.startswith("xul.pdb/") and n.count("/") >= 2})
print("run %s: %s has xul.pdb ids %s" % (run, z.name, pdbs))
if args.id in pdbs:
keep = args.out / ("symbols-%s.zip" % run)
shutil.move(str(z), keep)
shutil.rmtree(tmp, ignore_errors=True)
print("SYMBOLS: %s" % keep)
return 0
shutil.rmtree(tmp, ignore_errors=True)
print("SYMBOLS: none (the id %s is in none of the %d artifact(s) tried)" % (args.id, min(len(runs), MAX_DOWNLOADS)))
return 0
if __name__ == "__main__":
sys.exit(main())
+669
View File
@@ -0,0 +1,669 @@
"""HUNT ONLY (branch hunt/cpu-render-path, never merged): what happens in the first 80 seconds of a NEW profile, and what can a page read of it?
python scripts/hunt_first_run.py fetch-retail --out DIR [--retail-version 159.0] # once: Mozilla's installer, verified, unpacked
python scripts/hunt_first_run.py census --arm retail --retail-from DIR --out DIR2 # 1. the first 80 s of a fresh profile, in 10 s slices
python scripts/hunt_first_run.py census --arm ours --binary "$FF" --out DIR2
python scripts/hunt_first_run.py census-table DIR2 # ours and retail in one table
python scripts/hunt_first_run.py probe --arm retail_fresh|retail_used|ours_fresh|ours_used --mode seq|late ... --out DIR3 # 2. what a page reads
python scripts/hunt_first_run.py probe-table DIR3
THE QUESTION OF PART 1. In ours with a fresh profile the parent shows a ~15 s CPU burst between +8 and +50 s after the launch, with these downloads:
remote settings 18.9 MB, CRLite 6 MB, safebrowsing 8.5 MB, Widevine 23 MB, the newtab xpi; after that it drops to zero. Does retail Firefox 159.0 (the
stable release, Mozilla's installer checked against its SHA256SUMS, launched by hand: subprocess, -no-remote, a fresh profile, an idle local page, no
automation prefs, no Playwright, the environment untouched) show the same burst, with the same duration and the same downloads?
census one browser for 80 s. The parent's CPU per 10 s slice (the sampler of hunt_cpu_per_browser.py: NtQuerySystemInformation every 250 ms) and per
thread NAME per slice (hunt_cpu_baseline.Watcher: psutil threads + GetThreadDescription every 0.5 s); the files written in the PROFILE per slice
(the profile directory is walked every 2 s: path, size, grouped by top-level directory, and every file in gmp-*, security_state, safebrowsing,
settings, features, extensions listed with its size); the bytes received and sent by the machine's network interfaces per slice (psutil
net_io_counters, loopback excluded: the runner is otherwise idle, but its own agent traffic is in the number). A process that lives less than
the polling period is not seen; a file created and deleted between two walks is not seen.
Retail is closed at the end the way a user closes it (taskkill without /F, WM_CLOSE), so that the profile is left as a used one.
THE QUESTION OF PART 2. A page reads state that first-run downloads change: requestMediaKeySystemAccess waits for the Widevine download (it is rejected
after 60 s if there is none), the WebRTC H.264 entries depend on the OpenH264 GMP (and in ours on a declaration), and so on; the code that shows it is
cited in the table headings of probe-table. `probe` serves a page (scripts/hunt_first_run_probe.js) that runs every probe at +5, +20, +40 and +90 s after the
launch and posts, per probe and moment: the outcome (resolved, rejected, timeout), the time the probe took, and the value (the configuration returned, the
codec lists, ...). Arms: ours_fresh (a new profile_dir), ours_used (the same profile_dir, launched a second time after an 80 s first launch), retail_fresh,
retail_used (retail launched by hand a second time on the profile of the census). Modes: `seq` (all four moments in one launch: an early probe can start a
download, so a later one answers after it) and `late` (ONE moment, +90 s, nothing before it: it shows whether asking early changed the answer).
`probe-table` prints a table per probe and moment and then, for each arm family, the probes whose answer differs between a fresh and a used profile.
"""
from __future__ import annotations
import argparse
import asyncio
import contextlib
import json
import os
import re
import shutil
import statistics
import subprocess
import sys
import tempfile
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
import hunt_cpu_baseline as hb # noqa: E402
import hunt_cpu_per_browser as hunt # noqa: E402
WINDOW_S = 80.0
SLICE_S = 10.0
MOMENT_GRACE_S = 95.0 # a probe may wait 80 s: the run lasts until the last moment + this
WATCHED = re.compile(r"(?i)^(gmp-|security_state|safebrowsing|settings|features|extensions|datareporting|startupCache|storage|saved-telemetry|"
r"crashes|minidumps|sessionstore|bookmarkbackups|cache2|shader-cache|offlineCache)")
BIG = 100 * 1024
class Idle(BaseHTTPRequestHandler):
"""The page every browser of part 1 opens: nothing on it."""
t0_ms = 0
results: List[Dict[str, Any]] = []
lock = threading.Lock()
def _send(self, body: bytes, ctype: str = "text/html; charset=utf-8", code: int = 200) -> None:
self.send_response(code)
self.send_header("Content-Type", ctype)
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(body)
def do_GET(self): # noqa: N802
path = self.path.split("?")[0]
if path == "/t0":
self._send(str(Idle.t0_ms).encode(), "text/plain")
elif path == "/probe":
self._send(b'<!doctype html><meta charset=utf-8><title>probe</title><body><script src="/probe.js"></script></body>')
elif path == "/probe.js":
self._send((HERE / "hunt_first_run_probe.js").read_bytes(), "text/javascript; charset=utf-8")
else:
self._send(b"<!doctype html><meta charset=utf-8><title>idle</title><body>idle</body>")
def do_POST(self): # noqa: N802
n = int(self.headers.get("Content-Length") or 0)
try:
row = json.loads(self.rfile.read(n).decode("utf-8", "replace"))
row["arrived_ms"] = int(time.time() * 1000) - Idle.t0_ms
with Idle.lock:
Idle.results.append(row)
except Exception: # noqa: BLE001
pass
self._send(b"ok", "text/plain")
def log_message(self, *a): # noqa: D102
pass
# -------------------------------------------------------------------------------------------------------------- the watchers
class Net(threading.Thread):
"""Bytes received and sent by every non-loopback interface, once a second."""
def __init__(self) -> None:
super().__init__(daemon=True)
self.stop_flag = threading.Event()
self.rows: List[Tuple[float, int, int]] = []
def run(self) -> None:
import psutil
while not self.stop_flag.is_set():
try:
c = psutil.net_io_counters(pernic=True)
recv = sum(v.bytes_recv for k, v in c.items() if not re.search(r"(?i)loopback|^lo$|isatap|teredo", k))
sent = sum(v.bytes_sent for k, v in c.items() if not re.search(r"(?i)loopback|^lo$|isatap|teredo", k))
self.rows.append((time.time(), recv, sent))
except Exception: # noqa: BLE001
pass
self.stop_flag.wait(1.0)
def between(self, a: float, b: float) -> Tuple[float, float]:
def at(t: float, i: int) -> int:
best = None
for row in self.rows:
if row[0] <= t:
best = row
return (best[i] if best else (self.rows[0][i] if self.rows else 0))
return (at(b, 1) - at(a, 1)) / 1e6, (at(b, 2) - at(a, 2)) / 1e6
class Files(threading.Thread):
"""Walks the profile directory every 2 s and records every file that is new or changed (size, mtime)."""
def __init__(self, root: Path) -> None:
super().__init__(daemon=True)
self.root = root
self.stop_flag = threading.Event()
self.state: Dict[str, Tuple[int, int]] = {}
self.events: List[Tuple[float, str, int, str]] = [] # (time, relative path, size, new|changed)
self.sizes_at: List[Tuple[float, Dict[str, int]]] = [] # (time, size by top-level dir)
def scan(self) -> None:
now = time.time()
seen: Dict[str, Tuple[int, int]] = {}
by_top: Dict[str, int] = {}
if self.root.is_dir():
for dirpath, _dirs, names in os.walk(self.root):
for n in names:
p = os.path.join(dirpath, n)
try:
st = os.stat(p)
except OSError:
continue
rel = os.path.relpath(p, self.root).replace("\\", "/")
seen[rel] = (st.st_size, st.st_mtime_ns)
top = rel.split("/")[0] if "/" in rel else "(root)"
by_top[top] = by_top.get(top, 0) + st.st_size
for rel, v in seen.items():
old = self.state.get(rel)
if old is None:
self.events.append((now, rel, v[0], "new"))
elif old != v:
self.events.append((now, rel, v[0], "changed"))
self.state = seen
self.sizes_at.append((now, by_top))
def run(self) -> None:
while not self.stop_flag.is_set():
try:
self.scan()
except Exception: # noqa: BLE001
pass
self.stop_flag.wait(2.0)
def finish(self) -> None:
with contextlib.suppress(Exception):
self.scan()
# ----------------------------------------------------------------------------------------------------------------- launching
def parents_of_firefox() -> List[int]:
import psutil
out = []
for p in psutil.process_iter(["pid", "name"]):
if (p.info.get("name") or "").lower().startswith("firefox"):
try:
if "-contentproc" not in p.cmdline():
out.append(p.info["pid"])
except Exception: # noqa: BLE001
pass
return out
def close_like_a_user(timeout: float = 25.0) -> str:
"""taskkill without /F (WM_CLOSE) on every parent process, then wait; whatever is left is killed."""
pids = parents_of_firefox()
for pid in pids:
subprocess.run(["taskkill", "/PID", str(pid)] if sys.platform == "win32" else ["kill", str(pid)],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
end = time.time() + timeout
while time.time() < end and parents_of_firefox():
time.sleep(0.5)
left = parents_of_firefox()
note = "closed gracefully" if not left else "still running after %.0f s: killed" % timeout
hb.kill_firefox()
return note
def launch_retail(exe: Path, url: str, profile: Path, t0: float, until: float) -> str:
profile.mkdir(parents=True, exist_ok=True)
proc = subprocess.Popen([str(exe), "-no-remote", "-profile", str(profile), url], stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
time.sleep(max(0.0, until - time.time()))
note = close_like_a_user()
with contextlib.suppress(Exception):
proc.wait(timeout=10)
return note
async def ours_session(binary: str, url: str, profile: Path, until: float) -> str:
from invisible_playwright.async_api import InvisiblePlaywright
profile.mkdir(parents=True, exist_ok=True)
async with InvisiblePlaywright(seed=100, binary_path=binary, headless=True, locale="en-US", timezone="Europe/Rome",
profile_dir=str(profile)) as browser:
page = await browser.new_page()
await page.goto(url, wait_until="load", timeout=60000)
await asyncio.sleep(max(0.0, until - time.time()))
return "closed by the context manager"
def retail_exe(args) -> Tuple[Path, str]:
if args.retail_from:
info = json.loads((Path(args.retail_from) / "retail.json").read_text(encoding="utf-8"))
return Path(info["exe"]), info["note"]
work = Path(tempfile.mkdtemp(prefix="hunt-retail-"))
exe, why = hb.find_retail(args, work)
if exe is None:
raise SystemExit("no retail binary: %s" % why)
return exe, "%s; %s" % (why, hb.application_ini(exe))
def fetch_retail(args) -> int:
args.out.mkdir(parents=True, exist_ok=True)
exe, why = hb.find_retail(args, args.out)
if exe is None:
print("no retail binary: %s" % why)
return 1
note = "%s; %s" % (why, hb.application_ini(exe))
(args.out / "retail.json").write_text(json.dumps({"exe": str(exe), "note": note}), encoding="utf-8")
print("RETAIL BINARY: %s\n %s" % (exe, note))
return 0
# ------------------------------------------------------------------------------------------------------------------- part 1
def serve() -> Tuple[ThreadingHTTPServer, str]:
httpd = ThreadingHTTPServer(("127.0.0.1", 0), Idle)
httpd.daemon_threads = True
threading.Thread(target=httpd.serve_forever, daemon=True).start()
return httpd, "http://127.0.0.1:%d" % httpd.server_address[1]
def census(args) -> int:
args.out.mkdir(parents=True, exist_ok=True)
httpd, base = serve()
work = Path(tempfile.mkdtemp(prefix="hunt-census-"))
profile = Path(args.keep_profile) if args.keep_profile else work / "profile"
if profile.exists():
shutil.rmtree(profile, ignore_errors=True)
hb.kill_firefox()
note = ""
if args.arm == "retail":
exe, note = retail_exe(args)
print("RETAIL BINARY: %s" % note)
sampler = hunt.Sampler()
sampler.start()
watcher = hb.Watcher()
watcher.start()
net = Net()
net.start()
files = Files(profile)
files.start()
err = ""
t0 = time.time()
Idle.t0_ms = int(t0 * 1000)
try:
if args.arm == "retail":
how = launch_retail(exe, base + "/idle", profile, t0, t0 + WINDOW_S)
else:
how = asyncio.run(ours_session(args.binary, base + "/idle", profile, t0 + WINDOW_S))
print("closed: %s" % how)
except BaseException as exc: # noqa: BLE001
err = "%s: %s" % (type(exc).__name__, str(exc)[:400])
time.sleep(0.8)
for t in (watcher, net, files):
t.stop_flag.set()
watcher.join(5)
net.join(3)
files.join(5)
files.finish()
sampler.stop()
hb.kill_firefox()
httpd.shutdown()
series = hunt.Series(sampler.samples)
where, _roots = hunt.roots_and_kinds(sampler.info)
slices = []
n_slices = int(WINDOW_S / SLICE_S)
for i in range(n_slices):
a, b = t0 + i * SLICE_S, t0 + (i + 1) * SLICE_S
cpu = {k: 0.0 for k in hunt.TYPES}
for pid, (_root, kind) in where.items():
cpu[kind] += series.used(pid, a, b)
threads: Dict[str, float] = {}
for t in watcher.used(a, b):
if t["kind"] == "parent":
threads[hb.normalise(t["name"])] = threads.get(hb.normalise(t["name"]), 0.0) + t["cpu_s"]
recv, sent = net.between(a, b)
ev = [e for e in files.events if a <= e[0] < b]
by_dir: Dict[str, List[int]] = {}
latest: Dict[str, int] = {}
for _t, rel, size, _kind in ev:
latest[rel] = size
for rel, size in latest.items():
top = rel.split("/")[0] if "/" in rel else "(root)"
d = by_dir.setdefault(top, [0, 0])
d[0] += 1
d[1] += size
notable = sorted(((rel, size) for rel, size in latest.items() if WATCHED.match(rel) or size >= BIG), key=lambda x: -x[1])
end_sizes = {}
for ts, sizes in files.sizes_at:
if ts <= b:
end_sizes = sizes
slices.append({"slice": i, "from_s": i * SLICE_S, "to_s": (i + 1) * SLICE_S, "cpu": cpu, "threads": threads, "net_recv_mb": recv, "net_sent_mb": sent,
"files_by_dir": by_dir, "notable_files": notable[:40], "dir_sizes_at_end": end_sizes})
first_seen: Dict[str, Tuple[int, int]] = {}
for ts, rel, size, _k in files.events:
i = min(n_slices - 1, int((ts - t0) // SLICE_S)) if ts >= t0 else 0
if rel not in first_seen:
first_seen[rel] = (i, size)
else:
first_seen[rel] = (first_seen[rel][0], size)
result = {"arm": args.arm, "note": note, "error": err, "window_s": WINDOW_S, "slice_s": SLICE_S, "slices": slices,
"downloads": sorted(((rel, i, size) for rel, (i, size) in first_seen.items() if size >= BIG or WATCHED.match(rel)), key=lambda x: (x[1], -x[2]))[:300],
"profile_final_bytes": sum(v[0] for v in files.state.values()), "processes": hunt.process_listing(sampler, t0),
"watcher_error": watcher.error}
(args.out / ("%s.json" % args.arm)).write_text(json.dumps(result, indent=1), encoding="utf-8")
print_census(result)
if args.keep_profile:
print("profile kept in %s (%.1f MB)" % (profile, result["profile_final_bytes"] / 1e6))
else:
shutil.rmtree(work, ignore_errors=True)
return 1 if err else 0
def print_census(r: Dict[str, Any]) -> None:
print("=" * 110)
print("FIRST-RUN CENSUS, arm %s%s, %.0f s from the launch, slices of %.0f s%s" % (r["arm"], (" (" + r["note"][:120] + ")") if r["note"] else "", r["window_s"],
r["slice_s"], (" ERROR " + r["error"]) if r["error"] else ""))
print("%-9s %8s %6s %6s %6s | %9s %9s | %s" % ("slice", "parent s", "gpu", "tab", "other", "recv MB", "sent MB", "files written in the profile (dir: files, MB)"))
for s in r["slices"]:
other = sum(v for k, v in s["cpu"].items() if k not in ("parent", "gpu", "tab"))
dirs = ", ".join("%s: %d, %.2f" % (d, c, b / 1e6) for d, (c, b) in sorted(s["files_by_dir"].items(), key=lambda kv: -kv[1][1])[:5])
print("+%2d..%2d s %8.2f %6.2f %6.2f %6.2f | %9.2f %9.2f | %s" % (s["from_s"], s["to_s"], s["cpu"]["parent"], s["cpu"]["gpu"], s["cpu"]["tab"], other,
s["net_recv_mb"], s["net_sent_mb"], dirs or "-"))
busy = [s for s in r["slices"] if s["cpu"]["parent"] >= 0.5]
total_parent = sum(s["cpu"]["parent"] for s in r["slices"])
print("parent CPU in the window: %.2f s; slices with at least 0.5 s: %s%s" % (
total_parent, ", ".join("+%d..%d" % (s["from_s"], s["to_s"]) for s in busy) or "none",
(" -> burst from +%d s to +%d s (%d s)" % (busy[0]["from_s"], busy[-1]["to_s"], busy[-1]["to_s"] - busy[0]["from_s"])) if busy else ""))
print("network received in the window: %.1f MB, sent %.1f MB; profile at the end: %.1f MB" % (
sum(s["net_recv_mb"] for s in r["slices"]), sum(s["net_sent_mb"] for s in r["slices"]), r["profile_final_bytes"] / 1e6))
print("-" * 110)
print("PARENT CPU BY THREAD NAME, per slice (the 4 largest of each slice)")
for s in r["slices"]:
top = sorted(s["threads"].items(), key=lambda kv: -kv[1])[:4]
print(" +%2d..%2d s %s" % (s["from_s"], s["to_s"], ", ".join("%s %.2f" % (n[:28], v) for n, v in top if v >= 0.01) or "(nothing above 0.01 s)"))
print("-" * 110)
print("FILES per slice (path, size): everything in gmp-*, security_state, safebrowsing, settings, features, extensions, ... and any file of 100 KB or more")
for s in r["slices"]:
if s["notable_files"]:
print(" +%2d..%2d s" % (s["from_s"], s["to_s"]))
for rel, size in s["notable_files"][:14]:
print(" %-90s %12d" % (rel[:90], size))
if len(s["notable_files"]) > 14:
print(" ... %d more" % (len(s["notable_files"]) - 14))
print("-" * 110)
print("size of each top-level directory of the profile at the end of each slice (MB), the ones above 0.5 MB:")
for s in r["slices"]:
print(" +%2d s %s" % (s["to_s"], ", ".join("%s %.1f" % (d, b / 1e6) for d, b in sorted(s["dir_sizes_at_end"].items(), key=lambda kv: -kv[1]) if b >= 5e5) or "-"))
hunt.print_processes(r["processes"])
sys.stdout.flush()
def norm_path(rel: str) -> str:
rel = re.sub(r"[0-9a-f]{8,}", "H", rel)
rel = re.sub(r"\d+(\.\d+)+", "V", rel)
return rel
def census_table(root: Path) -> int:
arms = [(n, json.loads((root / (n + ".json")).read_text(encoding="utf-8"))) for n in ("retail", "ours") if (root / (n + ".json")).is_file()]
if not arms:
print("no census in %s" % root)
return 1
print("=" * 110)
print("FIRST RUN, a fresh profile: %s" % ", ".join("%s%s" % (n, " (ERROR)" if r["error"] else "") for n, r in arms))
for n, r in arms:
if n == "retail":
print(" retail binary: %s" % r["note"][:300])
print("%-10s" % "slice" + "".join(" | %-9s %-9s %-9s" % (n + " CPU", n + " recv", n + " MB wr") for n, _ in arms))
for i in range(int(WINDOW_S / SLICE_S)):
cells = ""
for _n, r in arms:
s = r["slices"][i]
written = sum(b for _c, b in s["files_by_dir"].values()) / 1e6
cells += " | %-9.2f %-9.2f %-9.2f" % (s["cpu"]["parent"], s["net_recv_mb"], written)
print("+%2d..%2d s %s" % (i * SLICE_S, (i + 1) * SLICE_S, cells))
for n, r in arms:
busy = [s for s in r["slices"] if s["cpu"]["parent"] >= 0.5]
print("%-8s parent CPU total %.2f s; busy slices (>= 0.5 s): %s; network received %.1f MB" % (
n, sum(s["cpu"]["parent"] for s in r["slices"]), ", ".join("+%d" % s["from_s"] for s in busy) or "none", sum(s["net_recv_mb"] for s in r["slices"])))
print("-" * 110)
print("THE DOWNLOADS: files of 100 KB or more, and everything in gmp-*, security_state, safebrowsing, settings, features (slice of first appearance, final size)")
names: Dict[str, Dict[str, Tuple[int, int]]] = {}
for n, r in arms:
for rel, i, size in r["downloads"]:
names.setdefault(norm_path(rel), {})[n] = (i, size)
print(" %-80s" % "path (version and hash blanked)" + "".join(" | %-18s" % n for n, _ in arms))
for p in sorted(names, key=lambda p: min(v[0] for v in names[p].values())):
if max(v[1] for v in names[p].values()) < BIG and not any(WATCHED.match(p) for _ in (0,)):
continue
print(" %-80s" % p[:80] + "".join(" | %-18s" % (("+%d s, %.2f MB" % (names[p][n][0] * SLICE_S, names[p][n][1] / 1e6)) if n in names[p] else "-") for n, _ in arms))
if len(arms) == 2:
only = {n: [p for p in names if n in names[p] and (arms[0][0] if n == arms[1][0] else arms[1][0]) not in names[p] and names[p][n][1] >= BIG] for n, _ in arms}
for n, lst in only.items():
print(" files of 100 KB or more only in %s: %s" % (n, ", ".join(lst[:15]) or "none"))
print("-" * 110)
print("PARENT CPU BY THREAD NAME over the whole window (the 12 largest of each arm)")
for n, r in arms:
tot: Dict[str, float] = {}
for s in r["slices"]:
for k, v in s["threads"].items():
tot[k] = tot.get(k, 0.0) + v
print(" %-8s %s" % (n, ", ".join("%s %.2f" % (k[:26], v) for k, v in sorted(tot.items(), key=lambda kv: -kv[1])[:12])))
return 0
# ------------------------------------------------------------------------------------------------------------------- part 2
def probe(args) -> int:
args.out.mkdir(parents=True, exist_ok=True)
httpd, base = serve()
moments = [90] if args.mode == "late" else [5, 20, 40, 90]
work = Path(tempfile.mkdtemp(prefix="hunt-probe-"))
family = "retail" if args.arm.startswith("retail") else "ours"
used = args.arm.endswith("used")
profile = work / "profile"
hb.kill_firefox()
note = ""
exe = None
if family == "retail":
exe, note = retail_exe(args)
if used:
if family == "retail":
if not args.profile or not Path(args.profile).is_dir():
print("retail_used needs --profile (the profile left by `census --arm retail --keep-profile`)")
return 1
shutil.copytree(args.profile, profile, ignore=shutil.ignore_patterns("parent.lock", "lock", ".parentlock"))
else:
# ours_used: a first launch of 80 s on this profile_dir, then the measured one
httpd0, base0 = serve()
print("ours_used: first launch of %.0f s on the profile" % WINDOW_S)
t = time.time()
Idle.t0_ms = int(t * 1000)
asyncio.run(ours_session(args.binary, base0 + "/idle", profile, t + WINDOW_S))
hb.kill_firefox()
httpd0.shutdown()
Idle.results = []
deadline_s = max(moments) + MOMENT_GRACE_S + 15
t0 = time.time()
Idle.t0_ms = int(t0 * 1000)
url = "%s/probe?moments=%s" % (base, ",".join(str(m) for m in moments))
err = ""
how = ""
def waiter():
while time.time() < t0 + deadline_s:
with Idle.lock:
if any(r.get("probe") == "page.done" for r in Idle.results):
return
time.sleep(1)
try:
if family == "retail":
def run_retail():
nonlocal how
profile.mkdir(parents=True, exist_ok=True)
proc = subprocess.Popen([str(exe), "-no-remote", "-profile", str(profile), url], stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
waiter()
how = close_like_a_user()
with contextlib.suppress(Exception):
proc.wait(timeout=10)
run_retail()
else:
async def run_ours():
from invisible_playwright.async_api import InvisiblePlaywright
async with InvisiblePlaywright(seed=100, binary_path=args.binary, headless=True, locale="en-US", timezone="Europe/Rome",
profile_dir=str(profile)) as browser:
page = await browser.new_page()
await page.goto(url, wait_until="load", timeout=60000)
await asyncio.get_running_loop().run_in_executor(None, waiter)
asyncio.run(run_ours())
how = "closed by the context manager"
except BaseException as exc: # noqa: BLE001
err = "%s: %s" % (type(exc).__name__, str(exc)[:400])
hb.kill_firefox()
httpd.shutdown()
with Idle.lock:
rows = list(Idle.results)
result = {"arm": args.arm, "mode": args.mode, "moments": moments, "note": note, "error": err, "closed": how, "rows": rows}
(args.out / ("%s-%s.json" % (args.arm, args.mode))).write_text(json.dumps(result, indent=1), encoding="utf-8")
print("probe arm %s, mode %s%s: %d result rows%s; browser %s" % (args.arm, args.mode, (" (" + note[:100] + ")") if note else "", len(rows),
("; ERROR " + err) if err else "", how))
for r in sorted(rows, key=lambda r: (r.get("moment", 0), r.get("probe", ""))):
if r.get("moment", 0) >= 0:
print(" +%-3s %-26s started +%6.1f s, took %6d ms, %-9s %s" % (r["moment"], r["probe"], r["started_ms"] / 1000, r["ms"], r["status"],
json.dumps(r["value"])[:160]))
shutil.rmtree(work, ignore_errors=True)
return 1 if err else 0
def probe_table(root: Path) -> int:
runs: Dict[Tuple[str, str], Dict[str, Any]] = {}
for p in sorted(root.glob("*.json")):
r = json.loads(p.read_text(encoding="utf-8"))
runs[(r["arm"], r["mode"])] = r
if not runs:
print("no probe results in %s" % root)
return 1
arms = ["ours_fresh", "ours_used", "retail_fresh", "retail_used"]
print("=" * 120)
print("WHAT A PAGE READS OF THE STATE OF A PROFILE. runs: %s" % ", ".join("%s/%s%s" % (a, m, " (ERROR)" if r["error"] else "") for (a, m), r in sorted(runs.items())))
for (a, m), r in sorted(runs.items()):
if r["note"]:
print(" %s binary: %s" % (a, r["note"][:200]))
ua = {}
for (a, m), r in runs.items():
for row in r["rows"]:
if row.get("probe") == "page.loaded":
ua[a] = row["value"]
for a, u in sorted(ua.items()):
print(" %-13s user agent %s" % (a, u))
def cell(row: Optional[Dict[str, Any]]) -> str:
if row is None:
return "-"
v = row["value"]
text = v if isinstance(v, str) else json.dumps(v, sort_keys=True)
return "%s %dms %s" % (row["status"], row["ms"], text)
index: Dict[Tuple[str, str, int, str], Dict[str, Any]] = {}
probes_seen: List[str] = []
for (a, m), r in runs.items():
for row in r["rows"]:
if row.get("moment", -1) >= 0:
index[(a, m, row["moment"], row["probe"])] = row
if row["probe"] not in probes_seen:
probes_seen.append(row["probe"])
for name in probes_seen:
print("=" * 120)
print("PROBE %s" % name)
for mode, moments in (("seq", [5, 20, 40, 90]), ("late", [90])):
for mo in moments:
cells = [(a, index.get((a, mode, mo, name))) for a in arms if (a, mode) in runs]
if not cells:
continue
print(" [%s] +%d s" % (mode, mo))
for a, row in cells:
print(" %-13s %s" % (a, cell(row)[:230]))
def key_of(row: Optional[Dict[str, Any]]) -> str:
if row is None:
return "missing"
return "%s|%s" % (row["status"], json.dumps(row["value"], sort_keys=True))
print("=" * 120)
print("CAN A PAGE TELL A PROFILE JUST BORN FROM A USED ONE? Probes (outcome and value, not the time) that differ between a fresh and a used profile at the same moment:")
for fam in ("ours", "retail"):
fresh, usedn = fam + "_fresh", fam + "_used"
for mode, moments in (("seq", [5, 20, 40, 90]), ("late", [90])):
if (fresh, mode) not in runs or (usedn, mode) not in runs:
continue
diffs = []
for mo in moments:
for name in probes_seen:
a, b = index.get((fresh, mode, mo, name)), index.get((usedn, mode, mo, name))
if a is not None and b is not None and key_of(a) != key_of(b):
diffs.append("+%d %s [%s -> %s]" % (mo, name, a["status"], b["status"]))
print(" %-7s %-5s %s" % (fam, mode, ("%d differ: %s" % (len(diffs), "; ".join(diffs))) if diffs else "NONE differ: fresh and used answer the same at every moment"))
print("-" * 120)
print("DOES THE ANSWER CHANGE WITH TIME IN ONE PROFILE? (the same arm, the same mode, +5 against +90 s, outcome or value)")
for a in arms:
if (a, "seq") in runs:
ch = [n for n in probes_seen if key_of(index.get((a, "seq", 5, n))) != key_of(index.get((a, "seq", 90, n)))]
print(" %-13s %s" % (a, ("changes: " + ", ".join(ch)) if ch else "nothing changes between +5 and +90 s"))
print("-" * 120)
print("DID ASKING EARLY CHANGE THE ANSWER AT +90 s? (mode seq against mode late, same arm)")
for a in arms:
if (a, "seq") in runs and (a, "late") in runs:
ch = [n for n in probes_seen if key_of(index.get((a, "seq", 90, n))) != key_of(index.get((a, "late", 90, n)))]
print(" %-13s %s" % (a, ("differs: " + ", ".join(ch)) if ch else "no difference"))
print("-" * 120)
print("PROBE TIMES: median ms per probe over the moments, per arm (seq runs)")
print(" %-26s" % "" + "".join(" %-14s" % a for a in arms))
for name in probes_seen:
line = " %-26s" % name
for a in arms:
ms = [index[(a, "seq", mo, name)]["ms"] for mo in (5, 20, 40, 90) if (a, "seq", mo, name) in index]
line += " %-14s" % (("%d" % statistics.median(ms)) if ms else "-")
print(line)
return 0
def main() -> int:
ap = argparse.ArgumentParser()
sub = ap.add_subparsers(dest="cmd", required=True)
def common(p, arms):
p.add_argument("--arm", choices=arms, required=True)
p.add_argument("--binary", default=os.environ.get("INVPW_BINARY_PATH", ""))
p.add_argument("--retail-from", default="", help="the --out of fetch-retail")
p.add_argument("--retail-binary", default="")
p.add_argument("--retail-version", default="159.0")
p.add_argument("--out", type=Path, required=True)
f = sub.add_parser("fetch-retail")
f.add_argument("--out", type=Path, required=True)
f.add_argument("--retail-binary", default="")
f.add_argument("--retail-version", default="159.0")
c = sub.add_parser("census")
common(c, ("retail", "ours"))
c.add_argument("--keep-profile", default="", help="the profile directory to use and keep (the used profile of part 2)")
ct = sub.add_parser("census-table")
ct.add_argument("root", type=Path)
p = sub.add_parser("probe")
common(p, ("ours_fresh", "ours_used", "retail_fresh", "retail_used"))
p.add_argument("--mode", choices=("seq", "late"), required=True)
p.add_argument("--profile", default="", help="retail_used: the profile left by census --keep-profile")
pt = sub.add_parser("probe-table")
pt.add_argument("root", type=Path)
args = ap.parse_args()
if args.cmd == "fetch-retail":
return fetch_retail(args)
if args.cmd == "census-table":
return census_table(args.root)
if args.cmd == "probe-table":
return probe_table(args.root)
if args.arm.startswith("ours") and not args.binary:
ap.error("the ours arms need --binary (or INVPW_BINARY_PATH)")
return census(args) if args.cmd == "census" else probe(args)
if __name__ == "__main__":
sys.exit(main())
+109
View File
@@ -0,0 +1,109 @@
// HUNT ONLY (branch hunt/cpu-render-path, never merged). Served by scripts/hunt_first_run.py as /probe.js, loaded by the page /probe.
// What can a page read of the state a profile builds up in its first minutes (downloaded components: Widevine, OpenH264, the lists)?
// At each moment (seconds after the LAUNCH, read from /t0 and the shared clock) every probe below runs, concurrently, and posts its own result to
// /result as soon as it is done, so that a probe that waits (requestMediaKeySystemAccess waits for the CDM download, up to 60 s: see
// dom/media/eme/MediaKeySystemAccessManager.cpp AwaitInstall) does not delay the others. Each result: {moment, probe, started_ms (after launch), ms (how
// long the probe took), status: resolved | rejected | timeout, value}.
(async () => {
const MOMENTS = (new URLSearchParams(location.search).get("moments") || "5,20,40,90").split(",").map(Number);
const t0 = Number(await (await fetch("/t0", { cache: "no-store" })).text());
const post = (o) => fetch("/result", { method: "POST", body: JSON.stringify(o), keepalive: true }).catch(() => {});
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const EME_CFG = [{
initDataTypes: ["cenc", "webm"],
audioCapabilities: [{ contentType: 'audio/mp4;codecs="mp4a.40.2"' }, { contentType: 'audio/webm;codecs="opus"' }],
videoCapabilities: [{ contentType: 'video/mp4;codecs="avc1.42E01E"' }, { contentType: 'video/webm;codecs="vp8"' }],
distinctiveIdentifier: "optional", persistentState: "optional", sessionTypes: ["temporary"],
}];
const H264 = "video/H264;level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f";
async function timed(fn, limit) {
const s = performance.now();
try {
const v = await Promise.race([fn(), sleep(limit).then(() => { throw { __timeout: true }; })]);
return { status: "resolved", ms: Math.round(performance.now() - s), value: v };
} catch (e) {
if (e && e.__timeout) return { status: "timeout", ms: Math.round(performance.now() - s), value: "no answer in " + limit + " ms" };
return { status: "rejected", ms: Math.round(performance.now() - s), value: (e && e.name ? e.name + ": " : "") + String((e && e.message) || e).slice(0, 200) };
}
}
const eme = (ks, cfg) => async () => {
const a = await navigator.requestMediaKeySystemAccess(ks, cfg || EME_CFG);
return { keySystem: a.keySystem, config: a.getConfiguration() };
};
const mcEncrypted = (ks) => async () => {
const r = await navigator.mediaCapabilities.decodingInfo({
type: "media-source",
video: { contentType: 'video/mp4; codecs="avc1.42E01E"', width: 640, height: 360, bitrate: 1000000, framerate: 30 },
keySystemConfiguration: { keySystem: ks, initDataType: "cenc", video: { robustness: "" } },
});
return { supported: r.supported, smooth: r.smooth, powerEfficient: r.powerEfficient, keySystemAccess: r.keySystemAccess ? r.keySystemAccess.keySystem : null };
};
const mcPlain = (kind, cfg) => async () => {
const r = await navigator.mediaCapabilities[kind](cfg);
return { supported: r.supported, smooth: r.smooth, powerEfficient: r.powerEfficient };
};
const track = (url) => async () => {
const c = new AbortController(); const t = setTimeout(() => c.abort(), 8000);
try { await fetch(url, { mode: "no-cors", cache: "no-store", signal: c.signal }); return "fetch resolved"; }
finally { clearTimeout(t); }
};
const probes = {
"eme.widevine": () => timed(eme("com.widevine.alpha"), 80000),
"eme.clearkey": () => timed(eme("org.w3.clearkey"), 80000),
"eme.playready": () => timed(eme("com.microsoft.playready"), 80000),
"eme.widevine.hwdrm": () => timed(eme("com.widevine.alpha", [{ initDataTypes: ["cenc"], videoCapabilities: [{ contentType: 'video/mp4;codecs="avc1.42E01E"', robustness: "HW_SECURE_ALL" }] }]), 80000),
"mc.decoding.widevine": () => timed(mcEncrypted("com.widevine.alpha"), 80000),
"mc.decoding.clearkey": () => timed(mcEncrypted("org.w3.clearkey"), 80000),
"mc.decoding.plain": () => timed(mcPlain("decodingInfo", { type: "file", video: { contentType: 'video/mp4; codecs="avc1.42E01E"', width: 640, height: 360, bitrate: 1000000, framerate: 30 } }), 20000),
"mc.decoding.webrtc.h264": () => timed(mcPlain("decodingInfo", { type: "webrtc", video: { contentType: H264, width: 640, height: 480, bitrate: 1000000, framerate: 30 } }), 20000),
"mc.encoding.webrtc.h264": () => timed(mcPlain("encodingInfo", { type: "webrtc", video: { contentType: H264, width: 640, height: 480, bitrate: 1000000, framerate: 30 } }), 20000),
"mc.encoding.webrtc.vp8": () => timed(mcPlain("encodingInfo", { type: "webrtc", video: { contentType: "video/VP8", width: 640, height: 480, bitrate: 1000000, framerate: 30 } }), 20000),
"rtc.capabilities": () => timed(async () => {
const f = (x) => x ? x.codecs.map((c) => c.mimeType + (c.sdpFmtpLine ? ";" + c.sdpFmtpLine : "")) : null;
return { senderVideo: f(RTCRtpSender.getCapabilities("video")), receiverVideo: f(RTCRtpReceiver.getCapabilities("video")),
senderAudio: f(RTCRtpSender.getCapabilities("audio")), receiverAudio: f(RTCRtpReceiver.getCapabilities("audio")) };
}, 20000),
"rtc.offer.codecs": () => timed(async () => {
const pc = new RTCPeerConnection({ iceServers: [] });
pc.addTransceiver("video"); pc.addTransceiver("audio");
const o = await pc.createOffer(); pc.close();
return o.sdp.split(/\r?\n/).filter((l) => /^a=(rtpmap|fmtp)/.test(l) && /H264|VP8|VP9|AV1|red|ulpfec|rtx/i.test(l)).slice(0, 60);
}, 20000),
"media.canplay": () => timed(async () => {
const v = document.createElement("video");
const types = ['video/mp4; codecs="avc1.42E01E"', 'audio/mp4; codecs="mp4a.40.2"', 'video/webm; codecs="vp9"', 'video/mp4; codecs="hev1.1.6.L93.B0"', 'video/mp4; codecs="av01.0.05M.08"'];
return { canPlayType: types.map((t) => v.canPlayType(t)), isTypeSupported: types.map((t) => MediaSource.isTypeSupported(t)) };
}, 20000),
"media.devices": () => timed(async () => {
const d = await navigator.mediaDevices.enumerateDevices();
return { keys: Object.getOwnPropertyNames(Object.getPrototypeOf(navigator.mediaDevices)).sort(), devices: d.map((x) => [x.kind, x.label ? "labelled" : "no label"]) };
}, 10000),
"nav.plugins": () => timed(async () => ({ plugins: Array.from(navigator.plugins).map((p) => p.name), mimeTypes: Array.from(navigator.mimeTypes).map((m) => m.type), pdf: navigator.pdfViewerEnabled }), 5000),
"storage.estimate": () => timed(async () => { const e = await navigator.storage.estimate(); return { quota: e.quota, usage: e.usage }; }, 10000),
"permissions": () => timed(async () => {
const out = {};
for (const n of ["notifications", "geolocation", "camera", "microphone", "persistent-storage", "midi"]) {
try { out[n] = (await navigator.permissions.query({ name: n })).state; } catch (e) { out[n] = "ERR " + e.name; }
}
return out;
}, 10000),
"net.control.same_origin": () => timed(async () => { await fetch("/t0", { cache: "no-store" }); return "ok"; }, 8000),
"net.cryptomining_host": () => timed(track("https://coinhive.com/lib/coinhive.min.js"), 10000),
"net.analytics_host": () => timed(track("https://www.google-analytics.com/analytics.js"), 10000),
};
async function run(moment) {
const wait = t0 + moment * 1000 - Date.now();
if (wait > 0) await sleep(wait);
const startedMs = Date.now() - t0;
await Promise.all(Object.entries(probes).map(async ([name, fn]) => {
const r = await fn();
await post({ moment, probe: name, started_ms: startedMs, ...r });
}));
}
await post({ moment: -1, probe: "page.loaded", started_ms: Date.now() - t0, status: "resolved", ms: 0, value: navigator.userAgent });
await Promise.all(MOMENTS.map(run));
await post({ moment: -2, probe: "page.done", started_ms: Date.now() - t0, status: "resolved", ms: 0, value: "all moments done" });
})();
+329
View File
@@ -0,0 +1,329 @@
"""HUNT ONLY (branch hunt/cpu-render-path, never merged): does our forced multisample make WebGL readPixels slow, and does MSAA change pixels a page can read?
python scripts/hunt_msaa.py run --arm ours|ours_nomsaa|stockheaded|retail [--binary B] [--retail-from DIR] --out DIR
python scripts/hunt_msaa.py facts --arm ... --out DIR # effective webgl.msaa-* prefs, Troubleshoot's WebGL lines
python scripts/hunt_msaa.py table DIR [DIR ...] # one DIR per round
MEASURED: WebGL readPixels of 1024x1024 takes ~400 ms (p50) in ours and in ours_vmretail, ~89 ms in stock and in retail 159.
HYPOTHESIS: the multisample we force. GLContext.cpp:783-787 marks framebuffer_multisample unsupported on the Microsoft Basic Render Driver (bug 978966); our hook at
GLContext.cpp:799 (StealthDeclaredMultisample, gfx/gl/StealthGLMultisample.cpp:24-26) turns it back on whenever webgl.msaa-samples > 0; the core sets webgl.msaa-samples=4 and
webgl.msaa-force=true on Windows (invisible_core/prefs.py:1263-1264). The default framebuffer is then multisampled (WebGLContext.cpp:461-465, MozFramebuffer::Create with
mMsaaSamples) and every readPixels resolves it, in software on WARP.
THE ARMS (one browser each; ours, ours_nomsaa and stockheaded through the clients of hunt_cpu_baseline.py, retail by hand: Mozilla's 159.0, subprocess, -no-remote, a fresh profile,
the page posts its result to the local server):
ours the declared persona (webgl.msaa-samples=4, webgl.msaa-force=true)
ours_nomsaa ours with webgl.msaa-samples=0 and webgl.msaa-force=false, passed ONLY by the hunt (hunt_cpu_per_browser.ARM_PREFS). With samples 0 Mozilla turns antialias off
for every context (dom/canvas/ClientWebGLContext.cpp:1091-1094): a page reads antialias:false and SAMPLES 0
stockheaded stock Playwright's firefox, headless=False
retail Mozilla's Firefox 159.0
WHAT THE PAGE MEASURES (scripts/hunt_msaa_probe.js), in each browser: readPixels / toDataURL timing of a 1024x1024 context with antialias:true and with antialias:false in the SAME
browser (if the multisample resolve is the cost, the antialias:false context is fast where the antialias:true one is slow); a 256x256 scene with diagonal edges (a rotated triangle,
thin rotated lines and slivers) in both, read back with readPixels AND toDataURL, edge pixels hashed apart from interior pixels (an interior pixel equals its eight neighbours in the
antialias:false image), antialiased pixels counted; getContextAttributes().antialias, SAMPLES, SAMPLE_BUFFERS, MAX_SAMPLES and the RGBA8 sample counts. `table` also compares the
raw readPixels of the antialias:true scene between arms pixel by pixel.
WHAT RETAIL DOES, from the sources (this tree): the default of the attribute is webgl.default-antialias (StaticPrefList.yaml:20451, true off Android); webgl.msaa-samples defaults to 4
(StaticPrefList.yaml:20650); samples 0 forces antialias false (ClientWebGLContext.cpp:1091-1094); the default framebuffer is created with those samples (WebGLContext.cpp:461-465)
and MozFramebuffer::Create returns null when the GL has no framebuffer_multisample or MAX_SAMPLES is lower (MozFramebuffer.cpp:30-37), in which case the context falls back to no
samples (WebGLContext.cpp:467-472) and `mOptions.antialias &= bool(mDefaultFB->mSamples)` (WebGLContext.cpp:670) makes the attribute false. So: on a real GPU through ANGLE/D3D11,
framebuffer_multisample is supported (ANGLE_framebuffer_multisample, GLContext.cpp:83), the renderer is not the Basic Render Driver, and retail has MSAA on (antialias true, SAMPLES
4 or the GPU's MAX_SAMPLES if lower); on the Basic Render Driver (a VM, this runner) retail marks it unsupported (GLContext.cpp:783-787) and a page reads antialias:false, SAMPLES 0.
"""
from __future__ import annotations
import argparse
import asyncio
import base64
import contextlib
import json
import os
import subprocess
import sys
import tempfile
import threading
import time
from http.server import ThreadingHTTPServer
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
import hunt_cpu_per_browser as hunt # noqa: E402
import hunt_cpu_render_path as rp # noqa: E402
import hunt_compositor_visible as cv # noqa: E402
ARMS = ["ours", "ours_nomsaa", "stockheaded", "retail"]
class MsaaPage(cv.Page):
"""The page of this hunt: same server as hunt_compositor_visible, the probe of this file."""
def do_GET(self): # noqa: N802
if self.path.startswith("/probe.js"):
self._send((HERE / "hunt_msaa_probe.js").read_bytes(), "text/javascript; charset=utf-8")
else:
self._send(b'<!doctype html><meta charset=utf-8><title>msaa</title><body style="margin:0"><script src="/probe.js"></script></body>', "text/html; charset=utf-8")
def serve() -> Tuple[ThreadingHTTPServer, str]:
httpd = ThreadingHTTPServer(("127.0.0.1", 0), MsaaPage)
httpd.daemon_threads = True
threading.Thread(target=httpd.serve_forever, daemon=True).start()
return httpd, "http://127.0.0.1:%d/" % httpd.server_address[1]
def run(args) -> int:
args.out.mkdir(parents=True, exist_ok=True)
httpd, url = serve()
cv.Page.result = None
cv.kill_firefox()
note, err = "", ""
t0 = time.time()
try:
if args.arm == "retail":
exe, note = cv.retail_exe(args)
profile = Path(tempfile.mkdtemp(prefix="hunt-msaa-retail-"))
proc = subprocess.Popen([str(exe), "-no-remote", "-profile", str(profile), url], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
try:
end = time.time() + cv.WAIT_S
while cv.Page.result is None and time.time() < end:
time.sleep(0.5)
finally:
cv.kill_firefox()
with contextlib.suppress(Exception):
proc.wait(timeout=10)
elif args.arm == "stockheaded":
asyncio.run(cv.stock_run(url))
else:
asyncio.run(cv.ours_run(args.binary, url, hunt.arm_prefs(args.arm)))
except BaseException as exc: # noqa: BLE001
err = "%s: %s" % (type(exc).__name__, str(exc)[:400])
cv.kill_firefox()
httpd.shutdown()
data: Dict[str, Any] = {}
if cv.Page.result:
try:
data = json.loads(cv.Page.result)
except ValueError as exc:
err = err or "unreadable result: %s" % exc
else:
err = err or "the page posted nothing in %d s" % cv.WAIT_S
doc = {"arm": args.arm, "note": note, "error": err, "wall_s": time.time() - t0, "probe": data,
"prefs_passed": hunt.arm_prefs(args.arm) if args.arm.startswith("ours") and args.arm != "ours_vmretail" else None}
(args.out / ("%s.json" % args.arm)).write_text(json.dumps(doc, indent=1), encoding="utf-8")
print("arm %s: %s%s" % (args.arm, "result received" if data else "NO RESULT", ("; ERROR " + err) if err else ""))
if data.get("errors"):
print(" page errors: %s" % data["errors"])
print_arm(doc)
return 1 if err else 0
def facts(args) -> int:
out = args.out / ("%s-facts" % args.arm)
out.mkdir(parents=True, exist_ok=True)
cv.kill_firefox()
report: Dict[str, Any] = {"arm": args.arm}
async def ours_like():
async with rp.launched(args.arm, args.binary or "", marionette=True) as browser:
page = await browser.new_page()
await page.goto("about:blank")
await asyncio.get_running_loop().run_in_executor(None, rp.privileged_route, out, report)
try:
if args.arm == "retail":
exe, note = cv.retail_exe(args)
profile = Path(tempfile.mkdtemp(prefix="hunt-msaa-facts-"))
proc = subprocess.Popen([str(exe), "-no-remote", "-marionette", "-remote-allow-system-access", "-profile", str(profile), "about:blank"],
env=dict(os.environ, MOZ_REMOTE_ALLOW_SYSTEM_ACCESS="1"), stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
try:
rp.privileged_route(out, report)
finally:
cv.kill_firefox()
with contextlib.suppress(Exception):
proc.wait(timeout=10)
else:
asyncio.run(ours_like())
except BaseException as exc: # noqa: BLE001
report["error"] = "%s: %s" % (type(exc).__name__, str(exc)[:300])
cv.kill_firefox()
print_facts(args.arm, out)
return 0
def print_facts(arm: str, out: Path) -> None:
print("-" * 110)
print("FACTS of %s: the multisample prefs as the browser reads them, and what Troubleshoot says of WebGL" % arm)
pf = out / "effective_prefs.json"
if pf.is_file():
prefs = json.loads(pf.read_text(encoding="utf-8"))
for n in sorted(prefs):
if n.startswith(("webgl.msaa", "webgl.default-antialias", "webgl.angle", "webgl.disable", "webgl.force", "gfx.webrender.software", "webgl.out-of-process")):
print(" pref %s = %s (user-set: %s)" % (n, prefs[n][1], prefs[n][0]))
else:
print(" effective_prefs.json missing")
sf = out / "troubleshoot.json"
if sf.is_file():
g = json.loads(sf.read_text(encoding="utf-8")).get("graphics", {})
for k in ("webgl1Renderer", "webgl1Version", "webgl1DriverRenderer", "webgl2Renderer", "webgl2Version", "webgl1Extensions", "windowLayerManagerType", "webgl1WSIInfo"):
if k in g:
print(" Troubleshoot %s: %s" % (k, str(g[k])[:200]))
else:
print(" troubleshoot.json missing")
# ------------------------------------------------------------------------------------------------------------------------ table
def get(doc: Dict[str, Any], path: str) -> Any:
cur: Any = doc.get("probe", {})
for p in path.split("."):
if not isinstance(cur, dict) or p not in cur:
return None
cur = cur[p]
return cur
TIMING = [
("readPixels 1024 first ms, antialias:true", "timing.antialias_true.first_readPixels_ms"),
("readPixels 1024 repeat p50 ms, antialias:true", "timing.antialias_true.repeat_readPixels_ms_p50"),
("draw then 1px readPixels p50 ms, antialias:true", "timing.antialias_true.draw_then_1px_readPixels_ms_p50"),
("toDataURL png 1024 ms, antialias:true", "timing.antialias_true.toDataURL_png_ms"),
("readPixels 1024 first ms, antialias:false", "timing.antialias_false.first_readPixels_ms"),
("readPixels 1024 repeat p50 ms, antialias:false", "timing.antialias_false.repeat_readPixels_ms_p50"),
("draw then 1px readPixels p50 ms, antialias:false", "timing.antialias_false.draw_then_1px_readPixels_ms_p50"),
("toDataURL png 1024 ms, antialias:false", "timing.antialias_false.toDataURL_png_ms"),
]
VALUES = [
("getContextAttributes().antialias, requested true (webgl)", "attributes.webgl.antialias_true.attributes_antialias"),
("getContextAttributes().antialias, requested false (webgl)", "attributes.webgl.antialias_false.attributes_antialias"),
("SAMPLES, requested true (webgl)", "attributes.webgl.antialias_true.SAMPLES"),
("SAMPLE_BUFFERS, requested true (webgl)", "attributes.webgl.antialias_true.SAMPLE_BUFFERS"),
("getContextAttributes().antialias, requested true (webgl2)", "attributes.webgl2.antialias_true.attributes_antialias"),
("SAMPLES, requested true (webgl2)", "attributes.webgl2.antialias_true.SAMPLES"),
("MAX_SAMPLES (webgl2)", "attributes.webgl2.antialias_true.MAX_SAMPLES"),
("RGBA8 renderbuffer sample counts (webgl2)", "attributes.webgl2.antialias_true.RGBA8_samples"),
("unmasked renderer (webgl)", "attributes.webgl.antialias_true.UNMASKED_RENDERER"),
("scene: edge pixels (from the antialias:false image)", "scene.edge_pixels"),
("scene, antialias:true, antialiased pixels (readPixels)", "scene.aa_true.readPixels.antialiased_pixels"),
("scene, antialias:true, edge hash (readPixels)", "scene.aa_true.readPixels.edge_hash"),
("scene, antialias:true, interior hash (readPixels)", "scene.aa_true.readPixels.interior_hash"),
("scene, antialias:true, edge hash (toDataURL decoded)", "scene.aa_true.toDataURL_decoded.edge_hash"),
("scene, antialias:true, interior hash (toDataURL decoded)", "scene.aa_true.toDataURL_decoded.interior_hash"),
("scene, antialias:true, toDataURL pixels == readPixels", "scene.aa_true.png_equals_readPixels"),
("scene, antialias:false, antialiased pixels (readPixels)", "scene.aa_false.readPixels.antialiased_pixels"),
("scene, antialias:false, edge hash (readPixels)", "scene.aa_false.readPixels.edge_hash"),
("scene, antialias:false, interior hash (readPixels)", "scene.aa_false.readPixels.interior_hash"),
("scene, antialias:true against antialias:false: pixels that differ", "scene.aa_true_against_aa_false_readPixels.differing_pixels"),
(" ... of them at edges", "scene.aa_true_against_aa_false_readPixels.at_edges"),
(" ... of them in the interior", "scene.aa_true_against_aa_false_readPixels.in_interior"),
(" ... largest channel delta", "scene.aa_true_against_aa_false_readPixels.largest_delta"),
]
def pixel_diff(a: Optional[str], b: Optional[str]) -> str:
if not a or not b:
return "missing"
x, y = base64.b64decode(a), base64.b64decode(b)
if len(x) != len(y):
return "sizes differ"
n, mx = 0, 0
for i in range(0, len(x), 4):
d = max(abs(x[i + k] - y[i + k]) for k in range(4))
if d:
n += 1
mx = max(mx, d)
return "identical" if n == 0 else "%d of %d pixels differ, largest channel delta %d" % (n, len(x) // 4, mx)
def fmt(v: Any) -> str:
return "-" if v is None else (json.dumps(v) if isinstance(v, (list, dict)) else str(v))
def print_arm(doc: Dict[str, Any]) -> None:
print("-" * 110)
print("ARM %s%s%s" % (doc["arm"], (" (" + doc["note"][:80] + ")") if doc.get("note") else "", (" prefs passed: %s" % doc["prefs_passed"]) if doc.get("prefs_passed") else ""))
for label, path in TIMING + VALUES:
print(" %-70s %s" % (label, fmt(get(doc, path))))
sys.stdout.flush()
def table(dirs: List[Path]) -> int:
rounds: List[Dict[str, Dict[str, Any]]] = []
for d in dirs:
docs = {a: json.loads((d / ("%s.json" % a)).read_text(encoding="utf-8")) for a in ARMS if (d / ("%s.json" % a)).is_file()}
if docs:
rounds.append(docs)
if not rounds:
print("no results")
return 1
arms = [a for a in ARMS if any(a in r for r in rounds)]
print("=" * 130)
print("MSAA AND readPixels: %d round(s), arms %s" % (len(rounds), ", ".join(arms)))
print("=" * 130)
print("TIMING (ms; one value per round, round 1 / round 2 ...)")
print("%-62s" % "" + "".join(" %-24s" % a for a in arms))
for label, path in TIMING:
print("%-62s" % label[:62] + "".join(" %-24s" % ("/".join(fmt(get(r[a], path)) for r in rounds if a in r))[:24] for a in arms))
print("=" * 130)
print("VALUES (what the page reads; round 1)")
r1 = rounds[0]
print("%-62s" % "" + "".join(" %-22s" % a for a in arms))
for label, path in VALUES:
print("%-62s" % label[:62] + "".join(" %-22s" % fmt(get(r1[a], path))[:22] if a in r1 else " %-22s" % "-" for a in arms))
print("=" * 130)
print("THE ANTIALIASED SCENE, pixel by pixel (readPixels of the antialias:true context, round 1)")
pairs = [("ours", "retail"), ("ours_nomsaa", "retail"), ("ours", "ours_nomsaa"), ("ours", "stockheaded"), ("stockheaded", "retail")]
for a, b in pairs:
if a in r1 and b in r1:
print(" %-12s against %-12s: antialias:true image: %s; antialias:false image: %s" % (a, b,
pixel_diff(get(r1[a], "scene.aa_true_readPixels_b64"), get(r1[b], "scene.aa_true_readPixels_b64")),
pixel_diff(get(r1[a], "scene.aa_false_readPixels_b64"), get(r1[b], "scene.aa_false_readPixels_b64"))))
print("=" * 130)
print("WHAT DIFFERS (VALUES read by a page), against retail and ours against ours_nomsaa")
for a, b in (("ours", "retail"), ("ours_nomsaa", "retail"), ("ours", "ours_nomsaa")):
if a in r1 and b in r1:
diff = [(l, get(r1[a], p), get(r1[b], p)) for l, p in VALUES if get(r1[a], p) != get(r1[b], p)]
print(" %s AGAINST %s: %d value(s) differ" % (a.upper(), b.upper(), len(diff)))
for l, x, y in diff:
print(" %-70s %s | %s" % (l[:70], fmt(x)[:30], fmt(y)[:30]))
print("=" * 130)
print("THE HYPOTHESIS, per arm and round: readPixels 1024 repeat p50, antialias:true against antialias:false in the SAME browser")
for a in arms:
cells = []
for r in rounds:
if a in r:
t, f = get(r[a], "timing.antialias_true.repeat_readPixels_ms_p50"), get(r[a], "timing.antialias_false.repeat_readPixels_ms_p50")
cells.append("%s / %s ms%s" % (fmt(t), fmt(f), (" = x%.1f" % (t / f)) if t and f else ""))
print(" %-12s %s" % (a, "; ".join(cells)))
for d in dirs:
for a in arms:
fd = d / ("%s-facts" % a)
if fd.is_dir():
print_facts(a, fd)
return 0
def main() -> int:
ap = argparse.ArgumentParser()
sub = ap.add_subparsers(dest="cmd", required=True)
for name in ("run", "facts"):
p = sub.add_parser(name)
p.add_argument("--arm", choices=ARMS, required=True)
p.add_argument("--binary", default=os.environ.get("INVPW_BINARY_PATH", ""))
p.add_argument("--retail-from", default="")
p.add_argument("--out", type=Path, required=True)
t = sub.add_parser("table")
t.add_argument("dirs", type=Path, nargs="+")
args = ap.parse_args()
if args.cmd == "table":
return table(args.dirs)
if args.arm.startswith("ours") and not args.binary:
ap.error("the ours arms need --binary (or INVPW_BINARY_PATH)")
if args.arm == "retail" and not args.retail_from:
ap.error("the arm retail needs --retail-from (hunt_first_run.py fetch-retail)")
return run(args) if args.cmd == "run" else facts(args)
if __name__ == "__main__":
sys.exit(main())
+141
View File
@@ -0,0 +1,141 @@
// HUNT ONLY (branch hunt/cpu-render-path, never merged). Served by scripts/hunt_msaa.py as /probe.js; the page posts ONE JSON result to /result.
// Hypothesis: our forced multisample (webgl.msaa-samples=4, webgl.msaa-force=true; GLContext.cpp:799 turns framebuffer_multisample back on for the Basic Render
// Driver, which GLContext.cpp:783-787 turns off) makes every readPixels of the default framebuffer resolve MSAA in software: ~400 ms for 1024x1024 in ours against ~89 ms in
// stock and retail. Two things are measured IN EACH BROWSER:
// 1. readPixels / toDataURL timing of a 1024x1024 WebGL canvas, once with antialias:true (the default) and once with antialias:false in the same browser: if the
// multisample resolve is the cost, the antialias:false context is fast in the browser that is slow with antialias:true;
// 2. a 256x256 scene with diagonal edges (a rotated triangle, thin rotated lines, thin rotated slivers) drawn in an antialias:true context and in an antialias:false
// one, read back with readPixels AND toDataURL. The edge pixels are told from the interior ones (an interior pixel has the same colour as its eight neighbours in
// the antialias:false image) and hashed separately; the antialiased pixels (colours that are not one of the flat colours) are counted.
// Also: getContextAttributes().antialias, SAMPLES, SAMPLE_BUFFERS, MAX_SAMPLES and the multisample counts of RGBA8 (WebGL 2).
(async () => {
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const now = () => performance.now();
const q = (a, p) => { if (!a.length) return null; const s = a.slice().sort((x, y) => x - y); return s[Math.min(s.length - 1, Math.floor(p * s.length))]; };
const r3 = (x) => (x === null || x === undefined ? null : Math.round(x * 1000) / 1000);
const result = { timing: {}, attributes: {}, scene: {}, errors: [] };
function hash(u8) { let h1 = 0xdeadbeef ^ u8.length, h2 = 0x41c6ce57 ^ u8.length; for (let i = 0; i < u8.length; i++) { h1 = Math.imul(h1 ^ u8[i], 2654435761); h2 = Math.imul(h2 ^ u8[i], 1597334677); } return (h2 >>> 0).toString(16) + (h1 >>> 0).toString(16); }
function b64(u8) { let s = ""; for (let i = 0; i < u8.length; i += 0x8000) s += String.fromCharCode.apply(null, u8.subarray(i, i + 0x8000)); return btoa(s); }
async function step(name, fn) { try { await fn(); } catch (e) { result.errors.push(name + ": " + ((e && e.message) || e)); } }
function context(kind, w, h, antialias) {
const c = document.createElement("canvas"); c.width = w; c.height = h; c.style.cssText = "position:fixed;left:0;top:0";
document.body.appendChild(c);
const gl = c.getContext(kind, { antialias, preserveDrawingBuffer: true, alpha: true });
if (!gl) { c.remove(); throw new Error("no " + kind + " with antialias:" + antialias); }
return { c, gl };
}
function program(gl, fs) {
const mk = (t, s) => { const x = gl.createShader(t); gl.shaderSource(x, s); gl.compileShader(x); if (!gl.getShaderParameter(x, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(x)); return x; };
const p = gl.createProgram();
gl.attachShader(p, mk(gl.VERTEX_SHADER, "attribute vec2 p; void main(){ gl_Position=vec4(p,0.,1.); }"));
gl.attachShader(p, mk(gl.FRAGMENT_SHADER, fs));
gl.bindAttribLocation(p, 0, "p"); gl.linkProgram(p); gl.useProgram(p);
return p;
}
function verts(gl, arr) {
const b = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, b); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(arr), gl.STREAM_DRAW);
gl.enableVertexAttribArray(0); gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);
}
// ------------------------------------------------------------------------------------------------------------- attributes, per context kind
for (const kind of ["webgl", "webgl2"]) for (const aa of [true, false]) {
await step("attributes " + kind + " " + aa, async () => {
const { c, gl } = context(kind, 64, 64, aa);
const info = gl.getExtension("WEBGL_debug_renderer_info");
const o = { requested_antialias: aa, attributes_antialias: gl.getContextAttributes().antialias, SAMPLES: gl.getParameter(gl.SAMPLES), SAMPLE_BUFFERS: gl.getParameter(gl.SAMPLE_BUFFERS),
RENDERER: gl.getParameter(gl.RENDERER), UNMASKED_RENDERER: info ? gl.getParameter(info.UNMASKED_RENDERER_WEBGL) : null };
if (kind === "webgl2") {
o.MAX_SAMPLES = gl.getParameter(gl.MAX_SAMPLES);
try { o.RGBA8_samples = Array.from(gl.getInternalformatParameter(gl.RENDERBUFFER, gl.RGBA8, gl.SAMPLES)); } catch (e) { o.RGBA8_samples = "ERR " + e.message; }
}
result.attributes[kind + ".antialias_" + aa] = o;
c.remove();
});
}
// ------------------------------------------------------------------------------------------------------------- 1. timing, 1024x1024
for (const aa of [true, false]) {
await step("timing " + aa, async () => {
const { c, gl } = context("webgl", 1024, 1024, aa);
program(gl, "precision highp float; void main(){ gl_FragColor=vec4(fract(gl_FragCoord.x/97.), fract(gl_FragCoord.y/89.), .5, 1.); }");
verts(gl, [-1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, 1]);
gl.viewport(0, 0, 1024, 1024);
const px = new Uint8Array(1024 * 1024 * 4), full = [], one = [], p1 = new Uint8Array(4);
for (let i = 0; i < 7; i++) { gl.drawArrays(gl.TRIANGLES, 0, 6); const s = now(); gl.readPixels(0, 0, 1024, 1024, gl.RGBA, gl.UNSIGNED_BYTE, px); full.push(now() - s); }
for (let i = 0; i < 7; i++) { gl.drawArrays(gl.TRIANGLES, 0, 6); const s = now(); gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, p1); one.push(now() - s); }
gl.drawArrays(gl.TRIANGLES, 0, 6);
const s2 = now(); c.toDataURL("image/png"); const png = now() - s2;
result.timing["antialias_" + aa] = { attributes_antialias: gl.getContextAttributes().antialias, first_readPixels_ms: r3(full[0]), repeat_readPixels_ms_p50: r3(q(full.slice(1), 0.5)),
draw_then_1px_readPixels_ms_p50: r3(q(one, 0.5)), toDataURL_png_ms: r3(png), pixels_hash: hash(px) };
c.remove();
});
}
// ------------------------------------------------------------------------------------------------------------- 2. the scene with diagonal edges
const W = 256, H = 256;
function scene(gl) {
gl.viewport(0, 0, W, H); gl.clearColor(1, 1, 1, 1); gl.clear(gl.COLOR_BUFFER_BIT);
const col = (r, g, b) => program(gl, "precision mediump float; void main(){ gl_FragColor=vec4(" + r + "," + g + "," + b + ",1.); }");
const rot = (x, y, a) => [x * Math.cos(a) - y * Math.sin(a), x * Math.sin(a) + y * Math.cos(a)];
const tri = [[-0.62, -0.5], [0.58, -0.44], [0.02, 0.71]].flatMap(([x, y]) => rot(x, y, 17 * Math.PI / 180));
col(0.1, 0.3, 0.8); verts(gl, tri); gl.drawArrays(gl.TRIANGLES, 0, 3);
col(0.8, 0.1, 0.1); gl.lineWidth(1);
const lines = []; for (let k = 0; k < 12; k++) { const a = (k * 15 + 7) * Math.PI / 180; lines.push(0.05 * Math.cos(a), 0.05 * Math.sin(a), 0.93 * Math.cos(a), 0.93 * Math.sin(a)); }
verts(gl, lines); gl.drawArrays(gl.LINES, 0, 24);
col(0.0, 0.55, 0.1);
const sl = []; for (let k = 0; k < 5; k++) { const a = (k * 31 + 11) * Math.PI / 180; const [x0, y0] = rot(-0.9, -0.85 + k * 0.05, a), [x1, y1] = rot(0.9, -0.85 + k * 0.05, a), [x2, y2] = rot(0.9, -0.845 + k * 0.05, a); sl.push(x0, y0, x1, y1, x2, y2); }
verts(gl, sl); gl.drawArrays(gl.TRIANGLES, 0, 15);
}
function read(gl) { const u = new Uint8Array(W * H * 4); gl.readPixels(0, 0, W, H, gl.RGBA, gl.UNSIGNED_BYTE, u); return u; }
async function viaDataURL(c) {
const im = new Image(); im.src = c.toDataURL(); await im.decode();
const c2 = document.createElement("canvas"); c2.width = W; c2.height = H; const g = c2.getContext("2d"); g.drawImage(im, 0, 0);
const d = g.getImageData(0, 0, W, H).data;
// WebGL's readPixels is bottom-up and the PNG top-down: flip the decoded rows to compare like with like
const out = new Uint8Array(W * H * 4);
for (let y = 0; y < H; y++) out.set(d.subarray(y * W * 4, (y + 1) * W * 4), (H - 1 - y) * W * 4);
return out;
}
await step("scene", async () => {
const imgs = {};
for (const aa of [true, false]) {
const { c, gl } = context("webgl", W, H, aa);
scene(gl);
imgs[aa] = { read: read(gl), url: await viaDataURL(c), attr: gl.getContextAttributes().antialias, samples: gl.getParameter(gl.SAMPLES) };
c.remove();
}
const off = imgs[false].read;
const same = (i, j) => off[i] === off[j] && off[i + 1] === off[j + 1] && off[i + 2] === off[j + 2] && off[i + 3] === off[j + 3];
const edge = new Uint8Array(W * H);
for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) {
const i = (y * W + x) * 4;
for (let dy = -1; dy <= 1; dy++) for (let dx = -1; dx <= 1; dx++) {
const xx = Math.min(W - 1, Math.max(0, x + dx)), yy = Math.min(H - 1, Math.max(0, y + dy));
if (!same(i, (yy * W + xx) * 4)) edge[y * W + x] = 1;
}
}
const flat = new Set();
for (let i = 0; i < W * H * 4; i += 4) flat.add(off[i] + "," + off[i + 1] + "," + off[i + 2] + "," + off[i + 3]);
const split = (u8) => {
const e = [], n = []; let inter = 0;
for (let p = 0; p < W * H; p++) {
const i = p * 4, k = u8[i] + "," + u8[i + 1] + "," + u8[i + 2] + "," + u8[i + 3];
(edge[p] ? e : n).push(u8[i], u8[i + 1], u8[i + 2], u8[i + 3]);
if (!flat.has(k)) inter++;
}
return { edge_hash: hash(Uint8Array.from(e)), interior_hash: hash(Uint8Array.from(n)), antialiased_pixels: inter };
};
const diffs = (a, b) => { let n = 0, inEdge = 0, inInterior = 0, mx = 0; for (let p = 0; p < W * H; p++) { const i = p * 4; let d = 0; for (let k = 0; k < 4; k++) d = Math.max(d, Math.abs(a[i + k] - b[i + k])); if (d) { n++; mx = Math.max(mx, d); edge[p] ? inEdge++ : inInterior++; } } return { differing_pixels: n, at_edges: inEdge, in_interior: inInterior, largest_delta: mx }; };
result.scene = {
size: [W, H], edge_pixels: edge.reduce((s, x) => s + x, 0), flat_colours: flat.size,
aa_true: { attributes_antialias: imgs[true].attr, SAMPLES: imgs[true].samples, readPixels: split(imgs[true].read), toDataURL_decoded: split(imgs[true].url),
png_equals_readPixels: hash(imgs[true].url) === hash(imgs[true].read) },
aa_false: { attributes_antialias: imgs[false].attr, SAMPLES: imgs[false].samples, readPixels: split(imgs[false].read), toDataURL_decoded: split(imgs[false].url),
png_equals_readPixels: hash(imgs[false].url) === hash(imgs[false].read) },
aa_true_against_aa_false_readPixels: diffs(imgs[true].read, imgs[false].read),
aa_true_readPixels_b64: b64(imgs[true].read), aa_false_readPixels_b64: b64(imgs[false].read),
};
});
await fetch("/result", { method: "POST", body: JSON.stringify(result) });
})().catch((e) => fetch("/result", { method: "POST", body: JSON.stringify({ fatal: String((e && e.message) || e) }) }));
+273
View File
@@ -0,0 +1,273 @@
"""HUNT ONLY (branch hunt/cpu-render-path, never merged): does ANY byte a page reads change when our browser runs software WebRender?
The arm `ours_swwr` is `ours` with gfx.webrender.software=true, passed only here through extra_prefs (scripts/hunt_cpu_per_browser.ARM_PREFS).
The wrapper's own byte suites cannot take a pref, so two instruments:
python scripts/hunt_page_bytes.py collect --arm ours --binary "$FF" --out DIR [--launches 2]
python scripts/hunt_page_bytes.py collect --arm ours_swwr --binary "$FF" --out DIR [--launches 2]
python scripts/hunt_page_bytes.py collect --arm ours_vmretail --binary "$FF" --out DIR # needs HUNT_VMRETAIL_PREFS (scripts/hunt_vmretail.py)
python scripts/hunt_page_bytes.py diff DIR [--a ours --b ours_swwr]
python scripts/hunt_page_bytes.py suites A.xml B.xml [--a ours --b ours_swwr]
collect launches the arm `--launches` times (same seed 42 every time), loads a local page, and evaluates scripts/hunt_page_bytes_probe.js: canvas 2D
(getImageData, toDataURL png/jpeg/webp, toBlob, OffscreenCanvas, measureText), WebGL 1 and 2 (VENDOR, RENDERER, unmasked strings, the
extensions and the objects they give, limits, precision formats, readPixels of 10+ scenes, toDataURL, drawImage of the canvas, MSAA resolve,
float targets), an OffscreenCanvas WebGL in a worker, WebGPU adapter facts, the boxes of text in 14 fonts, wrapped paragraphs, system colours.
One gzipped JSON per launch: DIR/<arm>-<n>.json.gz.
diff compares the arms key by key. Launching the same arm twice says which keys are NOT stable by themselves (the noise of the seed, a font
that loads late): those are listed apart and do not count. For every pixel key that differs it says how many bytes, the largest delta and
the first pixel. The last line is the answer: "ANY byte differs: YES/NO".
suites reads the two JUnit files of the wrapper's byte suites run under both arms (pytest -p hunt_extra_prefs_plugin, HUNT_EXTRA_PREFS) and
prints each test's outcome in both. A test that passes in one arm and not in the other is the finding; both passing means both arms read
the bytes of the retail references those tests hold.
"""
from __future__ import annotations
import argparse
import base64
import gzip
import json
import os
import sys
import threading
import xml.etree.ElementTree as ET
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import Any, Dict, List, Optional
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
from hunt_cpu_per_browser import arm_prefs # noqa: E402
SEED = 42
class Blank(BaseHTTPRequestHandler):
def do_GET(self): # noqa: N802
body = b"<!doctype html><meta charset=utf-8><title>probe</title><body></body>"
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *a): # noqa: D102
pass
def collect_once(arm: str, binary: str) -> Dict[str, Any]:
from invisible_playwright import InvisiblePlaywright
httpd = ThreadingHTTPServer(("127.0.0.1", 0), Blank)
httpd.daemon_threads = True
threading.Thread(target=httpd.serve_forever, daemon=True).start()
url = "http://127.0.0.1:%d/" % httpd.server_address[1]
expression = (HERE / "hunt_page_bytes_probe.js").read_text(encoding="utf-8")
try:
with InvisiblePlaywright(seed=SEED, binary_path=binary, headless=True, locale="en-US", timezone="Europe/Rome",
extra_prefs=arm_prefs(arm)) as browser:
page = browser.new_page()
page.goto(url, wait_until="load", timeout=60000)
return page.evaluate(expression)
finally:
httpd.shutdown()
def collect(arm: str, binary: str, out: Path, launches: int) -> int:
out.mkdir(parents=True, exist_ok=True)
rc = 0
for n in range(1, launches + 1):
try:
data = collect_once(arm, binary)
except BaseException as exc: # noqa: BLE001
print("arm %s launch %d: FAILED %s: %s" % (arm, n, type(exc).__name__, str(exc)[:400]))
rc = 1
continue
path = out / ("%s-%d.json.gz" % (arm, n))
with gzip.open(path, "wt", encoding="utf-8") as f:
json.dump(data, f)
errors = sorted(k for k in data if k.endswith(".error"))
pixel = [k for k, v in data.items() if "b64" in v or "w" in v]
print("arm %s launch %d: %d keys, %d pixel/byte keys, %d scene error(s)%s -> %s (%.1f MB)"
% (arm, n, len(data), len(pixel), len(errors), (": " + ", ".join("%s=%s" % (k, data[k].get("s")) for k in errors)) if errors else "",
path, path.stat().st_size / 2 ** 20))
for k in ("gl1.unmasked", "gl2.unmasked", "gl1.context", "gl2.context", "gpu.webgpu.info", "env.dpr"):
if k in data:
print(" %s = %s" % (k, str(data[k].get("s", data[k]))[:200]))
sys.stdout.flush()
return rc
# -------------------------------------------------------------------------------------------------------------------- diff
def load_runs(root: Path, arm: str) -> List[Dict[str, Any]]:
runs = []
for p in sorted(root.glob("%s-*.json.gz" % arm)):
with gzip.open(p, "rt", encoding="utf-8") as f:
runs.append(json.load(f))
return runs
def ident(v: Dict[str, Any]) -> str:
"""What identifies a value: its string, or the hash of its bytes."""
return ("s:" + v["s"]) if "s" in v else ("h:%s/%s" % (v.get("h"), v.get("n")))
def short(v: Dict[str, Any], limit: int = 160) -> str:
return (v["s"] if "s" in v else "%s bytes, hash %s%s" % (v.get("n"), v.get("h"), (", starts " + v["s0"][:60]) if v.get("s0") else ""))[:limit]
def byte_diff(a: Dict[str, Any], b: Dict[str, Any]) -> str:
if "b64" not in a or "b64" not in b:
return "bytes not kept (larger than 400 KiB)"
x, y = base64.b64decode(a["b64"]), base64.b64decode(b["b64"])
if len(x) != len(y):
return "different lengths %d / %d" % (len(x), len(y))
n, mx, first = 0, 0, None
for i, (p, q) in enumerate(zip(x, y)):
if p != q:
n += 1
mx = max(mx, abs(p - q))
if first is None:
first = i
bpp, w = a.get("bpp", 4), a.get("w")
where = ""
if first is not None and w:
px = first // bpp
where = ", first at pixel (%d, %d)" % (px % w, px // w)
return "%d of %d bytes differ, largest delta %d%s" % (n, len(x), mx, where)
def diff(root: Path, arm_a: str, arm_b: str) -> int:
ra, rb = load_runs(root, arm_a), load_runs(root, arm_b)
print("=" * 100)
print("PAGE-READABLE BYTES, %s (%d launch(es)) against %s (%d launch(es))" % (arm_a, len(ra), arm_b, len(rb)))
if not ra or not rb:
print("no data for %s" % (arm_a if not ra else arm_b))
return 1
keys = sorted(set().union(*[set(r) for r in ra + rb]))
unstable, differ, same, missing = [], [], [], []
for k in keys:
va = [r[k] for r in ra if k in r]
vb = [r[k] for r in rb if k in r]
if len(va) != len(ra) or len(vb) != len(rb):
missing.append((k, len(va), len(vb)))
continue
sa, sb = {ident(v) for v in va}, {ident(v) for v in vb}
if len(sa) > 1 or len(sb) > 1:
unstable.append((k, len(sa), len(sb), bool(sa & sb)))
elif sa != sb:
differ.append(k)
else:
same.append(k)
print("%d keys: %d identical in both arms, %d DIFFER, %d not stable inside an arm (listed apart), %d missing in a launch"
% (len(keys), len(same), len(differ), len(unstable), len(missing)))
for prefix in ("env", "c2d", "gl1", "gl2", "worker", "gpu", "dom"):
ks = [k for k in keys if k.split(".")[0] == prefix]
if ks:
print(" %-7s %3d keys, %3d identical, %3d differ" % (prefix, len(ks), len([k for k in ks if k in same]), len([k for k in ks if k in differ])))
if differ:
print("-" * 100)
print("KEYS THAT DIFFER between %s and %s (launch 1 of each shown):" % (arm_a, arm_b))
for k in differ:
va, vb = ra[0][k], rb[0][k]
print(" %s" % k)
if "b64" in va or "w" in va:
print(" %s" % byte_diff(va, vb))
print(" %s: %s" % (arm_a, short(va)))
print(" %s: %s" % (arm_b, short(vb)))
if unstable:
print("-" * 100)
print("NOT STABLE inside an arm (the same arm launched again gave another value; not counted): key (values in %s, in %s, overlap)" % (arm_a, arm_b))
for k, na, nb, overlap in unstable:
print(" %s (%d, %d, %s)" % (k, na, nb, "overlap" if overlap else "no overlap"))
if missing:
print("-" * 100)
print("MISSING in some launch: " + ", ".join("%s (%d/%d)" % m for m in missing))
errs = [k for k in keys if k.endswith(".error")]
if errs:
print("-" * 100)
print("scenes that threw (the message is compared like any value): " + ", ".join(errs))
print("-" * 100)
print("ANY byte a page reads differs between %s and %s: %s (%d key(s) differ of %d compared; %d unstable keys left out)"
% (arm_a, arm_b, "YES" if differ else "NO", len(differ), len(same) + len(differ), len(unstable)))
return 0
# ------------------------------------------------------------------------------------------------------------------ suites
def junit(path: Path) -> Dict[str, str]:
out: Dict[str, str] = {}
for tc in ET.parse(path).getroot().iter("testcase"):
name = "%s::%s" % (tc.get("classname"), tc.get("name"))
state = "passed"
for child in tc:
if child.tag in ("failure", "error"):
state = "FAILED: " + (child.get("message") or "")[:160].replace("\n", " ")
elif child.tag == "skipped":
state = "skipped: " + (child.get("message") or "")[:100].replace("\n", " ")
out[name] = state
return out
def suites(xa: Path, xb: Path, arm_a: str, arm_b: str) -> int:
print("=" * 100)
print("THE WRAPPER'S BYTE SUITES under %s and under %s (JUnit)" % (arm_a, arm_b))
try:
a, b = junit(xa), junit(xb)
except (OSError, ET.ParseError) as exc:
print("cannot read the JUnit files: %s: %s" % (type(exc).__name__, exc))
return 1
names = sorted(set(a) | set(b))
def kind(s: Optional[str]) -> str:
return "missing" if s is None else s.split(":")[0].lower()
counts = {}
for n in names:
key = (kind(a.get(n)), kind(b.get(n)))
counts[key] = counts.get(key, 0) + 1
print("%d tests; (outcome in %s, outcome in %s): count" % (len(names), arm_a, arm_b))
for key, c in sorted(counts.items()):
print(" %-9s %-9s %d" % (key[0], key[1], c))
print("-" * 100)
for n in names:
sa, sb = a.get(n), b.get(n)
flag = "" if kind(sa) == kind(sb) else " <-- DIFFERS"
print("%-9s %-9s %s%s" % (kind(sa), kind(sb), n, flag))
if kind(sa) in ("failed", "error") or kind(sb) in ("failed", "error"):
print(" %s: %s" % (arm_a, sa))
print(" %s: %s" % (arm_b, sb))
differs = [n for n in names if kind(a.get(n)) != kind(b.get(n))]
print("-" * 100)
print("tests whose outcome differs between the arms: %d%s" % (len(differs), "" if not differs else " -> " + ", ".join(differs[:20])))
return 0
def main() -> int:
ap = argparse.ArgumentParser()
sub = ap.add_subparsers(dest="cmd", required=True)
c = sub.add_parser("collect")
c.add_argument("--arm", choices=("ours", "ours_swwr", "ours_vmretail", "ours_nomsaa"), required=True)
c.add_argument("--binary", default=os.environ.get("INVPW_BINARY_PATH", ""))
c.add_argument("--out", type=Path, required=True)
c.add_argument("--launches", type=int, default=2)
d = sub.add_parser("diff")
d.add_argument("root", type=Path)
d.add_argument("--a", default="ours")
d.add_argument("--b", default="ours_swwr", help="ours_swwr, ours_vmretail or ours_nomsaa")
s = sub.add_parser("suites")
s.add_argument("a", type=Path)
s.add_argument("b", type=Path)
s.add_argument("--a-name", default="ours")
s.add_argument("--b-name", default="ours_swwr", help="ours_swwr or ours_vmretail")
args = ap.parse_args()
if args.cmd == "collect":
if not args.binary:
ap.error("--binary (or INVPW_BINARY_PATH)")
return collect(args.arm, args.binary, args.out, args.launches)
if args.cmd == "diff":
return diff(args.root, args.a, args.b)
return suites(args.a, args.b, args.a_name, args.b_name)
if __name__ == "__main__":
sys.exit(main())
@@ -1,475 +1,422 @@
// The probe of tests/test_the_bytes_a_page_reads_do_not_change_e2e.py: one expression that resolves to a flat object
// {key: {s: "a short string"} | {h, n, s0} | {h, n, w, b64}} of everything a page can read about drawing and text:
// c2d.* canvas 2D: getImageData bytes, toDataURL (png, jpeg, webp), toBlob, OffscreenCanvas.convertToBlob, measureText; drawImage scaled up
// and down with imageSmoothing off and on at every imageSmoothingQuality (c2d.scale.*); gradients (linear, radial, conic) filling and
// stroking text (c2d.gradtext)
// gl1.* WebGL 1 and gl2.* WebGL 2: strings, extensions, limits, precision formats, readPixels bytes of several scenes, toDataURL, drawImage of the canvas
// worker.* an OffscreenCanvas WebGL context in a worker
// gpu.* the WebGPU adapter
// dom.* text layout: the boxes of spans in many fonts, wrapped paragraphs, system colours
// env.* the values the persona declares around it
// A PNG the page reads (toDataURL, toBlob, convertToBlob) keeps its bytes in `b64`: the test compares the pixels it decodes to, because the engine
// writes a per-launch ancillary chunk into every PNG (tests/_page_bytes.py). Every scene is wrapped: an exception becomes `<scene>.error` and is
// compared like any other value, so every launch gives the same keys.
// Taken from the hunt that measured the Windows reference (scripts/hunt_page_bytes_probe.js of run 43652292533), with its encoding mode removed.
(async () => {
const out = {};
const enc = new TextEncoder();
function hashBytes(u8) { // cyrb53 over bytes: no crypto.subtle (it needs a secure context)
let h1 = 0xdeadbeef ^ u8.length, h2 = 0x41c6ce57 ^ u8.length;
for (let i = 0; i < u8.length; i++) { const ch = u8[i]; h1 = Math.imul(h1 ^ ch, 2654435761); h2 = Math.imul(h2 ^ ch, 1597334677); }
h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(16);
}
function b64(u8) {
let s = "";
for (let i = 0; i < u8.length; i += 0x8000) s += String.fromCharCode.apply(null, u8.subarray(i, i + 0x8000));
return btoa(s);
}
function put(k, v, w) {
if (ArrayBuffer.isView(v) || v instanceof ArrayBuffer) {
const u8 = v instanceof ArrayBuffer ? new Uint8Array(v) : new Uint8Array(v.buffer, v.byteOffset, v.byteLength);
out[k] = { h: hashBytes(u8), n: u8.length };
if (w) { out[k].w = w; out[k].bpp = 4 * (v.BYTES_PER_ELEMENT || 1); } // pixels per row, bytes per pixel (RGBA)
if (u8.length <= 400 * 1024) out[k].b64 = b64(u8);
} else {
const s = typeof v === "string" ? v : JSON.stringify(v);
out[k] = s.length <= 3000 ? { s } : { h: hashBytes(enc.encode(s)), n: s.length, s0: s.slice(0, 200) };
if (s.length > 3000 && s.startsWith("data:image/png;base64,") && s.length <= 600 * 1024) out[k].b64 = s.slice(22);
}
}
async function scene(k, fn) {
try { await fn(); } catch (e) { put(k + ".error", String((e && e.message) || e)); }
}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
// ------------------------------------------------------------------------------------------------------------ env
await scene("env", async () => {
put("env.ua", navigator.userAgent);
put("env.platform", navigator.platform);
put("env.oscpu", navigator.oscpu || "");
put("env.hw", navigator.hardwareConcurrency);
put("env.lang", navigator.languages);
put("env.dpr", window.devicePixelRatio);
put("env.screen", [screen.width, screen.height, screen.availWidth, screen.availHeight, screen.colorDepth, screen.pixelDepth]);
put("env.mq", ["(color-gamut: srgb)", "(color-gamut: p3)", "(dynamic-range: high)", "(prefers-color-scheme: dark)", "(prefers-reduced-motion: reduce)",
"(forced-colors: active)", "(inverted-colors: inverted)"].map((q) => matchMedia(q).matches));
});
// ---------------------------------------------------------------------------------------------------- canvas 2D
function c2d(w, h) { const c = document.createElement("canvas"); c.width = w; c.height = h; return [c, c.getContext("2d")]; }
function dataUrlBytes(url) {
const bin = atob(url.split(",")[1]);
const u = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) u[i] = bin.charCodeAt(i);
return u;
}
async function read2d(k, c, g) {
put(k + ".getImageData", g.getImageData(0, 0, c.width, c.height).data, c.width);
put(k + ".png", c.toDataURL());
put(k + ".jpeg", c.toDataURL("image/jpeg", 0.8));
put(k + ".webp", c.toDataURL("image/webp", 0.8));
const blob = await new Promise((r) => c.toBlob(r));
put(k + ".toBlob", blob ? new Uint8Array(await blob.arrayBuffer()) : "null");
}
await scene("c2d.shapes", async () => {
const [c, g] = c2d(256, 160);
g.fillStyle = "#fff"; g.fillRect(0, 0, 256, 160);
const lg = g.createLinearGradient(0, 0, 256, 0);
lg.addColorStop(0, "#f00"); lg.addColorStop(0.5, "rgba(0,200,0,.5)"); lg.addColorStop(1, "#00f");
g.fillStyle = lg; g.fillRect(8, 8, 240, 40);
const rg = g.createRadialGradient(60, 100, 4, 60, 100, 50);
rg.addColorStop(0, "#ff0"); rg.addColorStop(1, "rgba(255,0,255,.2)");
g.fillStyle = rg; g.beginPath(); g.arc(60, 100, 50, 0, Math.PI * 2); g.fill();
g.strokeStyle = "#123"; g.lineWidth = 1.5; g.beginPath(); g.moveTo(130, 60); g.bezierCurveTo(160, 20, 200, 140, 240, 70); g.stroke();
g.lineWidth = 0.7; g.beginPath(); g.ellipse(190, 110, 40, 20, 0.5, 0, Math.PI * 2); g.stroke();
g.save(); g.shadowColor = "rgba(0,0,0,.6)"; g.shadowBlur = 6; g.shadowOffsetX = 3; g.shadowOffsetY = 3; g.fillStyle = "#38c"; g.fillRect(120, 100, 50, 30); g.restore();
g.save(); g.translate(30, 140); g.rotate(0.3); g.scale(1.3, 0.8); g.fillStyle = "#a40"; g.fillRect(0, 0, 40, 20); g.restore();
if (g.createConicGradient) {
const cg = g.createConicGradient(0.5, 215, 140);
cg.addColorStop(0, "#f80"); cg.addColorStop(0.5, "#08f"); cg.addColorStop(1, "#f80");
g.fillStyle = cg; g.fillRect(190, 120, 60, 36);
}
await read2d("c2d.shapes", c, g);
});
await scene("c2d.composite", async () => {
const ops = ["source-over", "source-in", "source-out", "source-atop", "destination-over", "destination-in", "destination-out", "destination-atop",
"lighter", "copy", "xor", "multiply", "screen", "overlay", "darken", "lighten", "color-dodge", "color-burn", "hard-light", "soft-light",
"difference", "exclusion", "hue", "saturation", "color", "luminosity"];
const [c, g] = c2d(8 * 32, 4 * 32);
ops.forEach((op, i) => {
const x = (i % 8) * 32, y = Math.floor(i / 8) * 32;
g.save(); g.beginPath(); g.rect(x, y, 32, 32); g.clip();
g.globalCompositeOperation = "source-over";
g.fillStyle = "rgba(200,60,40,.8)"; g.fillRect(x + 2, y + 2, 20, 20);
g.globalCompositeOperation = op;
g.fillStyle = "rgba(30,90,220,.6)"; g.fillRect(x + 10, y + 10, 20, 20);
g.restore();
});
await read2d("c2d.composite", c, g);
});
await scene("c2d.filter_draw_image", async () => {
const [c, g] = c2d(160, 120);
const [s, sg] = c2d(10, 10);
for (let i = 0; i < 100; i++) { sg.fillStyle = "hsl(" + ((i * 37) % 360) + ",70%,50%)"; sg.fillRect(i % 10, Math.floor(i / 10), 1, 1); }
g.imageSmoothingEnabled = true; g.imageSmoothingQuality = "high";
g.drawImage(s, 0, 0, 10, 10, 5.5, 5.5, 70.3, 70.3);
g.imageSmoothingEnabled = false; g.drawImage(s, 80, 5, 60, 60);
if ("filter" in g) { g.filter = "blur(2px) saturate(1.4)"; g.drawImage(s, 5, 70, 40, 40); g.filter = "none"; }
const p = g.createPattern(s, "repeat"); g.fillStyle = p; g.fillRect(60, 70, 90, 40);
const d = g.getImageData(0, 0, 40, 40); g.putImageData(d, 100, 80);
await read2d("c2d.image", c, g);
});
const FONTS = ["16px sans-serif", "20px serif", "18px monospace", "bold 16px Arial", "italic 15px 'Segoe UI'", "16px 'Times New Roman'", "16px Calibri",
"14px Consolas", "16px Verdana", "16px Tahoma", "17px Georgia", "16px 'Segoe UI Emoji'", "16px 'Microsoft YaHei'", "16px 'Yu Gothic'"];
const TEXTS = ["Hamburgefonstiv 0123456789", "The quick brown fox jumps over the lazy dog", "ÀÉÎÕÜ ß fi fl ffl", "日本語のテキスト 漢字", "😀🚀👍🏽", "مرحبا بالعالم"];
await scene("c2d.text", async () => {
const [c, g] = c2d(520, FONTS.length * 28 + 20);
g.fillStyle = "#fff"; g.fillRect(0, 0, c.width, c.height);
FONTS.forEach((f, i) => {
g.font = f; g.fillStyle = "#101820"; g.textBaseline = "alphabetic";
g.fillText(TEXTS[i % TEXTS.length], 6, 22 + i * 28);
g.strokeStyle = "rgba(200,0,0,.8)"; g.lineWidth = 0.6; g.strokeText("Ag", 470, 22 + i * 28);
});
await read2d("c2d.text", c, g);
const m = [];
for (const f of FONTS) {
g.font = f;
for (const t of TEXTS) {
const r = g.measureText(t);
m.push([f, t, r.width, r.actualBoundingBoxLeft, r.actualBoundingBoxRight, r.actualBoundingBoxAscent, r.actualBoundingBoxDescent,
r.fontBoundingBoxAscent, r.fontBoundingBoxDescent]);
}
}
put("c2d.measure", m);
});
await scene("c2d.offscreen", async () => {
if (typeof OffscreenCanvas === "undefined") { put("c2d.offscreen", "no OffscreenCanvas"); return; }
const oc = new OffscreenCanvas(160, 80), g = oc.getContext("2d");
g.fillStyle = "#fed"; g.fillRect(0, 0, 160, 80); g.fillStyle = "rgba(10,120,200,.7)"; g.beginPath(); g.arc(50, 40, 30, 0, 6.2); g.fill();
g.font = "bold 18px sans-serif"; g.fillStyle = "#222"; g.fillText("offscreen 2d", 70, 45);
put("c2d.offscreen.getImageData", g.getImageData(0, 0, 160, 80).data, 160);
const blob = await oc.convertToBlob();
put("c2d.offscreen.convertToBlob", new Uint8Array(await blob.arrayBuffer()));
});
// ----------------------------------------------------------------------------------------- drawImage scaled, smoothing and quality
// A 24x24 source with hard edges and a ramp, a 200x200 one (to scale down), each drawn up and down, rotated and not, with imageSmoothing off and
// on at low, medium and high. The pixels (getImageData) and the PNG of the same canvas, which the test compares decoded.
await scene("c2d.scale", async () => {
const [s1, sg1] = c2d(24, 24);
for (let y = 0; y < 24; y++) for (let x = 0; x < 24; x++) {
sg1.fillStyle = (x + y) % 5 === 0 ? "#000" : "hsl(" + ((x * 13 + y * 7) % 360) + "," + (40 + (y * 2)) + "%," + (30 + x) + "%)";
sg1.fillRect(x, y, 1, 1);
}
const [s2, sg2] = c2d(200, 200);
for (let i = 0; i < 40; i++) {
sg2.fillStyle = "hsl(" + (i * 9) + ",70%,50%)"; sg2.fillRect((i * 17) % 190, (i * 29) % 190, 23 + (i % 7), 11 + (i % 5));
sg2.strokeStyle = i % 2 ? "#fff" : "#111"; sg2.lineWidth = 1; sg2.beginPath(); sg2.moveTo(i * 5, 0); sg2.lineTo(200 - i * 4, 200); sg2.stroke();
}
const configs = [["off", false, "low"], ["low", true, "low"], ["medium", true, "medium"], ["high", true, "high"]];
for (const [name, on, quality] of configs) {
const [c, g] = c2d(220, 130);
g.fillStyle = "#fff"; g.fillRect(0, 0, 220, 130);
g.imageSmoothingEnabled = on; g.imageSmoothingQuality = quality;
g.drawImage(s1, 0, 0, 24, 24, 3.25, 3.25, 97.3, 97.3); // up, not an integer factor
g.drawImage(s2, 0, 0, 200, 200, 110.5, 4.5, 37, 37); // down, far
g.drawImage(s2, 20, 20, 120, 120, 150, 4, 61, 61); // down, near, a part of the source
g.drawImage(s1, 0, 0, 24, 24, 110, 50, 24, 24); // 1:1 at a whole pixel
g.save(); g.translate(180, 95); g.rotate(0.35); g.drawImage(s1, 0, 0, 24, 24, -20, -20, 40, 40); g.restore(); // rotated and scaled up
g.save(); g.translate(60, 118); g.scale(1.7, 0.45); g.drawImage(s2, 0, 0, 200, 200, 0, -20, 30, 30); g.restore(); // scaled by a transform
put("c2d.scale." + name + ".getImageData", g.getImageData(0, 0, 220, 130).data, 220);
put("c2d.scale." + name + ".png", c.toDataURL());
}
});
// Text filled and stroked with gradients of the three kinds, with a shadow and with a global alpha: the paths the canvas takes for a gradient
// over glyphs.
await scene("c2d.gradtext", async () => {
const [c, g] = c2d(420, 210);
g.fillStyle = "#fff"; g.fillRect(0, 0, 420, 210);
const lin = g.createLinearGradient(10, 0, 400, 0);
lin.addColorStop(0, "#d00"); lin.addColorStop(0.4, "#fc0"); lin.addColorStop(0.7, "rgba(0,160,60,.6)"); lin.addColorStop(1, "#04d");
const rad = g.createRadialGradient(100, 90, 4, 130, 100, 90);
rad.addColorStop(0, "#fff"); rad.addColorStop(0.5, "#c0c"); rad.addColorStop(1, "#036");
const rad2 = g.createRadialGradient(300, 60, 30, 340, 80, 8); // the focal circle outside the start circle
rad2.addColorStop(0, "#f60"); rad2.addColorStop(1, "#0af");
const con = g.createConicGradient ? g.createConicGradient(0.6, 210, 150) : lin;
con.addColorStop(0, "#f80"); con.addColorStop(0.33, "#0c8"); con.addColorStop(0.66, "#80f"); con.addColorStop(1, "#f80");
g.textBaseline = "alphabetic";
g.font = "bold 40px sans-serif"; g.fillStyle = lin; g.fillText("Gradient 0123", 10, 44);
g.font = "italic 34px serif"; g.fillStyle = rad; g.fillText("Hamburgefonstiv", 10, 90);
g.font = "28px monospace"; g.fillStyle = rad2; g.fillText("radial focal 1/2", 220, 40);
g.font = "bold 44px Arial"; g.strokeStyle = lin; g.lineWidth = 2.5; g.strokeText("Stroke", 10, 140);
g.font = "36px 'Times New Roman'"; g.fillStyle = con; g.fillText("Conic text", 150, 150);
g.save(); g.shadowColor = "rgba(0,0,0,.55)"; g.shadowBlur = 4; g.shadowOffsetX = 2; g.shadowOffsetY = 3; g.globalAlpha = 0.8;
g.font = "30px 'Segoe UI'"; g.fillStyle = lin; g.fillText("Shadow and alpha", 10, 190); g.restore();
g.font = "20px sans-serif"; g.fillStyle = con; g.fillRect(300, 150, 110, 50); g.fillStyle = "#fff"; g.fillText("on conic", 310, 180);
put("c2d.gradtext.getImageData", g.getImageData(0, 0, 420, 210).data, 420);
put("c2d.gradtext.png", c.toDataURL());
});
// ------------------------------------------------------------------------------------------------------------ WebGL
const P1 = ["VERSION", "SHADING_LANGUAGE_VERSION", "VENDOR", "RENDERER", "MAX_TEXTURE_SIZE", "MAX_CUBE_MAP_TEXTURE_SIZE", "MAX_RENDERBUFFER_SIZE",
"MAX_VIEWPORT_DIMS", "ALIASED_LINE_WIDTH_RANGE", "ALIASED_POINT_SIZE_RANGE", "MAX_VERTEX_ATTRIBS", "MAX_VARYING_VECTORS",
"MAX_COMBINED_TEXTURE_IMAGE_UNITS", "MAX_VERTEX_TEXTURE_IMAGE_UNITS", "MAX_TEXTURE_IMAGE_UNITS", "MAX_VERTEX_UNIFORM_VECTORS",
"MAX_FRAGMENT_UNIFORM_VECTORS", "RED_BITS", "GREEN_BITS", "BLUE_BITS", "ALPHA_BITS", "DEPTH_BITS", "STENCIL_BITS", "SAMPLES",
"SAMPLE_BUFFERS", "SUBPIXEL_BITS"];
const P2 = ["MAX_3D_TEXTURE_SIZE", "MAX_ARRAY_TEXTURE_LAYERS", "MAX_COLOR_ATTACHMENTS", "MAX_DRAW_BUFFERS", "MAX_ELEMENTS_INDICES", "MAX_ELEMENTS_VERTICES",
"MAX_FRAGMENT_INPUT_COMPONENTS", "MAX_FRAGMENT_UNIFORM_BLOCKS", "MAX_FRAGMENT_UNIFORM_COMPONENTS", "MAX_PROGRAM_TEXEL_OFFSET", "MAX_SAMPLES",
"MAX_SERVER_WAIT_TIMEOUT", "MAX_TEXTURE_LOD_BIAS", "MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS", "MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS",
"MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS", "MAX_UNIFORM_BLOCK_SIZE", "MAX_UNIFORM_BUFFER_BINDINGS", "MAX_VARYING_COMPONENTS",
"MAX_VERTEX_OUTPUT_COMPONENTS", "MAX_VERTEX_UNIFORM_BLOCKS", "MAX_VERTEX_UNIFORM_COMPONENTS", "MIN_PROGRAM_TEXEL_OFFSET",
"MAX_COMBINED_UNIFORM_BLOCKS", "MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS", "MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS", "UNIFORM_BUFFER_OFFSET_ALIGNMENT"];
function glInfo(p, gl, v2) {
const params = {};
for (const n of P1.concat(v2 ? P2 : [])) {
try { let v = gl.getParameter(gl[n]); if (ArrayBuffer.isView(v)) v = Array.from(v); params[n] = v; } catch (e) { params[n] = "ERR " + e.message; }
}
put(p + ".params", params);
const exts = gl.getSupportedExtensions() || [];
put(p + ".extensions", exts);
const eo = [];
for (const e of exts) {
try { const o = gl.getExtension(e); eo.push([e, o ? Object.keys(Object.getPrototypeOf(o)).length : -1]); } catch (er) { eo.push([e, "ERR"]); }
}
put(p + ".extension_objects", eo);
const dbg = gl.getExtension("WEBGL_debug_renderer_info");
put(p + ".unmasked", dbg ? [gl.getParameter(dbg.UNMASKED_VENDOR_WEBGL), gl.getParameter(dbg.UNMASKED_RENDERER_WEBGL)] : "no WEBGL_debug_renderer_info");
const an = gl.getExtension("EXT_texture_filter_anisotropic");
put(p + ".anisotropy", an ? gl.getParameter(an.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : "none");
const prec = [];
for (const sh of ["VERTEX_SHADER", "FRAGMENT_SHADER"]) for (const lv of ["LOW_FLOAT", "MEDIUM_FLOAT", "HIGH_FLOAT", "LOW_INT", "MEDIUM_INT", "HIGH_INT"]) {
const f = gl.getShaderPrecisionFormat(gl[sh], gl[lv]);
prec.push([sh, lv, f && f.rangeMin, f && f.rangeMax, f && f.precision]);
}
put(p + ".precision", prec);
put(p + ".attributes", gl.getContextAttributes());
}
function program(gl, vs, fs) {
const mk = (type, src) => {
const s = gl.createShader(type); gl.shaderSource(s, src); gl.compileShader(s);
if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) throw new Error("shader: " + gl.getShaderInfoLog(s));
return s;
};
const pr = gl.createProgram();
gl.attachShader(pr, mk(gl.VERTEX_SHADER, vs)); gl.attachShader(pr, mk(gl.FRAGMENT_SHADER, fs));
gl.bindAttribLocation(pr, 0, "p"); gl.bindAttribLocation(pr, 1, "c");
gl.linkProgram(pr);
if (!gl.getProgramParameter(pr, gl.LINK_STATUS)) throw new Error("link: " + gl.getProgramInfoLog(pr));
gl.useProgram(pr);
return pr;
}
function buffer(gl, loc, data, size) {
const b = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, b); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(data), gl.STATIC_DRAW);
gl.enableVertexAttribArray(loc); gl.vertexAttribPointer(loc, size, gl.FLOAT, false, 0, 0);
return b;
}
function pixels(gl, w, h) { const u = new Uint8Array(w * h * 4); gl.readPixels(0, 0, w, h, gl.RGBA, gl.UNSIGNED_BYTE, u); return u; }
const VS = "attribute vec2 p; attribute vec4 c; varying vec4 v; varying vec2 uv; void main(){ v=c; uv=p*0.5+0.5; gl_Position=vec4(p,0.,1.); gl_PointSize=7.5; }";
const FS_COLOR = "precision mediump float; varying vec4 v; void main(){ gl_FragColor=v; }";
const QUAD = [-1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, 1];
async function glScenes(p, v2) {
const kind = v2 ? "webgl2" : "webgl";
const mkctx = (w, h, attrs) => {
const c = document.createElement("canvas"); c.width = w; c.height = h;
return [c, c.getContext(kind, Object.assign({ preserveDrawingBuffer: true }, attrs || {}))];
};
let [c0, gl0] = mkctx(64, 64);
if (!gl0) { put(p + ".context", "null"); return; }
glInfo(p, gl0, v2);
await scene(p + ".triangle", async () => {
const [c, gl] = mkctx(96, 96, { antialias: false });
gl.viewport(0, 0, 96, 96); gl.clearColor(0.1, 0.2, 0.3, 0.4); gl.clear(gl.COLOR_BUFFER_BIT);
program(gl, VS, FS_COLOR);
buffer(gl, 0, [-0.8, -0.7, 0.9, -0.5, -0.1, 0.85], 2);
buffer(gl, 1, [1, 0, 0, 1, 0, 1, 0, 0.7, 0, 0, 1, 0.3], 4);
gl.drawArrays(gl.TRIANGLES, 0, 3);
put(p + ".triangle.readPixels", pixels(gl, 96, 96), 96);
put(p + ".triangle.toDataURL", c.toDataURL());
put(p + ".triangle.toDataURL_jpeg", c.toDataURL("image/jpeg", 0.8));
const [d, g2] = c2d(96, 96); g2.drawImage(c, 0, 0);
put(p + ".triangle.drawImage", g2.getImageData(0, 0, 96, 96).data, 96);
});
await scene(p + ".antialias", async () => {
for (const aa of [true, false]) {
const [c, gl] = mkctx(96, 96, { antialias: aa });
gl.viewport(0, 0, 96, 96); gl.clearColor(1, 1, 1, 1); gl.clear(gl.COLOR_BUFFER_BIT);
program(gl, VS, FS_COLOR);
buffer(gl, 0, [-0.83, -0.71, 0.77, -0.43, -0.1, 0.89, 0.3, 0.9, 0.9, 0.2, 0.6, 0.95], 2);
buffer(gl, 1, [0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0.8, 0, 0, 1, 0.8, 0, 0, 1, 0.8, 0, 0, 1], 4);
gl.drawArrays(gl.TRIANGLES, 0, 6);
put(p + ".antialias." + aa + ".samples", gl.getParameter(gl.SAMPLES));
put(p + ".antialias." + aa + ".readPixels", pixels(gl, 96, 96), 96);
}
});
for (const prec of ["highp", "mediump"]) await scene(p + ".math." + prec, async () => {
const [c, gl] = mkctx(64, 64, { antialias: false });
const fp = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT);
const use = prec === "highp" && !(fp && fp.precision) ? "mediump" : prec;
gl.viewport(0, 0, 64, 64);
program(gl, VS, "precision " + use + " float; varying vec2 uv;" +
"void main(){ float x=uv.x*6.0; gl_FragColor=vec4(fract(sin(x)*43758.5453), fract(exp(uv.y*3.0)), fract(pow(uv.x+0.5, 2.2+uv.y)), fract(sqrt(uv.x*uv.y)*17.0)); }");
buffer(gl, 0, QUAD, 2); gl.drawArrays(gl.TRIANGLES, 0, 6);
put(p + ".math." + prec + ".readPixels", pixels(gl, 64, 64), 64);
});
await scene(p + ".texture", async () => {
const [c, gl] = mkctx(64, 64, { antialias: false });
gl.viewport(0, 0, 64, 64);
program(gl, VS, "precision mediump float; varying vec2 uv; uniform sampler2D t; void main(){ gl_FragColor=texture2D(t, uv*0.9+0.03); }");
const tex = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, tex);
const d = new Uint8Array(32 * 32 * 4); let s = 12345;
for (let i = 0; i < d.length; i++) { s = (s * 1103515245 + 12345) & 0x7fffffff; d[i] = (s >> 16) & 255; }
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 32, 32, 0, gl.RGBA, gl.UNSIGNED_BYTE, d);
gl.generateMipmap(gl.TEXTURE_2D);
for (const [name, mag, min] of [["linear", gl.LINEAR, gl.LINEAR], ["mip", gl.LINEAR, gl.LINEAR_MIPMAP_LINEAR], ["nearest", gl.NEAREST, gl.NEAREST]]) {
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, mag); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, min);
gl.clear(gl.COLOR_BUFFER_BIT);
buffer(gl, 0, QUAD, 2); gl.drawArrays(gl.TRIANGLES, 0, 6);
put(p + ".texture." + name + ".readPixels", pixels(gl, 64, 64), 64);
}
});
await scene(p + ".blend", async () => {
const [c, gl] = mkctx(64, 64, { antialias: false, premultipliedAlpha: false });
gl.viewport(0, 0, 64, 64); gl.clearColor(0.2, 0.4, 0.6, 0.5); gl.clear(gl.COLOR_BUFFER_BIT);
program(gl, VS, FS_COLOR); gl.enable(gl.BLEND);
for (const [src, dst] of [[gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA], [gl.ONE, gl.ONE_MINUS_SRC_ALPHA], [gl.DST_COLOR, gl.ZERO]]) {
gl.blendFunc(src, dst);
buffer(gl, 0, [-0.9, -0.9, 0.3, -0.5, -0.3, 0.7], 2);
buffer(gl, 1, [0.9, 0.2, 0.1, 0.37, 0.1, 0.8, 0.3, 0.55, 0.2, 0.3, 0.9, 0.21], 4);
gl.drawArrays(gl.TRIANGLES, 0, 3);
}
put(p + ".blend.readPixels", pixels(gl, 64, 64), 64);
});
await scene(p + ".lines_points", async () => {
const [c, gl] = mkctx(64, 64, { antialias: false });
gl.viewport(0, 0, 64, 64); gl.clearColor(1, 1, 1, 1); gl.clear(gl.COLOR_BUFFER_BIT);
program(gl, VS, FS_COLOR);
buffer(gl, 1, [0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1], 4);
buffer(gl, 0, [-0.9, -0.3, 0.9, 0.5, -0.9, 0.6, 0.2, -0.9], 2);
gl.lineWidth(1); gl.drawArrays(gl.LINES, 0, 4);
gl.lineWidth(3); buffer(gl, 0, [-0.6, -0.8, 0.8, 0.9], 2); gl.drawArrays(gl.LINES, 0, 2);
buffer(gl, 0, [-0.5, 0.5, 0.4, -0.2], 2); gl.drawArrays(gl.POINTS, 0, 2);
put(p + ".lines_points.readPixels", pixels(gl, 64, 64), 64);
});
await scene(p + ".depth_stencil", async () => {
const [c, gl] = mkctx(64, 64, { antialias: false, depth: true, stencil: true });
gl.viewport(0, 0, 64, 64); gl.clearColor(0, 0, 0, 1); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);
program(gl, "attribute vec3 p; attribute vec4 c; varying vec4 v; void main(){ v=c; gl_Position=vec4(p,1.); }", FS_COLOR);
gl.enable(gl.DEPTH_TEST); gl.enable(gl.STENCIL_TEST); gl.stencilFunc(gl.ALWAYS, 1, 255); gl.stencilOp(gl.KEEP, gl.KEEP, gl.REPLACE);
buffer(gl, 0, [-0.9, -0.9, 0.2, 0.9, -0.5, -0.4, 0.0, 0.9, 0.6], 3);
buffer(gl, 1, [1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1], 4);
gl.drawArrays(gl.TRIANGLES, 0, 3);
buffer(gl, 0, [-0.9, 0.9, 0.0, 0.9, 0.9, 0.0, 0.0, -0.9, 0.5], 3);
buffer(gl, 1, [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1], 4);
gl.drawArrays(gl.TRIANGLES, 0, 3);
put(p + ".depth_stencil.readPixels", pixels(gl, 64, 64), 64);
});
if (v2) {
await scene(p + ".msaa_resolve", async () => {
const [c, gl] = mkctx(64, 64, { antialias: false });
const rb = gl.createRenderbuffer(); gl.bindRenderbuffer(gl.RENDERBUFFER, rb);
gl.renderbufferStorageMultisample(gl.RENDERBUFFER, 4, gl.RGBA8, 64, 64);
const fb = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, rb);
const tx = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, tx);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 64, 64, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
const fb2 = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, fb2);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tx, 0);
gl.bindFramebuffer(gl.FRAMEBUFFER, fb); gl.viewport(0, 0, 64, 64); gl.clearColor(1, 1, 1, 1); gl.clear(gl.COLOR_BUFFER_BIT);
program(gl, VS, FS_COLOR);
buffer(gl, 0, [-0.83, -0.71, 0.77, -0.43, -0.1, 0.89], 2);
buffer(gl, 1, [0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1], 4);
gl.drawArrays(gl.TRIANGLES, 0, 3);
gl.bindFramebuffer(gl.READ_FRAMEBUFFER, fb); gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, fb2);
gl.blitFramebuffer(0, 0, 64, 64, 0, 0, 64, 64, gl.COLOR_BUFFER_BIT, gl.NEAREST);
gl.bindFramebuffer(gl.FRAMEBUFFER, fb2);
put(p + ".msaa_resolve.readPixels", pixels(gl, 64, 64), 64);
});
await scene(p + ".float_target", async () => {
const [c, gl] = mkctx(32, 32, { antialias: false });
if (!gl.getExtension("EXT_color_buffer_float")) { put(p + ".float_target", "no EXT_color_buffer_float"); return; }
const tx = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, tx);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA32F, 32, 32, 0, gl.RGBA, gl.FLOAT, null);
const fb = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tx, 0);
gl.viewport(0, 0, 32, 32);
program(gl, VS, "precision highp float; varying vec2 uv; void main(){ gl_FragColor=vec4(sin(uv.x*9.0)*exp(uv.y), pow(uv.x+0.1, 1.7), sqrt(uv.y), uv.x/(uv.y+0.37)); }");
buffer(gl, 0, QUAD, 2); gl.drawArrays(gl.TRIANGLES, 0, 6);
const f = new Float32Array(32 * 32 * 4); gl.readPixels(0, 0, 32, 32, gl.RGBA, gl.FLOAT, f);
put(p + ".float_target.readPixels", f, 32);
});
}
}
await scene("gl1", () => glScenes("gl1", false));
await scene("gl2", () => glScenes("gl2", true));
await scene("worker.webgl", async () => {
if (typeof Worker === "undefined" || typeof OffscreenCanvas === "undefined") { put("worker.webgl", "no worker or OffscreenCanvas"); return; }
const src = "onmessage = () => { try { const c = new OffscreenCanvas(32, 32), gl = c.getContext('webgl'); if (!gl) { postMessage({err: 'no webgl'}); return; }" +
"const d = gl.getExtension('WEBGL_debug_renderer_info');" +
"gl.clearColor(0.25, 0.5, 0.75, 1); gl.clear(gl.COLOR_BUFFER_BIT); const u = new Uint8Array(32*32*4); gl.readPixels(0,0,32,32,gl.RGBA,gl.UNSIGNED_BYTE,u);" +
"postMessage({vendor: gl.getParameter(gl.VENDOR), renderer: gl.getParameter(gl.RENDERER), unmasked: d ? [gl.getParameter(d.UNMASKED_VENDOR_WEBGL), gl.getParameter(d.UNMASKED_RENDERER_WEBGL)] : null," +
"exts: gl.getSupportedExtensions(), px: Array.from(u.subarray(0, 16))}); } catch (e) { postMessage({err: String(e)}); } };";
const w = new Worker(URL.createObjectURL(new Blob([src])));
const r = await Promise.race([new Promise((res) => { w.onmessage = (e) => res(e.data); w.onerror = (e) => res({ err: "worker error " + e.message }); w.postMessage(1); }),
sleep(10000).then(() => ({ err: "timeout" }))]);
w.terminate();
put("worker.webgl", r);
});
await scene("gpu.webgpu", async () => {
if (!navigator.gpu) { put("gpu.webgpu", "no navigator.gpu"); return; }
const a = await Promise.race([navigator.gpu.requestAdapter(), sleep(10000).then(() => "timeout")]);
if (!a || a === "timeout") { put("gpu.webgpu", String(a)); return; }
const info = a.info || (a.requestAdapterInfo ? await a.requestAdapterInfo() : {});
// Features and limits are read by NAME, never by iterating them: the expression runs with the page's objects behind Xray wrappers, and
// `Array.from(a.features)` / `for (k in a.limits)` threw "Xray wrapping of iterators not supported" there (run 43652292533). `has` and a property
// read are plain calls. The names are those of the WebGPU specification (limits table and GPUFeatureName); one the engine does not know reads
// false / undefined, which is a value like any other.
const featureNames = ["depth-clip-control", "depth32float-stencil8", "texture-compression-bc", "texture-compression-bc-sliced-3d",
"texture-compression-etc2", "texture-compression-astc", "texture-compression-astc-sliced-3d", "timestamp-query", "indirect-first-instance",
"shader-f16", "rg11b10ufloat-renderable", "bgra8unorm-storage", "float32-filterable", "float32-blendable", "clip-distances",
"dual-source-blending", "subgroups"];
const limitNames = ["maxTextureDimension1D", "maxTextureDimension2D", "maxTextureDimension3D", "maxTextureArrayLayers", "maxBindGroups",
"maxBindGroupsPlusVertexBuffers", "maxBindingsPerBindGroup", "maxDynamicUniformBuffersPerPipelineLayout",
"maxDynamicStorageBuffersPerPipelineLayout", "maxSampledTexturesPerShaderStage", "maxSamplersPerShaderStage",
"maxStorageBuffersPerShaderStage", "maxStorageTexturesPerShaderStage", "maxUniformBuffersPerShaderStage", "maxUniformBufferBindingSize",
"maxStorageBufferBindingSize", "minUniformBufferOffsetAlignment", "minStorageBufferOffsetAlignment", "maxVertexBuffers", "maxBufferSize",
"maxVertexAttributes", "maxVertexBufferArrayStride", "maxInterStageShaderVariables", "maxColorAttachments",
"maxColorAttachmentBytesPerSample", "maxComputeWorkgroupStorageSize", "maxComputeInvocationsPerWorkgroup", "maxComputeWorkgroupSizeX",
"maxComputeWorkgroupSizeY", "maxComputeWorkgroupSizeZ", "maxComputeWorkgroupsPerDimension"];
const lim = {}, feat = {};
for (const k of limitNames) { try { lim[k] = a.limits[k]; } catch (e) { lim[k] = "ERR " + e.message; } }
for (const f of featureNames) { try { feat[f] = a.features.has(f); } catch (e) { feat[f] = "ERR " + e.message; } }
put("gpu.webgpu.info", { vendor: info.vendor, architecture: info.architecture, device: info.device, description: info.description });
put("gpu.webgpu.features", feat);
put("gpu.webgpu.limits", lim);
});
// ------------------------------------------------------------------------------------------------------------ DOM text
await scene("dom.text", async () => {
const box = document.createElement("div"); box.style.cssText = "position:absolute;left:0;top:0;white-space:nowrap";
document.body.appendChild(box);
const rows = [];
for (const f of FONTS) for (const t of TEXTS) {
const s = document.createElement("span"); s.style.font = f; s.textContent = t; box.appendChild(s);
const r = s.getBoundingClientRect();
rows.push([f, t, r.width, r.height, s.offsetWidth, s.offsetHeight]);
box.removeChild(s);
}
put("dom.span_boxes", rows);
const para = [];
for (const f of ["16px sans-serif", "15px 'Times New Roman'", "14px Consolas"]) {
const d = document.createElement("div"); d.style.cssText = "width:200px;font:" + f; d.textContent = TEXTS.join(" · ") + " " + TEXTS.join(" · ");
box.appendChild(d); const r = d.getBoundingClientRect(); para.push([f, r.width, r.height]); box.removeChild(d);
}
put("dom.paragraphs", para);
put("dom.fonts_check", FONTS.map((f) => [f, document.fonts.check(f)]));
const colors = ["Canvas", "CanvasText", "ButtonFace", "ButtonText", "ButtonBorder", "Field", "FieldText", "Highlight", "HighlightText", "GrayText", "LinkText",
"VisitedText", "ActiveText", "Mark", "MarkText", "AccentColor", "AccentColorText", "SelectedItem", "SelectedItemText"];
put("dom.system_colors", colors.map((c) => { const e = document.createElement("i"); e.style.color = c; box.appendChild(e); const v = getComputedStyle(e).color; box.removeChild(e); return [c, v]; }));
document.body.removeChild(box);
});
return out;
})()
// HUNT ONLY (branch hunt/cpu-render-path, never merged). Evaluated in a page by scripts/hunt_page_bytes.py: one expression that resolves to a
// flat object {key: {s: "a short string"} | {h, n, s0} | {h, n, w, b64}} of everything a page can read about drawing and text:
// c2d.* canvas 2D: getImageData bytes, toDataURL (png, jpeg, webp), toBlob, OffscreenCanvas.convertToBlob, measureText
// gl1.* WebGL 1 and gl2.* WebGL 2: strings, extensions, limits, precision formats, readPixels bytes of several scenes, toDataURL, drawImage of the canvas
// worker.* an OffscreenCanvas WebGL context in a worker
// dom.* text layout: the boxes of spans in many fonts, wrapped paragraphs, system colours
// env.* the values the persona declares around it (so that a difference in them is seen, not guessed)
// ENCODING MODE (scripts/hunt_encoding.py sets globalThis.__ENCODING_MODE = true before this expression): only the scenes whose PNG output was not stable
// between two launches run (c2d shapes/composite/image/text, OffscreenCanvas, the WebGL triangle), and each one, instead of the usual keys, puts
// <scene>.getImageData / readPixels the pixels of the draw
// <scene>.png1..3, <scene>.blob1..3 the raw bytes of three toDataURL and three toBlob calls on the SAME canvas in the SAME page
// <scene>.png.decoded the pixels the browser itself decodes from png1
// so that "the pixels differ" and "only the encoding differs" can be told apart, and a call that is not repeatable inside one page is seen.
// Every scene is wrapped: an exception becomes `<scene>.error` and is compared like any other value, so both arms give the same keys.
(async () => {
const out = {};
const ENC = globalThis.__ENCODING_MODE === true;
const ENC_SCENES = new Set(["env", "c2d.shapes", "c2d.composite", "c2d.filter_draw_image", "c2d.text", "c2d.offscreen", "gl1", "gl2", "gl1.triangle", "gl2.triangle"]);
const enc = new TextEncoder();
function hashBytes(u8) { // cyrb53 over bytes: no crypto.subtle (it needs a secure context)
let h1 = 0xdeadbeef ^ u8.length, h2 = 0x41c6ce57 ^ u8.length;
for (let i = 0; i < u8.length; i++) { const ch = u8[i]; h1 = Math.imul(h1 ^ ch, 2654435761); h2 = Math.imul(h2 ^ ch, 1597334677); }
h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(16);
}
function b64(u8) {
let s = "";
for (let i = 0; i < u8.length; i += 0x8000) s += String.fromCharCode.apply(null, u8.subarray(i, i + 0x8000));
return btoa(s);
}
function put(k, v, w) {
if (ArrayBuffer.isView(v) || v instanceof ArrayBuffer) {
const u8 = v instanceof ArrayBuffer ? new Uint8Array(v) : new Uint8Array(v.buffer, v.byteOffset, v.byteLength);
out[k] = { h: hashBytes(u8), n: u8.length };
if (w) { out[k].w = w; out[k].bpp = 4 * (v.BYTES_PER_ELEMENT || 1); } // pixels per row, bytes per pixel (RGBA)
if (u8.length <= 400 * 1024) out[k].b64 = b64(u8);
} else {
const s = typeof v === "string" ? v : JSON.stringify(v);
out[k] = s.length <= 3000 ? { s } : { h: hashBytes(enc.encode(s)), n: s.length, s0: s.slice(0, 200) };
}
}
async function scene(k, fn) {
if (ENC && !ENC_SCENES.has(k)) return;
try { await fn(); } catch (e) { put(k + ".error", String((e && e.message) || e)); }
}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
// ------------------------------------------------------------------------------------------------------------ env
await scene("env", async () => {
put("env.ua", navigator.userAgent);
put("env.platform", navigator.platform);
put("env.oscpu", navigator.oscpu || "");
put("env.hw", navigator.hardwareConcurrency);
put("env.lang", navigator.languages);
put("env.dpr", window.devicePixelRatio);
put("env.screen", [screen.width, screen.height, screen.availWidth, screen.availHeight, screen.colorDepth, screen.pixelDepth]);
put("env.mq", ["(color-gamut: srgb)", "(color-gamut: p3)", "(dynamic-range: high)", "(prefers-color-scheme: dark)", "(prefers-reduced-motion: reduce)",
"(forced-colors: active)", "(inverted-colors: inverted)"].map((q) => matchMedia(q).matches));
});
// ---------------------------------------------------------------------------------------------------- canvas 2D
function c2d(w, h) { const c = document.createElement("canvas"); c.width = w; c.height = h; return [c, c.getContext("2d")]; }
function dataUrlBytes(url) {
const bin = atob(url.split(",")[1]);
const u = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) u[i] = bin.charCodeAt(i);
return u;
}
async function encProbe(k, c, px, w) {
put(k + ".getImageData", px, w);
const urls = [c.toDataURL(), c.toDataURL(), c.toDataURL()];
for (let i = 0; i < 3; i++) put(k + ".png" + (i + 1), dataUrlBytes(urls[i]));
for (let i = 0; i < 3; i++) {
const blob = await new Promise((r) => c.toBlob(r));
put(k + ".blob" + (i + 1), new Uint8Array(await blob.arrayBuffer()));
}
const im = new Image(); im.src = urls[0]; await im.decode();
const [c2, g2] = c2d(im.naturalWidth, im.naturalHeight); g2.drawImage(im, 0, 0);
put(k + ".png.decoded", g2.getImageData(0, 0, im.naturalWidth, im.naturalHeight).data, im.naturalWidth);
}
async function read2d(k, c, g) {
if (ENC) return encProbe(k, c, g.getImageData(0, 0, c.width, c.height).data, c.width);
put(k + ".getImageData", g.getImageData(0, 0, c.width, c.height).data, c.width);
put(k + ".png", c.toDataURL());
put(k + ".jpeg", c.toDataURL("image/jpeg", 0.8));
put(k + ".webp", c.toDataURL("image/webp", 0.8));
const blob = await new Promise((r) => c.toBlob(r));
put(k + ".toBlob", blob ? new Uint8Array(await blob.arrayBuffer()) : "null");
}
await scene("c2d.shapes", async () => {
const [c, g] = c2d(256, 160);
g.fillStyle = "#fff"; g.fillRect(0, 0, 256, 160);
const lg = g.createLinearGradient(0, 0, 256, 0);
lg.addColorStop(0, "#f00"); lg.addColorStop(0.5, "rgba(0,200,0,.5)"); lg.addColorStop(1, "#00f");
g.fillStyle = lg; g.fillRect(8, 8, 240, 40);
const rg = g.createRadialGradient(60, 100, 4, 60, 100, 50);
rg.addColorStop(0, "#ff0"); rg.addColorStop(1, "rgba(255,0,255,.2)");
g.fillStyle = rg; g.beginPath(); g.arc(60, 100, 50, 0, Math.PI * 2); g.fill();
g.strokeStyle = "#123"; g.lineWidth = 1.5; g.beginPath(); g.moveTo(130, 60); g.bezierCurveTo(160, 20, 200, 140, 240, 70); g.stroke();
g.lineWidth = 0.7; g.beginPath(); g.ellipse(190, 110, 40, 20, 0.5, 0, Math.PI * 2); g.stroke();
g.save(); g.shadowColor = "rgba(0,0,0,.6)"; g.shadowBlur = 6; g.shadowOffsetX = 3; g.shadowOffsetY = 3; g.fillStyle = "#38c"; g.fillRect(120, 100, 50, 30); g.restore();
g.save(); g.translate(30, 140); g.rotate(0.3); g.scale(1.3, 0.8); g.fillStyle = "#a40"; g.fillRect(0, 0, 40, 20); g.restore();
if (g.createConicGradient) {
const cg = g.createConicGradient(0.5, 215, 140);
cg.addColorStop(0, "#f80"); cg.addColorStop(0.5, "#08f"); cg.addColorStop(1, "#f80");
g.fillStyle = cg; g.fillRect(190, 120, 60, 36);
}
await read2d("c2d.shapes", c, g);
});
await scene("c2d.composite", async () => {
const ops = ["source-over", "source-in", "source-out", "source-atop", "destination-over", "destination-in", "destination-out", "destination-atop",
"lighter", "copy", "xor", "multiply", "screen", "overlay", "darken", "lighten", "color-dodge", "color-burn", "hard-light", "soft-light",
"difference", "exclusion", "hue", "saturation", "color", "luminosity"];
const [c, g] = c2d(8 * 32, 4 * 32);
ops.forEach((op, i) => {
const x = (i % 8) * 32, y = Math.floor(i / 8) * 32;
g.save(); g.beginPath(); g.rect(x, y, 32, 32); g.clip();
g.globalCompositeOperation = "source-over";
g.fillStyle = "rgba(200,60,40,.8)"; g.fillRect(x + 2, y + 2, 20, 20);
g.globalCompositeOperation = op;
g.fillStyle = "rgba(30,90,220,.6)"; g.fillRect(x + 10, y + 10, 20, 20);
g.restore();
});
await read2d("c2d.composite", c, g);
});
await scene("c2d.filter_draw_image", async () => {
const [c, g] = c2d(160, 120);
const [s, sg] = c2d(10, 10);
for (let i = 0; i < 100; i++) { sg.fillStyle = "hsl(" + ((i * 37) % 360) + ",70%,50%)"; sg.fillRect(i % 10, Math.floor(i / 10), 1, 1); }
g.imageSmoothingEnabled = true; g.imageSmoothingQuality = "high";
g.drawImage(s, 0, 0, 10, 10, 5.5, 5.5, 70.3, 70.3);
g.imageSmoothingEnabled = false; g.drawImage(s, 80, 5, 60, 60);
if ("filter" in g) { g.filter = "blur(2px) saturate(1.4)"; g.drawImage(s, 5, 70, 40, 40); g.filter = "none"; }
const p = g.createPattern(s, "repeat"); g.fillStyle = p; g.fillRect(60, 70, 90, 40);
const d = g.getImageData(0, 0, 40, 40); g.putImageData(d, 100, 80);
await read2d("c2d.image", c, g);
});
const FONTS = ["16px sans-serif", "20px serif", "18px monospace", "bold 16px Arial", "italic 15px 'Segoe UI'", "16px 'Times New Roman'", "16px Calibri",
"14px Consolas", "16px Verdana", "16px Tahoma", "17px Georgia", "16px 'Segoe UI Emoji'", "16px 'Microsoft YaHei'", "16px 'Yu Gothic'"];
const TEXTS = ["Hamburgefonstiv 0123456789", "The quick brown fox jumps over the lazy dog", "ÀÉÎÕÜ ß fi fl ffl", "日本語のテキスト 漢字", "😀🚀👍🏽", "مرحبا بالعالم"];
await scene("c2d.text", async () => {
const [c, g] = c2d(520, FONTS.length * 28 + 20);
g.fillStyle = "#fff"; g.fillRect(0, 0, c.width, c.height);
FONTS.forEach((f, i) => {
g.font = f; g.fillStyle = "#101820"; g.textBaseline = "alphabetic";
g.fillText(TEXTS[i % TEXTS.length], 6, 22 + i * 28);
g.strokeStyle = "rgba(200,0,0,.8)"; g.lineWidth = 0.6; g.strokeText("Ag", 470, 22 + i * 28);
});
await read2d("c2d.text", c, g);
const m = [];
for (const f of FONTS) {
g.font = f;
for (const t of TEXTS) {
const r = g.measureText(t);
m.push([f, t, r.width, r.actualBoundingBoxLeft, r.actualBoundingBoxRight, r.actualBoundingBoxAscent, r.actualBoundingBoxDescent,
r.fontBoundingBoxAscent, r.fontBoundingBoxDescent]);
}
}
put("c2d.measure", m);
});
await scene("c2d.offscreen", async () => {
if (typeof OffscreenCanvas === "undefined") { put("c2d.offscreen", "no OffscreenCanvas"); return; }
const oc = new OffscreenCanvas(160, 80), g = oc.getContext("2d");
g.fillStyle = "#fed"; g.fillRect(0, 0, 160, 80); g.fillStyle = "rgba(10,120,200,.7)"; g.beginPath(); g.arc(50, 40, 30, 0, 6.2); g.fill();
g.font = "bold 18px sans-serif"; g.fillStyle = "#222"; g.fillText("offscreen 2d", 70, 45);
put("c2d.offscreen.getImageData", g.getImageData(0, 0, 160, 80).data, 160);
if (ENC) {
for (let i = 1; i <= 3; i++) { const b = await oc.convertToBlob(); put("c2d.offscreen.png" + i, new Uint8Array(await b.arrayBuffer())); }
return;
}
const blob = await oc.convertToBlob();
put("c2d.offscreen.convertToBlob", new Uint8Array(await blob.arrayBuffer()));
});
// ------------------------------------------------------------------------------------------------------------ WebGL
const P1 = ["VERSION", "SHADING_LANGUAGE_VERSION", "VENDOR", "RENDERER", "MAX_TEXTURE_SIZE", "MAX_CUBE_MAP_TEXTURE_SIZE", "MAX_RENDERBUFFER_SIZE",
"MAX_VIEWPORT_DIMS", "ALIASED_LINE_WIDTH_RANGE", "ALIASED_POINT_SIZE_RANGE", "MAX_VERTEX_ATTRIBS", "MAX_VARYING_VECTORS",
"MAX_COMBINED_TEXTURE_IMAGE_UNITS", "MAX_VERTEX_TEXTURE_IMAGE_UNITS", "MAX_TEXTURE_IMAGE_UNITS", "MAX_VERTEX_UNIFORM_VECTORS",
"MAX_FRAGMENT_UNIFORM_VECTORS", "RED_BITS", "GREEN_BITS", "BLUE_BITS", "ALPHA_BITS", "DEPTH_BITS", "STENCIL_BITS", "SAMPLES",
"SAMPLE_BUFFERS", "SUBPIXEL_BITS"];
const P2 = ["MAX_3D_TEXTURE_SIZE", "MAX_ARRAY_TEXTURE_LAYERS", "MAX_COLOR_ATTACHMENTS", "MAX_DRAW_BUFFERS", "MAX_ELEMENTS_INDICES", "MAX_ELEMENTS_VERTICES",
"MAX_FRAGMENT_INPUT_COMPONENTS", "MAX_FRAGMENT_UNIFORM_BLOCKS", "MAX_FRAGMENT_UNIFORM_COMPONENTS", "MAX_PROGRAM_TEXEL_OFFSET", "MAX_SAMPLES",
"MAX_SERVER_WAIT_TIMEOUT", "MAX_TEXTURE_LOD_BIAS", "MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS", "MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS",
"MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS", "MAX_UNIFORM_BLOCK_SIZE", "MAX_UNIFORM_BUFFER_BINDINGS", "MAX_VARYING_COMPONENTS",
"MAX_VERTEX_OUTPUT_COMPONENTS", "MAX_VERTEX_UNIFORM_BLOCKS", "MAX_VERTEX_UNIFORM_COMPONENTS", "MIN_PROGRAM_TEXEL_OFFSET",
"MAX_COMBINED_UNIFORM_BLOCKS", "MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS", "MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS", "UNIFORM_BUFFER_OFFSET_ALIGNMENT"];
function glInfo(p, gl, v2) {
const params = {};
for (const n of P1.concat(v2 ? P2 : [])) {
try { let v = gl.getParameter(gl[n]); if (ArrayBuffer.isView(v)) v = Array.from(v); params[n] = v; } catch (e) { params[n] = "ERR " + e.message; }
}
put(p + ".params", params);
const exts = gl.getSupportedExtensions() || [];
put(p + ".extensions", exts);
const eo = [];
for (const e of exts) {
try { const o = gl.getExtension(e); eo.push([e, o ? Object.keys(Object.getPrototypeOf(o)).length : -1]); } catch (er) { eo.push([e, "ERR"]); }
}
put(p + ".extension_objects", eo);
const dbg = gl.getExtension("WEBGL_debug_renderer_info");
put(p + ".unmasked", dbg ? [gl.getParameter(dbg.UNMASKED_VENDOR_WEBGL), gl.getParameter(dbg.UNMASKED_RENDERER_WEBGL)] : "no WEBGL_debug_renderer_info");
const an = gl.getExtension("EXT_texture_filter_anisotropic");
put(p + ".anisotropy", an ? gl.getParameter(an.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : "none");
const prec = [];
for (const sh of ["VERTEX_SHADER", "FRAGMENT_SHADER"]) for (const lv of ["LOW_FLOAT", "MEDIUM_FLOAT", "HIGH_FLOAT", "LOW_INT", "MEDIUM_INT", "HIGH_INT"]) {
const f = gl.getShaderPrecisionFormat(gl[sh], gl[lv]);
prec.push([sh, lv, f && f.rangeMin, f && f.rangeMax, f && f.precision]);
}
put(p + ".precision", prec);
put(p + ".attributes", gl.getContextAttributes());
}
function program(gl, vs, fs) {
const mk = (type, src) => {
const s = gl.createShader(type); gl.shaderSource(s, src); gl.compileShader(s);
if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) throw new Error("shader: " + gl.getShaderInfoLog(s));
return s;
};
const pr = gl.createProgram();
gl.attachShader(pr, mk(gl.VERTEX_SHADER, vs)); gl.attachShader(pr, mk(gl.FRAGMENT_SHADER, fs));
gl.bindAttribLocation(pr, 0, "p"); gl.bindAttribLocation(pr, 1, "c");
gl.linkProgram(pr);
if (!gl.getProgramParameter(pr, gl.LINK_STATUS)) throw new Error("link: " + gl.getProgramInfoLog(pr));
gl.useProgram(pr);
return pr;
}
function buffer(gl, loc, data, size) {
const b = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, b); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(data), gl.STATIC_DRAW);
gl.enableVertexAttribArray(loc); gl.vertexAttribPointer(loc, size, gl.FLOAT, false, 0, 0);
return b;
}
function pixels(gl, w, h) { const u = new Uint8Array(w * h * 4); gl.readPixels(0, 0, w, h, gl.RGBA, gl.UNSIGNED_BYTE, u); return u; }
const VS = "attribute vec2 p; attribute vec4 c; varying vec4 v; varying vec2 uv; void main(){ v=c; uv=p*0.5+0.5; gl_Position=vec4(p,0.,1.); gl_PointSize=7.5; }";
const FS_COLOR = "precision mediump float; varying vec4 v; void main(){ gl_FragColor=v; }";
const QUAD = [-1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, 1];
async function glScenes(p, v2) {
const kind = v2 ? "webgl2" : "webgl";
const mkctx = (w, h, attrs) => {
const c = document.createElement("canvas"); c.width = w; c.height = h;
return [c, c.getContext(kind, Object.assign({ preserveDrawingBuffer: true }, attrs || {}))];
};
let [c0, gl0] = mkctx(64, 64);
if (!gl0) { put(p + ".context", "null"); return; }
glInfo(p, gl0, v2);
await scene(p + ".triangle", async () => {
const [c, gl] = mkctx(96, 96, { antialias: false });
gl.viewport(0, 0, 96, 96); gl.clearColor(0.1, 0.2, 0.3, 0.4); gl.clear(gl.COLOR_BUFFER_BIT);
program(gl, VS, FS_COLOR);
buffer(gl, 0, [-0.8, -0.7, 0.9, -0.5, -0.1, 0.85], 2);
buffer(gl, 1, [1, 0, 0, 1, 0, 1, 0, 0.7, 0, 0, 1, 0.3], 4);
gl.drawArrays(gl.TRIANGLES, 0, 3);
if (ENC) { await encProbe(p + ".triangle", c, pixels(gl, 96, 96), 96); return; }
put(p + ".triangle.readPixels", pixels(gl, 96, 96), 96);
put(p + ".triangle.toDataURL", c.toDataURL());
put(p + ".triangle.toDataURL_jpeg", c.toDataURL("image/jpeg", 0.8));
const [d, g2] = c2d(96, 96); g2.drawImage(c, 0, 0);
put(p + ".triangle.drawImage", g2.getImageData(0, 0, 96, 96).data, 96);
});
await scene(p + ".antialias", async () => {
for (const aa of [true, false]) {
const [c, gl] = mkctx(96, 96, { antialias: aa });
gl.viewport(0, 0, 96, 96); gl.clearColor(1, 1, 1, 1); gl.clear(gl.COLOR_BUFFER_BIT);
program(gl, VS, FS_COLOR);
buffer(gl, 0, [-0.83, -0.71, 0.77, -0.43, -0.1, 0.89, 0.3, 0.9, 0.9, 0.2, 0.6, 0.95], 2);
buffer(gl, 1, [0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0.8, 0, 0, 1, 0.8, 0, 0, 1, 0.8, 0, 0, 1], 4);
gl.drawArrays(gl.TRIANGLES, 0, 6);
put(p + ".antialias." + aa + ".samples", gl.getParameter(gl.SAMPLES));
put(p + ".antialias." + aa + ".readPixels", pixels(gl, 96, 96), 96);
}
});
for (const prec of ["highp", "mediump"]) await scene(p + ".math." + prec, async () => {
const [c, gl] = mkctx(64, 64, { antialias: false });
const fp = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT);
const use = prec === "highp" && !(fp && fp.precision) ? "mediump" : prec;
gl.viewport(0, 0, 64, 64);
program(gl, VS, "precision " + use + " float; varying vec2 uv;" +
"void main(){ float x=uv.x*6.0; gl_FragColor=vec4(fract(sin(x)*43758.5453), fract(exp(uv.y*3.0)), fract(pow(uv.x+0.5, 2.2+uv.y)), fract(sqrt(uv.x*uv.y)*17.0)); }");
buffer(gl, 0, QUAD, 2); gl.drawArrays(gl.TRIANGLES, 0, 6);
put(p + ".math." + prec + ".readPixels", pixels(gl, 64, 64), 64);
});
await scene(p + ".texture", async () => {
const [c, gl] = mkctx(64, 64, { antialias: false });
gl.viewport(0, 0, 64, 64);
program(gl, VS, "precision mediump float; varying vec2 uv; uniform sampler2D t; void main(){ gl_FragColor=texture2D(t, uv*0.9+0.03); }");
const tex = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, tex);
const d = new Uint8Array(32 * 32 * 4); let s = 12345;
for (let i = 0; i < d.length; i++) { s = (s * 1103515245 + 12345) & 0x7fffffff; d[i] = (s >> 16) & 255; }
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 32, 32, 0, gl.RGBA, gl.UNSIGNED_BYTE, d);
gl.generateMipmap(gl.TEXTURE_2D);
for (const [name, mag, min] of [["linear", gl.LINEAR, gl.LINEAR], ["mip", gl.LINEAR, gl.LINEAR_MIPMAP_LINEAR], ["nearest", gl.NEAREST, gl.NEAREST]]) {
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, mag); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, min);
gl.clear(gl.COLOR_BUFFER_BIT);
buffer(gl, 0, QUAD, 2); gl.drawArrays(gl.TRIANGLES, 0, 6);
put(p + ".texture." + name + ".readPixels", pixels(gl, 64, 64), 64);
}
});
await scene(p + ".blend", async () => {
const [c, gl] = mkctx(64, 64, { antialias: false, premultipliedAlpha: false });
gl.viewport(0, 0, 64, 64); gl.clearColor(0.2, 0.4, 0.6, 0.5); gl.clear(gl.COLOR_BUFFER_BIT);
program(gl, VS, FS_COLOR); gl.enable(gl.BLEND);
for (const [src, dst] of [[gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA], [gl.ONE, gl.ONE_MINUS_SRC_ALPHA], [gl.DST_COLOR, gl.ZERO]]) {
gl.blendFunc(src, dst);
buffer(gl, 0, [-0.9, -0.9, 0.3, -0.5, -0.3, 0.7], 2);
buffer(gl, 1, [0.9, 0.2, 0.1, 0.37, 0.1, 0.8, 0.3, 0.55, 0.2, 0.3, 0.9, 0.21], 4);
gl.drawArrays(gl.TRIANGLES, 0, 3);
}
put(p + ".blend.readPixels", pixels(gl, 64, 64), 64);
});
await scene(p + ".lines_points", async () => {
const [c, gl] = mkctx(64, 64, { antialias: false });
gl.viewport(0, 0, 64, 64); gl.clearColor(1, 1, 1, 1); gl.clear(gl.COLOR_BUFFER_BIT);
program(gl, VS, FS_COLOR);
buffer(gl, 1, [0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1], 4);
buffer(gl, 0, [-0.9, -0.3, 0.9, 0.5, -0.9, 0.6, 0.2, -0.9], 2);
gl.lineWidth(1); gl.drawArrays(gl.LINES, 0, 4);
gl.lineWidth(3); buffer(gl, 0, [-0.6, -0.8, 0.8, 0.9], 2); gl.drawArrays(gl.LINES, 0, 2);
buffer(gl, 0, [-0.5, 0.5, 0.4, -0.2], 2); gl.drawArrays(gl.POINTS, 0, 2);
put(p + ".lines_points.readPixels", pixels(gl, 64, 64), 64);
});
await scene(p + ".depth_stencil", async () => {
const [c, gl] = mkctx(64, 64, { antialias: false, depth: true, stencil: true });
gl.viewport(0, 0, 64, 64); gl.clearColor(0, 0, 0, 1); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);
program(gl, "attribute vec3 p; attribute vec4 c; varying vec4 v; void main(){ v=c; gl_Position=vec4(p,1.); }", FS_COLOR);
gl.enable(gl.DEPTH_TEST); gl.enable(gl.STENCIL_TEST); gl.stencilFunc(gl.ALWAYS, 1, 255); gl.stencilOp(gl.KEEP, gl.KEEP, gl.REPLACE);
buffer(gl, 0, [-0.9, -0.9, 0.2, 0.9, -0.5, -0.4, 0.0, 0.9, 0.6], 3);
buffer(gl, 1, [1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1], 4);
gl.drawArrays(gl.TRIANGLES, 0, 3);
buffer(gl, 0, [-0.9, 0.9, 0.0, 0.9, 0.9, 0.0, 0.0, -0.9, 0.5], 3);
buffer(gl, 1, [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1], 4);
gl.drawArrays(gl.TRIANGLES, 0, 3);
put(p + ".depth_stencil.readPixels", pixels(gl, 64, 64), 64);
});
if (v2) {
await scene(p + ".msaa_resolve", async () => {
const [c, gl] = mkctx(64, 64, { antialias: false });
const rb = gl.createRenderbuffer(); gl.bindRenderbuffer(gl.RENDERBUFFER, rb);
gl.renderbufferStorageMultisample(gl.RENDERBUFFER, 4, gl.RGBA8, 64, 64);
const fb = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, rb);
const tx = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, tx);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 64, 64, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
const fb2 = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, fb2);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tx, 0);
gl.bindFramebuffer(gl.FRAMEBUFFER, fb); gl.viewport(0, 0, 64, 64); gl.clearColor(1, 1, 1, 1); gl.clear(gl.COLOR_BUFFER_BIT);
program(gl, VS, FS_COLOR);
buffer(gl, 0, [-0.83, -0.71, 0.77, -0.43, -0.1, 0.89], 2);
buffer(gl, 1, [0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1], 4);
gl.drawArrays(gl.TRIANGLES, 0, 3);
gl.bindFramebuffer(gl.READ_FRAMEBUFFER, fb); gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, fb2);
gl.blitFramebuffer(0, 0, 64, 64, 0, 0, 64, 64, gl.COLOR_BUFFER_BIT, gl.NEAREST);
gl.bindFramebuffer(gl.FRAMEBUFFER, fb2);
put(p + ".msaa_resolve.readPixels", pixels(gl, 64, 64), 64);
});
await scene(p + ".float_target", async () => {
const [c, gl] = mkctx(32, 32, { antialias: false });
if (!gl.getExtension("EXT_color_buffer_float")) { put(p + ".float_target", "no EXT_color_buffer_float"); return; }
const tx = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, tx);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA32F, 32, 32, 0, gl.RGBA, gl.FLOAT, null);
const fb = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tx, 0);
gl.viewport(0, 0, 32, 32);
program(gl, VS, "precision highp float; varying vec2 uv; void main(){ gl_FragColor=vec4(sin(uv.x*9.0)*exp(uv.y), pow(uv.x+0.1, 1.7), sqrt(uv.y), uv.x/(uv.y+0.37)); }");
buffer(gl, 0, QUAD, 2); gl.drawArrays(gl.TRIANGLES, 0, 6);
const f = new Float32Array(32 * 32 * 4); gl.readPixels(0, 0, 32, 32, gl.RGBA, gl.FLOAT, f);
put(p + ".float_target.readPixels", f, 32);
});
}
}
await scene("gl1", () => glScenes("gl1", false));
await scene("gl2", () => glScenes("gl2", true));
await scene("worker.webgl", async () => {
if (typeof Worker === "undefined" || typeof OffscreenCanvas === "undefined") { put("worker.webgl", "no worker or OffscreenCanvas"); return; }
const src = "onmessage = () => { try { const c = new OffscreenCanvas(32, 32), gl = c.getContext('webgl'); if (!gl) { postMessage({err: 'no webgl'}); return; }" +
"const d = gl.getExtension('WEBGL_debug_renderer_info');" +
"gl.clearColor(0.25, 0.5, 0.75, 1); gl.clear(gl.COLOR_BUFFER_BIT); const u = new Uint8Array(32*32*4); gl.readPixels(0,0,32,32,gl.RGBA,gl.UNSIGNED_BYTE,u);" +
"postMessage({vendor: gl.getParameter(gl.VENDOR), renderer: gl.getParameter(gl.RENDERER), unmasked: d ? [gl.getParameter(d.UNMASKED_VENDOR_WEBGL), gl.getParameter(d.UNMASKED_RENDERER_WEBGL)] : null," +
"exts: gl.getSupportedExtensions(), px: Array.from(u.subarray(0, 16))}); } catch (e) { postMessage({err: String(e)}); } };";
const w = new Worker(URL.createObjectURL(new Blob([src])));
const r = await Promise.race([new Promise((res) => { w.onmessage = (e) => res(e.data); w.onerror = (e) => res({ err: "worker error " + e.message }); w.postMessage(1); }),
sleep(10000).then(() => ({ err: "timeout" }))]);
w.terminate();
put("worker.webgl", r);
});
await scene("gpu.webgpu", async () => {
if (!navigator.gpu) { put("gpu.webgpu", "no navigator.gpu"); return; }
const a = await Promise.race([navigator.gpu.requestAdapter(), sleep(10000).then(() => "timeout")]);
if (!a || a === "timeout") { put("gpu.webgpu", String(a)); return; }
const info = a.info || (a.requestAdapterInfo ? await a.requestAdapterInfo() : {});
const lim = {}; for (const k in a.limits) lim[k] = a.limits[k];
put("gpu.webgpu.info", { vendor: info.vendor, architecture: info.architecture, device: info.device, description: info.description });
put("gpu.webgpu.features", Array.from(a.features).sort());
put("gpu.webgpu.limits", lim);
});
// ------------------------------------------------------------------------------------------------------------ DOM text
await scene("dom.text", async () => {
const box = document.createElement("div"); box.style.cssText = "position:absolute;left:0;top:0;white-space:nowrap";
document.body.appendChild(box);
const rows = [];
for (const f of FONTS) for (const t of TEXTS) {
const s = document.createElement("span"); s.style.font = f; s.textContent = t; box.appendChild(s);
const r = s.getBoundingClientRect();
rows.push([f, t, r.width, r.height, s.offsetWidth, s.offsetHeight]);
box.removeChild(s);
}
put("dom.span_boxes", rows);
const para = [];
for (const f of ["16px sans-serif", "15px 'Times New Roman'", "14px Consolas"]) {
const d = document.createElement("div"); d.style.cssText = "width:200px;font:" + f; d.textContent = TEXTS.join(" · ") + " " + TEXTS.join(" · ");
box.appendChild(d); const r = d.getBoundingClientRect(); para.push([f, r.width, r.height]); box.removeChild(d);
}
put("dom.paragraphs", para);
put("dom.fonts_check", FONTS.map((f) => [f, document.fonts.check(f)]));
const colors = ["Canvas", "CanvasText", "ButtonFace", "ButtonText", "ButtonBorder", "Field", "FieldText", "Highlight", "HighlightText", "GrayText", "LinkText",
"VisitedText", "ActiveText", "Mark", "MarkText", "AccentColor", "AccentColorText", "SelectedItem", "SelectedItemText"];
put("dom.system_colors", colors.map((c) => { const e = document.createElement("i"); e.style.color = c; box.appendChild(e); const v = getComputedStyle(e).color; box.removeChild(e); return [c, v]; }));
document.body.removeChild(box);
});
return out;
})()
+417
View File
@@ -0,0 +1,417 @@
"""HUNT ONLY (branch hunt/cpu-render-path, never merged): read the Gecko profiles of scripts/hunt_cpu_render_path.py and print what a person
would otherwise click through in the Firefox Profiler.
python scripts/hunt_profile_summary.py DIR [--symbols ZIP ...] [--detail 2] [--ids] [--only gpu] [--threads 4] [--top 12] [--thread-table]
DIR holds profile-<pid>.json(.gz), one per process (written at each process's clean shutdown, MOZ_PROFILER_SHUTDOWN=...%p.json). A file may
also carry the profiles of child processes under "processes"; those are read too.
For every process: pid, type (the thread's processType: default = the parent, gpu, tab, socket, ...), threads, samples and the CPU the
profiler measured (the `cpu` feature: threadCPUDelta of every sample, microseconds; without it every sample counts 1).
For the DETAIL busiest files of each of the types default and gpu, and for the four busiest threads of each: the CPU by module of the leaf
frame (self time: xul.dll, d3d10warp.dll, a vendor driver, ntdll, ...) and the twelve hottest leaf functions.
Symbols. A native frame is a module and an RVA. Module names are always known (the profile's libs). Function names come from
1. Breakpad .sym files inside the zips given with --symbols (our engine: the candidate's artifact symbols-win-x86_64), matched on the
module's debug name and breakpad id, streamed (only the RVAs asked for are kept);
2. Mozilla's symbol server (https://symbolication.services.mozilla.com/symbolicate/v5), for every module the zips do not have.
A module neither source knows stays `module+0xRVA`, and the report says which modules were and were not symbolicated. Nothing here fails
the job: every problem is printed as a line.
--only gpu limits the detail to the process types listed (comma separated; default: default and gpu), --threads is how many threads of a process get
their own table, --top how many leaf functions each table lists. For every detailed process a PROCESS-WIDE table comes first: self weight by module
and the hottest leaf functions over all its threads together (this is the "d3d10warp.dll against d3d11.dll against xul.dll" number).
--thread-table adds, for every detailed process, ONE LINE PER THREAD (all of them): name, tid, weight, share, and the self weight by module of that
thread; then a total for the threads that have no name. If DIR holds cpu_profiled.json (written by `hunt_cpu_render_path.py profile`), each detailed
process is also compared with the CPU the sampler measured for that pid: how much of the process the profile's threads account for (the rest is in
threads the profiler does not register).
--ids prints `debugName breakpadId name` of the libs of the first parent profile and exits (used to pick the symbols artifact).
Formats read: tables as columns (`{"length": n, "func": [...]}`) or as `{"schema": {...}, "data": [[...]]}`; frames through funcTable and
resourceTable, or through a `location` string (absolute address `0x...`, mapped to a lib by the libs' start/end).
"""
from __future__ import annotations
import argparse
import bisect
import collections
import gzip
import io
import json
import re
import sys
import urllib.request
import zipfile
from pathlib import Path
from typing import Any, Dict, Iterator, List, Optional, Tuple
SERVER = "https://symbolication.services.mozilla.com/symbolicate/v5"
HEX = re.compile(r"^0x[0-9a-fA-F]+$")
PROCESS_TYPES = {0: "default", 1: "plugin", 2: "tab", 3: "ipdlunittest", 4: "gmplugin", 5: "gpu", 6: "vr", 7: "rdd", 8: "socket",
9: "remotesandboxbroker", 10: "forkserver", 11: "utility"}
def load_json(path: Path) -> dict:
opener = gzip.open if path.suffix == ".gz" else open
with opener(path, "rb") as f:
return json.loads(f.read().decode("utf-8", "replace"))
def walk(profile: dict) -> Iterator[dict]:
yield profile
for sub in profile.get("processes") or []:
yield from walk(sub)
def cols(t: Any) -> dict:
"""A table as {field: list}, whichever of the two shapes it has."""
if not t:
return {}
if isinstance(t, dict) and "schema" in t and "data" in t:
return {k: [row[i] if i < len(row) else None for row in t["data"]] for k, i in t["schema"].items()}
return t
def strings(profile: dict, thread: dict) -> List[str]:
return thread.get("stringArray") or thread.get("stringTable") or (profile.get("shared") or {}).get("stringArray") or []
def lib_of_address(libs: List[dict], addr: int) -> Tuple[Optional[int], int]:
for i, lib in enumerate(libs):
start, end = lib.get("start"), lib.get("end")
if isinstance(start, int) and isinstance(end, int) and start <= addr < end:
return i, addr - start + (lib.get("offset") or 0)
return None, addr
class Frames:
"""For one thread: frame index -> (key, label, lib index or None, rva or None, is_js)."""
def __init__(self, profile: dict, thread: dict) -> None:
libs = profile.get("libs") or thread.get("libs") or []
strs = strings(profile, thread)
def s(i):
return strs[i] if isinstance(i, int) and 0 <= i < len(strs) else (i if isinstance(i, str) else "?")
ft = cols(thread.get("frameTable"))
self.items: List[tuple] = []
n = ft.get("length") or max((len(v) for v in ft.values() if isinstance(v, list)), default=0)
if thread.get("funcTable"):
fu, res = cols(thread["funcTable"]), cols(thread.get("resourceTable"))
for i in range(n):
f = ft["func"][i]
name = s(fu["name"][f])
isjs = fu.get("isJS") or []
is_js = bool(isjs[f]) if f < len(isjs) else False
r = fu["resource"][f] if fu.get("resource") else None
lib = res["lib"][r] if isinstance(r, int) and r >= 0 and res.get("lib") and r < len(res["lib"]) else None
addr = ft["address"][i] if ft.get("address") else None
rva = addr if isinstance(addr, int) and addr >= 0 else (int(name, 16) if HEX.match(name) else None)
if lib is None and HEX.match(name) and rva is not None:
lib, rva = lib_of_address(libs, rva)
self._add(libs, name, lib, rva, is_js)
else:
for i in range(n):
loc = s(ft["location"][i]) if ft.get("location") else "?"
if HEX.match(loc):
lib, rva = lib_of_address(libs, int(loc, 16))
self._add(libs, loc, lib, rva if lib is not None else None, False)
else:
self._add(libs, loc, None, None, True)
def _add(self, libs, name, lib, rva, is_js) -> None:
if lib is not None and rva is not None and 0 <= lib < len(libs):
mod = libs[lib].get("name") or "?"
self.items.append((("n", lib, rva), "%s+0x%x" % (mod, rva), lib, rva, False))
elif is_js:
self.items.append((("j", name), "[JS] " + name, None, None, True))
else:
self.items.append((("o", name), name, None, None, False))
def thread_weights(profile: dict, thread: dict) -> Tuple[Dict[int, float], int, float]:
"""({leaf frame: weight}, samples, total weight). Weight = threadCPUDelta (us) when the profile has it, else 1 per sample."""
sm = cols(thread.get("samples"))
stacks = sm.get("stack") or []
deltas = sm.get("threadCPUDelta")
st = cols(thread.get("stackTable"))
frame_of = st.get("frame") or []
use_cpu = bool(deltas) and any(isinstance(d, (int, float)) and d for d in deltas)
out: Dict[int, float] = collections.defaultdict(float)
total = 0.0
for i, stack in enumerate(stacks):
if stack is None or not isinstance(stack, int) or stack >= len(frame_of):
continue
w = float(deltas[i] or 0) if use_cpu else 1.0
out[frame_of[stack]] += w
total += w
return out, len(stacks), total
# ----------------------------------------------------------------------------------------------------------- symbolication
def local_symbols(zips: List[Path], wanted: Dict[Tuple[str, str], List[int]], found: Dict[Tuple[str, str, int], str], notes: List[str]) -> None:
for z in zips:
try:
zf = zipfile.ZipFile(z)
except Exception as exc: # noqa: BLE001
notes.append("symbols zip %s unreadable: %s" % (z, exc))
continue
names = zf.namelist()
for (debug, bid), rvas in wanted.items():
members = [n for n in names if n.endswith(".sym") and ("/%s/%s/" % (debug, bid)) in "/" + n]
if not members:
continue
rvas = sorted(set(rvas))
hits = 0
with zf.open(members[0]) as raw:
for line in io.TextIOWrapper(raw, encoding="utf-8", errors="replace"):
if not line.startswith("FUNC "):
continue
rest = line[5:]
if rest.startswith("m "):
rest = rest[2:]
try:
addr_s, size_s, _param, name = rest.split(" ", 3)
addr, size = int(addr_s, 16), int(size_s, 16)
except ValueError:
continue
j = bisect.bisect_left(rvas, addr)
while j < len(rvas) and rvas[j] < addr + max(size, 1):
if (debug, bid, rvas[j]) not in found:
found[(debug, bid, rvas[j])] = name.strip()
hits += 1
j += 1
notes.append("local symbols: %s %s: %d of %d addresses named (from %s)" % (debug, bid, hits, len(rvas), z.name))
def server_symbols(wanted: Dict[Tuple[str, str], List[int]], found: Dict[Tuple[str, str, int], str], notes: List[str]) -> None:
for (debug, bid), rvas in wanted.items():
todo = sorted({r for r in rvas if (debug, bid, r) not in found})
if not todo:
continue
hits = 0
try:
for k in range(0, len(todo), 400):
chunk = todo[k:k + 400]
body = json.dumps({"jobs": [{"memoryMap": [[debug, bid]], "stacks": [[[0, r] for r in chunk]]}]}).encode()
req = urllib.request.Request(SERVER, body, {"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=60) as resp:
data = json.loads(resp.read())
frames = data["results"][0]["stacks"][0]
for r, fr in zip(chunk, frames):
fn = fr.get("function")
if fn and not HEX.match(str(fn)):
found[(debug, bid, r)] = str(fn)
hits += 1
notes.append("Mozilla symbol server: %s %s: %d of %d addresses named" % (debug, bid, hits, len(todo)))
except Exception as exc: # noqa: BLE001
notes.append("Mozilla symbol server: %s %s: %s: %s" % (debug, bid, type(exc).__name__, str(exc)[:200]))
# ------------------------------------------------------------------------------------------------------------------ report
def process_type(profile: dict) -> str:
for t in profile.get("threads") or []:
if t.get("processType"):
return str(t["processType"])
pt = (profile.get("meta") or {}).get("processType")
return PROCESS_TYPES.get(pt, str(pt))
def pid_of(profile: dict) -> Any:
for t in profile.get("threads") or []:
if t.get("pid") is not None:
return t["pid"]
return (profile.get("meta") or {}).get("pid", "?")
def analyse(profile: dict) -> dict:
libs = profile.get("libs") or []
threads = []
for t in profile.get("threads") or []:
try:
frames = Frames(profile, t)
weights, nsamples, total = thread_weights(profile, t)
self_by_key: Dict[tuple, float] = collections.defaultdict(float)
info: Dict[tuple, tuple] = {}
for fi, w in weights.items():
if 0 <= fi < len(frames.items):
key, label, lib, rva, js = frames.items[fi]
self_by_key[key] += w
info[key] = (label, lib, rva, js)
threads.append({"name": t.get("name") or "?", "tid": t.get("tid"), "samples": nsamples, "total": total,
"self": self_by_key, "info": info})
except Exception as exc: # noqa: BLE001
threads.append({"name": t.get("name") or "?", "tid": t.get("tid"), "samples": 0, "total": 0.0, "self": {}, "info": {},
"error": "%s: %s" % (type(exc).__name__, str(exc)[:160])})
return {"profile": profile, "libs": libs, "threads": threads, "type": process_type(profile), "pid": pid_of(profile),
"total": sum(t["total"] for t in threads), "samples": sum(t["samples"] for t in threads),
"cpu": any(((cols(t.get("samples")).get("threadCPUDelta")) for t in profile.get("threads") or []))}
def thread_modules(a: dict, t: dict) -> Dict[str, float]:
"""Self weight by module of one thread."""
out: Dict[str, float] = collections.defaultdict(float)
for key, w in t["self"].items():
label, lib, rva, js = t["info"][key]
out["[JS]" if js else (a["libs"][lib].get("name") if lib is not None else "(no module: %s)" % label[:40])] += w
return out
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("dir", type=Path)
ap.add_argument("--symbols", nargs="*", default=[], type=Path)
ap.add_argument("--detail", type=int, default=2)
ap.add_argument("--ids", action="store_true")
ap.add_argument("--only", default="default,gpu", help="process types that get the detail tables")
ap.add_argument("--threads", type=int, default=4)
ap.add_argument("--top", type=int, default=12)
ap.add_argument("--thread-table", action="store_true")
args = ap.parse_args()
files = sorted(list(args.dir.glob("profile-*.json")) + list(args.dir.glob("profile-*.json.gz")))
if not files:
print("no profile files in %s" % args.dir)
return 0
procs = []
for f in files:
try:
for p in walk(load_json(f)):
if p.get("threads"):
a = analyse(p)
a["file"] = f.name
procs.append(a)
except Exception as exc: # noqa: BLE001
print("%s: unreadable: %s: %s" % (f.name, type(exc).__name__, str(exc)[:200]))
if args.ids:
for a in procs:
if a["type"] == "default":
for lib in a["libs"]:
if (lib.get("name") or "").lower() in ("xul.dll", "firefox.exe", "d3d10warp.dll"):
print(lib.get("debugName"), lib.get("breakpadId"), lib.get("name"))
break
return 0
sampler_cpu_by_pid: Dict[str, float] = {}
cp = args.dir / "cpu_profiled.json"
if cp.is_file():
try:
for r in json.loads(cp.read_text(encoding="utf-8")).get("processes", []):
sampler_cpu_by_pid[str(r["pid"])] = float(r["cpu_s"])
except Exception as exc: # noqa: BLE001
print("cpu_profiled.json unreadable: %s" % exc)
unit = "us of CPU" if any(a["cpu"] for a in procs) else "samples"
print("%d process profile(s) from %d file(s); weights are %s" % (len(procs), len(files), unit))
print("%-8s %-26s %7s %9s %14s file" % ("pid", "type", "threads", "samples", "weight"))
for a in sorted(procs, key=lambda a: (a["type"], -a["total"])):
print("%-8s %-26s %7d %9d %14.0f %s" % (a["pid"], a["type"], len(a["threads"]), a["samples"], a["total"], a["file"]))
by_type: Dict[str, float] = collections.defaultdict(float)
for a in procs:
by_type[a["type"]] += a["total"]
print("total weight by process type: " + ", ".join("%s %.0f" % kv for kv in sorted(by_type.items(), key=lambda kv: -kv[1])))
chosen = []
for kind in [k for k in args.only.split(",") if k]:
chosen += sorted([a for a in procs if a["type"] == kind], key=lambda a: -a["total"])[:args.detail]
# which addresses to name
wanted: Dict[Tuple[str, str], List[int]] = collections.defaultdict(list)
for a in chosen:
wide: Dict[tuple, float] = collections.defaultdict(float)
winfo: Dict[tuple, tuple] = {}
for t in a["threads"]:
for key, w in t["self"].items():
wide[key] += w
winfo[key] = t["info"][key]
a["wide"], a["winfo"] = wide, winfo
for tbl, inf in [(wide, winfo)] + [(t["self"], t["info"]) for t in sorted(a["threads"], key=lambda t: -t["total"])[:args.threads]]:
for key, w in sorted(tbl.items(), key=lambda kv: -kv[1])[:args.top]:
label, lib, rva, js = inf[key]
if lib is not None and rva is not None:
L = a["libs"][lib]
if L.get("debugName") and L.get("breakpadId"):
wanted[(L["debugName"], L["breakpadId"])].append(rva)
found: Dict[Tuple[str, str, int], str] = {}
notes: List[str] = []
zips = [p for p in args.symbols if p.is_file()]
if wanted:
if zips:
local_symbols(zips, wanted, found, notes)
else:
notes.append("no symbols zip given: our engine's functions stay module+offset")
server_symbols(wanted, found, notes)
print("symbolication:")
for n in notes:
print(" " + n)
for a in chosen:
print("=" * 100)
print("process %s, type %s, file %s: %d thread(s), weight %.0f %s" % (a["pid"], a["type"], a["file"], len(a["threads"]), a["total"], unit))
print("-" * 100)
print("PROCESS-WIDE (all %d threads together), weight %.0f" % (len(a["threads"]), a["total"]))
wmod: Dict[str, float] = collections.defaultdict(float)
for key, w in a["wide"].items():
label, lib, rva, js = a["winfo"][key]
wmod["[JS]" if js else (a["libs"][lib].get("name") if lib is not None else "(no module: %s)" % label[:40])] += w
wtot = a["total"] or 1
print(" self weight by module: " + ", ".join("%s %.0f (%.1f%%)" % (m, w, 100 * w / wtot)
for m, w in sorted(wmod.items(), key=lambda kv: -kv[1])[:10]))
print(" weight by thread: " + ", ".join("%s %.0f (%.1f%%)" % (t["name"], t["total"], 100 * t["total"] / wtot)
for t in sorted(a["threads"], key=lambda t: -t["total"])[:10]))
for key, w in sorted(a["wide"].items(), key=lambda kv: -kv[1])[:args.top * 2]:
label, lib, rva, js = a["winfo"][key]
if lib is not None and rva is not None:
L = a["libs"][lib]
name = found.get((L.get("debugName"), L.get("breakpadId"), rva))
if name:
label = "%s!%s" % (L.get("name"), name)
print(" %9.0f %5.1f%% %s" % (w, 100 * w / wtot, label[:200]))
sampler_cpu = sampler_cpu_by_pid.get(str(a["pid"]))
if sampler_cpu is not None:
print(" the sampler measured %.2f s of CPU for pid %s; the profile's threads weigh %.2f s (%.0f%% of it; the rest is CPU the profile did not attribute: threads the profiler does not register, time before and after sampling, the buffer overwritten)"
% (sampler_cpu, a["pid"], a["total"] / 1e6, 100 * a["total"] / 1e6 / sampler_cpu if sampler_cpu else 0))
if args.thread_table:
print("-" * 100)
print("EVERY THREAD of process %s (%s), by weight; self weight by module" % (a["pid"], a["type"]))
unnamed: Dict[str, float] = collections.defaultdict(float)
for t in sorted(a["threads"], key=lambda t: -t["total"]):
mods = thread_modules(a, t)
tot = t["total"] or 1
mod_text = ", ".join("%s %.0f%%" % (m, 100 * w / tot) for m, w in sorted(mods.items(), key=lambda kv: -kv[1])[:4]) or "(no samples)"
nm = t["name"] if t["name"] not in ("", "?", None) else "(unnamed)"
print(" %-26s tid %-7s %10.0f %5.1f%% %s" % (nm[:26], t["tid"], t["total"], 100 * t["total"] / (a["total"] or 1), mod_text))
if nm == "(unnamed)":
for m, w in mods.items():
unnamed[m] += w
if unnamed:
ut = sum(unnamed.values()) or 1
print(" UNNAMED threads together: weight %.0f (%.1f%% of the process), by module: %s"
% (ut, 100 * ut / (a["total"] or 1), ", ".join("%s %.0f%%" % (m, 100 * w / ut) for m, w in sorted(unnamed.items(), key=lambda kv: -kv[1])[:5])))
else:
print(" every thread has a name")
for t in sorted(a["threads"], key=lambda t: -t["total"])[:args.threads]:
print("-" * 100)
print("thread %s (tid %s): %d samples, weight %.0f%s" % (t["name"], t["tid"], t["samples"], t["total"],
" ERROR " + t["error"] if t.get("error") else ""))
by_mod: Dict[str, float] = collections.defaultdict(float)
for key, w in t["self"].items():
label, lib, rva, js = t["info"][key]
by_mod["[JS]" if js else (a["libs"][lib].get("name") if lib is not None else "(no module: %s)" % label[:40])] += w
tot = t["total"] or 1
print(" self weight by module: " + ", ".join("%s %.0f (%.0f%%)" % (m, w, 100 * w / tot)
for m, w in sorted(by_mod.items(), key=lambda kv: -kv[1])[:8]))
for key, w in sorted(t["self"].items(), key=lambda kv: -kv[1])[:args.top]:
label, lib, rva, js = t["info"][key]
if lib is not None and rva is not None:
L = a["libs"][lib]
name = found.get((L.get("debugName"), L.get("breakpadId"), rva))
if name:
label = "%s!%s" % (L.get("name"), name)
print(" %9.0f %5.1f%% %s" % (w, 100 * w / tot, label[:200]))
return 0
if __name__ == "__main__":
sys.exit(main())
+331
View File
@@ -0,0 +1,331 @@
"""HUNT ONLY (branch hunt/cpu-render-path, never merged): why does a 1024x1024 WebGL readPixels take ~250-290 ms in ours against 5-9 ms in stock and retail?
python scripts/hunt_readback.py run --arm ours|ours_noproj|stockheaded|retail [--binary B] [--retail-from DIR] --out DIR
python scripts/hunt_readback.py facts --arm ... --out DIR # the effective zoom.stealth.canvas.* and fpp.hw_seed prefs
python scripts/hunt_readback.py profile --arm ours|ours_noproj --binary B --out DIR # Gecko profile of 20 readPixels + 20 toDataURL (every process, every thread)
python scripts/hunt_readback.py table DIR [DIR ...] # one DIR per round
MSAA was not the cause (run 43656857973). The suspect is the canvas noise of the engine (the engine source tree): decision "noise only on read".
- the code: gfx/2d/StealthCanvasProjection.cpp StealthProjectPixels (lines 133-274), called for WebGL/WebGPU only (a 2D canvas is never projected: StealthCanvasProjection.h:62-71,
dom/canvas/StealthCanvasNoise.cpp:44-48). Roads: readPixels (dom/canvas/ClientWebGLContext.cpp:5486 -> StealthWebGLReadback.h:89-98 ReadPixels, which reads TWICE: DoReadPixels
for the page and, inside ProjectReadPixels, a second DoReadPixels of the rectangle grown by one pixel, lines 200-209, then copies the rows back, 237-249), toDataURL/toBlob
(ClientWebGLContext.cpp:1367 and :1399 -> StealthWebGLReadback.h:60-66 -> CanvasUtils::StealthProjectSnapshot, dom/canvas/StealthCanvasNoise.cpp:50-69, which creates a new data
surface and copies the whole canvas before projecting, gfx/2d/StealthCanvasProjection.cpp:276-308), PBO reads (StealthWebGLReadback.h:108-171: two more reads and one BufferSubData per row);
- the seed is zoom.stealth.fpp.hw_seed; the projection is ON when it is > 0 AND zoom.stealth.canvas.substitute_pixels is true (gfx/thebes/StealthDeclarationGate.h:54-62; the pref is
declared in modules/libpref/init/StealthPrefList.yaml:385-388, set by the core in invisible_core/prefs.py:1015). zoom.stealth.canvas.edge_tolerance (prefs.py:1019, 4) is its tolerance.
- the cost is DATA-DEPENDENT: a pixel is touched only if one of its four neighbours differs once the low bit of R, G, B is cleared (StealthCanvasProjection.cpp:187-193); an edge pixel
builds its 3x3 neighbourhood and runs OnOneSegment (lines 89-129: 36 pair distances, each of 4 channels, then up to 9 segment tests) and, if it passes, 8 Mix() calls and the carry
logic (lines 202-265). A flat canvas is a memcpy, a canvas in which EVERY pixel is an edge costs roughly a thousand operations per pixel. The earlier probes (hunt_compositor_probe.js,
hunt_msaa_probe.js) drew fract(gl_FragCoord.x/97.): every pixel an edge, the worst case.
THE ARMS: ours; ours_noproj = ours with zoom.stealth.canvas.substitute_pixels=false passed ONLY by the hunt (hunt_cpu_per_browser.ARM_PREFS); stockheaded; retail 159.0 by hand (the page
posts its result to the local server).
`run` (scripts/hunt_readback_probe.js, mode timing): per content (flat, halves, triangle, gradient, noise) WebGL readPixels p50, toDataURL p50, 1-pixel readPixels, canvas 2D getImageData p50 and
toDataURL p50, all 1024x1024, antialias:false; a hash of the bytes; and the 256x256 diagonal-edge scene (antialias:false) with its raw bytes.
`profile` (mode profile): 20 readPixels + 20 toDataURL of the gradient canvas with the Gecko profiler on in EVERY process and thread (MOZ_PROFILER_STARTUP_FILTERS=*); the workflow then runs
hunt_profile_summary.py with symbols for the content ("tab") and GPU processes.
`table`: ms and ms per MB per content and arm; ours against ours_noproj; the 2D control; the pixel diff of the edge scene (is the 1-level difference of ours against retail the projection?).
"""
from __future__ import annotations
import argparse
import asyncio
import base64
import contextlib
import gzip
import json
import os
import subprocess
import sys
import tempfile
import threading
import time
from http.server import ThreadingHTTPServer
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
import hunt_cpu_per_browser as hunt # noqa: E402
import hunt_cpu_render_path as rp # noqa: E402
import hunt_compositor_visible as cv # noqa: E402
ARMS = ["ours", "ours_noproj", "stockheaded", "retail"]
CONTENTS = ["flat", "halves", "triangle", "gradient", "noise"]
MB = 1024 * 1024 * 4 / 1048576.0 # a 1024x1024 RGBA canvas is 4 MiB
class ReadbackPage(cv.Page):
def do_GET(self): # noqa: N802
if self.path.startswith("/probe.js"):
self._send((HERE / "hunt_readback_probe.js").read_bytes(), "text/javascript; charset=utf-8")
else:
self._send(b'<!doctype html><meta charset=utf-8><title>readback</title><body style="margin:0"><script src="/probe.js"></script></body>', "text/html; charset=utf-8")
def serve(query: str = "") -> Tuple[ThreadingHTTPServer, str]:
httpd = ThreadingHTTPServer(("127.0.0.1", 0), ReadbackPage)
httpd.daemon_threads = True
threading.Thread(target=httpd.serve_forever, daemon=True).start()
return httpd, "http://127.0.0.1:%d/%s" % (httpd.server_address[1], query)
def run(args) -> int:
args.out.mkdir(parents=True, exist_ok=True)
httpd, url = serve()
cv.Page.result = None
cv.kill_firefox()
note, err = "", ""
try:
if args.arm == "retail":
exe, note = cv.retail_exe(args)
profile = Path(tempfile.mkdtemp(prefix="hunt-readback-retail-"))
proc = subprocess.Popen([str(exe), "-no-remote", "-profile", str(profile), url], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
try:
end = time.time() + cv.WAIT_S
while cv.Page.result is None and time.time() < end:
time.sleep(0.5)
finally:
cv.kill_firefox()
with contextlib.suppress(Exception):
proc.wait(timeout=10)
elif args.arm == "stockheaded":
asyncio.run(cv.stock_run(url))
else:
asyncio.run(cv.ours_run(args.binary, url, hunt.arm_prefs(args.arm)))
except BaseException as exc: # noqa: BLE001
err = "%s: %s" % (type(exc).__name__, str(exc)[:400])
cv.kill_firefox()
httpd.shutdown()
data: Dict[str, Any] = {}
if cv.Page.result:
try:
data = json.loads(cv.Page.result)
except ValueError as exc:
err = err or "unreadable result: %s" % exc
else:
err = err or "the page posted nothing in %d s" % cv.WAIT_S
doc = {"arm": args.arm, "note": note, "error": err, "probe": data, "prefs_passed": hunt.arm_prefs(args.arm) if args.arm.startswith("ours") else None}
(args.out / ("%s.json" % args.arm)).write_text(json.dumps(doc, indent=1), encoding="utf-8")
print("arm %s: %s%s" % (args.arm, "result received" if data else "NO RESULT", ("; ERROR " + err) if err else ""))
if data.get("errors"):
print(" page errors: %s" % data["errors"])
print_arm(doc)
return 1 if err else 0
def facts(args) -> int:
out = args.out / ("%s-facts" % args.arm)
out.mkdir(parents=True, exist_ok=True)
cv.kill_firefox()
report: Dict[str, Any] = {"arm": args.arm}
async def go():
async with rp.launched(args.arm, args.binary or "", marionette=True) as browser:
page = await browser.new_page()
await page.goto("about:blank")
await asyncio.get_running_loop().run_in_executor(None, rp.privileged_route, out, report)
try:
asyncio.run(go())
except BaseException as exc: # noqa: BLE001
report["error"] = "%s: %s" % (type(exc).__name__, str(exc)[:300])
cv.kill_firefox()
print_facts(args.arm, out)
return 0
def print_facts(arm: str, out: Path) -> None:
print("-" * 110)
print("FACTS of %s: the canvas-noise prefs as the browser reads them (the projection is on when hw_seed > 0 and substitute_pixels is true)" % arm)
pf = out / "effective_prefs.json"
if not pf.is_file():
print(" effective_prefs.json missing")
return
prefs = json.loads(pf.read_text(encoding="utf-8"))
for n in sorted(prefs):
if n.startswith(("zoom.stealth.canvas", "zoom.stealth.fpp")):
print(" pref %s = %s (user-set: %s)" % (n, prefs[n][1], prefs[n][0]))
# -------------------------------------------------------------------------------------------------------------------- profile
def profile(args) -> int:
out = args.out / args.arm
out.mkdir(parents=True, exist_ok=True)
pattern = str(out / "profile-%p.json")
os.environ.update({"MOZ_PROFILER_STARTUP": "1", "MOZ_PROFILER_STARTUP_FEATURES": "stackwalk,cpu,threads,processcpu", "MOZ_PROFILER_STARTUP_FILTERS": "*",
"MOZ_PROFILER_STARTUP_ENTRIES": "4194304", "MOZ_PROFILER_STARTUP_INTERVAL": "1", "MOZ_PROFILER_SHUTDOWN": pattern})
print(rp.let_profiler_env_through())
print("profile arm %s: %s; environment %s" % (args.arm, pattern, ", ".join("%s=%s" % (k, v) for k, v in sorted(os.environ.items()) if k.startswith("MOZ_PROFILER_"))))
httpd, url = serve("?mode=profile")
cv.Page.result = None
cv.kill_firefox()
err = ""
try:
asyncio.run(cv.ours_run(args.binary, url, hunt.arm_prefs(args.arm)))
except BaseException as exc: # noqa: BLE001
err = "%s: %s" % (type(exc).__name__, str(exc)[:300])
httpd.shutdown()
print(rp.wait_until_no_firefox(90))
cv.kill_firefox()
time.sleep(3)
page = json.loads(cv.Page.result) if cv.Page.result else {}
print("the page: %s%s" % (json.dumps(page.get("profile", {}).get("readPixels_ms_p50")) + " ms readPixels p50, " + json.dumps(page.get("profile", {}).get("toDataURL_ms_p50")) + " ms toDataURL p50",
("; ERROR " + err) if err else ""))
files = sorted(out.glob("profile-*.json"))
for f in files:
raw = f.read_bytes()
try:
json.loads(raw.decode("utf-8", "replace"))
state = "valid JSON"
except ValueError as exc:
state = "NOT VALID JSON (%s)" % str(exc)[:80]
print(" %s: %.1f MB, %s" % (f.name, len(raw) / 2 ** 20, state))
with gzip.open(str(f) + ".gz", "wb", 6) as g:
g.write(raw)
f.unlink()
(out / "page.json").write_text(json.dumps(page, indent=1), encoding="utf-8")
print("%d profile file(s) in %s" % (len(files), out))
return 1 if err or not files else 0
# ----------------------------------------------------------------------------------------------------------------------- table
def get(doc: Dict[str, Any], path: str) -> Any:
cur: Any = doc.get("probe", {})
for p in path.split("."):
if not isinstance(cur, dict) or p not in cur:
return None
cur = cur[p]
return cur
def fmt(v: Any) -> str:
return "-" if v is None else (("%.1f" % v) if isinstance(v, float) else str(v))
def print_arm(doc: Dict[str, Any]) -> None:
print("-" * 110)
print("ARM %s%s" % (doc["arm"], (" prefs passed: %s" % doc["prefs_passed"]) if doc.get("prefs_passed") else ""))
print(" %-10s %12s %12s %12s %12s %12s %12s" % ("content", "gl read ms", "gl 1px ms", "gl png ms", "2d get ms", "2d png ms", "gl ms/MB"))
for c in CONTENTS:
g, d = get(doc, "contents.%s.webgl" % c) or {}, get(doc, "contents.%s.canvas2d" % c) or {}
rp_ = g.get("readPixels_ms_p50")
print(" %-10s %12s %12s %12s %12s %12s %12s" % (c, fmt(rp_), fmt(g.get("readPixels_1px_ms_p50")), fmt(g.get("toDataURL_ms_p50")), fmt(d.get("getImageData_ms_p50")),
fmt(d.get("toDataURL_ms_p50")), fmt(rp_ / MB if rp_ is not None else None)))
sys.stdout.flush()
def pixel_diff(a: Optional[str], b: Optional[str]) -> Tuple[str, List[Tuple[int, int, int]]]:
if not a or not b:
return "missing", []
x, y = base64.b64decode(a), base64.b64decode(b)
if len(x) != len(y):
return "sizes differ", []
diffs = []
w = 256
for i in range(0, len(x), 4):
d = max(abs(x[i + k] - y[i + k]) for k in range(4))
if d:
p = i // 4
diffs.append((p % w, p // w, d))
if not diffs:
return "identical", []
return "%d of %d pixels differ, largest channel delta %d, first at (%d, %d)" % (len(diffs), len(x) // 4, max(d for _, _, d in diffs), diffs[0][0], diffs[0][1]), diffs
def table(dirs: List[Path]) -> int:
rounds: List[Dict[str, Dict[str, Any]]] = []
for d in dirs:
docs = {a: json.loads((d / ("%s.json" % a)).read_text(encoding="utf-8")) for a in ARMS if (d / ("%s.json" % a)).is_file()}
if docs:
rounds.append(docs)
if not rounds:
print("no results")
return 1
arms = [a for a in ARMS if any(a in r for r in rounds)]
print("=" * 130)
print("READBACK COST, 1024x1024, antialias:false: %d round(s), arms %s. ms are p50 of the repeats; one value per round (round 1 / round 2 ...)" % (len(rounds), ", ".join(arms)))
for label, path_of in (("WebGL readPixels ms", lambda c: "contents.%s.webgl.readPixels_ms_p50" % c), ("WebGL toDataURL ms", lambda c: "contents.%s.webgl.toDataURL_ms_p50" % c),
("WebGL 1-pixel readPixels ms", lambda c: "contents.%s.webgl.readPixels_1px_ms_p50" % c),
("canvas 2D getImageData ms (never projected)", lambda c: "contents.%s.canvas2d.getImageData_ms_p50" % c),
("canvas 2D toDataURL ms (never projected)", lambda c: "contents.%s.canvas2d.toDataURL_ms_p50" % c)):
print("-" * 130)
print(label)
print(" %-10s" % "content" + "".join(" %-22s" % a for a in arms))
for c in CONTENTS:
print(" %-10s" % c + "".join(" %-22s" % ("/".join(fmt(get(r[a], path_of(c))) for r in rounds if a in r))[:22] for a in arms))
print("=" * 130)
print("COST PER MB of the WebGL readPixels (4 MiB per canvas): ms / 4, round 1; and the cost the projection adds = ours minus ours_noproj")
r1 = rounds[0]
print(" %-10s" % "content" + "".join(" %-14s" % a for a in arms) + " %-22s" % "projection ms/MB")
for c in CONTENTS:
cells, vals = "", {}
for a in arms:
v = get(r1[a], "contents.%s.webgl.readPixels_ms_p50" % c) if a in r1 else None
vals[a] = v
cells += " %-14s" % (fmt(v / MB) if v is not None else "-")
add = (vals["ours"] - vals["ours_noproj"]) / MB if vals.get("ours") is not None and vals.get("ours_noproj") is not None else None
print(" %-10s" % c + cells + " %-22s" % fmt(add))
print(" the toDataURL equivalent (ms/MB, projection = ours - ours_noproj):")
for c in CONTENTS:
o, n = (get(r1[a], "contents.%s.webgl.toDataURL_ms_p50" % c) if a in r1 else None for a in ("ours", "ours_noproj"))
print(" %-10s ours %s ms, ours_noproj %s ms -> %s ms/MB" % (c, fmt(o), fmt(n), fmt((o - n) / MB) if o is not None and n is not None else "-"))
print("=" * 130)
print("THE VERDICT FOR THE HYPOTHESIS (round 1)")
for c in ("gradient", "noise", "triangle", "flat"):
parts = []
for a in arms:
if a in r1:
parts.append("%s %s ms" % (a, fmt(get(r1[a], "contents.%s.webgl.readPixels_ms_p50" % c))))
print(" WebGL readPixels, %-9s %s" % (c + ":", "; ".join(parts)))
for c in ("gradient", "noise"):
parts = ["%s %s ms" % (a, fmt(get(r1[a], "contents.%s.canvas2d.getImageData_ms_p50" % c))) for a in arms if a in r1]
print(" canvas 2D getImageData, %-9s %s" % (c + ":", "; ".join(parts)))
print("=" * 130)
print("WHAT A PAGE READS: hashes of the bytes per content (WebGL readPixels), round 1; a difference is a different answer to the same question")
print(" %-10s" % "content" + "".join(" %-20s" % a for a in arms))
for c in CONTENTS:
print(" %-10s" % c + "".join(" %-20s" % fmt(get(r1[a], "contents.%s.webgl.pixels_hash" % c)) if a in r1 else " %-20s" % "-" for a in arms))
print(" canvas 2D (never projected):")
for c in CONTENTS:
print(" %-10s" % c + "".join(" %-20s" % fmt(get(r1[a], "contents.%s.canvas2d.pixels_hash" % c)) if a in r1 else " %-20s" % "-" for a in arms))
print("=" * 130)
print("THE DIAGONAL-EDGE SCENE (antialias:false, 256x256, readPixels), pixel by pixel, round 1: is the 1-level difference of ours against retail the projection?")
for a, b in (("ours", "retail"), ("ours_noproj", "retail"), ("ours", "ours_noproj"), ("ours", "stockheaded"), ("ours_noproj", "stockheaded"), ("stockheaded", "retail")):
if a in r1 and b in r1:
text, diffs = pixel_diff(get(r1[a], "scene.readPixels_b64"), get(r1[b], "scene.readPixels_b64"))
print(" %-12s against %-12s: %s" % (a, b, text))
for d in dirs:
for a in arms:
fd = d / ("%s-facts" % a)
if fd.is_dir():
print_facts(a, fd)
return 0
def main() -> int:
ap = argparse.ArgumentParser()
sub = ap.add_subparsers(dest="cmd", required=True)
for name in ("run", "facts", "profile"):
p = sub.add_parser(name)
p.add_argument("--arm", choices=ARMS, required=True)
p.add_argument("--binary", default=os.environ.get("INVPW_BINARY_PATH", ""))
p.add_argument("--retail-from", default="")
p.add_argument("--out", type=Path, required=True)
t = sub.add_parser("table")
t.add_argument("dirs", type=Path, nargs="+")
args = ap.parse_args()
if args.cmd == "table":
return table(args.dirs)
if args.arm.startswith("ours") and not args.binary:
ap.error("the ours arms need --binary (or INVPW_BINARY_PATH)")
if args.arm == "retail" and not args.retail_from and args.cmd != "profile":
ap.error("the arm retail needs --retail-from (hunt_first_run.py fetch-retail)")
if args.cmd == "profile" and not args.arm.startswith("ours"):
ap.error("profile is for the ours arms")
return {"run": run, "facts": facts, "profile": profile}[args.cmd](args)
if __name__ == "__main__":
sys.exit(main())
+134
View File
@@ -0,0 +1,134 @@
// HUNT ONLY (branch hunt/cpu-render-path, never merged). Served by scripts/hunt_readback.py as /probe.js; the page posts ONE JSON result to /result.
// Why does a 1024x1024 WebGL readPixels take ~250-290 ms in ours against 5-9 ms in stock and retail, with or without MSAA?
// In the engine (firefox-64 series, the engine source tree) the WebGL read roads go through the canvas noise, gfx::StealthProjectPixels (gfx/2d/StealthCanvasProjection.cpp):
// a pixel is looked at only if it is an EDGE (a 4-neighbour differs once the low bit of R, G and B is cleared); on such a pixel the function builds the 3x3 neighbourhood and
// runs OnOneSegment (36 pair distances and up to 9 segment tests, integer, per pixel). A flat canvas costs a memcpy; a canvas in which EVERY pixel is an edge costs ~1000 operations
// per pixel. The earlier probes drew exactly that: a per-pixel ramp (fract(gl_FragCoord.x/97.)), whose neighbours differ by ~2.6 levels everywhere. So the content is the variable:
// mode=timing per content (flat, halves, triangle, gradient, noise): WebGL readPixels (p50 of 5), WebGL toDataURL (p50 of 3), canvas 2D getImageData (p50 of 5), canvas 2D toDataURL
// (p50 of 3), all 1024x1024, antialias:false (MSAA out of the picture); a hash of the bytes read; and the 256x256 diagonal-edge scene (antialias:false) read back, raw
// bytes returned, to compare pixel by pixel with retail.
// mode=profile 20 readPixels and 20 toDataURL of the gradient 1024x1024 WebGL canvas (the worst case), nothing else, for the Gecko profile.
(async () => {
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const now = () => performance.now();
const mode = new URLSearchParams(location.search).get("mode") || "timing";
const q = (a, p) => { if (!a.length) return null; const s = a.slice().sort((x, y) => x - y); return s[Math.min(s.length - 1, Math.floor(p * s.length))]; };
const r3 = (x) => (x === null || x === undefined ? null : Math.round(x * 1000) / 1000);
const result = { mode, contents: {}, scene: {}, errors: [] };
function hash(u8) { let h1 = 0xdeadbeef ^ u8.length, h2 = 0x41c6ce57 ^ u8.length; for (let i = 0; i < u8.length; i++) { h1 = Math.imul(h1 ^ u8[i], 2654435761); h2 = Math.imul(h2 ^ u8[i], 1597334677); } return (h2 >>> 0).toString(16) + (h1 >>> 0).toString(16); }
function b64(u8) { let s = ""; for (let i = 0; i < u8.length; i += 0x8000) s += String.fromCharCode.apply(null, u8.subarray(i, i + 0x8000)); return btoa(s); }
async function step(name, fn) { try { await fn(); } catch (e) { result.errors.push(name + ": " + ((e && e.message) || e)); } }
const N = 1024;
function glContext(w, h) {
const c = document.createElement("canvas"); c.width = w; c.height = h; c.style.cssText = "position:fixed;left:0;top:0";
document.body.appendChild(c);
const gl = c.getContext("webgl", { antialias: false, preserveDrawingBuffer: true, alpha: true });
if (!gl) { c.remove(); throw new Error("no webgl"); }
return { c, gl };
}
function program(gl, fs) {
const mk = (t, s) => { const x = gl.createShader(t); gl.shaderSource(x, s); gl.compileShader(x); if (!gl.getShaderParameter(x, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(x)); return x; };
const p = gl.createProgram();
gl.attachShader(p, mk(gl.VERTEX_SHADER, "attribute vec2 p; void main(){ gl_Position=vec4(p,0.,1.); }"));
gl.attachShader(p, mk(gl.FRAGMENT_SHADER, fs));
gl.bindAttribLocation(p, 0, "p"); gl.linkProgram(p); gl.useProgram(p);
return p;
}
function verts(gl, arr) {
const b = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, b); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(arr), gl.STREAM_DRAW);
gl.enableVertexAttribArray(0); gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);
}
const QUAD = [-1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, 1];
// the same per-pixel formulas in JS (for the 2D canvas) and in GLSL (for WebGL)
const rampPixel = (x, y) => [Math.floor(((x / 97) % 1) * 255), Math.floor(((y / 89) % 1) * 255), 128];
function noisePixel(x, y) { let h = (x * 374761393 + y * 668265263) | 0; h = Math.imul(h ^ (h >>> 13), 1274126177); h ^= h >>> 16; return [h & 255, (h >>> 8) & 255, (h >>> 16) & 255]; }
function drawGL(gl, kind) {
gl.viewport(0, 0, N, N); gl.disable(gl.SCISSOR_TEST);
if (kind === "flat") { gl.clearColor(0.2, 0.4, 0.6, 1); gl.clear(gl.COLOR_BUFFER_BIT); return; }
if (kind === "halves") { gl.clearColor(1, 1, 1, 1); gl.clear(gl.COLOR_BUFFER_BIT); gl.enable(gl.SCISSOR_TEST); gl.scissor(0, 0, N / 2, N); gl.clearColor(0.1, 0.5, 0.2, 1); gl.clear(gl.COLOR_BUFFER_BIT); return; }
if (kind === "triangle") {
gl.clearColor(1, 1, 1, 1); gl.clear(gl.COLOR_BUFFER_BIT);
program(gl, "precision mediump float; void main(){ gl_FragColor=vec4(.1,.3,.8,1.); }");
verts(gl, [-0.9, -0.8, 0.85, -0.6, -0.1, 0.9]); gl.drawArrays(gl.TRIANGLES, 0, 3); return;
}
if (kind === "gradient") {
program(gl, "precision highp float; void main(){ gl_FragColor=vec4(fract(gl_FragCoord.x/97.), fract(gl_FragCoord.y/89.), .5, 1.); }");
verts(gl, QUAD); gl.drawArrays(gl.TRIANGLES, 0, 6); return;
}
if (kind === "noise") {
program(gl, "precision highp float; float h(vec2 p){ return fract(sin(dot(p, vec2(12.9898,78.233)))*43758.5453); } void main(){ vec2 p=gl_FragCoord.xy; gl_FragColor=vec4(h(p), h(p+17.), h(p+31.), 1.); }");
verts(gl, QUAD); gl.drawArrays(gl.TRIANGLES, 0, 6); return;
}
}
function draw2D(g, kind) {
if (kind === "flat") { g.fillStyle = "rgb(51,102,153)"; g.fillRect(0, 0, N, N); return; }
if (kind === "halves") { g.fillStyle = "#fff"; g.fillRect(0, 0, N, N); g.fillStyle = "rgb(26,128,51)"; g.fillRect(0, 0, N / 2, N); return; }
if (kind === "triangle") { g.fillStyle = "#fff"; g.fillRect(0, 0, N, N); g.fillStyle = "rgb(26,77,204)"; g.beginPath(); g.moveTo(51, 92); g.lineTo(947, 205); g.lineTo(461, 972); g.closePath(); g.fill(); return; }
const id = g.createImageData(N, N), d = id.data, f = kind === "gradient" ? rampPixel : noisePixel;
for (let y = 0; y < N; y++) for (let x = 0; x < N; x++) { const p = f(x, y), i = (y * N + x) * 4; d[i] = p[0]; d[i + 1] = p[1]; d[i + 2] = p[2]; d[i + 3] = 255; }
g.putImageData(id, 0, 0);
}
const reps = async (n, fn) => { const t = []; for (let i = 0; i < n; i++) { const s = now(); const v = fn(); t.push(now() - s); if (i === n - 1) t.last = v; } return t; };
if (mode === "profile") {
await step("profile", async () => {
const { c, gl } = glContext(N, N);
drawGL(gl, "gradient");
const px = new Uint8Array(N * N * 4), rp = [], td = [];
await sleep(300);
for (let i = 0; i < 20; i++) { const s = now(); gl.readPixels(0, 0, N, N, gl.RGBA, gl.UNSIGNED_BYTE, px); rp.push(now() - s); }
await sleep(300);
for (let i = 0; i < 20; i++) { const s = now(); c.toDataURL("image/png"); td.push(now() - s); }
result.profile = { readPixels_ms_p50: r3(q(rp, 0.5)), toDataURL_ms_p50: r3(q(td, 0.5)), readPixels_ms: rp.map(r3), toDataURL_ms: td.map(r3) };
c.remove();
});
await fetch("/result", { method: "POST", body: JSON.stringify(result) });
return;
}
// ----------------------------------------------------------------------------------------------------------------------- timing, per content
for (const kind of ["flat", "halves", "triangle", "gradient", "noise"]) {
await step("webgl " + kind, async () => {
const { c, gl } = glContext(N, N);
drawGL(gl, kind);
const px = new Uint8Array(N * N * 4);
const rp = await reps(5, () => gl.readPixels(0, 0, N, N, gl.RGBA, gl.UNSIGNED_BYTE, px));
const td = await reps(3, () => c.toDataURL("image/png"));
const one = await reps(5, () => gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array(4)));
(result.contents[kind] = result.contents[kind] || {}).webgl = { readPixels_first_ms: r3(rp[0]), readPixels_ms_p50: r3(q(rp.slice(1), 0.5)), toDataURL_ms_p50: r3(q(td, 0.5)),
readPixels_1px_ms_p50: r3(q(one, 0.5)), pixels_hash: hash(px) };
c.remove();
});
await step("2d " + kind, async () => {
const c = document.createElement("canvas"); c.width = c.height = N;
const g = c.getContext("2d");
draw2D(g, kind);
let d = null;
const gi = await reps(5, () => { d = g.getImageData(0, 0, N, N); });
const td = await reps(3, () => c.toDataURL("image/png"));
(result.contents[kind] = result.contents[kind] || {}).canvas2d = { getImageData_first_ms: r3(gi[0]), getImageData_ms_p50: r3(q(gi.slice(1), 0.5)), toDataURL_ms_p50: r3(q(td, 0.5)), pixels_hash: hash(new Uint8Array(d.data.buffer)) };
});
}
// ----------------------------------------------------------------------------------------------------------------------- the diagonal-edge scene, antialias:false, 256x256
await step("scene", async () => {
const W = 256, H = 256;
const { c, gl } = (() => { const c = document.createElement("canvas"); c.width = W; c.height = H; document.body.appendChild(c);
return { c, gl: c.getContext("webgl", { antialias: false, preserveDrawingBuffer: true }) }; })();
gl.viewport(0, 0, W, H); gl.clearColor(1, 1, 1, 1); gl.clear(gl.COLOR_BUFFER_BIT);
const col = (r, g, b) => program(gl, "precision mediump float; void main(){ gl_FragColor=vec4(" + r + "," + g + "," + b + ",1.); }");
const rot = (x, y, a) => [x * Math.cos(a) - y * Math.sin(a), x * Math.sin(a) + y * Math.cos(a)];
col(0.1, 0.3, 0.8); verts(gl, [[-0.62, -0.5], [0.58, -0.44], [0.02, 0.71]].flatMap(([x, y]) => rot(x, y, 17 * Math.PI / 180))); gl.drawArrays(gl.TRIANGLES, 0, 3);
col(0.8, 0.1, 0.1); gl.lineWidth(1);
const lines = []; for (let k = 0; k < 12; k++) { const a = (k * 15 + 7) * Math.PI / 180; lines.push(0.05 * Math.cos(a), 0.05 * Math.sin(a), 0.93 * Math.cos(a), 0.93 * Math.sin(a)); }
verts(gl, lines); gl.drawArrays(gl.LINES, 0, 24);
col(0.0, 0.55, 0.1);
const sl = []; for (let k = 0; k < 5; k++) { const a = (k * 31 + 11) * Math.PI / 180; const [x0, y0] = rot(-0.9, -0.85 + k * 0.05, a), [x1, y1] = rot(0.9, -0.85 + k * 0.05, a), [x2, y2] = rot(0.9, -0.845 + k * 0.05, a); sl.push(x0, y0, x1, y1, x2, y2); }
verts(gl, sl); gl.drawArrays(gl.TRIANGLES, 0, 15);
const u = new Uint8Array(W * H * 4); gl.readPixels(0, 0, W, H, gl.RGBA, gl.UNSIGNED_BYTE, u);
result.scene = { size: [W, H], attributes_antialias: gl.getContextAttributes().antialias, pixels_hash: hash(u), readPixels_b64: b64(u) };
c.remove();
});
await fetch("/result", { method: "POST", body: JSON.stringify(result) });
})().catch((e) => fetch("/result", { method: "POST", body: JSON.stringify({ fatal: String((e && e.message) || e) }) }));
-75
View File
@@ -1,75 +0,0 @@
"""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])
+173
View File
@@ -0,0 +1,173 @@
"""HUNT ONLY (branch hunt/cpu-render-path, never merged): make OUR browser take the retail decisions of this VM, from the hunt only.
python scripts/hunt_vmretail.py build --binary "$FF" --out DIR # reads ours and stock, writes DIR/prefs.json, prints the table
python scripts/hunt_vmretail.py prefs-json DIR/prefs.json # the prefs as one JSON line (HUNT_EXTRA_PREFS for the pytest plugin)
WHAT STOCK DOES HERE. On the Windows VM runner the adapter is Microsoft Hyper-V Video; stock Firefox's GfxInfo blocks D3D11 compositing and
WebRender with FEATURE_FAILURE_VM_VENDOR and falls back to WebRender (Software) with no D3D11. Ours declares OK for these features through
`zoom.stealth.gfx.feature_status` (the core's declaration of the persona: NAME|STATUS[|FAILURE] for every live feature, answered by the engine's
StealthGfxDeclaredStatus before any blocklist is read), so ours takes the hardware path on the same adapter.
WHAT THIS DOES. `build` launches
1. ours with Marionette (chrome scope) and reads the DECLARED table: the pref zoom.stealth.gfx.feature_status, as the core wrote it;
2. stock Playwright's firefox, headed, with Marionette, and asks nsIGfxInfo.getFeatureStatusStr(NAME) for every feature of that table: the
status and the failure id Mozilla's own decision gives on this machine;
then prints, for EVERY feature, declared against stock, and builds the extra_prefs of the arm `ours_vmretail`:
- zoom.stealth.gfx.feature_status: the declared table with ONLY the compositing features replaced by stock's decision (DIRECT3D_11_LAYERS, GPU_PROCESS,
WEBRENDER, WEBRENDER_*, D3D11_KEYED_MUTEX, DX_INTEROP2, CANVAS2D_ACCELERATION, ACCELERATED_CANVAS2D). The WebGL features (WEBGL*, WEBGPU,
DIRECT3D_11_ANGLE), the media ones and everything else keep what the persona declares: the page-readable WebGL values stay as declared.
- gfx.webrender.software = true (WebRender's software backend, explicit)
- gfx.webrender.software.d3d11 = false (no D3D11 compositor for it: "WebRender (Software)", not "Software D3D11")
- webgl.angle.force-warp = true (WebGL on ANGLE with an explicit WARP device)
Everything is passed through extra_prefs by hunt_cpu_per_browser.arm_prefs; the product is not touched. `support --arm ours_vmretail` then reads the
effective prefs and Troubleshoot back and says what took effect.
"""
from __future__ import annotations
import argparse
import asyncio
import json
import os
import re
import sys
from pathlib import Path
from typing import Any, Dict, List, Optional
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
import hunt_cpu_render_path as rp # noqa: E402
#: the features that decide where and how the page is composited: replaced by stock's decision
COMPOSITING = re.compile(r"^(DIRECT3D_9_LAYERS|DIRECT3D_10_LAYERS|DIRECT3D_10_1_LAYERS|DIRECT3D_11_LAYERS|GPU_PROCESS|WEBRENDER[A-Z_]*|D3D11_KEYED_MUTEX|"
r"DX_INTEROP2|CANVAS2D_ACCELERATION|ACCELERATED_CANVAS2D)$")
STATUS = {"STATUS_OK": 1, "STATUS_UNKNOWN": 2, "BLOCKED_DRIVER_VERSION": 3, "BLOCKED_DEVICE": 4, "DISCOURAGED": 5, "BLOCKED_OS_VERSION": 6,
"BLOCKED_MISMATCHED_VERSION": 7, "DENIED": 8, "ALLOW_ALWAYS": 9, "ALLOW_QUALIFIED": 10, "BLOCKED_PLATFORM_TEST": 11}
NUMBER_TO_NAME = {v: k for k, v in STATUS.items()}
WEBGL_PREFS = {"gfx.webrender.software": True, "gfx.webrender.software.d3d11": False, "webgl.angle.force-warp": True}
DECLARED_JS = """
let cb = arguments[arguments.length - 1];
let out = {};
for (let n of ["zoom.stealth.gfx.feature_status"]) {
try { out[n] = Services.prefs.getStringPref(n); } catch (e) { out[n] = null; }
}
out.version = Services.appinfo.version;
cb(JSON.stringify(out));
"""
STOCK_JS = """
let cb = arguments[arguments.length - 1];
let names = arguments[0];
let gi = Cc["@mozilla.org/gfx/info;1"].getService(Ci.nsIGfxInfo);
let out = {version: Services.appinfo.version, features: {}};
for (let n of names) {
try { let f = {}; let st = gi.getFeatureStatusStr(n, f); out.features[n] = [st, f.value || ""]; }
catch (e) { out.features[n] = ["ERR", String(e).slice(0, 120)]; }
}
cb(JSON.stringify(out));
"""
def chrome(js: str, args: List[Any]) -> Dict[str, Any]:
m = rp.Marionette()
try:
m.call("WebDriver:NewSession", {"capabilities": {"alwaysMatch": {}}})
m.call("WebDriver:SetTimeouts", {"script": 120000})
m.call("Marionette:SetContext", {"value": "chrome"})
res = rp.marionette_value(m.call("WebDriver:ExecuteAsyncScript", {"script": js, "args": args}))
return json.loads(res) if isinstance(res, str) else res
finally:
m.close()
async def ask(arm: str, binary: str, js: str, args: List[Any]) -> Dict[str, Any]:
rp.kill_firefox()
try:
async with rp.launched(arm, binary, marionette=True) as browser:
page = await browser.new_page()
await page.goto("about:blank")
return await asyncio.get_running_loop().run_in_executor(None, chrome, js, args)
finally:
rp.kill_firefox()
def parse_declaration(text: str) -> List[List[str]]:
return [e.split("|") for e in text.split(",") if e]
def build(binary: str, out: Path) -> int:
out.mkdir(parents=True, exist_ok=True)
declared_res = asyncio.run(ask("ours", binary, DECLARED_JS, []))
text = declared_res.get("zoom.stealth.gfx.feature_status")
print("ours (engine %s): zoom.stealth.gfx.feature_status %s" % (declared_res.get("version"), ("is %d characters" % len(text)) if text else "NOT READABLE"))
if not text:
print("cannot build the arm without the declared table")
return 1
table = parse_declaration(text)
names = [e[0] for e in table]
stock_res = asyncio.run(ask("stockheaded", "", STOCK_JS, [names]))
stock = stock_res.get("features", {})
print("stock (Firefox %s) answered for %d of %d features" % (stock_res.get("version"), len([n for n in names if stock.get(n, ["ERR"])[0] != "ERR"]), len(names)))
new_entries: List[str] = []
overridden: List[str] = []
print("=" * 100)
print("%-36s %-34s %-34s %s" % ("feature", "declared by the persona (ours)", "decided by stock on this runner", "in ours_vmretail"))
for e in table:
name = e[0]
decl = "%s%s" % (NUMBER_TO_NAME.get(int(e[1]), e[1]), ("|" + e[2]) if len(e) > 2 else "")
st = stock.get(name)
stock_text = "-" if not st else ("%s%s" % (st[0], ("|" + st[1]) if st[1] else ""))
keep = "|".join(e)
verdict = "declared"
if COMPOSITING.match(name) and st and st[0] in STATUS:
number = STATUS[st[0]]
ok_class = number == 1
failure = st[1] or ("" if ok_class else "FEATURE_FAILURE_VM_VENDOR")
candidate = "%s|%d%s" % (name, number, ("|" + failure) if failure and not ok_class else "")
if number in (8, 9, 10):
verdict = "declared (stock status %s cannot be declared for this feature)" % st[0]
else:
if candidate != keep:
overridden.append(name)
verdict = "STOCK'S"
keep = candidate
elif COMPOSITING.match(name):
verdict = "declared (stock gave no answer)"
new_entries.append(keep)
differs = " <-- differs" if st and st[0] in STATUS and (STATUS[st[0]], (st[1] or "")) != (int(e[1]), e[2] if len(e) > 2 else "") else ""
print("%-36s %-34s %-34s %s%s" % (name, decl, stock_text, verdict, differs))
prefs: Dict[str, Any] = {"zoom.stealth.gfx.feature_status": ",".join(new_entries)}
prefs.update(WEBGL_PREFS)
(out / "prefs.json").write_text(json.dumps({"prefs": prefs, "overridden_features": overridden, "ours_engine": declared_res.get("version"),
"stock_version": stock_res.get("version")}, indent=1), encoding="utf-8")
print("=" * 100)
print("ARM ours_vmretail: the extra_prefs passed by the hunt (%s):" % (out / "prefs.json"))
for k, v in prefs.items():
if k == "zoom.stealth.gfx.feature_status":
print(" %s = <the declared table with %d feature(s) replaced by stock's decision: %s>" % (k, len(overridden), ", ".join(overridden) or "none"))
else:
print(" %s = %s" % (k, json.dumps(v)))
if not overridden:
print("WARNING: stock's decisions are the declared ones for every compositing feature: nothing of the table changed (the three prefs still apply)")
return 0
def main() -> int:
ap = argparse.ArgumentParser()
sub = ap.add_subparsers(dest="cmd", required=True)
b = sub.add_parser("build")
b.add_argument("--binary", default=os.environ.get("INVPW_BINARY_PATH", ""))
b.add_argument("--out", type=Path, required=True)
j = sub.add_parser("prefs-json")
j.add_argument("file", type=Path)
args = ap.parse_args()
if args.cmd == "prefs-json":
print(json.dumps(json.loads(args.file.read_text(encoding="utf-8"))["prefs"], separators=(",", ":")))
return 0
if not args.binary:
ap.error("--binary (or INVPW_BINARY_PATH)")
return build(args.binary, args.out)
if __name__ == "__main__":
sys.exit(main())
+195
View File
@@ -0,0 +1,195 @@
"""Run the same e2e through BOTH transports and compare, test by test.
⛔ THIS IS THE JUDGEMENT ITEM 8 WAITS FOR. The Node driver and the Python
server answer the same protocol, so the only honest way to know the second one
is correct is to run the same session through both and compare the results
name by name. Deleting the driver before this has run leaves the new path with
nothing to be measured against - a build that agrees with itself.
⛔ AND A DIFFERENCE IS NOT AUTOMATICALLY OURS. In two days this comparison has
already answered in both directions: `go_back` fails identically on both arms,
so it is the engine ([B185]); an unanswered dialog failed only on ours, so it
was ours. The table below keeps them apart instead of counting failures.
python scripts/judge_both_transports.py <firefox-binary>
python scripts/judge_both_transports.py <binary> -k juggler # a subset
⛔ THE MACHINE MUST BE QUIET. Both arms launch real browsers, and this project
has three recorded cases of measuring under load and reading the noise as a
product defect. The script refuses to start if a firefox is already alive.
⛔ AND THE ARMS RUN INTERLEAVED PER FILE, never all-of-A then all-of-B. Machine
load and disk cache drift over minutes; running one arm to completion first
puts every one of its tests in a different window from the other's, which turns
"this arm is worse" and "that minute was worse" into the same measurement.
"""
from __future__ import annotations
import argparse
import pathlib
import re
import subprocess
import sys
ROOT = pathlib.Path(__file__).resolve().parent.parent
#: The files worth running on both. ⛔ NOT the whole suite: most of it never
#: touches a transport, so running it twice would double the time and add no
#: information. These are the ones that drive a browser through the seam.
FILES = [
"tests/test_juggler_transport.py",
"tests/test_hidden_desktop.py",
"tests/test_new_page_defaults.py",
"tests/test_cross_origin_iframe.py",
"tests/test_file_chooser.py",
]
ESITO = re.compile(r"^(tests[^\s:]+)::(\S+)\s+(PASSED|FAILED|ERROR|XFAIL|XPASS|SKIPPED)",
re.M)
def quiet_machine() -> int:
r = subprocess.run(
["powershell", "-NoProfile", "-Command",
"(Get-Process firefox -ErrorAction SilentlyContinue | Measure-Object).Count"],
capture_output=True, text=True)
try:
return int((r.stdout or "0").strip() or 0)
except ValueError:
return -1
#: A checkout that still carries the Node driver, for the day this one does not.
#:
#: ⛔ THIS GATE EXISTS ONLY WHILE THERE ARE TWO ARMS, and the driver is on its
#: way out of the tree. When it goes, the second arm comes from a git worktree
#: at the last commit that carried it:
#:
#: git worktree add /tmp/judge <that commit>
#: INVPW_DRIVER_TREE=/tmp/judge python scripts/judge_both_transports.py <bin>
#:
#: A worktree rather than an installed release, because a published wrapper
#: pins a published core and a sealed engine and therefore cannot drive a
#: locally built binary - which is the only kind worth judging.
DRIVER_TREE_ENV = "INVPW_DRIVER_TREE"
def run_one(transport: str, binary: str, path: str, extra: list) -> dict:
import os
env = dict(os.environ)
env["INVPW_TRANSPORT"] = transport
env["INVPW_BINARY_PATH"] = binary
tree = os.environ.get(DRIVER_TREE_ENV)
if transport == "driver" and tree:
# ⛔ PREPENDED, so the older tree's package wins the import. The TESTS
# still come from this checkout: what is being borrowed is the driver,
# not the suite, and running the old suite would compare two different
# sets of assertions and call it a transport difference.
src = str(pathlib.Path(tree) / "src")
env["PYTHONPATH"] = os.pathsep.join(
[src] + ([env["PYTHONPATH"]] if env.get("PYTHONPATH") else []))
r = subprocess.run(
[sys.executable, "-m", "pytest", path, "-o", "addopts=", "-v",
"-p", "no:cacheprovider"] + extra,
cwd=ROOT, env=env, capture_output=True, text=True, timeout=3600)
return {name: verdict
for _, name, verdict in ESITO.findall(r.stdout + r.stderr)}
def main() -> int:
p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
p.add_argument("binary")
p.add_argument("-k", dest="selection", default=None)
p.add_argument("--allow-busy", action="store_true",
help="run even with a browser already alive. ⛔ The result "
"is then not a measurement, and the report says so.")
a = p.parse_args()
alive = quiet_machine()
if alive and not a.allow_busy:
print("REFUSING: %d firefox processes are already alive. A run under "
"load is not a measurement - this project has three recorded "
"cases of reading that noise as a product defect. Close them, or "
"pass --allow-busy and read the result as indicative." % alive)
return 2
if alive:
print("WARNING: %d firefox alive, the result is INDICATIVE" % alive)
extra = ["-k", a.selection] if a.selection else []
driver, juggler = {}, {}
for path in FILES:
if not (ROOT / path).exists():
print(" (skipped, absent: %s)" % path)
continue
print("running %s ..." % path, flush=True)
# ⛔ Interleaved per file: see the module docstring.
driver.update(run_one("driver", a.binary, path, extra))
juggler.update(run_one("juggler", a.binary, path, extra))
names = sorted(set(driver) | set(juggler))
ok = both_fail = only_ours = only_theirs = not_run = 0
rows = []
for name in names:
d = driver.get(name, "ABSENT")
j = juggler.get(name, "ABSENT")
good = ("PASSED", "XFAIL", "SKIPPED")
# ⛔ A TEST THE OTHER ARM NEVER RAN IS NOT A TEST THE OTHER ARM
# FAILED, and folding the two was making this gate lie in the
# comfortable direction. The driver arm imports an OLD `src/`, so any
# test file naming something added since that commit fails to COLLECT
# there and every test in it comes back ABSENT. Counted as "only the
# driver fails", they printed under "ours is BETTER here" - measured
# 2026-08-28 at 32 of them, essentially all of that kind. The number
# grows on its own as this tree moves, which is the property that
# turns a gate into decoration.
if "ABSENT" in (d, j) and not (d in good and j in good):
not_run += 1
rows.append(("NOT RUN", name, d, j))
elif d in good and j in good:
ok += 1
elif d not in good and j not in good:
both_fail += 1
rows.append(("ENGINE?", name, d, j))
elif d in good:
only_ours += 1
rows.append(("OURS", name, d, j))
else:
only_theirs += 1
rows.append(("DRIVER", name, d, j))
print()
print("=" * 78)
print("%-8s %-46s %-10s %s" % ("verdict", "test", "driver", "juggler"))
print("-" * 78)
for kind, name, d, j in rows:
print("%-8s %-46s %-10s %s" % (kind, name[:46], d, j))
print("-" * 78)
print("both green %d" % ok)
print("BOTH fail -> the ENGINE %d" % both_fail)
print("only OURS fails %d <- the ones that are ours to fix"
% only_ours)
print("only the DRIVER fails %d <- ours is BETTER here, verify why"
% only_theirs)
print("never ran on one arm %d <- NOT a comparison: the old arm "
"could not collect these" % not_run)
if not_run:
print()
print(" WARNING: %d of the rows above were never compared at all. The driver "
"arm's `src/` is a worktree that ages: a test naming anything "
"added since it was cut fails to collect there. When this number "
"approaches the total, this gate has stopped answering its own "
"question and the worktree needs re-cutting." % not_run)
print()
if only_ours:
print("VERDICT: not ready to delete the driver. %d tests pass through "
"it and fail through us." % only_ours)
return 1
print("VERDICT: no test passes on the driver and fails on us.")
if both_fail:
print(" (%d fail on BOTH: engine defects, not a reason to wait)"
% both_fail)
return 0
if __name__ == "__main__":
sys.exit(main())
+1 -1
View File
@@ -7,7 +7,7 @@ against anything of ours: its `conftest.py` imports the real `playwright`
package, so it has only ever measured Microsoft's client.
The plan it serves: replacing the channel between our client and our server
removes the boundary the old protocol comparison compared across, so the judgement has to
removes the boundary `diff_protocol.py` compares across, so the judgement has to
move up a level, from the PROTOCOL to the CONTRACT. This suite is that judge -
but only if we know, before touching anything, which of those 2173 pass TODAY.
A baseline taken afterwards proves nothing: every failure would be arguable.
+6 -6
View File
@@ -52,14 +52,14 @@ did so on evidence rather than on the code looking finished:
regenerating them. `injected.js` (the selector engines, actionability and
`expect` that run in the page), `keylayout.py` (both in `invisible_core.juggler`
since 0.30.0, with their extractors in the core's `scripts/`), and the four rules
the `user.js` writer was compared against (the comparison script and the frozen
rules file were later deleted; they are in git history).
- ⛔ And the second arm. A comparison between the two transports only exists
while there are two implementations to compare, and the scripts that did it
were deleted with the driver arm. To get one back:
`prefs_byte_parity.py` compares our `user.js` writer against - now frozen in
`tests/gates/driver_prefs_rules.json` with the sha of the bundle and of the
exact window they came from.
- ⛔ And the second arm. `judge_both_transports.py` and `diff_protocol.py` exist
only while there are two implementations to compare. To get one back:
git worktree add /tmp/judge <the last commit that carried _driver/>
INVPW_DRIVER_TREE=/tmp/judge python scripts/capture_protocol.py <bin>
INVPW_DRIVER_TREE=/tmp/judge python scripts/judge_both_transports.py <bin>
A worktree rather than an installed release, because a published wrapper pins
a published core and a sealed engine and therefore cannot drive a locally
@@ -1,88 +0,0 @@
"""`expose_binding` / `expose_function`: the script a page runs, and the way a call is read and answered.
THE RULE: THE PAGE SEES `foo` AND NOTHING ELSE. A page can list the names on its window, so a transport left there ("a binding
function", a controller) is the driver's signature. Nothing is left:
* One engine binding PER EXPOSED NAME (`Browser.addBinding` for a context, `Page.addBinding` for a page), under a native name chosen
for the session. The engine puts the native function on the window of every document of the page or context, present and future,
in every process, BEFORE any script of the page, and then runs the script below.
* The script takes the native function off the window at once and keeps it in a closure; defines `foo` (an ordinary function whose
source says nothing of what it is for); and hands the engine, through the native function, the function that answers a call
(the engine keeps it as an object of that context and reports its id: `payload.bindingEnd`).
* A call travels as a JSON string through the native function; the answer is `Runtime.callFunction` on the kept function.
LIMIT, SAID HERE. Arguments and results cross as JSON: `undefined`, functions and `NaN` arrive as `null`, and a `Date` as its ISO
string. A caller who needs one passes it as a string. Workers do not get the function (the engine installs bindings in the frames
of a page, as Playwright's does).
"""
from __future__ import annotations
import functools
import json
def install_script(native: str, name: str) -> str:
"""Run by the engine in each document, after it exports the native function `native` on the window."""
return (
"(() => {"
" const send = globalThis[%(native)s];"
" try { delete globalThis[%(native)s]; } catch (e) {}"
" if (typeof send !== 'function') return;"
" const text = JSON.stringify, waiting = new Map();"
" let last = 0;"
" const ask = (name, args) => new Promise((resolve, reject) => {"
" const id = ++last; waiting.set(id, [resolve, reject]);"
" try { send(text({ name, seq: id, args })); } catch (e) { waiting.delete(id); reject(e); } });"
" const f = { [%(name)s]: function (...args) { return ask(%(name)s, args); } }[%(name)s];"
" Object.defineProperty(globalThis, %(name)s,"
" { value: f, writable: true, configurable: true, enumerable: true });"
" send(function (id, ok, value) {"
" const w = waiting.get(id); if (!w) return; waiting.delete(id);"
" if (ok) w[0](value); else w[1](new Error(value)); });"
" })()") % {"native": json.dumps(native), "name": json.dumps(name)}
def remove_script(native: str, name: str) -> str:
"""The same binding again, as the engine runs the last one it was given for a native name: it takes the native function
off the window and the exposed function with it. A document that exists loses `foo`; one to come never gets it."""
return ("(() => { try { delete globalThis[%s]; } catch (e) {}"
" try { delete globalThis[%s]; } catch (e) {} })()") % (json.dumps(native), json.dumps(name))
#: `Runtime.callFunction` with the kept function as the first argument.
DELIVER = "(end, seq, ok, value) => end(seq, ok, value)"
def read_call(payload) -> tuple:
"""`(name, seq, args)` of a `Page.bindingCalled` payload, or `None` if it is not a call."""
try:
data = json.loads(payload) if isinstance(payload, str) else payload
return str(data["name"]), int(data["seq"]), list(data.get("args") or [])
except (TypeError, ValueError, KeyError):
return None
@functools.lru_cache(maxsize=16)
def engine_supports(engine_dir: str) -> bool:
"""Whether the engine in `engine_dir` has `Page.addBinding` and the binding that hands its end over.
Read from the engine's own files (the schema of its protocol, and its Runtime), so an engine without them is known BEFORE a
function is exposed: there is no fallback to a name on the window, and a clear refusal is the answer. An engine that cannot
be read is treated as one that cannot."""
if not engine_dir:
return False
try:
import os
from invisible_core.juggler._gen_protocol import protocol_source
_label, text = protocol_source(engine_dir)
if text.count("'addBinding'") < 2:
return False
omni = os.path.join(engine_dir, "omni.ja")
if os.path.isfile(omni):
from invisible_core.jar import open_jar
jar = open_jar(omni)
return b"bindingEnd" in jar.read("modules/juggler/content/Runtime.js")
return True
except BaseException:
return False
@@ -1,126 +0,0 @@
"""The one way this package starts a thread from a place that must not wait for it.
`Thread.start` does not return until the new thread is running (`self._started.wait()`), and on Windows under load that wait is
milliseconds long. Two places in the package cannot afford it: the engine connection's reader (an event is measured late by every
millisecond the reader is late) and the user's event loop (`InProcessTransport.connect`: four worker starts held the loop ~200 ms per
launch with four browsers in one process). Both hand the thread to `ThreadStarter`.
"""
from __future__ import annotations
import _thread as _raw_thread
import queue
import threading
from typing import Any, Callable, Optional
class ThreadStarter:
"""The ONE long-lived thread that starts the other threads it is handed.
⛔ NO `Thread.start` ON THE CALLER, AND THAT INCLUDES BUILDING THE STARTER. `start` and `start_built` only queue (a `Thread` that is
only BUILT waits for nothing); this thread starts what is queued. The starter's own thread is begun with `_thread.start_new_thread`
running `Thread.start`: the OS makes a thread and the caller returns at once, and the wait for the starter to run happens on that
raw thread, not on the caller. The starter is still a `threading.Thread` named `invpw-thread-starter` (it is alive a moment after
the constructor returns, not before).
It starts threads and does not run the work itself, on purpose: an adoption waits for the engine as long as the engine takes (a popup
whose destination never answers is waited for without a limit), and a worker that ran it would hold every later adoption behind it,
`new_page()` included. Each piece of work keeps the thread of its own and the name it always had.
"""
#: Every starter built and not yet ended (from the constructor, which returns before its thread runs, to the end of that thread).
#: Without it a starter whose thread has not begun yet is in no `threading.enumerate()` and nobody can count it: the census of
#: tests/_browser_census.py missed the leaked starters on a machine where the raw thread was late to run.
_open: "set" = set()
_open_lock = threading.Lock()
@classmethod
def open_starters(cls) -> list:
with cls._open_lock:
return list(cls._open)
def __init__(self, on_error: Callable[[str], None]) -> None:
with ThreadStarter._open_lock:
ThreadStarter._open.add(self)
self._queue: "queue.SimpleQueue" = queue.SimpleQueue()
self._on_error = on_error
self._stopped = False
self._thread = threading.Thread(target=self._run, daemon=True, name="invpw-thread-starter")
_raw_thread.start_new_thread(self._begin, ())
def _begin(self) -> None:
try:
self._thread.start()
except BaseException as failure:
self._ended()
self._report("%s could not be started: %s" % (self._thread.name, failure))
def _ended(self) -> None:
with ThreadStarter._open_lock:
ThreadStarter._open.discard(self)
def start(self, **thread_arguments: Any) -> None:
"""Called from any thread, the reader's and the loop's included: builds a daemon thread and queues it. Never waits."""
if self._stopped:
return
self._queue.put((threading.Thread(daemon=True, **thread_arguments), None))
def start_built(self, thread: threading.Thread, on_failure: Optional[Callable[[str], None]] = None) -> None:
"""Queue a thread the caller built (its name, its daemon flag, its target). Never waits.
`on_failure(why)` runs on the starter if this thread cannot be started, besides the starter's own report."""
if self._stopped:
return
self._queue.put((thread, on_failure))
def stop(self) -> None:
self._stopped = True
self._queue.put(None)
def _report(self, why: str) -> None:
try:
self._on_error(why)
except Exception:
pass
def _run(self) -> None:
try:
self._loop()
finally:
self._ended()
def _loop(self) -> None:
while True:
item = self._queue.get()
if item is None:
return
thread, on_failure = item
try:
thread.start()
except Exception as failure:
why = "%s could not be started: %s" % (thread.name, failure)
self._report(why)
if on_failure is not None:
try:
on_failure(why)
except Exception:
pass
class ThreadStarterLease:
"""One browser's use of the connection's starter: `start` while the browser's connection lives, nothing after it.
The starter is the SERVER's (one thread per connection, however many browsers it launches, `Server.thread_starter`) and ends with
the server. A browser's connection ends earlier than that: from then on a thread its events ask for must not start, which is
what `stop` on the browser's own starter used to give. The starter is asked for on the first `start`, so a browser that never
needs a thread makes none."""
def __init__(self, get_starter: Callable[[], ThreadStarter]) -> None:
self._get_starter = get_starter
self._stopped = False
def start(self, **thread_arguments: Any) -> None:
if not self._stopped:
self._get_starter().start(**thread_arguments)
def stop(self) -> None:
self._stopped = True
@@ -39,7 +39,6 @@ import time
from typing import Any, Callable, Dict, List, Optional
from . import perimeter, variants
from ._threads import ThreadStarter
# One class for a target that is gone, raised here for a disposed object and
# by the connection for a closed pipe. Defined there, the lower layer.
from invisible_core.juggler.connection import TargetClosedError # noqa: F401 - re-exported on purpose
@@ -275,30 +274,8 @@ class Server:
self._on_shutdown: list = []
#: What `shutdown` runs after every hook. See `after_shutdown`.
self._after_shutdown: list = []
self._starter: Optional[ThreadStarter] = None
self._starter_lock = threading.Lock()
self._is_shut_down = False
#: Why a thread the starter was handed could not be started (the last few).
self.start_errors: list = []
# ── plumbing ────────────────────────────────────────────────────────────
@property
def thread_starter(self) -> ThreadStarter:
"""The ONE thread that starts threads for this connection: the transport's workers and every browser's reader hand theirs to it.
Built on first use, ended by `shutdown`. Served by several clients (`remote._SharedServer`) it is the same one: the server
is the connection's owner there too, and its browser's contexts come and go under it."""
with self._starter_lock:
if self._starter is None:
self._starter = ThreadStarter(self._start_failed)
if self._is_shut_down:
self._starter.stop()
return self._starter
def _start_failed(self, why: str) -> None:
if len(self.start_errors) < 32:
self.start_errors.append(why)
def attach(self, transport: Any) -> None:
self._transport = transport
@@ -459,11 +436,6 @@ class Server:
except Exception:
pass
self._after_shutdown.clear()
with self._starter_lock:
self._is_shut_down = True
starter = self._starter
if starter is not None:
starter.stop()
# ── the entry point ─────────────────────────────────────────────────────
def handle(self, message: Dict) -> Any:
@@ -169,6 +169,13 @@ FIXED_AT_BUILD = {
#: Our debt, plainly. Nothing external blocks these: they are not written yet.
#: This set is the honest list of what "100% compatible" does not cover today.
NOT_WIRED_YET = {
"exposeBinding",
# ⛔ `reject` shares its handler with `resolve`, and that is how it stayed
# invisible: the first scan keyed the method table by python name, so the
# second operation routed to `op_binding_reply` overwrote the first. Two
# operations, one handler, one of them unaccounted for.
"reject",
"resolve",
"setExtraHTTPHeaders",
}
@@ -837,6 +837,7 @@ 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", "")
+96 -244
View File
@@ -36,7 +36,6 @@ import pathlib
import queue
import sys
import tempfile
import secrets
import threading
import collections
import time
@@ -47,8 +46,7 @@ from invisible_core.juggler import PageActs, popup_number
from invisible_core.juggler import connection as juggler
from invisible_core.juggler.actions import Actions
from invisible_core.juggler.deadline import Deadline
from . import _bindings, dialogs
from ._threads import ThreadStarterLease
from . import dialogs
from .pointer import Pointer
from .dispatcher import (Dispatcher, ExpectNotMet, ProtocolException,
Server, current_call)
@@ -549,12 +547,6 @@ def _run_callers_code(injected: InjectedScript, frame_id: str, params: Dict,
return remote
def _round_px(value: float) -> int:
"""To the nearest whole pixel, halves up (Python's `round` goes to even: 0.5 -> 0, 1.5 -> 2)."""
import math
return int(math.floor(value + 0.5))
class ElementHandleDispatcher(Dispatcher):
TYPE = "ElementHandle"
METHODS = {
@@ -568,7 +560,6 @@ class ElementHandleDispatcher(Dispatcher):
"inputValue": "op_input_value",
"getAttribute": "op_get_attribute",
"scrollIntoViewIfNeeded": "op_scroll_into_view",
"screenshot": "op_screenshot",
"ownerFrame": "op_owner_frame",
"contentFrame": "op_content_frame",
"getProperty": "op_get_property",
@@ -808,44 +799,6 @@ class ElementHandleDispatcher(Dispatcher):
params.get("rect"))
return None
def op_screenshot(self, params: Dict) -> Any:
"""A picture of this element: scroll it into view, take its box, and
ask the page's own screenshot for exactly that rectangle.
⛔ THE BOX IS IN THE MAIN FRAME'S VIEWPORT, AND THE ENGINE'S CLIP IS IN
DOCUMENT COORDINATES. `Page.getContentQuads` answers in the main frame's
space whatever frame the element is in (it carries a node up every
`<iframe>`, across processes), so the same box is right for an element
of the page, of a frame of another site and of a frame nested in it.
What is missing to reach the document is the main frame's scroll, read
after the element has been scrolled in. The screenshot itself is the
page's (`PageDispatcher.op_screenshot`): a second path would be a second
place for the type, the quality and the scale to disagree.
The rectangle is rounded to whole pixels outward-stable, the way
Playwright's screenshotter does: the left and top edges to the nearest
pixel, the size from the rounded right and bottom edges.
"""
# An element with no layout object (display: none, detached) cannot be scrolled to: the engine says so
# with an exception of its own. For the caller that is the same answer as an empty box.
try:
self.injected.scroll_into_view(self.frame.frame_id, self.object_id, None)
box = self.injected.bounding_box(self.frame.frame_id, self.object_id)
except Exception:
box = None
if not box or box["width"] <= 0 or box["height"] <= 0:
raise ValueError("Element is not visible")
page = self.page
scroll = page.injected.evaluate(
page.frame.frame_id, "({x: window.scrollX, y: window.scrollY})") or {"x": 0, "y": 0}
left = _round_px(box["x"] + scroll["x"])
top = _round_px(box["y"] + scroll["y"])
right = _round_px(box["x"] + scroll["x"] + box["width"])
bottom = _round_px(box["y"] + scroll["y"] + box["height"])
clip = {"x": left, "y": top,
"width": max(right - left, 1), "height": max(bottom - top, 1)}
return page.op_screenshot(dict(params, clip=clip))
def op_owner_frame(self, params: Dict) -> Any:
return {"frame": self.frame.channel}
@@ -1105,9 +1058,6 @@ class FrameDispatcher(Dispatcher):
#: The load states the client has been told this frame has (the initializer's, then each `loadstate`): what the hand-over of the
#: page from its buffer to its dispatcher compares the lifecycle's states with (`PageDispatcher._reconcile_frame`).
self.told_states = set(load_states or ["commit"])
#: The address the client has been TOLD (the initializer's, then each `navigated` once it has gone up). `url`
#: is set a moment before the event is sent; a BindingCall waits for this one (`_announce_binding`).
self.committed_url = url
#: Same reason, and both navigation events report it: a same-document
#: navigation carries no name, so it has to repeat the one the frame
#: already has rather than blank it.
@@ -2734,48 +2684,6 @@ def _target_is_gone(error: BaseException) -> bool:
return True
text = str(error).lower()
return "cannot find session" in text or "target closed" in text or "session closed" in text
class BindingCallDispatcher(Dispatcher):
"""One call of an exposed function, waiting for the client's answer.
The client runs the Python function and sends `resolve` or `reject`; the answer goes back into the promise the page is
holding, in the context the call came from (`controller.deliver`, see `_bindings`)."""
TYPE = "BindingCall"
METHODS = {"resolve": "op_resolve", "reject": "op_reject"}
def __init__(self, server, page: "PageDispatcher", frame: "FrameDispatcher", context_id: str, native: str,
name: str, seq: int, args: List[Any]) -> None:
self.page = page
self.context_id = context_id
self.native = native
self.seq = seq
super().__init__(server, page, {
"frame": frame.channel, "name": name,
"args": [_serialize(a) for a in args]})
@staticmethod
def _deliver(page: "PageDispatcher", context_id: str, native: str, seq: int, ok: bool, value: Any) -> None:
end = page._binding_ends.get((context_id, native))
if end is None:
return # the document left (or never handed its end over): nobody is waiting
try:
page.injected.call_raw(context_id, _bindings.DELIVER,
[{"objectId": end}, {"value": seq}, {"value": ok}, {"value": value}],
by_value=True, timeout=10.0)
except Exception:
pass # the document left: nobody is waiting for the answer
def op_resolve(self, params: Dict) -> Any:
self._deliver(self.page, self.context_id, self.native, self.seq, True, _deserialize(params.get("result")))
self.dispose()
return None
def op_reject(self, params: Dict) -> Any:
error = (params.get("error") or {}).get("error") or {}
self._deliver(self.page, self.context_id, self.native, self.seq, False,
error.get("message") or error.get("name") or "binding failed")
self.dispose()
return None
class PageDispatcher(Dispatcher):
@@ -2810,6 +2718,8 @@ class PageDispatcher(Dispatcher):
"touchscreenTap": "op_touchscreen_tap",
"requests": "op_requests",
"__waitInfo__": "op_noop",
"reject": "op_binding_reply",
"resolve": "op_binding_reply",
"requestGC": "op_request_gc",
"addScriptTag": "op_add_script_tag",
"addStyleTag": "op_add_style_tag",
@@ -3013,14 +2923,6 @@ class PageDispatcher(Dispatcher):
#: to answer after a reader's pause, see `dialogs.plan_answer_ms`.
self._dialogs_open: Dict[str, Any] = {}
self._dialogs_seen = 0
#: `page.expose_binding` names -> the script that makes the function (see `_bindings`).
self._exposed: Dict[str, str] = {}
#: The calls of exposed functions, announced in the order they were made, by one worker (see `_on_binding_called`).
self._binding_jobs: "queue.Queue" = queue.Queue()
self._binding_running = False
self._binding_lock = threading.Lock()
#: (execution context, native name) -> objectId of the function that answers the calls made there (see `_bindings`).
self._binding_ends: Dict[tuple, str] = {}
self.main_frame_id = self._main_frame_unless_gone()
# ⛔ The Frame is created BEFORE the Page and adopted after: the Page
# initializer has to name a mainFrame the client can already resolve.
@@ -3277,7 +3179,6 @@ class PageDispatcher(Dispatcher):
frame.url, frame.name, frame.told_commit = url, name, commit
navigation = known._commits[-1][1] if known._commits else None
frame.emit("navigated", {"url": url, "name": name, "newDocument": self.navigation_document(navigation)})
frame.committed_url = url
for state in self.CANON_STATES:
if state in known.states and state not in frame.told_states:
frame.emit("loadstate", {"add": state})
@@ -3360,7 +3261,6 @@ class PageDispatcher(Dispatcher):
"newDocument": self.navigation_document(navigation),
})
child.emit("loadstate", {"add": "commit"})
child.committed_url = child.url
#: Events held while the page is being built. The birth of a page is a
#: burst of a few dozen; a page that never finishes building must not
@@ -3541,11 +3441,9 @@ class PageDispatcher(Dispatcher):
# Doing it here would block the reader waiting for a message the
# reader is the one who has to receive.
# ⛔ AND NOT STARTED HERE EITHER: `Thread.start` waits for the new thread to run, and this is the reader.
# The browser's thread starter does it (`ThreadStarter`).
# The browser's thread starter does it (`_ThreadStarter`).
self.context.browser.thread_starter.start(
target=self._announce_file_chooser, args=(params,))
elif method == "Page.bindingCalled":
self._on_binding_called(params)
elif method == "Page.crashed":
self.emit("crash")
# ⛔ `Page.frameAttached` / `Page.frameDetached` ARE NOT READ HERE: the
@@ -3574,15 +3472,6 @@ class PageDispatcher(Dispatcher):
# cannot disagree about a request, a redirect or a replay.
if method == "Network.requestWillBeSent" and params.get("isIntercepted"):
self._let_through(params.get("requestId"))
elif (method == "Network.requestWillBeSent" and params.get("method") == "OPTIONS"
and not params.get("isIntercepted")):
# ⛔ AS PLAYWRIGHT'S OWN SERVER (ffNetworkManager `_onRequestWillBeSent`: `if (event.method === "OPTIONS" &&
# !event.isIntercepted) return;`): an OPTIONS request that no route holds is a CORS preflight, which the browser
# makes for the page and the page cannot see; a client never hears of it. Reported here, a page with a
# preflighted fetch showed one request more than on stock Firefox (10 per page on cnbc.com, 18 on scmp.com),
# in `page.on("request")`, in `route`, in a request counter. Its response and its end find no request and are
# dropped with it.
pass
elif method == "Network.requestWillBeSent":
request = RequestDispatcher(self.server, self, params)
self._requests[params.get("requestId")] = request
@@ -4227,83 +4116,39 @@ class PageDispatcher(Dispatcher):
def op_requests(self, params: Dict) -> Any:
return {"requests": [r.channel for r in self._request_log]}
# ── expose_binding / expose_function ────────────────────────────────────
def op_binding_reply(self, params: Dict) -> Any:
"""⛔ `resolve` and `reject` are the REPLY half of `expose_binding`,
and they are unreachable while that is refused: they arrive on a
BindingCall object, and no BindingCall is ever created. This exists so
the refusal names the feature instead of answering "Page has no method
resolve", which would send the reader looking in the wrong place."""
raise ProtocolException(
"this is the reply path of expose_binding(), which is not "
"implemented: no binding is ever installed, so nothing can call "
"back into one")
def op_expose_binding(self, params: Dict) -> Any:
"""`page.expose_binding` / `page.expose_function`: the function `name` on this page, in the page's own world
(a site can see it, which is what the caller asked for, and nothing else: see `_bindings`). The engine installs it
in every document of the page, present and future, in every process the frames live in."""
name = params["name"]
native = self.context.binding_native(name)
self.context.require_binding_engine()
self._exposed[name] = native
self.send("Page.addBinding", {"name": native, "script": _bindings.install_script(native, name)})
"""`expose_binding` / `expose_function`.
def undo() -> None:
self._exposed.pop(name, None)
self.send("Page.addBinding", {"name": native, "script": _bindings.remove_script(native, name)})
handle = DisposableDispatcher(self.server, self, undo)
return {"disposable": handle.channel}
⛔ THE PAGE-FACING HALF IS NOT THE HARD PART. Installing a function on
the page is one init script; what makes this a real feature is the
REPLY path - the page calls it, the server raises `bindingCalled`, the
client runs Python, and the answer has to travel back into the promise
the page is holding. That is what `reject` and `resolve` are for, and
they are only reachable through the BindingCall object this creates.
def _on_binding_called(self, params: Dict) -> None:
"""The page called an exposed function. Announced to the client from a worker, in order, and not here.
OFF THE READER THREAD, because the announcement may need an answer from the engine (the address of the document
that called, see `_announce_binding`), which only the reader can deliver. In order, because two calls made one
after the other are announced one after the other: one worker per page, started by the first call and gone after
thirty idle seconds."""
payload = params.get("payload")
if isinstance(payload, dict) and payload.get("bindingEnd"):
# The page-side end of a binding, handed over by its script once, before any call: kept for the answers.
self._binding_ends[(params.get("executionContextId"), params.get("name"))] = payload["bindingEnd"]
return
call = _bindings.read_call(payload)
if call is None:
return
self._binding_jobs.put((params.get("executionContextId"), call))
with self._binding_lock:
if self._binding_running:
return
self._binding_running = True
# ⛔ NOT `Thread.start` HERE: this is the reader, and the browser's thread starter does it (`ThreadStarter`).
self.context.browser.thread_starter.start(target=self._binding_loop)
def _binding_loop(self) -> None:
while True:
try:
context_id, call = self._binding_jobs.get(timeout=30.0)
except queue.Empty:
with self._binding_lock:
if self._binding_jobs.empty():
self._binding_running = False
return
continue
try:
self._announce_binding(context_id, *call)
except Exception:
pass
def _announce_binding(self, context_id: str, name: str, seq: int, args: List[Any]) -> None:
"""A BindingCall to the client, or an error to the page when nobody exposed `name` here (left alone the
page's promise would wait for ever).
THE FRAME THE CLIENT IS TOLD OF HAS TO HAVE ITS ADDRESS. A script that calls the function in its first lines
runs before the lifecycle has told the client the document committed, and the call would name a frame whose
`url` is still the empty one. The address is asked of the document that called, and the call waits (a second
at most) until the client has been told that same address."""
injected = self.injected
native = self._exposed.get(name) or self.context._exposed.get(name)
if native is None:
return # nothing exposed under this name here: the page's promise cannot be answered, and was not offered
frame = self.frame_for(injected.frame_of_context(context_id) or self.frame.frame_id)
try:
href = injected.call_raw(context_id, "() => location.href", [], by_value=True, timeout=5.0).get("value")
except Exception:
href = None
end = time.monotonic() + 1.0
while href and frame.committed_url != href and time.monotonic() < end:
time.sleep(0.005)
binding = BindingCallDispatcher(self.server, self, frame, context_id, native, name, seq, args)
self.emit("bindingCall", {"binding": binding.channel})
⛔ AND THE FUNCTION MUST LIVE IN THE PAGE'S WORLD. Installed behind the
Xray it would be invisible to the site, which is the whole point of the
call. Juggler's `Page.addBinding` does that, so the world is not ours
to choose here - which is also why it cannot be hidden from the page:
a binding is a name the site can enumerate, and a caller asking for one
is asking for that trade.
"""
raise ProtocolException(
"expose_binding() is not implemented yet: the page-facing half is "
"one init script, but the reply path - bindingCalled, then resolve "
"or reject into the promise the page holds - is not wired, and a "
"binding that never answers hangs the page that called it")
def op_bring_to_front(self, params: Dict) -> Any:
self.send("Page.bringToFront", {})
@@ -4497,10 +4342,9 @@ class PageDispatcher(Dispatcher):
# too, because `_connection.py` only drops an object when it is told
# to. The driver disposes Page, BrowserContext, Browser, ElementHandle
# and APIRequestContext; the only one we were missing was Page, which
# is why the protocol comparison that used to exist needed a fifth
# dimension to see it: the other four compared `__create__`, initializers,
# events and parentage, and the event comparison skips every method
# starting with `__`.
# is why `diff_protocol.py` grew a fifth dimension to see it: the other
# four compare `__create__`, initializers, events and parentage, and
# the event comparison skips every method starting with `__`.
@@ -4644,7 +4488,6 @@ class BrowserContextDispatcher(Dispatcher):
"close": "op_close",
"updateSubscription": "op_noop",
"addInitScript": "op_context_init_script",
"exposeBinding": "op_expose_binding",
"addCookies": "op_add_cookies",
"cookies": "op_cookies",
"clearCookies": "op_clear_cookies",
@@ -4702,51 +4545,11 @@ class BrowserContextDispatcher(Dispatcher):
#: The caller's context-level init scripts, in order. The engine's
#: command replaces the list, so the accumulation lives here.
self._init_scripts: List[str] = []
#: `context.expose_binding` names -> the engine's native name for each (see `binding_native`).
self._exposed: Dict[str, str] = {}
self._native_names: Dict[str, str] = {}
self._transport_lock = threading.Lock()
@property
def conn(self) -> "juggler.Connection":
return self.browser.conn
def binding_native(self, name: str) -> str:
"""The name of the engine's native function for the exposed function `name`: unique to this context and this
session, chosen here (the page never sees it: its script takes it off the window before any script of the page)."""
with self._transport_lock:
native = self._native_names.get(name)
if native is None:
native = "__%s_%d" % (self.browser.binding_token, len(self._native_names))
self._native_names[name] = native
return native
def require_binding_engine(self) -> None:
"""Exposed functions need the engine that hands the page-side end of a binding over and has `Page.addBinding`.
With an engine that does not, they REFUSE: the way around it is a global on the window that a page can list,
and that is the tell this design exists to avoid."""
if not _bindings.engine_supports(self.browser.engine_dir):
raise ProtocolException(
"expose_function() and expose_binding() need a newer engine than this one (the one with "
"Page.addBinding and the binding that hands its end over): this engine would have to leave a "
"name on the page's window to answer the calls, and a page can list its globals")
def op_expose_binding(self, params: Dict) -> Any:
"""`context.expose_binding` / `context.expose_function`: the function `name` on every page of the context,
present and future. The engine installs it in every document of every page, in every process (see
`_bindings`); one registration, no init script, nothing run by this server in the documents."""
name = params["name"]
native = self.binding_native(name)
self.require_binding_engine()
self._exposed[name] = native
self._browser_send("Browser.addBinding", {"name": native, "script": _bindings.install_script(native, name)})
def undo() -> None:
self._exposed.pop(name, None)
self._browser_send("Browser.addBinding", {"name": native, "script": _bindings.remove_script(native, name)})
handle = DisposableDispatcher(self.server, self, undo)
return {"disposable": handle.channel}
def released(self) -> None:
"""⛔ THE BROWSER'S LIST LET GO TOO. Every way a context ends passes
here, and `browser.contexts` kept each one - with its options, its
@@ -4780,6 +4583,11 @@ class BrowserContextDispatcher(Dispatcher):
self._browser_send("Browser.setInitScripts",
{"scripts": [{"script": s}
for s in self._init_scripts]})
for page in list(self.pages):
try:
page.injected.add_init_script(source)
except Exception:
pass
handle = DisposableDispatcher(self.server, self,
lambda: self._remove_init_script(source))
return {"disposable": handle.channel}
@@ -4791,6 +4599,11 @@ class BrowserContextDispatcher(Dispatcher):
self._browser_send("Browser.setInitScripts",
{"scripts": [{"script": s}
for s in self._init_scripts]})
for page in list(self.pages):
try:
page.injected.remove_init_script(source)
except Exception:
pass
def op_set_storage_state(self, params: Dict) -> Any:
"""⛔ COOKIES ONLY, and it refuses the rest rather than dropping it.
@@ -5017,6 +4830,51 @@ NO_OVERRIDE = "no-override"
NO_OVERRIDE_OPTIONS = ("colorScheme", "reducedMotion", "forcedColors")
class _ThreadStarter:
"""The ONE long-lived thread that starts the other threads the engine's events ask for.
⛔ NO `Thread.start` ON THE CONNECTION'S READER THREAD. `Thread.start` does not return until the new thread is running
(`self._started.wait()`), and on Windows under load that wait is milliseconds long: it was the larger part of the reader's delay, and
every millisecond the reader is late is a millisecond a `networkidle` quiet is measured late (7 misses in 400 with four browsers at
once, none in 400 when the start did not wait). A listener that runs on the reader and needs work done elsewhere hands it to `start`
here: a `Thread` that is only BUILT on the reader (building waits for nothing) goes into a queue, and this thread starts it.
It starts threads and does not run the work itself, on purpose: an adoption waits for the engine as long as the engine takes (a popup
whose destination never answers is waited for without a limit), and a worker that ran it would hold every later adoption behind it,
`new_page()` included. Each piece of work keeps the thread of its own and the name it always had.
"""
def __init__(self, on_error: Callable[[str], None]) -> None:
self._queue: "queue.SimpleQueue" = queue.SimpleQueue()
self._on_error = on_error
self._stopped = False
self._thread = threading.Thread(target=self._run, daemon=True, name="invpw-thread-starter")
self._thread.start()
def start(self, **thread_arguments: Any) -> None:
"""Called from any thread, the reader's included: builds the thread and queues it. Never waits."""
if self._stopped:
return
self._queue.put(threading.Thread(daemon=True, **thread_arguments))
def stop(self) -> None:
self._stopped = True
self._queue.put(None)
def _run(self) -> None:
while True:
thread = self._queue.get()
if thread is None:
return
try:
thread.start()
except Exception as failure:
try:
self._on_error("%s could not be started: %s" % (thread.name, failure))
except Exception:
pass
class BrowserDispatcher(Dispatcher):
TYPE = "Browser"
METHODS = {"newContext": "op_new_context", "close": "op_close",
@@ -5089,10 +4947,6 @@ class BrowserDispatcher(Dispatcher):
#: Where this session measures a proxy's UDP exit from (the launch's `udp_stun_servers`, "ip:port"
#: strings; None = the two public defaults): the launch and every context proxy use the same list.
self.udp_stun_servers = udp_stun_servers
#: Chosen for this browser: the prefix of the native names of its exposed functions (see `_bindings`), and the
#: directory of its engine (set by `launch`), which says whether the engine has what they need.
self.binding_token = secrets.token_hex(6)
self.engine_dir = ""
#: Whether this browser's pages walk the pointer onto their targets
#: (`pointer.py`): the launcher chose the Python generator. Off for a
#: browser built without saying so, which acts as the caller wrote.
@@ -5209,9 +5063,8 @@ class BrowserDispatcher(Dispatcher):
# subscriber seeing an event before this one records the session, and
# recording earlier can only shorten the window in which `session_for`
# is waiting for something that has already arrived.
# ⛔ NOT A STARTER OF ITS OWN: the connection's server owns the one (`Server.thread_starter`), and this is the browser's lease on
# it, ended by the browser's connection.
self._starter = ThreadStarterLease(lambda: server.thread_starter)
self._starter = _ThreadStarter(
lambda why: conn.handler_errors.append(why) if len(conn.handler_errors) < 32 else None)
conn.add_close_listener(self._starter.stop)
conn.add_listener(self._route_browser_event)
# The last step of starting the browser, under what is left of the
@@ -5237,8 +5090,8 @@ class BrowserDispatcher(Dispatcher):
self._adopt_enabled = True
@property
def thread_starter(self) -> "ThreadStarterLease":
"""What starts threads on behalf of the engine's reader: the connection's one starter (`Server.thread_starter`), while this browser lives."""
def thread_starter(self) -> "_ThreadStarter":
"""The one thread that starts threads on behalf of the engine's reader (`_ThreadStarter`)."""
return self._starter
def require_interception(self, what: str) -> None:
@@ -6300,7 +6153,6 @@ class BrowserTypeDispatcher(Dispatcher):
except BaseException:
conn.close()
raise
browser.engine_dir = os.path.dirname(str(executable))
return {"browser": browser.channel}
+14 -79
View File
@@ -43,7 +43,6 @@ 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
@@ -51,7 +50,6 @@ 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
@@ -103,33 +101,15 @@ class InProcessTransport(Transport):
self._stopped = threading.Event()
self._stopped_future: asyncio.Future = loop.create_future()
self._threads: list = []
#: The thread that runs the server's shutdown (see `request_stop`); None until the stop is requested.
self._shutdown_thread: Optional[threading.Thread] = None
#: Set once the raw thread has begun (or failed to begin) the shutdown thread, so the join below knows whether to wait.
self._shutdown_begun = threading.Event()
server.attach(self)
# ── the five methods the seam declares ──────────────────────────────────
async def connect(self) -> None:
"""⛔ NO `Thread.start` ON THE LOOP, NOT EVEN ONE. `connect` is a coroutine of the caller's event loop, and
`Thread.start` does not return until the new thread is running (`self._started.wait()`): measured with four
browsers in one process under CPU load on Windows, the four starts held the loop ~200 ms per launch (4.4% of the
main thread's wall time), the same wait the engine's reader is spared by the same starter.
The four `Thread` objects are only BUILT here (building waits for nothing), so `request_stop` still knows how many
sentinels the pool needs, and the server's one starter (`Server.thread_starter`, shared with every browser's reader) starts them. Messages sent before a worker runs wait in the queue and are
answered when it does, which is what `send` always relied on."""
self._threads = [
threading.Thread(target=self._work, name="juggler-%d" % i, daemon=True)
for i in range(self.WORKERS)]
server_starter = self._server.thread_starter
for t in self._threads:
server_starter.start_built(t, self._workers_could_not_start)
def _workers_could_not_start(self, why: str) -> None:
"""No worker may ever answer a queued message, so the session cannot go on: end it, the way a transport that lost
its other end ends, instead of leaving every call to wait for a reply that cannot come."""
self.request_stop()
for i in range(self.WORKERS):
t = threading.Thread(target=self._work, name="juggler-%d" % i,
daemon=True)
t.start()
self._threads.append(t)
async def run(self) -> None:
"""⛔ Must not return until the transport is stopped: `Connection.run`
@@ -137,14 +117,6 @@ 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()
@@ -152,58 +124,21 @@ 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:
_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()
self._server.shutdown()
except Exception:
pass
if not self._stopped_future.done():
self._loop.call_soon_threadsafe(self._settle)
def _settle(self) -> None:
if not self._stopped_future.done():
self._stopped_future.set_result(None)
def _join_workers(self) -> None:
"""What `wait_until_stopped` waits for besides the stop itself: the workers (and the shutdown thread, which has settled the stop
and is ending). Blocking, so never on the loop."""
for t in self._threads:
# A worker the starter never started (the transport stopped first) has nothing to join.
if t.is_alive():
t.join(timeout=5)
shutdown = self._shutdown_thread
if shutdown is not None:
self._shutdown_begun.wait(5) # the raw thread that begins it may be a moment late
if shutdown.is_alive():
shutdown.join(timeout=5)
async def wait_until_stopped(self) -> None:
await self._stopped_future
await off_the_loop(self._join_workers)
for t in self._threads:
t.join(timeout=5)
def send(self, message: Dict) -> None:
"""⛔ ENQUEUE ONLY. Running the operation here would run it on the
@@ -347,8 +282,8 @@ def make_transport(loop: asyncio.AbstractEventLoop) -> "InProcessTransport":
"only transport - unset %s and it runs. To get the old arm back "
"for a COMPARISON (the only thing it was still for): check out "
"the last commit that carried it into a git worktree and point "
"INVPW_DRIVER_TREE at it, which `scripts/capture_protocol.py` "
"reads." % CHOICE_ENV)
"INVPW_DRIVER_TREE at it. Both `judge_both_transports.py` and "
"`diff_protocol.py` read that variable." % CHOICE_ENV)
from .server import JugglerServer
if (os.environ.get(WIRE_ENV) or "").strip().lower() == "json":
return JsonWireTransport(loop, JugglerServer())
@@ -26,7 +26,7 @@ What each 1.62 addition becomes here:
target into view first, which is `auto`; `none` asks to act on the element
where it is, and honouring it needs an action path that does not scroll,
which does not exist. The action still happens, scrolled.
* `noGlobal` on exposeBinding: not read. The function is always defined on the page's `window`, as `expose_function` documents.
* `noGlobal` on exposeBinding: moot, `exposeBinding` is refused as a whole.
* `type` "webp" on screenshot: REFUSED. The engine captures PNG and JPEG, and
answering a webp request with PNG bytes would hand the caller a file that
is not the format it asked for.
@@ -102,5 +102,5 @@ class Transport(ABC):
#
# ⛔ To get the old arm back for a comparison - which is the only thing it
# was still for - check out the last commit that carried it into a git
# worktree and point `INVPW_DRIVER_TREE` at it. `scripts/capture_protocol.py`
# reads that variable.
# worktree and point `INVPW_DRIVER_TREE` at it. `judge_both_transports.py`
# and `diff_protocol.py` both read that variable.
+28 -61
View File
@@ -20,7 +20,6 @@ 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,
@@ -437,72 +436,19 @@ 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, None
return False
# 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, 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
return True
vd = make_virtual_display()
if vd is not None:
vd.start()
self._virtual_display = vd
return False
def _default_context_kwargs(self) -> Dict[str, Any]:
# The screen and viewport in CSS pixels, derived once in the core:
@@ -600,3 +546,24 @@ 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
+12 -11
View File
@@ -15,7 +15,6 @@ 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
@@ -130,7 +129,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 = await self._resolve_headless_async()
pw_headless = self._resolve_headless()
prefs = self._build_prefs()
playwright_proxy = _configure_proxy_shared(self._proxy, prefs)
self._session_token = SessionToken.mint()
@@ -154,6 +153,7 @@ 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,6 +167,7 @@ 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
@@ -350,18 +351,18 @@ class InvisiblePlaywright(_session.CommonLaunch):
if self._pw is not None:
await close(self._pw.stop())
self._pw = 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))
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
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:
await off_the_loop(self._lifetime_guard.reap, self._session_token)
except asyncio.CancelledError as stop:
cancelled = stop
self._lifetime_guard.reap(self._session_token)
except Exception:
pass
self._session_token = SessionToken()
+5 -3
View File
@@ -358,6 +358,7 @@ 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(
@@ -373,6 +374,7 @@ 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
@@ -569,12 +571,12 @@ class InvisiblePlaywright(_session.CommonLaunch):
except Exception:
pass
self._pw = None
display = self._take_display()
if display is not None:
if self._virtual_display is not None:
try:
display.stop()
self._virtual_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
@@ -1,114 +0,0 @@
"""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]
+7 -16
View File
@@ -1,44 +1,35 @@
"""The check that no test module leaves a browser open.
A connection's server owns ONE daemon thread, "invpw-thread-starter" (`Server.thread_starter`, made when the first thread is asked of it), and
stops it only on `shutdown`. A unit test that builds a dispatcher on a server and never shuts the server down leaves that thread alive, and the thread keeps the connection,
A `BrowserDispatcher` starts one daemon thread, "invpw-thread-starter", and stops it only when the connection's close listeners fire. A
unit test that builds a dispatcher on a fake connection and never closes it leaves that thread alive, and the thread keeps the connection,
the browser and every context alive for the rest of the worker (a gc census of a closed context once found 7 of them, and one file alone
left 635). So the number of live starters, counted when the last test of a module has torn down, must be what it was before the module.
Module level and not per test: a module-scoped browser (the e2e ones) is legitimately open between its tests and closed at the end.
"""
import sys
import threading
import time
import pytest
STARTER_NAME = "invpw-thread-starter"
_THREADS_MODULE = "invisible_playwright._juggler._threads"
# `stop` is asynchronous: it queues a None and the thread leaves on its next turn. A moment, not a wait for a leak that will not leave.
_JOIN_SECONDS = 5.0
def starters_alive():
"""The starters built and not ended, counted from their construction: `ThreadStarter` begins its thread without waiting for it, so
one that has not run yet is in no `threading.enumerate()` (a census of live threads missed 2 leaks on a Linux runner).
NO IMPORT HERE. A module that never loaded `_threads` cannot have built a starter, so the answer is empty without importing anything:
the census runs from conftest in every job, including ones that install pytest alone and have no `invisible_core` (the `version`
job failed on `invisible_playwright._pin` when this function imported the package)."""
threads = sys.modules.get(_THREADS_MODULE)
if threads is None:
return []
return threads.ThreadStarter.open_starters()
return [t for t in threading.enumerate() if t.name == STARTER_NAME and t.is_alive()]
def wait_until_back_to(before, seconds=_JOIN_SECONDS):
"""The starters still open after `seconds` beyond the `before` that were there already (0 when the module closed everything)."""
"""The starters still alive after `seconds` beyond the `before` that were there already (0 when the module closed everything)."""
deadline = time.monotonic() + seconds
while True:
extra = len(starters_alive()) - before
if extra <= 0 or time.monotonic() >= deadline:
return max(extra, 0)
time.sleep(0.05)
for t in starters_alive():
t.join(0.05)
@pytest.fixture(scope="module", autouse=True)
-106
View File
@@ -1,106 +0,0 @@
"""The CPU the engine's processes use, by type of process, read from the processes of this test.
A Firefox browser is a tree: the parent, content processes (`tab`), and, where there are any, a GPU process (`gpu`), a socket process,
a media process (`rdd`) and utility processes. Every one but the parent is started with `-contentproc ... <type>` as the last argument
of its command line, so the type is read from there; no `-contentproc` is the parent.
`CpuSampler` reads the cumulative CPU time (user + kernel) of every engine process below the process that runs the test, every
`period` seconds, from a thread. A process that ends inside the window keeps the last value read before its end (at most one period of
its end is lost). The CPU of a type in a window is the sum, over its processes, of the last value minus the value at the start of the
window (zero for a process born after it).
The process of a test is the root: the browser a test starts is its descendant, and so is nothing else of the engine (an e2e run opens
several browsers at once, in several workers, each in its own process tree).
"""
from __future__ import annotations
import threading
import time
from typing import Dict, List, Tuple
TYPES = ("parent", "tab", "gpu", "socket", "rdd", "utility", "forkserver", "other")
def classify(cmdline: List[str]) -> str:
"""parent = no `-contentproc`; otherwise the last argument (tab, gpu, socket, rdd, utility, forkserver), `other` for any other."""
if "-contentproc" not in cmdline:
return "parent"
last = str(cmdline[-1]).strip('"').lower() if cmdline else "?"
return last if last in TYPES else "other"
def delta_by_type(start: Dict[int, Tuple[str, float]], last: Dict[int, Tuple[str, float]]) -> Dict[str, float]:
"""CPU seconds per type over a window: `start` and `last` map pid -> (type, cumulative CPU seconds)."""
out = {t: 0.0 for t in TYPES}
for pid, (kind, cpu) in last.items():
out[kind] = out.get(kind, 0.0) + max(0.0, cpu - start.get(pid, (kind, 0.0))[1])
return out
def is_engine(proc) -> bool:
"""True when the process runs the firefox executable (its file name, whatever name the process gave itself)."""
import psutil
try:
exe = proc.exe()
except (psutil.Error, OSError):
exe = ""
# Either separator: the file name of the executable, whichever system wrote the path.
return (exe or proc.name()).replace("\\", "/").rsplit("/", 1)[-1].lower().startswith("firefox")
def engine_processes(root_pid: int) -> Dict[int, Tuple[str, float]]:
"""pid -> (type, cumulative CPU seconds) of every process of the engine below `root_pid`, now.
⛔ AN ENGINE PROCESS IS KNOWN BY ITS EXECUTABLE, NOT BY ITS NAME. On Linux a child names itself after its role ("Web Content",
"Isolated Web Co", "forkserver", "Socket Process", read from /proc/<pid>/comm) while its executable stays the firefox binary, so a
filter on the name kept the parent alone and the content processes were never counted (e2e Linux, run 43701692047). On Windows the
name and the executable are the same file."""
import psutil
out: Dict[int, Tuple[str, float]] = {}
try:
below = psutil.Process(root_pid).children(recursive=True)
except psutil.Error:
return out
for proc in below:
try:
if not is_engine(proc):
continue
times = proc.cpu_times()
out[proc.pid] = (classify(proc.cmdline()), times.user + times.system)
except psutil.Error:
continue
return out
class CpuSampler:
def __init__(self, root_pid: int, period: float = 0.25) -> None:
self.root_pid = root_pid
self.period = period
self.last: Dict[int, Tuple[str, float]] = {}
self.start: Dict[int, Tuple[str, float]] = {}
self._halt = threading.Event()
self._thread = threading.Thread(target=self._run, name="cpu-sampler", daemon=True)
def _take(self) -> None:
self.last.update(engine_processes(self.root_pid))
def _run(self) -> None:
while not self._halt.is_set():
self._take()
self._halt.wait(self.period)
def begin(self) -> None:
"""Mark the start of the window (what every process has used until now is not counted) and start sampling."""
self._take()
self.start = dict(self.last)
self._thread.start()
def end(self) -> Dict[str, float]:
"""Stop, take one more sample, and return the CPU seconds of the window by type."""
self._halt.set()
self._thread.join(timeout=10)
time.sleep(0.3)
self._take()
return delta_by_type(self.start, self.last)
-243
View File
@@ -1,243 +0,0 @@
"""What the Fission frame tests (`test_fission_frames_*_e2e.py`) share: three sites, and a proof of a process.
Three SITES on one machine, told apart by HOST and never by port (`127.0.0.1:1` and `127.0.0.1:2` are one site,
so a frame served from the other port stays in the process of its page):
A 127.0.0.1 the top page, and the A inside A > B > A > C
B localhost the iframe of another site
C 127.0.0.2 the third site
The wrapper runs Fission the way retail Firefox does (strategy 1, one content process per site), so with no pref a
frame of B inside a page of A runs in another process.
`assert_other_process` is how a test proves that, from inside the pages and with no help from the driver: the
frame spins for 600 ms and the observer frame times a 10 ms timer, which stalls only when the two share a process.
A test file calls it at least once, so the suite cannot silently turn into a same-process suite.
"""
from __future__ import annotations
import json
import struct
import threading
import zlib
import time
from http.server import BaseHTTPRequestHandler
from urllib.parse import parse_qs, urlsplit
from _servers import LocalServer
HOSTS = {"A": "127.0.0.1", "B": "localhost", "C": "127.0.0.2"}
#: How long the frame keeps its main thread busy, and the longest gap of the observer's timer that still means
#: "another process" (a process shared with the frame is stalled for about the whole spin).
SPIN_MS = 600
OWN_PROCESS_GAP_MS = 300
HTML = "text/html; charset=utf-8"
class Sites:
"""Three local servers, one per site, and the routes they serve.
``route(site, path, body, ...)`` registers a page; ``body`` is a string or bytes, or a function of the request
that returns the same (the request is the handler: ``.headers``, ``.query``). ``requests`` lists what arrived,
as dicts with ``site``, ``path``, ``query``, ``method`` and ``headers``.
"""
def __init__(self):
self._routes = {}
self.requests = []
self.servers = {}
self.origin = {}
sites = self
class Handler(BaseHTTPRequestHandler):
timeout = 10
def log_message(self, *args):
pass
def _answer(self):
url = urlsplit(self.path)
self.query = parse_qs(url.query)
site = self.server.site
length = int(self.headers.get("Content-Length") or 0)
self.body = self.rfile.read(length) if length else b""
sites.requests.append({"site": site, "path": url.path, "query": self.query,
"method": self.command, "headers": dict(self.headers)})
spec = sites._routes.get((site, url.path))
if spec is None:
self.send_response(404)
self.send_header("Content-Length", "0")
self.end_headers()
return
body = spec["body"](self) if callable(spec["body"]) else spec["body"]
if isinstance(body, str):
body = body.encode("utf-8")
if spec["delay"]:
time.sleep(spec["delay"])
try:
self.send_response(spec["status"])
self.send_header("Content-Type", spec["ctype"])
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-store")
for name, value in spec["headers"]:
self.send_header(name, value)
self.end_headers()
self.wfile.write(body)
except OSError:
pass
do_GET = _answer
do_POST = _answer
self._handler = Handler
def __enter__(self):
for site, host in HOSTS.items():
server = LocalServer((host if host != "localhost" else "127.0.0.1", 0), self._handler)
server.site = site
threading.Thread(target=server.serve_forever, daemon=True).start()
self.servers[site] = server
self.origin[site] = "http://%s:%d" % (host, server.server_address[1])
return self
def __exit__(self, *exc):
for server in self.servers.values():
server.shutdown()
server.server_close()
def url(self, site, path=""):
return self.origin[site] + path
def route(self, site, path, body, ctype=HTML, status=200, headers=(), delay=0):
self._routes[(site, path)] = {"body": body, "ctype": ctype, "status": status,
"headers": list(headers), "delay": delay}
def seen(self, site, path):
return [r for r in self.requests if r["site"] == site and r["path"] == path]
def wait_for(page, predicate, seconds=10.0):
"""Until ``predicate()``, with the client's events being read (the sync client takes the engine's events only
inside its own calls, so a plain sleep would never see a frame arrive)."""
end = time.monotonic() + seconds
while time.monotonic() < end:
if predicate():
return True
page.wait_for_timeout(100)
return bool(predicate())
def frame_of(page, origin, path=None):
"""The frame of ``page`` whose url starts with ``origin`` (and ``path``), or None."""
prefix = origin + (path or "")
for frame in page.frames:
if frame.url.startswith(prefix):
return frame
return None
def wait_frame(page, origin, path=None, seconds=10.0):
wait_for(page, lambda: frame_of(page, origin, path) is not None, seconds)
frame = frame_of(page, origin, path)
assert frame is not None, "no frame at %s%s; page.frames = %r" % (origin, path or "", [f.url for f in page.frames])
return frame
def launch(binary, humanize=False, **kwargs):
"""The browser of every test here: seed 42, headless, no humanizing unless asked."""
from invisible_playwright import InvisiblePlaywright
return InvisiblePlaywright(seed=42, binary_path=binary, humanize=humanize, headless=True, **kwargs)
def new_page(browser, **context_kwargs):
context = browser.new_context(**context_kwargs)
page = context.new_page()
page.set_default_timeout(8000)
page.set_default_navigation_timeout(30000)
return context, page
def longest_timer_gap(observer, frame, spin_ms=SPIN_MS):
"""Make ``frame`` spin for ``spin_ms`` and return the longest gap (ms) between two ticks of a 10 ms timer that
``observer`` (a frame) runs meanwhile."""
observer.evaluate("""() => {
window.__gap = 0;
let last = performance.now();
window.__tick = setInterval(() => {
const now = performance.now();
window.__gap = Math.max(window.__gap, now - last);
last = now;
}, 10);
}""")
frame.evaluate("""(ms) => { setTimeout(() => {
const end = performance.now() + ms;
while (performance.now() < end) { /* spin */ }
}, 50); }""", spin_ms)
observer.page.wait_for_timeout(spin_ms + 800)
return observer.evaluate("() => { clearInterval(window.__tick); return window.__gap; }")
def assert_other_process(observer, frame):
"""``frame`` runs in a process of its own, not the one of ``observer``: a spin in it does not stall the timer."""
gap = longest_timer_gap(observer, frame)
assert gap < OWN_PROCESS_GAP_MS, (
"the frame at %s shares the process of the observer at %s: a %d ms spin stalled the observer's timer for "
"%.0f ms" % (frame.url, observer.url, SPIN_MS, gap))
def js(value):
"""``value`` as a JavaScript literal, for a page built from a template."""
return json.dumps(value)
def decode_png(data):
"""``(width, height, pixel)`` of a PNG made by the browser (8 bits, no interlace); ``pixel(x, y)`` is the
``(r, g, b)`` tuple. Enough to ask what colour a screenshot has at a point, with no imaging library."""
assert data[:8] == bytes([137, 80, 78, 71, 13, 10, 26, 10]), "not a PNG"
pos, idat, width = 8, b"", None
while pos < len(data):
(length,) = struct.unpack(">I", data[pos:pos + 4])
kind, body = data[pos + 4:pos + 8], data[pos + 8:pos + 8 + length]
if kind == b"IHDR":
width, height, depth, color, _, _, interlace = struct.unpack(">IIBBBBB", body)
assert depth == 8 and interlace == 0 and color in (2, 6), (depth, color, interlace)
channels = 3 if color == 2 else 4
elif kind == b"IDAT":
idat += body
pos += 12 + length
raw = zlib.decompress(idat)
stride = width * channels
rows, previous = [], bytearray(stride)
for y in range(height):
start = y * (stride + 1)
filter_type, line = raw[start], bytearray(raw[start + 1:start + 1 + stride])
for i in range(stride):
left = line[i - channels] if i >= channels else 0
up = previous[i]
upleft = previous[i - channels] if i >= channels else 0
if filter_type == 1:
line[i] = (line[i] + left) & 255
elif filter_type == 2:
line[i] = (line[i] + up) & 255
elif filter_type == 3:
line[i] = (line[i] + (left + up) // 2) & 255
elif filter_type == 4:
estimate = left + up - upleft
pa, pb, pc = abs(estimate - left), abs(estimate - up), abs(estimate - upleft)
line[i] = (line[i] + (left if pa <= pb and pa <= pc else up if pb <= pc else upleft)) & 255
rows.append(line)
previous = line
def pixel(x, y):
offset = x * channels
return tuple(rows[y][offset:offset + 3])
return width, height, pixel
def near(color, expected, tolerance=3):
"""``color`` is ``expected`` give or take ``tolerance`` per channel."""
return all(abs(a - b) <= tolerance for a, b in zip(color, expected))
-216
View File
@@ -1,216 +0,0 @@
"""What the page-bytes e2e needs, apart from the browser: the probe's values, the PNG comparison on decoded pixels, and the
comparison with a reference committed per operating system (tests/data/page_bytes_<os>.json).
The probe (tests/page_bytes_probe.js) resolves to a flat object {key: value} where a value is
{"s": "a short string"} a string of at most 3000 characters, or
{"h": ..., "n": ..., "s0": ...} a longer string: the hash of its bytes (cyrb53), its length, its first 200 characters, or
{"h": ..., "n": ..., "w": ..., "b64": ...} bytes: hash, length, pixels per row, the bytes themselves when at most 400 KiB.
A PNG that the page reads (toDataURL, toBlob, convertToBlob) also carries `b64`: the bytes of the file.
Two kinds of key in the reference:
"keys" stable values, equal in every launch: compared as they are (the string, or the hash and the length);
"pngs" the keys that are PNG files. A PNG the engine writes holds a 16-byte ancillary chunk, `deBG`, that differs in every
launch (measured on the Windows runner, run 43652292533: the same arm launched twice differs in that chunk and
nowhere else, the length is the same). So its bytes are not compared: its length, and the pixels it decodes to
(width, height, colour type, and the sha256 of the unfiltered scanlines).
No value here is made up: an entry the reference does not hold is a problem (the test is red), and the problem carries the
entry the run measured, in the form the reference file takes, so that a run on the engine of the day writes it down.
"""
from __future__ import annotations
import base64
import hashlib
import json
import struct
import zlib
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
DATA_PREFIX = "data:image/png;base64,"
#: the end of a key that is a PNG file (the jpeg and webp encodings are stable and are compared as they are)
PNG_KEY_ENDS = (".png", ".toBlob", ".convertToBlob", ".toDataURL")
DATA_DIR = Path(__file__).resolve().parent / "data"
# ------------------------------------------------------------------------------------------------------------------ PNG
class NotAPng(ValueError):
pass
def png_chunks(png: bytes) -> List[Tuple[bytes, bytes]]:
if not png.startswith(PNG_SIGNATURE):
raise NotAPng("no PNG signature")
out, i = [], len(PNG_SIGNATURE)
while i + 12 <= len(png):
size = struct.unpack(">I", png[i:i + 4])[0]
tag, data = png[i + 4:i + 8], png[i + 8:i + 8 + size]
if len(data) != size:
raise NotAPng("a chunk is cut")
out.append((tag, data))
i += 12 + size
return out
def _paeth(a: int, b: int, c: int) -> int:
p = a + b - c
pa, pb, pc = abs(p - a), abs(p - b), abs(p - c)
return a if pa <= pb and pa <= pc else (b if pb <= pc else c)
def decode_png(png: bytes) -> Dict[str, Any]:
"""{w, h, ct, sha256} of a non-interlaced 8-bit PNG (grey, RGB, grey+alpha, RGBA): the sha256 is over the unfiltered
scanlines, so two files with the same pixels and different ancillary chunks or compression give the same answer."""
chunks = png_chunks(png)
head = [d for t, d in chunks if t == b"IHDR"]
if not head:
raise NotAPng("no IHDR")
w, h, depth, ct, _comp, _filt, interlace = struct.unpack(">IIBBBBB", head[0])
channels = {0: 1, 2: 3, 4: 2, 6: 4}.get(ct)
if depth != 8 or interlace != 0 or channels is None:
raise NotAPng("only 8-bit, non-interlaced, non-palette PNG is decoded here (bit depth %d, colour type %d, interlace %d)"
% (depth, ct, interlace))
raw = zlib.decompress(b"".join(d for t, d in chunks if t == b"IDAT"))
stride = w * channels
if len(raw) != h * (stride + 1):
raise NotAPng("the scanlines are %d bytes, %d expected" % (len(raw), h * (stride + 1)))
out = bytearray()
prev = bytearray(stride)
pos = 0
for _ in range(h):
ftype = raw[pos]
line = bytearray(raw[pos + 1:pos + 1 + stride])
pos += 1 + stride
if ftype == 1:
for i in range(channels, stride):
line[i] = (line[i] + line[i - channels]) & 255
elif ftype == 2:
for i in range(stride):
line[i] = (line[i] + prev[i]) & 255
elif ftype == 3:
for i in range(stride):
left = line[i - channels] if i >= channels else 0
line[i] = (line[i] + ((left + prev[i]) >> 1)) & 255
elif ftype == 4:
for i in range(stride):
left = line[i - channels] if i >= channels else 0
upleft = prev[i - channels] if i >= channels else 0
line[i] = (line[i] + _paeth(left, prev[i], upleft)) & 255
elif ftype != 0:
raise NotAPng("filter type %d" % ftype)
out += line
prev = line
return {"w": w, "h": h, "ct": ct, "sha256": hashlib.sha256(bytes(out)).hexdigest()}
def png_bytes_of(value: Dict[str, Any]) -> Optional[bytes]:
"""The PNG file a probe value holds, or None when the probe did not keep its bytes."""
if "b64" in value:
return base64.b64decode(value["b64"])
text = value.get("s")
if isinstance(text, str) and text.startswith(DATA_PREFIX):
return base64.b64decode(text[len(DATA_PREFIX):])
return None
def is_png_key(key: str) -> bool:
return key.endswith(PNG_KEY_ENDS)
# --------------------------------------------------------------------------------------------------------- the reference
def ident(value: Dict[str, Any]) -> Dict[str, Any]:
"""What identifies a stable value: its string, or the hash and the length of its bytes."""
if "s" in value:
return {"s": value["s"]}
return {"h": value.get("h"), "n": value.get("n")}
def png_entry(value: Dict[str, Any]) -> Dict[str, Any]:
"""The entry of a PNG key: its length and, when the bytes were kept, the pixels they decode to."""
# n: the length of the string for a data URL, of the file for bytes
entry: Dict[str, Any] = {"n": value["n"] if "n" in value else len(value.get("s", ""))}
data = png_bytes_of(value)
if data is None:
return entry
try:
entry.update(decode_png(data))
except (NotAPng, zlib.error) as exc:
entry["undecodable"] = str(exc)
return entry
def entry_of(key: str, value: Dict[str, Any]) -> Dict[str, Any]:
return png_entry(value) if is_png_key(key) else ident(value)
def reference_path(os_name: str) -> Path:
return DATA_DIR / ("page_bytes_%s.json" % os_name)
def load_reference(os_name: str) -> Dict[str, Any]:
"""The reference of an operating system; an empty one when the file does not exist yet (every key is then a problem
that carries its own entry, which is how the first reference is written)."""
path = reference_path(os_name)
if not path.is_file():
return {"keys": {}, "pngs": {}}
return json.loads(path.read_text(encoding="utf-8"))
def compare(reference: Dict[str, Any], measured: Dict[str, Dict[str, Any]]) -> Tuple[List[str], Dict[str, Dict[str, Any]]]:
"""(problems, record). `problems` is empty when every key the probe returned is in the reference with the same value
and the reference holds no key the probe did not return. `record` is the entry the run measured for every key that is
missing from the reference or incomplete in it (a PNG with no decoded pixels), in the form the reference file takes."""
problems: List[str] = []
record: Dict[str, Dict[str, Any]] = {}
stable, pngs = reference.get("keys", {}), reference.get("pngs", {})
for key in sorted(measured):
mine = entry_of(key, measured[key])
if is_png_key(key):
if "undecodable" in mine:
problems.append("%s: the PNG the page read does not decode (%s)" % (key, mine["undecodable"]))
continue
if "sha256" not in mine:
problems.append("%s: the probe did not keep the bytes of this PNG" % key)
continue
ref = pngs.get(key)
if ref is None:
problems.append("%s: not in the reference" % key)
record[key] = mine
elif ref.get("n") != mine.get("n"):
problems.append("%s: the PNG is %s bytes, the reference says %s" % (key, mine.get("n"), ref.get("n")))
elif "sha256" not in ref:
problems.append("%s: the reference has the length of this PNG and not yet its decoded pixels" % key)
record[key] = mine
elif (ref["w"], ref["h"], ref["ct"], ref["sha256"]) != (mine["w"], mine["h"], mine["ct"], mine["sha256"]):
problems.append("%s: the decoded pixels differ (%sx%s ct %s %s, the reference %sx%s ct %s %s)"
% (key, mine["w"], mine["h"], mine["ct"], mine["sha256"][:12],
ref["w"], ref["h"], ref["ct"], ref["sha256"][:12]))
else:
ref = stable.get(key)
if ref is None:
problems.append("%s: not in the reference" % key)
record[key] = mine
elif ref != mine:
problems.append("%s: %s, the reference %s" % (key, _short(mine), _short(ref)))
for key in sorted((set(stable) | set(pngs)) - set(measured)):
problems.append("%s: in the reference and not read by the probe" % key)
return problems, record
def _short(entry: Dict[str, Any], limit: int = 120) -> str:
return json.dumps(entry, sort_keys=True)[:limit]
def message(os_name: str, problems: List[str], record: Dict[str, Dict[str, Any]]) -> str:
"""The failure text: the problems, and the entries to add to tests/data/page_bytes_<os>.json."""
text = "%d problem(s) in the bytes a page reads on %s against %s:\n %s" % (
len(problems), os_name, reference_path(os_name).name, "\n ".join(problems[:60]))
if record:
keys = {k: v for k, v in record.items() if not is_png_key(k)}
pngs = {k: v for k, v in record.items() if is_png_key(k)}
text += ("\nTO RECORD (merge into tests/data/page_bytes_%s.json, from a run on the engine whose bytes are the reference):\n"
"RECORD-BEGIN %s\n%s\nRECORD-END" % (os_name, os_name, json.dumps({"keys": keys, "pngs": pngs}, sort_keys=True)))
return text
+23 -57
View File
@@ -97,11 +97,6 @@ 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()
@@ -110,12 +105,8 @@ 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
@@ -127,25 +118,9 @@ class FakeStun:
try:
self._sock.sendto(resp, peer)
except OSError:
if self._closing:
return
continue # a send that failed (the peer is gone) does not end the server for the next client
return
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()
@@ -458,12 +433,6 @@ 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)
@@ -471,31 +440,28 @@ class Gateway:
continue
except OSError:
return
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
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)
def outbound() -> None: # world -> client
while True:
-33
View File
@@ -88,39 +88,6 @@ 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
@@ -1,409 +0,0 @@
{
"os": "linux",
"source": "GitHub Actions run 43661728392 (workflow page-bytes-reference-hunt, runner image ubuntu24 20261111.370.1), wrapper commit 455d5619e5, invisible-core 64.71.0, engine firefox-64_159.0_20261114003728, seed 42, locale en-US, timezone Europe/Rome, headless=True; 2 launches, every key below is equal in all of them. `pngs`: the PNG keys, compared on their length and decoded pixels because every PNG carries a per-launch chunk.",
"keys": {
"c2d.composite.getImageData": {
"h": "df65ebe03bf31",
"n": 131072
},
"c2d.composite.jpeg": {
"h": "1c1b75006c5984",
"n": 11535
},
"c2d.composite.webp": {
"h": "182ab2238ae6c0",
"n": 5431
},
"c2d.gradtext.getImageData": {
"h": "ba9fb4487cdea",
"n": 352800
},
"c2d.image.getImageData": {
"h": "8218d41a1794c",
"n": 76800
},
"c2d.image.jpeg": {
"h": "125de65c968e30",
"n": 7315
},
"c2d.image.webp": {
"h": "26ea5dc80f98c",
"n": 5659
},
"c2d.measure": {
"h": "14a71ef40cb01c",
"n": 9488
},
"c2d.offscreen.getImageData": {
"h": "5a93b1c32ab60",
"n": 51200
},
"c2d.scale.high.getImageData": {
"h": "10d3beda5ba224",
"n": 114400
},
"c2d.scale.low.getImageData": {
"h": "10d3beda5ba224",
"n": 114400
},
"c2d.scale.medium.getImageData": {
"h": "10d3beda5ba224",
"n": 114400
},
"c2d.scale.off.getImageData": {
"h": "c673134829639",
"n": 114400
},
"c2d.shapes.getImageData": {
"h": "18fe9a0f7336da",
"n": 163840
},
"c2d.shapes.jpeg": {
"h": "18d82802030ab3",
"n": 6975
},
"c2d.shapes.webp": {
"h": "1ec9fa4e39f8de",
"n": 3287
},
"c2d.text.getImageData": {
"h": "e141df45718e",
"n": 856960
},
"c2d.text.jpeg": {
"h": "23b24c30781ee",
"n": 41751
},
"c2d.text.webp": {
"h": "1b0cc3c21c4f0f",
"n": 26215
},
"dom.fonts_check": {
"s": "[[\"16px sans-serif\",true],[\"20px serif\",true],[\"18px monospace\",true],[\"bold 16px Arial\",true],[\"italic 15px 'Segoe UI'\",true],[\"16px 'Times New Roman'\",true],[\"16px Calibri\",true],[\"14px Consolas\",true],[\"16px Verdana\",true],[\"16px Tahoma\",true],[\"17px Georgia\",true],[\"16px 'Segoe UI Emoji'\",true],[\"16px 'Microsoft YaHei'\",true],[\"16px 'Yu Gothic'\",true]]"
},
"dom.paragraphs": {
"s": "[[\"16px sans-serif\",200,21],[\"15px 'Times New Roman'\",200,20],[\"14px Consolas\",200,19]]"
},
"dom.span_boxes": {
"h": "1435dcc5a321d6",
"n": 5864
},
"dom.system_colors": {
"s": "[[\"Canvas\",\"rgb(255, 255, 255)\"],[\"CanvasText\",\"rgb(0, 0, 0)\"],[\"ButtonFace\",\"rgb(233, 233, 237)\"],[\"ButtonText\",\"rgb(0, 0, 0)\"],[\"ButtonBorder\",\"rgb(129, 127, 132)\"],[\"Field\",\"rgb(255, 255, 255)\"],[\"FieldText\",\"rgb(0, 0, 0)\"],[\"Highlight\",\"rgb(0, 120, 215)\"],[\"HighlightText\",\"rgb(255, 255, 255)\"],[\"GrayText\",\"rgb(109, 109, 109)\"],[\"LinkText\",\"rgb(0, 0, 238)\"],[\"VisitedText\",\"rgb(85, 26, 139)\"],[\"ActiveText\",\"rgb(238, 0, 0)\"],[\"Mark\",\"rgb(255, 255, 0)\"],[\"MarkText\",\"rgb(0, 0, 0)\"],[\"AccentColor\",\"rgb(0, 96, 223)\"],[\"AccentColorText\",\"rgb(255, 255, 255)\"],[\"SelectedItem\",\"rgb(0, 120, 215)\"],[\"SelectedItemText\",\"rgb(255, 255, 255)\"]]"
},
"env.dpr": {
"s": "1"
},
"env.hw": {
"s": "8"
},
"env.lang": {
"s": "[\"en-US\",\"en\"]"
},
"env.mq": {
"s": "[true,false,false,false,false,false,false]"
},
"env.oscpu": {
"s": "Windows NT 10.0; Win64; x64"
},
"env.platform": {
"s": "Win32"
},
"env.screen": {
"s": "[1920,1080,1920,1032,24,24]"
},
"env.ua": {
"s": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:159.0) Gecko/20100101 Firefox/159.0"
},
"gl1.anisotropy": {
"s": "16"
},
"gl1.antialias.false.readPixels": {
"h": "abed055e93fb8",
"n": 36864
},
"gl1.antialias.false.samples": {
"s": "0"
},
"gl1.antialias.true.readPixels": {
"h": "155744fc8af4b9",
"n": 36864
},
"gl1.antialias.true.samples": {
"s": "4"
},
"gl1.attributes": {
"s": "{\"alpha\":true,\"antialias\":true,\"depth\":true,\"failIfMajorPerformanceCaveat\":false,\"powerPreference\":\"default\",\"premultipliedAlpha\":true,\"preserveDrawingBuffer\":true,\"stencil\":false}"
},
"gl1.blend.readPixels": {
"h": "cfef8e9072c0c",
"n": 16384
},
"gl1.depth_stencil.readPixels": {
"h": "eaa3d5d41cfb",
"n": 16384
},
"gl1.extension_objects": {
"s": "[[\"ANGLE_instanced_arrays\",4],[\"EXT_blend_minmax\",2],[\"EXT_clip_control\",7],[\"EXT_color_buffer_half_float\",4],[\"EXT_depth_clamp\",1],[\"EXT_float_blend\",0],[\"EXT_frag_depth\",0],[\"EXT_polygon_offset_clamp\",2],[\"EXT_shader_texture_lod\",0],[\"EXT_sRGB\",4],[\"EXT_texture_compression_bptc\",4],[\"EXT_texture_compression_rgtc\",4],[\"EXT_texture_filter_anisotropic\",2],[\"EXT_texture_mirror_clamp_to_edge\",1],[\"OES_element_index_uint\",0],[\"OES_fbo_render_mipmap\",0],[\"OES_standard_derivatives\",1],[\"OES_texture_float\",0],[\"OES_texture_float_linear\",0],[\"OES_texture_half_float\",1],[\"OES_texture_half_float_linear\",0],[\"OES_vertex_array_object\",5],[\"WEBGL_color_buffer_float\",4],[\"WEBGL_compressed_texture_s3tc\",4],[\"WEBGL_compressed_texture_s3tc_srgb\",4],[\"WEBGL_debug_renderer_info\",2],[\"WEBGL_debug_shaders\",1],[\"WEBGL_depth_texture\",1],[\"WEBGL_draw_buffers\",35],[\"WEBGL_lose_context\",2],[\"WEBGL_provoking_vertex\",4]]"
},
"gl1.extensions": {
"s": "[\"ANGLE_instanced_arrays\",\"EXT_blend_minmax\",\"EXT_clip_control\",\"EXT_color_buffer_half_float\",\"EXT_depth_clamp\",\"EXT_float_blend\",\"EXT_frag_depth\",\"EXT_polygon_offset_clamp\",\"EXT_shader_texture_lod\",\"EXT_sRGB\",\"EXT_texture_compression_bptc\",\"EXT_texture_compression_rgtc\",\"EXT_texture_filter_anisotropic\",\"EXT_texture_mirror_clamp_to_edge\",\"OES_element_index_uint\",\"OES_fbo_render_mipmap\",\"OES_standard_derivatives\",\"OES_texture_float\",\"OES_texture_float_linear\",\"OES_texture_half_float\",\"OES_texture_half_float_linear\",\"OES_vertex_array_object\",\"WEBGL_color_buffer_float\",\"WEBGL_compressed_texture_s3tc\",\"WEBGL_compressed_texture_s3tc_srgb\",\"WEBGL_debug_renderer_info\",\"WEBGL_debug_shaders\",\"WEBGL_depth_texture\",\"WEBGL_draw_buffers\",\"WEBGL_lose_context\",\"WEBGL_provoking_vertex\"]"
},
"gl1.lines_points.readPixels": {
"h": "1841f80a258941",
"n": 16384
},
"gl1.math.highp.readPixels": {
"h": "14f93cecd95f86",
"n": 16384
},
"gl1.math.mediump.readPixels": {
"h": "14f93cecd95f86",
"n": 16384
},
"gl1.params": {
"s": "{\"VERSION\":\"WebGL 1.0\",\"SHADING_LANGUAGE_VERSION\":\"WebGL GLSL ES 1.0\",\"VENDOR\":\"Mozilla\",\"RENDERER\":\"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0), or similar\",\"MAX_TEXTURE_SIZE\":16384,\"MAX_CUBE_MAP_TEXTURE_SIZE\":16384,\"MAX_RENDERBUFFER_SIZE\":16384,\"MAX_VIEWPORT_DIMS\":[32767,32767],\"ALIASED_LINE_WIDTH_RANGE\":[1,1],\"ALIASED_POINT_SIZE_RANGE\":[1,1024],\"MAX_VERTEX_ATTRIBS\":16,\"MAX_VARYING_VECTORS\":30,\"MAX_COMBINED_TEXTURE_IMAGE_UNITS\":32,\"MAX_VERTEX_TEXTURE_IMAGE_UNITS\":16,\"MAX_TEXTURE_IMAGE_UNITS\":16,\"MAX_VERTEX_UNIFORM_VECTORS\":4096,\"MAX_FRAGMENT_UNIFORM_VECTORS\":1024,\"RED_BITS\":8,\"GREEN_BITS\":8,\"BLUE_BITS\":8,\"ALPHA_BITS\":8,\"DEPTH_BITS\":24,\"STENCIL_BITS\":0,\"SAMPLES\":4,\"SAMPLE_BUFFERS\":1,\"SUBPIXEL_BITS\":4}"
},
"gl1.precision": {
"s": "[[\"VERTEX_SHADER\",\"LOW_FLOAT\",127,127,23],[\"VERTEX_SHADER\",\"MEDIUM_FLOAT\",127,127,23],[\"VERTEX_SHADER\",\"HIGH_FLOAT\",127,127,23],[\"VERTEX_SHADER\",\"LOW_INT\",31,30,0],[\"VERTEX_SHADER\",\"MEDIUM_INT\",31,30,0],[\"VERTEX_SHADER\",\"HIGH_INT\",31,30,0],[\"FRAGMENT_SHADER\",\"LOW_FLOAT\",127,127,23],[\"FRAGMENT_SHADER\",\"MEDIUM_FLOAT\",127,127,23],[\"FRAGMENT_SHADER\",\"HIGH_FLOAT\",127,127,23],[\"FRAGMENT_SHADER\",\"LOW_INT\",31,30,0],[\"FRAGMENT_SHADER\",\"MEDIUM_INT\",31,30,0],[\"FRAGMENT_SHADER\",\"HIGH_INT\",31,30,0]]"
},
"gl1.texture.linear.readPixels": {
"h": "5fdcdb999f3e0",
"n": 16384
},
"gl1.texture.mip.readPixels": {
"h": "5fdcdb999f3e0",
"n": 16384
},
"gl1.texture.nearest.readPixels": {
"h": "160f810aa6835f",
"n": 16384
},
"gl1.triangle.drawImage": {
"h": "81a61d733e561",
"n": 36864
},
"gl1.triangle.readPixels": {
"h": "12bb7ce7d2f21",
"n": 36864
},
"gl1.triangle.toDataURL_jpeg": {
"s": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCABgAGADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDxKiiivTPOCiiigAopDwOaro5MpfnB7e1enl+V1ceqjp/ZV/V9vnqJuyuWaKKK81pp2YwooopAFFFFABRRRQAUUUUAMlPy4HU0RR05U3NmrMUdfdZXbBYZR6vV/wBeR1VaHJTV9yMxHZkdqjrTijqre25hYMPuN+h9K8LOKMZT9vT67/5/5nl0qtpezl8itRRRXhHUFFFFABRRRQAUqjJxSVYt4+MnvW+GipVE3sjvy7CvE1kui1YsUdW4o6WKOrcUdevUx3mehjqe4kUdWTbrLEyOPlYYp8UdW4o64KuNvofG46DTujj7y3a1uGifnHIOOoqGu01LTRfW2wELIpyjEd/Q+1cYysjFXBVgcEEYINeepxk9DfB4pV42fxLf/MSiiimdgUUUUAOiQu4UfjWpFHjFQafD8pc9+BWnFHWM8Uqd0j7zJsv9hg1Vkvenr8un+fzEijq3FHSxR1bijriqY7zPPx1PcSKOrcUdLFHVuKOuCpjvM+Nx1PcSKOsHxdpDPF9ugUl0GJVUD7v978On0+ldTFHVuKOuVZk6U1JHys608LVVWHT8Txyit/xboR0m7WSBXNnL91jyEb+7n9Rn9cGsCvp6FeFeCqU3dM+qoV4YimqlN6MKdGhkdUXqTim1p6PAGLSnnHyipxNdYek6jPaybLpZljIYdbPf0W/9dy/DEFAAHAGBVuKOlijqYyQQsFmmjRsZwzAGvk54yU3Zas/VsfCFOOtkvuJIo6txR1SbUrCDbvuYzn+5838s0kniHT4du1pJc9didPzxWXLiqnwU2/kz4jH1qKuudfebMUdW4o65iTxbaogMFtM755DkKMfUZqGbxpNsAtrKNHzyZHLjH0GKn+zsfU2hb1a/zufI4tRn8LO4ijq3FHXmsvjPU3iKRrbRMejohJH5kj9KpzeKNZmiaNr5wp6lFVD+YAIprh/HVPicV83+iPncRldSts0j1e+02HUrCW0uQxilGDtOCOcgj6ECvHdb0yfSNSmtLhWBU/IxGN654YfX/wCt2ok1fUpI2jk1C8eNgVZWnYgg9QRmqNe7lGWYjAOSnUTi+luve9/0Ncsy6rgpSvO8X0t17hUiTyooVJZFA7BiKjor25RUlaSue3TqzpO9OTT8tB0kjyHMjs5xjLHNNooppJKyJlJzfNJ3YUUUUCCiiigAooooAKKKKAP/2Q=="
},
"gl1.unmasked": {
"s": "[\"Google Inc. (Intel)\",\"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0), or similar\"]"
},
"gl2.anisotropy": {
"s": "16"
},
"gl2.antialias.false.readPixels": {
"h": "abed055e93fb8",
"n": 36864
},
"gl2.antialias.false.samples": {
"s": "0"
},
"gl2.antialias.true.readPixels": {
"h": "155744fc8af4b9",
"n": 36864
},
"gl2.antialias.true.samples": {
"s": "4"
},
"gl2.attributes": {
"s": "{\"alpha\":true,\"antialias\":true,\"depth\":true,\"failIfMajorPerformanceCaveat\":false,\"powerPreference\":\"default\",\"premultipliedAlpha\":true,\"preserveDrawingBuffer\":true,\"stencil\":false}"
},
"gl2.blend.readPixels": {
"h": "cfef8e9072c0c",
"n": 16384
},
"gl2.depth_stencil.readPixels": {
"h": "eaa3d5d41cfb",
"n": 16384
},
"gl2.extension_objects": {
"s": "[[\"EXT_clip_control\",7],[\"EXT_color_buffer_float\",0],[\"EXT_depth_clamp\",1],[\"EXT_float_blend\",0],[\"EXT_polygon_offset_clamp\",2],[\"EXT_texture_compression_bptc\",4],[\"EXT_texture_compression_rgtc\",4],[\"EXT_texture_filter_anisotropic\",2],[\"EXT_texture_mirror_clamp_to_edge\",1],[\"EXT_texture_norm16\",8],[\"OES_draw_buffers_indexed\",7],[\"OES_texture_float_linear\",0],[\"OVR_multiview2\",5],[\"WEBGL_compressed_texture_s3tc\",4],[\"WEBGL_compressed_texture_s3tc_srgb\",4],[\"WEBGL_debug_renderer_info\",2],[\"WEBGL_debug_shaders\",1],[\"WEBGL_lose_context\",2],[\"WEBGL_provoking_vertex\",4]]"
},
"gl2.extensions": {
"s": "[\"EXT_clip_control\",\"EXT_color_buffer_float\",\"EXT_depth_clamp\",\"EXT_float_blend\",\"EXT_polygon_offset_clamp\",\"EXT_texture_compression_bptc\",\"EXT_texture_compression_rgtc\",\"EXT_texture_filter_anisotropic\",\"EXT_texture_mirror_clamp_to_edge\",\"EXT_texture_norm16\",\"OES_draw_buffers_indexed\",\"OES_texture_float_linear\",\"OVR_multiview2\",\"WEBGL_compressed_texture_s3tc\",\"WEBGL_compressed_texture_s3tc_srgb\",\"WEBGL_debug_renderer_info\",\"WEBGL_debug_shaders\",\"WEBGL_lose_context\",\"WEBGL_provoking_vertex\"]"
},
"gl2.float_target.readPixels": {
"h": "1ba8f4b0bbe2d8",
"n": 16384
},
"gl2.lines_points.readPixels": {
"h": "1841f80a258941",
"n": 16384
},
"gl2.math.highp.readPixels": {
"h": "14f93cecd95f86",
"n": 16384
},
"gl2.math.mediump.readPixels": {
"h": "14f93cecd95f86",
"n": 16384
},
"gl2.msaa_resolve.readPixels": {
"h": "1a2cbef856e591",
"n": 16384
},
"gl2.params": {
"s": "{\"VERSION\":\"WebGL 2.0\",\"SHADING_LANGUAGE_VERSION\":\"WebGL GLSL ES 3.00\",\"VENDOR\":\"Mozilla\",\"RENDERER\":\"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0), or similar\",\"MAX_TEXTURE_SIZE\":16384,\"MAX_CUBE_MAP_TEXTURE_SIZE\":16384,\"MAX_RENDERBUFFER_SIZE\":16384,\"MAX_VIEWPORT_DIMS\":[32767,32767],\"ALIASED_LINE_WIDTH_RANGE\":[1,1],\"ALIASED_POINT_SIZE_RANGE\":[1,1024],\"MAX_VERTEX_ATTRIBS\":16,\"MAX_VARYING_VECTORS\":30,\"MAX_COMBINED_TEXTURE_IMAGE_UNITS\":32,\"MAX_VERTEX_TEXTURE_IMAGE_UNITS\":16,\"MAX_TEXTURE_IMAGE_UNITS\":16,\"MAX_VERTEX_UNIFORM_VECTORS\":4096,\"MAX_FRAGMENT_UNIFORM_VECTORS\":1024,\"RED_BITS\":8,\"GREEN_BITS\":8,\"BLUE_BITS\":8,\"ALPHA_BITS\":8,\"DEPTH_BITS\":24,\"STENCIL_BITS\":0,\"SAMPLES\":4,\"SAMPLE_BUFFERS\":1,\"SUBPIXEL_BITS\":4,\"MAX_3D_TEXTURE_SIZE\":2048,\"MAX_ARRAY_TEXTURE_LAYERS\":2048,\"MAX_COLOR_ATTACHMENTS\":8,\"MAX_DRAW_BUFFERS\":8,\"MAX_ELEMENTS_INDICES\":2147483647,\"MAX_ELEMENTS_VERTICES\":2147483647,\"MAX_FRAGMENT_INPUT_COMPONENTS\":120,\"MAX_FRAGMENT_UNIFORM_BLOCKS\":12,\"MAX_FRAGMENT_UNIFORM_COMPONENTS\":4096,\"MAX_PROGRAM_TEXEL_OFFSET\":7,\"MAX_SAMPLES\":8,\"MAX_SERVER_WAIT_TIMEOUT\":0,\"MAX_TEXTURE_LOD_BIAS\":2,\"MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS\":120,\"MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS\":4,\"MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS\":4,\"MAX_UNIFORM_BLOCK_SIZE\":65536,\"MAX_UNIFORM_BUFFER_BINDINGS\":24,\"MAX_VARYING_COMPONENTS\":120,\"MAX_VERTEX_OUTPUT_COMPONENTS\":120,\"MAX_VERTEX_UNIFORM_BLOCKS\":12,\"MAX_VERTEX_UNIFORM_COMPONENTS\":16384,\"MIN_PROGRAM_TEXEL_OFFSET\":-8,\"MAX_COMBINED_UNIFORM_BLOCKS\":24,\"MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS\":200704,\"MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS\":212992,\"UNIFORM_BUFFER_OFFSET_ALIGNMENT\":256}"
},
"gl2.precision": {
"s": "[[\"VERTEX_SHADER\",\"LOW_FLOAT\",127,127,23],[\"VERTEX_SHADER\",\"MEDIUM_FLOAT\",127,127,23],[\"VERTEX_SHADER\",\"HIGH_FLOAT\",127,127,23],[\"VERTEX_SHADER\",\"LOW_INT\",31,30,0],[\"VERTEX_SHADER\",\"MEDIUM_INT\",31,30,0],[\"VERTEX_SHADER\",\"HIGH_INT\",31,30,0],[\"FRAGMENT_SHADER\",\"LOW_FLOAT\",127,127,23],[\"FRAGMENT_SHADER\",\"MEDIUM_FLOAT\",127,127,23],[\"FRAGMENT_SHADER\",\"HIGH_FLOAT\",127,127,23],[\"FRAGMENT_SHADER\",\"LOW_INT\",31,30,0],[\"FRAGMENT_SHADER\",\"MEDIUM_INT\",31,30,0],[\"FRAGMENT_SHADER\",\"HIGH_INT\",31,30,0]]"
},
"gl2.texture.linear.readPixels": {
"h": "5fdcdb999f3e0",
"n": 16384
},
"gl2.texture.mip.readPixels": {
"h": "5fdcdb999f3e0",
"n": 16384
},
"gl2.texture.nearest.readPixels": {
"h": "160f810aa6835f",
"n": 16384
},
"gl2.triangle.drawImage": {
"h": "81a61d733e561",
"n": 36864
},
"gl2.triangle.readPixels": {
"h": "12bb7ce7d2f21",
"n": 36864
},
"gl2.triangle.toDataURL_jpeg": {
"s": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCABgAGADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDxKiiivTPOCiiigAopDwOaro5MpfnB7e1enl+V1ceqjp/ZV/V9vnqJuyuWaKKK81pp2YwooopAFFFFABRRRQAUUUUAMlPy4HU0RR05U3NmrMUdfdZXbBYZR6vV/wBeR1VaHJTV9yMxHZkdqjrTijqre25hYMPuN+h9K8LOKMZT9vT67/5/5nl0qtpezl8itRRRXhHUFFFFABRRRQAUqjJxSVYt4+MnvW+GipVE3sjvy7CvE1kui1YsUdW4o6WKOrcUdevUx3mehjqe4kUdWTbrLEyOPlYYp8UdW4o64KuNvofG46DTujj7y3a1uGifnHIOOoqGu01LTRfW2wELIpyjEd/Q+1cYysjFXBVgcEEYINeepxk9DfB4pV42fxLf/MSiiimdgUUUUAOiQu4UfjWpFHjFQafD8pc9+BWnFHWM8Uqd0j7zJsv9hg1Vkvenr8un+fzEijq3FHSxR1bijriqY7zPPx1PcSKOrcUdLFHVuKOuCpjvM+Nx1PcSKOsHxdpDPF9ugUl0GJVUD7v978On0+ldTFHVuKOuVZk6U1JHys608LVVWHT8Txyit/xboR0m7WSBXNnL91jyEb+7n9Rn9cGsCvp6FeFeCqU3dM+qoV4YimqlN6MKdGhkdUXqTim1p6PAGLSnnHyipxNdYek6jPaybLpZljIYdbPf0W/9dy/DEFAAHAGBVuKOlijqYyQQsFmmjRsZwzAGvk54yU3Zas/VsfCFOOtkvuJIo6txR1SbUrCDbvuYzn+5838s0kniHT4du1pJc9didPzxWXLiqnwU2/kz4jH1qKuudfebMUdW4o65iTxbaogMFtM755DkKMfUZqGbxpNsAtrKNHzyZHLjH0GKn+zsfU2hb1a/zufI4tRn8LO4ijq3FHXmsvjPU3iKRrbRMejohJH5kj9KpzeKNZmiaNr5wp6lFVD+YAIprh/HVPicV83+iPncRldSts0j1e+02HUrCW0uQxilGDtOCOcgj6ECvHdb0yfSNSmtLhWBU/IxGN654YfX/wCt2ok1fUpI2jk1C8eNgVZWnYgg9QRmqNe7lGWYjAOSnUTi+luve9/0Ncsy6rgpSvO8X0t17hUiTyooVJZFA7BiKjor25RUlaSue3TqzpO9OTT8tB0kjyHMjs5xjLHNNooppJKyJlJzfNJ3YUUUUCCiiigAooooAKKKKAP/2Q=="
},
"gl2.unmasked": {
"s": "[\"Google Inc. (Intel)\",\"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0), or similar\"]"
},
"gpu.webgpu.features": {
"s": "{\"depth-clip-control\":true,\"depth32float-stencil8\":true,\"texture-compression-bc\":true,\"texture-compression-bc-sliced-3d\":true,\"texture-compression-etc2\":false,\"texture-compression-astc\":false,\"texture-compression-astc-sliced-3d\":false,\"timestamp-query\":true,\"indirect-first-instance\":true,\"shader-f16\":true,\"rg11b10ufloat-renderable\":true,\"bgra8unorm-storage\":true,\"float32-filterable\":true,\"float32-blendable\":true,\"clip-distances\":false,\"dual-source-blending\":true,\"subgroups\":false}"
},
"gpu.webgpu.info": {
"s": "{\"vendor\":\"\",\"architecture\":\"\",\"device\":\"\",\"description\":\"\"}"
},
"gpu.webgpu.limits": {
"s": "{\"maxTextureDimension1D\":16384,\"maxTextureDimension2D\":16384,\"maxTextureDimension3D\":2048,\"maxTextureArrayLayers\":2048,\"maxBindGroups\":8,\"maxBindGroupsPlusVertexBuffers\":24,\"maxBindingsPerBindGroup\":4294967295,\"maxDynamicUniformBuffersPerPipelineLayout\":8,\"maxDynamicStorageBuffersPerPipelineLayout\":4,\"maxSampledTexturesPerShaderStage\":64,\"maxSamplersPerShaderStage\":64,\"maxStorageBuffersPerShaderStage\":64,\"maxStorageTexturesPerShaderStage\":64,\"maxUniformBuffersPerShaderStage\":64,\"maxUniformBufferBindingSize\":65536,\"maxStorageBufferBindingSize\":2147483644,\"minUniformBufferOffsetAlignment\":256,\"minStorageBufferOffsetAlignment\":32,\"maxVertexBuffers\":16,\"maxBufferSize\":2147483644,\"maxVertexAttributes\":30,\"maxVertexBufferArrayStride\":2048,\"maxInterStageShaderVariables\":31,\"maxColorAttachments\":8,\"maxColorAttachmentBytesPerSample\":128,\"maxComputeWorkgroupStorageSize\":32768,\"maxComputeInvocationsPerWorkgroup\":1024,\"maxComputeWorkgroupSizeX\":1024,\"maxComputeWorkgroupSizeY\":1024,\"maxComputeWorkgroupSizeZ\":64,\"maxComputeWorkgroupsPerDimension\":65535}"
},
"worker.webgl": {
"s": "{\"vendor\":\"Mozilla\",\"renderer\":\"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0), or similar\",\"unmasked\":[\"Google Inc. (Intel)\",\"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0), or similar\"],\"exts\":[\"ANGLE_instanced_arrays\",\"EXT_blend_minmax\",\"EXT_clip_control\",\"EXT_color_buffer_half_float\",\"EXT_depth_clamp\",\"EXT_float_blend\",\"EXT_frag_depth\",\"EXT_polygon_offset_clamp\",\"EXT_shader_texture_lod\",\"EXT_sRGB\",\"EXT_texture_compression_bptc\",\"EXT_texture_compression_rgtc\",\"EXT_texture_filter_anisotropic\",\"EXT_texture_mirror_clamp_to_edge\",\"OES_element_index_uint\",\"OES_fbo_render_mipmap\",\"OES_standard_derivatives\",\"OES_texture_float\",\"OES_texture_float_linear\",\"OES_texture_half_float\",\"OES_texture_half_float_linear\",\"OES_vertex_array_object\",\"WEBGL_color_buffer_float\",\"WEBGL_compressed_texture_s3tc\",\"WEBGL_compressed_texture_s3tc_srgb\",\"WEBGL_debug_renderer_info\",\"WEBGL_debug_shaders\",\"WEBGL_depth_texture\",\"WEBGL_draw_buffers\",\"WEBGL_lose_context\",\"WEBGL_provoking_vertex\"],\"px\":[64,128,191,255,64,128,191,255,64,128,191,255,64,128,191,255]}"
}
},
"pngs": {
"c2d.composite.png": {
"n": 2414,
"w": 256,
"h": 128,
"ct": 6,
"sha256": "fb585f18240eb1a787a5b146d6332a0376dae76f8c8716e99f68fbbf9eff905e"
},
"c2d.composite.toBlob": {
"n": 1794,
"w": 256,
"h": 128,
"ct": 6,
"sha256": "fb585f18240eb1a787a5b146d6332a0376dae76f8c8716e99f68fbbf9eff905e"
},
"c2d.gradtext.png": {
"n": 56850,
"w": 420,
"h": 210,
"ct": 6,
"sha256": "a294763c6eca0c9178d09052cfaa5ac92932d8cf32909f31bbb387810d473310"
},
"c2d.image.png": {
"n": 19502,
"w": 160,
"h": 120,
"ct": 6,
"sha256": "51bc3789f2e238dfbf8899eb7a965a4f04d3e0e7f2246b1bd3cfdc9597bd2a77"
},
"c2d.image.toBlob": {
"n": 14610,
"w": 160,
"h": 120,
"ct": 6,
"sha256": "51bc3789f2e238dfbf8899eb7a965a4f04d3e0e7f2246b1bd3cfdc9597bd2a77"
},
"c2d.offscreen.convertToBlob": {
"n": 2687,
"w": 160,
"h": 80,
"ct": 6,
"sha256": "38b7fa4aa1d61a5bae5b92e8b9216ff61ce4d4a8d15cc0fa6d8a8c8441a3fdb8"
},
"c2d.scale.high.png": {
"n": 47314,
"w": 220,
"h": 130,
"ct": 6,
"sha256": "8672b8676f90d662b4809e56c55da58e05be4e72b2f7c543b33da4bdafb0ce21"
},
"c2d.scale.low.png": {
"n": 47314,
"w": 220,
"h": 130,
"ct": 6,
"sha256": "8672b8676f90d662b4809e56c55da58e05be4e72b2f7c543b33da4bdafb0ce21"
},
"c2d.scale.medium.png": {
"n": 47314,
"w": 220,
"h": 130,
"ct": 6,
"sha256": "8672b8676f90d662b4809e56c55da58e05be4e72b2f7c543b33da4bdafb0ce21"
},
"c2d.scale.off.png": {
"n": 20890,
"w": 220,
"h": 130,
"ct": 6,
"sha256": "c28700e28636d69dfe9bf293fadebae1fdf970949ac90147836ab1837065f46d"
},
"c2d.shapes.png": {
"n": 19226,
"w": 256,
"h": 160,
"ct": 6,
"sha256": "89ee57c100f4682099bd3a5f2de56c5b31091dae253bd7e3db4f254fb8b9e6a3"
},
"c2d.shapes.toBlob": {
"n": 14402,
"w": 256,
"h": 160,
"ct": 6,
"sha256": "89ee57c100f4682099bd3a5f2de56c5b31091dae253bd7e3db4f254fb8b9e6a3"
},
"c2d.text.png": {
"n": 51610,
"w": 520,
"h": 412,
"ct": 6,
"sha256": "1c56511f78721be0423bbcef100bf7b52e9997da498bd1f771d0d8348a791d3b"
},
"c2d.text.toBlob": {
"n": 38691,
"w": 520,
"h": 412,
"ct": 6,
"sha256": "1c56511f78721be0423bbcef100bf7b52e9997da498bd1f771d0d8348a791d3b"
},
"gl1.triangle.toDataURL": {
"n": 7470,
"w": 96,
"h": 96,
"ct": 6,
"sha256": "3f24afcf21a411e18ef9256e558a30ec589bbb51923fedf485cd0e6a2dcd9919"
},
"gl2.triangle.toDataURL": {
"n": 7470,
"w": 96,
"h": 96,
"ct": 6,
"sha256": "3f24afcf21a411e18ef9256e558a30ec589bbb51923fedf485cd0e6a2dcd9919"
}
}
}
-409
View File
@@ -1,409 +0,0 @@
{
"os": "windows",
"source": "GitHub Actions run 43661728392 (workflow page-bytes-reference-hunt, runner image win22 20261112.366.7), wrapper commit 455d5619e5, invisible-core 64.71.0, engine firefox-64_159.0_20261114003728, seed 42, locale en-US, timezone Europe/Rome, headless=True; 2 launches, every key below is equal in all of them. `pngs`: the PNG keys, compared on their length and decoded pixels because every PNG carries a per-launch chunk.",
"keys": {
"c2d.composite.getImageData": {
"h": "df65ebe03bf31",
"n": 131072
},
"c2d.composite.jpeg": {
"h": "1c1b75006c5984",
"n": 11535
},
"c2d.composite.webp": {
"h": "182ab2238ae6c0",
"n": 5431
},
"c2d.gradtext.getImageData": {
"h": "42edf4d4d5394",
"n": 352800
},
"c2d.image.getImageData": {
"h": "8218d41a1794c",
"n": 76800
},
"c2d.image.jpeg": {
"h": "125de65c968e30",
"n": 7315
},
"c2d.image.webp": {
"h": "26ea5dc80f98c",
"n": 5659
},
"c2d.measure": {
"h": "a731f7d3287e2",
"n": 9495
},
"c2d.offscreen.getImageData": {
"h": "1d9666b372acb1",
"n": 51200
},
"c2d.scale.high.getImageData": {
"h": "10d3beda5ba224",
"n": 114400
},
"c2d.scale.low.getImageData": {
"h": "10d3beda5ba224",
"n": 114400
},
"c2d.scale.medium.getImageData": {
"h": "10d3beda5ba224",
"n": 114400
},
"c2d.scale.off.getImageData": {
"h": "c673134829639",
"n": 114400
},
"c2d.shapes.getImageData": {
"h": "18fe9a0f7336da",
"n": 163840
},
"c2d.shapes.jpeg": {
"h": "18d82802030ab3",
"n": 6975
},
"c2d.shapes.webp": {
"h": "1ec9fa4e39f8de",
"n": 3287
},
"c2d.text.getImageData": {
"h": "11041652732d2c",
"n": 856960
},
"c2d.text.jpeg": {
"h": "15a47ca2d73ab",
"n": 43163
},
"c2d.text.webp": {
"h": "59e03617b84b1",
"n": 26943
},
"dom.fonts_check": {
"s": "[[\"16px sans-serif\",true],[\"20px serif\",true],[\"18px monospace\",true],[\"bold 16px Arial\",true],[\"italic 15px 'Segoe UI'\",true],[\"16px 'Times New Roman'\",true],[\"16px Calibri\",true],[\"14px Consolas\",true],[\"16px Verdana\",true],[\"16px Tahoma\",true],[\"17px Georgia\",true],[\"16px 'Segoe UI Emoji'\",true],[\"16px 'Microsoft YaHei'\",true],[\"16px 'Yu Gothic'\",true]]"
},
"dom.paragraphs": {
"s": "[[\"16px sans-serif\",200,21],[\"15px 'Times New Roman'\",200,20],[\"14px Consolas\",200,19]]"
},
"dom.span_boxes": {
"h": "157207c863aeec",
"n": 5863
},
"dom.system_colors": {
"s": "[[\"Canvas\",\"rgb(255, 255, 255)\"],[\"CanvasText\",\"rgb(0, 0, 0)\"],[\"ButtonFace\",\"rgb(233, 233, 237)\"],[\"ButtonText\",\"rgb(0, 0, 0)\"],[\"ButtonBorder\",\"rgb(129, 127, 132)\"],[\"Field\",\"rgb(255, 255, 255)\"],[\"FieldText\",\"rgb(0, 0, 0)\"],[\"Highlight\",\"rgb(0, 120, 215)\"],[\"HighlightText\",\"rgb(255, 255, 255)\"],[\"GrayText\",\"rgb(109, 109, 109)\"],[\"LinkText\",\"rgb(0, 0, 238)\"],[\"VisitedText\",\"rgb(85, 26, 139)\"],[\"ActiveText\",\"rgb(238, 0, 0)\"],[\"Mark\",\"rgb(255, 255, 0)\"],[\"MarkText\",\"rgb(0, 0, 0)\"],[\"AccentColor\",\"rgb(0, 96, 223)\"],[\"AccentColorText\",\"rgb(255, 255, 255)\"],[\"SelectedItem\",\"rgb(0, 120, 215)\"],[\"SelectedItemText\",\"rgb(255, 255, 255)\"]]"
},
"env.dpr": {
"s": "1"
},
"env.hw": {
"s": "8"
},
"env.lang": {
"s": "[\"en-US\",\"en\"]"
},
"env.mq": {
"s": "[true,false,false,false,false,false,false]"
},
"env.oscpu": {
"s": "Windows NT 10.0; Win64; x64"
},
"env.platform": {
"s": "Win32"
},
"env.screen": {
"s": "[1920,1080,1920,1032,24,24]"
},
"env.ua": {
"s": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:159.0) Gecko/20100101 Firefox/159.0"
},
"gl1.anisotropy": {
"s": "16"
},
"gl1.antialias.false.readPixels": {
"h": "abed055e93fb8",
"n": 36864
},
"gl1.antialias.false.samples": {
"s": "0"
},
"gl1.antialias.true.readPixels": {
"h": "155744fc8af4b9",
"n": 36864
},
"gl1.antialias.true.samples": {
"s": "4"
},
"gl1.attributes": {
"s": "{\"alpha\":true,\"antialias\":true,\"depth\":true,\"failIfMajorPerformanceCaveat\":false,\"powerPreference\":\"default\",\"premultipliedAlpha\":true,\"preserveDrawingBuffer\":true,\"stencil\":false}"
},
"gl1.blend.readPixels": {
"h": "1e61b0c76b34d",
"n": 16384
},
"gl1.depth_stencil.readPixels": {
"h": "eaa3d5d41cfb",
"n": 16384
},
"gl1.extension_objects": {
"s": "[[\"ANGLE_instanced_arrays\",4],[\"EXT_blend_minmax\",2],[\"EXT_clip_control\",7],[\"EXT_color_buffer_half_float\",4],[\"EXT_depth_clamp\",1],[\"EXT_float_blend\",0],[\"EXT_frag_depth\",0],[\"EXT_polygon_offset_clamp\",2],[\"EXT_shader_texture_lod\",0],[\"EXT_sRGB\",4],[\"EXT_texture_compression_bptc\",4],[\"EXT_texture_compression_rgtc\",4],[\"EXT_texture_filter_anisotropic\",2],[\"EXT_texture_mirror_clamp_to_edge\",1],[\"OES_element_index_uint\",0],[\"OES_fbo_render_mipmap\",0],[\"OES_standard_derivatives\",1],[\"OES_texture_float\",0],[\"OES_texture_float_linear\",0],[\"OES_texture_half_float\",1],[\"OES_texture_half_float_linear\",0],[\"OES_vertex_array_object\",5],[\"WEBGL_color_buffer_float\",4],[\"WEBGL_compressed_texture_s3tc\",4],[\"WEBGL_compressed_texture_s3tc_srgb\",4],[\"WEBGL_debug_renderer_info\",2],[\"WEBGL_debug_shaders\",1],[\"WEBGL_depth_texture\",1],[\"WEBGL_draw_buffers\",35],[\"WEBGL_lose_context\",2],[\"WEBGL_provoking_vertex\",4]]"
},
"gl1.extensions": {
"s": "[\"ANGLE_instanced_arrays\",\"EXT_blend_minmax\",\"EXT_clip_control\",\"EXT_color_buffer_half_float\",\"EXT_depth_clamp\",\"EXT_float_blend\",\"EXT_frag_depth\",\"EXT_polygon_offset_clamp\",\"EXT_shader_texture_lod\",\"EXT_sRGB\",\"EXT_texture_compression_bptc\",\"EXT_texture_compression_rgtc\",\"EXT_texture_filter_anisotropic\",\"EXT_texture_mirror_clamp_to_edge\",\"OES_element_index_uint\",\"OES_fbo_render_mipmap\",\"OES_standard_derivatives\",\"OES_texture_float\",\"OES_texture_float_linear\",\"OES_texture_half_float\",\"OES_texture_half_float_linear\",\"OES_vertex_array_object\",\"WEBGL_color_buffer_float\",\"WEBGL_compressed_texture_s3tc\",\"WEBGL_compressed_texture_s3tc_srgb\",\"WEBGL_debug_renderer_info\",\"WEBGL_debug_shaders\",\"WEBGL_depth_texture\",\"WEBGL_draw_buffers\",\"WEBGL_lose_context\",\"WEBGL_provoking_vertex\"]"
},
"gl1.lines_points.readPixels": {
"h": "1841f80a258941",
"n": 16384
},
"gl1.math.highp.readPixels": {
"h": "85fe168c6de19",
"n": 16384
},
"gl1.math.mediump.readPixels": {
"h": "85fe168c6de19",
"n": 16384
},
"gl1.params": {
"s": "{\"VERSION\":\"WebGL 1.0\",\"SHADING_LANGUAGE_VERSION\":\"WebGL GLSL ES 1.0\",\"VENDOR\":\"Mozilla\",\"RENDERER\":\"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0), or similar\",\"MAX_TEXTURE_SIZE\":16384,\"MAX_CUBE_MAP_TEXTURE_SIZE\":16384,\"MAX_RENDERBUFFER_SIZE\":16384,\"MAX_VIEWPORT_DIMS\":[32767,32767],\"ALIASED_LINE_WIDTH_RANGE\":[1,1],\"ALIASED_POINT_SIZE_RANGE\":[1,1024],\"MAX_VERTEX_ATTRIBS\":16,\"MAX_VARYING_VECTORS\":30,\"MAX_COMBINED_TEXTURE_IMAGE_UNITS\":32,\"MAX_VERTEX_TEXTURE_IMAGE_UNITS\":16,\"MAX_TEXTURE_IMAGE_UNITS\":16,\"MAX_VERTEX_UNIFORM_VECTORS\":4096,\"MAX_FRAGMENT_UNIFORM_VECTORS\":1024,\"RED_BITS\":8,\"GREEN_BITS\":8,\"BLUE_BITS\":8,\"ALPHA_BITS\":8,\"DEPTH_BITS\":24,\"STENCIL_BITS\":0,\"SAMPLES\":4,\"SAMPLE_BUFFERS\":1,\"SUBPIXEL_BITS\":4}"
},
"gl1.precision": {
"s": "[[\"VERTEX_SHADER\",\"LOW_FLOAT\",127,127,23],[\"VERTEX_SHADER\",\"MEDIUM_FLOAT\",127,127,23],[\"VERTEX_SHADER\",\"HIGH_FLOAT\",127,127,23],[\"VERTEX_SHADER\",\"LOW_INT\",31,30,0],[\"VERTEX_SHADER\",\"MEDIUM_INT\",31,30,0],[\"VERTEX_SHADER\",\"HIGH_INT\",31,30,0],[\"FRAGMENT_SHADER\",\"LOW_FLOAT\",127,127,23],[\"FRAGMENT_SHADER\",\"MEDIUM_FLOAT\",127,127,23],[\"FRAGMENT_SHADER\",\"HIGH_FLOAT\",127,127,23],[\"FRAGMENT_SHADER\",\"LOW_INT\",31,30,0],[\"FRAGMENT_SHADER\",\"MEDIUM_INT\",31,30,0],[\"FRAGMENT_SHADER\",\"HIGH_INT\",31,30,0]]"
},
"gl1.texture.linear.readPixels": {
"h": "12a052fdb7d89f",
"n": 16384
},
"gl1.texture.mip.readPixels": {
"h": "12a052fdb7d89f",
"n": 16384
},
"gl1.texture.nearest.readPixels": {
"h": "160f810aa6835f",
"n": 16384
},
"gl1.triangle.drawImage": {
"h": "1f2476721e653d",
"n": 36864
},
"gl1.triangle.readPixels": {
"h": "e35b6ac5b7d59",
"n": 36864
},
"gl1.triangle.toDataURL_jpeg": {
"s": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCABgAGADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDxKiiivTPOCiiigAopDwOaro5MpfnB7e1enl+V1ceqjp/ZV/V9vnqJuyuWaKKK81pp2YwooopAFFFFABRRRQAUUUUAMlPy4HU0RR05U3NmrMUdfdZXbBYZR6vV/wBeR1VaHJTV9yMxHZkdqjrTijqre25hYMPuN+h9K8LOKMZT9vDrv/n/AJnl0qtpezl8itRRRXhHUFFFFABRRRQAUqjJxSVYt4+MnvW+GipVE3sjvy7CvE1kui1YsUdW4o6WKOrcUdevUx3mehjqe4kUdWTbrLEyOPlYYp8UdW4o64KuNvofG46DTujj7y3a1uGifnHIOOoqGu01LTRfW2wELIpyjEd/Q+1cYysjFXBVgcEEYINeepxk9DfB4pV42fxLf/MSiiimdgUUUUAOiQu4UfjWpFHjFQafD8pc9+BWnFHWM8Uqd0j7zJsv9hg1Vkvenr8un+fzEijq3FHSxR1bijriqY7zPPx1PcSKOrcUdLFHVuKOuCpjvM+Nx1PcSKOsHxdpDPF9ugUl0GJVUD7v978On0+ldTFHVuKOuVZk6U1JHys608LVVWHT8Txyit/xboR0m7WSBXNnL91jyEb+7n9Rn9cGsCvp6FeFeCqU3dM+qoV4YimqlN6MKdGhkdUXqTim1p6PAGLSnnHyipxNdYek6jPaybLpZljIYdbPf0W/9dy/DEFAAHAGBVuKOlijqYyQQsFmmjRsZwzAGvk54yU3Zas/VsfCFOOtkvuJIo6txR1SbUrCDbvuYzn+5838s0kniHT4du1pJc9didPzxWXLiqnwU2/kz4jH1qKuudfebMUdW4o65iTxbaogMFtM755DkKMfUZqGbxpNsAtrKNHzyZHLjH0GKn+zsfU2hb1a/wA7nyOLUZ/CzuIo6txR15rL4z1N4ika20THo6ISR+ZI/Sqc3ijWZomja+cKepRVQ/mACKa4fx1T4nFfN/oj53EZXUrbNI9XvtNh1KwltLkMYpRg7TgjnII+hArx3W9Mn0jUprS4VgVPyMRjeueGH1/+t2ok1fUpI2jk1C8eNgVZWnYgg9QRmqNe7lGWYjAOSnUTi+luve9/0Ncsy6rgpSvO8X0t17hUiTyooVJZFA7BiKjor25RUlaSue3TqzpO9OTT8tB0kjyHMjs5xjLHNNooppJKyJlJzfNJ3YUUUUCCiiigAooooAKKKKAP/9k="
},
"gl1.unmasked": {
"s": "[\"Google Inc. (Intel)\",\"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0), or similar\"]"
},
"gl2.anisotropy": {
"s": "16"
},
"gl2.antialias.false.readPixels": {
"h": "abed055e93fb8",
"n": 36864
},
"gl2.antialias.false.samples": {
"s": "0"
},
"gl2.antialias.true.readPixels": {
"h": "155744fc8af4b9",
"n": 36864
},
"gl2.antialias.true.samples": {
"s": "4"
},
"gl2.attributes": {
"s": "{\"alpha\":true,\"antialias\":true,\"depth\":true,\"failIfMajorPerformanceCaveat\":false,\"powerPreference\":\"default\",\"premultipliedAlpha\":true,\"preserveDrawingBuffer\":true,\"stencil\":false}"
},
"gl2.blend.readPixels": {
"h": "1e61b0c76b34d",
"n": 16384
},
"gl2.depth_stencil.readPixels": {
"h": "eaa3d5d41cfb",
"n": 16384
},
"gl2.extension_objects": {
"s": "[[\"EXT_clip_control\",7],[\"EXT_color_buffer_float\",0],[\"EXT_depth_clamp\",1],[\"EXT_float_blend\",0],[\"EXT_polygon_offset_clamp\",2],[\"EXT_texture_compression_bptc\",4],[\"EXT_texture_compression_rgtc\",4],[\"EXT_texture_filter_anisotropic\",2],[\"EXT_texture_mirror_clamp_to_edge\",1],[\"EXT_texture_norm16\",8],[\"OES_draw_buffers_indexed\",7],[\"OES_texture_float_linear\",0],[\"OVR_multiview2\",5],[\"WEBGL_compressed_texture_s3tc\",4],[\"WEBGL_compressed_texture_s3tc_srgb\",4],[\"WEBGL_debug_renderer_info\",2],[\"WEBGL_debug_shaders\",1],[\"WEBGL_lose_context\",2],[\"WEBGL_provoking_vertex\",4]]"
},
"gl2.extensions": {
"s": "[\"EXT_clip_control\",\"EXT_color_buffer_float\",\"EXT_depth_clamp\",\"EXT_float_blend\",\"EXT_polygon_offset_clamp\",\"EXT_texture_compression_bptc\",\"EXT_texture_compression_rgtc\",\"EXT_texture_filter_anisotropic\",\"EXT_texture_mirror_clamp_to_edge\",\"EXT_texture_norm16\",\"OES_draw_buffers_indexed\",\"OES_texture_float_linear\",\"OVR_multiview2\",\"WEBGL_compressed_texture_s3tc\",\"WEBGL_compressed_texture_s3tc_srgb\",\"WEBGL_debug_renderer_info\",\"WEBGL_debug_shaders\",\"WEBGL_lose_context\",\"WEBGL_provoking_vertex\"]"
},
"gl2.float_target.readPixels": {
"h": "4036e3357974d",
"n": 16384
},
"gl2.lines_points.readPixels": {
"h": "1841f80a258941",
"n": 16384
},
"gl2.math.highp.readPixels": {
"h": "85fe168c6de19",
"n": 16384
},
"gl2.math.mediump.readPixels": {
"h": "85fe168c6de19",
"n": 16384
},
"gl2.msaa_resolve.readPixels": {
"h": "1a2cbef856e591",
"n": 16384
},
"gl2.params": {
"s": "{\"VERSION\":\"WebGL 2.0\",\"SHADING_LANGUAGE_VERSION\":\"WebGL GLSL ES 3.00\",\"VENDOR\":\"Mozilla\",\"RENDERER\":\"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0), or similar\",\"MAX_TEXTURE_SIZE\":16384,\"MAX_CUBE_MAP_TEXTURE_SIZE\":16384,\"MAX_RENDERBUFFER_SIZE\":16384,\"MAX_VIEWPORT_DIMS\":[32767,32767],\"ALIASED_LINE_WIDTH_RANGE\":[1,1],\"ALIASED_POINT_SIZE_RANGE\":[1,1024],\"MAX_VERTEX_ATTRIBS\":16,\"MAX_VARYING_VECTORS\":30,\"MAX_COMBINED_TEXTURE_IMAGE_UNITS\":32,\"MAX_VERTEX_TEXTURE_IMAGE_UNITS\":16,\"MAX_TEXTURE_IMAGE_UNITS\":16,\"MAX_VERTEX_UNIFORM_VECTORS\":4096,\"MAX_FRAGMENT_UNIFORM_VECTORS\":1024,\"RED_BITS\":8,\"GREEN_BITS\":8,\"BLUE_BITS\":8,\"ALPHA_BITS\":8,\"DEPTH_BITS\":24,\"STENCIL_BITS\":0,\"SAMPLES\":4,\"SAMPLE_BUFFERS\":1,\"SUBPIXEL_BITS\":4,\"MAX_3D_TEXTURE_SIZE\":2048,\"MAX_ARRAY_TEXTURE_LAYERS\":2048,\"MAX_COLOR_ATTACHMENTS\":8,\"MAX_DRAW_BUFFERS\":8,\"MAX_ELEMENTS_INDICES\":2147483647,\"MAX_ELEMENTS_VERTICES\":2147483647,\"MAX_FRAGMENT_INPUT_COMPONENTS\":120,\"MAX_FRAGMENT_UNIFORM_BLOCKS\":12,\"MAX_FRAGMENT_UNIFORM_COMPONENTS\":4096,\"MAX_PROGRAM_TEXEL_OFFSET\":7,\"MAX_SAMPLES\":8,\"MAX_SERVER_WAIT_TIMEOUT\":0,\"MAX_TEXTURE_LOD_BIAS\":2,\"MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS\":120,\"MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS\":4,\"MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS\":4,\"MAX_UNIFORM_BLOCK_SIZE\":65536,\"MAX_UNIFORM_BUFFER_BINDINGS\":24,\"MAX_VARYING_COMPONENTS\":120,\"MAX_VERTEX_OUTPUT_COMPONENTS\":120,\"MAX_VERTEX_UNIFORM_BLOCKS\":12,\"MAX_VERTEX_UNIFORM_COMPONENTS\":16384,\"MIN_PROGRAM_TEXEL_OFFSET\":-8,\"MAX_COMBINED_UNIFORM_BLOCKS\":24,\"MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS\":200704,\"MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS\":212992,\"UNIFORM_BUFFER_OFFSET_ALIGNMENT\":256}"
},
"gl2.precision": {
"s": "[[\"VERTEX_SHADER\",\"LOW_FLOAT\",127,127,23],[\"VERTEX_SHADER\",\"MEDIUM_FLOAT\",127,127,23],[\"VERTEX_SHADER\",\"HIGH_FLOAT\",127,127,23],[\"VERTEX_SHADER\",\"LOW_INT\",31,30,0],[\"VERTEX_SHADER\",\"MEDIUM_INT\",31,30,0],[\"VERTEX_SHADER\",\"HIGH_INT\",31,30,0],[\"FRAGMENT_SHADER\",\"LOW_FLOAT\",127,127,23],[\"FRAGMENT_SHADER\",\"MEDIUM_FLOAT\",127,127,23],[\"FRAGMENT_SHADER\",\"HIGH_FLOAT\",127,127,23],[\"FRAGMENT_SHADER\",\"LOW_INT\",31,30,0],[\"FRAGMENT_SHADER\",\"MEDIUM_INT\",31,30,0],[\"FRAGMENT_SHADER\",\"HIGH_INT\",31,30,0]]"
},
"gl2.texture.linear.readPixels": {
"h": "12a052fdb7d89f",
"n": 16384
},
"gl2.texture.mip.readPixels": {
"h": "12a052fdb7d89f",
"n": 16384
},
"gl2.texture.nearest.readPixels": {
"h": "160f810aa6835f",
"n": 16384
},
"gl2.triangle.drawImage": {
"h": "1f2476721e653d",
"n": 36864
},
"gl2.triangle.readPixels": {
"h": "e35b6ac5b7d59",
"n": 36864
},
"gl2.triangle.toDataURL_jpeg": {
"s": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCABgAGADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDxKiiivTPOCiiigAopDwOaro5MpfnB7e1enl+V1ceqjp/ZV/V9vnqJuyuWaKKK81pp2YwooopAFFFFABRRRQAUUUUAMlPy4HU0RR05U3NmrMUdfdZXbBYZR6vV/wBeR1VaHJTV9yMxHZkdqjrTijqre25hYMPuN+h9K8LOKMZT9vDrv/n/AJnl0qtpezl8itRRRXhHUFFFFABRRRQAUqjJxSVYt4+MnvW+GipVE3sjvy7CvE1kui1YsUdW4o6WKOrcUdevUx3mehjqe4kUdWTbrLEyOPlYYp8UdW4o64KuNvofG46DTujj7y3a1uGifnHIOOoqGu01LTRfW2wELIpyjEd/Q+1cYysjFXBVgcEEYINeepxk9DfB4pV42fxLf/MSiiimdgUUUUAOiQu4UfjWpFHjFQafD8pc9+BWnFHWM8Uqd0j7zJsv9hg1Vkvenr8un+fzEijq3FHSxR1bijriqY7zPPx1PcSKOrcUdLFHVuKOuCpjvM+Nx1PcSKOsHxdpDPF9ugUl0GJVUD7v978On0+ldTFHVuKOuVZk6U1JHys608LVVWHT8Txyit/xboR0m7WSBXNnL91jyEb+7n9Rn9cGsCvp6FeFeCqU3dM+qoV4YimqlN6MKdGhkdUXqTim1p6PAGLSnnHyipxNdYek6jPaybLpZljIYdbPf0W/9dy/DEFAAHAGBVuKOlijqYyQQsFmmjRsZwzAGvk54yU3Zas/VsfCFOOtkvuJIo6txR1SbUrCDbvuYzn+5838s0kniHT4du1pJc9didPzxWXLiqnwU2/kz4jH1qKuudfebMUdW4o65iTxbaogMFtM755DkKMfUZqGbxpNsAtrKNHzyZHLjH0GKn+zsfU2hb1a/wA7nyOLUZ/CzuIo6txR15rL4z1N4ika20THo6ISR+ZI/Sqc3ijWZomja+cKepRVQ/mACKa4fx1T4nFfN/oj53EZXUrbNI9XvtNh1KwltLkMYpRg7TgjnII+hArx3W9Mn0jUprS4VgVPyMRjeueGH1/+t2ok1fUpI2jk1C8eNgVZWnYgg9QRmqNe7lGWYjAOSnUTi+luve9/0Ncsy6rgpSvO8X0t17hUiTyooVJZFA7BiKjor25RUlaSue3TqzpO9OTT8tB0kjyHMjs5xjLHNNooppJKyJlJzfNJ3YUUUUCCiiigAooooAKKKKAP/9k="
},
"gl2.unmasked": {
"s": "[\"Google Inc. (Intel)\",\"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0), or similar\"]"
},
"gpu.webgpu.features": {
"s": "{\"depth-clip-control\":true,\"depth32float-stencil8\":true,\"texture-compression-bc\":true,\"texture-compression-bc-sliced-3d\":true,\"texture-compression-etc2\":false,\"texture-compression-astc\":false,\"texture-compression-astc-sliced-3d\":false,\"timestamp-query\":true,\"indirect-first-instance\":true,\"shader-f16\":true,\"rg11b10ufloat-renderable\":true,\"bgra8unorm-storage\":true,\"float32-filterable\":true,\"float32-blendable\":true,\"clip-distances\":false,\"dual-source-blending\":true,\"subgroups\":false}"
},
"gpu.webgpu.info": {
"s": "{\"vendor\":\"\",\"architecture\":\"\",\"device\":\"\",\"description\":\"\"}"
},
"gpu.webgpu.limits": {
"s": "{\"maxTextureDimension1D\":16384,\"maxTextureDimension2D\":16384,\"maxTextureDimension3D\":2048,\"maxTextureArrayLayers\":2048,\"maxBindGroups\":8,\"maxBindGroupsPlusVertexBuffers\":24,\"maxBindingsPerBindGroup\":4294967295,\"maxDynamicUniformBuffersPerPipelineLayout\":8,\"maxDynamicStorageBuffersPerPipelineLayout\":4,\"maxSampledTexturesPerShaderStage\":64,\"maxSamplersPerShaderStage\":64,\"maxStorageBuffersPerShaderStage\":64,\"maxStorageTexturesPerShaderStage\":64,\"maxUniformBuffersPerShaderStage\":64,\"maxUniformBufferBindingSize\":65536,\"maxStorageBufferBindingSize\":2147483644,\"minUniformBufferOffsetAlignment\":256,\"minStorageBufferOffsetAlignment\":32,\"maxVertexBuffers\":16,\"maxBufferSize\":2147483644,\"maxVertexAttributes\":30,\"maxVertexBufferArrayStride\":2048,\"maxInterStageShaderVariables\":31,\"maxColorAttachments\":8,\"maxColorAttachmentBytesPerSample\":128,\"maxComputeWorkgroupStorageSize\":32768,\"maxComputeInvocationsPerWorkgroup\":1024,\"maxComputeWorkgroupSizeX\":1024,\"maxComputeWorkgroupSizeY\":1024,\"maxComputeWorkgroupSizeZ\":64,\"maxComputeWorkgroupsPerDimension\":65535}"
},
"worker.webgl": {
"s": "{\"vendor\":\"Mozilla\",\"renderer\":\"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0), or similar\",\"unmasked\":[\"Google Inc. (Intel)\",\"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0), or similar\"],\"exts\":[\"ANGLE_instanced_arrays\",\"EXT_blend_minmax\",\"EXT_clip_control\",\"EXT_color_buffer_half_float\",\"EXT_depth_clamp\",\"EXT_float_blend\",\"EXT_frag_depth\",\"EXT_polygon_offset_clamp\",\"EXT_shader_texture_lod\",\"EXT_sRGB\",\"EXT_texture_compression_bptc\",\"EXT_texture_compression_rgtc\",\"EXT_texture_filter_anisotropic\",\"EXT_texture_mirror_clamp_to_edge\",\"OES_element_index_uint\",\"OES_fbo_render_mipmap\",\"OES_standard_derivatives\",\"OES_texture_float\",\"OES_texture_float_linear\",\"OES_texture_half_float\",\"OES_texture_half_float_linear\",\"OES_vertex_array_object\",\"WEBGL_color_buffer_float\",\"WEBGL_compressed_texture_s3tc\",\"WEBGL_compressed_texture_s3tc_srgb\",\"WEBGL_debug_renderer_info\",\"WEBGL_debug_shaders\",\"WEBGL_depth_texture\",\"WEBGL_draw_buffers\",\"WEBGL_lose_context\",\"WEBGL_provoking_vertex\"],\"px\":[64,128,191,255,64,128,191,255,64,128,191,255,64,128,191,255]}"
}
},
"pngs": {
"c2d.composite.png": {
"n": 2414,
"w": 256,
"h": 128,
"ct": 6,
"sha256": "fb585f18240eb1a787a5b146d6332a0376dae76f8c8716e99f68fbbf9eff905e"
},
"c2d.composite.toBlob": {
"n": 1794,
"w": 256,
"h": 128,
"ct": 6,
"sha256": "fb585f18240eb1a787a5b146d6332a0376dae76f8c8716e99f68fbbf9eff905e"
},
"c2d.gradtext.png": {
"n": 55210,
"w": 420,
"h": 210,
"ct": 6,
"sha256": "1ce15c9ea557be69b62b4893b148345a694a93222c721b1bbb21cdcedebba5a0"
},
"c2d.image.png": {
"n": 19502,
"w": 160,
"h": 120,
"ct": 6,
"sha256": "51bc3789f2e238dfbf8899eb7a965a4f04d3e0e7f2246b1bd3cfdc9597bd2a77"
},
"c2d.image.toBlob": {
"n": 14610,
"w": 160,
"h": 120,
"ct": 6,
"sha256": "51bc3789f2e238dfbf8899eb7a965a4f04d3e0e7f2246b1bd3cfdc9597bd2a77"
},
"c2d.offscreen.convertToBlob": {
"n": 2251,
"w": 160,
"h": 80,
"ct": 6,
"sha256": "55b4c78cd7b05627e9b2767477d61063b6849a7636c5be2ce0a62c6a2c6c9cc4"
},
"c2d.scale.high.png": {
"n": 47314,
"w": 220,
"h": 130,
"ct": 6,
"sha256": "8672b8676f90d662b4809e56c55da58e05be4e72b2f7c543b33da4bdafb0ce21"
},
"c2d.scale.low.png": {
"n": 47314,
"w": 220,
"h": 130,
"ct": 6,
"sha256": "8672b8676f90d662b4809e56c55da58e05be4e72b2f7c543b33da4bdafb0ce21"
},
"c2d.scale.medium.png": {
"n": 47314,
"w": 220,
"h": 130,
"ct": 6,
"sha256": "8672b8676f90d662b4809e56c55da58e05be4e72b2f7c543b33da4bdafb0ce21"
},
"c2d.scale.off.png": {
"n": 20890,
"w": 220,
"h": 130,
"ct": 6,
"sha256": "c28700e28636d69dfe9bf293fadebae1fdf970949ac90147836ab1837065f46d"
},
"c2d.shapes.png": {
"n": 19226,
"w": 256,
"h": 160,
"ct": 6,
"sha256": "89ee57c100f4682099bd3a5f2de56c5b31091dae253bd7e3db4f254fb8b9e6a3"
},
"c2d.shapes.toBlob": {
"n": 14402,
"w": 256,
"h": 160,
"ct": 6,
"sha256": "89ee57c100f4682099bd3a5f2de56c5b31091dae253bd7e3db4f254fb8b9e6a3"
},
"c2d.text.png": {
"n": 42670,
"w": 520,
"h": 412,
"ct": 6,
"sha256": "93d6fc37d2263e52e7b1b46f77c65d9e607faf577eb7c255dc38cbce8b7d7602"
},
"c2d.text.toBlob": {
"n": 31986,
"w": 520,
"h": 412,
"ct": 6,
"sha256": "93d6fc37d2263e52e7b1b46f77c65d9e607faf577eb7c255dc38cbce8b7d7602"
},
"gl1.triangle.toDataURL": {
"n": 7474,
"w": 96,
"h": 96,
"ct": 6,
"sha256": "9989d00c92e8ae035dede9b81b1c9942223799c0ccc4d4875c8eca9efaca776c"
},
"gl2.triangle.toDataURL": {
"n": 7474,
"w": 96,
"h": 96,
"ct": 6,
"sha256": "9989d00c92e8ae035dede9b81b1c9942223799c0ccc4d4875c8eca9efaca776c"
}
}
}
+21
View File
@@ -0,0 +1,21 @@
{
"_why": "The four rules the Node driver's user.js writer follows, FROZEN. Until 2026-08-28 prefs_byte_parity.py read them out of src/invisible_playwright/_driver/package/lib/coreBundle.js on every run, deliberately, so that an upstream change moved the gate with it instead of leaving it comparing against a stale transcription. The bundle is being deleted with the Node driver, so the derived fact becomes a recorded one - and this file exists to make that visible rather than silent.",
"_how_to_verify": "While a bundle is still reachable, prefs_byte_parity.py re-extracts and compares against these values, and FAILS on a mismatch. To reach one after the deletion: git worktree add <dir> <the last commit that carried _driver/>, then point the gate at it with INVPW_DRIVER_BUNDLE=<dir>/src/invisible_playwright/_driver/package/lib/coreBundle.js.",
"_what_a_stale_copy_would_cost": "The gate would compare our writer against our own idea of the driver, which always agrees. That is the failure mode the run-time read existed to prevent, and it is why the provenance below is recorded to the byte instead of just being dated.",
"rules": {
"sorts": false,
"header": false,
"separator": true,
"integer_bare": true
},
"provenance": {
"frozen_on": "2026-08-28",
"file": "src/invisible_playwright/_driver/package/lib/coreBundle.js",
"bundle_bytes": 2780363,
"bundle_sha256_16": "97d55ec7f856966d",
"marker": "__ipwLit",
"marker_offset": 1775227,
"window_bytes": 1200,
"window_sha256_16": "4891de086d6625f6"
}
}
+243
View File
@@ -0,0 +1,243 @@
"""The two writers must produce the SAME `user.js`, byte for byte.
⛔ THIS IS THE CRITERION ITEM 1 WAS WRITTEN WITH, and it is stricter than
"both work" on purpose. Two prefs files can each be valid, each configure the
browser, and differ - a header comment, a different order, an integer written
as a string. Every one of those differences is invisible in a running browser
and every one of them means the Python path is configuring a browser the Node
path never configured. The whole point of keeping the driver as a judge is that
this comparison is possible; a looser check throws that away.
⛔ AND IT NEEDS NO BROWSER. Both writers are pure functions of the prefs dict:
the driver's is a JavaScript literal builder inside `coreBundle.js`, ours is
`invisible_core.launch.write_user_js`, the one writer since 0.30.0. The driver's rules are re-implemented here FROM ITS SOURCE,
read at run time rather than copied - so if upstream's writer changes, this gate
changes with it instead of silently comparing against a stale transcription.
python tests/gates/prefs_byte_parity.py
python tests/gates/prefs_byte_parity.py --selftest # 6 mutations, 3 that must not fire
"""
from __future__ import annotations
import argparse
import json
import os
import pathlib
import re
import sys
import tempfile
ROOT = pathlib.Path(__file__).resolve().parent.parent.parent
sys.path.insert(0, str(ROOT / "src"))
BUNDLE = ROOT / "src/invisible_playwright/_driver/package/lib/coreBundle.js"
#: A prefs dict shaped like a real one: the four value kinds that matter, a
#: name with a character JSON has to escape, and a deliberately unsorted order.
#: ⛔ THE ORDER IS PART OF THE FIXTURE. The driver uses `Object.keys()`, so a
#: writer that sorts produces a file that is equally correct and not identical,
#: and that is precisely the class of difference this gate exists to catch.
SAMPLE = {
"zoom.stealth.screen.width": 1920,
"app.update.auto": False,
"layout.css.devPixelsPerPx": "1.25",
"ui.textScaleFactor": 1.0,
"general.useragent.override": 'Mozilla/5.0 "quoted" \\ backslash',
"browser.startup.homepage": "about:blank",
}
class DriverRulesMissing(RuntimeError):
pass
#: The frozen copy, with its provenance. See the file itself for why.
FROZEN = pathlib.Path(__file__).resolve().parent / "driver_prefs_rules.json"
#: Where to find a bundle after the deletion: a git worktree at the last commit
#: that carried `_driver/`. Named here so the gate can say it out loud instead
#: of leaving the reader to work it out.
BUNDLE_ENV = "INVPW_DRIVER_BUNDLE"
def _bundle():
"""A reachable bundle, or None. Never raises: absence is a state."""
named = os.environ.get(BUNDLE_ENV)
if named:
candidate = pathlib.Path(named)
return candidate if candidate.exists() else None
return BUNDLE if BUNDLE.exists() else None
def driver_rules() -> dict:
"""The driver's literal rules: frozen, and re-checked whenever possible.
⛔ IT USED TO READ THE BUNDLE ON EVERY RUN, deliberately, so an upstream
change moved this gate with it instead of leaving it comparing against a
stale transcription. The bundle goes with the Node driver, so the rules are
now RECORDED - in `driver_prefs_rules.json`, with the sha of the bundle and
of the exact 1200-byte window they came from.
⛔ AND THE RE-CHECK IS THE WHOLE POINT OF FREEZING THEM THIS WAY. Whenever a
bundle IS reachable - still in the tree, or named by `INVPW_DRIVER_BUNDLE`
from a git worktree - the rules are extracted again and compared against the
frozen copy, and a mismatch FAILS. A recorded fact nobody can re-derive is a
transcription, and a transcription this gate cannot check is exactly what
the original design refused to have.
"""
frozen = json.loads(FROZEN.read_text(encoding="utf-8"))["rules"]
bundle = _bundle()
if bundle is None:
return frozen
live = _extract(bundle.read_text(encoding="utf-8", errors="replace"))
if live != frozen:
raise DriverRulesMissing(
"the frozen driver rules disagree with the bundle at %s.\n"
" frozen: %s\n bundle: %s\n"
"The frozen copy is stale: re-freeze it with the new provenance, "
"rather than loosening this comparison." % (bundle, frozen, live))
return frozen
def _extract(text: str) -> dict:
start = text.find("__ipwLit")
if start < 0:
raise DriverRulesMissing(
"the driver's pref writer is not in the bundle: it was renamed or "
"removed, and this gate cannot compare against something it "
"cannot read")
window = text[start:start + 1200]
return {
"sorts": "sort()" in window,
"header": bool(re.search(r'"//[^"]*"\s*\+', window)),
"separator": "String.fromCharCode(10)" in window or "\\n" in window,
"integer_bare": "Number.isInteger" in window,
}
def driver_user_js(prefs: dict) -> str:
"""What the driver writes, in Python, following the rules read above."""
rules = driver_rules()
names = sorted(prefs) if rules["sorts"] else list(prefs)
lines = []
for name in names:
value = prefs[name]
if isinstance(value, bool):
literal = "true" if value else "false"
elif isinstance(value, int):
literal = str(value)
elif isinstance(value, float):
# ⛔ Not an integer, so the driver quotes it: Gecko has no float
# pref type, and a bare fraction makes the parser fail and IGNORE
# EVERY LINE AFTER IT.
literal = json.dumps(str(value))
else:
literal = json.dumps(str(value))
lines.append("user_pref(%s, %s);" % (json.dumps(name), literal))
head = "// header\n" if rules["header"] else ""
return head + "\n".join(lines) + "\n"
def ours(prefs: dict) -> str:
from invisible_core.launch import write_user_js
directory = tempfile.mkdtemp(prefix="prefs_parity_")
write_user_js(directory, prefs)
return (pathlib.Path(directory) / "user.js").read_bytes().decode("utf-8")
def compare(prefs: dict) -> list:
theirs = driver_user_js(prefs)
mine = ours(prefs)
if theirs == mine:
return []
faults = []
a, b = theirs.splitlines(), mine.splitlines()
if len(a) != len(b):
faults.append("line count: driver %d, ours %d" % (len(a), len(b)))
for i, (x, y) in enumerate(zip(a, b)):
if x != y:
faults.append("line %d:\n driver: %s\n ours : %s"
% (i + 1, x, y))
if not faults:
faults.append("same lines, different bytes: trailing newline or "
"encoding")
return faults
# ── the selftest ────────────────────────────────────────────────────────────
def selftest() -> int:
bad = 0
def expect(name, produce, should_fire):
nonlocal bad
theirs = driver_user_js(SAMPLE)
mine = produce(theirs)
differs = theirs != mine
if differs != should_fire:
print(" %s: %s" % ("SURVIVED" if should_fire else "FALSE POSITIVE",
name))
bad += 1
else:
print(" %s: %s" % ("killed" if should_fire else "silent", name))
print("--- mutations that MUST fire ---")
expect("a header comment is added",
lambda t: "// written by us\n" + t, True)
expect("the lines are sorted",
lambda t: "\n".join(sorted(t.splitlines())) + "\n", True)
expect("an integer is quoted",
lambda t: t.replace("user_pref(\"zoom.stealth.screen.width\", 1920)",
"user_pref(\"zoom.stealth.screen.width\", \"1920\")"),
True)
expect("a boolean becomes a string",
lambda t: t.replace(", false)", ", \"false\")"), True)
expect("the trailing newline is dropped",
lambda t: t.rstrip("\n"), True)
expect("one pref goes missing",
lambda t: "\n".join(t.splitlines()[1:]) + "\n", True)
print("--- cases that must NOT fire ---")
expect("the same text", lambda t: t, False)
expect("the same text built twice", lambda t: driver_user_js(SAMPLE), False)
expect("a float stays quoted",
lambda t: t.replace('"1.0"', '"1.0"'), False)
print()
print("selftest: %s" % ("ALL GOOD" if not bad else "%d PROBLEMS" % bad))
return 1 if bad else 0
def main() -> int:
p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
p.add_argument("--selftest", action="store_true")
a = p.parse_args()
if a.selftest:
return selftest()
try:
rules = driver_rules()
except DriverRulesMissing as failure:
print("NOT COMPARABLE: %s" % failure)
return 2
# ⛔ IT SAYS WHICH SOURCE IT USED. The line used to read "driver rules read
# from the bundle" unconditionally, and after the freeze that sentence was
# simply false half the time - a gate that misreports where its own
# reference came from is worse than one with no message, because the reader
# stops looking.
bundle = _bundle()
print("driver rules %s: %s"
% ("re-checked against %s" % bundle if bundle
else "from the FROZEN copy (%s) - no bundle reachable, so nothing "
"re-derived them this run" % FROZEN.name,
", ".join("%s=%s" % kv for kv in sorted(rules.items()))))
faults = compare(SAMPLE)
if not faults:
print("PREFS BYTE PARITY: identical (%d prefs)" % len(SAMPLE))
return 0
print("the two writers DISAGREE:")
for f in faults:
print(" " + f)
return 1
if __name__ == "__main__":
sys.exit(main())
@@ -1,31 +0,0 @@
"""`context.add_init_script` added after a page exists runs once in each document, not twice.
The context-level script was registered on both sides: in the browser (`Browser.setInitScripts`, which the engine applies to every
page of the context, the ones already open included) and, for the pages already open, again in each page's own list. A page that
existed when the script was added ran it twice in every later document; a page opened afterwards ran it once, so the test that adds the
script first passed. Playwright runs a context script once in each document of each page.
"""
from __future__ import annotations
import pytest
pytestmark = pytest.mark.e2e
PAGE = ("<!doctype html><title>t</title><script>window.__seen = JSON.stringify(window.__o || []);</script>")
def test_a_context_script_added_after_the_page_exists_runs_once(firefox_binary, tmp_path):
from invisible_playwright import InvisiblePlaywright
(tmp_path / "p.html").write_text(PAGE, encoding="utf-8")
url = (tmp_path / "p.html").as_uri()
with InvisiblePlaywright(seed=4261, binary_path=firefox_binary, headless=True) as browser:
context = browser.new_context()
existing = context.new_page() # the page exists BEFORE the script
context.add_init_script("(window.__o = window.__o || []).push('init');")
later = context.new_page() # and a page opened AFTER it
for page in (existing, later):
page.goto(url, wait_until="load")
assert page.evaluate("window.__o") == ["init"], "the script ran %r" % page.evaluate("window.__o")
page.goto(url + "?again", wait_until="load") # the next document of the same page, too
assert page.evaluate("window.__o") == ["init"], "the second document ran %r" % page.evaluate("window.__o")
@@ -1,99 +0,0 @@
"""A CORS preflight is not a request the client hears of, as on stock Firefox.
A page at one origin fetches another origin with a header that needs a preflight: the browser sends an OPTIONS request first. Playwright's
own server drops an OPTIONS request that no route holds before the client can see it (ffNetworkManager `_onRequestWillBeSent`);
ours reported it, so a page with preflighted fetches showed more requests than on stock (measured on cnbc.com and scmp.com: 10 and
18 OPTIONS requests a page, none on stock). The test counts what the client hears: the document and the two fetches, no OPTIONS, with
and without a context route (a route that holds the request is another story and keeps it).
"""
from __future__ import annotations
import threading
from http.server import BaseHTTPRequestHandler
import pytest
from _servers import LocalServer
pytestmark = pytest.mark.e2e
class _Api(BaseHTTPRequestHandler):
hits: list = []
def log_message(self, *a):
pass
def _cors(self):
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Access-Control-Allow-Headers", "x-test")
self.send_header("Access-Control-Allow-Methods", "GET, OPTIONS")
def do_OPTIONS(self):
_Api.hits.append(("OPTIONS", self.path))
self.send_response(204)
self._cors()
self.end_headers()
def do_GET(self):
_Api.hits.append(("GET", self.path))
body = b'{"ok":1}'
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self._cors()
self.end_headers()
self.wfile.write(body)
def _page(api_origin):
return ("<!doctype html><title>preflight</title><script>"
"fetch('%s/one', {headers: {'x-test': '1'}}); fetch('%s/two', {headers: {'x-test': '2'}});"
"</script>" % (api_origin, api_origin)).encode()
@pytest.fixture
def two_origins():
_Api.hits = []
class Page(BaseHTTPRequestHandler):
def log_message(self, *a):
pass
def do_GET(self):
body = _page(self.server.api_origin)
self.send_response(200)
self.send_header("Content-Type", "text/html")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
api = LocalServer(("127.0.0.1", 0), _Api)
page = LocalServer(("127.0.0.1", 0), Page)
page.api_origin = "http://localhost:%d" % api.server_address[1]
for srv in (api, page):
threading.Thread(target=srv.serve_forever, daemon=True).start()
try:
yield "http://127.0.0.1:%d/" % page.server_address[1]
finally:
for srv in (api, page):
srv.shutdown()
srv.server_close()
@pytest.mark.parametrize("route", [False, True])
def test_the_client_hears_the_document_and_the_fetches_and_no_preflight(firefox_binary, two_origins, route):
from invisible_playwright import InvisiblePlaywright
heard = []
with InvisiblePlaywright(seed=4261, binary_path=firefox_binary, headless=True) as browser:
context = browser.new_context()
if route:
context.route("**/*", lambda r: r.continue_())
page = context.new_page()
page.on("request", lambda r: heard.append((r.method, r.url.rsplit("/", 1)[-1] or "page")))
page.goto(two_origins, wait_until="load")
page.wait_for_timeout(2000) # the events of a sync client are delivered while it calls the browser
assert ("OPTIONS", "/one") in _Api.hits or ("OPTIONS", "/two") in _Api.hits, "the browser made no preflight: %r" % _Api.hits
methods = sorted(m for m, _ in heard)
assert methods == ["GET", "GET", "GET"], "the client heard %r (the server saw %r)" % (heard, _Api.hits)
@@ -11,9 +11,9 @@ from pathlib import Path
TESTS = str(Path(__file__).resolve().parent)
_BUILD = """
from invisible_playwright._juggler._threads import ThreadStarter
from invisible_playwright._juggler.server import _ThreadStarter
def build():
return ThreadStarter(on_error=lambda message: None)
return _ThreadStarter(on_error=lambda message: None)
"""
@@ -81,29 +81,3 @@ def test_a_browser_shared_by_the_tests_of_a_module_may_stay_open_until_the_modul
out = done.stdout + done.stderr
assert done.returncode == 0, out
assert "2 passed" in out, out
def test_the_census_counts_a_starter_whose_thread_has_not_begun(monkeypatch):
"""The starter's thread is begun without waiting for it, so right after the constructor it can be in no `threading.enumerate()`:
the census must still count it (it missed both leaks of a module on a Linux runner, 3 of 3 jobs)."""
import threading
import time
sys.path.insert(0, TESTS)
import _browser_census as census
from invisible_playwright._juggler._threads import ThreadStarter
original = threading.Thread.start
def slow_start(self):
time.sleep(0.3)
return original(self)
monkeypatch.setattr(threading.Thread, "start", slow_start)
before = len(census.starters_alive())
starter = ThreadStarter(on_error=lambda message: None)
try:
assert len(census.starters_alive()) == before + 1
finally:
starter.stop()
assert census.wait_until_back_to(before) == 0
@@ -77,16 +77,12 @@ class _Page:
def test_a_page_the_engine_answers_after_35_s_is_still_a_page(monkeypatch):
monkeypatch.setattr(srv, "PageDispatcher", _Page)
engine = _SlowEngine()
server = Server()
browser = BrowserDispatcher(server, None, engine, "151.0", session_seed=1)
browser = BrowserDispatcher(Server(), None, engine, "151.0", session_seed=1)
engine.browser = browser
context = BrowserContextDispatcher(browser.server, browser, {}, "C1")
browser.contexts.append(context)
try:
result = context.op_new_page({"pageNumber": 0})
finally:
server.shutdown() # the connection's one starter ends with its server
result = context.op_new_page({"pageNumber": 0})
assert result == {"page": {"guid": "page-T0"}}
assert engine.bounds == [None], (
@@ -28,7 +28,6 @@ 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 = {
@@ -38,21 +37,6 @@ 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 = [];
@@ -129,16 +113,6 @@ 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:
@@ -170,7 +144,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=LAB_PREFS) as browser:
headless=True, extra_prefs=STRATEGY_1) as browser:
page = browser.new_context().new_page()
page.set_default_timeout(10000)
page.goto(sites[where]["page"], wait_until="load")
@@ -185,7 +159,6 @@ 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)
@@ -196,25 +169,15 @@ 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)
if promised:
assert ended < committed, "the worker was told ended only after the new page committed: %r" % _methods(events, forward)
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")
# 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
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")
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)
@@ -250,27 +213,3 @@ 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"
@@ -1,286 +0,0 @@
"""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"]
@@ -1,122 +0,0 @@
"""`InProcessTransport.connect` returns without waiting for any thread to start.
`connect` is a coroutine of the user's event loop, and `Thread.start` does not return until the new thread is running. Measured with
four browsers in one process under CPU load on Windows, the four worker starts held the loop ~200 ms per launch (4.4% of the main
thread's wall time). The workers are now started by a bootstrapper that is not the loop (and is itself begun without a
`Thread.start`), and a message sent right after `connect` waits in the queue until a worker runs.
NO BROWSER HERE: a scripted server behind the real transport, with `Thread.start` slowed to 300 ms, the way a loaded machine slows it.
Known-bad input: workers started inside `connect` -> `connect` takes 4 x 300 ms and fails the 50 ms bound.
"""
from __future__ import annotations
import asyncio
import threading
import time
import pytest
from invisible_playwright._juggler.dispatcher import Server
from invisible_playwright._juggler.transport import InProcessTransport
pytestmark = pytest.mark.unit
START_DELAY_S = 0.3
class _Server(Server):
"""The registry's base class, whose `thread_starter` the transport starts its workers through, answering every call with its id."""
def handle(self, message):
return {"echo": message["id"]}
def test_connect_returns_before_any_worker_has_started_and_a_message_is_still_answered(monkeypatch):
original = threading.Thread.start
def slow_start(self):
time.sleep(START_DELAY_S)
return original(self)
monkeypatch.setattr(threading.Thread, "start", slow_start)
async def scenario():
loop = asyncio.get_running_loop()
transport = InProcessTransport(loop, _Server())
replies: "asyncio.Queue" = asyncio.Queue()
transport.on_message = replies.put_nowait
began = time.perf_counter()
await transport.connect()
took = time.perf_counter() - began
transport.send({"id": 7, "guid": "g", "method": "m", "params": {}})
reply = await asyncio.wait_for(replies.get(), 10)
transport.request_stop()
await asyncio.wait_for(transport.wait_until_stopped(), 10)
return took, reply
took, reply = asyncio.run(scenario())
assert took < 0.05, "connect() waited %.0f ms: a thread was started on the loop" % (took * 1000)
assert reply == {"id": 7, "result": {"echo": 7}}
def test_a_transport_stopped_before_its_workers_started_ends_without_error(monkeypatch):
original = threading.Thread.start
def slow_start(self):
time.sleep(START_DELAY_S)
return original(self)
monkeypatch.setattr(threading.Thread, "start", slow_start)
async def scenario():
transport = InProcessTransport(asyncio.get_running_loop(), _Server())
await transport.connect()
transport.request_stop()
await asyncio.wait_for(transport.wait_until_stopped(), 10)
asyncio.run(scenario())
def test_building_the_shared_starter_waits_for_no_thread_start(monkeypatch):
"""The starter every caller of `ThreadStarter` builds on its own thread must not itself cost a `Thread.start` there."""
from invisible_playwright._juggler._threads import ThreadStarter
original = threading.Thread.start
def slow_start(self):
time.sleep(START_DELAY_S)
return original(self)
monkeypatch.setattr(threading.Thread, "start", slow_start)
began = time.perf_counter()
starter = ThreadStarter(on_error=lambda why: None)
ran = threading.Event()
starter.start(target=ran.set, name="invpw-test-started")
took = time.perf_counter() - began
try:
assert took < 0.05, "building the starter and queueing a thread waited %.0f ms" % (took * 1000)
assert ran.wait(10), "the queued thread never ran"
finally:
starter.stop()
def test_a_browsers_reader_and_the_transports_workers_share_ONE_starter():
"""Each browser costs one starter thread, not two: the transport's workers and the browser's lease both go through the server's."""
from invisible_playwright._juggler._threads import ThreadStarter, ThreadStarterLease
async def scenario():
server = _Server()
transport = InProcessTransport(asyncio.get_running_loop(), server)
before = len(ThreadStarter.open_starters())
await transport.connect()
lease = ThreadStarterLease(lambda: server.thread_starter)
ran = threading.Event()
lease.start(target=ran.set, name="invpw-test-started")
assert ran.wait(10)
opened = len(ThreadStarter.open_starters()) - before
transport.request_stop()
await asyncio.wait_for(transport.wait_until_stopped(), 10)
return opened
assert asyncio.run(scenario()) == 1
+19 -53
View File
@@ -27,22 +27,18 @@ needs an ``invisible-core`` that declares them.
Layers:
* ``unit`` - ``_BASELINE`` contains the prefs with the right values. No browser.
* ``e2e`` - launch the real binary against a LOCAL HTTP harness and
verify the four protocol operations that regressed: frame URL
tracking, ``handle.content_frame()``, ``frame.evaluate()``, and
``frame_locator(...).locator(...)`` element resolution. The page
is served from ``127.0.0.1`` and its iframes from ``localhost``:
two hosts are two SITES, so at strategy 1 each iframe runs in a
content process of its own. (Two ports of one host would be one
site, and those iframes would stay in the process of the page.)
``test_the_iframe_runs_in_another_process`` proves it from
inside the pages, so this file cannot fall back to the process
of the page unnoticed. The bench with its own hosts and
process counts is ``test_fission_strategy1_bench.py``.
* ``e2e`` - launch the real binary against a LOCAL HTTP harness on
``127.0.0.1`` and verify the four protocol operations that
regressed: frame URL tracking, ``handle.content_frame()``,
``frame.evaluate()``, and ``frame_locator(...).locator(...)``
element resolution. The harness uses two ports of one host,
which is one SITE: those iframes stay in the process of the
page even at strategy 1. The iframes that leave the process
(different hosts) are held by ``test_fission_strategy1_bench.py``.
The e2e tests run entirely offline. They never call out to a real site;
the cross-site shape is reproduced with two local HTTP servers on random
free ports, reached by two names of the loopback interface.
the cross-origin shape is reproduced with two local HTTP servers on
random free ports.
"""
from __future__ import annotations
@@ -172,13 +168,12 @@ def _serve(payload: bytes) -> tuple[ThreadingHTTPServer, int]:
@pytest.fixture
def cross_origin_harness():
"""Spin up TWO local HTTP servers: the page on ``127.0.0.1``, the iframes on ``localhost``.
"""Spin up TWO local HTTP servers on different localhost ports.
Two hosts = two SITES (and two origins under SOP). The parent page
embeds iframes with src pointing at the other host, which at strategy 1
puts them in another content process. Same cross-site browsing-context
shape as a parent-page-plus-third-party-iframe layout, fully offline.
The servers listen on 127.0.0.1 and the child is named ``localhost``.
Two ports = two distinct origins under SOP (same host, different port
→ different origin). The parent page on port A embeds an iframe with
src pointing at port B. Same cross-origin browsing-context shape as
a parent-page-plus-third-party-iframe layout, fully offline.
"""
# The CHILD goes up first, because the parent's markup has to name the
# child's port and there is no longer a way to learn that number without
@@ -191,49 +186,20 @@ def cross_origin_harness():
sb, pb = _serve(child_html)
parent_html = f"""<!doctype html><html><head><title>parent</title></head><body>
<h1>parent</h1>
<iframe id="ifr_plain" src="http://localhost:{pb}/child" width="300" height="120"></iframe>
<iframe id="ifr_sandbox" src="http://localhost:{pb}/child" width="300" height="120"
<iframe id="ifr_plain" src="http://127.0.0.1:{pb}/child" width="300" height="120"></iframe>
<iframe id="ifr_sandbox" src="http://127.0.0.1:{pb}/child" width="300" height="120"
sandbox="allow-scripts allow-same-origin"></iframe>
<iframe id="ifr_titled" src="http://localhost:{pb}/child" width="300" height="120"
<iframe id="ifr_titled" src="http://127.0.0.1:{pb}/child" width="300" height="120"
title="cross-origin titled iframe"></iframe>
</body></html>""".encode("utf-8")
sa, pa = _serve(parent_html)
try:
yield {"parent_url": f"http://127.0.0.1:{pa}/", "child_origin": f"http://localhost:{pb}"}
yield {"parent_url": f"http://127.0.0.1:{pa}/", "child_origin": f"http://127.0.0.1:{pb}"}
finally:
sa.shutdown()
sb.shutdown()
@pytest.mark.e2e
def test_the_iframe_runs_in_another_process(firefox_binary, cross_origin_harness):
"""The harness of this file really crosses a process: a spin in the iframe does not stall the page.
The iframe spins for 600 ms and the page times a 10 ms timer; the timer
stalls only when both share a content process. Without this, a harness
that went back to two ports of one host would keep every test below green
while testing a same-process iframe.
"""
from _fission_frames import assert_other_process
from invisible_playwright import InvisiblePlaywright
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, humanize=False) as browser:
page = browser.new_context().new_page()
# ⛔ `load`, NOT `domcontentloaded`. The `domcontentloaded` of a page says nothing about its frames: the
# frame of another site is listed as soon as it is attached, and its url is the one of its navigation,
# which commits in the frame's own process, usually AFTER the page's domcontentloaded. Read straight after
# a `domcontentloaded` goto the url was empty in 26 reads of 30 on firefox-62 (stock Playwright Firefox,
# whose frames commit in the process of the page, had it 30 of 30). After the `load` of the page the url
# was there 30 of 30 on both, with no wait: that is what is asserted here, so a `goto` that returns
# with a cross-site frame still without its url fails this test.
page.goto(cross_origin_harness["parent_url"], wait_until="load", timeout=30_000)
page.wait_for_selector("iframe#ifr_plain", timeout=10_000)
frame = page.query_selector("iframe#ifr_plain").content_frame()
assert frame is not None and cross_origin_harness["child_origin"] in frame.url, (
f"after the load of the page the iframe of the other site has url {getattr(frame, 'url', None)!r}")
assert_other_process(page.main_frame, frame)
@pytest.mark.e2e
def test_cross_origin_iframe_url_appears_in_page_frames(firefox_binary, cross_origin_harness):
"""``page.frames`` must list the cross-origin iframe with its real URL.
-109
View File
@@ -1,109 +0,0 @@
"""`Locator.screenshot()` / `ElementHandle.screenshot()` photograph the element: its size, its pixels, wherever it is.
The wrapper had no `screenshot` on an element handle ("ElementHandle has no method 'screenshot'"). The picture is the page's own
screenshot of the element's box, so the checks are the ones that can go wrong with a box: an element below the fold (it has to be
scrolled in and the document scroll added to a box that is in viewport coordinates), an element inside a frame that the page has
scrolled, an `<iframe>` element itself, and the size of the picture being the size of the box.
"""
from __future__ import annotations
import struct
import zlib
import pytest
pytestmark = pytest.mark.e2e
GREEN, PINK = (0, 204, 68), (255, 0, 170)
PAGE = (
"<!doctype html><title>shot</title><body style='margin:0;background:#fff'>"
"<div id='top' style='position:absolute;left:20px;top:10px;width:30px;height:20px;background:#ff00aa'></div>"
"<div id='below' style='position:absolute;left:40px;top:2500px;width:80px;height:60px;background:#00cc44'></div>"
"<iframe id='f' style='position:absolute;left:100px;top:900px;width:200px;height:120px;border:0' srcdoc=\""
"<body style='margin:0;background:#ff00aa'><div style='height:600px'></div>"
"<div id='inner' style='margin-left:15px;width:50px;height:40px;background:#00cc44'></div>"
"<div style='height:900px'></div>\"></iframe>"
"<div style='position:absolute;top:4000px;width:1px;height:1px'></div>"
)
def decode_png(data: bytes):
"""(width, height, pixel(x, y)) of an 8-bit RGB/RGBA PNG without interlacing."""
assert data[:8] == b"\x89PNG\r\n\x1a\n", "not a PNG"
pos, idat, width = 8, b"", 0
while pos < len(data):
length, kind = struct.unpack(">I4s", data[pos:pos + 8])
body = data[pos + 8:pos + 8 + length]
if kind == b"IHDR":
width, height, depth, color, _c, _f, interlace = struct.unpack(">IIBBBBB", body)
assert depth == 8 and color in (2, 6) and interlace == 0, (depth, color, interlace)
step = 3 if color == 2 else 4
elif kind == b"IDAT":
idat += body
pos += 12 + length
raw, stride, rows, prev = zlib.decompress(idat), width * step, [], bytearray(width * step)
for y in range(height):
ft, line = raw[y * (stride + 1)], bytearray(raw[y * (stride + 1) + 1:(y + 1) * (stride + 1)])
for i in range(stride):
a = line[i - step] if i >= step else 0
b = prev[i]
c = prev[i - step] if i >= step else 0
if ft == 1:
line[i] = (line[i] + a) & 255
elif ft == 2:
line[i] = (line[i] + b) & 255
elif ft == 3:
line[i] = (line[i] + (a + b) // 2) & 255
elif ft == 4:
p = a + b - c
pa, pb, pc = abs(p - a), abs(p - b), abs(p - c)
line[i] = (line[i] + (a if pa <= pb and pa <= pc else b if pb <= pc else c)) & 255
rows.append(line)
prev = line
return width, height, lambda x, y: tuple(rows[y][x * step:x * step + 3])
def _near(a, b, tol=6):
return all(abs(p - q) <= tol for p, q in zip(a, b))
def _whole(png, color):
width, height, pixel = decode_png(png)
for x, y in ((0, 0), (width - 1, 0), (0, height - 1), (width - 1, height - 1), (width // 2, height // 2)):
assert _near(pixel(x, y), color), ((x, y), pixel(x, y), color)
return width, height
def test_an_element_screenshot_is_the_element_wherever_it_is(firefox_binary, tmp_path):
from invisible_playwright import InvisiblePlaywright
(tmp_path / "p.html").write_text(PAGE, encoding="utf-8")
with InvisiblePlaywright(seed=4262, binary_path=firefox_binary, headless=True) as browser:
page = browser.new_context().new_page()
page.goto((tmp_path / "p.html").as_uri(), wait_until="load")
# in view
assert _whole(page.locator("#top").screenshot(scale="css"), PINK) == (30, 20)
# far below the fold: scrolled in, then the document scroll is added to its viewport box
assert page.evaluate("window.scrollY") == 0
assert _whole(page.locator("#below").screenshot(scale="css"), GREEN) == (80, 60)
# the same element again, now that the page has scrolled to it
assert _whole(page.locator("#below").screenshot(scale="css"), GREEN) == (80, 60)
# an element in a frame, below that frame's fold, in a page that is scrolled: size and pixels
frame = page.frames[1]
assert _whole(frame.locator("#inner").screenshot(scale="css"), GREEN) == (50, 40)
# the <iframe> element is the frame: pink around, the green swatch inside it
width, height, pixel = decode_png(page.locator("#f").screenshot(scale="css"))
assert (width, height) == (200, 120)
assert _near(pixel(3, 3), PINK)
def test_an_element_that_is_not_there_has_no_screenshot(firefox_binary, tmp_path):
from invisible_playwright import InvisiblePlaywright
(tmp_path / "p.html").write_text("<!doctype html><div id='gone' style='display:none'>x</div>", encoding="utf-8")
with InvisiblePlaywright(seed=4263, binary_path=firefox_binary, headless=True) as browser:
page = browser.new_context().new_page()
page.goto((tmp_path / "p.html").as_uri(), wait_until="load")
with pytest.raises(Exception, match="not visible"):
page.locator("#gone").screenshot(timeout=2000)
-283
View File
@@ -1,283 +0,0 @@
"""`page.expose_function` / `page.expose_binding` / `context.expose_function` / `context.expose_binding`.
They used to refuse ("not wired" / "no method 'exposeBinding'"). The page calls a Python function and gets its answer as a
promise: the value, a rejection when the Python function raised, an await when it is async.
THE RULE THAT MATTERS MORE THAN THE FEATURE: A PAGE SEES `foo` AND NOTHING ELSE. A page can list the names on its window, so a
transport left there is the driver's signature. These tests read what the page reads: the own properties of `window` (names and
symbols) with and without an exposed function, in the top, in a frame of another site (another process), in the document born
after a navigation and after `document.open()`; what `foo.toString()` and the stack of an error from `foo` say; and that `foo`
looks like a function the page defined itself (name, length, descriptor, own properties, position among the keys).
"""
from __future__ import annotations
import http.server
import threading
import pytest
pytestmark = pytest.mark.e2e
PAGE = "<!doctype html><title>t</title><body><iframe id='f' srcdoc='<p>frame</p>'></iframe>"
# What a page can read of its own window: every own name, own symbols, and the enumeration order.
WINDOW = ("(() => ({names: Object.getOwnPropertyNames(window).sort(), keys: Object.keys(window),"
" symbols: Object.getOwnPropertySymbols(window).map(String)}))()")
#: Words that would give the driver away, in anything the page can read.
TELLS = ("playwright", "binding", "juggler", "invisible", "chrome://", "resource://", "moz-src", "debugger eval")
@pytest.fixture
def browser(firefox_binary):
from invisible_playwright import InvisiblePlaywright
with InvisiblePlaywright(seed=4264, binary_path=firefox_binary, headless=True) as b:
yield b
@pytest.fixture
def url(tmp_path):
(tmp_path / "p.html").write_text(PAGE, encoding="utf-8")
return (tmp_path / "p.html").as_uri()
def _extra(seen, base):
return sorted(set(seen["names"]) - set(base["names"])), sorted(set(seen["symbols"]) - set(base["symbols"]))
def test_a_page_function_exposed_before_the_load_answers_and_survives_a_navigation(browser, url):
page = browser.new_context().new_page()
page.expose_function("add", lambda a, b: a + b)
for target in (url, url + "?again"):
page.goto(target, wait_until="load")
assert page.evaluate("add(2, 3)") == 5
def test_a_page_function_exposed_after_the_load_reaches_the_document_that_exists(browser, url):
page = browser.new_context().new_page()
page.goto(url, wait_until="load")
page.expose_function("twice", lambda x: x * 2)
assert page.evaluate("twice(21)") == 42
def test_two_functions_on_one_page_answer_each_its_own_calls(browser, url):
page = browser.new_context().new_page()
page.expose_function("one", lambda: "one")
page.expose_function("two", lambda: "two")
page.goto(url, wait_until="load")
assert page.evaluate("Promise.all([one(), two(), two(), one()])") == ["one", "two", "two", "one"]
def test_the_answer_is_awaited_and_a_python_error_rejects_the_promise(browser, url):
page = browser.new_context().new_page()
def boom(_):
raise ValueError("nope from python")
async def slow(x):
return {"got": x, "list": [1, 2]}
page.expose_function("boom", boom)
page.expose_function("slow", slow)
page.goto(url, wait_until="load")
assert page.evaluate("slow('a')") == {"got": "a", "list": [1, 2]}
assert "nope from python" in page.evaluate("boom(1).then(() => 'resolved', e => String(e.message))")
def test_a_binding_gets_the_source_page_and_frame(browser, url):
page = browser.new_context().new_page()
seen = {}
def binding(source, value):
seen.update(page=source["page"], frame=source["frame"], context=source["context"])
return value
page.expose_binding("who", binding)
page.goto(url, wait_until="load")
assert page.evaluate("who('x')") == "x"
assert seen["page"] is page and seen["frame"] is page.main_frame and seen["context"] is page.context
def test_a_page_function_is_not_on_another_page_of_the_context(browser, url):
context = browser.new_context()
first, second = context.new_page(), context.new_page()
first.expose_function("mine", lambda: "first")
first.goto(url, wait_until="load")
second.goto(url, wait_until="load")
assert first.evaluate("typeof mine") == "function"
assert second.evaluate("typeof mine") == "undefined"
def test_a_context_function_is_on_the_page_that_exists_the_page_to_come_and_their_frames(browser, url):
context = browser.new_context()
existing = context.new_page()
existing.goto(url, wait_until="load")
context.expose_function("ctx", lambda x: "ctx:" + x)
later = context.new_page()
later.goto(url, wait_until="load")
for page in (existing, later):
assert page.evaluate("ctx('a')") == "ctx:a"
frame = page.frames[1]
assert frame.evaluate("ctx('b')") == "ctx:b"
existing.goto(url + "?again", wait_until="load")
assert existing.evaluate("ctx('c')") == "ctx:c"
def test_a_disposed_function_is_gone_now_and_in_the_documents_to_come(browser, url):
page = browser.new_context().new_page()
page.goto(url, wait_until="load")
handle = page.expose_function("gone", lambda: 1)
assert page.evaluate("gone()") == 1
handle.dispose()
assert page.evaluate("typeof gone") == "undefined"
page.goto(url + "?again", wait_until="load")
assert page.evaluate("typeof gone") == "undefined"
# ── what the page can read ──────────────────────────────────────────────────────────────────────────────────────────────────
def test_without_an_exposed_function_nothing_is_added_and_with_one_only_its_name(browser, url):
"""No `expose_*`: the engine installs nothing, and the window has no name that is ours. After `expose_function('foo')` the
window has `foo` more, and no symbol more: the transport is not reachable."""
plain = browser.new_context().new_page()
plain.goto(url, wait_until="load")
base = plain.evaluate(WINDOW)
assert not [n for n in base["names"] if any(t in n.lower() for t in ("playwright", "binding", "juggler"))]
context = browser.new_context()
page = context.new_page()
context.expose_function("foo", lambda x: x)
page.goto(url, wait_until="load")
seen = page.evaluate(WINDOW)
assert _extra(seen, base) == (["foo"], [])
assert seen["keys"][: len(base["keys"])] == base["keys"], "the order of the keys moved"
assert seen["keys"][-1] == "foo"
def test_the_only_name_is_foo_in_a_frame_of_another_site_and_in_the_document_after_a_navigation(browser, tmp_path):
"""127.0.0.1 and localhost are two sites, so two processes. The frame of the other site, a nested frame, the document the
page navigates to and the one a `document.open()` rewrites: each shows `foo` and nothing else."""
class Handler(http.server.BaseHTTPRequestHandler):
pages = {}
def do_GET(self):
body = self.pages.get(self.path.split("?")[0], "<!doctype html><title>t</title>").encode()
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 log_message(self, *_):
pass
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
port = server.server_address[1]
Handler.pages = {
"/top": "<!doctype html><title>top</title><iframe src='http://localhost:%d/child'></iframe>" % port,
"/child": "<!doctype html><title>child</title><iframe src='http://127.0.0.1:%d/grand'></iframe>" % port,
"/grand": "<!doctype html><title>grand</title>",
}
try:
plain = browser.new_context().new_page()
plain.goto("http://127.0.0.1:%d/top" % port, wait_until="load")
plain.wait_for_function("window.frames.length >= 0")
plain.wait_for_timeout(1500)
base = {f.url: f.evaluate(WINDOW) for f in plain.frames}
assert len(base) == 3, sorted(base)
context = browser.new_context()
page = context.new_page()
context.expose_function("foo", lambda x: x)
for target in ("http://127.0.0.1:%d/top" % port, "http://127.0.0.1:%d/top?again" % port):
page.goto(target, wait_until="load")
page.wait_for_timeout(1500)
seen = {f.url.split("?")[0]: f.evaluate(WINDOW) for f in page.frames}
assert sorted(seen) == sorted(base)
for frame_url, window in seen.items():
assert _extra(window, base[frame_url]) == (["foo"], []), frame_url
# a child that reads its parent and its top finds no name of ours either
child = next(f for f in page.frames if f.url.startswith("http://localhost"))
# (cross-site: the parent is opaque to the child, which is the point; the same-origin case is the srcdoc test below)
assert child.evaluate("typeof foo") == "function"
# after document.open() the window of the document is the one it was
page.evaluate("document.open(); document.write('<!doctype html><p>again</p>'); document.close()")
after = page.evaluate(WINDOW)
assert _extra(after, base[sorted(base)[0]]) == (["foo"], []) or "foo" in after["names"]
assert not [n for n in after["names"] if any(t in n.lower() for t in ("playwright", "binding", "juggler"))]
finally:
server.shutdown()
def test_a_same_origin_child_reading_parent_and_top_finds_nothing_more_than_foo(browser, url):
plain = browser.new_context().new_page()
plain.goto(url, wait_until="load")
base = plain.evaluate(WINDOW)
context = browser.new_context()
page = context.new_page()
page.expose_function("foo", lambda x: x)
page.goto(url, wait_until="load")
child = page.frames[1]
for reach in ("parent", "top"):
seen = child.evaluate("(() => ({names: Object.getOwnPropertyNames(%s).sort(), symbols: Object.getOwnPropertySymbols(%s).length}))()"
% (reach, reach))
assert _extra({"names": seen["names"], "symbols": []}, base) == (["foo"], []), reach
assert seen["symbols"] == 0
page.evaluate("document.open(); document.write('<!doctype html><p>again</p>'); document.close()")
assert _extra(page.evaluate(WINDOW), base) == (["foo"], [])
def test_foo_reads_as_a_function_the_page_defined(browser, url):
"""Its source, its name, its length, its own properties, its descriptor on the window and its place among the keys are those of
`window.bar = function (...args) { ... }` written by the page, and nothing in what it says or in the stack of an error raised
from it names the driver."""
page = browser.new_context().new_page()
page.expose_function("foo", lambda x: x)
page.expose_function("raises", lambda x: (_ for _ in ()).throw(ValueError("python said no")))
page.goto(url, wait_until="load")
# a script tag runs in the page's own realm (an evaluate runs in the caller's, whose Function.prototype is another one)
page.add_script_tag(content="window.bar = function (...args) { return args; }")
read = page.evaluate("""(() => {
const d = n => { const x = Object.getOwnPropertyDescriptor(window, n); return {w: x.writable, e: x.enumerable, c: x.configurable, t: typeof x.value}; };
// the own properties FIRST: reading `name` or `length` resolves them and moves them in the list
const own = Object.getOwnPropertyNames(foo), ownBar = Object.getOwnPropertyNames(bar);
return {
own, ownBar, name: foo.name, length: foo.length,
desc: d('foo'), descBar: d('bar'), proto: Object.getPrototypeOf(foo) === Object.getPrototypeOf(bar),
source: foo.toString(), symbols: Object.getOwnPropertySymbols(foo).length,
keys: Object.keys(window).filter(k => k === 'foo' || k === 'bar' || k === 'raises'),
ctor: foo.constructor === bar.constructor,
};
})()""")
assert read["name"] == "foo" and read["length"] == 0
assert read["own"] == read["ownBar"]
assert read["desc"] == read["descBar"] and read["symbols"] == 0 and read["proto"] and read["ctor"]
assert read["keys"] == ["foo", "raises", "bar"], read["keys"]
assert not [t for t in TELLS if t in read["source"].lower()], read["source"]
# the stack of an error thrown by the call itself (a value that cannot be sent) and of a rejection from Python
stacks = page.evaluate("""(async () => {
const out = [];
try { await foo(1n); } catch (e) { out.push(String(e.stack), String(e.message), e.name); }
try { await raises(1); } catch (e) { out.push(String(e.stack), String(e.message), e.name); }
return out;
})()""")
assert len(stacks) == 6
for text in stacks:
assert not [t for t in TELLS if t in text.lower()], text
assert "python said no" in stacks[4]
def test_a_worker_gets_nothing(browser, url):
"""The engine installs a binding in the frames of a page, as Playwright's does: a worker has no `foo`, and its global
has nothing more than a worker of a page without one."""
page = browser.new_context().new_page()
probe = ("new Promise(r => { const w = new Worker(URL.createObjectURL(new Blob(["
"'postMessage(JSON.stringify({foo: typeof foo, names: Object.getOwnPropertyNames(self).sort()}))'])));"
" w.onmessage = e => r(JSON.parse(e.data)); })")
page.goto(url, wait_until="load")
base = page.evaluate(probe)
page.expose_function("foo", lambda: 1)
page.goto(url + "?again", wait_until="load")
seen = page.evaluate(probe)
assert seen == base and seen["foo"] == "undefined"
-35
View File
@@ -1,35 +0,0 @@
"""Exposed functions need an engine that hands the page-side end of a binding over and has `Page.addBinding`.
No fallback to a name on the window: an engine without them is refused with a sentence that says so, before anything is installed.
(No browser: the engine is read from its files.)
"""
from __future__ import annotations
import pytest
pytestmark = pytest.mark.unit
def test_an_engine_without_what_the_functions_need_refuses_and_leaves_no_name(tmp_path):
"""No fallback to a name on the window: an engine without `Page.addBinding` and the binding that hands its end over is
refused with a sentence that says so."""
from invisible_playwright._juggler import _bindings
from invisible_playwright._juggler.dispatcher import ProtocolException
from invisible_playwright._juggler.server import BrowserContextDispatcher
loose = tmp_path / "modules" / "juggler" / "protocol"
loose.mkdir(parents=True)
(loose / "Protocol.js").write_text("'addBinding': { params: {} },", encoding="utf-8")
assert _bindings.engine_supports(str(tmp_path)) is False # one addBinding: the browser's only
assert _bindings.engine_supports("") is False
(loose / "Protocol.js").write_text("'addBinding': { params: {} },\n'addBinding': { params: {} },", encoding="utf-8")
_bindings.engine_supports.cache_clear()
assert _bindings.engine_supports(str(tmp_path)) is True
class Browser:
engine_dir = str(tmp_path / "old")
context = object.__new__(BrowserContextDispatcher)
context.__dict__["browser"] = Browser()
with pytest.raises(ProtocolException, match="newer engine"):
BrowserContextDispatcher.require_binding_engine(context)
@@ -1,178 +0,0 @@
"""What a frame of another site starts reaches the page, and the answer reaches back.
A page of site A holds a frame of site B, which holds a frame of site C. From inside each of those two frames a
script opens a dialog (`alert`, `confirm`, `prompt`), a link starts a download, and `window.open` or a
`target=_blank` link opens a popup. In Fission the frame's process is not the page's, and each of these crosses
back to the browser process: the dialog is raised by the frame's process and answered by the driver, the download
belongs to the frame's channel, the popup is created by the frame's window with the frame's origin as its opener.
Asserted, and the same as stock Playwright Firefox does it:
* the `dialog` event of the PAGE fires for a dialog of a frame, with its type, message and default value, and what
the handler decides is what the frame's script gets back (`confirm` true or false, `prompt` the text or null);
* `page.expect_download()` fires for a link of the frame, with the file name, the url and the bytes served;
* `page.expect_popup()` fires for `window.open` and for a `target=_blank` link of the frame; the popup is at the
url asked for and `popup.opener()` is the page whose frame opened it; its `window.opener` is there for
`window.open` and absent for a `target=_blank` link, with or without `rel=noopener` (a link to a new tab is
`noopener` by default).
The first test proves the frames are in other processes (`_fission_frames.assert_other_process`), so the file
cannot turn into a same-process suite.
"""
from __future__ import annotations
import pytest
from _fission_frames import Sites, assert_other_process, launch, new_page, wait_frame
pytestmark = pytest.mark.e2e
PAYLOAD = b"fission-frame-download\x00\x01\x02" * 50
#: The controls of a document that starts things; `%s` is the url of the popup it opens.
CONTROLS = ("<button id='open' onclick=\"window.__win = window.open(%(popup)s)\">open</button>"
"<a id='blank' href=%(popup)s target='_blank'>blank</a>"
"<a id='noopener' href=%(popup)s target='_blank' rel='noopener'>noopener</a>"
"<a id='dl' href='/file.bin' download>download</a>"
"<a id='dl-header' href='/attachment.bin'>download by header</a>")
@pytest.fixture
def sites():
with Sites() as s:
popup = "'%s'" % s.url("C", "/popup")
s.route("A", "/top", "<!doctype html><title>top</title><iframe id='b' src='%s' width='600' height='300'>"
"</iframe>" % s.url("B", "/frame"))
s.route("B", "/frame", "<!doctype html><title>frame</title>" + CONTROLS % {"popup": popup}
+ "<iframe id='c' src='%s' width='450' height='150'></iframe>" % s.url("C", "/nested"))
s.route("C", "/nested", "<!doctype html><title>nested</title>" + CONTROLS % {"popup": popup})
s.route("C", "/popup", "<!doctype html><title>popup</title><body>popup at C"
"<script>window.__opener = window.opener !== null;</script>")
for site in ("B", "C"):
s.route(site, "/file.bin", PAYLOAD, ctype="application/octet-stream")
s.route(site, "/attachment.bin", PAYLOAD, ctype="application/octet-stream",
headers=[("Content-Disposition", 'attachment; filename="by-header.bin"')])
yield s
@pytest.fixture(scope="module")
def browser(firefox_binary):
with launch(firefox_binary) as browser:
yield browser
@pytest.fixture
def page(browser):
context, page = new_page(browser)
yield page
context.close()
@pytest.fixture
def opened(page, sites):
"""The page loaded, and the frame of B and the frame of C nested in it."""
page.goto(sites.url("A", "/top"), wait_until="load")
b = wait_frame(page, sites.url("B"), "/frame")
c = wait_frame(page, sites.url("C"), "/nested")
return page, {"frame": b, "nested": c}
def test_the_frames_are_in_other_processes(opened):
page, frames = opened
assert_other_process(page.main_frame, frames["frame"])
assert_other_process(frames["frame"], frames["nested"])
# ---------------------------------------------------------------------------
# dialogs
# ---------------------------------------------------------------------------
@pytest.mark.parametrize("target", ["frame", "nested"])
@pytest.mark.parametrize("kind,accept,text,expected", [
("alert", True, None, "returned"),
("confirm", True, None, True),
("confirm", False, None, False),
("prompt", True, "typed answer", "typed answer"),
("prompt", False, None, None),
])
def test_a_dialog_of_a_frame_reaches_the_page_and_the_answer_goes_back(opened, target, kind, accept, text,
expected):
page, frames = opened
frame = frames[target]
seen = []
def on_dialog(dialog):
seen.append((dialog.type, dialog.message, dialog.default_value))
if accept:
dialog.accept(text) if text is not None else dialog.accept()
else:
dialog.dismiss()
page.on("dialog", on_dialog)
call = {"alert": "alert('hello from the frame'); window.__r = {v: 'returned'}",
"confirm": "window.__r = {v: confirm('sure?')}",
"prompt": "window.__r = {v: prompt('name?', 'default text')}"}[kind]
frame.evaluate("() => { window.__r = null; setTimeout(() => { %s }, 0); }" % call)
frame.wait_for_function("window.__r !== null")
assert frame.evaluate("window.__r.v") == expected
message, default = {"alert": ("hello from the frame", ""), "confirm": ("sure?", ""),
"prompt": ("name?", "default text")}[kind]
assert seen == [(kind, message, default)]
def test_two_dialogs_one_after_the_other_from_different_frames(opened):
"""The dialog of the nested frame, then the one of its parent: each answered in turn by the same handler."""
page, frames = opened
answers = iter([True, False])
page.on("dialog", lambda dialog: dialog.accept() if next(answers) else dialog.dismiss())
nested, frame = frames["nested"], frames["frame"]
nested.evaluate("() => { window.__r = null; setTimeout(() => { window.__r = confirm('one'); }, 0); }")
nested.wait_for_function("window.__r !== null")
frame.evaluate("() => { window.__r = null; setTimeout(() => { window.__r = confirm('two'); }, 0); }")
frame.wait_for_function("window.__r !== null")
assert nested.evaluate("window.__r") is True
assert frame.evaluate("window.__r") is False
# ---------------------------------------------------------------------------
# downloads
# ---------------------------------------------------------------------------
@pytest.mark.parametrize("target", ["frame", "nested"])
@pytest.mark.parametrize("link,filename", [("#dl", "file.bin"), ("#dl-header", "by-header.bin")])
def test_a_download_started_in_a_frame_reaches_expect_download(opened, sites, target, link, filename):
page, frames = opened
frame = frames[target]
site, base = ("B", "/frame") if target == "frame" else ("C", "/nested")
with page.expect_download() as info:
frame.locator(link).click()
download = info.value
assert download.suggested_filename == filename
assert download.url.startswith(sites.url(site) + "/")
assert download.failure() is None
with open(download.path(), "rb") as saved:
assert saved.read() == PAYLOAD
assert frame.url == sites.url(site, base), "the frame stayed where it was"
# ---------------------------------------------------------------------------
# popups
# ---------------------------------------------------------------------------
@pytest.mark.parametrize("target", ["frame", "nested"])
@pytest.mark.parametrize("opener_control,has_opener", [("#open", True), ("#blank", False), ("#noopener", False)])
def test_a_popup_opened_from_a_frame_reaches_expect_popup(opened, sites, target, opener_control, has_opener):
page, frames = opened
with page.expect_popup() as info:
frames[target].locator(opener_control).click()
popup = info.value
popup.wait_for_load_state("load")
assert popup.url == sites.url("C", "/popup")
assert popup.evaluate("document.title") == "popup"
assert popup.evaluate("window.__opener") is has_opener
assert popup.opener() == page, "the popup's opener is the page whose frame opened it, noopener or not"
assert popup in page.context.pages
popup.close()
@@ -1,190 +0,0 @@
"""History across a frame of another site, and the processes a context leaves behind.
Three sites (see `_fission_frames.py`): the top is A (`127.0.0.1`), the frame B (`localhost`), the frame C
(`127.0.0.2`). With Fission each site is a content process of its own, and a navigation of the frame to another
site changes its process.
* History. The page holds a frame of B. A navigation inside the frame adds a session-history entry, so
`page.go_back()` moves the FRAME back (the top url does not change, the frame is at the url it had) and
`go_forward()` restores it; the same when the frame went to a third site (a new process). A top-level
navigation and `go_back()` restore the page with its frame of another site, and the frame answers `evaluate`.
The outcome asserted is what stock Firefox does (see the docstrings).
* Processes. A context whose page had frames of other sites leaves no content process behind once it is closed:
the count of web content processes under the engine, read after each of several such contexts, does not grow.
The first test proves the frame is in another process, so the file cannot turn into a same-process suite.
"""
from __future__ import annotations
import os
import time
from pathlib import Path
import pytest
from _fission_frames import Sites, assert_other_process, launch, new_page, wait_for, wait_frame
pytestmark = pytest.mark.e2e
@pytest.fixture
def sites():
with Sites() as s:
s.route("A", "/h-top", "<!doctype html><title>h-top</title><iframe id='b' name='b' src='%s' width='500' "
"height='200'></iframe>" % s.url("B", "/h1"))
for n in (1, 2):
s.route("B", "/h%d" % n, "<!doctype html><title>h%d</title><p id='p'>h%d" % (n, n))
s.route("C", "/h3", "<!doctype html><title>h3</title><p id='p'>h3")
s.route("A", "/other", "<!doctype html><title>other</title><p>other")
yield s
@pytest.fixture
def browser(firefox_binary):
with launch(firefox_binary) as browser:
yield browser
@pytest.fixture
def page(browser):
context, page = new_page(browser)
yield page
context.close()
def traverse(page, direction):
"""``page.go_back()`` or ``page.go_forward()``. When the entry belongs to a frame, no navigation of the main
frame follows, and the call gives up with a ``TimeoutError`` after the history has moved: as stock Firefox
does. A call that returns is just as good; what the tests judge is where the page and its frame are after."""
try:
getattr(page, direction)(timeout=3000)
except Exception as error: # the client's own TimeoutError class: the wrapper ships its own copy
if type(error).__name__ != "TimeoutError":
raise
def _frame_url(page):
"""The url of the one frame of the page, once there is one."""
wait_for(page, lambda: len(page.frames) == 2)
return page.frames[1].url
def test_the_frame_is_in_another_process(page, sites):
page.goto(sites.url("A", "/h-top"), wait_until="load")
assert_other_process(page.main_frame, wait_frame(page, sites.url("B"), "/h1"))
def test_back_and_forward_move_the_frame_not_the_top_after_a_navigation_inside_it(page, sites):
"""The frame goes h1 -> h2 (same site). Back: the top is where it was, the frame is at h1. Forward: at h2."""
page.goto(sites.url("A", "/h-top"), wait_until="load")
frame = wait_frame(page, sites.url("B"), "/h1")
frame.goto(sites.url("B", "/h2"))
assert frame.url == sites.url("B", "/h2") and page.url == sites.url("A", "/h-top")
traverse(page, "go_back")
assert wait_for(page, lambda: _frame_url(page) == sites.url("B", "/h1")), _frame_url(page)
assert page.url == sites.url("A", "/h-top")
assert page.frames[1].evaluate("document.title") == "h1"
traverse(page, "go_forward")
assert wait_for(page, lambda: _frame_url(page) == sites.url("B", "/h2")), _frame_url(page)
assert page.url == sites.url("A", "/h-top")
assert page.frames[1].evaluate("document.title") == "h2"
def test_back_and_forward_across_a_frame_that_went_to_a_third_site(page, sites):
"""The frame goes h1 (B) -> h2 (B) -> h3 (C: a change of site and of process). Each back moves it one entry; forward goes the way back came."""
page.goto(sites.url("A", "/h-top"), wait_until="load")
frame = wait_frame(page, sites.url("B"), "/h1")
frame.goto(sites.url("B", "/h2"))
frame.goto(sites.url("C", "/h3"))
assert wait_for(page, lambda: _frame_url(page) == sites.url("C", "/h3")), _frame_url(page)
assert_other_process(page.main_frame, page.frames[1])
for expected in ("B/h2", "B/h1"):
traverse(page, "go_back")
site, path = expected.split("/")
assert wait_for(page, lambda: _frame_url(page) == sites.url(site, "/" + path)), (expected, _frame_url(page))
assert page.url == sites.url("A", "/h-top")
assert page.frames[1].evaluate("document.title") == path
traverse(page, "go_forward")
assert wait_for(page, lambda: _frame_url(page) == sites.url("B", "/h2")), _frame_url(page)
traverse(page, "go_forward")
assert wait_for(page, lambda: _frame_url(page) == sites.url("C", "/h3")), _frame_url(page)
assert page.frames[1].evaluate("document.title") == "h3"
assert page.url == sites.url("A", "/h-top")
def test_a_top_level_navigation_and_back_restore_the_page_with_its_frame_usable(page, sites):
page.goto(sites.url("A", "/h-top"), wait_until="load")
frame = wait_frame(page, sites.url("B"), "/h1")
frame.goto(sites.url("B", "/h2"))
page.goto(sites.url("A", "/other"), wait_until="load")
assert page.url == sites.url("A", "/other")
traverse(page, "go_back")
assert page.url == sites.url("A", "/h-top")
assert wait_for(page, lambda: len(page.frames) == 2 and page.frames[1].url.startswith(sites.url("B"))), \
[f.url for f in page.frames]
restored = page.frames[1]
# the frame is where it was when the page was left (h2), as stock Firefox restores it
assert restored.url == sites.url("B", "/h2")
assert restored.evaluate("document.title") == "h2"
assert restored.evaluate("location.origin") == sites.url("B")
assert restored.locator("#p").inner_text() == "h2"
assert_other_process(page.main_frame, restored)
# ---------------------------------------------------------------------------
# processes
# ---------------------------------------------------------------------------
def _content_processes(engine_dir):
"""The pids of the engine's web content processes (`-contentproc ... tab`) below this test."""
import psutil
found = set()
for child in psutil.Process(os.getpid()).children(recursive=True):
try:
if not os.path.normcase(child.exe()).startswith(os.path.normcase(engine_dir)):
continue
command = child.cmdline()
except psutil.Error:
continue
if "-contentproc" in command and command[-1] == "tab":
found.add(child.pid)
return found
def _settled(engine_dir, seconds=2.0, limit=25.0):
"""The set of content processes once it has not changed for ``seconds``."""
end = time.monotonic() + limit
last, since = _content_processes(engine_dir), time.monotonic()
while time.monotonic() < end:
time.sleep(0.25)
now = _content_processes(engine_dir)
if now != last:
last, since = now, time.monotonic()
elif time.monotonic() - since >= seconds:
break
return last
def test_a_closed_context_with_frames_of_other_sites_leaves_no_content_process(firefox_binary, sites):
"""Four contexts in a row, each with a page whose frames are on B and (nested) on C. The processes the frames
took are gone once the context is closed: the count after the last is no higher than the count after the
first (the engine keeps one spare process that the first context may take or leave)."""
sites.route("B", "/leak-b", "<!doctype html><title>b</title><iframe src='%s'></iframe>" % sites.url("C", "/h3"))
sites.route("A", "/leak", "<!doctype html><title>leak</title><iframe id='b' src='%s'></iframe>"
% sites.url("B", "/leak-b"))
engine_dir = str(Path(firefox_binary).resolve().parent)
with launch(firefox_binary) as browser:
counts, during = [], []
for _ in range(4):
context, page = new_page(browser)
page.goto(sites.url("A", "/leak"), wait_until="load")
wait_frame(page, sites.url("C"), "/h3")
during.append(len(_settled(engine_dir)))
context.close()
counts.append(len(_settled(engine_dir)))
assert max(during) > counts[0], (
"the frames of other sites took no process of their own: %r while open, %r after" % (during, counts))
assert counts[-1] <= counts[0], "web content processes after each closed context: %r (open: %r)" % (
counts, during)
@@ -1,351 +0,0 @@
"""Routes, exposed functions, init scripts and postMessage, for an iframe of another site and one nested in it.
Fission puts a frame of another site in a content process of its own. What a script written against the Playwright
API does with such a frame is the same as with any other, and this file holds the parts that go through the
frame's own process:
* `page.route` and `context.route` see the requests the frame makes, `request.frame` is that frame (the same
object `page.frames` lists, with the url of its document), and fulfill, abort and continue each take effect in the
frame; `wait_for_load_state("networkidle")` waits for the late requests of the frame;
* `expose_function` and `expose_binding` are callable from the frame and from a frame nested in it, and the
binding's `source["frame"]` is the frame that called;
* an init script runs before the frame's own scripts, in the frame, in the nested frame, and again in the document
the frame navigates to (a third site);
* `postMessage` crosses between the top and a frame of another site both ways, and between two sibling frames of
other sites through the top: `event.origin` is the sender's, `event.source` answers.
The sites are told apart by host (see `_fission_frames.py`): the top is A (`127.0.0.1`), the frame is B
(`localhost`) and the frame nested in it is C (`127.0.0.2`).
The outcome asserted is the one of stock Playwright Firefox; none of it depends on the process model, and the
first test proves the frame is not in the process of the page, so the file cannot turn into a same-process suite.
"""
from __future__ import annotations
import json
import pytest
from _fission_frames import Sites, assert_other_process, launch, new_page, wait_frame
pytestmark = pytest.mark.e2e
@pytest.fixture
def sites():
with Sites() as s:
# A top page with a frame of B; the frame of B holds a frame of C. Each document reports through
# window.__log what it did, so a test reads it with evaluate.
s.route("A", "/top", '<!doctype html><title>top</title><iframe id="b" name="b" src="%s" '
'width="500" height="300"></iframe>' % s.url("B", "/frame"))
s.route("B", "/frame", '<!doctype html><title>frame</title><iframe id="c" name="c" src="%s" '
'width="300" height="150"></iframe>'
"<script>window.__got = [];"
"fetch('/api/b?from=load').then(r => r.text()).then(t => __got.push(['load', t]))"
".catch(e => __got.push(['load-error', String(e)]));</script>" % s.url("C", "/nested"))
s.route("C", "/nested", "<!doctype html><title>nested</title>"
"<script>window.__got = [];"
"fetch('/api/c?from=load').then(r => r.text()).then(t => __got.push(['load', t]))"
".catch(e => __got.push(['load-error', String(e)]));</script>")
s.route("B", "/api/b", "from-server-b", ctype="text/plain")
s.route("C", "/api/c", "from-server-c", ctype="text/plain")
yield s
@pytest.fixture(scope="module")
def browser(firefox_binary):
with launch(firefox_binary) as browser:
yield browser
@pytest.fixture
def page(browser):
context, page = new_page(browser)
yield page
context.close()
def _frames(page, sites):
"""The frame of B and the frame of C nested in it, once both have a document."""
b = wait_frame(page, sites.url("B"), "/frame")
c = wait_frame(page, sites.url("C"), "/nested")
return b, c
def test_the_frame_is_in_another_process_and_the_nested_one_in_a_third(page, sites):
"""The precondition of this file: B is not in the process of A, and C is not in the one of B."""
page.goto(sites.url("A", "/top"), wait_until="load")
b, c = _frames(page, sites)
assert b.parent_frame == page.main_frame and c.parent_frame == b
assert_other_process(page.main_frame, b)
assert_other_process(b, c)
# ---------------------------------------------------------------------------
# page.route and context.route
# ---------------------------------------------------------------------------
@pytest.mark.parametrize("where", ["page", "context"])
def test_a_route_sees_the_requests_of_a_frame_of_another_site_and_of_a_nested_one(page, sites, where):
"""The handler is called for the fetch of the frame of B and the one of the frame of C nested in it,
`request.frame` is the frame that made it (the object of `page.frames`, with its url), the request is a
sub-resource of that frame's document, and continuing it gives the page the server's answer."""
context = page.context
seen = []
def handler(route):
request = route.request
seen.append((request.url, request.frame, request.resource_type))
route.continue_()
(page if where == "page" else context).route("**/api/**", handler)
page.goto(sites.url("A", "/top"), wait_until="load")
b, c = _frames(page, sites)
for frame in (b, c):
frame.wait_for_function("window.__got.length > 0")
assert b.evaluate("window.__got") == [["load", "from-server-b"]]
assert c.evaluate("window.__got") == [["load", "from-server-c"]]
by_url = {url.split("?")[0]: (frame, kind) for url, frame, kind in seen}
assert set(by_url) == {sites.url("B", "/api/b"), sites.url("C", "/api/c")}, seen
frame_of_b, kind_b = by_url[sites.url("B", "/api/b")]
frame_of_c, kind_c = by_url[sites.url("C", "/api/c")]
assert frame_of_b is b and frame_of_b.url == sites.url("B", "/frame")
assert frame_of_c is c and frame_of_c.url == sites.url("C", "/nested")
assert frame_of_c.parent_frame is b
assert kind_b == kind_c == "fetch"
@pytest.mark.parametrize("action", ["fulfill", "abort", "continue"])
@pytest.mark.parametrize("target", ["frame", "nested"])
def test_fulfill_abort_and_continue_take_effect_in_a_frame_of_another_site(page, sites, action, target):
"""What the route decides is what the frame's fetch gets: the body and status given to `fulfill`, a rejected
fetch for `abort`, the server's answer for `continue`. A fetch the frame makes AFTER the load, to a url the
route covers."""
page.goto(sites.url("A", "/top"), wait_until="load")
b, c = _frames(page, sites)
frame, site = (b, "B") if target == "frame" else (c, "C")
sites.route(site, "/api/late", "from-server", ctype="text/plain")
routed = []
def handler(route):
routed.append(route.request.frame)
if action == "fulfill":
route.fulfill(status=201, body="from-route", content_type="text/plain",
headers={"access-control-allow-origin": "*"})
elif action == "abort":
route.abort()
else:
route.continue_()
page.route("**/api/late", handler)
result = frame.evaluate("""() => fetch('/api/late').then(
r => r.text().then(t => ({ok: true, status: r.status, body: t})),
e => ({ok: false, error: e.name}))""")
assert routed == [frame], routed
if action == "fulfill":
assert result == {"ok": True, "status": 201, "body": "from-route"}
elif action == "abort":
assert result["ok"] is False and result["error"] == "TypeError", result
assert not sites.seen(site, "/api/late"), "an aborted request reached the server"
else:
assert result == {"ok": True, "status": 200, "body": "from-server"}
assert len(sites.seen(site, "/api/late")) == 1
def test_a_route_set_before_the_load_fulfills_what_the_frame_asks_while_loading(page, sites):
"""The first request of the frame of another site is covered: the route is in place before the page goes to
its url, and the fetch the frame makes while loading is answered by the route."""
page.route("**/api/b**", lambda route: route.fulfill(body="routed-b", content_type="text/plain"))
page.goto(sites.url("A", "/top"), wait_until="load")
b, _ = _frames(page, sites)
b.wait_for_function("window.__got.length > 0")
assert b.evaluate("window.__got") == [["load", "routed-b"]]
assert not sites.seen("B", "/api/b"), "the request reached the server through the route"
def test_networkidle_waits_for_the_late_requests_of_a_frame_of_another_site(page, sites):
"""The frame makes a request 200 ms after it loads, and the next one as soon as that answers (the server holds
each for 300 ms): there is never half a second without a request, so `networkidle` of the PAGE is not reached
before both are done."""
chain = ("<!doctype html><title>late</title><script>window.__done = [];"
"addEventListener('load', () => setTimeout(() => fetch('/late/1').then(r => r.text())"
".then(t => { __done.push(t); return fetch('/late/2'); }).then(r => r.text())"
".then(t => __done.push(t)), 200));</script>")
sites.route("B", "/late-frame", chain)
sites.route("B", "/late/1", "one", ctype="text/plain", delay=0.3)
sites.route("B", "/late/2", "two", ctype="text/plain", delay=0.3)
sites.route("A", "/late-top", '<!doctype html><title>late top</title>'
'<iframe src="%s" width="300" height="100"></iframe>' % sites.url("B", "/late-frame"))
page.goto(sites.url("A", "/late-top"), wait_until="networkidle", timeout=30000)
frame = wait_frame(page, sites.url("B"), "/late-frame")
assert frame.evaluate("window.__done") == ["one", "two"]
page.wait_for_load_state("networkidle")
# ---------------------------------------------------------------------------
# expose_function, expose_binding and init scripts
# ---------------------------------------------------------------------------
@pytest.mark.parametrize("where", ["page", "context"])
def test_an_exposed_function_is_callable_from_a_frame_of_another_site_and_a_nested_one(page, sites, where):
context = page.context
(page if where == "page" else context).expose_function("add", lambda a, b: a + b)
page.goto(sites.url("A", "/top"), wait_until="load")
b, c = _frames(page, sites)
assert b.evaluate("add(2, 3)") == 5
assert c.evaluate("add(40, 2)") == 42
assert c.evaluate("typeof window.add") == "function"
@pytest.mark.parametrize("where", ["page", "context"])
def test_a_binding_knows_which_frame_called_it(page, sites, where):
"""`source["frame"]` is the frame that called: the frame of B, then the frame of C nested in it, then the
top; `source["page"]` is the page."""
context = page.context
calls = []
def binding(source, value):
calls.append((source["frame"], source["page"], value))
return "ack:%s" % value
(page if where == "page" else context).expose_binding("report", binding)
page.goto(sites.url("A", "/top"), wait_until="load")
b, c = _frames(page, sites)
assert c.evaluate("report('from-c')") == "ack:from-c"
assert b.evaluate("report('from-b')") == "ack:from-b"
assert page.main_frame.evaluate("report('from-top')") == "ack:from-top"
assert [(f, p is page, v) for f, p, v in calls] == [(c, True, "from-c"), (b, True, "from-b"),
(page.main_frame, True, "from-top")]
assert calls[0][0].url == sites.url("C", "/nested")
assert calls[1][0].url == sites.url("B", "/frame")
def test_a_binding_called_by_a_script_of_the_frame_while_it_loads(page, sites):
"""A page script of the frame of B calls the binding in its own first script, before any `evaluate`: the
binding is already there and knows the frame."""
sites.route("B", "/binds", "<!doctype html><title>binds</title><script>window.__ack = null;"
"report('while-loading').then(v => window.__ack = v);</script>")
sites.route("A", "/binds-top", '<!doctype html><iframe src="%s"></iframe>' % sites.url("B", "/binds"))
calls = []
def binding(source, value):
calls.append((source["frame"].url, value))
return "ack"
page.expose_binding("report", binding)
page.goto(sites.url("A", "/binds-top"), wait_until="load")
frame = wait_frame(page, sites.url("B"), "/binds")
frame.wait_for_function("window.__ack !== null")
assert calls == [(sites.url("B", "/binds"), "while-loading")]
ORDER_PAGE = ("<!doctype html><title>%s</title><script>"
"window.__seen = JSON.stringify(window.__o || []);"
"(window.__o = window.__o || []).push('page');</script>")
@pytest.mark.parametrize("where", ["page", "context"])
def test_an_init_script_runs_before_the_scripts_of_a_frame_of_another_site(page, sites, where):
"""In the top, in the frame of B and in the frame of C: the init script has pushed 'init' before the
document's own first script reads the list. The same, again, in the document the frame of B navigates to on a
third site (C): the new document in the new process gets the script before its own."""
context = page.context
script = "(window.__o = window.__o || []).push('init');"
(page if where == "page" else context).add_init_script(script)
sites.route("A", "/order-top", ORDER_PAGE.replace("%s", "top")
+ '<iframe src="%s"></iframe>' % sites.url("B", "/order-b"))
sites.route("B", "/order-b", ORDER_PAGE.replace("%s", "b")
+ '<iframe src="%s"></iframe>' % sites.url("C", "/order-c"))
sites.route("C", "/order-c", ORDER_PAGE.replace("%s", "c"))
sites.route("C", "/order-moved", ORDER_PAGE.replace("%s", "moved"))
page.goto(sites.url("A", "/order-top"), wait_until="load")
b = wait_frame(page, sites.url("B"), "/order-b")
c = wait_frame(page, sites.url("C"), "/order-c")
for frame in (page.main_frame, b, c):
assert frame.evaluate("window.__seen") == '["init"]', frame.url
assert frame.evaluate("window.__o") == ["init", "page"], frame.url
b.goto(sites.url("C", "/order-moved"))
assert b.url == sites.url("C", "/order-moved")
assert b.evaluate("window.__seen") == '["init"]'
assert b.evaluate("window.__o") == ["init", "page"]
# and the process changed with the site: the moved frame is not in the top's process either
assert_other_process(page.main_frame, b)
# ---------------------------------------------------------------------------
# postMessage
# ---------------------------------------------------------------------------
ECHO = ("<!doctype html><title>%(name)s</title><script>window.__in = [];"
"addEventListener('message', e => { __in.push({origin: e.origin, data: e.data, "
"fromParent: e.source === parent});"
"if (e.data && e.data.ping) e.source.postMessage({pong: e.data.ping, by: %(name)s}, e.origin); });"
"</script>")
def test_post_message_crosses_between_the_top_and_a_frame_of_another_site_both_ways(page, sites):
"""The top asks the frame of B, the frame answers on `event.source`, the top reads the answer with the origin
of B and `event.source` equal to the frame's window; and the frame speaks first to its parent."""
sites.route("B", "/echo", ECHO % {"name": '"b"'} +
"<script>parent.postMessage({hello: 'from-b'}, '*');</script>")
sites.route("A", "/msg-top", "<!doctype html><title>top</title><iframe id='f' src='%s'></iframe><script>"
"window.__in = []; addEventListener('message', e => __in.push({origin: e.origin, data: e.data, "
"fromFrame: e.source === document.getElementById('f').contentWindow}));</script>"
% sites.url("B", "/echo"))
page.goto(sites.url("A", "/msg-top"), wait_until="load")
frame = wait_frame(page, sites.url("B"), "/echo")
page.wait_for_function("window.__in.length >= 1")
assert page.evaluate("window.__in[0]") == {"origin": sites.url("B"), "data": {"hello": "from-b"},
"fromFrame": True}
page.evaluate("document.getElementById('f').contentWindow.postMessage({ping: 7}, %s)" % json.dumps(sites.url("B")))
page.wait_for_function("window.__in.length >= 2")
assert page.evaluate("window.__in[1]") == {"origin": sites.url("B"), "data": {"pong": 7, "by": "b"},
"fromFrame": True}
assert frame.evaluate("window.__in") == [{"origin": sites.url("A"), "data": {"ping": 7}, "fromParent": True}]
def test_post_message_between_two_sibling_frames_of_other_sites_goes_through_the_top(page, sites):
"""Frames of B and C side by side, in a page of A. They cannot see each other, only the top: B writes to the
top, the top relays to C naming the sender, C answers the top on `event.source`, the top relays back. Every
hop shows the origin of the document that sent it."""
sites.route("B", "/left", "<!doctype html><title>left</title><script>window.__in = [];"
"addEventListener('message', e => __in.push({origin: e.origin, data: e.data}));"
"parent.postMessage({to: 'right', text: 'hi from left'}, '*');</script>")
sites.route("C", "/right", "<!doctype html><title>right</title><script>window.__in = [];"
"addEventListener('message', e => { __in.push({origin: e.origin, data: e.data});"
"e.source.postMessage({to: 'left', text: 'hi from right'}, e.origin); });</script>")
# The top relays a message only once the frame it is for has loaded: the two frames load in two processes, in no
# fixed order, and a message posted to a frame whose document is not there yet is lost in any browser. The first
# version relayed at once, and one CI run in three never saw the answer.
sites.route("A", "/relay", "<!doctype html><title>relay</title><script>"
"window.__hops = []; window.__loaded = {}; window.__waiting = [];"
"const win = id => document.getElementById(id).contentWindow;"
"function deliver() { __waiting = __waiting.filter(m => {"
" if (!__loaded[m.to]) return true; win(m.to).postMessage(m.message, m.origin); return false; }); }"
"function loaded(id) { __loaded[id] = true; deliver(); }"
"addEventListener('message', e => {"
" const from = e.source === win('left') ? 'left' : e.source === win('right') ? 'right' : '?';"
" __hops.push({from, origin: e.origin, data: e.data});"
" if (e.data.to) { __waiting.push({to: e.data.to, message: {relayed: e.data.text, by: from},"
" origin: from === 'left' ? %s : %s}); deliver(); }"
"});</script>"
"<iframe id='left' onload=\"loaded('left')\" src='%s'></iframe>"
"<iframe id='right' onload=\"loaded('right')\" src='%s'></iframe>"
% (json.dumps(sites.url("C")), json.dumps(sites.url("B")),
sites.url("B", "/left"), sites.url("C", "/right")))
page.goto(sites.url("A", "/relay"), wait_until="load")
left = wait_frame(page, sites.url("B"), "/left")
right = wait_frame(page, sites.url("C"), "/right")
page.wait_for_function("window.__hops.length >= 2")
left.wait_for_function("window.__in.length >= 1")
assert page.evaluate("window.__hops") == [
{"from": "left", "origin": sites.url("B"), "data": {"to": "right", "text": "hi from left"}},
{"from": "right", "origin": sites.url("C"), "data": {"to": "left", "text": "hi from right"}},
]
assert right.evaluate("window.__in") == [
{"origin": sites.url("A"), "data": {"relayed": "hi from left", "by": "left"}}]
assert left.evaluate("window.__in") == [
{"origin": sites.url("A"), "data": {"relayed": "hi from right", "by": "right"}}]
assert_other_process(left, right)
@@ -1,371 +0,0 @@
"""The frame tree, typing, trusted clicks and screenshots, with frames in other processes.
Three sites (see `_fission_frames.py`): the top is A (`127.0.0.1`), the frame B (`localhost`), the frame C
(`127.0.0.2`). With Fission each site is a content process of its own, and the page the script drives is made of
documents that live in different ones. What a script written against the Playwright API does with such a page is
what it does with any other:
* the frame tree A > B > A > C (the second A is the site of the top again, below a frame of another site): every
level is in `page.frames` with its url and name, and `parent_frame` / `child_frames` give the same chain;
* typing into an input of a frame of another site and of a frame nested in it (`press_sequentially`,
`keyboard.type` after a focus, `press`): the keys are trusted and reach that input; `wait_for_selector` and
`Locator.wait_for` see an element that appears there later;
* a click by selector on an element inside such a frame lands on THAT element when the iframe is under a CSS
transform (scale and translate) and after the top page and the frame have both been scrolled (the page
records which element got the trusted click);
* `page.screenshot()` of a page whose frame of another site paints a known colour shows that colour inside the
frame's box, and `locator.screenshot()` of an element inside the frame, and inside a nested one, has the
element's size and colour.
Every test with a frame of B is run for the frame nested in it (C) as well where the scenario has one. The first
test of the file proves the frames are in other processes, so it cannot turn into a same-process suite.
"""
from __future__ import annotations
import pytest
from _fission_frames import (Sites, assert_other_process, decode_png, launch, near, new_page, wait_for,
wait_frame)
pytestmark = pytest.mark.e2e
@pytest.fixture
def sites():
with Sites() as s:
yield s
@pytest.fixture
def browser(firefox_binary):
with launch(firefox_binary) as browser:
yield browser
@pytest.fixture
def page(browser):
context, page = new_page(browser)
yield page
context.close()
# ---------------------------------------------------------------------------
# 1. the frame tree A > B > A > C
# ---------------------------------------------------------------------------
@pytest.fixture
def tree(sites):
sites.route("A", "/tree", "<!doctype html><title>level 0</title><iframe id='one' name='one' src='%s' "
"width='700' height='500'></iframe>" % sites.url("B", "/level1"))
sites.route("B", "/level1", "<!doctype html><title>level 1</title><iframe id='two' name='two' src='%s' "
"width='600' height='400'></iframe>" % sites.url("A", "/level2"))
sites.route("A", "/level2", "<!doctype html><title>level 2</title><iframe id='three' name='three' src='%s' "
"width='500' height='300'></iframe>" % sites.url("C", "/level3"))
sites.route("C", "/level3", "<!doctype html><title>level 3</title><p id='leaf'>leaf of the tree")
return sites
def test_the_tree_a_b_a_c_is_listed_at_every_level(page, tree):
page.goto(tree.url("A", "/tree"), wait_until="load")
wait_frame(page, tree.url("C"), "/level3")
expected = [("", tree.url("A", "/tree")), ("one", tree.url("B", "/level1")),
("two", tree.url("A", "/level2")), ("three", tree.url("C", "/level3"))]
assert wait_for(page, lambda: [(f.name, f.url) for f in page.frames] == expected), \
[(f.name, f.url) for f in page.frames]
main, one, two, three = page.frames
assert main == page.main_frame
assert [f.parent_frame for f in (main, one, two, three)] == [None, main, one, two]
assert [f.child_frames for f in (main, one, two, three)] == [[one], [two], [three], []]
assert all(f.page is page for f in page.frames)
assert [f.is_detached() for f in page.frames] == [False] * 4
# the lookups by name and by url find the same objects
assert page.frame(name="three") is three and page.frame(url=tree.url("A", "/level2")) is two
# and the document of each level answers for itself
assert [f.evaluate("location.href") for f in page.frames] == [u for _, u in expected]
assert [f.evaluate("document.title") for f in page.frames] == ["level 0", "level 1", "level 2", "level 3"]
assert [f.evaluate("window.name") for f in page.frames] == ["", "one", "two", "three"]
assert three.locator("#leaf").inner_text() == "leaf of the tree"
# the frames are in other processes: B is not A, and C is neither B nor the second A
assert_other_process(main, one)
assert_other_process(two, three)
# ---------------------------------------------------------------------------
# 2. typing, and waiting for what appears later
# ---------------------------------------------------------------------------
TYPING = ("<input id='t' autocomplete='off'><script>window.keys = [];"
"t.addEventListener('keydown', e => keys.push([e.key, e.isTrusted]));</script>")
@pytest.fixture
def typing(sites):
sites.route("A", "/typing", "<!doctype html><title>top</title><iframe id='b' src='%s' width='600' height='400'>"
"</iframe>" % sites.url("B", "/typing-b"))
sites.route("B", "/typing-b", "<!doctype html><title>b</title>" + TYPING +
"<iframe id='c' src='%s' width='400' height='150'></iframe>" % sites.url("C", "/typing-c"))
sites.route("C", "/typing-c", "<!doctype html><title>c</title>" + TYPING)
return sites
def _typing_frames(page, typing):
page.goto(typing.url("A", "/typing"), wait_until="load")
return {"frame": wait_frame(page, typing.url("B"), "/typing-b"),
"nested": wait_frame(page, typing.url("C"), "/typing-c")}
@pytest.mark.parametrize("target", ["frame", "nested"])
@pytest.mark.parametrize("how", ["press_sequentially", "keyboard_type", "press_keys"])
def test_typing_into_an_input_of_a_frame_of_another_site(page, typing, target, how):
frame = _typing_frames(page, typing)[target]
field = frame.locator("#t")
if how == "press_sequentially":
field.press_sequentially("Hello 42")
expected, keys = "Hello 42", list("Hello 42")
elif how == "keyboard_type":
field.focus()
assert frame.evaluate("document.activeElement.id") == "t"
page.keyboard.type("Typed text")
expected, keys = "Typed text", list("Typed text")
else:
field.focus()
for key in ("a", "b", "c", "Backspace", "d"):
page.keyboard.press(key)
field.press("e")
expected, keys = "abde", ["a", "b", "c", "Backspace", "d", "e"]
assert field.input_value() == expected
seen = frame.evaluate("window.keys")
# a capital letter is typed with the Shift key held, as on a keyboard: its own keydown comes first
assert [k for k, _ in seen if k != "Shift"] == keys
assert all(trusted for _, trusted in seen), seen
def test_the_other_frames_are_not_typed_into(page, typing):
"""The keys go to the focused input and to no other document: the input of the nested frame and the one of
its parent each keep only what was typed in them."""
frames = _typing_frames(page, typing)
frames["frame"].locator("#t").press_sequentially("outer")
frames["nested"].locator("#t").press_sequentially("inner")
assert frames["frame"].locator("#t").input_value() == "outer"
assert frames["nested"].locator("#t").input_value() == "inner"
assert [k for k, _ in frames["frame"].evaluate("window.keys")] == list("outer")
assert [k for k, _ in frames["nested"].evaluate("window.keys")] == list("inner")
LATE = ("<p id='anchor'>anchor</p><script>"
"setTimeout(() => { const d = document.createElement('div'); d.id = 'late'; d.textContent = 'arrived';"
"document.body.appendChild(d); }, 700);"
"setTimeout(() => { const d = document.createElement('div'); d.id = 'shown'; d.textContent = 'shown';"
"d.style.display = 'none'; document.body.appendChild(d); }, 300);"
"setTimeout(() => { document.getElementById('shown').style.display = 'block'; }, 1000);</script>")
@pytest.fixture
def late(sites):
sites.route("A", "/late", "<!doctype html><title>top</title><iframe id='b' src='%s' width='600' height='400'>"
"</iframe>" % sites.url("B", "/late-b"))
sites.route("B", "/late-b", "<!doctype html><title>b</title>" + LATE +
"<iframe id='c' src='%s' width='400' height='150'></iframe>" % sites.url("C", "/late-c"))
sites.route("C", "/late-c", "<!doctype html><title>c</title>" + LATE)
return sites
@pytest.mark.parametrize("target", ["frame", "nested"])
def test_waiting_for_an_element_that_appears_later_in_a_frame_of_another_site(page, late, target):
page.goto(late.url("A", "/late"), wait_until="load")
frame = {"frame": wait_frame(page, late.url("B"), "/late-b"),
"nested": wait_frame(page, late.url("C"), "/late-c")}[target]
# the element is not there yet when the wait starts, or it is by now: either way the wait returns it
handle = frame.wait_for_selector("#late", timeout=8000)
try:
assert handle.inner_text() == "arrived"
assert handle.owner_frame() is frame
finally:
handle.dispose()
# the same, by the locator of the frame and by the frame locator of the page
frame.locator("#shown").wait_for(state="visible", timeout=8000)
outer = page.frame_locator("#b")
scoped = outer.locator("#late") if target == "frame" else outer.frame_locator("#c").locator("#late")
scoped.wait_for(state="attached", timeout=8000)
assert scoped.inner_text() == "arrived"
def test_waiting_in_a_frame_of_another_site_times_out_on_what_never_comes(page, late):
"""The wait is not satisfied by an element of another document: `#nothing` is in none, and the error is the
wait's TimeoutError naming the selector, not a protocol error about the frame."""
page.goto(late.url("A", "/late"), wait_until="load")
frame = wait_frame(page, late.url("B"), "/late-b")
with pytest.raises(Exception) as error:
frame.wait_for_selector("#nothing", timeout=1500)
assert type(error.value).__name__ == "TimeoutError" and "#nothing" in str(error.value), error.value
# ---------------------------------------------------------------------------
# 3. a click by selector under a transform and after scrolling
# ---------------------------------------------------------------------------
GRID = ("<style>html,body{margin:0}button{position:absolute;width:60px;height:40px;margin:0;padding:0}"
"%s</style>%s<script>window.landed = [];"
"addEventListener('click', e => landed.push({id: e.target.id || e.target.tagName, "
"trusted: e.isTrusted}), true);</script>")
def _grid(rows=4, cols=4, tall=0):
css = "".join("#r%dc%d{left:%dpx;top:%dpx}" % (r, c, 20 + c * 90, 20 + r * 70) for r in range(rows)
for c in range(cols))
buttons = "".join("<button id='r%dc%d'>%d,%d</button>" % (r, c, r, c) for r in range(rows)
for c in range(cols))
if tall:
buttons += "<div style='position:absolute;left:0;top:%dpx;width:10px;height:10px'></div>" % tall
return GRID % (css, buttons)
@pytest.fixture
def transformed(sites):
"""The frame of B inside a transformed box; the frame of C inside that one, transformed as well."""
sites.route("B", "/grid", "<!doctype html>" + _grid() +
"<iframe id='c' src='%s' style='position:absolute;left:400px;top:20px;width:420px;height:320px;"
"border:0;transform:translate(10px, 15px) scale(0.75);transform-origin:0 0'></iframe>"
% sites.url("C", "/grid"))
sites.route("C", "/grid", "<!doctype html>" + _grid(3, 3))
return sites
TRANSFORMS = [("scale", "translate(40px, 30px) scale(0.5)"), ("scale-up", "translate(10px, 10px) scale(1.4)"),
("rotate-ish", "translate(60px, 20px) scale(0.8) skewX(-8deg)")]
@pytest.fixture(params=[False, True], ids=["plain", "humanized"])
def pointer_browser(request, firefox_binary):
"""A browser per way of moving the pointer: a click of the humanized one lands off the centre of the element."""
with launch(firefox_binary, humanize=request.param) as browser:
yield browser
@pytest.fixture
def pointer_page(pointer_browser):
context, page = new_page(pointer_browser)
yield page
context.close()
@pytest.mark.parametrize("name,transform", TRANSFORMS, ids=[t[0] for t in TRANSFORMS])
def test_a_click_by_selector_in_a_frame_under_a_transform_lands_on_that_element(pointer_page, transformed, name,
transform):
"""The iframe sits in a box under `transform` (translate and scale, and a skew). One click per button, by
selector, in the frame of B and in the frame of C nested in it (which is transformed as well): each is
recorded by the document it landed in, as a trusted click on the button that was asked for, and by that
document only."""
page = pointer_page
transformed.route("A", "/t", "<!doctype html><title>t</title><body style='margin:0;height:2000px'>"
"<div style='transform:%s;transform-origin:0 0;position:absolute;left:30px;top:20px'>"
"<iframe id='b' src='%s' width='900' height='450' style='border:0'></iframe></div>"
% (transform, transformed.url("B", "/grid")))
page.goto(transformed.url("A", "/t"), wait_until="load")
frames = {"frame": wait_frame(page, transformed.url("B"), "/grid"),
"nested": wait_frame(page, transformed.url("C"), "/grid")}
expected = {"frame": [], "nested": []}
for target, button in (("frame", "r2c1"), ("nested", "r1c1"), ("frame", "r3c3"), ("nested", "r2c2"),
("frame", "r0c0")):
frames[target].locator("#" + button).click()
expected[target].append({"id": button, "trusted": True})
for name_, frame in frames.items():
assert frame.evaluate("window.landed") == expected[name_], (target, button, name_)
def test_the_transformed_frames_are_in_other_processes(pointer_page, transformed):
page = pointer_page
transformed.route("A", "/t", "<!doctype html><title>t</title><div style='transform:scale(0.5)'>"
"<iframe id='b' src='%s' width='900' height='450'></iframe></div>"
% transformed.url("B", "/grid"))
page.goto(transformed.url("A", "/t"), wait_until="load")
b = wait_frame(page, transformed.url("B"), "/grid")
assert_other_process(page.main_frame, b)
assert_other_process(b, wait_frame(page, transformed.url("C"), "/grid"))
def test_a_click_by_selector_after_scrolling_the_page_and_the_frame(pointer_page, sites):
"""The page and the frame are both scrolled, so the element is where neither document's own coordinates say:
the click still lands on it. Below the fold of the frame, which is below the fold of the page; once in the
frame of B and once in the frame of C nested in it (scrolled too)."""
page = pointer_page
sites.route("B", "/tall", "<!doctype html>" + _grid(rows=14, cols=2) +
"<iframe id='c' src='%s' style='position:absolute;left:300px;top:20px;width:400px;height:300px;"
"border:0'></iframe><div style='position:absolute;top:1500px;width:1px;height:1px'></div>"
% sites.url("C", "/tall-c"))
sites.route("C", "/tall-c", "<!doctype html>" + _grid(rows=14, cols=2))
sites.route("A", "/scrolled", "<!doctype html><title>scrolled</title><body style='margin:0'>"
"<div style='height:900px'>spacer</div><iframe id='b' src='%s' width='900' height='400' "
"style='border:0'></iframe><div style='height:1200px'></div>" % sites.url("B", "/tall"))
page.goto(sites.url("A", "/scrolled"), wait_until="load")
outer = wait_frame(page, sites.url("B"), "/tall")
inner = wait_frame(page, sites.url("C"), "/tall-c")
page.evaluate("window.scrollTo(0, 700)")
outer.evaluate("window.scrollTo(0, 500)")
assert page.evaluate("window.scrollY") == 700 and outer.evaluate("window.scrollY") == 500
outer.locator("#r12c1").click()
assert outer.evaluate("window.landed") == [{"id": "r12c1", "trusted": True}]
inner.evaluate("window.scrollTo(0, 400)")
inner.locator("#r12c0").click()
assert inner.evaluate("window.landed") == [{"id": "r12c0", "trusted": True}]
assert outer.evaluate("window.landed") == [{"id": "r12c1", "trusted": True}]
# ---------------------------------------------------------------------------
# 8. screenshots
# ---------------------------------------------------------------------------
PINK, GREEN, BLUE, GOLD = (255, 0, 170), (0, 204, 68), (34, 85, 238), (255, 204, 0)
@pytest.fixture
def painted(sites):
sites.route("A", "/paint", "<!doctype html><title>paint</title><body style='margin:0;background:#fff'>"
"<iframe id='b' src='%s' style='position:absolute;left:50px;top:40px;width:300px;height:200px;"
"border:0'></iframe>" % sites.url("B", "/paint"))
sites.route("B", "/paint", "<!doctype html><body style='margin:0;background:#ff00aa'>"
"<div id='swatch' style='position:absolute;left:20px;top:30px;width:80px;height:60px;"
"background:#00cc44'></div>"
"<iframe id='c' src='%s' style='position:absolute;left:120px;top:20px;width:150px;height:120px;"
"border:0'></iframe>" % sites.url("C", "/paint"))
sites.route("C", "/paint", "<!doctype html><body style='margin:0;background:#2255ee'>"
"<div id='swatch' style='position:absolute;left:10px;top:10px;width:50px;height:40px;"
"background:#ffcc00'></div>")
return sites
def test_a_page_screenshot_shows_the_content_of_the_frames_of_other_sites(page, painted):
page.goto(painted.url("A", "/paint"), wait_until="load")
wait_frame(page, painted.url("C"), "/paint")
page.wait_for_timeout(500)
assert_other_process(page.main_frame, wait_frame(page, painted.url("B"), "/paint"))
_, _, pixel = decode_png(page.screenshot(scale="css"))
# outside the frame the page's own white; inside it the frame's pink; its swatch; the nested frame's blue
assert near(pixel(10, 10), (255, 255, 255)), pixel(10, 10)
assert near(pixel(50 + 5, 40 + 5), PINK), pixel(55, 45)
assert near(pixel(50 + 20 + 40, 40 + 30 + 30), GREEN), pixel(110, 100)
assert near(pixel(50 + 120 + 5, 40 + 20 + 5), BLUE), pixel(175, 65)
assert near(pixel(50 + 120 + 10 + 25, 40 + 20 + 10 + 20), GOLD), pixel(205, 90)
assert near(pixel(50 + 300 + 10, 40 + 10), (255, 255, 255)), "right of the frame"
@pytest.mark.parametrize("target,size,color", [("frame", (80, 60), GREEN), ("nested", (50, 40), GOLD)])
def test_a_locator_screenshot_of_an_element_in_a_frame_of_another_site(page, painted, target, size, color):
page.goto(painted.url("A", "/paint"), wait_until="load")
frame = {"frame": wait_frame(page, painted.url("B"), "/paint"),
"nested": wait_frame(page, painted.url("C"), "/paint")}[target]
page.wait_for_timeout(500)
width, height, pixel = decode_png(frame.locator("#swatch").screenshot(scale="css"))
assert (width, height) == size
for x, y in ((0, 0), (width - 1, height - 1), (width // 2, height // 2), (width - 1, 0)):
assert near(pixel(x, y), color), ((x, y), pixel(x, y))
def test_a_locator_screenshot_of_the_iframe_element_shows_the_frame(page, painted):
page.goto(painted.url("A", "/paint"), wait_until="load")
wait_frame(page, painted.url("C"), "/paint")
page.wait_for_timeout(500)
width, height, pixel = decode_png(page.locator("#b").screenshot(scale="css"))
assert (width, height) == (300, 200)
assert near(pixel(5, 5), PINK) and near(pixel(60, 60), GREEN) and near(pixel(125, 25), BLUE)
@@ -1,323 +0,0 @@
"""Workers made in frames of other sites, what a frame of another site keeps, and the frames that have no address.
Three sites (see `_fission_frames.py`): the top is A (`127.0.0.1`), the frame B (`localhost`), the frame C
(`127.0.0.2`) nested in B. With Fission each site is a content process of its own.
* Identity inside workers. A dedicated Worker made in the top, in the frame of B and in the frame of C (blob and
script-url workers) reports the same `navigator.userAgent`, `language`, `languages`, `hardwareConcurrency`,
`platform` and time zone as the window of the top and as the window that made it: a worker lives in the process
of the frame that made it, and its identity has to be declared there like the window's. The comparison reads an
absence as a mismatch, never as an agreement. A SharedWorker and a ServiceWorker are made from the frame of B:
the outcome asserted is what stock Firefox does there (see the docstrings).
* Cookies and storage. A cookie set by site B inside a frame of A appears in `context.cookies()` with B's domain;
what `document.cookie`, `localStorage` and `sessionStorage` show to B-in-A is what stock Firefox shows, and B
opened as a top page does not see them: storage is partitioned by top-level site, as in retail Firefox (stock
Playwright Firefox has that protection off; see the docstrings).
* Frames with no address of their own, at the top level and inside the frame of B: `srcdoc`, `about:blank`, a
`data:` url and a `sandbox`ed frame with and without `allow-scripts allow-same-origin`: they are in
`page.frames`, `evaluate` works where scripts run, and `frame_locator` reaches into them (see the docstrings
for what stock Firefox does with a sandbox that forbids scripts).
The first test proves the frames are in other processes, so the file cannot turn into a same-process suite.
"""
from __future__ import annotations
import json
import pytest
from _fission_frames import Sites, assert_other_process, launch, new_page, wait_for, wait_frame
pytestmark = pytest.mark.e2e
#: What a worker reads about the browser it runs in, as an object literal for its source.
IDENTITY = ("{userAgent: navigator.userAgent, language: navigator.language, languages: navigator.languages.join('|'),"
" hardwareConcurrency: navigator.hardwareConcurrency, platform: navigator.platform,"
" timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone}")
FIELDS = ("userAgent", "language", "languages", "hardwareConcurrency", "platform", "timeZone")
#: Run in a frame: make a dedicated worker (from a blob, or from the script of the frame's site) and return what it
#: reports, or the error.
WORKER_JS = """(kind) => new Promise(resolve => {
const source = 'postMessage(' + %s + ')';
let worker;
try {
worker = kind === 'blob' ? new Worker(URL.createObjectURL(new Blob([source], {type: 'text/javascript'})))
: new Worker('/identity-worker.js');
} catch (e) { resolve({error: String(e)}); return; }
worker.onmessage = e => resolve(e.data);
worker.onerror = e => resolve({error: 'worker error: ' + e.message});
setTimeout(() => resolve({error: 'timeout'}), 10000);
})""" % json.dumps(IDENTITY)
WINDOW_JS = "() => (%s)" % IDENTITY
@pytest.fixture
def sites():
with Sites() as s:
yield s
@pytest.fixture(scope="module")
def browser(firefox_binary):
with launch(firefox_binary) as browser:
yield browser
@pytest.fixture
def page(browser):
context, page = new_page(browser)
yield page
context.close()
def _absent(value):
return value is None or value == "" or (isinstance(value, str) and value.startswith("error"))
def mismatches(reference, other, fields=FIELDS):
"""Every field in which ``other`` differs from ``reference``; an absence on either side is a mismatch."""
problems = []
for field in fields:
if _absent(reference.get(field)):
problems.append("reference has no %s: %r" % (field, reference.get(field)))
elif _absent(other.get(field)):
problems.append("%s is absent (%r), the reference reads %r" % (field, other.get(field), reference[field]))
elif other[field] != reference[field]:
problems.append("%s = %r, the reference reads %r" % (field, other[field], reference[field]))
return problems
# ---------------------------------------------------------------------------
# identity inside workers
# ---------------------------------------------------------------------------
@pytest.fixture
def worker_pages(sites):
sites.route("A", "/workers", "<!doctype html><title>top</title><iframe id='b' src='%s' width='600' height='300'>"
"</iframe>" % sites.url("B", "/workers-b"))
sites.route("B", "/workers-b", "<!doctype html><title>b</title><iframe id='c' src='%s' width='400' height='150'>"
"</iframe>" % sites.url("C", "/workers-c"))
sites.route("C", "/workers-c", "<!doctype html><title>c</title>")
for site in ("A", "B", "C"):
sites.route(site, "/identity-worker.js", "postMessage(%s)" % IDENTITY, ctype="text/javascript")
return sites
def test_the_frames_are_in_other_processes(page, worker_pages):
page.goto(worker_pages.url("A", "/workers"), wait_until="load")
b = wait_frame(page, worker_pages.url("B"), "/workers-b")
assert_other_process(page.main_frame, b)
assert_other_process(b, wait_frame(page, worker_pages.url("C"), "/workers-c"))
@pytest.mark.parametrize("kind", ["blob", "url"])
def test_a_dedicated_worker_reports_the_identity_of_the_window_in_every_frame(page, worker_pages, kind):
page.goto(worker_pages.url("A", "/workers"), wait_until="load")
frames = {"top": page.main_frame,
"frame": wait_frame(page, worker_pages.url("B"), "/workers-b"),
"nested": wait_frame(page, worker_pages.url("C"), "/workers-c")}
reference = page.main_frame.evaluate(WINDOW_JS)
assert not mismatches(reference, reference), reference
problems = []
for name, frame in frames.items():
window = frame.evaluate(WINDOW_JS)
worker = frame.evaluate(WORKER_JS, kind)
problems += ["%s window: %s" % (name, p) for p in mismatches(reference, window)]
problems += ["%s %s worker: %s" % (name, kind, p) for p in mismatches(reference, worker)]
problems += ["%s worker against its own window: %s" % (name, p) for p in mismatches(window, worker)]
assert not problems, "identity differs between the top window and the frames and workers:\n " + "\n ".join(problems)
SHARED_WORKER_JS = """() => new Promise(resolve => {
try {
const worker = new SharedWorker('/shared-worker.js');
worker.port.onmessage = e => resolve({outcome: 'ok', identity: e.data});
worker.onerror = e => resolve({outcome: 'error', message: String(e.message || e)});
} catch (e) { resolve({outcome: 'throw', message: e.name + ': ' + e.message}); }
setTimeout(() => resolve({outcome: 'timeout'}), 10000);
})"""
SERVICE_WORKER_JS = """() => new Promise(resolve => {
try {
navigator.serviceWorker.register('/service-worker.js').then(
registration => navigator.serviceWorker.ready.then(ready => {
navigator.serviceWorker.onmessage = e => resolve({outcome: 'registered', scope: registration.scope,
identity: e.data});
(ready.active || registration.active).postMessage('who');
}),
e => resolve({outcome: 'rejected', message: e.name + ': ' + e.message}));
} catch (e) { resolve({outcome: 'throw', message: e.name + ': ' + e.message}); }
setTimeout(() => resolve({outcome: 'timeout'}), 15000);
})"""
def test_a_shared_worker_made_in_a_frame_of_another_site_reports_the_identity_of_the_top(page, worker_pages):
"""As stock Firefox does: a SharedWorker can be made from a frame of another site (its own site's worker
script), starts, and answers. What it reports about the browser is what the top window reads."""
worker_pages.route("B", "/shared-worker.js", "onconnect = e => { e.ports[0].postMessage(%s); };" % IDENTITY,
ctype="text/javascript")
page.goto(worker_pages.url("A", "/workers"), wait_until="load")
frame = wait_frame(page, worker_pages.url("B"), "/workers-b")
result = frame.evaluate(SHARED_WORKER_JS)
assert result["outcome"] == "ok", result
assert not mismatches(page.main_frame.evaluate(WINDOW_JS), result["identity"]), result
def test_a_service_worker_registered_from_a_frame_of_another_site_reports_the_identity_of_the_top(page, worker_pages):
"""As stock Firefox does: a frame of another site registers a ServiceWorker of its own site (scope the site's
root), it becomes active, and answers a message; what it reports about the browser is what the top window
reads."""
worker_pages.route("B", "/service-worker.js",
"self.addEventListener('install', e => self.skipWaiting());"
"self.addEventListener('activate', e => e.waitUntil(clients.claim()));"
"self.addEventListener('message', e => e.source.postMessage(%s));" % IDENTITY,
ctype="text/javascript", headers=[("Service-Worker-Allowed", "/")])
page.goto(worker_pages.url("A", "/workers"), wait_until="load")
frame = wait_frame(page, worker_pages.url("B"), "/workers-b")
result = frame.evaluate(SERVICE_WORKER_JS)
assert result["outcome"] == "registered", result
assert result["scope"] == worker_pages.url("B", "/"), result
assert not mismatches(page.main_frame.evaluate(WINDOW_JS), result["identity"]), result
# ---------------------------------------------------------------------------
# cookies and storage
# ---------------------------------------------------------------------------
@pytest.fixture
def storage_pages(sites):
read = "window.__r = {cookie: document.cookie, ls: localStorage.getItem('k'), ss: sessionStorage.getItem('k')};"
sites.route("A", "/storage", "<!doctype html><title>top</title><iframe id='b' src='%s'></iframe>"
% sites.url("B", "/storage-b"))
sites.route("B", "/storage-b", "<!doctype html><title>b</title><script>"
"document.cookie = 'jscookie=2; path=/'; localStorage.setItem('k', 'frame-ls');"
"sessionStorage.setItem('k', 'frame-ss'); %s</script>" % read,
headers=[("Set-Cookie", "hdrcookie=1; Path=/")])
sites.route("B", "/storage-own", "<!doctype html><title>own</title><script>%s</script>" % read)
# B as a top page writes a cookie and an item of its own; B in a frame of A reads them (they must not be there)
sites.route("B", "/storage-top-writes", "<!doctype html><title>top writes</title><script>"
"document.cookie = 'topcookie=3; path=/'; localStorage.setItem('top-only', 'top-ls');"
"window.__r = {cookie: document.cookie, top: localStorage.getItem('top-only')};</script>")
sites.route("B", "/storage-read-b", "<!doctype html><title>reads</title><script>"
"window.__r = {cookie: document.cookie, top: localStorage.getItem('top-only')};</script>")
sites.route("A", "/storage-read", "<!doctype html><title>top</title><iframe id='b' src='%s'></iframe>"
% sites.url("B", "/storage-read-b"))
return sites
def test_what_a_frame_of_another_site_stores_is_seen_by_the_frame_and_by_the_context(page, storage_pages):
"""As stock Firefox does: a cookie set by site B inside a frame of A (by a header and by script) is in
`context.cookies()` with B's domain, `document.cookie` of the frame shows both, and so do `localStorage` and
`sessionStorage` of the frame what the frame wrote; a second page of the context with the same frame sees
the same cookies and local storage, and the session storage of its own tab (the frame wrote it there too)."""
context = page.context
page.goto(storage_pages.url("A", "/storage"), wait_until="load")
frame = wait_frame(page, storage_pages.url("B"), "/storage-b")
assert frame.evaluate("window.__r") == {"cookie": "hdrcookie=1; jscookie=2", "ls": "frame-ls", "ss": "frame-ss"}
assert sorted((c["name"], c["domain"]) for c in context.cookies()) == [("hdrcookie", "localhost"),
("jscookie", "localhost")]
assert sorted(c["name"] for c in context.cookies(storage_pages.url("B"))) == ["hdrcookie", "jscookie"]
assert context.cookies(storage_pages.url("A")) == []
second = context.new_page()
second.goto(storage_pages.url("A", "/storage"), wait_until="load")
again = wait_frame(second, storage_pages.url("B"), "/storage-b")
assert again.evaluate("window.__r") == {"cookie": "hdrcookie=1; jscookie=2", "ls": "frame-ls", "ss": "frame-ss"}
def test_storage_of_site_b_is_partitioned_between_a_frame_of_a_and_b_as_a_top_page(page, storage_pages):
"""The retail outcome, not stock Playwright's: cookies and web storage are partitioned by the top-level site.
What site B wrote inside a frame of A is not visible to B opened as a top page: its `document.cookie` is empty
and its `localStorage` item is null (`context.cookies()` still lists B's cookies, with B's domain, because it
reads the whole jar). The reverse holds too: a cookie and a local-storage item that B wrote as a top page are
not visible to B inside the frame of A. The session storage of the top page is empty in both cases.
Why the reference here is the retail Firefox and not stock Playwright Firefox: the reference of this project
is what a page reads in a Firefox a user installed, and retail Firefox partitions third-party cookies and
storage by top-level site (Total Cookie Protection). Playwright's own Firefox ships with that protection off
and shows the stored values to B as a top page (observed with Playwright 1.62: `document.cookie` is
`hdrcookie=1; jscookie=2` and the item is `frame-ls`), which is not what a page sees in a real browser, so
its answer is not the one asserted."""
context = page.context
page.goto(storage_pages.url("A", "/storage"), wait_until="load")
wait_frame(page, storage_pages.url("B"), "/storage-b")
own = context.new_page()
own.goto(storage_pages.url("B", "/storage-own"), wait_until="load")
assert own.evaluate("window.__r") == {"cookie": "", "ls": None, "ss": None}
assert sorted(c["name"] for c in context.cookies(storage_pages.url("B"))) == ["hdrcookie", "jscookie"]
# the reverse: B writes as a top page, then is framed by A and reads
own.goto(storage_pages.url("B", "/storage-top-writes"), wait_until="load")
assert own.evaluate("window.__r") == {"cookie": "topcookie=3", "top": "top-ls"}
reader = context.new_page()
reader.goto(storage_pages.url("A", "/storage-read"), wait_until="load")
frame = wait_frame(reader, storage_pages.url("B"), "/storage-read-b")
# B inside A reads its own partition: the two cookies the frame wrote above are there, what B wrote as a top page
# (`topcookie`, the `top-only` item) is not.
assert frame.evaluate("window.__r") == {"cookie": "hdrcookie=1; jscookie=2", "top": None}
# ---------------------------------------------------------------------------
# frames with no address of their own
# ---------------------------------------------------------------------------
INNER = "&lt;p id=x&gt;%s&lt;/p&gt;&lt;script&gt;window.v=1&lt;/script&gt;"
SPECIAL = ('<iframe id="srcdoc" srcdoc="%s"></iframe>' % (INNER % "in srcdoc")
+ '<iframe id="blank"></iframe>'
+ '<iframe id="data" src="data:text/html,%s"></iframe>' % (INNER % "in data")
+ '<iframe id="sb0" sandbox srcdoc="%s"></iframe>' % (INNER % "sb0")
+ '<iframe id="sb1" sandbox="allow-scripts allow-same-origin" srcdoc="%s"></iframe>' % (INNER % "sb1")
+ '<iframe id="sb2" sandbox="allow-scripts" srcdoc="%s"></iframe>' % (INNER % "sb2"))
#: id -> (url of the frame, `window.v` in it, text of #x). `window.v` is 1 where the document's script ran;
#: a sandbox without `allow-scripts` runs none, but `evaluate` still works there and answers undefined.
SPECIAL_FRAMES = {
"srcdoc": ("about:srcdoc", 1, "in srcdoc"),
"blank": ("about:blank", None, None),
"data": (None, 1, "in data"),
"sb0": ("about:srcdoc", None, "sb0"),
"sb1": ("about:srcdoc", 1, "sb1"),
"sb2": ("about:srcdoc", 1, "sb2"),
}
@pytest.fixture
def special_pages(sites):
sites.route("A", "/special", "<!doctype html><title>special</title>" + SPECIAL)
sites.route("B", "/special", "<!doctype html><title>special b</title>" + SPECIAL)
sites.route("A", "/special-in-b", "<!doctype html><title>top</title><iframe id='b' src='%s'></iframe>"
% sites.url("B", "/special"))
return sites
@pytest.mark.parametrize("where", ["top", "inside_b"])
def test_special_frames_are_listed_evaluated_and_reached_by_frame_locator(page, special_pages, where):
"""As stock Firefox does: `srcdoc` and every `sandbox`ed srcdoc frame is `about:srcdoc`, the empty one is
`about:blank`, the `data:` one keeps its url; all are in `page.frames` under their parent, named by their id;
`evaluate` works in all of them and finds `window.v` where the document's script could run (not in the
sandbox without `allow-scripts`, not in the empty frame); `frame_locator` reaches the text inside each, in
the empty frame once something is written there; the same at the top level and inside a frame of B."""
path = "/special" if where == "top" else "/special-in-b"
page.goto(special_pages.url("A", path), wait_until="load")
owner_site = "A" if where == "top" else "B"
owner = wait_frame(page, special_pages.url(owner_site), "/special")
if where == "inside_b":
assert_other_process(page.main_frame, owner)
expected_count = 1 + (where == "inside_b") + len(SPECIAL_FRAMES)
assert wait_for(page, lambda: len(page.frames) == expected_count), [(f.name, f.url) for f in page.frames]
inner = {f.name: f for f in page.frames if f.parent_frame is owner}
assert sorted(inner) == sorted(SPECIAL_FRAMES), [(f.name, f.url) for f in page.frames]
scope = page.frame_locator("#b") if where == "inside_b" else page
for frame_id, (url, value, text) in SPECIAL_FRAMES.items():
frame = inner[frame_id]
if url is None:
assert frame.url.startswith("data:text/html,"), frame.url
else:
assert frame.url == url, (frame_id, frame.url)
assert frame.evaluate("window.v") == value, frame_id
if frame_id == "blank":
frame.evaluate("document.body.innerHTML = '<p id=x>written</p>'")
text = "written"
assert scope.frame_locator("#" + frame_id).locator("#x").inner_text() == text, frame_id
+1 -1
View File
@@ -189,7 +189,7 @@ def test_a_long_session_does_not_accumulate_subscribers(firefox_binary, first_ru
assert leaked_objects == 0, (
"forty open-and-close cycles left %d objects in the server's guid "
"registry; a closed page must be disposed, which is also what the "
"driver does and what the old protocol comparison's fifth dimension compared"
"driver does and what diff_protocol's fifth dimension compares"
% leaked_objects)
+2 -2
View File
@@ -92,7 +92,7 @@ def test_the_default_is_the_PYTHON_SERVER(monkeypatch):
user session into an experiment. What flipped it is four measurements taken
on one code state, not the code looking done: `run_e2e.py` 188 passed on
BOTH transports; the transport judge 50 green on both with 0 red only on
ours; the protocol comparison at parity on methods, parameters, object types,
ours; `diff_protocol.py` at parity on methods, parameters, object types,
initializer fields, events and parentage; and the realness gates green on
this path for the first time.
@@ -108,7 +108,7 @@ def test_the_driver_is_still_reachable_by_name(monkeypatch):
"""⛔ The way back has to keep working, or the flip above is one-way.
A user whose session behaves differently on the new path must be able to
say so and get the old one, and any comparison between the two arms needs it to have
say so and get the old one, and `judge_both_transports.py` needs it to have
a second arm at all.
"""
monkeypatch.setenv(factory.CHOICE_ENV, "driver")
+6
View File
@@ -171,6 +171,12 @@ 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
@@ -4,7 +4,7 @@
four browsers at once, it was 75% of the reader's lag, and it made `networkidle` miss 7 times in 400 (none in 400 once the start no longer
waited). Two listeners of this package started a thread from the reader: `Browser.attachedToTarget` (one thread per adoption) and
`Page.fileChooserOpened` (one thread to announce the chooser). Both now hand the thread to the browser's ONE long-lived starter
(`ThreadStarter`, made with the browser), which starts it.
(`_ThreadStarter`, made with the browser), which starts it.
NO BROWSER HERE: the real dispatchers over a scripted Juggler connection, and every event of the engine delivered FROM A THREAD OF ITS OWN
(the reader's stand-in), the way the connection delivers them. `Thread.start` is replaced by a recorder of the thread that called it.
@@ -127,20 +127,16 @@ def test_an_attached_target_and_a_file_chooser_start_no_thread_on_the_reader(sta
server.shutdown()
def test_the_starter_of_a_browser_ends_with_its_connection_and_the_connections_thread_with_the_server(starts):
def test_the_starter_of_a_browser_ends_with_its_connection(starts):
server, conn, browser, context, opener_target = _world(starts)
try:
starter = browser.thread_starter
starter.start(target=lambda: None, name="invpw-test-started")
assert _wait(lambda: ("invpw-thread-starter", "invpw-test-started") in starts, 3)
conn.announce_closed()
starter.start(target=lambda: None, name="invpw-test-after-the-end") # after the connection's end: nothing is started, nothing raises
shared = server.thread_starter
assert shared is server.thread_starter, "the server must own ONE starter"
assert shared._thread.is_alive(), "the server's starter must outlive one browser's connection"
server.shutdown()
shared._thread.join(5)
assert not shared._thread.is_alive(), "the starter outlived the server"
starter._thread.join(5)
assert not starter._thread.is_alive(), "the starter outlived the connection"
starter.start(target=lambda: None, name="invpw-test-after-the-end") # after the end: nothing is started, nothing raises
assert all(c[1] != "invpw-test-after-the-end" for c in starts)
finally:
server.shutdown()
+2 -4
View File
@@ -258,14 +258,12 @@ class _Page:
def engine(monkeypatch):
monkeypatch.setattr(srv, "PageDispatcher", _Page)
e = _Engine()
server = Server()
browser = BrowserDispatcher(server, None, e, "151.0", session_seed=1)
browser = BrowserDispatcher(Server(), None, e, "151.0", session_seed=1)
e.browser = browser
context = BrowserContextDispatcher(browser.server, browser, {}, "C1")
browser.contexts.append(context)
e.context = context
yield e
server.shutdown() # the connection's one starter ends with its server
return e
def _new_page_in_thread(engine, number, out):
@@ -1,278 +0,0 @@
"""The engine DECLARES software compositing on every machine, and what a page reads does not change by it.
The core declares, in the feature-status table (`zoom.stealth.gfx.feature_status`), the decision that Firefox retail takes on a
virtual machine: the compositing features (WEBRENDER, WEBRENDER_COMPOSITOR, the D3D*_LAYERS, CANVAS2D_ACCELERATION, ...) are
blocklisted with FEATURE_FAILURE_VM_VENDOR, and on Windows the core sets `gfx.webrender.software=true` and
`gfx.webrender.software.d3d11=false`. WebGL, WebGPU and the media features stay as the persona declares them. Three things follow, one test each:
1. the compositor the engine runs is WebRender (Software), on Windows AND on Linux (on Linux this closes the risk that the table,
with no pref beside it, sends the engine down another road);
2. the GPU process, which is where a hardware WebRender spends its CPU, spends almost none on a fixed scene;
3. no byte a page reads of canvas 2D, WebGL, WebGPU, text and the declared values changes: the keys of the probe (the 86 of the first
hunt, WebGPU features and limits read by name, and the canvas 2D scenes added for the canvas blocklist: drawImage scaled up and down
with imageSmoothing off and on at three qualities, text filled and stroked with gradients of three kinds) equal the reference of the
operating system, tests/data/page_bytes_<os>.json.
Known-bad input: the engine with the core of firefox-64 before this declaration (64.71.0). On the Windows runner `gfx.webrender.software`
is false there (the effective prefs of run 43652292533, arm ours) and the GPU process uses 2.7 to 4.2 s on the scene of test 2 (GitHub
Actions runs 43652292533 and 43642744101): tests 1 and 2 are red on it. Whether test 1 is red on Linux with that core is not measured.
How the compositor is read. `Troubleshoot.snapshot().graphics` is what about:support shows and carries `windowLayerManagerType`, but on
this engine the provider throws before it gets there (`ext is null`: it asks WebGL for the chrome-only MOZ_debug extension, which the
engine does not give), so `graphics` is an error string. The test reads what the provider reads, the same two properties of each window
(`windowUtils.layerManagerType` and `.layerManagerRemote`, Troubleshoot.sys.mjs), in chrome scope through Marionette: the route
tests/webfont_probe.py uses (`-marionette -remote-allow-system-access` and MOZ_REMOTE_ALLOW_SYSTEM_ACCESS=1).
"""
from __future__ import annotations
import http.server
import json
import sys
import threading
import time
from pathlib import Path
import pytest
pytestmark = pytest.mark.e2e
OS_NAME = "windows" if sys.platform == "win32" else "linux"
SOFTWARE = "WebRender (Software)"
MARIONETTE_ARGS = ["-marionette", "-remote-allow-system-access"]
#: What a launch is given in the hunt that measured the Windows reference (same seed, locale and timezone, so the same persona).
LAUNCH = dict(seed=42, headless=True, locale="en-US", timezone="Europe/Rome")
# --------------------------------------------------------------------------------------------------------- the privileged reads
WINDOWS_JS = """
const out = [];
for (const win of Services.ww.getWindowEnumerator()) {
try {
const u = win.windowUtils;
out.push([u.layerManagerType, u.layerManagerRemote]);
} catch (e) { out.push(["error: " + e, false]); }
}
return JSON.stringify(out);
"""
PREFS_JS = """
const out = {};
for (const name of arguments[0]) {
const t = Services.prefs.getPrefType(name);
out[name] = t === 32 ? Services.prefs.getStringPref(name)
: t === 64 ? Services.prefs.getIntPref(name)
: t === 128 ? Services.prefs.getBoolPref(name) : null;
}
return JSON.stringify(out);
"""
def _marionette(port):
import webfont_probe
m = webfont_probe._Marionette(port)
m.call("WebDriver:NewSession", {"capabilities": {"alwaysMatch": {}}})
m.call("Marionette:SetContext", {"value": "chrome"})
return m
def _script(marionette, script, args=()):
return json.loads(marionette.call("WebDriver:ExecuteScript", {"script": script, "args": list(args)})["value"])
def _a_page_server(page_html):
class Handler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
body = page_html.encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
server.daemon_threads = True
threading.Thread(target=server.serve_forever, daemon=True).start()
return server, "http://127.0.0.1:%d/" % server.server_address[1]
# ------------------------------------------------------------------------------------------------ 1. the compositor
def test_the_compositor_is_webrender_software_whatever_the_machine(firefox_binary, monkeypatch):
import webfont_probe
from invisible_playwright import InvisiblePlaywright
monkeypatch.setenv("MOZ_REMOTE_ALLOW_SYSTEM_ACCESS", "1") # the chrome-scope reads below
port = webfont_probe.MARIONETTE_PORT
pref_names = ["zoom.stealth.gfx.feature_status", "gfx.webrender.software", "gfx.webrender.software.d3d11"]
server, url = _a_page_server("<!doctype html><title>compositor</title><body>x</body>")
marionette = None
try:
with InvisiblePlaywright(binary_path=firefox_binary, extra_args=MARIONETTE_ARGS,
extra_prefs={"marionette.port": port}, **LAUNCH) as browser:
page = browser.new_page()
page.goto(url, wait_until="load", timeout=60000)
marionette = _marionette(port)
# a window gets its layer manager a moment after it is shown: the same wait for the answer as about:support has none, so poll
windows, end = [], time.time() + 30
while time.time() < end:
windows = _script(marionette, WINDOWS_JS)
if any(kind not in ("None", "") and remote for kind, remote in windows):
break
time.sleep(0.5)
prefs = _script(marionette, PREFS_JS, [pref_names])
finally:
if marionette is not None:
marionette.close()
server.shutdown()
shown = [kind for kind, remote in windows if kind != "None" and remote]
assert shown, "no window of the engine has a layer manager (windowUtils.layerManagerType, layerManagerRemote): %r" % (windows,)
assert set(shown) == {SOFTWARE}, (
"the compositor of the window(s) is %r on %s, expected %r: the engine did not take the VM decision for the compositing features"
% (shown, OS_NAME, SOFTWARE))
table = {}
for entry in (prefs["zoom.stealth.gfx.feature_status"] or "").split(","):
name, _, rest = entry.partition("|")
table[name] = rest.split("|")
webrender = table.get("WEBRENDER")
assert webrender is not None, "the declared table has no WEBRENDER entry: %r" % (prefs["zoom.stealth.gfx.feature_status"],)
assert webrender[1:2] == ["FEATURE_FAILURE_VM_VENDOR"], (
"WEBRENDER is declared %r, expected blocklisted with FEATURE_FAILURE_VM_VENDOR" % (webrender,))
if OS_NAME == "windows":
assert prefs["gfx.webrender.software"] is True, "gfx.webrender.software is %r on Windows" % (prefs["gfx.webrender.software"],)
assert prefs["gfx.webrender.software.d3d11"] is False, \
"gfx.webrender.software.d3d11 is %r on Windows" % (prefs["gfx.webrender.software.d3d11"],)
# ------------------------------------------------------------------------------------------------ 2. the GPU process
#: The scene of the hunt that measured it (scripts/hunt_cpu_per_browser.py of the branch hunt/cpu-render-path): a page that builds an
#: RTCPeerConnection with no ICE servers and waits for the gather, draws 200 DOM elements and one 2D canvas frame; the browser goes to
#: the next copy of it, 10 times.
ROUNDS = 10
ICE_WAIT_MS = 15000
SCENE = """<!doctype html><meta charset=utf-8><title>scenario</title>
<body><div id=root></div><canvas id=c width=320 height=200></canvas>
<script>
window.__ready = (async () => {
const pc = new RTCPeerConnection({iceServers: []});
pc.createDataChannel("x");
const done = new Promise(res => {
const t = setTimeout(() => res("timeout:" + pc.iceGatheringState), %(ice_wait)d);
pc.addEventListener("icegatheringstatechange", () => {
if (pc.iceGatheringState === "complete") { clearTimeout(t); res("complete"); }
});
});
await pc.setLocalDescription(await pc.createOffer());
const state = pc.iceGatheringState === "complete" ? "complete" : await done;
const root = document.getElementById("root");
for (let i = 0; i < 200; i++) {
const d = document.createElement("div");
d.textContent = "element " + i;
d.style.cssText = "display:inline-block;width:40px;height:16px;margin:1px;background:hsl(" + (i * 7 %% 360) + ",60%%,60%%)";
root.appendChild(d);
}
const g = document.getElementById("c").getContext("2d");
for (let i = 0; i < 40; i++) {
g.fillStyle = "hsl(" + (i * 9) + ",70%%,50%%)";
g.fillRect(i * 8, (i * 5) %% 160, 60, 30);
}
g.font = "16px sans-serif";
g.fillText("a frame of the scenario", 10, 100);
g.getImageData(0, 0, 1, 1);
pc.close();
return state;
})();
</script>
""" % {"ice_wait": ICE_WAIT_MS}
#: CPU seconds the GPU process may use for the 10 scenes of ONE browser, per operating system.
#:
#: WINDOWS: 1.5 s. Measured on the windows-2022 runner (Hyper-V, no real GPU), 4 browsers at once, the same 10 scenes each, GPU process,
#: median per browser: 0.32 s with the VM decision declared (run 43652292533, arm ours_vmretail, mean of two rounds 0.324 s) and 2.7 to
#: 4.2 s without it (run 43652292533, arm ours, 2.68 s, and run 43642744101). Stock Firefox 159 headed on the same runner: 0.004 s.
#: 1.5 s is about 4.7 times what the declared engine used and 0.55 times the least the undeclared one used: a run that is slow for
#: 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 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):
import os
from _cpu_by_type import CpuSampler
from invisible_playwright import InvisiblePlaywright
server, base = _a_page_server(SCENE)
states = []
try:
with InvisiblePlaywright(binary_path=firefox_binary, **LAUNCH) as browser:
page = browser.new_page()
sampler = CpuSampler(os.getpid())
sampler.begin()
try:
for n in range(ROUNDS):
page.goto("%sp/%d" % (base, n), wait_until="load", timeout=60000)
states.append(page.evaluate("window.__ready"))
finally:
cpu = sampler.end()
seen = sorted({kind for kind, _cpu in sampler.last.values()})
finally:
server.shutdown()
with capsys.disabled():
print("\nCPU seconds of the engine by process type over %d scenes of one browser on %s: %s (types seen: %s)"
% (ROUNDS, OS_NAME, json.dumps({k: round(v, 3) for k, v in cpu.items() if v or k in seen}), ", ".join(seen)))
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]
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 "
"declared as software it used 0.32 s on the Windows runner (run 43652292533), without it 2.7 to 4.2 s (runs 43652292533, 43642744101)"
% (cpu["gpu"], ROUNDS, OS_NAME, limit, json.dumps({k: round(v, 2) for k, v in cpu.items() if v})))
# ------------------------------------------------------------------------------------------------ 3. what a page reads
def test_the_bytes_a_page_reads_are_the_reference_of_the_system(firefox_binary):
import _page_bytes
from invisible_playwright import InvisiblePlaywright
expression = (Path(__file__).resolve().parent / "page_bytes_probe.js").read_text(encoding="utf-8")
server, url = _a_page_server("<!doctype html><meta charset=utf-8><title>probe</title><body></body>")
try:
with InvisiblePlaywright(binary_path=firefox_binary, **LAUNCH) as browser:
page = browser.new_page()
page.goto(url, wait_until="load", timeout=60000)
measured = page.evaluate(expression)
finally:
server.shutdown()
problems, record = _page_bytes.compare(_page_bytes.load_reference(OS_NAME), measured)
assert not problems, _page_bytes.message(OS_NAME, problems, record)
-30
View File
@@ -1,30 +0,0 @@
"""The leak census runs from conftest in every job, including the ones that install pytest alone. There it must import nothing of the
package: the `version` job of the release pull request failed with `No module named 'invisible_core'` when the census imported
`invisible_playwright._juggler._threads` (which pulls `invisible_playwright._pin`)."""
import subprocess
import sys
import textwrap
from pathlib import Path
TESTS = Path(__file__).resolve().parent
def test_a_census_in_a_process_that_never_loaded_the_package_imports_nothing_and_counts_nothing():
script = textwrap.dedent("""
import sys
sys.path.insert(0, %r)
class _NoPackage:
def find_spec(self, name, path=None, target=None):
if name == "invisible_core" or name.startswith(("invisible_core.", "invisible_playwright")):
raise ImportError("the census imported %%s" %% name)
return None
sys.meta_path.insert(0, _NoPackage())
import _browser_census as census
assert census.starters_alive() == [], census.starters_alive()
assert census.wait_until_back_to(0, seconds=0) == 0
loaded = sorted(m for m in sys.modules if m.startswith(("invisible_core", "invisible_playwright")))
assert not loaded, loaded
print("OK")
""") % str(TESTS)
done = subprocess.run([sys.executable, "-I", "-c", script], capture_output=True, text=True, timeout=60)
assert done.returncode == 0 and done.stdout.strip() == "OK", done.stdout + done.stderr
@@ -1,130 +0,0 @@
"""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))
@@ -1,244 +0,0 @@
"""The helpers of tests/test_software_compositing_is_declared_e2e.py, on known inputs (no browser).
* a PNG is compared by the pixels it decodes to: the same pixels with another per-launch chunk (`deBG`) and another compression are the
same; one pixel changed is not;
* the comparison with the reference names every key that differs, is missing, or is extra, and a missing one carries the entry to record;
* the process type is read from the last argument of `-contentproc`; the CPU of a window is the last value minus the first, a process
born inside it counted whole.
The committed reference of Windows is held to its own shape: every key of the stable part has a value, and every PNG entry has a length.
"""
from __future__ import annotations
import base64
import json
import struct
import zlib
import pytest
import _cpu_by_type as cpu
import _page_bytes as pb
pytestmark = pytest.mark.unit
def _chunk(tag, data):
return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)
def _png(w, h, rgba, extra=b"", level=6, ftype=0):
rows = b"".join(bytes([ftype]) + rgba[y * w * 4:(y + 1) * w * 4] for y in range(h))
return (pb.PNG_SIGNATURE + _chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 6, 0, 0, 0))
+ _chunk(b"IDAT", zlib.compress(rows, level)) + extra + _chunk(b"IEND", b""))
PIXELS = bytes((7 * i + 3) % 256 for i in range(4 * 5 * 4))
def _value(png, data_url=False):
if data_url:
return {"h": "x", "n": len(png) * 2, "b64": base64.b64encode(png).decode()}
return {"h": "x", "n": len(png), "b64": base64.b64encode(png).decode()}
def test_the_same_pixels_with_another_chunk_and_another_compression_are_the_same():
a = pb.decode_png(_png(4, 5, PIXELS, extra=_chunk(b"deBG", b"4620504988720C77"), level=6))
b = pb.decode_png(_png(4, 5, PIXELS, extra=_chunk(b"deBG", b"D5E4439F1FAC5913"), level=1))
assert a == b and a["w"] == 4 and a["h"] == 5 and a["ct"] == 6
def test_one_pixel_changed_is_another_png():
changed = bytearray(PIXELS)
changed[17] ^= 1
assert pb.decode_png(_png(4, 5, PIXELS))["sha256"] != pb.decode_png(_png(4, 5, bytes(changed)))["sha256"]
@pytest.mark.parametrize("ftype", [1, 2, 3, 4])
def test_every_scanline_filter_decodes_to_the_pixels(ftype):
"""The encoder of the engine chooses a filter per row; the decoder must undo each of them. The rows are filtered by hand."""
w, h, bpp = 4, 5, 4
stride = w * bpp
rows = [PIXELS[y * stride:(y + 1) * stride] for y in range(h)]
out = bytearray()
prev = bytes(stride)
for row in rows:
line = bytearray()
for i in range(stride):
left = row[i - bpp] if i >= bpp else 0
up = prev[i]
upleft = prev[i - bpp] if i >= bpp else 0
if ftype == 1:
pred = left
elif ftype == 2:
pred = up
elif ftype == 3:
pred = (left + up) >> 1
else:
pred = pb._paeth(left, up, upleft)
line.append((row[i] - pred) & 255)
out += bytes([ftype]) + line
prev = row
png = (pb.PNG_SIGNATURE + _chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 6, 0, 0, 0))
+ _chunk(b"IDAT", zlib.compress(bytes(out))) + _chunk(b"IEND", b""))
assert pb.decode_png(png) == pb.decode_png(_png(w, h, PIXELS))
def test_something_that_is_not_a_png_is_refused():
with pytest.raises(pb.NotAPng):
pb.decode_png(b"GIF89a....")
def _reference_of(measured):
ref = {"keys": {}, "pngs": {}}
for key, value in measured.items():
(ref["pngs"] if pb.is_png_key(key) else ref["keys"])[key] = pb.entry_of(key, value)
return ref
def _measured(png_extra=b"", pixels=PIXELS):
return {
"env.ua": {"s": "Mozilla"},
"c2d.shapes.getImageData": {"h": "abc", "n": 80, "w": 4, "b64": "AAAA"},
"c2d.shapes.png": _value(_png(4, 5, pixels, extra=png_extra), data_url=True),
"c2d.shapes.toBlob": _value(_png(4, 5, pixels, extra=png_extra)),
}
def test_a_launch_equal_to_its_reference_has_no_problem_whatever_its_png_chunk():
reference = _reference_of(_measured(png_extra=_chunk(b"deBG", b"4620504988720C77")))
problems, record = pb.compare(reference, _measured(png_extra=_chunk(b"deBG", b"D5E4439F1FAC5913")))
assert problems == [] and record == {}
def test_a_changed_stable_value_a_changed_pixel_a_missing_and_an_extra_key_are_each_named():
reference = _reference_of(_measured())
changed = bytearray(PIXELS)
changed[0] ^= 9
measured = _measured(pixels=bytes(changed))
measured["env.ua"] = {"s": "Other"}
measured["c2d.scale.off.getImageData"] = {"h": "n", "n": 1}
del measured["c2d.shapes.getImageData"]
problems, record = pb.compare(reference, measured)
text = "\n".join(problems)
assert "env.ua" in text
assert "c2d.shapes.png: the decoded pixels differ" in text and "c2d.shapes.toBlob: the decoded pixels differ" in text
assert "c2d.shapes.getImageData: in the reference and not read by the probe" in text
assert "c2d.scale.off.getImageData: not in the reference" in text
assert list(record) == ["c2d.scale.off.getImageData"]
assert "RECORD-BEGIN" in pb.message("linux", problems, record)
def test_a_reference_that_holds_only_the_length_of_a_png_asks_for_its_pixels():
measured = _measured()
reference = _reference_of(measured)
del reference["pngs"]["c2d.shapes.png"]["sha256"]
problems, record = pb.compare(reference, measured)
assert problems == ["c2d.shapes.png: the reference has the length of this PNG and not yet its decoded pixels"]
assert record["c2d.shapes.png"]["sha256"] == pb.entry_of("c2d.shapes.png", measured["c2d.shapes.png"])["sha256"]
def test_no_reference_file_makes_every_key_a_problem_with_its_entry():
problems, record = pb.compare({"keys": {}, "pngs": {}}, _measured())
assert len(problems) == 4 and sorted(record) == sorted(_measured())
def test_a_png_the_page_read_that_does_not_decode_is_a_problem_not_a_pass():
measured = {"c2d.shapes.png": {"h": "x", "n": 10, "b64": base64.b64encode(b"not a png at all").decode()}}
problems, record = pb.compare({"keys": {}, "pngs": {}}, measured)
assert len(problems) == 1 and "does not decode" in problems[0] and record == {}
def test_a_png_data_url_short_enough_to_be_a_string_is_decoded_too():
png = _png(4, 5, PIXELS)
value = {"s": pb.DATA_PREFIX + base64.b64encode(png).decode()}
entry = pb.png_entry(value)
assert entry["n"] == len(value["s"]) and entry["sha256"] == pb.decode_png(png)["sha256"]
def test_the_keys_that_are_png_files_and_the_ones_that_are_not():
for key in ("c2d.shapes.png", "c2d.shapes.toBlob", "c2d.offscreen.convertToBlob", "gl1.triangle.toDataURL", "c2d.scale.high.png"):
assert pb.is_png_key(key), key
for key in ("c2d.shapes.jpeg", "c2d.shapes.webp", "gl1.triangle.toDataURL_jpeg", "c2d.scale.high.getImageData", "env.ua"):
assert not pb.is_png_key(key), key
def test_the_type_of_a_process_is_the_last_argument_of_contentproc():
assert cpu.classify(["firefox.exe", "-no-remote", "-profile", "p"]) == "parent"
assert cpu.classify(["firefox.exe", "-contentproc", "-parentBuildID", "1", "gpu"]) == "gpu"
assert cpu.classify(["firefox.exe", "-contentproc", "-isForBrowser", '"tab"']) == "tab"
assert cpu.classify(["firefox", "-contentproc", "x", "forkserver"]) == "forkserver"
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)}
out = cpu.delta_by_type(start, last)
assert out["parent"] == 2.5 and out["gpu"] == 0.75 and out["tab"] == 2.0 and out["socket"] == 0.0
def test_the_reference_committed_for_windows_has_the_shape_the_comparison_reads():
ref = json.loads(pb.reference_path("windows").read_text(encoding="utf-8"))
assert ref["os"] == "windows" and ref["source"]
assert ref["keys"] and all(("s" in v) != ("h" in v) for v in ref["keys"].values())
assert all(not pb.is_png_key(k) for k in ref["keys"])
assert ref["pngs"] and all(pb.is_png_key(k) and isinstance(v.get("n"), int) for k, v in ref["pngs"].items())
assert all(len(v["sha256"]) == 64 for v in ref["pngs"].values() if "sha256" in v)
@@ -1,188 +0,0 @@
"""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
+5 -4
View File
@@ -17,7 +17,6 @@ import math
import pytest
from invisible_playwright._juggler import wire
from invisible_playwright._juggler.dispatcher import Server
from invisible_playwright._juggler.transport import InProcessTransport, JsonWireTransport
pytestmark = pytest.mark.unit
@@ -68,11 +67,10 @@ def test_a_lone_surrogate_survives_the_text():
# ── the transport ──────────────────────────────────────────────────────────
class _Server(Server):
"""What `InProcessTransport` needs of a server: attach, handle, shutdown, and the one starter it starts its workers through."""
class _Server:
"""What `InProcessTransport` needs of a server: attach, handle, shutdown."""
def __init__(self, result):
super().__init__()
self._result = result
self.seen = []
@@ -83,6 +81,9 @@ class _Server(Server):
self.seen.append(message)
return self._result
def shutdown(self):
pass
def _call(transport_class, result, message):
"""Send `message` through a `transport_class` over a server answering `result`;
@@ -1,177 +0,0 @@
"""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)
+2 -5
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 bench_report, declared_udp, declared_udp_or_absent, egress_by_proxy, measure_servers
from _udp_line import declared_udp, egress_by_proxy, measure_servers
# ──────────────────────────────────────────────────────────────────────────
# Pure SDP / ICE-candidate helpers (no I/O) - the heart of the sentinels.
@@ -438,14 +438,11 @@ 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; {bench}")
f"UDP ASSOCIATEs the gateway saw: {associates}; round trip to the gateway: {rtt_ms} ms")
return bool(srflx) and (STUN_NUMBER, STUN_PORT) in carried, verdict, res["at_ms"]
-111
View File
@@ -1,111 +0,0 @@
"""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