Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7806a97595 | ||
|
|
ea7c1b11f9 |
No files matched your search
@@ -1,206 +0,0 @@
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# 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
|
||||
@@ -1,312 +0,0 @@
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# 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
|
||||
@@ -1,330 +0,0 @@
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# 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
|
||||
+5
-165
@@ -6,7 +6,8 @@
|
||||
# launched Firefox in true HEADLESS mode, which is content-process unstable on
|
||||
# the hosted runners (eval-CSP / context-destroyed). The stealth wrapper instead
|
||||
# launches Firefox HEADED on a real display; under `xvfb-run` (a virtual X
|
||||
# server) that's exactly what we get on a headless CI box - stable.
|
||||
# server) that's exactly what we get on a headless CI box - stable, and the same
|
||||
# thing webrtc-e2e.yml already relies on.
|
||||
#
|
||||
# Secret-free, so it's safe in public CI: the binary is the PUBLIC firefox-9
|
||||
# release (no token), and the webrtc e2e fake a local TCP-only SOCKS. The proxy
|
||||
@@ -33,15 +34,6 @@ on:
|
||||
- 'docs/**'
|
||||
- 'LICENSE'
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
only:
|
||||
description: "Which job. `windows-control-a` runs only the Windows job of the keyboard shortcut (after the core of a release is on the index and its engine is published); `all` runs the whole workflow."
|
||||
required: false
|
||||
default: "all"
|
||||
type: choice
|
||||
options:
|
||||
- all
|
||||
- windows-control-a
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -83,7 +75,7 @@ jobs:
|
||||
e2e:
|
||||
name: e2e (linux, xvfb)
|
||||
needs: core-on-index
|
||||
if: needs.core-on-index.outputs.available == 'true' && inputs.only != 'windows-control-a'
|
||||
if: needs.core-on-index.outputs.available == 'true'
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 40
|
||||
steps:
|
||||
@@ -124,13 +116,6 @@ jobs:
|
||||
# The generator moved into the core with the module it writes (0.30.0),
|
||||
# so the check runs against the core this package installs.
|
||||
run: python -m invisible_core.juggler._gen_protocol --check --binary "$(dirname "$FF")"
|
||||
# The GeoIP database is made by the repository (scripts/ci_lab_geoip.py: the same bytes on every run, the sha256 in ci/geoip.json), never a
|
||||
# site and never a licensed file: without STEALTHFOX_GEOIP_MMDB the core asks GitHub which database is the latest on every call
|
||||
# (run 43211837926). The variable reaches every later step of the job.
|
||||
- name: The GeoIP database (made by the repository, same bytes every run)
|
||||
shell: bash
|
||||
run: python scripts/ci_lab_geoip.py build
|
||||
|
||||
- name: Run the full e2e suite under a virtual display, without the root ones
|
||||
# PYTHONUNBUFFERED, and it is not a nicety. Without it Python block-buffers
|
||||
# stdout when it is a pipe, and this step printed NOTHING for 39 minutes
|
||||
@@ -149,11 +134,9 @@ jobs:
|
||||
INVPW_TEST_WATCHDOG_FILE: ${{ runner.temp }}/e2e-watchdog.log
|
||||
ROOT_FILES: tests/test_a_proxy_that_cannot_carry_udp_leaks_nothing_direct_e2e.py
|
||||
ROOT_NODES: tests/test_the_whole_udp_chain_by_name_e2e.py::test_a_turn_srflx_by_name_arrives_through_the_relay_before_the_tick
|
||||
SANDBOX_FILES: tests/test_the_socket_process_is_sandboxed_e2e.py
|
||||
# The root ones are left out by name and run in the step below, as root: here, as the runner user, they errored. The sandbox one is left out
|
||||
# by name too and runs in its own step after them: it is red on a runner whose AppArmor refuses user namespaces to a normal user.
|
||||
# The root ones are left out by name and run in the step below, as root: here, as the runner user, they errored.
|
||||
run: |
|
||||
IGNORE=(); for f in $ROOT_FILES $SANDBOX_FILES; do IGNORE+=("--ignore=$f"); done
|
||||
IGNORE=(); for f in $ROOT_FILES; do IGNORE+=("--ignore=$f"); done
|
||||
DESELECT=(); for n in $ROOT_NODES; do DESELECT+=("--deselect=$n"); done
|
||||
xvfb-run -a python -u scripts/run_e2e.py "$FF" "${IGNORE[@]}" "${DESELECT[@]}"
|
||||
|
||||
@@ -192,32 +175,6 @@ jobs:
|
||||
if counts["tests"] != int(os.environ["ROOT_TESTS"]) or counts["failures"] or counts["errors"] or counts["skipped"]:
|
||||
sys.exit("the root e2e must be exactly %s tests, all passed: %s" % (os.environ["ROOT_TESTS"], counts))
|
||||
PY
|
||||
# THE SANDBOX E2E (wrapper.e2e.udp.sandbox), as the gate runs its first file: the browser WITH its sandbox, run by the runner user. On this runner AppArmor
|
||||
# refuses user namespaces to a normal user (kernel.apparmor_restrict_unprivileged_userns=1), so the browser of every other step starts WITHOUT the sandbox
|
||||
# of its socket and content processes, and tests/test_the_socket_process_is_sandboxed_e2e.py (which fails unless both have a seccomp filter) can only
|
||||
# be green after the restriction is turned off. It is left out of the run above by name (SANDBOX_FILES) so that it cannot fail on a runner without the
|
||||
# sysctl, and it runs here, after the run and the root step (whatever the sysctl changes cannot reach a launch of the run), as the runner user. Nothing
|
||||
# is skipped silently: the step reads its own junit and refuses anything but exactly that many tests, all passed.
|
||||
# tests/test_the_sandbox_e2e_runs_where_user_namespaces_are_on.py holds this step, the exclusion above and the order.
|
||||
- name: The sandbox e2e (wrapper.e2e.udp.sandbox), with unprivileged user namespaces on
|
||||
if: success() || failure()
|
||||
env:
|
||||
PYTHONUNBUFFERED: "1"
|
||||
SANDBOX_FILES: tests/test_the_socket_process_is_sandboxed_e2e.py
|
||||
SANDBOX_TESTS: "1"
|
||||
run: |
|
||||
sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0
|
||||
JUNIT="${RUNNER_TEMP}/sandbox-e2e.xml"
|
||||
xvfb-run -a env -u PYTEST_ADDOPTS INVPW_BINARY_PATH="$FF" STEALTHFOX_E2E_BINARY="$FF" python -m pytest $SANDBOX_FILES -m e2e -o addopts='' -o junit_family=xunit2 -q -p no:cacheprovider -p no:rerunfailures -rs --junitxml="$JUNIT" || true
|
||||
python - <<'PY'
|
||||
import os, sys, xml.etree.ElementTree as ET
|
||||
root = ET.parse(os.path.join(os.environ["RUNNER_TEMP"], "sandbox-e2e.xml")).getroot()
|
||||
suite = root if root.tag == "testsuite" else root.find("testsuite")
|
||||
counts = {k: int(suite.get(k, 0)) for k in ("tests", "failures", "errors", "skipped")}
|
||||
print("sandbox e2e:", counts)
|
||||
if counts["tests"] != int(os.environ["SANDBOX_TESTS"]) or counts["failures"] or counts["errors"] or counts["skipped"]:
|
||||
sys.exit("the sandbox e2e must be exactly %s tests, all passed: %s" % (os.environ["SANDBOX_TESTS"], counts))
|
||||
PY
|
||||
- name: What the root step left behind (diagnostic, decides nothing)
|
||||
if: always()
|
||||
run: |
|
||||
@@ -225,15 +182,6 @@ jobs:
|
||||
echo "-- /etc/resolv.conf"; cat /etc/resolv.conf || true
|
||||
echo "-- lo"; ip -4 addr show lo || true
|
||||
|
||||
# The leg ran with the pinned database, and the core never went past it to GitHub (tests/geoip_used.py wrote what it did).
|
||||
- name: The leg ran with the pinned GeoIP database
|
||||
if: always()
|
||||
shell: bash
|
||||
run: |
|
||||
python scripts/ci_lab_geoip.py evidence --out "$(dirname "$GEOIP_USED_OUT")/geoip-evidence.json" > /dev/null
|
||||
python scripts/ci_lab_geoip.py verify --evidence "$(dirname "$GEOIP_USED_OUT")/geoip-evidence.json" --used "$GEOIP_USED_OUT"
|
||||
|
||||
|
||||
# Runs ONLY if the full run above fails, and before 2026-08-13 it could not
|
||||
# exist: the hang was killed by the 40-minute ceiling, so the job came out
|
||||
# `cancelled` and the following steps did not start at all. With
|
||||
@@ -271,111 +219,3 @@ jobs:
|
||||
path: ${{ runner.temp }}/e2e-watchdog.log
|
||||
if-no-files-found: warn
|
||||
retention-days: 14
|
||||
|
||||
# ``Control+A`` selects all in a field, on the PUBLISHED engine and the core this package pins, on Windows, where the keyboard of a real
|
||||
# user is: the shortcut letter used to reach the browser as Control+Shift+A (invisible-core 63.66.0 fixes it). The e2e is red on the
|
||||
# keyboard that held Shift for the capital A (tests/test_control_a_selects_all_in_a_field_e2e.py: 5 ways to press it x an <input> and a
|
||||
# <textarea>, in-process and served to the stock Playwright client). Same gate as the Linux job: it is SKIPPED, with the reason in the
|
||||
# summary, until the core is on the index, and it runs unchanged after; `workflow_dispatch` with `only: windows-control-a` runs it alone.
|
||||
e2e-windows-control-a:
|
||||
name: e2e (windows, Control+A)
|
||||
needs: core-on-index
|
||||
if: needs.core-on-index.outputs.available == 'true'
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 20
|
||||
# `run:` blocks are PowerShell on Windows unless said otherwise (e2e-hunt.yml had a ParserError on its first launch there).
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
with: { fetch-depth: 1 }
|
||||
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
|
||||
with: { python-version: '3.11' }
|
||||
- name: Install wrapper + test deps (the stock client is in the dev extra)
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
python -m pip install ".[dev]"
|
||||
- name: Fetch the published firefox binary
|
||||
run: echo "FF=$(python -m invisible_playwright fetch | tail -1)" >> "$GITHUB_ENV"
|
||||
- name: The keyboard shortcut selects all (the browser opens on the runner's desktop, as in e2e-hunt.yml)
|
||||
env:
|
||||
PYTHONUNBUFFERED: "1"
|
||||
run: INVPW_BINARY_PATH="$FF" python -u -m pytest -m e2e -p no:cacheprovider -v tests/test_control_a_selects_all_in_a_field_e2e.py
|
||||
|
||||
# THE SAME e2e ON WINDOWS (Federico, 12/11: every test of the product runs on Linux AND Windows; where Windows behaves
|
||||
# differently the test adapts to the system). Before this, 562 of the 808 e2e had never run on Windows in any round. The census
|
||||
# of 12/11 (run 43307193708) took ~50 minutes in one job, so the files are split in four parts (the sorted list, every fourth
|
||||
# file: a split that does not move when a file is added elsewhere). Left out, by name, are the suites ci/required-suites.json
|
||||
# declares `linux_only` (the reason is on the row); tests/test_every_suite_runs_on_linux_and_windows.py holds both together.
|
||||
e2e-windows:
|
||||
name: e2e (windows, part ${{ matrix.part }})
|
||||
needs: core-on-index
|
||||
if: needs.core-on-index.outputs.available == 'true' && inputs.only != 'windows-control-a'
|
||||
runs-on: windows-2022
|
||||
timeout-minutes: 40
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
part: [1, 2, 3, 4]
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
with: { fetch-depth: 1 }
|
||||
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
|
||||
with: { python-version: '3.11' }
|
||||
- name: Install wrapper + test deps (+ Playwright ONLY as a system tool)
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
python -m pip install ".[dev]"
|
||||
python -m pip install "playwright==$(cat scripts/playwright_pin.txt)"
|
||||
- name: Fetch the published firefox binary
|
||||
run: echo "FF=$(cd "$RUNNER_TEMP" && python -m invisible_playwright fetch | tail -1)" >> "$GITHUB_ENV"
|
||||
# The GeoIP database made by the repository, as on the Linux run (no download, the same bytes every run).
|
||||
- name: The GeoIP database (made by the repository, same bytes every run)
|
||||
run: python scripts/ci_lab_geoip.py build
|
||||
- name: The files of this part, without the linux_only suites
|
||||
run: |
|
||||
set -e
|
||||
python -m pytest --collect-only -q -m e2e -o addopts= -p no:cacheprovider 2>/dev/null | grep "::" | cut -d: -f1 | sort -u > "$RUNNER_TEMP/e2e_files.txt"
|
||||
python - "${{ matrix.part }}" "$RUNNER_TEMP" <<'PY'
|
||||
import json, os, sys
|
||||
part, tmp = int(sys.argv[1]), sys.argv[2]
|
||||
rows = json.load(open("ci/required-suites.json", encoding="utf-8"))
|
||||
left_out = [t for r in rows if r.get("linux_only") for t in r["tests"]]
|
||||
files = [l.strip() for l in open(os.path.join(tmp, "e2e_files.txt")) if l.strip()]
|
||||
files = [f for f in files if f not in left_out]
|
||||
mine = [f for i, f in enumerate(files) if i % 4 == part - 1]
|
||||
nodes = [t for t in left_out if "::" in t and t.split("::")[0] in mine]
|
||||
open(os.path.join(tmp, "e2e_args.txt"), "w").write("\n".join(mine + ["--deselect=" + n for n in nodes]) + "\n")
|
||||
print("%d e2e files, %d left out as linux_only, %d in part %d, %d node(s) deselected"
|
||||
% (len(files) + len([t for t in left_out if "::" not in t]), len(left_out), len(mine), part, len(nodes)))
|
||||
PY
|
||||
- name: Run this part of the e2e
|
||||
env:
|
||||
PYTHONUNBUFFERED: "1"
|
||||
INVPW_TEST_WATCHDOG_FILE: ${{ runner.temp }}/e2e-watchdog.log
|
||||
run: |
|
||||
mapfile -t ARGS < <(tr -d '\r' < "$RUNNER_TEMP/e2e_args.txt")
|
||||
python -u scripts/run_e2e.py "$FF" "${ARGS[@]}"
|
||||
- name: The leg ran with the pinned GeoIP database
|
||||
if: always()
|
||||
run: |
|
||||
python scripts/ci_lab_geoip.py evidence --out "$(dirname "$GEOIP_USED_OUT")/geoip-evidence.json" > /dev/null
|
||||
python scripts/ci_lab_geoip.py verify --evidence "$(dirname "$GEOIP_USED_OUT")/geoip-evidence.json" --used "$GEOIP_USED_OUT"
|
||||
- name: Close every Firefox left
|
||||
if: always()
|
||||
shell: pwsh
|
||||
run: |
|
||||
Get-Process firefox -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue
|
||||
"left: " + @(Get-Process firefox -ErrorAction SilentlyContinue).Count
|
||||
- name: Upload the hang evidence
|
||||
if: always()
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
with:
|
||||
name: e2e-watchdog-windows-${{ matrix.part }}-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
path: ${{ runner.temp }}/e2e-watchdog.log
|
||||
if-no-files-found: warn
|
||||
retention-days: 14
|
||||
@@ -1,177 +0,0 @@
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# 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
|
||||
@@ -1,175 +0,0 @@
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# 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
|
||||
@@ -1,213 +0,0 @@
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# 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
|
||||
@@ -196,27 +196,8 @@ jobs:
|
||||
# code no job has run.
|
||||
run: python -m pytest -q
|
||||
|
||||
# The three checks on the REAL GeoIP database, and only here (the release): the legs of the pull requests and of the gates launch with the database that
|
||||
# scripts/ci_lab_geoip.py makes (a few networks, the same bytes every run, no download), so what only the real one can show is looked at once per release:
|
||||
# the product's own road (no variable, cold cache, the latest database downloaded), the lab database against it for the six exits, and every
|
||||
# time_zone of the database known to the runner's tz database. See the docstring of scripts/ci_real_geoip_check.py.
|
||||
real-geoip-database:
|
||||
needs: already-published
|
||||
if: needs.already-published.outputs.present != 'yes'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.12"
|
||||
- name: Install the wrapper (its core comes from the index)
|
||||
run: python -m pip install -e . maxminddb
|
||||
- name: The real GeoIP database - the product's road, the lab database against it, every zone known
|
||||
run: python scripts/ci_real_geoip_check.py
|
||||
|
||||
upload:
|
||||
needs: [already-published, gate, real-geoip-database]
|
||||
needs: [already-published, gate]
|
||||
if: needs.already-published.outputs.present != 'yes'
|
||||
runs-on: ubuntu-latest
|
||||
environment: pypi # the trust relationship lives HERE, behind the gate
|
||||
|
||||
@@ -1,224 +0,0 @@
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# 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
|
||||
@@ -0,0 +1,78 @@
|
||||
# study-processes-hunt.yml - hunt scaffolding, never merged. Runs only on a push to a `hunt/study-processes**` branch.
|
||||
#
|
||||
# The studies of row 6 of the night plan (13/11) and the Windows sandbox twin: the retail Firefox 159.0 (from archive.mozilla.org)
|
||||
# and this browser (the published engine through the package) on the same local page, one after the other, on Windows and on Linux:
|
||||
# the memory of every process by kind, the sandbox of every process (Windows token, Linux seccomp), the names each resolved
|
||||
# (MOZ_LOG nsHostResolver) and the files of the profile's datareporting/. scripts/study_processes.py; the numbers go to the study
|
||||
# repository with their run.
|
||||
name: study processes hunt
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ['hunt/study-processes**']
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: study-processes-hunt-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
|
||||
jobs:
|
||||
study:
|
||||
name: study (${{ matrix.os }})
|
||||
runs-on: ${{ matrix.os }}
|
||||
timeout-minutes: 30
|
||||
strategy:
|
||||
fail-fast: false
|
||||
max-parallel: 2
|
||||
matrix:
|
||||
os: [windows-2022, ubuntu-24.04]
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
|
||||
with: { python-version: '3.11' }
|
||||
- name: Install the wrapper, the published engine, the retail Firefox 159.0
|
||||
run: |
|
||||
set -e
|
||||
python -m pip install --quiet --upgrade pip
|
||||
python -m pip install --quiet ".[dev]" psutil
|
||||
echo "OURS=$(cd "$RUNNER_TEMP" && python -m invisible_playwright fetch | tail -1)" >> "$GITHUB_ENV"
|
||||
if [ "$RUNNER_OS" = "Windows" ]; then
|
||||
curl -sSL -o "$RUNNER_TEMP/setup.exe" "https://archive.mozilla.org/pub/firefox/releases/159.0/win64/en-US/Firefox%20Setup%20159.0.exe"
|
||||
"$RUNNER_TEMP/setup.exe" /S "/InstallDirectoryPath=C:\retail159"
|
||||
for i in $(seq 1 60); do [ -f /c/retail159/firefox.exe ] && break; sleep 2; done
|
||||
echo "RETAIL=C:\retail159\firefox.exe" >> "$GITHUB_ENV"
|
||||
else
|
||||
sudo apt-get update -qq && sudo apt-get install -y -qq xvfb >/dev/null
|
||||
python -m pip install --quiet "playwright==$(cat scripts/playwright_pin.txt)" && sudo "$(which python)" -m playwright install-deps firefox >/dev/null
|
||||
curl -sSL "https://archive.mozilla.org/pub/firefox/releases/159.0/linux-x86_64/en-US/firefox-159.0.tar.xz" | tar -xJ -C "$RUNNER_TEMP"
|
||||
echo "RETAIL=$RUNNER_TEMP/firefox/firefox" >> "$GITHUB_ENV"
|
||||
fi
|
||||
sha256sum "$RUNNER_TEMP"/setup.exe 2>/dev/null || true
|
||||
- name: The study
|
||||
env:
|
||||
PYTHONUNBUFFERED: "1"
|
||||
run: |
|
||||
if [ "$RUNNER_OS" = "Linux" ]; then PRE="xvfb-run -a"; else PRE=""; fi
|
||||
$PRE python scripts/study_processes.py --retail "$RETAIL" --ours "$OURS" --out evidence --seconds 30 | tee -a "$GITHUB_STEP_SUMMARY"
|
||||
- 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 evidence
|
||||
if: always()
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
with:
|
||||
name: study-processes-${{ matrix.os }}-${{ github.run_id }}
|
||||
path: evidence
|
||||
if-no-files-found: warn
|
||||
retention-days: 30
|
||||
@@ -173,15 +173,15 @@ jobs:
|
||||
# untested until 2026-08-01, and the user who opened issue #51 was on
|
||||
# 3.14. test_marker_vocabulary.py compares this list to the floor.
|
||||
python: ["3.11", "3.12", "3.13", "3.14"]
|
||||
# The FULL Python range on ubuntu; Windows on the two ends of the range,
|
||||
# 3.11 and 3.14 (Federico, 12/11: every test on Linux AND Windows; the
|
||||
# ends are where a version-specific difference shows first). The runners
|
||||
# are free for this public repository; the account runs 20 jobs at once.
|
||||
# The python LIST above stays complete so test_marker_vocabulary still
|
||||
# sees every version.
|
||||
# Windows runners are the scarce, 2x-cost, slow-to-schedule ones, and a
|
||||
# burst of pushes queues them for a long time. Run the FULL Python range
|
||||
# on ubuntu (cheap, fast) and cover Windows on 3.12 only - this is a
|
||||
# pure-Python package, the OS-specific surface is tiny. The python LIST
|
||||
# above stays complete so test_marker_vocabulary still sees every version.
|
||||
exclude:
|
||||
- { os: windows-latest, python: "3.12" }
|
||||
- { os: windows-latest, python: "3.11" }
|
||||
- { os: windows-latest, python: "3.13" }
|
||||
- { os: windows-latest, python: "3.14" }
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
@@ -222,27 +222,12 @@ jobs:
|
||||
run: |
|
||||
python -m ruff check --select F821,F811,F601 --no-cache --output-format concise .
|
||||
|
||||
# The GeoIP database is made by the repository (scripts/ci_lab_geoip.py: the same bytes on every run, the sha256 in ci/geoip.json), never a
|
||||
# site and never a licensed file: without STEALTHFOX_GEOIP_MMDB the core asks GitHub which database is the latest on every call
|
||||
# (run 43211837926). The variable reaches every later step of the job.
|
||||
- name: The GeoIP database (made by the repository, same bytes every run)
|
||||
shell: bash
|
||||
run: python scripts/ci_lab_geoip.py build
|
||||
|
||||
- name: Run pytest
|
||||
shell: bash
|
||||
run: |
|
||||
set -o pipefail # or tee would swallow pytest's exit code
|
||||
pytest tests/ -v --tb=short -rs | tee tests-report.txt
|
||||
|
||||
# The leg ran with the pinned database, and the core never went past it to GitHub (tests/geoip_used.py wrote what it did).
|
||||
- name: The leg ran with the pinned GeoIP database
|
||||
if: always()
|
||||
shell: bash
|
||||
run: |
|
||||
python scripts/ci_lab_geoip.py evidence --out "$(dirname "$GEOIP_USED_OUT")/geoip-evidence.json" > /dev/null
|
||||
python scripts/ci_lab_geoip.py verify --evidence "$(dirname "$GEOIP_USED_OUT")/geoip-evidence.json" --used "$GEOIP_USED_OUT"
|
||||
|
||||
# This repo has the largest suite of the three and was the only one with
|
||||
# no floor. pytest's exit code cannot distinguish "everything passed"
|
||||
# from "the marker expression deselected everything", and `addopts`
|
||||
|
||||
@@ -94,12 +94,12 @@ jobs:
|
||||
- uses: actions/setup-python@v5
|
||||
with: { python-version: '3.11' }
|
||||
|
||||
# Only what the TEST needs (and `uv`, for the wait below to ask uv, which the release test installs the package with). The package under test is installed by the
|
||||
# Only what the TEST needs. The package under test is installed by the
|
||||
# test itself, into a venv it creates, from the index - installing it
|
||||
# here as well would put a second copy on the path and the assertions
|
||||
# would be reading the wrong one.
|
||||
- name: Test harness only
|
||||
run: python -m pip install --upgrade pip pytest packaging uv
|
||||
run: python -m pip install --upgrade pip pytest packaging
|
||||
|
||||
# PyPI does not serve a new version to pip the instant twine finishes, and
|
||||
# this workflow runs on the ledger pull request, which the publish run
|
||||
@@ -115,11 +115,9 @@ jobs:
|
||||
# started later, was green). Those are three different pages of the index, and
|
||||
# the job only needs the one pip installs from.
|
||||
#
|
||||
# So the question asked here is the INSTALLERS' own, both: the upgrade test installs with pip, the release test with uv (the README's
|
||||
# way in), so each round asks `pip download invisible-playwright==X` AND `uv pip compile` of it (no cache, nothing installed), and the
|
||||
# job goes on only after three rounds in a row in which both said yes, 15 s apart (one yes proves that one request saw the version, not
|
||||
# that the next is served by the same node of the index); a no restarts the count and a call that does not answer in two minutes is
|
||||
# a no. Bounded at ten minutes: a forgotten publish still fails, and it fails HERE, saying that the index does not have the
|
||||
# So the question asked here is pip's own: `pip download invisible-playwright==X`,
|
||||
# the same client, the same index, no cache. Bounded at ten minutes: a forgotten
|
||||
# publish still fails, and it fails HERE, saying that the index does not have the
|
||||
# version, instead of three steps later as a test that compares two versions.
|
||||
#
|
||||
# Only on the ledger pull request. A scheduled or dispatched run is not
|
||||
@@ -136,40 +134,21 @@ jobs:
|
||||
deadline = time.monotonic() + 600
|
||||
deadline = min(deadline, time.monotonic() + float(os.environ.get("INDEX_WAIT_SECONDS", "600")))
|
||||
poll = float(os.environ.get("INDEX_WAIT_POLL", "15"))
|
||||
need = int(os.environ.get("INDEX_WAIT_CONFIRMATIONS", "3"))
|
||||
call_limit = float(os.environ.get("INDEX_WAIT_CALL_SECONDS", "120"))
|
||||
asks = [
|
||||
("pip", [sys.executable, "-m", "pip", "download", "--no-deps", "--no-cache-dir", "--disable-pip-version-check", "--quiet",
|
||||
"-d", tempfile.mkdtemp(), f"{dist}=={version}"], None),
|
||||
("uv", [sys.executable, "-m", "uv", "pip", "compile", "-", "--no-deps", "--no-cache", "--quiet"], f"{dist}=={version}\n"),
|
||||
]
|
||||
|
||||
|
||||
def round_says():
|
||||
"""An empty string when every installer resolves the version, else what the first that did not said."""
|
||||
for tool, command, stdin in asks:
|
||||
try:
|
||||
r = subprocess.run(command, input=stdin, capture_output=True, text=True, timeout=call_limit)
|
||||
except subprocess.TimeoutExpired:
|
||||
return f"{tool} did not answer within {call_limit:.0f} s"
|
||||
if r.returncode != 0:
|
||||
return f"{tool} said: " + ((r.stderr.strip().splitlines() or [""])[-1])
|
||||
return ""
|
||||
|
||||
|
||||
n = streak = 0
|
||||
n = 0
|
||||
said = ""
|
||||
while True:
|
||||
n += 1
|
||||
said = round_says()
|
||||
streak = 0 if said else streak + 1
|
||||
if streak >= need:
|
||||
print(f"::notice::pip and uv resolve {dist} {version} from the index, {need} rounds in a row (attempt {n})")
|
||||
r = subprocess.run([sys.executable, "-m", "pip", "download", "--no-deps", "--no-cache-dir",
|
||||
"--disable-pip-version-check", "--quiet", "-d", tempfile.mkdtemp(),
|
||||
f"{dist}=={version}"], capture_output=True, text=True)
|
||||
if r.returncode == 0:
|
||||
print(f"::notice::pip downloads {dist} {version} from the index (attempt {n})")
|
||||
sys.exit(0)
|
||||
said = (r.stderr.strip().splitlines() or [""])[-1]
|
||||
if time.monotonic() >= deadline:
|
||||
minutes = int(float(os.environ.get("INDEX_WAIT_SECONDS", "600")) // 60) or 1
|
||||
print(f"::error::the index does not have {dist} {version} yet, after {minutes} minutes "
|
||||
f"and {n} attempts, {streak} of {need} rounds in a row ({said})")
|
||||
f"and {n} attempts (pip said: {said})")
|
||||
sys.exit(1)
|
||||
time.sleep(poll)
|
||||
PY
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
name: webrtc-e2e
|
||||
|
||||
# Live WebRTC realness check against the shipped patched binary.
|
||||
#
|
||||
# Manual (workflow_dispatch) on purpose: it needs a firefox-N binary that
|
||||
# carries the WebRTC fixes (synthetic srflx in genuine nICEr form + the
|
||||
# default-route fallback behind a proxy). Run it after publishing such a
|
||||
# binary - it is the release gate for "WebRTC looks real behind a proxy".
|
||||
# On this Linux runner an engine older than firefox-35 never gets the synthetic
|
||||
# srflx behind a SOCKS proxy (the wildcard default-route probe, fixed in
|
||||
# firefox-35): test_not_blocked_behind_tcp_only_socks skips on it, naming that
|
||||
# defect, and the floor below turns the skip red. From firefox-35 on, a
|
||||
# missing srflx fails the test itself.
|
||||
#
|
||||
# No external proxy provider, no credentials: the "behind a proxy" condition is faked by an
|
||||
# in-process TCP-only SOCKS5 server (refuses UDP ASSOCIATE) and the egress IP
|
||||
# is injected as an RFC 5737 TEST-NET address. Fully self-contained.
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
# Engine and GeoIP downloads go through the release API with this token.
|
||||
# Anonymous requests share a 60-an-hour limit per runner address and are the
|
||||
# ones GitHub drops first when it is degraded (2026-11-08: timeouts for
|
||||
# unauthenticated users failed the gates three times). user-install.yml stays
|
||||
# anonymous on purpose: it is the user's path.
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
|
||||
jobs:
|
||||
# `pip install -e ".[dev]"` below resolves `invisible-core==N.M.0` from the
|
||||
# package index, and the core is published BEFORE this package. This gate
|
||||
# answers whether it is there yet; during that window the realness job is
|
||||
# SKIPPED with the reason in the run summary rather than faked green, and
|
||||
# once the core is up it runs unchanged. See
|
||||
# .github/workflows/core-on-index.yml.
|
||||
core-on-index:
|
||||
uses: ./.github/workflows/core-on-index.yml
|
||||
|
||||
webrtc-e2e:
|
||||
name: webrtc realness (ubuntu, py3.12)
|
||||
needs: core-on-index
|
||||
if: needs.core-on-index.outputs.available == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Python 3.12
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.12"
|
||||
cache: pip
|
||||
|
||||
- name: Install package + dev extras
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install -e ".[dev]"
|
||||
|
||||
- name: Fetch the patched Firefox binary and expose its path
|
||||
shell: bash
|
||||
run: |
|
||||
# NOT `echo "VAR=$(cmd)" >> $GITHUB_ENV`. echo exits 0 whatever the
|
||||
# substitution did, so `set -e` never sees a failure and an EMPTY
|
||||
# value lands in the environment. Both tests below then hit
|
||||
# `pytest.skip("no patched binary")`, pytest exits 0, and the job is
|
||||
# green having verified nothing - which is exactly what run #1 did.
|
||||
set -euo pipefail
|
||||
FETCH_OUTPUT="$(python -m invisible_playwright fetch)"
|
||||
printf '%s\n' "$FETCH_OUTPUT"
|
||||
BIN="$(printf '%s\n' "$FETCH_OUTPUT" | tail -n 1)"
|
||||
if [ -z "$BIN" ] || [ ! -e "$BIN" ]; then
|
||||
echo "invisible_playwright fetch returned '$BIN', which is not a" >&2
|
||||
echo "file. Refusing to run a suite that would skip itself green." >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "STEALTHFOX_E2E_BINARY=$BIN" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Run WebRTC realness e2e (xvfb for the headless Firefox)
|
||||
run: |
|
||||
set -o pipefail
|
||||
sudo apt-get update && sudo apt-get install -y xvfb
|
||||
xvfb-run -a pytest tests/test_webrtc_realness.py -m e2e -o addopts="" -v -rs | tee webrtc-report.txt
|
||||
|
||||
# Run #1 was GREEN with the headline assertion skipped: "1 passed, 1
|
||||
# skipped", and the skipped one is the test this workflow's own header
|
||||
# calls the point of the gate. pytest's exit code cannot tell that from a
|
||||
# pass, and this file was the only one of four without a floor.
|
||||
- name: Refuse a run whose main assertion did not execute
|
||||
shell: bash
|
||||
run: |
|
||||
python - <<'PY'
|
||||
import pathlib, re, sys
|
||||
text = pathlib.Path("webrtc-report.txt").read_text(encoding="utf-8", errors="ignore")
|
||||
passed = int((re.search(r"(\d+) passed", text) or [0, 0])[1] or 0)
|
||||
skipped = int((re.search(r"(\d+) skipped", text) or [0, 0])[1] or 0)
|
||||
if skipped:
|
||||
print("these tests SKIPPED, so the gate verified less than it "
|
||||
"claims:", file=sys.stderr)
|
||||
for line in text.splitlines():
|
||||
if line.startswith("SKIPPED"):
|
||||
print(" " + line, file=sys.stderr)
|
||||
if passed < 2 or skipped:
|
||||
print(f"{passed} passed / {skipped} skipped - this gate exists for "
|
||||
f"the synthetic-srflx assertion; a run that skips it is not "
|
||||
f"a pass.", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
print(f"{passed} tests ran, none skipped")
|
||||
PY
|
||||
+11
-58
@@ -6,69 +6,11 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.52.0] - 2026-11-14
|
||||
|
||||
### Changed
|
||||
- Pins invisible-core 64.71.0 and with it the engine firefox-64. A request a page causes now leaves in the context of that
|
||||
page, by that context's proxy and resolver: the name of a TURN server over TCP, the OCSP request of a certificate, the TLS
|
||||
over a tunnel, the Safe Browsing completion of a page load. Nothing of a context with a proxy goes out DIRECT when a proxy
|
||||
lookup fails or the context has just closed. On Linux the profile lock no longer looks up the machine's host name.
|
||||
- Typing: each key is sent at its planned time measured from the start of the action, so a late reply no longer shifts the
|
||||
keys after it, and the engine delivers each key at once with its event born the declared latency in the past. Measured
|
||||
against stock Playwright Firefox, 20 runs per cell, slip of the last key against the plan (median): Windows 635 ms before,
|
||||
6 ms now (stock 122); Linux 554 ms before, -5 ms now (stock 91).
|
||||
|
||||
### Fixed
|
||||
- Screencast: a frame that arrives while the start of the screencast is being answered is held and acknowledged,
|
||||
not dropped, so the stream no longer dies from its first frame (the engine keeps one frame in flight and waits for its
|
||||
acknowledgement).
|
||||
- No thread is started on the engine connection's reader any more (the adoption of a new page and the file chooser hand
|
||||
their work to one long-lived starter). On Windows under load a Thread.start there held every event behind it; without
|
||||
instrumentation, goto(..., wait_until="networkidle") on pages that replace themselves missed 1 in 1200 instead of 4.
|
||||
|
||||
### Tests
|
||||
- The suites "nothing of a context leaves but through its proxy" (a witness of every direct arrival, the engine's resolver
|
||||
log as the sink of native lookups), on Linux and Windows, including two contexts with their own proxies at once and a
|
||||
PeerConnection of a torn-down window.
|
||||
- Windows: the isolated-page test moves the page when the test says so instead of on a 500 ms timer; the sandbox test
|
||||
reads again a process that is still starting.
|
||||
|
||||
|
||||
## [0.51.1] - 2026-11-13
|
||||
|
||||
### Changed
|
||||
- Pins invisible-core 63.68.0 (core fixes on the same firefox-63 engine: two sessions starting together on Windows no longer fail on the shared font-manifest cache; no MOZ_*, GL or toolkit variable of the host reaches the engine; GitHub is asked for the latest GeoIP database once a day, not on every launch; mouse moves carry the pressed buttons; a CORS preflight does not count for networkidle).
|
||||
- The project moved to the oss-invisible GitHub organization: every GitHub link, the issue templates and the package URLs point to github.com/oss-invisible/playwright. The PyPI name and the import name do not change; the old addresses redirect.
|
||||
|
||||
### Fixed
|
||||
- A popup (a `window.open` or a `target=_blank` link) could be handed to the client at `about:blank`, with the blank page's `load`, when it
|
||||
was opened with no route on the context: the commit of its address, or its `DOMContentLoaded` and `load`, arrived while the page was being
|
||||
handed from its buffer to its dispatcher and was told to nobody (`page.url` stayed `about:blank`, or `wait_for_load_state("load")` timed
|
||||
out). Measured on Windows with the library's client in the same process, `test_popups_reach_the_client_e2e.py` x20 on 4 workers: 3 runs
|
||||
red with the published firefox-62 engine and 11 with firefox-63. The page is now handed over in one step: what the client was not told is
|
||||
said once, in order, and nothing the engine sent in that period is lost.
|
||||
- The same hand-over dropped every event that is not a request: a `console` message, a `pageError`, a `dialog` (an `alert()` that opened
|
||||
while the popup was being built blocked its page for good, because no client had been told of it and none could answer it), a `crash`, a file chooser. All
|
||||
of them are given back now, in the order they arrived. The only bound left is the memory of the buffer (512 events): an event beyond it is
|
||||
lost and a `RuntimeWarning` says how many, once per page.
|
||||
- The hand-over holds when the engine's reader, the adoption and a close run at the same time: a `load` is told to the client once (not twice,
|
||||
so `page.on("load")` runs once); an event the engine sends while the held ones are being given back waits for them (a response is never handled
|
||||
before its request); a document committed at the same address as the previous one is told; a page closed while it was being adopted is not given
|
||||
frames, and is not announced, after its `__dispose__`; one frame never gets two dispatchers.
|
||||
- A popup could still be handed to the client at `about:blank` (or with its navigation pending again, and "Execution context was destroyed" in its
|
||||
first evaluate) when the destination committed while the events the page had missed were being replayed to it: the engine's reader went on
|
||||
delivering the live events to the lifecycle, and the replay then brought older ones after them. The page now subscribes its readers and is
|
||||
handed the missed events in one step, with the delivery of the sessions' events held, so a live event never overtakes the replay.
|
||||
With the three corrections together, on Windows with the library's client in the same process, under load: 680/680 and 256/256 popup cases
|
||||
green (run 43261858525).
|
||||
- `Control+A` selects all in an `<input>` and a `<textarea>` on Windows, on the published engine and the core this package pins: a new end-to-end
|
||||
test (five ways to press the shortcut, in-process and served to the stock client), run by `e2e.yml` on Windows, 20/20 green (run 43262320744).
|
||||
- Tests only: the e2e tests of the test servers take their ports from one sequence (no two servers draw the same one); the two tests that read a
|
||||
consecutive pair of host ports run alone, after the parallel tests; the sandbox e2e (the browser's seccomp filter) runs in a step of its own that
|
||||
turns unprivileged user namespaces on, and is left out of the normal run; every leg launches with a GeoIP database the repository builds (same
|
||||
bytes every run, no download); the CodeQL alerts of the test code are fixed; the install job waits for the package index through both installers;
|
||||
the raw Juggler tests wait for `Page.ready` and the main frame instead of a fixed time.
|
||||
|
||||
## [0.51.0] - 2026-11-12
|
||||
|
||||
### Changed
|
||||
@@ -120,6 +62,17 @@ comparison run is saved). The result of a `window.open` (`null` or a window) is
|
||||
`extra_prefs={"dom.disable_open_during_load": False}` for the session, knowing that a page then sees a browser that differs from a
|
||||
retail Firefox.
|
||||
|
||||
### Known issues
|
||||
- **A popup opened without a route can be announced while it is still on `about:blank`.** A popup opened with no route on the context
|
||||
(a `target=_blank` link, or `window.open` from a click) can be announced to the client while it is still on `about:blank`; its `url`
|
||||
then stays `about:blank`, or its `load` never arrives. Seen on a Windows runner with the library's client in the same process and four
|
||||
workers running the popup tests in parallel (`test_popups_reach_the_client_e2e.py`, 20 runs): with the firefox-63 engine 17 cases of 640
|
||||
in 12 of 20 runs; with the published firefox-62 engine (so also with 0.50.1) 15 cases of 640. Both causes found are in the wrapper: the hand-over of
|
||||
a new page to the client, and the replay of a new page's events while live ones are being delivered. The correction of the first alone,
|
||||
not in this release, lowers the red cases over 20 runs from 15 to 2 with engine 62 and from 17 to 13 with engine 63; the correction of the
|
||||
second is under test. On Linux no run was red (0 of 20). Not measured: a served
|
||||
launch with numbers of its own, other machines, a run without parallel workers, macOS.
|
||||
|
||||
## [0.50.1] - 2026-11-12
|
||||
|
||||
0.50.0 was tagged and never published: its end-to-end gate was red on two tests that counted processes.
|
||||
|
||||
-1191
File diff suppressed because it is too large.
Load diff
@@ -1,7 +0,0 @@
|
||||
{
|
||||
"comment": "The GeoIP database every CI leg launches with (STEALTHFOX_GEOIP_MMDB): made by scripts/ci_lab_geoip.py, the same bytes on every run, no download and no licensed data. One record answers every public address that is not one of the lab's networks and not reserved (the runner's own egress address is not known in advance). To change it (a network, a field): change the table of the script and mmdb_sha256 here in one commit; `build` refuses to go on when they differ.",
|
||||
"generator": "scripts/ci_lab_geoip.py",
|
||||
"mmdb": "geoip-aio-all.mmdb",
|
||||
"mmdb_sha256": "d02825fd0336afa72ad7b7573769f1d9efddea447133f99ae3008c56d5308929",
|
||||
"mmdb_bytes": 2706
|
||||
}
|
||||
@@ -1,13 +1,11 @@
|
||||
[
|
||||
{"id": "wrapper.e2e.udp", "giro": "G2", "os": ["linux", "windows"], "min_tests": 43, "exact": true, "tests": ["tests/test_preload_newtab_turns_the_privileged_about_process_off_e2e.py", "tests/test_the_association_is_ready_when_the_peerconnection_is_born_e2e.py", "tests/test_turn_over_tcp_is_tried_for_real_e2e.py", "tests/test_webrtc_realness.py::test_the_gather_is_real_without_a_proxy", "tests/test_the_whole_udp_chain_by_name_e2e.py::test_a_turn_srflx_by_name_arrives_through_the_relay_when_the_exit_of_the_lab_is_loopback", "tests/test_declared_host_network_e2e.py", "tests/test_a_page_over_ipv6_gathers_on_a_machine_declared_without_it_e2e.py", "tests/test_webrtc_realness.py::test_a_gateway_with_coherent_udp_gives_the_page_a_srflx_born_through_its_relay", "tests/test_webrtc_realness.py::test_a_host_with_ipv6_addresses_gathers_through_an_ipv4_relay", "tests/test_webrtc_realness.py::test_a_gateway_that_is_far_away_still_gives_the_page_a_srflx_born_through_its_relay", "tests/test_webrtc_realness.py::test_the_first_candidate_of_a_gather_does_not_wait_for_a_gateway_that_is_far_away", "tests/test_webrtc_realness.py::test_a_gather_after_the_page_loaded_through_the_gateway_costs_only_the_road_to_the_server", "tests/test_webrtc_realness.py::test_two_contexts_with_two_proxies_each_gets_the_srflx_of_its_own", "tests/test_webrtc_realness.py::test_the_turn_over_tcp_of_a_context_goes_through_the_proxy_of_that_context", "tests/test_webrtc_realness.py::test_a_proxy_that_does_not_relay_udp_gives_no_srflx_at_all", "tests/test_webrtc_realness.py::test_a_proxy_whose_udp_leaves_from_another_address_gives_no_srflx_at_all", "tests/test_webrtc_realness.py::test_a_proxy_whose_relay_never_answers_gives_no_srflx_at_all"], "marker": "e2e", "needs_root": false, "note": "Needs the candidate binary (STEALTHFOX_E2E_BINARY) and the engine that carries the UDP line. 57 = 1+7+6+1+21 from the five files + 21 from the 10 UDP-line tests of test_webrtc_realness.py (parametrized). The chain by name is here in its variant with the lab's exit on loopback (127.0.0.2) and the pref `media.peerconnection.ice.loopback`, on Linux and Windows: the exit of the lab is loopback, and a loopback mapped address is thrown away by nICEr unless the ICE context allows it. The variant without the pref (an exit that is not loopback) is the suite wrapper.e2e.udp.exit, Linux only; the address added to the interface of the Windows runner is work of the release after firefox-63. The preload_newtab test (2) is here: seen green on Linux as root (Docker) and on Windows 10 runs of 10 (windows-2022, round 5 engine); it reads the engine's own process log."},
|
||||
{"id": "wrapper.e2e.udp.exit", "giro": "G2", "os": ["linux"], "min_tests": 7, "exact": true, "tests": ["tests/test_the_whole_udp_chain_by_name_e2e.py::test_a_turn_srflx_by_name_arrives_through_the_relay_before_the_tick", "tests/test_a_proxy_that_cannot_carry_udp_leaks_nothing_direct_e2e.py"], "marker": "e2e", "needs_root": ["linux"], "note": "Linux only, and not collected on Windows: the exit of the lab is a documentation address (198.51.100.9) added to lo with `ip addr add`, which needs root and iproute2; a mapped address in 127/8 would be thrown away by nICEr as bogus (stun_client_ctx.cpp nr_stun_transport_addr_check) and the pref that allows it is off in a product. The page reads a srflx equal to the gateway exit and the relay of the TURN server, the TURN name resolved by the DoH through the proxy, in the tick of 2 s. On the Windows runner of GitHub (administrator, the network of the runner) it could run too: not yet. A skipped test would turn the verdict red, hence a suite of its own. Its twin with the lab's exit on loopback and the pref stays in wrapper.e2e.udp on both systems, so that Windows keeps the walk of the chain by name.", "linux_only": "The lab's exit is a documentation address the host must hold besides its loopback (nICEr throws away a mapped address in 127/8). Linux holds it on lo as root; Windows takes no extra address on its loopback pseudo-interface, and adding it to the runner's adapter took the runner off the network (runs 43314251547 and 43334169682 died in the test step). A Windows twin waits for a way that leaves the runner's network alone."},
|
||||
{"id": "wrapper.e2e.udp.sandbox", "giro": "G2", "os": ["linux"], "min_tests": 13, "exact": true, "tests": ["tests/test_the_socket_process_is_sandboxed_e2e.py", "tests/test_webrtc_realness.py::test_the_gather_is_real_without_a_proxy", "tests/test_webrtc_realness.py::test_a_gateway_with_coherent_udp_gives_the_page_a_srflx_born_through_its_relay", "tests/test_ice_names_by_the_context_proxy_e2e.py::test_a_gateway_without_udp_resolves_the_ice_name_then_ends_in_701"], "marker": "e2e", "needs_root": false, "note": "The browser WITH its sandbox, run by a normal user, as on any Linux that allows user namespaces. On the Ubuntu 24.04 runner AppArmor refuses them to a user, so every other non-root suite runs a browser WITHOUT the sandbox of its socket and content processes; the gate turns the restriction off for this leg (sysctl kernel.apparmor_restrict_unprivileged_userns=0) and the first test fails unless the socket and a tab process have a seccomp filter (Seccomp: 2). The three situations of the UDP line: A (a proxy that carries UDP: the srflx born through the relay), B (no proxy: the gather is real), C (a proxy with no UDP: the ICE server name goes by DoH through the proxy and the gather ends in 701). No root and no resolver trap needed.", "linux_only": "It reads the seccomp filter of the socket and tab processes in /proc. The Windows twin reads the sandbox token of the same processes (integrity level, restrictions) and needs a measurement of the retail Firefox's tokens first; until then Linux only."},
|
||||
{"id": "wrapper.e2e.udp.exit", "giro": "G2", "os": ["linux"], "min_tests": 7, "exact": true, "tests": ["tests/test_the_whole_udp_chain_by_name_e2e.py::test_a_turn_srflx_by_name_arrives_through_the_relay_before_the_tick", "tests/test_a_proxy_that_cannot_carry_udp_leaks_nothing_direct_e2e.py"], "marker": "e2e", "needs_root": ["linux"], "note": "Linux only, and not collected on Windows: the exit of the lab is a documentation address (198.51.100.9) added to lo with `ip addr add`, which needs root and iproute2; a mapped address in 127/8 would be thrown away by nICEr as bogus (stun_client_ctx.cpp nr_stun_transport_addr_check) and the pref that allows it is off in a product. The page reads a srflx equal to the gateway exit and the relay of the TURN server, the TURN name resolved by the DoH through the proxy, in the tick of 2 s. On the Windows runner of GitHub (administrator, the network of the runner) it could run too: not yet. A skipped test would turn the verdict red, hence a suite of its own. Its twin with the lab's exit on loopback and the pref stays in wrapper.e2e.udp on both systems, so that Windows keeps the walk of the chain by name."},
|
||||
{"id": "wrapper.e2e.udp.sandbox", "giro": "G2", "os": ["linux"], "min_tests": 13, "exact": true, "tests": ["tests/test_the_socket_process_is_sandboxed_e2e.py", "tests/test_webrtc_realness.py::test_the_gather_is_real_without_a_proxy", "tests/test_webrtc_realness.py::test_a_gateway_with_coherent_udp_gives_the_page_a_srflx_born_through_its_relay", "tests/test_ice_names_by_the_context_proxy_e2e.py::test_a_gateway_without_udp_resolves_the_ice_name_then_ends_in_701"], "marker": "e2e", "needs_root": false, "note": "The browser WITH its sandbox, run by a normal user, as on any Linux that allows user namespaces. On the Ubuntu 24.04 runner AppArmor refuses them to a user, so every other non-root suite runs a browser WITHOUT the sandbox of its socket and content processes; the gate turns the restriction off for this leg (sysctl kernel.apparmor_restrict_unprivileged_userns=0) and the first test fails unless the socket and a tab process have a seccomp filter (Seccomp: 2). The three situations of the UDP line: A (a proxy that carries UDP: the srflx born through the relay), B (no proxy: the gather is real), C (a proxy with no UDP: the ICE server name goes by DoH through the proxy and the gather ends in 701). No root and no resolver trap needed."},
|
||||
{"id": "wrapper.e2e.web", "giro": "G2", "os": ["linux", "windows"], "min_tests": 27, "exact": true, "tests": ["tests/test_networkidle_through_a_served_browser_with_routes_e2e.py", "tests/test_http3_through_the_proxy_e2e.py"], "marker": "e2e", "needs_root": false, "note": "The networkidle e2e with routes and the HTTP/3 e2e, split from wrapper.e2e.udp (about 260 s of 500 on Linux; the whole suite did not fit the 15 minutes of Windows)."},
|
||||
{"id": "wrapper.e2e.doh", "giro": "G2", "os": ["linux", "windows"], "min_tests": 19, "exact": true, "tests": ["tests/test_the_hosts_file_of_the_host_is_never_read_e2e.py", "tests/test_resolver_race_e2e.py", "tests/test_doh_under_stress_e2e.py", "tests/test_context_proxy_only_resolves_by_doh_e2e.py", "tests/test_doh_through_the_proxy_e2e.py", "tests/test_ice_names_by_the_context_proxy_e2e.py"], "marker": "e2e", "needs_root": ["linux"], "note": "Linux needs root: the resolver trap of the file (ResolverTrap) points /etc/resolv.conf at a counting resolver on port 53. Su Windows il resolver trap non gira: l'asserzione sul resolver di sistema è l'unica omessa. Run it without xdist (port 53 is one per host). On the Linux leg the gate exports INVPW_REQUIRE_TRAP=1: a trap that cannot run or bind port 53 is a failure, not a skipped assertion."},
|
||||
{"id": "wrapper.e2e.context.egress", "giro": "G2", "os": ["linux", "windows"], "min_tests": 14, "exact": true, "tests": ["tests/test_nothing_leaves_but_the_proxy_e2e.py", "tests/test_a_turn_name_over_tcp_goes_through_the_proxy_of_the_context_e2e.py"], "marker": "e2e", "needs_root": ["linux"], "note": "Taken from the minimal-engine port (branch tests/minimal-port) unchanged but for the removed engine gate: 12 = 6 kinds of page work (hints, image/fetch/WebSocket/EventSource, WebRTC STUN and TURN-udp by name, geolocation, a service worker with push, a page still loading when its context closes) x 2 schemes (no proxy at launch and a gateway on the context; a launch gateway and a different one on the context), and 2 = the TURN server named over TCP in those two schemes. EXPECTED RED on the published firefox-63: the 2 TURN-by-name cases (the lookup of the TCP socket takes user context 0; fixed by commits ac0214bff4 and 058edd6cc6 of firefox-64). The 12 have not run on any engine yet. Like wrapper.e2e.doh: the Linux leg runs as root for the resolver trap (INVPW_REQUIRE_TRAP=1); on Windows the DoH log and the gateway's CONNECTs are the sink."},
|
||||
{"id": "wrapper.e2e.context.sink", "giro": "G2", "os": ["linux", "windows"], "min_tests": 35, "exact": true, "tests": ["tests/test_nothing_of_a_context_leaves_but_through_its_proxy_e2e.py"], "marker": "e2e", "needs_root": ["linux"], "note": "The behavioural half of the class gate 'nothing of a context leaves but through its proxy', with a witness at an address of this host (no root, no address on lo) and the engine's own resolver log as the native-lookup sink. 35 = 31 + the 4 OCSP cases; the 31 are 19 probes (fetch, WebSocket, stun, turn over UDP, turn and turns over TCP, each by name, by IP and by a .local name, behind SOCKS5 and behind an HTTP proxy where the road differs) + 3 controls (the same probe by IP with no proxy IS heard by the witness) + 1 control of the native sink. + 4 PeerConnections built from a torn-down window (a detached iframe, a closed popup; behind SOCKS5 and behind HTTP; defect B3: EXPECTED RED on firefox-63, green on firefox-64) + 2 controls of them (the same PeerConnection from an attached iframe, green on both). + 2 cases of two contexts alive at once (each with its own proxy and DoH, a TURN server over TCP by a different name in each; behind SOCKS5 EXPECTED RED on firefox-63 like turn_tcp-name-socks5, behind HTTP green on both). EXPECTED RED on firefox-63: turn_tcp-name-socks5, turns_tcp-name-socks5 (user context 0, fixed in firefox-64) and the three .local cases fetch-local-socks5, stun-local-socks5, stun-local-http (audit B4, also red on firefox-64 until decided). The Linux leg runs as root so the resolver trap is a second sink. Windows reads the same engine log (its getaddrinfo lines are in the parent process file under the sandbox: run 43574494194), with the no-proxy native control as its positive control. THE OCSP CASES (4): a TLS page whose leaf, signed by a lab CA the engine trusts (put in the profile by the engine's xpcshell, no ignore_https_errors), names its OCSP responder by a NAME (ocsp-<nonce>.lab.test) and by an IP; a context behind the gateway loads it and the request must go through the gateway, never be looked up natively, in user context 0, or reach the responder (2 cases, EXPECTED RED on firefox-63, green on firefox-64); the same page in a context with no proxy IS asked of the responder (control); a page of an issuer the engine does not trust makes no OCSP request (negative control)."},
|
||||
{"id": "wrapper.e2e.realness", "giro": "G2", "os": ["linux", "windows"], "min_tests": 32, "exact": true, "tests": ["tests/test_realness_behind_a_declared_exit_e2e.py"], "marker": "e2e", "needs_root": ["linux"], "note": "The realness check without a real proxy: six declared exits, the values a page reads, and the roads. Linux runs as root without xdist like the DoH suite (the resolver trap); on Windows the trap does not exist and the assertion on the system resolver is the only one omitted."},
|
||||
{"id": "wrapper.unit.udp", "giro": "G1", "os": ["linux", "windows"], "min_tests": 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.unit.udp", "giro": "G1", "os": ["linux", "windows"], "min_tests": 221, "exact": true, "tests": ["tests/test_a_served_launch_cannot_turn_the_launch_counter_off.py", "tests/test_the_witness_picks_a_port_both_sockets_bind.py", "tests/test_preload_newtab_reaches_the_core_only_when_asked.py", "tests/test_the_resolver_trap_counts_its_own_users.py", "tests/test_the_doh_e2e_launch_on_a_virtual_display.py", "tests/test_the_realness_helpers.py", "tests/test_the_h3_line_helpers.py", "tests/test_the_fake_doh_delays_and_refuses.py", "tests/test_the_host_address_helper.py", "tests/test_the_udp_chain_helper.py", "tests/test_the_fake_doh_answers.py", "tests/test_doh_session_prefs_unit.py", "tests/test_the_leak_watcher_sees_a_direct_connection.py", "tests/test_the_http_proxy_helper_asks_for_credentials.py", "tests/test_every_route_command_is_answered_may_fail.py", "tests/test_the_network_declaration_reaches_the_engine.py", "tests/test_the_resolver_trap_is_required_by_the_gate.py", "tests/test_the_exit_of_a_context_is_discovered_through_its_own_gateway.py", "tests/test_the_witness_hears_a_direct_send.py"], "marker": "unit", "needs_root": false, "note": "92 = 6+32+21+7+8+3+9+6. The leak watcher file defines exactly one of its two resolver-trap tests per host (7 everywhere), so no test is skipped. `exact`: min_tests is raised by hand when a test is added."},
|
||||
{"id": "wrapper.e2e.page", "giro": "G2", "os": ["linux", "windows"], "min_tests": 115, "exact": true, "tests": ["tests/test_a_tiny_download_on_a_served_browser_is_saved_e2e.py", "tests/test_a_page_that_moves_on_e2e.py", "tests/test_a_popup_is_reported_when_the_engine_says_it_is_ready_as_playwright_does_e2e.py", "tests/test_a_popup_of_a_link_reaches_the_client_e2e.py", "tests/test_popup_destinations_e2e.py", "tests/test_popups_reach_the_client_e2e.py", "tests/test_route_superseded_e2e.py"], "marker": "e2e", "needs_root": false, "note": "114 = 100 + the 14 of test_a_page_that_moves_on_e2e.py (a navigation the page overtook with location.replace ends; the engine fix 860ef8a6d9 is proved by it). 100 counted at the collection; was 96 = 10+32+16+34+4 before the popup tests of 6200bc2). A page is handed over when the engine says Page.ready; a popup reaches the client (link, noopener, window.open; own site and another; with and without a route; in-process and over launch_server) as Playwright's does; a superseded route. Needs the candidate binary, and the stock Playwright client of the dev extra."},
|
||||
{"id": "wrapper.unit.page", "giro": "G1", "os": ["linux", "windows"], "min_tests": 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.unit.page", "giro": "G1", "os": ["linux", "windows"], "min_tests": 44, "exact": true, "tests": ["tests/test_a_download_finished_before_it_was_announced_is_finished.py", "tests/test_every_order_of_the_events_of_a_popup_gives_one_page_event.py", "tests/test_ci_drive_gate_goes_through_the_core.py", "tests/test_a_page_is_handed_over_only_when_the_engine_says_it_is_ready.py", "tests/test_a_new_page_waits_for_the_engine.py", "tests/test_page_number_follows_the_call.py"], "marker": "unit", "needs_root": false, "note": "24 (counted at the collection; was 20 = 3+8+1+8 before 6200bc2). The page dispatcher's wait for Page.ready and what it hands over; the drive gate goes through the core (the engine waits for the session's road)."}
|
||||
]
|
||||
@@ -1,20 +1,17 @@
|
||||
---
|
||||
title: "Canvas and WebGL fingerprints across OSes"
|
||||
description: "Canvas and WebGL fingerprints across Windows and Linux: 2D canvas is drawn on the CPU, noise is projected only when WebGL and WebGPU pixels are read back, and it depends only on the seed."
|
||||
title: "Canvas and WebGL fingerprints, identical across OSes"
|
||||
description: "Canvas and WebGL fingerprints identical across Windows and Linux: intercept readback, not the render, so one seed produces a byte-identical hash on every OS."
|
||||
parent: "Canvas, WebGL, Fonts and Audio"
|
||||
grand_parent: "Guides"
|
||||
nav_order: 9
|
||||
---
|
||||
|
||||
|
||||
# Canvas and WebGL fingerprints across OSes
|
||||
# Canvas and WebGL fingerprints, identical across OSes
|
||||
|
||||
A GPU-backed render surface can't be read from or written to directly and safely, so
|
||||
the fix intercepts the one place JavaScript can actually see the result instead - the
|
||||
same seed then gives the same noise on Windows and Linux. 2D canvas is drawn on the CPU, so it
|
||||
does not depend on the GPU; the noise is projected only when WebGL and WebGPU pixels are read back.
|
||||
Text and GPU raster can still differ slightly between the two OSes, and the PNG container is left
|
||||
as a stock Firefox writes it.
|
||||
same seed then produces a byte-identical canvas and WebGL hash on Windows and Linux.
|
||||
|
||||
[Why headless browsers render different fonts](headless-fonts-differ.md) and
|
||||
[how to make Linux and macOS report real Windows fonts](bundled-fonts-cross-platform.md)
|
||||
@@ -95,18 +92,17 @@ for the same reason: nothing about it resembles noise added on top of a real sig
|
||||
| Additive per-call noise | Perturbs a fraction of pixels on top of the real render | Two reads in one page differ; the real render's font/GPU signature still shows through; the noise has a high-frequency shape a single read can flag |
|
||||
| Full substitution | Replaces pixels with a pure function of the seed and the pixel position, with zero input from the render underneath | Must leave low-entropy buffers untouched so it does not break legitimate canvas reads |
|
||||
|
||||
## What was checked, and what was not
|
||||
## The proof: byte-identical hashes, not just "looks similar"
|
||||
|
||||
Rendered the same seed's canvas (text plus a gradient) and WebGL scene (a
|
||||
high-entropy draw) on Windows and on Linux, hashed both in-page, and ran a commercial
|
||||
fingerprint scanner across multiple seeds. What holds: the noise is a pure function of
|
||||
the seed and of the pixels it is applied to, so two reads of the same bytes give the same
|
||||
result, and the 2D path does not depend on the GPU.
|
||||
high-entropy draw) on Windows and on Linux, hashed both in-page. The hashes matched
|
||||
byte for byte on both platforms. Run against a commercial fingerprint scanner across
|
||||
multiple seeds, zero failures on either OS.
|
||||
|
||||
What is not claimed: that every byte matches between a Windows and a Linux host. Text
|
||||
pixels follow the host's rasteriser on Linux, and GPU raster can differ by one level
|
||||
between drivers. Whether two profiles with the same font can be linked by the way they
|
||||
rasterise has not been measured.
|
||||
That is a stronger claim than "produces a plausible fingerprint." It's the same
|
||||
identity, provably, regardless of which OS is actually running underneath - which is
|
||||
what makes a seed a real, portable identity instead of a value that happens to look
|
||||
right on the machine it was tested on.
|
||||
|
||||
## What this generalises to, and where the edges still are
|
||||
|
||||
@@ -125,8 +121,8 @@ a fact that becomes true once and stays true.
|
||||
The render was never the reachable surface. Content only ever sees a canvas or a
|
||||
WebGL scene through a handful of readback calls, and putting the substitution there
|
||||
instead of in the renderer is what makes a seed portable: the same identity produces
|
||||
the same noise on Windows and on Linux, because the noise comes from the seed and not from
|
||||
the host's rendering pipeline.
|
||||
the same bytes on Windows and on Linux, because nothing about either host's actual
|
||||
rendering pipeline reaches the output.
|
||||
|
||||
The tradeoff is honest rather than free - the fix covers only the readback paths it
|
||||
enumerates, and a masking-safe design still has to leave genuinely low-entropy canvas
|
||||
@@ -135,10 +131,10 @@ fingerprinting.
|
||||
|
||||
## Short answers to the questions that lead here
|
||||
|
||||
**Can canvas and WebGL fingerprints be made the same across operating systems?** The
|
||||
noise can: it is applied where content can read the result, from the seed, rather than at
|
||||
the render itself, which can't be touched directly on a GPU-backed surface. The pixels
|
||||
underneath still differ slightly between hosts for text and GPU raster.
|
||||
**Can canvas and WebGL fingerprints be made identical across operating systems?** Yes,
|
||||
if the interception happens at every point content can read the result rather
|
||||
than at the render itself, which is the part that can't be touched directly on a
|
||||
GPU-backed surface.
|
||||
|
||||
**Why substitution instead of adding noise to the real render?** Noise on top of a
|
||||
real image still carries the host's own rendering signature underneath it.
|
||||
@@ -166,7 +162,7 @@ content can observe, not at the source - applied to a different surface.
|
||||
retrieved 2026-08-28, the enumerable set of readback calls this page's interception
|
||||
point covers.
|
||||
- This project's own render-readback interception work and its cross-platform
|
||||
validation (same-seed hashes on Windows and Linux, multi-seed
|
||||
validation (same-seed byte-identical hashes on Windows and Linux, multi-seed
|
||||
results against a commercial fingerprint scanner).
|
||||
|
||||
**See also:** [canvas fingerprint noise](canvas-fingerprint-noise.md), for why
|
||||
|
||||
+2
-2
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
||||
|
||||
[project]
|
||||
name = "invisible_playwright"
|
||||
version = "0.52.0"
|
||||
version = "0.51.1"
|
||||
description = "Playwright wrapper for a patched Firefox with deterministic stealth profile."
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.11"
|
||||
@@ -69,7 +69,7 @@ dependencies = [
|
||||
# metadata; nothing in src/ hardcodes a second copy (tests/test_core_pin.py
|
||||
# fails if one appears). What stays invisible to install-time machinery is the
|
||||
# --no-deps / lockfile residue, and _pin.py is the only layer that sees it.
|
||||
"invisible_core==64.71.0",
|
||||
"invisible_core==63.67.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
|
||||
|
||||
@@ -1,354 +0,0 @@
|
||||
"""The GeoIP database of a CI leg: written by this file, the same bytes on every run, and the proof that the leg launched with it.
|
||||
|
||||
python scripts/ci_lab_geoip.py build [--pin ci/geoip.json] [--dest DIR] # writes DIR/geoip-aio-all.mmdb, exports STEALTHFOX_GEOIP_MMDB
|
||||
python scripts/ci_lab_geoip.py evidence [--out result/geoip.json] # what the environment of THIS command says
|
||||
python scripts/ci_lab_geoip.py verify [--pin ci/geoip.json] --evidence FILE [--used FILE] # exit 1: the leg did not run with the pinned database
|
||||
|
||||
Why this exists (run 43211837926, the root legs of the realness suite): without ``STEALTHFOX_GEOIP_MMDB`` the core asked GitHub which GeoIP
|
||||
database is the latest on every call, from the python of the test, and a resolver trap counted those names (github.com, api.github.com) as the
|
||||
browser's. A CI leg reaches no site for its data and uses no licensed one: the database is made here, from the table below, with nothing but the
|
||||
standard library. It holds the networks the tests look up (the six exits of tests/_realness_support.py EXITS) and the fields the core reads
|
||||
(``country.iso_code``, ``location.latitude`` / ``longitude`` / ``time_zone``); an address that is not in it (the documentation ranges the lab uses,
|
||||
loopback, any IPv6) is "not in the database", as in the real one. ``ci/geoip.json`` holds the sha256 of the file: ``build`` refuses to go on when
|
||||
what it wrote is not that, ``evidence`` says which file a launch ran with, and ``scripts/ci_verdict.py judge --geoip`` turns a leg that ran with
|
||||
anything else red. The real database is looked at only by the release (scripts/ci_real_geoip_check.py).
|
||||
|
||||
The format is MaxMind DB 2.0 (https://maxmind.github.io/MaxMind-DB/): a binary search tree of node_count nodes of two records of 24 bits, 16 zero
|
||||
bytes, the data section, the marker and the metadata map. The tree is an ip_version 6 tree with the IPv4 space under ::/96, as in the real database,
|
||||
so that a lookup of an IPv6 address answers "not found" instead of raising. The metadata integers have the types libmaxminddb checks.
|
||||
|
||||
``build`` writes ``STEALTHFOX_GEOIP_MMDB=<path>`` to ``$GITHUB_ENV`` (every later step of the job sees it, ``sudo -E`` carries it to a root leg) and to
|
||||
stdout.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import ipaddress
|
||||
import json
|
||||
import os
|
||||
import struct
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ENV = "STEALTHFOX_GEOIP_MMDB"
|
||||
FILE_NAME = "geoip-aio-all.mmdb"
|
||||
MARKER = b"\xab\xcd\xefMaxMind.com"
|
||||
RECORD_BITS = 24
|
||||
BUILD_EPOCH = 1793790075 # fixed: the same bytes on every run
|
||||
|
||||
|
||||
def addr(*octets: int) -> str:
|
||||
"""A dotted address from its numbers (no address is written out as text in this repository: the tests and this table build theirs)."""
|
||||
return ".".join(str(o) for o in octets)
|
||||
|
||||
|
||||
def net(a: int, b: int, c: int) -> str:
|
||||
"""The /24 of a.b.c."""
|
||||
return addr(a, b, c, 0) + "/24"
|
||||
|
||||
|
||||
#: The six exits of tests/_realness_support.py EXITS (each test declares the .5 of its /24) and what the core reads of them: country, IANA zone,
|
||||
#: and the coordinates of the city centre (public geography). The tests ask the database for their truth at test time, so any coherent values do.
|
||||
NETWORKS = {
|
||||
net(1, 178, 10): ("DE", "Europe/Berlin", 50.1109, 8.6821), # germany
|
||||
net(1, 0, 16): ("JP", "Asia/Tokyo", 35.6895, 139.6917), # japan
|
||||
net(1, 6, 0): ("IN", "Asia/Kolkata", 12.9716, 77.5946), # india
|
||||
net(1, 0, 4): ("AU", "Australia/Melbourne", -37.8136, 144.9631), # australia
|
||||
net(1, 178, 32): ("BR", "America/Sao_Paulo", -23.5505, -46.6333), # brazil
|
||||
net(1, 32, 239): ("US", "America/Los_Angeles", 34.0522, -118.2437), # united_states
|
||||
}
|
||||
|
||||
|
||||
class Refused(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class U16(int):
|
||||
"""A uint16 of the metadata: not the smallest type that holds it, libmaxminddb checks the type of each key."""
|
||||
|
||||
|
||||
class U32(int):
|
||||
pass
|
||||
|
||||
|
||||
class U64(int):
|
||||
pass
|
||||
|
||||
|
||||
def _control(kind: int, size: int) -> bytes:
|
||||
"""The control byte(s) of a value of type `kind` (1..15) and `size`."""
|
||||
if kind <= 7:
|
||||
first, ext = kind << 5, b""
|
||||
else:
|
||||
first, ext = 0, bytes([kind - 7])
|
||||
if size < 29:
|
||||
return bytes([first | size]) + ext
|
||||
if size < 285:
|
||||
return bytes([first | 29]) + ext + bytes([size - 29])
|
||||
if size < 65821:
|
||||
return bytes([first | 30]) + ext + struct.pack(">H", size - 285)
|
||||
return bytes([first | 31]) + ext + struct.pack(">I", size - 65821)[1:]
|
||||
|
||||
|
||||
def _unsigned(kind: int, value: int, width: int) -> bytes:
|
||||
raw = value.to_bytes(width, "big").lstrip(bytes([0])) # MaxMind DB integers drop their leading zero bytes
|
||||
return _control(kind, len(raw)) + raw
|
||||
|
||||
|
||||
def encode(value) -> bytes:
|
||||
if isinstance(value, U16):
|
||||
return _unsigned(5, int(value), 2)
|
||||
if isinstance(value, U32):
|
||||
return _unsigned(6, int(value), 4)
|
||||
if isinstance(value, U64):
|
||||
return _unsigned(9, int(value), 8)
|
||||
if isinstance(value, str):
|
||||
raw = value.encode("utf-8")
|
||||
return _control(2, len(raw)) + raw
|
||||
if isinstance(value, float):
|
||||
return _control(3, 8) + struct.pack(">d", value)
|
||||
if isinstance(value, dict):
|
||||
out = _control(7, len(value))
|
||||
for key in sorted(value): # sorted: the same bytes whatever the order of the table
|
||||
out += encode(key) + encode(value[key])
|
||||
return out
|
||||
if isinstance(value, (list, tuple)):
|
||||
return _control(11, len(value)) + b"".join(encode(v) for v in value)
|
||||
raise TypeError("cannot encode %r" % (value,))
|
||||
|
||||
|
||||
#: Every address that is not reserved (RFC 6890: this network, private, shared, loopback, link-local, protocol assignments, documentation,
|
||||
#: benchmarking, multicast, the rest of class E) and is not one of the six exits above answers ONE record: the egress address of the machine that
|
||||
#: runs a test is not known in advance (a runner of any provider, any region) and a launch with no proxy asks the database for it. Without this
|
||||
#: record such a launch ends in "egress IP not present in the geoip database" (run 43351424907 of PR 486: 495 errors of one cause). The record is
|
||||
#: declared here, so it is the same on every machine, which a download of the real database is not. The reserved ranges stay "not in the
|
||||
#: database", as in the real one: the lab's own exits (the documentation addresses) must not resolve to anything.
|
||||
FALLBACK = ("US", "America/New_York", 40.7128, -74.006)
|
||||
RESERVED = tuple(ipaddress.ip_network(n) for n in (
|
||||
addr(0, 0, 0, 0) + "/8", addr(10, 0, 0, 0) + "/8", addr(100, 64, 0, 0) + "/10", addr(127, 0, 0, 0) + "/8", addr(169, 254, 0, 0) + "/16",
|
||||
addr(172, 16, 0, 0) + "/12", addr(192, 0, 0, 0) + "/24", addr(192, 0, 2, 0) + "/24", addr(192, 88, 99, 0) + "/24", addr(192, 168, 0, 0) + "/16",
|
||||
addr(198, 18, 0, 0) + "/15", addr(198, 51, 100, 0) + "/24", addr(203, 0, 113, 0) + "/24", addr(224, 0, 0, 0) + "/4", addr(240, 0, 0, 0) + "/4"))
|
||||
|
||||
|
||||
def fallback_networks() -> list:
|
||||
"""The public space minus the reserved ranges minus the networks of the table: disjoint CIDRs (the writer takes no overlap)."""
|
||||
if FALLBACK is None: # a test builds the database without it, to stand for one that has no answer for an address
|
||||
return []
|
||||
left = [ipaddress.ip_network("0.0.0.0/0")]
|
||||
for hole in list(RESERVED) + [ipaddress.ip_network(c) for c in NETWORKS]:
|
||||
nxt = []
|
||||
for net in left:
|
||||
if net.overlaps(hole):
|
||||
nxt.extend(net.address_exclude(hole) if net.supernet_of(hole) else [])
|
||||
else:
|
||||
nxt.append(net)
|
||||
left = nxt
|
||||
return sorted(left, key=lambda n: (int(n.network_address), n.prefixlen))
|
||||
|
||||
|
||||
def records() -> dict:
|
||||
def one(country, zone, lat, lon):
|
||||
return {"country": {"iso_code": country}, "location": {"latitude": lat, "longitude": lon, "time_zone": zone}}
|
||||
|
||||
table = {cidr: one(*row) for cidr, row in NETWORKS.items()}
|
||||
table.update({str(net): one(*FALLBACK) for net in fallback_networks()})
|
||||
return table
|
||||
|
||||
|
||||
def build_bytes() -> bytes:
|
||||
"""The database: the same bytes on every call."""
|
||||
data = bytearray()
|
||||
offsets: dict = {}
|
||||
leaves = []
|
||||
table = records()
|
||||
for cidr in sorted(table, key=lambda c: (int(ipaddress.ip_network(c).network_address), ipaddress.ip_network(c).prefixlen)):
|
||||
blob = encode(table[cidr])
|
||||
if blob not in offsets:
|
||||
offsets[blob] = len(data)
|
||||
data += blob
|
||||
leaves.append((ipaddress.ip_network(cidr), offsets[blob]))
|
||||
# the trie: nodes are [left, right]; a child is None (no data), ("node", index) or ("data", offset)
|
||||
nodes = [[None, None]]
|
||||
for net, offset in leaves:
|
||||
if net.version != 4:
|
||||
raise ValueError("this writer takes IPv4 networks: %s" % net)
|
||||
bits = int(net.network_address)
|
||||
prefix = 96 + net.prefixlen # the IPv4 space sits under ::/96
|
||||
index = 0
|
||||
for depth in range(prefix):
|
||||
bit = (bits >> (127 - depth)) & 1
|
||||
if depth == prefix - 1:
|
||||
nodes[index][bit] = ("data", offset)
|
||||
else:
|
||||
child = nodes[index][bit]
|
||||
if child is None:
|
||||
nodes.append([None, None])
|
||||
child = ("node", len(nodes) - 1)
|
||||
nodes[index][bit] = child
|
||||
elif child[0] != "node":
|
||||
raise ValueError("%s sits inside a network that already has data" % net)
|
||||
index = child[1]
|
||||
count = len(nodes)
|
||||
|
||||
def record(child) -> int:
|
||||
if child is None:
|
||||
return count
|
||||
return child[1] if child[0] == "node" else count + 16 + child[1]
|
||||
|
||||
tree = bytearray()
|
||||
for left, right in nodes:
|
||||
for child in (left, right):
|
||||
value = record(child)
|
||||
if value >= 1 << RECORD_BITS:
|
||||
raise ValueError("a record does not fit in %d bits" % RECORD_BITS)
|
||||
tree += value.to_bytes(RECORD_BITS // 8, "big")
|
||||
metadata = {
|
||||
"binary_format_major_version": U16(2),
|
||||
"binary_format_minor_version": U16(0),
|
||||
"build_epoch": U64(BUILD_EPOCH),
|
||||
"database_type": "GeoIP2-City",
|
||||
"description": {"en": "invisible CI lab database: the networks the tests look up, and one record for every other public address"},
|
||||
"ip_version": U16(6),
|
||||
"languages": ["en"],
|
||||
"node_count": U32(count),
|
||||
"record_size": U16(RECORD_BITS),
|
||||
}
|
||||
return bytes(tree) + bytes(16) + bytes(data) + MARKER + encode(metadata)
|
||||
|
||||
|
||||
def sha256_of_bytes(blob: bytes) -> str:
|
||||
return hashlib.sha256(blob).hexdigest()
|
||||
|
||||
|
||||
def sha256_of(path) -> str:
|
||||
h = hashlib.sha256()
|
||||
with open(path, "rb") as f:
|
||||
for block in iter(lambda: f.read(1 << 20), b""):
|
||||
h.update(block)
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def load_pin(path) -> dict:
|
||||
try:
|
||||
pin = json.loads(Path(path).read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError) as exc:
|
||||
raise Refused("the pin %s cannot be read: %s" % (path, exc))
|
||||
sha = pin.get("mmdb_sha256") if isinstance(pin, dict) else None
|
||||
if not isinstance(sha, str) or len(sha) != 64 or any(c not in "0123456789abcdef" for c in sha):
|
||||
raise Refused("the pin %s has no mmdb_sha256 that is a sha256" % path)
|
||||
return pin
|
||||
|
||||
|
||||
def build(pin: dict, dest: Path) -> Path:
|
||||
"""Write the database to DEST and check it against the pin: a writer that no longer makes the pinned bytes is red."""
|
||||
blob = build_bytes()
|
||||
got = sha256_of_bytes(blob)
|
||||
if got != pin["mmdb_sha256"]:
|
||||
raise Refused("the lab database made by scripts/ci_lab_geoip.py has sha256 %s, the pin (ci/geoip.json) says %s: change both in one commit"
|
||||
% (got, pin["mmdb_sha256"]))
|
||||
dest.mkdir(parents=True, exist_ok=True)
|
||||
target = dest / FILE_NAME
|
||||
target.write_bytes(blob)
|
||||
return target
|
||||
|
||||
|
||||
def evidence(environ=None) -> dict:
|
||||
"""What the environment of this command says about the database: the value of the variable, whether it is a file, its sha256."""
|
||||
environ = os.environ if environ is None else environ
|
||||
value = environ.get(ENV, "")
|
||||
out = {"env": value, "exists": False, "sha256": None}
|
||||
if value and os.path.isfile(value):
|
||||
out["exists"] = True
|
||||
out["sha256"] = sha256_of(value)
|
||||
return out
|
||||
|
||||
|
||||
def verify(pin: dict, evidence_file, used_file=None) -> list:
|
||||
"""The reasons a leg did not run with the pinned database ([] = it did). The same reading as the judge's (scripts/ci_verdict.py), and
|
||||
independent of it: a step of the workflow runs this, so that a judge that does not know the evidence yet (the first merge to main ends that)
|
||||
is not the only thing standing between a leg with no database and a green run.
|
||||
|
||||
``evidence_file``: what the environment said BEFORE pytest was launched (the ``evidence`` command). ``used_file``: what the process of the
|
||||
tests used (tests/geoip_used.py, written when pytest ends): the variable at the end, the sha256 of that file, and how many times the core went
|
||||
to GitHub for a database, which has to be none."""
|
||||
problems = []
|
||||
|
||||
def read(path, what):
|
||||
try:
|
||||
data = json.loads(Path(path).read_text(encoding="utf-8"))
|
||||
if not isinstance(data, dict):
|
||||
raise ValueError("not a JSON object")
|
||||
return data
|
||||
except (OSError, ValueError) as exc:
|
||||
problems.append("the %s %s cannot be read: %s" % (what, path, exc))
|
||||
return None
|
||||
|
||||
for what, path in (("evidence", evidence_file), ("record of use", used_file)):
|
||||
if path is None:
|
||||
continue
|
||||
data = read(path, what)
|
||||
if data is None:
|
||||
continue
|
||||
if not data.get("env"):
|
||||
problems.append("the %s says STEALTHFOX_GEOIP_MMDB was not set" % what)
|
||||
elif not data.get("exists") or not data.get("sha256"):
|
||||
problems.append("the %s says STEALTHFOX_GEOIP_MMDB=%s is not a file" % (what, data.get("env")))
|
||||
elif data["sha256"] != pin["mmdb_sha256"]:
|
||||
problems.append("the %s says the database has sha256 %s, the pin says %s" % (what, data["sha256"], pin["mmdb_sha256"]))
|
||||
if what == "record of use" and data.get("asked_github"):
|
||||
problems.append("the core asked GitHub for a database %s time(s) during the run: it went past STEALTHFOX_GEOIP_MMDB" % data["asked_github"])
|
||||
return problems
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
ap = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0])
|
||||
sub = ap.add_subparsers(dest="cmd", required=True)
|
||||
b = sub.add_parser("build")
|
||||
b.add_argument("--pin", default="ci/geoip.json")
|
||||
b.add_argument("--dest", default=None, help="default: $RUNNER_TEMP/geoip, or ./.geoip")
|
||||
e = sub.add_parser("evidence")
|
||||
e.add_argument("--out", default=None)
|
||||
v = sub.add_parser("verify")
|
||||
v.add_argument("--pin", default="ci/geoip.json")
|
||||
v.add_argument("--evidence", required=True)
|
||||
v.add_argument("--used", default=None)
|
||||
ns = ap.parse_args(argv)
|
||||
if ns.cmd == "build":
|
||||
try:
|
||||
dest = Path(ns.dest or os.path.join(os.environ.get("RUNNER_TEMP", "."), "geoip" if os.environ.get("RUNNER_TEMP") else ".geoip"))
|
||||
path = build(load_pin(ns.pin), dest.resolve())
|
||||
except Refused as exc:
|
||||
print("ci_lab_geoip: %s" % exc, file=sys.stderr)
|
||||
return 1
|
||||
# Where the process of the tests writes what the core did about the database (tests/geoip_used.py, read by `verify`).
|
||||
used = path.parent / "geoip-used.json"
|
||||
print("%s=%s" % (ENV, path))
|
||||
print("GEOIP_USED_OUT=%s" % used)
|
||||
env_file = os.environ.get("GITHUB_ENV")
|
||||
if env_file:
|
||||
with open(env_file, "a", encoding="utf-8") as fh:
|
||||
fh.write("%s=%s\n" % (ENV, path))
|
||||
fh.write("GEOIP_USED_OUT=%s\n" % used)
|
||||
return 0
|
||||
if ns.cmd == "verify":
|
||||
try:
|
||||
problems = verify(load_pin(ns.pin), ns.evidence, ns.used)
|
||||
except Refused as exc:
|
||||
print("ci_lab_geoip: %s" % exc, file=sys.stderr)
|
||||
return 1
|
||||
for problem in problems:
|
||||
print("ci_lab_geoip: FAIL: %s" % problem, file=sys.stderr)
|
||||
print("the leg ran with the pinned GeoIP database" if not problems else "%d problem(s)" % len(problems))
|
||||
return 1 if problems else 0
|
||||
data = evidence()
|
||||
text = json.dumps(data, indent=1)
|
||||
if ns.out:
|
||||
Path(ns.out).parent.mkdir(parents=True, exist_ok=True)
|
||||
Path(ns.out).write_text(text, encoding="utf-8")
|
||||
print(text)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -1,131 +0,0 @@
|
||||
"""The three checks on the REAL GeoIP database: the only place a CI run touches it, and only in the release (publish.yml, job `real-geoip-database`).
|
||||
|
||||
The legs of the gates and of the pull requests launch with the database made by scripts/ci_lab_geoip.py (a few networks, the same bytes every run, no
|
||||
download). What it cannot prove is proved here, once per release, against the database a user gets:
|
||||
|
||||
1. THE PRODUCT'S OWN ROAD. With STEALTHFOX_GEOIP_MMDB unset and a cold cache the core downloads the latest database (``ensure_geoip_mmdb``), the file
|
||||
opens with the reader the core uses (MODE_MMAP) and answers for an address.
|
||||
2. THE LAB DATABASE AGREES. For the exit of each network of the lab database the real one gives the same country and the same IANA zone: if it does
|
||||
not, the lab table is stale (the tests ask their truth of the database at test time, so a stale table does not break them; it says the lab no longer
|
||||
looks like the world).
|
||||
3. EVERY ZONE IS KNOWN. Each distinct ``location.time_zone`` of the real database is a zone this runner's tz database knows (``ip_to_timezone``
|
||||
validates with ZoneInfo: a name the database has and the runner has not is a launch that fails for the user).
|
||||
|
||||
python scripts/ci_real_geoip_check.py # exit 0: all three hold; 1: one does not (said); 2: wrong use; 3: no database came (the network)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
import ci_lab_geoip as lab # noqa: E402
|
||||
|
||||
#: The database did not come: not a finding about it (see main).
|
||||
EXIT_NO_DATABASE = 3
|
||||
|
||||
|
||||
def exit_of(cidr: str) -> str:
|
||||
"""The address each test declares in a lab network: the .5 of its /24 (tests/_realness_support.py EXITS)."""
|
||||
base = cidr.split("/")[0].rsplit(".", 1)[0]
|
||||
return "%s.5" % base
|
||||
|
||||
|
||||
def check_open_and_answer(path: Path) -> list:
|
||||
import maxminddb
|
||||
|
||||
try:
|
||||
with maxminddb.open_database(str(path), mode=maxminddb.MODE_MMAP) as reader:
|
||||
record = reader.get("8.8.8.8")
|
||||
except (OSError, ValueError, getattr(maxminddb, "InvalidDatabaseError", ValueError)) as exc:
|
||||
return ["the database %s does not open with the reader of the core: %s" % (path, exc)]
|
||||
code = ((record or {}).get("country") or {}).get("iso_code")
|
||||
return [] if code else ["the database %s has no country for 8.8.8.8: %r" % (path, record)]
|
||||
|
||||
|
||||
def check_lab_agrees(real: Path, lab_path: Path) -> list:
|
||||
from invisible_core._geo import GeoTimezoneError, ip_to_country, ip_to_timezone
|
||||
|
||||
problems = []
|
||||
for cidr in sorted(lab.NETWORKS):
|
||||
ip = exit_of(cidr)
|
||||
try:
|
||||
ours = (ip_to_country(ip, lab_path), ip_to_timezone(ip, lab_path))
|
||||
theirs = (ip_to_country(ip, real), ip_to_timezone(ip, real))
|
||||
except GeoTimezoneError as exc:
|
||||
problems.append("%s (%s): %s" % (cidr, ip, exc))
|
||||
continue
|
||||
if ours != theirs:
|
||||
problems.append("%s (%s): the lab database says %s, the real one %s" % (cidr, ip, ours, theirs))
|
||||
return problems
|
||||
|
||||
|
||||
def zones_of(path: Path) -> set:
|
||||
import maxminddb
|
||||
|
||||
zones = set()
|
||||
with maxminddb.open_database(str(path), mode=maxminddb.MODE_MMAP_EXT if hasattr(maxminddb, "MODE_MMAP_EXT") else maxminddb.MODE_MMAP) as reader:
|
||||
for _network, record in reader:
|
||||
zone = (record.get("location") or {}).get("time_zone") if isinstance(record, dict) else None
|
||||
if zone:
|
||||
zones.add(zone)
|
||||
return zones
|
||||
|
||||
|
||||
def check_zones(path: Path) -> list:
|
||||
problems = []
|
||||
zones = zones_of(path)
|
||||
if not zones:
|
||||
return ["the database %s has no time_zone at all" % path]
|
||||
for zone in sorted(zones):
|
||||
try:
|
||||
ZoneInfo(zone)
|
||||
except Exception as exc: # noqa: BLE001 - ZoneInfoNotFoundError, ValueError, OSError: all the same finding
|
||||
problems.append("the zone %r of the database is not known to the tz database of this runner: %s" % (zone, exc))
|
||||
print("%d distinct zones in %s" % (len(zones), path))
|
||||
return problems
|
||||
|
||||
|
||||
def product_download(cache: Path) -> Path:
|
||||
"""The core's own road: no variable, a cold cache."""
|
||||
os.environ.pop(lab.ENV, None)
|
||||
os.environ["INVISIBLE_PLAYWRIGHT_CACHE_DIR"] = str(cache)
|
||||
from invisible_core.download import ensure_geoip_mmdb
|
||||
|
||||
return Path(ensure_geoip_mmdb())
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
if len(argv if argv is not None else sys.argv[1:]):
|
||||
print(__doc__)
|
||||
return 2
|
||||
problems = []
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
td = Path(td)
|
||||
try:
|
||||
real = product_download(td / "cache")
|
||||
except Exception as exc: # noqa: BLE001
|
||||
# Exit 3: the database did not come (the network, GitHub, the download), which says nothing about the database. The release
|
||||
# waits for a rerun; it is not a defect of the product and not one of the three checks.
|
||||
print("1. the product's own road: NO DATABASE (%s: %s): exit 3, run it again" % (type(exc).__name__, exc))
|
||||
return EXIT_NO_DATABASE
|
||||
print("1. the product's road gave %s: tag %s, %d bytes, sha256 %s" % (real, real.parent.name, real.stat().st_size, lab.sha256_of(real)))
|
||||
results = []
|
||||
for label, found in (
|
||||
("1. it opens with the reader of the core and answers for an address", check_open_and_answer(real)),
|
||||
("2. the lab database agrees with it on the six exits (country, zone)",
|
||||
check_lab_agrees(real, lab.build(lab.load_pin(Path(__file__).resolve().parents[1] / "ci" / "geoip.json"), td / "lab"))),
|
||||
("3. every time_zone of it is known to the tz database of this runner", check_zones(real))):
|
||||
print("%s: %s" % (label, "ok" if not found else "FAILED (%d)" % len(found)))
|
||||
problems += found
|
||||
for p in problems:
|
||||
print("FAIL: %s" % p)
|
||||
print("real GeoIP database: %s" % ("all three checks hold" if not problems else "%d problem(s)" % len(problems)))
|
||||
return 1 if problems else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -307,37 +307,6 @@ def _seal_problems(path, result):
|
||||
return []
|
||||
|
||||
|
||||
def _geoip_problems(path, pin_path, result):
|
||||
"""A leg launched with the GeoIP database of the pin, or it is red.
|
||||
|
||||
``path`` is the evidence the leg wrote with ``scripts/ci_lab_geoip.py evidence``, run in the very environment pytest was started in
|
||||
(``sudo -E`` included): the value of STEALTHFOX_GEOIP_MMDB, whether it is a file, its sha256. Without the variable the core asks GitHub which
|
||||
database is the latest on every call, from the python of the test (run 43211837926: a resolver trap counted github.com and api.github.com as
|
||||
the browser's), and a leg that reaches a site for its data is not a leg of the gate.
|
||||
"""
|
||||
try:
|
||||
evidence = json.loads(Path(path).read_text(encoding="utf-8"))
|
||||
if not isinstance(evidence, dict):
|
||||
raise ValueError("not a JSON object")
|
||||
except (OSError, ValueError) as exc:
|
||||
result["geoip_sha256"] = "unreadable"
|
||||
return ["the GeoIP evidence %s cannot be read: %s: the leg did not say which database it ran with" % (path, exc)]
|
||||
result["geoip_sha256"] = evidence.get("sha256")
|
||||
if not evidence.get("env"):
|
||||
return ["the leg launched without STEALTHFOX_GEOIP_MMDB: the core would ask GitHub for its database on every call (the database of "
|
||||
"the gate is ci/geoip.json, made by scripts/ci_lab_geoip.py)"]
|
||||
if not evidence.get("exists") or not evidence.get("sha256"):
|
||||
return ["STEALTHFOX_GEOIP_MMDB=%s is not a file: the leg ran without a database" % evidence.get("env")]
|
||||
try:
|
||||
pin = json.loads(Path(pin_path).read_text(encoding="utf-8")) if pin_path else None
|
||||
expected = pin["mmdb_sha256"]
|
||||
except (OSError, ValueError, KeyError, TypeError) as exc:
|
||||
return ["the pin of the GeoIP database %s cannot be read: %s" % (pin_path, exc)]
|
||||
if evidence["sha256"] != expected:
|
||||
return ["the leg ran with a GeoIP database of sha256 %s, the pin (%s) says %s" % (evidence["sha256"], pin_path, expected)]
|
||||
return []
|
||||
|
||||
|
||||
def cmd_judge(ns):
|
||||
problems = []
|
||||
result = {"suite": ns.suite, "os": ns.os, "commit": commit_sha(ns.commit), "binary_sha256": sha256_of(ns.binary),
|
||||
@@ -360,8 +329,6 @@ def cmd_judge(ns):
|
||||
problems.append("the binary %s does not exist: a result with no hash of the engine is not a result" % ns.binary)
|
||||
if ns.seal:
|
||||
problems += _seal_problems(ns.seal, result)
|
||||
if ns.geoip:
|
||||
problems += _geoip_problems(ns.geoip, ns.geoip_pin, result)
|
||||
|
||||
counts = {"passed": 0, "failed": 0, "skipped": 0, "errors": 0}
|
||||
cases = []
|
||||
@@ -509,8 +476,6 @@ def main(argv=None):
|
||||
j.add_argument("--binary")
|
||||
j.add_argument("--commit")
|
||||
j.add_argument("--seal")
|
||||
j.add_argument("--geoip", help="the evidence of the leg (scripts/ci_lab_geoip.py evidence): a leg launched without the database is red")
|
||||
j.add_argument("--geoip-pin", help="ci/geoip.json: the sha256 of the database the leg has to have run with (main's, when main has it)")
|
||||
j.add_argument("--out")
|
||||
j.add_argument("--main-required")
|
||||
j.add_argument("--main-has-no-list", action="store_true",
|
||||
|
||||
@@ -1,182 +0,0 @@
|
||||
// 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) }) }));
|
||||
@@ -1,433 +0,0 @@
|
||||
"""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())
|
||||
@@ -1,599 +0,0 @@
|
||||
"""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())
|
||||
@@ -1,556 +0,0 @@
|
||||
"""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())
|
||||
@@ -1,654 +0,0 @@
|
||||
"""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())
|
||||
@@ -1,585 +0,0 @@
|
||||
"""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())
|
||||
@@ -1,48 +0,0 @@
|
||||
"""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))
|
||||
@@ -1,92 +0,0 @@
|
||||
"""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())
|
||||
@@ -1,669 +0,0 @@
|
||||
"""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())
|
||||
@@ -1,109 +0,0 @@
|
||||
// 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" });
|
||||
})();
|
||||
@@ -1,329 +0,0 @@
|
||||
"""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())
|
||||
@@ -1,141 +0,0 @@
|
||||
// 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) }) }));
|
||||
@@ -1,273 +0,0 @@
|
||||
"""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,422 +0,0 @@
|
||||
// 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;
|
||||
})()
|
||||
@@ -1,417 +0,0 @@
|
||||
"""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())
|
||||
@@ -1,331 +0,0 @@
|
||||
"""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())
|
||||
@@ -1,134 +0,0 @@
|
||||
// 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) }) }));
|
||||
@@ -1,173 +0,0 @@
|
||||
"""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())
|
||||
@@ -0,0 +1,206 @@
|
||||
"""HUNT SCAFFOLDING, NEVER MERGED: the processes of the retail Firefox and of this browser on the same page, measured the same way.
|
||||
|
||||
python scripts/study_processes.py --retail <firefox executable> --ours <firefox executable> --out <dir> [--seconds 30]
|
||||
|
||||
One local page (a PeerConnection, so the socket process starts, and an iframe of another site) opened in a fresh profile by each
|
||||
browser, one after the other. After `--seconds`, for every process of the browser's tree: its kind (from the -contentproc command
|
||||
line), resident and private memory, the sandbox (Windows: integrity level and AppContainer of the token; Linux: the Seccomp line of
|
||||
/proc), and its connections that are not loopback; the names the browser resolved (MOZ_LOG nsHostResolver:5) and the files under
|
||||
the profile's datareporting/ at the end. The retail is launched bare (its own command line); ours through the package, as a user
|
||||
launches it. Writes <out>/<name>.json and prints a table.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import ctypes
|
||||
import glob
|
||||
import http.server
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
|
||||
import psutil
|
||||
|
||||
PAGE = b"""<!doctype html><title>study</title><body>study
|
||||
<iframe src="http://localhost:%d/frame"></iframe>
|
||||
<script>
|
||||
const pc = new RTCPeerConnection({iceServers: []});
|
||||
pc.createDataChannel('x');
|
||||
pc.createOffer().then(o => pc.setLocalDescription(o));
|
||||
</script></body>"""
|
||||
|
||||
|
||||
def _serve():
|
||||
class H(http.server.BaseHTTPRequestHandler):
|
||||
def do_GET(self): # noqa: N802
|
||||
body = PAGE % self.server.server_address[1] if self.path == "/" else b"<!doctype html><title>frame</title>frame"
|
||||
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, *a):
|
||||
pass
|
||||
|
||||
srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), H)
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
return srv
|
||||
|
||||
|
||||
def _kind(cmd):
|
||||
if "-contentproc" not in cmd:
|
||||
return "parent" if cmd else "?"
|
||||
for k in ("socket", "gpu", "rdd", "utility", "tab", "gmplugin", "forkserver"):
|
||||
if k in cmd:
|
||||
return k
|
||||
return cmd[-1] if cmd else "?"
|
||||
|
||||
|
||||
def _integrity(pid):
|
||||
if sys.platform != "win32":
|
||||
try:
|
||||
for line in open("/proc/%d/status" % pid):
|
||||
if line.startswith("Seccomp:"):
|
||||
return "seccomp=" + line.split()[1]
|
||||
except OSError:
|
||||
return None
|
||||
return None
|
||||
k32, adv = ctypes.windll.kernel32, ctypes.windll.advapi32
|
||||
vp = ctypes.c_void_p
|
||||
k32.OpenProcess.restype, k32.OpenProcess.argtypes = vp, [ctypes.c_ulong, ctypes.c_int, ctypes.c_ulong]
|
||||
k32.CloseHandle.argtypes = [vp]
|
||||
adv.OpenProcessToken.argtypes = [vp, ctypes.c_ulong, ctypes.POINTER(vp)]
|
||||
adv.GetTokenInformation.argtypes = [vp, ctypes.c_int, vp, ctypes.c_ulong, ctypes.POINTER(ctypes.c_ulong)]
|
||||
adv.GetSidSubAuthorityCount.restype, adv.GetSidSubAuthorityCount.argtypes = ctypes.POINTER(ctypes.c_ubyte), [vp]
|
||||
adv.GetSidSubAuthority.restype, adv.GetSidSubAuthority.argtypes = ctypes.POINTER(ctypes.c_ulong), [vp, ctypes.c_ulong]
|
||||
h = k32.OpenProcess(0x1000, False, pid)
|
||||
if not h:
|
||||
return None
|
||||
tok = vp()
|
||||
try:
|
||||
if not adv.OpenProcessToken(h, 0x0008, ctypes.byref(tok)):
|
||||
return None
|
||||
need = ctypes.c_ulong()
|
||||
adv.GetTokenInformation(tok, 25, None, 0, ctypes.byref(need))
|
||||
buf = ctypes.create_string_buffer(need.value)
|
||||
if not adv.GetTokenInformation(tok, 25, ctypes.cast(buf, vp), need, ctypes.byref(need)):
|
||||
return None
|
||||
sid = ctypes.cast(buf, ctypes.POINTER(vp))[0]
|
||||
count = adv.GetSidSubAuthorityCount(sid)[0]
|
||||
rid = adv.GetSidSubAuthority(sid, count - 1)[0]
|
||||
level = {0: "untrusted", 0x1000: "low", 0x2000: "medium", 0x2100: "medium+", 0x3000: "high", 0x4000: "system"}.get(rid, hex(rid))
|
||||
app = ctypes.c_ulong()
|
||||
adv.GetTokenInformation(tok, 29, ctypes.cast(ctypes.byref(app), vp), 4, ctypes.byref(need))
|
||||
return level + (" appcontainer" if app.value else "")
|
||||
finally:
|
||||
if tok:
|
||||
k32.CloseHandle(tok)
|
||||
k32.CloseHandle(h)
|
||||
|
||||
|
||||
def _snapshot(exe):
|
||||
"""Every process whose executable sits in the folder of `exe` (the retail's launcher process on Windows starts the browser
|
||||
again and exits, so its own pid has no tree)."""
|
||||
folder = os.path.normcase(os.path.dirname(os.path.abspath(exe)))
|
||||
procs = []
|
||||
for p in psutil.process_iter(["exe"]):
|
||||
try:
|
||||
if p.info["exe"] and os.path.normcase(os.path.dirname(p.info["exe"])) == folder:
|
||||
procs.append(p)
|
||||
except psutil.Error:
|
||||
continue
|
||||
out = []
|
||||
for p in procs:
|
||||
try:
|
||||
cmd = p.cmdline()
|
||||
mem = p.memory_full_info()
|
||||
conns = [("%s:%s" % c.raddr) for c in p.net_connections(kind="inet") if c.raddr and not c.raddr.ip.startswith(("127.", "::1"))]
|
||||
out.append({"pid": p.pid, "name": p.name(), "kind": _kind(cmd), "rss_mb": round(mem.rss / 2**20, 1),
|
||||
"private_mb": round(getattr(mem, "private", getattr(mem, "uss", 0)) / 2**20, 1),
|
||||
"sandbox": _integrity(p.pid), "connections": sorted(set(conns))})
|
||||
except psutil.Error:
|
||||
continue
|
||||
return out
|
||||
|
||||
|
||||
def _resolved(logdir):
|
||||
names = set()
|
||||
for f in glob.glob(os.path.join(logdir, "*")):
|
||||
for line in open(f, encoding="utf-8", errors="replace"):
|
||||
m = re.search(r"Resolving host \[([^\]]+)\]|host \[([^\]]+)\]", line)
|
||||
if m:
|
||||
names.add((m.group(1) or m.group(2)).split(":")[0])
|
||||
return sorted(n for n in names if n not in ("localhost", "127.0.0.1"))
|
||||
|
||||
|
||||
def _datareporting(profile):
|
||||
root = os.path.join(profile, "datareporting")
|
||||
return sorted(os.path.relpath(os.path.join(d, f), profile) for d, _s, fs in os.walk(root) for f in fs) if os.path.isdir(root) else []
|
||||
|
||||
|
||||
def retail(exe, url, seconds, work):
|
||||
profile = tempfile.mkdtemp(prefix="retail_", dir=work)
|
||||
logdir = tempfile.mkdtemp(prefix="retail_log_", dir=work)
|
||||
env = dict(os.environ, MOZ_LOG="timestamp,nsHostResolver:5", MOZ_LOG_FILE=os.path.join(logdir, "moz"))
|
||||
subprocess.Popen([exe, "-no-remote", "-profile", profile, url], env=env)
|
||||
time.sleep(seconds)
|
||||
snap = _snapshot(exe)
|
||||
for q in snap:
|
||||
try:
|
||||
psutil.Process(q["pid"]).kill()
|
||||
except psutil.Error:
|
||||
pass
|
||||
time.sleep(3)
|
||||
return {"browser": "retail", "processes": snap, "resolved": _resolved(logdir), "datareporting": _datareporting(profile)}
|
||||
|
||||
|
||||
def ours(exe, url, seconds, work):
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
logdir = tempfile.mkdtemp(prefix="ours_log_", dir=work)
|
||||
os.environ.update(MOZ_LOG="timestamp,nsHostResolver:5", MOZ_LOG_FILE=os.path.join(logdir, "moz"))
|
||||
with InvisiblePlaywright(binary_path=exe, headless=True) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto(url)
|
||||
time.sleep(seconds)
|
||||
snap = _snapshot(exe)
|
||||
parents = [psutil.Process(q["pid"]) for q in snap if q["kind"] == "parent"]
|
||||
cmd = parents[0].cmdline() if parents else []
|
||||
profile = cmd[cmd.index("-profile") + 1] if "-profile" in cmd else None
|
||||
reporting = _datareporting(profile) if profile else []
|
||||
return {"browser": "ours", "processes": snap, "resolved": _resolved(logdir), "datareporting": reporting}
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--retail", required=True)
|
||||
ap.add_argument("--ours", required=True)
|
||||
ap.add_argument("--out", required=True)
|
||||
ap.add_argument("--seconds", type=int, default=30)
|
||||
ap.add_argument("--repeat", type=int, default=3)
|
||||
a = ap.parse_args()
|
||||
os.makedirs(a.out, exist_ok=True)
|
||||
work = tempfile.mkdtemp(prefix="study_")
|
||||
srv = _serve()
|
||||
url = "http://127.0.0.1:%d/" % srv.server_address[1]
|
||||
for n in range(1, a.repeat + 1):
|
||||
for name, fn, exe in (("retail", retail, a.retail), ("ours", ours, a.ours)):
|
||||
r = fn(exe, url, a.seconds, work)
|
||||
r.update(platform=sys.platform, seconds=a.seconds, executable=exe, round=n)
|
||||
json.dump(r, open(os.path.join(a.out, "%s_%d.json" % (name, n)), "w"), indent=1)
|
||||
print("== %s round %d: %d processes, %d names resolved, %d datareporting files" % (name, n, len(r["processes"]), len(r["resolved"]), len(r["datareporting"])))
|
||||
for p in sorted(r["processes"], key=lambda x: x["kind"]):
|
||||
print(" %-10s rss %6.1f MB private %6.1f MB sandbox %-22s conns %d" % (p["kind"], p["rss_mb"], p["private_mb"], p["sandbox"], len(p["connections"])))
|
||||
print(" resolved:", ", ".join(r["resolved"]))
|
||||
print(" datareporting:", ", ".join(r["datareporting"]))
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -155,15 +155,10 @@ class MemProbe:
|
||||
}
|
||||
|
||||
def write(self, event: str) -> None:
|
||||
# The row is stamped (`t` in `sample`) and written under ONE lock: the tick thread and
|
||||
# the thread that closes a context both come here, and a row stamped before the lock
|
||||
# can be written after a later one (slow sample, e.g. USS on Windows), which puts the
|
||||
# file out of time order.
|
||||
try:
|
||||
with self._lock:
|
||||
line = json.dumps(self.sample(event))
|
||||
with open(self.path, "a", encoding="utf-8") as out:
|
||||
out.write(line + "\n")
|
||||
line = json.dumps(self.sample(event))
|
||||
with self._lock, open(self.path, "a", encoding="utf-8") as out:
|
||||
out.write(line + "\n")
|
||||
except Exception:
|
||||
pass # a probe never takes the server down
|
||||
|
||||
|
||||
@@ -33,7 +33,6 @@ import contextlib
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import queue
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
@@ -297,6 +296,23 @@ def session_udp_stun_servers(prefs: Dict) -> Optional[list]:
|
||||
return ["%s:%d" % server for server in stun_servers(str(value).split(","))]
|
||||
|
||||
|
||||
def refuse_the_launch_counter(prefs: Dict) -> None:
|
||||
"""The launch counter is part of the package and a client of this server cannot turn it off or point it elsewhere.
|
||||
|
||||
⛔ The core refuses `invisible_firefox.usage_ping.enabled` and `.url` in `extra_prefs` (invisible_core.prefs), but a client of
|
||||
this server sends `firefoxUserPrefs` straight into `session_for_launch`: a stock Playwright `launch(firefox_user_prefs=...)`
|
||||
is put on TOP of the session the server composes, and a launch marked as composed is taken as it comes. Either road would
|
||||
have carried the two prefs past the core. The only thing allowed is the address the core itself wrote, in a composed launch."""
|
||||
from invisible_core.prefs import USAGE_PING_PREFS, USAGE_PING_REFUSAL, USAGE_PING_URL
|
||||
composed = COMPOSED_PREF in prefs
|
||||
for key in USAGE_PING_PREFS:
|
||||
if key not in prefs:
|
||||
continue
|
||||
if composed and key.endswith(".url") and prefs[key] == USAGE_PING_URL:
|
||||
continue
|
||||
raise ValueError("%s: %s" % (key, USAGE_PING_REFUSAL))
|
||||
|
||||
|
||||
def session_for_launch(prefs: Dict, executable: str, proxy: Optional[Dict] = None) -> tuple:
|
||||
"""What a launch writes into its profile and adds to its environment: always a
|
||||
composed session. Returns (prefs, session_env).
|
||||
@@ -326,6 +342,7 @@ def session_for_launch(prefs: Dict, executable: str, proxy: Optional[Dict] = Non
|
||||
measures there (timezone, locale) and the network it declares are the proxy's,
|
||||
not this machine's. The engine is told the proxy by `op_launch`, as before.
|
||||
"""
|
||||
refuse_the_launch_counter(prefs)
|
||||
if COMPOSED_PREF in prefs:
|
||||
return dict(prefs), {}
|
||||
from invisible_playwright._session import default_session
|
||||
@@ -995,36 +1012,15 @@ class FrameDispatcher(Dispatcher):
|
||||
detached = False
|
||||
|
||||
def emit(self, method: str, params: Optional[Dict] = None) -> None:
|
||||
if method == "loadstate" and params:
|
||||
# ⛔ A LOAD STATE IS TOLD ONCE. The hand-over reconciles the frame with the lifecycle and the page's own listener then hears the
|
||||
# same `DOMContentLoaded`/`load`: whichever comes second finds the state already told and says nothing (a `page.on("load")`
|
||||
# that fired twice). A commit removes the states first, so the next document's are told again.
|
||||
state = params.get("add")
|
||||
told = bool(state) and not params.get("remove") and state in self.told_states
|
||||
if state in ("domcontentloaded", "load"):
|
||||
page = self.page
|
||||
with page._announce_lock:
|
||||
# ⛔ KEPT FOR THE REPLAY EVEN WHEN THE CLIENT KNOWS IT ALREADY (from the snapshot of the initializer, or from the
|
||||
# reconciliation): the replay after the announcement is what makes `page.on("load")` run for a popup that loaded
|
||||
# before the client heard of it, once per frame and state.
|
||||
if not page._announced and not any(
|
||||
f is self and p.get("add") == state for f, p in page._said_before_announcement):
|
||||
page._said_before_announcement.append((self, dict(params)))
|
||||
if not told:
|
||||
self._track_states(params)
|
||||
super().emit(method, params)
|
||||
return
|
||||
if told:
|
||||
return
|
||||
self._track_states(params)
|
||||
if method == "loadstate" and params and params.get("add") in ("domcontentloaded", "load"):
|
||||
page = self.page
|
||||
with page._announce_lock:
|
||||
if not page._announced:
|
||||
page._said_before_announcement.append((self, dict(params)))
|
||||
super().emit(method, params)
|
||||
return
|
||||
super().emit(method, params)
|
||||
|
||||
def _track_states(self, params: Dict) -> None:
|
||||
if params.get("add"):
|
||||
self.told_states.add(params["add"])
|
||||
if params.get("remove"):
|
||||
self.told_states.discard(params["remove"])
|
||||
|
||||
def detach(self) -> None:
|
||||
"""The frame left the page: its handles go (their frame is no more), the frame itself stays and refuses."""
|
||||
self.detached = True
|
||||
@@ -1042,22 +1038,15 @@ class FrameDispatcher(Dispatcher):
|
||||
def __init__(self, server, page: "PageDispatcher", frame_id: str,
|
||||
url: str = "about:blank", name: str = "",
|
||||
load_states: Optional[List[str]] = None,
|
||||
parent_frame: Optional["FrameDispatcher"] = None,
|
||||
told_commit: Any = None) -> None:
|
||||
parent_frame: Optional["FrameDispatcher"] = None) -> None:
|
||||
self.page = page
|
||||
self.frame_id = frame_id
|
||||
#: Which commit of the lifecycle the client was last told (its place in the engine's stream): two documents at the same address
|
||||
#: and with the same name differ only by this (`PageDispatcher._reconcile_frame`).
|
||||
self.told_commit = told_commit
|
||||
self.parent_frame = parent_frame
|
||||
#: ⛔ Kept here because the INITIALIZER is a snapshot: the client reads
|
||||
#: the url from it once, at creation, and afterwards only from
|
||||
#: `navigated` events. A frame created before it navigates keeps an
|
||||
#: empty url forever unless something updates this.
|
||||
self.url = url
|
||||
#: 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"])
|
||||
#: 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.
|
||||
@@ -2772,16 +2761,6 @@ class PageDispatcher(Dispatcher):
|
||||
# The id Juggler gave the running screencast, or None. One per page,
|
||||
# because the engine holds one capture sink per window.
|
||||
self._screencast_id: Optional[str] = None
|
||||
# ⛔ THE THREE FIELDS BELOW ARE ONE STATE AND MOVE TOGETHER, under
|
||||
# `_screencast_lock`: the id, whether a start is still waiting for its
|
||||
# reply, and the frame that came in during that wait. The frames
|
||||
# arrive on the reader thread and the start/stop on a worker, and the
|
||||
# engine lets ONE frame be in flight until it is acknowledged, so a
|
||||
# frame the handler cannot acknowledge ends the stream for good (see
|
||||
# `_on_screencast_frame`).
|
||||
self._screencast_lock = threading.Lock()
|
||||
self._screencast_starting = False
|
||||
self._screencast_early: Optional[Dict] = None
|
||||
conn = context.browser.conn
|
||||
# ⛔ THIS PAGE'S OWN EVENTS ARE HELD FROM HERE, not dropped. A page the
|
||||
# SITE opened has usually sent its document request, and often had the
|
||||
@@ -2806,9 +2785,6 @@ class PageDispatcher(Dispatcher):
|
||||
# replay.
|
||||
self._held: Optional[List] = []
|
||||
self._held_lock = threading.Lock()
|
||||
self._frames_lock = threading.RLock()
|
||||
#: The events that did not fit in the hold (`HELD_CAP`): counted, and said once when the hold ends (`_install_events`).
|
||||
self._held_dropped = 0
|
||||
#: ⛔ THE `domcontentloaded` AND `load` OF A POPUP THAT ARE SAID BEFORE IT IS ANNOUNCED. The page is built at once and announced when
|
||||
#: the engine says Page.ready, which is also when its document commits, so the document may have loaded before the client hears
|
||||
#: of the page: a `page.on("load")` registered in the handler of the `page` event would never fire. Playwright's own page is
|
||||
@@ -2817,33 +2793,9 @@ class PageDispatcher(Dispatcher):
|
||||
self._announce_lock = threading.RLock()
|
||||
self._announced = False
|
||||
self._said_before_announcement: List = []
|
||||
# ⛔ SUBSCRIBE AND BE HANDED THE MISSED EVENTS IN ONE STEP, with the events of the sessions held (`events_gate`): an event the
|
||||
# engine's reader delivers between the subscription and the replay would reach the lifecycle BEFORE the older ones the replay
|
||||
# brings, and the lifecycle would end at the older state (a popup at about:blank after its destination committed). Nothing in the
|
||||
# step waits for an event or a reply: the readers are subscribed, the buffer is handed over, the gate opens.
|
||||
try:
|
||||
with context.browser.events_gate():
|
||||
self.lifecycle = Lifecycle(conn, session)
|
||||
self.injected = InjectedScript(conn, session)
|
||||
conn.add_listener(self._route_juggler_event)
|
||||
# ⛔ THE EVENTS THIS PAGE ALREADY MISSED, handed over now that the two things that need them exist. `Page.frameAttached` and
|
||||
# the `Runtime.executionContextCreated` pair are sent by the browser BEFORE the `Browser.newPage` reply that told us which
|
||||
# session to build this object for, so without the replay the lifecycle waits twenty seconds for a main frame that was
|
||||
# announced before it was born.
|
||||
#
|
||||
# ⛔ AND IT DELIBERATELY DOES NOT REACH `_on_juggler_event`, which is not wired yet and cannot be: that handler emits on
|
||||
# `self.channel`, and the channel does not exist until `super().__init__` has run, which needs the main frame this replay
|
||||
# is what delivers. The events that precede a page describe its birth, and the initializer built below carries that - the
|
||||
# main frame is in it by name. (The page's own listener holds them: `_held`.)
|
||||
self.replayed_events = context.browser.replay(session, conn.dispatch_event)
|
||||
except BaseException:
|
||||
conn.remove_listener(self._route_juggler_event)
|
||||
for part in ("lifecycle", "injected"):
|
||||
try:
|
||||
getattr(self, part).detach()
|
||||
except Exception:
|
||||
pass
|
||||
raise
|
||||
self.lifecycle = Lifecycle(conn, session)
|
||||
self.injected = InjectedScript(conn, session)
|
||||
conn.add_listener(self._route_juggler_event)
|
||||
try:
|
||||
self._build(server, context, session, conn, opener)
|
||||
except BaseException:
|
||||
@@ -2896,9 +2848,22 @@ class PageDispatcher(Dispatcher):
|
||||
context.browser.session_seed, context.browser.motion_budget_s,
|
||||
lambda: self.viewport_size,
|
||||
draws=context.browser.pointer_draws)
|
||||
# ⛔ THE EVENTS THIS PAGE ALREADY MISSED, handed over now that the two
|
||||
# things that need them exist. `Page.frameAttached` and the
|
||||
# `Runtime.executionContextCreated` pair are sent by the browser BEFORE
|
||||
# the `Browser.newPage` reply that told us which session to build this
|
||||
# object for, so without the replay the lifecycle waits twenty seconds
|
||||
# for a main frame that was announced before it was born.
|
||||
#
|
||||
# ⛔ AND IT DELIBERATELY DOES NOT REACH `_on_juggler_event`, which is
|
||||
# not wired yet and cannot be: that handler emits on `self.channel`,
|
||||
# and the channel does not exist until `super().__init__` has run,
|
||||
# which needs the main frame this replay is what delivers. The events
|
||||
# that precede a page describe its birth, and the initializer built
|
||||
# below carries that - the main frame is in it by name.
|
||||
replayed = context.browser.replay(session, conn.dispatch_event)
|
||||
self.replayed_events = replayed
|
||||
self._frames: Dict[str, Any] = {}
|
||||
#: The child frames the client was told of (`frameAttached`), to tell it of the ones born before the hook was in.
|
||||
self._told_attached: set = set()
|
||||
self._requests: Dict[str, Any] = {}
|
||||
#: navigationId -> the document RequestDispatcher of that navigation.
|
||||
#: ⛔ AN INDEX, NOT A SECOND COPY: the response itself keeps living on
|
||||
@@ -2934,8 +2899,7 @@ class PageDispatcher(Dispatcher):
|
||||
server, self, self.main_frame_id,
|
||||
url=getattr(known, "url", "") or "",
|
||||
name=getattr(known, "name", "") or "",
|
||||
load_states=sorted(getattr(known, "states", []) or []) or None,
|
||||
told_commit=self._last_commit(known))
|
||||
load_states=sorted(getattr(known, "states", []) or []) or None)
|
||||
viewport = self.viewport_size
|
||||
# `pageNumber` is ours, not Playwright's: the number the page's
|
||||
# rhythms are drawn under (`pointer.py` and the actions' nonce read it
|
||||
@@ -2997,21 +2961,13 @@ class PageDispatcher(Dispatcher):
|
||||
def announce(self, context: "BrowserContextDispatcher", replay: bool) -> None:
|
||||
"""Tell the client of the page (the context's `page` event) and, for a popup, say again the load states it reached before:
|
||||
under one lock, so a state said live in between waits for the ones that came first."""
|
||||
# ⛔ NOT A PAGE THAT WAS CLOSED BEFORE ITS ANNOUNCEMENT (the context or the browser closed while it was being adopted): the close
|
||||
# has sent `close` and `__dispose__` for its guid, and a `page` event that names it makes the client throw. The close's lock first,
|
||||
# as in `_deliver`: the close is either over (nothing is announced) or waits for the announcement (and follows it).
|
||||
with self._close_lock, self._announce_lock:
|
||||
if self._announced_closed:
|
||||
self._announced = True
|
||||
self._said_before_announcement = []
|
||||
return
|
||||
with self._announce_lock:
|
||||
context.emit("page", {"page": self.channel})
|
||||
earlier, self._said_before_announcement = self._said_before_announcement, []
|
||||
self._announced = True
|
||||
if replay:
|
||||
for frame, params in earlier:
|
||||
if not frame.detached:
|
||||
frame.told_states.discard(params["add"]) # said again on purpose: the emit would call it a duplicate
|
||||
frame.emit("loadstate", params)
|
||||
|
||||
def settle_events(self) -> None:
|
||||
@@ -3037,17 +2993,12 @@ class PageDispatcher(Dispatcher):
|
||||
their page prints nothing.
|
||||
"""
|
||||
# ⛔ Registered on the connection's list, never chained, and already
|
||||
# in `__init__`: what is left here is to stop holding. EVERY event held
|
||||
# is delivered, of whatever kind, in the order it arrived: a `console`
|
||||
# message, a `pageError`, a `dialog` (an `alert()` blocks the page until
|
||||
# the client accepts it, and a client never told of it cannot), a
|
||||
# `crash`, a load state, a request. (Until 0.51.1 only the `Network.*`
|
||||
# ones were, and the rest were dropped.) The ones this handler does not
|
||||
# read - `Page.frameAttached` and the other events the lifecycle owns -
|
||||
# reach nothing here, and the lifecycle's own announcements are
|
||||
# reconciled below. A live event waits for the held ones and keeps
|
||||
# their order: a response handled before its request is dropped as
|
||||
# unknown.
|
||||
# in `__init__`: what is left here is to stop holding. Only the NETWORK
|
||||
# events held are delivered - the rest describe the page's birth,
|
||||
# which the initializer already carries, and replaying a main frame's
|
||||
# `frameAttached` would announce it twice. Delivered under the lock, so
|
||||
# a live event waits for the held ones and keeps their order: a
|
||||
# response handled before its request is dropped as unknown.
|
||||
#
|
||||
# ⛔ AND EACH EVENT ONCE, AT ITS LAST PLACE. One that arrived after the
|
||||
# subscriber was registered but before the replay marked the session
|
||||
@@ -3055,52 +3006,15 @@ class PageDispatcher(Dispatcher):
|
||||
# hands it over a second time, behind events older than it. It is the
|
||||
# same params object both times; keeping its last occurrence restores
|
||||
# the order the engine sent them in and announces each request once.
|
||||
#
|
||||
# ⛔ THE HOLD ENDS WHEN IT IS EMPTY, NOT WHEN IT IS TAKEN. The held events are delivered in rounds, outside the lock, and
|
||||
# `_held` is cleared only by a round that finds nothing: while a round is being delivered, a live event from the reader still
|
||||
# goes to the hold and waits for its turn. (Clearing it first, a live event went straight to its handler beside the round,
|
||||
# and a response could be handled before the request it answers.)
|
||||
delivered: Dict[int, Any] = {} # the params objects already delivered, kept alive so their ids are not reused
|
||||
|
||||
def give_back(held: List) -> None:
|
||||
with self._held_lock:
|
||||
held, self._held = self._held or [], None
|
||||
last = {id(params): i for i, (_, params) in enumerate(held)}
|
||||
for i, (method, params) in enumerate(held):
|
||||
if last[id(params)] == i and id(params) not in delivered:
|
||||
delivered[id(params)] = params
|
||||
if last[id(params)] == i and method.startswith("Network."):
|
||||
try:
|
||||
self._deliver(method, params)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# A round ends when the reader is quiet. After FOUR rounds the rest is given back with the lock held (the old way): a page
|
||||
# that prints in a tight loop while it is born cannot keep the hold open for ever. The handlers do not wait for the reader, so
|
||||
# the lock is only a delay for it.
|
||||
for _ in range(4):
|
||||
with self._held_lock:
|
||||
held = self._held
|
||||
if not held:
|
||||
self._held = None
|
||||
break
|
||||
self._held = []
|
||||
give_back(held)
|
||||
else:
|
||||
with self._held_lock:
|
||||
while self._held:
|
||||
held, self._held = self._held, []
|
||||
give_back(held)
|
||||
self._held = None
|
||||
if self._held_dropped:
|
||||
warnings.warn(
|
||||
"invisible_playwright: %d event(s) of the page of target %s were lost while it was handed over to its dispatcher: more than "
|
||||
"%d were held (the cap that bounds the memory of a page that never finishes building)"
|
||||
% (self._held_dropped, self.target_id, self.HELD_CAP), RuntimeWarning, stacklevel=2)
|
||||
# ⛔ THE HAND-OVER IS ONE STEP, UNDER THE LIFECYCLE'S LOCK (`_hear_lifecycle`). What the client is told of a frame comes from two
|
||||
# places: the initializer, a snapshot of what the lifecycle knew when the frame dispatcher was made, and the lifecycle's own
|
||||
# announcements through a hook installed here. An event the lifecycle heard AFTER the snapshot and BEFORE the hook was told to
|
||||
# nobody - the commit of a popup's destination left its frame at `about:blank` for good - and the `DOMContentLoaded`/`load` held
|
||||
# at the same time were dropped with every held event that is not a `Network.*` one. Now the hook goes in and what the client was
|
||||
# not told is said in the same step, with the lock held: an event the lifecycle has heard is compared with what the client was
|
||||
# told, and the difference is said; one it has not heard yet waits for the lock and is announced by the hook.
|
||||
self._hear_lifecycle()
|
||||
|
||||
def _hear_lifecycle(self) -> None:
|
||||
@@ -3114,76 +3028,8 @@ class PageDispatcher(Dispatcher):
|
||||
`expect_navigation(wait_until="networkidle")` - which wait for exactly
|
||||
that event - timed out on a loaded, silent page. One definition, two
|
||||
consumers: `goto`'s wait and this event.
|
||||
|
||||
The hook is installed and the frames are reconciled with what the client was told in the same step, with the lifecycle's lock held
|
||||
(not while the held events are delivered: their handlers may ask the engine, and the reader thread that answers needs the lock).
|
||||
"""
|
||||
with self.lifecycle._cv:
|
||||
# ⛔ NOT ON A PAGE THAT CLOSED IN THE MEANTIME. The close detaches the lifecycle (no hook) and tells the client the page is gone
|
||||
# (`__dispose__`); the flag is set under the close's lock before it waits for this one. A hook put back now, and a frame
|
||||
# made under a page the client has dropped, is a `__create__` under a parent that no longer exists.
|
||||
if self._announced_closed:
|
||||
return
|
||||
self.lifecycle.announce = self._on_lifecycle
|
||||
self._reconcile_frames()
|
||||
|
||||
@staticmethod
|
||||
def _last_commit(known: Any) -> Any:
|
||||
"""The place in the engine's stream of the last document the lifecycle holds for this frame (None: none with an id)."""
|
||||
commits = getattr(known, "_commits", None)
|
||||
return commits[-1][0] if commits else None
|
||||
|
||||
CANON_STATES = ("commit", "domcontentloaded", "load", "networkidle")
|
||||
|
||||
def _forget_said_before_announcement(self, frame: "FrameDispatcher") -> None:
|
||||
"""The load states a frame said before the page was announced belong to the document it had then: a commit drops them."""
|
||||
with self._announce_lock:
|
||||
if not self._announced:
|
||||
self._said_before_announcement = [e for e in self._said_before_announcement if e[0] is not frame]
|
||||
|
||||
def _reconcile_frames(self) -> None:
|
||||
"""Say to the client what the lifecycle heard between the snapshot of the initializer and the hook: the frames born or gone, the
|
||||
document a frame committed, the load states it reached. Under the lifecycle's lock."""
|
||||
lifecycle = self.lifecycle
|
||||
if self._announced_closed:
|
||||
return
|
||||
for frame_id in list(self._frames):
|
||||
if frame_id not in lifecycle.frames:
|
||||
child = self._frames.pop(frame_id, None)
|
||||
if frame_id in self._told_attached:
|
||||
self._told_attached.discard(frame_id)
|
||||
self.emit("frameDetached", {"frame": child.channel})
|
||||
child.detach()
|
||||
for frame_id in sorted(lifecycle.frames, key=lifecycle._depth):
|
||||
if frame_id == self.frame.frame_id:
|
||||
continue
|
||||
child = self.frame_for(frame_id)
|
||||
if frame_id not in self._told_attached:
|
||||
self._told_attached.add(frame_id)
|
||||
self.emit("frameAttached", {"frame": child.channel})
|
||||
for frame_id, known in list(lifecycle.frames.items()):
|
||||
frame = self.frame if frame_id == self.frame.frame_id else self._frames.get(frame_id)
|
||||
if frame is not None:
|
||||
self._reconcile_frame(frame, known)
|
||||
|
||||
def _reconcile_frame(self, frame: "FrameDispatcher", known: Any) -> None:
|
||||
url, name = known.url or "", known.name or ""
|
||||
commit = self._last_commit(known)
|
||||
# A document the client was not told: a different address or name, or the same ones with another commit (a reload, a
|
||||
# navigation to the same address, between the snapshot and the hook).
|
||||
if url and ((url, name) != (frame.url, frame.name) or commit != frame.told_commit): # no address yet: nothing committed
|
||||
# what a commit says (`_on_lifecycle`), once
|
||||
self._forget_said_before_announcement(frame)
|
||||
for state in self.CANON_STATES:
|
||||
frame.emit("loadstate", {"remove": state})
|
||||
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)})
|
||||
for state in self.CANON_STATES:
|
||||
if state in known.states and state not in frame.told_states:
|
||||
frame.emit("loadstate", {"add": state})
|
||||
elif state not in known.states and state in frame.told_states and state != "commit":
|
||||
frame.emit("loadstate", {"remove": state})
|
||||
self.lifecycle.announce = self._on_lifecycle
|
||||
|
||||
def _on_lifecycle(self, what: str, frame_id: str,
|
||||
url: Optional[str] = None, *, name: str = "",
|
||||
@@ -3198,7 +3044,6 @@ class PageDispatcher(Dispatcher):
|
||||
# `page.frames` held eight entries for two frames (2026-10-12).
|
||||
if what == "frameDetached":
|
||||
child = self._frames.pop(frame_id, None)
|
||||
self._told_attached.discard(frame_id)
|
||||
if child is not None:
|
||||
self.emit("frameDetached", {"frame": child.channel})
|
||||
child.detach()
|
||||
@@ -3208,7 +3053,6 @@ class PageDispatcher(Dispatcher):
|
||||
# the first time, and this page is built after its main frame was
|
||||
# seen (`wait_for_main_frame`); the initializer carries it.
|
||||
child = self.frame_for(frame_id)
|
||||
self._told_attached.add(frame_id)
|
||||
self.emit("frameAttached", {"frame": child.channel})
|
||||
return
|
||||
child = self.frame_for(frame_id)
|
||||
@@ -3249,10 +3093,8 @@ class PageDispatcher(Dispatcher):
|
||||
# the page is closed: `_deliver` would not have delivered it.
|
||||
if self._announced_closed:
|
||||
return
|
||||
self._forget_said_before_announcement(child)
|
||||
for state in ("commit", "domcontentloaded", "load", "networkidle"):
|
||||
child.emit("loadstate", {"remove": state})
|
||||
child.told_commit = self._last_commit(self.lifecycle.frame(frame_id))
|
||||
child.url = url or ""
|
||||
child.name = name or ""
|
||||
child.emit("navigated", {
|
||||
@@ -3264,9 +3106,7 @@ class PageDispatcher(Dispatcher):
|
||||
|
||||
#: 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
|
||||
#: grow this without bound. The ones beyond the cap are lost, and not in
|
||||
#: silence: they are counted and said once, with the count, when the
|
||||
#: hold ends (`_install_events`).
|
||||
#: grow this without bound.
|
||||
HELD_CAP = 512
|
||||
|
||||
def _route_juggler_event(self, method: str, params: Dict,
|
||||
@@ -3278,8 +3118,6 @@ class PageDispatcher(Dispatcher):
|
||||
if self._held is not None:
|
||||
if len(self._held) < self.HELD_CAP:
|
||||
self._held.append((method, params))
|
||||
else:
|
||||
self._held_dropped += 1
|
||||
return
|
||||
self._deliver(method, params)
|
||||
|
||||
@@ -3324,62 +3162,29 @@ class PageDispatcher(Dispatcher):
|
||||
# that is about to go. The engine stops it when the page is disposed
|
||||
# too; asking first means a page closed from here never leaves a
|
||||
# frame in flight with nobody to acknowledge it.
|
||||
with self._screencast_lock:
|
||||
running = self._screencast_id
|
||||
self._screencast_id = None
|
||||
self._screencast_early = None
|
||||
if running:
|
||||
if self._screencast_id:
|
||||
conn.post("Page.stopScreencast", {}, session=self.session)
|
||||
|
||||
def _on_screencast_frame(self, params: Dict) -> None:
|
||||
"""One `Page.screencastFrame`: up to the client, and acknowledged.
|
||||
|
||||
⛔ ON THE READER THREAD, and both halves have to respect that.
|
||||
The frame goes up to the client as the event `Screencast`
|
||||
listens for - base64 stays base64, the client decodes - under
|
||||
the names the vendored client reads (`viewportWidth`, not the
|
||||
engine's `deviceWidth`). The ack goes back with `post`: a `send`
|
||||
here would wait for a reply only this thread can deliver.
|
||||
|
||||
⛔ A FRAME THAT ARRIVES BEFORE `op_screencast_start` KNOWS THE ID IS
|
||||
HELD, NOT DROPPED. The engine keeps one frame in flight until it is
|
||||
acknowledged (`kMaxFramesInFlight` is 1, and its heartbeat only
|
||||
repeats a frame when none is in flight), so a frame this thread drops
|
||||
without an ack is the last frame of the stream: no error, no more
|
||||
frames, `start()` having returned. And it was not a theory: the reader
|
||||
wakes the caller on the start's reply and goes straight on to the next
|
||||
message, so a frame behind the reply is handled before the caller has
|
||||
stored the id - 84 of 200 start cycles stalled that way in
|
||||
`tests/test_screencast_ack_race.py` with the frame right behind the
|
||||
reply. The newest such frame is kept (a second cannot exist: the
|
||||
first is unacknowledged) and `op_screencast_start` hands it on once
|
||||
the id is in.
|
||||
"""
|
||||
with self._screencast_lock:
|
||||
screencast_id = self._screencast_id
|
||||
if not screencast_id:
|
||||
if self._screencast_starting:
|
||||
self._screencast_early = params
|
||||
return
|
||||
self._hand_up_screencast_frame(screencast_id, params)
|
||||
|
||||
def _hand_up_screencast_frame(self, screencast_id: str, params: Dict) -> None:
|
||||
# The id is the one the frame was accepted under, read once: a stop
|
||||
# between the check and the ack must not turn the ack into one for
|
||||
# "None".
|
||||
self.emit("screencastFrame", {
|
||||
"data": params.get("data") or "",
|
||||
"timestamp": params.get("timestamp") or 0,
|
||||
"viewportWidth": params.get("deviceWidth") or 0,
|
||||
"viewportHeight": params.get("deviceHeight") or 0,
|
||||
})
|
||||
self.conn.post("Page.screencastFrameAck",
|
||||
{"screencastId": screencast_id},
|
||||
session=self.session)
|
||||
self._screencast_id = None
|
||||
|
||||
def _on_juggler_event(self, method: str, params: Dict) -> None:
|
||||
if method == "Page.screencastFrame":
|
||||
self._on_screencast_frame(params)
|
||||
# ⛔ ON THE READER THREAD, and both halves have to respect that.
|
||||
# The frame goes up to the client as the event `Screencast`
|
||||
# listens for - base64 stays base64, the client decodes - under
|
||||
# the names the vendored client reads (`viewportWidth`, not the
|
||||
# engine's `deviceWidth`). The ack goes back with `post`: a `send`
|
||||
# here would wait for a reply only this thread can deliver.
|
||||
if not self._screencast_id:
|
||||
return
|
||||
self.emit("screencastFrame", {
|
||||
"data": params.get("data") or "",
|
||||
"timestamp": params.get("timestamp") or 0,
|
||||
"viewportWidth": params.get("deviceWidth") or 0,
|
||||
"viewportHeight": params.get("deviceHeight") or 0,
|
||||
})
|
||||
self.conn.post("Page.screencastFrameAck",
|
||||
{"screencastId": self._screencast_id},
|
||||
session=self.session)
|
||||
elif method == "Runtime.console":
|
||||
# ⛔ THE LOG FILLS HERE, not inside `console_messages()`. A log
|
||||
# filled on request can only ever hold what arrived AFTER the
|
||||
@@ -3440,10 +3245,9 @@ class PageDispatcher(Dispatcher):
|
||||
# is a command whose answer only that same read loop can deliver.
|
||||
# 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`).
|
||||
self.context.browser.thread_starter.start(
|
||||
target=self._announce_file_chooser, args=(params,))
|
||||
threading.Thread(
|
||||
target=self._announce_file_chooser, args=(params,),
|
||||
daemon=True).start()
|
||||
elif method == "Page.crashed":
|
||||
self.emit("crash")
|
||||
# ⛔ `Page.frameAttached` / `Page.frameDetached` ARE NOT READ HERE: the
|
||||
@@ -3634,24 +3438,18 @@ class PageDispatcher(Dispatcher):
|
||||
"""
|
||||
if frame_id == self.frame.frame_id:
|
||||
return self.frame
|
||||
# ⛔ CHECK AND CREATE IN ONE STEP. The reader thread (a held `eventFired` of a child, a frame the lifecycle announces) and the
|
||||
# adoption thread (the reconciliation of the hand-over) both come here for a frame that is new: without the lock each saw
|
||||
# no dispatcher and made one, two `__create__` for one frame, and the load states went to one of them. Recursive: the parent
|
||||
# is made by the same call.
|
||||
with self._frames_lock:
|
||||
existing = self._frames.get(frame_id)
|
||||
if existing is not None and not existing.disposed:
|
||||
return existing
|
||||
frame = self.lifecycle.frame(frame_id)
|
||||
parent_id = getattr(frame, "parent", None)
|
||||
made = FrameDispatcher(
|
||||
self.server, self, frame_id,
|
||||
url=getattr(frame, "url", "") or "",
|
||||
parent_frame=self.frame_for(parent_id) if parent_id else None,
|
||||
load_states=sorted(getattr(frame, "states", []) or []) or ["commit"],
|
||||
told_commit=self._last_commit(frame))
|
||||
self._frames[frame_id] = made
|
||||
return made
|
||||
existing = self._frames.get(frame_id)
|
||||
if existing is not None and not existing.disposed:
|
||||
return existing
|
||||
frame = self.lifecycle.frame(frame_id)
|
||||
parent_id = getattr(frame, "parent", None)
|
||||
made = FrameDispatcher(
|
||||
self.server, self, frame_id,
|
||||
url=getattr(frame, "url", "") or "",
|
||||
parent_frame=self.frame_for(parent_id) if parent_id else None,
|
||||
load_states=sorted(getattr(frame, "states", []) or []) or ["commit"])
|
||||
self._frames[frame_id] = made
|
||||
return made
|
||||
|
||||
def op_set_interception(self, params: Dict) -> Any:
|
||||
"""`page.route()`: hold this page's requests until a handler answers.
|
||||
@@ -4198,10 +3996,9 @@ class PageDispatcher(Dispatcher):
|
||||
rebuilt - and the refusal at context creation for `record_video_dir`
|
||||
is the same decision one level up.
|
||||
"""
|
||||
with self._screencast_lock:
|
||||
if self._screencast_id or self._screencast_starting:
|
||||
raise ProtocolException(
|
||||
"a screencast is already running on this page; stop it first")
|
||||
if self._screencast_id:
|
||||
raise ProtocolException(
|
||||
"a screencast is already running on this page; stop it first")
|
||||
if params.get("record"):
|
||||
raise ProtocolException(
|
||||
"screencast to a video FILE is not available: the engine "
|
||||
@@ -4225,47 +4022,22 @@ class PageDispatcher(Dispatcher):
|
||||
fps = params.get("fps")
|
||||
if fps is None:
|
||||
fps = self.SCREENCAST_FPS
|
||||
# ⛔ FROM HERE UNTIL THE ID IS STORED A FRAME CAN ARRIVE, and the
|
||||
# handler needs to know it is a start in progress and not a stopped
|
||||
# screencast (`_on_screencast_frame`). Claimed under the lock, so two
|
||||
# starts cannot both pass the check above either.
|
||||
with self._screencast_lock:
|
||||
if self._screencast_id or self._screencast_starting:
|
||||
raise ProtocolException(
|
||||
"a screencast is already running on this page; stop it first")
|
||||
self._screencast_starting = True
|
||||
self._screencast_early = None
|
||||
try:
|
||||
result = self.send("Page.startScreencast", {
|
||||
"width": int(size["width"]),
|
||||
"height": int(size["height"]),
|
||||
"quality": int(quality),
|
||||
"fullWindow": True,
|
||||
"fps": int(fps),
|
||||
})
|
||||
screencast_id = result["screencastId"]
|
||||
except BaseException:
|
||||
with self._screencast_lock:
|
||||
self._screencast_starting = False
|
||||
self._screencast_early = None
|
||||
raise
|
||||
with self._screencast_lock:
|
||||
self._screencast_id = screencast_id
|
||||
self._screencast_starting = False
|
||||
early, self._screencast_early = self._screencast_early, None
|
||||
if early is not None:
|
||||
self._hand_up_screencast_frame(screencast_id, early)
|
||||
result = self.send("Page.startScreencast", {
|
||||
"width": int(size["width"]),
|
||||
"height": int(size["height"]),
|
||||
"quality": int(quality),
|
||||
"fullWindow": True,
|
||||
"fps": int(fps),
|
||||
})
|
||||
self._screencast_id = result["screencastId"]
|
||||
# The client's `start()` reads an optional `artifact` from the reply
|
||||
# for the video-file case, which does not exist here.
|
||||
return {}
|
||||
|
||||
def op_screencast_stop(self, params: Dict) -> Any:
|
||||
with self._screencast_lock:
|
||||
running = self._screencast_id
|
||||
self._screencast_id = None
|
||||
self._screencast_early = None
|
||||
if not running:
|
||||
if not self._screencast_id:
|
||||
return None
|
||||
self._screencast_id = None
|
||||
self.send("Page.stopScreencast", {})
|
||||
return None
|
||||
|
||||
@@ -4830,61 +4602,11 @@ 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",
|
||||
"newPage": "op_new_page"}
|
||||
|
||||
#: How long the engine's reader waits for the gate of the events before it delivers the event anyway (see `events_gate`).
|
||||
GATE_WAIT_S = 5.0
|
||||
#: How long a page that is being built waits for the gate before it is built without it.
|
||||
PAGE_GATE_WAIT_S = 30.0
|
||||
|
||||
def __init__(self, server, browser_type: "BrowserTypeDispatcher",
|
||||
conn: Any, version: str, session_seed: Any = None,
|
||||
motion_budget_s: Any = None,
|
||||
@@ -4892,58 +4614,6 @@ class BrowserDispatcher(Dispatcher):
|
||||
layout: str = "us", pointer_draws: bool = False,
|
||||
udp_stun_servers: Optional[list] = None) -> None:
|
||||
self.conn = conn
|
||||
# ⛔ THE EVENTS OF A SESSION GO THROUGH A GATE. A new page is handed the events it missed (`replay`) by the thread that builds it,
|
||||
# while the engine's reader goes on delivering the live ones to the same subscribers: a popup's destination committed (live) in the
|
||||
# middle of the replay of its first events, and the replay then went on with older ones (the initial about:blank, the
|
||||
# `navigationStarted` of the same navigation) - the lifecycle ended at about:blank, or with the navigation pending again. The
|
||||
# reader takes the gate for each event of a session; the page takes it for the whole of "subscribe, then replay" (`events_gate`).
|
||||
# The gate belongs to the CONNECTION (one wrapper, one gate, whoever builds a dispatcher over it).
|
||||
gate = getattr(conn, "_events_gate", None)
|
||||
if gate is None:
|
||||
gate = threading.RLock()
|
||||
try:
|
||||
conn._events_gate = gate
|
||||
except Exception:
|
||||
pass
|
||||
self._events_gate = gate
|
||||
self._gate_timeouts = 0
|
||||
if not getattr(conn, "_events_gate_installed", False):
|
||||
#: The delivery the reader would have made: an override on the instance if there is one, else the class's method looked up
|
||||
#: at each event (a patch of the class made after this dispatcher was built still applies).
|
||||
own = conn.__dict__.get("dispatch_event")
|
||||
stuck = {"until": 0.0}
|
||||
owner = self
|
||||
|
||||
def raw_dispatch(method, params, session):
|
||||
if own is not None:
|
||||
return own(method, params, session)
|
||||
return type(conn).dispatch_event(conn, method, params, session)
|
||||
|
||||
def gated_dispatch(method, params, session):
|
||||
if not session:
|
||||
return raw_dispatch(method, params, session)
|
||||
waiting = time.monotonic() >= stuck["until"]
|
||||
got = gate.acquire(timeout=owner.GATE_WAIT_S) if waiting else gate.acquire(blocking=False)
|
||||
if got:
|
||||
try:
|
||||
return raw_dispatch(method, params, session)
|
||||
finally:
|
||||
gate.release()
|
||||
# ⛔ WHOEVER HOLDS THE GATE DOES NOT LET GO: the event is delivered all the same (the old, unordered way), and the reader does
|
||||
# not wait again for a while (the bound is on the hold, not on each event). Said once per hold, where the connection records
|
||||
# what its handlers failed at.
|
||||
if waiting:
|
||||
stuck["until"] = time.monotonic() + 30.0
|
||||
owner._gate_timeouts += 1
|
||||
errors = getattr(conn, "handler_errors", None)
|
||||
if isinstance(errors, list) and len(errors) < 32:
|
||||
errors.append("events gate: held more than %.1fs, events delivered ungated for 30s" % owner.GATE_WAIT_S)
|
||||
return raw_dispatch(method, params, session)
|
||||
conn.dispatch_event = gated_dispatch
|
||||
try:
|
||||
conn._events_gate_installed = True
|
||||
except Exception:
|
||||
pass
|
||||
#: 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
|
||||
@@ -5063,9 +4733,6 @@ 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.
|
||||
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
|
||||
# caller's `launch(timeout=)` (`Connection.startup_send`), not a
|
||||
@@ -5089,11 +4756,6 @@ class BrowserDispatcher(Dispatcher):
|
||||
# the target map): recorded for its session, never built into a page.
|
||||
self._adopt_enabled = True
|
||||
|
||||
@property
|
||||
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:
|
||||
"""Refuse a route this browser cannot honour, instead of ignoring it.
|
||||
|
||||
@@ -5207,22 +4869,6 @@ class BrowserDispatcher(Dispatcher):
|
||||
if len(held) < self.BUFFER_CAP:
|
||||
held.append((method, params))
|
||||
|
||||
@contextlib.contextmanager
|
||||
def events_gate(self):
|
||||
"""Hold the delivery of the events of every session: the engine's reader waits (at most `GATE_WAIT_S`) at its next event of a
|
||||
session. For a short step that waits for no event and no reply: a page subscribes its readers and is handed the events it missed."""
|
||||
got = self._events_gate.acquire(timeout=self.PAGE_GATE_WAIT_S)
|
||||
if not got:
|
||||
# the reader is stuck inside a handler: the page is built all the same (the old, unordered way), and it is said
|
||||
warnings.warn("invisible_playwright: the engine's events were held for more than %.0f s by a handler; a page is built without "
|
||||
"the gate of the events (its replay may be overtaken by a live event)" % self.PAGE_GATE_WAIT_S,
|
||||
RuntimeWarning, stacklevel=3)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
if got:
|
||||
self._events_gate.release()
|
||||
|
||||
def replay(self, session: str, deliver) -> int:
|
||||
"""Hand a new consumer the events of its session that it missed.
|
||||
|
||||
@@ -5295,10 +4941,11 @@ class BrowserDispatcher(Dispatcher):
|
||||
else:
|
||||
self._strays += 1
|
||||
number = popup_number(None, self._strays)
|
||||
self._starter.start(
|
||||
thread = threading.Thread(
|
||||
target=self._adopt_target,
|
||||
args=(target_id, session_id, browser_context_id, opener, number),
|
||||
name="invpw-adopt-%s" % target_id[:8])
|
||||
daemon=True, name="invpw-adopt-%s" % target_id[:8])
|
||||
thread.start()
|
||||
|
||||
# ── the states of an adoption: the ONLY places a record changes state. Each is one method so that a test can stop the adoption thread
|
||||
# between any two of them and deliver an event of the engine there.
|
||||
|
||||
@@ -1,69 +0,0 @@
|
||||
"""The check that no test module leaves a browser open.
|
||||
|
||||
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 threading
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
STARTER_NAME = "invpw-thread-starter"
|
||||
# `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():
|
||||
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 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)
|
||||
for t in starters_alive():
|
||||
t.join(0.05)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", autouse=True)
|
||||
def _a_module_leaves_no_browser_open(request):
|
||||
before = len(starters_alive())
|
||||
yield
|
||||
left = wait_until_back_to(before)
|
||||
if left:
|
||||
pytest.fail(
|
||||
"%s left %d browser(s) open: close their connection (fire its close listeners) or shut the server down, in a "
|
||||
"finally or a fixture teardown. Each one keeps a thread named %r alive, and with it the connection, the browser "
|
||||
"and every context, for the rest of the worker." % (request.module.__name__, left, STARTER_NAME),
|
||||
pytrace=False,
|
||||
)
|
||||
|
||||
|
||||
_made = []
|
||||
|
||||
|
||||
def closes_with_the_test(connection):
|
||||
"""Register a fake connection a test builds: when the test ends it is closed the way a real one ends, `announce_closed()`, which fires
|
||||
its close listeners (a `BrowserDispatcher` registered `_starter.stop` on them). Returns the connection, so it goes inline:
|
||||
`conn = closes_with_the_test(Engine())`, or from the `__init__` of a fake class so that every instance is covered.
|
||||
|
||||
Nothing intercepts the starter: a test that builds a browser on a connection it did not register still leaves the thread open, and the
|
||||
module check above says so.
|
||||
"""
|
||||
_made.append(connection)
|
||||
return connection
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _the_connections_a_test_made_are_closed_with_it():
|
||||
yield
|
||||
made, _made[:] = list(_made), []
|
||||
for connection in reversed(made):
|
||||
connection.announce_closed()
|
||||
@@ -265,12 +265,6 @@ class FakeDoh:
|
||||
self._closed = False
|
||||
threading.Thread(target=self._accept, daemon=True).start()
|
||||
|
||||
def use_certificate(self, certificate: Path, key: Path) -> None:
|
||||
"""Serve this certificate from now on (new connections): a test whose session must TRUST the DoH by its profile, not through
|
||||
``ignore_https_errors`` (which would also switch off the check the test is about), has a CA of its own sign it."""
|
||||
self._context.load_cert_chain(str(certificate), str(key))
|
||||
self.certificate_path, self._key_path = Path(certificate), Path(key)
|
||||
|
||||
# --- what a test reads ------------------------------------------------------------------------------------
|
||||
def queries_for(self, name: str, qtype: Optional[int] = None) -> List[DohQuery]:
|
||||
name = name.lower().rstrip(".")
|
||||
@@ -286,19 +280,6 @@ class FakeDoh:
|
||||
with self._lock:
|
||||
return [a for a in self.answers if a.name == name and (qtype is None or a.qtype == qtype)]
|
||||
|
||||
def certificate_refusals(self) -> List[Tuple[str, str]]:
|
||||
"""The failed handshakes in which the client REFUSED the certificate: a TLS alert (unknown CA, bad certificate...).
|
||||
|
||||
Not every failed handshake is one. A client that drops a connection before the handshake ends (a speculative or a
|
||||
duplicate DoH connection the browser abandons) fails it too, and says nothing about the certificate: on Windows as
|
||||
ConnectionAbortedError [WinError 10053], elsewhere as a reset or an end of file. Only a refusal means that a lookup
|
||||
of a context without the certificate exception reached the DoH. Windows census of 12/11 (run 43333574229): a
|
||||
ConnectionAbortedError through the gateway of a context that HAS the exception was read as such a lookup.
|
||||
"""
|
||||
with self._lock:
|
||||
return [(via, error) for via, error in self.tls_failures
|
||||
if "ALERT" in error.upper() or "CERTIFICATE" in error.upper()]
|
||||
|
||||
def seen_names(self) -> List[str]:
|
||||
with self._lock:
|
||||
return sorted({q.name for q in self.queries})
|
||||
|
||||
@@ -1,162 +0,0 @@
|
||||
"""The sink of "nothing of a context leaves but through its proxy": what a test reads to know that a request went AROUND the proxy (no pytest in here).
|
||||
|
||||
A context with a proxy and a session with none: the default context is then the machine's own network, so "everything that leaves" cannot be
|
||||
judged (the browser's own background resolves and connects there, and may). What a test judges is what ITS probe made the browser do: every
|
||||
name of a probe carries a nonce (``fetch-name-3fa91c.test``) and every address a probe uses is the one of a WITNESS no proxy of the test
|
||||
forwards to (the gateways refuse a CONNECT past loopback and relay no datagram), so whatever arrives at the witness arrived direct. The sink
|
||||
has four parts, each of which a test proves is not blind:
|
||||
|
||||
* the WITNESS (``_witness.Witness``) at an address of this host: a TCP connection or a datagram that reaches it came from the browser, direct;
|
||||
* the WATCHER (``_leaks.Watcher``): a connection of a browser process to that address, seen in ``/proc`` or the connection table;
|
||||
* the NATIVE LOOKUPS of the probe's names: ``native_lookup_names`` is the ONE function a test calls. On Linux and on Windows alike it is the
|
||||
engine's own log (``nsHostResolver.cpp`` writes ``DNS resolve task - Calling getaddrinfo for host [<name>]`` before every native lookup; on
|
||||
Windows that is the call into the system resolver too) and, where the resolver trap runs (Linux, root), the trap's questions. The lines are
|
||||
in the PARENT process's file (``moz--main.<pid>.log.moz_log``); the child files are empty, under the sandbox of both systems (measured on a
|
||||
runner of each, run 43574494194). A log that holds no resolver start is blind and ``native_lookup_names`` raises ``BlindSink``: it never
|
||||
answers "nothing" for a sink that cannot see;
|
||||
* the LOOKUPS IN USER CONTEXT 0: the same log says in which context each name was asked (``Resolving host [<name>]<^userContextId=N>``): a
|
||||
probe name asked with no ``userContextId`` is a lookup that lost the context of its page, whichever road it then took.
|
||||
|
||||
The log is the engine's, not a hook of the test: ``MOZ_LOG=sync,nsHostResolver:5`` and ``MOZ_LOG_FILE=<dir>/moz-%PID.log`` give one file per
|
||||
process (``moz-<pid>.log`` and ``moz-<pid>.log.child-<n>``), as ``test_the_hosts_file_of_the_host_is_never_read_e2e.py`` reads it.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import glob
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import sys
|
||||
from typing import Callable, Dict, Iterable, List, Optional, Sequence
|
||||
|
||||
MOZ_LOG = "sync,nsHostResolver:5"
|
||||
LOG_FILE_NAME = "moz-%PID.log"
|
||||
|
||||
_NATIVE = re.compile(r"Calling getaddrinfo for host \[([^\]]+)\]")
|
||||
_RESOLVING = re.compile(r"Resolving host \[([^\]]+)\]<([^>]*)>")
|
||||
_STARTED = "nsHostResolver::Init"
|
||||
|
||||
|
||||
def new_nonce() -> str:
|
||||
"""Six hex digits: unique in a run, and a legal label."""
|
||||
return secrets.token_hex(3)
|
||||
|
||||
|
||||
def log_files(directory) -> List[str]:
|
||||
return sorted(glob.glob(os.path.join(str(directory), "moz-*.log*")))
|
||||
|
||||
|
||||
def _lines(directory) -> Iterable[str]:
|
||||
for path in log_files(directory):
|
||||
with open(path, "rb") as handle:
|
||||
for raw in handle:
|
||||
yield raw.decode("utf-8", "replace")
|
||||
|
||||
|
||||
def engine_log_native_lookups(directory, nonce: Optional[str] = None) -> List[str]:
|
||||
"""The names the engine looked up with the machine's resolver (``getaddrinfo``), in the order it did, only those with ``nonce`` when given."""
|
||||
out = []
|
||||
for line in _lines(directory):
|
||||
found = _NATIVE.search(line)
|
||||
if found and (nonce is None or nonce in found.group(1)):
|
||||
out.append(found.group(1))
|
||||
return out
|
||||
|
||||
|
||||
def engine_log_context_zero_lookups(directory, nonce: Optional[str] = None) -> List[str]:
|
||||
"""The names asked of the resolver in a request with NO user context (user context 0: the suffix has no ``userContextId``)."""
|
||||
out = []
|
||||
for line in _lines(directory):
|
||||
found = _RESOLVING.search(line)
|
||||
if found and "userContextId" not in found.group(2) and (nonce is None or nonce in found.group(1)):
|
||||
out.append(found.group(1))
|
||||
return out
|
||||
|
||||
|
||||
def engine_log_is_alive(directory) -> bool:
|
||||
"""The control of the log sink: some process logged the start of its resolver. A log with no such line says nothing."""
|
||||
return any(_STARTED in line for line in _lines(directory))
|
||||
|
||||
|
||||
class BlindSink(RuntimeError):
|
||||
"""The engine's log cannot say anything: no file, or no process logged the start of its resolver."""
|
||||
|
||||
|
||||
def native_lookup_names(directory, nonce: str, trap=None, platform: Optional[str] = None) -> List[str]:
|
||||
"""Every name with ``nonce`` that the machine's resolver was asked for by the browser: the ONE function every test calls, on every system.
|
||||
|
||||
The engine's log on Linux and on Windows; plus ``trap`` (a ``_leaks.ResolverTrap``, Linux and root) when given. Raises ``BlindSink`` when
|
||||
the log is empty or holds no resolver start. ``platform`` is for the unit test of this function."""
|
||||
platform = platform or sys.platform
|
||||
if not log_files(directory):
|
||||
raise BlindSink("the engine wrote no log in %s: the native-lookup sink is blind" % directory)
|
||||
if not engine_log_is_alive(directory):
|
||||
raise BlindSink("no process of the browser logged the start of its resolver (%r) in %s: the native-lookup sink is blind" % (_STARTED, directory))
|
||||
names = set(engine_log_native_lookups(directory, nonce))
|
||||
if trap is not None and platform.startswith("linux"):
|
||||
names |= {n for n in trap.names() if nonce in n}
|
||||
return sorted(names)
|
||||
|
||||
|
||||
class EgressSink:
|
||||
"""What a probe of one case left behind, and the verdicts the test makes of it.
|
||||
|
||||
``witness`` is the ``_witness.Witness`` of the case, ``watcher`` the ``_leaks.Watcher`` (stopped), ``directory`` the folder of the engine's
|
||||
log, ``nonce`` the one of the probe's names, ``trap`` the resolver trap or None."""
|
||||
|
||||
def __init__(self, witness, watcher, directory, nonce: str, trap=None, native: Callable[..., List[str]] = native_lookup_names):
|
||||
self.witness, self.watcher, self.directory, self.nonce, self.trap = witness, watcher, directory, nonce, trap
|
||||
self._native = native
|
||||
|
||||
def arrivals(self) -> Dict[str, list]:
|
||||
"""Everything the witness heard: nothing is forwarded to it by any proxy of the tests, so each one is a send around the proxy."""
|
||||
return self.witness.heard()
|
||||
|
||||
def direct_connections(self) -> list:
|
||||
return [c for c in self.watcher.direct if c.remote.rsplit(":", 1)[0] == self.witness.address]
|
||||
|
||||
def native_lookups(self) -> List[str]:
|
||||
return self._native(self.directory, self.nonce, self.trap)
|
||||
|
||||
def context_zero_lookups(self) -> List[str]:
|
||||
return engine_log_context_zero_lookups(self.directory, self.nonce)
|
||||
|
||||
def blind_problems(self) -> List[str]:
|
||||
"""The reasons this sink cannot be trusted: a green over a sink that sees nothing proves nothing."""
|
||||
out = []
|
||||
if not self.watcher.watched_pids:
|
||||
out.append("the watcher never saw a browser process (it saw: %s)" % self.watcher.process_names)
|
||||
if not log_files(self.directory):
|
||||
out.append("the engine wrote no log in %s: the native-lookup sink is blind (MOZ_LOG / MOZ_LOG_FILE did not reach it)" % self.directory)
|
||||
elif not engine_log_is_alive(self.directory):
|
||||
out.append("no process of the browser logged the start of its resolver (%r): the native-lookup sink is blind" % _STARTED)
|
||||
return out
|
||||
|
||||
def leak_problems(self) -> List[str]:
|
||||
"""The sentences of every leak the sink saw, empty when the probe stayed home."""
|
||||
out = []
|
||||
heard = self.arrivals()
|
||||
if heard["tcp"] or heard["udp"]:
|
||||
out.append("the witness at %s was reached direct: %d TCP connection(s) from %s, %d datagram(s) from %s"
|
||||
% (self.witness.address, len(heard["tcp"]), sorted({h[0] for h in heard["tcp"]}), len(heard["udp"]),
|
||||
sorted({h[0] for h in heard["udp"]})))
|
||||
seen = self.direct_connections()
|
||||
if seen:
|
||||
out.append("the watcher saw the browser connect to %s without the proxy: %s"
|
||||
% (self.witness.address, "; ".join("%s %s -> %s %s" % (c.process, c.protocol, c.remote, c.status) for c in seen)))
|
||||
try:
|
||||
native = self.native_lookups()
|
||||
except BlindSink as exc:
|
||||
out.append(str(exc))
|
||||
native = []
|
||||
if native:
|
||||
out.append("the machine's resolver was asked for %s (a lookup of a proxied context took the native road)" % native)
|
||||
zero = self.context_zero_lookups()
|
||||
if zero:
|
||||
out.append("%s was looked up in user context 0, not in the context of its page" % sorted(set(zero)))
|
||||
return out
|
||||
|
||||
|
||||
def named_connects(gateway_connects: Sequence, is_address: Callable[[str], bool], allowed_names: Sequence[str] = ()) -> List[tuple]:
|
||||
"""The CONNECTs of a SOCKS5 gateway that carry a NAME (the browser must resolve and connect by address), except ``allowed_names``."""
|
||||
return [(h, p) for h, p in gateway_connects if not is_address(h) and h not in allowed_names]
|
||||
+38
-27
@@ -14,17 +14,15 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import datetime
|
||||
import ipaddress
|
||||
import random
|
||||
import socket
|
||||
import socketserver
|
||||
import ssl
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from typing import List, Tuple
|
||||
|
||||
from _ports import bind_tcp_and_probe_udp
|
||||
|
||||
|
||||
def _certificate(address: str, directory: Path):
|
||||
from cryptography import x509
|
||||
@@ -50,19 +48,44 @@ def _certificate(address: str, directory: Path):
|
||||
#: The one document every path answers, over TCP and over QUIC.
|
||||
PAGE = b"<!doctype html><meta charset=utf-8><title>h3</title><p>ok</p>"
|
||||
|
||||
# How many port numbers are tried, and where the ones after the system's own pick are drawn from: the same as the witness's.
|
||||
from _witness import DRAW_FROM as _WITNESS_DRAW_FROM, TRIES as _WITNESS_TRIES # noqa: E402
|
||||
|
||||
|
||||
class _TcpServer(socketserver.ThreadingTCPServer):
|
||||
# On Windows SO_REUSEADDR is "share the port": with a number the picker drew (tests/_ports.py) it would bind over a listener that is there.
|
||||
allow_reuse_address = sys.platform != "win32"
|
||||
allow_reuse_address = True
|
||||
daemon_threads = True
|
||||
|
||||
|
||||
def _tcp_server_on_a_port_udp_binds(address: str):
|
||||
"""A TCP server on a port number that UDP can bind too, as ``(server, port)``: the one picker of the harness (tests/_ports.py), which the
|
||||
witness and the resolver trap walk the same sequence of. The first try is the system's own pick (port 0); the others are drawn at random
|
||||
below the dynamic range, because Windows hands out ephemeral TCP ports in sequence and keeps excluded ranges of a hundred ports for UDP
|
||||
inside the same zone (run 43230437094, ``wrapper.e2e.web`` on Windows: fifty consecutive picks refused, three tests red). Every refusal is
|
||||
kept with its code and the last three are in the error."""
|
||||
return bind_tcp_and_probe_udp(address, lambda host, number: _TcpServer((host, number), _TcpHandler), socket_module=socket)
|
||||
"""A TCP server on a port number that UDP can bind too, as ``(server, port)``.
|
||||
|
||||
The first try is the system's own pick (port 0); the others are drawn at random below the dynamic range. Windows hands out
|
||||
ephemeral TCP ports in sequence and keeps excluded ranges of a hundred ports for UDP inside the same zone, so asking the
|
||||
system again lands in the same refused range again and again (run 43230437094, ``wrapper.e2e.web`` on Windows: fifty
|
||||
consecutive picks refused, three tests red; the witness had the same defect and the same remedy,
|
||||
``test_the_witness_picks_a_port_both_sockets_bind.py``)."""
|
||||
draw = random.Random()
|
||||
refusals: List[str] = []
|
||||
for attempt in range(_WITNESS_TRIES):
|
||||
wanted = 0 if attempt == 0 else draw.randint(*_WITNESS_DRAW_FROM)
|
||||
try:
|
||||
tcp = _TcpServer((address, wanted), _TcpHandler)
|
||||
except OSError as exc:
|
||||
refusals.append("%s: %s" % (wanted or "system pick", exc))
|
||||
continue
|
||||
port = tcp.server_address[1]
|
||||
probe = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
try:
|
||||
probe.bind((address, port))
|
||||
return tcp, port
|
||||
except OSError as exc:
|
||||
refusals.append("%s: %s" % (port, exc))
|
||||
tcp.server_close()
|
||||
finally:
|
||||
probe.close()
|
||||
raise RuntimeError("no port free for both TCP and UDP on %s after %d tries; the last refusals: %s"
|
||||
% (address, _WITNESS_TRIES, "; ".join(refusals[-3:])))
|
||||
|
||||
|
||||
class _TcpHandler(socketserver.BaseRequestHandler):
|
||||
@@ -212,20 +235,9 @@ class H3Server:
|
||||
self._quic = self._loop.run_until_complete(
|
||||
serve(address, port, configuration=configuration, create_protocol=Protocol))
|
||||
started.set()
|
||||
try:
|
||||
self._loop.run_forever()
|
||||
finally:
|
||||
# ⛔ THE LOOP IS CLOSED HERE, ON ITS OWN THREAD, after the QUIC server. A loop that is only stopped is closed later by
|
||||
# BaseEventLoop.__del__ on whatever thread the garbage collector runs in, and on Windows the proactor's close then
|
||||
# waits for the UDP receive still pending on it, for ever: the HTTP/3 e2e hung inside a later test's goto or
|
||||
# new_page, the test thread in base_events.__del__ -> proactor close -> _poll (Windows hunt of 13/11, run
|
||||
# 43377799126, 3 runs of 15; PR #486 part 1 twice).
|
||||
self._quic.close()
|
||||
self._loop.run_until_complete(asyncio.sleep(0.05))
|
||||
self._loop.close()
|
||||
self._loop.run_forever()
|
||||
|
||||
self._thread = threading.Thread(target=run, daemon=True)
|
||||
self._thread.start()
|
||||
threading.Thread(target=run, daemon=True).start()
|
||||
if not started.wait(10):
|
||||
raise RuntimeError("the QUIC server did not start")
|
||||
|
||||
@@ -236,9 +248,8 @@ class H3Server:
|
||||
def close(self) -> None:
|
||||
self._tcp.shutdown()
|
||||
self._tcp.server_close()
|
||||
if not self._loop.is_closed():
|
||||
self._loop.call_soon_threadsafe(self._loop.stop)
|
||||
self._thread.join(10)
|
||||
self._quic.close()
|
||||
self._loop.call_soon_threadsafe(self._loop.stop)
|
||||
self._dir.cleanup()
|
||||
|
||||
def __enter__(self) -> "H3Server":
|
||||
|
||||
@@ -1,319 +0,0 @@
|
||||
"""A lab certificate authority the ENGINE trusts, leaves that name an OCSP responder, and the servers that stand behind them (no pytest in here).
|
||||
|
||||
Why. A revocation check is asked only for a chain that builds to a trusted root: with an issuer the engine does not trust the handshake fails
|
||||
first and no OCSP request is ever made, so a page served with ``ignore_https_errors`` (which switches every check off) says nothing about the
|
||||
road of an OCSP request. The lab therefore makes a CA, puts it in the NSS database of the profile BEFORE the launch, and serves a leaf signed
|
||||
by it whose Authority Information Access names an OCSP URL (by a NAME, or by an IP).
|
||||
|
||||
How the CA gets into the profile. The engine's own ``-xpcshell`` (the same code on every system, no OS store, no root) runs
|
||||
``x509certdb.addCertFromBase64(pem, "C,,")`` on the profile directory the session is then launched with (``profile_dir=``); first shown on a
|
||||
runner of each system (run 43574494194): the page loads trusted with no ``ignore_https_errors`` and a listener at the OCSP URL gets
|
||||
``POST application/ocsp-request``. The prefs the session needs for it are ``OCSP_PREFS``.
|
||||
|
||||
The script prints ``JavaScript error: ... uncaught exception: 2147500037`` for its own lines 25 and 26 (and, on Linux, for a line of
|
||||
``nsAsyncShutdown.sys.mjs``): an observer of ``profile-do-change`` / ``profile-after-change`` throws NS_ERROR_FAILURE in a shell with no application.
|
||||
It changes nothing: the verdict is the result file the script writes after ``addCertFromBase64`` returned, and the trust read back with
|
||||
``isCertTrusted``, never the exit code or the text.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import datetime
|
||||
import ipaddress
|
||||
import json
|
||||
import os
|
||||
import ssl
|
||||
import subprocess
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from typing import Dict, List, NamedTuple, Optional, Sequence, Tuple
|
||||
|
||||
from _servers import LocalServer
|
||||
|
||||
#: ``security.pki.crlite_mode`` 0 takes CRLite out of the answer (the lab's issuer is in no filter anyway); ``security.OCSP.enabled`` 1 asks;
|
||||
#: ``require`` false makes a missing answer a soft failure, so the page still loads and the test reads the road, not the page.
|
||||
OCSP_PREFS = {"security.OCSP.enabled": 1, "security.OCSP.require": False, "security.pki.crlite_mode": 0}
|
||||
|
||||
XPCSHELL_JS = r"""
|
||||
"use strict";
|
||||
const result = Services.env.get("LAB_RESULT");
|
||||
const out = { steps: [] };
|
||||
let done = false;
|
||||
function finish(ok) {
|
||||
out.ok = ok;
|
||||
IOUtils.writeUTF8(result, JSON.stringify(out)).then(() => { done = true; }, e => { dump("write failed " + e + "\n"); done = true; });
|
||||
}
|
||||
try {
|
||||
const profd = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
|
||||
profd.initWithPath(Services.env.get("LAB_PROFILE"));
|
||||
const provider = {
|
||||
getFile(prop, persistent) {
|
||||
persistent.value = true;
|
||||
if (prop == "ProfD" || prop == "ProfLD" || prop == "ProfDS" || prop == "UpdRootD") {
|
||||
return profd.clone();
|
||||
}
|
||||
throw Cr.NS_ERROR_FAILURE;
|
||||
},
|
||||
QueryInterface: ChromeUtils.generateQI(["nsIDirectoryServiceProvider"]),
|
||||
};
|
||||
Services.dirsvc.QueryInterface(Ci.nsIDirectoryService).registerProvider(provider);
|
||||
out.steps.push("profile provider registered");
|
||||
Services.obs.notifyObservers(null, "profile-do-change", "xpcshell-do-get-profile");
|
||||
Services.obs.notifyObservers(null, "profile-after-change", "xpcshell-do-get-profile");
|
||||
out.steps.push("profile notified");
|
||||
const certdb = Cc["@mozilla.org/security/x509certdb;1"].getService(Ci.nsIX509CertDB);
|
||||
out.steps.push("x509certdb service obtained");
|
||||
const cert = certdb.addCertFromBase64(Services.env.get("LAB_CERT_B64"), "C,,");
|
||||
out.steps.push("addCertFromBase64 returned");
|
||||
try { out.subject = cert.subjectName; } catch (e) { out.subject_error = String(e); }
|
||||
try {
|
||||
out.trusted_ssl = certdb.isCertTrusted(cert, Ci.nsIX509Cert.CA_CERT, Ci.nsIX509CertDB.TRUSTED_SSL);
|
||||
} catch (e) { out.trusted_error = String(e); }
|
||||
finish(true);
|
||||
} catch (e) {
|
||||
out.error = String(e);
|
||||
out.stack = e && e.stack ? String(e.stack) : "";
|
||||
finish(false);
|
||||
}
|
||||
Services.tm.spinEventLoopUntil("lab-ca-xpcshell", () => done);
|
||||
quit(0);
|
||||
"""
|
||||
|
||||
|
||||
class LabCa:
|
||||
"""A CA made for one test: the key stays here, the certificate goes to the profile (``ca_b64``) or nowhere (an untrusted issuer)."""
|
||||
|
||||
def __init__(self, directory: Path, label: str = "lab egress CA"):
|
||||
from cryptography import x509
|
||||
from cryptography.hazmat.primitives import hashes, serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import ec
|
||||
from cryptography.x509.oid import NameOID
|
||||
|
||||
self.directory = Path(directory)
|
||||
self.label = label
|
||||
now = datetime.datetime.now(datetime.timezone.utc)
|
||||
self._key = ec.generate_private_key(ec.SECP256R1())
|
||||
self._name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, label)])
|
||||
self._cert = (x509.CertificateBuilder().subject_name(self._name).issuer_name(self._name).public_key(self._key.public_key())
|
||||
.serial_number(x509.random_serial_number()).not_valid_before(now - datetime.timedelta(days=1))
|
||||
.not_valid_after(now + datetime.timedelta(days=90))
|
||||
.add_extension(x509.BasicConstraints(ca=True, path_length=0), critical=True)
|
||||
.add_extension(_usage(digital_signature=True, key_cert_sign=True, crl_sign=True), critical=True)
|
||||
.add_extension(x509.SubjectKeyIdentifier.from_public_key(self._key.public_key()), critical=False)
|
||||
.sign(self._key, hashes.SHA256()))
|
||||
self.ca_pem = self.directory / ("%s.pem" % label.replace(" ", "-"))
|
||||
self.ca_pem.write_bytes(self._cert.public_bytes(serialization.Encoding.PEM))
|
||||
#: What ``addCertFromBase64`` takes: the DER, base64.
|
||||
self.ca_b64 = base64.b64encode(self._cert.public_bytes(serialization.Encoding.DER)).decode("ascii")
|
||||
|
||||
def leaf(self, tag: str, dns_names: Sequence[str], ip_addresses: Sequence[str], ocsp_url: Optional[str]) -> Tuple[Path, Path]:
|
||||
"""A leaf for ``dns_names`` and ``ip_addresses`` whose AIA names ``ocsp_url`` (none: no AIA). Returns (certificate, key), both PEM."""
|
||||
from cryptography import x509
|
||||
from cryptography.hazmat.primitives import hashes, serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import ec
|
||||
from cryptography.x509.oid import AuthorityInformationAccessOID, ExtendedKeyUsageOID, NameOID
|
||||
|
||||
now = datetime.datetime.now(datetime.timezone.utc)
|
||||
key = ec.generate_private_key(ec.SECP256R1())
|
||||
san = [x509.DNSName(n) for n in dns_names] + [x509.IPAddress(ipaddress.ip_address(a)) for a in ip_addresses]
|
||||
builder = (x509.CertificateBuilder()
|
||||
.subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, (list(dns_names) + list(ip_addresses))[0])]))
|
||||
.issuer_name(self._name).public_key(key.public_key())
|
||||
.serial_number(x509.random_serial_number()).not_valid_before(now - datetime.timedelta(days=1))
|
||||
.not_valid_after(now + datetime.timedelta(days=60))
|
||||
.add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True)
|
||||
.add_extension(_usage(digital_signature=True), critical=True)
|
||||
.add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH]), critical=False)
|
||||
.add_extension(x509.SubjectAlternativeName(san), critical=False)
|
||||
.add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(self._key.public_key()), critical=False))
|
||||
if ocsp_url:
|
||||
builder = builder.add_extension(
|
||||
x509.AuthorityInformationAccess([x509.AccessDescription(AuthorityInformationAccessOID.OCSP,
|
||||
x509.UniformResourceIdentifier(ocsp_url))]), critical=False)
|
||||
leaf = builder.sign(self._key, hashes.SHA256())
|
||||
cert_path, key_path = self.directory / ("leaf-%s.pem" % tag), self.directory / ("leaf-%s-key.pem" % tag)
|
||||
cert_path.write_bytes(leaf.public_bytes(serialization.Encoding.PEM))
|
||||
key_path.write_bytes(key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption()))
|
||||
return cert_path, key_path
|
||||
|
||||
|
||||
def _usage(**given):
|
||||
from cryptography import x509
|
||||
|
||||
base = dict(digital_signature=False, content_commitment=False, key_encipherment=False, data_encipherment=False, key_agreement=False,
|
||||
key_cert_sign=False, crl_sign=False, encipher_only=False, decipher_only=False)
|
||||
base.update(given)
|
||||
return x509.KeyUsage(**base)
|
||||
|
||||
|
||||
def aia_ocsp_urls(leaf_pem: Path) -> List[str]:
|
||||
"""The OCSP URLs a leaf names (for the unit test of the lab and for the message of a failed case)."""
|
||||
from cryptography import x509
|
||||
from cryptography.x509.oid import AuthorityInformationAccessOID, ExtensionOID
|
||||
|
||||
cert = x509.load_pem_x509_certificate(Path(leaf_pem).read_bytes())
|
||||
try:
|
||||
aia = cert.extensions.get_extension_for_oid(ExtensionOID.AUTHORITY_INFORMATION_ACCESS).value
|
||||
except x509.ExtensionNotFound:
|
||||
return []
|
||||
return [d.access_location.value for d in aia if d.access_method == AuthorityInformationAccessOID.OCSP]
|
||||
|
||||
|
||||
class OcspRequest(NamedTuple):
|
||||
method: str
|
||||
path: str
|
||||
content_type: str
|
||||
length: int
|
||||
|
||||
|
||||
class OcspResponder:
|
||||
"""What the OCSP URL of a leaf points at: it records every request and answers 503 (a soft failure), so the page still loads.
|
||||
|
||||
Bound at ``address`` (an address of this host that no proxy of the tests forwards to): a request that arrives here came from the browser, direct."""
|
||||
|
||||
def __init__(self, address: str = "127.0.0.1"):
|
||||
import http.server
|
||||
|
||||
outer = self
|
||||
self.address = address
|
||||
self.requests: List[OcspRequest] = []
|
||||
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
def _answer(self):
|
||||
length = int(self.headers.get("Content-Length") or 0)
|
||||
if length:
|
||||
self.rfile.read(length)
|
||||
outer.requests.append(OcspRequest(self.command, self.path[:80], self.headers.get("Content-Type", ""), length))
|
||||
self.send_response(503)
|
||||
self.send_header("Content-Length", "0")
|
||||
self.end_headers()
|
||||
|
||||
do_GET = do_POST = _answer # noqa: N815
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
self._server = LocalServer((address, 0), Handler)
|
||||
self.port = self._server.server_address[1]
|
||||
threading.Thread(target=self._server.serve_forever, daemon=True).start()
|
||||
|
||||
@property
|
||||
def asked(self) -> List[OcspRequest]:
|
||||
"""The requests that are OCSP ones (``POST application/ocsp-request``, or a GET of the base64 form)."""
|
||||
return [r for r in self.requests if r.content_type == "application/ocsp-request" or r.method == "GET"]
|
||||
|
||||
def url_by_address(self) -> str:
|
||||
return "http://%s:%d/" % (self.address, self.port)
|
||||
|
||||
def close(self) -> None:
|
||||
self._server.shutdown()
|
||||
self._server.server_close()
|
||||
|
||||
|
||||
class TlsPage:
|
||||
"""A page over TLS at ``address`` with the given leaf. The handshake is made in the thread of the connection, not in the accept loop."""
|
||||
|
||||
def __init__(self, leaf: Path, key: Path, body: str, address: str = "127.0.0.1"):
|
||||
import http.server
|
||||
|
||||
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||
context.load_cert_chain(str(leaf), str(key))
|
||||
self.handshakes: List[str] = []
|
||||
self.body = body
|
||||
outer = self
|
||||
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
def setup(self):
|
||||
try:
|
||||
self.request = context.wrap_socket(self.request, server_side=True)
|
||||
outer.handshakes.append("ok")
|
||||
except (ssl.SSLError, OSError) as exc:
|
||||
outer.handshakes.append("failed: %s" % exc)
|
||||
raise
|
||||
super().setup()
|
||||
|
||||
def do_GET(self): # noqa: N802
|
||||
payload = ("<!doctype html><title>lab</title><body>%s</body>" % outer.body).encode()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/html; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(payload)))
|
||||
self.end_headers()
|
||||
self.wfile.write(payload)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
class Server(LocalServer):
|
||||
def handle_error(self, request, client_address):
|
||||
pass
|
||||
|
||||
self._server = Server((address, 0), Handler)
|
||||
self.port = self._server.server_address[1]
|
||||
threading.Thread(target=self._server.serve_forever, daemon=True).start()
|
||||
|
||||
def close(self) -> None:
|
||||
self._server.shutdown()
|
||||
self._server.server_close()
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------------- the profile
|
||||
def xpcshell_commands(binary: str) -> List[Tuple[str, List[str]]]:
|
||||
"""The ways to start the engine's xpcshell, the plain one first (the one that worked on both systems)."""
|
||||
exe = str(Path(binary).resolve())
|
||||
gre = str(Path(exe).parent)
|
||||
return [("plain", [exe, "-xpcshell"]), ("with -g and -a", [exe, "-xpcshell", "-g", gre, "-a", gre])]
|
||||
|
||||
|
||||
def _kill_tree(proc: subprocess.Popen) -> None:
|
||||
try:
|
||||
import psutil
|
||||
|
||||
parent = psutil.Process(proc.pid)
|
||||
for child in parent.children(recursive=True):
|
||||
child.kill()
|
||||
parent.kill()
|
||||
except Exception: # noqa: BLE001 - the process may be gone already
|
||||
proc.kill()
|
||||
|
||||
|
||||
def _run(argv: List[str], env: Dict[str, str], timeout: float, cwd: str) -> Tuple[Optional[int], str]:
|
||||
proc = subprocess.Popen(argv, env=env, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL)
|
||||
try:
|
||||
out, _ = proc.communicate(timeout=timeout)
|
||||
return proc.returncode, out.decode("utf-8", "replace")
|
||||
except subprocess.TimeoutExpired:
|
||||
_kill_tree(proc)
|
||||
out, _ = proc.communicate()
|
||||
return None, "TIMEOUT after %ss\n%s" % (timeout, out.decode("utf-8", "replace"))
|
||||
|
||||
|
||||
def trusted_by_the_script(result: Optional[dict]) -> bool:
|
||||
"""The verdict of one run of ``XPCSHELL_JS`` from the file it wrote: the call returned AND the NSS database says the root is trusted for TLS."""
|
||||
return bool(result) and result.get("ok") is True and result.get("trusted_ssl") is True
|
||||
|
||||
|
||||
def add_ca_to_profile(binary: str, profile: Path, ca_b64: str, work: Path, timeout: float = 120) -> List[str]:
|
||||
"""Trust ``ca_b64`` in the NSS database of ``profile`` with the engine's own xpcshell. Returns the evidence lines; raises ``RuntimeError`` with
|
||||
them when no way to start the shell ended with the root trusted. The profile directory is the one the session is launched with afterwards."""
|
||||
profile, work = Path(profile), Path(work)
|
||||
profile.mkdir(parents=True, exist_ok=True)
|
||||
work.mkdir(parents=True, exist_ok=True)
|
||||
script = work / "add_ca.js"
|
||||
script.write_text(XPCSHELL_JS, encoding="utf-8")
|
||||
evidence: List[str] = []
|
||||
for label, head in xpcshell_commands(binary):
|
||||
result_file = work / ("xpcshell-result-%s.json" % label.replace(" ", "_"))
|
||||
env = dict(os.environ, LAB_PROFILE=str(profile), LAB_CERT_B64=ca_b64, LAB_RESULT=str(result_file), MOZ_LAUNCHER_PROCESS="0",
|
||||
MOZ_CRASHREPORTER_DISABLE="1")
|
||||
code, output = _run(head + [str(script)], env, timeout, str(Path(binary).resolve().parent))
|
||||
body = None
|
||||
if result_file.exists():
|
||||
try:
|
||||
body = json.loads(result_file.read_text(encoding="utf-8"))
|
||||
except ValueError:
|
||||
body = {"unreadable": result_file.read_text(encoding="utf-8", errors="replace")[:300]}
|
||||
evidence.append("xpcshell [%s] exit=%s result=%s" % (label, code, json.dumps(body) if body is not None else "(no result file)"))
|
||||
evidence.append("xpcshell [%s] output: %s" % (label, output.strip()[:600].replace("\n", " | ") or "(empty)"))
|
||||
if trusted_by_the_script(body):
|
||||
return evidence
|
||||
raise RuntimeError("the engine's xpcshell could not trust the lab CA in %s:\n %s" % (profile, "\n ".join(evidence)))
|
||||
+20
-10
@@ -31,8 +31,6 @@ from pathlib import Path
|
||||
from typing import Dict, Iterable, List, NamedTuple, Optional, Set, Tuple
|
||||
|
||||
from _doh_servers import RCODE_REFUSED, DohQuery, answer_for, build_response, parse_query
|
||||
from _ports import candidates
|
||||
from _ports import who_holds as _who_holds
|
||||
|
||||
RESOLV_CONF = Path("/etc/resolv.conf")
|
||||
|
||||
@@ -174,6 +172,19 @@ def _trap_capability() -> Tuple[bool, str]:
|
||||
TRAP_ADDRESSES = ("127.0.0.1", "127.0.0.2", "127.0.0.3", "127.0.0.4", "127.0.0.5", "127.0.0.6", "127.0.0.7", "127.0.0.8")
|
||||
|
||||
|
||||
def _who_holds(port: int) -> str:
|
||||
"""What the machine says about the sockets of `port` (Linux: ss), for the message of a trap that could not bind."""
|
||||
import subprocess
|
||||
for command in (["ss", "-H", "-lntup"], ["netstat", "-lntup"]):
|
||||
try:
|
||||
done = subprocess.run(command, capture_output=True, text=True, timeout=10)
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
continue
|
||||
lines = [line for line in done.stdout.splitlines() if (":%d " % port) in line]
|
||||
return "; held by: " + (" | ".join(lines) if lines else "nothing listed by %s" % command[0])
|
||||
return "; no ss or netstat to say who holds it"
|
||||
|
||||
|
||||
class Asker(NamedTuple):
|
||||
"""Who sent a question to the trap: the user, the process (None when its socket could not be traced) and its command."""
|
||||
uid: int
|
||||
@@ -424,12 +435,12 @@ class ResolverTrap:
|
||||
try:
|
||||
addresses = TRAP_ADDRESSES if self.port != 0 else TRAP_ADDRESSES[:1]
|
||||
for address in addresses:
|
||||
# A port asked for (53) is tried once per address; with 0 the numbers are the harness's sequence (tests/_ports.py): the
|
||||
# system's own pick, then numbers drawn below the ephemeral range, where Windows' excluded UDP blocks are not.
|
||||
for wanted in ([self.port] if self.port != 0 else candidates(200)):
|
||||
made = self._bind_once(discarded, address, wanted)
|
||||
for attempt in range(200):
|
||||
made = self._bind_once(discarded, address)
|
||||
if made:
|
||||
break
|
||||
if self.port != 0:
|
||||
break
|
||||
if made:
|
||||
self.address = address
|
||||
break
|
||||
@@ -447,11 +458,10 @@ class ResolverTrap:
|
||||
self._threads.append(t)
|
||||
t.start()
|
||||
|
||||
def _bind_once(self, discarded: List[socket.socket], address: str = "127.0.0.1", wanted: Optional[int] = None) -> List[socket.socket]:
|
||||
"""One attempt, on the number ``wanted`` (the trap's own port when None, 0 for the system's pick): the sockets bound, or [] after
|
||||
putting what it opened in ``discarded``."""
|
||||
def _bind_once(self, discarded: List[socket.socket], address: str = "127.0.0.1") -> List[socket.socket]:
|
||||
"""One attempt: the sockets bound, or [] after putting what it opened in ``discarded``."""
|
||||
made: List[socket.socket] = []
|
||||
port = self.port if wanted is None else wanted
|
||||
port = self.port
|
||||
for family, host, required in ((socket.AF_INET, address, True), (socket.AF_INET6, "::1", False)):
|
||||
pair: List[socket.socket] = [] # this family's TCP and UDP, kept or dropped together
|
||||
try:
|
||||
|
||||
@@ -1,137 +0,0 @@
|
||||
"""The page work of the "nothing leaves but the proxy" e2e: the names, the pages and the server (no pytest in here).
|
||||
|
||||
A page can make a browser do much more than load a document: hints (``dns-prefetch``, ``preconnect``, ``prefetch``, ``preload``), an
|
||||
image, a ``fetch``, a WebSocket, an EventSource, a WebRTC gather with a STUN and a TURN server, a geolocation request, a service worker
|
||||
with push, and a page still loading when its context is closed. Each of them is tried in a context of its own behind a SOCKS5 gateway,
|
||||
and what the test asks is where the browser went: no question to the resolver of the machine, no direct connection, every name asked
|
||||
to the DoH THROUGH the gateway of the context, every CONNECT by an ADDRESS.
|
||||
|
||||
The names are the zone of a ``FakeDoh``. The pages are served from 127.0.0.1 and reached by a name (``<case>-site.test``) that points
|
||||
there. Every name the page work uses points at a DOCUMENTATION address (RFC 5737, 198.51.100.0/24), never at loopback, for two reasons:
|
||||
a connection a browser opens straight to it is seen by the leak watcher (a loopback one never is), and the gateway of the tests refuses
|
||||
a CONNECT to a non-loopback address and lists it, which is how a test sees that the browser CONNECTed by the address the DoH gave.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import http.server
|
||||
import threading
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
from _servers import LocalServer
|
||||
|
||||
#: The zone of the page work: name -> the documentation address a lookup of it answers.
|
||||
ROUTABLE: Dict[str, str] = {
|
||||
"prefetch-a.test": "198.51.100.21", "preconnect-b.test": "198.51.100.22", "prefetch-c.test": "198.51.100.23",
|
||||
"preload-d.test": "198.51.100.24",
|
||||
"img-e.test": "198.51.100.25", "fetch-f.test": "198.51.100.26", "ws-g.test": "198.51.100.27", "es-h.test": "198.51.100.28",
|
||||
"stun-i.test": "198.51.100.29", "turn-j.test": "198.51.100.30",
|
||||
}
|
||||
|
||||
#: The pages' own names: they point at the local server. ``push`` is served by its address (a service worker needs a secure
|
||||
#: context, and ``.test`` is not one; 127.0.0.1 is).
|
||||
SITES: Dict[str, str] = {"hints-site.test": "127.0.0.1", "subresources-site.test": "127.0.0.1", "webrtc-site.test": "127.0.0.1",
|
||||
"geolocation-site.test": "127.0.0.1", "closing-site.test": "127.0.0.1"}
|
||||
|
||||
ZONE: Dict[str, str] = {**SITES, **ROUTABLE}
|
||||
|
||||
#: What each case's page does. ``%`` is not used: the names are written out, the page of a case is a constant.
|
||||
CASES: Dict[str, str] = {
|
||||
"hints": '<link rel=dns-prefetch href="//prefetch-a.test"><link rel=preconnect href="http://preconnect-b.test">'
|
||||
'<link rel=prefetch href="http://prefetch-c.test/x"><link rel=preload as=image href="http://preload-d.test/i.png">',
|
||||
"subresources": '<img src="http://img-e.test/i.png"><script>fetch("http://fetch-f.test/x").catch(() => {});'
|
||||
'try { new WebSocket("ws://ws-g.test/s").onerror = () => {}; } catch (e) {}'
|
||||
'try { new EventSource("http://es-h.test/s").onerror = function () { this.close(); }; } catch (e) {}</script>',
|
||||
"webrtc": '<script>(async () => { const pc = new RTCPeerConnection({iceServers: [{urls: "stun:stun-i.test:3478"},'
|
||||
'{urls: "turn:turn-j.test:3478", username: "u", credential: "p"}]});'
|
||||
'pc.createDataChannel("d"); await pc.setLocalDescription(await pc.createOffer()); })().catch(() => {});</script>',
|
||||
"geolocation": '<script>try { navigator.geolocation.getCurrentPosition(() => {}, () => {}, {timeout: 4000}); } catch (e) {}</script>',
|
||||
# a page still loading when its context is closed: requests made between the close and the death of its processes. These names
|
||||
# are in no zone: the DoH answers NXDOMAIN, and what is asked is where the question goes.
|
||||
"closing": '<script>let n = 0; setInterval(() => { for (let k = 0; k < 3; k++) fetch("http://late-" + (n++) + ".test/x")'
|
||||
'.catch(() => {}); }, 5);</script>',
|
||||
# `__pushStage` says how far the page got (registering, registered, ready, subscription-read): a page that stays `pending` names the step it
|
||||
# is stuck in.
|
||||
"push": '<script>window.__push = "pending"; window.__pushStage = "start"; (async () => { if (!navigator.serviceWorker) { window.__push = "no-service-worker"; return; }'
|
||||
'window.__pushStage = "registering"; const r = await navigator.serviceWorker.register("/sw.js"); window.__pushStage = "registered";'
|
||||
'await navigator.serviceWorker.ready; window.__pushStage = "ready";'
|
||||
# WHY THE PAGE ASKS AGAIN (run 43501478312: Linux, both schemes, stage `ready`, `pending` for 30 s; Windows passes). The launch has `-silent`
|
||||
# (invisible_core/juggler/connection.py:1245), which means NO window at start-up (browser/components/BrowserContentHandler.sys.mjs:626,
|
||||
# preventDefault) and Juggler declares the browser started at once (juggler/components/Juggler.js:86-88) instead of waiting for
|
||||
# `browser-idle-startup-tasks-finished` (Juggler.js:93). The first window is made by the first new page; only then does
|
||||
# `sessionstore-windows-restored` (browser/components/sessionstore/SessionStore.sys.mjs:1865) schedule BrowserGlue's idle tasks
|
||||
# (browser/components/BrowserGlue.sys.mjs:828-885), among them `PushService.ensureReady` (BrowserGlue.sys.mjs:984-1000), which is the first
|
||||
# thing that creates the parent's PushServiceParent. Its message listeners are registered in the constructor (dom/push/PushComponents.sys.mjs:49-52),
|
||||
# so a `Push:Registration` sent by the content process before that (PushComponents.sys.mjs:425-430) is lost, not queued: `getSubscription()` never
|
||||
# settles. This is Mozilla/Juggler behaviour, not ours: stock Playwright 1.61 also starts a non-persistent Firefox with `-silent` (driver
|
||||
# coreBundle.js, defaultArgs: `if (isPersistent) firefoxArguments.push("about:blank"); else firefoxArguments.push("-silent");`). A page
|
||||
# that asks early is a property of this lab, so the page asks again every 2 s as a page would, bounded: 15 asks, 30 s, then it stays
|
||||
# `pending` and the test fails with the stage. How long the push service takes to exist is UNMEASURED (the only runs are the red ones, where
|
||||
# it had not existed 30 s after the page was loaded; no run has a number for a green Linux leg).
|
||||
'let sub; for (let i = 1; i <= 15 && sub === undefined; i++) { window.__pushTries = i; sub = await Promise.race([r.pushManager.getSubscription(),'
|
||||
' new Promise(res => setTimeout(() => res(undefined), 2000))]); }'
|
||||
'if (sub === undefined) return; window.__push = "sub:" + JSON.stringify(sub); window.__pushStage = "subscription-read";'
|
||||
'await r.pushManager.subscribe({userVisibleOnly: true, applicationServerKey: new Uint8Array(65).fill(4)});'
|
||||
'})().catch(e => { window.__push = String(window.__push).startsWith("sub:") ? window.__push : "error:" + e.name; });</script>',
|
||||
}
|
||||
|
||||
#: The names the DoH must be asked for, by case, when the work is done (a hint is speculative: the browser may skip it, so none is demanded).
|
||||
ASKED: Dict[str, List[str]] = {
|
||||
"hints": [], "subresources": ["img-e.test", "fetch-f.test", "ws-g.test", "es-h.test"], "webrtc": ["stun-i.test", "turn-j.test"],
|
||||
"geolocation": [], "closing": ["late-0.test"], "push": [],
|
||||
}
|
||||
|
||||
#: How long the page is left to work before the context is closed, in seconds: a case that does little is closed sooner.
|
||||
SETTLE_SECONDS: Dict[str, float] = {"hints": 6.0, "subresources": 6.0, "webrtc": 6.0, "geolocation": 6.0, "closing": 1.5, "push": 6.0}
|
||||
|
||||
SW = b"self.addEventListener('push', () => {});"
|
||||
|
||||
|
||||
def site_name(case: str) -> Optional[str]:
|
||||
"""The name a case's page is reached by, or None for the one reached by its address."""
|
||||
name = "%s-site.test" % case
|
||||
return name if name in SITES else None
|
||||
|
||||
|
||||
def is_documentation_address(address: str) -> bool:
|
||||
"""True for an address of 198.51.100.0/24 (TEST-NET-2)."""
|
||||
return address.startswith("198.51.100.")
|
||||
|
||||
|
||||
class CaseSite:
|
||||
"""A local HTTP server: ``/<case>`` answers the page of that case, ``/sw.js`` a service worker with a push listener."""
|
||||
|
||||
def __init__(self):
|
||||
outer = self
|
||||
self.hits: List[tuple] = []
|
||||
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
def do_GET(self): # noqa: N802
|
||||
path = self.path.split("?", 1)[0]
|
||||
outer.hits.append((self.headers.get("Host", ""), path))
|
||||
if path == "/sw.js":
|
||||
body, kind = SW, "application/javascript"
|
||||
elif path.lstrip("/") in CASES:
|
||||
body, kind = ("<!doctype html><meta charset=utf-8><title>%s</title>%s" % (path.lstrip("/"), CASES[path.lstrip("/")])
|
||||
).encode(), "text/html; charset=utf-8"
|
||||
else:
|
||||
body, kind = b"", "text/plain"
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", kind)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
self._server = LocalServer(("127.0.0.1", 0), Handler)
|
||||
self.port = self._server.server_address[1]
|
||||
threading.Thread(target=self._server.serve_forever, daemon=True).start()
|
||||
|
||||
def url(self, case: str) -> str:
|
||||
name = site_name(case)
|
||||
return "http://%s:%d/%s" % (name or "127.0.0.1", self.port, case)
|
||||
|
||||
def close(self) -> None:
|
||||
self._server.shutdown()
|
||||
self._server.server_close()
|
||||
@@ -1,67 +0,0 @@
|
||||
"""One port number that TCP and UDP both bind on an address, found the way the witness finds it (tests/_witness.py), and said when it is not found.
|
||||
|
||||
Windows hands out ephemeral TCP ports in sequence and keeps excluded ranges of a hundred ports for UDP in the same zone, so asking the system for
|
||||
fifty TCP ports in a row can give fifty consecutive numbers inside one range UDP may not bind: the first try is the system's own pick, the others
|
||||
are drawn at random below the ephemeral range (run 43230437094, wrapper.e2e.web on Windows: ``H3Server`` found "no port free for both TCP and UDP"
|
||||
three times, and the refusals it had swallowed were never read). Every refusal is kept, with its code, and the last ones are in the message.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import random
|
||||
import socket
|
||||
import subprocess
|
||||
from typing import Any, Callable, List, Tuple
|
||||
|
||||
TRIES = 200
|
||||
#: Below Linux's ephemeral range (32768): a number drawn here is not the next of a sequence the system hands out.
|
||||
DRAW_FROM = (20000, 32767)
|
||||
|
||||
|
||||
def who_holds(port: int) -> str:
|
||||
"""What the machine says about the sockets of `port` (ss, or netstat), for the message of a picker or a trap that found no number."""
|
||||
for command in (["ss", "-H", "-lntup"], ["netstat", "-lntup"]):
|
||||
try:
|
||||
done = subprocess.run(command, capture_output=True, text=True, timeout=10)
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
continue
|
||||
lines = [line for line in done.stdout.splitlines() if (":%d " % port) in line]
|
||||
return "; held by: " + (" | ".join(lines) if lines else "nothing listed by %s" % command[0])
|
||||
return "; no ss or netstat to say who holds it"
|
||||
|
||||
|
||||
def candidates(tries: int = TRIES, draw: Any = None):
|
||||
"""The port numbers to try, in order: 0 (the system's own pick) first, then numbers drawn at random below the ephemeral range. The ONE
|
||||
sequence of the harness for "the same number on TCP and UDP": the HTTP/3 server, the witness and the resolver trap all walk it."""
|
||||
draw = draw or random.Random()
|
||||
for attempt in range(tries):
|
||||
yield 0 if attempt == 0 else draw.randint(*DRAW_FROM)
|
||||
|
||||
|
||||
def bind_tcp_and_probe_udp(address: str, make_tcp: Callable[[str, int], Any], tries: int = TRIES, socket_module: Any = None,
|
||||
draw: Any = None) -> Tuple[Any, int]:
|
||||
"""``make_tcp(address, port)`` makes the TCP server (it binds, with port 0 for the system's pick; it has ``server_address`` and
|
||||
``server_close``). Returns ``(that server, its port)`` once UDP binds the same number too (the probe is closed again: whoever needs the UDP
|
||||
socket binds it next). Raises RuntimeError saying how many tries were made and the last refusals, codes included."""
|
||||
sock = socket_module or socket
|
||||
refusals: List[str] = []
|
||||
last = 0
|
||||
for wanted in candidates(tries, draw):
|
||||
tcp = None
|
||||
try:
|
||||
tcp = make_tcp(address, wanted)
|
||||
port = tcp.server_address[1]
|
||||
probe = sock.socket(sock.AF_INET, sock.SOCK_DGRAM)
|
||||
try:
|
||||
probe.bind((address, port))
|
||||
finally:
|
||||
probe.close()
|
||||
return tcp, port
|
||||
except OSError as exc:
|
||||
refusals.append("%s: %s" % (wanted or "system pick", exc))
|
||||
if tcp is not None:
|
||||
last = tcp.server_address[1]
|
||||
tcp.server_close()
|
||||
else:
|
||||
last = wanted
|
||||
raise RuntimeError("no port free for both TCP and UDP on %s, after %d tries (the last number tried: %s)%s; the last refusals: %s"
|
||||
% (address, tries, last or "the system's pick", who_holds(last) if last else "", "; ".join(refusals[-3:])))
|
||||
@@ -1,68 +0,0 @@
|
||||
"""What a test of the screencast needs to say when a stream delivers nothing.
|
||||
|
||||
A dead stream is silent on the wrapper side (the engine keeps one frame in
|
||||
flight and sends no error), so the only account of why is the engine's own
|
||||
output and the clock: the lines it printed that start with ``screencast:`` and,
|
||||
per stream, how long after the start reply the first frame came (if one did).
|
||||
Shared by `test_screencast.py` and `test_hidden_desktop.py`.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
|
||||
|
||||
def engine_screencast_lines(page):
|
||||
"""The lines the engine printed that start with ``screencast:``, from the
|
||||
browser's own stdout/stderr (the core keeps the last 200 lines of the
|
||||
pipe for the whole life of the process, `ProcessOutput`). Where the
|
||||
engine has no line for it the answer says so, so a failure message never
|
||||
comes out empty. Read while the browser is still up."""
|
||||
try:
|
||||
impl = page._impl_obj
|
||||
server = impl._connection._transport._server
|
||||
output = server.object(impl._guid).conn.output
|
||||
lines = output.tail(output.KEEP)
|
||||
except Exception as failure: # the message is the point, not the lookup
|
||||
return "(the engine output could not be read: %r)" % (failure,)
|
||||
mine = [l for l in lines if l.lstrip().startswith("screencast:")]
|
||||
return "\n".join(mine) if mine else "(the engine printed no line starting with 'screencast:')"
|
||||
|
||||
|
||||
class Stream:
|
||||
"""One screencast's frames and the clock around them.
|
||||
|
||||
`on_frame` is a plain function held in an attribute, not a bound method:
|
||||
the sync client tags the handler with an attribute, which a bound method
|
||||
cannot carry.
|
||||
"""
|
||||
|
||||
def __init__(self, name="stream"):
|
||||
self.name = name
|
||||
self.frames = []
|
||||
self.started = None # when `start()` returned, i.e. the reply was handled
|
||||
self.first = None # when the first frame reached the handler
|
||||
|
||||
def on_frame(frame):
|
||||
if self.first is None:
|
||||
self.first = time.monotonic()
|
||||
self.frames.append(frame)
|
||||
|
||||
self.on_frame = on_frame
|
||||
|
||||
def start(self, page, **kwargs):
|
||||
page.screencast.start(on_frame=self.on_frame, **kwargs)
|
||||
self.started = time.monotonic()
|
||||
|
||||
def first_after_start(self):
|
||||
"""Seconds from the start reply to the first frame, or None. Negative
|
||||
when the frame was handed to the handler before `start()` returned."""
|
||||
if self.first is None or self.started is None:
|
||||
return None
|
||||
return self.first - self.started
|
||||
|
||||
def describe(self):
|
||||
delay = self.first_after_start()
|
||||
return "%s: %d frame(s), first frame %s" % (
|
||||
self.name, len(self.frames),
|
||||
"never arrived" if delay is None else
|
||||
"%+.3f s after the start reply" % delay)
|
||||
@@ -143,14 +143,14 @@ class TurnServer:
|
||||
self.sock.sendto(_message(0x0113, tid, err), src)
|
||||
continue
|
||||
user = attrs[0x0006].decode(errors="replace")
|
||||
key = hashlib.md5(("%s:%s:%s" % (user, REALM, PASSWORD)).encode(), usedforsecurity=False).digest()
|
||||
key = hashlib.md5(("%s:%s:%s" % (user, REALM, PASSWORD)).encode()).digest()
|
||||
body = (_attr(0x0016, _xor_addr(*RELAYED)) + _attr(0x0020, _xor_addr(src[0], src[1])) +
|
||||
_attr(0x000D, struct.pack("!I", 600)))
|
||||
self.allocations.append((src[0], src[1], user, time.monotonic()))
|
||||
self.sock.sendto(_message(0x0103, tid, body, key), src)
|
||||
elif mtype in (0x0004, 0x0008, 0x0009): # Refresh, CreatePermission, ChannelBind
|
||||
user = attrs.get(0x0006, b"").decode(errors="replace")
|
||||
key = hashlib.md5(("%s:%s:%s" % (user, REALM, PASSWORD)).encode(), usedforsecurity=False).digest()
|
||||
key = hashlib.md5(("%s:%s:%s" % (user, REALM, PASSWORD)).encode()).digest()
|
||||
body = _attr(0x000D, struct.pack("!I", 600)) if mtype == 0x0004 else b""
|
||||
self.sock.sendto(_message(mtype | 0x0100, tid, body, key), src)
|
||||
|
||||
|
||||
+9
-6
@@ -10,6 +10,7 @@ saw, so a road that works also gives the page a server-reflexive candidate.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import random
|
||||
import socket
|
||||
import sys
|
||||
import struct
|
||||
@@ -18,11 +19,11 @@ from typing import Dict, Iterable, List, Tuple
|
||||
|
||||
_MAGIC = b"\x21\x12\xa4\x42"
|
||||
|
||||
#: How many port numbers the witness tries before it gives up, and where it draws them from after the system's own pick: the sequence of
|
||||
#: tests/_ports.py, which the HTTP/3 server and the resolver trap walk too. Below the start of Windows' dynamic range (49152), where its excluded
|
||||
#: ranges are reserved in blocks of a hundred, and below Linux's ephemeral range (32768): a number drawn there is not the next of a sequence the
|
||||
#: system hands out.
|
||||
from _ports import DRAW_FROM, TRIES, candidates # noqa: E402
|
||||
#: How many port numbers the witness tries before it gives up, and where it draws them from after the system's own pick.
|
||||
TRIES = 200
|
||||
#: Below the start of Windows' dynamic range (49152), where its excluded ranges are reserved in blocks of a hundred, and
|
||||
#: below Linux's ephemeral range (32768): a number drawn here is not the next of a sequence the system hands out.
|
||||
DRAW_FROM = (20000, 32767)
|
||||
|
||||
|
||||
class Witness:
|
||||
@@ -44,7 +45,9 @@ class Witness:
|
||||
@staticmethod
|
||||
def _bind_both(address: str, port: int):
|
||||
refusals: List[str] = []
|
||||
for wanted in ([port] if port else candidates(TRIES)):
|
||||
draw = random.Random()
|
||||
for attempt in range(1 if port else TRIES):
|
||||
wanted = port if port else (0 if attempt == 0 else draw.randint(*DRAW_FROM))
|
||||
tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
udp = None
|
||||
try:
|
||||
|
||||
+1
-8
@@ -11,7 +11,6 @@ from pathlib import Path
|
||||
import pytest
|
||||
|
||||
from _servers import LocalServer
|
||||
from _browser_census import _a_module_leaves_no_browser_open, _the_connections_a_test_made_are_closed_with_it # noqa: F401 (autouse)
|
||||
|
||||
# ── The watchdog that says WHERE it is stuck, while it is still stuck ─────────
|
||||
#
|
||||
@@ -74,12 +73,6 @@ def pytest_configure(config):
|
||||
# The run stops at the first refusal of the engine (tests/engine_refusal.py).
|
||||
from engine_refusal import StopAtTheFirstRefusal
|
||||
config.pluginmanager.register(StopAtTheFirstRefusal(config), "engine-refusal-stop")
|
||||
# What the core did about the GeoIP database during the run, for scripts/ci_lab_geoip.py verify (the CI legs set GEOIP_USED_OUT).
|
||||
if os.environ.get("GEOIP_USED_OUT"):
|
||||
from geoip_used import GeoipUsedRecorder
|
||||
recorder = GeoipUsedRecorder(os.environ["GEOIP_USED_OUT"])
|
||||
recorder.start()
|
||||
config.pluginmanager.register(recorder, "geoip-used")
|
||||
|
||||
|
||||
def pytest_runtest_setup(item):
|
||||
@@ -251,7 +244,7 @@ def _skip_unless_engine_at_least(minimum, tag):
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def engine_at_least():
|
||||
"""``engine_at_least("firefox-65")``: skip the test unless the engine in
|
||||
"""``engine_at_least("firefox-64")``: skip the test unless the engine in
|
||||
use is that release or a later one (see above for how it is read). A seal
|
||||
whose tag has no number (``local``, anything but firefox-N or
|
||||
firefox-N-candidate) makes the test FAIL, saying so: it neither skips nor
|
||||
|
||||
@@ -1,54 +0,0 @@
|
||||
"""What the core did about the GeoIP database during a pytest run, written when the run ends.
|
||||
|
||||
Registered by tests/conftest.py when ``GEOIP_USED_OUT`` names a file (the CI legs set it; a developer's run does not). ``scripts/ci_lab_geoip.py
|
||||
verify`` reads the file: the proof of a leg is not only the environment it was LAUNCHED in (``evidence``, written before pytest) but what the
|
||||
process of the tests used: the value of ``STEALTHFOX_GEOIP_MMDB`` when the run ended, the sha256 of that file, and how many times the core went
|
||||
past the override to ask GitHub for the latest database (``_resolve_latest_geoip_tag``) or to download one (``_download_geoip_tag``): none, in a leg
|
||||
with the database of the pin. A test that removes the variable on purpose (the user-path e2e files do, in a throwaway environment of their own)
|
||||
runs in another process and is not counted here.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class GeoipUsedRecorder:
|
||||
def __init__(self, path: str) -> None:
|
||||
self.path = Path(path)
|
||||
self.asked_github = 0
|
||||
self._undo = []
|
||||
|
||||
def start(self) -> None:
|
||||
try:
|
||||
from invisible_core import _geoip_db
|
||||
except ImportError: # a run without the core installed: the file says so
|
||||
return
|
||||
for name in ("_resolve_latest_geoip_tag", "_download_geoip_tag"):
|
||||
original = getattr(_geoip_db, name, None)
|
||||
if original is None:
|
||||
continue
|
||||
|
||||
def counted(*args, __original=original, **kwargs):
|
||||
self.asked_github += 1
|
||||
return __original(*args, **kwargs)
|
||||
|
||||
setattr(_geoip_db, name, counted)
|
||||
self._undo.append((_geoip_db, name, original))
|
||||
|
||||
def stop(self) -> None:
|
||||
for module, name, original in reversed(self._undo):
|
||||
setattr(module, name, original)
|
||||
self._undo = []
|
||||
|
||||
def pytest_sessionfinish(self, session, exitstatus) -> None: # noqa: ARG002
|
||||
value = os.environ.get("STEALTHFOX_GEOIP_MMDB", "")
|
||||
digest = None
|
||||
if value and os.path.isfile(value):
|
||||
digest = hashlib.sha256(Path(value).read_bytes()).hexdigest()
|
||||
data = {"env": value, "exists": digest is not None, "sha256": digest, "asked_github": self.asked_github}
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
self.path.write_text(json.dumps(data, indent=1), encoding="utf-8")
|
||||
self.stop()
|
||||
@@ -34,7 +34,6 @@ from invisible_playwright._juggler.server import (
|
||||
ArtifactDispatcher, BrowserContextDispatcher, BrowserDispatcher,
|
||||
DebuggerDispatcher, JugglerServer, LocalUtilsDispatcher, PageDispatcher,
|
||||
StreamDispatcher, TracingDispatcher)
|
||||
from _browser_census import closes_with_the_test
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
@@ -45,7 +44,6 @@ class ScriptedJuggler(EventListeners):
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
closes_with_the_test(self)
|
||||
self._contexts = itertools.count(1)
|
||||
self._targets = itertools.count(1)
|
||||
self.sessions = {}
|
||||
@@ -152,47 +150,24 @@ def test_the_browser_does_not_keep_the_contexts_it_closed(browser):
|
||||
assert browser._buffered == {} and browser._live == set()
|
||||
|
||||
|
||||
def _census(browser):
|
||||
"""What this browser's server built and is still alive, after a collection.
|
||||
Only ITS objects: another browser of the same process (an earlier test of the
|
||||
same worker that left its contexts open) is not this server's census."""
|
||||
kinds = (BrowserContextDispatcher, PageDispatcher, DebuggerDispatcher,
|
||||
TracingDispatcher)
|
||||
gc.collect()
|
||||
return collections.Counter(type(o).__name__ for o in gc.get_objects()
|
||||
if type(o) in kinds and o.server is browser.server)
|
||||
|
||||
|
||||
def _assert_the_census_is_stable(browser):
|
||||
for n in range(20):
|
||||
_cycle(browser, n, close_page_first=n % 2 == 0)
|
||||
first = _census(browser)
|
||||
for n in range(20, 60):
|
||||
_cycle(browser, n, close_page_first=n % 2 == 0)
|
||||
assert _census(browser) == first
|
||||
assert first.get("BrowserContextDispatcher", 0) == 0, first
|
||||
|
||||
|
||||
def test_the_count_of_objects_is_stable_across_cycles(browser):
|
||||
"""The census of what the server builds, after a collection, does not move
|
||||
between 20 cycles and 60."""
|
||||
_assert_the_census_is_stable(browser)
|
||||
kinds = (BrowserContextDispatcher, PageDispatcher, DebuggerDispatcher,
|
||||
TracingDispatcher)
|
||||
|
||||
def census():
|
||||
gc.collect()
|
||||
return collections.Counter(type(o).__name__ for o in gc.get_objects()
|
||||
if type(o) in kinds)
|
||||
|
||||
def test_the_census_does_not_count_another_browsers_open_context(browser):
|
||||
# The census counted every dispatcher of the process: run after a file that
|
||||
# leaves its contexts open in the same worker, it saw 7 BrowserContextDispatcher
|
||||
# that were not this server's (core #272, wrapper-on-this-core linux part 2).
|
||||
server = remote._SharedServer()
|
||||
other = remote.SharedBrowserDispatcher(server, remote.SharedBrowserType(server),
|
||||
ScriptedJuggler(), "firefox/1")
|
||||
left_open = server.object(server.handle(
|
||||
{"guid": other.guid, "method": "newContext", "params": {}})["context"]["guid"])
|
||||
try:
|
||||
_assert_the_census_is_stable(browser)
|
||||
assert left_open.guid in server._objects
|
||||
finally:
|
||||
server.shutdown()
|
||||
for n in range(20):
|
||||
_cycle(browser, n, close_page_first=n % 2 == 0)
|
||||
first = census()
|
||||
for n in range(20, 60):
|
||||
_cycle(browser, n, close_page_first=n % 2 == 0)
|
||||
assert census() == first
|
||||
assert first.get("BrowserContextDispatcher", 0) == 0, first
|
||||
|
||||
|
||||
def test_a_download_and_its_stream_are_let_go_with_their_context(browser):
|
||||
|
||||
@@ -57,7 +57,6 @@ def _page(handled):
|
||||
page.disposed = False
|
||||
page._held = None
|
||||
page._held_lock = threading.Lock()
|
||||
page._held_dropped = 0
|
||||
page._detach_listeners = lambda: None
|
||||
page._hear_lifecycle = lambda: None
|
||||
page.context = types.SimpleNamespace(browser=types.SimpleNamespace(
|
||||
|
||||
@@ -1,275 +0,0 @@
|
||||
"""The destination's commit of a popup, whenever it comes while the page is handed from the buffer to its dispatcher, reaches the client once.
|
||||
|
||||
NO BROWSER HERE (the real dispatchers over a scripted Juggler connection, as `test_every_order_of_the_events_of_a_popup_gives_one_page_event`).
|
||||
|
||||
A popup's page is built the moment the engine attaches its target, and what the client is told of its frame comes from two places: the
|
||||
INITIALIZER (a snapshot of what the lifecycle knew when the frame dispatcher was made: url, name, load states) and the lifecycle's own
|
||||
announcements (`navigated`, `loadstate`, a new frame), which go up through a hook (`Lifecycle.announce`) that the page installs at the
|
||||
end of its construction (`_install_events` -> `_hear_lifecycle`). The page's own listener holds the events of the same period and
|
||||
`_install_events` hands over only the `Network.*` ones. So an event that the lifecycle heard AFTER the snapshot and BEFORE the hook was
|
||||
told to nobody: the commit of the destination left the client's frame at `about:blank` for good, and the `DOMContentLoaded`/`load` of
|
||||
the destination was dropped with the held events (measured on Windows, `test_popups_reach_the_client_e2e.py` with no route on the context:
|
||||
the popup "is at about:blank", or `wait_for_load_state("load")` times out).
|
||||
|
||||
The test parks the adoption thread at FOUR points of that passage - after the main frame is known (before the snapshot), as the main
|
||||
frame's dispatcher is made (after the snapshot), as the events are installed (the hold is still on) and after they are installed (the hook
|
||||
is in) - and delivers the destination's commit, `DOMContentLoaded` and `load` (in this order) at every placement of the three among the
|
||||
four points, 20 cases, none sampled. (The hand-over itself, from the release of the hold to the hook, is one step with the lifecycle's lock
|
||||
held: there is no point inside it to park at, which is the property that is wanted.) The page is then made ready and announced, and what the CLIENT was
|
||||
told of the main frame (the initializer, then each `navigated` and `loadstate`, in order) must be what the lifecycle holds: the url of the
|
||||
destination, the states commit/domcontentloaded/load, and the destination's url told exactly once.
|
||||
|
||||
Known-bad input: the code as it was -> the orders with an event between the snapshot and the hook are red.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import itertools
|
||||
import threading
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
from invisible_playwright._juggler import dispatcher as base
|
||||
from invisible_playwright._juggler import remote
|
||||
from invisible_playwright._juggler import server as server_mod
|
||||
from invisible_playwright._juggler.server import LocalUtilsDispatcher
|
||||
|
||||
from test_every_order_of_the_events_of_a_popup_gives_one_page_event import Engine, FRAME, SESSION, TARGET, _thread, _wait
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
DEST = "http://dest.test/p"
|
||||
POINTS = ["after_main_frame", "frame_dispatcher", "events_install", "events_installed"]
|
||||
STATES = ("commit", "domcontentloaded", "load")
|
||||
|
||||
|
||||
class PopupEngine(Engine):
|
||||
def start(self):
|
||||
self.dispatch_event("Page.navigationStarted", {"frameId": FRAME, "navigationId": "n2", "url": DEST}, SESSION)
|
||||
|
||||
def commit_dest(self):
|
||||
self.dispatch_event("Page.navigationCommitted", {"frameId": FRAME, "navigationId": "n2", "url": DEST, "name": ""}, SESSION)
|
||||
|
||||
def dcl(self):
|
||||
self.dispatch_event("Page.eventFired", {"frameId": FRAME, "name": "DOMContentLoaded"}, SESSION)
|
||||
|
||||
def load(self):
|
||||
self.dispatch_event("Page.eventFired", {"frameId": FRAME, "name": "load"}, SESSION)
|
||||
|
||||
|
||||
class Parking:
|
||||
"""Stops the adoption thread of the popup at the four points of the passage, until the test lets it go on."""
|
||||
|
||||
def __init__(self):
|
||||
self.reached = [threading.Event() for _ in POINTS]
|
||||
self.release = [threading.Event() for _ in POINTS]
|
||||
|
||||
def pause(self, index):
|
||||
if threading.current_thread().name != "invpw-adopt-%s" % TARGET or self.reached[index].is_set():
|
||||
return
|
||||
self.reached[index].set()
|
||||
self.release[index].wait(10)
|
||||
|
||||
def open_all(self):
|
||||
for event in self.release:
|
||||
event.set()
|
||||
|
||||
|
||||
def _install(mp, parking, told):
|
||||
"""The parking points, and a record of what the client is told of the main frame of the popup."""
|
||||
original_wait = server_mod.Lifecycle.wait_for_main_frame
|
||||
|
||||
def after_main_frame(self, *args, **kwargs):
|
||||
result = original_wait(self, *args, **kwargs)
|
||||
parking.pause(0)
|
||||
return result
|
||||
mp.setattr(server_mod.Lifecycle, "wait_for_main_frame", after_main_frame)
|
||||
|
||||
original_init = server_mod.FrameDispatcher.__init__
|
||||
|
||||
def frame_init(self, server, page, frame_id, url="about:blank", name="", load_states=None, parent_frame=None, told_commit=None):
|
||||
if frame_id == FRAME and parent_frame is None:
|
||||
parking.pause(1)
|
||||
told["url"] = url
|
||||
told["states"] = set(load_states or ["commit"])
|
||||
told["navigated"] = []
|
||||
told["ops"] = []
|
||||
return original_init(self, server, page, frame_id, url=url, name=name, load_states=load_states, parent_frame=parent_frame, told_commit=told_commit)
|
||||
mp.setattr(server_mod.FrameDispatcher, "__init__", frame_init)
|
||||
|
||||
original_install = server_mod.PageDispatcher._install_events
|
||||
|
||||
def install(self):
|
||||
parking.pause(2)
|
||||
result = original_install(self)
|
||||
parking.pause(3)
|
||||
return result
|
||||
mp.setattr(server_mod.PageDispatcher, "_install_events", install)
|
||||
|
||||
original_emit = base.Dispatcher.emit
|
||||
|
||||
def spy(self, method, params=None):
|
||||
if getattr(self, "TYPE", "") == "Frame" and getattr(self, "frame_id", None) == FRAME and "ops" in told:
|
||||
if method == "navigated":
|
||||
told["navigated"].append(params["url"])
|
||||
told["ops"].append(("url", params["url"]))
|
||||
elif method == "loadstate":
|
||||
for key in ("add", "remove"):
|
||||
if key in params:
|
||||
told["ops"].append((key, params[key]))
|
||||
return original_emit(self, method, params)
|
||||
mp.setattr(base.Dispatcher, "emit", spy)
|
||||
|
||||
|
||||
def _client_view(told):
|
||||
url, states = told["url"], set(told["states"])
|
||||
for op, value in told["ops"]:
|
||||
if op == "url":
|
||||
url = value
|
||||
elif op == "add":
|
||||
states.add(value)
|
||||
elif op == "remove":
|
||||
states.discard(value)
|
||||
return url, states
|
||||
|
||||
|
||||
def _run(placement):
|
||||
"""One case: commit_dest, dcl and load delivered at the points in `placement` (one per event, in order)."""
|
||||
parking, told, announced = Parking(), {}, []
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
_install(mp, parking, told)
|
||||
original_emit = base.Dispatcher.emit
|
||||
|
||||
def page_spy(self, method, params=None):
|
||||
if method == "page" and getattr(self, "TYPE", "") == "BrowserContext":
|
||||
announced.append(time.monotonic())
|
||||
return original_emit(self, method, params)
|
||||
mp.setattr(base.Dispatcher, "emit", page_spy)
|
||||
server = remote._SharedServer()
|
||||
browser_type = remote.SharedBrowserType(server)
|
||||
LocalUtilsDispatcher(server)
|
||||
conn = PopupEngine()
|
||||
browser = remote.SharedBrowserDispatcher(server, browser_type, conn, "firefox/1")
|
||||
try:
|
||||
context = server.object(server.handle({"guid": browser.guid, "method": "newContext", "params": {}})["context"]["guid"])
|
||||
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
|
||||
opener_target = next(t for t in conn.sessions if t != TARGET)
|
||||
del announced[:]
|
||||
conn.attach(opener_target, context.context_id)
|
||||
conn.frame()
|
||||
conn.commit() # the initial about:blank
|
||||
conn.start() # the navigation to the address starts
|
||||
todo = list(zip(["commit_dest", "dcl", "load"], placement))
|
||||
for i in range(len(POINTS)):
|
||||
assert parking.reached[i].wait(5), "the adoption thread never reached %s" % POINTS[i]
|
||||
for event, where in list(todo):
|
||||
if where == i:
|
||||
getattr(conn, event)()
|
||||
todo.remove((event, where))
|
||||
parking.release[i].set()
|
||||
conn.ready()
|
||||
assert _wait(lambda: announced), "the popup was never announced"
|
||||
assert _wait(lambda: _thread() is None), "the adoption thread never ended"
|
||||
page = browser._page_targets.get(TARGET)
|
||||
frame = page.lifecycle.frames[FRAME]
|
||||
return _client_view(told), (frame.url, {s for s in frame.states if s in STATES}), told
|
||||
finally:
|
||||
parking.open_all()
|
||||
try:
|
||||
server.shutdown()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def test_the_commit_and_the_load_of_the_destination_reach_the_client_whenever_they_come_while_the_page_is_handed_over():
|
||||
failures, count = [], 0
|
||||
for combo in itertools.combinations_with_replacement(range(len(POINTS)), 3):
|
||||
count += 1
|
||||
(client_url, client_states), (url, states), told = _run(combo)
|
||||
label = "commit_dest/dcl/load at %s" % [POINTS[i] for i in combo]
|
||||
problems = []
|
||||
if client_url != url:
|
||||
problems.append("the client's frame is at %r, the lifecycle's at %r" % (client_url, url))
|
||||
if {s for s in client_states if s in STATES} != states:
|
||||
problems.append("the client has the states %s, the lifecycle %s" % (sorted(client_states & set(STATES)), sorted(states)))
|
||||
told_dest = (1 if told["url"] == DEST else 0) + told["navigated"].count(DEST)
|
||||
if told_dest != 1:
|
||||
problems.append("the destination's address was told %d times" % told_dest)
|
||||
if problems:
|
||||
failures.append("%s: %s" % (label, "; ".join(problems)))
|
||||
assert count == 20
|
||||
assert not failures, "%d of %d orders lost or doubled an event, e.g.:\n %s" % (len(failures), count, "\n ".join(failures[:12]))
|
||||
|
||||
|
||||
def _run_announcement(where):
|
||||
"""The blank page loads, the page is made ready, and the destination's commit comes at `where`: before the ready, or WHILE the page is
|
||||
announced (the adoption thread is parked inside the announcement, after the `page` event and before the replay of the states said
|
||||
before it, and the commit is delivered by another thread, as the engine's reader would)."""
|
||||
told, announced, inside = {}, [], threading.Event()
|
||||
go = threading.Event()
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
open_parking = Parking()
|
||||
open_parking.open_all()
|
||||
_install(mp, open_parking, told) # the record of what the client is told; its parking points are open
|
||||
original_emit = base.Dispatcher.emit
|
||||
|
||||
def page_spy(self, method, params=None):
|
||||
result = original_emit(self, method, params)
|
||||
if method == "page" and getattr(self, "TYPE", "") == "BrowserContext" and threading.current_thread().name == "invpw-adopt-%s" % TARGET:
|
||||
announced.append(True)
|
||||
inside.set()
|
||||
go.wait(10)
|
||||
return result
|
||||
mp.setattr(base.Dispatcher, "emit", page_spy)
|
||||
server = remote._SharedServer()
|
||||
browser_type = remote.SharedBrowserType(server)
|
||||
LocalUtilsDispatcher(server)
|
||||
conn = PopupEngine()
|
||||
browser = remote.SharedBrowserDispatcher(server, browser_type, conn, "firefox/1")
|
||||
try:
|
||||
context = server.object(server.handle({"guid": browser.guid, "method": "newContext", "params": {}})["context"]["guid"])
|
||||
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
|
||||
opener_target = next(t for t in conn.sessions if t != TARGET)
|
||||
del announced[:]
|
||||
told.clear()
|
||||
conn.attach(opener_target, context.context_id)
|
||||
conn.frame()
|
||||
conn.commit()
|
||||
conn.start()
|
||||
assert _wait(lambda: (browser._adoptions.get(TARGET) is not None and browser._adoptions[TARGET].state == "waiting")), \
|
||||
"the adoption never waited for the ready"
|
||||
conn.dcl() # the blank page's load, said live and kept for the replay
|
||||
conn.load()
|
||||
deliverer = None
|
||||
if where == "before_ready":
|
||||
conn.commit_dest()
|
||||
conn.ready()
|
||||
else:
|
||||
conn.ready()
|
||||
assert inside.wait(5), "the page was never announced"
|
||||
deliverer = threading.Thread(target=conn.commit_dest, daemon=True)
|
||||
deliverer.start()
|
||||
time.sleep(0.2) # the commit is on its way while the announcement is not over
|
||||
go.set()
|
||||
if deliverer is not None:
|
||||
deliverer.join(5)
|
||||
assert _wait(lambda: _thread() is None), "the adoption thread never ended"
|
||||
page = browser._page_targets.get(TARGET)
|
||||
known = page.lifecycle.frames[FRAME]
|
||||
return _client_view(told), (known.url, {s for s in known.states if s in STATES}), told
|
||||
finally:
|
||||
go.set()
|
||||
try:
|
||||
server.shutdown()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
@pytest.mark.parametrize("where", ["before_ready", "during_announcement"])
|
||||
def test_a_commit_before_or_during_the_announcement_leaves_the_client_with_the_states_of_the_destination(where):
|
||||
(client_url, client_states), (url, states), told = _run_announcement(where)
|
||||
assert client_url == url == DEST
|
||||
assert {s for s in client_states if s in STATES} == states == {"commit"}, (
|
||||
"the client has the states %s of a destination that has only committed: the load of the blank page, said again after the "
|
||||
"commit, is still on its frame" % sorted(client_states & set(STATES)))
|
||||
assert (1 if told["url"] == DEST else 0) + told["navigated"].count(DEST) == 1
|
||||
@@ -29,7 +29,6 @@ from invisible_core.juggler.connection import EventListeners
|
||||
from invisible_playwright import _session
|
||||
from invisible_playwright._juggler.server import (BrowserDispatcher, Server, UDP_STUN_PREF,
|
||||
session_udp_stun_servers, take_session_motion)
|
||||
from _browser_census import closes_with_the_test
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
@@ -40,7 +39,6 @@ STUN = ["%s:%d" % (STUN_NUMBER, STUN_PORT)]
|
||||
class _Connection(EventListeners):
|
||||
def __init__(self, gateways=()):
|
||||
super().__init__()
|
||||
closes_with_the_test(self)
|
||||
self.sent = []
|
||||
self.datagrams_before = {}
|
||||
self._gateways = gateways
|
||||
|
||||
@@ -16,7 +16,6 @@ from invisible_core.juggler.connection import EventListeners
|
||||
from invisible_playwright._juggler.server import (
|
||||
BrowserContextDispatcher, BrowserDispatcher, Server,
|
||||
)
|
||||
from _browser_census import closes_with_the_test
|
||||
|
||||
|
||||
class _Engine(EventListeners):
|
||||
@@ -24,7 +23,6 @@ class _Engine(EventListeners):
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
closes_with_the_test(self)
|
||||
self.sent = []
|
||||
|
||||
def startup_send(self, method, params=None):
|
||||
|
||||
@@ -34,8 +34,6 @@ def page():
|
||||
page.injected = Mock()
|
||||
page.actions = Mock()
|
||||
page._frames = {}
|
||||
page._told_attached = set()
|
||||
page._frames_lock = __import__("threading").RLock()
|
||||
page._navigation_requests = {}
|
||||
page._announced_closed = False
|
||||
Dispatcher.__init__(page, server, context)
|
||||
|
||||
@@ -331,7 +331,6 @@ def _seed_whose_first_field_pause_is_longer_than(seconds):
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
@pytest.mark.wall_clock
|
||||
@pytest.mark.parametrize("how", ["fill", "press_sequentially"])
|
||||
def test_a_store_that_answers_the_focus_does_not_eat_the_text(firefox_binary, store_url, how):
|
||||
"""Known-bad, measured on 0.25.8 before this change: the store's write at
|
||||
|
||||
@@ -24,7 +24,6 @@ from invisible_playwright._juggler.server import (
|
||||
BrowserTypeDispatcher, JugglerServer)
|
||||
from invisible_playwright._juggler.transport import _translate_exception
|
||||
from invisible_playwright.sync_api import TimeoutError as PlaywrightTimeout
|
||||
from _browser_census import closes_with_the_test
|
||||
|
||||
PROXY = {"server": "socks5://127.0.0.1:1080", "username": "u", "password": "p"}
|
||||
|
||||
@@ -35,7 +34,6 @@ class _Engine(EventListeners):
|
||||
|
||||
def __init__(self, silent=()):
|
||||
EventListeners.__init__(self)
|
||||
closes_with_the_test(self)
|
||||
self.silent = set(silent)
|
||||
self.bounds: dict = {}
|
||||
self.startup: list = []
|
||||
|
||||
@@ -24,7 +24,6 @@ from invisible_playwright import _session
|
||||
from invisible_playwright._juggler import server as module
|
||||
from invisible_playwright._juggler.server import (SESSION_SEED_PREF, BrowserTypeDispatcher,
|
||||
JugglerServer)
|
||||
from _browser_census import closes_with_the_test
|
||||
|
||||
# Read with a default so that, on the code before the fix, the test fails on what the
|
||||
# profile holds and not on an import.
|
||||
@@ -36,7 +35,6 @@ _LINE = re.compile(r'^user_pref\("([^"]+)",\s*(.*)\);\s*$')
|
||||
class _Engine(EventListeners):
|
||||
def __init__(self):
|
||||
EventListeners.__init__(self)
|
||||
closes_with_the_test(self)
|
||||
|
||||
def send(self, method, params=None, session=None, timeout=30.0):
|
||||
return {"browserContextId": "ctx-1", "targetId": "t-1"}
|
||||
|
||||
@@ -1,190 +0,0 @@
|
||||
"""An event the engine sends LIVE while the events a new page missed are being replayed to it does not reach it before them.
|
||||
|
||||
NO BROWSER HERE (the real dispatchers over a scripted Juggler connection, as `test_the_hand_over_of_a_popup_holds_under_concurrency`).
|
||||
|
||||
The browser buffers the events of a session nobody reads yet, and `PageDispatcher` is handed them (`BrowserDispatcher.replay`) once its
|
||||
lifecycle and its injected script are subscribed. The replay ran on the adoption thread while the engine's reader went on delivering the
|
||||
live events to the same subscribers: a popup's destination committed (live) in the middle of the replay of its first events, and the
|
||||
replay then went on with the OLDER ones - the initial `about:blank` (no navigation of ours) and the `navigationStarted` of the same
|
||||
navigation. The lifecycle ended at `about:blank` for good (a popup "at about:blank": the client was never told of the destination), or
|
||||
had the navigation pending again after its own commit ("Execution context was destroyed" in the first evaluate). Measured on Windows with
|
||||
the engine's events traced (`POPUP-63-SECONDA-CAUSA.md`): the second `Page.frameAttached` of every popup in the traces IS the replay, and
|
||||
the engine sends each event once - 13 reds in 20 runs of the popup file on engine 63 after the hand-over fix, none of them with a second
|
||||
`frameAttached` from the engine (`PageHandler._onFrameAttached` answers nothing for a frame it holds live).
|
||||
|
||||
Sequence of the test: the first events of a popup are buffered (frame, blank commit, the destination's navigation started) -> the page is
|
||||
built and the replay starts, stopped after its first event -> the engine's reader delivers the destination's commit -> the replay goes on.
|
||||
Whatever the interleaving, the lifecycle must end at the destination, with the navigation committed and not pending, and the client's
|
||||
frame must be told the destination.
|
||||
|
||||
Known-bad input: the replay as it was -> the lifecycle ends at `about:blank` and the navigation of the destination is pending again.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
|
||||
import pytest
|
||||
|
||||
from invisible_playwright._juggler import server as server_mod
|
||||
|
||||
from test_a_commit_at_any_point_of_the_hand_over_reaches_the_client_once import DEST
|
||||
from test_the_hand_over_of_a_popup_holds_under_concurrency import World, _finish
|
||||
from test_every_order_of_the_events_of_a_popup_gives_one_page_event import FRAME, SESSION, TARGET, _thread, _wait
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
|
||||
def _case(stop_after, scenario="commit"):
|
||||
"""The replay is stopped after `stop_after` of its events; the live event of the scenario is delivered by another thread (the reader):
|
||||
the destination's commit, or (`context`) the creation of a new utility context after the old one was destroyed."""
|
||||
parked, go, delivered = threading.Event(), threading.Event(), []
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
original = server_mod.BrowserDispatcher.replay
|
||||
|
||||
def replay(self, session, deliver):
|
||||
if session != SESSION:
|
||||
return original(self, session, deliver)
|
||||
count = [0]
|
||||
|
||||
def slow(method, params, s):
|
||||
deliver(method, params, s)
|
||||
delivered.append(method)
|
||||
count[0] += 1
|
||||
if count[0] == stop_after:
|
||||
parked.set()
|
||||
go.wait(10)
|
||||
return original(self, session, slow)
|
||||
mp.setattr(server_mod.BrowserDispatcher, "replay", replay)
|
||||
# the adoption thread is held before the page is built, so that the first events of the popup are buffered when it is
|
||||
entered, begin = threading.Event(), threading.Event()
|
||||
original_build = server_mod.BrowserDispatcher._enter_building
|
||||
|
||||
def enter_building(self, *args, **kwargs):
|
||||
if threading.current_thread().name == "invpw-adopt-%s" % TARGET:
|
||||
entered.set()
|
||||
begin.wait(10)
|
||||
return original_build(self, *args, **kwargs)
|
||||
mp.setattr(server_mod.BrowserDispatcher, "_enter_building", enter_building)
|
||||
world = World()
|
||||
reader = None
|
||||
try:
|
||||
conn = world.conn
|
||||
conn.attach(world.opener_target, world.context.context_id)
|
||||
assert entered.wait(5), "the adoption never started"
|
||||
conn.frame()
|
||||
conn.commit() # the initial about:blank (navigation n1)
|
||||
conn.start() # the navigation to the destination starts (n2)
|
||||
if scenario == "context":
|
||||
conn.dispatch_event("Runtime.executionContextDestroyed", {"executionContextId": "eutility"}, SESSION)
|
||||
begin.set() # the page is built now, and the replay hands it those events
|
||||
assert parked.wait(5), "the replay never delivered %d event(s): %s" % (stop_after, delivered)
|
||||
live = conn.commit_dest if scenario == "commit" else (lambda: conn.dispatch_event("Runtime.executionContextCreated", {
|
||||
"executionContextId": "eutility2", "auxData": {"frameId": FRAME, "name": "utility"}}, SESSION))
|
||||
reader = threading.Thread(target=live, daemon=True, name="engine-reader")
|
||||
reader.start()
|
||||
reader.join(0.3) # with the replay ordered, the reader waits behind it; unordered, it is through
|
||||
go.set()
|
||||
reader.join(5)
|
||||
assert not reader.is_alive(), "the reader never got through"
|
||||
conn.ready()
|
||||
assert _wait(lambda: _thread() is None), "the adoption thread never ended"
|
||||
page = world.browser._page_targets.get(TARGET)
|
||||
known = page.lifecycle.frames[FRAME]
|
||||
if scenario == "context":
|
||||
return page.injected.contexts.get((FRAME, "utility"))
|
||||
return known.url, known.navigation, sorted(known.states), page.frame.url
|
||||
finally:
|
||||
begin.set()
|
||||
go.set()
|
||||
world.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("stop_after", [1, 2, 3, 4, 5])
|
||||
def test_the_destination_commit_delivered_while_the_replay_goes_on_is_the_last_word(stop_after):
|
||||
url, navigation, states, told = _case(stop_after)
|
||||
assert url == DEST, "the lifecycle ended at %r: an older event of the replay came after the live commit" % url
|
||||
assert navigation == "n2", "the frame's navigation is %r" % navigation
|
||||
assert "commit" in states
|
||||
assert told == DEST, "the client's frame is at %r" % told
|
||||
|
||||
|
||||
@pytest.mark.parametrize("stop_after", [1, 2])
|
||||
def test_a_context_created_while_the_replay_goes_on_is_not_undone_by_an_older_event(stop_after):
|
||||
"""The same race for the injected script: the replay brings the creation of the utility context and its destruction, the engine creates a
|
||||
new one meanwhile. The new one is the context the injected script must end with."""
|
||||
context = _case(stop_after, "context")
|
||||
assert context == "eutility2", "the injected script ended with the utility context %r" % (context,)
|
||||
|
||||
|
||||
def test_a_patch_of_the_class_made_after_the_browser_was_built_still_sees_the_events():
|
||||
"""The reader looked the delivery up on the class at each event; the gate keeps doing so (the e2e fixtures that record the events patch
|
||||
`EventListeners.dispatch_event` after the browser exists)."""
|
||||
from invisible_core.juggler.connection import EventListeners
|
||||
|
||||
world = World()
|
||||
try:
|
||||
seen = []
|
||||
original = EventListeners.dispatch_event
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
mp.setattr(EventListeners, "dispatch_event", lambda self, method, params, session: seen.append((method, session)))
|
||||
world.conn.dispatch_event("Page.x", {}, "S-patched")
|
||||
assert seen == [("Page.x", "S-patched")]
|
||||
assert EventListeners.dispatch_event is original
|
||||
finally:
|
||||
world.close()
|
||||
|
||||
|
||||
def test_a_gate_that_is_never_let_go_costs_the_reader_one_wait_and_is_said():
|
||||
"""The bound is on the hold, not on each event: the first event waits GATE_WAIT_S, the next ones are delivered at once, and the
|
||||
connection records it."""
|
||||
import time
|
||||
|
||||
world = World()
|
||||
held, release, got = threading.Event(), threading.Event(), []
|
||||
try:
|
||||
world.browser.GATE_WAIT_S = 0.2
|
||||
|
||||
def holder():
|
||||
with world.browser.events_gate():
|
||||
held.set()
|
||||
release.wait(10)
|
||||
t = threading.Thread(target=holder, daemon=True)
|
||||
t.start()
|
||||
assert held.wait(5)
|
||||
world.conn.add_listener(lambda m, p, s: got.append(m) if s == "S-stuck" else None)
|
||||
began = time.monotonic()
|
||||
for n in range(3):
|
||||
world.conn.dispatch_event("Page.e%d" % n, {}, "S-stuck")
|
||||
took = time.monotonic() - began
|
||||
assert got == ["Page.e0", "Page.e1", "Page.e2"], got
|
||||
assert took < 1.0, "the reader waited %.2fs for three events: the bound is per event" % took
|
||||
assert world.browser._gate_timeouts == 1
|
||||
assert any("events gate" in str(e) for e in world.conn.handler_errors), world.conn.handler_errors
|
||||
finally:
|
||||
release.set()
|
||||
world.close()
|
||||
|
||||
|
||||
def test_a_page_built_while_the_reader_is_stuck_in_a_handler_is_built_all_the_same_and_it_is_said():
|
||||
import warnings
|
||||
|
||||
world = World()
|
||||
held, release = threading.Event(), threading.Event()
|
||||
try:
|
||||
world.browser.PAGE_GATE_WAIT_S = 0.2
|
||||
|
||||
def stuck_reader():
|
||||
with world.browser.events_gate():
|
||||
held.set()
|
||||
release.wait(10)
|
||||
t = threading.Thread(target=stuck_reader, daemon=True)
|
||||
t.start()
|
||||
assert held.wait(5)
|
||||
with warnings.catch_warnings(record=True) as caught:
|
||||
warnings.simplefilter("always")
|
||||
with world.browser.events_gate():
|
||||
pass
|
||||
assert any("held for more than" in str(w.message) for w in caught), [str(w.message) for w in caught]
|
||||
finally:
|
||||
release.set()
|
||||
world.close()
|
||||
@@ -74,7 +74,7 @@ ON_WINDOWS = sys.platform == "win32"
|
||||
@pytest.mark.skipif(ON_WINDOWS, reason="the system theme is declared, and its absence refused, on Linux only")
|
||||
@pytest.mark.parametrize("pref", MISSING)
|
||||
def test_a_missing_pref_refuses_the_launch(firefox_binary, engine_at_least, pref):
|
||||
engine_at_least("firefox-65")
|
||||
engine_at_least("firefox-64")
|
||||
with pytest.raises(RuntimeError) as err:
|
||||
c, profile_dir = _launch(firefox_binary, pref)
|
||||
# Not reached when the engine refuses: close what must not be running.
|
||||
@@ -88,7 +88,7 @@ def test_a_missing_pref_refuses_the_launch(firefox_binary, engine_at_least, pref
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_every_pref_declared_the_launch_succeeds(firefox_binary, engine_at_least):
|
||||
engine_at_least("firefox-65")
|
||||
engine_at_least("firefox-64")
|
||||
c, profile_dir = _launch(firefox_binary, None)
|
||||
try:
|
||||
assert c.ready_seen, "the browser did not announce the protocol"
|
||||
|
||||
@@ -1,83 +0,0 @@
|
||||
"""The check of tests/_browser_census.py is red on a module that leaks a browser and green on one that closes it.
|
||||
|
||||
Each case is a module of its own in a fresh pytest (the check is module level and the leak would otherwise count against this file).
|
||||
"""
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import textwrap
|
||||
from pathlib import Path
|
||||
|
||||
TESTS = str(Path(__file__).resolve().parent)
|
||||
|
||||
_BUILD = """
|
||||
from invisible_playwright._juggler.server import _ThreadStarter
|
||||
def build():
|
||||
return _ThreadStarter(on_error=lambda message: None)
|
||||
"""
|
||||
|
||||
|
||||
def _run(tmp_path, body):
|
||||
(tmp_path / "conftest.py").write_text("from _browser_census import _a_module_leaves_no_browser_open # noqa\n")
|
||||
(tmp_path / "test_the_module.py").write_text(textwrap.dedent(_BUILD) + textwrap.dedent(body))
|
||||
env = dict(os.environ, PYTHONPATH=TESTS + os.pathsep + os.environ.get("PYTHONPATH", ""))
|
||||
return subprocess.run(
|
||||
[sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider", "-o", "addopts=", str(tmp_path / "test_the_module.py")],
|
||||
cwd=str(tmp_path), env=env, capture_output=True, text=True, timeout=120,
|
||||
)
|
||||
|
||||
|
||||
def test_a_module_that_never_closes_what_it_built_fails(tmp_path):
|
||||
done = _run(tmp_path, """
|
||||
def test_one():
|
||||
build()
|
||||
|
||||
def test_two():
|
||||
build()
|
||||
""")
|
||||
out = done.stdout + done.stderr
|
||||
assert done.returncode != 0, out
|
||||
assert "left 2 browser(s) open: close their connection" in out, out
|
||||
assert "2 passed" in out and "1 error" in out, out # the tests pass; the module is the one that fails
|
||||
|
||||
|
||||
def test_a_module_that_closes_what_it_built_passes(tmp_path):
|
||||
done = _run(tmp_path, """
|
||||
import pytest
|
||||
|
||||
@pytest.fixture
|
||||
def starter():
|
||||
built = build()
|
||||
yield built
|
||||
built.stop()
|
||||
|
||||
def test_one(starter):
|
||||
pass
|
||||
|
||||
def test_two(starter):
|
||||
pass
|
||||
""")
|
||||
out = done.stdout + done.stderr
|
||||
assert done.returncode == 0, out
|
||||
assert "2 passed" in out and "error" not in out, out
|
||||
|
||||
|
||||
def test_a_browser_shared_by_the_tests_of_a_module_may_stay_open_until_the_module_ends(tmp_path):
|
||||
done = _run(tmp_path, """
|
||||
import pytest
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def shared():
|
||||
built = build()
|
||||
yield built
|
||||
built.stop()
|
||||
|
||||
def test_one(shared):
|
||||
pass
|
||||
|
||||
def test_two(shared):
|
||||
pass
|
||||
""")
|
||||
out = done.stdout + done.stderr
|
||||
assert done.returncode == 0, out
|
||||
assert "2 passed" in out, out
|
||||
@@ -19,7 +19,6 @@ from invisible_playwright._juggler import server as srv
|
||||
from invisible_playwright._juggler.server import (
|
||||
BrowserContextDispatcher, BrowserDispatcher, Server,
|
||||
)
|
||||
from _browser_census import closes_with_the_test
|
||||
|
||||
#: How long this engine takes to answer `Browser.newPage`, in its own clock.
|
||||
ANSWER_AFTER_S = 35.0
|
||||
@@ -31,7 +30,6 @@ class _SlowEngine(EventListeners):
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
closes_with_the_test(self)
|
||||
self.browser = None
|
||||
self.bounds = []
|
||||
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
"""A popup's page that is closed (the caller closes the context or the browser) while it is being adopted is not announced to the client afterwards.
|
||||
|
||||
NO BROWSER HERE (the real dispatchers over a scripted Juggler connection, as `test_the_hand_over_of_a_popup_holds_under_concurrency`).
|
||||
|
||||
The page's guid exists for the client from the moment the page is built (its `__create__`), and the context's `page` event is what tells the client
|
||||
to treat it as a page. A close that comes in between sends `close` and `__dispose__` for that guid; the adoption then said `page` for it, and the
|
||||
client threw (an event naming an object it had dropped, the family of `'dict' object has no attribute '_object'`).
|
||||
|
||||
Sequence: the adoption thread is parked before the hook goes in -> the page is closed (`announce_closed`) -> the adoption thread goes on to
|
||||
announce the page. Nothing may be sent for the page, or about it, after its `__dispose__`.
|
||||
|
||||
Known-bad input: 436f815 + the fixes of the concurrency review, without the guard in `announce` -> a `page` event after the `__dispose__`.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
|
||||
import pytest
|
||||
|
||||
from test_the_hand_over_of_a_popup_holds_under_concurrency import World, _adopter, _wait, _thread, POINTS, Parking, _install
|
||||
from invisible_playwright._juggler import server as server_mod
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
|
||||
def test_a_page_closed_before_its_announcement_is_never_announced():
|
||||
parking, told = Parking(), {}
|
||||
sent, caught, at_hook, go = [], [], threading.Event(), threading.Event()
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
_install(mp, parking, told)
|
||||
original = server_mod.PageDispatcher._hear_lifecycle
|
||||
|
||||
def hear(self):
|
||||
if _adopter() and not caught:
|
||||
caught.append(self)
|
||||
at_hook.set()
|
||||
go.wait(10)
|
||||
return original(self)
|
||||
mp.setattr(server_mod.PageDispatcher, "_hear_lifecycle", hear)
|
||||
world = World()
|
||||
mp.setattr(world.server, "send_up", lambda message: sent.append(message))
|
||||
try:
|
||||
world.born()
|
||||
for i in range(3):
|
||||
assert parking.reached[i].wait(5), "the adoption thread never reached %s" % POINTS[i]
|
||||
parking.release[i].set()
|
||||
assert at_hook.wait(5), "the adoption thread never reached the hook"
|
||||
page = caught[0]
|
||||
page.announce_closed()
|
||||
disposed_at = next(i for i, m in enumerate(sent) if m.get("method") == "__dispose__" and m.get("guid") == page.guid)
|
||||
go.set()
|
||||
parking.open_all()
|
||||
assert _wait(lambda: _thread() is None), "the adoption thread never ended"
|
||||
after = [m for m in sent[disposed_at + 1:] if m.get("method") in ("page", "__create__")
|
||||
or m.get("params", {}).get("page", {}).get("guid") == page.guid]
|
||||
assert not after, "told after the page's __dispose__: %s" % [(m.get("method"), m.get("guid")) for m in after]
|
||||
finally:
|
||||
go.set()
|
||||
parking.open_all()
|
||||
world.close()
|
||||
@@ -0,0 +1,50 @@
|
||||
"""A client of the server cannot turn the launch counter off or point it elsewhere (no browser).
|
||||
|
||||
The core refuses the two prefs of the counter in ``extra_prefs``; the server takes ``firefoxUserPrefs`` from a client and, for a launch
|
||||
that names no session, puts them on top of the session it composes, and for a marked launch takes them as they come. Both roads are
|
||||
closed here, at ``session_for_launch``, with the core's own refusal.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from invisible_core.prefs import USAGE_PING_PREFS, USAGE_PING_REFUSAL, USAGE_PING_URL
|
||||
from invisible_playwright._juggler import server
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
ENABLED, URL = USAGE_PING_PREFS
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def composed_session(monkeypatch):
|
||||
"""The session the server composes for an unmarked launch, without composing one (that needs an engine)."""
|
||||
import invisible_playwright._session as session
|
||||
monkeypatch.setattr(session, "default_session", lambda executable, proxy=None: ({URL: USAGE_PING_URL, "x": 1}, {}))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("pref,value", [(ENABLED, False), (ENABLED, True), (ENABLED, None), (URL, "https://example.invalid/x"), (URL, None)])
|
||||
@pytest.mark.parametrize("marked", [False, True], ids=["bare launch", "marked launch"])
|
||||
def test_a_client_cannot_send_the_counter_prefs(pref, value, marked):
|
||||
prefs = {pref: value}
|
||||
if marked:
|
||||
prefs[server.COMPOSED_PREF] = True
|
||||
with pytest.raises(ValueError) as refused:
|
||||
server.session_for_launch(prefs, "firefox")
|
||||
assert pref in str(refused.value) and USAGE_PING_REFUSAL in str(refused.value)
|
||||
|
||||
|
||||
def test_the_address_the_core_wrote_travels_in_a_marked_launch():
|
||||
prefs, _env = server.session_for_launch({server.COMPOSED_PREF: True, URL: USAGE_PING_URL, "y": 2}, "firefox")
|
||||
assert prefs[URL] == USAGE_PING_URL and prefs["y"] == 2 and ENABLED not in prefs
|
||||
|
||||
|
||||
def test_a_bare_launch_gets_the_core_address_and_the_clients_other_prefs():
|
||||
prefs, _env = server.session_for_launch({"z": 3}, "firefox")
|
||||
assert prefs[URL] == USAGE_PING_URL and prefs["z"] == 3 and ENABLED not in prefs
|
||||
|
||||
|
||||
def test_the_same_address_in_a_bare_launch_is_still_refused():
|
||||
"""Only the address the CORE wrote, inside a composed launch, is let through: a bare client that names it is refused too."""
|
||||
with pytest.raises(ValueError):
|
||||
server.session_for_launch({URL: USAGE_PING_URL}, "firefox")
|
||||
@@ -28,10 +28,8 @@ def _serve():
|
||||
pass
|
||||
|
||||
def do_GET(self):
|
||||
asked = self.path.strip("/").split("/")[0].split("?")[0]
|
||||
# the name that goes into the header is the dict's own key, found by comparison: nothing of the request is written back
|
||||
kind = next((name for name in BODIES if name == asked), None)
|
||||
if kind is not None:
|
||||
kind = self.path.strip("/").split("/")[0].split("?")[0]
|
||||
if kind in BODIES:
|
||||
body = BODIES[kind]
|
||||
self.send_response(200)
|
||||
self.send_header("content-type", "application/octet-stream")
|
||||
|
||||
@@ -1,116 +0,0 @@
|
||||
"""E2E: a TURN server given by NAME, over TCP, in a context with a proxy, is resolved by the DoH through THAT proxy.
|
||||
|
||||
EXPECTED RED ON THE PUBLISHED ENGINE firefox-63, GREEN ON firefox-64 (the engine fix is commit ac0214bff4 with 058edd6cc6). The test is not gated and
|
||||
not skipped: it runs on every engine, so the candidate of firefox-64 (this branch runs there as ``wrapper_ref``) is red when the fix is missing, and
|
||||
firefox-63 is red because it does not have it.
|
||||
|
||||
The defect. A page asks for ``turn:<name>:3478?transport=tcp``. The TCP socket that talks to the TURN server (``WebrtcTCPSocket``) did not
|
||||
carry the origin attributes of its PeerConnection, so its name lookup was made in the DEFAULT user context. In a session with no proxy at
|
||||
launch and a proxy on the context (the scheme of ``test_context_proxy_only_resolves_by_doh_e2e.py``) the default context resolves natively:
|
||||
the lookup went to the system resolver (a question for a name of a proxied page, and the DoH never saw it); with a proxy at launch AND a
|
||||
different one on the context, the DoH request left by the proxy of the LAUNCH, the wrong exit. The STUN and the TURN-over-UDP names do not
|
||||
have the defect (``test_ice_names_by_the_context_proxy_e2e.py``), and the TURN over TCP by an IP does not resolve at all
|
||||
(``test_webrtc_realness.py::test_the_turn_over_tcp_of_a_context_goes_through_the_proxy_of_that_context``): no test of the main line made the
|
||||
browser resolve a TURN name over TCP, so nothing showed it. Found by the minimal engine's matrix of page work behind a proxy.
|
||||
|
||||
What the page does and what is read (two schemes, as in ``test_nothing_leaves_but_the_proxy_e2e.py``):
|
||||
|
||||
* ``context_only``: no launch proxy, a context with a SOCKS5 gateway. The name must reach the DoH by that gateway, the resolver of the
|
||||
machine must be asked nothing for it (the trap, Linux root), and the gateway must be handed the ADDRESS the DoH answered (198.51.100.7,
|
||||
a documentation address nothing routes: the gateway refuses it and lists it);
|
||||
* ``launch_and_context``: a launch gateway and a different one for the context. The name must reach the DoH by the gateway of the CONTEXT
|
||||
and by no other, and nothing at all may go direct or ask the resolver.
|
||||
|
||||
Red on the defect: the DoH is never asked for the name (the lookup took the native road, or the default context's DoH request failed its
|
||||
handshake by design), and on Linux the trap heard the name.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
# The fixtures and the helpers of the DoH e2e (imported, not copied). `doh`, `gateway`, `pages`, `trap` and `watcher` are in conftest.py.
|
||||
from test_doh_through_the_proxy_e2e import ( # noqa: F401 (the hermetic session is autouse and imported by name)
|
||||
DOH_ADDRESSES, ZONE, _assert_every_connection_went_through_the_gateway, _direct_to_the_doh, _hermetic_session, _is_address, _launch,
|
||||
_page_in, _why)
|
||||
|
||||
import _doh_servers as ds
|
||||
from _doh_servers import DOH_HOST, QTYPE_A, FakeDoh
|
||||
|
||||
pytestmark = [pytest.mark.e2e]
|
||||
|
||||
#: A documentation address of its own (not the STUN one, 198.51.100.5, nor the core's measurement one, 198.51.100.6).
|
||||
TURN_NUMBER = "198.51.100.7"
|
||||
TURN_NAME = "turn-a.test"
|
||||
TURN_PORT = 3478
|
||||
TURN_ZONE = {**ZONE, TURN_NAME: TURN_NUMBER}
|
||||
#: How long the page waits for the ICE agent to try the server, in milliseconds.
|
||||
WAIT_MS = 6000
|
||||
#: How long to wait for the DoH to be asked and for the gateway to be handed the address, in seconds.
|
||||
ASKED_SECONDS = 25
|
||||
|
||||
_PROBE_JS = """async ([url, waitMs]) => {
|
||||
const errors = [], found = [];
|
||||
const pc = new RTCPeerConnection({iceServers: [{urls: url, username: 'u', credential: 'p'}]});
|
||||
pc.createDataChannel('d');
|
||||
pc.onicecandidateerror = (e) => errors.push(e.errorCode);
|
||||
pc.onicecandidate = (e) => { if (e.candidate) found.push(e.candidate.candidate); };
|
||||
await pc.setLocalDescription(await pc.createOffer());
|
||||
await new Promise((resolve) => setTimeout(resolve, waitMs));
|
||||
pc.close();
|
||||
return {errors, candidates: found.length};
|
||||
}"""
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def doh():
|
||||
"""The FakeDoh with the TURN name pointing at a documentation address (overrides the one of conftest.py)."""
|
||||
import h2 # noqa: F401 - the dev extra installs it: a missing one is a failure, never a skip
|
||||
|
||||
server = FakeDoh(TURN_ZONE)
|
||||
yield server
|
||||
server.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("scheme", ["context_only", "launch_and_context"])
|
||||
def test_a_turn_server_named_over_tcp_is_resolved_by_the_doh_through_the_proxy_of_the_context(
|
||||
scheme, firefox_binary, doh, pages, gateway, trap, watcher):
|
||||
"""EXPECTED RED on the published firefox-63 (the defect), green with the engine fix of firefox-64."""
|
||||
gw_context = gateway("gw-context")
|
||||
gw_launch = gateway("gw-launch") if scheme == "launch_and_context" else None
|
||||
gateways = [g for g in (gw_context, gw_launch) if g is not None]
|
||||
with _launch(firefox_binary, gw_launch.proxy if gw_launch else None) as browser:
|
||||
context, page = _page_in(browser, proxy=gw_context.proxy)
|
||||
page.goto(pages.url("page-a.test"), wait_until="load", timeout=30000)
|
||||
result = page.evaluate(_PROBE_JS, ["turn:%s:%d?transport=tcp" % (TURN_NAME, TURN_PORT), WAIT_MS])
|
||||
asked = ds.wait_until(lambda: doh.queries_for(TURN_NAME, QTYPE_A), ASKED_SECONDS)
|
||||
handed = ds.wait_until(lambda: (TURN_NUMBER, TURN_PORT) in gw_context.connects, ASKED_SECONDS)
|
||||
context.close()
|
||||
watcher.stop()
|
||||
|
||||
why = _why(doh, *gateways) + "\n the page: %s" % (result,)
|
||||
assert asked, (
|
||||
"the DoH was never asked for the TURN name %s over TCP: the lookup of the socket took the user context of no proxy (the "
|
||||
"system resolver, or the default context's DoH request)" % TURN_NAME + why)
|
||||
assert doh.vias_of(TURN_NAME, QTYPE_A) == {gw_context.name}, (
|
||||
"%s (A) was not asked by the gateway of the context only: %s" % (TURN_NAME, sorted(doh.vias_of(TURN_NAME, QTYPE_A))) + why)
|
||||
assert handed, "the gateway of the context was never handed the address %s:%d the DoH answered" % (TURN_NUMBER, TURN_PORT) + why
|
||||
for gw in gateways:
|
||||
named = [h for h, _p in gw.connects if not _is_address(h) and h != DOH_HOST]
|
||||
assert named == [], "%s was sent a NAME in a CONNECT: %s" % (gw.name, named) + why
|
||||
if gw_launch is not None:
|
||||
assert (TURN_NUMBER, TURN_PORT) not in gw_launch.connects, "the TURN address was handed to the gateway of the LAUNCH" + why
|
||||
assert [q for q in doh.queries if q.via == gw_launch.name and q.name == TURN_NAME] == [], (
|
||||
"the name of the TURN server left by the gateway of the LAUNCH, not by the one of the context" + why)
|
||||
_assert_every_connection_went_through_the_gateway(doh, *gateways)
|
||||
|
||||
assert watcher.watched_pids, "the watcher never saw a browser process (it saw: %s)" % watcher.process_names
|
||||
assert _direct_to_the_doh(watcher) == [], (
|
||||
"the browser reached a DoH (%s) or a DNS server (port 53) without the proxy: %s" % (", ".join(DOH_ADDRESSES), watcher.describe()))
|
||||
assert [c for c in watcher.direct if c.remote.rsplit(":", 1)[0] == TURN_NUMBER] == [], (
|
||||
"the browser connected straight to the TURN server, around the proxy: %s" % watcher.describe())
|
||||
if gw_launch is not None:
|
||||
assert watcher.direct == [], "the browser connected past the gateways, with every context proxied: %s" % watcher.describe()
|
||||
if trap is not None:
|
||||
assert not trap.asked(TURN_NAME), "the browser asked the resolver of the machine for the TURN name: %s" % trap.describe()
|
||||
if gw_launch is not None:
|
||||
assert trap.queries == [], "the browser asked the resolver of the machine, with every context proxied: %s" % trap.describe()
|
||||
@@ -18,13 +18,6 @@ Runtime.js) and the core drops every world on `executionContextsCleared`
|
||||
Each round checks `crossOriginIsolated` on the first page: a round where the
|
||||
engine did not isolate it would not have changed process, and would pass for
|
||||
the wrong reason.
|
||||
|
||||
The page moves to the second one when the test says so, right after the read
|
||||
on the first: it used to go on its own 500 ms after `load`, and on a loaded
|
||||
Windows runner more than 500 ms can pass between `domcontentloaded` and the
|
||||
first read, so that read met the second page or the move itself (2 rounds in 20
|
||||
under four workers, runs 43435932449 and 43439508625: `crossOriginIsolated`
|
||||
false, and "Execution context was destroyed").
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -39,8 +32,8 @@ ROUNDS = 3
|
||||
|
||||
PAGES = {
|
||||
"/isolated": (b"<!doctype html><html><body><p id=p>isolated</p><script>"
|
||||
b"window.moveOn = () => setTimeout(() => "
|
||||
b"location.replace('/plain' + location.search), 0)"
|
||||
b"addEventListener('load', () => setTimeout(() => "
|
||||
b"location.replace('/plain' + location.search), 500))"
|
||||
b"</script></body></html>"),
|
||||
"/plain": b"<!doctype html><html><body><p id=p>plain</p></body></html>",
|
||||
}
|
||||
@@ -89,9 +82,7 @@ def test_reads_after_the_isolated_page_answer(page, site):
|
||||
"the engine did not isolate the page: this round tests nothing")
|
||||
# The read on the isolated page is what builds the script that went
|
||||
# stale; without it the bug never showed.
|
||||
assert page.locator("#p").inner_text(timeout=10_000) == "isolated"
|
||||
# The page sends itself on, as a challenge page does: the move is its own location.replace, not a goto of ours.
|
||||
page.evaluate("moveOn()")
|
||||
assert page.locator("#p").inner_text(timeout=10_000) in ("isolated", "plain")
|
||||
page.wait_for_url("**/plain?i=%d" % i, timeout=10_000)
|
||||
assert page.evaluate("self.crossOriginIsolated") is False
|
||||
assert page.locator("#p").inner_text(timeout=10_000) == "plain"
|
||||
|
||||
@@ -113,7 +113,7 @@ def _serve(imgs, listing):
|
||||
@pytest.mark.e2e
|
||||
@pytest.mark.timeout(300, method="thread")
|
||||
def test_tagged_images_read_back_as_retail_windows_reads_them(firefox_binary, engine_at_least):
|
||||
engine_at_least("firefox-65")
|
||||
engine_at_least("firefox-64")
|
||||
refs_path = DATA / "refs.json"
|
||||
if not refs_path.is_file():
|
||||
pytest.fail("tests/data/canvas_icc_ref/refs.json is missing: it is the reference "
|
||||
|
||||
@@ -104,7 +104,7 @@ def _want(cases):
|
||||
@pytest.mark.e2e
|
||||
@pytest.mark.timeout(600, method="thread")
|
||||
def test_coloured_text_is_what_retail_windows_draws(firefox_binary, engine_at_least):
|
||||
engine_at_least("firefox-65")
|
||||
engine_at_least("firefox-64")
|
||||
refs = _refs()
|
||||
assert refs["colors"]["count"] == len(refs["colors"]["cases"]) == 14
|
||||
got = _launch(firefox_binary, refs, None, {})
|
||||
@@ -128,7 +128,7 @@ def _keys():
|
||||
@pytest.mark.parametrize("tag", _keys())
|
||||
def test_text_under_a_cleartype_key_is_what_retail_windows_draws(
|
||||
tag, firefox_binary, engine_at_least):
|
||||
engine_at_least("firefox-65")
|
||||
engine_at_least("firefox-64")
|
||||
refs = _refs()
|
||||
k = refs["keys"][tag]
|
||||
want_black, want_colors = _want(k["black"]), _want(k["colors"])
|
||||
|
||||
@@ -58,7 +58,7 @@ from invisible_playwright import InvisiblePlaywright
|
||||
@pytest.mark.e2e
|
||||
@pytest.mark.timeout(1800, method="thread")
|
||||
def test_canvas_text_is_what_retail_windows_draws(firefox_binary, engine_at_least):
|
||||
engine_at_least("firefox-65")
|
||||
engine_at_least("firefox-64")
|
||||
refs_path = DATA / "refs.json"
|
||||
if not refs_path.is_file():
|
||||
pytest.fail("tests/data/canvas_text_ref/refs.json is missing: it is the reference "
|
||||
|
||||
@@ -1,128 +0,0 @@
|
||||
"""scripts/ci_lab_geoip.py: the GeoIP database of a CI leg is made by the repository, the same bytes on every run, and a leg says what it ran with."""
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def _load():
|
||||
spec = importlib.util.spec_from_file_location("ci_lab_geoip_under_test", ROOT / "scripts" / "ci_lab_geoip.py")
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
lab = _load()
|
||||
EXITS = {"germany": lab.addr(1, 178, 10, 5), "japan": lab.addr(1, 0, 16, 5), "india": lab.addr(1, 6, 0, 5), "australia": lab.addr(1, 0, 4, 5),
|
||||
"brazil": lab.addr(1, 178, 32, 5), "united_states": lab.addr(1, 32, 239, 5)}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def database(tmp_path):
|
||||
path = tmp_path / lab.FILE_NAME
|
||||
path.write_bytes(lab.build_bytes())
|
||||
return path
|
||||
|
||||
|
||||
def test_the_same_bytes_on_every_run_and_the_pin_is_their_hash():
|
||||
first, second = lab.build_bytes(), lab.build_bytes()
|
||||
assert first == second
|
||||
pin = lab.load_pin(ROOT / "ci" / "geoip.json")
|
||||
assert lab.sha256_of_bytes(first) == pin["mmdb_sha256"], "the table of scripts/ci_lab_geoip.py and ci/geoip.json changed apart"
|
||||
assert len(first) == pin["mmdb_bytes"]
|
||||
|
||||
|
||||
def test_the_exits_of_the_realness_suite_are_the_networks_of_the_database():
|
||||
support = (ROOT / "tests" / "_realness_support.py").read_text(encoding="utf-8")
|
||||
for label, address in EXITS.items():
|
||||
assert '"%s": _address(%s)' % (label, ", ".join(address.split("."))) in support, "%s moved in tests/_realness_support.py" % label
|
||||
net = ".".join(address.split(".")[:3]) + ".0/24"
|
||||
assert net in lab.NETWORKS, "%s (%s) is not a network of the lab database" % (label, address)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mode", ["MODE_MMAP_EXT", "MODE_MMAP", "MODE_FILE", "MODE_MEMORY"])
|
||||
def test_every_reader_of_maxminddb_opens_it(database, mode):
|
||||
maxminddb = pytest.importorskip("maxminddb")
|
||||
if not hasattr(maxminddb, mode):
|
||||
pytest.skip("no %s in this maxminddb" % mode)
|
||||
with maxminddb.open_database(str(database), mode=getattr(maxminddb, mode)) as reader:
|
||||
record = reader.get(EXITS["germany"])
|
||||
assert record["country"]["iso_code"] == "DE" and record["location"]["time_zone"] == "Europe/Berlin"
|
||||
|
||||
|
||||
def test_the_core_reads_what_it_reads_from_it(database):
|
||||
from invisible_core._geo import ip_to_coordinates, ip_to_country, ip_to_timezone
|
||||
|
||||
for cidr, (country, zone, lat, lon) in lab.NETWORKS.items():
|
||||
ip = cidr.split("/")[0].rsplit(".", 1)[0] + ".5"
|
||||
assert ip_to_country(ip, database) == country
|
||||
assert ip_to_timezone(ip, database) == zone
|
||||
assert ip_to_coordinates(ip, database) == (lat, lon)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("address", ["198.51.100.4", "198.51.100.5", "198.51.100.6", "198.51.100.9", "203.0.113.7", "127.0.0.1",
|
||||
"2001:db8::1", "::1"])
|
||||
def test_an_address_that_is_not_in_it_is_not_in_the_database_and_never_an_error(database, address):
|
||||
from invisible_core._geo import GeoTimezoneError, ip_to_country, ip_to_timezone
|
||||
|
||||
assert ip_to_country(address, database) is None
|
||||
with pytest.raises(GeoTimezoneError) as caught:
|
||||
ip_to_timezone(address, database)
|
||||
assert caught.value.kind == "ip_not_in_db"
|
||||
|
||||
|
||||
def test_a_writer_that_no_longer_makes_the_pinned_bytes_is_refused_and_exports_nothing(tmp_path, monkeypatch, capsys):
|
||||
pin = tmp_path / "geoip.json"
|
||||
pin.write_text(json.dumps({"mmdb_sha256": "0" * 64}), encoding="utf-8")
|
||||
env_file = tmp_path / "github_env"
|
||||
monkeypatch.setenv("GITHUB_ENV", str(env_file))
|
||||
code = lab.main(["build", "--pin", str(pin), "--dest", str(tmp_path / "dest")])
|
||||
assert code == 1 and not env_file.exists() and not (tmp_path / "dest" / lab.FILE_NAME).exists()
|
||||
assert "change both in one commit" in capsys.readouterr().err
|
||||
|
||||
|
||||
def test_a_pin_that_is_not_a_pin_is_refused(tmp_path):
|
||||
bad = tmp_path / "geoip.json"
|
||||
for text in ("not json", "{}", json.dumps({"mmdb_sha256": "xyz"})):
|
||||
bad.write_text(text, encoding="utf-8")
|
||||
with pytest.raises(lab.Refused):
|
||||
lab.load_pin(bad)
|
||||
|
||||
|
||||
def test_the_evidence_is_what_the_environment_says(tmp_path):
|
||||
db = tmp_path / "db.mmdb"
|
||||
db.write_bytes(b"x")
|
||||
assert lab.evidence({lab.ENV: str(db)})["exists"] is True
|
||||
assert lab.evidence({}) == {"env": "", "exists": False, "sha256": None}
|
||||
assert lab.evidence({lab.ENV: str(tmp_path / "no")}) == {"env": str(tmp_path / "no"), "exists": False, "sha256": None}
|
||||
|
||||
|
||||
def test_the_evidence_command_writes_the_file_the_judge_reads(tmp_path, monkeypatch):
|
||||
out = tmp_path / "result" / "geoip.json"
|
||||
monkeypatch.delenv(lab.ENV, raising=False)
|
||||
assert lab.main(["evidence", "--out", str(out)]) == 0
|
||||
assert json.loads(out.read_text(encoding="utf-8")) == {"env": "", "exists": False, "sha256": None}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("address", [lab.addr(20, 118, 230, 145), lab.addr(8, 8, 8, 8), lab.addr(1, 178, 11, 5), lab.addr(52, 0, 0, 1), lab.addr(223, 255, 255, 1)])
|
||||
def test_a_public_address_that_is_not_a_lab_network_answers_the_declared_record(database, address):
|
||||
"""A launch with no proxy asks the database for the egress address of the runner, which is not known in advance (run 43351424907 of PR 486: 495
|
||||
errors "egress IP ... not present in the geoip database", every one from a test that launches without a proxy). One declared record answers it."""
|
||||
from invisible_core._geo import ip_to_country, ip_to_timezone
|
||||
|
||||
country, zone, _lat, _lon = lab.FALLBACK
|
||||
assert ip_to_country(address, database) == country and ip_to_timezone(address, database) == zone
|
||||
|
||||
|
||||
def test_the_fallback_cuts_out_every_network_of_the_table_and_every_reserved_range():
|
||||
import ipaddress
|
||||
|
||||
cut = lab.fallback_networks()
|
||||
for net in [ipaddress.ip_network(c) for c in lab.NETWORKS] + list(lab.RESERVED):
|
||||
assert not any(n.overlaps(net) for n in cut), "%s is covered by the fallback" % net
|
||||
assert sum(n.num_addresses for n in cut) + sum(ipaddress.ip_network(c).num_addresses for c in lab.NETWORKS) + sum(n.num_addresses for n in lab.RESERVED) == 1 << 32
|
||||
@@ -1,71 +0,0 @@
|
||||
"""scripts/ci_lab_geoip.py verify: the leg ran with the pinned database and the core never went past it to GitHub; and `build` says where the record goes."""
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def _load():
|
||||
spec = importlib.util.spec_from_file_location("ci_lab_geoip_verify_under_test", ROOT / "scripts" / "ci_lab_geoip.py")
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
lab = _load()
|
||||
PIN = ROOT / "ci" / "geoip.json"
|
||||
|
||||
|
||||
def _proof(tmp_path, name, **fields):
|
||||
data = {"env": "/db/geoip-aio-all.mmdb", "exists": True, "sha256": lab.load_pin(PIN)["mmdb_sha256"]}
|
||||
data.update(fields)
|
||||
path = tmp_path / name
|
||||
path.write_text(json.dumps(data), encoding="utf-8")
|
||||
return path
|
||||
|
||||
|
||||
def test_build_exports_the_variable_and_the_place_of_the_record_of_use(tmp_path, monkeypatch, capsys):
|
||||
env_file = tmp_path / "github_env"
|
||||
monkeypatch.setenv("GITHUB_ENV", str(env_file))
|
||||
assert lab.main(["build", "--pin", str(PIN), "--dest", str(tmp_path / "dest")]) == 0
|
||||
path = (tmp_path / "dest" / lab.FILE_NAME).resolve()
|
||||
used = path.parent / "geoip-used.json"
|
||||
assert env_file.read_text(encoding="utf-8") == "STEALTHFOX_GEOIP_MMDB=%s\nGEOIP_USED_OUT=%s\n" % (path, used)
|
||||
assert "GEOIP_USED_OUT=%s" % used in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_a_leg_with_the_pinned_database_and_no_question_to_github_verifies(tmp_path):
|
||||
evidence = _proof(tmp_path, "evidence.json")
|
||||
used = _proof(tmp_path, "used.json", asked_github=0)
|
||||
assert lab.verify(lab.load_pin(PIN), evidence, used) == []
|
||||
assert lab.main(["verify", "--pin", str(PIN), "--evidence", str(evidence), "--used", str(used)]) == 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize("fields, said", [({"env": "", "exists": False, "sha256": None}, "was not set"),
|
||||
({"exists": False, "sha256": None}, "is not a file"),
|
||||
({"sha256": "d" * 64}, "the pin says")])
|
||||
def test_evidence_of_a_leg_without_the_database_does_not_verify(tmp_path, fields, said):
|
||||
problems = lab.verify(lab.load_pin(PIN), _proof(tmp_path, "evidence.json", **fields))
|
||||
assert len(problems) == 1 and said in problems[0], problems
|
||||
|
||||
|
||||
def test_a_core_that_went_past_the_variable_to_github_does_not_verify(tmp_path):
|
||||
problems = lab.verify(lab.load_pin(PIN), _proof(tmp_path, "evidence.json"), _proof(tmp_path, "used.json", asked_github=3))
|
||||
assert len(problems) == 1 and "asked GitHub" in problems[0] and "3 time" in problems[0]
|
||||
|
||||
|
||||
def test_a_variable_gone_by_the_end_of_the_run_does_not_verify(tmp_path):
|
||||
used = _proof(tmp_path, "used.json", env="", exists=False, sha256=None, asked_github=0)
|
||||
problems = lab.verify(lab.load_pin(PIN), _proof(tmp_path, "evidence.json"), used)
|
||||
assert len(problems) == 1 and "record of use" in problems[0]
|
||||
|
||||
|
||||
def test_a_record_that_is_not_there_does_not_verify(tmp_path):
|
||||
problems = lab.verify(lab.load_pin(PIN), _proof(tmp_path, "evidence.json"), tmp_path / "none.json")
|
||||
assert len(problems) == 1 and "cannot be read" in problems[0]
|
||||
assert lab.main(["verify", "--pin", str(PIN), "--evidence", str(tmp_path / "none.json")]) == 1
|
||||
@@ -1,109 +0,0 @@
|
||||
"""scripts/ci_real_geoip_check.py, the three checks on the REAL database that only the release runs: here against databases made on the spot."""
|
||||
import importlib.util
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def _load(name):
|
||||
spec = importlib.util.spec_from_file_location(name + "_under_test", ROOT / "scripts" / (name + ".py"))
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
check = _load("ci_real_geoip_check")
|
||||
lab = check.lab
|
||||
|
||||
|
||||
def _database(tmp_path, name, networks=None):
|
||||
"""A database made like the lab one, from `networks` (the table of the script when None)."""
|
||||
old = dict(lab.NETWORKS)
|
||||
try:
|
||||
if networks is not None:
|
||||
lab.NETWORKS.clear()
|
||||
lab.NETWORKS.update(networks)
|
||||
path = tmp_path / name
|
||||
path.write_bytes(lab.build_bytes())
|
||||
return path
|
||||
finally:
|
||||
lab.NETWORKS.clear()
|
||||
lab.NETWORKS.update(old)
|
||||
|
||||
|
||||
def _database_without_fallback(tmp_path, name):
|
||||
"""The lab table alone, with no record for the other public addresses: a database that has no answer for 8.8.8.8."""
|
||||
old = lab.FALLBACK
|
||||
lab.FALLBACK = None
|
||||
try:
|
||||
return _database(tmp_path, name)
|
||||
finally:
|
||||
lab.FALLBACK = old
|
||||
|
||||
|
||||
def test_the_exit_of_a_network_is_the_dot_five_of_its_slash_24():
|
||||
assert check.exit_of(lab.net(1, 178, 10)) == lab.addr(1, 178, 10, 5)
|
||||
|
||||
|
||||
def test_a_database_that_agrees_passes_the_comparison_and_the_zones(tmp_path, capsys):
|
||||
real = _database(tmp_path, "real.mmdb")
|
||||
ours = _database(tmp_path, "lab.mmdb")
|
||||
assert check.check_lab_agrees(real, ours) == []
|
||||
assert check.check_zones(real) == []
|
||||
assert "distinct zones" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_a_zone_that_differs_is_said_with_the_network(tmp_path):
|
||||
changed = dict(lab.NETWORKS)
|
||||
changed[lab.net(1, 0, 16)] = ("JP", "Asia/Seoul", 35.0, 139.0)
|
||||
real = _database(tmp_path, "real.mmdb", changed)
|
||||
ours = _database(tmp_path, "lab.mmdb")
|
||||
problems = check.check_lab_agrees(real, ours)
|
||||
assert len(problems) == 1 and lab.net(1, 0, 16) in problems[0] and "Asia/Seoul" in problems[0]
|
||||
|
||||
|
||||
def test_a_network_the_real_database_does_not_have_is_said(tmp_path):
|
||||
real = _database(tmp_path, "real.mmdb", {lab.net(1, 178, 10): lab.NETWORKS[lab.net(1, 178, 10)]})
|
||||
ours = _database(tmp_path, "lab.mmdb")
|
||||
problems = check.check_lab_agrees(real, ours)
|
||||
assert len(problems) == len(lab.NETWORKS) - 1
|
||||
|
||||
|
||||
def test_a_zone_the_runner_does_not_know_is_a_finding(tmp_path):
|
||||
odd = dict(lab.NETWORKS)
|
||||
odd[lab.net(1, 6, 0)] = ("IN", "Mars/Olympus_Mons", 1.0, 1.0)
|
||||
real = _database(tmp_path, "real.mmdb", odd)
|
||||
problems = check.check_zones(real)
|
||||
assert len(problems) == 1 and "Mars/Olympus_Mons" in problems[0]
|
||||
|
||||
|
||||
def test_a_database_that_does_not_open_or_has_no_country_is_a_finding(tmp_path):
|
||||
broken = tmp_path / "broken.mmdb"
|
||||
broken.write_bytes(b"not a database")
|
||||
assert check.check_open_and_answer(broken)
|
||||
assert check.check_open_and_answer(_database_without_fallback(tmp_path, "lab.mmdb")) # no 8.8.8.8 in it: no country
|
||||
|
||||
|
||||
def test_the_command_takes_no_argument():
|
||||
assert check.main(["--something"]) == 2
|
||||
|
||||
|
||||
def test_the_product_road_is_the_one_without_the_variable_and_with_a_cold_cache(tmp_path, monkeypatch):
|
||||
seen = {}
|
||||
|
||||
def fake():
|
||||
seen["variable"] = os.environ.get("STEALTHFOX_GEOIP_MMDB")
|
||||
seen["cache"] = os.environ.get("INVISIBLE_PLAYWRIGHT_CACHE_DIR")
|
||||
return tmp_path / "x.mmdb"
|
||||
|
||||
monkeypatch.setenv("STEALTHFOX_GEOIP_MMDB", "/somewhere")
|
||||
monkeypatch.setenv("INVISIBLE_PLAYWRIGHT_CACHE_DIR", "/before")
|
||||
import invisible_core.download as download
|
||||
monkeypatch.setattr(download, "ensure_geoip_mmdb", fake)
|
||||
assert check.product_download(tmp_path / "cold") == tmp_path / "x.mmdb"
|
||||
assert seen == {"variable": None, "cache": str(tmp_path / "cold")}
|
||||
@@ -1,41 +0,0 @@
|
||||
"""scripts/ci_real_geoip_check.py exits 3 when no database came (the network): that says nothing about the database, and the release is run again."""
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def _load():
|
||||
spec = importlib.util.spec_from_file_location("ci_real_geoip_exit_under_test", ROOT / "scripts" / "ci_real_geoip_check.py")
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
check = _load()
|
||||
|
||||
|
||||
def test_a_database_that_did_not_come_is_exit_3_and_not_a_finding(monkeypatch, capsys):
|
||||
def no_network(cache):
|
||||
raise OSError("name resolution failed")
|
||||
|
||||
monkeypatch.setattr(check, "product_download", no_network)
|
||||
assert check.main([]) == check.EXIT_NO_DATABASE == 3
|
||||
assert "NO DATABASE" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_a_database_that_came_and_fails_a_check_is_exit_1_and_names_the_check(tmp_path, monkeypatch, capsys):
|
||||
lab = check.lab
|
||||
broken = tmp_path / "geoip-aio-all.mmdb"
|
||||
with monkeypatch.context() as m:
|
||||
m.setattr(lab, "FALLBACK", None) # no record for 8.8.8.8 in the lab database: the first check fails
|
||||
broken.write_bytes(lab.build_bytes())
|
||||
monkeypatch.setattr(check, "product_download", lambda cache: broken)
|
||||
assert check.main([]) == 1
|
||||
out = capsys.readouterr().out
|
||||
assert "sha256 %s" % lab.sha256_of(broken) in out and "1. it opens with the reader of the core and answers for an address: FAILED" in out
|
||||
assert "2. the lab database agrees" in out and "3. every time_zone" in out
|
||||
@@ -316,53 +316,6 @@ def test_a_seal_that_cannot_be_read_is_red(tmp_path, capsys):
|
||||
assert code == 1 and "cannot be read" in capsys.readouterr().out
|
||||
|
||||
|
||||
# --- the GeoIP database of the leg ---------------------------------------------------------------------------------
|
||||
MMDB_SHA = "c" * 64
|
||||
|
||||
|
||||
def _geoip(tmp_path, **evidence):
|
||||
pin = tmp_path / "geoip.json"
|
||||
pin.write_text(json.dumps({"mmdb_sha256": MMDB_SHA}), encoding="utf-8")
|
||||
proof = tmp_path / "geoip-evidence.json"
|
||||
base = {"env": "/db/geoip-aio-all.mmdb", "exists": True, "sha256": MMDB_SHA}
|
||||
base.update(evidence)
|
||||
proof.write_text(json.dumps(base), encoding="utf-8")
|
||||
return ["--geoip", str(proof), "--geoip-pin", str(pin)]
|
||||
|
||||
|
||||
def test_a_leg_that_ran_with_the_database_of_the_pin_is_green(tmp_path):
|
||||
code, result = _judge(tmp_path, GREEN, extra=_geoip(tmp_path))
|
||||
assert code == 0 and result["geoip_sha256"] == MMDB_SHA
|
||||
|
||||
|
||||
def test_a_leg_launched_without_the_variable_is_red(tmp_path, capsys):
|
||||
code, result = _judge(tmp_path, GREEN, extra=_geoip(tmp_path, env="", exists=False, sha256=None))
|
||||
out = capsys.readouterr().out
|
||||
assert code == 1 and result["verdict"] == "red" and "without STEALTHFOX_GEOIP_MMDB" in out
|
||||
|
||||
|
||||
def test_a_variable_that_names_no_file_is_red(tmp_path, capsys):
|
||||
code, _r = _judge(tmp_path, GREEN, extra=_geoip(tmp_path, exists=False, sha256=None))
|
||||
assert code == 1 and "is not a file" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_a_database_that_is_not_the_one_of_the_pin_is_red(tmp_path, capsys):
|
||||
code, _r = _judge(tmp_path, GREEN, extra=_geoip(tmp_path, sha256="d" * 64))
|
||||
assert code == 1 and "the pin" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_evidence_that_is_missing_or_unreadable_is_red(tmp_path, capsys):
|
||||
code, _r = _judge(tmp_path, GREEN, extra=["--geoip", str(tmp_path / "none.json"), "--geoip-pin", str(tmp_path / "geoip.json")])
|
||||
assert code == 1 and "did not say which database" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_a_pin_that_cannot_be_read_is_red(tmp_path, capsys):
|
||||
extra = _geoip(tmp_path)
|
||||
(tmp_path / "geoip.json").write_text("not json", encoding="utf-8")
|
||||
code, _r = _judge(tmp_path, GREEN, extra=extra)
|
||||
assert code == 1 and "pin of the GeoIP database" in capsys.readouterr().out
|
||||
|
||||
|
||||
# --- exact, every test of a file, xunit2 ---------------------------------------------------------------------------
|
||||
def test_an_exact_suite_with_more_tests_than_min_tests_is_red(tmp_path, capsys):
|
||||
cases = GREEN + [_case(FILE_B, "test_new")]
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
"""The workflows that run the wrapper's tests launch with the GeoIP database of ci/geoip.json; the release alone looks at the real one.
|
||||
|
||||
Without STEALTHFOX_GEOIP_MMDB the core asks GitHub which database is the latest on every call (run 43211837926). tests.yml and e2e.yml (its Linux run and its Windows parts) make
|
||||
the database (scripts/ci_lab_geoip.py: the same bytes every run, no download) BEFORE the step that runs pytest. user-install.yml proves the installation a user
|
||||
gets and is left as it is. publish.yml is the release: it runs the three checks on the REAL database (scripts/ci_real_geoip_check.py) before it uploads, and
|
||||
nothing else touches it.
|
||||
"""
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
WORKFLOWS = Path(__file__).resolve().parents[1] / ".github" / "workflows"
|
||||
BUILD = "scripts/ci_lab_geoip.py build"
|
||||
REAL = "scripts/ci_real_geoip_check.py"
|
||||
RUNS_PYTEST = {
|
||||
"tests.yml": " - name: Run pytest\n",
|
||||
"e2e.yml": " - name: Run the full e2e suite under a virtual display, without the root ones\n",
|
||||
"e2e.yml#windows": " - name: Run this part of the e2e\n",
|
||||
}
|
||||
|
||||
|
||||
def _scope(name):
|
||||
"""The text of one workflow, or of one leg of it: `e2e.yml` is its Linux job, `e2e.yml#windows` its Windows parts."""
|
||||
file, _, leg = name.partition("#")
|
||||
text = (WORKFLOWS / file).read_text(encoding="utf-8")
|
||||
if file != "e2e.yml":
|
||||
return text
|
||||
windows = text.index("\n e2e-windows:\n")
|
||||
if leg == "windows":
|
||||
return text[windows:]
|
||||
ends = [i for i in (text.find("\n e2e-windows-control-a:\n"), windows) if i >= 0]
|
||||
return text[:min(ends)]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name, pytest_step", sorted(RUNS_PYTEST.items()))
|
||||
def test_the_database_is_made_before_the_step_that_runs_the_tests(name, pytest_step):
|
||||
text = _scope(name)
|
||||
assert text.count(BUILD) == 1, "%s makes the GeoIP database %d times" % (name, text.count(BUILD))
|
||||
assert pytest_step in text, "the step that runs the tests of %s moved: update this test with it" % name
|
||||
assert text.index(BUILD) < text.index(pytest_step), "%s makes the database after the tests started" % name
|
||||
assert REAL not in text, "the real database is the release's alone"
|
||||
|
||||
|
||||
def test_the_workflow_that_proves_the_installation_is_left_alone():
|
||||
text = (WORKFLOWS / "user-install.yml").read_text(encoding="utf-8")
|
||||
assert BUILD not in text and REAL not in text
|
||||
|
||||
|
||||
def test_the_release_checks_the_real_database_before_it_uploads_and_makes_no_lab_one():
|
||||
text = (WORKFLOWS / "publish.yml").read_text(encoding="utf-8")
|
||||
assert text.count("python " + REAL) == 1 and BUILD not in text
|
||||
assert " real-geoip-database:\n" in text
|
||||
assert "needs: [already-published, gate, real-geoip-database]" in text, "the upload does not wait for the real database"
|
||||
# and no other workflow runs the real checks
|
||||
for other in sorted(WORKFLOWS.glob("*.yml")):
|
||||
if other.name != "publish.yml":
|
||||
assert REAL not in other.read_text(encoding="utf-8"), "%s runs the checks of the release" % other.name
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name, pytest_step", sorted(RUNS_PYTEST.items()))
|
||||
def test_the_leg_verifies_after_the_tests_that_it_ran_with_the_pinned_database(name, pytest_step):
|
||||
text = _scope(name)
|
||||
step = " - name: The leg ran with the pinned GeoIP database\n if: always()\n"
|
||||
assert text.count(step) == 1 and "ci_lab_geoip.py verify" in text, name
|
||||
assert text.index(pytest_step) < text.index(step), "%s verifies before the tests ran" % name
|
||||
@@ -22,7 +22,6 @@ import pytest
|
||||
from invisible_core import SessionGeo, SessionLocale, decide_session_locale
|
||||
from invisible_core.juggler.connection import EventListeners
|
||||
from invisible_playwright._juggler.server import BrowserDispatcher, Server
|
||||
from _browser_census import closes_with_the_test
|
||||
|
||||
_PKG_DIR = pathlib.Path(__file__).resolve().parent.parent / "src" / "invisible_playwright"
|
||||
|
||||
@@ -30,7 +29,6 @@ _PKG_DIR = pathlib.Path(__file__).resolve().parent.parent / "src" / "invisible_p
|
||||
class _Connection(EventListeners):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
closes_with_the_test(self)
|
||||
self.sent = []
|
||||
|
||||
def startup_send(self, method, params=None):
|
||||
|
||||
@@ -89,11 +89,11 @@ def test_a_context_that_is_the_only_proxy_resolves_its_names_by_doh_through_it(f
|
||||
assert _asked_outside(doh, "page-a.test") == [], (
|
||||
"the DoH was asked for a name that is not the proxied context's: the default context, which has no proxy, must "
|
||||
"resolve natively and never use the DoH: %s" % _asked_outside(doh, "page-a.test") + why)
|
||||
# A lookup of a context without `ignore_https_errors` (the default one) can only REFUSE the FakeDoh's certificate: a refusal
|
||||
# is a lookup of the wrong context that reached the DoH through this gateway (a dropped connection is not one).
|
||||
assert doh.certificate_refusals() == [], (
|
||||
"a DoH handshake was refused: a context that does not accept the FakeDoh certificate (the default context, which has no "
|
||||
"proxy) used the DoH: %s (every failed handshake: %s)" % (doh.certificate_refusals(), doh.tls_failures) + why)
|
||||
# A lookup of a context without `ignore_https_errors` (the default one) can only fail the handshake with the FakeDoh:
|
||||
# a failed handshake is a lookup of the wrong context that reached the DoH through this gateway.
|
||||
assert doh.tls_failures == [], (
|
||||
"a DoH handshake failed: a context that does not accept the FakeDoh certificate (the default context, which has no "
|
||||
"proxy) used the DoH: %s" % doh.tls_failures + why)
|
||||
|
||||
assert watcher.watched_pids, ("the watcher never saw a browser process (it saw: %s): a watcher that cannot see proves "
|
||||
"nothing" % watcher.process_names)
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
"""``Control+A`` selects all in an <input> and a <textarea>, in-process and served to the stock Playwright client, as it does on the stock Firefox.
|
||||
|
||||
Measured on the published wrapper 0.50.1 and on the engine of the giro 7 (Docker Linux, a field with 11 characters, focus, the selection collapsed
|
||||
before each press): ``press("Control+A")``, ``press("ControlOrMeta+A")``, ``down("Control")`` + ``press("A")`` + ``up("Control")`` and
|
||||
``locator.press("Control+A")`` left ``selectionStart == selectionEnd == 0``; ``press("Control+a")`` selected all (0, 11); the stock Firefox of
|
||||
Playwright selected all with every one of them. Cause: the keyboard of invisible_core held Shift for the capital ``A`` (a character that only
|
||||
exists with Shift), so the browser got Control+Shift+A, which is not the select-all command (juggler/keyboard.py, ``_shortcut_letter``).
|
||||
|
||||
What a page reads here is only ``selectionStart`` and ``selectionEnd`` after the shortcut: the same on every machine.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
_HTML = '<html><body><input id="i" value="hello world"><br><textarea id="t">hello world</textarea></body></html>'
|
||||
_LENGTH = len("hello world")
|
||||
|
||||
_VARIANTS = ["Control+A", "Control+a", "ControlOrMeta+A", "separate", "locator.press"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("variant", _VARIANTS)
|
||||
@pytest.mark.parametrize("field", ["i", "t"])
|
||||
def test_control_a_selects_all_in_the_field(browser, field, variant):
|
||||
page = browser.new_page()
|
||||
try:
|
||||
page.set_content(_HTML)
|
||||
page.evaluate("(id) => { const e = document.getElementById(id); e.focus(); e.setSelectionRange(0, 0); }", field)
|
||||
if variant == "separate":
|
||||
page.keyboard.down("Control")
|
||||
page.keyboard.press("A")
|
||||
page.keyboard.up("Control")
|
||||
elif variant == "locator.press":
|
||||
page.locator("#" + field).press("Control+A")
|
||||
else:
|
||||
page.keyboard.press(variant)
|
||||
got = page.evaluate(
|
||||
"(id) => { const e = document.getElementById(id); return [e.selectionStart, e.selectionEnd, document.activeElement.id]; }",
|
||||
field)
|
||||
finally:
|
||||
page.close()
|
||||
assert got == [0, _LENGTH, field], (
|
||||
"%s in #%s: selection %r, expected (0, %d) in the same field" % (variant, field, got, _LENGTH))
|
||||
@@ -314,10 +314,6 @@ def test_cross_origin_iframe_frame_locator_resolves_button(firefox_binary, cross
|
||||
page.goto(cross_origin_harness["parent_url"], wait_until="domcontentloaded", timeout=30_000)
|
||||
page.wait_for_selector("iframe#ifr_plain", timeout=10_000)
|
||||
|
||||
# count() does not wait (Playwright's own semantics): the iframe ELEMENT is in the parent, but its cross-origin document,
|
||||
# in a process of its own, can load later on a loaded runner (Windows CI of 13/11, run 43383366904: 0 elements). Wait for
|
||||
# the button first, as a script that counts it would.
|
||||
page.frame_locator("iframe#ifr_plain").locator("button#ok").wait_for(timeout=10_000)
|
||||
for selector in ("button#ok", "button.btn-primary"):
|
||||
cnt = page.frame_locator("iframe#ifr_plain").locator(selector).count()
|
||||
assert cnt == 1, f"locator({selector!r}) found {cnt} elements (expected 1)"
|
||||
|
||||
@@ -73,7 +73,7 @@ def test_the_data_has_every_function_and_the_inputs_that_tell_the_libraries_apar
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_css_calc_functions_are_ucrtbase_bytes(firefox_binary, engine_at_least):
|
||||
engine_at_least("firefox-65")
|
||||
engine_at_least("firefox-64")
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
cases = _cases()
|
||||
|
||||
@@ -32,8 +32,6 @@ import pytest
|
||||
from test_webrtc_realness import _e2e_binary, _launch, candidates, decode_priority, host_candidates, is_mdns # noqa: F401
|
||||
|
||||
pytestmark = [pytest.mark.e2e, pytest.mark.usefixtures("the_udp_line")]
|
||||
# The two tests that read a consecutive pair of ports (N, N+1) carry `wall_clock`: the e2e run gives them the machine alone, after the parallel tests,
|
||||
# so that another worker's browser or test server cannot take port N+1 between the engine's draw and the bind (tests/test_the_consecutive_port_tests_run_serially.py).
|
||||
|
||||
NETWORK_ENV = "STEALTHFOX_WEBRTC_NETWORK"
|
||||
# retail 159 on Windows. The interface rank is the position in the prioritizer's sort, starting at 127
|
||||
@@ -160,7 +158,6 @@ def test_ipv6_without_the_exit_prefix_is_no_ipv6(local_https_page, socks5_tcp_on
|
||||
assert _by_protocol(hosts) == {"UDP": [UDP_127], "TCP": [TCP_127]}, hosts
|
||||
|
||||
|
||||
@pytest.mark.wall_clock
|
||||
def test_the_host_ports_are_those_of_a_windows_machine(local_https_page, socks5_tcp_only, monkeypatch):
|
||||
"""Retail on Windows (6 of 6 runs, ``captures/retail/firefox-159.0-win/direct-dualstack-srflx-ports``): the UDP host
|
||||
ports are in the dynamic range 49152-65535 and, on one connection, the IPv4 port and the IPv6 port are consecutive
|
||||
@@ -191,7 +188,6 @@ def _ports_of_two_connections(declaration, socks, page_url, monkeypatch, seed):
|
||||
sorted(c["port"] for c in second if c["proto"] == "UDP"))
|
||||
|
||||
|
||||
@pytest.mark.wall_clock
|
||||
def test_two_connections_on_one_page_get_their_own_port_pair(local_https_page, socks5_tcp_only, monkeypatch):
|
||||
"""Retail (``captures/retail/firefox-159.0-win/two-pc-port-sequence``, 6 of 6): each connection gets its own pair,
|
||||
consecutive (N, N+1) in the range, and the second pair is unrelated to the first (not increasing)."""
|
||||
|
||||
@@ -86,8 +86,7 @@ def test_the_bootstrap_address_is_a_public_address_and_not_the_proxy(compose):
|
||||
|
||||
def test_a_session_without_a_proxy_declares_the_provider_and_no_state(compose):
|
||||
prefs = compose(None)
|
||||
assert sorted(k for k in prefs if k.startswith("network.trr.")) == ["network.trr.bootstrapAddr", "network.trr.builtin-excluded-domains", "network.trr.uri"]
|
||||
assert prefs["network.trr.builtin-excluded-domains"] == "localhost", "only localhost stays off DoH: a *.local name behind a proxy is not read from the host"
|
||||
assert sorted(k for k in prefs if k.startswith("network.trr.")) == ["network.trr.bootstrapAddr", "network.trr.uri"]
|
||||
assert prefs.get("network.proxy.allow_bypass") is not False, "no proxy, no closed fallback"
|
||||
assert prefs["network.parental_controls_cached_state"] is False, "declared off with or without a proxy"
|
||||
|
||||
|
||||
@@ -96,11 +96,9 @@ def _only_the_doh_road_was_used(doh, gw, watcher):
|
||||
"a CONNECT carried a name: the browser must resolve with the DoH and connect by address" + why)
|
||||
assert "direct" not in {q.via for q in doh.queries}, "something reached the DoH without the proxy of the context" + why
|
||||
_assert_every_connection_went_through_the_gateway(doh, gw)
|
||||
# Context-only layout: the default context resolves natively and never uses the DoH, so a refused certificate (the lookup
|
||||
# Context-only layout: the default context resolves natively and never uses the DoH, so a failed handshake (the lookup
|
||||
# of a context that does not accept the FakeDoh certificate) is a lookup of the wrong context sent to the DoH.
|
||||
assert doh.certificate_refusals() == [], (
|
||||
"a DoH handshake was refused: the default context used the DoH: %s (every failed handshake: %s)"
|
||||
% (doh.certificate_refusals(), doh.tls_failures) + why)
|
||||
assert doh.tls_failures == [], "a DoH handshake failed: the default context used the DoH: %s" % doh.tls_failures + why
|
||||
assert watcher.watched_pids, ("the watcher never saw a browser process (it saw: %s): a watcher that cannot see proves "
|
||||
"nothing" % watcher.process_names)
|
||||
assert _direct_to_the_doh(watcher) == [], (
|
||||
|
||||
@@ -36,16 +36,11 @@ from invisible_core.juggler.connection import EventListeners
|
||||
from invisible_playwright._juggler.server import BrowserDispatcher, Server
|
||||
|
||||
from _servers import LocalServer
|
||||
from _browser_census import closes_with_the_test
|
||||
|
||||
SEED = 106
|
||||
|
||||
|
||||
class _Connection(EventListeners):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
closes_with_the_test(self)
|
||||
|
||||
def startup_send(self, method, params=None):
|
||||
return self.send(method, params, timeout=None)
|
||||
|
||||
|
||||
@@ -1,143 +0,0 @@
|
||||
"""Every test of the product runs on Linux AND on Windows (no browser here).
|
||||
|
||||
Federico, 12/11: a test seen only on Linux proves nothing about the system the product imitates. On that day 562 of the 808
|
||||
e2e of this package had never run on Windows in any round (the e2e of a pull request ran on Linux only, and the candidate's
|
||||
gate carried 246 of them), and two suites of the gate (`wrapper.e2e.udp.exit`, `wrapper.e2e.udp.sandbox`) were Linux only.
|
||||
Where Windows behaves differently the test adapts to the system; it does not stay on one.
|
||||
|
||||
What this holds, reading the files as text (PyYAML is not a dependency of this package):
|
||||
|
||||
* every row of ci/required-suites.json names both systems, or names its Windows twin (`windows_twin`: the id of a row
|
||||
that runs on Windows), or says why it can only be Linux (`linux_only`: a test of Linux converging on Windows, which has
|
||||
no Windows counterpart because Windows IS the reference);
|
||||
* the jobs of e2e.yml that run scripts/run_e2e.py run on a Linux and on a Windows runner between them;
|
||||
* the unit job of tests.yml runs on both.
|
||||
|
||||
Known-bad inputs: the files as they were on 12/11 (two Linux-only rows with no twin; e2e.yml on ubuntu-24.04 only) ->
|
||||
`problems` names each of them.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SUITES = ROOT / "ci" / "required-suites.json"
|
||||
WORKFLOWS = ROOT / ".github" / "workflows"
|
||||
|
||||
|
||||
def suite_problems(rows: list) -> list:
|
||||
out = []
|
||||
windows_ids = {r["id"] for r in rows if "windows" in r.get("os", [])}
|
||||
for r in rows:
|
||||
systems = set(r.get("os", []))
|
||||
if {"linux", "windows"} <= systems:
|
||||
continue
|
||||
twin = r.get("windows_twin")
|
||||
reason = (r.get("linux_only") or "").strip()
|
||||
if "windows" not in systems and twin:
|
||||
if twin not in windows_ids:
|
||||
out.append("%s: its windows_twin %r is not a row that runs on Windows" % (r["id"], twin))
|
||||
continue
|
||||
if "windows" not in systems and reason:
|
||||
continue
|
||||
missing = sorted({"linux", "windows"} - systems)
|
||||
out.append("%s runs on %s only: it needs %s, a windows_twin, or a linux_only reason"
|
||||
% (r["id"], "/".join(sorted(systems)) or "nothing", " and ".join(missing)))
|
||||
return out
|
||||
|
||||
|
||||
def _jobs(text: str) -> list:
|
||||
"""(name, body) of each job under `jobs:` (two-space indentation, as every workflow here is written)."""
|
||||
body = text.split("\njobs:\n", 1)[1] if "\njobs:\n" in text else ""
|
||||
marks = list(re.finditer(r"^ ([A-Za-z0-9_-]+):\s*$", body, re.M))
|
||||
return [(m.group(1), body[m.start():(marks[i + 1].start() if i + 1 < len(marks) else len(body))]) for i, m in enumerate(marks)]
|
||||
|
||||
|
||||
def _runs_on_both(job: str) -> bool:
|
||||
runners = re.findall(r"\b(ubuntu-[0-9a-z.]+|windows-[0-9a-z.]+)\b", job)
|
||||
return any(r.startswith("ubuntu") for r in runners) and any(r.startswith("windows") for r in runners)
|
||||
|
||||
|
||||
def workflow_problems(e2e_text: str, tests_text: str) -> list:
|
||||
out = []
|
||||
e2e = [(n, b) for n, b in _jobs(e2e_text) if "scripts/run_e2e.py" in b]
|
||||
if not e2e:
|
||||
out.append("e2e.yml has no job that runs scripts/run_e2e.py")
|
||||
elif not _runs_on_both(" ".join(b for _n, b in e2e)):
|
||||
out.append("the jobs of e2e.yml that run scripts/run_e2e.py (%s) do not run on both a Linux and a Windows runner"
|
||||
% ", ".join(n for n, _b in e2e))
|
||||
unit = [(n, b) for n, b in _jobs(tests_text) if re.search(r"python -m pytest|pytest ", b) and "matrix" in b]
|
||||
if not unit:
|
||||
out.append("tests.yml has no unit job with a matrix")
|
||||
for name, body in unit:
|
||||
if not _runs_on_both(body):
|
||||
out.append("tests.yml job %r does not run on both a Linux and a Windows runner" % name)
|
||||
return out
|
||||
|
||||
|
||||
def test_every_suite_of_the_gate_runs_on_both_systems_or_names_its_twin():
|
||||
assert suite_problems(json.loads(SUITES.read_text(encoding="utf-8"))) == []
|
||||
|
||||
|
||||
def test_the_e2e_and_the_unit_tests_of_a_pull_request_run_on_both_systems():
|
||||
assert workflow_problems((WORKFLOWS / "e2e.yml").read_text(encoding="utf-8"),
|
||||
(WORKFLOWS / "tests.yml").read_text(encoding="utf-8")) == []
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------------------- the checkers can fail
|
||||
ROWS_OF_12_11 = [
|
||||
{"id": "wrapper.e2e.udp", "os": ["linux", "windows"]},
|
||||
{"id": "wrapper.e2e.udp.exit", "os": ["linux"]},
|
||||
{"id": "wrapper.e2e.udp.sandbox", "os": ["linux"]},
|
||||
]
|
||||
|
||||
E2E_OF_12_11 = """
|
||||
jobs:
|
||||
core-on-index:
|
||||
uses: ./.github/workflows/core-on-index.yml
|
||||
e2e:
|
||||
name: e2e (linux, xvfb)
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- run: xvfb-run -a python -u scripts/run_e2e.py "$FF"
|
||||
"""
|
||||
|
||||
TESTS_OF_12_11 = """
|
||||
jobs:
|
||||
unit:
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
matrix:
|
||||
include:
|
||||
- { os: ubuntu-latest, python: '3.11' }
|
||||
- { os: windows-latest, python: '3.12' }
|
||||
steps:
|
||||
- run: python -m pytest -m unit
|
||||
"""
|
||||
|
||||
|
||||
def test_the_rows_of_12_11_are_refused():
|
||||
found = suite_problems(ROWS_OF_12_11)
|
||||
assert len(found) == 2 and all("linux only" in p for p in found), found
|
||||
|
||||
|
||||
def test_a_twin_that_does_not_run_on_windows_is_refused():
|
||||
rows = [{"id": "a", "os": ["linux"], "windows_twin": "b"}, {"id": "b", "os": ["linux"]}]
|
||||
assert any("windows_twin 'b' is not a row that runs on Windows" in p for p in suite_problems(rows))
|
||||
|
||||
|
||||
def test_a_twin_or_a_reason_is_accepted():
|
||||
rows = [{"id": "a", "os": ["linux"], "windows_twin": "b"}, {"id": "b", "os": ["windows"], "windows_twin": None},
|
||||
{"id": "c", "os": ["linux"], "linux_only": "Linux converging on Windows: Windows is the reference"}]
|
||||
assert [p for p in suite_problems(rows) if not p.startswith("b ")] == []
|
||||
|
||||
|
||||
def test_the_e2e_of_12_11_is_refused_and_the_unit_job_passes():
|
||||
found = workflow_problems(E2E_OF_12_11, TESTS_OF_12_11)
|
||||
assert found == ["the jobs of e2e.yml that run scripts/run_e2e.py (e2e) do not run on both a Linux and a Windows runner"], found
|
||||
@@ -265,7 +265,7 @@ def test_a_killed_stand_in_leaves_neither_strace_nor_the_browser(firefox_binary,
|
||||
|
||||
|
||||
def test_no_process_reads_the_host_fontconfig(firefox_binary, tmp_path, engine_at_least):
|
||||
engine_at_least("firefox-65")
|
||||
engine_at_least("firefox-64")
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
_require_strace_can_trace(tmp_path)
|
||||
|
||||
@@ -33,11 +33,6 @@ def page():
|
||||
page.injected = Mock()
|
||||
page.actions = Mock()
|
||||
page._frames = {}
|
||||
page._told_attached = set()
|
||||
page._frames_lock = __import__("threading").RLock()
|
||||
page._announce_lock = threading.RLock()
|
||||
page._announced = True
|
||||
page._said_before_announcement = []
|
||||
page._navigation_requests = {}
|
||||
page._announced_closed = False
|
||||
Dispatcher.__init__(page, server, context)
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
"""tests/geoip_used.py: what the core did about the GeoIP database during a run, for `scripts/ci_lab_geoip.py verify`."""
|
||||
import json
|
||||
import sys
|
||||
import types
|
||||
|
||||
import pytest
|
||||
|
||||
import geoip_used
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
|
||||
def _fake_core(monkeypatch):
|
||||
module = types.ModuleType("invisible_core._geoip_db")
|
||||
module.calls = []
|
||||
module._resolve_latest_geoip_tag = lambda: module.calls.append("tag") or "2026.11.04"
|
||||
module._download_geoip_tag = lambda tag, attempts=1: module.calls.append("download") or "x"
|
||||
package = types.ModuleType("invisible_core")
|
||||
package._geoip_db = module
|
||||
monkeypatch.setitem(sys.modules, "invisible_core", package)
|
||||
monkeypatch.setitem(sys.modules, "invisible_core._geoip_db", module)
|
||||
return module
|
||||
|
||||
|
||||
def test_the_recorder_counts_the_questions_to_github_and_gives_the_functions_back(tmp_path, monkeypatch):
|
||||
core = _fake_core(monkeypatch)
|
||||
original = (core._resolve_latest_geoip_tag, core._download_geoip_tag)
|
||||
db = tmp_path / "db.mmdb"
|
||||
db.write_bytes(b"x")
|
||||
monkeypatch.setenv("STEALTHFOX_GEOIP_MMDB", str(db))
|
||||
out = tmp_path / "used" / "geoip-used.json"
|
||||
recorder = geoip_used.GeoipUsedRecorder(str(out))
|
||||
recorder.start()
|
||||
core._resolve_latest_geoip_tag()
|
||||
core._download_geoip_tag("2026.11.04")
|
||||
recorder.pytest_sessionfinish(None, 0)
|
||||
data = json.loads(out.read_text(encoding="utf-8"))
|
||||
assert data["asked_github"] == 2 and data["env"] == str(db) and data["exists"] is True and len(data["sha256"]) == 64
|
||||
assert core.calls == ["tag", "download"], "the real functions were called through"
|
||||
assert (core._resolve_latest_geoip_tag, core._download_geoip_tag) == original, "the functions were given back"
|
||||
|
||||
|
||||
def test_a_run_with_no_variable_is_recorded_as_such(tmp_path, monkeypatch):
|
||||
_fake_core(monkeypatch)
|
||||
monkeypatch.delenv("STEALTHFOX_GEOIP_MMDB", raising=False)
|
||||
out = tmp_path / "geoip-used.json"
|
||||
recorder = geoip_used.GeoipUsedRecorder(str(out))
|
||||
recorder.start()
|
||||
recorder.pytest_sessionfinish(None, 0)
|
||||
assert json.loads(out.read_text(encoding="utf-8")) == {"env": "", "exists": False, "sha256": None, "asked_github": 0}
|
||||
|
||||
|
||||
def test_the_conftest_registers_it_only_when_a_file_is_named():
|
||||
from pathlib import Path
|
||||
|
||||
text = (Path(__file__).parent / "conftest.py").read_text(encoding="utf-8")
|
||||
assert 'os.environ.get("GEOIP_USED_OUT")' in text and "GeoipUsedRecorder" in text
|
||||
@@ -18,46 +18,13 @@ that surface now; what hides the window is WHERE it is created.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import http.server
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
from _screencast_evidence import Stream, engine_screencast_lines
|
||||
from _servers import LocalServer
|
||||
|
||||
# The page the session loads: served by this test from 127.0.0.1, so nothing
|
||||
# here depends on a site of the real web.
|
||||
_PAGE = (b"<!doctype html><html><head><meta charset=utf-8><title>hidden desktop</title>"
|
||||
b"</head><body style=\"background:#fff;color:#000;font:24px sans-serif\">"
|
||||
b"<h1>hidden desktop</h1><p>a page the test serves itself</p></body></html>")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def served():
|
||||
class H(http.server.BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/html; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(_PAGE)))
|
||||
self.end_headers()
|
||||
self.wfile.write(_PAGE)
|
||||
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
with LocalServer(("127.0.0.1", 0), H) as srv:
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
try:
|
||||
yield "http://127.0.0.1:%d/" % srv.server_address[1]
|
||||
finally:
|
||||
srv.shutdown()
|
||||
|
||||
|
||||
_WEBGL_RENDERER = """() => {
|
||||
const g = document.createElement('canvas').getContext('webgl');
|
||||
if (!g) return 'NO-WEBGL';
|
||||
@@ -115,12 +82,12 @@ def _moz_windows_on(desktop_name, session):
|
||||
@pytest.mark.e2e
|
||||
@pytest.mark.skipif(sys.platform != "win32",
|
||||
reason="the hidden desktop is the Windows path; Linux hides via Xvfb")
|
||||
def test_hidden_desktop_takes_the_window_off_screen_but_keeps_rendering(firefox_binary, served):
|
||||
def test_hidden_desktop_takes_the_window_off_screen_but_keeps_rendering(firefox_binary):
|
||||
# Control arm: the enumeration sees a headed window where it should be.
|
||||
headed = InvisiblePlaywright(seed=42, binary_path=firefox_binary, headless=False)
|
||||
with headed as browser:
|
||||
page = browser.new_page()
|
||||
page.goto(served, timeout=30_000)
|
||||
page.goto("https://example.com", timeout=30_000)
|
||||
time.sleep(1.0)
|
||||
assert _moz_windows_on(None, headed) >= 1, (
|
||||
"a headed session left no window on the interactive desktop, so "
|
||||
@@ -129,7 +96,7 @@ def test_hidden_desktop_takes_the_window_off_screen_but_keeps_rendering(firefox_
|
||||
ip = InvisiblePlaywright(seed=42, binary_path=firefox_binary, headless=True)
|
||||
with ip as browser:
|
||||
page = browser.new_page()
|
||||
page.goto(served, timeout=30_000)
|
||||
page.goto("https://example.com", timeout=30_000)
|
||||
time.sleep(2)
|
||||
|
||||
desktop = ip._virtual_display.name
|
||||
@@ -160,16 +127,16 @@ def test_hidden_desktop_takes_the_window_off_screen_but_keeps_rendering(firefox_
|
||||
# for good: 0 frames in 15 s on firefox-33. firefox-34 keeps a
|
||||
# window of another desktop on the window capturer. This is the
|
||||
# line that makes the engine's release gate prove it per build.
|
||||
stream = Stream("hidden desktop")
|
||||
stream.start(page)
|
||||
frames = []
|
||||
|
||||
def on_frame(frame):
|
||||
frames.append(frame)
|
||||
|
||||
page.screencast.start(on_frame=on_frame)
|
||||
deadline = time.time() + 15
|
||||
while not stream.frames and time.time() < deadline:
|
||||
while not frames and time.time() < deadline:
|
||||
time.sleep(0.1)
|
||||
page.screencast.stop()
|
||||
frames = stream.frames
|
||||
assert frames, ("no screencast frame arrived from the hidden desktop "
|
||||
"in 15 s: the window capturer is not being used there\n"
|
||||
"%s\n"
|
||||
"engine output (lines starting with 'screencast:'):\n%s"
|
||||
% (stream.describe(), engine_screencast_lines(page)))
|
||||
"in 15 s: the window capturer is not being used there")
|
||||
assert frames[0]["data"][:3] == b"\xff\xd8\xff", "not a JPEG"
|
||||
@@ -335,7 +335,7 @@ def test_linux_xvfb_workarounds_with_socks_proxy(monkeypatch):
|
||||
|
||||
assert pw_proxy is not None # a single path, here too
|
||||
# Xvfb workarounds present.
|
||||
assert "gfx.webrender.all" not in prefs # core 63.68.0: a pref that does nothing is not declared
|
||||
assert prefs["gfx.webrender.all"] is False
|
||||
# WebGL2 is not the host adapter's decision: since invisible-core 9d74a77 the
|
||||
# engine answers the blocklist from the declared outcomes, and
|
||||
# webgl.force-enabled left the core.
|
||||
|
||||
@@ -111,14 +111,9 @@ def _open(binary, body):
|
||||
srv = LocalServer(("127.0.0.1", 0), _serve(body))
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
c = conn.launch(binary, profile_dir, headless=True, env=plan.env)
|
||||
# ⛔ THE PAGE'S LISTENERS ARE BORN ON THE ATTACH, on the reader thread, before the next event of the session is delivered:
|
||||
# the connection hands each event to the listeners of that moment (dispatch_event copies the list), so a Lifecycle built
|
||||
# later from this thread missed the page's first frameAttached and Page.ready when they came in between, and waited for
|
||||
# ever (Windows CI of 13/11, run 43373058301 part 2: "the engine never said Page.ready (frames seen: [])").
|
||||
sessions: dict = {}
|
||||
c.add_listener(lambda m, p, s: (
|
||||
sessions.__setitem__(p["targetInfo"]["targetId"], (p["sessionId"], Lifecycle(c, p["sessionId"]),
|
||||
InjectedScript(c, p["sessionId"])))
|
||||
sessions.__setitem__(p["targetInfo"]["targetId"], p["sessionId"])
|
||||
if m == "Browser.attachedToTarget" else None))
|
||||
c.send("Browser.enable", {"attachToDefaultContext": True})
|
||||
ctx = c.send("Browser.createBrowserContext", {"removeOnDetach": True})
|
||||
@@ -127,12 +122,11 @@ def _open(binary, body):
|
||||
deadline = time.time() + 20
|
||||
while page["targetId"] not in sessions and time.time() < deadline:
|
||||
time.sleep(0.02)
|
||||
sess, lifecycle, inj = sessions[page["targetId"]]
|
||||
sess = sessions[page["targetId"]]
|
||||
lifecycle = Lifecycle(c, sess)
|
||||
inj = InjectedScript(c, sess)
|
||||
inj.install()
|
||||
# The page is the caller's when the engine says it is ready, as Playwright hands it over (Page.ready); a fixed 0.4 s was a race
|
||||
# that the Windows census lost (run 43307193708: "no frame: the page has not announced its main frame yet", 6 tests).
|
||||
lifecycle.wait_for_page_ready(30)
|
||||
lifecycle.wait_for_main_frame(30)
|
||||
time.sleep(0.4)
|
||||
lifecycle.goto("http://127.0.0.1:%d/" % srv.server_address[1],
|
||||
until="load", timeout=30)
|
||||
actions = Actions(c, sess, lifecycle, inj, acts=PageActs(1),
|
||||
|
||||
@@ -22,7 +22,6 @@ import pytest
|
||||
|
||||
from invisible_playwright._juggler.server import BrowserDispatcher, Server
|
||||
from invisible_core.juggler.connection import EventListeners
|
||||
from _browser_census import closes_with_the_test
|
||||
|
||||
|
||||
class FakeConnection(EventListeners):
|
||||
@@ -30,7 +29,6 @@ class FakeConnection(EventListeners):
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
closes_with_the_test(self)
|
||||
self.sent = []
|
||||
|
||||
def startup_send(self, method, params=None):
|
||||
|
||||
Loaded 100 of 150 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user