Compare commits

..
371 changed files with 29360 additions and 59908 deletions

No files matched your search

-15
View File
@@ -13,18 +13,3 @@
# Linux one. The gate folds CRLF vs LF deliberately, but there is no reason to
# make it do that work.
PUBLISHED.json text eol=lf
# The persona seeds are compared byte for byte with their canonical rendering (tests/test_persona_cover.py): LF on every checkout.
ci/persona-seeds.json text eol=lf
# The wire-method budget is compared with what `dump()` writes, byte for byte
# (tests/test_every_wire_method_is_served_or_refused.py): a Windows runner checks
# out with autocrlf and would hand the test CRLF that nobody wrote.
tests/gates/wire_method_debt.json text eol=lf
# The lock of the gate is hashed byte for byte: its header names the sha256 of gate.in, so neither file may be rewritten with CRLF on a Windows checkout.
ci/py-lock/** text eol=lf
# The vendored bundles are third-party bytes whose sha256 is pinned in tests/vendor/README.md: no checkout converts their line endings
# (a Windows runner with core.autocrlf=true would hand them over with CRLF and the hash would no longer match).
tests/vendor/*.js -text
+3 -3
View File
@@ -35,18 +35,18 @@ jobs:
timeout-minutes: 10
steps:
- name: Check out the script (main)
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 (v4.4.0)
uses: actions/checkout@v4
with:
path: main
- name: Check out the badges branch
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 (v4.4.0)
uses: actions/checkout@v4
with:
ref: badges
path: badges
- name: Set up Python
uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 (v5.6.0)
uses: actions/setup-python@v5
with:
python-version: "3.12"
+84 -71
View File
@@ -22,14 +22,9 @@
# Windows runner separates the two without asking anyone to stay off it
# for six hours.
#
# A second use, chosen by the input `ab_network_webrtc_seed` (empty = the loop
# above, as always): the network oracle's WebRTC walk of that seed, alone,
# `runs` times for each engine of its A/A (the published engine twice). It
# exists to tell two readings apart when the A/A of that walk differs from
# itself in the number of TURN Allocate datagrams (scripts/ci_ab_network.py:
# AB_NETWORK_HUNT): each repetition keeps every datagram with its time and its
# STUN transaction id and the page's own ICE times (network/hunt/<engine>-<i>.json,
# summary in network/hunt/summary.json). It decides nothing: the step exits 0.
# A SECOND PATTERN, `pattern=init-map`: not a hunt, a measurement. It maps what a launch does from `InvisiblePlaywright(...)` to the first page and the first goto,
# with the time of every step (scripts/init_map.py), on Linux and on Windows, and uploads a JSON and a Markdown table. No threshold and no verdict: the job is green
# when it measured, and the numbers are read by whoever is looking for where to optimise. The loop above does not run for it.
#
# Doesn't start on its own: `workflow_dispatch` only. It's not a gate, it's
# an investigation tool, and it must not be added to the required contexts.
@@ -43,10 +38,18 @@ on:
description: "How many runs at most (at 12% it takes ~18 for a 90% chance)"
required: false
default: "18"
ab_network_webrtc_seed:
description: "A seed (e.g. 4) to repeat ONLY the network oracle's WebRTC walk of, `runs` times for each engine of its A/A, instead of the e2e loop. Empty: the e2e loop."
pattern:
description: "What to run. hang = the loop below (e2e until it catches a hang); init-map = the map of the launch's steps with their time (Linux and Windows; `runs` and `os` do not apply)"
required: false
default: ""
default: "hang"
type: choice
options:
- hang
- init-map
map_runs:
description: "pattern=init-map: how many launches are measured, on a warm cache, for each scenario"
required: false
default: "10"
os:
description: "Where to hunt. windows-latest answers a DIFFERENT question: are the interaction retries seen on the dev machine the product or contention?"
required: false
@@ -72,27 +75,10 @@ env:
GITHUB_TOKEN: ${{ github.token }}
jobs:
# The Ubuntu packages of the Linux hunt, from Ubuntu's archive once per runner image and list (linux-deps.yml), never by the hunt. On Windows this job is
# skipped and the hunt runs on (the condition below accepts `skipped` and `success`, nothing else).
linux-deps-hunt:
name: linux-deps-hunt
if: startsWith(inputs.os, 'ubuntu')
uses: ./.github/workflows/linux-deps.yml
with:
name: hunt
packages: xvfb
playwright_wrapper_ref: ${{ github.sha }}
hunt:
name: hunt (${{ inputs.os }})
needs: linux-deps-hunt
if: ${{ !cancelled() && (needs.linux-deps-hunt.result == 'success' || needs.linux-deps-hunt.result == 'skipped') }}
if: inputs.pattern != 'init-map'
runs-on: ${{ inputs.os }}
# TEMP and TMP on D:\a\_temp (the runner's temp folder): the Firefox profiles land in TEMP and on C: they saturate the disk (queue up to 144,
# latencies up to 4 s, parent main thread still 40-60 s). On the job, not in a step: `runner.temp` is not readable in a job's `env`.
env:
TEMP: ${{ startsWith(inputs.os, 'windows') && 'D:\a\_temp' || '/tmp' }}
TMP: ${{ startsWith(inputs.os, 'windows') && 'D:\a\_temp' || '/tmp' }}
# 18 runs of ~6 minutes plus install time. Deliberately generous: the
# ceiling here must NEVER be the thing that stops the hunt, or we're back
# to a killed job that explains nothing, which is the original defect.
@@ -119,49 +105,16 @@ jobs:
# Linux only: on Windows the browser launches on the runner's desktop,
# and `firefox-launch-matrix.yml` has shown for months that it really
# starts there.
- name: The Linux packages (the run's linux-deps-hunt job, no mirror)
if: runner.os == 'Linux'
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
with:
name: ${{ needs.linux-deps-hunt.outputs.artifact }}
path: /tmp/linux-deps
- name: System deps (xvfb + Firefox runtime libs; the repository of the linux-deps-hunt job)
- name: System deps (xvfb + Firefox runtime libs)
if: runner.os == 'Linux'
run: |
set -euo pipefail
# The run's linux-deps repository and nothing else: apt reads only its sources list and lists folder, the files are already in apt's archives,
# and the roots are installed by name with --no-download: a package the repository does not hold is named here and red, never fetched.
read -r OS VER < /tmp/linux-deps/image.txt
echo "the repository was read on $OS $VER; this runner is $ImageOS $ImageVersion"
sudo mkdir -p /tmp/linux-deps-apt/lists/partial /tmp/linux-deps-apt/parts
echo "deb [trusted=yes] file:/tmp/linux-deps ./" | sudo tee /tmp/linux-deps-apt/sources.list >/dev/null
APT="-o Dir::Etc::SourceList=/tmp/linux-deps-apt/sources.list -o Dir::Etc::SourceParts=/tmp/linux-deps-apt/parts -o Dir::State::Lists=/tmp/linux-deps-apt/lists -o Acquire::Languages=none"
sudo apt-get $APT update
sudo cp /tmp/linux-deps/*.deb /var/cache/apt/archives/
sudo apt-get $APT install -y --no-download --no-install-recommends $(cat /tmp/linux-deps/roots.txt)
- name: The security state (a fixed directory of the repository)
if: inputs.ab_network_webrtc_seed != ''
run: python scripts/ci_lab_security_state.py set --pin ci/security-state.pin.json
sudo apt-get update
sudo apt-get install -y xvfb
sudo "$(which python)" -m playwright install-deps firefox
- name: Fetch the published firefox binary
run: echo "FF=$(python -m invisible_playwright fetch | tail -1)" >> "$GITHUB_ENV"
- name: The GeoIP database (made by the repository, same bytes every run)
if: inputs.ab_network_webrtc_seed != ''
run: python scripts/ci_lab_geoip.py build
# The hunt of the network oracle's WebRTC walk: instead of the loop below, never with it. `runs` is the number of repetitions per engine.
- name: The network oracle's WebRTC walk of one seed, repeated (decides nothing)
if: inputs.ab_network_webrtc_seed != ''
env:
PYTHONUNBUFFERED: "1"
AB_NETWORK_HUNT: webrtc:${{ inputs.ab_network_webrtc_seed }}:${{ inputs.runs }}
run: |
set -u
if [ "$RUNNER_OS" = "Linux" ]; then PRE="xvfb-run -a"; else PRE=""; fi
mkdir -p network
$PRE python -u scripts/ci_ab_network.py ab --a-a --out network --published-binary "$FF"
- name: Loop until it catches one
if: inputs.ab_network_webrtc_seed == ''
env:
PYTHONUNBUFFERED: "1"
INVPW_TEST_WATCHDOG_FILE: evidence/e2e-watchdog.log
@@ -217,11 +170,71 @@ jobs:
if-no-files-found: warn
retention-days: 14
- name: Upload the hunt of the network oracle's WebRTC walk
if: always() && inputs.ab_network_webrtc_seed != ''
# pattern=init-map: the map of a launch (scripts/init_map.py). The published engine, the core and the wrapper of this ref. Warm cache: one launch that is not
# counted, then `map_runs` launches in a fresh interpreter each, for three scenarios (no proxy; behind a SOCKS5 gateway of the runner, which keeps the UDP
# measurement beside the TCP discovery; `headless=True`); then one launch on a cold cache (a new cache directory, the engine kept) and one under cProfile. The
# engine's download is timed apart (the `fetch` step). Nothing here is a gate.
init-map:
name: init-map (${{ matrix.os }})
if: inputs.pattern == 'init-map'
runs-on: ${{ matrix.runner }}
timeout-minutes: 90
strategy:
fail-fast: false
max-parallel: 2
matrix:
include:
- { os: linux, runner: ubuntu-24.04 }
- { os: windows, runner: windows-2022 }
env:
# The profile of every Firefox is made in TEMP: on the Windows runners the default is on C:, whose disk the browsers saturate (the reason of the e2e jobs).
TEMP: ${{ startsWith(matrix.runner, 'windows') && 'D:\a\_temp' || '/tmp' }}
TMP: ${{ startsWith(matrix.runner, 'windows') && 'D:\a\_temp' || '/tmp' }}
PYTHONUTF8: "1"
PYTHONUNBUFFERED: "1"
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 the wrapper (and the stock client, for the system libraries of Firefox)
run: |
python -m pip install --upgrade pip
python -m pip install .
python -m pip install "playwright==$(cat scripts/playwright_pin.txt)"
- name: System deps (xvfb + Firefox runtime libs)
if: matrix.os == 'linux'
run: |
sudo apt-get update
sudo apt-get install -y xvfb
sudo "$(which python)" -m playwright install-deps firefox
- name: Fetch the published firefox binary (timed apart, a cold download is not a step of the map)
run: |
t0=$(python -c "import time; print(time.time())")
python -m invisible_playwright fetch | tee fetch.log
t1=$(python -c "import time; print(time.time())")
echo "INIT_MAP_FETCH_SECONDS=$(python -c "print(round($t1 - $t0, 2))")" >> "$GITHUB_ENV"
- name: The map of the launch
env:
INIT_MAP_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
run: |
mkdir -p init-map-out
if [ "$RUNNER_OS" = "Linux" ]; then PRE="xvfb-run -a"; else PRE=""; fi
$PRE python -u scripts/init_map.py --runs "${{ inputs.map_runs }}" --out init-map-out 2>&1 | tee init-map-out/init-map.log
test -f "init-map-out/init-map-$(python -c "import os; print('windows' if os.name == 'nt' else 'linux')").md"
- name: The table in the summary
if: always()
run: cat init-map-out/init-map-*.md >> "$GITHUB_STEP_SUMMARY" || true
- name: Upload the map
if: always()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: e2e-hunt-network-webrtc-${{ inputs.os }}-${{ github.run_id }}-${{ github.run_attempt }}
path: network/hunt
name: init-map-${{ matrix.os }}-${{ github.run_id }}-${{ github.run_attempt }}
path: |
init-map-out
fetch.log
if-no-files-found: warn
retention-days: 14
retention-days: 30
+68 -1186
View File
File diff suppressed because it is too large. Load diff
+9 -39
View File
@@ -53,27 +53,11 @@ jobs:
core-on-index:
uses: ./.github/workflows/core-on-index.yml
# The Ubuntu packages of the Linux legs, from Ubuntu's archive once per runner image and list (linux-deps.yml), never by a leg.
linux-deps-fakeweb:
name: linux-deps-fakeweb
needs: core-on-index
if: needs.core-on-index.outputs.available == 'true'
uses: ./.github/workflows/linux-deps.yml
with:
name: fakeweb
packages: xvfb
playwright_wrapper_ref: ${{ github.sha }}
walk:
name: fakeweb ${{ matrix.profile }} (${{ matrix.os }})
needs: [core-on-index, linux-deps-fakeweb]
needs: core-on-index
if: needs.core-on-index.outputs.available == 'true'
runs-on: ${{ matrix.runner }}
# TEMP and TMP on D:\a\_temp (the runner's temp folder): the Firefox profiles land in TEMP and on C: they saturate the disk (queue up to 144,
# latencies up to 4 s, parent main thread still 40-60 s). On the job, not in a step: `runner.temp` is not readable in a job's `env`.
env:
TEMP: ${{ startsWith(matrix.runner, 'windows') && 'D:\a\_temp' || '/tmp' }}
TMP: ${{ startsWith(matrix.runner, 'windows') && 'D:\a\_temp' || '/tmp' }}
timeout-minutes: 30
strategy:
fail-fast: false
@@ -96,32 +80,18 @@ jobs:
python -m pip install --upgrade pip
python -m pip install ".[dev]"
python -m pip install "playwright==$(cat scripts/playwright_pin.txt)"
- name: The Linux packages (the run's linux-deps-fakeweb job, no mirror)
if: matrix.os == 'linux'
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
with:
name: ${{ needs.linux-deps-fakeweb.outputs.artifact }}
path: /tmp/linux-deps
- name: System deps (xvfb + Firefox runtime libs; the repository of the linux-deps-fakeweb job)
- name: System deps (xvfb + Firefox runtime libs)
if: matrix.os == 'linux'
run: |
set -euo pipefail
# The run's linux-deps repository and nothing else: apt reads only its sources list and lists folder, the files are already in apt's archives,
# and the roots are installed by name with --no-download: a package the repository does not hold is named here and red, never fetched.
read -r OS VER < /tmp/linux-deps/image.txt
echo "the repository was read on $OS $VER; this runner is $ImageOS $ImageVersion"
sudo mkdir -p /tmp/linux-deps-apt/lists/partial /tmp/linux-deps-apt/parts
echo "deb [trusted=yes] file:/tmp/linux-deps ./" | sudo tee /tmp/linux-deps-apt/sources.list >/dev/null
APT="-o Dir::Etc::SourceList=/tmp/linux-deps-apt/sources.list -o Dir::Etc::SourceParts=/tmp/linux-deps-apt/parts -o Dir::State::Lists=/tmp/linux-deps-apt/lists -o Acquire::Languages=none"
sudo apt-get $APT update
sudo cp /tmp/linux-deps/*.deb /var/cache/apt/archives/
sudo apt-get $APT install -y --no-download --no-install-recommends $(cat /tmp/linux-deps/roots.txt)
sudo apt-get update
sudo apt-get install -y xvfb
sudo "$(which python)" -m playwright install-deps firefox
- name: Playwright's own Firefox (the control)
run: python -m playwright install firefox
# The security state is a ready directory of the repository (ci/security-state/, a result with no data, the sha256 in ci/security-state.pin.json): with
# STEALTHFOX_SECURITY_STATE set the core neither downloads nor generates one. BEFORE `fetch`, which makes the state present (it would download and generate it).
- name: The security state (a fixed directory of the repository)
run: python scripts/ci_lab_security_state.py set --pin ci/security-state.pin.json
# The preloaded-intermediates list is a file of the repository (ci/intermediates.json, empty, the sha256 in ci/intermediates.pin.json): with
# STEALTHFOX_INTERMEDIATES set the core neither downloads nor checks Mozilla's. BEFORE `fetch`, which makes the list present (it would download it).
- name: The intermediates list (a fixed file of the repository)
run: python scripts/ci_lab_intermediates.py set --pin ci/intermediates.pin.json
- 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 (no download, the same bytes every run).
+3 -8
View File
@@ -50,11 +50,6 @@ jobs:
needs: core-on-index
if: needs.core-on-index.outputs.available == 'true'
runs-on: ${{ matrix.os }}
# TEMP and TMP on D:\a\_temp (the runner's temp folder): the Firefox profiles land in TEMP and on C: they saturate the disk (queue up to 144,
# latencies up to 4 s, parent main thread still 40-60 s). On the job, not in a step: `runner.temp` is not readable in a job's `env`.
env:
TEMP: 'D:\a\_temp'
TMP: 'D:\a\_temp'
strategy:
fail-fast: false
matrix:
@@ -65,10 +60,10 @@ jobs:
python: ["3.12"]
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 (v4.4.0)
- uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python }}
uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 (v5.6.0)
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python }}
cache: pip
@@ -151,7 +146,7 @@ jobs:
- name: Upload diagnostics on failure
if: failure()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 (v4.6.2)
uses: actions/upload-artifact@v4
with:
name: launch-failure-${{ matrix.os }}-py${{ matrix.python }}
path: |
-188
View File
@@ -1,188 +0,0 @@
# ─────────────────────────────────────────────────────────────────────────────
# linux-deps.yml — the Ubuntu packages of a workflow's Linux jobs, read from Ubuntu's archive ONCE per runner image and list, never by the jobs.
# The same file in the series and in the wrapper.
#
# Republish 45297517213: wrapper.e2e.fakeweb-linux-x86_64 was cancelled at its 25 minutes with every step green, because `playwright install-deps
# firefox` fetched 48.8 MB from the archive's mirror at 102 kB/s ("Fetched 48.8 MB in 7min 59s"). The speed of a mirror is a third party's.
# The first form of this file handed the jobs only the packages missing on ITS runner image and installed them against the job's own image: the
# wrapper's PR #584 ran that job on ubuntu24 20261116.376.1 and the legs on 20261116.133.1, and the legs' apt wanted a package the files did not
# hold ("E: Unable to fetch some archives"). GitHub mixes builds of an image in one run, so the files cannot depend on the image they were read on.
#
# So this job hands the jobs a REPOSITORY: the roots (the packages named with their recommends, the recommends themselves, the packages named without,
# and the roots `playwright install-deps firefox` installs for the Playwright of the wrapper's pin, read from its table), their whole closure of
# Depends and Pre-Depends with the virtual packages' providers, INCLUDING what the image already has, a Packages index, and roots.txt. A job
# installs the roots BY NAME with an apt that reads only that repository (its own sources list and lists folder) and --no-download: whatever its
# image has or lacks is resolved from the files, and a package that is not there is named by apt, red, never fetched from a mirror.
# The files are kept in a cache entry keyed by the image's OS, the date of its release and the sha of the list (an entry of .deb files on GitHub's
# runners, this file only), and handed to the run's jobs as the artifact linux-deps-<name>. Not by the image's build: the repository does not depend
# on it, and the builds of one release are mixed in a run (20261116.133.1, 20261116.376.1), so a key per build missed the entry run after run and
# read the archive each time (wrapper PR #585: 13 minutes for a closure, from a slow mirror). The download runs 8 at a time: the slowness seen is
# per connection.
# ─────────────────────────────────────────────────────────────────────────────
name: linux-deps
on:
workflow_call:
inputs:
name:
description: the artifact is linux-deps-<name>
type: string
required: true
packages:
description: packages installed with their recommends (as `apt-get install -y` did)
type: string
default: ''
packages_no_recommends:
description: packages installed without their recommends
type: string
default: ''
playwright_wrapper_ref:
description: the oss-invisible/playwright ref whose scripts/playwright_pin.txt names the Playwright of `install-deps firefox`; empty for none
type: string
default: ''
outputs:
artifact:
description: the artifact that holds the repository
value: ${{ jobs.debs.outputs.artifact }}
permissions: { contents: read }
jobs:
debs:
name: debs
runs-on: ubuntu-24.04
timeout-minutes: 20
outputs:
artifact: linux-deps-${{ inputs.name }}
steps:
- name: Checkout wrapper (its Playwright pin)
if: inputs.playwright_wrapper_ref != ''
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
with:
repository: oss-invisible/playwright
ref: ${{ inputs.playwright_wrapper_ref }}
path: linux-deps-pin
fetch-depth: 1
sparse-checkout: scripts/playwright_pin.txt
sparse-checkout-cone-mode: false
- name: Set up Python
if: inputs.playwright_wrapper_ref != ''
uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
with: { python-version: '3.11' }
- name: The list and its entry (the runner image and the sha of the list)
id: spec
shell: bash
env:
PACKAGES: ${{ inputs.packages }}
NO_REC: ${{ inputs.packages_no_recommends }}
PW_REF: ${{ inputs.playwright_wrapper_ref }}
run: |
set -euo pipefail
: "${ImageOS:?no ImageOS: not a GitHub runner image}" "${ImageVersion:?no ImageVersion: not a GitHub runner image}"
PIN=""
if [ -n "$PW_REF" ]; then PIN="$(tr -d '[:space:]' < linux-deps-pin/scripts/playwright_pin.txt)"; [ -n "$PIN" ] || { echo "ERROR: empty scripts/playwright_pin.txt at $PW_REF"; exit 1; }; fi
mkdir -p "$RUNNER_TEMP/linux-deps-spec"
printf 'form: repository of the closure\nrecommends: %s\nno-recommends: %s\nplaywright-roots-firefox: %s\n' "$PACKAGES" "$NO_REC" "$PIN" > "$RUNNER_TEMP/linux-deps-spec/spec.txt"
cat "$RUNNER_TEMP/linux-deps-spec/spec.txt"
SHA="$(sha256sum < "$RUNNER_TEMP/linux-deps-spec/spec.txt" | cut -c1-16)"
echo "pin=$PIN" >> "$GITHUB_OUTPUT"
RELEASE="${ImageVersion%%.*}"
echo "key=linux-deps-$ImageOS-$RELEASE-$SHA" | tee -a "$GITHUB_OUTPUT"
- name: The entry of this image and list
id: restore
uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: /tmp/linux-deps
key: ${{ steps.spec.outputs.key }}
- name: A new image or list - the repository from Ubuntu's archive, once
if: steps.restore.outputs.cache-hit != 'true'
shell: bash
env:
PACKAGES: ${{ inputs.packages }}
NO_REC: ${{ inputs.packages_no_recommends }}
PIN: ${{ steps.spec.outputs.pin }}
run: |
set -euo pipefail
printf '%s\n' 'Acquire::http::Timeout "60";' 'Acquire::https::Timeout "60";' 'Acquire::Retries "5";' \
| sudo tee /etc/apt/apt.conf.d/80-ci-network >/dev/null
sudo apt-get update -qq
command -v apt-ftparchive >/dev/null || sudo apt-get install -y -qq apt-utils
PW_ROOTS=""
if [ -n "$PIN" ]; then
python -m pip install --quiet "playwright==$PIN"
# The roots `playwright install-deps firefox` installs (with --no-install-recommends): the `tools` and `firefox` lists of this system's
# entry in the driver's table, the list install-deps itself reads.
PLATFORM="ubuntu$(. /etc/os-release && echo "$VERSION_ID")-x64"
PW_ROOTS="$(python - "$PLATFORM" <<'PY'
import os, re, sys
import playwright
path = os.path.join(os.path.dirname(playwright.__file__), "driver", "package", "lib", "coreBundle.js")
text = open(path, encoding="utf-8").read()
at = text.find('"%s": {' % sys.argv[1])
if at < 0:
sys.exit("no entry %s in %s" % (sys.argv[1], path))
roots = []
for group in ("tools", "firefox"):
m = re.compile(r"\b%s: \[(.*?)\]" % group, re.S).search(text, at)
if not m:
sys.exit("no %s list after the entry %s" % (group, sys.argv[1]))
roots += re.findall(r'"([a-z0-9][a-z0-9.+-]*)"', m.group(1))
if "xvfb" not in roots or len(roots) < 10:
sys.exit("the roots read from %s are not install-deps' list: %s" % (path, roots))
print(" ".join(sorted(set(roots))))
PY
)"
echo "playwright install-deps firefox roots: $PW_ROOTS"
fi
# The recommends of the packages named with their recommends (as `apt-get install -y` installed them), one level, as roots themselves.
RECS=""
[ -z "$PACKAGES" ] || RECS="$(apt-cache depends --no-depends --no-pre-depends --no-suggests --no-conflicts --no-breaks --no-replaces --no-enhances $PACKAGES \
| sed -n 's/^ *|\{0,1\}Recommends: \([a-z0-9][^ <>]*\)$/\1/p' | sort -u | tr '\n' ' ')"
NAMED="$(echo $PACKAGES $RECS $NO_REC $PW_ROOTS | tr ' ' '\n' | sed '/^$/d' | sort -u | tr '\n' ' ')"
# A name only provided (libgtk-3-0, libgtk-3-0t64's on noble) is its provider, as `apt-get install` resolved it: `apt-cache depends
# --recurse` does not walk from a virtual root (wrapper PR #585: the closure of libgtk-3-0 came without libgtk-3-0t64, 92 packages of 230).
ROOTS=""
for r in $NAMED; do
if apt-cache show --no-all-versions "$r" 2>/dev/null | grep -qx "Package: $r"; then ROOTS="$ROOTS $r"; continue; fi
p="$(apt-cache showpkg "$r" | sed -n '/^Reverse Provides:/,$p' | sed '1d' | awk 'NF {sub(/:.*/, "", $1); print $1}' | sort -u)"
[ "$(echo "$p" | wc -w)" = 1 ] || { echo "ERROR: the root $r is not a package and is provided by [$p], not by one package"; exit 1; }
echo "the root $r is provided by $p"
ROOTS="$ROOTS $p"
done
ROOTS="$(echo $ROOTS | tr ' ' '\n' | sort -u | tr '\n' ' ')"
echo "roots: $ROOTS"
# The closure: Depends and Pre-Depends, recursively, the providers of every virtual package, what the image has included.
CLOSURE="$(apt-cache depends --recurse --no-recommends --no-suggests --no-conflicts --no-breaks --no-replaces --no-enhances $ROOTS \
| grep -E '^[a-z0-9]' | sed 's/:amd64$//' | grep -v ':' | sort -u)"
REAL="$({ apt-cache show --no-all-versions $CLOSURE 2>/dev/null || true; } | sed -n 's/^Package: //p' | sort -u)"
rm -rf /tmp/linux-deps && mkdir -p /tmp/linux-deps
# The lists were refreshed above (apt-get update), so every closure name has its current version; each fetch retries 5 times. The MB and
# the seconds of the download go to the log, so the archive's speed is measured run after run.
T0="$(date +%s)"
( cd /tmp/linux-deps && echo "$REAL" | xargs -n 20 -P 8 apt-get download -qq -o Acquire::Retries=5 )
T1="$(date +%s)"
echo "download: $(echo "$REAL" | wc -w) packages, $(du -sm /tmp/linux-deps | cut -f1) MB in $((T1 - T0)) s"
( cd /tmp/linux-deps && apt-ftparchive packages . > Packages )
for p in $REAL; do grep -qx "Package: $p" /tmp/linux-deps/Packages || { echo "ERROR: $p of the closure was not downloaded"; exit 1; }; done
# A root is a package of the repository or a name one of them provides (libgtk-3-0 is libgtk-3-0t64's on noble, as `apt-get install` resolved it)
for r in $ROOTS; do
e="$(printf '%s' "$r" | sed 's/[.+]/\\&/g')"
grep -qE "^(Package: $e|Provides: (.*, )?$e( \(.*\))?(,.*)?)$" /tmp/linux-deps/Packages || { echo "ERROR: the root $r is not in the repository"; exit 1; }
done
echo "$ROOTS" | tr ' ' '\n' | sed '/^$/d' > /tmp/linux-deps/roots.txt
cp "$RUNNER_TEMP/linux-deps-spec/spec.txt" /tmp/linux-deps/spec.txt
echo "$ImageOS $ImageVersion" > /tmp/linux-deps/image.txt
echo "$(wc -l < /tmp/linux-deps/roots.txt) roots, $(find /tmp/linux-deps -name '*.deb' | wc -l) packages in the closure, $(du -sh /tmp/linux-deps | cut -f1)"
- name: Keep the entry
if: steps.restore.outputs.cache-hit != 'true'
uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: /tmp/linux-deps
key: ${{ steps.spec.outputs.key }}
- name: The repository for the jobs of this run
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: linux-deps-${{ inputs.name }}
path: /tmp/linux-deps
retention-days: 1
if-no-files-found: error
+1 -1
View File
@@ -9,4 +9,4 @@ permissions:
contents: read
jobs:
noreply-identity:
uses: oss-invisible/core/.github/workflows/noreply-identity.yml@6d048ac02fc886a50791a4ae0423cbca2a547d72 # core main, the last change of noreply-identity.yml
uses: oss-invisible/core/.github/workflows/noreply-identity.yml@main
+2 -2
View File
@@ -63,10 +63,10 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Check out the repo (docs + the converter)
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 (v4.4.0)
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 (v5.6.0)
uses: actions/setup-python@v5
with:
python-version: "3.12"
+8 -8
View File
@@ -62,7 +62,7 @@ jobs:
present: ${{ steps.probe.outputs.present }}
version: ${{ steps.probe.outputs.version }}
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 (v4.4.0)
- uses: actions/checkout@v4
- id: probe
shell: bash
run: |
@@ -88,10 +88,10 @@ jobs:
contents: read
checks: read
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 (v4.4.0)
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 (v5.6.0)
- uses: actions/setup-python@v5
with:
python-version: "3.12"
@@ -206,8 +206,8 @@ jobs:
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 (v4.4.0)
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 (v5.6.0)
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: Install the wrapper (its core comes from the index)
@@ -225,10 +225,10 @@ jobs:
contents: write # to commit the ledger entry back
pull-requests: write # and to open one when protection declines the push
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 (v4.4.0)
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 (v5.6.0)
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- run: python -m pip install --upgrade pip build
@@ -237,7 +237,7 @@ jobs:
run: |
pip install twine
twine check dist/*
- uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3
- uses: pypa/gh-action-pypi-publish@release/v1
- name: record what was published, and commit it back
# The action above holds the OIDC credential and does the upload; the
# thing that writes PUBLISHED.json is invisible_core.release. So the
+8 -56
View File
@@ -146,29 +146,16 @@ jobs:
echo "version=$version" >> "$GITHUB_OUTPUT"
echo "admission: $admission, invisible-playwright $version"
# The Ubuntu packages of the Linux legs, from Ubuntu's archive once per runner image and list (linux-deps.yml), never by a leg.
linux-deps-real-sites:
name: linux-deps-real-sites
needs: plan
uses: ./.github/workflows/linux-deps.yml
with:
name: real-sites
packages: xvfb libgtk-3-0 libdbus-glib-1-2 libasound2t64
round:
name: round (${{ matrix.os }})
needs: [plan, linux-deps-real-sites]
needs: plan
runs-on: ${{ matrix.os }}
timeout-minutes: 40
strategy:
fail-fast: false # one system failing must not hide the other's table
matrix:
os: [ubuntu-24.04, windows-latest]
# TEMP and TMP on D:\a\_temp (the runner's temp folder): the Firefox profiles land in TEMP and on C: they saturate the disk (queue up to 144,
# latencies up to 4 s, parent main thread still 40-60 s). On the job, not in a step: `runner.temp` is not readable in a job's `env`.
env:
TEMP: ${{ startsWith(matrix.os, 'windows') && 'D:\a\_temp' || '/tmp' }}
TMP: ${{ startsWith(matrix.os, 'windows') && 'D:\a\_temp' || '/tmp' }}
VERSION: ${{ needs.plan.outputs.version }}
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
@@ -176,26 +163,11 @@ jobs:
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
with: { python-version: '3.12' }
- name: The Linux packages (the run's linux-deps-real-sites job, no mirror)
if: runner.os == 'Linux'
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
with:
name: ${{ needs.linux-deps-real-sites.outputs.artifact }}
path: /tmp/linux-deps
- name: Linux runtime libraries for the browsers (the repository of the linux-deps-real-sites job)
- name: Linux runtime libraries for the browsers
if: runner.os == 'Linux'
run: |
set -euo pipefail
# The run's linux-deps repository and nothing else: apt reads only its sources list and lists folder, the files are already in apt's archives,
# and the roots are installed by name with --no-download: a package the repository does not hold is named here and red, never fetched.
read -r OS VER < /tmp/linux-deps/image.txt
echo "the repository was read on $OS $VER; this runner is $ImageOS $ImageVersion"
sudo mkdir -p /tmp/linux-deps-apt/lists/partial /tmp/linux-deps-apt/parts
echo "deb [trusted=yes] file:/tmp/linux-deps ./" | sudo tee /tmp/linux-deps-apt/sources.list >/dev/null
APT="-o Dir::Etc::SourceList=/tmp/linux-deps-apt/sources.list -o Dir::Etc::SourceParts=/tmp/linux-deps-apt/parts -o Dir::State::Lists=/tmp/linux-deps-apt/lists -o Acquire::Languages=none"
sudo apt-get $APT update
sudo cp /tmp/linux-deps/*.deb /var/cache/apt/archives/
sudo apt-get $APT install -y --no-download --no-install-recommends $(cat /tmp/linux-deps/roots.txt)
sudo apt-get update
sudo apt-get install -y xvfb libgtk-3-0 libdbus-glib-1-2 libasound2t64
# Two venvs that share nothing: what a user gets from the index, and what a user of stock Playwright gets. The wrapper is installed by its published version
# (the index may lag a few minutes behind a publication: only the install is asked again), then its engine is fetched the way a user fetches it.
@@ -273,14 +245,9 @@ jobs:
# One pass of stock over the list, on one system: five of them per system make the admission.
admit:
name: admit (${{ matrix.os }}, pass ${{ matrix.repeat }})
needs: [plan, linux-deps-real-sites]
needs: plan
if: needs.plan.outputs.admission == 'true'
runs-on: ${{ matrix.os }}
# TEMP and TMP on D:\a\_temp (the runner's temp folder): the Firefox profiles land in TEMP and on C: they saturate the disk (queue up to 144,
# latencies up to 4 s, parent main thread still 40-60 s). On the job, not in a step: `runner.temp` is not readable in a job's `env`.
env:
TEMP: ${{ startsWith(matrix.os, 'windows') && 'D:\a\_temp' || '/tmp' }}
TMP: ${{ startsWith(matrix.os, 'windows') && 'D:\a\_temp' || '/tmp' }}
timeout-minutes: 40
strategy:
fail-fast: false
@@ -293,26 +260,11 @@ jobs:
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
with: { python-version: '3.12' }
- name: The Linux packages (the run's linux-deps-real-sites job, no mirror)
if: runner.os == 'Linux'
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
with:
name: ${{ needs.linux-deps-real-sites.outputs.artifact }}
path: /tmp/linux-deps
- name: Linux runtime libraries for the browser (the repository of the linux-deps-real-sites job)
- name: Linux runtime libraries for the browser
if: runner.os == 'Linux'
run: |
set -euo pipefail
# The run's linux-deps repository and nothing else: apt reads only its sources list and lists folder, the files are already in apt's archives,
# and the roots are installed by name with --no-download: a package the repository does not hold is named here and red, never fetched.
read -r OS VER < /tmp/linux-deps/image.txt
echo "the repository was read on $OS $VER; this runner is $ImageOS $ImageVersion"
sudo mkdir -p /tmp/linux-deps-apt/lists/partial /tmp/linux-deps-apt/parts
echo "deb [trusted=yes] file:/tmp/linux-deps ./" | sudo tee /tmp/linux-deps-apt/sources.list >/dev/null
APT="-o Dir::Etc::SourceList=/tmp/linux-deps-apt/sources.list -o Dir::Etc::SourceParts=/tmp/linux-deps-apt/parts -o Dir::State::Lists=/tmp/linux-deps-apt/lists -o Acquire::Languages=none"
sudo apt-get $APT update
sudo cp /tmp/linux-deps/*.deb /var/cache/apt/archives/
sudo apt-get $APT install -y --no-download --no-install-recommends $(cat /tmp/linux-deps/roots.txt)
sudo apt-get update
sudo apt-get install -y xvfb libgtk-3-0 libdbus-glib-1-2 libasound2t64
- name: Stock Playwright and its Firefox, then one pass
shell: bash
+19 -67
View File
@@ -53,8 +53,8 @@ jobs:
needs: core-on-index
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 (v4.4.0)
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 (v5.6.0)
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: install the pinned core, which carries the gate
@@ -82,8 +82,8 @@ jobs:
needs: core-on-index
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 (v4.4.0)
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 (v5.6.0)
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: install the pinned core, which carries the gate
@@ -108,8 +108,8 @@ jobs:
needs: core-on-index
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 (v4.4.0)
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 (v5.6.0)
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: install the pinned core, which carries the gate
@@ -135,8 +135,8 @@ jobs:
needs: core-on-index
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 (v4.4.0)
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 (v5.6.0)
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: install the pinned core, which carries the gate
@@ -164,18 +164,13 @@ jobs:
# email (author, committer, tagger). The judge lives in oss-invisible/core and
# is read from its main, never from this branch.
noreply-identity:
uses: oss-invisible/core/.github/workflows/noreply-identity.yml@6d048ac02fc886a50791a4ae0423cbca2a547d72 # core main, the last change of noreply-identity.yml
uses: oss-invisible/core/.github/workflows/noreply-identity.yml@main
unit:
name: pytest (${{ matrix.os }}, py${{ matrix.python }})
needs: core-on-index
if: needs.core-on-index.outputs.available == 'true'
runs-on: ${{ matrix.os }}
# TEMP and TMP on D:\a\_temp (the runner's temp folder): the Firefox profiles land in TEMP and on C: they saturate the disk (queue up to 144,
# latencies up to 4 s, parent main thread still 40-60 s). On the job, not in a step: `runner.temp` is not readable in a job's `env`.
env:
TEMP: ${{ startsWith(matrix.os, 'windows') && 'D:\a\_temp' || '/tmp' }}
TMP: ${{ startsWith(matrix.os, 'windows') && 'D:\a\_temp' || '/tmp' }}
strategy:
fail-fast: false
matrix:
@@ -195,7 +190,7 @@ jobs:
- { os: windows-latest, python: "3.13" }
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 (v4.4.0)
- uses: actions/checkout@v4
# main, for the tests that compare a list of this change with the list of main (tests/test_the_e2e_tests_do_not_wait_on_clocks.py: the debt of
# the e2e tests only shrinks). The checkout is one commit deep; without this the comparison has nothing to read and the test says so.
@@ -204,7 +199,7 @@ jobs:
run: git fetch --no-tags --depth=1 origin main:refs/remotes/origin/main
- name: Set up Python ${{ matrix.python }}
uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 (v5.6.0)
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python }}
cache: pip
@@ -239,11 +234,11 @@ jobs:
run: |
python -m ruff check --select F821,F811,F601 --no-cache --output-format concise .
# The security state is a ready directory of the repository (ci/security-state/, a result with no data, the sha256 in ci/security-state.pin.json): with
# STEALTHFOX_SECURITY_STATE set the core neither downloads nor generates one.
- name: The security state (a fixed directory of the repository)
# The preloaded-intermediates list is a file of the repository (ci/intermediates.json, empty, the sha256 in ci/intermediates.pin.json): with
# STEALTHFOX_INTERMEDIATES set the core neither downloads nor checks Mozilla's.
- name: The intermediates list (a fixed file of the repository)
shell: bash
run: python scripts/ci_lab_security_state.py set --pin ci/security-state.pin.json
run: python scripts/ci_lab_intermediates.py set --pin ci/intermediates.pin.json
# 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
@@ -253,37 +248,11 @@ jobs:
run: python scripts/ci_lab_geoip.py build
- name: Run pytest
if: matrix.python != '3.11'
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 legs of Python 3.11 (the version the engine series' gate runs, on both of its systems) run the suite the way that gate does: the files and the
# marker of the row wrapper.unit.all.<os> of ci/required-suites.json (printed by scripts/ci_verdict.py args), one junit, and the judge below reads
# it. Until 2026-11-24 this workflow ran `pytest tests/` with a floor of 380 and nothing judged the exact counts the gate holds: PR #590 added a test
# without raising min_tests, this workflow was green, and the gate went red on main's next series run ("the suite is exact").
# No test runs twice: the row leaves out the files of the environment (a clone with its hooks armed, one with origin/main, the package index, ...: named,
# each with its reason, in tests/test_the_unit_suite_is_accounted_for.py), so a second pytest, with --ignore for every file of the row, runs those
# and any file that is in no row: together the two runs are what `pytest tests/` ran.
- name: Run pytest (the selection of the gate, then the files outside the row)
if: matrix.python == '3.11'
shell: bash
env:
SUITE_OS: ${{ startsWith(matrix.os, 'windows') && 'windows' || 'linux' }}
run: |
unset PYTEST_ADDOPTS
python scripts/ci_verdict.py args --required ci/required-suites.json --suite "wrapper.unit.all.$SUITE_OS" --os "$SUITE_OS" --with-marker | tr -d '\r' > "$RUNNER_TEMP/unit_args.txt"
mapfile -t ARGS < "$RUNNER_TEMP/unit_args.txt"
IGNORE=()
for a in "${ARGS[@]}"; do
case "$a" in tests/*::*) ;; tests/*) IGNORE+=("--ignore=$a") ;; esac
done
rc=0
python -m pytest "${ARGS[@]}" -o addopts='' -o junit_family=xunit2 -q --tb=short -p no:cacheprovider -p no:rerunfailures -rs --junitxml="$RUNNER_TEMP/unit-junit.xml" || rc=$?
python -m pytest tests/ "${IGNORE[@]}" -v --tb=short -rs || rc=$?
exit $rc
# 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()
@@ -298,7 +267,6 @@ jobs:
# already filters on two markers - one more, or a typo in one, silently
# turns 726 tests into 0 and reports success.
- name: Refuse a run in which the suite deselected itself
if: matrix.python != '3.11'
shell: bash
run: |
python - <<'PY'
@@ -325,22 +293,6 @@ jobs:
print(f"{passed} tests ran")
PY
# The judge of the engine series' gate on the junit of the step above: the exact count of the row (not one test more, not one less), no skip, every
# file of the row passed, and the list only grows against main. The judge and the list it compares with are read from main, never from the branch under
# judgment (a branch that edits its own judge or its own list cannot pass itself): a PR that adds a test and does not raise min_tests is red here.
# The suite launches no browser, so --binary names the interpreter that ran it (the judge wants a file to hash; nothing reads that hash: no --out).
- name: Judge the suite wrapper.unit.all (the exact count, with the judge and the list of main)
if: always() && matrix.python == '3.11'
shell: bash
env:
SUITE_OS: ${{ startsWith(matrix.os, 'windows') && 'windows' || 'linux' }}
run: |
mkdir -p "$RUNNER_TEMP/main"
git show origin/main:scripts/ci_verdict.py > "$RUNNER_TEMP/main/ci_verdict.py"
git show origin/main:ci/required-suites.json > "$RUNNER_TEMP/main/required-suites.json"
if git cat-file -e origin/main:ci/retired-tests.json; then git show origin/main:ci/retired-tests.json > "$RUNNER_TEMP/main/retired-tests.json"; fi
python "$RUNNER_TEMP/main/ci_verdict.py" judge --required ci/required-suites.json --suite "wrapper.unit.all.$SUITE_OS" --os "$SUITE_OS" --junit "$RUNNER_TEMP/unit-junit.xml" --binary "$(python -c 'import sys; print(sys.executable)')" --main-required "$RUNNER_TEMP/main/required-suites.json"
# ONE SINGLE CONTEXT FOR BRANCH PROTECTION. Measured 2026-08-13: this
# repo's protection required `pytest (windows-latest, py3.11)`, which the
# matrix explicitly EXCLUDES a few lines up - a context no job can ever
@@ -375,8 +327,8 @@ jobs:
if: needs.core-on-index.outputs.available == 'true'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 (v4.4.0)
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 (v5.6.0)
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
cache: pip
@@ -472,12 +424,12 @@ jobs:
if: github.event_name == 'pull_request'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 (v4.4.0)
- uses: actions/checkout@v4
with:
# The gate diffs the tree against the tag of the published
# version; a shallow clone has no tags and cannot tell.
fetch-depth: 0
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 (v5.6.0)
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: the version this change proposes is still free
+8 -40
View File
@@ -79,23 +79,9 @@ concurrency:
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
# The Ubuntu packages of the Linux leg, from Ubuntu's archive once per runner image and list (linux-deps.yml), never by the leg.
linux-deps-user-install:
name: linux-deps-user-install
uses: ./.github/workflows/linux-deps.yml
with:
name: user-install
packages: xvfb libgtk-3-0 libdbus-glib-1-2 libasound2t64
install:
needs: linux-deps-user-install
name: ${{ matrix.os }} - install from ${{ github.event.inputs.source || 'index' }} and launch
runs-on: ${{ matrix.os }}
# TEMP and TMP on D:\a\_temp (the runner's temp folder): the Firefox profiles land in TEMP and on C: they saturate the disk (queue up to 144,
# latencies up to 4 s, parent main thread still 40-60 s). On the job, not in a step: `runner.temp` is not readable in a job's `env`.
env:
TEMP: ${{ startsWith(matrix.os, 'windows') && 'D:\a\_temp' || '/tmp' }}
TMP: ${{ startsWith(matrix.os, 'windows') && 'D:\a\_temp' || '/tmp' }}
timeout-minutes: 45
strategy:
fail-fast: false # one OS failing must not hide the other's result
@@ -103,20 +89,17 @@ jobs:
os: [ubuntu-24.04, windows-latest]
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 (v4.4.0)
- uses: actions/checkout@v4
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 (v5.6.0)
- uses: actions/setup-python@v5
with: { python-version: '3.11' }
# Only what the TEST needs, from the wrapper's hashed lock (ci/py-lock/gate.txt), the one the other test jobs read: never a hand list, which is how
# `psutil` (imported by the OS-cursor helper of the tests since #609) was missing here and ledger #618 was red. The lock holds `uv` (the wait below asks it, and the
# release test installs the package with it) and holds neither invisible-playwright nor invisible-core: the package under test is installed by the
# Only what the TEST needs (and `uv`, for the wait below to ask uv, which the release test installs the package with). The package under test is installed by the
# test itself, into a venv it creates, from the index - installing it
# here as well would put a second copy on the path and the assertions
# would be reading the wrong one. The runner's own pip, nothing unhashed.
# A rule test of the unit suite (the install job has every module its tests import) holds every third-party module the tests import to that lock.
# would be reading the wrong one.
- name: Test harness only
run: python -m pip install --require-hashes -r ci/py-lock/gate.txt
run: python -m pip install --upgrade pip pytest packaging uv
# ⛔ THE VERSION OF A LEDGER PULL REQUEST IS THE ONE IT ADDS TO PUBLISHED.json, NOT THE ONE THE TREE DECLARES.
# The ledger PR of a release is merged after this job is green, and the next release's tree can already be on main: ledger #534 recorded
@@ -214,26 +197,11 @@ jobs:
time.sleep(poll)
PY
- name: The Linux packages (the run's linux-deps-user-install job, no mirror)
if: runner.os == 'Linux'
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
with:
name: ${{ needs.linux-deps-user-install.outputs.artifact }}
path: /tmp/linux-deps
- name: Linux runtime libraries for the browser (the repository of the linux-deps-user-install job)
- name: Linux runtime libraries for the browser
if: runner.os == 'Linux'
run: |
set -euo pipefail
# The run's linux-deps repository and nothing else: apt reads only its sources list and lists folder, the files are already in apt's archives,
# and the roots are installed by name with --no-download: a package the repository does not hold is named here and red, never fetched.
read -r OS VER < /tmp/linux-deps/image.txt
echo "the repository was read on $OS $VER; this runner is $ImageOS $ImageVersion"
sudo mkdir -p /tmp/linux-deps-apt/lists/partial /tmp/linux-deps-apt/parts
echo "deb [trusted=yes] file:/tmp/linux-deps ./" | sudo tee /tmp/linux-deps-apt/sources.list >/dev/null
APT="-o Dir::Etc::SourceList=/tmp/linux-deps-apt/sources.list -o Dir::Etc::SourceParts=/tmp/linux-deps-apt/parts -o Dir::State::Lists=/tmp/linux-deps-apt/lists -o Acquire::Languages=none"
sudo apt-get $APT update
sudo cp /tmp/linux-deps/*.deb /var/cache/apt/archives/
sudo apt-get $APT install -y --no-download --no-install-recommends $(cat /tmp/linux-deps/roots.txt)
sudo apt-get update
sudo apt-get install -y xvfb libgtk-3-0 libdbus-glib-1-2 libasound2t64
- name: The user path, end to end
env:
-60
View File
@@ -4,66 +4,6 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.60.0] - 2026-11-27
### Changed
- Pins invisible-core 70.83.0 on the engine firefox-70 (Firefox 159.0).
- The engine carries Firefox's fix for the race between the start and the shutdown of its telemetry (Glean): a browser closed while it was
still starting no longer leaves that work half done.
- ElementHandle pointer actions (`click`, `dblclick`, `hover`, `tap`, `check`, `uncheck`, `set_checked`) now use the same humanised pointer walk as selector actions (they used to jump to the exact centre of the element in one move).
- Screenshot parameters that Playwright honours by modifying the page (`mask`/`maskColor`, `style`, `animations="disabled"`,
`caret="initial"`) are now refused by name with a clear error instead of being silently ignored; `omitBackground` with PNG answers
Firefox's own `Not implemented`, as stock Playwright does. A refused screenshot of an element or a locator is refused before the page is
scrolled or measured.
## [0.59.0] - 2026-11-24
### Changed
- Pins invisible-core 69.82.0 on the engine firefox-69 (Firefox 159.0).
### Added
- An element handle serves the methods of Playwright's `ElementHandle` that it used to refuse as a gap: `query_selector`, `query_selector_all`,
`eval_on_selector`, `eval_on_selector_all` (rooted at the element), `evaluate_handle`, `is_visible`, `is_hidden`, `is_enabled`, `is_disabled`,
`is_checked`, `is_editable`, `wait_for_element_state`, `dblclick`, `select_text` and `dispatch_event`, with the answers and the errors
Playwright's own server gives. `wait_for_selector` on an element handle is still refused.
- `set_input_files` with a file path works from a client attached with `connect`: the file is streamed into the session, as a stock client does
over a remote connection, and a stream can be used only by the context that made it.
### Fixed
- The argument of `evaluate` and its kin (`page.evaluate(fn, element)`, `evaluate_handle`, `eval_on_selector`, `eval_on_selector_all` and the
frame and handle forms) reaches the page as Playwright sends it: element and JS handles, dates, URLs, errors, shared references, `undefined`,
`-0` and `ArrayBuffer` are decoded in the page instead of arriving as `null`.
- `screenshot(scale="css")` is a picture in CSS pixels, as in stock Playwright; the scale was ignored and the picture was in device pixels.
- `tap` on a context without `has_touch` is refused with Playwright's own message before anything is sent to the page.
- A read that waits for its element (`inner_text`, `text_content`, `get_attribute` and the others) and runs out of time now always fails with
Playwright's own `Timeout Nms exceeded`. On Windows it could fail with the engine connection's `no response in 0s` instead, when the last
probe ran out of the caller's time a moment before the clock said so.
### Engine firefox-69
- On Linux the engine no longer runs the host's GL probe when the machine is declared: whether WebGL is available comes from the declaration alone.
- A navigation that changes process is no longer ended by the document it left, and a page is reported ready only after its document.
- A request to a page process that went away is answered instead of being left waiting, and the end of a network request and the contexts of a
frame are reported as Playwright expects.
- The engine's security-state generation no longer ends in a crash now and then (the telemetry was starting during shutdown).
- On Windows, the port a WebRTC connection holds is its own.
### Known issues
- `tap` with `has_touch` fails with an engine error: the engine cannot send a touch event since Firefox 159. It will be fixed in the engine.
## [0.58.0] - 2026-11-21
### Changed
- Pins invisible-core 68.80.0 on the engine firefox-68 (Firefox 159.0).
- Every profile starts with the security state a retail Firefox has: the intermediate certificates, OneCRL and the CRLite revocation filters.
`invisible-playwright fetch` downloads them from Mozilla's service and has the engine build them once; every launch copies the result into its
profile. Filters ten days old or more are left out, as a retail Firefox does, with one warning that says to run `fetch`.
### Fixed
- `networkidle` waits for the end of the document request that is still arriving when the page is cut, instead of ending early.
- A navigation the page's process reports as aborted while the parent is still carrying its request now waits for that request, so a
`goto` no longer fails with a false abort.
- Behind a SOCKS5 proxy, WebRTC sockets on ports Windows reserves no longer take the proxy's UDP association from the sockets that work.
## [0.57.1] - 2026-11-20
### Fixed
-2211
View File
File diff suppressed because it is too large. Load diff
-14
View File
@@ -1,14 +0,0 @@
{
"format": "ab-host-expected/1",
"differences": [
{
"id": "gfxtest-69",
"os": "linux",
"category": "proc",
"name": "gfxtest",
"published": "present",
"candidate": "absent",
"reason": "the 69 no longer spawns the graphics probe gfxtest (GFX_PROBE_BINARY, widget/gtk/GfxInfo.cpp:55; commit 0e896e4ee1, the probe never reads the host); the paths only that process touched go with it"
}
]
}
-38
View File
@@ -1,38 +0,0 @@
{
"format": "ab-network-volatile/1",
"about": "The leaves of the network transcript that differ between two runs of ONE engine (the A/A of scripts/ci_ab_network.py). Each entry: `pattern` (fnmatch over the leaf path seeds/<seed>/<category>/...), `reason` (why that leaf is noise), `aa_run` (the A/A run that proved it). Born from the evidence of the A/A, never written ahead of it. It may only shrink: an entry that matches no leaf of a run is red as stale.",
"entries": [
{
"pattern": "seeds/*/journey/connects/counts/*",
"reason": "How many TCP connections the browser opens to each destination of the journey (the DoH, the two origins) is the connection pool's: parallel and speculative connections, keep-alive connections that close and reopen, DoH connections. The CONNECTs of the launch stage are counted with the journey ones (the DoH connection at start-up lands in either). The set of destinations and the order they were first reached stay compared (journey/connects/order). Totals of the two runs: Linux DoH 226 and 225, origin A 14 and 13, origin O 20 and 12; Windows DoH 222 and 230, A 23 and 15, O 22 and 14.",
"aa_run": "44946411675 (linux, windows)"
},
{
"pattern": "seeds/*/webrtc/connects/counts/*",
"reason": "The connections to the DoH during the WebRTC page: 14 and 25 between the two Windows runs. Same pool; the destinations of the page (webrtc/connects/order) stay compared.",
"aa_run": "44946411675 (windows)"
},
{
"pattern": "seeds/*/https/*/wire/resumed_connections",
"optional": true,
"reason": "Whether a connection that resumes a session carried a request at all follows the ticket and the pool: an origin had one in a run and none in the other (seed 2 and seed 4 on Linux, h1: 108 leaves each), so what is under it is compared where both runs have a resumption and excused where only one has. The fresh connections (wire/connections) and the protocols stay compared always.",
"aa_run": "44982522362 (linux)"
},
{
"pattern": "seeds/*/h3/wire/resumed_connections",
"optional": true,
"reason": "The same for the HTTP/3 site's resumed connection.",
"aa_run": "44982522362 (linux)"
},
{
"pattern": "seeds/*/https/*/wire/*connections/*/tls/extensions/encrypted_client_hello/aead",
"reason": "The engine sends an ECH extension with no real configuration (GREASE) and picks its AEAD at random for each ClientHello it builds, whether the handshake is fresh or resumed: NSS security/nss/lib/ssl/tls13ech.c:2257, `aead = (rawData->data[0] & 1) ? HpkeAeadAes128Gcm : HpkeAeadChaCha20Poly1305;` where rawData is HKDF output of a freshly generated key (tls13_MaybeGreaseEch, called from ssl3con.c:5888 for every ClientHello that has no real ECH, with or without a pre_shared_key). 1 (AES-128-GCM) or 3 (ChaCha20-Poly1305): Windows h2 first connection 1 then 3, h1 3 then 1, both values inside one run; resumed h1 connections 3 and 1 (seeds 2 and 4 on Windows, seed 63 on Linux). The rest of the extension (type, kdf, enc and payload lengths) stays compared.",
"aa_run": "44946411675 and 44982522362 (linux, windows)"
},
{
"pattern": "seeds/*/h3/wire/*connections/*/tls/extensions/encrypted_client_hello/aead",
"reason": "The same ECH GREASE draw (tls13ech.c:2257) on the TLS connection of the HTTP/3 site (the HTTP/2 connection that opens before QUIC): 1 in one run and 3 in the other, on Linux and on Windows.",
"aa_run": "44946411675 and 44982522362 (linux, windows)"
}
]
}
+1
View File
@@ -0,0 +1 @@
{"format":1,"collection":"security-state/intermediates","collection_timestamp":0,"fetched_utc":"1970-01-01T00:00:00Z","count":0,"set_sha256":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855","certs":[]}
+6
View File
@@ -0,0 +1,6 @@
{
"comment": "The preloaded-intermediates list every CI leg launches with (STEALTHFOX_INTERMEDIATES): EMPTY (format 1, no certificates), so a leg never asks Mozilla for the real list (the core neither downloads nor checks when the variable is set) and every run has the same bytes. Set by scripts/ci_lab_intermediates.py. To change the list, change ci/intermediates.json and sha256 here in one commit; `set` refuses to go on when they differ. The real list is looked at only by what the release proves about the product.",
"file": "ci/intermediates.json",
"sha256": "f4f6a2332a4d589a1e8aaa4e73c820644a764125bb2970667afc7351e7cb3465",
"bytes": 219
}
-566
View File
@@ -1,566 +0,0 @@
{
"candidate": [
0,
2,
4,
6,
63
],
"core_version": "70.83.0",
"counts": {
"audio": {
"audio.sample_rate=44100|audio.output_latency_ms=20|audio.max_channel_count=2": 4315,
"audio.sample_rate=44100|audio.output_latency_ms=40|audio.max_channel_count=2": 14437,
"audio.sample_rate=44100|audio.output_latency_ms=50|audio.max_channel_count=2": 8614,
"audio.sample_rate=48000|audio.output_latency_ms=20|audio.max_channel_count=2": 21542,
"audio.sample_rate=48000|audio.output_latency_ms=20|audio.max_channel_count=6": 7783,
"audio.sample_rate=48000|audio.output_latency_ms=25|audio.max_channel_count=2": 5091,
"audio.sample_rate=48000|audio.output_latency_ms=30|audio.max_channel_count=2": 19799,
"audio.sample_rate=48000|audio.output_latency_ms=40|audio.max_channel_count=2": 18419
},
"codecs": {
"media.av1.enabled=false|media.encoder.webm.enabled=false|media.mp4.enabled=true|media.webm.enabled=true|media.decode_support=sha:9c24a8728f": 4264,
"media.av1.enabled=false|media.encoder.webm.enabled=true|media.mp4.enabled=true|media.webm.enabled=true|media.decode_support=sha:9c24a8728f": 18331,
"media.av1.enabled=true|media.encoder.webm.enabled=false|media.mp4.enabled=true|media.webm.enabled=true|media.decode_support=sha:960968735a": 12026,
"media.av1.enabled=true|media.encoder.webm.enabled=true|media.mp4.enabled=false|media.webm.enabled=true|media.decode_support=sha:960968735a": 4065,
"media.av1.enabled=true|media.encoder.webm.enabled=true|media.mp4.enabled=true|media.webm.enabled=false|media.decode_support=sha:960968735a": 4500,
"media.av1.enabled=true|media.encoder.webm.enabled=true|media.mp4.enabled=true|media.webm.enabled=true|media.decode_support=sha:960968735a": 56814
},
"cores": {
"hw_concurrency=10": 591,
"hw_concurrency=12": 21879,
"hw_concurrency=14": 1593,
"hw_concurrency=16": 13914,
"hw_concurrency=2": 2532,
"hw_concurrency=20": 3999,
"hw_concurrency=22": 1038,
"hw_concurrency=24": 2270,
"hw_concurrency=28": 1047,
"hw_concurrency=3": 1215,
"hw_concurrency=32": 2317,
"hw_concurrency=4": 16106,
"hw_concurrency=5": 800,
"hw_concurrency=6": 2189,
"hw_concurrency=7": 572,
"hw_concurrency=8": 27517,
"hw_concurrency=9": 421
},
"dark_theme": {
"ui.systemUsesDarkTheme=0|layout.css.prefers-color-scheme.content-override=1": 59856,
"ui.systemUsesDarkTheme=1|layout.css.prefers-color-scheme.content-override=0": 40144
},
"dpr": {
"layout.css.devPixelsPerPx=\"1.0\"|screen.frame_border=8|screen.popup_ui=72": 70210,
"layout.css.devPixelsPerPx=\"1.25\"|screen.frame_border=9|screen.popup_ui=90": 18299,
"layout.css.devPixelsPerPx=\"1.5\"|screen.frame_border=11|screen.popup_ui=106": 11491
},
"gfx_device": {
"adliris_7085": 7197,
"arl_6629": 2281,
"gtx1650_62101": 5882,
"gtx980_58278": 6133,
"icl_2145": 2398,
"irisxe_7085": 9685,
"renoir_21925": 8650,
"rpl770_7092": 3631,
"rtx3060_62101": 6058,
"rtx4060_62101": 6044,
"rtx5060_62101": 6044,
"rtx5060ti_62101": 5881,
"rtx5070_62101": 6289,
"rtx5080l_61742": 5891,
"rx580_21925": 1855,
"rx6600_32015": 1817,
"rx7600_32015": 1865,
"uhd620_2145": 2680,
"uhd630_2145": 7419,
"uhd770_7092": 2300
},
"gfx_feature_status": {
"gfx.feature_status=sha:05ce56d3c0": 22813,
"gfx.feature_status=sha:098c0bf836": 2281,
"gfx.feature_status=sha:2f5fe3776b": 14187,
"gfx.feature_status=sha:80c00ab015": 9817,
"gfx.feature_status=sha:b153aef69f": 48222,
"gfx.feature_status=sha:d1db3983c9": 2680
},
"render_noise": {
"fpp.hw_seed=11": 11111,
"fpp.hw_seed=16": 11111,
"fpp.hw_seed=19": 11111,
"fpp.hw_seed=20": 11111,
"fpp.hw_seed=28": 11111,
"fpp.hw_seed=5": 22223,
"fpp.hw_seed=6": 11111,
"fpp.hw_seed=9": 11111
},
"screen_panel": {
"screen.width=1280|screen.height=720|screen.avail_device_width=1920|screen.avail_device_height=1008|layout.css.devPixelsPerPx=\"1.5\"": 9276,
"screen.width=1536|screen.height=864|screen.avail_device_width=1920|screen.avail_device_height=1020|layout.css.devPixelsPerPx=\"1.25\"": 15893,
"screen.width=1920|screen.height=1080|screen.avail_device_width=1920|screen.avail_device_height=1032|layout.css.devPixelsPerPx=\"1.0\"": 41031,
"screen.width=1920|screen.height=1200|screen.avail_device_width=1920|screen.avail_device_height=1152|layout.css.devPixelsPerPx=\"1.0\"": 5228,
"screen.width=2048|screen.height=1152|screen.avail_device_width=2560|screen.avail_device_height=1380|layout.css.devPixelsPerPx=\"1.25\"": 2406,
"screen.width=2560|screen.height=1080|screen.avail_device_width=2560|screen.avail_device_height=1032|layout.css.devPixelsPerPx=\"1.0\"": 1918,
"screen.width=2560|screen.height=1440|screen.avail_device_width=2560|screen.avail_device_height=1392|layout.css.devPixelsPerPx=\"1.0\"": 19886,
"screen.width=2560|screen.height=1440|screen.avail_device_width=3840|screen.avail_device_height=2088|layout.css.devPixelsPerPx=\"1.5\"": 2215,
"screen.width=3840|screen.height=2160|screen.avail_device_width=3840|screen.avail_device_height=2112|layout.css.devPixelsPerPx=\"1.0\"": 2147
},
"webgl_renderer": {
"ANGLE (AMD, Radeon HD 3200 Graphics Direct3D11 vs_5_0 ps_5_0, D3D11)": 8650,
"ANGLE (AMD, Radeon R9 200 Series Direct3D11 vs_5_0 ps_5_0, D3D11)": 5537,
"ANGLE (Intel, Intel(R) HD Graphics 400 Direct3D11 vs_5_0 ps_5_0, D3D11)": 16030,
"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0, D3D11)": 21561,
"ANGLE (NVIDIA, NVIDIA GeForce GTX 980 Direct3D11 vs_5_0 ps_5_0, D3D11)": 48222
}
},
"dimensions": {
"audio": [
"audio.sample_rate=44100|audio.output_latency_ms=20|audio.max_channel_count=2",
"audio.sample_rate=44100|audio.output_latency_ms=40|audio.max_channel_count=2",
"audio.sample_rate=44100|audio.output_latency_ms=50|audio.max_channel_count=2",
"audio.sample_rate=48000|audio.output_latency_ms=20|audio.max_channel_count=2",
"audio.sample_rate=48000|audio.output_latency_ms=20|audio.max_channel_count=6",
"audio.sample_rate=48000|audio.output_latency_ms=25|audio.max_channel_count=2",
"audio.sample_rate=48000|audio.output_latency_ms=30|audio.max_channel_count=2",
"audio.sample_rate=48000|audio.output_latency_ms=40|audio.max_channel_count=2"
],
"codecs": [
"media.av1.enabled=false|media.encoder.webm.enabled=false|media.mp4.enabled=true|media.webm.enabled=true|media.decode_support=sha:9c24a8728f",
"media.av1.enabled=false|media.encoder.webm.enabled=true|media.mp4.enabled=true|media.webm.enabled=true|media.decode_support=sha:9c24a8728f",
"media.av1.enabled=true|media.encoder.webm.enabled=false|media.mp4.enabled=true|media.webm.enabled=true|media.decode_support=sha:960968735a",
"media.av1.enabled=true|media.encoder.webm.enabled=true|media.mp4.enabled=false|media.webm.enabled=true|media.decode_support=sha:960968735a",
"media.av1.enabled=true|media.encoder.webm.enabled=true|media.mp4.enabled=true|media.webm.enabled=false|media.decode_support=sha:960968735a",
"media.av1.enabled=true|media.encoder.webm.enabled=true|media.mp4.enabled=true|media.webm.enabled=true|media.decode_support=sha:960968735a"
],
"cores": [
"hw_concurrency=10",
"hw_concurrency=12",
"hw_concurrency=14",
"hw_concurrency=16",
"hw_concurrency=2",
"hw_concurrency=20",
"hw_concurrency=22",
"hw_concurrency=24",
"hw_concurrency=28",
"hw_concurrency=3",
"hw_concurrency=32",
"hw_concurrency=4",
"hw_concurrency=5",
"hw_concurrency=6",
"hw_concurrency=7",
"hw_concurrency=8",
"hw_concurrency=9"
],
"dark_theme": [
"ui.systemUsesDarkTheme=0|layout.css.prefers-color-scheme.content-override=1",
"ui.systemUsesDarkTheme=1|layout.css.prefers-color-scheme.content-override=0"
],
"dpr": [
"layout.css.devPixelsPerPx=\"1.0\"|screen.frame_border=8|screen.popup_ui=72",
"layout.css.devPixelsPerPx=\"1.25\"|screen.frame_border=9|screen.popup_ui=90",
"layout.css.devPixelsPerPx=\"1.5\"|screen.frame_border=11|screen.popup_ui=106"
],
"gfx_device": [
"adliris_7085",
"arl_6629",
"gtx1650_62101",
"gtx980_58278",
"icl_2145",
"irisxe_7085",
"renoir_21925",
"rpl770_7092",
"rtx3060_62101",
"rtx4060_62101",
"rtx5060_62101",
"rtx5060ti_62101",
"rtx5070_62101",
"rtx5080l_61742",
"rx580_21925",
"rx6600_32015",
"rx7600_32015",
"uhd620_2145",
"uhd630_2145",
"uhd770_7092"
],
"gfx_feature_status": [
"gfx.feature_status=sha:05ce56d3c0",
"gfx.feature_status=sha:098c0bf836",
"gfx.feature_status=sha:2f5fe3776b",
"gfx.feature_status=sha:80c00ab015",
"gfx.feature_status=sha:b153aef69f",
"gfx.feature_status=sha:d1db3983c9"
],
"render_noise": [
"fpp.hw_seed=11",
"fpp.hw_seed=16",
"fpp.hw_seed=19",
"fpp.hw_seed=20",
"fpp.hw_seed=28",
"fpp.hw_seed=5",
"fpp.hw_seed=6",
"fpp.hw_seed=9"
],
"screen_panel": [
"screen.width=1280|screen.height=720|screen.avail_device_width=1920|screen.avail_device_height=1008|layout.css.devPixelsPerPx=\"1.5\"",
"screen.width=1536|screen.height=864|screen.avail_device_width=1920|screen.avail_device_height=1020|layout.css.devPixelsPerPx=\"1.25\"",
"screen.width=1920|screen.height=1080|screen.avail_device_width=1920|screen.avail_device_height=1032|layout.css.devPixelsPerPx=\"1.0\"",
"screen.width=1920|screen.height=1200|screen.avail_device_width=1920|screen.avail_device_height=1152|layout.css.devPixelsPerPx=\"1.0\"",
"screen.width=2048|screen.height=1152|screen.avail_device_width=2560|screen.avail_device_height=1380|layout.css.devPixelsPerPx=\"1.25\"",
"screen.width=2560|screen.height=1080|screen.avail_device_width=2560|screen.avail_device_height=1032|layout.css.devPixelsPerPx=\"1.0\"",
"screen.width=2560|screen.height=1440|screen.avail_device_width=2560|screen.avail_device_height=1392|layout.css.devPixelsPerPx=\"1.0\"",
"screen.width=2560|screen.height=1440|screen.avail_device_width=3840|screen.avail_device_height=2088|layout.css.devPixelsPerPx=\"1.5\"",
"screen.width=3840|screen.height=2160|screen.avail_device_width=3840|screen.avail_device_height=2112|layout.css.devPixelsPerPx=\"1.0\""
],
"webgl_renderer": [
"ANGLE (AMD, Radeon HD 3200 Graphics Direct3D11 vs_5_0 ps_5_0, D3D11)",
"ANGLE (AMD, Radeon R9 200 Series Direct3D11 vs_5_0 ps_5_0, D3D11)",
"ANGLE (Intel, Intel(R) HD Graphics 400 Direct3D11 vs_5_0 ps_5_0, D3D11)",
"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0, D3D11)",
"ANGLE (NVIDIA, NVIDIA GeForce GTX 980 Direct3D11 vs_5_0 ps_5_0, D3D11)"
]
},
"dpr": {
"0": 1.0,
"107": 1.0,
"11": 1.5,
"134": 1.0,
"1633": 1.25,
"190": 1.0,
"19013": 1.0,
"2": 1.0,
"258": 1.0,
"271": 1.25,
"29735": 1.0,
"3580": 1.0,
"4": 1.0,
"49": 1.0,
"50": 1.0,
"5469": 1.5,
"59": 1.0,
"6": 1.25,
"610": 1.25,
"63": 1.5,
"7": 1.0,
"72": 1.0,
"89": 1.0,
"9219": 1.0
},
"excluded": {
"zoom.stealth.media.enumeration_ms": "the time of the first enumerateDevices(): a draw from its own stream, hundreds of values, no class of seeds to cover"
},
"features": {
"0": {
"audio": "audio.sample_rate=48000|audio.output_latency_ms=40|audio.max_channel_count=2",
"codecs": "media.av1.enabled=false|media.encoder.webm.enabled=true|media.mp4.enabled=true|media.webm.enabled=true|media.decode_support=sha:9c24a8728f",
"cores": "hw_concurrency=12",
"dark_theme": "ui.systemUsesDarkTheme=0|layout.css.prefers-color-scheme.content-override=1",
"dpr": "layout.css.devPixelsPerPx=\"1.0\"|screen.frame_border=8|screen.popup_ui=72",
"gfx_device": "rtx5070_62101",
"gfx_feature_status": "gfx.feature_status=sha:b153aef69f",
"render_noise": "fpp.hw_seed=5",
"screen_panel": "screen.width=1920|screen.height=1080|screen.avail_device_width=1920|screen.avail_device_height=1032|layout.css.devPixelsPerPx=\"1.0\"",
"webgl_renderer": "ANGLE (NVIDIA, NVIDIA GeForce GTX 980 Direct3D11 vs_5_0 ps_5_0, D3D11)"
},
"107": {
"audio": "audio.sample_rate=48000|audio.output_latency_ms=40|audio.max_channel_count=2",
"codecs": "media.av1.enabled=true|media.encoder.webm.enabled=true|media.mp4.enabled=true|media.webm.enabled=true|media.decode_support=sha:960968735a",
"cores": "hw_concurrency=22",
"dark_theme": "ui.systemUsesDarkTheme=1|layout.css.prefers-color-scheme.content-override=0",
"dpr": "layout.css.devPixelsPerPx=\"1.0\"|screen.frame_border=8|screen.popup_ui=72",
"gfx_device": "uhd630_2145",
"gfx_feature_status": "gfx.feature_status=sha:80c00ab015",
"render_noise": "fpp.hw_seed=6",
"screen_panel": "screen.width=2560|screen.height=1440|screen.avail_device_width=2560|screen.avail_device_height=1392|layout.css.devPixelsPerPx=\"1.0\"",
"webgl_renderer": "ANGLE (Intel, Intel(R) HD Graphics 400 Direct3D11 vs_5_0 ps_5_0, D3D11)"
},
"11": {
"audio": "audio.sample_rate=48000|audio.output_latency_ms=20|audio.max_channel_count=6",
"codecs": "media.av1.enabled=true|media.encoder.webm.enabled=true|media.mp4.enabled=true|media.webm.enabled=true|media.decode_support=sha:960968735a",
"cores": "hw_concurrency=32",
"dark_theme": "ui.systemUsesDarkTheme=1|layout.css.prefers-color-scheme.content-override=0",
"dpr": "layout.css.devPixelsPerPx=\"1.5\"|screen.frame_border=11|screen.popup_ui=106",
"gfx_device": "rpl770_7092",
"gfx_feature_status": "gfx.feature_status=sha:05ce56d3c0",
"render_noise": "fpp.hw_seed=16",
"screen_panel": "screen.width=1280|screen.height=720|screen.avail_device_width=1920|screen.avail_device_height=1008|layout.css.devPixelsPerPx=\"1.5\"",
"webgl_renderer": "ANGLE (Intel, Intel(R) HD Graphics 400 Direct3D11 vs_5_0 ps_5_0, D3D11)"
},
"134": {
"audio": "audio.sample_rate=48000|audio.output_latency_ms=20|audio.max_channel_count=2",
"codecs": "media.av1.enabled=false|media.encoder.webm.enabled=false|media.mp4.enabled=true|media.webm.enabled=true|media.decode_support=sha:9c24a8728f",
"cores": "hw_concurrency=5",
"dark_theme": "ui.systemUsesDarkTheme=0|layout.css.prefers-color-scheme.content-override=1",
"dpr": "layout.css.devPixelsPerPx=\"1.0\"|screen.frame_border=8|screen.popup_ui=72",
"gfx_device": "gtx980_58278",
"gfx_feature_status": "gfx.feature_status=sha:b153aef69f",
"render_noise": "fpp.hw_seed=6",
"screen_panel": "screen.width=1920|screen.height=1200|screen.avail_device_width=1920|screen.avail_device_height=1152|layout.css.devPixelsPerPx=\"1.0\"",
"webgl_renderer": "ANGLE (NVIDIA, NVIDIA GeForce GTX 980 Direct3D11 vs_5_0 ps_5_0, D3D11)"
},
"1633": {
"audio": "audio.sample_rate=48000|audio.output_latency_ms=20|audio.max_channel_count=6",
"codecs": "media.av1.enabled=true|media.encoder.webm.enabled=true|media.mp4.enabled=true|media.webm.enabled=true|media.decode_support=sha:960968735a",
"cores": "hw_concurrency=24",
"dark_theme": "ui.systemUsesDarkTheme=1|layout.css.prefers-color-scheme.content-override=0",
"dpr": "layout.css.devPixelsPerPx=\"1.25\"|screen.frame_border=9|screen.popup_ui=90",
"gfx_device": "adliris_7085",
"gfx_feature_status": "gfx.feature_status=sha:05ce56d3c0",
"render_noise": "fpp.hw_seed=5",
"screen_panel": "screen.width=2048|screen.height=1152|screen.avail_device_width=2560|screen.avail_device_height=1380|layout.css.devPixelsPerPx=\"1.25\"",
"webgl_renderer": "ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0, D3D11)"
},
"190": {
"audio": "audio.sample_rate=44100|audio.output_latency_ms=50|audio.max_channel_count=2",
"codecs": "media.av1.enabled=true|media.encoder.webm.enabled=true|media.mp4.enabled=false|media.webm.enabled=true|media.decode_support=sha:960968735a",
"cores": "hw_concurrency=6",
"dark_theme": "ui.systemUsesDarkTheme=1|layout.css.prefers-color-scheme.content-override=0",
"dpr": "layout.css.devPixelsPerPx=\"1.0\"|screen.frame_border=8|screen.popup_ui=72",
"gfx_device": "gtx1650_62101",
"gfx_feature_status": "gfx.feature_status=sha:b153aef69f",
"render_noise": "fpp.hw_seed=20",
"screen_panel": "screen.width=1920|screen.height=1080|screen.avail_device_width=1920|screen.avail_device_height=1032|layout.css.devPixelsPerPx=\"1.0\"",
"webgl_renderer": "ANGLE (NVIDIA, NVIDIA GeForce GTX 980 Direct3D11 vs_5_0 ps_5_0, D3D11)"
},
"19013": {
"audio": "audio.sample_rate=48000|audio.output_latency_ms=25|audio.max_channel_count=2",
"codecs": "media.av1.enabled=true|media.encoder.webm.enabled=true|media.mp4.enabled=true|media.webm.enabled=true|media.decode_support=sha:960968735a",
"cores": "hw_concurrency=20",
"dark_theme": "ui.systemUsesDarkTheme=1|layout.css.prefers-color-scheme.content-override=0",
"dpr": "layout.css.devPixelsPerPx=\"1.0\"|screen.frame_border=8|screen.popup_ui=72",
"gfx_device": "uhd620_2145",
"gfx_feature_status": "gfx.feature_status=sha:d1db3983c9",
"render_noise": "fpp.hw_seed=28",
"screen_panel": "screen.width=3840|screen.height=2160|screen.avail_device_width=3840|screen.avail_device_height=2112|layout.css.devPixelsPerPx=\"1.0\"",
"webgl_renderer": "ANGLE (Intel, Intel(R) HD Graphics 400 Direct3D11 vs_5_0 ps_5_0, D3D11)"
},
"2": {
"audio": "audio.sample_rate=48000|audio.output_latency_ms=40|audio.max_channel_count=2",
"codecs": "media.av1.enabled=true|media.encoder.webm.enabled=false|media.mp4.enabled=true|media.webm.enabled=true|media.decode_support=sha:960968735a",
"cores": "hw_concurrency=8",
"dark_theme": "ui.systemUsesDarkTheme=1|layout.css.prefers-color-scheme.content-override=0",
"dpr": "layout.css.devPixelsPerPx=\"1.0\"|screen.frame_border=8|screen.popup_ui=72",
"gfx_device": "renoir_21925",
"gfx_feature_status": "gfx.feature_status=sha:2f5fe3776b",
"render_noise": "fpp.hw_seed=16",
"screen_panel": "screen.width=1920|screen.height=1080|screen.avail_device_width=1920|screen.avail_device_height=1032|layout.css.devPixelsPerPx=\"1.0\"",
"webgl_renderer": "ANGLE (AMD, Radeon HD 3200 Graphics Direct3D11 vs_5_0 ps_5_0, D3D11)"
},
"258": {
"audio": "audio.sample_rate=48000|audio.output_latency_ms=40|audio.max_channel_count=2",
"codecs": "media.av1.enabled=true|media.encoder.webm.enabled=true|media.mp4.enabled=true|media.webm.enabled=true|media.decode_support=sha:960968735a",
"cores": "hw_concurrency=14",
"dark_theme": "ui.systemUsesDarkTheme=0|layout.css.prefers-color-scheme.content-override=1",
"dpr": "layout.css.devPixelsPerPx=\"1.0\"|screen.frame_border=8|screen.popup_ui=72",
"gfx_device": "rtx3060_62101",
"gfx_feature_status": "gfx.feature_status=sha:b153aef69f",
"render_noise": "fpp.hw_seed=19",
"screen_panel": "screen.width=1920|screen.height=1080|screen.avail_device_width=1920|screen.avail_device_height=1032|layout.css.devPixelsPerPx=\"1.0\"",
"webgl_renderer": "ANGLE (NVIDIA, NVIDIA GeForce GTX 980 Direct3D11 vs_5_0 ps_5_0, D3D11)"
},
"271": {
"audio": "audio.sample_rate=48000|audio.output_latency_ms=20|audio.max_channel_count=2",
"codecs": "media.av1.enabled=true|media.encoder.webm.enabled=false|media.mp4.enabled=true|media.webm.enabled=true|media.decode_support=sha:960968735a",
"cores": "hw_concurrency=16",
"dark_theme": "ui.systemUsesDarkTheme=1|layout.css.prefers-color-scheme.content-override=0",
"dpr": "layout.css.devPixelsPerPx=\"1.25\"|screen.frame_border=9|screen.popup_ui=90",
"gfx_device": "rx580_21925",
"gfx_feature_status": "gfx.feature_status=sha:2f5fe3776b",
"render_noise": "fpp.hw_seed=20",
"screen_panel": "screen.width=1536|screen.height=864|screen.avail_device_width=1920|screen.avail_device_height=1020|layout.css.devPixelsPerPx=\"1.25\"",
"webgl_renderer": "ANGLE (AMD, Radeon R9 200 Series Direct3D11 vs_5_0 ps_5_0, D3D11)"
},
"29735": {
"audio": "audio.sample_rate=48000|audio.output_latency_ms=20|audio.max_channel_count=2",
"codecs": "media.av1.enabled=false|media.encoder.webm.enabled=false|media.mp4.enabled=true|media.webm.enabled=true|media.decode_support=sha:9c24a8728f",
"cores": "hw_concurrency=28",
"dark_theme": "ui.systemUsesDarkTheme=0|layout.css.prefers-color-scheme.content-override=1",
"dpr": "layout.css.devPixelsPerPx=\"1.0\"|screen.frame_border=8|screen.popup_ui=72",
"gfx_device": "irisxe_7085",
"gfx_feature_status": "gfx.feature_status=sha:05ce56d3c0",
"render_noise": "fpp.hw_seed=6",
"screen_panel": "screen.width=2560|screen.height=1080|screen.avail_device_width=2560|screen.avail_device_height=1032|layout.css.devPixelsPerPx=\"1.0\"",
"webgl_renderer": "ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0, D3D11)"
},
"3580": {
"audio": "audio.sample_rate=48000|audio.output_latency_ms=30|audio.max_channel_count=2",
"codecs": "media.av1.enabled=true|media.encoder.webm.enabled=true|media.mp4.enabled=false|media.webm.enabled=true|media.decode_support=sha:960968735a",
"cores": "hw_concurrency=4",
"dark_theme": "ui.systemUsesDarkTheme=0|layout.css.prefers-color-scheme.content-override=1",
"dpr": "layout.css.devPixelsPerPx=\"1.0\"|screen.frame_border=8|screen.popup_ui=72",
"gfx_device": "icl_2145",
"gfx_feature_status": "gfx.feature_status=sha:80c00ab015",
"render_noise": "fpp.hw_seed=11",
"screen_panel": "screen.width=2560|screen.height=1440|screen.avail_device_width=2560|screen.avail_device_height=1392|layout.css.devPixelsPerPx=\"1.0\"",
"webgl_renderer": "ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0, D3D11)"
},
"4": {
"audio": "audio.sample_rate=44100|audio.output_latency_ms=20|audio.max_channel_count=2",
"codecs": "media.av1.enabled=true|media.encoder.webm.enabled=true|media.mp4.enabled=true|media.webm.enabled=true|media.decode_support=sha:960968735a",
"cores": "hw_concurrency=12",
"dark_theme": "ui.systemUsesDarkTheme=1|layout.css.prefers-color-scheme.content-override=0",
"dpr": "layout.css.devPixelsPerPx=\"1.0\"|screen.frame_border=8|screen.popup_ui=72",
"gfx_device": "uhd630_2145",
"gfx_feature_status": "gfx.feature_status=sha:80c00ab015",
"render_noise": "fpp.hw_seed=5",
"screen_panel": "screen.width=1920|screen.height=1080|screen.avail_device_width=1920|screen.avail_device_height=1032|layout.css.devPixelsPerPx=\"1.0\"",
"webgl_renderer": "ANGLE (Intel, Intel(R) HD Graphics 400 Direct3D11 vs_5_0 ps_5_0, D3D11)"
},
"49": {
"audio": "audio.sample_rate=48000|audio.output_latency_ms=25|audio.max_channel_count=2",
"codecs": "media.av1.enabled=true|media.encoder.webm.enabled=true|media.mp4.enabled=true|media.webm.enabled=true|media.decode_support=sha:960968735a",
"cores": "hw_concurrency=8",
"dark_theme": "ui.systemUsesDarkTheme=0|layout.css.prefers-color-scheme.content-override=1",
"dpr": "layout.css.devPixelsPerPx=\"1.0\"|screen.frame_border=8|screen.popup_ui=72",
"gfx_device": "rx6600_32015",
"gfx_feature_status": "gfx.feature_status=sha:2f5fe3776b",
"render_noise": "fpp.hw_seed=5",
"screen_panel": "screen.width=2560|screen.height=1440|screen.avail_device_width=2560|screen.avail_device_height=1392|layout.css.devPixelsPerPx=\"1.0\"",
"webgl_renderer": "ANGLE (AMD, Radeon R9 200 Series Direct3D11 vs_5_0 ps_5_0, D3D11)"
},
"50": {
"audio": "audio.sample_rate=48000|audio.output_latency_ms=40|audio.max_channel_count=2",
"codecs": "media.av1.enabled=false|media.encoder.webm.enabled=true|media.mp4.enabled=true|media.webm.enabled=true|media.decode_support=sha:9c24a8728f",
"cores": "hw_concurrency=4",
"dark_theme": "ui.systemUsesDarkTheme=1|layout.css.prefers-color-scheme.content-override=0",
"dpr": "layout.css.devPixelsPerPx=\"1.0\"|screen.frame_border=8|screen.popup_ui=72",
"gfx_device": "rtx5060_62101",
"gfx_feature_status": "gfx.feature_status=sha:b153aef69f",
"render_noise": "fpp.hw_seed=28",
"screen_panel": "screen.width=1920|screen.height=1080|screen.avail_device_width=1920|screen.avail_device_height=1032|layout.css.devPixelsPerPx=\"1.0\"",
"webgl_renderer": "ANGLE (NVIDIA, NVIDIA GeForce GTX 980 Direct3D11 vs_5_0 ps_5_0, D3D11)"
},
"5469": {
"audio": "audio.sample_rate=44100|audio.output_latency_ms=20|audio.max_channel_count=2",
"codecs": "media.av1.enabled=true|media.encoder.webm.enabled=true|media.mp4.enabled=true|media.webm.enabled=true|media.decode_support=sha:960968735a",
"cores": "hw_concurrency=8",
"dark_theme": "ui.systemUsesDarkTheme=0|layout.css.prefers-color-scheme.content-override=1",
"dpr": "layout.css.devPixelsPerPx=\"1.5\"|screen.frame_border=11|screen.popup_ui=106",
"gfx_device": "arl_6629",
"gfx_feature_status": "gfx.feature_status=sha:098c0bf836",
"render_noise": "fpp.hw_seed=19",
"screen_panel": "screen.width=2560|screen.height=1440|screen.avail_device_width=3840|screen.avail_device_height=2088|layout.css.devPixelsPerPx=\"1.5\"",
"webgl_renderer": "ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0, D3D11)"
},
"59": {
"audio": "audio.sample_rate=44100|audio.output_latency_ms=40|audio.max_channel_count=2",
"codecs": "media.av1.enabled=true|media.encoder.webm.enabled=false|media.mp4.enabled=true|media.webm.enabled=true|media.decode_support=sha:960968735a",
"cores": "hw_concurrency=3",
"dark_theme": "ui.systemUsesDarkTheme=1|layout.css.prefers-color-scheme.content-override=0",
"dpr": "layout.css.devPixelsPerPx=\"1.0\"|screen.frame_border=8|screen.popup_ui=72",
"gfx_device": "rtx5080l_61742",
"gfx_feature_status": "gfx.feature_status=sha:b153aef69f",
"render_noise": "fpp.hw_seed=28",
"screen_panel": "screen.width=1920|screen.height=1080|screen.avail_device_width=1920|screen.avail_device_height=1032|layout.css.devPixelsPerPx=\"1.0\"",
"webgl_renderer": "ANGLE (NVIDIA, NVIDIA GeForce GTX 980 Direct3D11 vs_5_0 ps_5_0, D3D11)"
},
"6": {
"audio": "audio.sample_rate=48000|audio.output_latency_ms=25|audio.max_channel_count=2",
"codecs": "media.av1.enabled=true|media.encoder.webm.enabled=false|media.mp4.enabled=true|media.webm.enabled=true|media.decode_support=sha:960968735a",
"cores": "hw_concurrency=12",
"dark_theme": "ui.systemUsesDarkTheme=0|layout.css.prefers-color-scheme.content-override=1",
"dpr": "layout.css.devPixelsPerPx=\"1.25\"|screen.frame_border=9|screen.popup_ui=90",
"gfx_device": "adliris_7085",
"gfx_feature_status": "gfx.feature_status=sha:05ce56d3c0",
"render_noise": "fpp.hw_seed=19",
"screen_panel": "screen.width=1536|screen.height=864|screen.avail_device_width=1920|screen.avail_device_height=1020|layout.css.devPixelsPerPx=\"1.25\"",
"webgl_renderer": "ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0, D3D11)"
},
"610": {
"audio": "audio.sample_rate=44100|audio.output_latency_ms=20|audio.max_channel_count=2",
"codecs": "media.av1.enabled=true|media.encoder.webm.enabled=false|media.mp4.enabled=true|media.webm.enabled=true|media.decode_support=sha:960968735a",
"cores": "hw_concurrency=7",
"dark_theme": "ui.systemUsesDarkTheme=0|layout.css.prefers-color-scheme.content-override=1",
"dpr": "layout.css.devPixelsPerPx=\"1.25\"|screen.frame_border=9|screen.popup_ui=90",
"gfx_device": "rx7600_32015",
"gfx_feature_status": "gfx.feature_status=sha:2f5fe3776b",
"render_noise": "fpp.hw_seed=11",
"screen_panel": "screen.width=1536|screen.height=864|screen.avail_device_width=1920|screen.avail_device_height=1020|layout.css.devPixelsPerPx=\"1.25\"",
"webgl_renderer": "ANGLE (AMD, Radeon R9 200 Series Direct3D11 vs_5_0 ps_5_0, D3D11)"
},
"63": {
"audio": "audio.sample_rate=48000|audio.output_latency_ms=20|audio.max_channel_count=2",
"codecs": "media.av1.enabled=false|media.encoder.webm.enabled=true|media.mp4.enabled=true|media.webm.enabled=true|media.decode_support=sha:9c24a8728f",
"cores": "hw_concurrency=32",
"dark_theme": "ui.systemUsesDarkTheme=0|layout.css.prefers-color-scheme.content-override=1",
"dpr": "layout.css.devPixelsPerPx=\"1.5\"|screen.frame_border=11|screen.popup_ui=106",
"gfx_device": "rx7600_32015",
"gfx_feature_status": "gfx.feature_status=sha:2f5fe3776b",
"render_noise": "fpp.hw_seed=5",
"screen_panel": "screen.width=1280|screen.height=720|screen.avail_device_width=1920|screen.avail_device_height=1008|layout.css.devPixelsPerPx=\"1.5\"",
"webgl_renderer": "ANGLE (AMD, Radeon R9 200 Series Direct3D11 vs_5_0 ps_5_0, D3D11)"
},
"7": {
"audio": "audio.sample_rate=48000|audio.output_latency_ms=30|audio.max_channel_count=2",
"codecs": "media.av1.enabled=true|media.encoder.webm.enabled=true|media.mp4.enabled=true|media.webm.enabled=true|media.decode_support=sha:960968735a",
"cores": "hw_concurrency=4",
"dark_theme": "ui.systemUsesDarkTheme=0|layout.css.prefers-color-scheme.content-override=1",
"dpr": "layout.css.devPixelsPerPx=\"1.0\"|screen.frame_border=8|screen.popup_ui=72",
"gfx_device": "rtx5060ti_62101",
"gfx_feature_status": "gfx.feature_status=sha:b153aef69f",
"render_noise": "fpp.hw_seed=11",
"screen_panel": "screen.width=1920|screen.height=1080|screen.avail_device_width=1920|screen.avail_device_height=1032|layout.css.devPixelsPerPx=\"1.0\"",
"webgl_renderer": "ANGLE (NVIDIA, NVIDIA GeForce GTX 980 Direct3D11 vs_5_0 ps_5_0, D3D11)"
},
"72": {
"audio": "audio.sample_rate=48000|audio.output_latency_ms=25|audio.max_channel_count=2",
"codecs": "media.av1.enabled=true|media.encoder.webm.enabled=true|media.mp4.enabled=true|media.webm.enabled=true|media.decode_support=sha:960968735a",
"cores": "hw_concurrency=10",
"dark_theme": "ui.systemUsesDarkTheme=0|layout.css.prefers-color-scheme.content-override=1",
"dpr": "layout.css.devPixelsPerPx=\"1.0\"|screen.frame_border=8|screen.popup_ui=72",
"gfx_device": "uhd770_7092",
"gfx_feature_status": "gfx.feature_status=sha:05ce56d3c0",
"render_noise": "fpp.hw_seed=5",
"screen_panel": "screen.width=1920|screen.height=1080|screen.avail_device_width=1920|screen.avail_device_height=1032|layout.css.devPixelsPerPx=\"1.0\"",
"webgl_renderer": "ANGLE (Intel, Intel(R) HD Graphics 400 Direct3D11 vs_5_0 ps_5_0, D3D11)"
},
"89": {
"audio": "audio.sample_rate=44100|audio.output_latency_ms=50|audio.max_channel_count=2",
"codecs": "media.av1.enabled=true|media.encoder.webm.enabled=true|media.mp4.enabled=true|media.webm.enabled=true|media.decode_support=sha:960968735a",
"cores": "hw_concurrency=9",
"dark_theme": "ui.systemUsesDarkTheme=0|layout.css.prefers-color-scheme.content-override=1",
"dpr": "layout.css.devPixelsPerPx=\"1.0\"|screen.frame_border=8|screen.popup_ui=72",
"gfx_device": "rtx4060_62101",
"gfx_feature_status": "gfx.feature_status=sha:b153aef69f",
"render_noise": "fpp.hw_seed=6",
"screen_panel": "screen.width=1920|screen.height=1080|screen.avail_device_width=1920|screen.avail_device_height=1032|layout.css.devPixelsPerPx=\"1.0\"",
"webgl_renderer": "ANGLE (NVIDIA, NVIDIA GeForce GTX 980 Direct3D11 vs_5_0 ps_5_0, D3D11)"
},
"9219": {
"audio": "audio.sample_rate=44100|audio.output_latency_ms=40|audio.max_channel_count=2",
"codecs": "media.av1.enabled=true|media.encoder.webm.enabled=true|media.mp4.enabled=true|media.webm.enabled=false|media.decode_support=sha:960968735a",
"cores": "hw_concurrency=2",
"dark_theme": "ui.systemUsesDarkTheme=1|layout.css.prefers-color-scheme.content-override=0",
"dpr": "layout.css.devPixelsPerPx=\"1.0\"|screen.frame_border=8|screen.popup_ui=72",
"gfx_device": "renoir_21925",
"gfx_feature_status": "gfx.feature_status=sha:2f5fe3776b",
"render_noise": "fpp.hw_seed=9",
"screen_panel": "screen.width=1920|screen.height=1200|screen.avail_device_width=1920|screen.avail_device_height=1152|layout.css.devPixelsPerPx=\"1.0\"",
"webgl_renderer": "ANGLE (AMD, Radeon HD 3200 Graphics Direct3D11 vs_5_0 ps_5_0, D3D11)"
}
},
"final": [
0,
7,
11,
49,
50,
59,
72,
89,
107,
134,
190,
258,
271,
610,
1633,
3580,
5469,
9219,
19013,
29735
],
"format": "persona-seeds/1",
"max_seed": 100000,
"sha256": "8deb3cf63f4017d5c615938941ed7b44e9840d92fc19aeef064d428d90b6c7bf"
}
-28
View File
@@ -1,28 +0,0 @@
# Input of the gate lock; `python scripts/ci_py_lock.py` writes it and gate.txt from the sources below. Wrapper-owned (ci-03), read at the wrapper_ref.
# python-version: 3.11
# exclude-newer: 2026-11-25T00:00:00Z
# wrapper: pyproject.toml sha256 64c93d06773cc6573cd062fe67b1c852d2a36b07426ea7076632900eebe956a1 (at generation); its dependencies without invisible_core, and its `dev` extra
# core: invisible_core==70.83.0, tag v70.83.0, pyproject.toml sha256 c0d14a4d26d3650005076ab72347eb24fba4b89e643f514e7f7334bd0a2ac174 (at generation); the core is a wheel of ours, only what it depends on is locked
# core-requires: platformdirs>=4 | psutil>=5.9 | requests[socks]>=2.31 | maxminddb>=2.2 | tzdata>=2024.1
# playwright: 1.61.0 from scripts/playwright_pin.txt (the stock client the gate drives the engine with)
# cryptography: 44.0.3 (the lab's PKI)
# harness: uv>=0.5 (the installers of the install-from-index job)
aioquic>=1.2
build>=1
cryptography==44.0.3
cryptography>=41
greenlet>=3.1.1,<4.0.0
h2>=4,<5
maxminddb>=2.2
platformdirs>=4
playwright==1.61.0
psutil>=5.9
pyee>=13,<14
pytest>=7
pytest-timeout>=2
pytest-xdist>=3
requests[socks]>=2.31
ruff>=0.6
tzdata>=2024.1
uv>=0.5
websockets>=13
-845
View File
@@ -1,845 +0,0 @@
# Generated by `python scripts/ci_py_lock.py`: do not edit. Wrapper-owned (ci-03).
# input: ci/py-lock/gate.in sha256 fc40deb4a528db91e487756180b44cfc8d6c9a1f64d548c1e8746e1cacf483e9
# resolver: uv pip compile --universal --generate-hashes --no-build --python-version 3.11 --exclude-newer 2026-11-25T00:00:00Z
# Every file of each version is hashed (Linux and Windows wheels of every Python from 3.11, and the sdist): one lock for every OS.
# A consumer installs it with: pip install --no-index --find-links <wheelhouse> --require-hashes -r <this file>
aioquic==1.8.0 \
--hash=sha256:12333f99f7493af4bc6b9af24f5ac45ae993a2780b9c469c38bdf4461189d5db \
--hash=sha256:14c8f0e4d7a74ee6ba3ade9434601f21ab8d6f9948f602efddbfc082d2bbb385 \
--hash=sha256:3da2c9609cd7299ee2965ff4b0df7a5d50ebe4eacd0cf50f8243686612c2d801 \
--hash=sha256:6fd3cd612aa739be38ab15005e596087cfc0ecbbe935a0343dc82f8b60532669 \
--hash=sha256:78616046a99831c55ca3aac3405b6353e79a923c67a6e5b1dd134585cfcc8e66 \
--hash=sha256:90d1a379ff0057a84863ba7d886af7f49eedfd1a14def5ba5a3ba719ab99c37f \
--hash=sha256:a17bf2347cb9f92c5ccb93fd88be65550e47db2a76e086602b226259f814b111 \
--hash=sha256:a4b57b3235014074fd7316dae5f4ee08cf46fa9b9c7bdf8718c3f310aaff9155 \
--hash=sha256:ac365806f09cba9127fe716f570219bf1fb7d733e847eef7535ade5c08aed721 \
--hash=sha256:b2acf9f4b7214502792d3430a341907f872cedd25042430f2c4138f9b7092d87 \
--hash=sha256:d9de93041c7749f1a93dbc0367408572ed76d710566fd7d74241ce7f69388350 \
--hash=sha256:eb44d2276ad670e8608bc2f2a926afc8e06f62de87275afb56d7ed8aa8a4f298
attrs==26.1.0 \
--hash=sha256:c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309 \
--hash=sha256:d03ceb89cb322a8fd706d4fb91940737b6642aa36998fe130a9bc96c985eff32
build==1.6.1 \
--hash=sha256:51cc11666391ab6f092070437ac747002ff46f3e4113a3622177ee6b488bfc53 \
--hash=sha256:ecd351a4be9d35a9eaaba244a7687143c9c7d4aea6ac964e7e7ddab20cbcf4e7
certifi==2026.11.20 \
--hash=sha256:7422df25243767b9877031a2248cb14d09ddac9beee846f4cef3d5c9191d488f \
--hash=sha256:af1cb240a8133f105aa52684a3a3258339d7f2fd0bd4e2812698ff5cf5588c4e
cffi==2.1.1 ; platform_python_implementation != 'PyPy' \
--hash=sha256:046bfc24911b37851ee1b51aab8bffe713d89c68c6a057b09484ce9fd5f69b4e \
--hash=sha256:06c72bb76605a4b0cd0aad6930b69d4baf7dd5d806cfc409b824191099700e66 \
--hash=sha256:0beceaabe56af686895136a2de78db54ecd8e4046b236b8fd6d6cb61389e9bf2 \
--hash=sha256:154852545011f779917b11c78db2358d095da62a9a172b78ad0a583ee5adc0d0 \
--hash=sha256:194cffa889098ced9976c3fc6340305e43f6303657d298da55366907c05c22d6 \
--hash=sha256:19ee6127ee34de7d83ce3d371ebc5ed91addbdcc39f9ab15ce4eb35a4e534971 \
--hash=sha256:1a18a57b58cfb21fc28d72e876acf10eaed67a1ed96226f92af4df681d571c4c \
--hash=sha256:1aa5645c30469b09530c4ebca77ebf8f17618293c58f8549cb1a543a50236e7d \
--hash=sha256:1dea0e4d7d4f11f619fe8c1d76caf49e24405b4b5743c0e3be16a500ecd930c9 \
--hash=sha256:208f941bb9d18e768138677f0a6d2ce01f590df56043dda1df1535ac57c88517 \
--hash=sha256:210019b6c7cf07f081b4c54635c8cf744377001350e29cc0f81c4377b4797735 \
--hash=sha256:246fa40ce8645a614ff682e0b70f37134e460eaf93a775e0cbe3cca585a67a80 \
--hash=sha256:25792eac27877609e7bb06d42ff88278a6624fff2ba9bbb523c09616b117e80f \
--hash=sha256:27350daa11d4f10c540e6e89dada4c54feb7256ad03e9a4dc075ebad7ba360d1 \
--hash=sha256:28907ab9bfb6aa13184cfc17c6b8e1023c5ab6fd7076d8c20a35e59fe04f8f29 \
--hash=sha256:2ae64be792b8966f2c69538199728b290e34726562896df1e5dc8ffd8d8188e8 \
--hash=sha256:31348097ff5bbe827ccc41795d4dd099d9f0625e7def00ee653c137a490c2a6c \
--hash=sha256:3143d81e29e1e20a9ce10901ec369012947876596f75a222235965f2b7ae832e \
--hash=sha256:3222ba5d678f80a030e6afbcc33dc1ae5cb45facabb61cee2c7016b8432fde48 \
--hash=sha256:3311ed60d36f83378794e1009ac6258bafbf81f7888b4caa7b35a521e3f95813 \
--hash=sha256:334644fbac4eff73d985a17a91226df55d0f394160c4cfb880e084c8f7161cac \
--hash=sha256:34e261f78cb6ceaaa36f42f2613f4380d94d9c759a9c73c769ee6e0247364632 \
--hash=sha256:363e05fa78e15116c3c32c210ee36884fd6b9afa6d440e47112c3bd511d64cb6 \
--hash=sha256:398aff33cee2767e3e781d2554c54bd0dff386bb437581e0d8011fde1a942ec1 \
--hash=sha256:3d22a20b1fb1632cc72c22f95f7b0d2961c3e1c235f245ba4c606c4771035659 \
--hash=sha256:42a494cee34437f05546455144f2b5d9ac09b1face62bcfce597d2e521066688 \
--hash=sha256:42e2f76b9455f5a9a844f770bf3e200ed3da0e15f5df3db9c31fe80b04b3d004 \
--hash=sha256:42f6930c31dc7f50732c9ae793c2786c7b6b044195967bbdde40bb9be81c4cc0 \
--hash=sha256:456a61fa52d579ebf9df2e9552ead5129855dbaff6c1e5a9b1bc408809bdc062 \
--hash=sha256:471cee653ae88de62096552e6d24ccb4a5adb8c8c9f10b5054d0122c15bf2779 \
--hash=sha256:49cbc70e6542d4ccccb936558d1064a8012541e78f821f955cff24e357776c94 \
--hash=sha256:4a7c934f7360e8cd64fe9efadcbd10c7c6364f531e432b9a4bf5ccbc9e0e8b50 \
--hash=sha256:4be96343e422f2dfcd12ab5c9f5aebe03f82f737c6bffeca6830b3875cb44aab \
--hash=sha256:4f42141fc14250de6dde5ee7ea4432be017252d91f19c5ad043c084cea629cac \
--hash=sha256:507a24c282e0f42f8ed737cf048572cbf580468da5555764a8331735e9c736b6 \
--hash=sha256:51b31d1c98274844cfd7838ce00bfc27c7423a4dc00fc0772fc3331c2cc90676 \
--hash=sha256:58acb8ab8e295e6c5ea12f888cbb13cf21511ef2a3303a23f4325c29d17fe5c1 \
--hash=sha256:5a59cc1c4442bc3d5c703bf720b51138d0bfc173618807c9ee2490a7541dd3d9 \
--hash=sha256:5bb4e7ea95dcd6a014a6fef62e62467d67d8e582326443f3d68e71d6320a9fcf \
--hash=sha256:5c58fe613dc5e5336357eff555824a314d8e43282600435c8d1cb6a7a2fedd13 \
--hash=sha256:5e7cecbaadb83884793e05828cee59b210b24583b9c7425d0ba6a754fe22eb4e \
--hash=sha256:616f097f2fe415bc92a247f02e11f634e1f9e9a83d327e3c915c15089c87869e \
--hash=sha256:63bbfd5ded17c4840ac07cd8f1c21ba9d9708141f840b324f422f41b207e3973 \
--hash=sha256:64faea20f4e2613363a1a9b9c7dd73058f3ecd00133a511e72ad7c511658f527 \
--hash=sha256:661c298b4821edebead0c91edd2b00374d67ad7c5a1f7a91d4442633b79d6a72 \
--hash=sha256:68e62fe11f30d5ca8289242866f0a5291402d8529ca2178ab8afc5c9694ae890 \
--hash=sha256:6a8dddef476fab96d066d578fc88526767b836ab5ab21754e1d5bf3879c31c7c \
--hash=sha256:6e192623c49c94421616a5778fba35cf0d5a8d000650c1967ef4448ee5cdd990 \
--hash=sha256:7225e4514edb64eb6740324353e0da0711954fd8d7da4576755b1c6e09b697cd \
--hash=sha256:75f80557d1389eddbd0de2681f6a390a0c5338c31ddaa821381c203fc3fd50d9 \
--hash=sha256:770de9db11e84213beec501cfcaa013b019820ca881e03344dea5844f7876d94 \
--hash=sha256:7750c6449dff7864bb9bb27ddfb0267756189201a3afc911d82b3caacd70dfc3 \
--hash=sha256:7bde5e4cc5c10140859842b9d383af292b22639a4dffb725314baf45968cef80 \
--hash=sha256:7ce713ace7c0e4520535b42b77eaa742c16dab813978064913e5a3cf82973b41 \
--hash=sha256:7da0c5eff80f0197f3b3d1232ec5a682a9325f4ae9016a78f5f5ca35f9ced1f5 \
--hash=sha256:7dbb61fe3a7699468030f71bbe5f8a0e326a151daa91beb11a6fc1f980c55e1c \
--hash=sha256:811bd1e21d32de12efca32393a0ab3f5133b54fce9bd44b8bd77ab07da14bf6a \
--hash=sha256:8ef53b2de9bcb9197d31854256575d59dbac0cba72ac627bb291ef5eceb74be4 \
--hash=sha256:937c0052c05a31ca1daf18de3158eed4dbfcb9cc107adbea227728d647be701e \
--hash=sha256:9d2055050ea716bd38b7f7f1579c275386646b4894c155a3e2f3cd62ed41b7c6 \
--hash=sha256:9f8d177621de5cb38ee3e731eda45d421db093ec0739f46a5594babda7987a98 \
--hash=sha256:a2d7755bef5a12ed488f4ef1f1b69ee9191d7396083b755a5d2295f6edb4768b \
--hash=sha256:a48d62ab9d6f4f98c983223a547af44be6ca3691074c31cecced6facd3ba2dc1 \
--hash=sha256:a4f00aa42f75d6e4595e8866e748cc1705adc0cddfeb2ca86d0d03993d63ba03 \
--hash=sha256:a6e721d4b0e45d5b65e87534470e67b18dcd092c83f68fba09f152b9cbc061af \
--hash=sha256:a730a083190634c65cca36ba5f489531576ebd79bcd5c8e172130f6453127231 \
--hash=sha256:a931079504ecc49efed7744c476a5c343a92fabf66dec2db95edb1b2fdc770e2 \
--hash=sha256:aa9511c62d14da7aacc9b4bf51f3f697a621e83b2d6919008243c3aad168eea3 \
--hash=sha256:ab36d55f9ed2d067327667c2fea18dda018eb628dd6347aa01dda6cf1f5d3836 \
--hash=sha256:ad2c86c495b899d862ea0f4b42891b8713a3bd45dd4105c7fd51c2a72f39f3a5 \
--hash=sha256:aeae0e330c9f6acd681f647d46cefd30c29f93e3392882e792e82080c9691399 \
--hash=sha256:b0431303acaea1089ad4b3e9ce4e6518193def1118d4073ca848635ee4ea2e96 \
--hash=sha256:b5bdfd1c873d4e093aabc0ca84c4ca6dbc4f752afb5c86f146d9742580c9da2e \
--hash=sha256:baed1e86cc735622097354b9d1281406caf42ff42a886d29faa8e8d1630333be \
--hash=sha256:c1453022f490d2459a11819d83ad1d586e9ff65a12ac3e705ffebd46d3685dcf \
--hash=sha256:c26608d2222fb1e94487e4a387d85f13eb55d5ed725cb25a0c589ac4ee60e7bc \
--hash=sha256:c7659f22557c5a0bc4855cd635f55edec690cc008a40768527762cb9fb263455 \
--hash=sha256:c8c69575568085ba0b1b10c0249d779a214aea6f6522e949a0fc9fb0fcb449d0 \
--hash=sha256:c8d2c9fd1f2d16f780d15127abb050d13d1a76c03a4bd87d7e4980e45e511e12 \
--hash=sha256:ca82be1a1d406ecfe1d25dc16cb33488e5a16bf4438c9fb590484ea29d92478b \
--hash=sha256:cc572dace3f60ef98d7b12ff411d20f5362feb31a0439eab0085bbfd349982d7 \
--hash=sha256:d18e5ac0f2f03f4f518d3e23db0f0cad7faa1da8620e9c09461d443bbf6e6692 \
--hash=sha256:d28630f5854ab07ab1fd4aba756de52326c82e6be15d414b12793f1975048b54 \
--hash=sha256:d9c275eaacd24aa73f94ffd6de08fc3f932424d8b6c376f4bed7cde376fe7bc3 \
--hash=sha256:da0e573f9f97159390c89d9f1a9e41908b66d408cc5b58d08cf3847d844c531b \
--hash=sha256:dd31f52ea1086513bb9df30f8fcee9b8918323ae067a3d5b78bc826a000712be \
--hash=sha256:dddad92b554513a31f272570678ba307fb9f618f05e3d4a5eacafff9eae03e1d \
--hash=sha256:df423d40ee8654634421812bc3b196da3f9bd7d32929da813f8394c4348a5358 \
--hash=sha256:df913725b79db7bcf03448f36b7bf8815363417d5b58deecf9305e3e30f0f21a \
--hash=sha256:e0bcb7e0f677f543555d2adff3bf19c05f66cdb4796e5ff602442ab2fe3c4ef7 \
--hash=sha256:e2d65b31f36619cda3999b78b2aa9632e76b78448e7a56fc4240824200e7c4fc \
--hash=sha256:e6e8cff14d6fb0be70a09c0bdc58096f501952d04624ebf867e0e56da2df8960 \
--hash=sha256:f16c709686a78c727bbbf059f92b0bf41c6fc60deec706d2dc19f529175a6125 \
--hash=sha256:f24fb43132a4c6b4cb4eb029492919b2db645be6808d738f244fd146c03c32cb \
--hash=sha256:f53e442b08449d42821fa4a4fba000095af9f62742a500f978a9f557ec44339a \
--hash=sha256:f5cfbc5fe74540d335175b656c725d74d90e3730c626d92575eea35029d9afaa \
--hash=sha256:f81b3b8f3d4e343550fa4baa0e479bba9f2d29ce9c2e9b51d1ce1718d7442fcf \
--hash=sha256:f8ec5e643a9a937f64e1999eb9f75d072263751912dc5cd06d3c85f8f44be7c3 \
--hash=sha256:fb92203a88b3d3053034db775110081c49d28be6551923805e039924093761e4 \
--hash=sha256:fcd22650c908d7b7da162bbfaab594a1227a15d1643a98c68b122ac642fa2264
charset-normalizer==3.5.3 \
--hash=sha256:00edb7682962c596f774bfa126e6b6f885b7af2319f448d327591c284a482de8 \
--hash=sha256:01b35bec964b92b89bdf94adf931d2e80a15f1c7b93bf850b4430cca23f7a2a2 \
--hash=sha256:020cabbb90926b2d8b022a5e057ab349f28844b61f34117323fc08c2971915e3 \
--hash=sha256:02b1abf64742b2d0782172cd2542616e462c201c829c23aff833390babe2967f \
--hash=sha256:06d07272f70d9880fba32d4876e966ae4dc9961134bc989066a0901509dfd8cf \
--hash=sha256:0810592b80dc5a97f8103443460264b588f31c6baa8a20abae7c683435d8117a \
--hash=sha256:085a5d1f49eaf96596d79494fcab18d9a32db6e345da15d6debfc90110b20679 \
--hash=sha256:09833ba78c91f0d1fd06387c69dae9f079428b77ea05eaaf1553eecead31fb68 \
--hash=sha256:0b3fc6f7dd9db4a7782e65dc98eb80b2a91a854cf54a03dd93649be2f7ca638d \
--hash=sha256:0c0fe07631dce6dae788a59c20ed927adc6feeb2d9ed440747eb367d89822a45 \
--hash=sha256:0ca25f1b1167e9fb94d93d3708df0b631de241bf8440947b0cb9f8c4cb66fed0 \
--hash=sha256:0ca2da4a505fae7ef95922f8d48235b2e49ff8f10f4edcc0481e5f6526ba3841 \
--hash=sha256:0cf4cb8d75090a8da3bd30c0963b2c6c6114e791c6fc060c3cef8971497b1f04 \
--hash=sha256:106b9d0438e2ff0a0e8ebd869273fcb3640af28323bba8651c714c57efb38e51 \
--hash=sha256:11ad35a0b856ad8bbd0c9e900c069461a4661694714aa17b6e6e2e8621e1c373 \
--hash=sha256:139aeb8ca63946dc79364c37f2c9cfe5c1b7f3882f2c47484d0e54bf14b921b0 \
--hash=sha256:1714ff1ba001da5241a585fbd17a7742a61ad34efb4be8404aca5679f51e53ea \
--hash=sha256:183aee7e84789391e547ec1609f8269332b9b123d21e97f7ef79eaa474c47e08 \
--hash=sha256:1a34385837db59d5de814c9f1e0f4157b571f9ce0eabdaeace410aa93bf5df62 \
--hash=sha256:1b2704f4651539eab50ba104a975b96c3cd5246011aa0755d2dd71ac12546644 \
--hash=sha256:2246873913d7db43ed5a3d98ace398b989b2ae20b77c8d761a7bef5fdb9bed42 \
--hash=sha256:249bf0b6f43985c33c83adbbab0ca71246ec24c82d960fa00c4ddb2cfed25db9 \
--hash=sha256:256b434b2860ef9da1cb6a5fd4ebb5d600936668e50e2035858948b96b068ecd \
--hash=sha256:26c6ad87bb79628954b52f8f7b9e18ab5cd9667546712ded9689fb7677e630d6 \
--hash=sha256:277b72183b96879887f0c3aa0bdac1fee08a6c7e67bad53145c4fd416d99dfd3 \
--hash=sha256:28ba8e6361e0f319641707484994096ceb77e05c29eaad2919756218c0c89001 \
--hash=sha256:28d954a437bfa5fcdfe7ad8902cf4347a8486f34a86c5f39003bc1288eb67d72 \
--hash=sha256:2978c799237eb66619d8951d2ab7efd317414cb6682160e05614ce1c8b5c905f \
--hash=sha256:29ac44f5878142128ffe4fa7e041ddc4cc5fafe43983245b9a141908c40b515d \
--hash=sha256:2a6f937e0b70133d1f826d0a253331b6fe1a4c874808cc12e16f2fb8177042f4 \
--hash=sha256:2b7797a5b0cb197f118fd13b41c14c5a3c38dd625a87c1da58a3066cf53254fd \
--hash=sha256:2c4e0050b732ee3dca3676a5f5cf7fbd0c131761c194f1bb1d24c055fad071cf \
--hash=sha256:2e7fbd98443f28a5ed8004f0b058edcc4720a3d344adf007c0b7f1adbff2f59f \
--hash=sha256:2f2d973d3c79fbd1066d63d1bafb2ade66934c0840ed149f6fac13c3fdf80793 \
--hash=sha256:323d5cf6df3ea724afcc3bfb07c73be06d2e8200a8b6b37979a300ae1e7836d0 \
--hash=sha256:326a7a0e3715c3ac24c21e7a3b831d6799cc795bff260aa49c23b69025852f99 \
--hash=sha256:34054580168b04e90e6c7c0f6c80173fa2d4f72c4db91c9095598454f96d6389 \
--hash=sha256:366f5efe95a6149ecbcebf779c2594a6a4ff6fc116402826c72ed0eccd6aabe9 \
--hash=sha256:390ef7c7e018c0abb8c0ec2d28ee137567ff50c3706facf6d115cac832ac993b \
--hash=sha256:39229c222445415db07a0be4dff8ad1addc3126644d7aa72d73f1575b637d69e \
--hash=sha256:396fdf2d4367674531a7c8d54ecabbc8e5131e3a1a06270285eb99f3140143df \
--hash=sha256:39e019884c8f857393df954d35f42bf99c5ab85af226fe74d1410188c6fec31f \
--hash=sha256:3ce4e4587e451ebc7d9899a7a1f539ea30a3c712d7bc8e0d256923c697fd5dcc \
--hash=sha256:3e8da696ef1935a019c10ec16555a062183ddf6d5901e296edeca4b2a8f84e1d \
--hash=sha256:40b2ba91f0851aa864994b3c7022e4d96d09026717e6a72e44410d6fb3a74a13 \
--hash=sha256:45aa4ccf5a6caba138dd0f8bf36fa3e26654585d534881b62ce5e4fea2487772 \
--hash=sha256:4831fb33e98e92140fa17d4d673a9f49f9c0ddd056115b722858793e4b86b0c5 \
--hash=sha256:48f7c7f537246bb3af2b3139f44716a30b21e78c2fd1cff0f3e392fbd55d8044 \
--hash=sha256:499e4bbeb1e79b14756311a1d12cb88112f244423e152d80981d9bcaff3279fa \
--hash=sha256:4a991dbd7aec868fe10802b02bddbf898173a47ba236f2d6afb4ab1f98243534 \
--hash=sha256:4ff5e27478681ef1b13b036baaf9beaf9b4c6990e903c752ad3b8764692c6d6c \
--hash=sha256:56405211fa124c393eea14b3aeacf5b90de72b1f69b0a60c9bc40b01dfe71a42 \
--hash=sha256:581d6e7df9b58d34147e21efde42a480b5087fe54f31e42550c26321566ba1e4 \
--hash=sha256:5970d148182b6b7c22b8290a81f02fb521c4e7aee6747743b3e645db58d5001a \
--hash=sha256:5f86753952f7de3abc7ce871f8239ce4e0d32a91c84d22f3a667e669907c3897 \
--hash=sha256:6118055f4ad0d94e016eadbb86caed9caf2c9033631ed70964ba631c1336984f \
--hash=sha256:61e32fdbf56f4cd25a1efa451c8b5fe886fc5e00143ccaacafdf21f301fad059 \
--hash=sha256:61f3258f700412c68fde407e7c749ed6930e795ea8f5ead9a40afddefbec12c4 \
--hash=sha256:6423accb6ecd1456bf824bbac98ba919398523a69ee5f1680dd1da88769de866 \
--hash=sha256:643724071b01cc0369026e259850791212cc187c6031d0e930abcd253f128e0c \
--hash=sha256:656b9744bac4493561d28b56d7d646afd7a8471254ef7004d849aa8368020037 \
--hash=sha256:6651fecdac146ecfa52700e02a5fa3b3677bddf5fced4983b43e904244de3f6a \
--hash=sha256:67bb767a8de7a2b1164c74fdbe5cdc32b9c15d7142efd9a6dc77ff63da94e846 \
--hash=sha256:6b702d36c565f6c650f4b479488f475b2982132ab8d0840d42b1442462c21056 \
--hash=sha256:6bfbbb9414dd0f5b81c259deb7e50b4b44e65e05879eee482351bdabed49d7f4 \
--hash=sha256:6c80b4e83e2fbddd25fe27804cdfc45ef71bb387522caa575af42118d72dc970 \
--hash=sha256:6c8abe7d59bbc891e5080b8b142c36db93154f840c4baf7c83ad6273a1a15397 \
--hash=sha256:6dde7edd9ba5005389bc7c0ab461411f281dbacb2b06e52bd23592eba42bb503 \
--hash=sha256:6eea31136fd924ecbb4e7c4f3df4b18230409629a22b3896f38a6754d5857794 \
--hash=sha256:70f65dd0c2ed79ea2d9776096e9c7d25e398c2c03eb31877753598d201d91784 \
--hash=sha256:73b4ddf1230df56c9e7017a16e3f5171b6ef0e4ff554a418a370d7ac7245bd84 \
--hash=sha256:747e83d415939612284afdc99f15295382639c0d3fc69a73aeb84b380d1f4af3 \
--hash=sha256:7a7e5bb8974842ad747d4a2b9fb928f84c3cdbe2c2fd7e405197fc1a1badaeaa \
--hash=sha256:7c313b46730b4a68bb31450973467313b2c496fefa42ae316b86c186cba74613 \
--hash=sha256:7fd816f466883dcaac196ac77271d0292eee4a81f4db1191b95d15328f335937 \
--hash=sha256:7fdd11094a0b07bce306b359fa7311c71d93466d967b3b345f2e9f03d8b2c959 \
--hash=sha256:806e72ebaeef54d7faa03414be9e8409eb3dcae49fba089d62063a60c0b5a4e5 \
--hash=sha256:81132eaffa984f0a399233df4cd383caad18e8cadc6c24c568cf9324732a9768 \
--hash=sha256:8231365b03b702b516aad35c9515694177ac31c9dc6240326f07308a4c45c708 \
--hash=sha256:826d82356907350f345cf0aa744d43a69ac7948bd60f460f997cde86928beadf \
--hash=sha256:84356c7b7ddf090e3e4692cb99fc820e6189b5f6662ca7e8589f41095cc8efca \
--hash=sha256:87d5a237d6531c654e7b9b319be9ba7e368665c466e02a03cfd4d3d77730782e \
--hash=sha256:87f7d6c595465a25d33fa3d5215a571a98c4cad00ead3ad18ebfb62adb3d3e6e \
--hash=sha256:885f202d6e4e2298bea9802ffc6d8c7dc45394199a8dd9e1492f05fe32dce311 \
--hash=sha256:8b969f0309de905101bc3d2471c112e9ccbba711a7590b12d51f372b4163688a \
--hash=sha256:8baddc6349faf49edae4d1322f12b681b9e86acacd01874457c997437ef4ccaa \
--hash=sha256:8c4dfcd3269f13dff7f29f9c332d54a4a21f17be818b49e769e111befd4d39e6 \
--hash=sha256:90b1ff6cb9c7a204a3b79b1b0ed6ac8a1d8fed3b6dc69e50ae5de0f358ee81d4 \
--hash=sha256:92bf85ecec3ad6374ae50d870bd1deb34de12bc1158b5fd09036d4c435c6f58c \
--hash=sha256:92ddc32b6a1508ea145f4f7995e00666db454b8fd3e2cae6c2ecbde4f4d44616 \
--hash=sha256:948fb3649416a70bcdbb267d79c7048e8aa16e989ab9da09f416e67cdd3d6b8c \
--hash=sha256:94b595e64bc2927f679774de50df340b7828dc1c07c99149ba7c2d0828dd8bf3 \
--hash=sha256:94c9d5d91c16554f6397b823d9e47181ba100d830ab16b5d720adc229e17b2e2 \
--hash=sha256:9510da88bdebc903be7844f31523ac8d7b3f63e167db54b6045104a2354afa6a \
--hash=sha256:96387278c3b17bc1170f80693398d0babac7b41df128ced8e27588a7155d95b2 \
--hash=sha256:96e268b0cbda016ac519513294fcd17032264085b600abaac58b93049477e132 \
--hash=sha256:9902e80096a94cf70fb72d12ae40e3b187b40e96fa722873d4d62afcd0333c46 \
--hash=sha256:9a6b95b1737f9b5942c35676c52db0c302d60fa806efde3fc2d9f54247ecf4be \
--hash=sha256:9b887e8a7103ae2171dccbab00a4bb2bf1560f5c10c28227e5513bc90a608cad \
--hash=sha256:9c1bd8321a840729a6b2620774cf4000fafe66c54cac9064972a10c4f607794b \
--hash=sha256:9eba4613d45b49196af04a5cbadfc5e9379ba94aac85184b72cb1107ad31af0d \
--hash=sha256:a094178c51530c9ebd1775e72d160af0eac4be244fb06ff1b6f182128c71903c \
--hash=sha256:a09ca76391f6e17b12d55c1068b4b5f8f6c9b44b432d936075372fa12782292d \
--hash=sha256:a250888753faa289e2997962fbb17c4960cbdb58575533ca6fceee68c224bdff \
--hash=sha256:a312fedd182357f2c22f066d17dcd7413b6a205ee3d063d36950e94e3019d3de \
--hash=sha256:a36bba41dc7fd263417688c4daf95a1091f93e1f6957c0f71ad7798907c5a10c \
--hash=sha256:a3f4044dd5d2f7b958be6b9903cb432e6a0fd944d673707ca5cab68137d0592c \
--hash=sha256:a43831574e14423103d69fb1357e76e4f2347041c98e8357ab88ef21812e80d9 \
--hash=sha256:a491d4afb361aba32d55d7df7ccde766a3aa9a34c002d2c32c2743bf6e77c13c \
--hash=sha256:a5a7e0326566759f9a7bc44f4b9a179cc40a297e09e759b0bc7c848c06347527 \
--hash=sha256:a6eba94fc00d899f8d268712772c8dcafc40215aa9b51701a397afc9426e012b \
--hash=sha256:a8f92cc9080bff47555c79b88e7fb8655438ce3bcf29c5f01ed2ed5efdf174a4 \
--hash=sha256:aa2476abf8669be493689634bdb79f468a6fe57b005a5126db7e9f61d1954fe2 \
--hash=sha256:aa8be1f24fbc03a07cfe002b70ba0716effc6b3011fd9e5560ca399d3d0605ad \
--hash=sha256:aa9390d89822dd06f9920ae3038819cb121643a72f4753b2eee1a79b2f1215f8 \
--hash=sha256:acaa0e100f39287dc5d13de96e33ba0786f1cdfb5b4ca28918913ab0eec3af72 \
--hash=sha256:ad1becd776f5a41a4d91cb9ee51778f4fd687ef15e4919779e00a33c6cff6948 \
--hash=sha256:af217012cfdaf6ea5dc0c538aac29b7bd030eb865056cc60f1d973b982b7917b \
--hash=sha256:b013417037c931583578639cab2523d5a2efc35a584c192d07f4c909b133f6b0 \
--hash=sha256:b0aa6b81bc632af7cac7b270c933298cb5ee858506dcf344e0da006667e0c351 \
--hash=sha256:b30e5496e453ac971bb17f5e096b84fbaae16d09e2613f6148ff528c08a54a0c \
--hash=sha256:b66a0e045cf859d7418f26a554509b65f21ebb6d90a95152460781939e8264f4 \
--hash=sha256:b6dad86d938104f9d43404029e5fc8392f82762d171933be4f192a6008bffa53 \
--hash=sha256:b6ea5bf7e3c39f6e56957d82274ac7cfab469590085883fdbc86e754cde76b11 \
--hash=sha256:b8fc4fe56992b089d6177021fe6db641321bb2bc2fc7a1abf815c29a80ca2137 \
--hash=sha256:ba26e4d073a4f7f2594676f2ff20ab80a7f03332b81c3f9964e9e53bf2305329 \
--hash=sha256:bed05639ae1bc23df7996a4fd13ea5064ddf60dc7dabd754f8badf060daec63f \
--hash=sha256:c08e06fc69750827d7ccebba63ebc97a85e479cd5c9dbdb80f5e08a77b774fdb \
--hash=sha256:c39a4fe28a16e8fa667c55c154f62c6c3cd9ca2491cca9f16330dd7360d05b76 \
--hash=sha256:c437ed8775d201d37206f37d233f547506e3aef60b9711584c65444c686b4905 \
--hash=sha256:c43d9737c3b85ccd16b1862b1e7aa5c4bf30a6033068403713c0a2bba5bda979 \
--hash=sha256:c9d1f467d121b33b06865c94ed5ed8388a9ef76f5e1acc1c8a854ac653493f5d \
--hash=sha256:caefc441edff6070a9f9749ca880a22731a1715d9e74b24304a546eec44bfc16 \
--hash=sha256:cb18428af7399e0a6f7e3b45f110d57a1a47cf07fd4b3ce50e2366d99a38959a \
--hash=sha256:cb4c25a9d3410262216b5c7447e51bfd2de0efae0a7640772dc6d2a8741590de \
--hash=sha256:cbd09b22b340f846671e79e8d832167fac60c1884be4c71fd667211486a3b58e \
--hash=sha256:cd5422fd4f8a7859846c9289e310dd95c0d1890c31819667942753e510f88f69 \
--hash=sha256:d12571adb9ceeb9ba0640db46433430062f5f1dec89e39713a2a5a8ce3016c37 \
--hash=sha256:d1b7a3fe4cf679eb3870b91b86b8ce12cacd5cf4d74bc114864a5cd65319ddac \
--hash=sha256:d313494077f849d8199f36166947785da1eeb36335fda15fde2e8f801ef271b6 \
--hash=sha256:d3c9d5284d64f4c1015d95b751577b260fd6d14e3f8edf21710f4436e7ac4c49 \
--hash=sha256:d4e7ecaa25f0dae672ac783c2e5aa9054a62e011749d64ff47b887af360a3e82 \
--hash=sha256:d57f1b6affc3581fbf0bc6d783cc60e7c9957adfd9c7b89f8a9f3573ad1cd49a \
--hash=sha256:d8f85e019c9f08ec134648a378ddd3f6f073c1e4b5ce9bdacd9a9e7b60749cd2 \
--hash=sha256:d93403a13c8f6f2d027185d90ab695e81d95e3ebd000f0078e201a1c3159d4d1 \
--hash=sha256:da606e3015dbd4b9a31c0468898a0c4c998846197ddfda78308821dc8c9e9be3 \
--hash=sha256:db2eedef732424346f98d0aba5c6ad688b648bc79847f4cc70dfca830130b1e6 \
--hash=sha256:dbdd407104ebf2360464ce02c7933c6ffac58bd5b64cdf6ef7dc0e787e782aaf \
--hash=sha256:ddea089587432e3df6771a4a405ef249cc9727f7becb1de3f00ab571b2432002 \
--hash=sha256:dfbde696fb427301ec40cd82b8eec0b528e44c6af8239f33ede2b2552d9a085a \
--hash=sha256:e1cdbde56f9fa6d426b78941c381e2ba160c1214809baa47e02c1d0d8881d598 \
--hash=sha256:e282983b8def5ada758fa1f18bf9060bb8ce6cdd73be32f62a2de59820d3286d \
--hash=sha256:e34f591669498a03cd70993b0a79b9f0ef40c4e6f8232466bac33c42f0c15742 \
--hash=sha256:e405cce4170de1fe520d9a92de9d7ececc23dfcf6888c62ab608a21be50838eb \
--hash=sha256:e4a0f2adf29a69dd8fe58e42bb191f3c87067b05fcc63279983e8c9ce5092abd \
--hash=sha256:e4f85c34f9be32ec5568a0668fb8bc029d3e729285fb8fccc38695e185379a9b \
--hash=sha256:e5e4785d8a0adeadfbdf75f4efc357911842674651cbafd7e97f69b11ec3cbc6 \
--hash=sha256:e86a27ab632d2e888c22b79263864eaff8b7dea9e87328a9bb0ea04eff24786f \
--hash=sha256:ea880ae1a692ae694c11bca7be74864614ff1a58bdfff4605f36d1956b4b1588 \
--hash=sha256:ee9de080e8d6221bbe4ba2667367b1cee0f47a53f60ffc5e431b698cd2f2b214 \
--hash=sha256:ef8b925f2b331a1f17d6fb32625e09fd571cf41844f578379f934dab0067cf0d \
--hash=sha256:f06e257ee0cc85a7e4ec44f171ae2595fd901c34212f3c9e7ab8fd8621401e99 \
--hash=sha256:f1214052966421a88ed526ba93e4463b39346862fa4721be5306434b33dae795 \
--hash=sha256:f160f03e15bd1e3c35db9bfc20c42ff83155d37f9b0c79806cb10051ca725f13 \
--hash=sha256:f1b357340e4cd29011683bd81226175611ad835fec22e5b7df83b96701571226 \
--hash=sha256:f39290a0c2e3f4196563189bb45e6ef5d5badf50864e1bfaafa9003f0595573f \
--hash=sha256:f5a5c311e5de6954c36230a37863b5ca58ce232589bd637ad2881c4056897b12 \
--hash=sha256:f7a841170fde40b0e1345884bee09ceca7db49a9291fa340089bec66a366c243 \
--hash=sha256:f7fb9a3275f1a1528e542a0f5a3d2c89fcaf68e797fc5c6530434cbd92a852c4 \
--hash=sha256:fc540d1618c5638fcf5aea97060cf011467918b010bf682a84ecc0c9474e6cd0 \
--hash=sha256:fcb17f1d40c38912a2cdb56ea47aadac3527cd0b06fe24f3a0c4896febbea063 \
--hash=sha256:fd0341b9dea133d187d7c5a2cd7e21ae6449a7b68ea8c2454f9cf77def11ec1b
colorama==0.4.6 ; os_name == 'nt' or sys_platform == 'win32' \
--hash=sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44 \
--hash=sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6
cryptography==44.0.3 \
--hash=sha256:02f55fb4f8b79c1221b0961488eaae21015b69b210e18c386b69de182ebb1259 \
--hash=sha256:157f1f3b8d941c2bd8f3ffee0af9b049c9665c39d3da9db2dc338feca5e98a43 \
--hash=sha256:192ed30fac1728f7587c6f4613c29c584abdc565d7417c13904708db10206645 \
--hash=sha256:21a83f6f35b9cc656d71b5de8d519f566df01e660ac2578805ab245ffd8523f8 \
--hash=sha256:25cd194c39fa5a0aa4169125ee27d1172097857b27109a45fadc59653ec06f44 \
--hash=sha256:3883076d5c4cc56dbef0b898a74eb6992fdac29a7b9013870b34efe4ddb39a0d \
--hash=sha256:3bb0847e6363c037df8f6ede57d88eaf3410ca2267fb12275370a76f85786a6f \
--hash=sha256:3be3f649d91cb182c3a6bd336de8b61a0a71965bd13d1a04a0e15b39c3d5809d \
--hash=sha256:3f07943aa4d7dad689e3bb1638ddc4944cc5e0921e3c227486daae0e31a05e54 \
--hash=sha256:479d92908277bed6e1a1c69b277734a7771c2b78633c224445b5c60a9f4bc1d9 \
--hash=sha256:4ffc61e8f3bf5b60346d89cd3d37231019c17a081208dfbbd6e1605ba03fa137 \
--hash=sha256:5639c2b16764c6f76eedf722dbad9a0914960d3489c0cc38694ddf9464f1bb2f \
--hash=sha256:58968d331425a6f9eedcee087f77fd3c927c88f55368f43ff7e0a19891f2642c \
--hash=sha256:5d186f32e52e66994dce4f766884bcb9c68b8da62d61d9d215bfe5fb56d21334 \
--hash=sha256:5d20cc348cca3a8aa7312f42ab953a56e15323800ca3ab0706b8cd452a3a056c \
--hash=sha256:6866df152b581f9429020320e5eb9794c8780e90f7ccb021940d7f50ee00ae0b \
--hash=sha256:7d5fe7195c27c32a64955740b949070f21cba664604291c298518d2e255931d2 \
--hash=sha256:896530bc9107b226f265effa7ef3f21270f18a2026bc09fed1ebd7b66ddf6375 \
--hash=sha256:962bc30480a08d133e631e8dfd4783ab71cc9e33d5d7c1e192f0b7c06397bb88 \
--hash=sha256:978631ec51a6bbc0b7e58f23b68a8ce9e5f09721940933e9c217068388789fe5 \
--hash=sha256:9b4d4a5dbee05a2c390bf212e78b99434efec37b17a4bff42f50285c5c8c9647 \
--hash=sha256:ab0b005721cc0039e885ac3503825661bd9810b15d4f374e473f8c89b7d5460c \
--hash=sha256:af653022a0c25ef2e3ffb2c673a50e5a0d02fecc41608f4954176f1933b12359 \
--hash=sha256:b0cc66c74c797e1db750aaa842ad5b8b78e14805a9b5d1348dc603612d3e3ff5 \
--hash=sha256:b424563394c369a804ecbee9b06dfb34997f19d00b3518e39f83a5642618397d \
--hash=sha256:c138abae3a12a94c75c10499f1cbae81294a6f983b3af066390adee73f433028 \
--hash=sha256:c6cd67722619e4d55fdb42ead64ed8843d64638e9c07f4011163e46bc512cf01 \
--hash=sha256:c91fc8e8fd78af553f98bc7f2a1d8db977334e4eea302a4bfd75b9461c2d8904 \
--hash=sha256:cad399780053fb383dc067475135e41c9fe7d901a97dd5d9c5dfb5611afc0d7d \
--hash=sha256:cb90f60e03d563ca2445099edf605c16ed1d5b15182d21831f58460c48bffb93 \
--hash=sha256:dad80b45c22e05b259e33ddd458e9e2ba099c86ccf4e88db7bbab4b747b18d06 \
--hash=sha256:dd3db61b8fe5be220eee484a17233287d0be6932d056cf5738225b9c05ef4fff \
--hash=sha256:e28d62e59a4dbd1d22e747f57d4f00c459af22181f0b2f787ea83f5a876d7c76 \
--hash=sha256:e909df4053064a97f1e6565153ff8bb389af12c5c8d29c343308760890560aff \
--hash=sha256:f3ffef566ac88f75967d7abd852ed5f182da252d23fac11b4766da3957766759 \
--hash=sha256:fc3c9babc1e1faefd62704bb46a69f359a9819eb0292e40df3fb6e3574715cd4 \
--hash=sha256:fe19d8bc5536a91a24a8133328880a41831b6c5df54599a8417b62fe015d3053
execnet==2.1.2 \
--hash=sha256:63d83bfdd9a23e35b9c6a3261412324f964c2ec8dcd8d3c6916ee9373e0befcd \
--hash=sha256:67fba928dd5a544b783f6056f449e5e3931a5c378b128bc18501f7ea79e296ec
greenlet==3.5.6 \
--hash=sha256:0616b8f878098c5681fd8f0dc92d887551717402342a70f0abcbfea5f5ad8a44 \
--hash=sha256:06c0e933290fba8ffe53ead4ae1b8044b0e9754b75cebf381aa2bc3e50d82fac \
--hash=sha256:128813fc29f2336a21b4d06eedd5e16bcc7ea46f59e9ff1cb30ea70e48195d88 \
--hash=sha256:188bf333769b7145e2b0b4a7f09615ec550ed44d3a2a8395fb7b36f0e9901e13 \
--hash=sha256:1c20ea32a73d17b9b60e3371240e17b0068120c98a5ec01a224a7dd8c89733ba \
--hash=sha256:2ab5f42ac6c238eb71770715e6e909ad9a1a92b6c681ccb64cd5a0f07edb953f \
--hash=sha256:301102a49120b095e72a7838792b41233975fc1c155daec6d98f81c00c9280e0 \
--hash=sha256:311018b46472fb26ee85870847fb89eb64cc8aaddb617400789d87076f7cfeec \
--hash=sha256:3ac3494c381dab876cad7d0b22f3a722f3e0c8deb3a65b9e7f35ad7f58b8fcb3 \
--hash=sha256:3c6dede9133e1da41d561bc3fb14e92b47e2ce39ae60edefaad145658ea7c5e2 \
--hash=sha256:3dbb4596a6a4e5d47121a33ff20533a81e60f302d9e67b69909a8bc21a43f0a7 \
--hash=sha256:3deccbb57a481e3a408fe61cdfd5c13e0678fc0a30fdd09597917ca87b4be877 \
--hash=sha256:45663c01a4de48b9a64a2ee1509d92d1dfd3afb02b2ccfc9333029d11aef996a \
--hash=sha256:45bfd2b51e38aaa5f9849f114d9c7c1d75f69187c849b3549cd64c465283abfa \
--hash=sha256:460e70b033aba8ed47e2ac9b5d0d2157b05a34fbfa30a241400aef4118902cdc \
--hash=sha256:4fb8e59f68845d56c23c031dcd79c329f345e4a9d2ffac91c3d1ab366bdc457b \
--hash=sha256:520648db8fb92eef7b3e6013f5a6f901cdf0d6685f639c2f7a245879f865bef7 \
--hash=sha256:5599b380c1f28efeb724e81569eac80cd92f99a85bd9775456caaf3225d40b11 \
--hash=sha256:59deccd347735a7774223b05a93773fddbb298aba3cea21be4337fb4752dbe32 \
--hash=sha256:5a0b2791239c99992a86c1b635b787fe2a877d9eaaa26f8891ce943832b585ae \
--hash=sha256:5adcbbfe78bdc242c71740a02e0991cc1b2f34d33c8bb15ca45eee8fd1140942 \
--hash=sha256:5b602b4201b965a8354d74e232364a66ff243dd142e350d035f46169bb36e13d \
--hash=sha256:5bbda3c70dd35d60671bc33b01916802707a052130d9e50cdb871d34594d35cb \
--hash=sha256:602024dae6d77e161f4b89491b62ca1d4f19949d79d47b2db057e476d21179d6 \
--hash=sha256:61a61b4a95a4f97922c3a6f5606d3e360851584bd47e500a5161373c53810e3d \
--hash=sha256:63aff70fe5aac59c72215f42ec39fcb59ff46774fa966e717f8ecb6ee2273577 \
--hash=sha256:71890d5247020c25c21a6b65202782bfc281d4e6e244842419d30e3492bb6dcc \
--hash=sha256:73a29b5ba642e35433166a03a3e02935e7238c4b3467fbd77523b99edea23e5b \
--hash=sha256:7969bffa322c097bd46ae595ada6a931cefda613f18ba64587e9cff4cb320756 \
--hash=sha256:7ac4abb3877c43af320392c664774eef6fa2cc063c79a55fc02d844a3cbe7395 \
--hash=sha256:7f731ebac68ea06d628658295cb2d217b10186329fcf9a3b6a149045059bf92e \
--hash=sha256:7f924a5a9d5890649566f2f6682e0d8ad8ca23028bacffbbac36dbd7fd680176 \
--hash=sha256:874cea8bb1ec1ddccbacbd027856f6bf496f6bc18aba97a918c20e067edab236 \
--hash=sha256:876077e7ebb8c84ed068e2b23d4c62ebb010d60df84b9591af1be2f39010ffb2 \
--hash=sha256:886bcf1870af74c32bc310fd00a6b803445e17e51b7d5a107c7b35c0f362cc16 \
--hash=sha256:8b27df301f56e3b3d2298095c8f7d6b68f2521f6b1693e901fa039bdbae34424 \
--hash=sha256:8b7c73d1cef3d9ae963e9ff03f6222df43efbb9054ffd2f1969c935b7fc84c02 \
--hash=sha256:8cda13494d86a4f12429641117cb6ac4bbbc9c30a33f711f7d3a2e5fbe4b0b7e \
--hash=sha256:8cddea1b8339451c2fb3388e138347b6126744f33b611bdb55b7357361cfef46 \
--hash=sha256:8dba0129b93e7091dfefaf4cf7000172741bff7f47bf6326fcf17f32fbb54d6b \
--hash=sha256:8e67c43bdfc88d5fee6db0d3e40175b362fc95fb85f0412d233b9b203c53a575 \
--hash=sha256:9133d68624b1f2e89ec2f554d56aea8a5b0d7168cd9320200ba58d4d794845a4 \
--hash=sha256:916f92f2a8db10508f739d0b5e00b83defe5d1115a997c54532a6d7cf8c95404 \
--hash=sha256:9297fb9c39b9a2c039dbcd306c410bd6906b95244dec3bba4318d36c718c164c \
--hash=sha256:95e7c44d072db623a1aab04ce488cf9533294a77ed9d072cd503a3596f4106ac \
--hash=sha256:975736b002ed080d124cf81a79cb7e05cb26d6b3f5c7a7b651c0fcce70353aa1 \
--hash=sha256:97c5a53e8c1754df58e73f047a99e287d4da1bdfe64b0072fb25c87000897951 \
--hash=sha256:9a09d59bef1db94f384b5bcc2d523694d338f3df6b757aeeaf7baca5d0c0be88 \
--hash=sha256:a364c1ea75dc51b83a17f52fe0c79cf8bc4ddf740403bebd4581c7666eea017d \
--hash=sha256:a3b4a01c6da07ef9f80d4fe8933b994bc99747bcea3eab0330a9c34d3c12655b \
--hash=sha256:a5876d0a60355af98d535c47f6cd6eb0f8a432396dab26845d380b92f8412422 \
--hash=sha256:a6a4b98a9132e0f45c9fc245a63894cfd8c45fb7a0d6bffc5eab3ec327cf7324 \
--hash=sha256:a6b4ff33f7e011bbaa148238d131c4fd4f8afbab3c104ddfbdb2b12b74ff7016 \
--hash=sha256:a93ee7c6e8fd0f8a83525a51bd777be57ee17787e91d805bd8d6faf9dcada18e \
--hash=sha256:b374e79ffa7511afc11773aef40a4ccea6191fba1c856ea2f9c56738dca69d7a \
--hash=sha256:b7d501d5eb5d4f67207df364752ad697465b834268744be7581c18d81d35d41d \
--hash=sha256:c59acfa8eb73a1e0d484392dc002bdf001fd4ce73394e0132df3d1ab6093d7cb \
--hash=sha256:c75116c9de79949de23006e2d9b35ee82874c594fcf5c0311b439acaa14b8441 \
--hash=sha256:ca80a49b53ed1d22f7282da7255f7bb2fd1935fd0f623d8613fda38745f18961 \
--hash=sha256:cad5782f93f7f738b62c6527b6f32a60694d924029f299a8b524758cfa53d815 \
--hash=sha256:ccadce0130fd813ec86ebfe969a6c58b42acc1d0fe55a47525375b740e07b605 \
--hash=sha256:d701eab36200c36224833d07dbdb709adb7fd4253429548ddb5e547b8ed40586 \
--hash=sha256:dad3d233d441a022c1f7155f0fb9d5aff7b97c1ea8c7dfa02cce586b16ab2d0b \
--hash=sha256:dd0b83bed3405b586a3133629f1d1a5bc7bfd64822a3b7ab342bdc68e6dbc61b \
--hash=sha256:de3de000d459402cda015068fd135aa50c0bf6f2477a80d4da1e646f123b4e78 \
--hash=sha256:de9923832f2d8c1a5ecd8d7260465a6ca5a86888a0d129e3bd5cf0406d2fc5bf \
--hash=sha256:df19e2d0b1620039af5102563fbd96e8938c7f5c3f5828528d641d9fc585525e \
--hash=sha256:e85880b538e59a59f55117b81f208a6660ad5ac328aad9305f812d9b8bc67a0f \
--hash=sha256:ee7d9da3bf493909cf811a3f038840cb34fab5ae2956b8a263919f6e289ab188 \
--hash=sha256:eed88b64a5e5da72d6a71cdc5aaeefaa5ced9b748f8d19f89800b339961dad39 \
--hash=sha256:f0ba7c2a329d650628f4c8572fd1db29f0a59dd70a3e3e0710dcf18a35cce9d8 \
--hash=sha256:f8e63209c3e1e828ee6a457529b4a6d8b05d050fe0ae03a7ae49e967c5d312e0 \
--hash=sha256:f8f0bd690e1a41294ac87905e8121c81a3761ec2583c768f13467428606c8c7a \
--hash=sha256:f96f0e30b5a95c7631b12bfe214cbc90ec8fe8cfa36920596c10514a65743519 \
--hash=sha256:f98e8215e172f567ce80eeaed9107fb4d32b6c44f26983d9b8334658136a205a \
--hash=sha256:f9fe868463ec7e1363733af77e38a5fda3e9b63940337048c945d69e0c80ff24 \
--hash=sha256:fdacf26402389bdd89857ad3c045a26fe8f3314f9a8b28226f82f88463a65b77 \
--hash=sha256:fe3170a69fe039b18ad18171e66faa9a75f6fe9d78f968fd9b54e09fbd714d81 \
--hash=sha256:fea4427d1ffdb3b523d7daa6712038428a4c16c450b9777bdd1221cfee0eab49
h2==4.4.1 \
--hash=sha256:0e25f1462b23c9cb82d9eb02e28bc706dac2a68cb457c6a0d74d63c8a2a5d0e6 \
--hash=sha256:4e866ffb1a869ae14dd9b5e6beb5c24a13da0495ad72b65925ded182521c1516
hpack==4.2.0 \
--hash=sha256:0895cfa3b5531fc65fe439c05eb65144f123bf7a394fcaa56aa423548d8e45c0 \
--hash=sha256:858ac0b02280fa582b5080d68db0899c62a80375e0e5413a74970c5e518b6986
hyperframe==6.1.0 \
--hash=sha256:b03380493a519fce58ea5af42e4a42317bf9bd425596f7a0835ffce80f1a42e5 \
--hash=sha256:f630908a00854a7adeabd6382b43923a4c4cd4b821fcb527e6ab9e15382a3b08
idna==3.20 \
--hash=sha256:a7db850025b95ded1eae8a46181a1a6c56c92c96f0e2b005d9ff8dc0210cab44 \
--hash=sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c
iniconfig==2.3.1 \
--hash=sha256:67f4b9c50da0dedf52af349e7749a80a9057a5031199791b906c3bb3ae878960 \
--hash=sha256:9121e2c1fdb355232495be3194c8dfe87ccc2d5dee45947b78e68f499790d7a7
maxminddb==3.3.0 \
--hash=sha256:02cc5c537c4114e28d016df20038782bb58ac8b2ff0c2b565c98b2d98b5f0fe5 \
--hash=sha256:07319eff57ffd7098e03134617ad5c7f914d142e480c8c94e03c1f6de5fac730 \
--hash=sha256:0bbe7c13bfbd2f31b07814af15aa3c00143f8ffb0d29395b9eea1be6455961e6 \
--hash=sha256:0ce3807a0152b15d3f21786df65b111a8125bbf6791116f8f7fc4bfa9400f1b3 \
--hash=sha256:0de3312ba04de27cadb94cb929a70e4e766e2c6ef2e03c7fe00d539aa37ac0f3 \
--hash=sha256:0e0ee21668fc19e363220f3ada0c711840d9a2113969196f72f839e693e04c71 \
--hash=sha256:0f5eb14e7aa94cd0a527d2204eec5300990dd625312ebc149fc3404dcaeeeb98 \
--hash=sha256:0faf21b6af26e16714c1a5a3bc25ed33fd54e36cc569a6d237fd933747c2bf88 \
--hash=sha256:1522beddd9469584592259adbeb7a8e9c245c711340e3d69ec119455122cc6d0 \
--hash=sha256:1ae6c42bb73a1d1fc49c444968226d7badc692da325bf7933fdd4914f3594f99 \
--hash=sha256:1d00629a61610b79049c58a038f2b153b753a3c49705feddddd5794e0fdb8ffe \
--hash=sha256:20f49792c0cbcc7ca471beb4fe2d672166f80214d995ca1904f7cdee9ec22a7f \
--hash=sha256:21f4f14eb7952be84ad8545c47b3dc6f74ec9c9376f558bfcc3010e8f39ab698 \
--hash=sha256:258dae2eaf1d41fd2cec24c35f4416db1fc5f229bf4e166e48b95ec63a56a14c \
--hash=sha256:27dcb821921058222f482a07e0197234acb20115f1d306ddc6a8366166119016 \
--hash=sha256:28dc9fdf062804d4f45f2a1db22a53bca4efb0a7819a91135e66f5a3128889f2 \
--hash=sha256:2c2ce11abe1e95024a89c94760363018117991c5beedabba31bdb8919233588b \
--hash=sha256:2c5b2e1d004bad06a5b69287b2f5e9dc62e627d53687add975fa2eb89e8935bc \
--hash=sha256:349efe73c27482bc2cf8102a54afbfb8d9edb354251f92f153f68ba37b337c90 \
--hash=sha256:365d4f1e278062669e67911c83a5e6cc0b6a7056eb809dab9510aaa2f3598039 \
--hash=sha256:3a04a057569c7a25f22bb09d2eb3642afdd68229f553d1fce45a5671ecb10933 \
--hash=sha256:3a9e909ea42c485f36827193a0c2e308b2507ec9f3dcc20a15007d9311da917a \
--hash=sha256:3e644605506108fc186b51cb4b8d0689a9b6e645e437d3a0d44aa9eaa703c929 \
--hash=sha256:3ff1a4df2f3bed1e59cc2e6d133b5958cc8ef0809099ea1832ef9254a512e704 \
--hash=sha256:40b3221611c5e7f4e2ea763f126750f0d07cd9008cf4dcbd2be556e2bcfef1df \
--hash=sha256:4116b442797b7abe627e0602a2bd18962f6334b6de9c8ac84975be1b1275cf57 \
--hash=sha256:41c76b7477242d750ba445cc546ba4f35b5e0c25697c5152394ada7a1e09201b \
--hash=sha256:467dbdc1057ef3654d67caf5786aefca06875601620d9b82b431863d95caf29b \
--hash=sha256:46bf4d61e7756c05eeaded62f1c4972937fd1f78565e2506a186819ba066b46c \
--hash=sha256:476f017ef7de4297c67e53e2f09797e467932192308e7076db5b1e92c875c3db \
--hash=sha256:49c265a28764299c80c42c571d61d04c636a2a2ba12cd9b03ef8ab7ba6da2405 \
--hash=sha256:4dcc5db21722eda1ef390da04ac07b404776f9883c04266ebfdeb0bda2d45173 \
--hash=sha256:509249b07366262792532ec08191eb342a50310001ce9a14ecb1750b82392f10 \
--hash=sha256:5a3a7921ab8c3d9ee885ece3111b91722fa5a376413de10caff61331108c6714 \
--hash=sha256:5c35330ff224d61c10a3d3b3d34eeb9b21cbb1639a8bfe7a7a8dc9eda745ca33 \
--hash=sha256:5cefe4162a1a61dc4a9e2b9dccfe24bc6e5e5f49f713f6d4fcb062bdba1bb326 \
--hash=sha256:5d07281b67c3db198073780657e452a7d75664bddc75b462246335569475b8d1 \
--hash=sha256:5ecacf5d13421d5222368874e98bec96b634aca4743f92384f0aead15fa16147 \
--hash=sha256:5efc65479e474059ae7f85aede693ad3a8e31c255437d39aa03528dc17d369cf \
--hash=sha256:5f82f74e1e15cd828a55ab392d0fd80d4fc6d51eb31b5262d3481b7027c18efc \
--hash=sha256:610fc2a2e62037e4b23b17391897b63be600fae99a92a7ae68169c73e7a4a4ae \
--hash=sha256:61acddb7247a405fe944368574d44e11bc0d1dcd6b61008abab75d0f5472e6bd \
--hash=sha256:6267226f6664c3f0260841295ef0c9af70a6ba05b70f2dc7475ac560aa3fbb90 \
--hash=sha256:64f2d3635d2cc9dc5271d84c4d05a4577b60e10abff5af52b2fd6b60959107b8 \
--hash=sha256:71aba1b8f867e62724beae2a23fa92cbf4276375067abfd225d0ac1f021ee500 \
--hash=sha256:7a9ad4ddddf7bc20798975a1171cbccf7c0f50cecb3e86be30659253d2d8bee7 \
--hash=sha256:7b81da613941cc7d9e82db57c1772f6bef5c100954cacc7d9876232aca59505e \
--hash=sha256:833121c30e701edf8ac2464b1c310607e51a3f54c0f26b2b9922344f363e596a \
--hash=sha256:8827cd2d85ef250460d9dd96a0e67c57ef8deaa14599caa3f06e290cc1838389 \
--hash=sha256:88d6c904009e5bec0e6a38ab5dfe421646a0d14f7084fa86a8b36142117418ce \
--hash=sha256:890bc8115b8750fa4af1cd548b1064e844f4804ec39527b11c794830bade51fd \
--hash=sha256:8ab285825e128d211f31d11a46517e44235bf5dca79cba9a2cb1f10bcf99ad27 \
--hash=sha256:8ab7572acf78e2ef8d630b667a0b85690278221cca76339803488fa6c1272786 \
--hash=sha256:8ac0f9fdd7e27f5b9815684616759bd6fb367bd37cd7f4217c5aa5c0541f0aed \
--hash=sha256:8cb0027692908d9c302ba8dd0dae0eb8a9955b7ccf72335b4651ef66778df284 \
--hash=sha256:8f12c30c765cd6181bcd91affc2f0138f5364daff567f4672a9ae7b77e631480 \
--hash=sha256:91c1cc2989d4e392a37c26de67505a79ba213c90eecc83740b7c81e2df3e60db \
--hash=sha256:9639ca7810411293c9c576ed9843d3e7a8666474a1371fd9982a6f62728e6c35 \
--hash=sha256:99620535d26c8da868bae2018affde754e59e5b43b8705902f0f4a6003356a13 \
--hash=sha256:9a1bebada95181fd1602ef554e9d5d36da00403691dc8520efb99751c52d9162 \
--hash=sha256:9a9c7ada72b6af6dc2920be812867ff17cb6168892f3cba87f052986d2125f2a \
--hash=sha256:9add6485ddb57071d919dcb8ee98617392d143ac39dad797d9786701d8397c7c \
--hash=sha256:9cc2c7c166f87080f1471f1c1b256fef57ff9f3db436d69f1659837b98793d98 \
--hash=sha256:a00220f8c1b5427eb541fed03329ed122b731de571f9379ce1c7b235ef43e75d \
--hash=sha256:a04d62ae564795a630e4e375b30ef2166933ba887862f825494b2ad40cfcf622 \
--hash=sha256:a2438674f20fa9a86961ef121d0e07baa27000e186356ebf29cebf1af3ea9db3 \
--hash=sha256:aae50ff65f1252476587c351af9b6509bef7931bafe2cb90bf76f14fc4a2c1af \
--hash=sha256:ac035833b9792e045eb425c887b95a2e31ef657edf7923c5e80989580c69c604 \
--hash=sha256:b0006b64890a98a88faf89cad185deb7b519c0bfbf405a8273ede74a521b64fb \
--hash=sha256:b4b808b90b6f7a360d7bd7a3c5093e072b8a7f5c8e58bad9747e7f072dec9434 \
--hash=sha256:b7ba63a56028e629205ecf09820a92247a43f2ec90177aebbc745a36d7504805 \
--hash=sha256:bb4bc63ec6599362f7d8dcef412b17d7231a828af4ae0961f570a99a13096f72 \
--hash=sha256:bda0e715d702b847ab2082be1ef298f2b4a6cdffb72435d9967b057e88e8d8ec \
--hash=sha256:bf0d031ae8536c3f255db2677712f32802a3075e19c5638fb39868e439fd8dfd \
--hash=sha256:c56dacc8b9a4c85c62e5363ba718f628c93ae542df9e2d4c806362ac823d99be \
--hash=sha256:c85a62953aece0e4ae5ae54bfef64bd6b5af5945febfb9d587cbca848b9e4bd9 \
--hash=sha256:c8d81122ae0c7433ff40b32ae15b033e092ab2d00a2dfdd14f1a281e5d34015c \
--hash=sha256:c928a8ec2bf02166fdb7ea2f7c34221a4cd7870efe9eb9880adb85c994e9d044 \
--hash=sha256:c9ac07bb579fe86b61eaf1afebacc814be9310735e57764b18ccdb4988ef18d8 \
--hash=sha256:c9caa99bc6c724d83b28ecb047ecf4025df3fca551dc55361277fa24fcb41294 \
--hash=sha256:caa27e2adfaf74e9543f7cab81c1ce7247ff6a916fa122aa5af9e2bf9ebfd074 \
--hash=sha256:d09e124045edeaa0d81f3682e58b7b7e4c661f7a4b5ca1fad51746ef3b88df60 \
--hash=sha256:d2c45dc64167e177241c875e43d6baef2c36add9e1494bbb695a802eb8958e1d \
--hash=sha256:d926424a2ab007733913698f85d229e3cc5063fc95fc425b9088ec565de35a84 \
--hash=sha256:db36ff8dad59bc58882ea3374f191557783203588cf9aa2f9c4542adce36eb63 \
--hash=sha256:de07a78680594a9b4c49bab13c7b3d280068ee4846a1580787ed3ca800e1604f \
--hash=sha256:df8121c8af59e9ec51810f54d47d3bf9b89ac20a8305a890d5b97133325d10c1 \
--hash=sha256:e0971046ef19aa64e77446e45d8a87a7aa4a7b867312253d0ae90f12dd53ab6c \
--hash=sha256:e1dc4c12292fc9629a95daa7c98ebf74cf59368e62b5eec79975a2598c91b5e5 \
--hash=sha256:e30ded32a953398b001a8856ddd2eae2ff79656cf25db62b26fdf8fc3e7597f5 \
--hash=sha256:e31dd47a404093a3b257285c70e230bcd76952ab11c1b326c21abe400a252a12 \
--hash=sha256:e4bf04ee9373307becc3e6cb70ae47b4c0dcf9e566d5f9bf59a97e569ef7d38e \
--hash=sha256:e621394915e565f671958e2453e5fb6cc7e34552c1e51a2768686d4b1501c2c3 \
--hash=sha256:e72ae1be344ee834ba6e9951b2a2b4866968f85443505078847b139549921884 \
--hash=sha256:ec86c26da32501ba0fa0ed47de784c61500614b1b2d9e2a78e6c621bdd17d2c1 \
--hash=sha256:ed94f267f0c5caaac4ab2430b11cad3af7b98a882498ea73101776ac881735eb \
--hash=sha256:eda4be57322b09230af7e3cbec89f8f3f90709835137902d5d741cfecda862fd \
--hash=sha256:edda68f4ea05a3ac537bc1505f916019d7a9eb47d88244904713aec5a2761421 \
--hash=sha256:f0fdc32d7b2e9890de5bf5c24d11f0740bbc7d137b97764a2e47374bbd581efb \
--hash=sha256:f198f726c515dac34a9a75fe663a475506f30b430631e10ea8f14dc15370154e \
--hash=sha256:f19a0a42d3c99a80edd14d0bd972cb83993989c714d54d41f5fe170031aca7b8 \
--hash=sha256:f21ff2e354e15b865af7cf393366c2c5b1169eacd5d5b1ca3660ac10a04706f1 \
--hash=sha256:f22a60827975d1ef37cfadf87cafda030e669c1b298deaee823e1f45cef7f886 \
--hash=sha256:f5a7a57ad94f2ac03cdd8f345c1d17f33a97f12fe75ff04c3a0d050fce91cad0 \
--hash=sha256:fc6bb1b23a4614377d6ca090e01da624d5141193abcc58be27b9bbe67ae86d02 \
--hash=sha256:fcaf3aa27b2872da169818c5f44bd55161ef509f83216cb9669499a0aa0f41cb \
--hash=sha256:fd7a6faa680a285f2747d22185401f09dbde094e40267201e743c91a8c6e2813 \
--hash=sha256:fff5ae9e651fb2098b8634e6a1bbec07077279d2fd0f20a1da529b9353515336
packaging==26.4 \
--hash=sha256:81383611a09c1bc0b08b76e0fd5829d7c6824c65b27a6aee339da133f4233ea2 \
--hash=sha256:c4b671c41ddb9bf26e543c37723610d28fb6bf7affc4da17cf048d419d2c062a
platformdirs==4.14.8 \
--hash=sha256:1e34af590de4d978631b751eb2202f2fee4497537a17c1720b12fcf57b331392 \
--hash=sha256:96893d686e84e9e6f358a9ea41a8de544df66dbf2ba6cda250e7dc73acf85b9b
playwright==1.61.0 \
--hash=sha256:009588c2a7e499bc5a8b425b61fa65490968bbda9cd69e0cf2cff10f8304659a \
--hash=sha256:35c6cc4589a5d00964a59d7b3e59641e0aac0c02f15479a7af77d20f6bc79597 \
--hash=sha256:372d55a6f1248fa1dd47599686980cb8fb5bbe6fcda59eab793eb657c11d8a9b \
--hash=sha256:54f3b39f6eab832e33458c1dd7da0b5682aedab3b09ae731b5c59fa12fd2024e \
--hash=sha256:93454322ade8c11d5d6c211bfd91bdfb9ffb4810e3e026371bcbc4bec1b7ee4c \
--hash=sha256:9f7de4536088d12037c13a52b7ea34b59270b78926bb56935070597ffac6b1af \
--hash=sha256:e9fcbffcf557a8620fdedd92491eb59a32d18e23d6f3b4f6214b952be324fe51 \
--hash=sha256:ff138c3a604f69911e9d42fd036e55c2a171e5616edf04c1e7f60a2a285540b0
pluggy==1.7.0 \
--hash=sha256:7dd7b0d8832ba3cb632c306926ded123429211b83641b35dc5c41ad2d34f9bec \
--hash=sha256:d1eaa46ebb595891b860ab086b4d09c8588af65ebd4361b8e8f4bb8920b90ba8
psutil==7.2.2 \
--hash=sha256:0746f5f8d406af344fd547f1c8daa5f5c33dbc293bb8d6a16d80b4bb88f59372 \
--hash=sha256:076a2d2f923fd4821644f5ba89f059523da90dc9014e85f8e45a5774ca5bc6f9 \
--hash=sha256:11fe5a4f613759764e79c65cf11ebdf26e33d6dd34336f8a337aa2996d71c841 \
--hash=sha256:1a571f2330c966c62aeda00dd24620425d4b0cc86881c89861fbc04549e5dc63 \
--hash=sha256:1a7b04c10f32cc88ab39cbf606e117fd74721c831c98a27dc04578deb0c16979 \
--hash=sha256:1fa4ecf83bcdf6e6c8f4449aff98eefb5d0604bf88cb883d7da3d8d2d909546a \
--hash=sha256:2edccc433cbfa046b980b0df0171cd25bcaeb3a68fe9022db0979e7aa74a826b \
--hash=sha256:7b6d09433a10592ce39b13d7be5a54fbac1d1228ed29abc880fb23df7cb694c9 \
--hash=sha256:8c233660f575a5a89e6d4cb65d9f938126312bca76d8fe087b947b3a1aaac9ee \
--hash=sha256:917e891983ca3c1887b4ef36447b1e0873e70c933afc831c6b6da078ba474312 \
--hash=sha256:ab486563df44c17f5173621c7b198955bd6b613fb87c71c161f827d3fb149a9b \
--hash=sha256:ae0aefdd8796a7737eccea863f80f81e468a1e4cf14d926bd9b6f5f2d5f90ca9 \
--hash=sha256:b0726cecd84f9474419d67252add4ac0cd9811b04d61123054b9fb6f57df6e9e \
--hash=sha256:b58fabe35e80b264a4e3bb23e6b96f9e45a3df7fb7eed419ac0e5947c61e47cc \
--hash=sha256:c7663d4e37f13e884d13994247449e9f8f574bc4655d509c3b95e9ec9e2b9dc1 \
--hash=sha256:e452c464a02e7dc7822a05d25db4cde564444a67e58539a00f929c51eddda0cf \
--hash=sha256:e78c8603dcd9a04c7364f1a3e670cea95d51ee865e4efb3556a3a63adef958ea \
--hash=sha256:eb7e81434c8d223ec4a219b5fc1c47d0417b12be7ea866e24fb5ad6e84b3d988 \
--hash=sha256:ed0cace939114f62738d808fdcecd4c869222507e266e574799e9c0faa17d486 \
--hash=sha256:eed63d3b4d62449571547b60578c5b2c4bcccc5387148db46e0c2313dad0ee00 \
--hash=sha256:fd04ef36b4a6d599bbdb225dd1d3f51e00105f6d48a28f006da7f9822f2606d8
pyasn1==0.6.5 \
--hash=sha256:4017b0fce125096b8573b39c989fdb1a4b19cf761e683398184550fea0e66587 \
--hash=sha256:6b11616a6bcf3a40e635f082bb232fa57b5e0dd7f517bd7ddd69ec3794508a47
pyasn1-modules==0.4.2 \
--hash=sha256:29253a9207ce32b64c3ac6600edc75368f98473906e8fd1043bd6b5b1de2c14a \
--hash=sha256:677091de870a80aae844b1ca6134f54652fa2c8c5a52aa396440ac3106e941e6
pycparser==3.12 ; implementation_name != 'PyPy' and platform_python_implementation != 'PyPy' \
--hash=sha256:a076f3f489b39b43ed13563a1dafe42447445bec2e294154ec5c57fcdda4c85e \
--hash=sha256:f03387877eab82ce01bbdfd0ba7252ee55a90b1c708d5129e2ce915475cf1db6
pyee==13.0.1 \
--hash=sha256:0b931f7c14535667ed4c7e0d531716368715e860b988770fc7eb8578d1f67fc8 \
--hash=sha256:af2f8fede4171ef667dfded53f96e2ed0d6e6bd7ee3bb46437f77e3b57689228
pygments==2.21.0 \
--hash=sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9 \
--hash=sha256:610ca751c9bc2492b38eb9a38a7fbc93edbbb2d7182edaf34e66ae493dee5c8c
pylsqpack==1.1.3 \
--hash=sha256:11242dfb87124853c1af0931dc766c34f99e000ceca9cf1912883297b19509c5 \
--hash=sha256:20e870f903bfad70c3b65536049091d5d325367bcde6855dd6d2b7b419c45ae6 \
--hash=sha256:4cac49c32d9f455bea012223b8e2bc64e79d4b94eb8a8a7f60a239947b09df97 \
--hash=sha256:6ba422e788309d0564f80cde1704d8857ae288951b7707f9fee7ab660ae56109 \
--hash=sha256:8fdb02cb2d4c7e5b31ad6959398ccc2d6963f449f5776bf754a3425fbbb830f2 \
--hash=sha256:b220afff798cf59baf15489a4f1bd8d5f167d0f3224695380b767e8dffe8316b \
--hash=sha256:b733be9fc7ea9ac37945a3333a11c79838d8d9886fb9f6169376fc258333530b \
--hash=sha256:bc3967c423fbba759b4353d0b467753b8f510c6f769bf3f68317ac4b8dfef9db \
--hash=sha256:c1f1c495c161415a371535e524ab1a68753fe15c6534aaf87a3a50bfd804e85c \
--hash=sha256:cd4de1c914be239e99b6251f0c03ceeca5fe4d19dc67b727e921dcf3d3587d4d \
--hash=sha256:f25a63d645a3e3ad59c5d453048f91b2d9b0f3655b146d1491c18c783d584a56 \
--hash=sha256:ff53d63bf96a90973fbfceb7381c11bf1656bd9704f703259f9ba38f71c6040d
pyopenssl==25.1.0 \
--hash=sha256:2b11f239acc47ac2e5aca04fd7fa829800aeee22a2eb30d744572a157bd8a1ab \
--hash=sha256:8d031884482e0c67ee92bf9a4d8cceb08d92aba7136432ffb0703c5280fc205b
pyproject-hooks==1.3.3 \
--hash=sha256:5fc53fdac9f7bd63fbcdc868fb5f90b4784d78a53a3d3388cd738b807441a20b \
--hash=sha256:defda19b854fa0d3bd4f76ea4ddcba8abd7dcfcdd585a6690ade050744fc5f43
pysocks==1.7.1 \
--hash=sha256:08e69f092cc6dbe92a0fdd16eeb9b9ffbc13cadfe5ca4c7bd92ffb078b293299 \
--hash=sha256:2725bd0a9925919b9b51739eea5f9e2bae91e83288108a9ad338b2e3a4435ee5 \
--hash=sha256:3f8804571ebe159c380ac6de37643bb4685970655d3bba243530d6558b799aa0
pytest==9.2.0 \
--hash=sha256:07acdcf88ec174f907dc01af70bf52d49b014bbab03faeeade31c96b18c2e588 \
--hash=sha256:97c4f3b1f3c7414aa36465e09b8220f1d03627993bd51b1282e193753c80557b
pytest-timeout==2.4.0 \
--hash=sha256:7e68e90b01f9eff71332b25001f85c75495fc4e3a836701876183c4bcfd0540a \
--hash=sha256:c42667e5cdadb151aeb5b26d114aff6bdf5a907f176a007a30b940d3d865b5c2
pytest-xdist==3.8.0 \
--hash=sha256:202ca578cfeb7370784a8c33d6d05bc6e13b4f25b5053c30a152269fd10f0b88 \
--hash=sha256:7e578125ec9bc6050861aa93f2d59f1d8d085595d6551c2c90b6f4fad8d3a9f1
requests==2.34.2 \
--hash=sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0 \
--hash=sha256:f288924cae4e29463698d6d60bc6a4da69c89185ad1e0bcc4104f584e960b9ed
ruff==0.17.6 \
--hash=sha256:0692088e6b33455572fb18465e891b443f196e98dc1986825685c77ff6f4c5ac \
--hash=sha256:084d9c8f5ec718e7eba007dba339e7cb4f7571d2f267558ae080bf428fb6a69b \
--hash=sha256:1939b3d701c7b6981b7cf93473de5bf88b129b9ba84efaed5154cc517c44634d \
--hash=sha256:1a0bea6aa1216e0ec4cd35d3dbccec0d772a7c2aad28ec9c6e82571dff2c20b0 \
--hash=sha256:2b04276561331300325040bdca21460770029ec574d4c479099e39e8ad1ed43c \
--hash=sha256:3db61f5015600543a581b07fa7f6f64afa0eeedefe16034cadd88c4074087582 \
--hash=sha256:435241c61af5909a022f76219d3d1bf24730dc1bf0acabb5ddf4b569ab3cbb30 \
--hash=sha256:6a12c50a33936dc00db2be21ba25fb168a8b95c55eda2a3ac85005af69885e4b \
--hash=sha256:9cd2fd9923e9806b8b6b67a3469e2258e84bd4d21e45d5a1a690afdfb9c8e57d \
--hash=sha256:9d44ef2140402043fd6f689ef541858b80883a8b0a02e38539ef0614ebe57d0c \
--hash=sha256:9fbddc08577592e283c265d865e0182de6e33db185494db7b06290d989d888e5 \
--hash=sha256:aa3b08254a732acba246891089a152c47c5733dc36b8ecb76ce8602f8326e5e4 \
--hash=sha256:b5aba93b3db4b70c5697e4fee6e0d5b9c8452a9a3a03679611cadc25915a2173 \
--hash=sha256:c2f4af6670b7a0501904e881bb3f1f24bd0d964dec1eedbd85f0eb73786e1128 \
--hash=sha256:d006bbb2945edb17b0ce6a0c1b5f5a8d81ba11dbac294a0a925effa22ce34feb \
--hash=sha256:d8b14e1473dc86ab9069cf7a2ba5041dc012f59110201844ed04cfddf07055a0 \
--hash=sha256:fb589e032806bb942e4fb526f30b80a1a64112147ed9f1d38cc3de2e255b6f45 \
--hash=sha256:fd661702202a89c00a4c9d0339008805fa5876bfa1c57e165495c2e62230dfbf
service-identity==24.2.0 \
--hash=sha256:6b047fbd8a84fd0bb0d55ebce4031e400562b9196e1e0d3e0fe2b8a59f6d4a85 \
--hash=sha256:b8683ba13f0d39c6cd5d625d2c5f65421d6d707b013b375c355751557cbe8e09
typing-extensions==4.16.0 \
--hash=sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8 \
--hash=sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5
tzdata==2026.6 \
--hash=sha256:0a10eec6e13ef16b627fabed9a5f2ba61a62b1c67f327305f4e7e412a70b4aec \
--hash=sha256:85d2cd9c09f81f0bb29db27759fc83af4f1e620efb814f8c5bf8b4cc4feece6d
urllib3==2.8.0 \
--hash=sha256:0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3 \
--hash=sha256:63bf2ead4c879426ebf22ef2a781eeb4aa3b4ae798a0435506f8687fd5bb9b63
uv==0.13.10 \
--hash=sha256:19a76fd50a6a2bba38ee088d8336566856569be08196865f98132a08806581fc \
--hash=sha256:2a9ff188b442419c7aadebc445fcc1f287b25f99af50fa6d563b90cc0047b7cf \
--hash=sha256:30e75714a9cff3aa56281c7bf533a4e93cb5bdfcc0325d3aae54b9106460bd63 \
--hash=sha256:3bf1c1b13cac2533a342ca16b1c5f41347cd399404c9477a04ff79c5f7cb4dea \
--hash=sha256:50bee2a59ea9422b493aabc0cde9288f58fbcf6e8d688c30c4ecd8309459cac1 \
--hash=sha256:5bcf77c50760146ff7b41022ab7aeb1954d42dd47b89fad36b43a1a8a43da994 \
--hash=sha256:771a749b34477501092c9fe6d5e52f45cef944d875b0f2e2c989047a2ee647ab \
--hash=sha256:7cc9c41b43d583e34c781fd3446405b06e9c5fa2db468ce2a534d353db6429e5 \
--hash=sha256:7fa025c4b0f33b9a5357252e1be058d94157e13bfb8ae45d7e27cfce3759c65d \
--hash=sha256:8b0a15613aae9a3e1c134bb5ee706583af0addced7eb1add992f8b1b3e3a92a0 \
--hash=sha256:a52ee170c00d4de1d42026c4dbb00c5d7f327edcf2b2bddeecd0cfb169868ac7 \
--hash=sha256:a9636b4430a9b8a37ecc4d85111d1fd2560ef616edf5301b84f474073bf89e2f \
--hash=sha256:bf7174b00c88879d4a1019b51256bbdb2dd61c55c7dc896031e16d090e380ce6 \
--hash=sha256:c85a2ecb62d09d61904f5405b525fcc51f971d081f8508a881fa2f9bae7543a7 \
--hash=sha256:d87b9cf8165f2b3cc596e856b5bf794da9cfad6d1b110ca9d87eed42a15b3684 \
--hash=sha256:e52a1af7f97b717572f9e2bd69e54eb253b2c88a705500e35811c21106c439d4 \
--hash=sha256:e89dd26ea831dde70639ba0a798fa04a4c7c0226fd2b241da86218bfa370e495 \
--hash=sha256:ee3bca6523ed93c3ae0d1a90c2733be307f5f7cc5287c746214e93a3bae0da13 \
--hash=sha256:ee403b6bbcfda1bc7db269be5c40c1624df27b3b838d3f8a416648e00e2de5d4
websockets==17.4 \
--hash=sha256:00ad98e4bb0df7a6711c645eec16d5a9fdf99f0692bd4f5b6cb85a68677ba8df \
--hash=sha256:0132e3cbd3f5cfc1ec77588961b302d72a02e2603b82c2c23fd5fb59dc4fa206 \
--hash=sha256:023dc13bdc42a55e152acc81c39c90ec6cc4159ed17d23c6d73460fa2a73ab16 \
--hash=sha256:02f380df26de14999ecace203fe1396ac14d1c6132afc7924eb6f8c8b646c69d \
--hash=sha256:03ddf4eb76ced8725dcbb000ff60b0fb8d7330ed011f6dc725a1925c5fe02051 \
--hash=sha256:043945a43873c7c11a3f75238d475c95f902e967de329eb8763704546cfaa6b6 \
--hash=sha256:046ed16d3d83d64594e4a40655fef061ccf36059d8c30a01feca8a9481fe13b8 \
--hash=sha256:06ea46717553cdd10f2682126cf7a66e91c8ed17b6969f4a95e94b4e01d06188 \
--hash=sha256:09d3939b70df0c8ad2da145ebd50978bccaee1d565e838b0e7921a34d38571eb \
--hash=sha256:0a57b99f2e28922b5a2434317580fd23fdf118caff4c5b752f5452836426205a \
--hash=sha256:0c22a9c6b2349204f56123dd0ca7779e989d68e336d0dc02ad823485d44925de \
--hash=sha256:0dcce83837328e6795225ead920d3aa8d867cc9d6922aa558b0e9111599fdbb9 \
--hash=sha256:0e51546a3bedadd80dfa5c2efaed840ac51b8632d8db7f9f502175f5349382a9 \
--hash=sha256:156221ad7638b5abccefd6f798916bf3f8ffd6ac51480eb4ba5b05df914ccbf3 \
--hash=sha256:16550e24ac22c27e0a728100d8de196b5f054bab6748ef9f0b168fb8b3c32e35 \
--hash=sha256:18d3710becc612ec6f0229425bd6495133dfcbf30f7b6569585acc8ed2f1b452 \
--hash=sha256:1962f3bfde085af18878f1bb1aafb300c9a6ac33da886d0b0d97e33c9ce7a222 \
--hash=sha256:203e42eb77e06f85778a908b34c5ad032f34e98a68ef33920d6685c1e65a9420 \
--hash=sha256:2103982762460a764a7ef0021443bb471f46d45ecc6858276e4fe699ebac6b94 \
--hash=sha256:25eb661d8ba7e2b85ebb4e7a1bb9f6a3280910ed10b84330a7abfb5ed32d2764 \
--hash=sha256:29b615c2d5dd883f89c107a782681b73a7aa8b2bd894130310e45eb09b143913 \
--hash=sha256:2a9cb5bbfc33b4ebd3c8d3714d6e09805437f60a14977774e4bd11b5ace46c23 \
--hash=sha256:2b23dacf7a8a88afe92f77bcdbf4cf043a84692bac2f2da02f4011c687e19b48 \
--hash=sha256:2fd562372d4afaf18d1c7f1c68e39bd32818bb16d5f57f778a4a4ed88eedcaae \
--hash=sha256:32110d954d9d0e51f36edb0396673bf4d35193a0a80ba7013bf7f7d58a33ca07 \
--hash=sha256:332b88022d0acd47c44158bcd43f47f14eaddcd979247f242b1a33291c45cdd1 \
--hash=sha256:361f9a21a33191d5287e7a75f508fc3b9bf47aaffb0241198d6b7be3384f294e \
--hash=sha256:37ed7782972545e67d97ef9a172e9499d25459b1e32cb99d1c2a30c572f2441b \
--hash=sha256:3acc45494c08a4d27375a2c28474537f68910219f42624a08011221b04623d04 \
--hash=sha256:3b76837cd051d8875913f3934b27205f7a592f78b8a4f4a1f3abc36a2420c5bc \
--hash=sha256:3b78b39377630a70aa2198e5f03be416e690364a046b1d8af80a9263733083d0 \
--hash=sha256:3d27153a0413696767b98b5d96173a2a7e27cbfca02000a6069cea7b977765a7 \
--hash=sha256:3d512e3a6c528c42ce220ed9c3caff83c6fdcd98a1b98249f08ccfc66ad111b1 \
--hash=sha256:4073ab7cefe5a2e7dc368c1f01eb27716dc8ea8f1c69e9b7725ebce05aa53cf7 \
--hash=sha256:42d7a6e818214336cf7af9a3aae5c6923f94f09fa07ac5aab98268ba2a98a6d5 \
--hash=sha256:4441d655a53185ef1b01b1d42ad9b3a96b905110a9219043e3fdaec855ba3b6e \
--hash=sha256:47beedf07a706140b50786457e082497ee6b5970c41e49bcd1572ee3f4c73f80 \
--hash=sha256:48c83103f82fce36191a9e3a8a80731d4340e2da544eae8c5aaaf6a45280e7d0 \
--hash=sha256:4b79ea31cf277c72d2307c6cb8bd32a2c151959e80a2f24fa85df620c5f2860c \
--hash=sha256:4c792e6cce24d08f92199d907785c9e64f74c357deeed3dbaf7d699ed5930b64 \
--hash=sha256:4d2636a5b61c69e32db0e74b57073dd4a66f1ad195e9398c5f01bba41090deea \
--hash=sha256:4fb2db1f649b6464711846b5bb9c1611bd906ce939d9460cbd1fa419552cd6c3 \
--hash=sha256:506623128d7a55b726a5a46e4c9a8eae4c9dd0f04ff60b041fe7df85b9d034fe \
--hash=sha256:51adfc30f467077293a6695d8149bcef501c0728386f3a491054f835dadb60b2 \
--hash=sha256:52c31d123f5adf14dec694c2a4036bf42c523df7cefc641d31cd05653de56e49 \
--hash=sha256:5830f94a7190a33e55d06d89242ea951ee2009c3a27fc31538f3ac9386b27edd \
--hash=sha256:5cec3e7fbc911ff4fcf43b24aaf1b96906381ad36030f42897def3ff4b78729e \
--hash=sha256:5da7f7f1ecf866186f195f7ecc374c915e1838496b86f2f3b41da27c798a25c3 \
--hash=sha256:5ec906bb21b35e66cfdcc2ea0133f249f52b7d89e3e45ec8d2bd2d84a0255d7d \
--hash=sha256:5f772007dfba8941873dbd276b6a6845428cc740888b5c6c37bf483b1ea34b42 \
--hash=sha256:648adde345cfd13335342e23cfe94871c7f7f55a43fb254f3b95acb071072968 \
--hash=sha256:6531540aa63e6864cb0615a3a5da70ae03191334507852a5385320bb7916df3f \
--hash=sha256:6597a1f7413189b4bc58437babcdf39b79da416e5c477ae98323a88ecc108188 \
--hash=sha256:6686d29eaafddeeab9e48af92103dc0d26161035faa4be083b8b488f1ab47219 \
--hash=sha256:679eef0123861ca381dd8fd9bdc1920e87636ac55eae6cff875c53dcb05fbcf8 \
--hash=sha256:6afc32a7a1a40b071070419537df3559d26907086556769683fa97b7b6e90fd5 \
--hash=sha256:6b061ea7ca94966af7cd7a87cb189ff15972c103244611a2b1e8408c04f1dbe6 \
--hash=sha256:6cf4c002268da5c11cae9083aec71ac943bce9d95e0f83c8bf9a95a3ce421fbb \
--hash=sha256:6e6558efbb256b532c9f06a21ba42bcac729718e365c505819f181f25e5c0eca \
--hash=sha256:6fd8cac4907fec8302726d49e6969acfffaf720bc39b1cee23f473b81f4dce01 \
--hash=sha256:70293c25d79d1f084fdd665894481547575e429d2a75e8d72caec2f6b6b07af8 \
--hash=sha256:71f76bb8e59be847330b8a8d3753f85397677e128f9f9692c215f8cf721cefc7 \
--hash=sha256:725be1aff55f1c873a79cea0f612df9dff21a9d2c2e05783665b824b8aa7c24e \
--hash=sha256:72d0a731eccf482d5661c6711abfcd5921f3dbfbbb0789061e1918ef4bc89c70 \
--hash=sha256:7390e060f830b3d132f484b21ac2783a2d227b682ef62bb8146e1c1b4ca0e45a \
--hash=sha256:73b00645316121105274fd266ed54a20e6514650126d399cdea39876ab1e7b04 \
--hash=sha256:74e46409666c358b93fce0d8c6f4cb107d8dd7cba1302a38d49adf6fa8193c7e \
--hash=sha256:75b32cf33ea40f945f226f97bc1d43151e1a5adff21f420b5e63c468b1a28114 \
--hash=sha256:769e4f7b090e10cae4c082e3e39b9458ec2444505df84953c16c0468b16539c4 \
--hash=sha256:7849a096d6fdba3f2bdf849eb89f2d233a24400c92faa3efb25fa8dc615b706c \
--hash=sha256:799c5a23126c9589cb10b6c6b54f9087246940dad20cd74bf3f06fc9ae3bbab5 \
--hash=sha256:7a7e9321822ca59ba56fa8744c3e3f01ef74d547aafe0d383d000d7a4d11eb79 \
--hash=sha256:7b23db4b469d9e051ac74d96db9bf61e27c9054de64f8263fefa32bf72867ba1 \
--hash=sha256:7b4ee34acefa9ba1333f02b817982f1e4127f6f9b975017a707c4e738d7f9fb9 \
--hash=sha256:829bcaa90be8737c132d9515d6a466e8528e3b3d050d3f3466f36ea94d3beb48 \
--hash=sha256:8588edf317fbe4f16a949bc5a6ccdd22b6e6fd5b4745d128bc40bccf31024ce5 \
--hash=sha256:868744c68e9342768888c7326604da2228c19bb6946aa46b5f9e1ac32ea8d40b \
--hash=sha256:88ba8a439b2bad97bb69c38db5bf0ec16a061ee834cf0f244089186ee803e899 \
--hash=sha256:8b45d40f07081b377f0b837ddbfba4a9ab4a89a7b569d3c095436564e767a27b \
--hash=sha256:8c00c5c49f80a588a2c4f99d519d2abed4ce26cdca11273041bc8b7e60af60de \
--hash=sha256:8c51ac7b31578a7275650f580aac985940985b6d2e57247ac6d5e07f2c936cd6 \
--hash=sha256:8d148b4b295224d3a19e7bd9f02ebe7344de254b3b2c4d0628ce42ade0bca119 \
--hash=sha256:8f32a6cb0b101170abc2d8053af1473a2a29ef2a06d7130994ee8455a50f5dbf \
--hash=sha256:8fd30d217a4275107667fe1d4f601e2d50c797d0727148cfbb384536d65f04d3 \
--hash=sha256:927d602fb8fb595a69e6b1ae998a6ec19851d0fb9391759456e6425090996647 \
--hash=sha256:94622cf24e80d03054ceb69a06a86c950e12fe993ed06b933f7895232cacbc3e \
--hash=sha256:954d43574f72be244b65f0fa61e2f814214b024f2ec849f487aa2f553f7c6e71 \
--hash=sha256:98f16db5e79f2605194c0f899d0532005bb12269e698bf96f62a5635bcf33010 \
--hash=sha256:9a4e95d56994a45ac76541853796720436ffe462957d0b1b89e87ff3d3b1627e \
--hash=sha256:9ae1429ee9e52b139167ed0169757806a27ed7307e942e8c62037a9184e9843b \
--hash=sha256:9e282f35ece8895b9fa5af406fc6a4cb42f01e1009525cf46641de584781c83b \
--hash=sha256:9ff89e36451a19775e7556d95ebfa4a0b24b84cc87565d6b5d0ec8ea82bf3f2c \
--hash=sha256:a0457561e8a87a6a3b509e21c35084d7d207ced262139de3f738e9676a476bbd \
--hash=sha256:a50bd9b44dd9b7b845802030b4d88610c01c7f95571b4cbd3a1aeec17a34c9fd \
--hash=sha256:a703f23ca15a51251fc94f1774683f5aa511588a7ad6bbb83960cdb2a4dcd978 \
--hash=sha256:a920e99155d75d1b1c08172da8aaa7200e7b30871fb628d1631d7891a333e30e \
--hash=sha256:a9b0026538719f7a532998d84640ab2e91ca1a051ce4b8d924fdcb607307e921 \
--hash=sha256:ab9e4bd60796866c578e3afa0a17c98636887827a39c2e238a61989c18fd8e7b \
--hash=sha256:accb5e9492b9bc9c9aeec5b72ea8f2ddcbefc6143d1c626fba960ecbdc89807e \
--hash=sha256:ad2e9e152bec6c4f7e4cdb4adcea6b708400090eec04bfe5ee5b30d368ffd721 \
--hash=sha256:adc30e5d064c9e33049e825408fa4e952f4e8a0cf4c329dc2ded72e1bb5bae08 \
--hash=sha256:b529ad6c81ad21db2f4e3d6e33db78ce3b9f272066b438b5d673361f9282898d \
--hash=sha256:b6c7f91520c29420639925fd1cecceac9ca07366b50c09ea24eac1cd116b4866 \
--hash=sha256:b7ea61af293a153f2d67430038cf0efc10140caa623f2bdf5a9f5a457ff20f57 \
--hash=sha256:b8451f31ae24620cc9372acd2728d87922f2bb0cae3fa57aed68b152844cdf08 \
--hash=sha256:bbb6bed49f083e2ec8ae0bb21c00c7c5171ab8e08a8b008c61a43fc6c944fdac \
--hash=sha256:bc581579885728bb54ef15000295c20e6a64a200b1b73d5cfca71879a3eb3e1f \
--hash=sha256:bcad49104711f88b2b7c3ba166de172857d837248205e541b044a552558fecc3 \
--hash=sha256:bfc86dff091104eec770c29ea1831dbe191968a70aa2d8ae8eda3240d863970a \
--hash=sha256:c00f0c45851a2c61efffd03dde8fb4d594026b5cc18196c94e15460f1225f2ed \
--hash=sha256:c0cc2cb47face4dae64bd70a9268dbebddb3e48c1b48cf6d7b6ac1471609fd88 \
--hash=sha256:c2db7b9e2d726f7e051bedb67abcf460b84b11437b2f9fdacda7e6931dace85b \
--hash=sha256:c44776f82b04e623eb9e1b81fcd17ac6e9808ae1ba5cdf8edce1f7c869a95a9b \
--hash=sha256:c564d1e6531611bf87078c28780456ecc75459dcca189629fff2fe7c020d8e67 \
--hash=sha256:c568e72f5425a74616daeb824afe28da460cbeea036432f41c6af5380b83300d \
--hash=sha256:c5e970d3996c597186c9dbb6e77a8048737a834ac03cb13186a54999e0e1c31e \
--hash=sha256:c634053459278cf31fb404ddb5ecd38124e4609e8b609166da621edc2d5796db \
--hash=sha256:c63c0d7832956d5f3bb77888b93c854569d13f806289ff75c43926d25c6e5fd2 \
--hash=sha256:c6bd2c9781915592b209160d0f017d4c7c82ad53075e6b0c24d2a89299e7f9e9 \
--hash=sha256:c74954409ea5789f7a60daa5f94580c00ad0b60b20751c47b35c4784877b5057 \
--hash=sha256:c7a56140fcbf4662cb263754a754c651a16fe2196cae1fd232d18f89acd30c83 \
--hash=sha256:c7b996c02de5e032cb63dc65482b73693b7ecaa586654126be2749ddea239c40 \
--hash=sha256:c7f66a53e9b7ec831abb15e3d9b6cee8f52d6a24cd0a374786bf46c3ec218bc6 \
--hash=sha256:c8052c3058c402d53602583da5ddcf1a15a63ab1efe0222f47c7be59944e6463 \
--hash=sha256:c9f8fdb7bbefc4907c2bb3593f810f2b67a2d5329e1d38724a1aa3d763cf63eb \
--hash=sha256:cbdf4b42f4514422051889424fd03bc269be8c5d751bf39ec29ad761590bd10d \
--hash=sha256:cc0cd4065a65ac98f3e2742ee9f314da9d224db49b07dc17d3a20cef0d79658d \
--hash=sha256:cebad8f4796248b91fc2168515e507e5cb6b663a32befd09f3b1e7920acdcb1a \
--hash=sha256:cf99debb17227a50620aee16647bb33a0387f5fa5418d628666c0f05745e0d2a \
--hash=sha256:cfbbba4597f19ad717f79fd3f2a67ae7efae647bd6a61e14554e1b5ad242a5bf \
--hash=sha256:d0acd8191c0e5a61d1c27bfa33b6ec8431982299f5d71c02129aa4f16f182ad0 \
--hash=sha256:d0b6a9bd86f865ebc9d847a1eb0a655a0e2b447cbcde743dda97c4298415cc0b \
--hash=sha256:d0f943b53bb1d7389d72a5380078670e5fcc34a1328142148b72d20fd82031c7 \
--hash=sha256:d48795c7d64ca1c42e3d61fcc6478cb15a19b6ad3f9c882bc8d8dee49d4a420f \
--hash=sha256:d8255971f6789cf0cb365e3e22b9b166eba978548a26241eaa5b7af0440d885a \
--hash=sha256:ddab54dc0ec46ed09ef9ac131252cb5740ed21fbe6fc145f3c6fed0b575a8f15 \
--hash=sha256:dde9cd67f18803949ebf96de8aba12b8ec5ee3115e34c75a2db85a3b0a6c20d5 \
--hash=sha256:de29795f23833cdfb68ba45c8a5cc0ec49778ea5deb670188f4465bba5930d25 \
--hash=sha256:e0feb03a338f8f5e819ae23a73aabb7b46fd3b73f15f7df782dd12d99e2b02ad \
--hash=sha256:e30550965c78223439815dbdf40c93eb8931dfbf12427110dcfcaeebef76feb6 \
--hash=sha256:e3e80cad85ba68c07c1e8d4ccc9cf51e63bf6a73d6bf631640be947bd72b6b63 \
--hash=sha256:e4beaef2f4796558e738e15ca0b8802e35f419a9fa374a978e41706f43c48b26 \
--hash=sha256:e6d2a185ec4ff0478089305abd833da3a9fda8803eb77325b89ebeae5585a3b7 \
--hash=sha256:ed7fe197b8bb66eef4f62c052e33752d456d2fdda74805469d4bd954950ab339 \
--hash=sha256:ee48728a07566c32e097d267f4d4d01b85123c9ae748a42da02185b908cbedc4 \
--hash=sha256:ee6c4e0085bff5f6621bf9c53452584dcb91ebd993ce841e1f4061ac12b6b556 \
--hash=sha256:ef03fb4b3685df0ed9dc6a074a090f030345cad2c23c61818da3e08e693a9caa \
--hash=sha256:f01a680d4b66fd15cc7513fae55c673cc8cc340d41340305b7f9a782abdbefed \
--hash=sha256:f0494d3d97502e270282cc6a1f8648cd7335b4fe8d5c452006e5b7f9d62b8892 \
--hash=sha256:f24bed98595b9d854da8d6debaf82754abf3e8fe63ec90505ef560566814df7e \
--hash=sha256:f42671900e0b602d05a074c52fd3d757c2f8e5c4f73f771794dae1aa4aea5f0e \
--hash=sha256:f5b1d315a615cec81a79e2ce3a94221dc5c23e7fd4012897085d3b5e5a5638d0 \
--hash=sha256:f5f06f59e19aa0770aaf651ce91c196fa620b35aed49a7e6c36e7335f3f83db7 \
--hash=sha256:fcac44d917672ad6257ad64b80b5168306f168a78cab5c0612e4c699caed18cf
-34
View File
@@ -1,34 +0,0 @@
{
"playwright": "1.61.0",
"platforms": {
"ubuntu24.04-x64": [
{
"path": "builds/firefox/1532/firefox-ubuntu-24.04.zip",
"sha256": "8f3c97b95caf84cec1e83acdbee5079156cce338fc21bf2f4bc6afe3eec616c0",
"size": 110001368
},
{
"path": "builds/ffmpeg/1011/ffmpeg-linux.zip",
"sha256": "ebc74fc5b94830176a3c2914ae96bd8bc7f6a91f4f33890230f84a172ee61ccc",
"size": 2376500
}
],
"win64": [
{
"path": "builds/firefox/1532/firefox-win64.zip",
"sha256": "c02daa45e8af1164cba27301f076a877d9419f0d40b51b9fab4fe415daf6f77f",
"size": 122449192
},
{
"path": "builds/ffmpeg/1011/ffmpeg-win64.zip",
"sha256": "8d08827c019ad36e7b9d49d3648447d884534cb2acf200e71c715f6dd834cc50",
"size": 1411741
},
{
"path": "builds/winldd/1007/winldd-win64.zip",
"sha256": "0069f0d11d4ad6df068a068c003d22fe7dbec192a47bba64b2e115e9c8ce41d8",
"size": 128684
}
]
}
}
+10 -23
View File
@@ -1,32 +1,19 @@
[
{"id": "wrapper.e2e.udp", "giro": "G2", "os": ["linux", "windows"], "min_tests": 44, "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_held_ice_port_blinds_the_loopback_checks_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", "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.", "needs_userns": true},
{"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).", "moz_log": "nsHttp:5,neqo_http3:5"},
{"id": "wrapper.e2e.udp.sandbox", "giro": "G2", "os": ["linux"], "min_tests": 13, "exact": true, "tests": ["tests/test_the_socket_process_is_sandboxed_e2e.py", "tests/test_webrtc_realness.py::test_the_gather_is_real_without_a_proxy", "tests/test_webrtc_realness.py::test_a_gateway_with_coherent_udp_gives_the_page_a_srflx_born_through_its_relay", "tests/test_ice_names_by_the_context_proxy_e2e.py::test_a_gateway_without_udp_resolves_the_ice_name_then_ends_in_701"], "marker": "e2e", "needs_root": false, "note": "The browser WITH its sandbox, run by a normal user, as on any Linux that allows user namespaces. On the Ubuntu 24.04 runner AppArmor refuses them to a user, so every other non-root suite runs a browser WITHOUT the sandbox of its socket and content processes; the gate turns the restriction off for this leg (sysctl kernel.apparmor_restrict_unprivileged_userns=0) and the first test fails unless the socket and a tab process have a seccomp filter (Seccomp: 2). The three situations of the UDP line: A (a proxy that carries UDP: the srflx born through the relay), B (no proxy: the gather is real), C (a proxy with no UDP: the ICE server name goes by DoH through the proxy and the gather ends in 701). No root and no resolver trap needed.", "linux_only": "It reads the seccomp filter of the socket and tab processes in /proc. The Windows twin reads the sandbox token of the same processes (integrity level, restrictions) and needs a measurement of the retail Firefox's tokens first; until then Linux only."},
{"id": "wrapper.e2e.web", "giro": "G2", "os": ["linux", "windows"], "min_tests": 27, "exact": true, "tests": ["tests/test_networkidle_through_a_served_browser_with_routes_e2e.py", "tests/test_http3_through_the_proxy_e2e.py"], "marker": "e2e", "needs_root": false, "note": "The networkidle e2e with routes and the HTTP/3 e2e, split from wrapper.e2e.udp (about 260 s of 500 on Linux; the whole suite did not fit the 15 minutes of Windows)."},
{"id": "wrapper.e2e.doh", "giro": "G2", "os": ["linux", "windows"], "min_tests": 19, "exact": true, "tests": ["tests/test_the_hosts_file_of_the_host_is_never_read_e2e.py", "tests/test_resolver_race_e2e.py", "tests/test_doh_under_stress_e2e.py", "tests/test_context_proxy_only_resolves_by_doh_e2e.py", "tests/test_doh_through_the_proxy_e2e.py", "tests/test_ice_names_by_the_context_proxy_e2e.py"], "marker": "e2e", "needs_root": ["linux"], "note": "Linux needs root: the resolver trap of the file (ResolverTrap) points /etc/resolv.conf at a counting resolver on port 53. Su Windows il resolver trap non gira: l'asserzione sul resolver di sistema è l'unica omessa. Run it without xdist (port 53 is one per host). On the Linux leg the gate exports INVPW_REQUIRE_TRAP=1: a trap that cannot run or bind port 53 is a failure, not a skipped assertion."},
{"id": "wrapper.e2e.context.egress", "giro": "G2", "os": ["linux", "windows"], "min_tests": 14, "exact": true, "tests": ["tests/test_nothing_leaves_but_the_proxy_e2e.py", "tests/test_a_turn_name_over_tcp_goes_through_the_proxy_of_the_context_e2e.py"], "marker": "e2e", "needs_root": ["linux"], "note": "Taken from the minimal-engine port (branch tests/minimal-port) unchanged but for the removed engine gate: 12 = 6 kinds of page work (hints, image/fetch/WebSocket/EventSource, WebRTC STUN and TURN-udp by name, geolocation, a service worker with push, a page still loading when its context closes) x 2 schemes (no proxy at launch and a gateway on the context; a launch gateway and a different one on the context), and 2 = the TURN server named over TCP in those two schemes. EXPECTED RED on the published firefox-63: the 2 TURN-by-name cases (the lookup of the TCP socket takes user context 0; fixed by commits ac0214bff4 and 058edd6cc6 of firefox-64). The 12 have not run on any engine yet. Like wrapper.e2e.doh: the Linux leg runs as root for the resolver trap (INVPW_REQUIRE_TRAP=1); on Windows the DoH log and the gateway's CONNECTs are the sink."},
{"id": "wrapper.e2e.context.sink", "giro": "G2", "os": ["linux", "windows"], "min_tests": 36, "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). THE CLOSED CONTEXT CASE (1, gated firefox-65): a beacon sent on pagehide as a proxied context closes, to a name never looked up, is resolved over the DoH through the context's gateway after the close; on firefox-64 it went to the machine's resolver every time (hunt 43733181674)."},
{"id": "wrapper.e2e.realness", "giro": "G2", "os": ["linux", "windows"], "min_tests": 31, "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": 273, "exact": true, "tests": ["tests/test_doh_session_prefs_unit.py", "tests/test_every_route_command_is_answered_may_fail.py", "tests/test_preload_newtab_is_written_only_when_asked.py", "tests/test_the_doh_e2e_launch_on_a_virtual_display.py", "tests/test_the_egress_sink_helpers.py", "tests/test_the_exit_of_a_context_is_discovered_through_its_own_gateway.py", "tests/test_the_fake_doh_answers.py", "tests/test_the_fake_doh_delays_and_refuses.py", "tests/test_the_h3_line_helpers.py", "tests/test_the_host_address_helper.py", "tests/test_the_http_proxy_helper_asks_for_credentials.py", "tests/test_the_lab_ca_and_its_ocsp_leaf.py", "tests/test_the_leak_watcher_sees_a_direct_connection.py", "tests/test_the_network_declaration_reaches_the_engine.py", "tests/test_the_realness_helpers.py", "tests/test_the_resolver_trap_counts_its_own_users.py", "tests/test_the_resolver_trap_is_required_by_the_gate.py", "tests/test_the_server_says_nothing_about_the_launch_counter.py", "tests/test_the_udp_bench_survives_what_a_loaded_machine_does_to_it.py", "tests/test_the_udp_chain_helper.py", "tests/test_the_witness_hears_a_direct_send.py", "tests/test_the_witness_picks_a_port_both_sockets_bind.py"], "marker": "unit", "needs_root": false, "note": "The leak watcher file defines exactly one of its two resolver-trap tests per host (7 everywhere), so no test is skipped. `exact`: min_tests is raised by hand when a test is added. The sink of the egress gate (tests/test_the_egress_sink_helpers.py, 20): the engine's log (the same on Linux and Windows) and the witness read on known inputs, and a blind log that must raise, never answer 'nothing'. The lab CA of its OCSP case (tests/test_the_lab_ca_and_its_ocsp_leaf.py, 17; tests/test_the_fake_doh_answers.py +1, the DoH serving a lab-CA leaf): the leaf's AIA, trusted and untrusted issuers, the responder, the xpcshell step."},
{"id": "wrapper.e2e.page", "giro": "G2", "os": ["linux", "windows"], "min_tests": 130, "exact": true, "tests": ["tests/test_a_tiny_download_on_a_served_browser_is_saved_e2e.py", "tests/test_a_page_that_moves_on_e2e.py", "tests/test_a_popup_is_reported_when_the_engine_says_it_is_ready_as_playwright_does_e2e.py", "tests/test_a_popup_of_a_link_reaches_the_client_e2e.py", "tests/test_popup_destinations_e2e.py", "tests/test_popups_reach_the_client_e2e.py", "tests/test_route_superseded_e2e.py", "tests/test_closing_one_of_four_browsers_does_not_hold_the_loop_e2e.py", "tests/test_a_drag_keeps_its_buttons_pressed_e2e.py"], "marker": "e2e", "needs_root": false, "note": "130 = 126 + the 4 of test_a_drag_keeps_its_buttons_pressed_e2e.py (a drag reaches the page with the button it holds: event.buttons is 1 on every mousemove of a left drag, 2 on a right one, 0 after the release; with and without humanize). The 126 before it: 116 + the 9 of test_closing_one_of_four_browsers_does_not_hold_the_loop_e2e.py (four browsers in one process, one closes: the loop is never seen inside a step of the close, the removal of the profile is held still and reached on a thread of the reaper while the close has returned, the other three keep answering; one control holds the loop on purpose, the other leaves it late in its selector and must not be charged). 116 = 100 + the 16 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; 2 of them the strict networkidle cases, a document still arriving that moves). 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.", "moz_log": "DocumentChannel:5,ProcessIsolation:5,nsDocShell:4,DocLoader:4", "juggler_trace": true},
{"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": 259, "exact": true, "tests": ["tests/test_doh_session_prefs_unit.py", "tests/test_every_route_command_is_answered_may_fail.py", "tests/test_preload_newtab_is_written_only_when_asked.py", "tests/test_the_doh_e2e_launch_on_a_virtual_display.py", "tests/test_the_egress_sink_helpers.py", "tests/test_the_exit_of_a_context_is_discovered_through_its_own_gateway.py", "tests/test_the_fake_doh_answers.py", "tests/test_the_fake_doh_delays_and_refuses.py", "tests/test_the_h3_line_helpers.py", "tests/test_the_host_address_helper.py", "tests/test_the_http_proxy_helper_asks_for_credentials.py", "tests/test_the_lab_ca_and_its_ocsp_leaf.py", "tests/test_the_leak_watcher_sees_a_direct_connection.py", "tests/test_the_network_declaration_reaches_the_engine.py", "tests/test_the_realness_helpers.py", "tests/test_the_resolver_trap_counts_its_own_users.py", "tests/test_the_resolver_trap_is_required_by_the_gate.py", "tests/test_the_server_says_nothing_about_the_launch_counter.py", "tests/test_the_udp_bench_survives_what_a_loaded_machine_does_to_it.py", "tests/test_the_udp_chain_helper.py", "tests/test_the_witness_hears_a_direct_send.py", "tests/test_the_witness_picks_a_port_both_sockets_bind.py"], "marker": "unit", "needs_root": false, "note": "92 = 6+32+21+7+8+3+9+6. The leak watcher file defines exactly one of its two resolver-trap tests per host (7 everywhere), so no test is skipped. `exact`: min_tests is raised by hand when a test is added. The sink of the egress gate (tests/test_the_egress_sink_helpers.py, 20): the engine's log (the same on Linux and Windows) and the witness read on known inputs, and a blind log that must raise, never answer 'nothing'. The lab CA of its OCSP case (tests/test_the_lab_ca_and_its_ocsp_leaf.py, 17; tests/test_the_fake_doh_answers.py +1, the DoH serving a lab-CA leaf): the leaf's AIA, trusted and untrusted issuers, the responder, the xpcshell step."},
{"id": "wrapper.e2e.page", "giro": "G2", "os": ["linux", "windows"], "min_tests": 130, "exact": true, "tests": ["tests/test_a_tiny_download_on_a_served_browser_is_saved_e2e.py", "tests/test_a_page_that_moves_on_e2e.py", "tests/test_a_popup_is_reported_when_the_engine_says_it_is_ready_as_playwright_does_e2e.py", "tests/test_a_popup_of_a_link_reaches_the_client_e2e.py", "tests/test_popup_destinations_e2e.py", "tests/test_popups_reach_the_client_e2e.py", "tests/test_route_superseded_e2e.py", "tests/test_closing_one_of_four_browsers_does_not_hold_the_loop_e2e.py", "tests/test_a_drag_keeps_its_buttons_pressed_e2e.py"], "marker": "e2e", "needs_root": false, "note": "130 = 126 + the 4 of test_a_drag_keeps_its_buttons_pressed_e2e.py (a drag reaches the page with the button it holds: event.buttons is 1 on every mousemove of a left drag, 2 on a right one, 0 after the release; with and without humanize). The 126 before it: 116 + the 9 of test_closing_one_of_four_browsers_does_not_hold_the_loop_e2e.py (four browsers in one process, one closes: the loop is never seen inside a step of the close, the removal of the profile is held still and reached on a thread of the reaper while the close has returned, the other three keep answering; one control holds the loop on purpose, the other leaves it late in its selector and must not be charged). 116 = 100 + the 16 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; 2 of them the strict networkidle cases, a document still arriving that moves). 100 counted at the collection; was 96 = 10+32+16+34+4 before the popup tests of 6200bc2). A page is handed over when the engine says Page.ready; a popup reaches the client (link, noopener, window.open; own site and another; with and without a route; in-process and over launch_server) as Playwright's does; a superseded route. Needs the candidate binary, and the stock Playwright client of the dev extra."},
{"id": "wrapper.unit.page", "giro": "G1", "os": ["linux", "windows"], "min_tests": 72, "exact": true, "tests": ["tests/test_a_download_finished_before_it_was_announced_is_finished.py", "tests/test_every_order_of_the_events_of_a_popup_gives_one_page_event.py", "tests/test_ci_drive_gate_goes_through_the_core.py", "tests/test_a_page_is_handed_over_only_when_the_engine_says_it_is_ready.py", "tests/test_a_new_page_waits_for_the_engine.py", "tests/test_page_number_follows_the_call.py", "tests/test_a_commit_at_any_point_of_the_hand_over_reaches_the_client_once.py", "tests/test_no_event_of_any_family_is_lost_by_the_hand_over.py", "tests/test_the_hand_over_of_a_popup_holds_under_concurrency.py", "tests/test_a_page_closed_before_its_announcement_is_not_announced.py", "tests/test_a_live_event_does_not_overtake_the_replay_of_a_new_page.py"], "marker": "unit", "needs_root": false, "note": "72 = 44 + 3+9+5+1+10 of the popup hand-over (24 counted at the collection before; was 20 = 3+8+1+8 before 6200bc2). The page dispatcher's wait for Page.ready and what it hands over; the drive gate goes through the core (the engine waits for the session's road)."},
{"id": "wrapper.e2e.compositing", "giro": "G2", "os": ["linux", "windows"], "min_tests": 9, "exact": true, "tests": ["tests/test_software_compositing_is_declared_e2e.py", "tests/test_a_screenshot_draws_the_text_of_the_bundled_fonts_as_the_content_does_e2e.py"], "marker": "e2e", "needs_root": false, "note": "The engine DECLARES software compositing on every machine (core: the compositing entries of zoom.stealth.gfx.feature_status carry the VM decision, and on Windows gfx.webrender.software=true, gfx.webrender.software.d3d11=false). 3 = (1) the compositor read from a privileged context is 'WebRender (Software)' on Windows and on Linux (windowUtils.layerManagerType of each window: Troubleshoot.snapshot().graphics throws on this engine, `ext is null`, so it is not the route); (2) the GPU process uses under 1.5 s of CPU on the fixed 10-scene loop of one browser (Windows runner: 0.32 s declared, 2.7-4.2 s not, runs 43652292533 and 43642744101; on Linux it is held to the bound if a GPU process exists); (3) the 86 keys of the page-bytes probe plus the canvas 2D scenes (drawImage scaled with smoothing off/low/medium/high, text with linear/radial/conic gradients) equal tests/data/page_bytes_<os>.json, PNGs on decoded pixels. EXPECTED RED on the core 64.71.0 (tests 1 and 2 on Windows). The reference of Windows holds the 75 stable keys and 6 of the 11 PNG keys of run 43652292533; the five other PNG keys and the new canvas keys, and all of Linux, are written from the first run on the engine of the reference (the failure of test 3 prints RECORD-BEGIN ... RECORD-END with the entries to merge): a reference that is not complete is red, never skipped. 9 = those 3 + the 6 families of tests/test_a_screenshot_draws_the_text_of_the_bundled_fonts_as_the_content_does_e2e.py (from firefox-66, engine_at_least): a screenshot draws the text of Arial, Times New Roman, Consolas and Segoe UI, with accents, the typographic apostrophe, the euro sign, Chinese, Arabic and Russian, and of MS PGothic (face 2 of msgothic5_32.ttc: Japanese and Latin) and NSimSun (face 1 of simsun.ttc: Chinese), two faces that are not the first of their collection, with the same bytes as the content process drew them in a canvas (an SVG image with a foreignObject of the same markup), cut from the same page.screenshot, on both systems and with no threshold. EXPECTED RED on every engine that rebuilds the text in the parent with another font than the bundle (Linux: fontconfig answers DejaVu Sans), and skipped, hence red here, on an engine older than firefox-66. It saves the screenshot, the two boxes and a result.json under RUNNER_TEMP/invpw-evidence.", "runner_image": {"windows": "windows-2022"}},
{"id": "wrapper.e2e.fakeweb", "giro": "G2", "os": ["linux", "windows"], "min_tests": 7, "exact": true, "tests": ["tests/test_fakeweb_p2_e2e.py", "tests/test_fakeweb_p4_e2e.py"], "marker": "e2e", "needs_root": false, "note": "The fake web, offline: our browser on the hard pages (profile P2: a reused routed page reaches networkidle every time, also under a load of three other browsers; the other site is another process) and on the 17-step journey of a person (profile P4: every step as stock, and every page left only once its noise is done), each judged against what stock Firefox does, as tests/fakeweb/pages.json declares it. 7 = 3 + 4 (the last two: a `load` that takes 20 s is a step that succeeds, and a `load` that never comes ends in an error that names the wait and the page). Stock itself is held to that declaration, and compared with ours step by step, by scripts/run_fakeweb.py in .github/workflows/fakeweb.yml. Needs the candidate binary (STEALTHFOX_E2E_BINARY).", "stock_firefox": true, "extra_steps": ["fakeweb_profiles"]},
{"id": "wrapper.e2e.compositing", "giro": "G2", "os": ["linux", "windows"], "min_tests": 9, "exact": true, "tests": ["tests/test_software_compositing_is_declared_e2e.py", "tests/test_a_screenshot_draws_the_text_of_the_bundled_fonts_as_the_content_does_e2e.py"], "marker": "e2e", "needs_root": false, "note": "The engine DECLARES software compositing on every machine (core: the compositing entries of zoom.stealth.gfx.feature_status carry the VM decision, and on Windows gfx.webrender.software=true, gfx.webrender.software.d3d11=false). 3 = (1) the compositor read from a privileged context is 'WebRender (Software)' on Windows and on Linux (windowUtils.layerManagerType of each window: Troubleshoot.snapshot().graphics throws on this engine, `ext is null`, so it is not the route); (2) the GPU process uses under 1.5 s of CPU on the fixed 10-scene loop of one browser (Windows runner: 0.32 s declared, 2.7-4.2 s not, runs 43652292533 and 43642744101; on Linux it is held to the bound if a GPU process exists); (3) the 86 keys of the page-bytes probe plus the canvas 2D scenes (drawImage scaled with smoothing off/low/medium/high, text with linear/radial/conic gradients) equal tests/data/page_bytes_<os>.json, PNGs on decoded pixels. EXPECTED RED on the core 64.71.0 (tests 1 and 2 on Windows). The reference of Windows holds the 75 stable keys and 6 of the 11 PNG keys of run 43652292533; the five other PNG keys and the new canvas keys, and all of Linux, are written from the first run on the engine of the reference (the failure of test 3 prints RECORD-BEGIN ... RECORD-END with the entries to merge): a reference that is not complete is red, never skipped. 9 = those 3 + the 6 families of tests/test_a_screenshot_draws_the_text_of_the_bundled_fonts_as_the_content_does_e2e.py (from firefox-66, engine_at_least): a screenshot draws the text of Arial, Times New Roman, Consolas and Segoe UI, with accents, the typographic apostrophe, the euro sign, Chinese, Arabic and Russian, and of MS PGothic (face 2 of msgothic5_32.ttc: Japanese and Latin) and NSimSun (face 1 of simsun.ttc: Chinese), two faces that are not the first of their collection, with the same bytes as the content process drew them in a canvas (an SVG image with a foreignObject of the same markup), cut from the same page.screenshot, on both systems and with no threshold. EXPECTED RED on every engine that rebuilds the text in the parent with another font than the bundle (Linux: fontconfig answers DejaVu Sans), and skipped, hence red here, on an engine older than firefox-66. It saves the screenshot, the two boxes and a result.json under RUNNER_TEMP/invpw-evidence."},
{"id": "wrapper.e2e.fakeweb", "giro": "G2", "os": ["linux", "windows"], "min_tests": 4, "exact": true, "tests": ["tests/test_fakeweb_p2_e2e.py", "tests/test_fakeweb_p4_e2e.py"], "marker": "e2e", "needs_root": false, "note": "The fake web, offline: our browser on the hard pages (profile P2: a reused routed page reaches networkidle every time, also under a load of three other browsers; the other site is another process) and on the 17-step journey of a person (profile P4), each judged against what stock Firefox does, as tests/fakeweb/pages.json declares it. 4 = 3 + 1. Stock itself is held to that declaration, and compared with ours step by step, by scripts/run_fakeweb.py in .github/workflows/fakeweb.yml. Needs the candidate binary (STEALTHFOX_E2E_BINARY)."},
{"id": "wrapper.e2e.fontconfig", "giro": "G2", "os": ["linux"], "min_tests": 2, "exact": true, "tests": ["tests/test_the_parent_reads_the_bundle_from_fontconfig_s_cache_linux_e2e.py"], "marker": "e2e", "needs_root": false, "linux_only": "Fontconfig exists only on Linux: the parent of the engine shows <GRE>/fonts to it (FcConfigAppFontAddDir) to rebuild a font from a path and a face index. On Windows DirectWrite opens the file from its path, with no folder to scan and no cache to read, so this test has no Windows counterpart.", "note": "2 = (1) the stand-in that runs the engine under strace stays in the engine's place, as the core launches it (the leader of a process group of its own): a fake engine with a child, no browser; the process the launcher holds lives as long as the fake engine, and the group killed holds strace and the child (the stand-in that exec'd setsid forked and exited 0 at once: candidate 44161687675); (2) the warm launch of the parent reads the bundle from fontconfig's cache and does not scan it again (from firefox-66, engine_at_least). Two launches under strace with the same XDG_CACHE_HOME of the test, the first cold and the second warm: the cold parent opens every font file of <GRE>/fonts (the folder as the disk lists it) before any page and fontconfig writes its cache; the warm parent does not open every one of them, and it opens a *.cache-* file of fontconfig (a few files are opened to be used, so the verdict asks about the whole folder, as a scan does). Scan and drawing are told apart by position: only what the parent opens before the first page counts (the opens that draw are written as after_startup). Evidence in RUNNER_TEMP/invpw-evidence/fontconfig-cache: the interval and the number of opens of the bundle, the names of the files of the bundle each launch opened before the first page, the size of the cache file, the VmRSS of the parent after about:blank and after a page with every family, and a third launch with gfx.bundled-fonts.activate=0 (the behaviour before), which is evidence only. Needs strace on the runner: without it both are red, not skipped. No threshold."},
{"id": "wrapper.unit.compositing", "giro": "G1", "os": ["linux", "windows"], "min_tests": 30, "exact": true, "tests": ["tests/test_the_page_bytes_reference_compares_decoded_pixels.py"], "marker": "unit", "needs_root": false, "note": "The helpers of wrapper.e2e.compositing on known inputs, no browser: the PNG compared on decoded pixels (another deBG chunk and compression are the same, one pixel is not, every scanline filter), the comparison with a reference (changed, missing and extra keys named, the entry to record), the type of an engine process, an engine process known by its executable and not by the name it gives itself (Linux), and the CPU of a window, and the shape of the committed Windows reference, and the box cut out of a screenshot (its pixels, a box outside the picture refused, written as a PNG and read back, two boxes told apart by a pixel that is named, the pixels that are not grey)."},
{"id": "wrapper.unit.all.linux", "giro": "G1", "os": ["linux"], "min_tests": 4116, "exact": true, "tests": ["tests/test_a_162_message_is_read_like_a_161_one.py", "tests/test_a_click_makes_one_mousemove_at_its_point.py", "tests/test_a_closed_context_leaves_nothing_in_the_registry.py", "tests/test_a_closed_page_says_nothing.py", "tests/test_a_closed_pipe_is_a_closed_target.py", "tests/test_a_commit_at_any_point_of_the_hand_over_reaches_the_client_once.py", "tests/test_a_context_proxy_carries_its_measured_udp_exit.py", "tests/test_a_context_route_disables_the_cache.py", "tests/test_a_detached_frame_answers_detached.py", "tests/test_a_dialog_is_a_protocol_object.py", "tests/test_a_dialog_is_answered_after_a_pause.py", "tests/test_a_download_finished_before_it_was_announced_is_finished.py", "tests/test_a_failed_expect_carries_its_call_log.py", "tests/test_a_failed_generation_of_the_security_state_keeps_its_evidence.py", "tests/test_a_failed_launch_stops_the_display.py", "tests/test_a_field_is_typed_after_a_pause.py", "tests/test_a_file_chooser_is_never_dropped_in_silence.py", "tests/test_a_frame_tap_needs_a_context_with_touch.py", "tests/test_a_gil_free_thread_dump_kills_a_busy_process_and_the_stack_watchdog_does_not.py", "tests/test_a_handle_action_walks_like_a_selector_action.py", "tests/test_a_launch_asks_nobody_on_the_internet_where_it_leaves_from.py", "tests/test_a_launch_gives_the_core_its_engine_for_the_security_state.py", "tests/test_a_launch_has_one_deadline.py", "tests/test_a_launch_without_a_session_gets_one.py", "tests/test_a_live_event_does_not_overtake_the_replay_of_a_new_page.py", "tests/test_a_module_that_leaves_a_browser_open_fails.py", "tests/test_a_new_page_waits_for_the_engine.py", "tests/test_a_non_finite_number_crosses_the_wire_as_a_tag.py", "tests/test_a_page_closed_before_its_announcement_is_not_announced.py", "tests/test_a_page_is_handed_over_only_when_the_engine_says_it_is_ready.py", "tests/test_a_path_leaves_as_one_stroke.py", "tests/test_a_port_number_is_held_until_it_is_used.py", "tests/test_a_read_whose_probe_ran_out_is_the_callers_timeout.py", "tests/test_a_request_and_a_response_are_light.py", "tests/test_a_request_says_what_it_is.py", "tests/test_a_screenshot_refuses_what_would_touch_the_page.py", "tests/test_a_screenshot_sends_its_scale_to_the_engine.py", "tests/test_a_session_ends_before_the_next_test_starts.py", "tests/test_a_streamed_upload_is_staged_in_the_session.py", "tests/test_a_stroke_is_judged_by_its_shape_not_its_length.py", "tests/test_a_test_that_is_not_e2e_never_leaves_the_machine.py", "tests/test_a_unit_test_does_not_read_the_seal_of_the_job.py", "tests/test_ab_host.py", "tests/test_ab_host_aa_stable.py", "tests/test_ab_network.py", "tests/test_ab_network_turn_credential.py", "tests/test_ab_network_turn_deallocation.py", "tests/test_ab_network_webrtc_evidence.py", "tests/test_ab_oracle.py", "tests/test_actions_without_a_point.py", "tests/test_add_script_tag.py", "tests/test_an_element_handle_serves_every_method_of_the_client.py", "tests/test_an_expect_reads_its_value_once.py", "tests/test_async_api.py", "tests/test_browser_output_is_drained.py", "tests/test_ci_downloads_are_authenticated.py", "tests/test_ci_drive_gate_goes_through_the_core.py", "tests/test_ci_host_gate.py", "tests/test_ci_host_gate_ab.py", "tests/test_ci_lab_geoip.py", "tests/test_ci_lab_geoip_verify.py", "tests/test_ci_lab_intermediates.py", "tests/test_ci_lab_security_state.py", "tests/test_ci_linux_legs_read_no_mirror.py", "tests/test_ci_poison_host.py", "tests/test_ci_real_geoip_check.py", "tests/test_ci_real_geoip_exit_code.py", "tests/test_ci_runs_once_per_commit.py", "tests/test_ci_suite_run.py", "tests/test_ci_verdict.py", "tests/test_ci_windows_temp_is_on_d.py", "tests/test_ci_workflows_build_the_geoip_database.py", "tests/test_ci_workflows_set_the_intermediates_list.py", "tests/test_ci_workflows_set_the_security_state.py", "tests/test_cli.py", "tests/test_click_rhythm.py", "tests/test_connect_does_not_start_threads_on_the_loop.py", "tests/test_context_locale_is_a_list.py", "tests/test_core_pin.py", "tests/test_cpu_by_type_window.py", "tests/test_cross_origin_iframe.py", "tests/test_cursor_dispatch.py", "tests/test_cursor_wiring.py", "tests/test_docs_name_the_mcp_repo_as_it_is.py", "tests/test_doh_session_prefs_unit.py", "tests/test_drag_motion.py", "tests/test_e2e_hermetic.py", "tests/test_element_handle_actions.py", "tests/test_every_action_is_pinned_by_commit_sha.py", "tests/test_every_argument_reaches_the_page_as_playwright_sends_it.py", "tests/test_every_held_request_of_the_journey_starts_after_the_load.py", "tests/test_every_order_of_the_events_of_a_popup_gives_one_page_event.py", "tests/test_every_page_draws_its_own_acts.py", "tests/test_every_refusal_is_declared.py", "tests/test_every_route_command_is_answered_may_fail.py", "tests/test_every_suite_runs_on_linux_and_windows.py", "tests/test_every_windows_job_keeps_a_dump_of_a_crashing_python.py", "tests/test_every_wire_method_isLine truncated
{"id": "wrapper.unit.all.windows", "giro": "G1", "os": ["windows"], "min_tests": 4128, "exact": true, "tests": ["tests/test_a_162_message_is_read_like_a_161_one.py", "tests/test_a_click_makes_one_mousemove_at_its_point.py", "tests/test_a_closed_context_leaves_nothing_in_the_registry.py", "tests/test_a_closed_page_says_nothing.py", "tests/test_a_closed_pipe_is_a_closed_target.py", "tests/test_a_commit_at_any_point_of_the_hand_over_reaches_the_client_once.py", "tests/test_a_context_proxy_carries_its_measured_udp_exit.py", "tests/test_a_context_route_disables_the_cache.py", "tests/test_a_detached_frame_answers_detached.py", "tests/test_a_dialog_is_a_protocol_object.py", "tests/test_a_dialog_is_answered_after_a_pause.py", "tests/test_a_download_finished_before_it_was_announced_is_finished.py", "tests/test_a_failed_expect_carries_its_call_log.py", "tests/test_a_failed_generation_of_the_security_state_keeps_its_evidence.py", "tests/test_a_failed_launch_stops_the_display.py", "tests/test_a_field_is_typed_after_a_pause.py", "tests/test_a_file_chooser_is_never_dropped_in_silence.py", "tests/test_a_frame_tap_needs_a_context_with_touch.py", "tests/test_a_gil_free_thread_dump_kills_a_busy_process_and_the_stack_watchdog_does_not.py", "tests/test_a_handle_action_walks_like_a_selector_action.py", "tests/test_a_launch_asks_nobody_on_the_internet_where_it_leaves_from.py", "tests/test_a_launch_gives_the_core_its_engine_for_the_security_state.py", "tests/test_a_launch_has_one_deadline.py", "tests/test_a_launch_without_a_session_gets_one.py", "tests/test_a_live_event_does_not_overtake_the_replay_of_a_new_page.py", "tests/test_a_module_that_leaves_a_browser_open_fails.py", "tests/test_a_new_page_waits_for_the_engine.py", "tests/test_a_non_finite_number_crosses_the_wire_as_a_tag.py", "tests/test_a_page_closed_before_its_announcement_is_not_announced.py", "tests/test_a_page_is_handed_over_only_when_the_engine_says_it_is_ready.py", "tests/test_a_path_leaves_as_one_stroke.py", "tests/test_a_port_number_is_held_until_it_is_used.py", "tests/test_a_read_whose_probe_ran_out_is_the_callers_timeout.py", "tests/test_a_request_and_a_response_are_light.py", "tests/test_a_request_says_what_it_is.py", "tests/test_a_screenshot_refuses_what_would_touch_the_page.py", "tests/test_a_screenshot_sends_its_scale_to_the_engine.py", "tests/test_a_session_ends_before_the_next_test_starts.py", "tests/test_a_streamed_upload_is_staged_in_the_session.py", "tests/test_a_stroke_is_judged_by_its_shape_not_its_length.py", "tests/test_a_test_that_is_not_e2e_never_leaves_the_machine.py", "tests/test_a_unit_test_does_not_read_the_seal_of_the_job.py", "tests/test_ab_host.py", "tests/test_ab_host_aa_stable.py", "tests/test_ab_network.py", "tests/test_ab_network_turn_credential.py", "tests/test_ab_network_turn_deallocation.py", "tests/test_ab_network_webrtc_evidence.py", "tests/test_ab_oracle.py", "tests/test_actions_without_a_point.py", "tests/test_add_script_tag.py", "tests/test_an_element_handle_serves_every_method_of_the_client.py", "tests/test_an_expect_reads_its_value_once.py", "tests/test_async_api.py", "tests/test_browser_output_is_drained.py", "tests/test_ci_downloads_are_authenticated.py", "tests/test_ci_drive_gate_goes_through_the_core.py", "tests/test_ci_host_gate.py", "tests/test_ci_host_gate_ab.py", "tests/test_ci_lab_geoip.py", "tests/test_ci_lab_geoip_verify.py", "tests/test_ci_lab_intermediates.py", "tests/test_ci_lab_security_state.py", "tests/test_ci_linux_legs_read_no_mirror.py", "tests/test_ci_poison_host.py", "tests/test_ci_real_geoip_check.py", "tests/test_ci_real_geoip_exit_code.py", "tests/test_ci_runs_once_per_commit.py", "tests/test_ci_suite_run.py", "tests/test_ci_verdict.py", "tests/test_ci_windows_temp_is_on_d.py", "tests/test_ci_workflows_build_the_geoip_database.py", "tests/test_ci_workflows_set_the_intermediates_list.py", "tests/test_ci_workflows_set_the_security_state.py", "tests/test_cli.py", "tests/test_click_rhythm.py", "tests/test_connect_does_not_start_threads_on_the_loop.py", "tests/test_context_locale_is_a_list.py", "tests/test_core_pin.py", "tests/test_cpu_by_type_window.py", "tests/test_cross_origin_iframe.py", "tests/test_cursor_dispatch.py", "tests/test_cursor_wiring.py", "tests/test_docs_name_the_mcp_repo_as_it_is.py", "tests/test_doh_session_prefs_unit.py", "tests/test_drag_motion.py", "tests/test_e2e_hermetic.py", "tests/test_element_handle_actions.py", "tests/test_every_action_is_pinned_by_commit_sha.py", "tests/test_every_argument_reaches_the_page_as_playwright_sends_it.py", "tests/test_every_held_request_of_the_journey_starts_after_the_load.py", "tests/test_every_order_of_the_events_of_a_popup_gives_one_page_event.py", "tests/test_every_page_draws_its_own_acts.py", "tests/test_every_pytest_process_clears_the_gp_fault_error_box_on_windows.py", "tests/test_every_refusal_is_declared.py", "tests/test_every_route_command_is_answered_may_fail.py", "tests/test_every_suite_runs_on_linux_and_windows.py", "tests/test_every_Line truncated
{"id": "wrapper.e2e.securitystate", "giro": "G2", "os": ["linux", "windows"], "min_tests": 4, "exact": true, "tests": ["tests/test_security_state_engine_e2e.py"], "marker": "e2e", "needs_root": false, "note": "The security state the core declares, against the engine: the engine launched directly in its generate mode makes what it is given (the contract's result, security_state/ with the bytes of the full filter and of the delta, the core's own validation of it); a normal launch declares no pref of the mode and re-imports nothing; a certificate that Mozilla's CRLite test data say is revoked in a delta is refused at the first navigation (SEC_ERROR_REVOKED_CERTIFICATE) while a valid one loads, and the revoked one loads when the ready directory has no data; a ready directory with no or an empty security_state/ starts. Certificates made on the run (a fresh root trusted in cert9.db by the engine's own xpcshell, Mozilla's default test key as the key of CN=int), servers on loopback, no network. Red on firefox-67 (no generate mode).", "core_dumps": "invpw-cores"},
{"id": "wrapper.e2e.suite.linux.1", "giro": "G2", "os": ["linux"], "min_tests": 447, "exact": true, "tests": ["tests/test_a_closed_browser_leaves_the_others_alone_e2e.py", "tests/test_a_context_that_ends_leaves_no_process_e2e.py", "tests/test_a_cors_preflight_is_not_a_request_of_the_page_e2e.py", "tests/test_a_declared_webgl_extension_survives_its_use_e2e.py", "tests/test_a_granted_permission_is_the_one_the_page_asks_for_e2e.py", "tests/test_a_held_ice_port_blinds_the_loopback_checks_e2e.py", "tests/test_a_launch_without_a_session_gets_one_e2e.py", "tests/test_a_left_documents_body_is_evicted_e2e.py", "tests/test_a_mouse_click_makes_one_mousemove_on_its_point_e2e.py", "tests/test_a_page_over_ipv6_gathers_on_a_machine_declared_without_it_e2e.py", "tests/test_a_popup_is_reported_when_the_engine_says_it_is_ready_as_playwright_does_e2e.py", "tests/test_a_screenshot_draws_the_text_of_the_bundled_fonts_as_the_content_does_e2e.py", "tests/test_a_screenshot_honours_its_scale_e2e.py", "tests/test_a_screenshot_refuses_what_would_touch_the_page_e2e.py", "tests/test_a_served_browser_answers_a_plain_client_e2e.py", "tests/test_a_tiny_download_on_a_served_browser_is_saved_e2e.py", "tests/test_a_turn_name_over_tcp_goes_through_the_proxy_of_the_context_e2e.py", "tests/test_accept_language_on_the_wire_e2e.py", "tests/test_browser_output_is_drained.py", "tests/test_click_rhythm.py", "tests/test_closing_one_of_four_browsers_does_not_hold_the_loop_e2e.py", "tests/test_control_a_selects_all_in_a_field_e2e.py", "tests/test_cross_origin_iframe.py", "tests/test_declared_host_network_e2e.py", "tests/test_detectors_e2e.py", "tests/test_e2e.py", "tests/test_element_handle_actions.py", "tests/test_element_screenshot_e2e.py", "tests/test_every_page_draws_its_own_acts.py", "tests/test_file_chooser.py", "tests/test_fingerprint_surface.py", "tests/test_fission_frames_history_and_processes_e2e.py", "tests/test_fission_frames_workers_storage_and_special_frames_e2e.py", "tests/test_frames_outlive_the_back_forward_cache_e2e.py", "tests/test_goto_networkidle_after_spa_e2e.py", "tests/test_goto_script_redirect_e2e.py", "tests/test_hidden_display_linux.py", "tests/test_ice_names_by_the_context_proxy_e2e.py::test_the_ice_name_of_a_context_goes_by_the_proxy_of_that_context", "tests/test_ignore_https_errors_e2e.py", "tests/test_injected_node_surface.py", "tests/test_juggler_connection.py", "tests/test_juggler_posix_pipe.py", "tests/test_juggler_transport.py", "tests/test_navigation_across_processes_e2e.py", "tests/test_navigation_response.py", "tests/test_networkidle_reaches_the_client_e2e.py", "tests/test_oop_frame_element.py", "tests/test_oop_frame_geometry.py", "tests/test_page_number_follows_the_call.py", "tests/test_persistent_profile_keeps_state.py", "tests/test_pointer_position.py", "tests/test_popups_reach_the_client_e2e.py", "tests/test_preload_newtab_turns_the_privileged_about_process_off_e2e.py", "tests/test_realness_behind_a_declared_exit_e2e.py", "tests/test_resolver_race_e2e.py", "tests/test_route_header_order_e2e.py", "tests/test_same_document_goto_e2e.py", "tests/test_screencast.py", "tests/test_screencast_stop_e2e.py", "tests/test_screenshot_looks_where_you_are.py", "tests/test_security_state_engine_e2e.py", "tests/test_service_worker.py", "tests/test_service_worker_controller_e2e.py", "tests/test_set_offline_e2e.py", "tests/test_shadow_trusted_input.py", "tests/test_strict_and_force.py", "tests/test_the_callers_code_is_not_counted_e2e.py", "tests/test_the_device_enumeration_takes_the_declared_time_e2e.py", "tests/test_the_engine_is_born_in_the_job_e2e.py::test_a_launch_scans_no_process_of_the_machine", "tests/test_the_engine_is_born_in_the_job_e2e.py::test_after_close_no_process_of_the_session_is_left", "tests/test_the_hosts_file_of_the_host_is_never_read_e2e.py", "tests/test_trial_does_not_act.py", "tests/test_turn_over_tcp_is_tried_for_real_e2e.py", "tests/test_ua_widget_not_selectable.py", "tests/test_voices_e2e.py", "tests/test_wait_for_function.py", "tests/test_webgl_draws_on_the_engine_s_own_gl_e2e.py", "tests/test_webgl_noise_active.py", "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_a_gather_after_the_page_loaded_through_the_gateway_costs_only_the_road_to_the_server", "tests/test_webrtc_realness.py::test_a_host_with_ipv6_addresses_gathers_through_an_ipv4_relay", "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_relay_never_answers_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_not_blocked_behind_tcp_only_socks", "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_the_turn_over_tcp_of_a_context_goes_throuLine truncated
{"id": "wrapper.e2e.suite.linux.2", "giro": "G2", "os": ["linux"], "min_tests": 414, "exact": true, "tests": ["tests/test_a_click_waits_for_the_navigation_it_plans_e2e.py", "tests/test_a_context_init_script_runs_once_e2e.py", "tests/test_a_drag_keeps_its_buttons_pressed_e2e.py", "tests/test_a_field_is_typed_after_a_pause.py", "tests/test_a_goto_to_a_response_with_no_document_ends_e2e.py", "tests/test_a_keepalive_request_reaches_the_client_e2e.py", "tests/test_a_latin_letter_on_a_cyrillic_persona_e2e.py", "tests/test_a_page_cannot_probe_the_juggler_e2e.py", "tests/test_a_page_that_moves_on_e2e.py", "tests/test_a_pointer_event_is_handled_before_the_call_returns_e2e.py", "tests/test_a_request_says_what_it_is_e2e.py", "tests/test_a_worker_comes_back_with_its_page_from_the_cache_e2e.py", "tests/test_actions_without_a_point.py", "tests/test_add_script_tag.py", "tests/test_an_isolated_page_and_the_next_e2e.py", "tests/test_bypass_csp_e2e.py", "tests/test_caller_world_handles_e2e.py", "tests/test_canvas_reads_as_drawn.py", "tests/test_canvas_render_stealth.py", "tests/test_context_locale_e2e.py", "tests/test_context_proxy_only_resolves_by_doh_e2e.py", "tests/test_doh_through_the_proxy_e2e.py", "tests/test_doh_under_stress_e2e.py", "tests/test_download_is_intercepted_e2e.py", "tests/test_drag_motion.py", "tests/test_expose_binding_e2e.py", "tests/test_fakeweb_p4_e2e.py", "tests/test_fingerprint_consistency.py", "tests/test_fission_frames_dialogs_downloads_popups_e2e.py", "tests/test_fission_frames_route_and_bindings_e2e.py", "tests/test_fission_identity_parity_e2e.py", "tests/test_fission_iframe_crash_e2e.py", "tests/test_fission_strategy1_bench.py", "tests/test_goto_to_the_same_url_e2e.py", "tests/test_http3_through_the_proxy_e2e.py", "tests/test_input_is_born_before_the_page_sees_it_e2e.py", "tests/test_juggler_actions.py", "tests/test_juggler_event_listeners.py", "tests/test_juggler_injected.py::test_a_javascript_that_THROWS_arrives_as_an_error_not_as_None", "tests/test_juggler_injected.py::test_actionability_DISTINGUISHES_instead_of_always_saying_yes", "tests/test_juggler_injected.py::test_reads_that_make_no_sense_are_REJECTED", "tests/test_juggler_injected.py::test_states_DISCRIMINATE_instead_of_always_saying_true", "tests/test_juggler_injected.py::test_the_DOM_READING_group", "tests/test_juggler_injected.py::test_the_selector_engines_respond", "tests/test_juggler_injected.py::test_the_text_reads", "tests/test_juggler_lifecycle_e2e.py", "tests/test_key_delay_reaches_the_keyboard.py", "tests/test_keyboard_rhythm.py", "tests/test_long_session_e2e.py", "tests/test_mouse.py", "tests/test_mouse_events_keep_their_values_e2e.py", "tests/test_new_page_defaults.py", "tests/test_popup_destinations_e2e.py", "tests/test_popup_pages.py", "tests/test_proxy_http_auth_e2e.py", "tests/test_proxy_reaches_the_browser.py", "tests/test_proxy_socks_auth_e2e.py", "tests/test_requestless_navigation.py", "tests/test_route_abort_code.py", "tests/test_route_e2e.py", "tests/test_route_post_data_e2e.py", "tests/test_route_sends_a_navigation_elsewhere_e2e.py", "tests/test_route_superseded_e2e.py", "tests/test_same_document_navigation.py", "tests/test_screenshot_of_text_returns_linux_e2e.py", "tests/test_scroll_into_view.py", "tests/test_scroll_only_if_needed_e2e.py", "tests/test_service_workers_blocked.py", "tests/test_set_input_files_payloads.py", "tests/test_software_compositing_is_declared_e2e.py", "tests/test_the_association_is_ready_when_the_peerconnection_is_born_e2e.py", "tests/test_the_callers_code_runs_once_e2e.py", "tests/test_the_close_returns_when_the_browser_has_exited_e2e.py", "tests/test_the_favicon_stays_out_of_sight_e2e.py", "tests/test_the_font_list_is_the_bundle_e2e.py", "tests/test_the_parent_reads_the_bundle_from_fontconfig_s_cache_linux_e2e.py", "tests/test_the_scheme_is_the_personas_e2e.py", "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_typing_a_character_without_a_key_e2e.py", "tests/test_wait_for_timeout.py", "tests/test_web_fonts_of_closed_contexts_e2e.py"], "marker": "e2e", "needs_root": false, "windows_twin": "wrapper.e2e.suite.windows.2", "note": "Part 2 of the whole e2e suite of the wrapper (every test that opens the browser: what e2e.yml runs on the published engine), on the engine under test, as two passes through scripts/ci_suite_run.py (4 browsers at once, then the wall_clock tests alone; no rerun). The files of the 2 rows of linux are the files of tests/ that tests/test_the_e2e_suite_is_accounted_for.py holds one by one: a file whole when every test of it is here, else its tests by name. Partition from the junits of runs 44942540063 and 44985244053, test time balanced (about 564 s of estimated wall time, 4 browsers). A new file is added by hand to a row of each system and the minimum of the row goes up by hand. Left out of every row, with the reason in the accounting test: the files and tests of wrapLine truncated
{"id": "wrapper.e2e.suite.linux.3", "giro": "G2", "os": ["linux"], "min_tests": 313, "exact": true, "tests": ["tests/test_a_click_in_an_iframe_lands_at_the_frames_own_screen_origin_e2e.py", "tests/test_a_context_language_is_the_accept_language_of_every_request_e2e.py", "tests/test_a_file_chooser_reaches_every_client_e2e.py", "tests/test_a_goto_to_a_refused_port_ends_with_its_reason_e2e.py", "tests/test_a_handle_action_walks_like_a_selector_action_e2e.py", "tests/test_a_launch_and_a_context_timezone_reach_the_page_e2e.py", "tests/test_a_navigation_that_moved_is_told_by_the_engine_e2e.py", "tests/test_a_popup_of_a_link_reaches_the_client_e2e.py", "tests/test_a_regional_indicator_pair_measures_the_same_first_and_after_other_families_e2e.py", "tests/test_an_element_handle_serves_every_method_of_the_client_e2e.py", "tests/test_audio_context_values_are_declared_e2e.py", "tests/test_audio_noise_e2e.py", "tests/test_audio_sample_rate_is_declared_e2e.py", "tests/test_bundle_font_names_e2e.py", "tests/test_canvas_create_pattern_projection_e2e.py", "tests/test_canvas_measure_text_metrics_e2e.py", "tests/test_css_media_reads_the_declared_screen_and_pointer_e2e.py", "tests/test_dom_iterables_from_evaluate_e2e.py", "tests/test_every_argument_reaches_the_page_e2e.py", "tests/test_every_reader_of_a_webgl_canvas_agrees_e2e.py", "tests/test_exslt_date_time_through_an_imported_stylesheet_is_in_the_declared_zone_e2e.py", "tests/test_fakeweb_p2_e2e.py", "tests/test_fission_frames_tree_input_and_pixels_e2e.py", "tests/test_focus_survives_os_deactivation_e2e.py", "tests/test_fullscreen_without_wm_e2e.py", "tests/test_geolocation_reads_nothing_of_the_host_windows_e2e.py", "tests/test_goto_and_every_way_it_is_stopped_e2e.py", "tests/test_hardware_values_are_declared_e2e.py", "tests/test_ipv6_literal_connect_e2e.py", "tests/test_moz_element_paints_a_webgl_canvas_as_drawn_e2e.py", "tests/test_native_line_endings_are_windows_e2e.py", "tests/test_nested_frame_actions.py", "tests/test_networkidle_through_a_served_browser_with_routes_e2e.py", "tests/test_nothing_leaves_but_the_proxy_e2e.py", "tests/test_nothing_of_a_context_leaves_but_through_its_proxy_e2e.py", "tests/test_page_element_atoms_run_in_a_sandbox_e2e.py", "tests/test_popup_geometry_is_the_declared_frame_e2e.py", "tests/test_script_cache_written_is_adopted_e2e.py", "tests/test_the_branding_a_page_loads_is_the_declared_archive_e2e.py", "tests/test_the_evaluated_code_has_no_debugger_name_e2e.py", "tests/test_the_host_gl_probe_runs_only_on_an_undeclared_engine_linux_e2e.py", "tests/test_the_launch_counter_is_one_plain_get_before_any_page_e2e.py", "tests/test_the_shutdown_ping_leaves_by_the_background_task_e2e.py", "tests/test_webgl_declared_parameters_e2e.py", "tests/test_webgl_shader_language_e2e.py", "tests/test_webgpu_adapter_is_declared_e2e.py", "tests/test_webgpu_canvas_readback_is_noised_e2e.py", "tests/test_webgpu_external_texture_e2e.py", "tests/test_window_occlusion_e2e.py"], "marker": "e2e", "needs_root": false, "windows_twin": "wrapper.e2e.suite.windows.3", "note": "Part 2 of the whole e2e suite of the wrapper (every test that opens the browser: what e2e.yml runs on the published engine), on the engine under test, as two passes through scripts/ci_suite_run.py (4 browsers at once, then the wall_clock tests alone; no rerun). The files of the 2 rows of linux are the files of tests/ that tests/test_the_e2e_suite_is_accounted_for.py holds one by one: a file whole when every test of it is here, else its tests by name. Partition from the junits of runs 44942540063 and 44985244053, test time balanced (about 565 s of estimated wall time, 4 browsers). A new file is added by hand to a row of each system and the minimum of the row goes up by hand. Left out of every row, with the reason in the accounting test: the files and tests of wrapper.e2e.udp.exit and wrapper.e2e.udp.sandbox (root and user namespaces, their own rows), the files of the round after the publication (tests/_post_publication.py), and the tests that skip on linux (a skip is red in the verdict).", "run": "suite_run"},
{"id": "wrapper.e2e.suite.windows.1", "giro": "G2", "os": ["windows"], "min_tests": 332, "exact": true, "tests": ["tests/test_a_click_waits_for_the_navigation_it_plans_e2e.py", "tests/test_a_closed_browser_leaves_the_others_alone_e2e.py", "tests/test_a_context_init_script_runs_once_e2e.py", "tests/test_a_goto_to_a_refused_port_ends_with_its_reason_e2e.py", "tests/test_a_granted_permission_is_the_one_the_page_asks_for_e2e.py", "tests/test_a_held_ice_port_blinds_the_loopback_checks_e2e.py", "tests/test_a_left_documents_body_is_evicted_e2e.py", "tests/test_a_page_cannot_probe_the_juggler_e2e.py", "tests/test_a_screenshot_honours_its_scale_e2e.py", "tests/test_a_screenshot_refuses_what_would_touch_the_page_e2e.py", "tests/test_a_tiny_download_on_a_served_browser_is_saved_e2e.py", "tests/test_a_worker_comes_back_with_its_page_from_the_cache_e2e.py", "tests/test_browser_output_is_drained.py", "tests/test_canvas_create_pattern_projection_e2e.py", "tests/test_click_rhythm.py", "tests/test_closing_one_of_four_browsers_does_not_hold_the_loop_e2e.py", "tests/test_context_locale_e2e.py", "tests/test_context_proxy_only_resolves_by_doh_e2e.py", "tests/test_detectors_e2e.py", "tests/test_download_is_intercepted_e2e.py", "tests/test_e2e.py", "tests/test_element_handle_actions.py", "tests/test_every_page_draws_its_own_acts.py", "tests/test_every_reader_of_a_webgl_canvas_agrees_e2e.py", "tests/test_fission_identity_parity_e2e.py", "tests/test_fission_iframe_crash_e2e.py", "tests/test_focus_survives_os_deactivation_e2e.py", "tests/test_geolocation_reads_nothing_of_the_host_windows_e2e.py", "tests/test_goto_to_the_same_url_e2e.py", "tests/test_ignore_https_errors_e2e.py", "tests/test_juggler_actions.py", "tests/test_juggler_transport.py", "tests/test_keyboard_rhythm.py", "tests/test_moz_element_paints_a_webgl_canvas_as_drawn_e2e.py", "tests/test_nested_frame_actions.py", "tests/test_popups_reach_the_client_e2e.py", "tests/test_preload_newtab_turns_the_privileged_about_process_off_e2e.py", "tests/test_route_superseded_e2e.py", "tests/test_scroll_only_if_needed_e2e.py", "tests/test_security_state_engine_e2e.py", "tests/test_service_worker.py", "tests/test_service_workers_blocked.py", "tests/test_strict_and_force.py", "tests/test_the_engine_is_born_in_the_job_e2e.py", "tests/test_the_hosts_file_of_the_host_is_never_read_e2e.py", "tests/test_the_shutdown_ping_leaves_by_the_background_task_e2e.py", "tests/test_trial_does_not_act.py", "tests/test_ua_widget_not_selectable.py", "tests/test_webgpu_canvas_readback_is_noised_e2e.py"], "marker": "e2e", "needs_root": false, "linux_twin": "wrapper.e2e.suite.linux.1", "note": "Part 1 of the whole e2e suite of the wrapper (every test that opens the browser: what e2e.yml runs on the published engine), on the engine under test, as two passes through scripts/ci_suite_run.py (4 browsers at once, then the wall_clock tests alone; no rerun). The files of the 4 rows of windows are the files of tests/ that tests/test_the_e2e_suite_is_accounted_for.py holds one by one: a file whole when every test of it is here, else its tests by name. Partition from the junits of runs 44942540063 and 44985244053, test time balanced (about 609 s of estimated wall time, 4 browsers). A new file is added by hand to a row of each system and the minimum of the row goes up by hand. Left out of every row, with the reason in the accounting test: the files and tests of wrapper.e2e.udp.exit and wrapper.e2e.udp.sandbox (root and user namespaces, their own rows), the files of the round after the publication (tests/_post_publication.py), and the tests that skip on windows (a skip is red in the verdict).", "runner_image": {"windows": "windows-2022"}, "run": "suite_run"},
{"id": "wrapper.e2e.suite.windows.2", "giro": "G2", "os": ["windows"], "min_tests": 286, "exact": true, "tests": ["tests/test_a_file_chooser_reaches_every_client_e2e.py", "tests/test_a_goto_to_a_response_with_no_document_ends_e2e.py", "tests/test_a_latin_letter_on_a_cyrillic_persona_e2e.py", "tests/test_a_navigation_that_moved_is_told_by_the_engine_e2e.py", "tests/test_a_regional_indicator_pair_measures_the_same_first_and_after_other_families_e2e.py", "tests/test_a_turn_name_over_tcp_goes_through_the_proxy_of_the_context_e2e.py", "tests/test_add_script_tag.py", "tests/test_an_element_handle_serves_every_method_of_the_client_e2e.py", "tests/test_an_isolated_page_and_the_next_e2e.py", "tests/test_audio_context_values_are_declared_e2e.py", "tests/test_bundle_font_names_e2e.py", "tests/test_caller_world_handles_e2e.py", "tests/test_canvas_reads_as_drawn.py", "tests/test_canvas_render_stealth.py", "tests/test_css_media_reads_the_declared_screen_and_pointer_e2e.py", "tests/test_declared_host_network_e2e.py", "tests/test_every_argument_reaches_the_page_e2e.py", "tests/test_expose_binding_e2e.py", "tests/test_fission_frames_dialogs_downloads_popups_e2e.py", "tests/test_fullscreen_without_wm_e2e.py", "tests/test_goto_networkidle_after_spa_e2e.py", "tests/test_goto_script_redirect_e2e.py", "tests/test_hidden_desktop.py", "tests/test_ice_names_by_the_context_proxy_e2e.py::test_the_ice_name_of_a_context_goes_by_the_proxy_of_that_context", "tests/test_juggler_lifecycle_e2e.py", "tests/test_key_delay_reaches_the_keyboard.py", "tests/test_long_session_e2e.py", "tests/test_mouse.py", "tests/test_native_line_endings_are_windows_e2e.py", "tests/test_navigation_across_processes_e2e.py", "tests/test_networkidle_reaches_the_client_e2e.py", "tests/test_nothing_leaves_but_the_proxy_e2e.py", "tests/test_nothing_of_a_context_leaves_but_through_its_proxy_e2e.py", "tests/test_oop_frame_geometry.py", "tests/test_proxy_socks_auth_e2e.py", "tests/test_resolver_race_e2e.py", "tests/test_route_e2e.py", "tests/test_screencast_stop_e2e.py", "tests/test_the_branding_a_page_loads_is_the_declared_archive_e2e.py", "tests/test_the_device_enumeration_takes_the_declared_time_e2e.py", "tests/test_the_evaluated_code_has_no_debugger_name_e2e.py", "tests/test_the_favicon_stays_out_of_sight_e2e.py", "tests/test_the_font_list_is_the_bundle_e2e.py", "tests/test_the_scheme_is_the_personas_e2e.py", "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_turn_over_tcp_is_tried_for_real_e2e.py", "tests/test_voices_e2e.py", "tests/test_wait_for_function.py", "tests/test_wait_for_timeout.py", "tests/test_web_fonts_of_closed_contexts_e2e.py", "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_a_gather_after_the_page_loaded_through_the_gateway_costs_only_the_road_to_the_server", "tests/test_webrtc_realness.py::test_a_host_with_ipv6_addresses_gathers_through_an_ipv4_relay", "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_relay_never_answers_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_not_blocked_behind_tcp_only_socks", "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_the_turn_over_tcp_of_a_context_goes_through_the_proxy_of_that_context", "tests/test_webrtc_realness.py::test_two_contexts_with_two_proxies_each_gets_the_srflx_of_its_own"], "marker": "e2e", "needs_root": false, "linux_twin": "wrapper.e2e.suite.linux.2", "note": "Part 2 of the whole e2e suite of the wrapper (every test that opens the browser: what e2e.yml runs on the published engine), on the engine under test, as two passes through scripts/ci_suite_run.py (4 browsers at once, then the wall_clock tests alone; no rerun). The files of the 4 rows of windows are the files of tests/ that tests/test_the_e2e_suite_is_accounted_for.py holds one by one: a file whole when every test of it is here, else its tests by name. Partition from the junits of runs 44942540063 and 44985244053, test time balanced (about 610 s of estimated wall time, 4 browsers). A new file is added by hand to a row of each system and the minimum of the row goes up by hand. Left out of every row, with the reason in the accounting test: the files and tests of wrapper.e2e.udp.exit and wrapper.e2e.udp.sandbox (root and user namespaces, their own rows), the files of the round after the publication (tests/_post_publication.py), and the tests that skip on windows (a skip is red in the verdict).", "runner_image": {"windows": "windows-2022"}, "run": "suite_run"},
{"id": "wrapper.e2e.suite.windows.3", "giro": "G2", "os": ["windows"], "min_tests": 276, "exact": true, "tests": ["tests/test_a_click_in_an_iframe_lands_at_the_frames_own_screen_origin_e2e.py", "tests/test_a_context_that_ends_leaves_no_process_e2e.py", "tests/test_a_cors_preflight_is_not_a_request_of_the_page_e2e.py", "tests/test_a_launch_without_a_session_gets_one_e2e.py", "tests/test_a_mouse_click_makes_one_mousemove_on_its_point_e2e.py", "tests/test_a_page_over_ipv6_gathers_on_a_machine_declared_without_it_e2e.py", "tests/test_a_served_browser_answers_a_plain_client_e2e.py", "tests/test_actions_without_a_point.py", "tests/test_audio_noise_e2e.py", "tests/test_audio_sample_rate_is_declared_e2e.py", "tests/test_bypass_csp_e2e.py", "tests/test_control_a_selects_all_in_a_field_e2e.py", "tests/test_cross_origin_iframe.py", "tests/test_dom_iterables_from_evaluate_e2e.py", "tests/test_drag_motion.py", "tests/test_element_screenshot_e2e.py", "tests/test_fakeweb_p4_e2e.py", "tests/test_fingerprint_consistency.py", "tests/test_first_launch_from_a_new_path.py", "tests/test_fission_frames_history_and_processes_e2e.py", "tests/test_fission_frames_workers_storage_and_special_frames_e2e.py", "tests/test_fission_strategy1_bench.py", "tests/test_goto_and_every_way_it_is_stopped_e2e.py", "tests/test_http3_through_the_proxy_e2e.py", "tests/test_input_is_born_before_the_page_sees_it_e2e.py", "tests/test_ipv6_literal_connect_e2e.py", "tests/test_networkidle_through_a_served_browser_with_routes_e2e.py", "tests/test_page_number_follows_the_call.py", "tests/test_persistent_profile_keeps_state.py", "tests/test_pointer_position.py", "tests/test_popup_destinations_e2e.py", "tests/test_popup_pages.py", "tests/test_proxy_http_auth_e2e.py", "tests/test_requestless_navigation.py", "tests/test_route_abort_code.py", "tests/test_route_post_data_e2e.py", "tests/test_same_document_navigation.py", "tests/test_screencast.py", "tests/test_screenshot_looks_where_you_are.py", "tests/test_service_worker_controller_e2e.py", "tests/test_set_input_files_payloads.py", "tests/test_set_offline_e2e.py", "tests/test_the_callers_code_is_not_counted_e2e.py", "tests/test_the_callers_code_runs_once_e2e.py", "tests/test_the_close_returns_when_the_browser_has_exited_e2e.py", "tests/test_the_launch_counter_is_one_plain_get_before_any_page_e2e.py", "tests/test_webgl_declared_parameters_e2e.py", "tests/test_webgl_shader_language_e2e.py", "tests/test_webgpu_adapter_is_declared_e2e.py", "tests/test_webgpu_external_texture_e2e.py"], "marker": "e2e", "needs_root": false, "linux_twin": "wrapper.e2e.suite.linux.1", "note": "Part 3 of the whole e2e suite of the wrapper (every test that opens the browser: what e2e.yml runs on the published engine), on the engine under test, as two passes through scripts/ci_suite_run.py (4 browsers at once, then the wall_clock tests alone; no rerun). The files of the 4 rows of windows are the files of tests/ that tests/test_the_e2e_suite_is_accounted_for.py holds one by one: a file whole when every test of it is here, else its tests by name. Partition from the junits of runs 44942540063 and 44985244053, test time balanced (about 610 s of estimated wall time, 4 browsers). A new file is added by hand to a row of each system and the minimum of the row goes up by hand. Left out of every row, with the reason in the accounting test: the files and tests of wrapper.e2e.udp.exit and wrapper.e2e.udp.sandbox (root and user namespaces, their own rows), the files of the round after the publication (tests/_post_publication.py), and the tests that skip on windows (a skip is red in the verdict).", "runner_image": {"windows": "windows-2022"}, "run": "suite_run"},
{"id": "wrapper.e2e.suite.windows.4", "giro": "G2", "os": ["windows"], "min_tests": 273, "exact": true, "tests": ["tests/test_a_context_language_is_the_accept_language_of_every_request_e2e.py", "tests/test_a_declared_webgl_extension_survives_its_use_e2e.py", "tests/test_a_drag_keeps_its_buttons_pressed_e2e.py", "tests/test_a_field_is_typed_after_a_pause.py", "tests/test_a_handle_action_walks_like_a_selector_action_e2e.py", "tests/test_a_keepalive_request_reaches_the_client_e2e.py", "tests/test_a_launch_and_a_context_timezone_reach_the_page_e2e.py", "tests/test_a_page_that_moves_on_e2e.py", "tests/test_a_pointer_event_is_handled_before_the_call_returns_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_a_request_says_what_it_is_e2e.py", "tests/test_a_screenshot_draws_the_text_of_the_bundled_fonts_as_the_content_does_e2e.py", "tests/test_accept_language_on_the_wire_e2e.py", "tests/test_canvas_measure_text_metrics_e2e.py", "tests/test_doh_through_the_proxy_e2e.py", "tests/test_doh_under_stress_e2e.py", "tests/test_exslt_date_time_through_an_imported_stylesheet_is_in_the_declared_zone_e2e.py", "tests/test_fakeweb_p2_e2e.py", "tests/test_file_chooser.py", "tests/test_fingerprint_surface.py", "tests/test_fission_frames_route_and_bindings_e2e.py", "tests/test_fission_frames_tree_input_and_pixels_e2e.py", "tests/test_frames_outlive_the_back_forward_cache_e2e.py", "tests/test_hardware_values_are_declared_e2e.py", "tests/test_injected_node_surface.py", "tests/test_juggler_connection.py", "tests/test_juggler_event_listeners.py", "tests/test_juggler_injected.py::test_a_javascript_that_THROWS_arrives_as_an_error_not_as_None", "tests/test_juggler_injected.py::test_actionability_DISTINGUISHES_instead_of_always_saying_yes", "tests/test_juggler_injected.py::test_reads_that_make_no_sense_are_REJECTED", "tests/test_juggler_injected.py::test_states_DISCRIMINATE_instead_of_always_saying_true", "tests/test_juggler_injected.py::test_the_DOM_READING_group", "tests/test_juggler_injected.py::test_the_selector_engines_respond", "tests/test_juggler_injected.py::test_the_text_reads", "tests/test_mouse_events_keep_their_values_e2e.py", "tests/test_navigation_response.py", "tests/test_new_page_defaults.py", "tests/test_oop_frame_element.py", "tests/test_page_element_atoms_run_in_a_sandbox_e2e.py", "tests/test_popup_geometry_is_the_declared_frame_e2e.py", "tests/test_proxy_reaches_the_browser.py", "tests/test_realness_behind_a_declared_exit_e2e.py", "tests/test_route_header_order_e2e.py", "tests/test_route_sends_a_navigation_elsewhere_e2e.py", "tests/test_same_document_goto_e2e.py", "tests/test_script_cache_written_is_adopted_e2e.py", "tests/test_scroll_into_view.py", "tests/test_shadow_trusted_input.py", "tests/test_software_compositing_is_declared_e2e.py", "tests/test_the_association_is_ready_when_the_peerconnection_is_born_e2e.py", "tests/test_typing_a_character_without_a_key_e2e.py", "tests/test_webgl_noise_active.py", "tests/test_window_occlusion_e2e.py"], "marker": "e2e", "needs_root": false, "linux_twin": "wrapper.e2e.suite.linux.2", "note": "Part 4 of the whole e2e suite of the wrapper (every test that opens the browser: what e2e.yml runs on the published engine), on the engine under test, as two passes through scripts/ci_suite_run.py (4 browsers at once, then the wall_clock tests alone; no rerun). The files of the 4 rows of windows are the files of tests/ that tests/test_the_e2e_suite_is_accounted_for.py holds one by one: a file whole when every test of it is here, else its tests by name. Partition from the junits of runs 44942540063 and 44985244053, test time balanced (about 609 s of estimated wall time, 4 browsers). A new file is added by hand to a row of each system and the minimum of the row goes up by hand. Left out of every row, with the reason in the accounting test: the files and tests of wrapper.e2e.udp.exit and wrapper.e2e.udp.sandbox (root and user namespaces, their own rows), the files of the round after the publication (tests/_post_publication.py), and the tests that skip on windows (a skip is red in the verdict).", "runner_image": {"windows": "windows-2022"}, "run": "suite_run"},
{"id": "wrapper.e2e.suite.windows.control_a", "giro": "G2", "os": ["windows"], "min_tests": 20, "exact": true, "tests": ["tests/test_control_a_selects_all_in_a_field_e2e.py"], "marker": "e2e", "needs_root": false, "linux_twin": "wrapper.e2e.suite.linux.1", "note": "The keyboard shortcut Control+A selects all in a field (5 ways to press it x an input and a textarea, in-process and served to the stock client), alone on its own Windows runner (windows-latest), as e2e.yml runs it on the published engine: the Windows keyboard of a real user is what it needs. The same file is in one of wrapper.e2e.suite.windows.1..4 and in wrapper.e2e.suite.linux.1.", "run": "suite_run"},
{"id": "wrapper.e2e.ab_oracle", "giro": "G2", "os": ["linux", "windows"], "min_tests": 1, "exact": true, "tests": ["tests/test_ab_oracle_e2e.py"], "marker": "e2e", "needs_root": false, "note": "Same seed, same bytes: the engine published as firefox-68 against the candidate, on one machine, with the same core and wrapper, after the control: the published engine against ITSELF (the A/A; a difference is a broken control, exit 2, and the A/B is not run). On a pull request (no candidate: INVPW_BINARY_PATH is the published engine, no INVISIBLE_SEAL_FILE) the A/A is the whole test, on the first two seeds of the candidate set (all five when the pull request changes a file of this oracle: the step of e2e.yml that runs scripts/ci_ab_pr_seeds.py exports AB_ORACLE_PR_SEEDS), and saves both dumps and the diff under $AB_ORACLE_OUT or $RUNNER_TEMP/invpw-evidence/ab-oracle. scripts/ci_ab_oracle.py runs the host gate's dump (scripts/ci_host_gate.py dump: the persona seeds of ci/persona-seeds.json, each at its own DPR with nothing pinned, the whole page of scripts/host_gate; the `candidate` set of 5 seeds that reach every webgl renderer and every DPR, or with AB_ORACLE_SEED_SET=final and AB_ORACLE_SHARD=i/n the 20 seeds that reach every value of every dimension split over n jobs) twice, once with the firefox-68 binary (the release's seal.json, then the core's own download.ensure_binary under that seal: the archive's sha256 is checked against the seal) and once with the candidate binary of the leg under its own seal, and compares every leaf of every visit: the only differences allowed are the `noise` entries of scripts/host_gate/exceptions.json and the diag. keys; anything else is red with the leaf, the two values and the seed; fewer leaves than the host gate's reference holds (16439 per visit; a DPR the reference does not record is held to the least of those it does) is red. The files (dump-68.json, dump-68-again.json, diff-a-a.json and, with a candidate, dump-candidate.json and diff.json) are the artifact ab-oracle-<os> of the leg. 1 = the one test; the comparator's own cases (51, the A/A's among them) are in tests/test_ab_oracle.py, the persona seeds' (15) in tests/test_persona_cover.py, in the rows of the whole unit suite. Needs the engine's binary (INVPW_BINARY_PATH) and, for the A/B, the candidate's seal (INVISIBLE_SEAL_FILE) and the network (the release assets of firefox-68). The engine of the candidate must accept the core of the leg and the 68 engine must accept it too: a core that declares something the published engine refuses is a red of this suite, not of the engine.", "timeout_minutes": 50, "core_dumps": "cores", "extra_steps": ["keep_oracle_files"], "artifact": "ab-oracle"},
{"id": "wrapper.e2e.ab_network", "giro": "G2", "os": ["linux", "windows"], "min_tests": 1, "exact": true, "tests": ["tests/test_ab_network_e2e.py"], "marker": "e2e", "needs_root": false, "note": "Network A/B oracle: the P4 journey, HTTPS h1/h2 (ClientHello, h2 frames, header order), HTTP/3 (transport parameters, H3 SETTINGS), WebRTC through the coherent SOCKS5 lab gateway, DNS through the fake DoH, and an idle launch; transcripts compared leaf by leaf, direct connections red on either side. A/A first (the published engine twice: a difference is a broken control; ci/ab-network-volatile.json holds the leaves the A/A proved volatile, and may only shrink), then the published engine against the candidate. Without a candidate (a PR's e2e) the A/A alone, on the first seed (all five when the pull request changes a file of this oracle: AB_NETWORK_PR_SEEDS), in jobs of its own in e2e.yml on Linux and on Windows (the shared e2e jobs leave this file out).", "timeout_minutes": 75, "core_dumps": "cores", "extra_steps": ["keep_oracle_files"]},
{"id": "wrapper.e2e.ab_host", "giro": "G2", "os": ["linux", "windows"], "min_tests": 1, "exact": true, "tests": ["tests/test_ab_host_e2e.py"], "marker": "e2e", "needs_root": false, "note": "Host A/B oracle: the whole TRACE of a closed run, from the launch to the exit of the browser, after the same journey. Compared: the processes by kind (the parent, -contentproc type, sandboxingKind, isForBrowser, the helpers by what they ran) with their count, except for the kinds of type tab whose count follows the idle time (only their presence counts), and the host paths the tree touched, judged by one rule (red if and only if a path is in all the measured launches of one engine and in no launch of the other, the long launches included; every other path that differs is listed in not-judged.json, not judged); what is ours (the package, the profile and temp dirs of the launch, the run cache, its own shared memory) leaves the comparison as a class. Linux: strace of the whole tree. Windows: the process-creation audit (event 4688, with the command line) and an ETW file trace of Kernel-File, which need an administrator. It has jobs of its own in e2e.yml on Linux and on Windows (a measurement shares the machine with no other browser), and its footprints keep the lifecycle of the tree (who started and ended when, how) and how the close ended. Each engine run starts with a discarded warm-up launch whose trace is kept and listed apart (what only the warm-up did, with the process that did it); only the tree of the launch is compared (a Windows service's paths are counted by process name and left out), and a path or a kind that differs names the processes to blame. A/A first, then the published engine against the candidate; the one declared difference (Linux glxtest, gone on the 69) is in ci/ab-host-expected.json, applied by kind, a list that may only shrink. There is no list of noise. Without a candidate (a PR e2e) the A/A alone, on the first two seeds (all five when the pull request changes a file of this oracle: AB_HOST_PR_SEEDS).", "runner_image": {"windows": "windows-2022"}, "timeout_minutes": 50, "core_dumps": "cores", "stock_firefox": ["windows"], "location_service": ["windows"], "extra_steps": ["keep_oracle_files"]},
{"id": "wrapper.e2e.ab_host_crash", "giro": "G2", "os": ["linux"], "min_tests": 1, "exact": true, "tests": ["tests/test_ab_host_crash_linux_e2e.py"], "marker": "e2e", "needs_root": false, "linux_only": "A signal sent to the parent of the browser with os.kill, the core the kernel writes and gdb reads, and the signal line of strace exist on Linux only: Windows has no counterpart of this test. What a Windows launch that did not end with 0 leaves (the `.extra` files and the minidump names, read from the crash folders) is held by the unit tests of the recorder with fake launches, and by every Windows leg of the three oracles, which are red on any parent that does not end with 0.", "note": "The recorder of the host oracle, tested on a launch that dies on purpose: scripts/ci_ab_host.py crash-probe launches the engine once under the oracle's stand-in (strace of the tree, cores enabled, a crash watcher), sends SIGSEGV to the browser's parent with os.kill and closes it as the oracle closes its launches; the test passes when the oracle reports RED (exit 1, `FAIL the parent process exited with code ...: seed N, launch crash`) and the artifact (RUNNER_TEMP/invpw-evidence/ab-host-crash) holds the signal line of the strace log (strace-signals.txt, strace-tail.txt), the core run through gdb (gdb-core.*.txt: `thread apply all bt`, the MOZ_CRASH reason, `info sharedlibrary`), the build ids and what the collectors did not find (said.txt). It fails when the oracle says green for a launch that died, when the evidence is missing and when the probe did not run; the red of the probe does not make the job red. It runs in the job of the host oracle on Linux (e2e-host: strace, gdb and elfutils installed, kernel.core_pattern pointed at INVPW_CORE_DIR), after the A/A, and is left out of the shared e2e job (OWN_JOB_FILES).", "timeout_minutes": 35, "core_dumps": "cores", "extra_steps": ["keep_oracle_files"]}
{"id": "wrapper.unit.all.linux", "giro": "G1", "os": ["linux"], "min_tests": 2183, "exact": true, "tests": ["tests/test_a_162_message_is_read_like_a_161_one.py", "tests/test_a_click_makes_one_mousemove_at_its_point.py", "tests/test_a_closed_context_leaves_nothing_in_the_registry.py", "tests/test_a_closed_page_says_nothing.py", "tests/test_a_closed_pipe_is_a_closed_target.py", "tests/test_a_commit_at_any_point_of_the_hand_over_reaches_the_client_once.py", "tests/test_a_context_proxy_carries_its_measured_udp_exit.py", "tests/test_a_context_route_disables_the_cache.py", "tests/test_a_detached_frame_answers_detached.py", "tests/test_a_dialog_is_a_protocol_object.py", "tests/test_a_dialog_is_answered_after_a_pause.py", "tests/test_a_download_finished_before_it_was_announced_is_finished.py", "tests/test_a_failed_expect_carries_its_call_log.py", "tests/test_a_failed_launch_stops_the_display.py", "tests/test_a_field_is_typed_after_a_pause.py", "tests/test_a_launch_asks_nobody_on_the_internet_where_it_leaves_from.py", "tests/test_a_launch_has_one_deadline.py", "tests/test_a_launch_without_a_session_gets_one.py", "tests/test_a_live_event_does_not_overtake_the_replay_of_a_new_page.py", "tests/test_a_module_that_leaves_a_browser_open_fails.py", "tests/test_a_new_page_waits_for_the_engine.py", "tests/test_a_non_finite_number_crosses_the_wire_as_a_tag.py", "tests/test_a_page_closed_before_its_announcement_is_not_announced.py", "tests/test_a_page_is_handed_over_only_when_the_engine_says_it_is_ready.py", "tests/test_a_path_leaves_as_one_stroke.py", "tests/test_a_port_number_is_held_until_it_is_used.py", "tests/test_a_request_and_a_response_are_light.py", "tests/test_a_request_says_what_it_is.py", "tests/test_a_session_ends_before_the_next_test_starts.py", "tests/test_a_stroke_is_judged_by_its_shape_not_its_length.py", "tests/test_a_unit_test_does_not_read_the_seal_of_the_job.py", "tests/test_actions_without_a_point.py", "tests/test_add_script_tag.py", "tests/test_an_expect_reads_its_value_once.py", "tests/test_async_api.py", "tests/test_browser_output_is_drained.py", "tests/test_ci_downloads_are_authenticated.py", "tests/test_ci_drive_gate_goes_through_the_core.py", "tests/test_ci_host_gate.py", "tests/test_ci_lab_geoip.py", "tests/test_ci_lab_geoip_verify.py", "tests/test_ci_lab_intermediates.py", "tests/test_ci_real_geoip_check.py", "tests/test_ci_real_geoip_exit_code.py", "tests/test_ci_runs_once_per_commit.py", "tests/test_ci_verdict.py", "tests/test_ci_workflows_build_the_geoip_database.py", "tests/test_ci_workflows_set_the_intermediates_list.py", "tests/test_cli.py", "tests/test_click_rhythm.py", "tests/test_connect_does_not_start_threads_on_the_loop.py", "tests/test_context_locale_is_a_list.py", "tests/test_core_pin.py", "tests/test_cpu_by_type_window.py", "tests/test_cross_origin_iframe.py", "tests/test_css_calc_is_windows_e2e.py", "tests/test_cursor_dispatch.py", "tests/test_cursor_wiring.py", "tests/test_docs_name_the_mcp_repo_as_it_is.py", "tests/test_doh_session_prefs_unit.py", "tests/test_drag_motion.py", "tests/test_e2e_hermetic.py", "tests/test_element_handle_actions.py", "tests/test_every_order_of_the_events_of_a_popup_gives_one_page_event.py", "tests/test_every_page_draws_its_own_acts.py", "tests/test_every_refusal_is_declared.py", "tests/test_every_route_command_is_answered_may_fail.py", "tests/test_every_suite_runs_on_linux_and_windows.py", "tests/test_expose_binding_refusal.py", "tests/test_fakeweb_p4_report.py", "tests/test_fission_identity_parity_e2e.py", "tests/test_fixtures_name_why_the_package_is_missing.py", "tests/test_fork.py", "tests/test_frame_dispatch.py", "tests/test_geoip_used.py", "tests/test_goto_follows_the_base_url.py", "tests/test_hook_wiring.py", "tests/test_imports.py", "tests/test_integration.py", "tests/test_juggler_event_buffer.py", "tests/test_juggler_event_listeners.py", "tests/test_juggler_injected.py", "tests/test_juggler_lives_in_the_core.py", "tests/test_juggler_posix_pipe.py", "tests/test_juggler_transport.py", "tests/test_key_delay_reaches_the_keyboard.py", "tests/test_keyboard_rhythm.py", "tests/test_launch_counters_run_on_github.py", "tests/test_launcher_config.py", "tests/test_launcher_helpers.py", "tests/test_math_sin_cos_tan_are_windows_e2e.py", "tests/test_motion_never_hides_a_programming_error.py", "tests/test_navigation_response.py", "tests/test_new_page_defaults.py", "tests/test_no_event_of_any_family_is_lost_by_the_hand_over.py", "tests/test_no_legacy_in_the_wrapper.py", "tests/test_no_override_leaves_the_persona_scheme.py", "tests/test_no_thread_is_started_on_the_reader.py", "tests/test_page_number_follows_the_call.py", "tests/test_persistent_profile_keeps_state.py", "tests/test_pin.py", "tests/test_pin_dicts_are_valid.py", "tests/test_pinning_doc.py", "tests/test_pointer_server.py", "tests/test_popup_adoption_unit.py", "tests/test_prefs_composition_arm.py", "tests/test_preload_newtab_is_written_only_when_asked.py", "tests/test_protocol_names_are_declared.py"Line truncated
{"id": "wrapper.unit.all.windows", "giro": "G1", "os": ["windows"], "min_tests": 2184, "exact": true, "tests": ["tests/test_a_162_message_is_read_like_a_161_one.py", "tests/test_a_click_makes_one_mousemove_at_its_point.py", "tests/test_a_closed_context_leaves_nothing_in_the_registry.py", "tests/test_a_closed_page_says_nothing.py", "tests/test_a_closed_pipe_is_a_closed_target.py", "tests/test_a_commit_at_any_point_of_the_hand_over_reaches_the_client_once.py", "tests/test_a_context_proxy_carries_its_measured_udp_exit.py", "tests/test_a_context_route_disables_the_cache.py", "tests/test_a_detached_frame_answers_detached.py", "tests/test_a_dialog_is_a_protocol_object.py", "tests/test_a_dialog_is_answered_after_a_pause.py", "tests/test_a_download_finished_before_it_was_announced_is_finished.py", "tests/test_a_failed_expect_carries_its_call_log.py", "tests/test_a_failed_launch_stops_the_display.py", "tests/test_a_field_is_typed_after_a_pause.py", "tests/test_a_launch_asks_nobody_on_the_internet_where_it_leaves_from.py", "tests/test_a_launch_has_one_deadline.py", "tests/test_a_launch_without_a_session_gets_one.py", "tests/test_a_live_event_does_not_overtake_the_replay_of_a_new_page.py", "tests/test_a_module_that_leaves_a_browser_open_fails.py", "tests/test_a_new_page_waits_for_the_engine.py", "tests/test_a_non_finite_number_crosses_the_wire_as_a_tag.py", "tests/test_a_page_closed_before_its_announcement_is_not_announced.py", "tests/test_a_page_is_handed_over_only_when_the_engine_says_it_is_ready.py", "tests/test_a_path_leaves_as_one_stroke.py", "tests/test_a_port_number_is_held_until_it_is_used.py", "tests/test_a_request_and_a_response_are_light.py", "tests/test_a_request_says_what_it_is.py", "tests/test_a_session_ends_before_the_next_test_starts.py", "tests/test_a_stroke_is_judged_by_its_shape_not_its_length.py", "tests/test_a_unit_test_does_not_read_the_seal_of_the_job.py", "tests/test_actions_without_a_point.py", "tests/test_add_script_tag.py", "tests/test_an_expect_reads_its_value_once.py", "tests/test_async_api.py", "tests/test_browser_output_is_drained.py", "tests/test_ci_downloads_are_authenticated.py", "tests/test_ci_drive_gate_goes_through_the_core.py", "tests/test_ci_host_gate.py", "tests/test_ci_lab_geoip.py", "tests/test_ci_lab_geoip_verify.py", "tests/test_ci_lab_intermediates.py", "tests/test_ci_real_geoip_check.py", "tests/test_ci_real_geoip_exit_code.py", "tests/test_ci_runs_once_per_commit.py", "tests/test_ci_verdict.py", "tests/test_ci_workflows_build_the_geoip_database.py", "tests/test_ci_workflows_set_the_intermediates_list.py", "tests/test_cli.py", "tests/test_click_rhythm.py", "tests/test_connect_does_not_start_threads_on_the_loop.py", "tests/test_context_locale_is_a_list.py", "tests/test_core_pin.py", "tests/test_cpu_by_type_window.py", "tests/test_cross_origin_iframe.py", "tests/test_css_calc_is_windows_e2e.py", "tests/test_cursor_dispatch.py", "tests/test_cursor_wiring.py", "tests/test_docs_name_the_mcp_repo_as_it_is.py", "tests/test_doh_session_prefs_unit.py", "tests/test_drag_motion.py", "tests/test_e2e_hermetic.py", "tests/test_element_handle_actions.py", "tests/test_every_order_of_the_events_of_a_popup_gives_one_page_event.py", "tests/test_every_page_draws_its_own_acts.py", "tests/test_every_refusal_is_declared.py", "tests/test_every_route_command_is_answered_may_fail.py", "tests/test_every_suite_runs_on_linux_and_windows.py", "tests/test_expose_binding_refusal.py", "tests/test_fakeweb_p4_report.py", "tests/test_fission_identity_parity_e2e.py", "tests/test_fixtures_name_why_the_package_is_missing.py", "tests/test_fork.py", "tests/test_frame_dispatch.py", "tests/test_geoip_used.py", "tests/test_goto_follows_the_base_url.py", "tests/test_hook_wiring.py", "tests/test_imports.py", "tests/test_integration.py", "tests/test_juggler_event_buffer.py", "tests/test_juggler_event_listeners.py", "tests/test_juggler_injected.py", "tests/test_juggler_lives_in_the_core.py", "tests/test_juggler_transport.py", "tests/test_key_delay_reaches_the_keyboard.py", "tests/test_keyboard_rhythm.py", "tests/test_launch_counters_run_on_github.py", "tests/test_launcher_config.py", "tests/test_launcher_helpers.py", "tests/test_math_sin_cos_tan_are_windows_e2e.py", "tests/test_motion_never_hides_a_programming_error.py", "tests/test_navigation_response.py", "tests/test_new_page_defaults.py", "tests/test_no_event_of_any_family_is_lost_by_the_hand_over.py", "tests/test_no_legacy_in_the_wrapper.py", "tests/test_no_override_leaves_the_persona_scheme.py", "tests/test_no_thread_is_started_on_the_reader.py", "tests/test_page_number_follows_the_call.py", "tests/test_persistent_profile_keeps_state.py", "tests/test_pin.py", "tests/test_pin_dicts_are_valid.py", "tests/test_pinning_doc.py", "tests/test_pointer_server.py", "tests/test_popup_adoption_unit.py", "tests/test_prefs_composition_arm.py", "tests/test_prefs_composition_arm_on_windows.py", "tests/test_preload_newtab_is_written_only_when_asked.py", "tests/test_protocol_nameLine truncated
]
-17
View File
@@ -1,17 +0,0 @@
[
{"file": "tests/test_css_calc_is_windows_e2e.py", "reason": "feature cancelled with the 69 backlog (21/11)", "date": "2026-11-21", "tests": {"wrapper.unit.all.linux": 1, "wrapper.unit.all.windows": 1}},
{"file": "tests/test_math_sin_cos_tan_are_windows_e2e.py", "reason": "feature cancelled with the 69 backlog (21/11)", "date": "2026-11-21", "tests": {"wrapper.unit.all.linux": 1, "wrapper.unit.all.windows": 1}},
{"file": "tests/test_system_fonts_and_colors_are_windows_e2e.py", "reason": "feature cancelled with the 69 backlog (21/11)", "date": "2026-11-21", "tests": {"wrapper.unit.all.linux": 1, "wrapper.unit.all.windows": 1}},
{"file": "tests/test_webgl_dot_has_the_declared_gpu_s_bits_e2e.py", "reason": "feature cancelled with the 69 backlog (21/11)", "date": "2026-11-21", "tests": {"wrapper.unit.all.linux": 3, "wrapper.unit.all.windows": 3}},
{"file": "tests/unit/test_canvas_icc_refs.py", "reason": "feature cancelled with the 69 backlog (21/11)", "date": "2026-11-21", "tests": {"wrapper.unit.all.linux": 9, "wrapper.unit.all.windows": 9}},
{"file": "tests/unit/test_canvas_text_colors_refs.py", "reason": "feature cancelled with the 69 backlog (21/11)", "date": "2026-11-21", "tests": {"wrapper.unit.all.linux": 8, "wrapper.unit.all.windows": 8}},
{"file": "tests/unit/test_canvas_text_refs.py", "reason": "feature cancelled with the 69 backlog (21/11)", "date": "2026-11-21", "tests": {"wrapper.unit.all.linux": 7, "wrapper.unit.all.windows": 7}},
{"file": "tests/unit/test_compare_canvas_text_runs.py", "reason": "feature cancelled with the 69 backlog (21/11)", "date": "2026-11-21", "tests": {"wrapper.unit.all.linux": 3, "wrapper.unit.all.windows": 3}},
{"file": "tests/unit/test_fontconfig_criterion.py", "reason": "feature cancelled with the 69 backlog (21/11)", "date": "2026-11-21", "tests": {"wrapper.unit.all.linux": 5, "wrapper.unit.all.windows": 5}},
{"file": "tests/unit/test_theme_refusal_drop.py", "reason": "feature cancelled with the 69 backlog (21/11)", "date": "2026-11-21", "tests": {"wrapper.unit.all.linux": 3, "wrapper.unit.all.windows": 3}},
{"nodeid": "tests/test_detectors_e2e.py::test_the_headless_detector_sees_no_headless_and_no_proxy_tell", "suite": "wrapper.e2e.suite.linux.1", "count": 1, "from_min_tests": 449, "reason": "removed with the vendored bundle whose licence notice cannot ship without a studied system's name (pm, 27/11)", "decided_by": "pm", "date": "2026-11-27"},
{"nodeid": "tests/test_realness_behind_a_declared_exit_e2e.py::test_the_vendored_detection_page_finds_nothing_behind_the_gateway", "suite": "wrapper.e2e.suite.linux.1", "count": 1, "from_min_tests": 449, "reason": "removed with the vendored bundle whose licence notice cannot ship without a studied system's name (pm, 27/11)", "decided_by": "pm", "date": "2026-11-27"},
{"nodeid": "tests/test_detectors_e2e.py::test_the_headless_detector_sees_no_headless_and_no_proxy_tell", "suite": "wrapper.e2e.suite.windows.1", "count": 1, "from_min_tests": 333, "reason": "removed with the vendored bundle whose licence notice cannot ship without a studied system's name (pm, 27/11)", "decided_by": "pm", "date": "2026-11-27"},
{"nodeid": "tests/test_realness_behind_a_declared_exit_e2e.py::test_the_vendored_detection_page_finds_nothing_behind_the_gateway", "suite": "wrapper.e2e.suite.windows.4", "count": 1, "from_min_tests": 274, "reason": "removed with the vendored bundle whose licence notice cannot ship without a studied system's name (pm, 27/11)", "decided_by": "pm", "date": "2026-11-27"},
{"nodeid": "tests/test_realness_behind_a_declared_exit_e2e.py::test_the_vendored_detection_page_finds_nothing_behind_the_gateway", "suite": "wrapper.e2e.realness", "count": 1, "from_min_tests": 32, "reason": "removed with the vendored bundle whose licence notice cannot ship without a studied system's name (pm, 27/11)", "decided_by": "pm", "date": "2026-11-27"}
]
-6
View File
@@ -1,6 +0,0 @@
{
"comment": "The ready security state every job of ci.yml launches with (STEALTHFOX_SECURITY_STATE, set at the top of the workflow): a result with NO data (format 1, ok, no CRLite hashes, zero timestamps, no engine) and no security_state/ directory, so a launch copies nothing and no job asks Mozilla for anything or runs the engine's generate mode (the core neither downloads nor generates when the variable is set). To change it, change ci/security-state/securitystate-result.json and sha256 here in one commit; tests/test_ci_sets_the_security_state.py fails when they differ.",
"file": "ci/security-state/securitystate-result.json",
"sha256": "15bed64b8d0d0db9e6e5cceeec231bbca5300cdc6715280a647895dd6f6f14a4",
"bytes": 260
}
@@ -1 +0,0 @@
{"format":1,"ok":true,"error":null,"engine":{"version":"","build_id":""},"collections":{"intermediates":{"collection_timestamp":0},"onecrl":{"collection_timestamp":0},"cert-revocations":{"collection_timestamp":0,"channel":"default"}},"crlite_filter_hashes":[]}
+2 -2
View File
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "invisible_playwright"
version = "0.60.0"
version = "0.57.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==70.83.0",
"invisible_core==67.79.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
+172
View File
@@ -0,0 +1,172 @@
"""Builds tests/data/canvas_icc_ref/refs.json, the reference of the canvas ICC readback test.
One measurement of retail Firefox 159.0 on Windows with the default prefs (the run
``a_win_default``: qcms converts a tagged image to the monitor profile, here the stock
"sRGB Color Space Profile.icm"), and one control run on the same machine with
gfx.color_management.force_srgb=true (``b_win_force_srgb``: the bytes without that
conversion), both made by index.html and the images of gen_images.py:
python -I scripts/build_canvas_icc_refs.py <a_win_default.json> <b_win_force_srgb.json> \
--repeat <a2_win_default_repeat.json> --host-profile <host_display_profile.json> \
--source <name of the capture> [--out tests/data/canvas_icc_ref/refs.json]
The script stops if the repeat run has other hashes than the reference run, if the runs
were not made on the same Firefox build, or if the prefs of the two runs are not the default
and force_srgb=true. The probes are the 72 of the page: for each of the 10 images drawImage,
drawImage at 32 px, createImageBitmap with the default colour space conversion and with
``none``; the 22 fill colours; the canvas colorSpace probe; the 9 environment values.
Standard library only: it does not import invisible_core, and the repository holds no PNG
and no run's pixel hex, only hashes and sizes.
"""
from __future__ import annotations
import argparse
import hashlib
import importlib.util
import json
import sys
from pathlib import Path
DEFAULT_OUT = Path(__file__).resolve().parents[1] / "tests" / "data" / "canvas_icc_ref" / "refs.json"
IMAGE_PROBES = ("drawImage", "drawImage_scaled32", "bitmap_default", "bitmap_none")
#: Value probes that are not colour management: the host's theme, which the retail machine
#: had dark; the test does not compare it (the persona's colour scheme is checked elsewhere).
NOT_COMPARED = ("env | prefers-color-scheme:dark",)
GEN_IMAGES = DEFAULT_OUT.parent / "gen_images.py"
def image_files():
"""{image id: {file, bytes, sha256}} of the ten images gen_images.py writes: the reference
names them, so a generator that drifts is seen before the engine is blamed."""
spec = importlib.util.spec_from_file_location("gen_images", GEN_IMAGES)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
imgs, _profiles = mod.build_images()
return {iid: {"file": "images/%s.%s" % (iid, ext), "bytes": len(data),
"sha256": hashlib.sha256(data).hexdigest()}
for iid, ext, data, _what in imgs}
class RefError(ValueError):
"""The runs cannot be one reference."""
def env_sha256(value):
"""The hash of an environment value: SHA-256 of its compact JSON (as JSON.stringify)."""
return hashlib.sha256(json.dumps(value, separators=(",", ":")).encode()).hexdigest()
def probes(R):
"""{probe name: {kind, sha256, bytes (pixel probes), value (env)}} of a page result R
(``window.R`` of index.html). ``bytes`` is the RGBA length: 4 x width x height."""
out = {}
for iid, v in R["images"].items():
for k in IMAGE_PROBES:
e = v.get(k)
if not isinstance(e, dict) or "sha256" not in e:
raise RefError("image %s probe %s has no hash: %r" % (iid, k, e))
size = 32 if k == "drawImage_scaled32" else 16
out["%s | %s" % (iid, k)] = {"kind": "image", "sha256": e["sha256"],
"bytes": 4 * size * size}
for f, v in R["fills"].items():
if "sha256" not in v:
raise RefError("fill %s has no hash: %r" % (f, v))
out["fill | " + f] = {"kind": "fill", "sha256": v["sha256"], "bytes": 4 * 16 * 16}
p3 = R["canvas_colorspace"].get("p3_fill_p3_canvas") or {}
if "sha256" not in p3:
raise RefError("the canvas colorSpace probe has no hash")
out["canvas colorSpace p3 fill"] = {"kind": "colorspace", "sha256": p3["sha256"],
"bytes": 4 * 16 * 16}
for k, v in R["env"].items():
out["env | " + k] = {"kind": "env", "sha256": env_sha256(v), "value": v}
return out
def build(a, b, repeat, host_profile, source):
"""The reference from the default run ``a``, the control run ``b`` (force_srgb), the
repeat of ``a`` and the host profile description; all as loaded JSON."""
for key in ("buildid", "exe_sha256", "version", "os"):
if a["firefox"][key] != b["firefox"][key] or a["firefox"][key] != repeat["firefox"][key]:
raise RefError("the runs differ in the Firefox %s" % key)
pa, pb, pr = probes(a["R"]), probes(b["R"]), probes(repeat["R"])
if pa != pr:
bad = sorted(k for k in pa if pa[k] != pr.get(k))
raise RefError("the repeat run differs from the reference run on %d probes: %s"
% (len(bad), ", ".join(bad[:5])))
if set(pa) != set(pb):
raise RefError("the control run has other probes than the reference run")
prefs_a, prefs_b = a["prefs_read_back"], b["prefs_read_back"]
if prefs_a.get("gfx.color_management.display_profile") not in ("", None):
raise RefError("the reference run has a display_profile pref: it must read the host's")
if prefs_a.get("gfx.color_management.force_srgb") is not False:
raise RefError("the reference run is not made with the default force_srgb (false)")
if prefs_b.get("gfx.color_management.force_srgb") is not True:
raise RefError("the control run is not made with force_srgb=true")
for k, v in prefs_a.items():
if k != "gfx.color_management.force_srgb" and prefs_b.get(k) != v:
raise RefError("the control run differs in %s" % k)
out = {}
dependent = []
for name, p in pa.items():
e = dict(p)
if pb[name]["sha256"] != p["sha256"]:
e["without_conversion_sha256"] = pb[name]["sha256"]
dependent.append(name)
if name in NOT_COMPARED:
e["compared"] = False
out[name] = e
return {
"test_page": "index.html",
"image_generator": "gen_images.py",
"source": {
"capture": source,
"reference_run": "runs/a_win_default.json",
"repeat_run": "runs/a2_win_default_repeat.json (same hashes on all probes)",
"control_run": "runs/b_win_force_srgb.json (gfx.color_management.force_srgb=true)",
"date": "2026-11-09",
},
"firefox": {**a["firefox"], "prefs": prefs_a},
"display_profile": {"file": host_profile["file"], "size": host_profile["size"],
"sha256": host_profile["sha256"], "api": "GetICMProfileW"},
"images": image_files(),
"probe_count": len(out),
"profile_dependent_count": len(dependent),
"profile_dependent": sorted(dependent),
"probes": out,
}
def main(argv):
ap = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("reference", help="run json of the retail default run (a_win_default)")
ap.add_argument("control", help="run json of the force_srgb run (b_win_force_srgb)")
ap.add_argument("--repeat", required=True, help="run json of the repeat of the default run")
ap.add_argument("--host-profile", required=True, help="host_display_profile.json")
ap.add_argument("--source", default="canvas-color/canvas-color-icc-readback",
help="name of the capture the runs come from")
ap.add_argument("--out", default=str(DEFAULT_OUT))
a = ap.parse_args(argv[1:])
def load(p):
return json.loads(Path(p).read_text(encoding="utf-8"))
try:
refs = build(load(a.reference), load(a.control), load(a.repeat),
load(a.host_profile), a.source)
except RefError as e:
print("error: %s" % e, file=sys.stderr)
return 1
Path(a.out).write_text(json.dumps(refs, ensure_ascii=False, indent=1) + "\n",
encoding="utf-8")
print("%d probes (%d depend on the display profile) -> %s"
% (refs["probe_count"], refs["profile_dependent_count"], a.out))
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
+184
View File
@@ -0,0 +1,184 @@
"""Builds tests/data/canvas_text_ref_colors/refs.json from the bytes retail Firefox drew.
The reference of tests/test_canvas_text_colors_and_cleartype_is_windows_e2e.py: coloured
canvas text, and 39 cases (25 of black text on white, 14 coloured) under three ClearType
keys, all measured on retail Firefox 159.0 on Windows with tests/data/canvas_text_ref_colors/
index.html (the 14 coloured cases) and tests/data/canvas_text_ref/index.html (the 25 black
ones). The measuring harness saved, for every case, the RGBA bytes of the canvas
(<name>.rgba) and a <name>.json with its id, width, height and sha256:
<BYTES>/colors/retail/<name>.{json,rgba} the 14 coloured cases, retail's own
ClearType state (the seed's)
<BYTES>/keys/<gamma>_<contrast>/retail/<name>.{json,rgba}
the 39 cases under that key; the case
id of a coloured one is "color:<id>"
python -I scripts/build_canvas_text_colors_refs.py --bytes <BYTES> \
[--keys 1800_100,1400_50,2200_0] [--out tests/data/canvas_text_ref_colors/refs.json]
The repository holds no .rgba: they are 270 kB each. The script hashes an .rgba when the
directory has it (and stops if that is not the sha256 its .json says, or the size is not
width x height x 4); when only the .json is there (a byte file kept only where the engine
differed) it takes the hash the harness wrote. It stops too when the black cases under
1800/100 are not the ones tests/data/canvas_text_ref/refs.json holds for the same ids, or
when the coloured cases under 1800/100 differ from the ones of colors/retail (same machine,
same key: they are one measurement). Standard library only.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import re
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
DATA = ROOT / "tests" / "data" / "canvas_text_ref_colors"
BASE_REFS = ROOT / "tests" / "data" / "canvas_text_ref" / "refs.json"
DEFAULT_KEYS = "1800_100,1400_50,2200_0"
SEED_KEY = "1800_100"
DATE = "2026-11-09"
#: The prefs of the retail profile for the keys (user.js), gamma and contrast per key.
RETAIL_PREFS = {
"gfx.canvas.accelerated": False,
"gfx.font_rendering.cleartype_params.gamma": "<gamma>",
"gfx.font_rendering.cleartype_params.enhanced_contrast": "<contrast>",
"gfx.font_rendering.cleartype_params.cleartype_level": 100,
"gfx.font_rendering.cleartype_params.pixel_structure": 1,
"gfx.font_rendering.cleartype_params.rendering_mode": 0,
}
#: The coloured cases of colors/retail were measured with the machine's own ClearType prefs,
#: and gfx.canvas.accelerated off.
COLORS_RETAIL_PREFS = {"gfx.canvas.accelerated": False}
class BuildError(ValueError):
"""The saved bytes cannot be this reference."""
def colors_of_page(html):
"""[[name, fg, bg], ...] and [sizes] from the measuring page, as the page declares them."""
m = re.search(r"const COLORS = (\[\[.*?\]\]);", html, re.S)
s = re.search(r"const SIZES = (\[[^\]]*\]);", html)
if not m or not s:
raise BuildError("index.html declares no COLORS / SIZES")
return json.loads(m.group(1)), json.loads(s.group(1))
def read_dir(d):
"""{case id: {"width", "height", "sha256"}} of the .json files of one directory."""
d = Path(d)
if not d.is_dir():
raise BuildError("%s is not a directory" % d)
out = {}
for j in sorted(d.glob("*.json")):
m = json.loads(j.read_text(encoding="utf-8"))
sha, w, h = m["sha256"], int(m["w"]), int(m["h"])
rgba = j.with_suffix(".rgba")
if rgba.is_file():
data = rgba.read_bytes()
if len(data) != w * h * 4:
raise BuildError("%s: %d bytes, not %d x %d x 4" % (rgba, len(data), w, h))
got = hashlib.sha256(data).hexdigest()
if got != sha:
raise BuildError("%s: sha256 %s, its json says %s" % (rgba, got, sha))
if not re.fullmatch(r"[0-9a-f]{64}", sha):
raise BuildError("%s: sha256 %r is not 64 hex digits" % (j, sha))
if m["id"] in out:
raise BuildError("%s: case %r twice in %s" % (j.name, m["id"], d))
out[m["id"]] = {"width": w, "height": h, "sha256": sha}
return out
def build(bytes_dir, keys, page_html, base):
colors, sizes = colors_of_page(page_html)
color_ids = ["%s|%s" % (c[0], s) for c in colors for s in sizes]
bytes_dir = Path(bytes_dir)
seed = read_dir(bytes_dir / "colors" / "retail")
if sorted(seed) != sorted(color_ids):
raise BuildError("colors/retail has %s, the page draws %s" % (sorted(seed), sorted(color_ids)))
spec = {"%s|%s" % (c[0], s): {"name": c[0], "fg": c[1], "bg": c[2], "size": s}
for c in colors for s in sizes}
out_colors = {i: {"id": i, **spec[i], **seed[i]} for i in color_ids}
out_keys = {}
for tag in keys:
gamma, contrast = (int(x) for x in tag.split("_"))
cases = read_dir(bytes_dir / "keys" / tag / "retail")
black = {i: v for i, v in cases.items() if not i.startswith("color:")}
col = {i[len("color:"):]: v for i, v in cases.items() if i.startswith("color:")}
if sorted(col) != sorted(color_ids):
raise BuildError("key %s: coloured cases %s, the page draws %s"
% (tag, sorted(col), sorted(color_ids)))
for i in black:
if i not in base["cases"]:
raise BuildError("key %s: %r is not a case of canvas_text_ref" % (tag, i))
out_keys[tag] = {
"gamma": gamma, "contrast": contrast, "count": len(black) + len(col),
"black": {i: {"id": i, **black[i]} for i in sorted(black)},
"colors": {i: {"id": i, **col[i]} for i in color_ids},
}
if SEED_KEY in out_keys:
k = out_keys[SEED_KEY]
for i, v in k["black"].items():
if v["sha256"] != base["cases"][i]["sha256"]:
raise BuildError("%s under %s: %s, canvas_text_ref/refs.json has %s"
% (i, SEED_KEY, v["sha256"], base["cases"][i]["sha256"]))
for i, v in k["colors"].items():
if v["sha256"] != out_colors[i]["sha256"]:
raise BuildError("%s under %s differs from colors/retail: %s vs %s"
% (i, SEED_KEY, v["sha256"], out_colors[i]["sha256"]))
arial = [f for f in base["fonts"] if f["family"] == "Arial"]
if len(arial) != 1:
raise BuildError("canvas_text_ref/refs.json has no single Arial entry")
return {
"test_page": "index.html",
"black_page": "../canvas_text_ref/index.html",
"text": base["text"],
"firefox": base["firefox"],
"canvas": base["canvas"],
"cleartype": base["cleartype"],
"fonts": arial,
"capture": {
"date": DATE,
"origin": "retail Firefox 159.0 (build %s, firefox.exe sha256 %s) on Windows, "
"headless, canvases read back with getImageData; bytes saved by the "
"measuring harness: colors/retail (the 14 coloured cases) and "
"keys/<gamma>_<contrast>/retail (39 cases per key) of the win-asset "
"analysis of 2026-11-09"
% (base["firefox"]["buildid"], base["firefox"]["exe_sha256"]),
"colors_prefs": COLORS_RETAIL_PREFS,
"keys_prefs": RETAIL_PREFS,
},
"colors": {"count": len(out_colors), "cases": out_colors},
"keys": out_keys,
}
def main(argv):
ap = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--bytes", required=True, metavar="DIR",
help="directory with colors/retail and keys/<gamma>_<contrast>/retail")
ap.add_argument("--keys", default=DEFAULT_KEYS,
help="ClearType keys, gamma_contrast, comma separated (default %(default)s)")
ap.add_argument("--out", default=str(DATA / "refs.json"))
a = ap.parse_args(argv[1:])
keys = [k for k in a.keys.split(",") if k]
try:
refs = build(a.bytes, keys, (DATA / "index.html").read_text(encoding="utf-8"),
json.loads(BASE_REFS.read_text(encoding="utf-8")))
except (BuildError, KeyError, ValueError) as e:
print("error: %s" % e, file=sys.stderr)
return 1
Path(a.out).write_text(json.dumps(refs, ensure_ascii=False, indent=1) + "\n",
encoding="utf-8", newline="\n")
print("%d coloured cases, %d keys x %d cases -> %s"
% (refs["colors"]["count"], len(refs["keys"]),
next(iter(refs["keys"].values()))["count"], a.out))
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
+106
View File
@@ -0,0 +1,106 @@
"""Builds tests/data/canvas_text_ref/refs.json, the one reference of the canvas text test.
Two measurements of retail Firefox 159.0 on Windows, made with the same page code, the same
bundled font files and the same machine, are merged by case id:
python -I scripts/build_canvas_text_refs.py <canvas_ref_bundle/refs.json> \
<canvas_ref_ext/refs.json> [--out tests/data/canvas_text_ref/refs.json]
The bundle file has the base cases (no ``gruppo`` field: they become group ``0_base``), the
extension file has the cases of the other groups. A case id that is in both files is kept
once, with the extension's group; the script stops if the two hashes of such a case differ,
or if the two files were not measured on the same Firefox build, with the same ClearType
state and the same font files. Fields that name a file of the measuring machine (the PNG
paths) are dropped: the repository holds no PNG and no font.
"""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
BASE_GROUP = "0_base"
DEFAULT_OUT = Path(__file__).resolve().parents[1] / "tests" / "data" / "canvas_text_ref" / "refs.json"
_DROP = ("png",)
class MergeError(ValueError):
"""The two measurements cannot be one reference."""
def _case(case, group):
out = {k: v for k, v in case.items() if k not in _DROP}
out.setdefault("alpha", True)
out.setdefault("stretch", "normal")
out.setdefault("text", "TEXT")
out["gruppo"] = group
return out
def merge(bundle, ext):
"""One reference from the bundle measurement and the extension measurement."""
for key in ("firefox", "canvas", "cleartype", "text"):
if bundle[key] != ext[key]:
raise MergeError("the two measurements differ in %r: %r vs %r"
% (key, bundle[key], ext[key]))
ext_fonts = {f["bundle_file"]: f for f in ext["fonts"]}
for f in bundle["fonts"]:
other = ext_fonts.get(f["bundle_file"])
if other is None or other["sha256"] != f["sha256"]:
raise MergeError("font %s is not the same file in the two measurements"
% f["bundle_file"])
cases = {}
for cid, c in bundle["cases"].items():
cases[cid] = _case(c, c.get("gruppo") or BASE_GROUP)
for cid, c in ext["cases"].items():
if not c.get("gruppo"):
raise MergeError("extension case %r has no group" % cid)
if cid in cases and cases[cid]["sha256"] != c["sha256"]:
raise MergeError("case %r has two different hashes: %s and %s"
% (cid, cases[cid]["sha256"], c["sha256"]))
cases[cid] = _case(c, c["gruppo"])
groups = {}
for c in cases.values():
groups[c["gruppo"]] = groups.get(c["gruppo"], 0) + 1
status = {**bundle.get("font_load_status", {}), **ext.get("font_load_status", {})}
return {
"test_page": "index.html",
"font_source": "bundle",
"text": bundle["text"],
"firefox": bundle["firefox"],
"canvas": bundle["canvas"],
"cleartype": bundle["cleartype"],
"fonts": ext["fonts"],
"font_load_status": status,
"case_count": len(cases),
"groups": dict(sorted(groups.items())),
"cases": cases,
}
def main(argv):
ap = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("bundle", help="refs.json of the base measurement (canvas_ref_bundle)")
ap.add_argument("ext", help="refs.json of the extension measurement (canvas_ref_ext)")
ap.add_argument("--out", default=str(DEFAULT_OUT))
a = ap.parse_args(argv[1:])
load = lambda p: json.loads(Path(p).read_text(encoding="utf-8"))
try:
refs = merge(load(a.bundle), load(a.ext))
except MergeError as e:
print("error: %s" % e, file=sys.stderr)
return 1
Path(a.out).write_text(json.dumps(refs, ensure_ascii=False, indent=1) + "\n",
encoding="utf-8")
print("%d cases -> %s" % (refs["case_count"], a.out))
for g, n in refs["groups"].items():
print(" %-30s %3d" % (g, n))
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
-620
View File
@@ -1,620 +0,0 @@
#!/usr/bin/env python3
"""A/B oracle: same seed, same bytes, the published engine against the candidate.
A page reads the same values from two engines that differ only by the work of one
release. This runs the host gate's dump (scripts/ci_host_gate.py dump: the page in
scripts/host_gate, whole APIs) twice on the SAME machine, with the same core and the same
wrapper, over the persona seeds (ci/persona-seeds.json, computed by scripts/persona_cover.py
from the prefs the core emits: the `candidate` set, 5 seeds that reach every webgl renderer
and every DPR, or the `final` set, 20 seeds that reach every value of every dimension). Each
seed runs at its OWN DPR (nothing is pinned):
1. with the published engine (firefox-68 by default): its seal and its archive are
downloaded the way the core downloads an engine (the release's seal.json, then
invisible_core.download.ensure_binary under that seal, which checks the sha256 of
the archive against the seal and the engine against the seal);
2. with the candidate binary the gate already holds, under its own seal.
The dump also reads what the host gate's retail comparison leaves alone, the ab. leaves (ci_host_gate.is_ab): ab.poison on every seed (zone, language, colour scheme, a
canary font and the audio context, which scripts/ci_poison_host.py holds to the declared identity on a poisoned host) and, on seeds 0 and 63, the extra visit of every realm and
window a page can make (--ab; ci_host_gate.ab_visit). They are compared like every other leaf; the diag. ones are not.
Then every leaf of every visit is compared. Everything must be equal. The only
differences allowed are the `noise` entries of host_gate/exceptions.json (values that
differ between two launches of one engine) and keys under the diag. prefix (what the
page records about the host). Any other difference is red and is printed with the leaf,
the two values and the seed. It is also red when a visit is missing on one side, or when a
visit compares fewer leaves than MIN_LEAVES says: a page that dumped less than the host gate's
own reference would pass anything.
python ci_ab_oracle.py run <candidate-firefox> --candidate-seal gate.seal.json \\
--leg linux-x86_64 --out ab-oracle [--engine-tag firefox-68] [--seed-set candidate|final] [--shard i/n]
python ci_ab_oracle.py run --published-binary <firefox> --leg linux-x86_64 --out ab-oracle --limit 2 (the A/A alone)
python ci_ab_oracle.py compare ab-oracle [--a-a] [--seed-set ...] [--shard i/n] (again, from the dumps)
--shard i/n (1-based) takes every n-th seed of the set, from the i-th: the final set can be split over n jobs
(more runners, not more browsers per runner). The seed set and the shard of `compare` must be those of the run:
they say which visits were asked for.
THE CONTROL. `run` first dumps the published engine TWICE and compares the two (the A/A): a difference there says the
oracle is broken (what is compared is not stable, or the engine is not repeatable), not that the candidate is wrong. It is
exit 2 and the A/B is not run. Without a candidate (a pull request: the engine under test IS the published one, given with
--published-binary) the A/A is the whole run; with a candidate (the gate's leg) the A/B follows, against the first dump of
the published engine. Exit codes: 0 green, 1 red (a finding), 2 broken control or a run that could not run.
--limit N visits only the first N seeds of the set (the A/A of a pull request, which has a time budget per test).
THE SECOND LAUNCH. The visit of seed 0 (RELAUNCH_SEED) is also launched twice on ONE profile folder (the wrapper's persistent context, the profile a user
keeps between runs): the dump keeps the items of the second launch in that visit under the prefix `relaunch.`, next to the visit's own items (a fresh
profile), so the retail comparison of the host gate is never touched. They are compared apart: the visit must have them on both sides, and as many as the
floor (they are not counted in the visit's own leaves, so a page that dumped less cannot hide behind them). The A/A and the A/B hold them to equality like the rest.
HOW EACH LAUNCH ENDS. Every browser a dump launches (the visits, the two launches of the pair on one profile, the ab visit) is seen by a probe in the dump process
(scripts/ci_crash_evidence.py: it reads the exit code of the browser's parent after the close the launch already makes, and a watcher reads the crash folders while it lives). A
parent that did not end with 0, or whose code was not seen, is a RED line that names the side, the seed, the dpr, the launch and the code, in the A/A and in the A/B alike; a dump
process whose probe wrote nothing is red too. What the launch left is kept in `<out>/crash/<run>/`: the core run through `gdb -batch` with the build ids, the `.extra` and the minidump
names, `said.txt` for what the collectors did not find, and `exits.json` with how every launch ended. This oracle runs no strace (a trace would slow the browser and change the
outcome it observes): the strace tail is the host oracle's.
WHAT A LAUNCH LEAVES, ALWAYS. The probe also saves, for EVERY launch of both engines (and of the A/A), what the browser wrote on stdout and stderr (the core merges them on one pipe) in
`<out>/crash/<run>/stderr/<launch>.txt`, green or not, and the cores written since the launch began (Linux) are run through gdb whatever code the parent ended with: a content process can
die and the parent still end with 0, and then the launch is red and names the core. A launch without a core says where it looked (`core_said` in exits.json). A TAB THAT DIED, or a session lost
during a visit (the core's `cannot find session`, a closed target), is the leaf `crash.tab.<launch>` of that visit, with the error and the step (`.error`, `.step`), and the comparison puts it FIRST:
`TAB CRASH side B seed 12 dpr 1.5 launch visit at step ...`. That leaf alone makes the verdict red; the leaves the dead tab could not read (or that only the other side has) are not listed as a
cascade of `<missing>`: they are counted in that line.
python ci_ab_oracle.py touched BASE_SHA (prints touched=true|false: does a pull request change a file of this oracle; e2e.yml's final-set job reads it)
Writes, in --out: dump-<N>.json and dump-<N>-again.json (the published engine's items, twice), diff-a-a.json (the A/A),
and with a candidate dump-candidate.json and diff.json (the verdict, the compared leaves per visit, every difference).
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import shutil
import subprocess
import sys
import tempfile
import time
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import ci_crash_evidence as crash # noqa: E402
import ci_host_gate as gate # noqa: E402
import persona_cover as personas # noqa: E402
FORMAT = "ab-oracle/1"
#: The engine the candidate is held to: the last one published.
ENGINE_TAG = "firefox-68"
CANDIDATE = "candidate"
#: What the host gate's own reference holds per visit (non-diag leaves at each DPR, today).
#: A visit that compares fewer leaves than this is red. Moves by hand with the reference
#: (tests/test_ab_oracle.py holds the two together). A DPR the reference does not record (the personas
#: also have 1.25) is held to the least of the ones it does.
MIN_LEAVES = {1.0: 16439, 1.5: 16439}
#: The seeds a run visits, from ci/persona-seeds.json: the smallest set that reaches every webgl renderer and every DPR,
#: or the one that reaches every value of every dimension the core declares.
SEED_SETS = ("candidate", "final")
SEED_SET = "candidate"
#: The seed whose visit is also launched twice on one profile folder, and the prefix its second launch's leaves have (scripts/ci_host_gate.py holds it).
RELAUNCH_SEED = 0
RELAUNCH = gate.RELAUNCH
#: A value in diff.json longer than this is replaced by its length and its sha256 (the full value is in the dumps).
CLIP = 400
#: How many differences one run prints; diff.json has all of them.
PRINT_LIMIT = 200
#: What a leaf that is not in a visit reads as.
MISSING = "<missing>"
#: How the verdict names a tab that died (or a session that was lost) during a visit, first of all the lines: the dump records it as the leaf `crash.tab.<launch>`
#: (scripts/ci_crash_evidence.py), and the leaves the dead tab could not read are consequences, not differences.
TAB_CRASH = "TAB CRASH"
#: Said by the run when no visit is dumped within this time (the host gate's own budget is 180 s per page).
DUMP_TIMEOUT_S = 40 * 60
def dump_name(engine_tag: str) -> str:
"""dump-68.json for firefox-68."""
return "dump-%s.json" % engine_tag.rsplit("-", 1)[-1]
# -
# The comparison: two sets of visits, leaf by leaf.
def _clip(value):
text = json.dumps(value, sort_keys=True)
if len(text) <= CLIP:
return value
return {"clipped": text[:CLIP // 2], "len": len(text), "sha256": hashlib.sha256(text.encode()).hexdigest()}
def visit_name(dpr, seed) -> str:
return "dpr%s_seed%d" % (dpr, seed)
def parse_shard(text: str | None) -> tuple:
"""(i, n) from "i/n" (1-based, 1 <= i <= n); None is the whole set, (1, 1)."""
if text is None:
return (1, 1)
try:
i, n = (int(x) for x in text.split("/"))
except ValueError:
raise SystemExit("--shard is i/n, two whole numbers, not %r" % (text,)) from None
if not 1 <= i <= n:
raise SystemExit("--shard is i/n with 1 <= i <= n, not %r" % (text,))
return (i, n)
def select_visits(seed_set: str = SEED_SET, shard: str | None = None, path: Path = personas.DEFAULT_PATH,
limit: int | None = None) -> list:
"""[(dpr, seed)] of the seed set, each seed at its own DPR, the i-th of n shards (every n-th seed from the i-th),
the first `limit` of them when a limit is given."""
if seed_set not in SEED_SETS:
raise SystemExit("--seed-set is one of %s, not %r" % ("/".join(SEED_SETS), seed_set))
i, n = parse_shard(shard)
every = [(dpr, seed) for seed, dpr in personas.load_visits(seed_set, path)]
mine = every[i - 1::n][:limit]
if not mine:
raise SystemExit("shard %d/%d of the %d seeds of %r is empty" % (i, n, len(every), seed_set))
return mine
def relaunch_visits(visits) -> tuple:
"""The visits (dpr, seed) that are launched twice on one profile folder: the ones of RELAUNCH_SEED."""
return tuple(key for key in visits if key[1] == RELAUNCH_SEED)
def _bare(leaf: str) -> str:
"""The leaf without the prefix of the second launch: what exceptions.json names."""
return leaf[len(RELAUNCH):] if leaf.startswith(RELAUNCH) else leaf
def comparable(items: dict) -> dict:
"""The leaves of one visit that are held to equality: everything but diag (a second launch's leaves keep their prefix)."""
return {k: v for k, v in gate.leaves(items).items() if not gate.is_diag(_bare(k))}
def split_launches(leaves: dict) -> tuple:
"""(the leaves of the visit on a fresh profile, the leaves of the second launch)."""
first = {k: v for k, v in leaves.items() if not k.startswith(RELAUNCH)}
return first, {k: v for k, v in leaves.items() if k.startswith(RELAUNCH)}
def tab_crashes(leaves: dict) -> list:
"""[(launch, error, step)] of the tab crashes one side's visit recorded: the leaves `crash.tab.<launch>.error` and `.step` (a second launch's keep their prefix)."""
found: dict = {}
for leaf, value in leaves.items():
bare = _bare(leaf)
if bare.startswith(crash.TAB_PREFIX):
launch, _, field = bare[len(crash.TAB_PREFIX):].partition(".")
found.setdefault((leaf.startswith(RELAUNCH), launch), {})[field or "error"] = value
return [(launch, f.get("error"), f.get("step")) for (_second, launch), f in sorted(found.items())]
def compare_visits(a: dict, b: dict, noise: list, min_leaves: dict | None = None,
expected: tuple | None = None, relaunch: tuple | None = None) -> dict:
"""a and b map (dpr, seed) to the items of that visit (as the dump returns them).
Returns the report: {"verdict": "green"|"red", "problems": [str], "differences":
[{"seed", "dpr", "leaf", "a", "b", "what"}], "compared": {visit: leaves}, "excused": n}.
`noise` is the list of entries of exceptions.json's "noise". `min_leaves` maps a dpr to the
fewest leaves a visit of that dpr may compare; `expected` is the visits both sides must have
(default: every seed at every DPR of the host gate). `relaunch` is the visits that were launched twice on one profile (default: those of RELAUNCH_SEED among the expected ones): each side must have the
second launch's leaves (prefix `relaunch.`) in them, as many as the floor, counted apart (report["relaunch"]), and a side must not have them in a visit that
was not asked to."""
min_leaves = MIN_LEAVES if min_leaves is None else min_leaves
if expected is None:
expected = tuple((dpr, seed) for dpr in gate.DPRS for seed in gate.SEEDS)
relaunch = relaunch_visits(expected) if relaunch is None else relaunch
problems, differences, compared, excused, relaunched = [], [], {}, 0, {}
crashes, cascade = [], {}
for side, visits in (("A", a), ("B", b)):
gone = [visit_name(*k) for k in expected if k not in visits]
if gone:
problems.append("side %s has no dump of %s" % (side, ", ".join(gone)))
stray = [visit_name(*k) for k in sorted(visits) if k not in expected]
if stray:
problems.append("side %s has dumps that were not asked for: %s" % (side, ", ".join(stray)))
for key in expected:
if key not in a or key not in b:
continue
dpr, seed = key
la, lb = comparable(a[key]), comparable(b[key])
count, again, skipped = 0, 0, 0
floor = min_leaves.get(dpr, min(min_leaves.values(), default=0))
died = {"A": tab_crashes(la), "B": tab_crashes(lb)}
crashed = bool(died["A"] or died["B"])
for side, found in died.items():
crashes += [{"side": side, "seed": seed, "dpr": dpr, "launch": launch, "error": error, "step": step} for launch, error, step in found]
for leaf in sorted(set(la) | set(lb)):
if gate.matching(noise, _bare(leaf)):
excused += 1
continue
if _bare(leaf).startswith(crash.TAB_PREFIX):
continue # said as a TAB CRASH, once, with its error and its step: not a difference of values
if crashed and (leaf not in la or leaf not in lb):
skipped += 1 # what the dead tab could not read (or the other side read and this one never got to): a consequence, said once below
continue
second = leaf.startswith(RELAUNCH)
count, again = count + (not second), again + second
va, vb = la.get(leaf, MISSING), lb.get(leaf, MISSING)
if va != vb:
differences.append({"seed": seed, "dpr": dpr, "leaf": leaf, "a": _clip(va), "b": _clip(vb),
"what": gate.describe(va, vb)})
compared[visit_name(dpr, seed)] = count
if skipped:
cascade[visit_name(dpr, seed)] = skipped
if count < floor and not crashed:
problems.append("%s compared %d leaves, fewer than the %d of the host gate's reference: "
"the page dumped less than it should" % (visit_name(dpr, seed), count, floor))
for side, leaves_of in (("A", la), ("B", lb)):
has = len(split_launches(leaves_of)[1])
if key in relaunch and has < floor and not crashed:
problems.append("side %s: the second launch of %s on a reused profile has %d leaves under %s, fewer than the %d of the host gate's "
"reference: it did not run, or the page dumped less than it should" % (side, visit_name(dpr, seed), has, RELAUNCH, floor))
if key not in relaunch and has and not crashed:
problems.append("side %s has the second launch of %s on a reused profile, which was not asked for" % (side, visit_name(dpr, seed)))
if key in relaunch:
relaunched[visit_name(dpr, seed)] = again
tab_lines = ["%s side %s seed %d dpr %s launch %s at step %s: %s%s" % (
TAB_CRASH, c["side"], c["seed"], c["dpr"], c["launch"], c["step"], c["error"],
" (the %d leaves of this visit that the tab could not read, or that only the other side has, are not compared)" % cascade[visit_name(c["dpr"], c["seed"])]
if visit_name(c["dpr"], c["seed"]) in cascade else "") for c in crashes]
problems = tab_lines + problems # the tab crash is the first line of the verdict, before anything it caused
for d in differences:
problems.append("seed %d dpr %s %s: %s" % (d["seed"], d["dpr"], d["leaf"], d["what"]))
return {"verdict": "red" if problems else "green", "problems": problems, "differences": differences, "tab_crashes": crashes,
"compared": compared, "relaunch": relaunched, "excused": excused}
# -
# The files: what a run writes and what compare reads back.
def read_visits(directory: Path) -> dict:
"""(dpr, seed) -> items, from the *.json the host gate's dump wrote in directory."""
visits = {}
for path in sorted(directory.glob("*.json")):
d = json.loads(path.read_text(encoding="utf-8"))
visits[(d["dpr"], d["seed"])] = d["result"]["items"]
return visits
def pack(engine: str, visits: dict) -> dict:
return {"format": FORMAT, "engine": engine,
"visits": [{"dpr": dpr, "seed": seed, "items": visits[(dpr, seed)]} for dpr, seed in sorted(visits)]}
def unpack(document: dict) -> dict:
if document.get("format") != FORMAT:
raise SystemExit("not an %s dump: format %r" % (FORMAT, document.get("format")))
return {(v["dpr"], v["seed"]): v["items"] for v in document["visits"]}
def judge(published: dict, candidate: dict, noise: list, extra_problems=(), expected: tuple | None = None,
relaunch: tuple | None = None) -> dict:
report = compare_visits(published, candidate, noise, expected=expected, relaunch=relaunch)
if extra_problems:
crashed = [x for x in report["problems"] if x.startswith(TAB_CRASH)] # a tab that died is named before the exit code of the dump it left
report["problems"] = crashed + list(extra_problems) + report["problems"][len(crashed):]
report["verdict"] = "red"
return report
def write_json(path: Path, document) -> None:
path.write_text(json.dumps(document, sort_keys=True), encoding="utf-8")
def print_report(report: dict, published: str, other: str = CANDIDATE, title: str = "AB ORACLE") -> None:
n = len(report["differences"])
print("compared %d visits, leaves per visit: %s; %d leaves excused as noise"
% (len(report["compared"]), ", ".join("%s %d" % kv for kv in sorted(report["compared"].items())) or "none",
report["excused"]))
if report.get("relaunch"):
print("second launch on a reused profile, leaves per visit: %s" % ", ".join("%s %d" % kv for kv in sorted(report["relaunch"].items())))
for d in report["differences"][:PRINT_LIMIT]:
print("DIFF seed %d dpr %s leaf %s: %s %s | %s %s" % (d["seed"], d["dpr"], d["leaf"], published,
json.dumps(d["a"], sort_keys=True)[:160],
other, json.dumps(d["b"], sort_keys=True)[:160]))
if n > PRINT_LIMIT:
print("... and %d more differences in diff.json" % (n - PRINT_LIMIT))
for p in report["problems"][:len(report["problems"]) - n]: # the differences are the last n problems
print("FAIL " + p)
print("%s %s: %d differences, %d problems"
% (title, "OK" if report["verdict"] == "green" else "FAILED", n, len(report["problems"])))
# -
# The run: two dumps, one per engine, as subprocesses (the seal a process runs under is read at import).
def fetch_published(tag: str, work: Path) -> tuple:
"""(binary, seal path) of the published engine `tag`, fetched the way the core fetches an engine."""
os.environ.setdefault("INVISIBLE_CORE_AUTOFIX", "off")
os.environ.setdefault("INVISIBLE_CORE_PIN", "allow")
from invisible_core import download
from invisible_core.constants import RELEASE_URL_TEMPLATE
from invisible_core.seal import load_seal
owner, repo = download._parse_owner_repo(RELEASE_URL_TEMPLATE)
seal_path = work / ("seal-%s.json" % tag)
sources = download.release_asset_urls(owner, repo, tag, "seal.json",
RELEASE_URL_TEMPLATE.format(tag=tag, asset="seal.json"))
download._download_file(sources, seal_path)
seal = load_seal(seal_path)
if seal.tag != tag or seal.is_local:
raise SystemExit("the seal of the release %s says tag %r (local: %s)" % (tag, seal.tag, seal.is_local))
print("published engine %s: %s" % (tag, seal.describe()))
sys.stdout.flush()
# the engine store of this fetch only: the dumps that follow run under the environment they were given
before = os.environ.get(download.ENGINE_DIR_ENV)
os.environ[download.ENGINE_DIR_ENV] = str(work / "engines")
try:
binary = download.ensure_binary(seal=seal)
finally:
if before is None:
os.environ.pop(download.ENGINE_DIR_ENV, None)
else:
os.environ[download.ENGINE_DIR_ENV] = before
return str(binary), seal_path
def own_cache_env(env: dict, folder: str, platform: str | None = None) -> dict:
"""`env` with the engine's per-user cache in a folder of this run (Linux: `XDG_CACHE_HOME`), and the wrapper's own cache where it was.
Why. fontconfig names the cache of the bundle's font folder by the md5 of its path, and writes it to the first writable cache folder
it knows, `$XDG_CACHE_HOME/fontconfig` or the legacy `~/.fontconfig`; it reads all of them. Every launch of the published engine of a
job has the same bundle path, so a launch that shares the user's folders leaves the cache of the bundle where a later launch of the
job reads it and finds it warm: tests/test_the_parent_reads_the_bundle_from_fontconfig_s_cache_linux_e2e.py needs its first launch
COLD (its run 44946411675 found `~/.fontconfig/<md5>-le64.cache-9` already there). The oracles' launches use a folder of their own, so
they neither read what an earlier test left nor leave what a later one would read. Both engines of an A/A start from the same empty
cache, which is also what makes their first launch the same.
`XDG_CACHE_HOME` is also where the wrapper looks for its engine (`platformdirs`): `INVISIBLE_PLAYWRIGHT_CACHE_DIR` is pinned to where
that is now, and an engine folder or a cache folder the caller set is kept. Windows has no fontconfig: `env` comes back as it was."""
if (platform or sys.platform) == "win32":
return env
import platformdirs
out = dict(env)
out.setdefault("INVISIBLE_PLAYWRIGHT_CACHE_DIR", platformdirs.user_cache_dir("invisible-playwright"))
out["XDG_CACHE_HOME"] = str(folder)
return out
def dump_with_exits(name: str, exe: str, seal_file, leg: str, visits, target: Path, out: Path) -> tuple:
"""The dump of one engine run as `run_dump` makes it, with the folder where its probe writes how each browser ended (`<out>/crash/<name>`, named to the dump process by
AB_CRASH_DIR): `(rc or "timeout", the red lines of the launches that did not end with 0, or that nobody saw)`. A dump process whose probe wrote nothing is red: an oracle
that does not see how its browsers end does not see them."""
crash_dir = out / "crash" / name
try:
with crash.environment(**{crash.CRASH_DIR_ENV: crash_dir}):
rc = run_dump(exe, Path(seal_file) if seal_file else None, leg, target, visits)
except subprocess.TimeoutExpired:
rc = "timeout"
return rc, crash.exits_of_run(crash_dir, name, windows=leg.startswith("win"), needed=(rc == 0))
def run_dump(binary: str, seal: Path | None, leg: str, out: Path, visits: list | None = None) -> int:
"""The host gate's dump of `visits` ([(dpr, seed)], each seed at its own DPR) as a subprocess; None is the host gate's own grid."""
env = dict(os.environ, INVISIBLE_CORE_AUTOFIX="off", INVISIBLE_CORE_PIN="allow")
if seal is not None: # None: the engine runs under the seal of the core it is launched with (a pull request's published engine)
env["INVISIBLE_SEAL_FILE"] = str(seal)
for name in ("MOZ_LOG", "MOZ_LOG_FILE"): # the e2e legs log the engine; a dump runs as the host gate's does
env.pop(name, None)
cmd = [sys.executable, str(Path(gate.__file__)), "dump", binary, "--leg", leg, "--out", str(out)]
if visits is not None:
if relaunch_visits(visits):
cmd += ["--relaunch-seed", str(RELAUNCH_SEED)]
cmd += ["--no-pin", "--ab"] + [a for dpr, seed in visits for a in ("--visit", "%d:%s" % (seed, dpr))]
with tempfile.TemporaryDirectory(prefix="ab-oracle-cache-") as cache:
return subprocess.run(cmd, env=own_cache_env(env, cache), timeout=DUMP_TIMEOUT_S).returncode
def run(candidate: str, candidate_seal: Path, leg: str, out: Path, engine_tag: str,
published: tuple | None = None, visits: list | None = None) -> int:
"""`visits` is [(dpr, seed)] (default: the candidate set of the persona seeds, each at its own DPR)."""
visits = select_visits() if visits is None else visits
out.mkdir(parents=True, exist_ok=True)
work = Path(tempfile.mkdtemp(prefix="ab-oracle-"))
started = time.time()
problems, dumps = [], {}
try:
binary, seal = published or fetch_published(engine_tag, work)
for name, exe, seal_file in ((engine_tag, binary, seal), (CANDIDATE, candidate, candidate_seal)):
target = work / name
print("=== dump with %s: %s (seal %s), seeds %s"
% (name, exe, seal_file, " ".join("%d@%s" % (seed, dpr) for dpr, seed in visits)))
sys.stdout.flush()
rc, exits = dump_with_exits(name, exe, seal_file, leg, visits, target, out)
if rc != 0:
problems.append("the dump with %s ended with %s" % (name, rc))
problems += exits
dumps[name] = read_visits(target) if target.is_dir() else {}
write_json(out / (dump_name(engine_tag) if name == engine_tag else "dump-%s.json" % CANDIDATE),
pack(name, dumps[name]))
except SystemExit:
raise
except Exception as e: # noqa: BLE001 - a run that could not get its engine is red and says why
problems.append("%s: %s" % (type(e).__name__, str(e)[:500]))
for name in (engine_tag, CANDIDATE):
dumps.setdefault(name, {})
finally:
shutil.rmtree(work, ignore_errors=True)
noise = gate.load_exceptions().get("noise", [])
report = judge(dumps[engine_tag], dumps[CANDIDATE], noise, problems, expected=tuple(visits))
report.update(format=FORMAT, engine=engine_tag, leg=leg, seconds=round(time.time() - started),
visits=["%d@%s" % (seed, dpr) for dpr, seed in visits])
write_json(out / "diff.json", report)
print_report(report, engine_tag)
return 0 if report["verdict"] == "green" else 1
def again_name(engine_tag: str) -> str:
"""dump-68-again.json for firefox-68: the second dump of the published engine, the A/A's other side."""
return dump_name(engine_tag)[:-len(".json")] + "-again.json"
def _dump_visits(name: str, exe: str, seal_file, leg: str, visits: list, work: Path, out: Path, file_name: str) -> tuple:
"""One engine's dump of `visits`: ({(dpr, seed): items}, problems); the packed dump is written to out/file_name."""
target = work / name
print("=== dump with %s: %s (seal %s), seeds %s"
% (name, exe, seal_file or "of the core", " ".join("%d@%s" % (seed, dpr) for dpr, seed in visits)))
sys.stdout.flush()
rc, exits = dump_with_exits(name, exe, seal_file, leg, visits, target, out)
problems = ([] if rc == 0 else ["the dump with %s ended with %s" % (name, rc)]) + exits
dumped = read_visits(target) if target.is_dir() else {}
write_json(out / file_name, pack(name, dumped))
return dumped, problems
def run_ab(leg: str, out: Path, engine_tag: str, published: tuple | None = None, candidate: str | None = None,
candidate_seal: Path | None = None, visits: list | None = None) -> int:
"""The A/A (the published engine twice), then, with a candidate, the A/B against the first dump. 0 green, 1 a finding,
2 a broken control (the A/A differs, or a dump of it did not run: the A/B is not run) .
`published` is (binary, seal or None); without it the engine is fetched the way the core fetches one."""
visits = select_visits() if visits is None else visits
expected = tuple(visits)
out.mkdir(parents=True, exist_ok=True)
work = Path(tempfile.mkdtemp(prefix="ab-oracle-"))
started = time.time()
noise = gate.load_exceptions().get("noise", [])
asked = ["%d@%s" % (seed, dpr) for dpr, seed in visits]
try:
try:
binary, seal = published or fetch_published(engine_tag, work)
first, p1 = _dump_visits(engine_tag, binary, seal, leg, visits, work, out, dump_name(engine_tag))
again, p2 = _dump_visits(engine_tag + "-again", binary, seal, leg, visits, work, out, again_name(engine_tag))
problems = p1 + p2
except SystemExit:
raise
except Exception as e: # noqa: BLE001 - a run that could not get its engine is red and says why
first, again, problems = {}, {}, ["%s: %s" % (type(e).__name__, str(e)[:500])]
control = judge(first, again, noise, problems, expected=expected)
control.update(format=FORMAT, engine=engine_tag, leg=leg, control=True, seconds=round(time.time() - started), visits=asked)
write_json(out / "diff-a-a.json", control)
print_report(control, engine_tag, engine_tag + "-again", "AB ORACLE A/A")
if control["verdict"] != "green":
print("BROKEN CONTROL: the published engine differs from itself (or did not run twice), so what is compared is not stable: "
"the A/B is not run, and the candidate is not judged")
return 2
if candidate is None:
return 0
cand, pc = _dump_visits(CANDIDATE, candidate, candidate_seal, leg, visits, work, out, "dump-%s.json" % CANDIDATE)
report = judge(first, cand, noise, pc, expected=expected)
report.update(format=FORMAT, engine=engine_tag, leg=leg, seconds=round(time.time() - started), visits=asked)
write_json(out / "diff.json", report)
print_report(report, engine_tag)
return 0 if report["verdict"] == "green" else 1
finally:
shutil.rmtree(work, ignore_errors=True)
def clean_name(engine_tag: str) -> str:
"""poison-clean-68.json for firefox-68: the published engine's dump on the CLEAN runner, kept beside the poisoned run's (scripts/ci_poison_host.py)."""
return "poison-clean-" + dump_name(engine_tag)[len("dump-"):]
def run_clean(leg: str, out: Path, engine_tag: str, visits: list, published: tuple | None = None) -> int:
"""The published engine's dump of `visits` on this machine, written to out/clean_name(engine_tag), before the poison is applied. It judges nothing: 0
when it dumped, 1 when it did not (the by-product of the poisoned run is then missing and says so)."""
out.mkdir(parents=True, exist_ok=True)
work = Path(tempfile.mkdtemp(prefix="ab-oracle-clean-"))
try:
binary, seal = published or fetch_published(engine_tag, work)
_, problems = _dump_visits(engine_tag + "-clean", binary, seal, leg, visits, work, out, clean_name(engine_tag))
except SystemExit:
raise
except Exception as e: # noqa: BLE001 - said, not raised: this is a by-product
problems = ["%s: %s" % (type(e).__name__, str(e)[:500])]
finally:
shutil.rmtree(work, ignore_errors=True)
for p in problems:
print("CLEAN DUMP: " + p)
return 1 if problems else 0
def recompare(directory: Path, engine_tag: str, visits: list | None = None, a_a: bool = False) -> int:
visits = select_visits() if visits is None else visits
published = unpack(json.loads((directory / dump_name(engine_tag)).read_text(encoding="utf-8")))
if a_a:
again = unpack(json.loads((directory / again_name(engine_tag)).read_text(encoding="utf-8")))
report = judge(published, again, gate.load_exceptions().get("noise", []), expected=tuple(visits))
report.update(format=FORMAT, engine=engine_tag, control=True, visits=["%d@%s" % (seed, dpr) for dpr, seed in visits])
write_json(directory / "diff-a-a.json", report)
print_report(report, engine_tag, engine_tag + "-again", "AB ORACLE A/A")
return 0 if report["verdict"] == "green" else 2
candidate = unpack(json.loads((directory / ("dump-%s.json" % CANDIDATE)).read_text(encoding="utf-8")))
report = judge(published, candidate, gate.load_exceptions().get("noise", []), expected=tuple(visits))
report.update(format=FORMAT, engine=engine_tag, visits=["%d@%s" % (seed, dpr) for dpr, seed in visits])
write_json(directory / "diff.json", report)
print_report(report, engine_tag)
return 0 if report["verdict"] == "green" else 1
def touched(changed) -> bool:
"""Does a change to `changed` (paths of a pull request) touch a file of this oracle (scripts/ci_ab_pr_seeds.py holds the list)?"""
import ci_ab_pr_seeds as pr
return bool(pr.touches(changed, pr.ORACLES["AB_ORACLE_PR_SEEDS"][2]))
def main(argv=None) -> int:
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
sub = ap.add_subparsers(dest="cmd", required=True)
r = sub.add_parser("run")
r.add_argument("candidate", nargs="?", help="the candidate's firefox binary (none: the A/A of the published engine alone)")
r.add_argument("--candidate-seal", type=Path, default=os.environ.get("INVISIBLE_SEAL_FILE"),
help="the candidate's seal (default: INVISIBLE_SEAL_FILE)")
r.add_argument("--leg", required=True)
r.add_argument("--out", type=Path, required=True)
r.add_argument("--engine-tag", default=ENGINE_TAG)
r.add_argument("--seed-set", choices=SEED_SETS, default=SEED_SET,
help="the persona seeds to visit (ci/persona-seeds.json), each at its own DPR")
r.add_argument("--shard", help="i/n: every n-th seed of the set from the i-th (the final set over n jobs)")
r.add_argument("--limit", type=int, help="visit only the first N seeds of the set (the A/A of a pull request)")
r.add_argument("--published-binary", type=Path, help="use this binary for the published engine instead of fetching it")
r.add_argument("--published-seal", type=Path, help="with --published-binary: the seal of that engine")
t = sub.add_parser("touched", help="touched=true|false: does the pull request (BASE_SHA..HEAD) change a file of this oracle")
t.add_argument("base")
k = sub.add_parser("clean", help="the published engine's dump on this (clean) machine, for the poisoned run's by-product")
k.add_argument("--leg", required=True)
k.add_argument("--out", type=Path, required=True)
k.add_argument("--engine-tag", default=ENGINE_TAG)
k.add_argument("--seed-set", choices=SEED_SETS, default=SEED_SET)
k.add_argument("--shard")
k.add_argument("--limit", type=int)
c = sub.add_parser("compare")
c.add_argument("directory", type=Path)
c.add_argument("--engine-tag", default=ENGINE_TAG)
c.add_argument("--seed-set", choices=SEED_SETS, default=SEED_SET)
c.add_argument("--shard")
c.add_argument("--limit", type=int)
c.add_argument("--a-a", action="store_true", help="compare the two dumps of the published engine (the control)")
args = ap.parse_args(argv)
if args.cmd == "touched":
import ci_ab_pr_seeds as pr
sys.stdout.reconfigure(newline="\n") # the line goes to $GITHUB_OUTPUT: a carriage return would be part of the value
print("touched=%s" % ("true" if touched(pr.changed_files(args.base)) else "false"))
return 0
if args.cmd == "clean":
return run_clean(args.leg, args.out, args.engine_tag, select_visits(args.seed_set, args.shard, limit=args.limit))
if args.cmd == "compare":
return recompare(args.directory, args.engine_tag, select_visits(args.seed_set, args.shard, limit=args.limit), args.a_a)
if args.published_seal and not args.published_binary:
ap.error("--published-seal goes with --published-binary")
if args.candidate:
if not args.candidate_seal:
ap.error("--candidate-seal (or INVISIBLE_SEAL_FILE) is required: the candidate runs under its own seal")
if args.published_binary and not args.published_seal:
ap.error("--published-binary and --published-seal go together when there is a candidate")
elif not args.published_binary:
ap.error("a candidate, or --published-binary (the A/A of the published engine alone)")
given = (str(args.published_binary), args.published_seal) if args.published_binary else None
return run_ab(args.leg, args.out, args.engine_tag, given, args.candidate,
Path(args.candidate_seal) if args.candidate else None, select_visits(args.seed_set, args.shard, limit=args.limit))
if __name__ == "__main__":
sys.exit(main())
-93
View File
@@ -1,93 +0,0 @@
#!/usr/bin/env python3
"""How many persona seeds the A/A of each oracle visits on a pull request.
The page, network and host oracles run their A/A (the published engine against itself) on a pull request, where a test has a time budget: a few seeds. The A/A is
the control that every A/B verdict rests on, so when the pull request changes the code or the data of an oracle, its A/A runs on every seed of the `candidate` set
of ci/persona-seeds.json (the seeds the gate's leg runs), not on the first few: a change that makes the control unstable on one seed is found on the pull request.
`e2e.yml` runs this once per job, on a pull request, with the base commit of the pull request:
python scripts/ci_ab_pr_seeds.py "$BASE_SHA" >> "$GITHUB_ENV"
It fetches that commit (the checkout is shallow), lists the files the pull request changed (`git diff --name-only <base> HEAD`: HEAD is the merge commit the
runner checks out, so this is exactly what the pull request changes), and prints one `VARIABLE=N` line per oracle: N is every seed of the set when a file of the
oracle (ORACLES below, with what it shares with the others) is in the list, else the oracle's default. The tests read the variable with `pr_seed_count`; without it
(a push to main, a manual run) they use the default.
"""
from __future__ import annotations
import fnmatch
import json
import os
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
#: What every oracle depends on: the page oracle's driver (the others use its fetch of the published engine and its cache folder), the recorder of how a launch ended, this file and the seeds.
SHARED = ("scripts/ci_ab_oracle.py", "scripts/ci_crash_evidence.py", "scripts/ci_ab_pr_seeds.py", "scripts/persona_cover.py", "ci/persona-seeds.json")
#: variable -> (oracle, seeds by default on a pull request that does not touch it, the files of the oracle: exact paths or fnmatch patterns).
ORACLES = {
"AB_ORACLE_PR_SEEDS": ("page", 2, SHARED + ("scripts/ci_host_gate.py", "scripts/ci_poison_host.py", "scripts/host_gate/*", "tests/test_ab_oracle*", "tests/test_ci_host_gate*",
"tests/test_ci_poison_host.py")),
"AB_NETWORK_PR_SEEDS": ("network", 1, SHARED + ("scripts/ci_ab_network.py", "ci/ab-network-volatile.json", "tests/test_ab_network*")),
"AB_HOST_PR_SEEDS": ("host", 2, SHARED + ("scripts/ci_ab_host.py", "tests/_strace_stand_in.py", "ci/ab-host-expected.json", "tests/test_ab_host*")),
}
FALLBACK_SEEDS = 5
def candidate_seed_count() -> int:
"""How many seeds the `candidate` set of ci/persona-seeds.json has (5 when the file cannot be read)."""
try:
seeds = json.loads((ROOT / "ci" / "persona-seeds.json").read_text(encoding="utf-8")).get("candidate")
return len(seeds) if seeds else FALLBACK_SEEDS
except (OSError, ValueError, AttributeError):
return FALLBACK_SEEDS
def touches(changed, patterns) -> list:
"""The changed files that are one of `patterns` (exact paths or fnmatch patterns, `/` separated)."""
return sorted(p for p in changed if any(fnmatch.fnmatchcase(p, pattern) for pattern in patterns))
def pr_seed_counts(changed, every: int | None = None) -> dict:
"""{variable: how many seeds} for a pull request that changed `changed`: every seed for an oracle whose own files are in it, else its default."""
every = candidate_seed_count() if every is None else every
return {variable: (every if touches(changed, files) else default) for variable, (_name, default, files) in ORACLES.items()}
def pr_seed_count(variable: str, default: int, environ=None) -> int:
"""What a test reads: the number in `variable` (set by the step of e2e.yml), else `default`. A value that is not a whole number of at least 1 is an error."""
raw = (os.environ if environ is None else environ).get(variable, "").strip()
if not raw:
return default
if not raw.isdigit() or int(raw) < 1:
raise ValueError("%s=%r: the number of seeds is a whole number of at least 1" % (variable, raw))
return int(raw)
def changed_files(base: str, run=subprocess.run) -> list:
"""The files that differ between the base commit of the pull request and HEAD (the merge commit of the checkout)."""
run(["git", "fetch", "--no-tags", "--depth=1", "origin", base], check=True, capture_output=True, text=True)
done = run(["git", "diff", "--name-only", base, "HEAD"], check=True, capture_output=True, text=True)
return [line.strip() for line in done.stdout.splitlines() if line.strip()]
def main(argv=None) -> int:
args = sys.argv[1:] if argv is None else argv
if len(args) != 1:
print("usage: ci_ab_pr_seeds.py BASE_SHA", file=sys.stderr)
return 2
sys.stdout.reconfigure(newline="\n") # the lines go to $GITHUB_ENV: a carriage return would be part of the value
changed = changed_files(args[0])
counts = pr_seed_counts(changed)
for variable, (name, default, files) in ORACLES.items():
hit = touches(changed, files)
print("%s oracle: %d seeds (%s)" % (name, counts[variable], ("its files changed: " + ", ".join(hit[:6])) if hit else "default %d" % default),
file=sys.stderr)
print("%s=%d" % (variable, counts[variable]))
return 0
if __name__ == "__main__":
sys.exit(main())
-989
View File
@@ -1,989 +0,0 @@
#!/usr/bin/env python3
"""A browser that ended with a code other than 0 is RED in every oracle, and what it left is saved (one place, used by the page, network and host oracles).
The three A/B oracles (scripts/ci_ab_oracle.py, scripts/ci_ab_network.py, scripts/ci_ab_host.py) launch many browsers and used to look at how each one ended only as
evidence: run 45030727459 had a firefox-68 parent die with -11 (SIGSEGV) in a normal close of 2.3 s, and nothing was kept to find out why. Now:
* `exit_problem`: the exit code of the root (parent) process of a launch is 0 or the launch is a verdict line that names the seed, the run, the launch and the code.
A launch whose code was not seen is red too (an oracle that does not see how its browsers end does not see them).
* `collect`: for a launch that did not end with 0, on Linux the last 100 strace lines and the lines of the fatal signals of the whole log (the host oracle's
trace; the page and network oracles run no strace, and say so), the core run through `gdb -batch` (`thread apply all bt`, the MOZ_CRASH reason, `info
sharedlibrary`) with the build ids of the binary and of the core, and the crash reporter's `.extra` and the minidump names; on Windows the `.extra` files and the
minidump list. Whatever a collector does not find is SAID (`said`), never left silent.
* `LaunchProbe`: the observer the page and network oracles use. They launch through the wrapper, which keeps the browser's process inside the core's `Connection`;
the probe wraps `Connection.__init__` and `Connection.close` (it reads the code after the close the launch already makes, and a watcher thread of the same
crash folders that the host oracle's launches read too), so nothing about the launch changes: same environment, same prefs, same durations, same launch count.
Three more things the probe keeps, in EVERY launch and not only in a bad one:
* what the browser wrote (`stderr/<launch>.txt` in the crash folder): the core reads the browser's stdout and stderr (one pipe) through `ProcessOutput`, one reader for the whole life of
the process; the probe puts a tee in front of that reader, so the bytes are the ones the reader gets, the whole output and not the last 200 lines the core keeps, and the browser
cannot tell. A launch whose output could not be tee'd says so (`stderr_said`), and that is red;
* the cores written since the launch began (Linux): a core of a content process or of the parent goes through gdb whatever the code of the parent was (a tab can die and the parent
end with 0); a launch with a core, or with a minidump, whose parent ended with 0 is red, and a launch with none says where it looked (`core_said`);
* a tab that died is not here: it is the dump's leaf `crash.tab.<launch>` (`tab_lost`, `tab_crash_item`), which the page oracle's comparison puts first.
A probe never changes the outcome it observes: nothing here sets an environment variable of the browser, a pref, a crash reporter option or a working directory.
Cores are enabled the one way that cannot reach a launch that does not crash: the soft core limit of the oracle's own process is raised to the hard one (a child
inherits it), and where the kernel writes the core is the job's `kernel.core_pattern` (`INVPW_CORE_DIR` names that folder).
"""
from __future__ import annotations
import contextlib
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
import threading
import time
from pathlib import Path
FORMAT = "launch-exits/1"
#: The folder the job points the kernel's core pattern at (`sudo sysctl kernel.core_pattern=$INVPW_CORE_DIR/core.%e.%p.%t`).
CORE_DIR_ENV = "INVPW_CORE_DIR"
#: Where an oracle's launch probe writes what it saw (a folder of the oracle's artifact), named by the oracle that starts the run process.
CRASH_DIR_ENV = "AB_CRASH_DIR"
#: Where the probe saves what each browser wrote (a folder of the crash folder), and the most of it one launch keeps (the core's own reader keeps 200 lines; a launch writes a few KB).
STDERR_DIR = "stderr"
STDERR_LIMIT = 4 * 1024 * 1024
#: The prefix of the leaf a dump records when the tab of a visit died or its session was lost, and what says it (the lowercased text of the error: the core's `cannot find session`,
#: the client's `Target closed` / `has been closed`, a closed pipe, the page's own `crashed`).
TAB_PREFIX = "crash.tab."
TAB_LOST = ("cannot find session", "target closed", "targetclosederror", "session closed", "has been closed", "pipe is closed", "pipe closed", "page crashed", "tab crashed")
STRACE_TAIL_LINES = 100
SIGNAL_LINES = 20
#: The gdb commands: every thread's stack, the reason MOZ_CRASH wrote, the libraries the core mapped.
GDB_COMMANDS = ("thread apply all bt", "x/s *(char**)&gMozCrashReason", "info sharedlibrary")
GDB_LIMIT = 400_000
CORE_LIMIT = 3
#: The exit code of Linux processes that a signal ended is the negative of its number (Python's `Popen`).
SIGNALS = {1: "SIGHUP", 2: "SIGINT", 3: "SIGQUIT", 4: "SIGILL", 5: "SIGTRAP", 6: "SIGABRT", 7: "SIGBUS", 8: "SIGFPE", 9: "SIGKILL", 10: "SIGUSR1", 11: "SIGSEGV",
12: "SIGUSR2", 13: "SIGPIPE", 14: "SIGALRM", 15: "SIGTERM", 31: "SIGSYS"}
#: The NTSTATUS values a Windows crash gives as the exit code of the process.
NTSTATUS = {0xC0000005: "access violation", 0xC0000409: "stack buffer overrun / fast fail", 0xC000013A: "control-C", 0x80000003: "breakpoint",
0xC0000374: "heap corruption", 0xC00000FD: "stack overflow", 0xC000001D: "illegal instruction", 0xC0000094: "integer divide by zero"}
_FATAL = re.compile(r"^\d+\s+--- SIG(?:SEGV|BUS|ABRT|ILL|FPE|SYS|TRAP|TERM|INT|QUIT|HUP)\b")
#: A line of the strace log that is a signal delivered (`1234 --- SIGCHLD {...} ---`): never data of the comparison.
SIGNAL_LINE = re.compile(r"^\d+\s+--- SIG")
# -
# The verdict line.
def describe_exit(code, windows: bool | None = None) -> str:
"""`-11 (SIGSEGV)`, `0xC0000005 (access violation)`, `1`, or what it is when the code was not seen."""
if code is None:
return "no code (the exit code was not seen)"
windows = (sys.platform == "win32") if windows is None else windows
if windows and (code < 0 or code >= 0x80000000):
value = code & 0xFFFFFFFF
name = NTSTATUS.get(value)
return "0x%08X (%s)" % (value, name) if name else "0x%08X" % value
if code < 0:
return "%d (%s)" % (code, SIGNALS.get(-code, "signal %d" % -code))
return str(code)
def tab_lost(error) -> bool:
"""Does this error (an exception, or its text) say that the tab died or the session was lost? The dump records that as a leaf of its own (`tab_crash_item`) and goes on."""
text = ("%s: %s" % (type(error).__name__, error)) if isinstance(error, BaseException) else str(error)
text = text.lower()
return any(word in text for word in TAB_LOST)
def tab_crash_item(launch: str, step: str, error) -> dict:
"""The item a dump adds to a visit whose tab died: `{"crash.tab.<launch>": {"error": ..., "step": ...}}`, the error text and the step of the visit it came in."""
text = ("%s: %s" % (type(error).__name__, error)) if isinstance(error, BaseException) else str(error)
return {TAB_PREFIX + launch: {"error": text[:300], "step": str(step)[:200]}}
#: The order the parts of a launch's name are told in (a JSON file writes its keys sorted).
LABEL_ORDER = ("seed", "dpr", "launch")
def side_of(label: str) -> str:
"""The side of a run in the A/A and the A/B: the published engine is A, its second run and the candidate are B."""
label = str(label)
return "B" if label.endswith("-again") or label.endswith(" again") or label.startswith("candidate") else "A"
def exit_problem(code, windows: bool | None = None, **who) -> str | None:
"""The red line of a launch that did not end with 0, or None when it did. `who` is what names the launch (run, side, seed, dpr, launch ...)."""
if code == 0:
return None
where = ", ".join("%s %s" % (k.replace("_", " "), v) for k, v in who.items() if v not in (None, ""))
return "the parent process exited with code %s: %s" % (describe_exit(code, windows), where or "launch not named")
def exit_problems(launches, run: str, windows: bool | None = None, side: str | None = None) -> list:
"""The red lines of the launches a probe recorded (`LaunchProbe.launches`, or the `launches` of an exits file) for the run `run`."""
out = []
for launch in launches or []:
who = {"run": run, "side": side or side_of(run)}
label = launch.get("label") or {}
who.update({k: label[k] for k in sorted(label, key=lambda k: (LABEL_ORDER.index(k) if k in LABEL_ORDER else len(LABEL_ORDER), k))})
who["launch number"] = launch.get("n")
line = exit_problem(launch.get("returncode"), windows, **who)
if line:
if launch.get("evidence"):
line += " (evidence: %s)" % launch["evidence"]
out.append(line)
elif launch.get("cores") or launch.get("dmp"):
# the parent ended with 0 and a process of the browser left a core or a minidump: a content process died (the parent does not say so)
line = "a process of the browser crashed while the parent ended with 0: %s left %s" % (
", ".join("%s %s" % kv for kv in who.items() if kv[1] not in (None, "")),
" and ".join(x for x in ("core " + ", ".join(launch["cores"]) if launch.get("cores") else "", "minidump " + ", ".join(launch["dmp"]) if launch.get("dmp") else "") if x))
if launch.get("evidence"):
line += " (evidence: %s)" % launch["evidence"]
out.append(line)
return out
def parent_exit_problems(lifecycle, root_code, **who) -> list:
"""Windows (and strace, which names it too): the exit of a process of the kind `parent` that the lifecycle says was not `exited 0`, when the root's own code did not
say it (the process the core spawns may be a launcher stub that exits by itself)."""
if root_code not in (0, None):
return []
out = []
for e in lifecycle or []:
if e.get("event") == "end" and e.get("kind") == "parent" and e.get("how") not in ("exited 0", "exited 0 "):
out.append("the process of the kind parent ended with `%s` though the root's code was %s: %s"
% (e.get("how"), "0" if root_code == 0 else "not seen", ", ".join("%s %s" % kv for kv in who.items() if kv[1] not in (None, ""))))
return out
# -
# What a crash leaves: the folders, the files, the cores (the collectors that scripts/ci_ab_host.py and the probe's launches share live here).
def crash_report_dirs(profile_dir, windows: bool) -> list:
"""The folders a crash leaves its `.dmp` and `.extra` in: the profile's `minidumps` and the `Crash Reports/pending` of the user's application data."""
dirs = [Path(profile_dir) / "minidumps"] if profile_dir else []
if windows:
base = os.environ.get("APPDATA")
if base:
dirs.append(Path(base) / "Mozilla" / "Firefox" / "Crash Reports" / "pending")
else:
home = Path(os.path.expanduser("~"))
dirs += [home / ".config" / "mozilla" / "firefox" / "Crash Reports" / "pending", home / ".mozilla" / "firefox" / "Crash Reports" / "pending"]
return dirs
def scan_crash_files(dirs, seen: dict) -> None:
"""Adds to `seen` ({path: {"name", "dir", "size", "content"}}) every `.dmp` and `.extra` of `dirs`: a `.extra` is read at once, as the profile is deleted when the
launch ends, and again while its size keeps changing (a file seen half written)."""
for folder in dirs:
try:
entries = list(Path(folder).iterdir())
except OSError:
continue
for entry in entries:
if entry.suffix not in (".dmp", ".extra"):
continue
try:
size = entry.stat().st_size
if str(entry) in seen and seen[str(entry)]["size"] == size:
continue
item = {"name": entry.name, "dir": str(entry.parent), "size": size}
if entry.suffix == ".extra":
item["content"] = entry.read_text(encoding="utf-8", errors="replace")[:20000]
except OSError:
continue
seen[str(entry)] = item
class CrashWatcher:
"""A thread that looks at the crash folders while the launch lives, so that what a crash leaves is read before the launch deletes its profile.
`ignore` is a set of paths that were there before the launch (the user's `Crash Reports/pending` keeps reports of earlier crashes): they are not this launch's."""
def __init__(self, dirs_fn, period: float = 0.25, ignore=()) -> None:
self.dirs_fn, self.period = dirs_fn, period
self.ignore = set(ignore)
self.seen: dict = {}
self.scans = 0
self._halt = threading.Event()
self._thread = threading.Thread(target=self._run, name="ab-crash-watch", daemon=True)
def start(self) -> None:
self._thread.start()
def scan_once(self) -> None:
"""One look at the crash folders (what the thread does every period, and `stop` once more): a file seen empty or half written is read again when its size changes."""
scan_crash_files(self.dirs_fn(), self.seen)
self.scans += 1
def _run(self) -> None:
while not self._halt.is_set():
self.scan_once()
self._halt.wait(self.period)
def stop(self) -> dict:
self._halt.set()
if self._thread.is_alive():
self._thread.join(timeout=10)
self.scan_once()
files = [f for f in self.seen.values() if os.path.join(f["dir"], f["name"]) not in self.ignore]
return {"files": sorted(files, key=lambda f: f["name"]), "scans": self.scans}
def existing_crash_files(dirs) -> set:
"""The paths of the crash files that are there now (what a launch that starts after this look did not make)."""
seen: dict = {}
scan_crash_files(dirs, seen)
return {os.path.join(f["dir"], f["name"]) for f in seen.values()}
def core_dirs(env=None, pattern=None) -> list:
"""The folders a core of this machine can be in: the job's `INVPW_CORE_DIR` and the folder of the kernel's `core_pattern` when that is an absolute path (a pipe to
apport or systemd-coredump leaves no file)."""
env = os.environ if env is None else env
out = []
if env.get(CORE_DIR_ENV):
out.append(Path(env[CORE_DIR_ENV]))
if pattern is None:
pattern = kernel_core_pattern()
if pattern and not pattern.startswith("|") and pattern.startswith("/"):
out.append(Path(pattern).parent)
return out
def kernel_core_pattern():
try:
return Path("/proc/sys/kernel/core_pattern").read_text(encoding="utf-8").strip()
except OSError:
return None
def find_cores(dirs, since=None, slack: float = 5.0) -> list:
"""The `core*` files of `dirs` written at `since` or after (a file of an earlier launch is not this one's), newest first."""
found = []
for folder in dirs:
try:
entries = list(Path(folder).glob("core*"))
except OSError:
continue
for entry in entries:
try:
if entry.is_file() and (since is None or entry.stat().st_mtime >= since - slack):
found.append((entry.stat().st_mtime, entry))
except OSError:
continue
return [p for _t, p in sorted(found, key=lambda x: x[0], reverse=True)]
def core_info(core_dir: Path, binary: str, run=subprocess.run, commands=("bt",), more_dirs=(), since=None, limit: int = 8000, which=None) -> dict:
"""What a Linux core dump of a launch is: the kernel's core pattern (a pipe to apport or systemd-coredump puts no file in `core_dir`), the cores found there (and in
`more_dirs`, written at `since` or after) and what gdb says of each (`gdb -batch` with `commands`, `bt` by default) when gdb is installed."""
pattern = kernel_core_pattern()
cores = sorted(p for p in Path(core_dir).glob("core*") if p.is_file()) if core_dir else []
if more_dirs:
cores += [c for c in find_cores(more_dirs, since) if c not in cores]
out = {"core_pattern": pattern, "cores": [c.name for c in cores], "backtraces": {}}
gdb = (which or shutil.which)("gdb")
for core in cores[:CORE_LIMIT]:
if gdb:
argv = [gdb, "-batch"]
for command in commands:
argv += ["-ex", command]
done = run(argv + [str(binary), str(core)], capture_output=True, text=True, errors="replace", timeout=300)
out["backtraces"][core.name] = (done.stdout + done.stderr)[-limit:]
else:
out["backtraces"][core.name] = "gdb is not installed"
return out
def build_ids(binary: str, core: Path | None, run=subprocess.run, which=None) -> dict:
"""The build ids of the engine: `readelf -n` of the binary and of the `libxul.so` beside it, and `eu-unstrip -n --core` (every module the core mapped, with its id)
when elfutils is installed. A tool that is not there is said."""
which = which or shutil.which
out: dict = {}
readelf, unstrip = which("readelf"), which("eu-unstrip")
here = Path(binary).parent
for name, path in (("binary", Path(binary)), ("libxul", here / "libxul.so")):
if not path.exists():
out[name] = "%s does not exist" % path
elif not readelf:
out[name] = "readelf is not installed"
else:
done = run([readelf, "-n", str(path)], capture_output=True, text=True, errors="replace", timeout=60)
ids = [line.strip() for line in done.stdout.splitlines() if "Build ID" in line]
out[name] = ids[0] if ids else "no build id in %s" % path
if core is not None:
if not unstrip:
out["core"] = "eu-unstrip is not installed"
else:
done = run([unstrip, "-n", "--core", str(core)], capture_output=True, text=True, errors="replace", timeout=120)
out["core"] = (done.stdout + done.stderr)[-GDB_LIMIT:]
return out
def strace_tail(log, n: int = STRACE_TAIL_LINES) -> list:
"""The last `n` lines of a strace log (read from the end: the log of a closed run is tens of megabytes)."""
with open(log, "rb") as f:
f.seek(0, os.SEEK_END)
pos, data = f.tell(), b""
while pos > 0 and data.count(b"\n") <= n:
step = min(65536, pos)
pos -= step
f.seek(pos)
data = f.read(step) + data
return data.decode("utf-8", errors="replace").splitlines()[-n:]
def strace_signals(log, limit: int = SIGNAL_LINES) -> list:
"""`[line number, text]` of the last fatal-signal lines of the whole strace log (`--- SIGSEGV {si_addr=...} ---`): they come before a long tail of syscalls of the
crash reporter, so the last 100 lines may not hold them."""
kept: list = []
with open(log, encoding="utf-8", errors="replace") as f:
for number, line in enumerate(f, 1):
if _FATAL.match(line):
kept.append([number, line.rstrip("\n")])
if len(kept) > limit:
kept.pop(0)
return kept
def collect(code, binary: str, *, strace_log=None, strace_said: str | None = None, watched: dict | None = None, core_folders=(), since=None, windows: bool | None = None,
run=subprocess.run, which=None, cores=None) -> dict:
"""Everything a launch that did not end with 0 (or that left a core or a minidump) left, and what could not be found, said: {"exit", "strace", "cores", "crash_files", "said"}.
`cores` is the list of cores this launch is given (the probe keeps a core for the first launch that finds it); None looks in `core_folders` for those written since `since`."""
windows = (sys.platform == "win32") if windows is None else windows
said: list = []
out: dict = {"exit": {"code": code, "text": describe_exit(code, windows)}}
if windows:
out["strace"] = None
out["cores"] = None
said.append("no strace and no core on Windows: the minidumps and the `.extra` are what a Windows crash leaves")
else:
if strace_log is None:
out["strace"] = None
said.append(strace_said or "this oracle runs no strace (a trace slows the browser and would change the outcome it observes)")
else:
try:
out["strace"] = {"tail": strace_tail(strace_log), "signals": strace_signals(strace_log)}
if not out["strace"]["signals"]:
said.append("the strace log holds no fatal signal line")
except OSError as e:
out["strace"] = None
said.append("the strace log could not be read: %s" % e)
cores = find_cores(core_folders, since) if cores is None else list(cores)
info = {"core_pattern": kernel_core_pattern(), "folders": [str(d) for d in core_folders], "cores": [c.name for c in cores], "backtraces": {}, "build_ids": {}}
if not cores:
said.append("no core file written since the launch began, in %s (core_pattern %s)" % (", ".join(str(d) for d in core_folders) or "no folder", info["core_pattern"]))
info["build_ids"]["binary only (no core)"] = build_ids(binary, None, run, which)
for core in cores[:CORE_LIMIT]:
info["backtraces"][core.name] = gdb_report(binary, core, run, which)
info["build_ids"][core.name] = build_ids(binary, core, run, which)
out["cores"] = info
files = (watched or {}).get("files", [])
out["crash_files"] = {"dmp": [f["name"] for f in files if f["name"].endswith(".dmp")], "extra": [{"name": f["name"], "content": f.get("content", "")} for f in files
if f["name"].endswith(".extra")], "scans": (watched or {}).get("scans")}
if not files:
said.append("no minidump and no `.extra` in the crash folders (the crash reporter may be off, or the process ended before it wrote them)")
out["said"] = said
return out
def gdb_report(binary: str, core: Path, run=subprocess.run, which=None) -> str:
"""`gdb -batch` over a core: every thread's backtrace, the MOZ_CRASH reason and the shared libraries; or the reason it could not be asked."""
gdb = (which or shutil.which)("gdb")
if not gdb:
return "gdb is not installed"
argv = [gdb, "-batch"]
for command in GDB_COMMANDS:
argv += ["-ex", command]
try:
done = run(argv + [str(binary), str(core)], capture_output=True, text=True, errors="replace", timeout=300)
except subprocess.TimeoutExpired:
return "gdb did not finish within 300 s"
return (done.stdout + done.stderr)[:GDB_LIMIT]
def _safe(name: str) -> str:
return re.sub(r"[^A-Za-z0-9._-]+", "_", name)[:80]
def write_crash_files(crash: dict, directory) -> list:
"""The evidence of `collect` as files a person can read in the artifact (`strace-tail.txt`, `strace-signals.txt`, `gdb-<core>.txt`, `build-ids.txt`, `<name>.extra.txt`,
`minidumps.txt`, `said.txt`) and `crash.json`; returns the names written."""
folder = Path(directory)
folder.mkdir(parents=True, exist_ok=True)
written = []
def put(name, text):
(folder / name).write_text(text, encoding="utf-8", newline="\n")
written.append(name)
strace = crash.get("strace")
if strace:
put("strace-tail.txt", "\n".join(strace["tail"]) + "\n")
put("strace-signals.txt", "\n".join("%d: %s" % (n, t) for n, t in strace["signals"]) + "\n")
cores = crash.get("cores")
if cores:
for name, text in cores["backtraces"].items():
put("gdb-%s.txt" % _safe(name), text)
ids = "\n\n".join("%s\n%s" % (name, json.dumps(value, indent=1, sort_keys=True)) for name, value in sorted(cores["build_ids"].items()))
if ids:
put("build-ids.txt", ids + "\n")
files = crash.get("crash_files") or {}
for item in files.get("extra", []):
put("%s.txt" % _safe(item["name"]), item.get("content", "") + "\n")
put("minidumps.txt", "\n".join(files.get("dmp", [])) + ("\n" if files.get("dmp") else ""))
put("said.txt", "\n".join(crash.get("said", [])) + "\n")
put("crash.json", json.dumps(crash, indent=1, sort_keys=True) + "\n")
return written
# -
# The probe of the oracles that launch through the wrapper (the page and network oracles).
def raise_core_limit() -> str:
"""Linux: the soft core limit of this process becomes the hard one (every browser it launches inherits it); what was done, or why not."""
try:
import resource
except ImportError:
return "not Linux: no core limit"
try:
soft, hard = resource.getrlimit(resource.RLIMIT_CORE)
if soft != hard:
resource.setrlimit(resource.RLIMIT_CORE, (hard, hard))
return "RLIMIT_CORE %s" % ("unlimited" if hard == resource.RLIM_INFINITY else hard)
except (OSError, ValueError) as e:
return "RLIMIT_CORE could not be raised: %s" % e
class OutputRecord:
"""What one launch's browser wrote (stdout and stderr: the core merges them on one pipe), kept whole by the tee that sits in front of the core's own reader."""
def __init__(self, n: int, label: dict, started: float) -> None:
self.n, self.label, self.started = n, dict(label), started
self.output = None # the core's ProcessOutput this belongs to (set once it exists)
self.size, self.truncated, self._chunks = 0, False, []
self._lock = threading.Lock()
self.written = None # the file the probe saved it in, relative to the artifact
def add(self, line) -> None:
data = line if isinstance(line, bytes) else str(line).encode("utf-8", "replace")
with self._lock:
if self.size + len(data) > STDERR_LIMIT:
self.truncated = True
return
self._chunks.append(data)
self.size += len(data)
def text(self) -> str:
with self._lock:
return b"".join(self._chunks).decode("utf-8", "replace")
class OutputTee:
"""The stream the core's `ProcessOutput` reads, with every line it reads copied to a record: the same lines in the same order to the same reader, and nothing written to the browser."""
def __init__(self, stream, record: OutputRecord) -> None:
self._stream, self._record = stream, record
def readline(self, *args):
line = self._stream.readline(*args)
if line:
try:
self._record.add(line)
except Exception: # noqa: BLE001 - a probe never breaks a launch
pass
return line
def __getattr__(self, name):
return getattr(self._stream, name)
def core_said(folders, pattern, windows: bool) -> str | None:
"""Where a launch looked for a core and found none (Linux), told so that a missing core is never silent: and, when the job's folder is not where the kernel writes, that a core would not have been seen."""
if windows:
return "Windows: no core (the minidumps and the `.extra` are what a crash leaves)"
where = ", ".join(str(f) for f in folders)
if not where:
return "no core folder to look in: INVPW_CORE_DIR is not set and core_pattern %r is not a path (a core, if one was written, was not seen)" % (pattern,)
said = "no core file written since the launch began, in %s (core_pattern %s)" % (where, pattern)
if os.environ.get(CORE_DIR_ENV) and not (pattern or "").startswith(str(Path(os.environ[CORE_DIR_ENV]))):
said += ": the kernel does not write into INVPW_CORE_DIR, so a core would not have been seen there"
return said
class LaunchProbe:
"""Sees every browser this process launches through the core (`invisible_core.juggler.connection.Connection`): how its parent ended, and what a bad end left.
`install` wraps `Connection.__init__` (the launch has begun: a crash watcher starts) and `Connection.close` (the launch is over: the exit code is read with `poll()`
after the close the launch already makes). The oracle names the launch it is about to make with `set_label` (seed, launch ...)."""
def __init__(self, binary: str, crash_dir=None, windows: bool | None = None, run=subprocess.run, clock=time.time, which=None, folders=None, core_folders=None) -> None:
self.binary = binary
self.core_folders = core_folders
self.crash_dir = Path(crash_dir) if crash_dir else None
self.windows = (sys.platform == "win32") if windows is None else windows
self.run, self.clock, self.which = run, clock, which
self.folders = folders
self.label: dict = {}
self.launches: list = []
self._open: dict = {}
self._lock = threading.Lock()
self._patched = None
self._patched_output = None
self.core_limit = None
#: what the browsers wrote, a record per launch, in the order of their birth; and why no output could be kept, when none could
self.records: list = []
self.stderr_said = None
self.unconnected: list = []
#: the cores a launch has been given: one core is one launch's
self._claimed: set = set()
def set_label(self, **label) -> None:
self.label = dict(label)
def install(self, connection=None, output=None) -> "LaunchProbe":
"""Wraps `Connection.__init__` and `close`, and puts a tee in front of the reader of the browser's output (`ProcessOutput.__init__`). With a `connection` of the caller's (a
stand-in) the output class is the caller's too, or none."""
if connection is None:
from invisible_core.juggler.connection import Connection as connection
from invisible_core.juggler import connection as module
output = getattr(module, "ProcessOutput", None)
probe, original_init, original_close = self, connection.__init__, connection.close
if output is None:
self.stderr_said = "the core has no `ProcessOutput` to put a tee in front of: what the browsers write is not saved"
else:
original_output = output.__init__
def output_init(out, stream, *args, **kwargs):
record = probe._born()
try:
original_output(out, OutputTee(stream, record), *args, **kwargs)
finally:
record.output = out
output_init.__wrapped__ = original_output
output.__init__ = output_init
self._patched_output = (output, original_output)
def __init__(conn, *args, **kwargs):
original_init(conn, *args, **kwargs)
probe._began(conn)
def close(conn, *args, **kwargs):
try:
return original_close(conn, *args, **kwargs)
finally:
probe._ended(conn)
__init__.__wrapped__, close.__wrapped__ = original_init, original_close
connection.__init__, connection.close = __init__, close
self._patched = (connection, original_init, original_close)
if not self.windows:
self.core_limit = raise_core_limit()
return self
def _born(self) -> OutputRecord:
with self._lock:
record = OutputRecord(len(self.records) + 1, self.label, self.clock())
self.records.append(record)
return record
def uninstall(self) -> None:
if self._patched_output:
output, original = self._patched_output
output.__init__ = original
self._patched_output = None
if self._patched:
connection, original_init, original_close = self._patched
connection.__init__, connection.close = original_init, original_close
self._patched = None
def _dirs(self):
if self.folders is not None:
return self.folders() if callable(self.folders) else list(self.folders)
tmp = Path(tempfile.gettempdir())
profiles = []
try:
profiles = sorted(tmp.glob("invisible_profile_*"))
except OSError:
pass
return [p / "minidumps" for p in profiles] + crash_report_dirs(None, self.windows)
def _began(self, conn) -> None:
try:
if getattr(conn, "_process", None) is None:
return
watcher = CrashWatcher(self._dirs, ignore=existing_crash_files(self._dirs()))
watcher.start()
with self._lock:
self._open[id(conn)] = {"label": dict(self.label), "started": self.clock(), "watcher": watcher, "pid": getattr(conn._process, "pid", None)}
except Exception: # noqa: BLE001 - a probe never breaks a launch
pass
def _core_folders(self) -> list:
if self.core_folders is not None:
return list(self.core_folders() if callable(self.core_folders) else self.core_folders)
return list(core_dirs())
def _ended(self, conn) -> None:
with self._lock:
state = self._open.pop(id(conn), None)
if state is None:
return
entry = {"n": len(self.launches) + 1, "label": state["label"], "pid": state["pid"], "returncode": None}
try:
try:
entry["returncode"] = conn._process.poll()
except Exception as e: # noqa: BLE001
entry["probe_error"] = "poll failed: %s" % e
watched = state["watcher"].stop()
folders = [] if self.windows else self._core_folders()
cores = [] if self.windows else [c for c in find_cores(folders, state["started"]) if c.name not in self._claimed]
dmp = [f["name"] for f in watched.get("files", []) if f["name"].endswith(".dmp")]
self._claimed.update(c.name for c in cores)
# EVERY launch: what the browser wrote is saved, and the cores since it began (a content process can die and the parent still end with 0)
self._save_output(conn, entry)
entry["cores"], entry["dmp"] = [c.name for c in cores], dmp
if not cores:
entry["core_said"] = core_said(folders, kernel_core_pattern(), self.windows)
if entry["returncode"] != 0 or cores or dmp:
crash = collect(entry["returncode"], self.binary, watched=watched, core_folders=folders, since=state["started"], windows=self.windows,
run=self.run, which=self.which, cores=cores, strace_said="this oracle runs no strace (a trace slows the browser and would change the outcome it observes)")
if self.crash_dir is not None:
name = "%02d-%s" % (entry["n"], _safe("-".join(str(v) for v in state["label"].values()) or "launch"))
write_crash_files(crash, self.crash_dir / name)
entry["evidence"] = "%s/%s" % (self.crash_dir.name, name)
entry["said"] = crash["said"]
except Exception as e: # noqa: BLE001 - what could not be collected is said
entry["probe_error"] = "%s: %s" % (type(e).__name__, e)
with self._lock:
self.launches.append(entry)
# -
# What the browsers wrote.
def _record_of(self, conn) -> OutputRecord | None:
output = getattr(conn, "output", None)
if output is None:
return None
with self._lock:
return next((r for r in self.records if r.output is output), None)
def _output_file(self, record: OutputRecord, suffix: str = "") -> str:
return "%02d-%s%s.txt" % (record.n, _safe("-".join(str(v) for v in record.label.values()) or "launch"), suffix)
def _write_output(self, record: OutputRecord, code=None, suffix: str = "", said: str = "") -> str | None:
"""The browser's output of one launch, as a file of the artifact: `stderr/<NN>-<launch>.txt`, whatever the launch's end was."""
if self.crash_dir is None:
return None
folder = self.crash_dir / STDERR_DIR
folder.mkdir(parents=True, exist_ok=True)
name = self._output_file(record, suffix)
head = ["# launch %d: %s" % (record.n, ", ".join("%s %s" % kv for kv in record.label.items()) or "not named"),
"# stdout and stderr of the browser, merged on one pipe by the core, as the core's reader got them: %d bytes%s" % (
record.size, " (kept the first %d, then the rest was dropped)" % STDERR_LIMIT if record.truncated else ""),
"# the parent's exit code when this was written: %s" % (describe_exit(code, self.windows) if code is not None else "not seen")]
if said:
head.append("# " + said)
(folder / name).write_text("\n".join(head) + "\n" + record.text(), encoding="utf-8", newline="\n")
record.written = "%s/%s/%s" % (self.crash_dir.name, STDERR_DIR, name)
return record.written
def _save_output(self, conn, entry: dict) -> None:
record = self._record_of(conn)
if record is None:
entry["stderr_said"] = self.stderr_said or "this launch's output was not seen by the tee (the core's `ProcessOutput` of this connection was not made while the probe was installed)"
return
entry["stderr_bytes"] = record.size
path = self._write_output(record, entry["returncode"])
if path:
entry["stderr"] = path
def finish(self) -> None:
"""At the end of the dump: every launch's output once more, after its reader has had the time to read to the end (a launch's file is written when it closes, and again here),
and the output of a launch that never made a connection (it died while starting: the error said what it printed, the file says all of it)."""
for record in list(self.records):
try:
if record.output is not None:
record.output.settle()
except Exception: # noqa: BLE001
pass
connected = next((x for x in self.launches if x.get("stderr") == record.written and record.written), None)
if connected is not None:
self._write_output(record, connected.get("returncode"))
else:
path = self._write_output(record, suffix="-no-connection", said="no connection was made over this launch (it ended while starting, or was still open)")
if path:
self.unconnected.append({"label": record.label, "stderr": path, "bytes": record.size})
def document(self) -> dict:
return {"format": FORMAT, "core_limit": self.core_limit, "stderr_said": self.stderr_said, "launches": list(self.launches), "launches_without_connection": list(self.unconnected)}
def write(self, path=None) -> Path | None:
path = Path(path) if path else (self.crash_dir / "exits.json" if self.crash_dir else None)
if path is None:
return None
try:
self.finish()
except Exception as e: # noqa: BLE001 - said, not raised
self.stderr_said = (self.stderr_said or "") + " finish: %s: %s" % (type(e).__name__, e)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(self.document(), indent=1, sort_keys=True) + "\n", encoding="utf-8", newline="\n")
return path
#: The probe of this process, when its oracle installed one (the page oracle's dump marks the launches it makes through `mark`).
PROBE: LaunchProbe | None = None
def start_probe(binary: str, crash_dir) -> LaunchProbe:
"""Installs the probe of this process (once) for the oracle run that has a crash folder."""
global PROBE
if PROBE is not None:
PROBE.uninstall()
PROBE = LaunchProbe(binary, crash_dir).install()
return PROBE
def stop_probe() -> LaunchProbe | None:
global PROBE
probe, PROBE = PROBE, None
if probe is not None:
probe.uninstall()
return probe
def mark(**label) -> None:
"""Names the launch the oracle is about to make (no probe installed: nothing happens)."""
if PROBE is not None:
PROBE.set_label(**label)
#: The file Glean's database writes on its first write, in the profile of a launch (the folder `db` is born when the database is opened, the file at the first write).
GLEAN_DB = Path("datareporting", "glean", "db", "data.safe.bin")
#: A safety net, not a measurement: the file is there at about +8 s in normal sessions, stock and ours (run 43649596941).
GLEAN_LIMIT_S = 60.0
class GleanNotReady(Exception):
"""Glean had not initialised (no database file in the profile) when the launch was to close."""
def wait_for_glean(profile: Path | None, limit_s: float = GLEAN_LIMIT_S, period: float = 0.25, sleep=time.sleep, now=time.monotonic) -> float:
"""The seconds waited until `GLEAN_DB` exists in `profile`, read again every `period` seconds; `GleanNotReady` when `limit_s` is over or the profile is not known.
Why: a session that closes before Glean has initialised normally makes Glean start inside the shutdown, where its `glean.init` thread can die with the panic "No database
found" and the parent exits with -11 (Mozilla's race, the same in the retail browser; the network A/A, Linux, run 45121964904). The oracles close only after this. It only
reads: nothing is written in the profile, and no preference of the browser changes."""
if profile is None:
raise GleanNotReady("Glean did not initialise in %g s: no %s in the profile of the launch: the profile of the launch is not known (the close would make it start inside the "
"shutdown, where it can crash: run 45121964904)" % (limit_s, GLEAN_DB.as_posix()))
target = Path(profile) / GLEAN_DB
start = now()
while not target.is_file():
waited = now() - start
if waited >= limit_s:
raise GleanNotReady("Glean did not initialise in %g s: no %s in the profile %s (the close would make it start inside the shutdown, where it can crash: run 45121964904)"
% (limit_s, GLEAN_DB.as_posix(), profile))
sleep(period)
return now() - start
#: Where a profile keeps what Glean and the data reporting policy write; its listing before the close is kept with the evidence of the launch (`save_datareporting`).
DATAREPORTING_DIR = "datareporting"
def datareporting_listing(profile) -> list:
"""The lines of the list of `<profile>/datareporting/`: `<path relative to it><TAB><size in bytes>` (a folder ends with `/` and has `-`), sorted. A line that starts with `# `
says what could not be read: the list never raises."""
if profile is None:
return ["# the profile of the launch is not known"]
root = Path(profile) / DATAREPORTING_DIR
if not root.is_dir():
return ["# %s is not a folder in the profile %s" % (DATAREPORTING_DIR, profile)]
rows, problems = [], []
for folder, names, files in os.walk(root, onerror=lambda e: problems.append("# cannot read %s: %s" % (getattr(e, "filename", "?"), e))):
base = Path(folder)
for name in names:
rows.append("%s/\t-" % (base / name).relative_to(root).as_posix())
for name in files:
path = base / name
try:
size = str(path.stat().st_size)
except OSError as exc:
size = "?"
problems.append("# cannot read the size of %s: %s" % (path.relative_to(root).as_posix(), exc))
rows.append("%s\t%s" % (path.relative_to(root).as_posix(), size))
return problems + sorted(rows)
def save_datareporting(profile) -> str | None:
"""Writes the list of `<profile>/datareporting/` of the launch the probe sees now, to `<crash dir>/datareporting/<NN>-<seed>-<launch>.tsv` (NN: the number of the launch, the
one of its file in `stderr/`), and returns the path as the evidence names it. None when no probe is installed or it has no folder. What it could not read is in the file; it
never raises. It is evidence for the next time a launch dies: it is not in the leaves that are compared."""
probe = PROBE
if probe is None or probe.crash_dir is None:
return None
try:
with probe._lock:
records = list(probe.records)
number = getattr(records[-1], "n", len(records)) if records else 0
name = "%02d-%s.tsv" % (number, _safe("-".join(str(v) for v in probe.label.values()) or "launch"))
folder = probe.crash_dir / DATAREPORTING_DIR
folder.mkdir(parents=True, exist_ok=True)
head = ["# launch %d: %s" % (number, ", ".join("%s %s" % kv for kv in probe.label.items()) or "not named"), "# path (relative to datareporting/)<TAB>size in bytes"]
(folder / name).write_text("\n".join(head + datareporting_listing(profile)) + "\n", encoding="utf-8", newline="\n")
return "%s/%s/%s" % (probe.crash_dir.name, DATAREPORTING_DIR, name)
except Exception: # noqa: BLE001 - the evidence never breaks a launch
return None
#: The line an oracle writes when it begins a launch (`launch_line`), and what reads it back (`last_launch`): the process that runs the oracle names, when the oracle does not end in
#: time, the launch that was alive.
LAUNCH_LINE = re.compile(r"^=== launch (?P<launch>\S+) seed (?P<seed>-?\d+) of (?P<label>.*?) began at (?P<at>\S+)\s*$", re.M)
def launch_line(seed, launch: str, label: str, at=None) -> str:
"""`=== launch <launch> seed <seed> of <label> began at <iso, UTC>`: what an oracle prints when `mark` names a launch."""
import datetime
at = at or datetime.datetime.now(datetime.timezone.utc)
return "=== launch %s seed %s of %s began at %s" % (launch, seed, label or "?", at.isoformat(timespec="seconds"))
def last_launch(text: str, now=None) -> dict | None:
"""The last launch line of `text` as {launch, seed, label, at, alive_s} (alive_s: seconds from `at` to `now`, None when `at` does not read), or None when there is none."""
import datetime
found = None
for found in LAUNCH_LINE.finditer(text or ""):
pass
if found is None:
return None
item = found.groupdict()
try:
began = datetime.datetime.fromisoformat(item["at"])
item["alive_s"] = ((now or datetime.datetime.now(datetime.timezone.utc)) - began).total_seconds()
except (ValueError, TypeError):
item["alive_s"] = None
return item
def kill_tree(pid: int) -> None:
"""Kills `pid` and everything that descends from it. With psutil the descendants are listed first (a parent that dies hides its children) and all are killed; without it
Windows has `taskkill /T /F` and Linux the process group (the child was started in its own session, `run_tree`)."""
try:
import psutil
except ImportError:
psutil = None
if psutil is not None:
try:
root = psutil.Process(pid)
victims = root.children(recursive=True) + [root]
except psutil.NoSuchProcess:
victims = []
for victim in victims:
with contextlib.suppress(psutil.Error):
victim.kill()
elif sys.platform == "win32":
subprocess.run(["taskkill", "/PID", str(pid), "/T", "/F"], capture_output=True, check=False)
if sys.platform != "win32":
import signal
with contextlib.suppress(OSError):
os.killpg(pid, signal.SIGKILL) # the group of the child, which is its own (start_new_session)
class TreeRun:
"""What `run_tree` saw: the code (None when the time ran out), the text of stdout and stderr, how long it ran and the launch line the oracle wrote last."""
def __init__(self, returncode, stdout: str, stderr: str, seconds: float, timed_out: bool) -> None:
self.returncode, self.stdout, self.stderr, self.seconds, self.timed_out = returncode, stdout, stderr, seconds, timed_out
self.launch = last_launch(stdout)
def timeout_message(self, who: str, limit_s: float) -> str:
"""The red of a run that did not end: the launch that was alive and for how long."""
if self.launch is None:
alive = "no launch had begun"
else:
alive = "the launch %s of seed %s (%s) was alive for %s s" % (self.launch["launch"], self.launch["seed"], self.launch["label"],
"%d" % self.launch["alive_s"] if self.launch["alive_s"] is not None else "?")
return "%s did not end within %d s: %s; its tree was killed" % (who, limit_s, alive)
def run_tree(command, out_dir, timeout_s: float, env=None, cwd=None, poll: float = 0.2) -> TreeRun:
"""Runs `command` with its output in FILES under `out_dir` (never a pipe), and at `timeout_s` kills the whole tree.
Why not `subprocess.run(capture_output=True, timeout=...)`: at the timeout it kills the child alone. The firefox that the child launched holds the write end of the pipe,
`communicate()` does not return until it exits, and the test went on to a pytest timeout 120 s later (run 45121964904, Windows, job.log 546-557). With files nothing waits
for a grandchild, and `kill_tree` ends them all."""
out_dir = Path(out_dir)
out_dir.mkdir(parents=True, exist_ok=True)
out_path, err_path = out_dir / "run-tree.stdout", out_dir / "run-tree.stderr"
start = time.monotonic()
with open(out_path, "wb") as out, open(err_path, "wb") as err:
extra = {"start_new_session": True} if sys.platform != "win32" else {}
child = subprocess.Popen(list(command), stdout=out, stderr=err, stdin=subprocess.DEVNULL, env=env, cwd=cwd, **extra)
timed_out = False
while child.poll() is None:
if time.monotonic() - start >= timeout_s:
timed_out = True
kill_tree(child.pid)
break
time.sleep(poll)
child.wait()
seconds = time.monotonic() - start
read = lambda path: path.read_bytes().decode("utf-8", "replace") # noqa: E731
return TreeRun(None if timed_out else child.returncode, read(out_path), read(err_path), seconds, timed_out)
def read_exits(path) -> dict | None:
"""The document a probe wrote, or None when there is none."""
try:
document = json.loads(Path(path).read_text(encoding="utf-8"))
except (OSError, ValueError):
return None
return document if document.get("format") == FORMAT else None
def exits_of_run(crash_dir, run: str, windows: bool | None = None, needed: bool = True) -> list:
"""The red lines of the launches a run process recorded in `crash_dir/exits.json`. No file, or no launch in it, is red when the run was to make some: an oracle
that did not see how its browsers ended did not see them."""
if not crash_dir:
return []
document = read_exits(Path(crash_dir) / "exits.json")
if document is None:
return ["the run %s left no record of how its browsers ended (%s/exits.json): the probe did not see them" % (run, Path(crash_dir).name)] if needed else []
if not document["launches"] and needed:
return ["the run %s recorded no launch in %s/exits.json: the probe did not see a browser" % (run, Path(crash_dir).name)]
problems = exit_problems(document["launches"], run, windows)
if document.get("stderr_said"):
problems.append("the run %s could not save what its browsers wrote: %s" % (run, document["stderr_said"]))
for launch in document["launches"]:
if launch.get("stderr_said"):
problems.append("the run %s did not save what the browser of launch %s wrote: %s" % (run, launch.get("n"), launch["stderr_said"]))
return problems
def current_label() -> dict:
"""The launch the oracle named last (`mark`), or {} when no probe is installed."""
return dict(PROBE.label) if PROBE is not None else {}
@contextlib.contextmanager
def environment(**values):
"""`os.environ` with `values` set for the length of the block, put back after it (None removes a variable)."""
old = {k: os.environ.get(k) for k in values}
try:
for k, v in values.items():
if v is None:
os.environ.pop(k, None)
else:
os.environ[k] = str(v)
yield
finally:
for k, v in old.items():
if v is None:
os.environ.pop(k, None)
else:
os.environ[k] = v
+36 -446
View File
@@ -41,10 +41,6 @@ legitimately differ on them and the retail reference does not record them.
compare() skips them by name; dump() prints them into the job log, so a run
tells why without its artifacts being downloaded.
Values under the ab. prefix are read for the A/B oracle: what a page reads of values a host may hold and the engine must never read
(ab.poison, with scripts/ci_poison_host.py) and, on the oracle's visits of seeds 0 and 63, the surfaces of every realm and window a page
can make (ab_visit). compare() skips them by name, as it skips diag.: the A/B compares them between the two engines.
Values under the state. prefix are the window in the states a page can drive
it to: state.normal, state.fullscreen (entered through a real click, a user
gesture) and state.after_fullscreen. The dump measures them after the page is
@@ -60,12 +56,6 @@ the same rule.
python ci_host_gate.py dump <firefox> --leg linux-x86_64 --out dumps/
python ci_host_gate.py compare dumps/ (reference: host_gate/reference/firefox-159)
python ci_host_gate.py compare dumps/ --junit gate-junit/host-gate.xml
--junit writes the verdict as a junit (xunit2) file, one testcase per invariant
(name `invariant:<name>`) and one per other check (`check:<name>`), classname
`scripts.ci_host_gate`: a failed check is a <failure>, a check with nothing to look at
(no dumps) is a <skipped/>, never a pass. The exit status is the gate's own.
"""
from __future__ import annotations
@@ -74,19 +64,11 @@ import base64
import fnmatch
import gzip
import json
import os
import shutil
import sys
import tempfile
import threading
import xml.etree.ElementTree as ET
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import Callable, NamedTuple
from urllib.parse import parse_qs, urlsplit
sys.path.insert(0, str(Path(__file__).resolve().parent))
import ci_crash_evidence as crash # noqa: E402 (how each launch's parent ended: the A/B oracle of the page turns a code other than 0 into a red line)
HERE = Path(__file__).resolve().parent / "host_gate"
PAGE = HERE / "host_gate_page.html"
@@ -106,31 +88,11 @@ ANCHOR = "win-x86_64"
#: Keys under this prefix are information, never compared (see the module docstring).
DIAG = "diag."
#: The items of a visit's SECOND launch on a profile that a first launch already used (`--relaunch-seed`, the A/B oracle's) live under this prefix, next to the
#: items of the visit on a fresh profile: the retail comparison (`compare`) never reads a dump made without that option, and the oracle compares the two
#: sets of leaves apart. The diag. items of the second launch are not kept: what the page records about the host is information, never compared.
RELAUNCH = "relaunch."
def relaunch_items(items: dict) -> dict:
"""The items of a second launch as they are stored in the visit: every key under RELAUNCH, the diag. ones left out."""
return {RELAUNCH + k: v for k, v in items.items() if not is_diag(k)}
def is_diag(key: str) -> bool:
return key.startswith(DIAG)
#: Keys under this prefix are read for the A/B oracle (scripts/ci_ab_oracle.py compares them between two engines on one machine). The host gate
#: does not hold them to either of its properties: the retail reference does not record them, and they are made on the oracle's machine
#: (a poisoned host, a launch in another locale), not on the gate's.
AB = "ab."
def is_ab(key: str) -> bool:
return key.startswith(AB)
def diag_lines(items: dict, before: dict | None = None) -> list:
"""The diag. leaves of one visit as 'key = value' lines; with before (an
earlier visit's diag leaves), only the keys whose value changed."""
@@ -413,363 +375,61 @@ def reference_zone(reference: Path) -> str:
return reference_items(reference, 1.0)["surface.intl"]["DateTimeFormat"]["timeZone"]
def visit_options(firefox: str, seed: int, dpr: float | None, zone: str, profile_dir: str | None = None) -> dict:
def visit_options(firefox: str, seed: int, dpr: float, zone: str) -> dict:
"""The launch of one (dpr, seed) visit. The DPR is PINNED in the persona
(screen.dpr), so the core declares a screen, a work area and a window made
at that scale. It used to be forced through
extra_prefs={"layout.css.devPixelsPerPx": ...} on whatever persona the seed
drew: a 100% persona at 1.5 read innerWidth 1920 inside an outerWidth of
1291 (run 41325657085), an identity no machine has, which the engine now
refuses to start with. With dpr None nothing is pinned: the seed's own persona decides the scale.
With a profile_dir the launch is the wrapper's persistent context on that folder (the profile a user keeps between runs)."""
options = {"seed": seed, "binary_path": firefox, "headless": True, "show_cursor": False,
"locale": "en-US", "timezone": zone}
if dpr is not None:
options["pin"] = {"screen.dpr": dpr}
if profile_dir is not None:
options["profile_dir"] = str(profile_dir)
return options
refuses to start with."""
return {"seed": seed, "binary_path": firefox, "headless": True, "show_cursor": False,
"locale": "en-US", "timezone": zone, "pin": {"screen.dpr": dpr}}
#: Which launch of the dump is being made, for the name of the leaf a tab that died is recorded under (`crash.tab.<launch>`): the visit, the two launches of the pair on one profile,
#: the ab visit. Set with the probe's own label (`_mark`), so that the leaf and the evidence of the launch have one name.
_LAUNCH = ["visit"]
def _mark(seed, dpr, launch: str) -> None:
_LAUNCH[0] = launch
crash.mark(seed=seed, dpr=dpr, launch=launch)
class Steps:
"""Which step of a launch is being made, so that a tab that dies says WHERE: `step` is the last one begun, and `failed` the (step, error) of the last call of `wrap` that raised."""
def __init__(self, step: str = "launch") -> None:
self.step, self.failed = step, None
def wrap(self, name: str, fn: Callable) -> Callable:
def run(*args, **kwargs):
self.step = "%s %s" % (name, ", ".join(str(a)[:60] for a in args))
try:
return fn(*args, **kwargs)
except Exception as e: # noqa: BLE001 - noted, and raised again
self.failed = (self.step, e)
raise
return run
def leaves_of_crash(items: dict) -> dict:
"""{key: {"error", "step"}} of the items that record a tab that died or a session that was lost (also those of the second launch, under RELAUNCH)."""
out = {}
for key, value in items.items():
bare = key[len(RELAUNCH):] if key.startswith(RELAUNCH) else key
if bare.startswith(crash.TAB_PREFIX) and isinstance(value, dict):
out[key] = value
return out
def tab_crash_lines(visit: str, items: dict) -> list:
"""The tab crashes a visit's items hold, as the lines a dump prints."""
return ["TAB CRASH %s %s: %s, at the step %s" % (visit, k, v.get("error"), v.get("step")) for k, v in sorted(leaves_of_crash(items).items())]
def read_page(options: dict, port: int, dpr: float, timeout_ms: int) -> dict:
"""One launch: the page's result (with the states driven when the page answered the format), the browser closed. With a profile_dir in
`options` the wrapper hands back a persistent context, not a browser, and the page is opened in it.
A tab that died, or a session that was lost, while the page was read (the error says it: `crash.tab_lost`) is not an exception of the dump: it is the leaf
`crash.tab.<launch>` of this visit, with the error and the step, and the dump goes on. It used to be a `{"error": ...}` in each state the drive had not reached, which the
comparison read as a cascade of leaves that were missing (candidate run: «cannot find session» in every `state.*`)."""
def dump(firefox: str, leg: str, out: Path, reference: Path, timeout_ms: int = 180_000) -> int:
from invisible_playwright import InvisiblePlaywright
launch, trace, result = _LAUNCH[0], Steps("new page"), None
with InvisiblePlaywright(**options) as browser:
try:
page = browser.new_page() if "profile_dir" in options else browser.new_context().new_page()
# The same budget as the wait below: a cold Windows runner took
# more than goto's default 30 s to reach `load` on the first
# visit (candidate 42410156024), and passed locally 6/6.
trace.step = "goto"
page.goto("http://127.0.0.1:%d/?dpr%s" % (port, dpr), timeout=timeout_ms)
trace.step = "wait for the page's result"
page.wait_for_function("document.title === 'done'", timeout=timeout_ms)
trace.step = "read the page's result"
result = page.evaluate("window.__hostGate")
if result.get("format") == FORMAT:
result["items"].update(drive_states(trace.wrap("evaluate", page.evaluate), trace.wrap("mouse move", page.mouse.move), trace.wrap("mouse click", page.mouse.click)))
if trace.failed is not None and crash.tab_lost(trace.failed[1]):
result["items"].update(crash.tab_crash_item(launch, "states: " + trace.failed[0], trace.failed[1]))
except Exception as e: # noqa: BLE001 - only a tab that died is recorded; anything else is raised as it always was
if not crash.tab_lost(e):
raise
result = {"format": FORMAT, "items": dict(result["items"]) if isinstance(result, dict) and isinstance(result.get("items"), dict) else {}}
result["items"].update(crash.tab_crash_item(launch, trace.step, e))
return result
def second_launch(options: dict, port: int, dpr: float, timeout_ms: int, read=None) -> dict:
"""The page's result of a SECOND launch on a profile the first one used: the same options and the same seed, on a folder of this call
that is made, launched on once (what that launch leaves in it is the point: cookies, cache, prefs.js, the session seed), closed,
launched on again, and removed. A first launch that did not answer the format is what comes back, for the caller to refuse."""
read = read or read_page
profile = tempfile.mkdtemp(prefix="host-gate-profile-")
try:
with_profile = dict(options, profile_dir=profile)
_mark(options.get("seed"), dpr, "relaunch-first")
first = read(with_profile, port, dpr, timeout_ms)
if first.get("format") != FORMAT:
return first
_mark(options.get("seed"), dpr, "relaunch-second")
again = read(with_profile, port, dpr, timeout_ms)
if again.get("format") == FORMAT: # a tab that died in the first launch is not lost because the second one was read
again["items"].update(leaves_of_crash(first.get("items") or {}))
return again
finally:
shutil.rmtree(profile, ignore_errors=True)
def dump(firefox: str, leg: str, out: Path, reference: Path, timeout_ms: int = 180_000,
visits: list | None = None, pin_dpr: bool = True, relaunch_seeds: tuple = (), ab: bool = False) -> int:
"""`visits` is [(dpr, seed)] (default: every seed of SEEDS at every DPR of DPRS, the DPR pinned). With pin_dpr
False the DPR is not pinned: it is the one the seed's persona has, and `dpr` of a visit only names the file and
the page's query. A seed of `relaunch_seeds` is visited once more, launched twice on one profile folder, and the
items of that second launch are added to the visit under RELAUNCH (the visit's own items stay those of a fresh profile).
With `ab`, the seeds of AB_SEEDS also get the extra visit of the A/B oracle (ab_visit): its leaves join the visit's items.
When the oracle that runs this dump names a folder for it (`AB_CRASH_DIR`, scripts/ci_ab_oracle.py), a probe sees how each launch's parent ends (scripts/ci_crash_evidence.py)
and writes it to `exits.json` there, whatever the dump's own result: a launch that did not end with 0 is red in the oracle, and what it left is saved in that folder."""
out.mkdir(parents=True, exist_ok=True)
crash_dir = os.environ.get(crash.CRASH_DIR_ENV)
probe = crash.start_probe(firefox, crash_dir) if crash_dir else None
server = ThreadingHTTPServer(("127.0.0.1", 0), _Page)
threading.Thread(target=server.serve_forever, daemon=True).start()
port = server.server_address[1]
zone = reference_zone(reference)
first_diag = None
try:
for dpr, seed in (visits if visits is not None else [(d, sd) for d in DPRS for sd in SEEDS]):
options = visit_options(firefox, seed, dpr if pin_dpr else None, zone)
_mark(seed, dpr, "visit")
result = read_page(options, port, dpr, timeout_ms)
if result.get("format") != FORMAT:
print("the page answered format %r, not %r" % (result.get("format"), FORMAT))
return 2
if seed in relaunch_seeds:
again = second_launch(options, port, dpr, timeout_ms)
if again.get("format") != FORMAT:
print("the second launch on a reused profile: the page answered format %r, not %r" % (again.get("format"), FORMAT))
for dpr in DPRS:
for seed in SEEDS:
with InvisiblePlaywright(**visit_options(firefox, seed, dpr, zone)) as browser:
page = browser.new_context().new_page()
# The same budget as the wait below: a cold Windows runner took
# more than goto's default 30 s to reach `load` on the first
# visit (candidate 42410156024), and passed locally 6/6.
page.goto("http://127.0.0.1:%d/?dpr%s" % (server.server_address[1], dpr),
timeout=timeout_ms)
page.wait_for_function("document.title === 'done'", timeout=timeout_ms)
result = page.evaluate("window.__hostGate")
if result.get("format") == FORMAT:
result["items"].update(drive_states(page.evaluate, page.mouse.move, page.mouse.click))
if result.get("format") != FORMAT:
print("the page answered format %r, not %r" % (result.get("format"), FORMAT))
return 2
result["items"].update(relaunch_items(again["items"]))
print("second launch of seed %d on a reused profile: %d items" % (seed, len(again["items"])))
if ab and seed in AB_SEEDS:
_mark(seed, dpr, "ab-visit")
result["items"].update(ab_visit(firefox, seed, zone, dpr if pin_dpr else None))
path = out / ("%s_dpr%s_seed%d.json" % (leg, dpr, seed))
path.write_text(json.dumps({"leg": leg, "dpr": dpr, "seed": seed, "result": result}),
encoding="utf-8")
print("dumped %s: %d items" % (path.name, len(result["items"])))
visit = "%s dpr %s seed %d" % (leg, dpr, seed)
for line in tab_crash_lines(visit, result["items"]):
print(line)
for line in diag_report(visit, result["items"], first_diag):
print(line)
# told here too, so the job log says it without the compare step
for line in invariant_lines(visit, result["items"]):
print(line)
sys.stdout.flush()
if first_diag is None:
first_diag = {k: v for k, v in leaves(result["items"]).items() if is_diag(k)}
path = out / ("%s_dpr%s_seed%d.json" % (leg, dpr, seed))
path.write_text(json.dumps({"leg": leg, "dpr": dpr, "seed": seed, "result": result}),
encoding="utf-8")
print("dumped %s: %d items" % (path.name, len(result["items"])))
visit = "%s dpr %s seed %d" % (leg, dpr, seed)
for line in diag_report(visit, result["items"], first_diag):
print(line)
# told here too, so the job log says it without the compare step
for line in invariant_lines(visit, result["items"]):
print(line)
sys.stdout.flush()
if first_diag is None:
first_diag = {k: v for k, v in leaves(result["items"]).items() if is_diag(k)}
finally:
server.shutdown()
if probe is not None:
crash.stop_probe()
probe.write()
for line in crash.exit_problems(probe.launches, "this dump", windows=leg.startswith("win")):
print("EXIT " + line)
return 0
# -
# The A/B oracle's extra visit: every realm and every kind of window a page can make, in a launch of another locale and in a context of yet
# another, on seeds 0 and 63. Its leaves are under ab. (see is_ab): scripts/ci_ab_oracle.py compares them between the two engines. It is a
# separate launch per seed, with its own server and its own functions: nothing here changes how the visits above are made.
#
# Seed 63 is the CONTROL of seed 0: an identity that is not seed 0's must read other values, so the same block on both must differ on at least
# AB_CONTROL_MIN ab. leaves (ab_control). A block that answered the same for two identities would pass an engine that ignores the identity.
AB_DIR = HERE / "ab"
AB_SEEDS = (0, 63)
AB_LAUNCH_LOCALE = "ja-JP"
#: (name of the context, what the context is made with). The first is the launch's own default context (locale ja-JP); the second overrides
#: both the language and the zone.
AB_CONTEXTS = (("launch", {}), ("context", {"locale": "de-DE", "timezone_id": "America/Lima"}))
AB_BUDGET_MS = 240_000
#: How many ab. leaves seed 63 must differ from seed 0 on. PROVISIONAL, from the core's prefs and not from a run: the two personas differ in their core
#: count (12 and 32), their GPU, their screen and their DPR, so hardwareConcurrency alone differs in every realm that must have read (top, cross-site
#: iframe, srcdoc iframe, worker, in each of the 2 contexts: 8 leaves) and the page-read GPU, the screen and the canvas leaves come on top of them.
#: The first run on GitHub prints the measured count (ab_control's line in the oracle's log, and ab-control.json): this number then moves to a safe
#: fraction of it, written here with the run it came from.
AB_CONTROL_MIN = 8
AB_CONTROL_NAMESPACES = tuple("%s%s." % (AB, name) for name, _ in AB_CONTEXTS)
_AB_TYPES = {".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8"}
#: A one-pixel GIF: what /ab/probe answers to a fetch and to an image alike.
_GIF = base64.b64decode("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")
class _AbSite(BaseHTTPRequestHandler):
"""The site of the ab visit: the files of scripts/host_gate/ab, /ab/probe (a pixel) and /ab/seen (the Accept-Language the server saw,
per context, by kind of request: `<Sec-Fetch-Dest>:<path>` -> the sorted distinct values)."""
def _send(self, status, content_type, body):
self.send_response(status)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self):
url = urlsplit(self.path)
ctx = (parse_qs(url.query).get("ctx") or [""])[0]
if url.path == "/ab/seen":
with self.server.ab_lock:
seen = {k: sorted(v) for k, v in self.server.ab_seen.get(ctx, {}).items()}
return self._send(200, "application/json", json.dumps(seen, sort_keys=True).encode())
if url.path.startswith("/ab/"):
with self.server.ab_lock:
kind = "%s:%s" % (self.headers.get("Sec-Fetch-Dest") or "none", url.path)
self.server.ab_seen.setdefault(ctx, {}).setdefault(kind, set()).add(self.headers.get("Accept-Language") or "<none>")
if url.path.startswith("/ab/probe"):
return self._send(200, "image/gif", _GIF)
name = url.path[len("/ab/"):] if url.path.startswith("/ab/") else ""
path = AB_DIR / name
if not name or "/" in name or "\\" in name or path.suffix not in _AB_TYPES or not path.is_file():
return self._send(404, "text/plain", b"not found")
return self._send(200, _AB_TYPES[path.suffix], path.read_bytes())
def log_message(self, *args):
pass
def ab_options(firefox: str, seed: int, dpr: float | None, zone: str) -> dict:
"""The launch of the ab visit: the host gate's own, in ja-JP."""
options = {"seed": seed, "binary_path": firefox, "headless": True, "show_cursor": False,
"locale": AB_LAUNCH_LOCALE, "timezone": zone}
if dpr is not None:
options["pin"] = {"screen.dpr": dpr}
return options
def ab_items(context: str, result, back) -> dict:
"""The items of one context of the ab visit: what the page recorded (ab.<context>.<step>...), what a page that came back from the history reads
again (ab.<context>.bfcache: whether it was restored from the back/forward cache is the engine's, not the identity's, and goes to diag.)."""
body = dict(result) if isinstance(result, dict) else {"result": result}
body["bfcache"] = back.get("data") if isinstance(back, dict) else back
return {AB + context: body, DIAG + AB + context: {"bfcache_persisted": back.get("persisted") if isinstance(back, dict) else None}}
def ab_visit(firefox: str, seed: int, zone: str, dpr: float | None = None, timeout_ms: int = AB_BUDGET_MS) -> dict:
"""Launch `firefox` with the seed in ja-JP, and read the ab site in its default context and in a context of de-DE and America/Lima;
returns {key: value} to add to the visit's items."""
from invisible_playwright import InvisiblePlaywright
server = ThreadingHTTPServer(("127.0.0.1", 0), _AbSite)
server.ab_seen, server.ab_lock = {}, threading.Lock()
threading.Thread(target=server.serve_forever, daemon=True).start()
base = "http://127.0.0.1:%d/ab/" % server.server_address[1]
items = {}
lost = None
try:
with InvisiblePlaywright(**ab_options(firefox, seed, dpr, zone)) as browser:
for name, options in AB_CONTEXTS:
context, step = None, "new context"
try:
context = browser.new_context(**options)
step = "new page"
page = context.new_page()
step = "goto surfaces"
page.goto(base + "surfaces.html?ctx=" + name, timeout=timeout_ms)
step = "wait for the page's result"
page.wait_for_function("document.title === 'ab-done'", timeout=timeout_ms)
step = "read the page's result"
result = page.evaluate("window.__abResult")
# away and back: the page that comes back reads again (pageshow), restored from the cache or loaded anew
step = "goto leave"
page.goto(base + "leave.html?ctx=" + name, timeout=timeout_ms)
step = "go back"
page.go_back(timeout=timeout_ms)
step = "wait for the page that came back"
page.wait_for_function("window.__abBf && window.__abBf.n >= 2", timeout=timeout_ms)
step = "read the page that came back"
back = page.evaluate("window.__abBf")
except Exception as e: # noqa: BLE001 - a tab that died is the leaf `crash.tab.ab-visit`; anything else is raised as it always was
if not crash.tab_lost(e):
raise
lost = crash.tab_crash_item("ab-visit", "%s (context %s)" % (step, name), e)
finally:
if context is not None:
try:
context.close()
except Exception: # noqa: BLE001 - closing a context whose tab died says nothing more
if lost is None:
raise
if lost is not None:
items.update(lost)
break
items.update(ab_items(name, result, back))
finally:
server.shutdown()
server.server_close()
return items
def ab_control(items_by_seed: dict, seeds: tuple = AB_SEEDS, minimum: int | None = None) -> dict:
"""The control of the ab visit: on how many leaves of the ab visit seeds[1] differs from seeds[0]. `items_by_seed` maps a seed to its items.
Returns {"status": "ok"|"too_few"|"not_visited", "differing", "compared", "minimum", "line"}; not_visited (a run that did not visit both,
the pull request's two seeds) is said, and the caller decides whether that is allowed."""
minimum = AB_CONTROL_MIN if minimum is None else minimum
a, b = seeds
mine = {}
for seed in seeds:
items = items_by_seed.get(seed)
mine[seed] = None if items is None else {k: v for k, v in leaves(items).items() if k.startswith(AB_CONTROL_NAMESPACES)}
if not mine[a] or not mine[b]:
missing = [s for s in seeds if not mine[s]]
return {"status": "not_visited", "differing": None, "compared": None, "minimum": minimum,
"line": "ab control: seed %s has no ab. leaves in this run" % " and ".join(map(str, missing))}
keys = sorted(set(mine[a]) | set(mine[b]))
differing = [k for k in keys if mine[a].get(k, "<missing>") != mine[b].get(k, "<missing>")]
status = "ok" if len(differing) >= minimum else "too_few"
return {"status": status, "differing": len(differing), "compared": len(keys), "minimum": minimum, "sample": differing[:12],
"line": "ab control: seed %d differs from seed %d on %d of %d ab. leaves (at least %d are required)%s"
% (b, a, len(differing), len(keys), minimum, "" if status == "ok" else ": an identity that is not seed %d's read the same" % a)}
#: The steps of the ab visit that must have read something in every context: a realm that answers `timeout` or an error says the page did not
#: read, and an A/B of two such answers compares nothing. The others (the service worker, the audio worklet, the popups) may be missing on a
#: host that has none of it; what they answered is compared like any leaf.
AB_REQUIRED_STEPS = ("top", "iframe_cross", "iframe_srcdoc", "worker", "accept_language")
def ab_coverage(items_by_seed: dict, seeds: tuple = AB_SEEDS) -> list:
"""What is missing from the ab visit of the seeds of this run that have one: [problem]. A seed of `seeds` that the run visited without an
ab visit, a context without its leaves, and a required step that did not read a dict are problems."""
problems = []
for seed in seeds:
items = items_by_seed.get(seed)
if items is None:
continue
for name, _ in AB_CONTEXTS:
body = items.get(AB + name)
if not isinstance(body, dict):
problems.append("seed %d: no %s%s leaves (the ab visit did not run, or the page recorded none)" % (seed, AB, name))
continue
for step in AB_REQUIRED_STEPS:
if not isinstance(body.get(step), dict):
problems.append("seed %d %s%s.%s: %s" % (seed, AB, name, step, json.dumps(body.get(step))[:160]))
return problems
# -
# Compare: every leg, every visit, against each other and against retail.
@@ -834,7 +494,7 @@ def compare(dumps: Path, reference: Path, exceptions: dict, notes: list | None =
for path in sorted(dumps.glob("*.json")):
d = json.loads(path.read_text(encoding="utf-8"))
items = d["result"]["items"]
visits[(d["leg"], d["dpr"], d["seed"])] = {k: v for k, v in leaves(items).items() if not is_diag(k) and not is_ab(k)}
visits[(d["leg"], d["dpr"], d["seed"])] = {k: v for k, v in leaves(items).items() if not is_diag(k)}
# the invariants: every leg, every visit, every state; no exception and no reference applies
failures += invariant_lines("%s dpr %s seed %d" % (d["leg"], d["dpr"], d["seed"]), items)
if not visits:
@@ -846,7 +506,7 @@ def compare(dumps: Path, reference: Path, exceptions: dict, notes: list | None =
items = reference_items(reference, dpr)
if items is None:
return ["no retail reference for dpr %s in %s" % (dpr, reference)]
refs[dpr] = {k: v for k, v in leaves(items).items() if not is_diag(k) and not is_ab(k)}
refs[dpr] = {k: v for k, v in leaves(items).items() if not is_diag(k)}
pending[dpr] = tuple(p for p in REFERENCE_PENDING if not any(k.startswith(p) for k in refs[dpr]))
for p in pending[dpr]:
if notes is not None:
@@ -918,61 +578,6 @@ def compare(dumps: Path, reference: Path, exceptions: dict, notes: list | None =
return failures
# -
# The junit: the verdict of compare() as one testcase per invariant and per
# other check, so a judge can ask "did this invariant pass" by name.
#: The classname is the script's path as a dotted module (the hook tests judge turns it back into
#: scripts/ci_host_gate.py, the file a hook names).
JUNIT_CLASSNAME = "scripts.ci_host_gate"
#: The checks of compare() other than the invariants, with the prefix of the
#: failure lines each one owns.
CHECKS = (
("dumps_complete", ("no dumps", "no retail reference")),
("host_independence", ("host ",)),
("retail_equality", ("retail ",)),
("exceptions_current", ("known defect",)),
)
def junit_cases(failures: list, dumps_seen: int) -> list:
"""The verdict as [(name, status, lines)], status being passed, failed or
skipped. Nothing to look at (no dump) skips an invariant; a failure line
is owned by the invariant or check it names."""
cases = []
for inv in INVARIANTS:
lines = [f for f in failures if f.startswith("invariant %s " % inv.name)]
cases.append(("invariant:" + inv.name, "failed" if lines else ("passed" if dumps_seen else "skipped"), lines))
no_dumps = any(f.startswith("no dumps") for f in failures)
no_reference = any(f.startswith("no retail reference") for f in failures)
for name, prefixes in CHECKS:
lines = [f for f in failures if f.startswith(prefixes) or (name == "dumps_complete" and ": no dump for seeds" in f)]
skipped = no_dumps or (no_reference and name != "dumps_complete")
cases.append(("check:" + name, "failed" if lines else ("skipped" if skipped else "passed"), lines))
return cases
def write_junit(path: Path, cases: list, suite: str = "host-gate") -> None:
"""cases: [(name, status, lines)] as a junit (xunit2) file at path."""
root = ET.Element("testsuites")
counts = {"failed": 0, "skipped": 0}
for _, status, _lines in cases:
if status in counts:
counts[status] += 1
ts = ET.SubElement(root, "testsuite", name=suite, tests=str(len(cases)), failures=str(counts["failed"]),
errors="0", skipped=str(counts["skipped"]), time="0")
for name, status, lines in cases:
tc = ET.SubElement(ts, "testcase", classname=JUNIT_CLASSNAME, name=name, time="0")
if status == "failed":
f = ET.SubElement(tc, "failure", message=lines[0][:300] if lines else "failed")
f.text = "\n".join(lines[:50])
elif status == "skipped":
ET.SubElement(tc, "skipped", message="nothing to check: the gate had no dumps or no reference")
path.parent.mkdir(parents=True, exist_ok=True)
ET.ElementTree(root).write(path, encoding="utf-8", xml_declaration=True)
def main(argv=None) -> int:
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
sub = ap.add_subparsers(dest="cmd", required=True)
@@ -981,33 +586,18 @@ def main(argv=None) -> int:
d.add_argument("--leg", required=True)
d.add_argument("--out", type=Path, required=True)
d.add_argument("--reference", type=Path, default=REFERENCE)
d.add_argument("--visit", action="append", metavar="SEED:DPR",
help="visit this seed (repeatable; default: the host gate's own seeds at its own DPRs)")
d.add_argument("--ab", action="store_true",
help="the seeds of AB_SEEDS also get the A/B oracle's extra visit (ab. leaves)")
d.add_argument("--no-pin", action="store_true",
help="do not pin the DPR: the seed's persona has its own (the DPR of --visit only names the file)")
d.add_argument("--relaunch-seed", action="append", type=int, default=[], metavar="SEED",
help="also launch this seed twice on one profile folder and keep the second launch's items under relaunch. (repeatable)")
c = sub.add_parser("compare")
c.add_argument("dumps", type=Path)
c.add_argument("--reference", type=Path, default=REFERENCE)
c.add_argument("--junit", type=Path, help="also write the verdict as a junit (xunit2) file")
args = ap.parse_args(argv)
if args.cmd == "dump":
visits = None
if args.visit:
visits = [(float(dpr), int(seed)) for seed, dpr in (v.split(":", 1) for v in args.visit)]
return dump(args.firefox, args.leg, args.out, args.reference, visits=visits, pin_dpr=not args.no_pin,
relaunch_seeds=tuple(args.relaunch_seed), ab=args.ab)
return dump(args.firefox, args.leg, args.out, args.reference)
notes = []
failures = compare(args.dumps, args.reference, load_exceptions(), notes)
for n in notes:
print("NOTE " + n)
for f in failures:
print("FAIL " + f)
if args.junit:
write_junit(args.junit, junit_cases(failures, len(list(args.dumps.glob("*.json")))))
print("HOST GATE %s: %d failures" % ("OK" if not failures else "FAILED", len(failures)))
return 1 if failures else 0
+82
View File
@@ -0,0 +1,82 @@
"""The preloaded-intermediates list of a CI leg: a fixed (empty) file of the repository, and the variable that makes the core use it.
python scripts/ci_lab_intermediates.py set [--pin ci/intermediates.pin.json] # checks the file against the pin, exports STEALTHFOX_INTERMEDIATES
Why this exists: without ``STEALTHFOX_INTERMEDIATES`` the core downloads Mozilla's intermediates list on a cold cache (in line, at the first launch or at
`invisible_playwright fetch`) and asks once a week whether it changed, from the python of the test. A CI leg reaches no site for its data and every run has to
have the same bytes, so the leg launches with ``ci/intermediates.json``: a valid list in the engine's format 1 with no certificate. With the variable set the
core neither downloads nor checks, ever. ``ci/intermediates.pin.json`` holds the sha256 of the file: ``set`` refuses to go on when the file is not that.
``set`` writes ``STEALTHFOX_INTERMEDIATES=<absolute path>`` to ``$GITHUB_ENV`` (every later step of the job sees it) and, when there is no
``$GITHUB_ENV``, to stdout. The paths of the pin are relative to the repository, not to the working directory of the caller.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import sys
from pathlib import Path
ENV = "STEALTHFOX_INTERMEDIATES"
ROOT = Path(__file__).resolve().parents[1]
class Refused(Exception):
pass
def sha256_of(path) -> str:
return hashlib.sha256(Path(path).read_bytes()).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("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 sha256 that is a sha256" % path)
if not isinstance(pin.get("file"), str) or not pin["file"]:
raise Refused("the pin %s names no file" % path)
return pin
def resolve(pin: dict, pin_path) -> Path:
"""The file the pin names, checked against its sha256: a file that is not the pinned one is refused."""
target = Path(pin["file"])
if not target.is_absolute():
target = ROOT / target
if not target.is_file():
raise Refused("the file %s of the pin cannot be found" % pin["file"])
got = sha256_of(target)
if got != pin["sha256"]:
raise Refused("%s has sha256 %s, the pin says %s: change both in one commit" % (pin["file"], got, pin["sha256"]))
return target.resolve()
def main(argv=None) -> int:
ap = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0])
sub = ap.add_subparsers(dest="cmd", required=True)
s = sub.add_parser("set")
s.add_argument("--pin", default="ci/intermediates.pin.json")
ns = ap.parse_args(argv)
try:
path = resolve(load_pin(ns.pin), ns.pin)
except Refused as exc:
print("ci_lab_intermediates: %s" % exc, file=sys.stderr)
return 1
line = "%s=%s" % (ENV, path)
env_file = os.environ.get("GITHUB_ENV")
if env_file:
with open(env_file, "a", encoding="utf-8", newline="\n") as fh:
fh.write(line + "\n")
else:
print(line)
return 0
if __name__ == "__main__":
sys.exit(main())
-87
View File
@@ -1,87 +0,0 @@
"""The security state of a CI leg: a fixed, ready directory of the repository, and the variable that makes the core use it.
python scripts/ci_lab_security_state.py set [--pin ci/security-state.pin.json] # checks the directory against the pin, exports STEALTHFOX_SECURITY_STATE
Why this exists: without ``STEALTHFOX_SECURITY_STATE`` the core downloads Mozilla's security-state collections on a cold cache (in line, at the first launch or at
`invisible_playwright fetch`), has the engine generate the state from them and copies it into every profile. A CI leg reaches no site for its data, runs no generation and
every run has to have the same bytes, so the leg launches with ``ci/security-state/``: a ready directory that holds ONLY ``securitystate-result.json`` (a result with no
data: format 1, ok, no CRLite hashes, zero timestamps, no engine) and no ``security_state/``, so a launch copies nothing. With the variable set the core neither downloads
nor generates, ever. ``ci/security-state.pin.json`` holds the sha256 of that file: ``set`` refuses to go on when the file is not that, or when the directory holds
anything else.
``set`` writes ``STEALTHFOX_SECURITY_STATE=<absolute directory>`` to ``$GITHUB_ENV`` (every later step of the job sees it) and, when there is no ``$GITHUB_ENV``, to
stdout. The paths of the pin are relative to the repository, not to the working directory of the caller.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import sys
from pathlib import Path
ENV = "STEALTHFOX_SECURITY_STATE"
ROOT = Path(__file__).resolve().parents[1]
class Refused(Exception):
pass
def sha256_of(path) -> str:
return hashlib.sha256(Path(path).read_bytes()).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("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 sha256 that is a sha256" % path)
if not isinstance(pin.get("file"), str) or not pin["file"]:
raise Refused("the pin %s names no file" % path)
return pin
def resolve(pin: dict, pin_path) -> Path:
"""The directory of the file the pin names, checked: the file has the pinned sha256 and it is the ONLY entry of its directory."""
target = Path(pin["file"])
if not target.is_absolute():
target = ROOT / target
if not target.is_file():
raise Refused("the file %s of the pin cannot be found" % pin["file"])
got = sha256_of(target)
if got != pin["sha256"]:
raise Refused("%s has sha256 %s, the pin says %s: change both in one commit" % (pin["file"], got, pin["sha256"]))
others = sorted(p.name for p in target.parent.iterdir() if p.name != target.name)
if others:
raise Refused("the directory %s holds more than %s: %s" % (target.parent, target.name, ", ".join(others)))
return target.parent.resolve()
def main(argv=None) -> int:
ap = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0])
sub = ap.add_subparsers(dest="cmd", required=True)
s = sub.add_parser("set")
s.add_argument("--pin", default="ci/security-state.pin.json")
ns = ap.parse_args(argv)
try:
path = resolve(load_pin(ns.pin), ns.pin)
except Refused as exc:
print("ci_lab_security_state: %s" % exc, file=sys.stderr)
return 1
line = "%s=%s" % (ENV, path)
env_file = os.environ.get("GITHUB_ENV")
if env_file:
with open(env_file, "a", encoding="utf-8", newline="\n") as fh:
fh.write(line + "\n")
else:
print(line)
return 0
if __name__ == "__main__":
sys.exit(main())
-135
View File
@@ -1,135 +0,0 @@
#!/usr/bin/env python3
"""Writes ci/py-lock/playwright-browsers.json: the sha256 of every archive of Playwright's own Firefox that the engine series' gate installs (ci-03).
The rows of the gate that compare the engine with the stock Firefox install it from Playwright's CDN. A third-party download is checked by a hash pinned in a
repository, so the archives are pinned HERE, at the wrapper_ref the gate selects, for the Playwright of scripts/playwright_pin.txt: what
`python -m playwright install --dry-run firefox` lists on each platform (Firefox, FFmpeg, and winldd on Windows), each downloaded once and hashed.
python scripts/ci_playwright_browsers.py [--python python] [--out ci/py-lock/playwright-browsers.json]
The interpreter must have the pinned Playwright installed (the dry-run is what names the archives, so a different version names different ones). The output is
sorted by platform, entries in the order the dry-run lists them, LF, two-space indent, so the same input gives the same bytes.
tests/test_the_playwright_browsers_pin_follows_the_pin.py reads the committed file with `problems`, offline.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import re
import subprocess
import sys
import urllib.request
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
OUT_PATH = ROOT / "ci" / "py-lock" / "playwright-browsers.json"
PLAYWRIGHT_PIN = ROOT / "scripts" / "playwright_pin.txt"
#: The CDN the dry-run is asked to name (the gate downloads from the same host).
DOWNLOAD_HOST = "https://cdn.playwright.dev/dbazure/download/playwright"
#: platform name in the file -> PLAYWRIGHT_HOST_PLATFORM_OVERRIDE of the dry-run.
PLATFORMS = {"ubuntu24.04-x64": "ubuntu24.04-x64", "win64": "win64"}
#: The archive kinds the dry-run lists for each platform (the first path segment after builds/).
KINDS = {"ubuntu24.04-x64": ["firefox", "ffmpeg"], "win64": ["firefox", "ffmpeg", "winldd"]}
PATH_RE = re.compile(r"^builds/([a-z0-9_-]+)/[0-9]+/[A-Za-z0-9._-]+\.zip$")
SHA_RE = re.compile(r"^[0-9a-f]{64}$")
def problems(data: object, pin: str) -> list:
"""What is wrong with a parsed playwright-browsers.json, given the Playwright pin; an empty list when it is sound."""
out = []
if not isinstance(data, dict) or set(data) != {"playwright", "platforms"}:
return ["the file is not an object with exactly `playwright` and `platforms`"]
if data["playwright"] != pin.strip():
out.append("playwright is %r but scripts/playwright_pin.txt pins %r: regenerate with scripts/ci_playwright_browsers.py" % (data["playwright"], pin.strip()))
platforms = data["platforms"]
if not isinstance(platforms, dict) or set(platforms) != set(PLATFORMS):
return out + ["platforms are %r, expected %r" % (sorted(platforms) if isinstance(platforms, dict) else platforms, sorted(PLATFORMS))]
for name in sorted(PLATFORMS):
entries = platforms[name]
if not isinstance(entries, list):
out.append("%s: not a list" % name)
continue
kinds = []
for e in entries:
path = e.get("path") if isinstance(e, dict) else None
m = PATH_RE.match(path) if isinstance(path, str) else None
if not m:
out.append("%s: %r is not a relative `builds/<kind>/<revision>/<archive>.zip` path" % (name, path))
continue
kinds.append(m.group(1))
if not isinstance(e.get("sha256"), str) or not SHA_RE.match(e["sha256"]):
out.append("%s: %s has no 64-hex sha256" % (name, path))
if "size" in e and not (isinstance(e["size"], int) and not isinstance(e["size"], bool) and e["size"] > 0):
out.append("%s: %s has a size that is not a positive integer" % (name, path))
if set(e) - {"path", "sha256", "size"}:
out.append("%s: %s has unknown fields %s" % (name, path, sorted(set(e) - {"path", "sha256", "size"})))
if sorted(kinds) != sorted(KINDS[name]):
out.append("%s: the archives are %s, the dry-run lists %s" % (name, sorted(kinds), sorted(KINDS[name])))
return out
def installed_version(py: str) -> str:
return subprocess.run([py, "-c", "import importlib.metadata as m; print(m.version('playwright'))"], capture_output=True, text=True, check=True).stdout.strip()
def dry_run_paths(py: str, platform: str) -> list:
env = dict(os.environ, PLAYWRIGHT_HOST_PLATFORM_OVERRIDE=PLATFORMS[platform], PLAYWRIGHT_DOWNLOAD_HOST=DOWNLOAD_HOST)
dry = subprocess.run([py, "-m", "playwright", "install", "--dry-run", "firefox"], capture_output=True, text=True, env=env, check=True).stdout
urls = re.findall(r"Download url:\s+(\S+)", dry)
prefix = DOWNLOAD_HOST + "/"
bad = [u for u in urls if not u.startswith(prefix)]
if bad or not urls:
raise SystemExit("%s: the dry-run names %r, not archives of %s" % (platform, bad or urls, DOWNLOAD_HOST))
return [u[len(prefix):] for u in urls]
def fetch_hash(path: str) -> tuple:
h, size = hashlib.sha256(), 0
with urllib.request.urlopen(DOWNLOAD_HOST + "/" + path, timeout=300) as r:
while chunk := r.read(1 << 20):
h.update(chunk)
size += len(chunk)
return h.hexdigest(), size
def render(data: object) -> str:
"""The bytes of the file for a parsed content: two-space indent, LF, one trailing newline (the same content always gives the same bytes)."""
return json.dumps(data, indent=2) + "\n"
def build(py: str, pin: str) -> str:
version = installed_version(py)
if version != pin.strip():
raise SystemExit("the interpreter has playwright %s, scripts/playwright_pin.txt pins %s: install the pinned one" % (version, pin.strip()))
platforms = {}
for name in sorted(PLATFORMS):
entries = []
for path in dry_run_paths(py, name):
sha, size = fetch_hash(path)
entries.append({"path": path, "sha256": sha, "size": size})
print(name, path, size, sha, flush=True)
platforms[name] = entries
data = {"playwright": version, "platforms": platforms}
bad = problems(data, pin)
if bad:
raise SystemExit("the generated file is not sound: " + "; ".join(bad))
return render(data)
def main(argv=None) -> int:
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("--python", default=sys.executable, help="interpreter with the pinned playwright installed (default: this one)")
ap.add_argument("--out", default=str(OUT_PATH))
a = ap.parse_args(argv)
text = build(a.python, PLAYWRIGHT_PIN.read_text(encoding="utf-8"))
Path(a.out).write_text(text, encoding="utf-8", newline="\n")
print("%s written" % Path(a.out).name)
return 0
if __name__ == "__main__":
sys.exit(main())
-842
View File
@@ -1,842 +0,0 @@
#!/usr/bin/env python3
"""The poisoned host of the page A/B oracle.
The page oracle compares two engines on one machine, so a value both read from that machine passes the comparison. This puts values on the
machine that the engine must never read, for the run of the page oracle only (the job of that leg: the host oracle's parsers read
tracerpt and strace output and are not in it), and proves that they are there with a NEGATIVE CONTROL: Playwright's own Firefox on the
same runner reads them. The engine's dumps are then held to the identity the core declares, never to the poison.
poison where Firefox reads it what the engine declares instead
time zone Lima (UTC-5, no DST): Windows `tzutil`, Linux `TZ` the zone of the host gate's reference (Asia/Bangkok), by the launch
language ja-JP: Windows `Set-Culture` and the user language list, en-US, by the launch
Linux `LANG`
colour scheme dark: Windows AppsUseLightTheme=0, Linux `GTK_THEME` the scheme of the seed's persona (dark for 40% of them)
fonts a user-installed CANARY font, family `ZZHostCanary`: no such family: a user font is not the declared machine's
Windows machine-wide fonts (the Fonts folder of the system and HKLM; the runner is an administrator), Linux ~/.local/share/fonts
audio (Linux) a null sink at 96000 Hz and 6 channels, the default sink the persona's sample rate (44100 or 48000) and channel count
The canary is generated here, byte for byte the same every time (`canary_font()`: a TrueType font of three glyphs, written from the
specification, no third-party font and so no licence): every letter and digit is a box 1.5 em wide, so a page that reads the family
measures a text far wider than any fallback. Its sha256 is CANARY_SHA256 and the tests hold the two together.
python ci_poison_host.py apply [--state FILE] [--no-audio] put the poison on this machine (and verify it); writes the undo state
python ci_poison_host.py verify [--expect-env] the poison is in force (--expect-env: this process also inherited the variables)
python ci_poison_host.py undo --state FILE put back what apply found
python ci_poison_host.py control --out FILE the negative control: stock Firefox of Playwright reads the poison, or exit 2 (broken control)
python ci_poison_host.py font --out FILE write the canary font
Windows warning. `Set-Culture` changes the number and date formats of every process started after it. Every PowerShell this script runs
starts by forcing the invariant culture on its own thread, and the state it keeps is text it read before the change: nothing here
parses a formatted number or a date. The poison belongs to the page oracle's job and `undo` runs before that job's judge.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import re
import struct
import subprocess
import sys
from pathlib import Path
from typing import Callable
HERE = Path(__file__).resolve().parent
PAGE = HERE / "host_gate" / "host_gate_page.html"
FAMILY = "ZZHostCanary"
FONT_FILE = FAMILY + ".ttf"
#: Where Firefox must read Lima from, in the two spellings: the Windows id and the IANA name (the offsets are what a page tells apart).
WINDOWS_ZONE, IANA_ZONE = "SA Pacific Standard Time", "America/Lima"
LIMA_OFFSETS = [300, 300]
CULTURE, LINUX_LANG = "ja-JP", "ja_JP.UTF-8"
GTK_THEME = "Adwaita:dark"
SINK, SINK_RATE, SINK_CHANNELS = "hostcanary", 96000, 6
SINK_MAP = "front-left,front-right,front-center,lfe,rear-left,rear-right"
#: The variables a Linux poison puts in the environment of the later steps ($GITHUB_ENV), and the one that says it is on.
LINUX_ENV = {"TZ": IANA_ZONE, "LANG": LINUX_LANG, "LANGUAGE": "ja", "GTK_THEME": GTK_THEME}
#: A text of 12 'm' at 12px in the canary: 12 boxes of 1.5 em. A generic family that measures this is the canary.
CANARY_TEXT_WIDTH = 216.0
GENERICS = ("sans-serif", "serif", "monospace")
SWITCH = "AB_ORACLE_POISON"
#: The variable that names the file `apply` wrote its undo state to.
STATE_SWITCH = "AB_ORACLE_POISON_STATE"
THEME_KEY = r"HKCU:\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize"
FONTS_KEY = r"HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts"
FONT_VALUE = FAMILY + " (TrueType)"
Run = Callable[[list], tuple]
# -
# The canary font.
def _checksum(data: bytes) -> int:
data += b"\0" * (-len(data) % 4)
return sum(struct.unpack(">%dI" % (len(data) // 4), data)) & 0xFFFFFFFF
def _pad(data: bytes) -> bytes:
return data + b"\0" * (-len(data) % 4)
def canary_font() -> bytes:
"""A TrueType font, family ZZHostCanary, of three glyphs: .notdef and every character of U+0021..U+007E are boxes, U+0020 is blank.
The advance of a box is 1500 units of 1000 per em, the space's 500. Deterministic: no clock, no randomness."""
upem, box_advance, space_advance = 1000, 1500, 500
box = struct.pack(">hhhhh", 1, 100, 0, 1400, 700) + struct.pack(">H", 3) + struct.pack(">H", 0) + bytes([1, 1, 1, 1]) \
+ struct.pack(">4h", 100, 0, 1300, 0) + struct.pack(">4h", 0, 700, 0, -700)
glyf = _pad(box) + _pad(box) # .notdef and the box: the same drawing
loca = struct.pack(">4I", 0, len(_pad(box)), 2 * len(_pad(box)), 2 * len(_pad(box))) # .notdef, box, space (empty)
hmtx = struct.pack(">HhHhHh", box_advance, 100, box_advance, 100, space_advance, 0)
head = struct.pack(">IIIIHHqqhhhhHHhhh", 0x00010000, 0x00010000, 0, 0x5F0F3CF5, 0x000B, upem,
3_700_000_000, 3_700_000_000, 0, 0, 1400, 700, 0, 8, 2, 1, 0)
hhea = struct.pack(">IhhhHhhhhhhhhhhhH", 0x00010000, 800, -200, 0, box_advance, 100, 100, 1400, 1, 0, 0, 0, 0, 0, 0, 0, 3)
maxp = struct.pack(">IHHHHHHHHHHHHHH", 0x00010000, 3, 4, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0)
os2 = struct.pack(">HhHHH11h", 4, 1500, 400, 5, 0, 650, 600, 0, 75, 650, 600, 0, 350, 50, 250, 0)
os2 += bytes(10) + struct.pack(">IIII", 1, 0, 0, 0) + b"NONE"
os2 += struct.pack(">HHHhhhHHII", 0x40, 0x20, 0x7E, 800, -200, 0, 800, 200, 1, 0) + struct.pack(">hhHHH", 500, 700, 0, 0x20, 1)
post = struct.pack(">IIhhIIIII", 0x00030000, 0, -100, 50, 0, 0, 0, 0, 0)
# cmap: format 4, one segment per character (a constant glyph needs no glyph-index array)
chars = [(0x20, 2)] + [(c, 1) for c in range(0x21, 0x7F)]
ends = [c for c, _ in chars] + [0xFFFF]
deltas = [(g - c) & 0xFFFF for c, g in chars] + [1]
seg = len(ends)
sub = (struct.pack(">HHHHHHH", 4, 16 + 8 * seg, 0, seg * 2, 128, 6, 2 * seg - 128)
+ struct.pack(">%dH" % seg, *ends) + struct.pack(">H", 0) + struct.pack(">%dH" % seg, *ends)
+ struct.pack(">%dH" % seg, *deltas) + struct.pack(">%dH" % seg, *([0] * seg)))
cmap = struct.pack(">HHHHI", 0, 1, 3, 1, 12) + sub
names = {1: FAMILY, 2: "Regular", 3: FAMILY + "-Regular-1.000", 4: FAMILY + " Regular", 5: "Version 1.000", 6: FAMILY + "-Regular"}
strings, records = b"", b""
for nid in sorted(names):
text = names[nid].encode("utf-16-be")
records += struct.pack(">HHHHHH", 3, 1, 0x409, nid, len(text), len(strings))
strings += text
name = struct.pack(">HHH", 0, len(names), 6 + 12 * len(names)) + records + strings
tables = {b"OS/2": os2, b"cmap": cmap, b"glyf": glyf, b"head": head, b"hhea": hhea, b"hmtx": hmtx,
b"loca": loca, b"maxp": maxp, b"name": name, b"post": post}
n = len(tables)
out = struct.pack(">IHHHH", 0x00010000, n, 128, 3, n * 16 - 128)
offset = 12 + 16 * n
body = b""
for tag in sorted(tables):
data = tables[tag]
out += struct.pack(">4sIII", tag, _checksum(data), offset + len(body), len(data))
body += _pad(data)
font = bytearray(out + body)
head_at = offset + sum(len(_pad(tables[t])) for t in sorted(tables) if t < b"head") + 8
struct.pack_into(">I", font, head_at, (0xB1B0AFBA - _checksum(bytes(font))) & 0xFFFFFFFF)
return bytes(font)
#: The sha256 of canary_font(): a font that changed is a different poison, said here and held by a test.
CANARY_SHA256 = "fc1a766e6253f2791fb422f241db7e14a9793a8975ebd867c13e1257110e4045"
def canary_sha256() -> str:
return hashlib.sha256(canary_font()).hexdigest()
def read_tables(font: bytes) -> dict:
"""{tag: bytes} of an sfnt, after checking the directory's checksums and the whole-file checksum (head.checkSumAdjustment)."""
n = struct.unpack_from(">H", font, 4)[0]
tables = {}
for i in range(n):
tag, csum, off, length = struct.unpack_from(">4sIII", font, 12 + 16 * i)
data = font[off:off + length]
if tag != b"head" and _checksum(data) != csum:
raise ValueError("table %r: bad checksum" % tag)
tables[tag.decode("latin-1")] = data
if _checksum(font) != 0xB1B0AFBA:
raise ValueError("the whole-file checksum is not the one head.checkSumAdjustment makes")
return tables
# -
# What the page reads: the probe lives in the page (host_gate_page.html, between the two markers) and the control evaluates the same text.
PROBE_BEGIN, PROBE_END = "// ab.poison:begin", "// ab.poison:end"
def probe_source(page: Path = PAGE) -> str:
"""The probe function of the page, `const abPoisonProbe = async () => {...};`, exactly as the page runs it."""
text = page.read_text(encoding="utf-8")
if text.count(PROBE_BEGIN) != 1 or text.count(PROBE_END) != 1 or text.index(PROBE_BEGIN) > text.index(PROBE_END):
raise SystemExit("%s must hold the probe between one %r and one %r" % (page.name, PROBE_BEGIN, PROBE_END))
return text.split(PROBE_BEGIN, 1)[1].split(PROBE_END, 1)[0]
# -
# The engine under the poison: what its dumps must say instead.
def declared(seed: int, reference=None, dpr: float = 1.0) -> dict:
"""What the identity of `seed` declares for each poisoned value: from the core's prefs of the seed (the dark scheme, the audio chain) and
from the retail reference of the host gate (the zone and the language the launch declares, the strings they make)."""
import ci_host_gate as gate
import persona_cover as personas
prefs = {k: json.loads(v) for k, v in personas.seed_features(seed)[1].items()}
intl = gate.reference_items(reference or gate.REFERENCE, dpr)["surface.intl"]
return {"timezone": intl["DateTimeFormat"]["timeZone"], "offsets": intl["offsets"], "locale": intl["DateTimeFormat"]["locale"],
"language": intl["languages"][0], "date_full": intl["strings"][4], "number": intl["strings"][3],
"dark": bool(prefs["ui.systemUsesDarkTheme"]),
"sample_rate": prefs[personas.P + "audio.sample_rate"], "max_channels": prefs[personas.P + "audio.max_channel_count"]}
def _is_canary_width(width) -> bool:
return isinstance(width, (int, float)) and abs(width - CANARY_TEXT_WIDTH) < 0.5
def findings(probe, want: dict) -> list:
"""What an engine's `ab.poison` leaves say about the host, against `want` (declared()): every line is a value that is the machine's
(or that is not what the persona declares), empty when the page read none of the poison. A page that dumped no probe is a finding too:
it would pass anything."""
if not isinstance(probe, dict) or not probe:
return ["the dump has no ab.poison leaves: the page did not read the poison, so nothing was checked"]
out = []
def expect(key, value, what):
if probe.get(key) != value:
out.append("%s: the page read %s, the identity declares %s" % (what, json.dumps(probe.get(key)), json.dumps(value)))
expect("timezone", want["timezone"], "time zone")
expect("offsets", want["offsets"], "UTC offsets of January and July")
if probe.get("offsets") == LIMA_OFFSETS and want["offsets"] != LIMA_OFFSETS:
out.append("time zone: the offsets are the host's Lima (UTC-5, no DST)")
expect("language", want["language"], "navigator.language")
expect("intl_locale", want["locale"], "the default Intl locale")
expect("date_full", want["date_full"], "a full date")
expect("number", want["number"], "a formatted number")
expect("dark", want["dark"], "prefers-color-scheme dark")
canary = probe.get("canary")
if not isinstance(canary, dict) or "present" not in canary:
out.append("canary font: the probe did not measure it")
elif canary["present"]:
out.append("canary font: a page measures the user-installed family %s (its text is %s wide, a fallback's %s)"
% (FAMILY, json.dumps(canary.get("with")), json.dumps(canary.get("without"))))
generic = probe.get("generic")
if not isinstance(generic, list) or len(generic) != len(GENERICS):
out.append("generic families: the probe did not measure them: %s" % json.dumps(generic))
else:
out += ["generic family %s: a page measures %s wide, the canary's width: the host's fontconfig chose it" % (g, w)
for g, w in zip(GENERICS, generic) if _is_canary_width(w)]
audio = probe.get("audio")
if not isinstance(audio, dict):
out.append("audio: the probe did not read the audio context: %s" % json.dumps(audio))
else:
if audio.get("sampleRate") != want["sample_rate"]:
out.append("audio: sampleRate %s, the persona declares %s" % (audio.get("sampleRate"), want["sample_rate"]))
if audio.get("maxChannelCount") != want["max_channels"]:
out.append("audio: maxChannelCount %s, the persona declares %s" % (audio.get("maxChannelCount"), want["max_channels"]))
return out
def dump_findings(dump: dict, wants: Callable = declared) -> list:
"""findings() of every visit of a packed dump (ci_ab_oracle.pack), as 'seed N dprD: line'."""
out = []
for visit in dump.get("visits", []):
probe = visit["items"].get("ab.poison")
out += ["seed %d dpr %s: %s" % (visit["seed"], visit["dpr"], line) for line in findings(probe, wants(visit["seed"]))]
return out
# -
# The by-product: what the published engine reads from the host that the poison changes.
#
# The same job dumps the published engine on the CLEAN runner (before the poison is applied) and, in the oracle's own run, on the POISONED one,
# the same seeds. Every leaf that differs is a host dependency the published engine ALREADY has: not a failure of the candidate and never red,
# a finding, kept in a file of its own and summarised in the job's summary.
CLEAN_FILE = "poison-clean-68.json"
DEPENDENCE_FILE = "poison-host-dependence-68.json"
DEPENDENCE_FORMAT = "poison-host-dependence/1"
CLIP = 300
def _clip(value):
text = json.dumps(value, sort_keys=True, ensure_ascii=False)
return value if len(text) <= CLIP else {"clipped": text[:CLIP], "len": len(text)}
def host_dependence(clean: dict, poisoned: dict) -> dict:
"""The leaves of the published engine that differ between its dump on the clean runner and on the poisoned one (both packed dumps,
ci_ab_oracle.pack), over the visits both have: {"visits", "missing", "leaves_compared", "differences": [{seed, dpr, leaf, clean, poisoned}]}."""
import ci_host_gate as gate
def by_visit(dump):
return {(v["dpr"], v["seed"]): {k: x for k, x in gate.leaves(v["items"]).items() if not gate.is_diag(k)} for v in dump.get("visits", [])}
a, b = by_visit(clean), by_visit(poisoned)
both = sorted(set(a) & set(b), key=lambda k: (k[1], k[0]))
differences, compared = [], 0
for dpr, seed in both:
for leaf in sorted(set(a[(dpr, seed)]) | set(b[(dpr, seed)])):
compared += 1
x, y = a[(dpr, seed)].get(leaf, "<missing>"), b[(dpr, seed)].get(leaf, "<missing>")
if x != y:
differences.append({"seed": seed, "dpr": dpr, "leaf": leaf, "clean": _clip(x), "poisoned": _clip(y)})
return {"format": DEPENDENCE_FORMAT, "visits": ["seed %d dpr %s" % (s, d) for d, s in both],
"missing": ["seed %d dpr %s" % (s, d) for d, s in sorted(set(a) ^ set(b), key=lambda k: (k[1], k[0]))],
"leaves_compared": compared, "differences": differences}
def dependence_markdown(report: dict | None) -> str:
"""The summary section of the job: the count, the leaves by family and the first few with both values."""
lines = ["### Host dependencies of the published engine (clean runner against poisoned runner)", ""]
if report is None:
return "\n".join(lines + ["No dump of the published engine on the clean runner: the step before the poison did not write one, "
"so the by-product is not available in this run.", ""])
diffs = report["differences"]
lines.append("%d of %d leaves differ over %d visits (%s). Each is a value the engine read from the host that the poison changed: "
"a finding about the published engine, not a failure of the candidate." % (len(diffs), report["leaves_compared"], len(report["visits"]),
", ".join(report["visits"]) or "none"))
if report["missing"]:
lines.append("Visits that only one of the two dumps has: %s." % ", ".join(report["missing"]))
families = {}
for d in diffs:
families[".".join(d["leaf"].split(".")[:2])] = families.get(".".join(d["leaf"].split(".")[:2]), 0) + 1
if families:
lines += ["", "| family | leaves |", "|---|---|"] + ["| %s | %d |" % kv for kv in sorted(families.items(), key=lambda kv: (-kv[1], kv[0]))[:30]]
lines += ["", "| seed | leaf | clean | poisoned |", "|---|---|---|---|"]
for d in diffs[:40]:
lines.append("| %s | %s | %s | %s |" % (d["seed"], d["leaf"], json.dumps(d["clean"], ensure_ascii=False)[:80].replace("|", "/"),
json.dumps(d["poisoned"], ensure_ascii=False)[:80].replace("|", "/")))
return "\n".join(lines + [""])
def write_dependence(out: Path, summary: Path | None = None) -> dict | None:
"""Write DEPENDENCE_FILE in `out` from CLEAN_FILE and dump-68.json there, and the markdown to `summary` (the job's $GITHUB_STEP_SUMMARY).
Returns the report, or None when there is no clean dump. Never a verdict."""
clean, poisoned = out / CLEAN_FILE, out / "dump-68.json"
report = None
if clean.is_file() and poisoned.is_file():
report = host_dependence(json.loads(clean.read_text(encoding="utf-8")), json.loads(poisoned.read_text(encoding="utf-8")))
(out / DEPENDENCE_FILE).write_text(json.dumps(report, sort_keys=True, ensure_ascii=False), encoding="utf-8")
text = dependence_markdown(report)
if summary:
with open(summary, "a", encoding="utf-8", newline="\n") as f:
f.write(text + "\n")
print(text)
return report
# -
# The negative control: what stock Firefox must read on the poisoned runner.
#: The requirements of the control: what stock Firefox must read of the poison on the poisoned runner, or the control is broken.
REQUIRED = ("timezone", "dark", "canary", "audio", "generic", "language")
#: IN TRIAL: requirements whose reading by stock Firefox is not yet shown on GitHub. They are still measured and printed (poison-control.json, "in_trial",
#: and the job summary), never silently, but they do not make the control broken until a run shows that stock reads them. {requirement: the systems where
#: it is in trial}. Empty since the two causes of run 45026082150 were taken away (the theme pref of Playwright's cfg, see reference_firefox; the per-user
#: font, now machine-wide); a requirement that a run shows unread goes back here, never silently dropped.
IN_TRIAL: dict = {}
def in_trial(requirement: str, system: str) -> bool:
return system in IN_TRIAL.get(requirement, ())
def control_failures(probe, system: str) -> list:
"""[(requirement, message)] of what stock Firefox did NOT read of the poison and must have. `system` is 'linux' or 'windows' (audio is Linux's)."""
if not isinstance(probe, dict):
return [("probe", "the probe returned %s" % json.dumps(probe))]
return [(name, message) for name, message in _control_misses(probe, system) if name in REQUIRED and not in_trial(name, system)]
def _control_misses(probe: dict, system: str) -> list:
"""Every requirement stock Firefox did not read, whether required, in trial or neither."""
out = []
if probe.get("offsets") != LIMA_OFFSETS:
out.append(("timezone", "stock Firefox read the offsets %s, not Lima's %s" % (json.dumps(probe.get("offsets")), LIMA_OFFSETS)))
if not language_reads(probe)["japanese"]:
out.append(("language", "stock Firefox read no Japanese language, date or number format: %s" % json.dumps(language_reads(probe)["reads"], ensure_ascii=False)))
if probe.get("dark") is not True:
out.append(("dark", "stock Firefox read prefers-color-scheme dark = %s" % json.dumps(probe.get("dark"))))
canary = probe.get("canary")
if not isinstance(canary, dict) or canary.get("present") is not True:
out.append(("canary", "stock Firefox did not measure the user-installed family %s: %s" % (FAMILY, json.dumps(canary))))
if system == "linux":
generic = probe.get("generic")
if not isinstance(generic, list) or not generic or not all(_is_canary_width(w) for w in generic):
out.append(("generic", "stock Firefox measured the generic families %s, not the canary's %s: the user's fonts.conf was not read"
% (json.dumps(generic), CANARY_TEXT_WIDTH)))
audio = probe.get("audio")
if not isinstance(audio, dict) or audio.get("sampleRate") != SINK_RATE:
out.append(("audio", "stock Firefox read the audio %s, not the null sink's %d Hz" % (json.dumps(audio), SINK_RATE)))
return out
def control_trials(probe, system: str) -> list:
"""[(requirement, message)] of the requirements IN TRIAL that stock Firefox did not read: measured and told, never a verdict."""
if not isinstance(probe, dict):
return []
every = _control_misses(probe, system)
return [(name, message) for name, message in every if in_trial(name, system)]
def language_reads(probe) -> dict:
"""What stock read of the language, for the log: the leaves and whether any of them is Japanese."""
keys = ("language", "languages", "intl_locale", "date_full", "number")
reads = {k: probe.get(k) for k in keys} if isinstance(probe, dict) else {}
text = json.dumps(reads, ensure_ascii=False)
return {"reads": reads, "japanese": bool(re.search(r'"ja\b|"ja-|[぀-ヿ一-鿿]', text))}
def control_markdown(report: dict) -> str:
"""The control's section of the job summary: what stock Firefox read, the broken requirements, and the ones in trial that it did not read."""
lines = ["### Negative control (stock Firefox of Playwright on the poisoned %s runner)" % report["system"], "",
"Verdict: **%s**." % report["verdict"]]
lines += ["- BROKEN (%s): %s" % (f["requirement"], f["message"]) for f in report["failures"]]
trial = report["in_trial"]
lines.append("In trial (measured, not required): %s." % (", ".join("%s on %s" % (k, "/".join(v)) for k, v in sorted(trial["requirements"].items())) or "none"))
lines += ["- not read, in trial (%s): %s" % (f["requirement"], f["message"]) for f in trial["not_read"]]
if not trial["not_read"]:
lines.append("- every requirement in trial was read")
return "\n".join(lines) + "\n\n"
def system_name() -> str:
return "windows" if sys.platform == "win32" else "linux"
#: What Playwright's Firefox forces in its own playwright.cfg that the poison is about: a pref, set before anything reads the host, answers the scheme
#: whatever the system says (widget/nsXPLookAndFeel.cpp GetIntValue reads the pref first, NativeGetInt after). The reference is a Firefox WITHOUT it.
CFG_DARK_PREF = "ui.systemUsesDarkTheme"
def reference_firefox(executable: str, dest: Path) -> tuple:
"""A copy of Playwright's own Firefox in `dest` whose playwright.cfg does not force the colour scheme; returns (path of its executable,
[the lines taken out]). The copy is the same build with the same other prefs: only the pref that overrides the system's theme is gone, so the
reference is a Firefox that reads the machine. Raises when the cfg is not where Playwright puts it or has no such line (the reference would not
be what it is said to be)."""
import shutil
source = Path(executable).resolve().parent
shutil.copytree(source, dest / source.name, symlinks=True)
root = dest / source.name
cfgs = sorted(root.glob("playwright.cfg")) or sorted(root.rglob("playwright.cfg"))
if not cfgs:
raise RuntimeError("Playwright's Firefox has no playwright.cfg under %s: the reference cannot be made" % source.name)
removed, kept = [], []
text = cfgs[0].read_bytes().decode("utf-8")
for line in text.splitlines(keepends=True):
if re.match(r"\s*(pref|lockPref|defaultPref)\(\"%s\"" % re.escape(CFG_DARK_PREF), line):
removed.append(line.strip())
else:
kept.append(line)
if not removed:
raise RuntimeError("playwright.cfg does not force %s: the reference was expected to differ from it" % CFG_DARK_PREF)
cfgs[0].write_bytes("".join(kept).encode("utf-8"))
return str(root / Path(executable).name), removed
def control(out: Path, headless: bool = False) -> int:
"""Launch Playwright's own Firefox (headed: a headless Firefox has no theme to read) on this runner, read the probe, write `out`.
0 when it read the poison, 2 BROKEN CONTROL (the poison is not in force or the control cannot see it)."""
from playwright.sync_api import sync_playwright
out.parent.mkdir(parents=True, exist_ok=True)
probe = None
error = None
removed = []
try:
import tempfile
with sync_playwright() as p, tempfile.TemporaryDirectory(prefix="poison-control-", ignore_cleanup_errors=True) as work:
executable, removed = reference_firefox(p.firefox.executable_path, Path(work))
browser = p.firefox.launch(executable_path=executable, headless=headless, firefox_user_prefs={"intl.regional_prefs.use_os_locales": True})
try:
# Playwright's default is a LIGHT scheme (an emulation): the control must follow the system, as a user's browser does
page = browser.new_context(color_scheme="no-override").new_page()
page.goto("about:blank")
probe = page.evaluate("(async () => {%s; return await abPoisonProbe(); })()" % probe_source())
finally:
browser.close()
except Exception as e: # noqa: BLE001 - a control that could not run is a broken control, with the reason
error = "%s: %s" % (type(e).__name__, str(e)[:500])
failures = [("run", error)] if error else control_failures(probe, system_name())
trials = control_trials(probe, system_name())
report = {"format": "poison-control/1", "system": system_name(), "probe": probe, "language": language_reads(probe),
"failures": [{"requirement": n, "message": m} for n, m in failures], "verdict": "green" if not failures else "broken",
"in_trial": {"requirements": {k: list(v) for k, v in IN_TRIAL.items()}, "not_read": [{"requirement": n, "message": m} for n, m in trials]},
"reference": {"taken_out_of_playwright_cfg": removed}}
out.write_text(json.dumps(report, sort_keys=True, indent=1, ensure_ascii=False), encoding="utf-8")
print("stock Firefox read: %s" % json.dumps(probe, sort_keys=True, ensure_ascii=False))
print("language, informational: %s" % json.dumps(report["language"], sort_keys=True, ensure_ascii=False))
for name, message in failures:
print("BROKEN CONTROL (%s): %s" % (name, message))
for name, message in trials:
print("IN TRIAL, not required (%s): %s" % (name, message))
summary = os.environ.get("GITHUB_STEP_SUMMARY")
if summary:
with open(summary, "a", encoding="utf-8", newline="\n") as f:
f.write(control_markdown(report))
print("POISON CONTROL %s" % ("OK" if not failures else "BROKEN"))
return 0 if not failures else 2
# -
# Putting the poison on a machine, and taking it off.
def _run(cmd: list) -> tuple:
try:
done = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=180)
except (OSError, subprocess.SubprocessError) as e: # the program is not on this machine, or did not answer
return 127, "%s: %s" % (type(e).__name__, e)
return done.returncode, (done.stdout or "") + (done.stderr if done.returncode else "")
#: Every PowerShell of this script: the invariant culture on its own thread first (the culture of the machine is what the poison changes).
PS_PRELUDE = ("[System.Threading.Thread]::CurrentThread.CurrentCulture = [System.Globalization.CultureInfo]::InvariantCulture; "
"$ErrorActionPreference = 'Stop'; ")
def ps(script: str) -> list:
return ["powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", PS_PRELUDE + script]
def _ok(run: Run, cmd: list, what: str) -> str:
rc, text = run(cmd)
if rc != 0:
raise SystemExit("the poison could not %s (exit %s): %s" % (what, rc, text.strip()[:400]))
return text.strip()
def _try(run: Run, cmd: list) -> str:
rc, text = run(cmd)
return text.strip() if rc == 0 else ""
def font_path_windows(env=None) -> Path:
"""Where the canary goes on Windows: the Fonts folder of the system, which every user and every process reads (HKLM lists it, FONTS_KEY)."""
env = env or os.environ
return Path(env.get("SystemRoot") or env.get("WINDIR") or "C:" + chr(92) + "Windows") / "Fonts" / FONT_FILE
def font_dir_linux(env=None) -> Path:
env = env or os.environ
base = env.get("XDG_DATA_HOME") or str(Path(env.get("HOME") or Path.home()) / ".local" / "share")
return Path(base) / "fonts"
def _reg_get(name: str) -> list:
return ps("$v = (Get-ItemProperty -Path '%s' -Name %s -ErrorAction SilentlyContinue).%s; if ($null -ne $v) { $v }" % (THEME_KEY, name, name))
def _reg_set(name: str, value) -> list:
if value in ("", None):
return ps("Remove-ItemProperty -Path '%s' -Name %s -ErrorAction SilentlyContinue" % (THEME_KEY, name))
return ps("New-ItemProperty -Path '%s' -Name %s -Value %s -PropertyType DWord -Force | Out-Null" % (THEME_KEY, name, int(value)))
def apply_windows(run: Run = _run, font_dir: Path | None = None) -> dict:
"""Put the poison on this Windows machine; returns the state `undo_windows` needs (what was there before, as text read before any change)."""
font = font_path_windows() if font_dir is None else Path(font_dir) / FONT_FILE
state = {"system": "windows", "font": str(font),
"timezone": _ok(run, ["tzutil", "/g"], "read the time zone"),
"culture": _ok(run, ps("(Get-Culture).Name"), "read the culture"),
"languages": _ok(run, ps("(Get-WinUserLanguageList | ForEach-Object { $_.LanguageTag }) -join ','"), "read the user languages"),
"theme": {n: _try(run, _reg_get(n)) for n in ("AppsUseLightTheme", "SystemUsesLightTheme")}}
_ok(run, ["tzutil", "/s", WINDOWS_ZONE], "set the time zone")
_ok(run, ps("Set-Culture -CultureInfo '%s'" % CULTURE), "set the culture")
_ok(run, ps("Set-WinUserLanguageList -LanguageList '%s' -Force" % CULTURE), "set the user language list")
for name in state["theme"]:
_ok(run, _reg_set(name, 0), "set " + name)
font.parent.mkdir(parents=True, exist_ok=True)
font.write_bytes(canary_font())
_ok(run, ps("New-ItemProperty -Path '%s' -Name '%s' -Value '%s' -PropertyType String -Force | Out-Null" % (FONTS_KEY, FONT_VALUE, font)),
"register the canary font")
_announce_font(str(font))
state["after"] = windows_reads(run)
return state
def primary_language(tag: str) -> str:
"""The language of a tag, whatever its form: 'ja', 'ja-JP' and 'ja_JP' are Japanese."""
return re.split(r"[-_]", (tag or "").strip(), maxsplit=1)[0].lower()
def windows_reads(run: Run = _run) -> dict:
"""What this Windows machine reports about the poison, in the form it reports it (Windows keeps the tag 'ja' for the list that was set from
'ja-JP'): the apply records it and verify holds the machine to it later, besides the semantic check that it is Japanese."""
return {"timezone": _try(run, ["tzutil", "/g"]),
"culture": _try(run, ps("(Get-Culture).Name")),
"languages": _try(run, ps("(Get-WinUserLanguageList | ForEach-Object { $_.LanguageTag }) -join ','")),
"theme": {n: _try(run, _reg_get(n)) for n in ("AppsUseLightTheme", "SystemUsesLightTheme")}}
def _announce_font(path: str) -> None:
"""Tell the running session about the font (AddFontResourceW and WM_FONTCHANGE); a process started later reads the registry anyway."""
try:
import ctypes
ctypes.windll.gdi32.AddFontResourceW(path)
ctypes.windll.user32.SendMessageTimeoutW(0xFFFF, 0x001D, 0, 0, 2, 1000, None)
except Exception: # noqa: BLE001 - best effort: the registry entry is what a new process reads
pass
def _forget_font(path: str) -> None:
try:
import ctypes
ctypes.windll.gdi32.RemoveFontResourceW(path)
except Exception: # noqa: BLE001 - best effort, as the announcement
pass
def undo_windows(state: dict, run: Run = _run) -> None:
font = Path(state["font"])
_try(run, ps("Remove-ItemProperty -Path '%s' -Name '%s' -ErrorAction SilentlyContinue" % (FONTS_KEY, FONT_VALUE)))
_forget_font(str(font))
try:
font.unlink()
except OSError:
pass
for name, value in state["theme"].items():
_try(run, _reg_set(name, value))
if state.get("languages"):
_try(run, ps("Set-WinUserLanguageList -LanguageList %s -Force" % ",".join("'%s'" % t for t in state["languages"].split(","))))
if state.get("culture"):
_try(run, ps("Set-Culture -CultureInfo '%s'" % state["culture"]))
if state.get("timezone"):
_try(run, ["tzutil", "/s", state["timezone"]])
def verify_windows(run: Run = _run, state: dict | None = None) -> list:
problems = []
font = Path(state["font"]) if state else font_path_windows()
tz = _try(run, ["tzutil", "/g"])
if tz != WINDOWS_ZONE:
problems.append("time zone is %r, not %r" % (tz, WINDOWS_ZONE))
reads = windows_reads(run)
recorded = (state or {}).get("after") or {}
for what, value in (("culture", reads["culture"]), ("first user language", reads["languages"].split(",")[0])):
if primary_language(value) != primary_language(CULTURE):
problems.append("the %s is %r, which is not Japanese" % (what, value))
for key, what in (("culture", "culture"), ("languages", "user language list")):
if recorded.get(key) and reads[key] != recorded[key]:
problems.append("the %s is %r, the apply recorded %r" % (what, reads[key], recorded[key]))
for name in ("AppsUseLightTheme", "SystemUsesLightTheme"):
value = _try(run, _reg_get(name))
if value != "0":
problems.append("%s is %r, not 0 (dark)" % (name, value))
registered = _try(run, ps("(Get-ItemProperty -Path '%s' -Name '%s' -ErrorAction SilentlyContinue).'%s'" % (FONTS_KEY, FONT_VALUE, FONT_VALUE)))
if os.path.normcase(registered) != os.path.normcase(str(font)):
problems.append("the canary font is registered at %r, not %r" % (registered, str(font)))
problems += _font_file_problems(font)
return problems
def _font_file_problems(font: Path) -> list:
if not font.is_file():
return ["the canary font file %s is missing" % font.name]
if hashlib.sha256(font.read_bytes()).hexdigest() != CANARY_SHA256:
return ["the canary font file is not the canary (sha256 differs from %s)" % CANARY_SHA256]
return []
def _sudo(cmd: list) -> list:
return cmd if getattr(os, "geteuid", lambda: 0)() == 0 else ["sudo", "-n"] + cmd
def _sink_server(info: str) -> str:
m = re.search(r"^Server String:\s*(\S+)", info, re.M)
return m.group(1) if m else ""
def fonts_conf() -> str:
"""The user's fontconfig file of the Linux poison: the canary is the first choice of the three generic families, and the rendering
settings are ones no desktop has (no antialiasing, full hinting, rgb subpixels, the light LCD filter). The engine's default FcConfig is
still the host's (FcConfigSubstitute(nullptr, ...) in gfxFcPlatformFontList and ScaledFontFontconfig), so a page that reads what this
changes read the host."""
aliases = "".join(' <alias binding="strong"><family>%s</family><prefer><family>%s</family></prefer></alias>\n' % (g, FAMILY) for g in GENERICS)
return ('<?xml version="1.0"?>\n<!DOCTYPE fontconfig SYSTEM "fonts.dtd">\n<fontconfig>\n' + aliases
+ ' <match target="font">\n'
' <edit name="antialias" mode="assign"><bool>false</bool></edit>\n'
' <edit name="hinting" mode="assign"><bool>true</bool></edit>\n'
' <edit name="hintstyle" mode="assign"><const>hintfull</const></edit>\n'
' <edit name="rgba" mode="assign"><const>rgb</const></edit>\n'
' <edit name="lcdfilter" mode="assign"><const>lcdlight</const></edit>\n'
' </match>\n</fontconfig>\n')
def fonts_conf_path(env=None) -> Path:
env = env or os.environ
base = env.get("XDG_CONFIG_HOME") or str(Path(env.get("HOME") or Path.home()) / ".config")
return Path(base) / "fontconfig" / "fonts.conf"
def apply_linux(run: Run = _run, font_dir: Path | None = None, audio: bool = True, conf_file: Path | None = None) -> dict:
"""Put the poison on this Linux machine; returns the state `undo_linux` needs. The environment part is for the later steps of the job
(state["env"], appended to $GITHUB_ENV by `apply`)."""
fonts = font_dir_linux() if font_dir is None else Path(font_dir)
state = {"system": "linux", "font": str(fonts / FONT_FILE), "env": dict(LINUX_ENV),
"before_env": {k: os.environ.get(k, "") for k in list(LINUX_ENV) + ["PULSE_SERVER"]}, "module": ""}
if "ja_jp.utf8" not in _try(run, ["locale", "-a"]).lower().replace("-", ""):
_ok(run, _sudo(["locale-gen", LINUX_LANG]), "generate the %s locale" % LINUX_LANG)
fonts.mkdir(parents=True, exist_ok=True)
(fonts / FONT_FILE).write_bytes(canary_font())
conf = fonts_conf_path() if conf_file is None else Path(conf_file)
state["fonts_conf"] = {"path": str(conf), "before": conf.read_text(encoding="utf-8") if conf.is_file() else None}
conf.parent.mkdir(parents=True, exist_ok=True)
conf.write_text(fonts_conf(), encoding="utf-8", newline="\n")
_ok(run, ["fc-cache", "-f", str(fonts)], "refresh the font cache")
if audio:
_try(run, ["pulseaudio", "--daemonize=yes", "--exit-idle-time=-1", "--disallow-exit"])
module = _ok(run, ["pactl", "load-module", "module-null-sink", "sink_name=" + SINK, "rate=%d" % SINK_RATE,
"channels=%d" % SINK_CHANNELS, "channel_map=" + SINK_MAP, "sink_properties=device.description=" + SINK],
"load the null sink")
state["module"] = module
_ok(run, ["pactl", "set-default-sink", SINK], "make the null sink the default")
server = _sink_server(_try(run, ["pactl", "info"]))
if server:
state["env"]["PULSE_SERVER"] = server if "://" in server or ":" in server.split("/")[0] else "unix:" + server
return state
def undo_linux(state: dict, run: Run = _run) -> None:
if state.get("module"):
_try(run, ["pactl", "unload-module", state["module"]])
_try(run, ["pulseaudio", "--kill"])
font = Path(state["font"])
try:
font.unlink()
except OSError:
pass
saved = state.get("fonts_conf")
if saved: # the file that was there comes back, or the one this wrote goes
conf = Path(saved["path"])
try:
if saved["before"] is None:
conf.unlink()
else:
conf.write_text(saved["before"], encoding="utf-8", newline="\n")
except OSError:
pass
_try(run, ["fc-cache", "-f", str(font.parent)])
def verify_linux(run: Run = _run, state: dict | None = None, expect_env: bool = False, audio: bool = True, env=None) -> list:
problems = []
font = Path(state["font"]) if state else font_dir_linux() / FONT_FILE
if "ja_jp.utf8" not in _try(run, ["locale", "-a"]).lower().replace("-", ""):
problems.append("the %s locale is not installed" % LINUX_LANG)
problems += _font_file_problems(font)
if FAMILY not in _try(run, ["fc-list", ":", "family"]):
problems.append("fontconfig does not list the family %s" % FAMILY)
conf = Path(state["fonts_conf"]["path"]) if state and state.get("fonts_conf") else fonts_conf_path()
if not conf.is_file() or conf.read_text(encoding="utf-8") != fonts_conf():
problems.append("the user's fonts.conf is not the poison's")
for generic in GENERICS:
picked = _try(run, ["fc-match", "-f", "%{family}", generic])
if FAMILY not in picked:
problems.append("fontconfig answers %r for %s, not the canary" % (picked, generic))
if audio:
sinks = _try(run, ["pactl", "list", "short", "sinks"])
line = next((ln for ln in sinks.splitlines() if SINK in ln), "")
if "%dch %dHz" % (SINK_CHANNELS, SINK_RATE) not in line:
problems.append("the null sink %s is not %d channels at %d Hz: %r" % (SINK, SINK_CHANNELS, SINK_RATE, line))
if SINK not in _try(run, ["pactl", "get-default-sink"]):
problems.append("the null sink is not the default sink")
if expect_env:
e = os.environ if env is None else env
problems += ["%s is %r in this process, not %r" % (k, e.get(k), v) for k, v in LINUX_ENV.items() if e.get(k) != v]
if audio and not e.get("PULSE_SERVER"):
problems.append("PULSE_SERVER is not set in this process: Firefox would not find the null sink's server")
return problems
def verify_here(expect_env: bool = False, run: Run = _run) -> list:
"""Is the poison in force on this machine, for a process that wants to know (the page oracle's test): what apply wrote in the state file
named by AB_ORACLE_POISON_STATE tells where the font is and whether there is a null sink."""
state_file = os.environ.get(STATE_SWITCH)
state = json.loads(Path(state_file).read_text(encoding="utf-8")) if state_file and Path(state_file).is_file() else None
if system_name() == "windows":
return verify_windows(run, state)
return verify_linux(run, state, expect_env, audio=bool(state and state.get("audio")))
def github_env_lines(env: dict) -> str:
return "".join("%s=%s\n" % (k, v) for k, v in env.items())
def apply(state_file: Path | None, audio: bool = True, run: Run = _run) -> int:
system = system_name()
state = apply_windows(run) if system == "windows" else apply_linux(run, audio=audio)
state["audio"] = audio and system == "linux"
if state_file:
state_file.parent.mkdir(parents=True, exist_ok=True)
state_file.write_text(json.dumps(state, sort_keys=True, indent=1), encoding="utf-8")
target = os.environ.get("GITHUB_ENV")
if target and state_file: # what was changed must be undoable even when it is not in force: the undo step reads this
with open(target, "a", encoding="utf-8", newline="\n") as f:
f.write(github_env_lines({STATE_SWITCH: str(state_file.resolve())}))
problems = verify_windows(run, state) if system == "windows" else verify_linux(run, state, audio=state["audio"])
for p in problems:
print("POISON NOT IN FORCE: " + p)
if problems:
return 2
env = dict(state.get("env", {}), **{SWITCH: "1"})
if state_file:
env[STATE_SWITCH] = str(state_file.resolve())
if target:
with open(target, "a", encoding="utf-8", newline="\n") as f:
f.write(github_env_lines(env))
print("the host is poisoned (%s): %s" % (system, json.dumps({k: v for k, v in state.items() if k not in ("before_env",)}, sort_keys=True)))
return 0
def undo(state_file: Path, run: Run = _run) -> int:
state = json.loads(state_file.read_text(encoding="utf-8"))
if state["system"] == "windows":
undo_windows(state, run)
else:
undo_linux(state, run)
target = os.environ.get("GITHUB_ENV")
if target: # the later steps of the job read what it was
with open(target, "a", encoding="utf-8", newline="\n") as f:
f.write(github_env_lines(dict(state["before_env"], **{SWITCH: "", STATE_SWITCH: ""})))
print("the poison is taken off (%s)" % state["system"])
return 0
def main(argv=None) -> int:
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
sub = ap.add_subparsers(dest="cmd", required=True)
a = sub.add_parser("apply")
a.add_argument("--state", type=Path)
a.add_argument("--no-audio", action="store_true", help="Linux: no null audio sink")
v = sub.add_parser("verify")
v.add_argument("--state", type=Path)
v.add_argument("--expect-env", action="store_true")
v.add_argument("--no-audio", action="store_true")
u = sub.add_parser("undo")
u.add_argument("--state", type=Path, required=True)
c = sub.add_parser("control")
c.add_argument("--out", type=Path, required=True)
c.add_argument("--headless", action="store_true")
f = sub.add_parser("font")
f.add_argument("--out", type=Path, required=True)
args = ap.parse_args(argv)
if args.cmd == "apply":
return apply(args.state, audio=not args.no_audio)
if args.cmd == "undo":
return undo(args.state)
if args.cmd == "control":
return control(args.out, args.headless)
if args.cmd == "font":
args.out.write_bytes(canary_font())
print(canary_sha256())
return 0
state = json.loads(args.state.read_text(encoding="utf-8")) if args.state else None
system = system_name()
problems = verify_windows(_run, state) if system == "windows" else verify_linux(_run, state, args.expect_env, not args.no_audio)
for p in problems:
print("POISON NOT IN FORCE: " + p)
return 2 if problems else 0
if __name__ == "__main__":
sys.exit(main())
-208
View File
@@ -1,208 +0,0 @@
#!/usr/bin/env python3
"""Writes ci/py-lock/gate.in from its sources and compiles ci/py-lock/gate.txt, the lock of the `gate` environment (ci-03).
The engine series' gate installs the wrapper's environment from a wheelhouse resolved once per image, Python and lock, offline: no unpinned `pip install`
anywhere. The lock of that environment lives HERE, because what it must cover is declared here and is read at the wrapper_ref the gate selects. It holds every
THIRD-PARTY distribution the gate installs from the wrapper:
* the wrapper's dependencies (`[project].dependencies` of pyproject.toml, without `invisible_core`, which is built as a wheel of ours) and its `dev` extra;
* the dependencies of the core the wrapper pins (`invisible_core==X`: the `[project].dependencies` of the core's pyproject.toml at the tag vX);
* playwright at scripts/playwright_pin.txt (the stock client the gate drives the engine with) and cryptography at CRYPTOGRAPHY (the lab's PKI);
* the installer the install-from-index job needs beside pytest (HARNESS: `uv`, which the release test installs the package with and the wait asks), so that
job installs its test harness from this lock and from nothing else (tests/test_the_install_job_has_every_module_its_tests_import.py).
One command regenerates both files after a dependency change or a bump of the core pin:
python scripts/ci_py_lock.py --core-pyproject <pyproject.toml of the core at the tag vX> [--exclude-newer 2026-11-25T00:00:00Z] [--uv uv]
The resolver is the series' (`uv pip compile --universal --generate-hashes --no-build`, every file of every version hashed), so the same input gives the same
bytes there and here. tests/test_the_gate_lock_follows_the_sources.py reads the committed files with this module, offline.
"""
from __future__ import annotations
import argparse
import hashlib
import re
import subprocess
import sys
import tempfile
import tomllib
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
LOCK_DIR = ROOT / "ci" / "py-lock"
IN_PATH = LOCK_DIR / "gate.in"
TXT_PATH = LOCK_DIR / "gate.txt"
PYPROJECT = ROOT / "pyproject.toml"
PLAYWRIGHT_PIN = ROOT / "scripts" / "playwright_pin.txt"
#: What the lab's PKI needs, as the series' gate installs it today.
CRYPTOGRAPHY = "cryptography==44.0.3"
#: Installers the install-from-index job (user-install.yml) needs and no dependency of the wrapper brings: the README's way in (`uv`) and the wait on the index.
HARNESS = ["uv>=0.5"]
#: The floor of the lock: the Python the unit job judges; `--universal` covers every Linux and Windows wheel of every Python from it.
PYTHON_VERSION = "3.11"
DEFAULT_EXCLUDE_NEWER = "2026-11-25T00:00:00Z"
#: The separator of the core's requirements in a header line (a requirement can contain commas).
SEP = " | "
HASH_RE = re.compile(r"^--hash=sha256:[0-9a-f]{64}$")
PIN_RE = re.compile(r"^([A-Za-z0-9][A-Za-z0-9._-]*(?:\[[A-Za-z0-9,._-]+\])?)==([A-Za-z0-9][A-Za-z0-9.!+_-]*)(?: ; (.+))?$")
CORE_PIN_RE = re.compile(r"^invisible[-_]core==([0-9][0-9A-Za-z.!+_-]*)$")
def norm(name: str) -> str:
return re.sub(r"[-_.]+", "-", name).lower()
def base_name(requirement: str) -> str:
return norm(re.split(r"[\[<>=!~ ;]", requirement, maxsplit=1)[0])
def sha256_text(text: str) -> str:
"""sha256 of the text with LF line ends: the bytes the index stores, whatever a Windows checkout did to them."""
return hashlib.sha256(text.replace("\r\n", "\n").encode("utf-8")).hexdigest()
def read_in(text: str) -> dict:
"""The input file: `# key: value` header lines, then one requirement per line."""
meta, reqs = {}, []
for line in text.replace("\r\n", "\n").splitlines():
line = line.strip()
if not line:
continue
m = re.match(r"^#\s*([a-z-]+):\s*(.*)$", line)
if m:
meta[m.group(1)] = m.group(2).strip()
elif not line.startswith("#"):
reqs.append(line)
return {"meta": meta, "requirements": reqs}
def parse_lock(text: str) -> list:
"""[(name, version, marker, [hashes])] of a lock. A line that is not `name==version [; marker]` with hashes under it is an error: a range, a URL, an
editable, an index option, an entry with no hash."""
entries, current = [], None
for lineno, raw in enumerate(text.replace("\r\n", "\n").splitlines(), 1):
line = raw.rstrip()
if not line.strip() or line.lstrip().startswith("#"):
continue
body = line.strip()
if body.endswith("\\"):
body = body[:-1].rstrip()
if body.startswith("--hash="):
if current is None or not HASH_RE.match(body):
raise ValueError("line %d: a hash that is not sha256:<64 hex>, or none to hold it: %r" % (lineno, body))
current[3].append(body.split(":", 1)[1])
continue
m = PIN_RE.match(body)
if not m or line[0] in " \t":
raise ValueError("line %d: not `name==version`: %r" % (lineno, body))
current = (m.group(1), m.group(2), m.group(3) or "", [])
entries.append(current)
for name, version, _, hashes in entries:
if not hashes:
raise ValueError("%s==%s has no --hash" % (name, version))
return entries
# ── the sources ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
def wrapper_sources(pyproject_text: str) -> dict:
"""What pyproject.toml declares: the core pin, the other dependencies, the dev extra."""
project = tomllib.loads(pyproject_text)["project"]
pins = [d for d in project["dependencies"] if CORE_PIN_RE.match(d.strip())]
if len(pins) != 1:
raise SystemExit("pyproject.toml must carry exactly one `invisible_core==X` pin, found %r" % pins)
return {
"core_version": CORE_PIN_RE.match(pins[0].strip()).group(1),
"dependencies": [d for d in project["dependencies"] if d != pins[0]],
"dev": list(project["optional-dependencies"]["dev"]),
}
def core_dependencies(core_pyproject_text: str) -> list:
return list(tomllib.loads(core_pyproject_text)["project"]["dependencies"])
def expected_requirements(pyproject_text: str, core_requires: list, playwright_pin: str) -> list:
"""The requirements the lock must cover, in the order the input prints them."""
src = wrapper_sources(pyproject_text)
reqs = set(src["dependencies"]) | set(src["dev"]) | set(core_requires) | set(HARNESS) | {"playwright==%s" % playwright_pin.strip(), CRYPTOGRAPHY}
return sorted(reqs, key=lambda r: (base_name(r), r))
def make_in(pyproject_text: str, core_pyproject_text: str, playwright_pin: str, exclude_newer: str) -> str:
src = wrapper_sources(pyproject_text)
core_requires = core_dependencies(core_pyproject_text)
head = [
"# Input of the gate lock; `python scripts/ci_py_lock.py` writes it and gate.txt from the sources below. Wrapper-owned (ci-03), read at the wrapper_ref.",
"# python-version: %s" % PYTHON_VERSION,
"# exclude-newer: %s" % exclude_newer,
"# wrapper: pyproject.toml sha256 %s (at generation); its dependencies without invisible_core, and its `dev` extra" % sha256_text(pyproject_text),
"# core: invisible_core==%s, tag v%s, pyproject.toml sha256 %s (at generation); the core is a wheel of ours, only what it depends on is locked" % (
src["core_version"], src["core_version"], sha256_text(core_pyproject_text)),
"# core-requires: %s" % SEP.join(core_requires),
"# playwright: %s from scripts/playwright_pin.txt (the stock client the gate drives the engine with)" % playwright_pin.strip(),
"# cryptography: %s (the lab's PKI)" % CRYPTOGRAPHY.split("==")[1],
"# harness: %s (the installers of the install-from-index job)" % SEP.join(HARNESS),
]
return "\n".join(head + expected_requirements(pyproject_text, core_requires, playwright_pin)) + "\n"
# ── the lock ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
def lock_header(in_text: str, meta: dict) -> str:
return "\n".join([
"# Generated by `python scripts/ci_py_lock.py`: do not edit. Wrapper-owned (ci-03).",
"# input: ci/py-lock/gate.in sha256 %s" % sha256_text(in_text),
"# resolver: uv pip compile --universal --generate-hashes --no-build --python-version %s --exclude-newer %s" % (meta["python-version"], meta["exclude-newer"]),
"# Every file of each version is hashed (Linux and Windows wheels of every Python from %s, and the sdist): one lock for every OS." % meta["python-version"],
"# A consumer installs it with: pip install --no-index --find-links <wheelhouse> --require-hashes -r <this file>",
]) + "\n"
def normalise(raw: str, header: str) -> str:
"""What uv printed (no header, no annotations) as a lock: entries by name, hashes sorted, the given header. Same input, same bytes."""
entries = sorted(parse_lock(raw), key=lambda e: (norm(e[0]), e[1], e[2]))
lines = [header.rstrip("\n")]
for name, version, marker, hashes in entries:
lines.append("%s==%s%s \\" % (name, version, (" ; " + marker) if marker else ""))
hs = sorted(set(hashes))
lines += [" --hash=sha256:%s%s" % (h, " \\" if i < len(hs) - 1 else "") for i, h in enumerate(hs)]
return "\n".join(lines) + "\n"
def compile_lock(in_text: str, uv: str = "uv") -> str:
parsed = read_in(in_text)
meta = parsed["meta"]
with tempfile.TemporaryDirectory() as tmp:
src = Path(tmp) / "in.txt"
src.write_text("\n".join(parsed["requirements"]) + "\n", encoding="utf-8")
out = subprocess.run([uv, "pip", "compile", str(src), "--universal", "--generate-hashes", "--no-build", "--no-header", "--no-annotate", "--quiet",
"--python-version", meta["python-version"], "--exclude-newer", meta["exclude-newer"]],
check=True, capture_output=True, text=True).stdout
return normalise(out, lock_header(in_text, meta))
def main(argv=None) -> int:
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("--core-pyproject", required=True, help="pyproject.toml of the core at the tag of the pin (invisible_core==X -> tag vX)")
ap.add_argument("--exclude-newer", default=None, help="ignore releases newer than this (default: the one of the committed gate.in, else %s)" % DEFAULT_EXCLUDE_NEWER)
ap.add_argument("--uv", default="uv", help="the uv executable")
a = ap.parse_args(argv)
exclude = a.exclude_newer
if exclude is None:
exclude = read_in(IN_PATH.read_text(encoding="utf-8"))["meta"].get("exclude-newer") if IN_PATH.exists() else None
in_text = make_in(PYPROJECT.read_text(encoding="utf-8"), Path(a.core_pyproject).read_text(encoding="utf-8"),
PLAYWRIGHT_PIN.read_text(encoding="utf-8"), exclude or DEFAULT_EXCLUDE_NEWER)
LOCK_DIR.mkdir(parents=True, exist_ok=True)
IN_PATH.write_text(in_text, encoding="utf-8", newline="\n")
txt = compile_lock(in_text, a.uv)
TXT_PATH.write_text(txt, encoding="utf-8", newline="\n")
print("ci/py-lock/gate.in and gate.txt written (%d direct requirements, %d locked distributions)" % (len(read_in(in_text)["requirements"]), len(parse_lock(txt))))
return 0
if __name__ == "__main__":
sys.exit(main())
-116
View File
@@ -1,116 +0,0 @@
#!/usr/bin/env python3
"""Run ONE row of the whole-e2e suite against a binary, for the candidate's gate, and write ONE junit for the judge.
ci_suite_run.py --required ci/required-suites.json --suite wrapper.e2e.suite.linux.1 --os linux --binary FF --junit result/x.xml
The run is the run of ``scripts/run_e2e.py`` (``invisible_core.testing.e2e``: the two passes, ``-m "e2e and not wall_clock"`` with 4 browsers at once and then
``-m "e2e and wall_clock"`` alone, ``--dist loadfile``, the deadline per test, no rerun) on the files and node ids of the row; this script does not copy it, it calls it.
What it adds is the end: that run writes one junit per pass, and the judge (``scripts/ci_verdict.py judge``) reads one. The two are merged into ONE xunit2 file, every
testcase as pytest wrote it (``classname`` kept, no ``file``/``line``).
The exit code is 0 when the passes reached their end, red tests included: the verdict is the judge's, and a failed test is a line of its list, not a reason to lose the
junit. It is not 0 when a pass did not run to its end (interrupted, an internal error, a usage error: the code of that pass) or when no junit was written at all.
"""
from __future__ import annotations
import argparse
import copy
import os
import sys
import tempfile
import xml.etree.ElementTree as ET
from pathlib import Path
from typing import Callable, Optional, Sequence
sys.path.insert(0, str(Path(__file__).resolve().parent))
import ci_verdict # noqa: E402 (the judge: the row is read the way it reads it)
#: pytest's exit codes that mean "the pass reached its end": all passed, some failed, nothing collected (a client with no `wall_clock` test has an empty pass).
_REACHED_THE_END = (0, 1, 5)
def row_arguments(required: str, suite: str, os_name: str) -> list:
"""The files and node ids of the row, in its order (what ``ci_verdict.py args`` prints, without the marker: the passes bring their own)."""
return list(ci_verdict.find_suite(ci_verdict.load_required(required), suite, os_name)["tests"])
def pass_junits(directory: Path, procs: str = "4") -> list:
"""The junit file of each pass of the run, in the order of the passes (``invisible_core.testing.e2e`` names them)."""
from invisible_core.testing import e2e
return [e2e.junit_file(Path(directory), selection) for _width, selection in e2e.passes(procs)]
def merge_junits(paths: Sequence, out: Path) -> int:
"""Write ONE xunit2 junit with every testcase of the junit files that exist, in the order given. -> the number of testcases.
The counts of the testsuite are those of the testcases written, not the sum of the headers read: a header that disagrees with its own cases is not copied.
A path that does not exist is a pass that wrote nothing (it is not an error here: the judge counts what is in the file)."""
cases = []
for path in paths:
if not Path(path).is_file():
continue
cases += [copy.deepcopy(c) for c in ET.parse(path).getroot().iter("testcase")]
tags = [{child.tag for child in c} for c in cases]
failures = sum(1 for t in tags if "failure" in t and "error" not in t)
errors = sum(1 for t in tags if "error" in t)
skipped = sum(1 for t in tags if "skipped" in t and not ({"failure", "error"} & t))
seconds = sum(float(c.get("time") or 0) for c in cases)
suite = ET.Element("testsuite", {"name": "pytest", "errors": str(errors), "failures": str(failures), "skipped": str(skipped),
"tests": str(len(cases)), "time": "%.3f" % seconds})
suite.extend(cases)
root = ET.Element("testsuites", {"name": "pytest tests"})
root.append(suite)
out = Path(out)
out.parent.mkdir(parents=True, exist_ok=True)
ET.ElementTree(root).write(out, encoding="utf-8", xml_declaration=True)
return len(cases)
def run(required: str, suite: str, os_name: str, binary: str, junit: str, *, repo: Path, procs: Optional[str] = None,
run_e2e: Optional[Callable] = None, junit_directory: Optional[Path] = None) -> int:
"""Run the row and write the merged junit. ``run_e2e`` is ``invisible_core.testing.e2e.main`` (a fake in the unit tests)."""
from invisible_core.testing import e2e
run_e2e = run_e2e or e2e.main
arguments = row_arguments(required, suite, os_name)
directory = Path(junit_directory or tempfile.mkdtemp(prefix="invpw-suite-junit-"))
# the core reads the directory of the junit from the environment (its own order: this variable, the watchdog's folder, the checkout): one name, set for this run
before = os.environ.get(e2e.JUNIT_DIR_ENV)
os.environ[e2e.JUNIT_DIR_ENV] = str(directory)
try:
code = run_e2e([binary] + (["-n", procs] if procs else []) + arguments, repo)
finally:
if before is None:
os.environ.pop(e2e.JUNIT_DIR_ENV, None)
else:
os.environ[e2e.JUNIT_DIR_ENV] = before
written = merge_junits(pass_junits(directory, procs or "4"), Path(junit))
print("[ci_suite_run] %s on %s: %d test(s) in %s" % (suite, os_name, written, junit), flush=True)
if code not in _REACHED_THE_END:
print("[ci_suite_run] a pass did not run to its end (exit %s)" % code, file=sys.stderr)
return code
if not written:
print("[ci_suite_run] no pass wrote a junit", file=sys.stderr)
return 3
return 0
def main(argv: Optional[Sequence[str]] = None) -> int:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--required", required=True, help="ci/required-suites.json")
parser.add_argument("--suite", required=True, help="the id of the row")
parser.add_argument("--os", required=True, choices=ci_verdict.OSES)
parser.add_argument("--binary", required=True, help="the engine under test")
parser.add_argument("--junit", required=True, help="the one junit written for the judge")
parser.add_argument("--procs", default=None, help="browsers at once, for the first pass (default: the run's own, 4)")
ns = parser.parse_args(argv)
try:
return run(ns.required, ns.suite, ns.os, ns.binary, ns.junit, repo=Path(__file__).resolve().parent.parent, procs=ns.procs)
except ci_verdict.Usage as exc:
print("ci_suite_run.py: %s" % exc, file=sys.stderr)
return 2
if __name__ == "__main__":
sys.exit(main())
+12 -235
View File
@@ -21,14 +21,6 @@ pytest wrote and fails on every one of them.
missing (--binary is mandatory: without it exit 2) or the commit cannot be known; the --seal is unreadable.
With --main-required (the list of main) the list only grows: a suite of main is gone, its minimum went down,
its `exact` went from true to false, its os or tests lost an element, or its marker changed is red.
The one exception is `retired-tests.json` NEXT TO main's list (read from main, never from the judged branch): a file it names that
no longer exists in the checkout may leave the rows, and the minimum of a row may go down by the tests main counted for it in that
row (`tests: {row id: n}`), and by no more. A retired file still on disk, or any other lost test, stays red.
The same file may also retire single tests whose file stays: {"nodeid": "<file>::<test>", "suite": <row id>, "count": n, "reason",
"decided_by", "date", "from_min_tests"}. The minimum of that row may go down by the sum of the `count` of its entries and by no more, and
only for a nodeid whose file the row of main lists, and only while main's minimum of that row still equals `from_min_tests` (once the removal
is on main and its floor is lower, the entry is inert); a declared nodeid that the judged leg still collects is red, and so is any test that
goes without an entry.
What the file of main is can be said only by the gate, which checks main out (a failed download is not
"main has no list"): the file exists -> it is compared; it does not exist and the gate passed
--main-has-no-list (main was checked out and has no such file) -> passed, declared; it does not exist
@@ -49,23 +41,6 @@ The list is validated by all three commands (a malformed one is exit 2, with the
row `os` a non-empty subset of {linux, windows}, `tests` a non-empty list of unique strings, `min_tests` an integer > 0,
`exact` a bool, `marker` a string, `needs_root` a bool or a list of the row's OSes.
Optional fields of a row, read by the gate to build the leg of the row (absent = the plain behaviour; a field that is
present with a wrong type or value is a malformed list, exit 2, naming the row and the field; a name that is not listed
here is ignored as it always was):
runner_image object OS -> runner image name, only OSes of the row, e.g. {"windows": "windows-2022"}
(default: ubuntu-24.04 on Linux, windows-latest on Windows)
timeout_minutes integer 1..360, the timeout of the job (default 25)
needs_userns bool or list of the row's OSes: user namespaces for a normal user (the sandbox suite)
core_dumps false, "cores" or "invpw-cores" (Linux only): where the kernel writes the cores of a crashed
browser, $RUNNER_TEMP/cores or $RUNNER_TEMP/invpw-cores
stock_firefox bool or list of the row's OSes: Playwright's own Firefox is installed for the leg
location_service bool or list of the row's OSes: the Windows location service is turned on
run "pytest" (default) or "suite_run" (scripts/ci_suite_run.py, two passes)
extra_steps list of names from the closed set {fakeweb_profiles, keep_oracle_files}
moz_log string of MOZ_LOG modules appended to the suite's MOZ_LOG, no space
juggler_trace bool: the Juggler's own trace is kept with the result
artifact name of the artifact that keeps the oracle files (default: the suite id)
A required entry of "tests" is a file (at least one test of it must exist and EVERY one collected must pass) or a node
id `tests/x.py::name` (that test must pass; a parametrized test is matched on the name before `[`, and every one of its
parameters must pass).
@@ -91,12 +66,6 @@ import xml.etree.ElementTree as ET
from pathlib import Path
OSES = ("linux", "windows")
#: The optional row fields of the form "bool or a list of the row's OSes" (besides needs_root).
OS_FLAGS = ("needs_userns", "stock_firefox", "location_service")
CORE_DUMPS = ("cores", "invpw-cores")
RUN_MODES = ("pytest", "suite_run")
#: The closed set of the extra steps a row may ask of the gate (a name here is a step the gate knows how to run).
EXTRA_STEPS = ("fakeweb_profiles", "keep_oracle_files")
class Usage(Exception):
@@ -150,70 +119,14 @@ def validate_list(data):
problems.append("%s: exact must be true or false, not %r" % (where, row.get("exact")))
if not isinstance(row.get("marker"), str) or not row.get("marker").strip():
problems.append("%s: marker must be a non-empty string, not %r" % (where, row.get("marker")))
for name in ("needs_root",) + OS_FLAGS:
if name in row or name == "needs_root":
value = row.get(name, False)
if not _is_os_flag(value, oses, oses_ok):
problems.append("%s: %s must be a bool or a list of the OSes of the row, not %r" % (where, name, value))
problems.extend(_row_field_problems(row, where, oses, oses_ok))
root = row.get("needs_root", False)
if not isinstance(root, bool):
if not (isinstance(root, list) and all(isinstance(o, str) for o in root) and set(root) <= set(OSES)
and (not oses_ok or set(root) <= set(oses))):
problems.append("%s: needs_root must be a bool or a list of the OSes of the row, not %r" % (where, root))
return problems
def _is_os_flag(value, oses, oses_ok):
"""A bool, or a list of OSes that are all OSes of the row."""
if isinstance(value, bool):
return True
return (isinstance(value, list) and all(isinstance(o, str) for o in value) and set(value) <= set(OSES)
and (not oses_ok or set(value) <= set(oses)))
def _row_field_problems(row, where, oses, oses_ok):
"""The optional fields of a row that tell the gate how to build the leg (see the docstring): absent is the plain
behaviour; a field that is present with a value outside its type or its closed set is a problem, named."""
out = []
if "runner_image" in row:
image = row["runner_image"]
if not (isinstance(image, dict) and image and all(isinstance(k, str) and isinstance(v, str) and v.strip()
for k, v in image.items())):
out.append("%s: runner_image must be a non-empty object of OS -> image name, not %r" % (where, image))
else:
wrong = sorted(k for k in image if k not in OSES or (oses_ok and k not in oses))
if wrong:
out.append("%s: runner_image names an OS the row does not have: %s" % (where, ", ".join(wrong)))
if "timeout_minutes" in row:
minutes = row["timeout_minutes"]
if not _is_int(minutes) or not 0 < minutes <= 360:
out.append("%s: timeout_minutes must be an integer between 1 and 360, not %r" % (where, minutes))
if "core_dumps" in row:
dumps = row["core_dumps"]
if dumps is not False and dumps not in CORE_DUMPS:
out.append("%s: core_dumps must be false or one of %s, not %r" % (where, "/".join(CORE_DUMPS), dumps))
elif dumps is not False and oses_ok and "linux" not in oses:
out.append("%s: core_dumps is a Linux setting and the row has no linux leg" % where)
if "run" in row and (row["run"] not in RUN_MODES):
out.append("%s: run must be one of %s, not %r" % (where, "/".join(RUN_MODES), row["run"]))
if "extra_steps" in row:
steps = row["extra_steps"]
if not (isinstance(steps, list) and all(isinstance(x, str) for x in steps) and len(set(steps)) == len(steps)):
out.append("%s: extra_steps must be a list of distinct names, not %r" % (where, steps))
else:
unknown = sorted(set(steps) - set(EXTRA_STEPS))
if unknown:
out.append("%s: extra_steps names %s, outside the closed set %s"
% (where, ", ".join(unknown), ", ".join(EXTRA_STEPS)))
if "moz_log" in row:
modules = row["moz_log"]
if not (isinstance(modules, str) and modules and not any(c.isspace() for c in modules)):
out.append("%s: moz_log must be a non-empty string of MOZ_LOG modules with no space, not %r" % (where, modules))
if "juggler_trace" in row and not isinstance(row["juggler_trace"], bool):
out.append("%s: juggler_trace must be true or false, not %r" % (where, row["juggler_trace"]))
if "artifact" in row:
name = row["artifact"]
if not (isinstance(name, str) and name and all(c.isalnum() or c in "._-" for c in name)):
out.append("%s: artifact must be a non-empty name of letters, digits, '.', '_' and '-', not %r" % (where, name))
return out
def _read_json_list(path):
try:
return json.loads(Path(path).read_text(encoding="utf-8"))
@@ -335,138 +248,12 @@ def _int(value):
return value if _is_int(value) else 0
RETIRED_NAME = "retired-tests.json"
def validate_retired(data, suite_ids=None):
"""-> the reasons why `data` is not a well-formed list of retired tests (empty if it is). Two kinds of entry, in one list:
a FILE that is gone ({file, reason, date, tests: {row id: number of tests the file had in that row on main, counted with the row's marker}}), and
a single TEST whose file stays ({nodeid: "<file>::<test>", suite: row id, count > 0, reason, decided_by, date, from_min_tests: the minimum of
the row on main when the entry was written, an integer >= count, the same for every entry of a suite}). `suite_ids`, when given, are the row
ids of main's list: the suite of a nodeid entry must be one of them."""
if not isinstance(data, list):
return ["the retired list must be a JSON list"]
problems, seen, seen_nodes, froms = [], set(), set(), {}
for i, e in enumerate(data):
where = "retired entry %d" % i
if not isinstance(e, dict):
problems.append("%s is not an object" % where)
continue
if "nodeid" in e or "suite" in e:
problems += _validate_retired_node(e, where, suite_ids, seen_nodes)
if isinstance(e.get("suite"), str) and _is_int(e.get("from_min_tests")):
froms.setdefault(e["suite"], set()).add(e["from_min_tests"])
continue
f = e.get("file")
if not isinstance(f, str) or not f.strip():
problems.append("%s has no file" % where)
elif f in seen:
problems.append("%s: the file %s appears more than once" % (where, f))
else:
seen.add(f)
where = "retired %s" % f
for key in ("reason", "date"):
if not isinstance(e.get(key), str) or not e.get(key).strip():
problems.append("%s: %s must be a non-empty string" % (where, key))
counts = e.get("tests")
if not (isinstance(counts, dict) and counts and all(isinstance(k, str) and _is_int(v) and v > 0 for k, v in counts.items())):
problems.append("%s: tests must be {row id: number of tests of the file in that row (> 0)}" % where)
for suite, values in sorted(froms.items()):
if len(values) > 1:
problems.append("the retired tests of %s disagree on from_min_tests (%s): one suite, one floor of main" % (suite, sorted(values)))
return problems
def _validate_retired_node(e, where, suite_ids, seen):
problems = []
nid, suite = e.get("nodeid"), e.get("suite")
if "file" in e or "tests" in e:
problems.append("%s: an entry is a retired file (file, tests) or a retired test (nodeid, suite, count), not both" % where)
parts = nid.split("::", 1) if isinstance(nid, str) else []
if len(parts) != 2 or not parts[0].strip() or not parts[1].strip():
problems.append("%s: nodeid must be \"<file>::<test>\"" % where)
else:
where = "retired test %s" % nid
if not isinstance(suite, str) or not suite.strip():
problems.append("%s: suite must be a non-empty string (the id of a row)" % where)
elif suite_ids is not None and suite not in suite_ids:
problems.append("%s: the suite %s is not a row of main's required list" % (where, suite))
if isinstance(nid, str) and isinstance(suite, str):
if (nid, suite) in seen:
problems.append("%s: appears more than once for the suite %s" % (where, suite))
seen.add((nid, suite))
if not _is_int(e.get("count")) or e.get("count") < 1:
problems.append("%s: count must be an integer >= 1 (the tests the suite loses)" % where)
for key in ("reason", "decided_by", "date"):
if not isinstance(e.get(key), str) or not e.get(key).strip():
problems.append("%s: %s must be a non-empty string" % (where, key))
frm = e.get("from_min_tests")
if not _is_int(frm) or frm < 1 or (_is_int(e.get("count")) and frm < e["count"]):
problems.append("%s: from_min_tests must be an integer >= count (the minimum of the suite on main when the entry was written)" % where)
return problems
def retired_of_main(main_required):
"""The retired files and tests of main: ``ci/retired-tests.json`` next to main's list, read from main and never from the judged branch. It may
not exist (main older than the format): nothing is retired. A malformed one is a problem, never an empty list. -> (entries, problems)."""
path = Path(main_required).with_name(RETIRED_NAME)
if not path.is_file():
return [], []
try:
data = json.loads(path.read_text(encoding="utf-8"))
except (OSError, ValueError) as exc:
return [], ["the retired list of main %s cannot be read: %s" % (path, exc)]
try:
rows = json.loads(Path(main_required).read_text(encoding="utf-8"))
suite_ids = {r.get("id") for r in rows if isinstance(r, dict)} if isinstance(rows, list) else None
except (OSError, ValueError):
suite_ids = None # the list of main itself is read (and refused) by the caller
bad = validate_retired(data, suite_ids)
if bad:
return [], ["the retired list of main %s is malformed: %s" % (path, "; ".join(bad))]
return data, []
def _retired_tests_of(row, retired, collected, judged):
"""-> (the number of tests the row may lose because main retired them one by one, problems). An entry counts only if the file of its nodeid is
in the row of main (a nodeid that the row does not run is not a test the row loses). The judge has the junit of the leg it judges and only
counts of main, so a declared nodeid that the judged leg still collects is red (and counts for nothing), and the nodeid of another row is taken
on its count, the leg of that row checking it. An entry counts only while the minimum of the row on main is still its `from_min_tests`: once
the removal is on main the floor is lower and the entry is inert (it allows nothing and asks nothing)."""
allowed, problems = 0, []
listed = row.get("tests", [])
for e in retired:
if not (isinstance(e, dict) and isinstance(e.get("nodeid"), str) and e.get("suite") == row.get("id")):
continue
nid = e["nodeid"]
if _int(row.get("min_tests")) != e.get("from_min_tests"):
continue
if nid not in listed and nid.split("::", 1)[0] not in listed:
continue
if collected is not None and judged == row.get("id") and any(n == nid or _base(n) == nid for n in collected):
problems.append("the test %s is declared retired for %s, but the suite still collects it: it did not leave" % (nid, row.get("id")))
continue
allowed += _int(e.get("count"))
return allowed, problems
def against_main(current, main, retired=(), exists=os.path.exists, collected=None, judged=None):
def against_main(current, main):
"""The list only grows: every suite of main is still here, with no lower minimum, no exact turned off, no lost
test or OS and the same marker. `main` is read leniently (it may be older than the current format).
The one way a test leaves a row is `retired` (the list of MAIN, never of the branch): a file that main retired and that no longer exists
(`exists`, in the checkout judged) is not a lost test, and the minimum of the row may go down by exactly the tests main counted for that file
in that row (``tests[row id]``), and by no more. A retired file that is still on disk is not excused: it must stay in its rows.
The other way is a single retired test (``nodeid``, ``suite``, ``count``) whose file stays in the row: the minimum of the suite may go down by
the ``count`` of its entries, and by no more. ``collected`` (the node ids of the junit of the judged leg) and ``judged`` (that leg's suite) let
the judge see that a declared nodeid is gone from the leg; of the collection of main it has only the count."""
test or OS and the same marker. `main` is read leniently (it may be older than the current format)."""
problems = []
if not isinstance(main, list):
return ["the list of main is not a JSON list: it cannot be compared"]
retired = list(retired)
gone = {e["file"]: e["tests"] for e in retired if isinstance(e, dict) and isinstance(e.get("file"), str)
and isinstance(e.get("tests"), dict) and not exists(e["file"])}
by_id = {s.get("id"): s for s in current if isinstance(s, dict)}
for old in main:
if not isinstance(old, dict):
@@ -476,19 +263,12 @@ def against_main(current, main, retired=(), exists=os.path.exists, collected=Non
if new is None:
problems.append("the suite %s of main is gone from the list" % sid)
continue
lost = [t for t in old.get("tests", []) if t not in new.get("tests", [])]
excused = [t for t in lost if t in gone]
lost = [t for t in lost if t not in gone]
allowed = sum(_int(gone[t].get(sid)) for t in excused)
by_test, why = _retired_tests_of(old, retired, collected, judged)
allowed += by_test
problems += why
if _int(new.get("min_tests")) < _int(old.get("min_tests")) - allowed:
problems.append("the minimum of %s went down: %s on main, %s here%s"
% (sid, old.get("min_tests"), new.get("min_tests"),
" (retired files and tests account for %d of it)" % allowed if allowed else ""))
if _int(new.get("min_tests")) < _int(old.get("min_tests")):
problems.append("the minimum of %s went down: %s on main, %s here"
% (sid, old.get("min_tests"), new.get("min_tests")))
if old.get("exact") is True and new.get("exact") is not True:
problems.append("the suite %s is no longer exact, as it is on main" % sid)
lost = [t for t in old.get("tests", []) if t not in new.get("tests", [])]
if lost:
problems.append("the suite %s lost %d required test(s) that main has: %s" % (sid, len(lost), ", ".join(lost)))
lost_os = [o for o in old.get("os", []) if o not in new.get("os", [])]
@@ -626,10 +406,7 @@ def cmd_judge(ns):
problems.append("the list of main %s exists, but --main-has-no-list says main has none" % ns.main_required)
elif exists:
try:
retired, retired_problems = retired_of_main(ns.main_required)
problems += retired_problems
problems += against_main(suites, _read_json_list(ns.main_required), retired,
collected={n for n, _o in cases}, judged=ns.suite)
problems += against_main(suites, _read_json_list(ns.main_required))
except Usage as exc:
problems.append(str(exc))
elif ns.main_has_no_list:
-122
View File
@@ -1,122 +0,0 @@
r"""Read the full user-mode dumps Windows Error Reporting left for a python.exe that died, and say what each one holds (CI evidence, no debugger needed).
The Windows e2e jobs set ``HKLM\SOFTWARE\Microsoft\Windows\Windows Error Reporting\LocalDumps\python.exe`` (full dump, folder ``<evidence>/dumps/python``)
before their tests; when a pytest-xdist worker dies from an unhandled exception ("node down: Not properly terminated", "Windows fatal exception: access violation")
WER writes ``python.exe.<pid>.dmp`` there and the evidence artifact carries it. This script runs after the tests (``if: always()``): it lists every dump with its size
and reads the header of the MINIDUMP file, with ``struct`` only, to name what a debugger would name first: the thread that raised, the exception code, the faulting
address and the module that holds it (with the offset in it), plus the access that failed for an access violation. The summary goes to stdout and to
``summary.txt`` beside the dumps. It never fails the job: no dump is the normal case.
Format of the file: https://learn.microsoft.com/windows/win32/api/minidumpapiset/ (MINIDUMP_HEADER, MINIDUMP_DIRECTORY, MINIDUMP_EXCEPTION_STREAM,
MINIDUMP_MODULE). Dump types and the LocalDumps key: https://learn.microsoft.com/windows/win32/wer/collecting-user-mode-dumps
"""
from __future__ import annotations
import shutil
import struct
import sys
import time
from pathlib import Path
SIGNATURE = b"MDMP"
MODULE_LIST_STREAM = 4
EXCEPTION_STREAM = 6
MODULE_SIZE = 108 # sizeof(MINIDUMP_MODULE)
EXCEPTION_NAMES = {
0xC0000005: "EXCEPTION_ACCESS_VIOLATION",
0xC0000374: "STATUS_HEAP_CORRUPTION",
0xC0000409: "STATUS_STACK_BUFFER_OVERRUN (fail fast)",
0xC00000FD: "EXCEPTION_STACK_OVERFLOW",
0xC000001D: "EXCEPTION_ILLEGAL_INSTRUCTION",
0xC0000094: "EXCEPTION_INT_DIVIDE_BY_ZERO",
0xC0000026: "STATUS_INVALID_DISPOSITION",
0xC0000096: "EXCEPTION_PRIV_INSTRUCTION",
0xC0000006: "EXCEPTION_IN_PAGE_ERROR",
0x80000003: "EXCEPTION_BREAKPOINT",
0xE06D7363: "C++ exception",
}
ACCESS = {0: "read", 1: "write", 8: "execute (DEP)"}
def read_dump(path: Path) -> dict:
"""The facts of one minidump: thread id, exception code and address, the module holding the address. Raises ValueError on a file that is not a minidump."""
with open(path, "rb") as f:
head = f.read(32)
if len(head) < 32 or head[:4] != SIGNATURE:
raise ValueError("not a minidump (no MDMP signature)")
_sig, _version, n_streams, dir_rva = struct.unpack_from("<4sIII", head, 0)
f.seek(dir_rva)
directory = [struct.unpack("<III", f.read(12)) for _ in range(n_streams)]
out: dict = {"streams": n_streams}
modules: list[tuple[int, int, str]] = []
for kind, size, rva in directory:
if kind == MODULE_LIST_STREAM:
f.seek(rva)
(count,) = struct.unpack("<I", f.read(4))
records = f.read(count * MODULE_SIZE)
for i in range(count):
base, image_size, _cs, _ts, name_rva = struct.unpack_from("<QIIII", records, i * MODULE_SIZE)
here = f.tell()
f.seek(name_rva)
(nbytes,) = struct.unpack("<I", f.read(4))
name = f.read(nbytes).decode("utf-16-le", "replace")
f.seek(here)
modules.append((base, image_size, name))
elif kind == EXCEPTION_STREAM:
f.seek(rva)
raw = f.read(8 + 8 + 8 + 8 + 8 + 15 * 8)
tid, _pad, code, flags, _chain, address, n_params, _pad2 = struct.unpack_from("<IIIIQQII", raw, 0)
params = struct.unpack_from("<15Q", raw, 8 + 32)
out.update(thread_id=tid, code=code, flags=flags, address=address, params=list(params[:n_params]))
out["module_count"] = len(modules)
if "address" in out:
for base, image_size, name in modules:
if base <= out["address"] < base + image_size:
out["module"] = name
out["offset"] = out["address"] - base
break
return out
def describe(path: Path) -> str:
size = path.stat().st_size
head = "%s: %.1f MB" % (path.name, size / 1e6)
try:
d = read_dump(path)
except (ValueError, OSError, struct.error) as e:
return "%s, unreadable header: %s" % (head, e)
if "code" not in d:
return "%s, %d modules, no exception stream (a dump taken on request, not on a fault)" % (head, d["module_count"])
name = EXCEPTION_NAMES.get(d["code"], "unknown")
lines = [
head,
" exception 0x%08X %s on thread %d" % (d["code"], name, d["thread_id"]),
" at 0x%016X in %s" % (d["address"], ("%s+0x%X" % (d["module"], d["offset"])) if "module" in d else "no module of the dump (JIT or freed code)"),
]
p = d["params"]
if d["code"] in (0xC0000005, 0xC0000006) and len(p) >= 2:
lines.append(" failed access: %s of 0x%016X" % (ACCESS.get(p[0], str(p[0])), p[1]))
return "\n".join(lines)
def summarize(folder: Path) -> str:
dumps = sorted(folder.glob("*.dmp")) if folder.is_dir() else []
cdb = shutil.which("cdb") or shutil.which("windbg")
lines = ["WER dumps of python.exe in %s: %d" % (folder, len(dumps)), "debugger on the runner: %s" % (cdb or "none (the header reader above is all there is)")]
for p in dumps:
lines.append(describe(p) + "\n written %s" % time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(p.stat().st_mtime)))
return "\n".join(lines) + "\n"
def main(argv: list[str]) -> int:
folder = Path(argv[1]) if len(argv) > 1 else Path(".")
text = summarize(folder)
sys.stdout.write(text)
if folder.is_dir():
(folder / "summary.txt").write_text(text, encoding="utf-8", newline="\n")
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
+50
View File
@@ -0,0 +1,50 @@
"""Which canvas text cases two runs draw differently.
tests/test_canvas_text_is_windows_e2e.py writes canvas_text_<tag>.json (case id -> SHA-256
of the RGBA bytes) into INVISIBLE_CANVAS_TEXT_OUT. Run it on Debian 12 and on Ubuntu 24.04
(and the retail reference, tests/data/canvas_text_ref/refs.json, is accepted too), then:
python scripts/compare_canvas_text_runs.py debian.json ubuntu.json
The exit status is 0 when every case is equal on both sides and both draw the same set.
"""
from __future__ import annotations
import json
import sys
def load(path):
"""case id -> sha256, from a run file or from refs.json."""
data = json.loads(open(path, encoding="utf-8").read())
if "cases" in data:
return {k: v["sha256"] for k, v in data["cases"].items()}
return data
def compare(a, b):
"""(only in a, only in b, ids whose hash differs)."""
only_a = sorted(set(a) - set(b))
only_b = sorted(set(b) - set(a))
differ = sorted(k for k in set(a) & set(b) if a[k] != b[k])
return only_a, only_b, differ
def main(argv):
if len(argv) != 3:
print(__doc__)
return 2
a, b = load(argv[1]), load(argv[2])
only_a, only_b, differ = compare(a, b)
for label, ids in (("only in %s" % argv[1], only_a), ("only in %s" % argv[2], only_b),
("differ", differ)):
if ids:
print("%s (%d):" % (label, len(ids)))
for k in ids:
print(" " + k)
print("%d cases compared, %d differ" % (len(set(a) & set(b)), len(differ)))
return 1 if (only_a or only_b or differ) else 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
-4
View File
@@ -1,4 +0,0 @@
<!doctype html>
<meta charset=utf-8>
<title>not controlled</title>
<p>The service worker did not answer this navigation.</p>
-14
View File
@@ -1,14 +0,0 @@
<!doctype html>
<meta charset=utf-8>
<title>frame</title>
<script>
document.write('<script src="/ab/realm.js' + location.search + '"><\/script>');
</script>
<script>
(async () => {
const q = new URLSearchParams(location.search);
const data = await abRealm();
data.host = location.hostname;
parent.postMessage({id: q.get('id'), data}, '*');
})();
</script>
-4
View File
@@ -1,4 +0,0 @@
<!doctype html>
<meta charset=utf-8>
<title>leave</title>
<p>The page of the back and forward step.</p>
-16
View File
@@ -1,16 +0,0 @@
<!doctype html>
<meta charset=utf-8>
<title>opened</title>
<script>
document.write('<script src="/ab/realm.js' + location.search + '"><\/script>');
</script>
<script>
(async () => {
const q = new URLSearchParams(location.search);
const data = await abRealm();
const bar = n => { try { return window[n].visible; } catch (e) { return 'ERR'; } };
data.geometry = {innerWidth, innerHeight, outerWidth, outerHeight, screenX, screenY, screen: [screen.width, screen.height, screen.availWidth, screen.availHeight],
bars: ['menubar', 'toolbar', 'locationbar', 'statusbar', 'scrollbars', 'personalbar'].map(bar), hasOpener: !!window.opener, name: window.name};
try { opener.postMessage({id: q.get('id'), data}, '*'); } catch (e) {}
})();
</script>
-95
View File
@@ -1,95 +0,0 @@
// The surface subset one realm reads: the same text is loaded by the page, a cross-site iframe, a srcdoc iframe, a worker, a shared worker, a
// service worker and an audio worklet, so that a value the engine declares for one realm and forgets for another shows as a difference.
// Everything here is a plain read of what the realm exposes; a realm that lacks an API says 'absent'.
(function (root) {
'use strict';
const errs = e => 'ERR ' + ((e && e.name) || '') + ': ' + ((e && e.message) || String(e));
const bytesHash = u8 => {
let a = 0x811c9dc5, b = 0xdeadbeef;
for (let i = 0; i < u8.length; i++) { a = Math.imul(a ^ u8[i], 0x01000193) >>> 0; b = Math.imul(b ^ u8[i], 0x5bd1e995) >>> 0; b ^= b >>> 13; }
return u8.length + ':' + a.toString(16) + b.toString(16);
};
// A PNG of Firefox carries a per-launch "deBG" chunk (the host gate's noise.png_deBG): the bytes are hashed without it, so that two launches of one engine agree.
const pngHash = u8 => {
const keep = [u8.subarray(0, 8)];
for (let i = 8; i + 12 <= u8.length;) {
const n = (u8[i] << 24 | u8[i + 1] << 16 | u8[i + 2] << 8 | u8[i + 3]) >>> 0, t = String.fromCharCode(u8[i + 4], u8[i + 5], u8[i + 6], u8[i + 7]);
if (t !== 'deBG') keep.push(u8.subarray(i, i + 12 + n));
i += 12 + n;
}
const out = new Uint8Array(keep.reduce((a, x) => a + x.length, 0)); let o = 0; for (const k of keep) { out.set(k, o); o += k.length; }
return bytesHash(out);
};
const dataUrlHash = url => pngHash(Uint8Array.from(atob(url.split(',')[1]), ch => ch.charCodeAt(0)));
const TEXT = 'Hamburgefonstiv 0123 ZZ';
const draw = g => {
g.fillStyle = '#fff'; g.fillRect(0, 0, 160, 40); g.fillStyle = '#036'; g.font = '16px sans-serif'; g.fillText(TEXT, 4, 16);
g.font = '14px serif'; g.fillText('\u65e5\u672c\u8a9e Stra\u00dfe', 4, 34);
};
const measure = g => ['sans-serif', 'serif', 'monospace', 'ZZHostCanary, sans-serif'].map(f => { g.font = '16px ' + f; return g.measureText(TEXT).width; });
const scene = c => {
const gl = c.getContext('webgl');
if (!gl) return 'no webgl';
const sh = (type, src) => { const s = gl.createShader(type); gl.shaderSource(s, src); gl.compileShader(s); return s; };
const p = gl.createProgram();
gl.attachShader(p, sh(gl.VERTEX_SHADER, 'attribute vec2 a;void main(){gl_Position=vec4(a,0.,1.);}'));
gl.attachShader(p, sh(gl.FRAGMENT_SHADER, 'precision mediump float;void main(){gl_FragColor=vec4(.9,.3,.1,1.);}'));
gl.linkProgram(p); gl.useProgram(p);
const buf = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buf);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-0.8, -0.8, 0.8, -0.8, 0, 0.8]), gl.STATIC_DRAW);
const a = gl.getAttribLocation(p, 'a'); gl.enableVertexAttribArray(a); gl.vertexAttribPointer(a, 2, gl.FLOAT, false, 0, 0);
gl.viewport(0, 0, 32, 32); gl.clearColor(0.2, 0.4, 0.6, 1); gl.clear(gl.COLOR_BUFFER_BIT); gl.drawArrays(gl.TRIANGLES, 0, 3);
const px = new Uint8Array(32 * 32 * 4); gl.readPixels(0, 0, 32, 32, gl.RGBA, gl.UNSIGNED_BYTE, px);
const dbg = gl.getExtension('WEBGL_debug_renderer_info');
return {pixels: bytesHash(px), vendor: gl.getParameter(gl.VENDOR), renderer: gl.getParameter(gl.RENDERER),
unmasked: dbg ? [gl.getParameter(dbg.UNMASKED_VENDOR_WEBGL), gl.getParameter(dbg.UNMASKED_RENDERER_WEBGL)] : 'absent'};
};
// What needs no await: the only part an audio worklet can read.
const readSync = () => {
const o = {};
const t = (k, f) => { try { o[k] = f(); } catch (e) { o[k] = errs(e); } };
const nav = root.navigator;
if (nav) {
t('language', () => nav.language); t('languages', () => Array.from(nav.languages)); t('platform', () => nav.platform);
t('hardwareConcurrency', () => nav.hardwareConcurrency); t('userAgent', () => nav.userAgent);
} else { o.navigator = 'absent'; }
t('intl', () => { const r = new Intl.DateTimeFormat().resolvedOptions(); return [r.locale, r.timeZone, r.calendar, r.numberingSystem]; });
const d = new Date(Date.UTC(2026, 0, 15, 12)), s = new Date(Date.UTC(2026, 6, 15, 12));
t('dates', () => [d.toString(), s.toString(), d.toLocaleString(), d.toLocaleDateString(undefined, {dateStyle: 'full'}), (1234567.891).toLocaleString(),
d.getTimezoneOffset(), s.getTimezoneOffset()]);
t('sampleRate', () => typeof root.sampleRate === 'number' ? root.sampleRate : 'absent');
return o;
};
const read = async () => {
const o = readSync();
const ta = async (k, f) => { try { o[k] = await f(); } catch (e) { o[k] = errs(e); } };
if (root.document && root.document.createElement) {
await ta('canvas', async () => {
const c = root.document.createElement('canvas'); c.width = 160; c.height = 40; const g = c.getContext('2d'); draw(g);
return {toDataURL: dataUrlHash(c.toDataURL()), pixels: bytesHash(g.getImageData(0, 0, 160, 40).data), measure: measure(g)};
});
await ta('webgl', async () => { const c = root.document.createElement('canvas'); c.width = 32; c.height = 32; return scene(c); });
} else { o.canvas = 'absent'; }
if (typeof root.OffscreenCanvas === 'function') {
await ta('offscreen', async () => {
const c = new root.OffscreenCanvas(160, 40), g = c.getContext('2d'); draw(g);
const m = measure(g), blob = await c.convertToBlob();
return {measure: m, png: pngHash(new Uint8Array(await blob.arrayBuffer()))};
});
await ta('offscreen_webgl', async () => scene(new root.OffscreenCanvas(32, 32)));
} else { o.offscreen = 'absent'; }
return o;
};
root.abRealm = read;
root.abRealmSync = readSync;
// An audio worklet runs this file as a module: its processor reports what the worklet's own realm reads, when it is created.
if (typeof root.registerProcessor === 'function' && typeof root.AudioWorkletProcessor === 'function') {
root.registerProcessor('ab-probe', class extends root.AudioWorkletProcessor {
constructor() { super(); this.port.postMessage(readSync()); }
process() { return false; }
});
}
})(typeof globalThis !== 'undefined' ? globalThis : self);
-5
View File
@@ -1,5 +0,0 @@
importScripts('/ab/realm.js' + location.search);
onconnect = e => {
const port = e.ports[0];
port.onmessage = async () => { port.postMessage(await abRealm()); };
};
-89
View File
@@ -1,89 +0,0 @@
<!doctype html>
<meta charset=utf-8>
<title>ab</title>
<body>
<script>
// The A/B oracle's visit of the surfaces a plain read of the top window does not reach: every realm and every kind of window a page can make
// reads the same subset (realm.js), and the server says which Accept-Language it saw for each kind of request. The page is served from
// http://127.0.0.1 (a secure context: service workers and the audio worklet need one); `?ctx=` names the context it runs in.
// What it records goes to window.__abResult; the title says when it is done. A step that does not answer says 'timeout: <step>' after its own
// budget, never silence, so that the two engines of an A/B compare the same leaves.
document.write('<script src="/ab/realm.js' + location.search + '"><\/script>');
</script>
<script>
(async () => {
const Q = new URLSearchParams(location.search), CTX = Q.get('ctx') || 'none', ID = '?ctx=' + encodeURIComponent(CTX);
const errs = e => 'ERR ' + ((e && e.name) || '') + ': ' + ((e && e.message) || String(e));
const within = (p, ms, what) => Promise.race([p, new Promise(res => setTimeout(() => res('timeout: ' + what), ms))]);
const step = async (R, k, f, ms = 15000) => { try { R[k] = await within(Promise.resolve().then(f), ms, k); } catch (e) { R[k] = errs(e); } };
const waiting = {};
addEventListener('message', e => { const m = e.data; if (m && typeof m.id === 'string' && waiting[m.id]) { waiting[m.id](Object.assign({origin: e.origin.replace(/:\d+$/, ':<port>')}, m.data)); delete waiting[m.id]; } });
const popups = [];
const pop = (id, name, features) => new Promise(res => {
waiting[id] = res;
const url = '/ab/opened.html' + ID + '&id=' + id;
const w = features === undefined ? window.open(url, name) : window.open(url, name, features);
if (w) popups.push(w); else res('blocked');
});
addEventListener('pageshow', async e => {
let n = 1;
try { n = (Number(sessionStorage.getItem('abPs')) || 0) + 1; sessionStorage.setItem('abPs', String(n)); } catch (x) {}
let data; try { data = JSON.parse(JSON.stringify(await abRealm())); } catch (x) { data = errs(x); }
window.__abBf = {n, persisted: e.persisted, data};
});
let done = false;
try { done = sessionStorage.getItem('abDone') === '1'; } catch (x) {}
if (done) { document.title = 'ab-done'; return; }
const R = {};
await step(R, 'top', () => abRealm());
await step(R, 'iframe_cross', () => new Promise(res => {
waiting.cross = res;
const f = document.createElement('iframe'); f.src = 'http://localhost:' + location.port + '/ab/frame.html' + ID + '&id=cross'; document.body.appendChild(f); }));
await step(R, 'iframe_srcdoc', () => new Promise((res, rej) => {
const f = document.createElement('iframe');
f.srcdoc = '<!doctype html><script src="/ab/realm.js' + ID + '"><\/script>';
f.onload = async () => { try { res(await f.contentWindow.abRealm()); } catch (e) { rej(e); } };
document.body.appendChild(f); }));
await step(R, 'worker', () => new Promise((res, rej) => {
const w = new Worker('/ab/worker.js' + ID); w.onmessage = e => { res(e.data); w.terminate(); }; w.onerror = () => { rej(new Error('worker error')); w.terminate(); }; w.postMessage('go'); }));
await step(R, 'shared_worker', () => new Promise((res, rej) => {
const w = new SharedWorker('/ab/shared.js' + ID); w.port.onmessage = e => res(e.data); w.onerror = () => rej(new Error('shared worker error')); w.port.postMessage('go'); }));
await step(R, 'service_worker', async () => {
if (!navigator.serviceWorker) return 'absent';
const reg = await navigator.serviceWorker.register('/ab/sw.js' + ID, {scope: '/ab/'});
try {
await navigator.serviceWorker.ready;
const f = document.createElement('iframe'), loaded = new Promise(r => { f.onload = r; });
f.src = '/ab/controlled.html' + ID; document.body.appendChild(f); await loaded;
const el = f.contentDocument.getElementById('sw');
return el ? JSON.parse(el.textContent) : 'the worker did not answer the navigation';
} finally { try { await reg.unregister(); } catch (e) {} }
}, 20000);
await step(R, 'audio_worklet', async () => {
const ac = new AudioContext();
try {
await ac.audioWorklet.addModule('/ab/realm.js' + ID);
const node = new AudioWorkletNode(ac, 'ab-probe');
const got = new Promise(res => { node.port.onmessage = e => res(e.data); });
ac.resume().catch(() => {});
return await got;
} finally { try { await ac.close(); } catch (e) {} }
}, 8000);
await step(R, 'popup_plain', () => pop('plain', 'abPlain'));
await step(R, 'popup_features', () => pop('features', 'abFeatures', 'popup,width=500,height=420,left=40,top=30'));
for (const w of popups) { try { w.close(); } catch (e) {} }
// two more kinds of request, so that the server has seen a fetch and an image next to the documents, scripts and workers
await step(R, 'requests', async () => {
await fetch('/ab/probe' + ID + '&k=fetch');
await new Promise(res => { const i = new Image(); i.onload = i.onerror = res; i.src = '/ab/probe' + ID + '&k=image'; });
return 'made'; }, 5000);
await step(R, 'accept_language', async () => (await fetch('/ab/seen' + ID)).json(), 5000);
window.__abResult = JSON.parse(JSON.stringify(R));
try { sessionStorage.setItem('abDone', '1'); } catch (e) {}
document.title = 'ab-done';
})();
</script>
-17
View File
@@ -1,17 +0,0 @@
// A service worker that answers one navigation itself: the page it builds carries what the worker's own realm reads and the headers the
// worker saw on the request, so a controlled navigation is read through the worker, not around it.
importScripts('/ab/realm.js' + location.search);
self.addEventListener('install', () => self.skipWaiting());
self.addEventListener('activate', e => e.waitUntil(self.clients.claim()));
self.addEventListener('fetch', e => {
const u = new URL(e.request.url);
if (u.pathname !== '/ab/controlled.html') return;
e.respondWith((async () => {
const data = await abRealm();
data.request = {acceptLanguage: e.request.headers.get('accept-language'), mode: e.request.mode, destination: e.request.destination};
try { data.own_fetch = (await fetch('/ab/probe' + u.search)).status; } catch (x) { data.own_fetch = 'ERR ' + ((x && x.name) || ''); }
const json = JSON.stringify(data).replace(/</g, '\\u003c');
return new Response('<!doctype html><meta charset=utf-8><title>controlled</title><script type="application/json" id="sw">' + json + '</script>',
{headers: {'Content-Type': 'text/html; charset=utf-8'}});
})());
});
-2
View File
@@ -1,2 +0,0 @@
importScripts('/ab/realm.js' + location.search);
onmessage = async () => { postMessage(await abRealm()); };
-38
View File
@@ -281,44 +281,6 @@ await safe('surface.branding', () => Promise.all(['chrome://branding/locale/bran
noise('history_length', history.length);
noise('main_loop_ms', await new Promise(r => { const t = performance.now(); setTimeout(() => r(Math.round(performance.now() - t)), 20); }));
// ================================================================= AB (read by the A/B oracle only, never by the retail comparison)
// ab.poison: what the page reads of values a host may hold and the engine must never read: the zone, the language, the colour scheme, a
// user-installed canary font (scripts/ci_poison_host.py puts them on the oracle's runner and holds the engine's dumps to the declared identity).
// The probe between the two markers is self-contained: the negative control evaluates the same text in Playwright's own Firefox.
// ab.poison:begin
const abPoisonProbe = async () => {
const o = {}, f = (k, g) => { try { o[k] = g(); } catch (e) { o[k] = 'ERR ' + ((e && e.name) || ''); } };
const jan = new Date(Date.UTC(2026, 0, 15, 12)), jul = new Date(Date.UTC(2026, 6, 15, 12));
f('timezone', () => Intl.DateTimeFormat().resolvedOptions().timeZone);
f('offsets', () => [jan.getTimezoneOffset(), jul.getTimezoneOffset()]);
f('language', () => navigator.language);
f('languages', () => Array.from(navigator.languages));
f('intl_locale', () => Intl.DateTimeFormat().resolvedOptions().locale);
f('date_full', () => jan.toLocaleDateString(undefined, {dateStyle: 'full'}));
f('number', () => (1234567.891).toLocaleString());
f('dark', () => matchMedia('(prefers-color-scheme: dark)').matches);
// document.fonts.check answers true for a family nobody has (the specification: nothing to load), so it is recorded and the WIDTH decides
f('canary_check', () => document.fonts.check('12px ZZHostCanary'));
f('canary', () => {
const box = document.createElement('div'); box.style.cssText = 'position:absolute;left:-9999px;top:0;visibility:hidden;white-space:nowrap';
document.documentElement.appendChild(box);
const width = fam => { const e = document.createElement('span'); e.style.cssText = 'font:12px ' + fam; e.textContent = 'mmmmmmmmmmmm'; box.appendChild(e); const w = e.getBoundingClientRect().width; e.remove(); return w; };
const out = {with: [width('ZZHostCanary, monospace'), width('ZZHostCanary, serif')], without: [width('monospace'), width('serif')]};
box.remove(); out.present = out.with.some(w => Math.abs(w - 216) < 1); return out; }); // 12 boxes of 1.5 em at 12px: the canary's own width, whatever the fallbacks are
// the width of a text in each generic family: a host whose fontconfig prefers a user font for them answers that font's width
f('generic', () => {
const box = document.createElement('div'); box.style.cssText = 'position:absolute;left:-9999px;top:0;visibility:hidden;white-space:nowrap';
document.documentElement.appendChild(box);
const out = ['sans-serif', 'serif', 'monospace'].map(fam => { const e = document.createElement('span'); e.style.cssText = 'font:12px ' + fam; e.textContent = 'mmmmmmmmmmmm';
box.appendChild(e); const w = e.getBoundingClientRect().width; e.remove(); return w; });
box.remove(); return out; });
try { const c = new AudioContext(); o.audio = {sampleRate: c.sampleRate, maxChannelCount: c.destination.maxChannelCount}; try { c.close(); } catch (e) {} }
catch (e) { o.audio = 'ERR ' + ((e && e.name) || ''); }
return o;
};
// ab.poison:end
await safe('ab.poison', abPoisonProbe);
// ================================================================= DIAG (information, never compared)
// diag.*: why this host's WebGL is what it is (no WebGL2, no MSAA). Last, so its extra contexts
// cannot disturb anything measured above; each is lost again once read.
+738
View File
@@ -0,0 +1,738 @@
#!/usr/bin/env python3
"""A MAP of what a launch does, from the user's call to the first page, with the time of every step.
One question: where does the time of `InvisiblePlaywright(...)` go, from the call to a page that has loaded a first page? It is a measurement and nothing else: no
threshold, no verdict, and nothing of the product is changed. The product is measured from the outside: each function that is a step is wrapped by a timer that
calls the original (`time.perf_counter_ns` before and after, the thread's name), installed on the modules' attributes in the worker process only. A step the product
renames makes a target that is not found: it is said in the report (`unpatched`), never silently skipped.
Two modes of one file.
driver (default) starts a worker process per launch (a fresh interpreter each: the import of the packages is a step of a launch), `--runs` times on a warm
cache after one warm-up launch that is not counted, for each scenario; then ONE launch on a cold cache (a new cache directory, the engine kept: the
engine's download is not this map's, the workflow times `fetch` apart); then ONE launch under cProfile; then writes `init-map-<system>.json` and
`init-map-<system>.md` in `--out`.
worker (--worker) one launch: imports, the wrapped steps, `InvisiblePlaywright(...)` -> `__enter__` -> `browser.new_page()` -> two `goto` of a page on 127.0.0.1 ->
`__exit__`, and writes its spans as JSON.
Scenarios (`--scenarios`):
direct `InvisiblePlaywright(seed=...)`: no proxy, the exit asked of the internet (what a user without a proxy pays), the engine on the surface of the system.
proxy the same behind a SOCKS5 gateway of this machine (`tests/_socks_servers.py`, the fake web's: no real proxy; it forwards the question of the exit for real): the TCP exit is asked THROUGH the proxy and the
UDP exit is measured beside it, on a thread (the product's decision: they stay parallel).
headless `headless=True`: the hidden surface (an Xvfb on Linux, a Win32 desktop on Windows) is made by the launch.
What a time is. Every time is milliseconds of `time.perf_counter_ns`, relative to the instant before `InvisiblePlaywright(...)` is called. A step's `self` time is its
time minus the time of the steps inside it. A step runs `in parallel` with another when they are not one inside the other and they overlap in half of the runs or more.
The tree is made by containment of the intervals, so a span that a background thread makes while the caller waits sits under whichever step was open (its thread is in
the column `thread`).
"""
from __future__ import annotations
import argparse
import contextlib
import functools
import importlib
import json
import math
import os
import platform
import shutil
import signal
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
ROOT = Path(__file__).resolve().parent.parent
HERE = Path(__file__).resolve()
# ── what is wrapped ─────────────────────────────────────────────────────────
# (module, "Class.attr" or "attr", label). The labels are the names of the steps in the map. An entry whose target is not found is reported as `unpatched`.
TARGETS: List[Tuple[str, str, str]] = [
# the wrapper: the three calls of the user and what `__enter__` does
("invisible_playwright.launcher", "InvisiblePlaywright.__init__", "ctor"),
("invisible_playwright.launcher", "generate_profile", "ctor.generate_profile"),
("invisible_playwright.launcher", "guard_for", "ctor.lifetime_guard"),
("invisible_playwright._session", "declared_network", "ctor.declared_network"),
("invisible_playwright.launcher", "InvisiblePlaywright.__enter__", "enter"),
("invisible_playwright.launcher", "prepare_session_geo", "geo"),
("invisible_core._geo", "discover_egress_ip", "geo.tcp_egress_discovery"),
("invisible_core._udp_exit", "start_measurement", "geo.udp_measurement_start"),
("invisible_core._udp_exit", "PendingMeasurement._run", "geo.udp_probe_thread"),
("invisible_core._udp_exit", "PendingMeasurement.result", "geo.udp_join"),
("invisible_core._geo", "ensure_geoip_mmdb", "geo.geoip_database"),
("invisible_core._geo", "ip_to_timezone", "geo.ip_to_timezone"),
("invisible_core._geo", "ip_to_coordinates", "geo.ip_to_coordinates"),
("invisible_core._geo", "position_to_declare", "geo.declared_position"),
("invisible_core._geo", "_decide", "geo.decide_locale"),
("invisible_playwright.launcher", "resolve_executable", "engine_check"),
("invisible_playwright._engine", "ensure_binary", "engine_check.ensure_binary"),
("invisible_core.download", "read_stamp", "engine_check.read_stamp"),
("invisible_core.download", "verify_engine", "engine_check.verify_engine"),
("invisible_core.seal", "read_engine_identity", "engine_check.read_engine_identity"),
("invisible_core.seal", "engine_problems", "engine_check.engine_problems"),
("invisible_playwright._session", "CommonLaunch._resolve_headless", "resolve_headless"),
("invisible_playwright._session", "make_virtual_display", "resolve_headless.make_virtual_display"),
("invisible_playwright._session", "CommonLaunch._build_prefs", "build_prefs"),
("invisible_playwright._session", "compose_session_prefs", "build_prefs.compose_session_prefs"),
("invisible_playwright.launcher", "_configure_proxy_shared", "configure_proxy"),
("invisible_playwright._session", "CommonLaunch._build_env", "build_env"),
("invisible_playwright._session", "resolve_executable", "build_env.engine_check_again"),
("invisible_playwright._session", "verify_font_manifest", "build_env.verify_font_manifest"),
("invisible_playwright._session", "cached_font_manifest_path", "build_env.font_manifest_file"),
("invisible_playwright._session", "build_launch_env", "build_env.build_launch_env"),
# the client and the in-process server
("invisible_playwright._pw.sync_api._context_manager", "PlaywrightContextManager.__enter__", "playwright_start"),
("invisible_playwright._pw.sync_api._generated", "BrowserType.launch", "client_launch"),
("invisible_playwright._pw.sync_api._generated", "BrowserType.launch_persistent_context", "client_launch_persistent"),
("invisible_playwright._juggler.server", "BrowserTypeDispatcher.op_launch", "server_launch"),
("invisible_playwright._juggler.server", "session_for_launch", "server_launch.session_for_launch"),
("invisible_core.juggler._profile", "SessionFiles.__init__", "server_launch.session_files"),
("invisible_playwright._juggler.server", "take_session_motion", "server_launch.take_session_motion"),
("invisible_playwright._juggler.server", "write_user_js", "write_profile"),
("invisible_core._intermediates", "ensure_intermediates", "write_profile.intermediates_list"),
("invisible_playwright._juggler.server", "launch_proxy_command", "server_launch.launch_proxy_command"),
("invisible_core.juggler.connection", "launch", "engine_start"),
("invisible_core._engine_env", "compose", "engine_start.compose_environment"),
("invisible_core.juggler.connection", "_spawn_windows", "engine_start.spawn_process"),
("invisible_core.juggler.connection", "_spawn_posix", "engine_start.spawn_process"),
("invisible_core.juggler.connection", "ProcessOutput.wait_for_ready", "engine_start.wait_listening"),
("invisible_core.juggler.connection", "Connection.__init__", "engine_start.connection_init"),
("invisible_core.juggler.connection", "Connection.send_placed", "send"),
("invisible_playwright._juggler.server", "read_version", "server_launch.read_version"),
("invisible_playwright._juggler.server", "BrowserDispatcher.__init__", "server_launch.browser_dispatcher"),
("invisible_playwright.launcher", "assert_wire_version", "assert_wire_version"),
("invisible_playwright.launcher", "InvisiblePlaywright._patch_new_context_defaults", "patch_new_context_defaults"),
("invisible_playwright._session", "CommonLaunch._arm_cursor_engine", "arm_cursor_engine"),
# the first page
("invisible_playwright._pw.sync_api._generated", "Browser.new_page", "client_new_page"),
("invisible_playwright.launcher", "InvisiblePlaywright._assert_uscita_invariata", "egress_recheck"),
("invisible_playwright._juggler.server", "BrowserDispatcher.op_new_context", "server_new_context"),
("invisible_playwright._juggler.server", "BrowserDispatcher._apply_context_options", "server_new_context.apply_options"),
("invisible_playwright._juggler.server", "BrowserContextDispatcher.op_new_page", "server_new_page"),
("invisible_playwright._juggler.server", "BrowserDispatcher._wait_for_page", "server_new_page.wait_for_page"),
# the first goto
("invisible_playwright._pw.sync_api._generated", "Page.goto", "client_goto"),
("invisible_playwright._juggler.server", "FrameDispatcher.op_goto", "server_goto"),
# the end (not part of the map: told for the record)
("invisible_playwright.launcher", "InvisiblePlaywright.__exit__", "exit"),
]
#: Steps that run on a thread of their own by design; the others are in the line of the caller.
BACKGROUND = {"geo.udp_probe_thread"}
#: One line for each step: what it does.
DESC = {
"ctor": "constructor: seed, profile (fingerprint) and guard",
"ctor.generate_profile": "the profile generated from the seed",
"ctor.lifetime_guard": "the process lifetime guard",
"ctor.declared_network": "the network declared by the seed",
"enter": "__enter__: everything up to the browser being ready",
"geo": "prepare_session_geo: exit, zone, language, position",
"geo.tcp_egress_discovery": "discovery of the exit IP (TCP, an HTTPS request)",
"geo.udp_measurement_start": "start of the UDP measurement thread",
"geo.udp_probe_thread": "UDP measurement of the exit (a thread, beside the TCP discovery)",
"geo.udp_join": "wait for the UDP measurement and its verdict",
"geo.geoip_database": "GeoIP database (cache, daily check)",
"geo.ip_to_timezone": "zone from the IP",
"geo.ip_to_coordinates": "coordinates from the IP",
"geo.declared_position": "position declared from the seed",
"geo.decide_locale": "language decided from the exit",
"engine_check": "choice and verification of the engine (the seal)",
"engine_check.ensure_binary": "ensure_binary: the engine's cache",
"engine_check.read_stamp": "read the cache stamp",
"engine_check.verify_engine": "verify_engine: the engine against the seal",
"engine_check.read_engine_identity": "application.ini and provenance of the engine",
"engine_check.engine_problems": "comparison with the seal",
"resolve_headless": "hidden surface (headless=True)",
"resolve_headless.make_virtual_display": "makes the Xvfb / Win32 desktop",
"build_prefs": "composition of the prefs",
"build_prefs.compose_session_prefs": "the core's compose_session_prefs",
"configure_proxy": "proxy configuration",
"build_env": "construction of the environment",
"build_env.engine_check_again": "second verification of the engine (made by _build_env)",
"build_env.verify_font_manifest": "the font list against the engine",
"build_env.font_manifest_file": "the font list file",
"build_env.build_launch_env": "the process environment",
"playwright_start": "sync_playwright().start(): in-process server and client",
"client_launch": "BrowserType.launch, client side",
"client_launch_persistent": "launch_persistent_context, client side",
"server_launch": "op_launch of the in-process server",
"server_launch.session_for_launch": "the launch's session",
"server_launch.session_files": "profile and temporary directories",
"server_launch.take_session_motion": "takes the session prefs out",
"write_profile": "writing user.js",
"write_profile.intermediates_list": "the intermediates list (cache)",
"server_launch.launch_proxy_command": "the proxy command",
"engine_start": "engine start (connection.launch)",
"engine_start.compose_environment": "the engine's environment (_engine_env.compose)",
"engine_start.spawn_process": "process creation",
"engine_start.wait_listening": "wait for the engine to be ready (the listening line)",
"engine_start.connection_init": "Juggler connection",
"send": "Juggler message (round trip)",
"server_launch.read_version": "the engine's version",
"server_launch.browser_dispatcher": "BrowserDispatcher (Browser.enable)",
"assert_wire_version": "version on the wire against the seal",
"patch_new_context_defaults": "context defaults",
"arm_cursor_engine": "cursor engine",
"client_new_page": "browser.new_page(), client side",
"egress_recheck": "check of the exit (with a proxy only)",
"server_new_context": "first context",
"server_new_context.apply_options": "context options",
"server_new_page": "first page",
"server_new_page.wait_for_page": "wait for Page.ready",
"client_goto": "page.goto, client side",
"server_goto": "goto, server side",
"exit": "closing (outside the map)",
}
# ── the worker ──────────────────────────────────────────────────────────────
class Recorder:
def __init__(self) -> None:
self.spans: List[Dict[str, Any]] = []
self.lock = threading.Lock()
def add(self, label: str, t0: int, t1: int, extra: Optional[str] = None) -> None:
span = {"label": label, "t0": t0, "t1": t1, "thread": threading.current_thread().name}
if extra:
span["extra"] = extra
with self.lock:
self.spans.append(span)
def _timed(recorder: Recorder, label: str, fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
start = time.perf_counter_ns()
extra = None
if label == "send":
method = args[1] if len(args) >= 2 else kwargs.get("method")
extra = method if isinstance(method, str) else None
try:
return fn(*args, **kwargs)
finally:
recorder.add(label if extra is None else "send:" + extra, start, time.perf_counter_ns())
return wrapper
def install(recorder: Recorder) -> List[str]:
"""Wrap every target; the labels of the targets that were not found."""
unpatched: List[str] = []
for module_name, dotted, label in TARGETS:
try:
module = importlib.import_module(module_name)
owner: Any = module
parts = dotted.split(".")
for part in parts[:-1]:
owner = getattr(owner, part)
original = getattr(owner, parts[-1])
setattr(owner, parts[-1], _timed(recorder, label, original))
except Exception as exc: # noqa: BLE001
unpatched.append("%s %s -> %s: %s" % (module_name, dotted, label, type(exc).__name__))
return unpatched
class _Page(BaseHTTPRequestHandler):
def do_GET(self): # noqa: N802
body = b"<!doctype html><title>init map</title><p>hello</p>"
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, *args):
pass
def worker(args: argparse.Namespace) -> int:
started = time.perf_counter_ns()
result: Dict[str, Any] = {"status": "error", "scenario": args.scenario}
out = Path(args.out)
try:
t = time.perf_counter_ns()
import invisible_core # noqa: F401
marks = {"import_core": time.perf_counter_ns() - t}
t = time.perf_counter_ns()
from invisible_playwright.sync_api import InvisiblePlaywright
import invisible_playwright.launcher # noqa: F401
import invisible_playwright._juggler.server # noqa: F401
marks["import_wrapper"] = time.perf_counter_ns() - t
result["marks_ns"] = marks
recorder = Recorder()
if args.dry:
_dry()
result["unpatched"] = install(recorder)
httpd = ThreadingHTTPServer(("127.0.0.1", 0), _Page)
threading.Thread(target=httpd.serve_forever, daemon=True, name="init-map-page").start()
url = "http://127.0.0.1:%d/" % httpd.server_address[1]
kwargs: Dict[str, Any] = {"seed": args.seed}
if args.scenario == "headless":
kwargs["headless"] = True
if args.scenario == "proxy":
kwargs["proxy"] = {"server": args.proxy}
if args.stun:
kwargs["udp_stun_servers"] = [args.stun]
profiler = None
if args.profile:
import cProfile
profiler = cProfile.Profile()
instance = None
entered = False
call_start = time.perf_counter_ns()
try:
if profiler:
profiler.enable()
instance = InvisiblePlaywright(**kwargs)
browser = instance.__enter__()
entered = True
page = browser.new_page()
call_end = time.perf_counter_ns()
if profiler:
profiler.disable()
t = time.perf_counter_ns()
page.goto(url + "?1")
recorder.add("goto1", t, time.perf_counter_ns())
t = time.perf_counter_ns()
page.goto(url + "?2")
recorder.add("goto2", t, time.perf_counter_ns())
result["status"] = "ok"
result["call_ns"] = [call_start, call_end]
finally:
if profiler:
with contextlib.suppress(Exception):
profiler.disable()
if instance is not None:
with contextlib.suppress(Exception):
if entered:
instance.__exit__(None, None, None)
else:
instance._teardown()
if profiler and args.profile_out:
import io
import pstats
text = io.StringIO()
for key in ("cumulative", "tottime"):
stats = pstats.Stats(profiler, stream=text)
text.write("\n=== sorted by %s (main thread only; the first 45) ===\n" % key)
stats.sort_stats(key).print_stats(45)
Path(args.profile_out).write_text(text.getvalue(), encoding="utf-8")
result["spans"] = recorder.spans
result["call_ns"] = result.get("call_ns") or [call_start, time.perf_counter_ns()]
except BaseException as exc: # noqa: BLE001
import traceback
result["error"] = "%s: %s" % (type(exc).__name__, exc)
result["traceback"] = traceback.format_exc()[-3000:]
if "recorder" in locals():
result["spans"] = recorder.spans
result.setdefault("call_ns", [started, time.perf_counter_ns()])
result["python"] = sys.version.split()[0]
out.write_text(json.dumps(result), encoding="utf-8")
return 0
def _dry() -> None:
"""Local check of the wrapping only (never in a workflow): the engine is not started, `launch` raises after the steps before it."""
import invisible_core.juggler.connection as connection
import invisible_playwright._engine as engine
import invisible_playwright._session as session
import invisible_playwright.launcher as launcher
class Dry(RuntimeError):
pass
def fake_launch(*a, **k):
raise Dry("dry run: the engine is not started")
fake = lambda *a, **k: Path(sys.executable) # noqa: E731
for owner in (engine, session, launcher):
setattr(owner, "resolve_executable", fake)
connection.launch = fake_launch
# ── the driver ──────────────────────────────────────────────────────────────
def kill_tree(proc: subprocess.Popen) -> None:
try:
if os.name == "nt":
subprocess.run(["taskkill", "/F", "/T", "/PID", str(proc.pid)], capture_output=True, timeout=30)
else:
os.killpg(os.getpgid(proc.pid), signal.SIGKILL)
except Exception: # noqa: BLE001
with contextlib.suppress(Exception):
proc.kill()
def run_worker(scenario: str, seed: int, workdir: Path, tag: str, *, proxy: str = "", stun: str = "", env_extra: Optional[Dict[str, str]] = None,
profile: bool = False, timeout: int = 300) -> Dict[str, Any]:
out = workdir / ("run-%s.json" % tag)
cmd = [sys.executable, "-u", str(HERE), "--worker", "--scenario", scenario, "--seed", str(seed), "--out", str(out)]
if proxy:
cmd += ["--proxy", proxy]
if stun:
cmd += ["--stun", stun]
if profile:
cmd += ["--profile", "--profile-out", str(workdir / ("profile-%s.txt" % tag))]
env = dict(os.environ, **(env_extra or {}))
kwargs: Dict[str, Any] = {"env": env, "stdout": subprocess.PIPE, "stderr": subprocess.STDOUT}
if os.name != "nt":
kwargs["start_new_session"] = True
proc = subprocess.Popen(cmd, **kwargs)
try:
text, _ = proc.communicate(timeout=timeout)
except subprocess.TimeoutExpired:
kill_tree(proc)
text, _ = proc.communicate()
return {"status": "timeout", "scenario": scenario, "log": (text or b"").decode("utf-8", "replace")[-2000:]}
if proc.poll() is None:
kill_tree(proc)
if not out.exists():
return {"status": "no-result", "scenario": scenario, "log": (text or b"").decode("utf-8", "replace")[-2000:]}
data = json.loads(out.read_text(encoding="utf-8"))
if data.get("status") != "ok":
data["log"] = (text or b"").decode("utf-8", "replace")[-1500:]
return data
def build_run(data: Dict[str, Any]) -> Dict[str, Any]:
"""One run's spans as a tree, in ms relative to the call."""
call0, call1 = data["call_ns"]
spans = []
for s in data.get("spans", []):
if s["t1"] < call0:
continue
spans.append({"label": s["label"], "t0": (s["t0"] - call0) / 1e6, "t1": (s["t1"] - call0) / 1e6, "thread": s["thread"]})
spans.append({"label": "call", "t0": 0.0, "t1": (call1 - call0) / 1e6, "thread": "MainThread"})
spans.sort(key=lambda s: (s["t0"], -s["t1"]))
stack: List[Dict[str, Any]] = []
for s in spans:
if s["label"] in BACKGROUND:
# not in the line of the caller: it hangs under the step it started inside, and never holds another open
holder = [p for p in stack if p["t0"] <= s["t0"] and s["t1"] <= p["t1"] + 1e-9]
s["parent"] = holder[-1] if holder else None
s["bg"] = True
continue
while stack and not (stack[-1]["t0"] <= s["t0"] and s["t1"] <= stack[-1]["t1"] + 1e-9):
stack.pop()
s["parent"] = stack[-1] if stack else None
s["bg"] = False
stack.append(s)
seen: Dict[Tuple[int, str], int] = {}
for s in spans:
parent = s["parent"]
key = (id(parent), s["label"])
seen[key] = seen.get(key, 0) + 1
s["path"] = ((parent["path"] + "/") if parent else "") + s["label"] + ("" if seen[key] == 1 else "#%d" % seen[key])
s["depth"] = (parent["depth"] + 1) if parent else 0
for s in spans:
kids = [k["t1"] - k["t0"] for k in spans if k["parent"] is s and not k["bg"]]
s["self"] = max(0.0, (s["t1"] - s["t0"]) - sum(kids))
marks = data.get("marks_ns", {})
return {"spans": spans, "call_ms": (call1 - call0) / 1e6,
"import_core_ms": marks.get("import_core", 0) / 1e6, "import_wrapper_ms": marks.get("import_wrapper", 0) / 1e6}
def pct(values: List[float], q: float) -> float:
v = sorted(values)
return v[max(0, math.ceil(q * len(v)) - 1)]
def ancestors(s: Dict[str, Any]) -> set:
out = set()
while s["parent"] is not None:
s = s["parent"]
out.add(s["path"])
return out
def aggregate(runs: List[Dict[str, Any]]) -> Dict[str, Any]:
n = len(runs)
by_path: Dict[str, Dict[str, Any]] = {}
for r in runs:
for s in r["spans"]:
e = by_path.setdefault(s["path"], {"path": s["path"], "label": s["label"], "depth": s["depth"], "dur": [], "self": [], "start": [],
"threads": set(), "bg": s["bg"], "parent": s["parent"]["path"] if s["parent"] else None})
e["dur"].append(s["t1"] - s["t0"])
e["self"].append(s["self"])
e["start"].append(s["t0"])
e["threads"].add(s["thread"])
# overlaps: two steps neither of which holds the other, overlapping in half of the runs or more
overlap_runs: Dict[Tuple[str, str], int] = {}
for r in runs:
spans = [s for s in r["spans"] if s["t1"] - s["t0"] >= 2.0]
up = {s["path"]: ancestors(s) for s in spans}
for i, a in enumerate(spans):
for b in spans[i + 1:]:
if a["path"] in up[b["path"]] or b["path"] in up[a["path"]]:
continue
common = min(a["t1"], b["t1"]) - max(a["t0"], b["t0"])
if common >= max(1.0, 0.5 * min(a["t1"] - a["t0"], b["t1"] - b["t0"])):
key = tuple(sorted((a["path"], b["path"])))
overlap_runs[key] = overlap_runs.get(key, 0) + 1
parallel: Dict[str, List[str]] = {}
for (a, b), count in overlap_runs.items():
if count * 2 >= n:
parallel.setdefault(a, []).append(b)
parallel.setdefault(b, []).append(a)
total = [r["import_core_ms"] + r["import_wrapper_ms"] + r["call_ms"] + _goto1(r) for r in runs]
total_median = statistics.median(total)
steps = []
for e in by_path.values():
steps.append({
"path": e["path"], "label": e["label"], "depth": e["depth"], "parent": e["parent"], "count": len(e["dur"]),
"median_ms": round(statistics.median(e["dur"]), 3), "p90_ms": round(pct(e["dur"], 0.9), 3),
"min_ms": round(min(e["dur"]), 3), "max_ms": round(max(e["dur"]), 3),
"self_median_ms": round(statistics.median(e["self"]), 3),
"start_median_ms": round(statistics.median(e["start"]), 3),
"pct_total": round(100.0 * statistics.median(e["dur"]) / total_median, 2) if total_median else 0.0,
"thread": ",".join(sorted(e["threads"])), "background": e["bg"],
"in_parallel_with": sorted(parallel.get(e["path"], [])),
})
steps.sort(key=lambda x: (x["start_median_ms"], x["depth"]))
return {
"runs": n,
"total_ms": {"median": round(total_median, 1), "p90": round(pct(total, 0.9), 1), "min": round(min(total), 1), "max": round(max(total), 1)},
"import_core_ms": _stat([r["import_core_ms"] for r in runs]),
"import_wrapper_ms": _stat([r["import_wrapper_ms"] for r in runs]),
"call_ms": _stat([r["call_ms"] for r in runs]),
"steps": _in_tree_order(steps),
}
def _goto1(r: Dict[str, Any]) -> float:
for s in r["spans"]:
if s["label"] == "goto1":
return s["t1"] - s["t0"]
return 0.0
def _stat(values: List[float]) -> Dict[str, float]:
return {"median": round(statistics.median(values), 2), "p90": round(pct(values, 0.9), 2), "min": round(min(values), 2), "max": round(max(values), 2)}
def _in_tree_order(steps: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
children: Dict[Optional[str], List[Dict[str, Any]]] = {}
for s in steps:
children.setdefault(s["parent"], []).append(s)
out: List[Dict[str, Any]] = []
def walk(parent: Optional[str]) -> None:
for s in sorted(children.get(parent, []), key=lambda x: x["start_median_ms"]):
out.append(s)
walk(s["path"])
walk(None)
return out
def describe(label: str) -> str:
if label.startswith("send:"):
return "Juggler: " + label[5:]
return DESC.get(label, "")
def markdown(report: Dict[str, Any]) -> str:
meta = report["meta"]
lines = ["# Map of the launch of invisible (%s)" % meta["system"], ""]
lines.append("A measurement, not a verdict: no threshold. Times in milliseconds, median and p90 of %s launches on a warm cache (one warm-up launch that is not counted; every launch in a new interpreter)." % report["config"]["runs"])
lines.append("")
lines.append("- system: %s, Python %s, %s CPUs" % (meta["platform"], meta["python"], meta["cpus"]))
lines.append("- core %s, wrapper %s, engine %s (%s)" % (meta["core"], meta["wrapper"], meta["engine_tag"], meta["engine_upstream"]))
lines.append("- run: %s" % meta.get("run_url", "local"))
if meta.get("fetch_seconds") is not None:
lines.append("- download of the engine on a cold cache (`fetch`, outside the map): %.1f s" % meta["fetch_seconds"])
lines.append("- time 0 is the instant before `InvisiblePlaywright(...)`; the total is the import + the call up to the first page + the first goto")
if meta.get("unpatched"):
lines.append("- steps that could not be measured (targets not found): %s" % "; ".join(sorted(set(meta["unpatched"]))))
lines.append("")
for name, sc in report["scenarios"].items():
lines += _scenario_md("Scenario `%s` (warm cache)" % name, sc)
cold = report.get("cold")
if cold:
lines += _scenario_md("Cold cache, scenario `direct`: ONE launch (a new cache directory: GeoIP database, intermediates list, font files; the engine was there)", cold)
for name, why in report.get("failed", {}).items():
lines += ["## %s: not measured" % name, "", why, ""]
return "\n".join(lines) + "\n"
def _scenario_md(title: str, sc: Dict[str, Any]) -> List[str]:
out = ["## " + title, ""]
t = sc["total_ms"]
out.append("Total (import to first goto): median %.0f ms, p90 %.0f ms (min %.0f, max %.0f). Import of the core %.0f ms, of the wrapper %.0f ms; the call up to the first page %.0f ms (p90 %.0f)." % (
t["median"], t["p90"], t["min"], t["max"], sc["import_core_ms"]["median"], sc["import_wrapper_ms"]["median"], sc["call_ms"]["median"], sc["call_ms"]["p90"]))
out.append("")
out.append("| step | what | median ms | p90 ms | % of total | own ms | in parallel with | thread |")
out.append("|---|---|---:|---:|---:|---:|---|---|")
total = t["median"]
out.append("| import of the core and the wrapper | the packages are imported | %.0f | %.0f | %.1f | %.0f | | MainThread |" % (
sc["import_core_ms"]["median"] + sc["import_wrapper_ms"]["median"],
sc["import_core_ms"]["p90"] + sc["import_wrapper_ms"]["p90"],
100.0 * (sc["import_core_ms"]["median"] + sc["import_wrapper_ms"]["median"]) / total if total else 0,
sc["import_core_ms"]["median"] + sc["import_wrapper_ms"]["median"]))
hidden: Dict[Optional[str], List[float]] = {}
visible = []
for s in sc["steps"]:
if s["median_ms"] < 0.3 and s["label"] != "call":
hidden.setdefault(s["parent"], []).append(s["median_ms"])
else:
visible.append(s)
for s in visible:
parallel = ", ".join(p.split("/")[-1] for p in s["in_parallel_with"])
name = ("&nbsp;&nbsp;" * s["depth"]) + "`" + s["path"].split("/")[-1] + "`"
names = s["thread"].split(",")
thread = "" if names == ["MainThread"] else ", ".join(names[:2]) + (" +%d" % (len(names) - 2) if len(names) > 2 else "")
out.append("| %s | %s | %.1f | %.1f | %.1f | %.1f | %s | %s |" % (
name, describe(s["label"]), s["median_ms"], s["p90_ms"], s["pct_total"], s["self_median_ms"], parallel, thread))
extra = hidden.get(s["path"])
if extra:
out.append("| %s+ %d steps under 0.3 ms | | %.1f | | | | | |" % ("&nbsp;&nbsp;" * (s["depth"] + 1), len(extra), sum(extra)))
out.append("")
return out
def top_three(sc: Dict[str, Any]) -> List[Dict[str, Any]]:
"""The three steps with the most time of their own in the line of the caller (not the ones that wait for what is under them)."""
cands = [s for s in sc["steps"] if not s["background"] and s["label"] not in ("call",)]
return sorted(cands, key=lambda s: -s["self_median_ms"])[:3]
def meta_of(unpatched: List[str]) -> Dict[str, Any]:
from invisible_core.seal import active_seal
import invisible_core
import invisible_playwright
seal = active_seal()
return {
"system": "Windows" if os.name == "nt" else "Linux", "platform": platform.platform(), "python": platform.python_version(),
"cpus": os.cpu_count(), "core": getattr(invisible_core, "__version__", "?"), "wrapper": getattr(invisible_playwright, "__version__", "?"),
"engine_tag": seal.tag, "engine_upstream": seal.upstream_version,
"run_url": os.environ.get("INIT_MAP_RUN_URL") or "locale", "unpatched": unpatched,
"date_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"temp": tempfile.gettempdir(),
}
def count_browsers() -> int:
try:
if os.name == "nt":
text = subprocess.run(["tasklist", "/FI", "IMAGENAME eq firefox.exe"], capture_output=True, text=True, timeout=30).stdout
return text.lower().count("firefox.exe")
text = subprocess.run(["pgrep", "-c", "-f", "firefox"], capture_output=True, text=True, timeout=30).stdout
return int(text.strip() or 0)
except Exception: # noqa: BLE001
return -1
def driver(args: argparse.Namespace) -> int:
out = Path(args.out)
out.mkdir(parents=True, exist_ok=True)
work = Path(tempfile.mkdtemp(prefix="init-map-"))
scenarios = [s for s in args.scenarios.split(",") if s]
report: Dict[str, Any] = {"config": {"runs": args.runs, "seed": args.seed, "scenarios": scenarios}, "scenarios": {}, "failed": {}}
gateway = None
proxy = stun = ""
exit_ip = ""
if "proxy" in scenarios:
sys.path.insert(0, str(ROOT / "tests"))
import _socks_servers
# The gateway of the tests refuses the question "what is my exit" (the lab declares it instead of asking the internet). Here the question is the step that
# is measured, so the gateway forwards it for real: the TCP discovery goes through it to the services, as it does through a real proxy.
_socks_servers.asks_the_world = lambda server, host, port: False
try:
from invisible_core._geo import discover_egress_ip
exit_ip = discover_egress_ip(None)
except Exception as exc: # noqa: BLE001
print("the exit address of this machine could not be asked (%s): the fake STUN answers its default" % exc)
gateway = _socks_servers.coherent(exit_ip=exit_ip) if exit_ip else _socks_servers.coherent()
proxy, stun = gateway.server, gateway.measure_servers[0]
report["config"]["proxy_gateway"] = "coherent SOCKS5 on loopback (tests/_socks_servers.py), TCP forwarded for real, UDP to a fake STUN that answers the machine's exit"
unpatched: List[str] = []
try:
for name in scenarios:
kw = {"proxy": proxy, "stun": stun} if name == "proxy" else {}
print("== %s: warm-up" % name, flush=True)
warm = run_worker(name, args.seed, work, name + "-warm", **kw)
if warm.get("status") != "ok":
report["failed"][name] = "the warm-up launch failed: %s %s" % (warm.get("error") or warm.get("status"), (warm.get("log") or warm.get("traceback") or "")[-600:])
print(report["failed"][name], flush=True)
continue
unpatched += warm.get("unpatched", [])
good: List[Dict[str, Any]] = []
failures = []
for i in range(args.runs):
data = run_worker(name, args.seed, work, "%s-%02d" % (name, i), **kw)
if data.get("status") == "ok":
good.append(build_run(data))
print("== %s run %d/%d: call %.0f ms" % (name, i + 1, args.runs, good[-1]["call_ms"]), flush=True)
else:
failures.append(data.get("error") or data.get("status"))
print("== %s run %d/%d FAILED: %s" % (name, i + 1, args.runs, failures[-1]), flush=True)
if good:
report["scenarios"][name] = aggregate(good)
report["scenarios"][name]["raw"] = [{"call_ms": r["call_ms"], "spans": [{k: s[k] for k in ("label", "path", "t0", "t1", "thread")} for s in r["spans"]]} for r in good]
if failures:
report["scenarios"][name]["failed_runs"] = failures
else:
report["failed"][name] = "no launch succeeded: %s" % failures[:3]
if "direct" in scenarios and "direct" in report["scenarios"]:
from invisible_core.download import engine_root
cold_cache = work / "cold-cache"
print("== cold cache (one launch, a new cache directory, the engine kept)", flush=True)
data = run_worker("direct", args.seed, work, "cold", env_extra={
"INVISIBLE_PLAYWRIGHT_CACHE_DIR": str(cold_cache), "INVISIBLE_PLAYWRIGHT_ENGINE_DIR": str(engine_root())})
if data.get("status") == "ok":
report["cold"] = aggregate([build_run(data)])
else:
report["failed"]["cold"] = "the cold-cache launch failed: %s %s" % (data.get("error") or data.get("status"), (data.get("log") or "")[-600:])
print("== profile (one launch under cProfile)", flush=True)
data = run_worker("direct", args.seed, work, "profile", profile=True)
if data.get("status") == "ok" and (work / "profile-profile.txt").exists():
shutil.copy(work / "profile-profile.txt", out / ("init-map-profile-%s.txt" % ("windows" if os.name == "nt" else "linux")))
finally:
if gateway is not None:
with contextlib.suppress(Exception):
gateway.close()
report["meta"] = meta_of(unpatched)
report["meta"]["browsers_left"] = count_browsers()
for name, sc in list(report["scenarios"].items()) + ([("cold", report["cold"])] if report.get("cold") else []):
sc["top_three_by_own_time"] = [{"path": s["path"], "self_median_ms": s["self_median_ms"], "median_ms": s["median_ms"]} for s in top_three(sc)]
if os.environ.get("INIT_MAP_FETCH_SECONDS"):
report["meta"]["fetch_seconds"] = float(os.environ["INIT_MAP_FETCH_SECONDS"])
system = "windows" if os.name == "nt" else "linux"
(out / ("init-map-%s.json" % system)).write_text(json.dumps(report, indent=1), encoding="utf-8")
text = markdown(report)
(out / ("init-map-%s.md" % system)).write_text(text, encoding="utf-8")
print(text)
shutil.rmtree(work, ignore_errors=True)
return 0 if report["scenarios"] else 1
def main() -> int:
for stream in (sys.stdout, sys.stderr):
with contextlib.suppress(Exception):
stream.reconfigure(encoding="utf-8")
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
ap.add_argument("--worker", action="store_true")
ap.add_argument("--dry", action="store_true", help="local check of the wrapping: the engine is not started (worker only)")
ap.add_argument("--scenario", default="direct")
ap.add_argument("--scenarios", default="direct,proxy,headless")
ap.add_argument("--runs", type=int, default=10)
ap.add_argument("--seed", type=int, default=4242)
ap.add_argument("--proxy", default="")
ap.add_argument("--stun", default="")
ap.add_argument("--profile", action="store_true")
ap.add_argument("--profile-out", default="")
ap.add_argument("--out", default="init-map")
args = ap.parse_args()
return worker(args) if args.worker else driver(args)
if __name__ == "__main__":
sys.exit(main())
+47
View File
@@ -0,0 +1,47 @@
import socket,json,subprocess,time,os,sys,base64
base=os.getcwd(); prof=base+'/prof'; os.makedirs(prof,exist_ok=True)
exe=base+'/ex3/core/firefox.exe'
open(prof+'/user.js','w').write('user_pref("marionette.port",2828);user_pref("browser.shell.checkDefaultBrowser",false);user_pref("datareporting.policy.dataSubmissionEnabled",false);user_pref("app.update.auto",false);user_pref("app.update.enabled",false);\n')
p=subprocess.Popen([exe,'-headless','-marionette','-remote-allow-system-access','-no-remote','-profile',prof,'about:blank'],env=dict(os.environ,MOZ_REMOTE_ALLOW_SYSTEM_ACCESS='1'),stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
try:
s=None
for i in range(60):
try:
s=socket.create_connection(('127.0.0.1',2828),timeout=5);break
except Exception: time.sleep(1)
f=s.makefile('rwb',buffering=0)
def rd():
n=b''
while True:
c=s.recv(1)
if c==b':':break
n+=c
n=int(n);d=b''
while len(d)<n: d+=s.recv(n-len(d))
return json.loads(d)
mid=[0]
def cmd(name,params=None):
mid[0]+=1
m=json.dumps([0,mid[0],name,params or {}]).encode()
s.sendall(str(len(m)).encode()+b':'+m)
while True:
r=rd()
if r[0]==1 and r[1]==mid[0]: return r[2] if r[2] else r[3]
s.settimeout(60)
rd()
cmd('WebDriver:NewSession',{'capabilities':{}})
h=cmd('WebDriver:GetWindowHandles'); cmd('WebDriver:SwitchToWindow',{'handle':h[0]})
cmd('WebDriver:Navigate',{'url':'data:text/html,<body><p id=p>text</p>'})
js="""
const fonts=['menu','caption','icon','message-box','small-caption','status-bar','system-ui'];
const colors=['Canvas','CanvasText','LinkText','VisitedText','ActiveText','ButtonFace','ButtonText','ButtonBorder','Field','FieldText','GrayText','Highlight','HighlightText','Mark','MarkText','SelectedItem','SelectedItemText','AccentColor','AccentColorText','ActiveBorder','ActiveCaption','AppWorkspace','Background','ButtonHighlight','ButtonShadow','CaptionText','InactiveBorder','InactiveCaption','InactiveCaptionText','InfoBackground','InfoText','Menu','MenuText','Scrollbar','ThreeDDarkShadow','ThreeDFace','ThreeDHighlight','ThreeDLightShadow','ThreeDShadow','Window','WindowFrame','WindowText'];
const o={fonts:{},light:{},dark:{},selection:{}};
for(const f of fonts){const d=document.createElement('div');d.style.font=f==='system-ui'?'16px system-ui':f;document.body.appendChild(d);const c=getComputedStyle(d);o.fonts[f]={family:c.fontFamily,size:c.fontSize,weight:c.fontWeight,style:c.fontStyle,stretch:c.fontStretch};d.remove();}
for(const sch of ['light','dark']){for(const k of colors){const d=document.createElement('div');d.style.colorScheme=sch;d.style.color=k;d.style.backgroundColor=k;document.body.appendChild(d);o[sch][k]=getComputedStyle(d).color;d.remove();}
const d=document.createElement('div');d.style.colorScheme=sch;d.textContent='x';document.body.appendChild(d);const c=getComputedStyle(d,'::selection');o.selection[sch]={color:c.color,bg:c.backgroundColor};d.remove();}
return o;"""
r=cmd('WebDriver:ExecuteScript',{'script':js,'args':[]})
json.dump(r['value'] if 'value' in r else r,open(base+'/retail_theme.json','w'),indent=1)
print(json.dumps(r)[:1500])
finally:
subprocess.run(['taskkill','/F','/T','/PID',str(p.pid)],capture_output=True)
-388
View File
@@ -1,388 +0,0 @@
#!/usr/bin/env python3
"""The seeds that cover the personas the core can declare.
The core turns a seed into an identity (invisible_core._fpforge.profile.generate_profile) and the identity into
the prefs the engine is launched with (invisible_core.prefs.translate_profile_to_prefs). A page can only see what
those prefs make it see, so the values a seed can make a page read are the values of the prefs that VARY across
seeds. This computes them from the prefs themselves, never from a list of the tables:
* every seed 0..MAX_SEED-1 goes through generate_profile and translate_profile_to_prefs (en-US, one zone: neither
is a seed dimension);
* every pref whose value differs between two seeds must belong to a DIMENSION below (a group of prefs read
together: the renderer, the screen panel, the audio chain...) or be named in EXCLUDED with its reason. A pref
that varies and is in neither is an error, so a new pref of a later core cannot go uncovered unnoticed. A pref that
is a function of a dimension (the bar of a maximized window is of the panel) is in DERIVED instead: it is checked to
take one value per value of its dimension, and it is no part of the stored features;
* a dimension's value for a seed is the joint value of its prefs; the reachable values of a dimension are the
ones some seed in range produces.
From that, two sets of seeds (a greedy set cover, ties to the smallest seed, then a reverse delete of every seed
the rest does without):
final covers every reachable value of every dimension: the whole persona space the core declares;
candidate the smallest set that covers every webgl renderer and every DPR (exact: every set of that size is
searched, the smallest seeds win): what the candidate run of the A/B oracle visits.
The result is ci/persona-seeds.json, with the sha256 of the canonical JSON of its dimensions and features.
`check` recomputes everything and exits 1 with what changed: a change of the core's tables (or of the code that
reads them) is red until `write` has been run again.
python persona_cover.py write [--path ci/persona-seeds.json] [--max-seed 100000]
python persona_cover.py check [--path ...]
python persona_cover.py show [--path ...]
"""
from __future__ import annotations
import argparse
import hashlib
import itertools
import json
import os
import sys
from concurrent.futures import ProcessPoolExecutor
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
DEFAULT_PATH = ROOT / "ci" / "persona-seeds.json"
FORMAT = "persona-seeds/1"
MAX_SEED = 100_000
#: Neither is a seed dimension (locale and zone come from the exit), so one value of each is used for every seed.
LOCALE = "en-US"
ZONE = "America/New_York"
P = "zoom.stealth."
#: dimension -> the prefs that are read together. A pref may be in more than one dimension (the DPR is in the panel and
#: in the scale). "webgl_renderer" is every webgl.* pref: they must be a function of the renderer (checked).
DIMENSIONS = {
"webgl_renderer": (P + "webgl.renderer",),
"gfx_feature_status": (P + "gfx.feature_status",),
"screen_panel": (P + "screen.width", P + "screen.height", P + "screen.avail_device_width",
P + "screen.avail_device_height", "layout.css.devPixelsPerPx"),
"dpr": ("layout.css.devPixelsPerPx", P + "screen.frame_border", P + "screen.popup_ui"),
"cores": (P + "hw_concurrency",),
"audio": (P + "audio.sample_rate", P + "audio.output_latency_ms", P + "audio.max_channel_count"),
"codecs": ("media.av1.enabled", "media.encoder.webm.enabled", "media.mp4.enabled", "media.webm.enabled",
P + "media.decode_support"),
"dark_theme": ("ui.systemUsesDarkTheme", "layout.css.prefers-color-scheme.content-override"),
"render_noise": (P + "fpp.hw_seed",),
}
#: Dimensions that are not prefs: the label of the device the persona declares (the prefs carry only its blocklist
#: outcome, gfx_feature_status, which has fewer values than there are devices).
PROFILE_DIMENSIONS = ("gfx_device",)
ALL_DIMENSIONS = tuple(DIMENSIONS) + PROFILE_DIMENSIONS
#: Prefs that vary and are not covered, with the reason: a dimension with hundreds of values cannot be visited.
EXCLUDED = {
P + "media.enumeration_ms": "the time of the first enumerateDevices(): a draw from its own stream, hundreds of values, "
"no class of seeds to cover",
}
#: Prefs that are a function of a dimension: {pref: the dimension}. They are not part of the dimension's value (so the
#: stored features do not depend on which core emits them) and compute() CHECKS that, across the seeds, each takes exactly
#: one value per value of its dimension, like the webgl prefs per renderer. A derived pref the core does not emit at all is
#: fine: it is the pref of a core that comes later than the one in use (or earlier than the one that added it), and the pair
#: of cores must give the same file. maximized_ui is of the panel because the core declares the bar from the work area's
#: height as well as from the scale (declared_maximized_ui: compact when the work area is short in CSS px).
DERIVED = {
P + "screen.maximized_ui": "screen_panel",
P + "screen.ui_normal": "dpr",
P + "screen.ui_compact": "dpr",
}
#: What the candidate run visits: the smallest set that reaches every one of these dimensions' values.
CANDIDATE_DIMENSIONS = ("webgl_renderer", "dpr")
WEBGL = P + "webgl."
#: A value longer than this is shown as its sha256 prefix.
LONG = 40
def _short(value) -> str:
text = json.dumps(value, sort_keys=True)
if isinstance(value, str) and len(value) > LONG:
return "sha:" + hashlib.sha256(value.encode("utf-8")).hexdigest()[:10]
return text
def _dimension_value(prefs: dict, keys: tuple) -> str:
return "|".join("%s=%s" % (k.removeprefix(P), _short(prefs.get(k, "<absent>"))) for k in keys)
# -
# One seed, and a range of seeds (a worker computes a range).
def seed_features(seed: int) -> tuple:
"""(features of the seed, {pref: its value as JSON}). The features are {dimension: value}."""
from invisible_core._fpforge.profile import generate_profile
from invisible_core.prefs import translate_profile_to_prefs
profile = generate_profile(seed)
prefs = translate_profile_to_prefs(profile, locale=LOCALE, timezone=ZONE)
features = {dim: _dimension_value(prefs, keys) for dim, keys in DIMENSIONS.items()}
features["webgl_renderer"] = prefs[P + "webgl.renderer"] # readable: the whole string
features["gfx_device"] = profile.gpu.device or "<none>"
webgl = {k: json.dumps(v, sort_keys=True) for k, v in prefs.items() if k.startswith(WEBGL)}
features["_webgl"] = hashlib.sha256(json.dumps(webgl, sort_keys=True).encode()).hexdigest()[:12]
features["_derived"] = {k: json.dumps(prefs.get(k, "<absent>"), sort_keys=True) for k in DERIVED}
return features, {k: json.dumps(v, sort_keys=True) for k, v in prefs.items()}
def _range(bounds: tuple) -> tuple:
"""(features per seed, {pref: up to 3 distinct values}) for seeds lo..hi-1."""
lo, hi = bounds
features, seen = {}, {}
for seed in range(lo, hi):
f, prefs = seed_features(seed)
features[seed] = f
for k, v in prefs.items():
s = seen.setdefault(k, set())
if len(s) < 3:
s.add(v)
for k in set(seen) - set(prefs): # a pref this seed does not have varies too
seen[k].add("<absent>")
return features, seen
def check_derived(features: dict) -> None:
"""Raises when a DERIVED pref takes two values within one value of its dimension. features: {seed: {dimension: value,
"_derived": {pref: value}}}. A pref no seed has is skipped (a core that does not emit it)."""
for pref, dim in DERIVED.items():
seen = {}
for seed in sorted(features):
value = features[seed]["_derived"][pref]
if seen.setdefault(features[seed][dim], (value, seed))[0] != value:
first = seen[features[seed][dim]]
raise SystemExit("the derived pref %s is not a function of the dimension %s (seed %d: %s, seed %d: %s, "
"both with %s): it belongs to a wider dimension" % (
pref, dim, first[1], first[0], seed, value, features[seed][dim]))
def compute(max_seed: int = MAX_SEED, workers: int | None = None) -> dict:
"""The features of every seed 0..max_seed-1: {seed: {dimension: value}} (the dimensions of ALL_DIMENSIONS).
Raises when a pref varies across the seeds and is in no dimension and not in EXCLUDED or DERIVED, when a DERIVED
pref is not a function of its dimension, or when the webgl prefs are not a function of the renderer."""
workers = workers or max(1, min(os.cpu_count() or 1, 8))
step = max(1, -(-max_seed // (workers * 4)))
bounds = [(lo, min(lo + step, max_seed)) for lo in range(0, max_seed, step)]
if workers == 1:
parts = [_range(b) for b in bounds]
else:
with ProcessPoolExecutor(max_workers=workers) as pool:
parts = list(pool.map(_range, bounds))
features, seen = {}, {}
for f, s in parts:
features.update(f)
for k, vs in s.items():
seen.setdefault(k, set()).update(vs)
covered = {k for keys in DIMENSIONS.values() for k in keys}
varying = sorted(k for k, vs in seen.items() if len(vs) > 1)
loose = [k for k in varying if k not in covered and k not in EXCLUDED and k not in DERIVED and not k.startswith(WEBGL)]
if loose:
raise SystemExit("prefs that vary across seeds and belong to no dimension and are not excluded: %s\n"
"add each to a DIMENSION, to DERIVED (a function of one) or to EXCLUDED (with the reason) in "
"scripts/persona_cover.py" % loose)
check_derived(features)
byrenderer = {}
for seed in sorted(features):
f = features[seed]
if byrenderer.setdefault(f["webgl_renderer"], f["_webgl"]) != f["_webgl"]:
raise SystemExit("the webgl prefs are not a function of the renderer (seed %d, %s): split the dimension"
% (seed, f["webgl_renderer"]))
del f["_webgl"]
for f in features.values():
del f["_derived"]
stale = [k for k in EXCLUDED if k not in seen or len(seen[k]) < 2]
if stale:
raise SystemExit("excluded prefs that no longer vary: %s: remove them from EXCLUDED" % stale)
return features
# -
# The covers.
def reachable(features: dict, dims=ALL_DIMENSIONS) -> dict:
"""{dimension: sorted reachable values}."""
out = {d: set() for d in dims}
for f in features.values():
for d in dims:
out[d].add(f[d])
return {d: sorted(v) for d, v in out.items()}
def counts(features: dict) -> dict:
out = {d: {} for d in ALL_DIMENSIONS}
for f in features.values():
for d in ALL_DIMENSIONS:
out[d][f[d]] = out[d].get(f[d], 0) + 1
return {d: dict(sorted(c.items())) for d, c in out.items()}
def _elements(f: dict, dims) -> frozenset:
return frozenset((d, f[d]) for d in dims)
def greedy_cover(features: dict, dims=ALL_DIMENSIONS) -> list:
"""Greedy set cover over the (dimension, value) pairs, ties to the smallest seed. Seeds that produce the same
pairs are one candidate (their smallest)."""
first = {}
for seed in sorted(features):
first.setdefault(_elements(features[seed], dims), seed)
todo = set().union(*first)
chosen = []
while todo:
best = max(sorted(first.items(), key=lambda kv: kv[1]), key=lambda kv: len(kv[0] & todo))
chosen.append(best[1])
todo -= best[0]
return chosen
def reverse_delete(features: dict, seeds: list, dims=ALL_DIMENSIONS) -> list:
"""Drops, last chosen first, every seed whose pairs the others cover."""
keep = list(seeds)
for seed in reversed(seeds):
rest = [s for s in keep if s != seed]
if rest and _elements(features[seed], dims) <= set().union(*(_elements(features[s], dims) for s in rest)):
keep = rest
return sorted(keep)
def final_cover(features: dict) -> list:
return reverse_delete(features, greedy_cover(features))
def candidate_cover(features: dict, dims=CANDIDATE_DIMENSIONS) -> list:
"""The smallest set covering every value of dims: the exact minimum (every combination of the seeds that are the
smallest of their kind is tried, size by size), the lexicographically smallest seeds of that size."""
kinds = {}
for seed in sorted(features):
kinds.setdefault(_elements(features[seed], dims), seed)
todo = set().union(*kinds)
seeds = sorted(kinds.values())
for size in range(1, len(seeds) + 1):
for combo in itertools.combinations(seeds, size):
if set().union(*(_elements(features[s], dims) for s in combo)) >= todo:
return list(combo)
raise AssertionError("unreachable: all the seeds cover everything")
def covers(features: dict, seeds, dims=ALL_DIMENSIONS) -> list:
"""The (dimension, value) pairs of the reachable space that `seeds` do not reach."""
want = set().union(*(_elements(f, dims) for f in features.values()))
got = set().union(*(_elements(features[s], dims) for s in seeds)) if seeds else set()
return sorted(want - got)
# -
# The file.
def canonical(document) -> str:
return json.dumps(document, sort_keys=True, separators=(",", ":"), ensure_ascii=True)
def build(features: dict, max_seed: int) -> dict:
import invisible_core
final, candidate = final_cover(features), candidate_cover(features)
stored = sorted(set(final) | set(candidate))
dimensions = reachable(features)
kept = {str(s): features[s] for s in stored}
dpr = {str(s): float(json.loads(features[s]["dpr"].split("|")[0].split("=", 1)[1])) for s in stored}
sha = hashlib.sha256(canonical({"dimensions": dimensions, "features": kept}).encode("utf-8")).hexdigest()
return {
"format": FORMAT, "core_version": invisible_core.__version__, "max_seed": max_seed,
"candidate": candidate, "final": final, "dpr": dpr, "features": kept, "dimensions": dimensions,
"counts": counts(features), "excluded": dict(sorted(EXCLUDED.items())), "sha256": sha,
}
def render(document: dict) -> bytes:
return (json.dumps(document, sort_keys=True, indent=1, ensure_ascii=True) + "\n").encode("utf-8")
def write(path: Path = DEFAULT_PATH, max_seed: int = MAX_SEED, workers: int | None = None) -> dict:
document = build(compute(max_seed, workers), max_seed)
Path(path).write_bytes(render(document))
return document
def differences(stored: dict, fresh: dict) -> list:
"""What differs between the file and a recompute, as lines (empty when they agree). core_version alone is no
difference: the same values from another version of the core are the same personas."""
out = []
for key in sorted(set(stored) | set(fresh)):
if key == "core_version" or stored.get(key) == fresh.get(key):
continue
a, b = stored.get(key), fresh.get(key)
if key == "dimensions" and isinstance(a, dict) and isinstance(b, dict):
for dim in sorted(set(a) | set(b)):
gone = sorted(set(a.get(dim, [])) - set(b.get(dim, [])))
new = sorted(set(b.get(dim, [])) - set(a.get(dim, [])))
if gone or new:
out.append("dimension %s: %d values no seed reaches any more %s; %d new %s"
% (dim, len(gone), gone[:3], len(new), new[:3]))
elif key == "features" and isinstance(a, dict) and isinstance(b, dict):
for seed in sorted(set(a) | set(b), key=int):
if a.get(seed) != b.get(seed):
moved = sorted(d for d in set(a.get(seed) or {}) | set(b.get(seed) or {})
if (a.get(seed) or {}).get(d) != (b.get(seed) or {}).get(d))
out.append("seed %s: %s changed" % (seed, ", ".join(moved) or "is not in one of the two"))
else:
out.append("%s: %s -> %s" % (key, json.dumps(a)[:160], json.dumps(b)[:160]))
return out
def check(path: Path = DEFAULT_PATH, workers: int | None = None) -> list:
stored = json.loads(Path(path).read_text(encoding="utf-8"))
fresh = build(compute(stored["max_seed"], workers), stored["max_seed"])
lines = differences(stored, fresh)
if not lines and Path(path).read_bytes() != render(fresh):
lines.append("the file is not the canonical rendering of its own content: run `write`")
return lines
def load(path: Path = DEFAULT_PATH) -> dict:
return json.loads(Path(path).read_text(encoding="utf-8"))
def load_seeds(kind: str = "candidate", path: Path = DEFAULT_PATH) -> list:
"""The seeds of `kind` ("candidate" or "final"), ascending."""
document = load(path)
if kind not in ("candidate", "final"):
raise ValueError("kind must be 'candidate' or 'final', not %r" % (kind,))
return sorted(document[kind])
def load_visits(kind: str = "candidate", path: Path = DEFAULT_PATH) -> list:
"""[(seed, the seed's own DPR)] of `kind`, ascending."""
document = load(path)
return [(s, document["dpr"][str(s)]) for s in load_seeds(kind, path)]
def show(document: dict) -> str:
lines = ["core %s, seeds 0..%d, sha256 %s" % (document["core_version"], document["max_seed"] - 1, document["sha256"][:16])]
for kind in ("candidate", "final"):
lines.append("%s (%d): %s" % (kind, len(document[kind]), document[kind]))
for dim, values in document["dimensions"].items():
lines.append("%-20s %2d values" % (dim, len(values)))
return "\n".join(lines)
def main(argv=None) -> int:
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
ap.add_argument("cmd", choices=("write", "check", "show"))
ap.add_argument("--path", type=Path, default=DEFAULT_PATH)
ap.add_argument("--max-seed", type=int, default=MAX_SEED)
ap.add_argument("--workers", type=int)
args = ap.parse_args(argv)
if args.cmd == "show":
print(show(load(args.path)))
return 0
if args.cmd == "write":
print(show(write(args.path, args.max_seed, args.workers)))
return 0
lines = check(args.path, args.workers)
for line in lines:
print("CHANGED " + line)
print("PERSONA SEEDS %s" % ("OK" if not lines else "STALE: run `python scripts/persona_cover.py write` and commit ci/persona-seeds.json"))
return 1 if lines else 0
if __name__ == "__main__":
sys.exit(main())
+4 -25
View File
@@ -10,12 +10,6 @@ red when our engine does not idle where stock does. Profile P4: a user journey o
(tests/fakeweb/journey_site.py); stock Firefox runs first, then our engine, and the verdict compares every step field by
field (ok, url, title, marker, cookies, history length, open pages, idle, the step's own values). --repetitions is the
number of walks (P4: default 1). The stock client drives both.
The bound of a P2 wait: a P2 page is finite (MAX_DELAY_MS, 3000 ms, is its longest response) and networkidle needs 500 ms of quiet,
so the 10 s default is a cap with margin, never to be read as a cause. A stock cell that does not idle is a broken control or, by
pages.json `stock_firefox_may_lose` (a request the page itself aborts, which stock may never report the end of), stock unsettled:
not red, and ours is then judged against the outcome the page declares. The report keeps `stock_unsettled`, `platform` and the
`stock_unsettled_rate` per pattern, so the rate per platform can be followed across runs from the artifacts.
"""
from __future__ import annotations
@@ -107,31 +101,16 @@ def main(argv=None):
if args.no_stock: # stock is what pages.json says it is
stock = [dict(c, idle=declared.get(c["pattern"], "idle") == "idle") for c in candidate]
may_lose = pages.get("stock_firefox_may_lose", {})
fails, broken, unsettled = profile_p2.verdict(candidate, stock, declared, may_lose)
return finish_p2(args, patterns, candidate, stock, fails, broken, unsettled, may_lose)
def finish_p2(args, patterns, candidate, stock, fails, broken, unsettled, may_lose):
"""The report of a P2 run (written to --out), the lines printed, and the exit code: 1 on a fail or a broken control, never on unsettled alone."""
by_key = {(c["round"], c["pattern"], c["canary"], c["after"]): c for c in stock}
unsettled_cells = [{"round": key[0], "pattern": key[1], "in_flight": [r.get("url") for r in by_key[key].get("in_flight") or []]}
for key, _err in unsettled]
rate = {pattern: {"unsettled": sum(1 for u in unsettled_cells if u["pattern"] == pattern),
"rounds": sum(1 for c in stock if c["pattern"] == pattern and not c["canary"])}
for pattern in may_lose}
report = {"profile": args.profile, "patterns": patterns, "repetitions": args.repetitions, "platform": sys.platform,
"candidate": candidate, "stock": stock, "fails": fails, "broken_control": broken,
"stock_unsettled": unsettled_cells, "stock_unsettled_rate": rate}
fails, broken = profile_p2.verdict(candidate, stock, declared)
report = {"profile": args.profile, "patterns": patterns, "repetitions": args.repetitions,
"candidate": candidate, "stock": stock, "fails": fails, "broken_control": broken}
if args.out:
pathlib.Path(args.out).write_text(json.dumps(report, indent=1), encoding="utf-8")
for key, err in fails:
print("FAIL round %d %s%s: %s" % (key[0], key[1], " (canary after %s)" % key[3] if key[2] else "", err))
for key, err in broken:
print("BROKEN CONTROL stock did not idle on %s round %d: %s" % (key[1], key[0], err))
for cell in unsettled_cells:
print("STOCK UNSETTLED %s round %d: %s (pages.json stock_firefox_may_lose)" % (cell["pattern"], cell["round"], ", ".join(map(str, cell["in_flight"]))))
print("cells: %d, fails: %d, broken controls: %d, stock unsettled: %d" % (len(candidate), len(fails), len(broken), len(unsettled_cells)))
print("cells: %d, fails: %d, broken controls: %d" % (len(candidate), len(fails), len(broken)))
return 1 if (fails or broken) else 0
+218
View File
@@ -0,0 +1,218 @@
"""The expected values of tests/test_css_calc_is_windows_e2e.py.
Run it with `python -I`. Two steps, because a number is only worth testing if
the two C libraries give a different page-visible text for it:
python -I scripts/ucrt_css_calc.py dump OUT # on Windows: ucrtbase.dll's f32 functions
python -I scripts/ucrt_css_calc.py dump OUT # on Linux: the host's libm
python -I scripts/ucrt_css_calc.py pick WIN LINUX tests/data/ucrt_css_calc.txt
`dump` computes, for a fixed grid of inputs, what the style engine (Servo's
calc.rs) makes of ``calc(1px * sin(x))`` and the others, and the text it then
serializes. The style engine does every step in f32 (CSSFloat): the library
function is the f32 one (sinf, cosf, tanf, asinf, acosf, atanf, atan2f, expf,
logf, powf), an angle is converted to degrees with one f32 multiplication, and
a number is written by cssparser's dtoa_short: the shortest decimal that
reads back as that f32, rounded half up to 6 significant digits. So two
libraries whose results differ in the last f32 bit only show on the page when
that bit moves the 6th digit - which `pick` looks for.
`pick` keeps every input whose text differs between the two dumps, and a few
that do not (the control: the same text from both libraries), in the format
the test reads:
<fn> <args...> <text on Windows>
The reference is ucrtbase's FMA3 code path, the one every Windows 11 CPU runs
(the same one idwr_math reproduces); the SSE2 fallback of older CPUs can differ in
the last bit and is not what a page on Windows 11 reads.
Inputs are exact in f32 (multiples of a power of two), so the page and this
script read the same number whatever the CSS parser does with decimals.
"""
from __future__ import annotations
import ctypes
import math
import struct
import sys
from decimal import ROUND_HALF_UP, Decimal
from pathlib import Path
#: Rust's f32::to_degrees multiplier, as an f32.
RAD_TO_DEG = struct.unpack("<f", struct.pack("<f", 57.2957795130823208767981548141051703))[0]
#: How many differing inputs of each function `pick` keeps, and how many of the
#: ones that agree.
KEEP_DIFFERENT = 6
KEEP_SAME = 3
def f32(x: float) -> float:
return struct.unpack("<f", struct.pack("<f", x))[0]
def load_libm():
if sys.platform == "win32":
lib = ctypes.CDLL("ucrtbase.dll")
else:
lib = ctypes.CDLL("libm.so.6")
funcs = {}
for name, nargs in (("sinf", 1), ("cosf", 1), ("tanf", 1), ("asinf", 1), ("acosf", 1),
("atanf", 1), ("atan2f", 2), ("expf", 1), ("logf", 1), ("powf", 2)):
fn = getattr(lib, name)
fn.restype = ctypes.c_float
fn.argtypes = [ctypes.c_float] * nargs
funcs[name] = fn
return funcs
def shortest_f32(x: float) -> str:
"""The shortest decimal text that reads back as this f32."""
for digits in range(1, 10):
text = "%.*e" % (digits - 1, x)
if f32(float(text)) == x:
return text
return "%.8e" % x
def serialize(x: float) -> str:
"""cssparser's number text for an f32: 6 significant digits, half up,
no trailing zeros, no exponent in the range the grid stays in."""
if x == 0:
return "0"
d = Decimal(shortest_f32(x))
exp = d.adjusted()
q = d.quantize(Decimal(1).scaleb(exp - 5), rounding=ROUND_HALF_UP)
text = format(q.normalize(), "f")
return "0" if text in ("-0", "") else text
def decimal(k: int, shift: int) -> str:
"""k / 2**shift as an exact decimal text."""
d = Decimal(k) / Decimal(2 ** shift)
return format(d.normalize(), "f")
def grid():
"""(fn, args as texts) for every case of the dump."""
out = []
for fn, lim, shift in (("sin", 16, 10), ("cos", 16, 10), ("tan", 16, 10)):
for k in range(-lim << shift, (lim << shift) + 1):
out.append((fn, [decimal(k, shift)]))
# Finer, over the stretch where the functions bend the most.
for k in range(-(4 << 13), (4 << 13) + 1):
out.append(("tan", [decimal(k, 13)]))
for k in range(-(8 << 12), (8 << 12) + 1):
out.append(("atan", [decimal(k, 12)]))
for k in range(-(4 << 12), (4 << 12) + 1):
out.append(("exp", [decimal(k, 12)]))
for k in range(1, 32 * 1024 + 1):
out.append(("log", [decimal(k, 10)]))
for a in range(-128, 129):
for b in range(-128, 129):
if a or b:
out.append(("atan2", [decimal(a, 6), decimal(b, 6)]))
for k in range(-4096, 4097):
out.append(("asin", [decimal(k, 12)]))
out.append(("acos", [decimal(k, 12)]))
for k in range(-8 * 512, 8 * 512 + 1):
out.append(("atan", [decimal(k, 9)]))
for a in range(-64, 65):
for b in range(-64, 65):
if a or b:
out.append(("atan2", [decimal(a, 4), decimal(b, 4)]))
for k in range(-10 * 256, 10 * 256 + 1):
out.append(("exp", [decimal(k, 8)]))
for k in range(1, 64 * 64 + 1):
out.append(("log", [decimal(k, 6)]))
for a in range(2, 513):
for b in (2, 3, 5, 7, 10):
out.append(("log", [decimal(a, 3), str(b)]))
for a in range(-32, 33):
for b in range(-32, 33):
out.append(("hypot", [decimal(a * 3, 4), decimal(b * 5, 4)]))
for a in range(4, 257):
for b in range(-64, 65):
out.append(("pow", [decimal(a, 4), decimal(b, 4)]))
return out
def evaluate(lib, fn, args):
"""(text, unit) the page shows, from f32 steps."""
v = [f32(float(a)) for a in args]
if fn in ("sin", "cos", "tan", "exp"):
return serialize(f32(lib[fn + "f"](v[0]))), "px"
if fn == "log":
if len(v) == 1:
return serialize(f32(lib["logf"](v[0]))), "px"
return serialize(f32(f32(lib["logf"](v[0])) / f32(lib["logf"](v[1])))), "px"
if fn == "hypot":
# powi(2) is a product, the sum is f32, sqrt is exact in IEEE: no library
# function here, so no difference between the two - the control.
return serialize(f32(math.sqrt(f32(f32(v[0] * v[0]) + f32(v[1] * v[1]))))), "px"
if fn == "pow":
return serialize(f32(lib["powf"](v[0], v[1]))), "px"
if fn in ("asin", "acos", "atan"):
return serialize(f32(f32(lib[fn + "f"](v[0])) * RAD_TO_DEG)), "deg"
if fn == "atan2":
return serialize(f32(f32(lib["atan2f"](v[0], v[1])) * RAD_TO_DEG)), "deg"
raise ValueError(fn)
def dump(out: Path) -> None:
lib = load_libm()
lines = []
for fn, args in grid():
text, unit = evaluate(lib, fn, args)
if text in ("nan", "inf", "-inf") or "e" in text.lower():
continue
lines.append("%s %s %s%s" % (fn, " ".join(args), text, unit))
out.write_text("\n".join(lines) + "\n")
print("wrote %s: %d cases (%s)" % (out, len(lines), sys.platform))
def read(path: Path) -> dict:
cases = {}
for line in path.read_text().splitlines():
parts = line.split()
cases[tuple(parts[:-1])] = parts[-1]
return cases
def pick(win: Path, linux: Path, out: Path) -> None:
a, b = read(win), read(linux)
chosen = ["# Expected text of getComputedStyle for calc(1px * f(args)) (word-spacing)",
"# and of rotate: f(args) for the angle functions, from ucrtbase.dll's f32",
"# functions. Generated by scripts/ucrt_css_calc.py (python -I) - do not edit.",
"# <fn> <args...> <text on Windows>"]
stats = []
for fn in ("sin", "cos", "tan", "asin", "acos", "atan", "atan2", "exp", "log", "pow", "hypot"):
keys = sorted(k for k in a if k[0] == fn and k in b)
different = [k for k in keys if a[k] != b[k]]
same = [k for k in keys if a[k] == b[k]]
# Spread over the list, not the first ones.
step_d = max(1, len(different) // KEEP_DIFFERENT)
quarter = max(1, len(same) // 4)
take = different[::step_d][:KEEP_DIFFERENT] + same[quarter::quarter][:KEEP_SAME]
stats.append("%s: %d of %d differ" % (fn, len(different), len(keys)))
for k in take:
chosen.append("%s %s" % (" ".join(k), a[k]))
out.write_text("\n".join(chosen) + "\n")
print("\n".join(stats))
print("wrote %s" % out)
def main(argv) -> int:
if len(argv) == 3 and argv[1] == "dump":
dump(Path(argv[2]))
elif len(argv) == 5 and argv[1] == "pick":
pick(Path(argv[2]), Path(argv[3]), Path(argv[4]))
else:
print(__doc__)
return 2
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
@@ -1,415 +0,0 @@
"""The argument of `page.evaluate(fn, arg)` and its kin, on its way into the page.
The client sends `{"value": <tagged>, "handles": [{guid}, ...]}`. THE ONE PLACE it is read for the caller's code: `_run_callers_code`, the element-scoped
calls, `wait_for_function` and the result of an exposed function all take it through `Argument`.
⛔ UNTIL THIS MODULE, THE SERVER KEPT A NUMBER, A STRING, A BOOLEAN, AN ARRAY AND AN OBJECT AND MADE EVERYTHING ELSE `null`: a handle (`h`), a date
(`d`), a URL (`u`), a regular expression (`r`), an error (`e`), a typed array (`ta`), a BigInt (`bi`), a reference to an object already seen (`ref`:
a repeat and a cycle), `undefined`, and `-0` (the Python client sends `-0` for EVERY float `0.0`). A bare Python `nan` went into the JSON. The call
went on with the wrong argument and answered.
What stock Playwright 1.61 does (driver bundle `coreBundle.js`, by function name):
* NODE SIDE. `parseArgument` -> `parseSerializedValue` builds the real values; `evaluateExpression` serialises them again with `serializeAsCallArgument`
(a number, a string and a boolean lose their tag, a Date is `{d: toJSON()}`, which is milliseconds, an Error's stack is normalised) and takes each
handle through `adoptIfNeeded`. A primitive handle falls through as its value (`fallThrough: handle._value`).
* The handle errors are thrown there: a handle that is not an element and is of another context or world is `JSHandles can be evaluated only in the
context they were created!`; an element of another frame or world is adopted (`Page.adoptNode`), and if the adoption answers nothing it is `Unable to
adopt element handle from a different document`; a disposed or unknown guid is `arg.handles[0]: no object with guid <guid>` (the path starts with the
parameter's name).
* PAGE SIDE. `UtilityScript.evaluate` runs `parseEvaluationResultValue` on every argument, BEFORE it evaluates the caller's text.
HERE, the same two steps. A tree of plain JSON (number, string, boolean, null, array, object; no reference, no handle, nothing special) goes as the
protocol value it always went as. A top-level NaN, Infinity, -Infinity or -0 is the engine's `unserializableValue`; a top-level `undefined` is an
argument with no `value`; a top-level object handle is its `objectId`. EVERYTHING ELSE is decoded in the page by one extra `Runtime.callFunction` in the
same caller context, whose declaration is stock's own `parseEvaluationResultValue` (below, verbatim: a test compares it with the text the core ships
and the bundle's), called with the spec and the handles' objects; what it made is the ONE argument of the unchanged `(f, ...a) => f(...a)` and is
released after the call. The decoder runs before the caller's function and leaves no global.
LIMITS, SAID. A BigInt as the WHOLE argument cannot be decoded here: the decoder would have to return a BigInt, and the protocol's JSON has no BigInt
(inside an array or an object it is fine). A utility-world value that is not a node (the properties `get_property` and `get_property_list` hand back)
cannot cross to the caller's world, which stock never needed because its handles are all of one world.
"""
from __future__ import annotations
import re
from typing import Any, Callable, Dict, List, Optional
from .dispatcher import ProtocolException
#: The text stock throws, node side.
NOT_IN_THE_CONTEXT = "JSHandles can be evaluated only in the context they were created!"
NOT_ADOPTED = "Unable to adopt element handle from a different document"
#: Playwright's `parseEvaluationResultValue`, `base64ToTypedArray` and the typed-array table, VERBATIM from the utility script the core ships
#: (`invisible_core/juggler/injected.js`, the same text as the driver bundle's `packages/isomorphic/utilityScriptSerializers.ts`).
_STOCK = r'''const typedArrayConstructors = {
i8: Int8Array,
ui8: Uint8Array,
ui8c: Uint8ClampedArray,
i16: Int16Array,
ui16: Uint16Array,
i32: Int32Array,
ui32: Uint32Array,
// TODO: add Float16Array once it's in baseline
f32: Float32Array,
f64: Float64Array,
bi64: BigInt64Array,
bui64: BigUint64Array
};
function base64ToTypedArray(base64, TypedArrayConstructor) {
const binary = atob(base64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++)
bytes[i] = binary.charCodeAt(i);
return new TypedArrayConstructor(bytes.buffer);
}
function parseEvaluationResultValue(value, handles = [], refs = /* @__PURE__ */ new Map()) {
if (Object.is(value, void 0))
return void 0;
if (typeof value === "object" && value) {
if ("ref" in value)
return refs.get(value.ref);
if ("v" in value) {
if (value.v === "undefined")
return void 0;
if (value.v === "null")
return null;
if (value.v === "NaN")
return NaN;
if (value.v === "Infinity")
return Infinity;
if (value.v === "-Infinity")
return -Infinity;
if (value.v === "-0")
return -0;
return void 0;
}
if ("d" in value) {
return new Date(value.d);
}
if ("u" in value)
return new URL(value.u);
if ("bi" in value)
return BigInt(value.bi);
if ("e" in value) {
const error = new Error(value.e.m);
error.name = value.e.n;
error.stack = value.e.s;
return error;
}
if ("r" in value)
return new RegExp(value.r.p, value.r.f);
if ("a" in value) {
const result = [];
refs.set(value.id, result);
for (const a of value.a)
result.push(parseEvaluationResultValue(a, handles, refs));
return result;
}
if ("o" in value) {
const result = {};
refs.set(value.id, result);
for (const { k, v } of value.o) {
if (k === "__proto__")
continue;
result[k] = parseEvaluationResultValue(v, handles, refs);
}
return result;
}
if ("h" in value)
return handles[value.h];
if ("ta" in value)
return base64ToTypedArray(value.ta.b, typedArrayConstructors[value.ta.k]);
if ("ab" in value)
return base64ToTypedArray(value.ab.b, Uint8Array).buffer;
}
return value;
}'''
#: The declaration of the one extra call: the spec first, then the objects of the handles, in the order the spec names them (`{"h": i}` is the
#: i-th). Run in the caller's context, by reference.
DECODER = "(spec, ...handles) => {\n" + _STOCK + "\nreturn parseEvaluationResultValue(spec, handles);\n}"
#: THE VALUE TAGS THIS MODULE HANDLES, each one a node `_to_spec` knows. They are the keys of the driver's protocol validator for a serialized value (`scheme.SerializedValue`
#: in `coreBundle.js`: `n b s v d u bi ta e r a o h ref`; `id` only marks an array or an object and is no value) and one more, `ab` (an ArrayBuffer): the validator
#: does not list it, the page side of stock (`parseEvaluationResultValue`, embedded above) decodes it, so it is passed to the decoder as it came. A test reads the
#: validator from the installed driver and compares it with this set.
VALUE_TAGS = ("n", "b", "s", "v", "d", "u", "bi", "ab", "ta", "e", "r", "a", "o", "h", "ref")
_SPECIAL_NUMBERS = ("NaN", "Infinity", "-Infinity", "-0")
_ISO_MILLISECONDS = re.compile(r"^(\d{4,6}-\d\d-\d\dT\d\d:\d\d:\d\d)(?:\.(\d+))?Z$")
_BIGINT_REMOTE = re.compile(r"^-?\d+n$")
def split(raw: Any):
"""`(tagged value, handle channels)` of what the client sent: the envelope `{value, handles}`, or a bare tagged value, or nothing."""
if isinstance(raw, dict) and "value" in raw and "handles" in raw:
return raw["value"], list(raw.get("handles") or [])
return raw, []
def refuse_handles(raw: Any, what: str, where: str) -> None:
"""A call whose argument stays a plain value (it goes into the page as JSON, through a command that has no object to carry) says so when
the caller passed a handle, instead of sending `null` in its place."""
handles = split(raw)[1]
if handles:
raise ProtocolException(
"%s cannot carry a JSHandle: it is read in %s, where the handle's object does not exist, and used to arrive as null. Pass the "
"handle's value (json_value) or its properties instead" % (what, where))
def _is_plain(node: Any) -> bool:
if not isinstance(node, dict):
return True
if "ref" in node or "h" in node:
return False
for tag in ("n", "s", "b"):
if tag in node:
value = node[tag]
return not (isinstance(value, float) and (value != value or value in (float("inf"), float("-inf"))))
if "v" in node:
return node["v"] == "null"
if "a" in node:
return all(_is_plain(x) for x in node["a"])
if "o" in node:
return all(entry["k"] != "__proto__" and _is_plain(entry["v"]) for entry in node["o"])
return False
def _plain(node: Any) -> Any:
if not isinstance(node, dict):
return node
for tag in ("n", "s", "b"):
if tag in node:
return node[tag]
if "v" in node:
return None
if "a" in node:
return [_plain(x) for x in node["a"]]
return {entry["k"]: _plain(entry["v"]) for entry in node["o"]}
def _milliseconds(iso: Any) -> Any:
"""A date as the node side re-emits it: `Date.prototype.toJSON`, milliseconds, truncated."""
found = _ISO_MILLISECONDS.match(iso) if isinstance(iso, str) else None
if not found:
return iso
return "%s.%sZ" % (found.group(1), ((found.group(2) or "") + "000")[:3])
def _error(entry: Dict) -> Dict:
"""`{e: {n, m, s}}` as `serializeAsCallArgument` emits it: the stack stays when it starts with `name: message`, else the head is put on it."""
name, message, stack = entry.get("n"), entry.get("m"), entry.get("s")
name = "" if name is None else str(name)
message = "" if message is None else str(message)
stack = "" if stack is None else str(stack)
head = name + ": " + message
return {"e": {"n": name, "m": message, "s": stack if stack.startswith(head) else head + "\n" + stack}}
def _argument_of(remote: Dict) -> Dict:
"""A RemoteObject as the engine's `CallFunctionArgument`."""
if remote.get("objectId"):
return {"objectId": remote["objectId"]}
if "unserializableValue" in remote:
return {"unserializableValue": remote["unserializableValue"]}
if "value" in remote:
return {"value": remote["value"]}
return {}
class Argument:
"""One argument, resolved against the caller's world `context` of the frame `frame_id` and ready to be the last argument of a call there.
Built before the caller's code runs (the handle errors are stock's, thrown before the script), so the code never runs on a refused argument. The
one extra command, the decoder, is made at `call_argument()` and once: a poll asks it every turn and gets the same object. `release()` lets go
of what this made (the decoded object and the copies of the elements it carried) and nothing of the caller's own handles; it is safe twice."""
def __init__(self, injected, context: str, frame_id: Optional[str], raw: Any, lookup: Optional[Callable[[str], Any]] = None, *,
what: str = "arg", handles_allowed: bool = True) -> None:
self.injected = injected
self.context = context
self.frame_id = frame_id
self.lookup = lookup
self.what = what
self.handles_allowed = handles_allowed
tagged, self._channels = split(raw)
self._plain: Any = None
self._spec: Any = None
self._root_is_handle = False
self._objects: List[str] = []
self._by_guid: Dict[str, Any] = {}
self._copies: List[str] = []
self._decoded: Optional[str] = None
self._argument: Optional[Dict] = None
self._is_plain = _is_plain(tagged)
try:
if self._is_plain:
self._plain = _plain(tagged)
else:
self._root_is_handle = isinstance(tagged, dict) and "h" in tagged and "ref" not in tagged
self._spec = self._to_spec(tagged)
if isinstance(self._spec, dict) and set(self._spec) == {"bi"}:
raise ProtocolException(
"a BigInt as the whole argument cannot be handed to the page: the engine's protocol carries no BigInt. Put it in an "
"array or an object, or pass it as a string")
except BaseException:
self.release()
raise
# ── the spec: what the page side reads ───────────────────────────────────
def _to_spec(self, node: Any) -> Any:
if not isinstance(node, dict):
return node
if "ref" in node:
return {"ref": node["ref"]}
if "n" in node:
number = node["n"]
if isinstance(number, float) and number != number:
return {"v": "NaN"}
if isinstance(number, float) and number in (float("inf"), float("-inf")):
return {"v": "Infinity" if number > 0 else "-Infinity"}
return number
if "s" in node:
return node["s"]
if "b" in node:
return node["b"]
if "v" in node:
return {"v": node["v"]}
if "d" in node:
return {"d": _milliseconds(node["d"])}
if "u" in node:
return {"u": node["u"]}
if "bi" in node:
return {"bi": node["bi"]}
if "e" in node:
return _error(node["e"])
if "r" in node:
return {"r": {"p": node["r"].get("p"), "f": node["r"].get("f")}}
if "ta" in node:
return {"ta": {"b": node["ta"]["b"], "k": node["ta"]["k"]}}
if "ab" in node:
return {"ab": node["ab"]}
if "a" in node:
spec = {"a": [self._to_spec(x) for x in node["a"]]}
if "id" in node:
spec["id"] = node["id"]
return spec
if "o" in node:
spec = {"o": [{"k": entry["k"], "v": self._to_spec(entry["v"])} for entry in node["o"]]}
if "id" in node:
spec["id"] = node["id"]
return spec
if "h" in node:
return self._handle(node["h"])
raise ProtocolException("Attempting to deserialize unexpected value: %r" % (node,))
# ── the handles ──────────────────────────────────────────────────────────
def _handle(self, index: int) -> Any:
"""`{"h": position}` (the position among the objects the decoder gets), or the value of a primitive handle."""
try:
channel = self._channels[index]
except (IndexError, TypeError):
raise ProtocolException("%s.handles[%s]: no object with guid undefined" % (self.what, index)) from None
guid = channel.get("guid") if isinstance(channel, dict) else None
if guid not in self._by_guid:
self._by_guid[guid] = self._resolve(index, guid)
kind, value = self._by_guid[guid]
if kind == "inline":
return value
return {"h": value}
def _resolve(self, index: int, guid: Optional[str]):
if not self.handles_allowed:
raise ProtocolException(
"%s carries a JSHandle, which cannot be delivered here: its object lives in the caller's world, and this answer is read in the "
"page's own" % self.what)
missing = ProtocolException("%s.handles[%d]: no object with guid %s" % (self.what, index, guid))
try:
handle = self.lookup(guid) if self.lookup is not None else None
except ProtocolException:
handle = None
if handle is None or getattr(handle, "disposed", False):
raise missing
frame = getattr(handle, "frame", None)
if frame is None:
raise missing
frame_id = frame.frame_id
if getattr(handle, "world", "utility") == "caller":
if not handle.object_id:
return ("inline", self._primitive(handle.remote or {}))
held_in = getattr(handle, "context", None)
if frame_id != self.frame_id or (held_in is not None and held_in != self.context):
raise ProtocolException(NOT_IN_THE_CONTEXT)
return ("object", self._place(handle.object_id))
if not getattr(handle, "node", True):
raise ProtocolException(NOT_IN_THE_CONTEXT)
if frame_id == self.frame_id:
copy = self.injected.node_to_caller(self.frame_id, handle.object_id)
else:
road = self.injected.adopt(frame_id, handle.object_id, into=self.frame_id)
if not road:
raise ProtocolException(NOT_ADOPTED)
try:
copy = self.injected.node_to_caller(self.frame_id, road)
finally:
self.injected.dispose(self.frame_id, road)
if not copy:
raise ProtocolException(NOT_ADOPTED)
self._copies.append(copy)
return ("object", self._place(copy))
def _place(self, object_id: str) -> int:
self._objects.append(object_id)
return len(self._objects) - 1
@staticmethod
def _primitive(remote: Dict) -> Any:
"""A primitive of the caller's world as a node of the spec: stock's `fallThrough: handle._value`."""
special = remote.get("unserializableValue")
if special in _SPECIAL_NUMBERS:
return {"v": special}
if isinstance(special, str) and _BIGINT_REMOTE.match(special):
return {"bi": special[:-1]}
if "value" in remote:
value = remote["value"]
if value is None:
return {"v": "null"}
if isinstance(value, float) and value != value:
return {"v": "NaN"}
return value
return {"v": "undefined"}
# ── the call ─────────────────────────────────────────────────────────────
def call_argument(self) -> Dict:
"""The engine's `CallFunctionArgument` for this argument. The decoder is called here, once."""
if self._argument is None:
self._argument = self._build()
return self._argument
def _build(self) -> Dict:
if self._is_plain:
return {"value": self._plain}
spec = self._spec
if self._root_is_handle and isinstance(spec, dict) and set(spec) == {"h"}:
return {"objectId": self._objects[spec["h"]]}
if isinstance(spec, dict) and set(spec) == {"v"}:
if spec["v"] in _SPECIAL_NUMBERS:
return {"unserializableValue": spec["v"]}
return {"value": None} if spec["v"] == "null" else {}
if not isinstance(spec, dict):
return {"value": spec}
decoded = self.injected.call_raw(
self.context, DECODER, [{"value": spec}] + [{"objectId": o} for o in self._objects], by_value=False)
if decoded.get("objectId"):
self._decoded = decoded["objectId"]
return _argument_of(decoded)
def release(self) -> None:
decoded, copies = self._decoded, self._copies
self._decoded, self._copies = None, []
if decoded:
self.injected.release(self.context, decoded)
for copy in copies:
self.injected.release(self.context, copy)
@@ -85,12 +85,7 @@ def _as_script(expression: str) -> str:
def _deserialize(value: Any) -> Any:
"""The tagged union Playwright sends for an ARGUMENT, back to a plain value.
⛔ ONLY FOR THE CONSUMERS THAT CARRY THEIR VALUE AS JSON (an event's init, an expected value): the argument of the caller's code is
`_arguments.Argument`, which keeps what this cannot (a handle, a date, `undefined`, a reference). `undefined` is `None` here because a
JSON value has no `undefined`; `-0` is `-0.0`, which JSON does carry (it was `None` until the Python client's `0.0` came through here).
"""
"""The tagged union Playwright sends for an ARGUMENT, back to a value."""
if not isinstance(value, dict):
return value
if "value" in value and "handles" in value:
@@ -101,7 +96,7 @@ def _deserialize(value: Any) -> Any:
return convert(value[tag])
if "v" in value:
return {"null": None, "undefined": None, "NaN": float("nan"),
"Infinity": float("inf"), "-0": -0.0,
"Infinity": float("inf"),
"-Infinity": float("-inf")}.get(value["v"])
if "a" in value:
return [_deserialize(x) for x in value["a"]]
+3 -42
View File
@@ -62,6 +62,8 @@ OUTSIDE = {
"clockRunFor": "clock",
"clockSetFixedTime": "clock",
"clockSetSystemTime": "clock",
# the streamed upload path - set_input_files with local paths works
"createTempFiles": "the streamed upload path - set_input_files with local paths works",
# recorder
"cancelPickLocator": "recorder",
"createSelectorForTest": "recorder",
@@ -101,6 +103,7 @@ OUTSIDE = {
"tracingStarted": "tracing",
"tracingStop": "tracing",
"tracingStopChunk": "tracing",
"write": "tracing",
"zip": "tracing",
# video annotations. ⛔ `screencastStart` and `screencastStop` are NOT
# here any more: since the engine's screencast came back (firefox-28) the
@@ -215,45 +218,3 @@ def refusal(operation):
"invisible_playwright does not implement: the package covers the "
"automation core, and " + feature + " is outside it by decision, "
"not by omission. See 32-stacco-da-playwright.md section 5.4.")
#: ⛔ A PARAMETER OF A SERVED OPERATION THAT IS REFUSED, keyed by (operation, parameter), and the sentence a caller reads.
#: The operations above are refused whole; these are refused one parameter (or one value of it) at a time, and the call
#: without them is served. They are raised in `server.py` by `_refuse_parameter(operation, parameter)`, the one function
#: that reads this table, and `tests/test_every_refusal_is_declared.py` holds the two sides to each other.
#:
#: ⛔ WHY THESE FIVE. Stock Playwright honours `mask`, `style` and `animations="disabled"` by MODIFYING THE PAGE (an overlay,
#: an injected `<style>`, animations finished or cancelled) before the picture and putting it back after. This package does
#: not touch a page to photograph it, and until now it did not read them either: the call succeeded and the picture was as
#: if they had not been written, which a caller cannot see. `caret="initial"` asks for the text caret to be drawn, and the
#: engine never draws it (the capture does not set the flag that draws it), so the picture it takes is the one `"hide"`
#: asks for, which is also Playwright's default: `"hide"` and an absent `caret` are served. `omitBackground` with png is
#: Firefox's own `Not implemented` in stock (`FFPage.setBackgroundColor`), word for word; with jpeg stock does nothing and
#: neither do we.
REFUSED_PARAMETERS = {
("screenshot", "mask"):
"screenshot(mask=...) is not served: Playwright covers the masked elements by modifying the page (an overlay is "
"put on it before the picture), and this package does not touch a page to take a picture. maskColor goes with "
"mask and is refused with it. Hide the elements yourself before the screenshot (for example set their "
"visibility to hidden in your own script) and restore them after.",
("screenshot", "style"):
"screenshot(style=...) is not served: Playwright applies it by modifying the page (a <style> element is "
"injected before the picture and removed after), and this package does not touch a page to take a picture. Add "
"the style yourself with page.add_style_tag() before the screenshot and remove the element it returns after.",
("screenshot", "animations"):
'screenshot(animations="disabled") is not served: Playwright does it by modifying the page (the finite '
"animations are finished and the infinite ones cancelled), and this package does not touch a page to take a "
"picture. Wait for the animations to end, or pause them in your own script (document.getAnimations()), before "
'the screenshot. animations="allow" is what is served.',
("screenshot", "caret"):
'screenshot(caret="initial") is not served: it asks for the text caret to be drawn in the picture, and the '
'engine never draws it (the picture is the one caret="hide" asks for, which is the default of Playwright). Leave '
'caret out or pass "hide".',
("screenshot", "omitBackground"):
"Not implemented",
}
def parameter_refusal(operation, parameter):
"""The sentence for a refused (operation, parameter): `KeyError` for one that is not declared."""
return REFUSED_PARAMETERS[(operation, parameter)]
+11 -31
View File
@@ -22,12 +22,9 @@ used to answer, carried over unchanged):
* NOT `Mouse.move`: an explicit move is the caller's. (The in-process client
marks its own with `humanise`, see `_cursor._wrap_mouse_move`; a client that
does not say so is answered with exactly the point it named.)
* `ElementHandle.click / dblclick / hover / tap / check / uncheck` (and so
`set_checked`): the same walk, onto the node the handle already names
(`act(..., element=)`: the node is not looked up again and is not disposed).
One click path is one fingerprint, so a handle click and a selector click
arrive as the same kind of stroke;
* NOT `dragAndDrop`, whose travel the core's `Actions` already draws.
* NOT the actions of an ElementHandle (they name a node, never a selector, and
the in-process client never walked onto them either) and NOT `dragAndDrop`,
whose travel the core's `Actions` already draws.
HOW IT STAYS THE SAME AS THE CLIENT WAS. The stroke generator, the planners
(`_behaviour`) and the discipline events are delivered under (`Pacer`) are the
@@ -394,14 +391,9 @@ class Pointer:
# -- the probes --------------------------------------------------------
def _element_box(self, frame_id: str, selector: str,
element: Optional[str] = None) -> Tuple[Optional[str], Optional[dict]]:
def _element_box(self, frame_id: str, selector: str) -> Tuple[Optional[str], Optional[dict]]:
"""Resolve the element and its box, or (None, None). Never raises.
``element`` is a node the caller already holds (an ElementHandle's): it is
measured as it is, never looked up again from ``selector``, and it is not
ours to dispose.
Deliberately non-blocking and deliberately forgiving: this is a hint
used to aim a mouse path, never a correctness step. It resolves the
element if it is already there and gives up otherwise, so it can
@@ -409,12 +401,6 @@ class Pointer:
failing one - the action itself still does its own waiting and raises
its own errors.
"""
if element is not None:
try:
box = self.injected.bounding_box(frame_id, element)
except _PROBE_ERRORS:
return None, None # the handle's node is gone: the action meets that itself
return (element, box) if box else (None, None)
try:
handle = self.injected.query_selector(frame_id, selector)
except _PROBE_ERRORS:
@@ -456,11 +442,10 @@ class Pointer:
return False
def _choose_landing(self, frame_id: str, selector: str,
position: Optional[dict],
element: Optional[str] = None) -> Optional[_Aim]:
position: Optional[dict]) -> Optional[_Aim]:
"""Pick the point on the element this action will land on."""
hand = self.hand
handle, box = self._element_box(frame_id, selector, element)
handle, box = self._element_box(frame_id, selector)
if handle is None or box is None:
return None
try:
@@ -491,8 +476,7 @@ class Pointer:
return _Aim(box, (box["x"] + box["width"] / 2.0,
box["y"] + box["height"] / 2.0), None)
finally:
if element is None: # a node the caller holds stays the caller's
self._dispose(frame_id, handle)
self._dispose(frame_id, handle)
# -- travelling --------------------------------------------------------
@@ -598,8 +582,7 @@ class Pointer:
# -- the entry points --------------------------------------------------
def approach(self, frame_id: str, selector: str, position: Optional[dict],
trial: bool = False,
element: Optional[str] = None) -> Optional[Dict[str, float]]:
trial: bool = False) -> Optional[Dict[str, float]]:
"""Walk the pointer onto the element this action is about to touch.
Returns the `position` the action should run with, or None.
@@ -615,7 +598,7 @@ class Pointer:
hand.busy = True
hand.action += 1
try:
aim = self._choose_landing(frame_id, selector, position, element)
aim = self._choose_landing(frame_id, selector, position)
if aim is None:
return None
w, h = self._viewport()
@@ -631,12 +614,9 @@ class Pointer:
def act(self, frame_id: str, selector: str, position: Optional[dict],
timeout: Optional[float], run: Callable[[Optional[dict], Optional[float]], Any],
*, trial: bool = False, element: Optional[str] = None) -> Any:
*, trial: bool = False) -> Any:
"""Run a pointer action on an element the way a hand would.
``element`` is the object id of a node the caller already holds (an
ElementHandle): the walk aims at THAT node and `selector` is not looked up.
`run(position, timeout)` performs the plain action with those two
arguments. The approach comes first; if it chose a landing point the
action is told to click it, within a bounded slice of the caller's
@@ -646,7 +626,7 @@ class Pointer:
"""
override = None
try:
override = self.approach(frame_id, selector, position, trial, element)
override = self.approach(frame_id, selector, position, trial)
except _PROBE_ERRORS as exc: # motion never fails an action for what the engine or the page answers; a bug of ours is not that
_cursor._warn_once(
"approach-failed",
+2 -6
View File
@@ -43,12 +43,8 @@ locale, timezone), and `context_options_override=True` makes the server's win.
LIMITS OF THIS FIRST VERSION, said instead of hidden.
* `launchPersistentContext` and `profile_dir` are not served.
* `x-playwright-proxy` (exposeNetwork) is recorded, not honoured.
* Downloads and other fused types follow the in-process client's path and
are not carried to a remote client. A file chooser is: the `fileChooser`
event reaches the client, and `set_files` with a path streams the file
(`createTempFiles`, `WritableStream`) into the session's upload area, where
it lives as long as its context and goes with it, or with a client that
drops in the middle of the copy (`_client_gone` closes the contexts it owns).
* Downloads, file choosers and other fused types follow the in-process
client's path and are not carried to a remote client.
* `RemoteServer.process` is the core's handle for the browser process
(`Connection._process`, a private attribute of the core: pid / poll / wait).
* Page numbers (`pageNumber`, which the in-process client reserves) are drawn
File diff suppressed because it is too large. Load diff
+6 -7
View File
@@ -38,7 +38,7 @@ import argparse
import sys
from . import __version__
from invisible_core import BINARY_VERSION, FIREFOX_UPSTREAM_VERSION, update_security_state
from invisible_core import BINARY_VERSION, FIREFOX_UPSTREAM_VERSION, update_intermediates
from invisible_core.download import cache_root, engine_root, ensure_binary # noqa: F401
from ._pin import (
@@ -86,14 +86,13 @@ def _cmd_fetch(_args: argparse.Namespace) -> int:
except Exception as e:
print(f"error: {e}", file=sys.stderr)
return 1
# The security state the core copies into every profile (the intermediates, OneCRL and the CRLite filters a retail Firefox has from its first second): `fetch` is
# where the user asks for what is current, so it looks for newer data EVERY time (a small request to the changes feed; a collection is downloaded only when it
# changed), has THIS engine generate the state from it and puts the result in the cache. A launch only copies from the cache. A failure here is a warning and
# nothing more: it changes neither the exit code nor the last line (`update_security_state` itself does not raise).
# The list of preloaded intermediate certificates the core declares to the engine: `fetch` is where the user asks for what is current, so it looks for a
# newer list EVERY time (a small request to the changes feed; the list is downloaded only when it changed) and puts it in the cache. A launch only reads the
# cache. A failure here is a warning and nothing more: it changes neither the exit code nor the last line (`update_intermediates` itself does not raise).
try:
update_security_state(engine=path)
update_intermediates()
except Exception as e:
print(f"warning: the security state could not be fetched: {e}", file=sys.stderr)
print(f"warning: the intermediates list could not be fetched: {e}", file=sys.stderr)
# Last line, alone, so `$(invisible-playwright fetch)` is a path.
print(path)
return 0
-274
View File
@@ -1,274 +0,0 @@
"""What the canvas-reader e2e tests share: one scene, the readers of a canvas, the page that serves them, and the comparison of bytes.
The engine applies its canvas noise (``gfx::StealthProjectPixels``) to a WebGL or WebGPU canvas when a PAGE reads it, and only then. These
tests ask whether every road by which a page reads such a canvas gives the same bytes, so they need one scene that the noise touches, the same
scene drawn through every API, and the same list of readers for every kind of canvas.
THE SCENE. Ten triangles with random vertex colours (a fixed generator, the same numbers in every launch and in every API: ``starVertices``)
over a white clear. The noise touches only an edge pixel whose 3x3 neighbourhood holds a THIRD colour besides a blend of two, so a flat clear
is never touched; ten overlapping triangles make hundreds of such junctions, and the chance that two reads of a noised and an un-noised canvas
differ nowhere is nil. The 2D twin (``draw2D``) draws the same triangles with translucent fills and a shadow: a canvas that WOULD be noised if
the 2D road were projected, and is not (a 2D canvas reads as drawn).
THE CONTROL. ``noised=False`` declares ``zoom.stealth.canvas.substitute_pixels`` false: the canvas noise is declared off and NOTHING else changes
(same declared GPU, same antialiasing, same raster), so the difference between the two launches is the noise and nothing else, which is why
the tests may ask that it touches only the low bit of R, G and B. (A launch with ``hw_seed`` 0 would also change the declared GPU.)
THE READERS (``readersOf``): the canvas's own read (``readPixels`` / ``getImageData``), ``drawImage`` onto a 2D canvas, ``createImageBitmap``, the
PNG of ``toDataURL`` / ``toBlob`` / ``convertToBlob`` (decoded here, never by the browser, so the browser's image decoding is not a variable)
and, for an OffscreenCanvas, ``transferToImageBitmap``. Every entry is the base64 of RGBA bytes, top row first; a name that ends in ``.png`` is a
PNG file.
Nothing here waits on a clock: the page's async functions end on events, and the one wait that needs polling (``wait_until``) ends on a condition.
"""
from __future__ import annotations
import base64
import contextlib
import json
import threading
from http.server import BaseHTTPRequestHandler
from typing import Dict, List
import _page_bytes as pb
from _servers import LocalServer
#: The side of every canvas of the scene.
SIZE = 128
#: A noise seed that no runner has.
HW_SEED = 12345
#: The persona (identity) seed of every launch: not the noise seed.
SEED = 7
#: The JS of the scene and of the readers. Plain script: it runs in the page and, as the head of a worker's source, in a worker (no ``document`` in it).
SHARED_JS = r"""
const W = 128, H = 128;
// ten triangles, 30 vertices of (x, y, r, g, b), x and y in clip space: a fixed generator, so every launch and every API draws the same scene
function starVertices() {
const v = []; let s = 12345;
const rnd = () => (s = (s * 1103515245 + 12345) & 0x7fffffff) / 0x7fffffff;
for (let i = 0; i < 30; i++) v.push(rnd() * 1.8 - 0.9, rnd() * 1.8 - 0.9, rnd(), rnd(), rnd());
return v;
}
function drawGL(canvas, kind) {
const gl = canvas.getContext(kind || 'webgl', {preserveDrawingBuffer: true, antialias: true});
if (!gl) throw new Error('no ' + (kind || 'webgl') + ' context');
const shader = (type, src) => {
const s = gl.createShader(type); gl.shaderSource(s, src); gl.compileShader(s);
if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(s));
return s;
};
const pr = gl.createProgram();
gl.attachShader(pr, shader(gl.VERTEX_SHADER, 'attribute vec2 p; attribute vec3 c; varying vec3 v; void main(){v=c;gl_Position=vec4(p,0.,1.);}'));
gl.attachShader(pr, shader(gl.FRAGMENT_SHADER, 'precision mediump float; varying vec3 v; void main(){gl_FragColor=vec4(v,1.);}'));
gl.linkProgram(pr);
if (!gl.getProgramParameter(pr, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(pr));
gl.useProgram(pr);
const b = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, b);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(starVertices()), gl.STATIC_DRAW);
const pl = gl.getAttribLocation(pr, 'p'), cl = gl.getAttribLocation(pr, 'c');
gl.enableVertexAttribArray(pl); gl.vertexAttribPointer(pl, 2, gl.FLOAT, false, 20, 0);
gl.enableVertexAttribArray(cl); gl.vertexAttribPointer(cl, 3, gl.FLOAT, false, 20, 8);
gl.clearColor(1, 1, 1, 1); gl.clear(gl.COLOR_BUFFER_BIT);
gl.drawArrays(gl.TRIANGLES, 0, 30);
gl.finish();
return gl;
}
// the same ten triangles on a 2D canvas, with translucent fills and a shadow
function draw2D(x) {
x.fillStyle = '#fff'; x.fillRect(0, 0, W, H);
const v = starVertices();
for (let t = 0; t < 10; t++) {
const q = v.slice(t * 15, t * 15 + 15);
x.fillStyle = 'rgba(' + Math.round(q[2] * 255) + ',' + Math.round(q[3] * 255) + ',' + Math.round(q[4] * 255) + ',' + (t % 2 ? 0.7 : 1) + ')';
x.beginPath();
for (let k = 0; k < 3; k++) {
const px = (q[k * 5] + 1) / 2 * W, py = (1 - q[k * 5 + 1]) / 2 * H;
if (k) x.lineTo(px, py); else x.moveTo(px, py);
}
x.closePath(); x.fill();
}
x.shadowColor = 'rgba(0, 0, 0, 0.6)'; x.shadowBlur = 4; x.shadowOffsetX = 3; x.shadowOffsetY = 2;
x.fillStyle = 'rgb(200, 120, 20)'; x.fillRect(40, 40, 30, 30);
}
// readPixels, top row first (readPixels gives the bottom row first)
function readGL(gl) {
const buf = new Uint8Array(W * H * 4);
gl.readPixels(0, 0, W, H, gl.RGBA, gl.UNSIGNED_BYTE, buf);
const out = new Uint8Array(W * H * 4);
for (let y = 0; y < H; y++) out.set(buf.subarray((H - 1 - y) * W * 4, (H - y) * W * 4), y * W * 4);
return out;
}
function readCtx(x) { return new Uint8Array(x.getImageData(0, 0, W, H).data); }
function b64(u8) {
let s = '';
for (let i = 0; i < u8.length; i += 8192) s += String.fromCharCode.apply(null, u8.subarray(i, i + 8192));
return btoa(s);
}
function blobB64(blob) {
return new Promise((ok, bad) => {
const r = new FileReader();
r.onload = () => ok(String(r.result).split(',')[1]);
r.onerror = () => bad(new Error('FileReader failed'));
r.readAsDataURL(blob);
});
}
// what a fresh 2D canvas (made by `make`) holds after `draw(context)`
function pixelsOf(make, draw) {
const c = make(); c.width = W; c.height = H;
const x = c.getContext('2d'); draw(x);
return readCtx(x);
}
// every road by which a page turns `src` into bytes: {name: base64 of RGBA, top row first}; a name ending in .png is a PNG file
async function readersOf(src, direct, make, withTransfer) {
const out = {direct: b64(direct())};
out.drawImage = b64(pixelsOf(make, x => x.drawImage(src, 0, 0)));
const bm = await createImageBitmap(src);
out.createImageBitmap = b64(pixelsOf(make, x => x.drawImage(bm, 0, 0)));
bm.close();
if (src.toDataURL) {
out['toDataURL.png'] = src.toDataURL('image/png').split(',')[1];
out['toBlob.png'] = await blobB64(await new Promise(r => src.toBlob(r, 'image/png')));
} else {
out['convertToBlob.png'] = await blobB64(await src.convertToBlob({type: 'image/png'}));
}
if (withTransfer && src.transferToImageBitmap) { // last: it empties the canvas
const tb = src.transferToImageBitmap();
out.transferToImageBitmap = b64(pixelsOf(make, x => x.drawImage(tb, 0, 0)));
tb.close();
}
return out;
}
const makeElement = () => document.createElement('canvas');
const makeOffscreen = () => new OffscreenCanvas(W, H);
"""
def page_html(page_js: str) -> str:
"""A page whose script holds SHARED_JS, ``WORKER_LIB`` (the same text, for the source of a worker) and the page's own functions."""
return ("<!doctype html><meta charset=utf-8><title>canvas readers</title><body><script>\n" + SHARED_JS
+ "\nconst WORKER_LIB = " + json.dumps(SHARED_JS) + ";\n" + page_js + "\n</script></body>")
@contextlib.contextmanager
def serve(html: str):
"""The page on a local http origin (a secure context, and a site a canvas has a principal on); port 0, the one the system gave."""
body = html.encode("utf-8")
class Page(BaseHTTPRequestHandler):
timeout = 5
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(body)))
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
httpd = LocalServer(("127.0.0.1", 0), Page)
threading.Thread(target=httpd.serve_forever, daemon=True).start()
try:
yield "http://127.0.0.1:%d/" % httpd.server_address[1]
finally:
httpd.shutdown()
httpd.server_close()
@contextlib.contextmanager
def launched(firefox_binary, html: str, noised: bool = True, pin=None, viewport=None):
"""The page open in a browser of the product: the engine on (a declared noise seed no runner has), and, when ``noised`` is false, the
canvas noise declared off and nothing else. One browser, closed on leaving."""
from invisible_playwright import InvisiblePlaywright
prefs = {"zoom.stealth.fpp.hw_seed": HW_SEED}
if not noised:
prefs["zoom.stealth.canvas.substitute_pixels"] = False
with serve(html) as url:
with InvisiblePlaywright(seed=SEED, binary_path=firefox_binary, headless=True, extra_prefs=prefs, pin=pin) as browser:
context = browser.new_context(viewport=viewport) if viewport else browser.new_context()
page = context.new_page()
page.goto(url, wait_until="load", timeout=60_000)
yield page
def run(page, call: str, deadline_s: int = 120):
"""Runs the page's async function ``call`` (a JS expression that gives a promise) to its end and returns what it resolved to. The end is
the promise's own: the deadline is only how long a lost event is allowed before the test says so."""
page.evaluate("() => { window.DONE = false; window.ERR = null; window.R = null;"
" Promise.resolve().then(() => %s).then(r => { window.R = r; window.DONE = true; },"
" e => { window.ERR = String((e && e.stack) || e); window.DONE = true; }); }" % call)
page.wait_for_function("window.DONE === true", timeout=deadline_s * 1000)
err = page.evaluate("window.ERR")
assert err is None, "the page could not run %s: %s" % (call, err)
return page.evaluate("window.R")
# ------------------------------------------------------------------------------------------------------------------ bytes
def rgba_of_image(image) -> bytes:
"""RGBA bytes of an ``_page_bytes.unfiltered`` image (RGB gets an opaque alpha)."""
data, channels = image["data"], image["channels"]
if channels == 4:
return data
assert channels == 3, "a PNG of %d channels is not read here" % channels
out = bytearray()
for i in range(0, len(data), 3):
out += data[i:i + 3] + b"\xff"
return bytes(out)
def rgba(name: str, value: str) -> bytes:
"""The RGBA bytes of a reader's entry: its base64, or, for a PNG, the pixels it decodes to."""
raw = base64.b64decode(value)
if name.endswith(".png"):
image = pb.unfiltered(raw)
assert (image["w"], image["h"]) == (SIZE, SIZE), "%s is a %dx%d image, not %dx%d" % (name, image["w"], image["h"], SIZE, SIZE)
return rgba_of_image(image)
assert len(raw) == SIZE * SIZE * 4, "%s holds %d bytes, not %d" % (name, len(raw), SIZE * SIZE * 4)
return raw
def decode(readers: Dict[str, str], prefix: str = "") -> Dict[str, bytes]:
return {prefix + name: rgba(name, value) for name, value in readers.items()}
def differing_pixels(a: bytes, b: bytes) -> int:
assert len(a) == len(b), "two images of %d and %d bytes" % (len(a), len(b))
return sum(1 for i in range(0, len(a), 4) if a[i:i + 4] != b[i:i + 4])
def only_the_low_bit_of_rgb(a: bytes, b: bytes) -> List[int]:
"""The pixels where ``a`` and ``b`` differ by more than the low bit of R, G and B (or in alpha): the noise writes nothing else."""
return [i // 4 for i in range(0, len(a), 4)
if (a[i] | 1, a[i + 1] | 1, a[i + 2] | 1, a[i + 3]) != (b[i] | 1, b[i + 1] | 1, b[i + 2] | 1, b[i + 3])]
def distinct_colours(a: bytes) -> int:
return len({a[i:i + 4] for i in range(0, len(a), 4)})
def disagreements(readers: Dict[str, bytes], reference: str) -> List[str]:
"""The readers whose bytes are not those of ``reference``, each with how many pixels differ."""
want = readers[reference]
return ["%s (%d pixels differ)" % (name, differing_pixels(want, got)) for name, got in readers.items() if got != want]
def assert_agree(what: str, readers: Dict[str, bytes], reference: str = "direct") -> None:
bad = disagreements(readers, reference)
assert not bad, (
"%s: the readers %s do not read what %s reads (readers: %s). Every road by which a page reads a canvas gives the same bytes "
"when it is the same canvas" % (what, "; ".join(bad), reference, ", ".join(sorted(readers))))
+115
View File
@@ -0,0 +1,115 @@
"""What the canvas text e2e tests share: the persona pin, the bundled fonts and the server.
tests/test_canvas_text_is_windows_e2e.py (black text, 342 cases) and
tests/test_canvas_text_colors_and_cleartype_is_windows_e2e.py (coloured text and the
ClearType keys) both compare the RGBA bytes of a canvas drawn by the engine with the ones
retail Firefox 159.0 on Windows drew, for pages served on localhost with the engine's own
bundled font files. This module holds what the two do the same way.
"""
from __future__ import annotations
import hashlib
import http.server
import json
import threading
from pathlib import Path
DATA = Path(__file__).parent / "data" / "canvas_text_ref"
#: What the reference's ``cleartype`` field says the retail machine had: FontSmoothing 2 with
#: FontSmoothingType 2 is ClearType (system text quality 5). The other tuning values are an
#: untuned Windows machine's (gamma 1.8, contrast 1.0, level 1.0), which refs.json does not
#: record.
UNTUNED = {"font.cleartype_gamma": 1800, "font.cleartype_contrast": 100,
"font.cleartype_level": 100}
def pin(refs):
"""The prefs that make the engine the machine ``refs["cleartype"]`` describes."""
ct = refs["cleartype"]
smoothing, kind = str(ct["FontSmoothing"]), str(ct["FontSmoothingType"])
if smoothing == "2" and kind in ("2", "0x2"):
quality = 5
elif smoothing == "2":
quality = 4
else:
quality = 0
return {"screen.dpr": 1.0, "font.system_text_quality": quality, **UNTUNED}
def bundle_font(fonts_dir, entry):
"""The bundled file a reference entry names."""
return Path(fonts_dir) / entry["bundle_file"]
def wrong_fonts(fonts_dir, entries):
"""One line for each reference font whose bundled file is not the one measured."""
wrong = []
for e in entries:
f = bundle_font(fonts_dir, e)
got = hashlib.sha256(f.read_bytes()).hexdigest() if f.is_file() else None
if got != e["sha256"]:
wrong.append("%s: the engine's %s has sha256 %s, the reference was made with %s"
% (e["family"], f.name, got, e["sha256"]))
return wrong
def serve(fonts_dir, entries, pages):
"""``pages`` (url path -> HTML bytes) and, under /bundle/<name>, the engine's bundled
font files. Returns the running server; the caller shuts it down."""
by_url = {"/bundle/" + e["bundle_file"]: bundle_font(fonts_dir, e) for e in entries}
class _H(http.server.BaseHTTPRequestHandler):
def do_GET(self):
path = self.path.split("?")[0]
if path in pages:
body, kind = pages[path], "text/html"
elif path in by_url and by_url[path].is_file():
body, kind = by_url[path].read_bytes(), "font/ttf"
else:
self.send_error(404)
return
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
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), _H)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server
_SPECS_LOOP = " window.R = {};\n for (const sp of SPECS) {"
def only_cases(html, ids):
"""canvas_text_ref/index.html as text, drawing only the cases ``ids``.
The page draws all 342 cases (the 400 px ones take minutes); a test that wants a few of
them serves this. The drawing code is untouched, so a case gives the bytes it gives in
the whole page."""
if _SPECS_LOOP not in html:
raise AssertionError("canvas_text_ref/index.html no longer has the loop over SPECS "
"that only_cases() narrows: update the helper")
return html.replace(
_SPECS_LOOP,
" window.R = {};\n const ONLY = new Set(%s);\n"
" for (const sp of SPECS.filter(s => ONLY.has(s.id))) {" % json.dumps(sorted(ids)))
def diff_lines(want, got, label=""):
"""One line for each case of ``want`` (id -> sha256) that ``got`` does not draw as
expected: its name, the hash retail gave, the hash the engine gave (or "not drawn")."""
lines = []
for cid in sorted(want):
have = got.get(cid)
if have != want[cid]:
lines.append("%s%s: expected %s, got %s"
% (label, cid, want[cid], have if have is not None else "not drawn"))
lines += ["%s%s: drawn but not in the reference" % (label, cid)
for cid in sorted(set(got) - set(want))]
return lines
+12 -26
View File
@@ -2,8 +2,8 @@
unit test feeds them the red case and the green case without a browser).
None of them reads how long something took: a loop that is held is told by WHERE the thread of the loop was (inside a blocking step of
the close), a browser that keeps answering is told by the ORDER of the events (a reply that arrived while the close was in flight,
and answers that came while the removal of the profile was held), and the removal of the profile is told by WHICH THREAD
the close), a browser that keeps answering is told by the ORDER of the events (a call that began and ended while the close was in
flight, and answers that came while the removal of the profile was held), and the removal of the profile is told by WHICH THREAD
reached it (the reaper's or its continuation's, never the loop's nor one of the close's) and by the order of the close's return and
the release of the hold. A machine that is slow stretches every duration and changes none of these.
@@ -85,35 +85,21 @@ def charged_more_than_ran_problem(held: float, busy_run: float) -> Optional[str]
"its selector (the machine did not schedule it) was counted as held" % (held * 1000, busy_run * 1000))
def others_answered_problem(others: Sequence[dict], gate: dict, loop_inside: Dict[str, dict]) -> Optional[str]:
def others_answered_problem(others: Sequence[dict], gate: dict) -> Optional[str]:
"""What is wrong with the way the other browsers answered while the first one closed, or None.
``others`` has one record per other browser: ``answered`` is the replies that ARRIVED while the close was in flight, whenever the
call began (a reply read during the close is proof that the loop ran then; a call that began a moment before the close and ended
in it is one), ``inside`` the calls that began AND ended in it (printed, not judged), ``during_removal`` the calls that began after
the removal of the closing browser's profile was reached and ended while it was still held. ``gate`` says how that hold ended:
``reached`` (the removal ran), ``released_by``: ``answered`` (the close had returned and every other browser had answered a call
that began after the removal was reached: the loop was free while the removal waited) or ``deadline`` (they had not, in 30 s: the
loop could not run while the removal was waiting, which is a removal made on the loop's thread). ``loop_inside`` is what the
watcher saw of the loop's thread during the close (see the head of this file).
A browser that answered nothing inside the close is the loop's fault only if the loop was HELD: the watcher saw its thread inside
a step of the close that waits, or no browser answered at all (nothing shows that the loop ran). One engine that did not answer
while the others did, and the loop was seen free, is a browser the machine did not run: the removal's hold below still asks every
browser to answer, once the close is over."""
``others`` has one record per other browser: ``inside`` is the calls that began AFTER the close began and ended BEFORE it ended
(a call that was answered during the close, in the order of the events, not by how long it took), ``during_removal`` the calls
that began after the removal of the closing browser's profile was reached and ended while it was still held. ``gate`` says how that
hold ended: ``reached`` (the removal ran), ``released_by``: ``answered`` (the close had returned and every other browser had
answered a call that began after the removal was reached: the loop was free while the removal waited) or ``deadline`` (they had not,
in 30 s: the loop could not run while the removal was waiting, which is a removal made on the loop's thread)."""
if len(others) != 3:
return "the client followed %d other browsers instead of 3: %r" % (len(others), others)
silent = [i for i, r in enumerate(others) if r["answered"] < 1]
silent = [i for i, r in enumerate(others) if r["inside"] < 1]
if silent:
held = blocked_by(loop_inside)
counts = [r["answered"] for r in others]
if held:
return ("the other browsers %s did not answer a single call inside the close (replies that arrived inside it, per "
"browser: %s) and the watcher saw the loop's thread inside %s: the loop that serves them did not run during "
"the close" % (silent, counts, held))
if len(silent) == len(others):
return ("no other browser answered a single call inside the close (replies that arrived inside it, per browser: %s): "
"nothing shows that the loop ran during the close" % counts)
return ("the other browsers %s did not answer a single call that began and ended inside the close (calls inside it, per "
"browser: %s): the loop that serves them did not run during the close" % (silent, [r["inside"] for r in others]))
if gate.get("reached") and gate.get("released_by") != "answered":
return ("the removal of the profile was held until every other browser answered, and they did not (%s): the loop that "
"serves them could not run while the removal waited, so the removal ran on it (answers during the removal, per "
-174
View File
@@ -1,174 +0,0 @@
"""TEMPORARY: the core of every crash of an engine the tests start, read by gdb after a test that fails. Remove it with tests/_generation_evidence.py once the
exit by SIGSEGV (-11) of the engine in generate mode on Linux (runs 44985244053 and 45014369018) is understood and fixed.
A release build crashes in silence: MOZ_CRASH, MOZ_RELEASE_ASSERT and a Rust panic write to a null address and print nothing, so stderr cannot tell a crash the
code wanted from a bad access. The core can: `gMozCrashReason` says the reason of a wanted crash, the faulting address and the thread that fell say the rest.
* `lift_the_core_limit_of_the_session()`: once, at the start of pytest (tests/conftest.py, `pytest_configure`), on Linux: the soft RLIMIT_CORE of the pytest
process raised to its hard limit. Every process a test starts inherits it, the engines the CORE launches included (its `generate` passes no limit of its own),
so a crash of any of them leaves a core where `kernel.core_pattern` says. The Linux e2e jobs (e2e.yml, and gate.yml of the engine series) point it at
`$INVPW_CORE_DIR` and install gdb.
* `after_the_report(nodeid, when, failed)`: tests/conftest.py calls it after each phase of every test (`pytest_runtest_makereport`). When `$INVPW_CORE_DIR` is set:
after a phase that FAILED, every `core*` there is read by gdb into `<evidence>/cores/<nodeid>/<core>.gdb.txt` and deleted, and `notes.txt` says what was found
(no core included); after the teardown of a test that did not fail, the cores left are deleted and listed in `<evidence>/cores/after-passing-tests.txt` (a crash
in a passing test is information too). `<evidence>` is `$RUNNER_TEMP/invpw-evidence`, the folder the e2e jobs upload.
* `gdb_text(core, into)`: the one gdb path of the tests: the executable is the one the core's header names (else `$INVPW_BINARY_PATH`), and the text holds the
backtrace of every thread, their names, the signal's address, `gMozCrashReason`, the registers, the shared libraries with their addresses and build ids, and the
mappings. Only the text is kept: a core of the engine is hundreds of MB.
Best effort: nothing here raises, and nothing here decides a test.
"""
from __future__ import annotations
import contextlib
import os
import re
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
#: The folder under `$RUNNER_TEMP` the e2e workflows upload (`invpw-evidence-*`, "Keep what the tests saved").
EVIDENCE_FOLDER = "invpw-evidence"
CORES = "cores"
AFTER_PASSING = "after-passing-tests.txt"
#: How long gdb may take to read a core of the engine, and to read its header only.
GDB_TIMEOUT_S = 600
HEADER_TIMEOUT_S = 120
#: What gdb prints from the core: the crashing thread first, then every thread with its name, the signal, the reason of a wanted crash, where libxul is.
GDB_COMMANDS = (
"set pagination off",
"set width 0",
"bt",
"info threads",
"thread apply all bt",
"p $_siginfo",
"p $_siginfo._sifields._sigfault.si_addr",
"x/s *(char**)&gMozCrashReason",
"info registers",
"x/8i $pc",
"info sharedlibrary",
"python print('\\n'.join('%s %s' % (o.filename, o.build_id) for o in gdb.objfiles()))",
"info proc mappings",
)
_HEADER = re.compile(r"Core was generated by `([^']*)'")
#: The tests a phase of which failed: their teardown reads its cores too.
_FAILED = set()
def lift_the_core_limit_of_the_session():
"""Linux: the soft RLIMIT_CORE of this process raised to its hard limit, inherited by every child. Elsewhere, or if it is refused, nothing."""
if not sys.platform.startswith("linux"):
return
try:
import resource
_soft, hard = resource.getrlimit(resource.RLIMIT_CORE)
resource.setrlimit(resource.RLIMIT_CORE, (hard, hard))
except (ImportError, OSError, ValueError):
pass
def core_pattern():
try:
return Path("/proc/sys/kernel/core_pattern").read_text(encoding="utf-8").strip()
except OSError as exc:
return "unreadable: %r" % (exc,)
def gdb():
"""The gdb command (a list), or None when gdb is not installed."""
found = shutil.which("gdb")
return [found] if found else None
def evidence_root():
base = os.environ.get("RUNNER_TEMP") or tempfile.gettempdir()
return Path(base) / EVIDENCE_FOLDER / CORES
def folder_name(nodeid):
return re.sub(r"[^A-Za-z0-9._-]+", "_", nodeid).strip("_")[:150] or "unnamed"
def _cores():
where = os.environ.get("INVPW_CORE_DIR")
if not where or not Path(where).is_dir():
return None, []
return Path(where), sorted((path for path in Path(where).glob("core*") if path.is_file()), key=lambda path: path.stat().st_mtime)
def executable_of(core, command):
"""The executable the core's header names when it is a file, else `$INVPW_BINARY_PATH` (or `$STEALTHFOX_E2E_BINARY`), else None. Returns (path, how)."""
header = ""
try:
done = subprocess.run(command + ["-batch", "-nx", "-c", str(core)], stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
timeout=HEADER_TIMEOUT_S)
header = done.stdout.decode("utf-8", "replace")
except Exception as exc: # best effort
header = "header unreadable: %r" % (exc,)
match = _HEADER.search(header)
named = match.group(1).split()[0] if match and match.group(1).split() else None
if named and Path(named).is_file():
return named, "from the core's header"
for variable in ("INVPW_BINARY_PATH", "STEALTHFOX_E2E_BINARY"):
if os.environ.get(variable) and Path(os.environ[variable]).is_file():
return os.environ[variable], "from $%s (the header names %r)" % (variable, named)
return None, "none (the header names %r)" % (named,)
def gdb_text(core, into):
"""gdb's text of `core` in `into/<core>.gdb.txt`. One line saying what was done. Does not delete the core."""
command = gdb()
size = core.stat().st_size
if command is None:
return "core %s (%d bytes, kernel.core_pattern %r) but gdb is not installed" % (core.name, size, core_pattern())
exe, how = executable_of(core, command)
argv = command + ["-batch", "-nx"]
for line in GDB_COMMANDS:
argv += ["-ex", line]
argv += ([exe] if exe else []) + ["-c", str(core)]
target = into / (core.name + ".gdb.txt")
try:
done = subprocess.run(argv, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=GDB_TIMEOUT_S)
target.write_bytes(("executable: %s (%s)\n\n" % (exe, how)).encode("utf-8") + done.stdout)
return "core %s (%d bytes): gdb exited %d, %d bytes of text in %s; executable %s" % (core.name, size, done.returncode, len(done.stdout), target.name, how)
except Exception as exc:
return "core %s (%d bytes): gdb failed: %r" % (core.name, size, exc)
def after_the_report(nodeid, when, failed):
"""After a phase (`setup`, `call`, `teardown`) of the test `nodeid`: see the module's docstring. Never raises."""
try:
failed_before = nodeid in _FAILED
if failed:
_FAILED.add(nodeid)
if when == "teardown":
_FAILED.discard(nodeid)
where, cores = _cores()
if where is None:
return
if failed or (failed_before and cores):
into = evidence_root() / folder_name(nodeid)
into.mkdir(parents=True, exist_ok=True)
notes = ["%s failed (phase %s); INVPW_CORE_DIR %s, kernel.core_pattern %r, gdb %s" % (nodeid, when, where, core_pattern(), gdb())]
if not cores:
notes.append("no core file in %s" % where)
for core in cores:
notes.append(gdb_text(core, into))
with open(str(into / "notes.txt"), "a", encoding="utf-8") as sink:
sink.write("\n".join(notes) + "\n")
elif when == "teardown" and cores:
root = evidence_root()
root.mkdir(parents=True, exist_ok=True)
with open(str(root / AFTER_PASSING), "a", encoding="utf-8") as sink:
for core in cores:
sink.write("%s\t%s\t%d bytes (deleted, not read)\n" % (nodeid, core.name, core.stat().st_size))
else:
return
for core in cores:
with contextlib.suppress(OSError):
core.unlink()
except Exception: # the evidence is best effort: the test's own outcome is what counts
pass
+2 -5
View File
@@ -42,7 +42,7 @@ from pathlib import Path
from typing import Callable, Dict, List, NamedTuple, Optional, Set, Tuple
from urllib.parse import parse_qs, urlsplit
from _socks_servers import EXIT, Gateway, WEB_NAME, WHOAMI4, WHOAMI6, _REQUEST
from _socks_servers import EXIT, Gateway, WEB_NAME, WHOAMI4, WHOAMI6
try: # the HTTP/2 side needs it; a test that wants h2 says pytest.importorskip("h2")
import h2.config
@@ -602,8 +602,7 @@ class DohGateway(Gateway):
* CONNECT to a loopback address is relayed for real (the pages and the echo servers of a test);
* the egress endpoints of the base class (``api.ipify.org:80``) keep working;
* any other CONNECT is refused (reply 2 "not allowed", for an address; 4 "host unreachable", for a name) and
listed in :attr:`refused` (and in ``guard``, the record every gateway of ``_socks_servers`` writes under ``$RUNNER_TEMP/invpw-evidence/``):
the gateway never resolves a name and never reaches past the loopback. Its UDP relay is the base one: only the lab's, the rest dropped and recorded.
listed in :attr:`refused`: the gateway never resolves a name and never reaches past the loopback.
:attr:`connects` (inherited) lists EVERY CONNECT target in order, so ``("page-a.test", 80)`` in it means the
browser sent a name where it should have sent an address. :attr:`credentials_seen` lists every
@@ -697,8 +696,6 @@ class DohGateway(Gateway):
if not is_loopback(host):
self.connects.append((host, port))
self.refused.append((host, port))
self.guard.refuse(host, port, getattr(_REQUEST, "atyp", 3), "tcp",
reason="past loopback: the DoH gateway carries only loopback (besides the DoH, the exit questions and the web name it answers)")
self._send(c, self._reply(2 if _is_address(host) else 4))
return
self.connects.append((host, port))
+1 -101
View File
@@ -23,11 +23,6 @@ THE RULES (a stable name each; ``CLASS`` is the letter of the audit of the e2e t
time a healthy run is allowed, and a loaded runner takes longer than a developer's machine: 30 s is the one the whole suite uses (the unit is read from the callee:
milliseconds for the Playwright API, seconds for the standard library and for the helpers of ``tests/``). A wait for something that must NOT happen is accepted by its shape
(inside ``pytest.raises``, under a ``try`` that swallows the timeout, or a limit that is NAMED ``NEGATIVE_...``); any other is a reviewed ``entries`` item with its reason.
* ``lab-delay`` (A): an e2e test that gives a lab gateway or lab server a delay (``Gateway(..., rtt_ms=N)``, ``Chain(rtt_ms=N)``, ``first_connection_delay=N``, ``doh.delay_names[...] = N``,
``sites.route(..., delay=N)``, ``_serve(..., delay=N)``, a test parameter named ``rtt_ms``, or a fixture of the file that does) and is not marked ``wall_clock``. The delay is a sleep or a
timer of the lab's own threads, and what the test waits for is decided by the product with a time budget (the core's UDP measurement, a DoH timeout): on a runner with no CPU left the
threads are scheduled late and the answer comes after the budget (run 45058944650). The test belongs to the ``wall_clock`` lane (serial, the whole machine). A delay of a literal 0 is none;
a value the test computes counts until it is shown to be 0. One occurrence per test.
* ``egress`` (D): the conftest has no autouse session fixture that declares the exit of the lab (tests/_lab_egress.py), so a launch asks three services of the internet.
WHAT IS ACCEPTED WITHOUT A LIST, because it is recognised by its shape: a pause that is the step of a poll with a deadline (a ``while``/``for`` that compares with a clock
@@ -50,7 +45,7 @@ from typing import Dict, Iterable, List, Optional, Set, Tuple
TESTS = Path(__file__).resolve().parent
#: The rule -> the class of the audit.
CLASS = {"sleep": "A", "js-timer": "A", "lab-delay": "A", "bound": "B", "port": "C", "env": "C", "net": "D", "egress": "D", "count": "E", "timeout": "F"}
CLASS = {"sleep": "A", "js-timer": "A", "bound": "B", "port": "C", "env": "C", "net": "D", "egress": "D", "count": "E", "timeout": "F"}
RULES = tuple(CLASS)
#: The files that say what is forbidden (their own patterns would be found) and the files of the round after a publication (``net`` is theirs by design).
@@ -613,98 +608,6 @@ def _is_e2e_file(tree: ast.Module) -> bool:
for sub in ast.walk(tree))
#: The delay knobs of the lab servers: the keyword of a call -> the callees it is a delay of (None: any). ``delay`` alone is too common a word (``keyboard.type(delay=120)``): it is a delay
#: of the lab only on the two helpers that serve a late page.
LAB_DELAY_KEYWORDS: Dict[str, Optional[Set[str]]] = {"rtt_ms": None, "first_connection_delay": None, "delay": {"route", "_serve"}}
#: A test parameter that is one of those knobs: the distance a ``parametrize`` gives the gateway.
LAB_DELAY_PARAMETERS = {"rtt_ms", "first_connection_delay"}
#: The tables of the lab servers that a test fills with a delay by name (``doh.delay_names["slow.test"] = 2.0``).
LAB_DELAY_TABLES = {"delay_names"}
def _is_zero(node: ast.AST) -> bool:
return isinstance(node, ast.Constant) and (node.value is None or node.value is False or (isinstance(node.value, (int, float)) and node.value == 0))
def _first_lab_delay(function: ast.AST) -> Optional[ast.AST]:
"""The first node in the body of ``function`` that gives a lab server a delay (see :data:`LAB_DELAY_KEYWORDS`), or None."""
for node in ast.walk(function):
if isinstance(node, ast.Call):
callee = _dotted(node.func).rsplit(".", 1)[-1]
for keyword in node.keywords:
where = LAB_DELAY_KEYWORDS.get(keyword.arg or "", False)
if where is not False and (where is None or callee in where) and not _is_zero(keyword.value):
return node
elif isinstance(node, (ast.Assign, ast.AugAssign)):
for target in node.targets if isinstance(node, ast.Assign) else [node.target]:
if isinstance(target, ast.Subscript) and _dotted(target.value).rsplit(".", 1)[-1] in LAB_DELAY_TABLES and not _is_zero(node.value):
return node
return None
def _lab_delays(tree: ast.Module) -> List[Tuple[str, int, str]]:
"""``(scope, line, text)`` of each e2e test that gives a lab server a delay and does not carry ``wall_clock``: in its own body, through a parameter named like a knob, or through a
fixture of the same file (``usefixtures`` and the fixtures that fixture takes included)."""
module_marks: Set[str] = set()
for node in tree.body:
if isinstance(node, ast.Assign) and any(isinstance(t, ast.Name) and t.id == "pytestmark" for t in node.targets):
module_marks |= _marks(node.value)
functions: List[Tuple[str, ast.AST, Set[str]]] = [] # qualified name, node, the marks of its classes and module
def collect(body: List[ast.stmt], prefix: str, inherited: Set[str]) -> None:
for node in body:
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
functions.append((prefix + node.name, node, inherited))
elif isinstance(node, ast.ClassDef):
marks = set(inherited)
for decorator in node.decorator_list:
marks |= _marks(decorator)
for stmt in node.body:
if isinstance(stmt, ast.Assign) and any(isinstance(t, ast.Name) and t.id == "pytestmark" for t in stmt.targets):
marks |= _marks(stmt.value)
collect(node.body, prefix + node.name + ".", marks)
collect(tree.body, "", module_marks)
def is_a_fixture(node: ast.AST) -> bool:
return any(_dotted(d.func if isinstance(d, ast.Call) else d).rsplit(".", 1)[-1] == "fixture" for d in node.decorator_list) # type: ignore[attr-defined]
def parameters(node: ast.AST) -> List[str]:
arguments = node.args # type: ignore[attr-defined]
return [a.arg for a in list(arguments.posonlyargs) + list(arguments.args) + list(arguments.kwonlyargs)]
delaying = {name.rsplit(".", 1)[-1] for name, node, _ in functions if is_a_fixture(node) and _first_lab_delay(node) is not None}
grew = True
while grew: # a fixture that takes a delaying fixture delays too
grew = False
for name, node, _ in functions:
short = name.rsplit(".", 1)[-1]
if is_a_fixture(node) and short not in delaying and delaying & set(parameters(node)):
delaying.add(short)
grew = True
out: List[Tuple[str, int, str]] = []
for name, node, inherited in functions:
if not name.rsplit(".", 1)[-1].startswith("test_") or is_a_fixture(node):
continue
marks = set(inherited)
for decorator in node.decorator_list: # type: ignore[attr-defined]
marks |= _marks(decorator)
if "e2e" not in marks or "wall_clock" in marks:
continue
used = set(parameters(node))
for decorator in node.decorator_list: # type: ignore[attr-defined]
if isinstance(decorator, ast.Call) and _dotted(decorator.func).rsplit(".", 1)[-1] == "usefixtures":
used |= {a.value for a in decorator.args if isinstance(a, ast.Constant) and isinstance(a.value, str)}
own = _first_lab_delay(node)
if own is not None:
out.append((name, getattr(own, "lineno", node.lineno), ast.unparse(own).splitlines()[0][:80]))
elif used & LAB_DELAY_PARAMETERS:
out.append((name, node.lineno, "parameter " + sorted(used & LAB_DELAY_PARAMETERS)[0]))
elif used & delaying:
out.append((name, node.lineno, "fixture " + sorted(used & delaying)[0]))
return out
def analyze(source: str, file: str, *, force: bool = False) -> List[Violation]:
"""The occurrences of ``source`` (the content of ``tests/<file>``). A test file with no ``e2e`` marker is not read, unless ``force`` (the helpers always are)."""
tree = ast.parse(source)
@@ -712,8 +615,6 @@ def analyze(source: str, file: str, *, force: bool = False) -> List[Violation]:
if not e2e or file in SELF:
return []
reader = _Reader(file, tree, e2e)
if file.startswith("test_"):
reader.found.extend((scope, "lab-delay", line, text) for scope, line, text in _lab_delays(tree))
reader.found.sort(key=lambda item: item[2])
counts: Dict[Tuple[str, str], int] = {}
out: List[Violation] = []
@@ -783,7 +684,6 @@ DEBT_REASON = {
"net": "A real host in a gate is a third party: serve the page and the answer from the test's own server.",
"count": "The number of processes is not something the product promises: count by site name or against the pool the product keeps (tests/_processes.py, tests/_waits.py).",
"timeout": "A deadline under 30 s on a wait for something that must happen is a verdict on the machine: a loaded runner is slower than the one it was written on. Give it 30 s (or the deadline the product itself has), and read the result after it.",
"lab-delay": "A delay given to a lab gateway or server, and a wait for what the product decides with a time budget, read the wall clock: mark the test wall_clock (the serial lane, the whole machine), or take the delay out of the verdict.",
"egress": "The launch asks three services of the internet where it leaves from: declare the exit (tests/_lab_egress.py).",
}
-197
View File
@@ -1,197 +0,0 @@
"""What an e2e test that fails leaves for a reader, and nothing when it passes.
``with FailureEvidence("name") as evidence:`` around the body of a test: while the body runs, the helper collects, in a temporary folder,
the sources the test points it at (the fake web's own record, the Juggler wire of the served browser, the engine's own Juggler trace,
the client's view of every request); when the body raises (an assertion included), it copies what it holds to
``$RUNNER_TEMP/invpw-evidence/<name>/<pid>-<ms>/``, the folder the e2e jobs upload (``invpw-evidence-*``), with a ``meta.json``; when the
body passes, it deletes it all. Off a runner (no ``RUNNER_TEMP``) nothing is copied. It changes no assertion, wait or deadline of the
test: it only listens.
A test that passed slowly may keep the evidence too: ``evidence.keep(why)`` saves what the helper holds at that moment (the same folder, a
``meta.json`` whose ``kept`` says why, judged after the fact and never a verdict). ``arm(moz_log=...)`` also starts the engine's own log
(``MOZ_LOG``, one file per process in the evidence: ``MOZ_LOG_FILE`` carries ``%PID``), and ``note_records(name, state)`` adds a record the test keeps itself (``state.lock``,
``state.records``) as ``<name>.jsonl``.
The times written: ``t``, wall-clock seconds since the epoch (``time.time()``; the engine's own trace writes milliseconds in ``t``, its
``performance.timeOrigin + now``, also since the epoch), and ``m``, ``time.perf_counter()`` of the test process, finer on Windows (whose wall
clock ticks every 15 ms) and shared by the fake web's record, the client's log and the Juggler wire.
"""
from __future__ import annotations
import json
import os
import pathlib
import platform
import shutil
import sys
import tempfile
import threading
import time
import pytest
#: The folder under ``$RUNNER_TEMP`` the e2e workflows upload (``invpw-evidence-*``).
EVIDENCE_FOLDER = "invpw-evidence"
#: The most characters of one Juggler message kept in the wire log: a message longer than this is cut and says so.
WIRE_LIMIT = 4000
#: The engine's trace: the variable `Trace.js` of the engine reads in the parent process (off without it).
TRACE_ENV = "INVISIBLE_JUGGLER_TRACE_DIR"
#: The base name of the engine's log files in the evidence, and the name given to ``MOZ_LOG_FILE``: Firefox expands ``%PID`` into ``-main.<pid>`` or
#: ``-child.<pid>`` (and adds ``.moz_log``, ``ExpandLogFileName`` in ``xpcom/base/Logging.cpp``), so that every process of every session of a test writes a
#: file of its own. Without it two sessions of one test wrote the same file and the parent's one was 0 bytes.
MOZ_LOG_BASE = "engine"
MOZ_LOG_FILE_NAME = MOZ_LOG_BASE + "%PID"
class FailureEvidence:
def __init__(self, name: str):
self.name = name
self.work = pathlib.Path(tempfile.mkdtemp(prefix="invpw-failure-evidence-"))
self.trace_dir = self.work / "juggler-engine-trace"
self.wire_path = self.work / "juggler-wire.jsonl"
self.moz_log_dir = self.work / "moz-log"
#: The records the test keeps itself, by name (``note_records``).
self.records = {}
#: What the client heard of each request (a list ``profile_p2.drive(client_log=...)`` fills).
self.client_log = []
#: The cells of the run, once it has returned (``note_cells``).
self.cells = None
self._stop = None
self._patch = None
self._wire = None
self._wire_lock = threading.Lock()
self.saved_to = None
# ---- what the test points the helper at ---------------------------------------------------------------------------
def watch_server(self, stop) -> None:
"""The ``stop`` function ``tests/fakeweb/sites.start`` returned: it carries the server's own record (``stop.state``)."""
self._stop = stop
def note_cells(self, cells) -> None:
self.cells = cells
def note_records(self, name: str, state) -> None:
"""A record the test keeps itself (``state.lock``, ``state.records``: a list of dicts), saved as ``<name>.jsonl``."""
self.records[name] = state
def arm(self, moz_log: str = "") -> None:
"""Before the browser under test is launched: the engine writes its trace, and the Juggler wire of this process is logged.
Armed after the other processes of the test were started, so that they do not inherit the variable. ``moz_log``, a value of
``MOZ_LOG`` (modules and levels), also starts the engine's own log into the evidence (a diagnostic no page reads: the core passes it)."""
self.trace_dir.mkdir(parents=True, exist_ok=True)
self._patch = pytest.MonkeyPatch()
self._patch.setenv(TRACE_ENV, str(self.trace_dir))
if moz_log:
self.moz_log_dir.mkdir(parents=True, exist_ok=True)
self._patch.setenv("MOZ_LOG", moz_log)
self._patch.setenv("MOZ_LOG_FILE", str(self.moz_log_dir / MOZ_LOG_FILE_NAME))
self._wire = open(self.wire_path, "w", encoding="utf-8")
try:
from invisible_core.juggler import connection
except Exception as exc: # the trace of the engine is still written; say that the wire is not
self._write_wire({"dir": "note", "what": "the Juggler wire is not logged: %r" % (exc,)})
return
owner = self
original_deliver, original_write = connection.Connection._deliver, connection.Connection._write
def deliver(connection_self, raw):
owner._log_wire("in", raw)
return original_deliver(connection_self, raw)
def write(connection_self, msg):
owner._log_wire("out", msg)
return original_write(connection_self, msg)
self._patch.setattr(connection.Connection, "_deliver", deliver)
self._patch.setattr(connection.Connection, "_write", write)
# ---- the wire ------------------------------------------------------------------------------------------------------
def _write_wire(self, record: dict) -> None:
try:
with self._wire_lock:
if self._wire is not None:
self._wire.write(json.dumps(record, default=str) + "\n")
self._wire.flush()
except Exception:
pass
def _log_wire(self, direction: str, message) -> None:
try:
if isinstance(message, (bytes, bytearray)):
text = bytes(message).decode("utf-8", "replace")
else:
text = json.dumps(message, default=str)
cut = len(text) > WIRE_LIMIT
self._write_wire({"t": round(time.time(), 4), "m": round(time.perf_counter(), 6), "dir": direction, "len": len(text), "cut": cut,
"msg": text[:WIRE_LIMIT]})
except Exception:
pass
# ---- the end ---------------------------------------------------------------------------------------------------------
def keep(self, why: str) -> None:
"""Saves what the helper holds now, though the test has not failed: a run judged after the fact as one to read (a step slower
than any healthy run). Not a verdict: nothing is raised and the test goes on. Never raises."""
try:
self._save(None, None, kept=why)
except Exception as problem:
sys.stderr.write("evidence: could not be kept: %r\n" % (problem,))
def __enter__(self) -> "FailureEvidence":
return self
def __exit__(self, exc_type, exc, tb) -> bool:
try:
if self._patch is not None:
self._patch.undo()
with self._wire_lock:
if self._wire is not None:
self._wire.close()
self._wire = None
if exc_type is not None:
self._save(exc_type, exc)
except Exception as problem: # the evidence never hides the failure it is about
sys.stderr.write("failure evidence: could not be saved: %r\n" % (problem,))
finally:
shutil.rmtree(self.work, ignore_errors=True)
return False
def _save(self, exc_type, exc, kept: str = "") -> None:
base = os.environ.get("RUNNER_TEMP")
if not base:
return
target = pathlib.Path(base) / EVIDENCE_FOLDER / self.name / ("%d-%d" % (os.getpid(), int(time.time() * 1000)))
target.mkdir(parents=True, exist_ok=True)
if self._stop is not None and getattr(self._stop, "state", None) is not None:
state = self._stop.state
with state.lock:
records = list(state.records)
self._jsonl(target / "fakeweb-server-record.jsonl", records)
for name, state in self.records.items():
with state.lock:
records = list(state.records)
self._jsonl(target / ("%s.jsonl" % name), records)
self._jsonl(target / "client-request-log.jsonl", list(self.client_log))
if self.cells is not None:
(target / "cells.json").write_text(json.dumps(self.cells, indent=1, default=str), encoding="utf-8")
if self.wire_path.exists():
shutil.copyfile(self.wire_path, target / "juggler-wire.jsonl")
if self.trace_dir.exists():
shutil.copytree(self.trace_dir, target / "juggler-engine-trace", dirs_exist_ok=True)
if self.moz_log_dir.exists():
shutil.copytree(self.moz_log_dir, target / "moz-log", dirs_exist_ok=True)
meta = {"test": self.name, "platform": sys.platform,
"machine": platform.machine(), "python": platform.python_version(), "saved_at": round(time.time(), 4),
"times": "t: wall-clock seconds since the epoch (the engine's trace: milliseconds, in t); m: time.perf_counter() of the test process, the scale shared by the server record, the client log and the wire",
"files": sorted(p.name for p in target.iterdir())}
if exc_type is not None:
meta["failure"] = "%s: %s" % (exc_type.__name__, str(exc)[:1500])
if kept:
meta["kept"] = kept
(target / "meta.json").write_text(json.dumps(meta, indent=1), encoding="utf-8")
self.saved_to = target
@staticmethod
def _jsonl(path: pathlib.Path, records) -> None:
with open(path, "w", encoding="utf-8") as out:
for record in records:
out.write(json.dumps(record, default=str) + "\n")
-133
View File
@@ -1,133 +0,0 @@
"""``FailureEvidence`` that also keeps a folder of extra files (the engine's own log of the launch, a lab server's record, a page's timeline).
The test writes whatever it wants to keep into ``evidence.files`` while it runs. When the body fails, the folder is copied next to the
rest of the evidence (``<evidence folder>/files/``) and ``meta.json`` lists it; when the body passes, it is deleted with the rest.
Nothing else differs from ``tests/_evidence_on_failure.py``.
"""
from __future__ import annotations
import json
import re
import shutil
import subprocess
import sys
import threading
import time
from _evidence_on_failure import FailureEvidence
class FailureEvidenceWithFiles(FailureEvidence):
def __init__(self, name: str):
super().__init__(name)
#: Under the helper's own temporary folder: removed with it when the body passes.
self.files = self.work / "files"
self.files.mkdir(parents=True, exist_ok=True)
def _save(self, exc_type, exc) -> None:
super()._save(exc_type, exc)
if self.saved_to is None or not self.files.exists():
return
shutil.copytree(self.files, self.saved_to / "files", dirs_exist_ok=True)
meta_path = self.saved_to / "meta.json"
meta = json.loads(meta_path.read_text(encoding="utf-8"))
meta["files"] = sorted(p.name for p in self.saved_to.iterdir())
meta["extra_files"] = sorted(str(p.relative_to(self.files)).replace("\\", "/") for p in self.files.rglob("*") if p.is_file())
meta_path.write_text(json.dumps(meta, indent=1), encoding="utf-8")
class _TeeStream:
"""The browser's merged stdout and stderr as the core reads it, copied line by line to a file: ``<wall clock> <perf_counter> <line>``.
The core reads the pipe with ``readline`` for the whole life of the process (``invisible_core.juggler.connection.ProcessOutput``) and keeps only the last
200 lines, so this sits between the pipe and that reader: every line it returns is also appended to ``path``, nothing else changes. The content processes
inherit the parent's stdout (ipc/chromium/src/base/process_util_win.cc ``GetStdHandle(STD_OUTPUT_HANDLE)``; a plain fork on Linux), so what they
``printf`` arrives here. The file is opened for each line and closed again: the folder it is in can be removed at any moment (a launch that went right)
with nothing left open. It never raises."""
def __init__(self, stream, path):
self._stream = stream
self._path = path
self._lock = threading.Lock()
def readline(self, *args):
raw = self._stream.readline(*args)
if raw and self._path:
try:
with self._lock, open(self._path, "ab") as out:
out.write(("%.4f %.6f " % (time.time(), time.perf_counter())).encode("ascii") + raw.rstrip(b"\r\n") + b"\n")
except Exception:
pass
return raw
def __getattr__(self, name):
return getattr(self._stream, name)
_TEE = {"path": None}
def tee_browser_output(monkeypatch, path) -> bool:
"""From now on, until the end of the test, the stdout of the browser the core launches next is also written to ``path`` (see ``_TeeStream``). Test side
only: it wraps the stream the core hands to its own reader, in the test process, and touches nothing of the product. Called again with another
``path`` it only changes where the next launch's lines go. False (and nothing changed) when the core has no such reader."""
try:
from invisible_core.juggler import connection
output = connection.ProcessOutput
original = output.__init__
except Exception:
return False
_TEE["path"] = str(path)
if getattr(original, "_invpw_tee", False):
return True
def init(self, stream):
original(self, _TeeStream(stream, _TEE["path"]))
init._invpw_tee = True
monkeypatch.setattr(output, "__init__", init)
return True
#: The most a command of the probe is waited for, in seconds (the suite's 30 s: a command that hangs is cut and the file says so).
_PROBE_COMMAND_S = 30
def _run(argv):
started = time.perf_counter()
try:
done = subprocess.run(argv, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=_PROBE_COMMAND_S)
text = (done.stdout or "") + (("\n[stderr]\n" + done.stderr) if done.stderr and done.stderr.strip() else "")
return "$ %s\n[exit %s, %.2f s]\n%s\n" % (" ".join(argv), done.returncode, time.perf_counter() - started, text.rstrip())
except Exception as problem:
return "$ %s\n[could not run: %r]\n" % (" ".join(argv), problem)
_SHOW_PROCESSES = (
"foreach ($p in @(%s)) { try { Get-Process -Id $p -ErrorAction Stop | Select-Object Id,ProcessName,StartTime,Path | Format-List } "
"catch { 'pid ' + $p + ': ' + $_.Exception.Message } }")
def probe_machine(path) -> None:
"""Who holds UDP 5353 on this machine, now, written to ``path``: the failure evidence of the mDNS test (the engine's responder binds it, and so does any
other browser of the machine). Windows: ``Get-NetUDPEndpoint -LocalPort 5353`` and ``Get-Process`` of each owning pid. Linux: ``ss -uapn``. Meant to be
called while the browser of the launch is still up. It only reads, never raises and never changes a verdict."""
try:
text = "taken_t %.4f\ntaken_m %.6f\nplatform %s\n\n" % (time.time(), time.perf_counter(), sys.platform)
if sys.platform == "win32":
endpoints = _run(["powershell", "-NoProfile", "-Command",
"Get-NetUDPEndpoint -LocalPort 5353 | Select-Object LocalAddress,LocalPort,OwningProcess,CreationTime | Format-List"])
text += endpoints + "\n"
pids = sorted({int(n) for n in re.findall(r"OwningProcess\s*:\s*(\d+)", endpoints)})
if pids:
text += _run(["powershell", "-NoProfile", "-Command", _SHOW_PROCESSES % ",".join(str(n) for n in pids)])
else:
text += _run(["ss", "-uapn", "sport", "=", ":5353"])
with open(path, "w", encoding="utf-8") as out:
out.write(text)
except Exception as problem:
try:
with open(path, "w", encoding="utf-8") as out:
out.write("the machine probe failed: %r\n" % (problem,))
except Exception:
pass
-359
View File
@@ -1,359 +0,0 @@
"""What a failed far-away gather says about the machine and the core's own measurement (the recorders of ``_Watch`` in tests/test_webrtc_realness.py).
The gateway of these tests simulates distance with sleeps and timers inside the process of pytest, which also runs the core's UDP measurement.
When the gather fails the question is where the time went: in the gateway's own answers, in a stall of the whole worker process, or in a
runner with no CPU left. Three recorders answer it, each kept as a list of records the evidence saves (``FailureEvidence.note_records``) and
each said in a few lines of the failure message:
* the times of every control connection of the gateway (connect, greeting, authentication, ASSOCIATE asked and answered), read from the
records the watch already makes, and how long the gateway sat on an answer;
* the records of the core's logger ``invisible_core._udp_exit`` at DEBUG (the outcome of its UDP measurement), set and removed around the test,
next to the marks the test makes (the launch that runs the measurement starts and returns);
* a witness of the whole process (a daemon thread that beats every 50 ms and records the gaps over 200 ms) and the runner's CPU load,
sampled every 0.5 s.
Nothing here changes an assertion, a wait, a deadline or a measurement: a recorder only listens, never raises into the test or into a server,
and takes every record as ONE dict (no keyword that can collide with a field of the data).
"""
from __future__ import annotations
import logging
import threading
import time
#: The logger of the core whose DEBUG records say how its UDP measurement ended (``invisible_core/_udp_exit.py``: ``log = getLogger(__name__)``).
UDP_EXIT_LOGGER = "invisible_core._udp_exit"
#: The beat of the witness and the gap it calls a stall, in seconds.
BEAT_S, STALL_S = 0.05, 0.2
#: How often the runner's load is sampled, in seconds.
LOAD_EVERY_S = 0.5
#: The most control connections and stalls said in the message (the evidence has all of them).
MESSAGE_CONNECTIONS, MESSAGE_STALLS = 3, 4
class Records:
"""A list of records for ``FailureEvidence.note_records`` (``lock``, ``records``). ``add`` never raises: it is called from threads of the test
and, through the watch, from the gateway's own."""
def __init__(self):
self.lock = threading.Lock()
self.records = []
def add(self, record):
try:
record = dict(record)
record.setdefault("t", round(time.time(), 4))
with self.lock:
self.records.append(record)
except Exception as problem: # noqa: BLE001 - recorded, never raised
try:
with self.lock:
self.records.append({"origin": "probe", "event": "a record could not be kept", "error": repr(problem)})
except Exception: # noqa: BLE001
pass
def all(self):
with self.lock:
return list(self.records)
def _say(value):
return "?" if value is None else ("%.2f" % value)
# ---- the witness of the whole process ----------------------------------------------------------------------------------------------
class StallWitness:
"""A daemon thread that beats every ``beat_s`` and keeps the gaps over ``stall_s``. A call that holds the GIL (a long call into C) or a
machine with no CPU left for this process delays the beat of every thread alike, so a gap is a stall of the whole worker process, the one
that also holds the gateway's own threads. Times are seconds from ``epoch`` (``time.monotonic()`` of the start of the gateway: the scale
of its records) and ``t``, the wall clock."""
def __init__(self, records, epoch, beat_s=BEAT_S, stall_s=STALL_S, clock=time.monotonic):
self.records, self.epoch, self.beat_s, self.stall_s, self._clock = records, epoch, beat_s, stall_s, clock
self.beats = 0
self.first = self.last = None
self.longest_gap_s = 0.0
self._stop = threading.Event()
self._thread = None
def beat(self):
"""One beat. Never raises: a clock that fails is a record."""
try:
now = self._clock()
if self.last is None:
self.first = now
else:
gap = now - self.last
self.longest_gap_s = max(self.longest_gap_s, gap)
if gap > self.stall_s:
self.records.add({"origin": "witness", "event": "stall", "from_gw": round(self.last - self.epoch, 4),
"to_gw": round(now - self.epoch, 4), "gap_s": round(gap, 4)})
self.last = now
self.beats += 1
except Exception as problem: # noqa: BLE001
self.records.add({"origin": "witness", "event": "a beat could not be made", "error": repr(problem)})
def _run(self):
try:
while not self._stop.wait(self.beat_s):
self.beat()
except Exception as problem: # noqa: BLE001
self.records.add({"origin": "witness", "event": "the witness ended", "error": repr(problem)})
def start(self):
try:
self.beat()
self._thread = threading.Thread(target=self._run, name="far-away-stall-witness", daemon=True)
self._thread.start()
except Exception as problem: # noqa: BLE001
self.records.add({"origin": "witness", "event": "the witness did not start", "error": repr(problem)})
def stop(self):
"""Ends the witness and says what it saw: the last gap (from its last beat to now) is a stall too if it is long."""
try:
self._stop.set()
if self._thread is not None:
self._thread.join(5)
self.beat()
self.records.add({"origin": "witness", "event": "the witness stopped", "beats": self.beats, "beat_s": self.beat_s,
"stall_s": self.stall_s, "longest_gap_s": round(self.longest_gap_s, 4),
"watched_s": None if self.first is None or self.last is None else round(self.last - self.first, 4)})
except Exception as problem: # noqa: BLE001
self.records.add({"origin": "witness", "event": "the witness did not stop cleanly", "error": repr(problem)})
def stalls(self):
return [r for r in self.records.all() if r.get("event") == "stall"]
# ---- the load of the runner -------------------------------------------------------------------------------------------------------
class LoadSampler:
"""The runner's CPU load every ``every_s`` seconds: ``cpu_percent(percpu=False)`` since the previous sample and, where the system has it,
the load average. ``source`` is ``psutil`` (a stand-in in the unit tests)."""
def __init__(self, records, epoch, every_s=LOAD_EVERY_S, source=None, clock=time.monotonic):
self.records, self.epoch, self.every_s, self._clock = records, epoch, every_s, clock
self.source = source
self._stop = threading.Event()
self._thread = None
def sample(self):
"""One sample. Never raises: a source that fails is a record."""
try:
record = {"origin": "load", "event": "sample", "gw": round(self._clock() - self.epoch, 4)}
record["cpu_percent"] = self.source.cpu_percent(percpu=False)
if hasattr(self.source, "getloadavg"):
try:
record["loadavg_1_5_15"] = [round(v, 2) for v in self.source.getloadavg()]
except Exception as problem: # noqa: BLE001
record["loadavg_error"] = repr(problem)
self.records.add(record)
except Exception as problem: # noqa: BLE001
self.records.add({"origin": "load", "event": "a sample could not be taken", "error": repr(problem)})
def _run(self):
try:
while not self._stop.wait(self.every_s):
self.sample()
except Exception as problem: # noqa: BLE001
self.records.add({"origin": "load", "event": "the sampler ended", "error": repr(problem)})
def start(self):
try:
if self.source is None:
import psutil
self.source = psutil
self.source.cpu_percent(percpu=False) # the first reading has no window: it is only the start of the first one
if hasattr(self.source, "getloadavg"):
self.source.getloadavg() # on Windows the first call starts the thread that makes the average
self._thread = threading.Thread(target=self._run, name="far-away-load-sampler", daemon=True)
self._thread.start()
except Exception as problem: # noqa: BLE001
self.records.add({"origin": "load", "event": "the sampler did not start", "error": repr(problem)})
def stop(self):
try:
self._stop.set()
if self._thread is not None:
self._thread.join(5)
self.sample()
except Exception as problem: # noqa: BLE001
self.records.add({"origin": "load", "event": "the sampler did not stop cleanly", "error": repr(problem)})
def samples(self):
return [r for r in self.records.all() if r.get("event") == "sample" and isinstance(r.get("cpu_percent"), (int, float))]
# ---- the core's logger ------------------------------------------------------------------------------------------------------------
class _KeepRecords(logging.Handler):
def __init__(self, records, epoch, clock):
super().__init__(level=logging.DEBUG)
self.records, self.epoch, self._clock = records, epoch, clock
def emit(self, record):
try:
self.records.add({"origin": "core", "event": "log", "logger": record.name, "level": record.levelname,
"message": record.getMessage(), "thread": record.threadName, "gw": round(self._clock() - self.epoch, 4)})
except Exception as problem: # noqa: BLE001 - a message that cannot be formatted is a record, not an error of the core's thread
try:
self.records.add({"origin": "probe", "event": "a log record could not be kept", "logger": getattr(record, "name", None),
"error": repr(problem)})
except Exception: # noqa: BLE001 - not even that: nothing is raised into the logging call of the core
pass
class LogCapture:
"""The records of the logger ``name`` at DEBUG while it is on: its level is set and the handler added at ``start``, and both are put back at
``stop`` whatever happened in between. The logger keeps passing every record on to its parents as before."""
def __init__(self, records, epoch, name=UDP_EXIT_LOGGER, clock=time.monotonic):
self.records, self.name = records, name
self._handler = _KeepRecords(records, epoch, clock)
self._level = None
self._on = False
def start(self):
try:
logger = logging.getLogger(self.name)
self._level = logger.level
logger.addHandler(self._handler)
self._on = True
logger.setLevel(logging.DEBUG)
except Exception as problem: # noqa: BLE001
self.records.add({"origin": "probe", "event": "the log capture did not start", "error": repr(problem)})
def stop(self):
try:
if self._on:
logger = logging.getLogger(self.name)
logger.removeHandler(self._handler)
logger.setLevel(self._level)
self._on = False
except Exception as problem: # noqa: BLE001
self.records.add({"origin": "probe", "event": "the log capture did not stop", "error": repr(problem)})
# ---- the times of the control connections ----------------------------------------------------------------------------------------
def control_times(records):
"""From the records of the watch's control journal (``gateway-control-connections``): for each control connection, in seconds from the start
of the gateway, when it was accepted (connect), when the greeting and the authentication were answered, when the ASSOCIATE was asked and
answered, and the longest time the gateway sat on an answer between the moment it was asked to send it and the moment it was sent.
``None`` is a step that was not seen. Never raises."""
table = {}
try:
for r in records:
conn = r.get("conn")
if conn is None or conn < 0:
continue
row = table.setdefault(conn, {"connect": None, "greeting": None, "authentication": None, "associate_asked": None,
"associate_answered": None, "longest_answer_wait_s": None})
event = r.get("event")
if event == "control connection accepted":
row["connect"] = r.get("gw")
elif event == "request" and r.get("command") == "UDP ASSOCIATE":
row["associate_asked"] = r.get("gw")
elif event == "answer sent":
what = str(r.get("what", ""))
if what.startswith("method selection"):
row["greeting"] = r.get("gw")
elif what.startswith("authentication status"):
row["authentication"] = r.get("gw")
elif r.get("kind") == "associate" and r.get("rep") == 0:
row["associate_answered"] = r.get("gw")
if r.get("gw") is not None and r.get("asked_gw") is not None:
wait = round(r["gw"] - r["asked_gw"], 4)
if row["longest_answer_wait_s"] is None or wait > row["longest_answer_wait_s"]:
row["longest_answer_wait_s"] = wait
except Exception as problem: # noqa: BLE001
table["error"] = repr(problem)
return table
def control_line(table):
"""The control connections in one line: ``#<n> connect|greeting|authentication|ASSOCIATE asked|ASSOCIATE answered`` in seconds from the start of
the gateway, the longest wait inside the gateway for an answer, and a reminder that #0 is the core's (the first accepted)."""
try:
rows = sorted((k, v) for k, v in table.items() if isinstance(k, int))
if not rows:
return "control connections of the gateway: none seen"
shown = " ".join("#%d %s|%s|%s|%s|%s (longest wait in the gateway %ss)" % (
k, _say(v["connect"]), _say(v["greeting"]), _say(v["authentication"]), _say(v["associate_asked"]), _say(v["associate_answered"]),
_say(v["longest_answer_wait_s"])) for k, v in rows[:MESSAGE_CONNECTIONS])
return ("control connections of the gateway, s from its start, connect|greeting answered|authentication answered|ASSOCIATE asked|"
"ASSOCIATE answered (#0 is the first accepted: the core's own measurement), %d of %d: %s" % (min(len(rows), MESSAGE_CONNECTIONS), len(rows), shown))
except Exception as problem: # noqa: BLE001
return "control connections of the gateway: not read (%r)" % (problem,)
def core_line(records):
"""The core's UDP measurement in one line: its DEBUG records and the marks of the test, each with its time in seconds from the start of the gateway."""
try:
parts = []
for r in records:
if r.get("event") == "log":
parts.append("%s: %r at %s" % (r.get("thread"), r.get("message"), _say(r.get("gw"))))
elif r.get("event") == "mark":
parts.append("%s at %s" % (r.get("what"), _say(r.get("gw"))))
return "the core's UDP measurement (logger %s, s from the gateway start): %s" % (UDP_EXIT_LOGGER, "; ".join(parts) or "no record")
except Exception as problem: # noqa: BLE001
return "the core's UDP measurement: not read (%r)" % (problem,)
def process_line(witness, sampler):
"""The stalls of the process and the runner's load in one line each."""
try:
stalls = sorted(witness.stalls(), key=lambda s: -s["gap_s"])
samples = sampler.samples() if sampler is not None else []
if stalls:
said = ", ".join("%.2fs (%.2f to %.2f)" % (s["gap_s"], s["from_gw"], s["to_gw"]) for s in stalls[:MESSAGE_STALLS])
stall = "%d stall(s) of the whole process over %.0f ms, longest first, gap (from to, s from the gateway start): %s" % (
len(stalls), witness.stall_s * 1000, said)
else:
stall = "no stall of the whole process over %.0f ms in %d beats of %.0f ms (longest gap %.3fs)" % (
witness.stall_s * 1000, witness.beats, witness.beat_s * 1000, witness.longest_gap_s)
if samples:
cpu = [s["cpu_percent"] for s in samples]
loads = [s["loadavg_1_5_15"][0] for s in samples if s.get("loadavg_1_5_15")]
load = "runner CPU every %.1fs: %d samples, max %.0f%%, mean %.0f%%, at least 90%% in %d%s" % (
sampler.every_s, len(cpu), max(cpu), sum(cpu) / len(cpu), sum(1 for c in cpu if c >= 90),
"; load average max %.2f" % max(loads) if loads else "")
else:
load = "runner CPU: no sample"
return stall + "\n" + load
except Exception as problem: # noqa: BLE001
return "stall witness and runner load: not read (%r)" % (problem,)
class FarAwayProbes:
"""The three recorders of one gather, started and stopped together. ``epoch`` is ``time.monotonic()`` at the start of the gateway."""
def __init__(self, epoch, load_source=None):
self.epoch = epoch
self.stall_records, self.load_records, self.core_records = Records(), Records(), Records()
self.witness = StallWitness(self.stall_records, epoch)
self.sampler = LoadSampler(self.load_records, epoch, source=load_source)
self.core = LogCapture(self.core_records, epoch)
def start(self):
self.core.start()
self.sampler.start()
self.witness.start()
def stop(self):
self.witness.stop()
self.sampler.stop()
self.core.stop()
def mark(self, what):
"""A moment of the test (the launch that runs the core's measurement starts, returns), on the scale of the core's records."""
self.core_records.add({"origin": "test", "event": "mark", "what": what, "gw": round(time.monotonic() - self.epoch, 4)})
def lines(self, control_records):
"""The failure message: the times of the control connections, the core's measurement, the stalls and the load."""
return "\n".join(["far-away probes:", control_line(control_times(control_records)), core_line(self.core_records.all()),
process_line(self.witness, self.sampler)])
def cells(self, control_records):
return {"control_connection_times_s_from_the_gateway_start": control_times(control_records),
"stalls_of_the_whole_process": self.witness.stalls(), "stall_beats": self.witness.beats,
"longest_gap_between_beats_s": round(self.witness.longest_gap_s, 4),
"runner_load_samples": self.sampler.samples(), "core_udp_exit_log_and_marks": self.core_records.all()}
-244
View File
@@ -1,244 +0,0 @@
"""What the e2e tests of the font list need to know about the bundle and about the host, read from files and never typed.
Two sources, both plain data:
* the bundle manifest the core hands to the engine (``invisible_core._fpforge.profile.FONT_MANIFEST``, the text of
``bundle-fonts.list``: ``F|<family>`` opens a family, ``f|<file>|<index>|...|<psname>|<upem>|<ascent>|<descent>|...`` is one of its faces,
``A|<alias>|<target>`` is a Windows font-substitute). The engine prefers this text to the copy in its own directory, so it is the list of
the families the engine answers to;
* the font files of the machine that runs the test (the host): the folders a system installs fonts in. Each file's ``name`` table gives the
family, PostScript and full names of each of its faces. A host font whose names are not in the bundle is a "host-only" face: the engine
must not know it, and a test that asks the page for it has a name that exists on this machine and in no bundle.
Only the header and the ``name`` table of a file are read (a font collection is several faces; ``simsun.ttc`` is 15 MB).
"""
from __future__ import annotations
import os
import struct
import sys
from pathlib import Path
from typing import Dict, Iterable, List, Optional, Set
#: What an sfnt file starts with: TrueType 1.0, OpenType with CFF outlines, the Apple TrueType tag, a collection.
_SFNT = (b"\x00\x01\x00\x00", b"OTTO", b"true")
_COLLECTION = b"ttcf"
_EXTENSIONS = {".ttf", ".otf", ".ttc", ".otc"}
#: name ids of the strings that name a face.
FAMILY, FULL, POSTSCRIPT, TYPOGRAPHIC_FAMILY = 1, 4, 6, 16
class Manifest:
"""The bundle manifest, parsed: families in order, the faces of each (file, index, PostScript name, metrics) and the aliases."""
def __init__(self, text: str):
self.families: List[str] = []
self.faces: Dict[str, List[dict]] = {}
self.aliases: Dict[str, str] = {}
current: Optional[str] = None
for line in text.splitlines():
if not line or line.startswith("#"):
continue
fields = line.split("|")
if fields[0] == "F" and len(fields) >= 2:
current = fields[1]
self.families.append(current)
self.faces[current] = []
elif fields[0] == "A" and len(fields) >= 3:
self.aliases[fields[1]] = fields[2]
elif fields[0] == "f" and current is not None and len(fields) >= 19:
self.faces[current].append({
"file": fields[1], "index": int(fields[2]), "psname": fields[8],
"upem": int(fields[9]), "ascent": int(fields[10]), "descent": int(fields[11]),
})
def family_of_psname(self, psname: str) -> Optional[str]:
for family, faces in self.faces.items():
if any(face["psname"] == psname for face in faces):
return family
return None
def face_with_psname(self, psname: str) -> dict:
for faces in self.faces.values():
for face in faces:
if face["psname"] == psname:
return face
raise AssertionError("the bundle manifest has no face with the PostScript name %r" % psname)
def known_names(self) -> Set[str]:
"""Every name the bundle answers to, lower case: its families, its aliases and the PostScript names of its faces."""
names = {family.lower() for family in self.families}
names |= {alias.lower() for alias in self.aliases}
names |= {face["psname"].lower() for faces in self.faces.values() for face in faces}
return names
def bundle_manifest() -> Manifest:
"""The manifest of the core installed with the wrapper under test, the one the engine is handed as ``zoom.stealth.fonts.manifest``."""
from invisible_core._fpforge.profile import FONT_MANIFEST
manifest = Manifest(FONT_MANIFEST)
assert manifest.families, "the manifest of the core has no family: the parser read nothing"
return manifest
def _decode(platform: int, encoding: int, raw: bytes) -> Optional[str]:
try:
if platform in (0, 3):
return raw.decode("utf-16-be")
if platform == 1 and encoding == 0:
return raw.decode("mac_roman")
except UnicodeDecodeError:
return None
return None
def _name_strings(table: bytes) -> Dict[int, List[tuple]]:
"""name id -> [(is english windows name, text)] of one ``name`` table."""
out: Dict[int, List[tuple]] = {}
if len(table) < 6:
return out
_format, count, string_offset = struct.unpack(">HHH", table[:6])
for i in range(count):
record = table[6 + 12 * i: 18 + 12 * i]
if len(record) < 12:
break
platform, encoding, language, name_id, length, offset = struct.unpack(">6H", record)
text = _decode(platform, encoding, table[string_offset + offset: string_offset + offset + length])
if text:
out.setdefault(name_id, []).append((platform == 3 and language == 0x409, text))
return out
def face_names(path: Path) -> List[dict]:
"""For each face of a font file: ``family`` (every family string, any language), ``psname`` and ``full`` (the English ones, or None).
An unreadable file, or a file that is not an sfnt, has no faces: a host folder holds other things than fonts."""
faces: List[dict] = []
try:
with open(path, "rb") as handle:
head = handle.read(12)
if len(head) < 12:
return faces
if head[:4] == _COLLECTION:
count = struct.unpack(">I", head[8:12])[0]
if count > 64:
return faces
offsets = struct.unpack(">%dI" % count, handle.read(4 * count))
elif head[:4] in _SFNT:
offsets = (0,)
else:
return faces
for base in offsets:
handle.seek(base + 4)
tables = struct.unpack(">H", handle.read(2))[0]
handle.seek(base + 12)
directory = handle.read(16 * tables)
name_table = None
for i in range(tables):
tag, _checksum, offset, length = struct.unpack(">4sIII", directory[16 * i: 16 * i + 16])
if tag == b"name" and 0 < length <= 1 << 20:
handle.seek(offset)
name_table = handle.read(length)
break
if name_table is None:
continue
strings = _name_strings(name_table)
def english(name_id: int) -> Optional[str]:
for is_english, text in strings.get(name_id, []):
if is_english:
return text
return None
families = []
for name_id in (FAMILY, TYPOGRAPHIC_FAMILY):
for _english, text in strings.get(name_id, []):
if text not in families:
families.append(text)
faces.append({"file": str(path), "families": families, "psname": english(POSTSCRIPT), "full": english(FULL)})
except (OSError, struct.error):
return []
return faces
def host_font_files() -> List[Path]:
"""The font files the host has installed, in a stable order."""
if sys.platform == "win32":
roots = [Path(os.environ.get("WINDIR", r"C:\Windows")) / "Fonts"]
local = os.environ.get("LOCALAPPDATA")
if local:
roots.append(Path(local) / "Microsoft" / "Windows" / "Fonts")
else:
roots = [Path("/usr/share/fonts"), Path("/usr/local/share/fonts"), Path.home() / ".fonts",
Path.home() / ".local" / "share" / "fonts"]
files: List[Path] = []
for root in roots:
if root.is_dir():
files += [p for p in root.rglob("*") if p.suffix.lower() in _EXTENSIONS and p.is_file()]
return sorted(files, key=lambda p: str(p).lower())
def _plain(name: Optional[str]) -> bool:
"""A name that goes into a CSS string between double quotes without an escape: printable ASCII, no quote, no backslash."""
return bool(name) and all(32 <= ord(ch) < 127 and ch not in "\"\\" for ch in name)
def bundle_file_names(manifest: Manifest, binary: str) -> Set[str]:
"""Every name (families of any language, PostScript, full), lower case, that the files of the bundle carry in their own ``name`` tables.
The engine answers to the other-language family names of a bundled face as it does to its family (a localized name is an alias of the
face it names), so a host font that carries such a name is not host-only. The folder is ``<engine>/fonts``; when the build has no such
folder the set is empty and the manifest alone decides."""
folder = Path(binary).resolve().parent / "fonts"
names: Set[str] = set()
if not folder.is_dir():
return names
for name in sorted({face["file"] for faces in manifest.faces.values() for face in faces}):
for face in face_names(folder / name):
names |= {family.lower() for family in face["families"]}
names |= {value.lower() for value in (face["psname"], face["full"]) if value}
return names
def host_only_faces(manifest: Manifest, extra_known: Iterable[str] = ()) -> List[dict]:
"""The faces of the host whose names the bundle does not know: no family, no alias and no PostScript name of the bundle."""
known = manifest.known_names() | set(extra_known)
out: List[dict] = []
for path in host_font_files():
for face in face_names(path):
names = [name.lower() for name in face["families"]]
if face["psname"]:
names.append(face["psname"].lower())
if names and not any(name in known for name in names):
out.append(face)
return out
def host_only_families(manifest: Manifest, extra_known: Iterable[str] = ()) -> List[str]:
"""The family names (every language) of the host-only faces, once each, in the order of the files."""
extra_known = set(extra_known)
known = manifest.known_names() | extra_known
seen: Set[str] = set()
out: List[str] = []
for face in host_only_faces(manifest, extra_known):
for family in face["families"]:
key = family.lower()
if key not in seen and key not in known and _plain(family):
seen.add(key)
out.append(family)
return out
def a_host_only_face(manifest: Manifest, prefer: Iterable[str] = (), extra_known: Iterable[str] = ()) -> dict:
"""One host-only face with a PostScript name and a full name a page can write: the first of the ``prefer`` families the host has, else the first.
The face is what a ``src: local()`` is given: its names exist on this machine (the file is on its disk) and in no bundle."""
faces = [f for f in host_only_faces(manifest, extra_known) if _plain(f["psname"]) and _plain(f["full"])]
assert faces, "the host has no font whose names are not the bundle's: there is nothing to ask the engine for that only the host knows"
for wanted in prefer:
for face in faces:
if wanted.lower() in (family.lower() for family in face["families"]):
return face
return faces[0]
-417
View File
@@ -1,417 +0,0 @@
"""What a failing Fission frame test leaves about the frames of its pages, and nothing it could change in the test.
``tests/_evidence_on_failure.py`` keeps the Juggler wire and the engine's own trace. This adds the client's view of the pages (the events
``frameattached``, ``framenavigated`` and ``framedetached`` with the url and name of the frame, the times at which a call of the test started and
came back, and ``page.frames`` at the failure) and a reading of the wire that answers "to which execution context, of which frame and url, was that
evaluate sent, and what came back".
The rule of a probe: it can never change the outcome of the call it watches. So
* nothing here raises into the test, into the browser's event dispatch or into the server: every recording runs inside one guard;
* nothing takes ``**fields``: a record keeps what it was given under ``data``, so that a field named ``what``, ``source`` or ``event`` of the thing
being recorded cannot collide with a keyword of ours (two earlier probes broke their tests exactly that way);
* ``observed`` returns what the call returned, and raises what the call raised, the same object, whatever the recording did.
"""
from __future__ import annotations
import json
import sys
import threading
import time
from _far_away_probes import LoadSampler, StallWitness
from _far_away_probes import Records as ProbeRecords
#: The events of a page the client hears, recorded with the frame they are about.
FRAME_EVENTS = ("frameattached", "framenavigated", "framedetached")
#: The most records of the wire the summary keeps (the window of one test is a few hundred messages).
SUMMARY_LIMIT = 600
#: The most commands without an answer the summary says (a browser that is closed leaves a few; the evidence has the wire itself).
UNANSWERED_LIMIT = 20
#: The commands that carry code to a context.
_CALLS = ("Runtime.evaluate", "Runtime.callFunction")
#: The events of the engine that say which frame and which world exist, and when they come and go.
_EVENTS = ("Page.frameAttached", "Page.frameDetached", "Page.navigationStarted", "Page.navigationCommitted", "Page.navigationAborted",
"Runtime.executionContextCreated", "Runtime.executionContextDestroyed", "Runtime.executionContextsCleared")
class Records:
"""A list of dicts with its lock: the shape ``FailureEvidence.note_records`` reads (``lock``, ``records``)."""
def __init__(self, records=None):
self.lock = threading.Lock()
self.records = [] if records is None else records
def add(self, record: dict) -> None:
"""Never raises."""
try:
with self.lock:
self.records.append(record)
except Exception:
pass
def _plain(data):
"""``data`` as plain JSON values (what cannot be written is written as its ``repr``); never raises."""
try:
return json.loads(json.dumps(data, default=repr))
except Exception:
try:
return {"unwritable": repr(data)[:500]}
except Exception:
return {"unwritable": "?"}
class FrameWatch(Records):
"""The client's own log of what the test did and heard, on the clocks of the evidence (``t`` wall, ``m`` ``time.perf_counter()``)."""
def __init__(self, records=None):
super().__init__(records)
#: The reading of the wire (``summarize_wire``), saved as its own file.
self.wire = Records()
self._pages = {}
self.started_m = None
# ---- one record --------------------------------------------------------------------------------------------------
def note(self, event: str, data=None) -> None:
"""One record: ``{t, m, event, data}``. What is recorded lives under ``data``, whatever fields it has. Never raises."""
try:
self.add({"t": round(time.time(), 4), "m": round(time.perf_counter(), 6), "event": str(event), "data": _plain(data)})
except Exception:
pass
@staticmethod
def frame_data(frame) -> dict:
"""What the client knows of a frame without asking the browser: url, name, whether it is the main frame, its parent's url, its guid.
A field that cannot be read is left out. Never raises."""
found = {}
try:
for field, read in (("url", lambda f: f.url), ("name", lambda f: f.name), ("guid", lambda f: getattr(f, "_guid", None)),
("main", lambda f: f.parent_frame is None),
("parent_url", lambda f: None if f.parent_frame is None else f.parent_frame.url),
("detached", lambda f: f.is_detached())):
try:
found[field] = read(frame)
except Exception as problem:
found[field] = "unreadable: %r" % (problem,)
except Exception:
pass
return found
# ---- the pages ---------------------------------------------------------------------------------------------------
def listen(self, page, label: str) -> None:
"""Records ``frameattached``, ``framenavigated`` and ``framedetached`` of ``page`` under ``label``, and the page's own ``domcontentloaded`` and
``load``. Call it right after the page is made. Never raises; a handler never raises into the client's dispatch."""
try:
self._pages[label] = page
except Exception:
pass
for event in FRAME_EVENTS:
self._on(page, event, lambda frame, event=event: self.note(event, {"page": label, "frame": self.frame_data(frame)}))
for event in ("domcontentloaded", "load"):
self._on(page, event, lambda _page, event=event: self.note(event, {"page": label, "frames": self.frames_of(_page)}))
def _on(self, page, event: str, handler) -> None:
def guarded(*args):
try:
handler(*args)
except Exception:
pass
try:
page.on(event, guarded)
except Exception:
pass
def frames_of(self, page) -> list:
"""``page.frames`` as url, name and guid of each (local state of the client); never raises."""
try:
return [self.frame_data(f) for f in list(page.frames)]
except Exception as problem:
return [{"unreadable": repr(problem)}]
def forget_pages(self) -> None:
self._pages = {}
# ---- a call of the test ------------------------------------------------------------------------------------------
def observed(self, label: str, call, describe=None):
"""``call()``, with a record when it starts, when it returns and when it raises. It returns what ``call`` returned and raises what it raised.
``describe(stage, value)``, if given, adds to the record: stage is ``"start"``, ``"returned"`` (value: the result) or ``"raised"`` (value: the
exception); what it returns, or what it raises, only goes into the record."""
self.note(label + ": start", self._describe(describe, "start", None))
try:
result = call()
except BaseException as problem:
self.note(label + ": raised", {"type": type(problem).__name__, "message": str(problem)[:1500],
"more": self._describe(describe, "raised", problem)})
raise
self.note(label + ": returned", self._describe(describe, "returned", result))
return result
@staticmethod
def _describe(describe, stage: str, value):
if describe is None:
return None
try:
return describe(stage, value)
except Exception as problem:
return {"describe raised": repr(problem)}
# ---- the test ----------------------------------------------------------------------------------------------------
def start(self, evidence=None) -> None:
"""The test begins: one record, and a note in the wire log (the module's browser is shared by tests that came before)."""
self.started_m = time.perf_counter()
self.note("test starts")
try:
if evidence is not None:
evidence._write_wire({"t": round(time.time(), 4), "m": round(self.started_m, 6), "dir": "note", "what": "the watched test starts"})
except Exception:
pass
def at_failure(self, evidence) -> None:
"""At the failure: ``page.frames`` of every page listened to, and the reading of the wire. Never raises."""
try:
self.note("page.frames at the failure", {label: self.frames_of(page) for label, page in list(self._pages.items())})
except Exception:
pass
try:
for record in summarize_wire(evidence.wire_path, self.started_m):
self.wire.add(record)
except Exception:
pass
def unanswered_line(self, limit: int = 3) -> str:
"""The commands the wire reading found with no answer, in one line each (id, method, context and its frame's url, seconds waited, whether the
context was announced and whether it was destroyed). Empty when there is none. Never raises."""
try:
with self.wire.lock:
found = [r for r in self.wire.records if r.get("event") == "command without an answer"]
parts = []
for r in found[:limit]:
end = r.get("context_at_the_end") or {}
frame = r.get("frame_at_the_end") or {}
parts.append("%s #%s to context %s (frame %s, %s) had no answer after %ss; context %s" % (
r.get("method"), r.get("id"), r.get("executionContextId"), end.get("frame"), frame.get("url"), r.get("waited_s"),
"not announced in the window" if not end else ("destroyed at m=%s" % end.get("destroyed_m") if end.get("destroyed_m") else "alive")))
return "; ".join(parts)
except Exception:
return ""
class ProcessProbes:
"""The stall witness and the runner's CPU load of ``tests/_far_away_probes.py``, on the clock of the wire: ``m`` is ``time.perf_counter()``
(their epoch is 0, so ``from_gw`` and ``to_gw`` are ``m``). A beat that is late is a stall of the whole test process, the one that also holds
the client's reader of the Juggler pipe; a quiet process and a call that gets no answer put the stall in the browser or in the context, not
in the client. ``evidence.note_records`` keeps both lists. Nothing here raises: both recorders keep a failure as a record."""
def __init__(self, load_source=None):
self.stall_records, self.load_records = ProbeRecords(), ProbeRecords()
self.witness = StallWitness(self.stall_records, 0.0, clock=time.perf_counter)
self.sampler = LoadSampler(self.load_records, 0.0, source=load_source, clock=time.perf_counter)
def keep_in(self, evidence) -> None:
evidence.note_records("stalls-of-the-test-process", self.stall_records)
evidence.note_records("runner-load", self.load_records)
def start(self) -> None:
self.witness.start()
self.sampler.start()
def stop(self) -> None:
self.witness.stop()
self.sampler.stop()
def line(self) -> str:
"""Stalls and load in one short line (``m`` of each stall). Never raises."""
try:
stalls = sorted(self.witness.stalls(), key=lambda r: -r["gap_s"])
if stalls:
said = ", ".join("%.2fs at m=%.2f" % (r["gap_s"], r["from_gw"]) for r in stalls[:3])
stall = "%d stall(s) of the test process over %.0f ms: %s" % (len(stalls), self.witness.stall_s * 1000, said)
else:
stall = "no stall of the test process over %.0f ms (%d beats, longest gap %.3fs)" % (
self.witness.stall_s * 1000, self.witness.beats, self.witness.longest_gap_s)
cpu = [r["cpu_percent"] for r in self.sampler.samples()]
load = "runner CPU max %.0f%%, mean %.0f%% in %d samples" % (max(cpu), sum(cpu) / len(cpu), len(cpu)) if cpu else "runner CPU: no sample"
return "%s; %s" % (stall, load)
except Exception as problem:
return "stalls and load: not read (%r)" % (problem,)
class OnFailure:
"""``with OnFailure(evidence, watch):`` around the body of a test: when the body fails, the frames and the wire reading are added and the
evidence is saved (the folder the e2e jobs upload); the exception goes on, the very one the body raised."""
def __init__(self, evidence, watch: FrameWatch, probes: ProcessProbes = None):
self.evidence = evidence
self.watch = watch
self.probes = probes
def __enter__(self):
self.watch.start(self.evidence)
self._probes("start")
return self
def _probes(self, action: str) -> None:
try:
if self.probes is not None:
getattr(self.probes, action)()
except Exception:
pass
def __exit__(self, exc_type, exc, tb):
self._probes("stop")
try:
if exc_type is not None and issubclass(exc_type, Exception): # not a skip, not an interrupt
self.watch.note("failure", {"type": exc_type.__name__, "message": str(exc)[:1500]})
self.watch.at_failure(self.evidence)
self._say(exc)
try:
self.evidence._save(exc_type, exc)
except Exception as problem:
sys.stderr.write("frame evidence: could not be saved: %r\n" % (problem,))
except Exception:
pass
finally:
try:
self.watch.forget_pages()
except Exception:
pass
return False
def _say(self, exc) -> None:
"""A note on the exception the body raised (the very object, its type and message untouched): what the wire says of the commands with no
answer, and the stalls and load of the process. It is read in the failure report next to the traceback."""
try:
lines = []
unanswered = self.watch.unanswered_line()
if unanswered:
lines.append("wire: " + unanswered)
if self.probes is not None:
lines.append("process: " + self.probes.line())
if lines:
self.watch.note("said at the failure", {"lines": lines})
add_note = getattr(exc, "add_note", None)
if add_note is not None:
add_note("evidence of this failure: " + " | ".join(lines))
except Exception:
pass
# ---- the wire --------------------------------------------------------------------------------------------------------
def _short(text, limit=160):
text = "" if text is None else str(text)
return text if len(text) <= limit else text[:limit] + "..."
def summarize_wire(path, since_m=None, marker: str = "window.__r") -> list:
"""What the Juggler wire log (``FailureEvidence`` ``juggler-wire.jsonl``) says about frames, worlds and the evaluate of the test, from ``since_m``
(``perf_counter``) on: the engine's frame and context events with their ids, urls and names; each ``Runtime.evaluate`` or ``callFunction`` sent
with its context id and the beginning of its code; each answer to one of those (its error text, if it has one); and, for every command whose code
contains ``marker``, a ``marker command`` record that joins the context id it was sent to with what the wire knows of that context (its frame id
and name, when it was announced and when it was destroyed) and of that frame (the url it last committed, its parent). Whatever the code, every
command that has no answer by the end of the log gets a ``command without an answer`` record with the same join, taken when it was sent and at
the end of the log, and the time it has waited: the evaluate that a client gave up on (``no response in 30s``) is there whether or not its code
has the marker. An answer says how long after its command it came (``after_s``). A line of the log that is not JSON, or was cut at the log's
limit, is counted, not read. Never raises: a failure is a record."""
try:
return _summarize_wire(path, since_m, marker)
except Exception as problem:
return [{"event": "the wire could not be read", "error": repr(problem)}]
def _join(contexts, frames, context_id):
"""What the wire knows now of a context, of its frame and of the frame's parent (copies: the entries change later); ``None`` for what it does
not know (a context announced before the window, or never)."""
context = dict(contexts.get(context_id) or {}) or None
frame = dict(frames.get((context or {}).get("frame")) or {}) or None
parent = dict(frames.get((frame or {}).get("parent")) or {}) or None
return context, frame, parent
def _after(start_m, end_m):
try:
return round(end_m - start_m, 4)
except Exception:
return None
def _summarize_wire(path, since_m, marker) -> list:
out = []
contexts = {} # context id -> {"frame", "name", "created_m", "destroyed_m"}
frames = {} # frame id -> {"url", "name", "parent", "attached_m", "detached_m", "committed_m"}
sent = {} # command id -> the record of the command
waiting = {} # command id -> what the wire knew of its context and frame when it was sent, until it is answered
last_m = None
unparsed = 0
with open(path, "r", encoding="utf-8", errors="replace") as handle:
for line in handle:
try:
row = json.loads(line)
except Exception:
unparsed += 1
continue
m = row.get("m")
if row.get("dir") == "note" or m is None or (since_m is not None and m < since_m):
continue
try:
message = json.loads(row.get("msg") or "")
except Exception:
unparsed += 1
out.append({"event": "unread message", "m": m, "t": row.get("t"), "dir": row.get("dir"), "len": row.get("len"),
"cut": row.get("cut"), "start": _short(row.get("msg"), 200)})
continue
if not isinstance(message, dict):
continue
last_m = m if last_m is None else max(last_m, m)
base = {"t": row.get("t"), "m": m, "dir": row.get("dir")}
method, params = message.get("method"), message.get("params") or {}
if row.get("dir") == "out" and method in _CALLS:
code = params.get("expression") or params.get("functionDeclaration") or ""
record = dict(base, event="command", method=method, id=message.get("id"), sessionId=message.get("sessionId"),
executionContextId=params.get("executionContextId"), code=_short(code))
sent[message.get("id")] = record
out.append(record)
context, frame, parent = _join(contexts, frames, params.get("executionContextId"))
waiting[message.get("id")] = {"record": record, "context": context, "frame": frame, "parent": parent}
if marker and marker in str(code):
out.append(dict(base, event="marker command", id=message.get("id"), executionContextId=params.get("executionContextId"),
context=context, frame=frame, parent=parent))
elif row.get("dir") == "in" and message.get("id") in sent:
answer = message.get("error")
result = message.get("result")
command = sent[message.get("id")]
waiting.pop(message.get("id"), None)
out.append(dict(base, event="answer", id=message.get("id"), to=command.get("code"), after_s=_after(command.get("m"), m),
error=_short(answer, 400) if answer is not None else None,
result=_short(json.dumps(result, default=str), 300) if answer is None else None))
elif row.get("dir") == "in" and method in _EVENTS:
out.append(dict(base, event=method, sessionId=message.get("sessionId"), params=_plain(params)))
if method == "Runtime.executionContextCreated":
aux = params.get("auxData") or {}
contexts[params.get("executionContextId")] = {"frame": aux.get("frameId"), "name": aux.get("name"), "created_m": m,
"destroyed_m": None}
elif method == "Runtime.executionContextDestroyed":
if params.get("executionContextId") in contexts:
contexts[params.get("executionContextId")]["destroyed_m"] = m
elif method == "Page.frameAttached":
frames.setdefault(params.get("frameId"), {})
frames[params.get("frameId")].update(parent=params.get("parentFrameId"), attached_m=m)
elif method == "Page.frameDetached":
frames.setdefault(params.get("frameId"), {})["detached_m"] = m
elif method == "Page.navigationCommitted":
frames.setdefault(params.get("frameId"), {}).update(url=params.get("url"), name=params.get("name"), committed_m=m)
if len(out) >= SUMMARY_LIMIT:
out.append({"event": "summary cut", "limit": SUMMARY_LIMIT})
break
for command_id, known in list(waiting.items())[:UNANSWERED_LIMIT]:
record = known["record"]
context_now, frame_now, parent_now = _join(contexts, frames, record.get("executionContextId"))
out.append({"event": "command without an answer", "id": command_id, "method": record.get("method"), "sessionId": record.get("sessionId"),
"executionContextId": record.get("executionContextId"), "code": record.get("code"), "sent_m": record.get("m"),
"waited_s": _after(record.get("m"), last_m), "context_known_when_sent": known["context"] is not None,
"context_when_sent": known["context"], "frame_when_sent": known["frame"], "parent_when_sent": known["parent"],
"context_at_the_end": context_now, "frame_at_the_end": frame_now, "parent_at_the_end": parent_now})
out.append({"event": "summary end", "unparsed_lines": unparsed, "last_m": last_m, "commands_without_an_answer": len(waiting), "since_m": since_m,
"contexts_known": len(contexts), "frames_known": len(frames)})
return out
-165
View File
@@ -1,165 +0,0 @@
"""TEMPORARY: what a generation of the security state that fails leaves for a reader, whoever started the engine. Remove it once the exit by SIGSEGV
(-11) of the engine in generate mode on the Linux e2e job (run 45014369018) is understood and fixed.
Two launches of the engine in generate mode run in tests/test_security_state_engine_e2e.py: the test's own (`-profile <p>` with the four prefs) and the
CORE's (`invisible_core._security_state_generate.generate`, which `_ready` calls once per module and whose outcome the three tests that need a ready
directory share). The core sends the engine's stdout and stderr to the null device, deletes its work profile before it raises `GenerationError`, and
starts the engine with the core size limit of the test process: a crash of its launch left nothing at all.
* `save_what_the_failed_generation_left` saves, in `$RUNNER_TEMP/invpw-evidence/<name>/` (the folder the e2e jobs upload), the engine's stdout and stderr and
the files of the profile with their sizes (the result, `user.js` and `security_state/` copied);
* `the_core_s_generation_keeps_its_evidence(work, name)` wraps the core's own launch while it is in force: its Popen writes stdout and stderr to files of
`work`, the files of the work profile are noted when the engine exits (before the core deletes them), and when `generate` raises, everything is saved
under `name` and the error is raised unchanged. The core's launch line, environment and outcome are not touched.
The CORE file of a crash is not read here: tests/_crash_cores.py lifts the core limit of the whole pytest session (every engine inherits it, the core's
launches included) and, after the test fails, saves gdb's text of every core in `$INVPW_CORE_DIR` under `invpw-evidence/cores/<test>/`.
Saving is best effort: it never raises and never decides a test (the assertion of the test, or the core's error, does).
"""
from __future__ import annotations
import contextlib
import importlib
import os
import shutil
import subprocess
import sys
import time
from pathlib import Path
import _crash_cores
#: The folder under `$RUNNER_TEMP` the e2e workflows upload (`invpw-evidence-*`).
EVIDENCE_FOLDER = "invpw-evidence"
RESULT_NAME = "securitystate-result.json"
STATE_DIR = "security_state"
def evidence_folder(name, fallback):
"""`$RUNNER_TEMP/invpw-evidence/<name>` on a runner, `<fallback>/<name>` elsewhere; made here."""
base = os.environ.get("RUNNER_TEMP")
folder = (Path(base) / EVIDENCE_FOLDER if base else Path(fallback)) / name
folder.mkdir(parents=True, exist_ok=True)
return folder
def _profile_of(argv):
argv = [str(part) for part in argv]
return Path(argv[argv.index("-profile") + 1]) if "-profile" in argv[:-1] else None
def snapshot_the_profile(profile, into):
"""The files of `profile` (path, size) in `into/profile-files.tsv`, with the result, `user.js` and `security_state/` copied: what the engine left, kept before
anybody deletes the profile. One line saying what was done."""
into.mkdir(parents=True, exist_ok=True)
if profile is None or not Path(profile).is_dir():
return "no profile directory (%s)" % (profile,)
profile = Path(profile)
listing = ["%s\t%d" % (path.relative_to(profile).as_posix(), path.stat().st_size) for path in sorted(profile.rglob("*")) if path.is_file()]
(into / "profile-files.tsv").write_text("\n".join(listing) + "\n", encoding="utf-8")
for name in (RESULT_NAME, "user.js"):
if (profile / name).is_file():
shutil.copyfile(str(profile / name), str(into / name))
if (profile / STATE_DIR).is_dir():
shutil.copytree(str(profile / STATE_DIR), str(into / STATE_DIR), dirs_exist_ok=True)
return "profile files: %d" % len(listing)
def save_what_the_failed_generation_left(profile, output, code, why, folder, *, snapshot=None):
"""ONLY after a generation that failed: `<output>.stdout` and `<output>.stderr` copied as `engine.stdout`/`engine.stderr` and the profile's files (from
`profile`, or from a `snapshot` folder made by `snapshot_the_profile` when the profile is gone); `notes.txt` says what was found, and where the core of a
crash goes. Never raises."""
notes = ["exit code %r; %s" % (code, why or "the engine exited")]
try:
for suffix in (".stdout", ".stderr"):
source = Path(str(output) + suffix)
if source.is_file():
shutil.copyfile(str(source), str(folder / ("engine" + suffix)))
notes.append("%s: %d bytes" % (source.name, source.stat().st_size))
else:
notes.append("%s: not written" % source.name)
if snapshot is not None and Path(snapshot).is_dir():
shutil.copytree(str(snapshot), str(folder), dirs_exist_ok=True)
notes.append("profile: as the engine left it at its exit (the core deleted it afterwards)")
else:
notes.append(snapshot_the_profile(profile, folder))
notes.append(where_the_core_goes())
except Exception as exc: # the evidence is best effort: the test reports the failure
notes.append("saving the evidence failed: %r" % (exc,))
with open(str(folder / "notes.txt"), "a", encoding="utf-8") as sink:
sink.write("\n".join(notes) + "\n")
def where_the_core_goes():
"""One line for `notes.txt`: where the core of a crash is read (Linux), or that there is none to read (elsewhere)."""
if not sys.platform.startswith("linux"):
return "core files: Linux only (tests/_crash_cores.py); none is looked for on %s" % sys.platform
return "core file: read by tests/_crash_cores.py after the test fails, into invpw-evidence/cores/<test>/ (INVPW_CORE_DIR %r, kernel.core_pattern %r, gdb %s)" % (
os.environ.get("INVPW_CORE_DIR"), _crash_cores.core_pattern(), _crash_cores.gdb())
class _Subprocess:
"""The `subprocess` the core's module sees while the wrapper is in force: the real module, with `Popen` replaced."""
def __init__(self, popen):
self.Popen = popen
def __getattr__(self, name):
return getattr(subprocess, name)
@contextlib.contextmanager
def the_core_s_generation_keeps_its_evidence(work, name):
"""While in force, every engine the core's `generate` starts writes its stdout and stderr to files of `work` and has the files of its profile noted when it
exits; if the block raises (the core's `GenerationError`), each launch is saved in the evidence folder `name` and the
exception goes on unchanged. Yields the list of the launches (dicts: argv, output, started_at, code, snapshot)."""
module = importlib.import_module("invisible_core._security_state_generate")
work = Path(work)
work.mkdir(parents=True, exist_ok=True)
launches = []
real_popen = subprocess.Popen
real_module, real_wait = module.subprocess, module._wait_for_exit
def popen(argv, *args, **kwargs):
output = work / ("engine-%d" % len(launches))
launch = {"argv": [str(part) for part in argv], "output": output, "started_at": time.time(), "code": "not exited", "snapshot": None}
launches.append(launch)
sinks = [open(str(output) + ".stdout", "wb"), open(str(output) + ".stderr", "wb")]
kwargs["stdout"], kwargs["stderr"] = sinks
try:
proc = real_popen(argv, *args, **kwargs)
finally:
for sink in sinks:
sink.close()
launch["proc"] = proc
return proc
def wait_for_exit(proc, timeout_s):
code = real_wait(proc, timeout_s)
for launch in launches:
if launch.get("proc") is proc:
launch["code"] = code
launch["snapshot"] = work / ("engine-%d-profile" % launches.index(launch))
try:
snapshot_the_profile(_profile_of(launch["argv"]), launch["snapshot"])
except Exception: # best effort, as every save here
launch["snapshot"] = None
return code
module.subprocess, module._wait_for_exit = _Subprocess(popen), wait_for_exit
try:
yield launches
except BaseException as exc:
folder = evidence_folder(name, work)
with open(str(folder / "notes.txt"), "a", encoding="utf-8") as sink:
sink.write("the core's generate raised %s: %s\nlaunches of the engine: %d\n" % (type(exc).__name__, exc, len(launches)))
for index, launch in enumerate(launches):
target = folder if len(launches) == 1 else folder / ("launch-%d" % index)
target.mkdir(parents=True, exist_ok=True)
with open(str(target / "notes.txt"), "a", encoding="utf-8") as sink:
sink.write("argv: %r\n" % (launch["argv"],))
save_what_the_failed_generation_left(_profile_of(launch["argv"]), launch["output"], launch["code"], str(exc), target, snapshot=launch["snapshot"])
raise
finally:
module.subprocess, module._wait_for_exit = real_module, real_wait
+15 -152
View File
@@ -7,13 +7,6 @@ later one read `h3` (retail Firefox 159, native DNS in loopback: h2, h3, h3; beh
came from: a connection that comes from anywhere but the relay of a gateway on this host (127.0.0.1) did not go through
the proxy.
A client that has a QUIC handshake in progress toward the server is served its next TCP connection only once that handshake has ended (``_QuicFirst``): a real network completes
QUIC in 1 round trip and TCP+TLS in 2, and a browser takes the first connection that is ready.
It also keeps its own record of what it saw (``H3Server.record``, ``write_record``): per TCP connection its accept, the ALPN, every request
path and its end, per QUIC connection its first datagram, its handshake, every request and its end (with the reason), each with ``m``
(``time.perf_counter()`` of the test process) and ``t`` (``time.time()``). It only listens: no answer depends on it.
Needs `aioquic` and `h2` (pip install aioquic h2; the dev extra installs both).
"""
from __future__ import annotations
@@ -21,17 +14,14 @@ from __future__ import annotations
import asyncio
import datetime
import ipaddress
import itertools
import json
import socket
import socketserver
import ssl
import sys
import tempfile
import threading
import time
from pathlib import Path
from typing import Dict, List, Tuple
from typing import List, Tuple
from _ports import bind_tcp_and_hold_udp
@@ -60,50 +50,6 @@ 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>"
class _QuicFirst:
"""Keeps the order of a real network between the two connections a browser opens to one server: QUIC is ready after 1 round trip and TCP+TLS after 2, so the QUIC one is
taken. The Python QUIC server of the lab needs longer than TCP+TLS under load and would invert that. For a peer address that has a QUIC handshake in progress toward the
server, the TLS of a new TCP connection from that address waits until the handshake has ended. It waits for an event, never for a time: ``ended`` is called when the
handshake completes (the client has had its connection ready for a round trip by then), fails, or the connection terminates (the idle timeout is one of them), and
``release_all`` when the server closes. With no handshake in progress for the address nothing is held.
The residual case: a client that starts a QUIC handshake and vanishes without a CONNECTION_CLOSE leaves its handshake in progress, so the TCP connections of the same
IP are held until the QUIC idle timeout ends the connection (aioquic: 60 s by default, ``H3Server(quic_idle_timeout=...)``). A real network does not hold the TCP of a
client for that long, but a client of the lab that opens QUIC and goes away is not one a test of the lab depends on; it is measured, with the order asserted and not a
duration, in tests/test_the_h3_lab_server_lets_quic_finish_first.py."""
def __init__(self):
self._changed = threading.Condition()
self._in_progress: Dict[str, int] = {}
self._closed = False
def began(self, peer: str) -> None:
with self._changed:
self._in_progress[peer] = self._in_progress.get(peer, 0) + 1
def ended(self, peer: str) -> None:
with self._changed:
left = self._in_progress.get(peer, 0) - 1
if left > 0:
self._in_progress[peer] = left
else:
self._in_progress.pop(peer, None)
self._changed.notify_all()
def hold(self, peer: str, held: List[str]) -> None:
"""Returns at once when no QUIC handshake of ``peer`` is in progress; otherwise records the hold in ``held`` and returns when none is."""
with self._changed:
if peer not in self._in_progress or self._closed:
return
held.append(peer)
self._changed.wait_for(lambda: self._closed or peer not in self._in_progress)
def release_all(self) -> None:
with self._changed:
self._closed = True
self._changed.notify_all()
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"
@@ -125,36 +71,29 @@ class _TcpHandler(socketserver.BaseRequestHandler):
def handle(self):
owner = self.server.owner
cid = "tcp-%d" % next(owner._ids)
owner.note("tcp_accept", conn=cid, peer=list(self.client_address[:2]))
reason = "handler ended"
try:
owner._quic_first.hold(self.client_address[0], owner.tcp_held)
self.request.settimeout(10)
tls = owner._tls.wrap_socket(self.request, server_side=True)
except (ssl.SSLError, OSError) as exc:
owner.note("tcp_handshake_failed", conn=cid, error=repr(exc))
except (ssl.SSLError, OSError):
return
try:
tls.settimeout(60)
alpn = tls.selected_alpn_protocol() or "http/1.1"
owner.tcp_alpn.append(alpn)
owner.note("tcp_handshake_done", conn=cid, alpn=alpn)
if alpn == "h2":
reason = self._h2(tls, owner, cid)
self._h2(tls, owner)
else:
reason = self._http1(tls, owner, cid)
except (ssl.SSLError, OSError) as exc:
reason = "error: %r" % (exc,)
self._http1(tls, owner)
except (ssl.SSLError, OSError):
pass
finally:
owner.note("tcp_close", conn=cid, reason=reason)
try:
tls.close()
except OSError:
pass
@staticmethod
def _h2(tls, owner, cid):
def _h2(tls, owner):
import h2.config
import h2.connection
import h2.events
@@ -166,16 +105,15 @@ class _TcpHandler(socketserver.BaseRequestHandler):
while True:
data = tls.recv(65536)
if not data:
return "the client closed the connection (EOF)"
return
try:
events = conn.receive_data(data)
except h2.exceptions.ProtocolError as exc:
except h2.exceptions.ProtocolError:
tls.sendall(conn.data_to_send())
return "h2 protocol error: %r" % (exc,)
return
for event in events:
if isinstance(event, h2.events.RequestReceived):
owner.tcp_requests.append(dict(event.headers).get(":path", ""))
owner.note("tcp_request", conn=cid, stream=event.stream_id, path=dict(event.headers).get(":path", ""))
conn.send_headers(event.stream_id, [
(":status", "200"), ("content-type", "text/html; charset=utf-8"),
("content-length", str(len(PAGE))), ("alt-svc", owner.alt_svc),
@@ -184,13 +122,13 @@ class _TcpHandler(socketserver.BaseRequestHandler):
elif isinstance(event, h2.events.DataReceived):
conn.acknowledge_received_data(event.flow_controlled_length, event.stream_id)
elif isinstance(event, h2.events.ConnectionTerminated):
return "h2 GOAWAY from the client (error code %s)" % (event.error_code,)
return
out = conn.data_to_send()
if out:
tls.sendall(out)
@staticmethod
def _http1(tls, owner, cid):
def _http1(tls, owner):
head = b""
while b"\r\n\r\n" not in head:
chunk = tls.recv(4096)
@@ -202,20 +140,18 @@ class _TcpHandler(socketserver.BaseRequestHandler):
tls.sendall(b"HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: %d\r\n"
b"Alt-Svc: %s\r\nAccess-Control-Allow-Origin: *\r\nConnection: close\r\n\r\n%s"
% (len(PAGE), owner.alt_svc.encode(), PAGE))
return "answered, Connection: close"
class H3Server:
"""TCP+TLS (HTTP/2) and QUIC (HTTP/3) on one port of `address`."""
def __init__(self, address: str, quic_idle_timeout: float = None):
"""``quic_idle_timeout`` (seconds) is the QUIC idle timeout of the server; None keeps aioquic's default (60 s)."""
def __init__(self, address: str):
from aioquic.asyncio.protocol import QuicConnectionProtocol
from aioquic.asyncio.server import QuicServer
from aioquic.h3.connection import H3_ALPN, H3Connection
from aioquic.h3.events import HeadersReceived
from aioquic.quic.configuration import QuicConfiguration
from aioquic.quic.events import ConnectionTerminated, HandshakeCompleted, ProtocolNegotiated
from aioquic.quic.events import ProtocolNegotiated
self.address = address
#: The address each QUIC connection came from.
@@ -223,22 +159,11 @@ class H3Server:
#: The same peers with the port they sent from: (address, port). On a machine where a gateway's relay sends from an address of
#: this host (Windows cannot send from 127.0.0.1 to it) the address cannot tell the relay from a client that came direct; its port can.
self.quic_peer_addrs: List[Tuple[str, int]] = []
#: EVERY datagram that reached the UDP port, whether or not a QUIC handshake came out of it: (address, port) of the sender. A browser
#: that TRIES h3 sends its Initial here before anything else, so this list is the attempt itself, the one signal of "the engine tried
#: HTTP/3" that does not depend on the attempt succeeding or on how long it takes; ``quic_peers`` only has the connections that
#: negotiated an ALPN (an attempt that never completes is not in it).
self.udp_datagrams: List[Tuple[str, int]] = []
#: The paths of the requests that were answered over HTTP/3, and over TCP.
self.h3_requests: List[str] = []
self.tcp_requests: List[str] = []
#: The ALPN each TCP connection negotiated ("h2", or "http/1.1").
self.tcp_alpn: List[str] = []
#: The peer address of each TCP connection whose TLS was held until a QUIC handshake of that address had ended (see ``_QuicFirst``).
self.tcp_held: List[str] = []
self._quic_first = _QuicFirst()
#: The server's own record of what it saw, in order (``note``): a list of dicts, each with ``m``, ``t`` and ``kind``.
self.record: List[dict] = []
self._ids = itertools.count(1)
self._dir = tempfile.TemporaryDirectory()
cert, key = _certificate(address, Path(self._dir.name))
@@ -261,47 +186,8 @@ class H3Server:
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._http = None
#: The address whose handshake this connection holds open in ``_quic_first``; None before its first datagram and once the handshake has ended.
self._handshaking = None
self._began = False
self._cid = "quic-%d" % next(server._ids)
self._datagrams = 0
self._last_datagram_m = None
def datagram_received(self, data, addr):
self._datagrams += 1
self._last_datagram_m = round(time.perf_counter(), 6)
if self._datagrams == 1:
server.note("quic_first_datagram", conn=self._cid, peer=list(addr[:2]), bytes=len(data))
# The first datagram of a peer is the start of its handshake: it is registered before the server answers it.
if not self._began:
self._began = True
self._handshaking = addr[0]
server._quic_first.began(addr[0])
super().datagram_received(data, addr)
# A close (the peer's, or ours after a failed handshake) ends the handshake before the event of the end of the connection.
if self._quic._close_event is not None:
self._handshake_ended()
def _handshake_ended(self):
if self._handshaking is not None:
peer, self._handshaking = self._handshaking, None
server._quic_first.ended(peer)
def quic_event_received(self, event):
if isinstance(event, (HandshakeCompleted, ConnectionTerminated)):
self._handshake_ended()
kind = type(event).__name__
if isinstance(event, ProtocolNegotiated):
server.note("quic_protocol_negotiated", conn=self._cid, alpn=event.alpn_protocol, datagrams=self._datagrams)
elif kind == "HandshakeCompleted":
server.note("quic_handshake_done", conn=self._cid, alpn=getattr(event, "alpn_protocol", None),
datagrams=self._datagrams)
elif kind == "ConnectionTerminated":
server.note("quic_close", conn=self._cid, error_code=event.error_code, frame_type=event.frame_type,
reason=event.reason_phrase, datagrams=self._datagrams, last_datagram_m=self._last_datagram_m)
elif kind == "StreamReset":
server.note("quic_stream_reset", conn=self._cid, stream=event.stream_id, error_code=event.error_code)
if isinstance(event, ProtocolNegotiated):
self._http = H3Connection(self._quic)
peer = self._quic._network_paths[0].addr
@@ -312,21 +198,13 @@ class H3Server:
if isinstance(http_event, HeadersReceived):
headers = dict(http_event.headers)
server.h3_requests.append(headers.get(b":path", b"").decode())
server.note("quic_request", conn=self._cid, stream=http_event.stream_id, path=server.h3_requests[-1])
self._http.send_headers(http_event.stream_id, [
(b":status", b"200"), (b"content-type", b"text/html; charset=utf-8"),
(b"access-control-allow-origin", b"*")])
self._http.send_data(http_event.stream_id, PAGE, end_stream=True)
self.transmit()
class Recording(QuicServer):
def datagram_received(self, data, addr):
server.udp_datagrams.append((addr[0], addr[1]))
super().datagram_received(data, addr)
configuration = QuicConfiguration(is_client=False, alpn_protocols=H3_ALPN)
if quic_idle_timeout is not None:
configuration.idle_timeout = quic_idle_timeout
configuration.load_cert_chain(str(cert), str(key))
self._loop = asyncio.new_event_loop()
started = threading.Event()
@@ -335,7 +213,7 @@ class H3Server:
asyncio.set_event_loop(self._loop)
# What ``aioquic.asyncio.serve(address, port)`` does (1.x), with the socket that already holds the number.
_transport, self._quic = self._loop.run_until_complete(self._loop.create_datagram_endpoint(
lambda: Recording(configuration=configuration, create_protocol=Protocol), sock=self._udp))
lambda: QuicServer(configuration=configuration, create_protocol=Protocol), sock=self._udp))
started.set()
try:
self._loop.run_forever()
@@ -358,22 +236,7 @@ class H3Server:
def url(self) -> str:
return "https://%s:%d/" % (self.address, self.port)
def note(self, kind: str, **fields) -> None:
"""One line of the server's record: ``m`` is ``time.perf_counter()`` of this process, ``t`` the wall clock. Never raises."""
try:
self.record.append({"m": round(time.perf_counter(), 6), "t": round(time.time(), 4), "kind": kind, **fields})
except Exception:
pass
def write_record(self, path) -> None:
"""The record as JSON lines (what the failure evidence of a test keeps)."""
with open(path, "w", encoding="utf-8") as out:
for line in list(self.record):
out.write(json.dumps(line, default=str) + "\n")
def close(self) -> None:
self._quic_first.release_all()
self.note("server_close", quic_connections=len(self.quic_peers), tcp_connections=len(self.tcp_alpn))
self._tcp.shutdown()
self._tcp.server_close()
if not self._loop.is_closed():
-213
View File
@@ -1,213 +0,0 @@
"""The pieces the e2e tests of the language and the zone a context declares share.
* ``serve(routes)``: a local HTTP server on a port the OS gives, answering a table of paths (the query is ignored), each with its bytes, its type
and, if the test needs them, extra headers. Nothing leaves the machine.
* ``open_chrome(port)`` / ``chrome(...)`` / ``set_pref(...)``: the engine's own chrome scope through Marionette, for what no protocol command of
the wrapper does: writing ``intl.accept_languages`` while a session runs, and ``content_process_prefs(...)``: what a pref holds in the
content process of each tab asked for (the proof that a process has taken a change, read from the process itself).
* ``read_in_page_realm(page, body)``: runs ``body`` as an inline ``<script>`` of the page, so in the page's own realm, and returns what it
wrote into the DOM. ``page.evaluate`` is not the page's realm on this engine; an inline script is what a site runs.
* the measuring scripts of the canvas tests (``MEASURE_JS``): the width of a few strings as a canvas of one language group draws them.
No clock, no port written as a number, no environment written here.
"""
from __future__ import annotations
import http.server
import json
import threading
from typing import Any, Dict, Tuple, Union
import webfont_probe
#: What the launch of a browser whose chrome scope is read through Marionette is given (the env var MOZ_REMOTE_ALLOW_SYSTEM_ACCESS
#: is set by the test with ``monkeypatch``).
MARIONETTE_ARGS = ["-marionette", "-remote-allow-system-access"]
Route = Union[bytes, Tuple[bytes, str], Tuple[bytes, str, Dict[str, str]]]
def serve(routes: Dict[str, Route]):
"""A server for ``routes``; returns ``(server, base_url)``. Stop it with :func:`stop`."""
class Handler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
path = self.path.split("?", 1)[0]
route = routes.get(path)
if route is None:
self.send_response(404)
self.send_header("Content-Length", "0")
self.end_headers()
return
if isinstance(route, bytes):
route = (route, "text/html; charset=utf-8")
body, kind = route[0], route[1]
extra = route[2] if len(route) > 2 else {}
self.send_response(200)
self.send_header("Content-Type", kind)
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-store")
for name, value in extra.items():
self.send_header(name, value)
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
server.daemon_threads = True
threading.Thread(target=server.serve_forever, daemon=True).start()
return server, "http://127.0.0.1:%d" % server.server_address[1]
def stop(server) -> None:
server.shutdown()
server.server_close()
PAGE = b"<!doctype html><html><head><meta charset=utf-8><title>t</title></head><body><p id=p>t</p></body></html>"
# ----------------------------------------------------------------------------------------------------------------- the chrome scope
def open_chrome(port: int):
"""A Marionette session in chrome scope on the engine that listens on ``port``."""
marionette = webfont_probe._Marionette(port)
marionette.call("WebDriver:NewSession", {"capabilities": {"alwaysMatch": {}}})
marionette.call("WebDriver:SetTimeouts", {"script": 240000})
marionette.call("Marionette:SetContext", {"value": "chrome"})
return marionette
def chrome(marionette, script: str, *args: Any) -> Any:
"""Run ``script`` (the body of a function that returns ``JSON.stringify(...)``) in chrome scope; its answer, decoded."""
return json.loads(marionette.call("WebDriver:ExecuteScript", {"script": script, "args": list(args)})["value"])
SET_STRING_PREF_JS = """
const [name, value] = arguments;
Services.prefs.setStringPref(name, value);
return JSON.stringify(Services.prefs.getStringPref(name));
"""
def set_pref(marionette, name: str, value: str) -> str:
return chrome(marionette, SET_STRING_PREF_JS, name, value)
#: What the content process of each tab holds for a pref, read in that process. ``arguments``: the pref's name and the labels of the tabs; a tab is
#: found by its address ending in ``?<label>``. A process script (``Services.ppmm.loadProcessScript``, a data: URL, only the processes that exist)
#: runs in every process and sends back its pid and the value ``Services.prefs`` of THAT process gives; the answer comes when each tab's process
#: has answered. The parent sends a pref change to a content process before this message on the same channel, and the process applies it
#: (and runs its observers) before it runs the script, so a process that answers has handled the change.
PROCESS_PREFS_JS = """
const [name, labels] = arguments;
const done = arguments[arguments.length - 1];
const wanted = {};
for (const win of Services.wm.getEnumerator('navigator:browser')) {
for (const tab of win.gBrowser.tabs) {
const spec = tab.linkedBrowser.currentURI.spec;
const wg = tab.linkedBrowser.browsingContext && tab.linkedBrowser.browsingContext.currentWindowGlobal;
for (const label of labels) {
if (spec.endsWith('?' + label) && wg && wg.domProcess) { wanted[label] = wg.domProcess.osPid; }
}
}
}
const missing = labels.filter((label) => !(label in wanted));
if (missing.length) { done(JSON.stringify({missing})); return; }
const KEY = 'invisible-probe:pref';
const answers = {};
const listener = {
receiveMessage(message) {
answers[message.data.pid] = message.data.value;
if (Object.values(wanted).every((pid) => pid in answers)) {
Services.ppmm.removeMessageListener(KEY, listener);
const prefs = {};
for (const [label, pid] of Object.entries(wanted)) { prefs[label] = answers[pid]; }
done(JSON.stringify({pids: wanted, prefs}));
}
},
};
Services.ppmm.addMessageListener(KEY, listener);
const body = 'sendAsyncMessage(' + JSON.stringify(KEY) + ', {pid: Services.appinfo.processID, value: Services.prefs.getStringPref(' + JSON.stringify(name) + ', "")});';
Services.ppmm.loadProcessScript('data:,' + encodeURIComponent(body), false);
"""
def content_process_prefs(marionette, name: str, labels) -> Dict[str, Any]:
"""``{"pids": {label: pid}, "prefs": {label: value}}``: what pref ``name`` holds in the content process of each tab whose address ends with
``?<label>`` (or ``{"missing": [labels]}`` when a tab is not there)."""
answer = marionette.call("WebDriver:ExecuteAsyncScript", {"script": PROCESS_PREFS_JS, "args": [name, list(labels)]})
return json.loads(answer["value"])
# -------------------------------------------------------------------------------------------------------------------- the page realm
def read_in_page_realm(page, body: str, name: str = "read") -> Any:
"""What ``body`` (the body of a function that returns a JSON-able value) gives when an inline script of the page runs it."""
page.add_script_tag(content=("document.documentElement.setAttribute('data-%s', JSON.stringify((() => {%s})()));" % (name, body)))
return json.loads(page.evaluate("n => document.documentElement.getAttribute('data-' + n)", name))
# ------------------------------------------------------------------------------------------------------------------------ the workers
#: A dedicated worker that answers every message with the language its realm and its navigator speak.
LANG_WORKER = b"""
onmessage = () => postMessage({languages: [...navigator.languages],
intl: Intl.DateTimeFormat().resolvedOptions().locale});
"""
#: Starts that worker in the page and leaves ``window.__ask()`` to ask it again; the worker lives as long as the page.
START_LANG_WORKER_JS = """() => {
window.__worker = new Worker('/lang-worker.js');
window.__ask = () => new Promise((ok) => {
window.__worker.onmessage = (e) => ok(e.data);
window.__worker.postMessage(0);
});
}"""
ASK_LANG_WORKER_JS = "() => window.__ask()"
# ----------------------------------------------------------------------------------------------------------------------- the canvases
#: The width of a few strings, in two generic families, as a canvas of ONE language group draws them: Latin text (the generic serif of each
#: group is another font), full-width Han, kana, half-width kana. ``widths(canvas)`` takes the 2D context's canvas, a main-thread or a
#: worker's OffscreenCanvas, or an element: the font is resolved the way each of them resolves it, which is what the tests compare.
MEASURE_JS = """
const STRINGS = ['Hamburgefonstiv', '\\u6f22\\u5b57', '\\u3042\\u3044\\u3046', '\\uff71\\uff72\\uff73', '\\u76f4\\u9aa8'];
function widths(context) {
const out = {};
for (const font of ['20px serif', '20px sans-serif']) {
context.font = font;
out[font] = STRINGS.map((s) => context.measureText(s).width);
}
return out;
}
"""
#: A dedicated worker that measures on its own OffscreenCanvas and answers with the widths.
MEASURE_WORKER = (MEASURE_JS + """
onmessage = () => postMessage(widths(new OffscreenCanvas(300, 60).getContext('2d')));
""").encode()
#: In the page: the worker's widths, the widths of an OffscreenCanvas of the main thread (no element, no ``lang``), and the widths of a canvas
#: ELEMENT whose ``lang`` is each of the two languages asked for.
MEASURE_PAGE_JS = """async (languages) => {
%s
const worker = await new Promise((ok) => {
const w = new Worker('/measure-worker.js');
w.onmessage = (e) => { ok(e.data); w.terminate(); };
w.postMessage(0);
});
const offscreen = widths(new OffscreenCanvas(300, 60).getContext('2d'));
const element = {};
for (const lang of languages) {
const c = document.createElement('canvas');
c.setAttribute('lang', lang);
document.body.appendChild(c);
element[lang] = widths(c.getContext('2d'));
}
return {worker, offscreen, element};
}""" % MEASURE_JS
-165
View File
@@ -1,165 +0,0 @@
"""A passive listener on the mDNS group (224.0.0.251, UDP 5353): what the lab heard of the engine's responder, packet by packet.
Failure evidence of ``tests/test_declared_host_network_e2e.py``. The engine's responder (dom/media/webrtc/transport/mdns_service/src/lib.rs) is
not heard in a release build: its ``trace!`` lines are compiled out (``release_max_level_info``), so the lab listens to the group itself.
IT ONLY LISTENS. It never sends a packet, never answers, never sets a multicast interface or the loop flag (those are the sender's), and it never raises:
every refusal (a bind, a join, a read, a parse) is written into its own record and the test goes on unchanged.
HOW IT BINDS, against the engine's own socket (lib.rs:124-135): the engine makes a UDP socket with SO_REUSEADDR, SO_REUSEPORT where the system has it
(not on Windows) and binds 0.0.0.0:5353. Both sockets here set the same options, so two sockets share the port and each receives every datagram sent
to the group, and the listener takes nothing from the engine:
* Linux: SO_REUSEADDR and SO_REUSEPORT, bound to the group address 224.0.0.251:5353. A socket bound to a multicast address receives only datagrams
addressed to that group, never a unicast one, so it cannot take a datagram that was meant for the engine's wildcard socket.
* Windows: SO_REUSEADDR, bound to 0.0.0.0:5353 (a multicast address cannot be bound there). The listener is started BEFORE the browser is launched, so the
engine's socket is the later one: Windows gives a unicast datagram to the socket bound last, and the engine's responder sends and answers on the group
address only (lib.rs: ``send_to(&buf, mdns_addr)``).
It joins the group on the interfaces the engine joins on: ``mdns_service_start`` is given ``nr_stealth_mdns_interfaces()``, which is ``"127.0.0.1;"``
(dom/media/webrtc/transport/nr_stealth_network.cpp:229), and the engine joins each address it is given (lib.rs:138-145) and sends through the first
(lib.rs:150-153). So the listener joins on 127.0.0.1 and nothing else.
The record (``write``): JSON lines, the first line ``{"kind": "listener", ...}`` (how the bind and the join went, and the packet counts), then one
line per packet: ``m`` (``time.perf_counter()`` of the test process, the scale of the page timeline once joined by the launch's ``started_m``), ``t`` (wall
clock), ``src`` ([address, port]), ``bytes``, ``kind`` (``query``, ``response`` or ``unparsed``), ``id``, ``questions`` ([{name, type, unicast_bit}]) and
``answers`` ([{name, type, ttl, data}]) as read by a minimal DNS parse.
"""
from __future__ import annotations
import ipaddress
import json
import socket
import struct
import sys
import threading
import time
GROUP = "224.0.0.251"
#: The engine's group, and the one interface it joins on (nr_stealth_mdns_interfaces).
MDNS_ADDRESS = (GROUP, 5353)
JOIN_INTERFACE = "127.0.0.1"
_TYPES = {1: "A", 12: "PTR", 16: "TXT", 28: "AAAA", 33: "SRV", 255: "ANY"}
def _name(data: bytes, offset: int, depth: int = 0):
"""The domain name at ``offset`` (compression followed) and the offset after it in the record the name started in."""
labels, end, jumped = [], None, False
while True:
if offset >= len(data) or depth > 20:
raise ValueError("name out of range")
length = data[offset]
if length == 0:
offset += 1
break
if length & 0xC0 == 0xC0:
pointer = ((length & 0x3F) << 8) | data[offset + 1]
if end is None:
end = offset + 2
offset, jumped, depth = pointer, True, depth + 1
continue
labels.append(data[offset + 1: offset + 1 + length].decode("utf-8", "replace"))
offset += 1 + length
return ".".join(labels), (end if jumped else offset)
def parse(data: bytes) -> dict:
"""A DNS message, minimally: its id, whether it is a query or a response, the questions and the answers."""
identifier, flags, qd, an, ns, ar = struct.unpack("!6H", data[:12])
out = {"id": identifier, "kind": "response" if flags & 0x8000 else "query", "counts": [qd, an, ns, ar], "questions": [], "answers": []}
offset = 12
for _ in range(qd):
name, offset = _name(data, offset)
qtype, qclass = struct.unpack("!HH", data[offset: offset + 4])
offset += 4
out["questions"].append({"name": name, "type": _TYPES.get(qtype, qtype), "unicast_bit": bool(qclass & 0x8000)})
for _ in range(an + ns + ar):
name, offset = _name(data, offset)
rtype, _rclass, ttl, length = struct.unpack("!HHIH", data[offset: offset + 10])
offset += 10
raw = data[offset: offset + length]
if rtype == 1 and length == 4:
value = str(ipaddress.IPv4Address(raw))
elif rtype == 28 and length == 16:
value = str(ipaddress.IPv6Address(raw))
else:
value = raw.hex()
out["answers"].append({"name": name, "type": _TYPES.get(rtype, rtype), "ttl": ttl, "data": value})
offset += length
return out
class MdnsListener:
def __init__(self):
self.packets = []
#: What happened to the listener itself: the bind, the join, a read or a parse that failed. Never raised.
self.status = []
self._socket = None
self._thread = None
self._stop = threading.Event()
def start(self) -> "MdnsListener":
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if sys.platform != "win32" and hasattr(socket, "SO_REUSEPORT"):
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
sock.bind((GROUP if sys.platform != "win32" else "0.0.0.0", MDNS_ADDRESS[1]))
self.status.append({"what": "bound", "address": sock.getsockname()[0], "port": sock.getsockname()[1]})
except Exception as exc:
self.status.append({"what": "bind failed: the listener hears nothing", "error": repr(exc)})
return self
try:
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, socket.inet_aton(GROUP) + socket.inet_aton(JOIN_INTERFACE))
self.status.append({"what": "joined", "group": GROUP, "interface": JOIN_INTERFACE})
except Exception as exc:
self.status.append({"what": "join failed", "group": GROUP, "interface": JOIN_INTERFACE, "error": repr(exc)})
try:
sock.settimeout(0.2)
self._socket = sock
self._thread = threading.Thread(target=self._run, name="mdns-listener", daemon=True)
self._thread.start()
except Exception as exc:
self.status.append({"what": "no reader thread", "error": repr(exc)})
return self
def _run(self) -> None:
sock = self._socket
while not self._stop.is_set():
try:
data, source = sock.recvfrom(9000)
except socket.timeout:
continue
except Exception as exc:
if not self._stop.is_set():
self.status.append({"what": "read failed: the listener stops", "error": repr(exc)})
return
record = {"m": round(time.perf_counter(), 6), "t": round(time.time(), 4), "src": [source[0], source[1]], "bytes": len(data)}
try:
record.update(parse(data))
except Exception as exc:
record.update(kind="unparsed", error=repr(exc), hex=data[:64].hex())
self.packets.append(record)
def stop(self) -> None:
self._stop.set()
try:
if self._socket is not None:
self._socket.close()
except Exception:
pass
if self._thread is not None:
self._thread.join()
def summary(self) -> dict:
kinds = {}
for packet in list(self.packets):
kinds[packet["kind"]] = kinds.get(packet["kind"], 0) + 1
return {"packets": len(self.packets), "by_kind": kinds, "status": list(self.status)}
def write(self, path) -> None:
with open(path, "w", encoding="utf-8") as out:
out.write(json.dumps(dict(kind="listener", group=GROUP, join_interface=JOIN_INTERFACE, **self.summary()), default=str) + "\n")
for packet in list(self.packets):
out.write(json.dumps(packet, default=str) + "\n")
-69
View File
@@ -1,69 +0,0 @@
"""The `goto` of the tests of pages that move on their own (`test_a_page_that_moves_on_e2e.py`), and the model of where the frame goes."""
from __future__ import annotations
def _landing(url: str) -> str:
"""Where the page of `url` sends itself: /landed with the query of its round, which no other round of the module has."""
return "/landed" + url[url.index("?"):]
#: The pages (by address) the frame may still go with, for each page of the browser (by `id`): the page sent last when `goto` answered, and, from a
#: `goto` that raised, every page it may have gone with (`_goto`). `forget` takes a page out when its test ends: an `id` is reused.
_SENT: dict = {}
#: An optional hook for the evidence a failing test leaves: called as ``note(what, **fields)`` where `_goto` sends, hears the answer and hears the error.
#: The test module sets it; it only listens and changes no wait or assertion.
note = None
def forget(page) -> None:
_SENT.pop(id(page), None)
def _goto(page, url, *, the_page_before_may_move, our_page_may_stop_ours, **kwargs) -> frozenset:
"""`page.goto`, and the pages the frame may go with: ``{url}`` when `goto` answers.
- ``the_page_before_may_move``: the pages sent before ours may still be moving (the rounds of the read test go on
while they do, module docstring). A `location.replace` of one of them may win: `goto` says ours was interrupted by it, or
stopped (NS_BINDING_ABORTED), and the frame lands on the landing of THAT page.
- ``our_page_may_stop_ours``: an engine before firefox-68, where `goto` may say NS_BINDING_ABORTED for our own
document, which had committed and then moved
(`test_networkidle_is_reached_only_on_the_page_that_replaced_a_document_still_arriving`); the frame then lands on
our landing.
When `goto` raises, the frame may still go with EITHER page: Playwright raises "interrupted" as soon as a different navigation commits,
while ours goes on, commits and moves to its own landing (run 44688029161: x50-4 raised for the landing of x50-3, and the frame then
navigated to the landing of x50-4). Nothing here knows which one it is, so the pages that may be moving are all of the pages before and
ours, and the next round accepts the landing of any of them. Stock Playwright behaves the same: the model was the test's.
Any other answer is red: an error that is neither answer, an "interrupted" that names a page that cannot be moving, and a navigation that
never answers. The detector of that last one is the timeout of the `goto` itself (each caller passes one): a bound of the test stricter
than it only judged the speed of the machine."""
from invisible_playwright.sync_api import Error
before = _SENT.get(id(page), frozenset()) if the_page_before_may_move else frozenset()
if note:
note("goto", url=url, before=sorted(before))
try:
page.goto(url, **kwargs)
if note:
note("goto-answered", url=url)
except Error as e:
text = str(e)
if note:
note("goto-raised", url=url, error=text[:300])
if "NS_BINDING_ABORTED" in text:
ends = tuple(_landing(u) for u in sorted(before | ({url} if our_page_may_stop_ours else frozenset())))
assert ends, e
page.wait_for_url(lambda u: u.endswith(ends), timeout=30_000)
else:
assert before, e
assert "is interrupted by another navigation to" in text, e
named = text.split("another navigation to")[1]
assert any(_landing(u) in named for u in before), (e, sorted(before))
possible = before | {url}
else:
possible = frozenset({url})
_SENT[id(page)] = possible
return possible
-99
View File
@@ -1,99 +0,0 @@
"""Reads the engine's own Juggler trace (``INVISIBLE_JUGGLER_TRACE_DIR``, `Trace.js`) for the line the parent writes when it moves a navigation.
The parent decides, synchronously (``DocumentLoadListener::TriggerProcessSwitch``), that a document load leaves the docShell that started it, and
tells the registry (observer topic ``juggler-navigation-moved``). The registry writes one line in the trace:
{"proc": "parent", "where": "navigations", "what": "onNavigationMoved",
"detail": {"frameId": "mainframe-<browser id>", "navigationId": "nav-<load id>",
"origin": {"browsingContextId": <id>, "childId": <id>}}}
``origin`` is the browsing context the load LEFT and the child id of the process that held it (0 is the parent process). The load is found by the
address the client sent: the registry writes ``onDocumentRequest`` with the same ``navigationId`` and the ``url`` of the request. A docShell that tells
the end of a navigation tells it with a ``reporter`` of the same shape (``onNavigationAborted``, ``onStateChange abort``): the docShell the load left is
the one whose reporter is ``origin``.
"""
from __future__ import annotations
import json
import pathlib
WHERE = "navigations"
MOVED = "onNavigationMoved"
REQUESTED = "onDocumentRequest"
def read_trace(trace_dir) -> list:
"""Every line of every file of the engine's trace folder, as dicts. A line that is not whole (the engine may still be writing) is left out."""
lines = []
for path in sorted(pathlib.Path(trace_dir).glob("*.jsonl")):
for raw in path.read_text(encoding="utf-8", errors="replace").splitlines():
try:
line = json.loads(raw)
except ValueError:
continue
if isinstance(line, dict):
lines.append(line)
return lines
def _detail(line) -> dict:
detail = line.get("detail")
return detail if isinstance(detail, dict) else {}
def navigation_ids_of(lines, url) -> set:
"""The ids of the navigations whose document request was for exactly ``url``."""
return {_detail(l).get("navigationId") for l in lines
if l.get("where") == WHERE and l.get("what") == REQUESTED and _detail(l).get("url") == url} - {None}
def moved_lines(lines, navigation_ids=None) -> list:
"""The ``onNavigationMoved`` lines, all of them or those of the given navigations."""
return [l for l in lines if l.get("where") == WHERE and l.get("what") == MOVED
and (navigation_ids is None or _detail(l).get("navigationId") in navigation_ids)]
def reporters_of(lines, navigation_ids, frame_id) -> list:
"""The ``(browsingContextId, childId)`` of every docShell that told something about these navigations in this frame, in the lines that carry a ``reporter``."""
out = []
for l in lines:
d = _detail(l)
reporter = d.get("reporter")
if d.get("navigationId") in navigation_ids and d.get("frameId") == frame_id and isinstance(reporter, dict):
out.append((reporter.get("browsingContextId"), reporter.get("childId")))
return out
def moved_origin(lines, url) -> tuple:
"""-> ``(browsingContextId, childId)`` the load of ``url`` left, said by exactly one ``onNavigationMoved`` line of its navigation.
Raises AssertionError with what the trace holds when the load is not in the trace (nothing proves anything then), when no line or more than one
is for it, when the line is not of a main frame or its origin is not a browsing context in a child process, or when a docShell that told the end
of this navigation is not the one the load left."""
ids = navigation_ids_of(lines, url)
assert ids, "the trace has no document request for %s: the engine's trace is not on, or the navigation was not seen" % url
found = moved_lines(lines, ids)
assert len(found) == 1, "%d onNavigationMoved line(s) for %s (navigations %s): %s" % (len(found), url, sorted(ids), found)
detail = _detail(found[0])
origin = detail.get("origin") or {}
assert str(detail.get("frameId", "")).startswith("mainframe-"), found[0]
bc, child = origin.get("browsingContextId"), origin.get("childId")
assert isinstance(bc, int) and bc > 0, "the origin names no browsing context: %s" % found[0]
assert isinstance(child, int) and child > 0, "the origin is not a content process (0 is the parent process): %s" % found[0]
told = set(reporters_of(lines, ids, detail["frameId"]))
assert told <= {(bc, child)}, "a docShell other than the one the load left told its end: %s, the origin is %s" % (sorted(told), (bc, child))
return bc, child
def assert_replaced_in_the_same_process(before, after) -> None:
"""Two origins, ``(browsingContextId, childId)``, of two loads one after the other of the same top-level frame: the second load left the browsing
context the first one created (the parent replaces the browsing context of a top-level navigation that can enter the back/forward cache), in the
process the first one left, which is also the process it went on in (same site)."""
assert before[1] == after[1], "a same-site load left another process: %s then %s" % (before, after)
assert before[0] != after[0], "the browsing context was not replaced: %s then %s" % (before, after)
def assert_nothing_moved_since(lines, already) -> None:
"""``already`` is the number of ``onNavigationMoved`` lines the trace held when the load began: it holds no more."""
found = moved_lines(lines)
assert len(found) == already, "the engine told that a navigation moved, and none left its process: %s" % found[already:]
-228
View File
@@ -1,228 +0,0 @@
"""A test that is not e2e never leaves the machine: every connection, datagram and name lookup it makes goes to this host or is refused.
The markers say it already (pyproject.toml: ``unit`` is "no network", ``integration`` is "no network"), and nothing enforced it:
``tests/unit/test_config_public.py`` composed the default prefs with no declared exit, the core asked api.ipify.org and icanhazip.com
where it leaves from, and the test failed on a machine whose network refused them. A test cannot fail for the reasons of a third party.
:func:`install` patches the four doors of the standard library that every client in the process goes through (``socket.socket.connect``,
``connect_ex`` and ``sendto``, and ``socket.getaddrinfo``): a destination on this host passes, anything else is refused with
:class:`LeftTheMachine` (a ``ConnectionRefusedError``, so the code under test sees what an offline machine shows it) AND recorded, so the test
fails at its teardown even when the code under test swallowed the refusal. The record names the test, the door and the destination.
asyncio has doors of its own, and on Windows they skip the four above: the Proactor loop connects with ``ConnectEx`` and sends datagrams with
``WSASendTo`` (``_overlapped``), never through ``socket.socket``. So the guard also patches the loop methods every asyncio client goes through, for
both loop kinds: ``BaseEventLoop.create_connection`` and ``create_datagram_endpoint`` (``remote_addr``), ``sock_connect`` and ``sock_sendto`` of the
selector and of the Proactor loop, and the Proactor datagram transport's ``sendto``.
What it cannot see, on any system: a socket made from ``_socket`` directly or used through ``_overlapped`` by hand (no library of this project
does), native code in the same process, and a child process (a subprocess has its own interpreter: the e2e are where a browser runs).
On this host: a loopback address (127/8, ::1), the unspecified address (0.0.0.0, ::, which a connect reaches on this host), a name that is
``localhost`` or ends in ``.localhost``, and an AF_UNIX path. The documentation ranges (192.0.2/24, 198.51.100/24, 203.0.113/24, 2001:db8::/32)
pass too: they are never routed, and the lab gives one of them to an interface of this host (the exit of the lab, tests/_lab_egress.py).
And the address this host sends from (its default route's, tests/_host_address.py): a relay of the tests that leaves from the address of the
host is on this host, and a datagram to it never leaves the machine.
"""
from __future__ import annotations
import ipaddress
import socket
import threading
from typing import Any, List, Optional, Sequence, Tuple
_DOCUMENTATION = tuple(ipaddress.ip_network(n) for n in ("192.0.2.0/24", "198.51.100.0/24", "203.0.113.0/24", "2001:db8::/32"))
RULE = ("a test that is not e2e never leaves the machine (pyproject.toml markers: unit and integration are 'no network'): "
"a test cannot fail for the reasons of a third party")
FIX = ("declare the value the code would ask the network for (timezone=, locale=, proxy= with a local gateway), use a server of the tests "
"on loopback (tests/_servers.py, the local_egress_echo fixture), or mark the test e2e if it is one")
#: The ONE file whose job is to ask a third party, and the hosts it may ask. Nothing else is declared, and a new entry is a decision, not a fix.
#: ``tests/test_version_is_not_taken.py`` is the version gate of a pull request: it asks the index whether the version the change proposes
#: is already published, which only the index can answer. It is skipped unless ``IPW_CHECK_VERSION`` is set, which only the ``version`` job
#: of tests.yml does. Its host is allowed for its name lookup and for the addresses that lookup answered, nothing else.
DECLARED_THIRD_PARTIES = {
"tests/test_version_is_not_taken.py": ("pypi.org",),
}
class LeftTheMachine(ConnectionRefusedError):
"""A destination outside this host, refused by the guard of the tests."""
def own_addresses() -> Tuple[str, ...]:
"""The addresses this host sends from, IPv4 and IPv6 (the source its default route picks). A UDP connect sends no packet; a family with
no route has none. Read BEFORE the doors are patched."""
found = []
for family, probe in ((socket.AF_INET, ("192.0.2.1", 9)), (socket.AF_INET6, ("2001:db8::1", 9))):
try:
with socket.socket(family, socket.SOCK_DGRAM) as s:
s.connect(probe)
found.append(s.getsockname()[0].split("%", 1)[0])
except OSError:
pass
return tuple(found)
def is_on_this_host(host: Any, own: Sequence[str] = ()) -> bool:
"""Whether ``host`` (an address, a name, or None) is on this host, the way the guard decides it; ``own`` are the addresses of this host
(:func:`own_addresses`)."""
if host is None:
return True
if isinstance(host, bytes):
host = host.decode("ascii", "replace")
host = str(host).strip("[]").split("%", 1)[0]
if host == "" or host.lower() == "localhost" or host.lower().endswith(".localhost"):
return True
try:
address = ipaddress.ip_address(host)
except ValueError:
return False # a name: resolving it is already a question to the network
if getattr(address, "ipv4_mapped", None) is not None:
address = address.ipv4_mapped
return (address.is_loopback or address.is_unspecified or any(address in net for net in _DOCUMENTATION)
or any(address == ipaddress.ip_address(mine) for mine in own))
def _destination(address: Any, own: Sequence[str] = ()) -> Optional[str]:
"""``host:port`` of a socket address that leaves the machine, or None when it does not (AF_UNIX paths and this host)."""
if not isinstance(address, tuple) or not address:
return None # an AF_UNIX path or an abstract name: this host
host = address[0]
if is_on_this_host(host, own):
return None
return "%s:%s" % (host, address[1] if len(address) > 1 else "?")
class Guard:
"""The record of one test: what it tried outside the machine. Thread-safe: a client thread of the test is recorded too."""
def __init__(self, test: str) -> None:
self.test = test
self.attempts: List[str] = []
self._lock = threading.Lock()
def refuse(self, door: str, destination: str) -> LeftTheMachine:
sentence = "%s %s" % (door, destination)
with self._lock:
if sentence not in self.attempts:
self.attempts.append(sentence)
return LeftTheMachine("WHERE: %s. WHAT: %s, outside this host, refused. FIX: %s. RULE: %s." % (self.test, sentence, FIX, RULE))
def verdict(self) -> Optional[str]:
"""The failure of the test, or None when it stayed on this host."""
if not self.attempts:
return None
return ("WHERE: %s. WHAT: the test tried to leave the machine: %s (each was refused). FIX: %s. RULE: %s."
% (self.test, "; ".join(self.attempts), FIX, RULE))
def install(monkeypatch: Any, test: str) -> Guard:
"""Patch the four doors for the duration of ``monkeypatch``; return the record of ``test``."""
guard = Guard(test)
declared_hosts = DECLARED_THIRD_PARTIES.get(test.split("::", 1)[0].replace("\\", "/"), ())
answered = set() # the addresses a lookup of a declared host answered: a connection to them is that host
own = tuple(own_addresses())
def mine():
return own + tuple(answered)
connect, connect_ex, sendto, getaddrinfo = (socket.socket.connect, socket.socket.connect_ex, socket.socket.sendto,
socket.getaddrinfo)
def guarded_connect(self, address):
where = _destination(address, mine())
if where is not None:
raise guard.refuse("connect to", where)
return connect(self, address)
def guarded_connect_ex(self, address):
where = _destination(address, mine())
if where is not None:
raise guard.refuse("connect to", where)
return connect_ex(self, address)
def guarded_sendto(self, data, *rest):
where = _destination(rest[-1] if rest else None, mine())
if where is not None:
raise guard.refuse("datagram to", where)
return sendto(self, data, *rest)
def guarded_getaddrinfo(host, *args, **kwargs):
if isinstance(host, str) and host.lower() in declared_hosts:
found = getaddrinfo(host, *args, **kwargs)
answered.update(info[4][0] for info in found)
return found
if not is_on_this_host(host, mine()):
raise guard.refuse("name lookup of", str(host))
return getaddrinfo(host, *args, **kwargs)
_install_asyncio(monkeypatch, guard, mine)
monkeypatch.setattr(socket.socket, "connect", guarded_connect)
monkeypatch.setattr(socket.socket, "connect_ex", guarded_connect_ex)
monkeypatch.setattr(socket.socket, "sendto", guarded_sendto)
monkeypatch.setattr(socket, "getaddrinfo", guarded_getaddrinfo)
return guard
def _install_asyncio(monkeypatch: Any, guard: Guard, mine: Any) -> None:
"""The asyncio doors (module docstring), for the selector loop and, where it exists, the Proactor loop."""
import asyncio.base_events as base_events
import asyncio.selector_events as selector_events
loops = [selector_events.BaseSelectorEventLoop]
datagram_transports = []
try:
import asyncio.proactor_events as proactor_events
loops.append(proactor_events.BaseProactorEventLoop)
datagram_transports.append(proactor_events._ProactorDatagramTransport)
except ImportError: # pragma: no cover - the module exists on every system; its loop runs only on Windows
pass
create_connection = base_events.BaseEventLoop.create_connection
create_datagram_endpoint = base_events.BaseEventLoop.create_datagram_endpoint
async def guarded_create_connection(self, protocol_factory, host=None, port=None, *args, **kwargs):
if host is not None and kwargs.get("sock") is None and not is_on_this_host(host, mine()):
raise guard.refuse("asyncio connect to", "%s:%s" % (host, port))
return await create_connection(self, protocol_factory, host, port, *args, **kwargs)
async def guarded_create_datagram_endpoint(self, protocol_factory, local_addr=None, remote_addr=None, **kwargs):
where = _destination(remote_addr, mine())
if where is not None:
raise guard.refuse("asyncio datagram endpoint to", where)
return await create_datagram_endpoint(self, protocol_factory, local_addr=local_addr, remote_addr=remote_addr, **kwargs)
monkeypatch.setattr(base_events.BaseEventLoop, "create_connection", guarded_create_connection)
monkeypatch.setattr(base_events.BaseEventLoop, "create_datagram_endpoint", guarded_create_datagram_endpoint)
for loop in loops:
sock_connect, sock_sendto = loop.sock_connect, loop.sock_sendto
def make(sock_connect=sock_connect, sock_sendto=sock_sendto):
async def guarded_sock_connect(self, sock, address):
where = _destination(address, mine())
if where is not None:
raise guard.refuse("asyncio connect to", where)
return await sock_connect(self, sock, address)
async def guarded_sock_sendto(self, sock, data, address):
where = _destination(address, mine())
if where is not None:
raise guard.refuse("asyncio datagram to", where)
return await sock_sendto(self, sock, data, address)
return guarded_sock_connect, guarded_sock_sendto
guarded_sock_connect, guarded_sock_sendto = make()
monkeypatch.setattr(loop, "sock_connect", guarded_sock_connect)
monkeypatch.setattr(loop, "sock_sendto", guarded_sock_sendto)
for transport in datagram_transports:
def make_sendto(sendto=transport.sendto):
def guarded_sendto(self, data, addr=None):
where = _destination(addr, mine())
if where is not None:
raise guard.refuse("asyncio datagram to", where)
return sendto(self, data, addr)
return guarded_sendto
monkeypatch.setattr(transport, "sendto", make_sendto())
-200
View File
@@ -1,200 +0,0 @@
"""Where the operating system's own cursor is while a headed browser window is on the desktop the test runs on.
A real window that appears under the OS cursor receives a native ``WM_MOUSEMOVE`` for it, and the first native move of a process always passes Gecko's
``LastMouseMoveData`` filter, so the page sees ``mousemove`` at the cursor's place with ``buttons=0``, at a moment the test does not choose. On a GitHub
Windows runner the cursor sits at (512, 384) and the headed window covers (-8, -8) to (1928, 1040): the move reached the page once in the middle of a drag
(``test_drag_motion.py::test_a_real_page_sees_a_drag_that_travelled`` saw ``mousemove 512,299 buttons=0`` after the press). The engine keeps delivering native
input to content, so the arrangement is the test's: the cursor is parked on a point of the desktop that no window of the browser covers, before the browser
starts, and a test that records pointer events checks it still is when its gesture begins.
* Windows: ``user32`` through ctypes. The windows are the visible top-level ones of the processes below the test process (the browsers it launched), seen from
the desktop the test runs on: a ``headless=True`` browser runs on a Win32 desktop of its own (``make_virtual_display``), is not enumerated here and cannot
receive the interactive cursor.
* Linux and macOS: nothing to do. The Linux e2e run under ``xvfb-run``: an X server with virtual pointer and keyboard devices (XTEST) and no physical one,
so nothing moves a pointer there; every function answers "outside" and ``park`` does nothing.
"""
from __future__ import annotations
import ctypes
import os
import sys
from typing import List, Optional, Sequence, Tuple
#: ``(left, top, right, bottom)`` as ``GetWindowRect`` gives it: ``right`` and ``bottom`` are the first pixel outside.
Rect = Tuple[int, int, int, int]
Point = Tuple[int, int]
#: How far from every window the parked cursor is, in pixels: a window is moved or grown by a border or a shadow, and the cursor must stay outside of it.
MARGIN = 8
class TheCursorIsInside(AssertionError):
"""The OS cursor is over a window of the browser while a gesture is about to start."""
class TheCursorCannotBeParked(RuntimeError):
"""No point of the desktop is free of the browser's windows, or the system did not move the cursor."""
def _inflate(rect: Rect, margin: int) -> Rect:
return (rect[0] - margin, rect[1] - margin, rect[2] + margin, rect[3] + margin)
def _contains(rect: Rect, point: Point) -> bool:
return rect[0] <= point[0] < rect[2] and rect[1] <= point[1] < rect[3]
def cursor_is_outside(window_rects: Sequence[Rect], cursor: Optional[Point] = None, margin: int = 0, *,
api: Optional["_Win32"] = None) -> bool:
"""True when ``cursor`` (read from the system when None) is outside every rectangle, ``margin`` pixels beyond its edge included.
Not Windows: True, there is no OS cursor that reaches a window."""
if cursor is None:
api = api or _api()
if api is None:
return True
cursor = api.cursor_position()
return not any(_contains(_inflate(r, margin), cursor) for r in window_rects)
def park_outside(window_rects: Sequence[Rect], screen_rect: Rect, margin: int = MARGIN) -> Point:
"""A pixel of the virtual screen that is at least ``margin`` pixels from every window rectangle: the bottom-right corner when it is free.
``screen_rect`` is ``(left, top, right, bottom)`` of the virtual screen, ``right`` and ``bottom`` exclusive (its origin is negative when a monitor lies left of or
above the primary one). The candidates are the screen's edges and the places just beyond each window's inflated edges; a free pixel exists only if one
of them is free (the free pixel can be slid left and up until it touches an edge, and it stays free), so a ``TheCursorCannotBeParked`` is exact."""
left, top, right, bottom = screen_rect
if right <= left or bottom <= top:
raise TheCursorCannotBeParked(
"park_outside: the virtual screen %r is empty. Where: the screen rectangle read from the system. What: no pixel to put the cursor on. "
"Fix: run the e2e on an interactive desktop session." % (screen_rect,))
inflated = [_inflate(r, margin) for r in window_rects]
xs = sorted({right - 1, left, *(min(max(r[2], left), right - 1) for r in inflated), *(min(max(r[0] - 1, left), right - 1) for r in inflated)},
reverse=True)
ys = sorted({bottom - 1, top, *(min(max(r[3], top), bottom - 1) for r in inflated), *(min(max(r[1] - 1, top), bottom - 1) for r in inflated)},
reverse=True)
for y in ys:
for x in xs:
if not any(_contains(r, (x, y)) for r in inflated):
return (x, y)
raise TheCursorCannotBeParked(
"park_outside: the windows %r cover every pixel of the screen %r with a margin of %d. Where: the headed browser window the test launched. What: the "
"OS cursor would be over the page whatever the point, and a native mouse move would reach it. Fix: shrink the window below the screen (the test's own "
"geometry; it is not this helper's to change) or run the test on a bigger desktop." % (list(window_rects), screen_rect, margin))
class _Win32:
"""What the desktop answers, by ``user32``. One object so a test can stand a fake in for it."""
def __init__(self) -> None:
from ctypes import wintypes
self.wintypes = wintypes
self.user32 = ctypes.WinDLL("user32", use_last_error=True)
u = self.user32
u.GetCursorPos.argtypes = (ctypes.POINTER(wintypes.POINT),)
u.GetCursorPos.restype = wintypes.BOOL
u.SetCursorPos.argtypes = (ctypes.c_int, ctypes.c_int)
u.SetCursorPos.restype = wintypes.BOOL
u.GetSystemMetrics.argtypes = (ctypes.c_int,)
u.GetSystemMetrics.restype = ctypes.c_int
u.GetWindowRect.argtypes = (wintypes.HWND, ctypes.POINTER(wintypes.RECT))
u.GetWindowRect.restype = wintypes.BOOL
u.IsWindowVisible.argtypes = (wintypes.HWND,)
u.IsWindowVisible.restype = wintypes.BOOL
u.IsIconic.argtypes = (wintypes.HWND,)
u.IsIconic.restype = wintypes.BOOL
u.GetWindowThreadProcessId.argtypes = (wintypes.HWND, ctypes.POINTER(wintypes.DWORD))
u.GetWindowThreadProcessId.restype = wintypes.DWORD
self.enum_proc = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)
u.EnumWindows.argtypes = (self.enum_proc, wintypes.LPARAM)
u.EnumWindows.restype = wintypes.BOOL
def cursor_position(self) -> Point:
point = self.wintypes.POINT()
if not self.user32.GetCursorPos(ctypes.byref(point)):
raise TheCursorCannotBeParked(
"GetCursorPos failed (error %d). Where: user32, on the desktop the test runs on. What: the OS cursor cannot be read. Fix: run the e2e on an "
"interactive desktop session (not a locked screen or a service)." % ctypes.get_last_error())
return (point.x, point.y)
def set_cursor_position(self, x: int, y: int) -> None:
self.user32.SetCursorPos(x, y)
def screen(self) -> Rect:
"""The virtual screen: ``SM_XVIRTUALSCREEN``, ``SM_YVIRTUALSCREEN``, ``SM_CXVIRTUALSCREEN``, ``SM_CYVIRTUALSCREEN``."""
x, y, w, h = (self.user32.GetSystemMetrics(n) for n in (76, 77, 78, 79))
return (x, y, x + w, y + h)
def windows_below(self, root_pid: int) -> List[Rect]:
"""The rectangles of the visible, not minimised, top-level windows of the processes below ``root_pid``."""
import psutil
try:
pids = {p.pid for p in psutil.Process(root_pid).children(recursive=True)}
except psutil.Error:
return []
found: List[Rect] = []
def each(hwnd, _):
owner = self.wintypes.DWORD()
self.user32.GetWindowThreadProcessId(hwnd, ctypes.byref(owner))
if owner.value in pids and self.user32.IsWindowVisible(hwnd) and not self.user32.IsIconic(hwnd):
rect = self.wintypes.RECT()
if self.user32.GetWindowRect(hwnd, ctypes.byref(rect)) and rect.right > rect.left and rect.bottom > rect.top:
found.append((rect.left, rect.top, rect.right, rect.bottom))
return True
self.user32.EnumWindows(self.enum_proc(each), 0)
return found
def _is_windows() -> bool:
return sys.platform == "win32"
def _api() -> Optional[_Win32]:
return _Win32() if _is_windows() else None
def browser_windows(root_pid: Optional[int] = None, *, api: Optional[_Win32] = None) -> List[Rect]:
"""The rectangles of the windows of the browsers below ``root_pid`` (the test process by default) on this desktop; empty when not Windows."""
api = api or _api()
if api is None:
return []
return api.windows_below(os.getpid() if root_pid is None else root_pid)
def park(root_pid: Optional[int] = None, *, api: Optional[_Win32] = None) -> Optional[Point]:
"""Windows: put the OS cursor on a point no window of the browsers below ``root_pid`` covers and read it back. Returns the point; None when not Windows.
Called before the browser starts there is no window yet and the point is the bottom-right corner of the virtual screen, where the engine places no window."""
api = api or _api()
if api is None:
return None
target = park_outside(api.windows_below(os.getpid() if root_pid is None else root_pid), api.screen())
api.set_cursor_position(*target)
read_back = api.cursor_position()
if read_back != target:
raise TheCursorCannotBeParked(
"SetCursorPos(%d, %d) left the cursor at %r. Where: user32, on the desktop the test runs on. What: the OS cursor cannot be moved, so a native "
"mouse move for it can reach a window of the browser mid-gesture. Fix: run the e2e on an interactive desktop session (not a locked screen "
"or a service), with no other program holding the cursor." % (target[0], target[1], read_back))
return target
def require_outside(root_pid: Optional[int] = None, *, api: Optional[_Win32] = None, margin: int = 0) -> None:
"""The precondition of a gesture a test judges by the pointer events the page records: the OS cursor is outside every window of the browsers.
Raises ``TheCursorIsInside`` otherwise, with the cursor and the windows. Not Windows: nothing."""
api = api or _api()
if api is None:
return
windows = api.windows_below(os.getpid() if root_pid is None else root_pid)
cursor = api.cursor_position()
if not cursor_is_outside(windows, cursor, margin):
raise TheCursorIsInside(
"the OS cursor is at %r, inside the browser window(s) %r, when a pointer gesture is about to start. Where: the desktop the test runs on. What: "
"a native WM_MOUSEMOVE for it passes Gecko's first-move filter and reaches the page as a mousemove with buttons=0 at a moment of the "
"system's choosing, in the middle of the gesture the test records. Fix: park the cursor outside the window before the browser starts "
"(the autouse fixture `_the_os_cursor_is_outside_the_browser_window` of tests/conftest.py does it for every e2e test on Windows)." % (cursor, windows))
-186
View File
@@ -1,186 +0,0 @@
"""What the window e2e tests ask the operating system itself: which window holds the input focus, on a display of the test's own.
A page's ``document.hasFocus()`` is what the engine reports. A test that judges "the first session kept the focus when another one took the display" must
first know that the OS did give the focus to the second session's window; otherwise a green means only that nothing happened (the second window never took
it, or took it later than the read). The OS answers that without the engine:
* Linux: the X input focus (``XGetInputFocus`` on the display the sessions share); the display is a private Xvfb started for the test (``a_display_of_its_own``),
so no other test's headed window moves the focus in it. No window manager runs there, so nobody ever sets the X input focus: it stays ``PointerRoot``
and GDK activates whichever toplevel is under the pointer (``has_pointer_focus``, ``gdk/x11/gdkdevicemanager-core-x11.c``), and Firefox raises a window
itself only when it is not active already (``nsWindow::SetFocus``, ``gtk_window_present_with_time``). The test therefore does what a window manager does
when the user clicks a window: ``XSetInputFocus`` on the toplevel the step names (found by its ``_NET_WM_NAME``), and reads ``XGetInputFocus`` back;
* Windows: the foreground window (``GetForegroundWindow``), the window of the session found by the title its page gave it.
"""
from __future__ import annotations
import contextlib
import ctypes
import subprocess
import sys
import threading
from typing import Iterator, Optional
#: ``RevertToParent`` and ``CurrentTime`` of ``XSetInputFocus`` (as GDK's own ``gdk_x11_window_focus`` without a window manager); ``IsViewable``.
_REVERT_TO_PARENT, _CURRENT_TIME, _IS_VIEWABLE = 2, 0, 2
class _XWindowAttributes(ctypes.Structure):
_fields_ = [("x", ctypes.c_int), ("y", ctypes.c_int), ("width", ctypes.c_int), ("height", ctypes.c_int), ("border_width", ctypes.c_int),
("depth", ctypes.c_int), ("visual", ctypes.c_void_p), ("root", ctypes.c_ulong), ("c_class", ctypes.c_int), ("bit_gravity", ctypes.c_int),
("win_gravity", ctypes.c_int), ("backing_store", ctypes.c_int), ("backing_planes", ctypes.c_ulong), ("backing_pixel", ctypes.c_ulong),
("save_under", ctypes.c_int), ("colormap", ctypes.c_ulong), ("map_installed", ctypes.c_int), ("map_state", ctypes.c_int),
("all_event_masks", ctypes.c_long), ("your_event_mask", ctypes.c_long), ("do_not_propagate_mask", ctypes.c_long),
("override_redirect", ctypes.c_int), ("screen", ctypes.c_void_p)]
#: An X error (a window gone between two requests, a focus asked for a window not yet viewable) is ignored instead of ending the process as Xlib's
#: default handler does; the wait that asked reads the focus again on its next look.
_X_ERROR_HANDLER = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p)
_ignore_x_error = _X_ERROR_HANDLER(lambda display, event: 0)
@contextlib.contextmanager
def a_display_of_its_own(monkeypatch) -> Iterator[str]:
"""Linux: a private Xvfb (the number chosen by the server, ``-displayfd``), set as ``DISPLAY`` for the test and stopped at its end.
Two headed sessions started inside it see each other and nothing else; the Xvfb of ``xvfb-run`` that the parallel workers share is never touched."""
process = subprocess.Popen(["Xvfb", "-displayfd", "1", "-screen", "0", "1920x1080x24", "-nolisten", "tcp"],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
answer = {}
reader = threading.Thread(target=lambda: answer.setdefault("line", process.stdout.readline()), daemon=True)
reader.start()
try:
reader.join(60)
number = answer.get("line", "").strip()
assert number.isdigit(), "the private Xvfb did not give a display number (it said %r, exit %r)" % (number, process.poll())
monkeypatch.setenv("DISPLAY", ":" + number)
for name in ("WAYLAND_DISPLAY", "XAUTHORITY"):
monkeypatch.delenv(name, raising=False)
yield ":" + number
finally:
process.terminate()
try:
process.wait(30)
except subprocess.TimeoutExpired:
process.kill()
process.wait(30)
process.stdout.close()
class XFocus:
"""The X input focus of a display, read and given through a connection of its own (libX11, as the engine's own client library)."""
def __init__(self, display: str) -> None:
x11 = self.x11 = ctypes.CDLL("libX11.so.6")
ulong_p, int_p = ctypes.POINTER(ctypes.c_ulong), ctypes.POINTER(ctypes.c_int)
x11.XOpenDisplay.restype, x11.XOpenDisplay.argtypes = ctypes.c_void_p, (ctypes.c_char_p,)
x11.XSetErrorHandler.argtypes = (_X_ERROR_HANDLER,)
x11.XDefaultRootWindow.restype, x11.XDefaultRootWindow.argtypes = ctypes.c_ulong, (ctypes.c_void_p,)
x11.XInternAtom.restype, x11.XInternAtom.argtypes = ctypes.c_ulong, (ctypes.c_void_p, ctypes.c_char_p, ctypes.c_int)
x11.XQueryTree.argtypes = (ctypes.c_void_p, ctypes.c_ulong, ulong_p, ulong_p, ctypes.POINTER(ulong_p), ctypes.POINTER(ctypes.c_uint))
x11.XGetWindowAttributes.argtypes = (ctypes.c_void_p, ctypes.c_ulong, ctypes.POINTER(_XWindowAttributes))
x11.XGetWindowProperty.argtypes = (ctypes.c_void_p, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_long, ctypes.c_long, ctypes.c_int, ctypes.c_ulong,
ulong_p, int_p, ulong_p, ulong_p, ctypes.POINTER(ctypes.c_void_p))
x11.XFree.argtypes = (ctypes.c_void_p,)
x11.XSetInputFocus.argtypes = (ctypes.c_void_p, ctypes.c_ulong, ctypes.c_int, ctypes.c_ulong)
x11.XSync.argtypes = (ctypes.c_void_p, ctypes.c_int)
x11.XGetInputFocus.argtypes = (ctypes.c_void_p, ulong_p, int_p)
x11.XCloseDisplay.argtypes = (ctypes.c_void_p,)
x11.XSetErrorHandler(_ignore_x_error)
self.connection = x11.XOpenDisplay(display.encode())
assert self.connection, "no connection to the display %r" % display
self.root = x11.XDefaultRootWindow(self.connection)
self.net_wm_name = x11.XInternAtom(self.connection, b"_NET_WM_NAME", False)
self.utf8_string = x11.XInternAtom(self.connection, b"UTF8_STRING", False)
def holder(self) -> int:
window, revert = ctypes.c_ulong(), ctypes.c_int()
self.x11.XGetInputFocus(self.connection, ctypes.byref(window), ctypes.byref(revert))
return int(window.value)
def _title(self, window: int) -> str:
kind, size, count, left, data = ctypes.c_ulong(), ctypes.c_int(), ctypes.c_ulong(), ctypes.c_ulong(), ctypes.c_void_p()
if self.x11.XGetWindowProperty(self.connection, window, self.net_wm_name, 0, 1024, False, self.utf8_string, ctypes.byref(kind),
ctypes.byref(size), ctypes.byref(count), ctypes.byref(left), ctypes.byref(data)) != 0 or not data.value:
return ""
try:
return ctypes.string_at(data.value, count.value).decode("utf-8", "replace") if size.value == 8 else ""
finally:
self.x11.XFree(data)
def _viewable(self, window: int) -> bool:
attributes = _XWindowAttributes()
return bool(self.x11.XGetWindowAttributes(self.connection, window, ctypes.byref(attributes))) and attributes.map_state == _IS_VIEWABLE
def window_titled(self, title: str) -> Optional[int]:
"""The one viewable toplevel (a child of the root: no window manager reparents it) whose ``_NET_WM_NAME`` starts with ``title``, or None."""
root, parent, children, count = ctypes.c_ulong(), ctypes.c_ulong(), ctypes.POINTER(ctypes.c_ulong)(), ctypes.c_uint()
if not self.x11.XQueryTree(self.connection, self.root, ctypes.byref(root), ctypes.byref(parent), ctypes.byref(children), ctypes.byref(count)):
return None
try:
windows = [int(children[i]) for i in range(count.value)]
finally:
if children:
self.x11.XFree(children)
found = [window for window in windows if self._title(window).startswith(title) and self._viewable(window)]
return found[0] if len(found) == 1 else None
def ask_for_the_foreground(self, window: int) -> int:
"""What a window manager does when the user clicks the window (none runs on this display): ``XSetInputFocus`` on it, then the focus is read back."""
self.x11.XSetInputFocus(self.connection, window, _REVERT_TO_PARENT, _CURRENT_TIME)
self.x11.XSync(self.connection, False)
return self.holder()
def close(self) -> None:
self.x11.XCloseDisplay(self.connection)
self.connection = None
class ForegroundWindow:
"""Windows: the foreground window of the desktop the sessions run on, and the Firefox window a title names."""
def __init__(self) -> None:
from ctypes import wintypes
self.user32 = ctypes.WinDLL("user32", use_last_error=True)
self.user32.GetForegroundWindow.restype = wintypes.HWND
self.user32.SetForegroundWindow.argtypes = (wintypes.HWND,)
self.enum = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)
def holder(self) -> int:
return self.user32.GetForegroundWindow() or 0
def window_titled(self, title: str) -> Optional[int]:
"""The one visible top-level Firefox window whose title starts with ``title``, or None (none, or more than one)."""
found = []
def each(hwnd, _):
name, text = ctypes.create_unicode_buffer(256), ctypes.create_unicode_buffer(512)
self.user32.GetClassNameW(hwnd, name, 256)
self.user32.GetWindowTextW(hwnd, text, 512)
if name.value.startswith("MozillaWindowClass") and text.value.startswith(title) and self.user32.IsWindowVisible(hwnd):
found.append(hwnd)
return True
self.user32.EnumWindows(self.enum(each), 0)
return found[0] if len(found) == 1 else None
def ask_for_the_foreground(self, hwnd: int) -> int:
"""What a user does by clicking the window: the system may refuse it, and then the foreground is what the test reads."""
self.user32.SetForegroundWindow(hwnd)
return self.holder()
def host_monitor_size() -> Optional[tuple]:
"""Windows: the primary monitor in device pixels (the reading of a per-monitor-aware process, whatever the test's own awareness is); None elsewhere."""
if sys.platform != "win32":
return None
user32 = ctypes.WinDLL("user32")
user32.SetThreadDpiAwarenessContext.restype = ctypes.c_void_p
user32.SetThreadDpiAwarenessContext.argtypes = (ctypes.c_void_p,)
previous = user32.SetThreadDpiAwarenessContext(ctypes.c_void_p(-4))
try:
return (user32.GetSystemMetrics(0), user32.GetSystemMetrics(1))
finally:
if previous:
user32.SetThreadDpiAwarenessContext(ctypes.c_void_p(previous))
-110
View File
@@ -1,110 +0,0 @@
"""A popup opened the way a page opens one, and what it reads of its own window.
Shared by `test_popup_geometry_is_the_declared_frame_e2e.py` and by the inner-size test of
`test_fingerprint_surface.py`: both need a popup (`window.open` with features, from a click) whose document may carry an
iframe of another site (so, under Fission, in another process), and both read the window geometry from inside it.
The popup is read with a CONDITION, not a pause: the reading is repeated (with the client's events being read between two
looks) until the caller's `ready` holds or 30 s have passed, and the last reading is returned either way, so the caller's
assertion names what was read when it never settled.
"""
from __future__ import annotations
import threading
from typing import Any, Callable, Dict, Optional
from _fission_frames import Sites, wait_frame
from _waits import wait_until
#: The scale at which the declared window frame is the one of `WINDOW_FRAME_BY_DPR[1.0]`: border 8, popup UI 72, default
#: position 4 (device pixels, and CSS pixels at 1.0). The screen is the one the other surface tests pin.
PIN = {"screen.width": 1920, "screen.height": 1080, "screen.dpr": 1.0}
#: A second declared window frame that no runner has: a border of 6, a popup UI of 53 above the content, a default position of 9. The declared frame at scale 1.0
#: (8, 72, 4) is the frame of a retail Windows window, so a Windows runner's own popup has it too (outer - inner = 16 x 80) and a launch with the engine off
#: cannot tell the declaration from the host there; a launch declared with ANOTHER frame can (the prefs are applied last, over the core's declaration).
OTHER_FRAME = {"zoom.stealth.screen.frame_border": 6, "zoom.stealth.screen.popup_ui": 53, "zoom.stealth.screen.popup_position": 9}
OTHER_BORDER, OTHER_POPUP_UI, OTHER_POSITION = 6, 53, 9
READ = """() => ({iw: innerWidth, ih: innerHeight, ow: outerWidth, oh: outerHeight,
sx: screenX, sy: screenY, mx: mozInnerScreenX, my: mozInnerScreenY})"""
def in_a_thread_of_its_own(fn: Callable[[], Any], timeout: float = 300) -> Any:
"""Runs `fn` in a thread with no asyncio loop and gives back its result or raises its error.
For a module whose own fixture keeps a sync client open for the whole module: an open sync client leaves its loop marked as
running in its thread, and a second sync client started in that thread refuses with "Playwright Sync API inside the asyncio
loop". The second browser needs a thread of its own.
"""
box: Dict[str, Any] = {}
def run() -> None:
try:
box["value"] = fn()
except BaseException as exc: # handed back to the test's thread below
box["error"] = exc
worker = threading.Thread(target=run, name="second-sync-client", daemon=True)
worker.start()
worker.join(timeout)
if worker.is_alive():
raise AssertionError("the browser of the test did not end within %d s" % timeout)
if "error" in box:
raise box["error"]
return box.get("value")
def frame_of_the_declaration():
"""The window frame the core declares at scale 1.0: what the engine adds to a popup's inner size."""
from invisible_core.constants import WINDOW_FRAME_BY_DPR
return WINDOW_FRAME_BY_DPR[1.0]
def frame_extra(border: int, popup_ui: int):
"""What a popup adds to its inner size: (outer - inner) wide and high, for a border and a popup UI."""
return (2 * border, popup_ui + border)
def _plausible(reading: Dict[str, Any]) -> bool:
"""Every size of every window read is above 0: the window (and its frame, if any) has been laid out."""
return all(r["iw"] > 0 and r["ih"] > 0 and r["ow"] > 0 and r["oh"] > 0
for r in (reading["popup"], reading["frame"]) if r is not None)
def read_popup(binary: str, extra_prefs: Optional[Dict[str, Any]] = None, iframe: bool = False,
ready: Optional[Callable[[Dict[str, Any]], bool]] = None,
features: str = "width=500,height=400") -> Dict[str, Any]:
"""Open `window.open(url, 'p', features)` (default `width=500,height=400`) from a click and read it.
Returns `{"popup": {...}, "frame": {...} or None}` with `iw ih ow oh sx sy mx my` (innerWidth, innerHeight,
outerWidth, outerHeight, screenX, screenY, mozInnerScreenX, mozInnerScreenY) of the popup and, with `iframe`, of its
iframe (another site, 200x150). `ready(reading)` says when the reading has settled (default: every size above 0).
"""
from invisible_playwright import InvisiblePlaywright
with Sites() as s:
s.route("A", "/main", "<!doctype html><title>main</title><button id='open' onclick=\"window.open('%s', 'p', "
"'%s')\">open</button>" % (s.url("A", "/popup"), features))
frame_html = ("<iframe id='f' src='%s' style='position:absolute;left:0;top:0;width:200px;height:150px;border:0'>"
"</iframe>" % s.url("B", "/frame")) if iframe else ""
s.route("A", "/popup", "<!doctype html><title>popup</title>" + frame_html)
s.route("B", "/frame", "<!doctype html><title>frame</title>")
with InvisiblePlaywright(seed=42, pin=PIN, binary_path=binary, headless=True, humanize=False,
extra_prefs=extra_prefs) as browser:
page = browser.new_page()
page.goto(s.url("A", "/main"), wait_until="load", timeout=30000)
with page.expect_popup(timeout=30000) as info:
page.click("#open", timeout=30000)
popup = info.value
popup.wait_for_load_state("load", timeout=30000)
frame = wait_frame(popup, s.origin["B"], "/frame", seconds=30) if iframe else None
seen: Dict[str, Any] = {}
def settled() -> bool:
seen["now"] = {"popup": popup.evaluate(READ), "frame": frame.evaluate(READ) if frame else None}
return _plausible(seen["now"]) and (ready is None or bool(ready(seen["now"])))
wait_until(settled, 30, lambda: popup.wait_for_timeout(100))
return seen["now"]
-232
View File
@@ -1,232 +0,0 @@
"""A sampler of the processes below a pid, from before a launch to after it, and what proves it missed none: the e2e of the host GL probe.
Firefox on Linux probes the host's GL in a child of the parent: ``<GRE>/gfxtest glx -f <fd>`` (``GfxInfo::FireGLXTestProcess``, widget/gtk/GfxInfo.cpp;
Mozilla's code and logs call it ``glxtest``, the binary is ``gfxtest`` and ``glx`` is the probe it runs). It lives as long as it takes to load the host's GL,
answer through the pipe and be reaped by the parent, and a poll of the process tree can fall between two of its samples. So the sampler alone never says
"absent". The complete list is the kernel's: under the strace stand-in (``tests/_strace_stand_in.py``) every ``execve`` of every process of the browser's tree is
written to the log, because ptrace stops the process AT the call and it cannot run past it unseen. Every exec of a probe in that log must have been seen by
the sampler too (same pid, named as a probe), and the sampler must have run from before the launch to after the page had its WebGL context. A probe that
strace saw and the sampler did not, a sampler that did not cover the launch, a log that does not hold the browser's own exec, or a sampler that died on an
error is a PROBLEM that ``reconcile`` returns, and a test that asserts ``problems == []`` first is red then: a miss is reported, never read as "no probe".
``TreeSampler`` takes ``read`` (``root -> {pid: (name, ppid, cmdline)}``, psutil by default) and ``clock``, so the unit tests drive it with a fake tree and a
counter (tests/test_the_process_sampler_cannot_miss_a_short_lived_probe.py). No browser here.
"""
from __future__ import annotations
import os
import re
import threading
import time
from dataclasses import dataclass, field
from typing import Callable, Dict, Iterable, List, Optional, Tuple
#: The names of the probe's executable: ``gfxtest`` since Mozilla merged its probes into one binary, ``glxtest`` before.
PROBE_NAMES = ("gfxtest", "glxtest")
#: What strace has to write for ``read_witness``: the execs, and the clones that make the tree.
TRACE = "execve,clone,clone3,fork,vfork"
Tree = Dict[int, Tuple[str, Optional[int], List[str]]]
@dataclass
class Seen:
"""A process the sampler saw: every name and command line it had (a child is first seen before its exec, with its parent's name), its parent, and the
clock at the first and the last sample that held it."""
pid: int
ppid: Optional[int]
names: List[str]
cmds: List[List[str]]
first: float
last: float
def is_probe(self) -> bool:
return any(n in PROBE_NAMES for n in self.names) or any(c and os.path.basename(c[0]) in PROBE_NAMES for c in self.cmds)
def psutil_tree(root: int) -> Tree:
"""``{pid: (name, ppid, cmdline)}`` of every process below ``root`` now. A zombie keeps its name and parent and has no command line."""
import psutil
out: Tree = {}
try:
children = psutil.Process(root).children(recursive=True)
except psutil.Error:
return out
for proc in children:
try:
with proc.oneshot():
name, ppid = proc.name(), proc.ppid()
try:
cmd = proc.cmdline()
except psutil.Error:
cmd = []
except psutil.Error:
continue
out[proc.pid] = (name, ppid, list(cmd))
return out
class TreeSampler:
"""Samples the tree below ``root`` in a thread, as fast as it can (a step of ``step`` seconds between two reads, so the test's own client keeps the
interpreter), from ``start`` to ``stop``. ``start`` takes the first sample before it returns and ``stop`` takes a last one after the thread has ended,
so what happens between the two calls is inside the samples. ``first_sample`` is the clock when the first read ENDED, ``last_sample`` the clock when
the last read BEGAN: the window the sampler covers."""
def __init__(self, root: int, read: Callable[[int], Tree] = psutil_tree, clock: Callable[[], float] = time.monotonic, step: float = 0.001) -> None:
self.root = root
self._read = read
self._clock = clock
self._step = step
self.seen: Dict[int, Seen] = {}
self.samples = 0
self.first_sample: Optional[float] = None
self.last_sample: Optional[float] = None
self.error: Optional[BaseException] = None
self._stopped = threading.Event()
self._lock = threading.Lock()
self._thread: Optional[threading.Thread] = None
def start(self) -> "TreeSampler":
self._sample()
self._thread = threading.Thread(target=self._poll, name="tree-sampler", daemon=True)
self._thread.start()
return self
def stop(self) -> None:
self._stopped.set()
if self._thread is not None:
self._thread.join()
if self.error is None:
self._sample()
def _poll(self) -> None:
try:
while not self._stopped.is_set():
self._sample()
self._stopped.wait(self._step)
except BaseException as exc: # the verdict reports it: a sampler that died covered nothing after it
self.error = exc
def _sample(self) -> None:
began = self._clock()
tree = self._read(self.root)
ended = self._clock()
with self._lock:
for pid, (name, ppid, cmd) in tree.items():
seen = self.seen.get(pid)
if seen is None:
self.seen[pid] = Seen(pid, ppid, [name] if name else [], [list(cmd)] if cmd else [], began, began)
continue
seen.last = began
if name and name not in seen.names:
seen.names.append(name)
if cmd and list(cmd) not in seen.cmds:
seen.cmds.append(list(cmd))
if self.first_sample is None:
self.first_sample = ended
self.last_sample = began
self.samples += 1
def view(self) -> Tuple[Dict[int, Seen], Optional[float], Optional[float], Optional[BaseException]]:
with self._lock:
return dict(self.seen), self.first_sample, self.last_sample, self.error
# --------------------------------------------------------------------------------------------------------------------------------- the witness: strace
@dataclass
class Exec:
"""One ``execve`` of the strace log: the pid, the path, the arguments, and the result (``None`` when the log ends before it)."""
pid: int
path: str
argv: List[str] = field(default_factory=list)
result: Optional[int] = None
def ran(self) -> bool:
"""The exec replaced the process (0), or the log stops before saying (counted as run: it can only make a test red)."""
return self.result is None or self.result == 0
_EXECVE = re.compile(r'^(\d+)\s+execve\("((?:[^"\\]|\\.)*)",\s*\[(.*?)\]')
_RESUMED_EXECVE = re.compile(r"^(\d+)\s+<\.\.\. execve resumed>")
_RESULT = re.compile(r"\)\s+=\s+(-?\d+)")
_QUOTED = re.compile(r'"((?:[^"\\]|\\.)*)"')
def read_execs(lines: Iterable[str]) -> List[Exec]:
"""Every ``execve`` of a ``strace -f`` log (no timestamps), with its result: on its line, or on the ``<... execve resumed>`` line of its pid when
another thread interrupted it."""
out: List[Exec] = []
pending: Dict[int, Exec] = {}
for line in lines:
m = _EXECVE.match(line)
if m:
found = Exec(int(m.group(1)), m.group(2), _QUOTED.findall(m.group(3)))
out.append(found)
if "<unfinished ...>" in line:
pending[found.pid] = found
else:
r = _RESULT.search(line[m.end():])
found.result = int(r.group(1)) if r else None
continue
m = _RESUMED_EXECVE.match(line)
if m and int(m.group(1)) in pending:
r = _RESULT.search(line)
pending.pop(int(m.group(1))).result = int(r.group(1)) if r else None
return out
def is_probe_exec(found: Exec) -> bool:
return os.path.basename(found.path) in PROBE_NAMES
def is_glx_probe(found: Exec) -> bool:
"""The GLX probe: the probe's executable with ``glx`` as its command (``gfxtest glx -f <fd>``; ``vaapi``, ``v4l2`` and ``vulkan`` are other probes)."""
return is_probe_exec(found) and found.argv[1:2] == ["glx"]
def browser_parents(execs: Iterable[Exec], real_binary: str) -> List[int]:
"""The pids that executed the browser itself (the real binary, not a content process): the parent the probe is a child of."""
return [e.pid for e in execs if e.ran() and e.path == real_binary and "-contentproc" not in e.argv]
def reconcile(seen: Dict[int, Seen], first_sample: Optional[float], last_sample: Optional[float], error: Optional[BaseException],
execs: List[Exec], real_binary: str, launched_at: float, ready_at: Optional[float]) -> Tuple[List[Exec], List[str]]:
"""``(probes, problems)``: the execs of a probe that ran, and every reason the observation cannot be trusted. ``problems`` is empty only when strace
saw the browser start, the sampler ran from before ``launched_at`` to after ``ready_at`` (the page has its WebGL context), and every probe strace saw
the kernel exec was seen by the sampler under the same pid as a probe, and the other way round."""
problems = []
if error is not None:
problems.append("the sampler stopped on an error: %r" % (error,))
if first_sample is None or first_sample > launched_at:
problems.append("the sampler's first sample (%s) is not before the launch (%s): what the launch started first is not in it" % (first_sample, launched_at))
if ready_at is None:
problems.append("the page never had its WebGL context: the window of the launch has no end")
elif last_sample is None or last_sample < ready_at:
problems.append("the sampler's last sample (%s) is before the page had its WebGL context (%s): it stopped early" % (last_sample, ready_at))
if not browser_parents(execs, real_binary):
problems.append("strace wrote no execve of the browser (%s): the witness is empty, and an empty witness proves no absence" % real_binary)
probes = [e for e in execs if is_probe_exec(e) and e.ran()]
for e in probes:
s = seen.get(e.pid)
if s is None or not s.is_probe():
problems.append("strace saw pid %d exec %s and the sampler %s: the sampler missed a probe"
% (e.pid, " ".join(e.argv[:3]) or e.path, "never saw the pid" if s is None else "saw it only as %s" % (s.names or s.cmds)))
witnessed = {e.pid for e in probes}
for s in seen.values():
if s.is_probe() and s.pid not in witnessed:
problems.append("the sampler saw a probe (pid %d, %s) that strace never saw exec: the two do not watch the same tree" % (s.pid, s.names))
return probes, problems
def describe(seen: Dict[int, Seen], execs: List[Exec], origin: float) -> str:
"""Every process the sampler saw (seconds from ``origin``, names, pid, ppid, head of the command line) and every exec strace wrote."""
rows = ["processes seen below the test (first..last sample, from the launch):"]
for s in sorted(seen.values(), key=lambda s: (s.first, s.pid)):
head = " ".join(a[:80] for a in (s.cmds[-1] if s.cmds else [])[:4])
rows.append(" +%.3fs..+%.3fs pid=%d ppid=%s names=%s cmd=%s" % (s.first - origin, s.last - origin, s.pid, s.ppid, "/".join(s.names), head))
rows.append("execs strace wrote:")
for e in execs:
rows.append(" pid=%d result=%s %s" % (e.pid, e.result, " ".join(a[:80] for a in e.argv[:4]) or e.path))
return "\n".join(rows)
+6 -105
View File
@@ -21,20 +21,10 @@ test-only: the product never sets it) a content process that hosts a site is nam
The process gets its name before any document loads in it, so when a page of the site has run, its process already
answers to the site. Windows names no process (ProcessUtils_none.cpp): a test that looks at sites skips there and
says so.
Windows names no process, but the engine's own log names the type of every process it creates (`Setting remoteType of
process <pid> to <type>` when a process is born with its type, `Changing remoteType of process <pid> from prealloc to
<type>` when a spare one is given its site: `dom/ipc/ContentChild.cpp`, `RecvSetRemoteType`, log module `Process`). The
type of a process that hosts a site is `webIsolated=<site>^<attributes>` (`dom/ipc/RemoteType.cpp`, `Stringify`), the
same site the Linux name carries, and the process gets it before any document loads in it. So on Windows a test starts the
engine with `LOG_ENV` and a file base (`MOZ_LOG_FILE`), and `remote_types(base)` reads which type each process was given (by pid and time, a pid being reused);
liveness and the engine's own directory are still told by the process tree, so a process that has ended is not counted.
"""
from __future__ import annotations
import calendar
import os
import re
import sys
import pytest
@@ -67,94 +57,9 @@ def hosts_site(name, site):
return len(prefix) >= NAME_LENGTH or name[len(prefix)] == "^"
#: The environment that makes the engine write the type of each process it creates (`MOZ_LOG_FILE` is added by the
#: test: a file base in its own temporary folder). Used where the system names no process (Windows).
LOG_ENV = {"MOZ_LOG": "Process:5,timestamp,sync"}
_TYPE_GIVEN = re.compile(r"(?:Setting remoteType of process (\d+) to|Changing remoteType of process (\d+) from \S+ to) (\S+)")
#: The start of a line of `MOZ_LOG` with the `timestamp` option: `2026-11-22 10:11:12.123456 UTC - [Process 12: Thread]: ...`.
_LOG_TIME = re.compile(r"^(\d{4})-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)\.(\d{6}) UTC - ")
#: How much earlier than the creation time of a process (psutil) its first log line may be stamped: the two clocks are
#: read at different moments of its birth.
BIRTH_SLACK = 0.25
def _natural(path):
"""The sort key that puts `base.child-2` before `base.child-10` (the plain order of names puts it after)."""
return [int(part) if part.isdigit() else part for part in re.split(r"(\d+)", path.name)]
def _stamp(line):
"""The time of a log line in seconds since the epoch (UTC), or None when the line carries no timestamp."""
match = _LOG_TIME.match(line)
if match is None:
return None
year, month, day, hour, minute, second, micro = (int(g) for g in match.groups())
return calendar.timegm((year, month, day, hour, minute, second)) + micro / 1e6
def remote_types(base):
"""`{pid: [(time, remote type), ...]}` of the processes the engine has logged to the files that start with the path
`base` (`MOZ_LOG_FILE`: the parent writes `base`, each child its own `base.child-N`), each list in the order of the
time the lines were logged (then the child number as a number, then the line). A pid alone does not name a process:
the system gives the number of an ended process to a later one, and a later process of another site must not
inherit the type of the old one. So the types stay stamped, and `type_of_process` chooses the ones of the process
instance in hand. A process that logs twice (a spare one, then the site it is given) has two entries, the last wins."""
entries = {}
for order, path in enumerate(sorted(base.parent.glob(base.name + "*"), key=_natural)):
for number, line in enumerate(path.read_text(encoding="utf-8", errors="replace").splitlines()):
match = _TYPE_GIVEN.search(line)
if match is None:
continue
stamp = _stamp(line)
key = (stamp if stamp is not None else float("-inf"), order, number)
entries.setdefault(int(match.group(1) or match.group(2)), []).append((key, stamp, match.group(3)))
return {pid: [(stamp, remote_type) for _key, stamp, remote_type in sorted(found, key=lambda entry: entry[0])]
for pid, found in entries.items()}
def type_of_process(types, pid, created):
"""The remote type the process `pid` born at `created` (epoch seconds, `psutil.Process.create_time()`) was given: the
last one logged for the pid at or after its birth (less `BIRTH_SLACK`). Entries logged before the process existed
are the ones of an earlier process that had the same pid, and are ignored. A line with no timestamp counts for any
birth. `""` when the process has not logged its type yet."""
chosen = ""
for stamp, remote_type in types.get(pid, ()):
if stamp is None or stamp >= created - BIRTH_SLACK:
chosen = remote_type
return chosen
def hosts_site_by_type(remote_type, site):
"""True when a process of the remote type `remote_type` hosts `site` (`http://a.test`): `<kind>=<site>` or
`<kind>=<site>^<attributes>`. A process with no site (`web`, `prealloc`, `privilegedabout`, `extension`) has no `=`."""
meta = remote_type.partition("=")[2]
return meta == site or meta.startswith(site + "^")
def site_pids_by_type(processes, site, types, engine_dir=None):
"""Like `site_pids`, told by the remote types the engine logged (`remote_types`) instead of by the process name."""
return _content_pids(processes, engine_dir, lambda proc, _name: hosts_site_by_type(_type_of(types, proc), site))
def _type_of(types, proc):
import psutil
try:
return type_of_process(types, proc.pid, proc.create_time())
except psutil.Error:
return ""
def site_pids(processes, site, engine_dir=None):
"""The pids, among `processes` (psutil-like), of the content processes (`-contentproc ... tab`) that host `site`;
with `engine_dir`, only those of the engine in that directory."""
return _content_pids(processes, engine_dir, lambda _proc, name: hosts_site(name, site))
def _content_pids(processes, engine_dir, hosts):
import psutil
pids = set()
@@ -165,23 +70,19 @@ def _content_pids(processes, engine_dir, hosts):
name, cmd = proc.name(), proc.cmdline()
except psutil.Error:
continue
if "-contentproc" in cmd and cmd and cmd[-1] == "tab" and hosts(proc, name):
if "-contentproc" in cmd and cmd and cmd[-1] == "tab" and hosts_site(name, site):
pids.add(proc.pid)
return pids
def site_processes_below(root_pid, site, engine_dir=None, types=None):
"""The pids of the processes below `root_pid` that host `site`. On Linux the name of the process says it; on Windows
`types` (a function that returns `remote_types(base)` of the engine's log, see `LOG_ENV`) does. With neither, the test
skips: no name says it."""
def site_processes_below(root_pid, site, engine_dir=None):
"""The pids of the processes below `root_pid` that host `site`. Off Linux the test skips: no name says it."""
import psutil
if not sys.platform.startswith("linux") and types is None:
pytest.skip("only Linux names a content process by the site it hosts; %s names none (pass `types`)" % sys.platform)
if not sys.platform.startswith("linux"):
pytest.skip("only Linux names a content process by the site it hosts; %s names none" % sys.platform)
try:
children = psutil.Process(root_pid).children(recursive=True)
except psutil.Error:
return set()
if sys.platform.startswith("linux"):
return site_pids(children, site, engine_dir)
return site_pids_by_type(children, site, types(), engine_dir)
return site_pids(children, site, engine_dir)
+24 -210
View File
@@ -33,23 +33,11 @@ answer as the service; the plain-HTTP endpoint ``api.ipify.org:80`` is still
answered here for the tests that ask it), and the UDP exit is what the fake STUN server puts in its XOR-MAPPED-ADDRESS.
Both are chosen by the test (``tcp_exit`` and ``udp_exit`` arguments).
HERMETIC: a gateway of this module carries a CONNECT or a datagram only to the LAB (:func:`is_lab_destination`: loopback, the
documentation ranges of RFC 5737 and RFC 3849 the tests use as lab exits and servers, the addresses of this host's own interfaces, where a server
of a test may stand, and the name ``localhost``). These tests run in the gate of the candidate, where no test may depend on a real service, and the
browser behind a gateway makes background requests of its own (a name of the vendor, a captive-portal check, a telemetry endpoint): such a
destination is REFUSED, never forwarded (a CONNECT is answered with reply 2, "not allowed"; a datagram is dropped), and RECORDED
(:class:`LabGuard`: the time since the gateway started, the SOCKS5 address type, the destination as it was received - the NAME for type 3 -, the
port, the protocol, ``tcp`` or ``udp``, and the REASON: which rule refused it, the lab's or the narrower one of a subclass). The interfaces of this
host are read ONCE, when the guard is made (``psutil.net_if_addrs``, written once in the record with how they were read), and every decision of that
guard is taken against that reading: a browser that retries a refused destination hundreds of times costs a list append each, not a reading of the
host; a reading that fails RAISES (``_witness.HostInterfacesUnreadable``), it is never an empty list. The record is always written, when the gateway is closed, under
``$RUNNER_TEMP/invpw-evidence/<gateway>/<pid>-<ms>/refused-destinations.json`` (the folder the e2e jobs upload; off a runner nothing is
written), so that a reader sees what the browser asked for besides what the test drives. There is no option that reopens it. A subclass can only
narrow it (:meth:`Gateway._admits`); the destinations it serves itself (the fake STUN server, the page of ``WEB_NAME``, the exit questions) are
answered before it, and a name mapped to a local server by :meth:`Gateway._target` is judged by the server it maps to. What a test sees of the
road is :attr:`Gateway.connects`, :attr:`Gateway.datagrams` (every datagram the relay read, carried or dropped) and
:attr:`Gateway.guard`. :class:`Socks5TcpOnly` and the SOCKS5 server of ``test_proxy_socks_auth_e2e.py`` are hermetic the same way (same rule,
same record).
Any other CONNECT is really forwarded, and any other UDP datagram is really
forwarded to its destination and the reply wrapped back, so a page, or an echo
server on 127.0.0.1, can be reached through the gateway and the test can
observe which road its bytes took (:attr:`Gateway.connects`,
:attr:`Gateway.datagrams`).
This is the ONE SOCKS5 gateway of the test suite. A road that needs more than the three above (a TURN server, a resolver,
a page, by NAME: ``tests/_turn_chain.py``) subclasses :class:`Gateway` and overrides the small hooks (:meth:`Gateway._route`,
@@ -58,10 +46,7 @@ ASSOCIATE, the relay or the round trip.
"""
from __future__ import annotations
import ipaddress
import json
import os
import pathlib
import select
import socket
import struct
@@ -70,7 +55,7 @@ import time
from typing import Callable, Dict, List, Optional, Set, Tuple
#: The name the product's STUN probe sends through the relay. The relay maps it
#: to the fake STUN server; every other destination is the lab's to carry or is refused (``LabGuard``).
#: to the fake STUN server; every other destination is forwarded for real.
STUN_NAME = "stun.l.google.com"
STUN_PORT = 19302
#: The same STUN server by NUMBER. A page cannot resolve a name behind the session (the engine forbids local
@@ -94,18 +79,19 @@ _MAGIC = b"\x21\x12\xa4\x42"
# ----------------------------------------------------------------------------------------------------------------
# The exit of a proxy that relays CONNECTs. The question "where do I leave from" is HTTPS (api.ipify.org:443), and no gateway
# of the tests can answer a TLS request as the service. A gateway of this module is hermetic (a CONNECT outside the lab is refused, see
# ``LabGuard``), so the question could not reach the internet through it anyway; but the product would then be told no exit at all. So such a
# proxy DECLARES its exit (``declare_exit``) and ``tests/_lab_egress.DeclaredExit`` answers the question with it; and as a backstop each of
# them refuses the question itself (``asks_the_world``), which records it and makes the test fail (``nobody_asked_the_world``), so that a
# proxy that forgot to declare is a red with its name and not a flaky green.
# The exit of a proxy that forwards for real. The question "where do I leave from" is HTTPS (api.ipify.org:443), and no gateway
# of the tests can answer a TLS request as the service: a proxy that FORWARDS (a CONNECT to anything outside loopback goes out for
# real) would carry it to the internet, and the answer would be the address of whatever machine runs the test (a GitHub runner
# that changes NAT in the middle of a session: ``ProxyEgressDrifted``). So such a proxy DECLARES its exit (``declare_exit``) and
# ``tests/_lab_egress.DeclaredExit`` answers the question with it; and as a backstop each of them refuses to forward the question
# (``asks_the_world``), which records it and makes the test fail (``nobody_asked_the_world``), so that a proxy that forgot to declare
# is a red with its name and not a flaky green.
# ----------------------------------------------------------------------------------------------------------------
#: The hosts of the services of the core that tell a caller its address (``invisible_core._geo._IP_ECHO_ENDPOINTS`` and
#: ``_IPV6_ECHO_ENDPOINTS``; ``tests/test_a_launch_asks_nobody_on_the_internet_where_it_leaves_from.py`` checks that this list covers them).
EXIT_SERVICES = ("api.ipify.org", "api6.ipify.org", "icanhazip.com", "ipv6.icanhazip.com", "checkip.amazonaws.com", "ifconfig.me")
#: ``host:port`` of a proxy of the tests that relays CONNECTs -> the exit it declares. Filled by the proxies themselves.
#: ``host:port`` of a proxy of the tests that forwards for real -> the exit it declares. Filled by the proxies themselves.
_DECLARED_EXITS: Dict[str, str] = {}
#: The questions of the exit that reached a forwarding proxy and were refused there: one sentence each, until a test reads them.
_WORLD_QUESTIONS: List[str] = []
@@ -117,7 +103,7 @@ def _endpoint(server: str) -> str:
def declare_exit(server: str, exit_ip: str) -> None:
"""The proxy at ``server`` relays CONNECTs and says its exit is ``exit_ip``."""
"""The proxy at ``server`` forwards for real and says its exit is ``exit_ip``."""
_DECLARED_EXITS[_endpoint(server)] = exit_ip
@@ -131,10 +117,10 @@ def declared_exit_of(server: Optional[str]) -> Optional[str]:
def asks_the_world(server: str, host: str, port: int) -> bool:
"""True, and the question is recorded, when a CONNECT to ``host:port`` is the question of the exit: the proxy must refuse it (the lab answers it with the declared exit)."""
"""True, and the question is recorded, when a CONNECT to ``host:port`` is the question of the exit: the proxy must refuse it, not forward it."""
if host.lower() not in EXIT_SERVICES:
return False
_WORLD_QUESTIONS.append("%s was asked %s:%d: the question of the exit reached a proxy of the lab, which refuses it (its exit is declared, not asked of the internet)" % (
_WORLD_QUESTIONS.append("%s was asked %s:%d: the question of the exit reached a proxy that would have forwarded it to the internet" % (
server, host, port))
return True
@@ -163,140 +149,6 @@ def _recv_exact(s: socket.socket, n: int) -> bytes:
return data
# ----------------------------------------------------------------------------------------------------------------
# The lab. A gateway of the tests forwards nothing that is not the lab's: the destination is refused and recorded.
# ----------------------------------------------------------------------------------------------------------------
#: The networks that are the lab's whatever the host: loopback, and the documentation ranges (RFC 5737 TEST-NET-1/2/3, RFC 3849) that the tests use
#: for their exits and their servers (nothing routes them: a test holds the ones a server stands at on ``lo``).
LAB_NETWORKS = tuple(ipaddress.ip_network(net) for net in (
"127.0.0.0/8", "::1/128", "192.0.2.0/24", "198.51.100.0/24", "203.0.113.0/24", "2001:db8::/32"))
#: The folder under ``$RUNNER_TEMP`` the e2e workflows upload (``invpw-evidence-*``).
EVIDENCE_FOLDER = "invpw-evidence"
def _own_interfaces() -> Dict[str, List[str]]:
"""The addresses assigned to each interface of this host (a server of a test stands at one of them), by interface name. It RAISES when they
cannot be listed (``_witness.HostInterfacesUnreadable``, or the ImportError of ``_witness``): never an empty list in place of an unreadable one."""
from _witness import read_host_interfaces
return read_host_interfaces()
def _own_addresses() -> Set[str]:
"""Every address of :func:`_own_interfaces` (raises as it does)."""
return {address for addresses in _own_interfaces().values() for address in addresses}
def _how_own_interfaces_are_read() -> str:
from _witness import how_host_interfaces_are_read
return how_host_interfaces_are_read()
def lab_refusal(host: str, own: Optional[Set[str]] = None) -> Optional[str]:
"""None when ``host`` (an address, or a name as a SOCKS5 client sent it) is the lab's: loopback, a documentation range, an address of one of this host's
own interfaces, or ``localhost``; otherwise WHY it is not, one sentence. Any other NAME is not the lab's: nothing here resolves a name for the internet's
sake, and the question would leave the machine. ``own`` is the addresses of this host's interfaces as a guard read them when it was made; None: they
are read now (:func:`_own_addresses`), only for an address outside loopback and the documentation ranges, and a reading that fails raises."""
text = host.strip().strip("[]").split("%", 1)[0].rstrip(".").lower()
try:
address = ipaddress.ip_address(text)
except ValueError:
if text == "localhost" or text.endswith(".localhost"):
return None
return "a name that is not localhost: a gateway of the tests resolves no name, the question would leave the machine"
mapped = getattr(address, "ipv4_mapped", None)
if mapped is not None:
address = mapped
if any(address in network for network in LAB_NETWORKS):
return None
read_at = "read at the decision" if own is None else "read when the gateway was made"
own = _own_addresses() if own is None else own
if address.compressed in own:
return None
return ("%s is not loopback, not in a documentation range and not one of the %d addresses of this host's interfaces %s"
% (address.compressed, len(own), read_at))
def is_lab_destination(host: str) -> bool:
"""Whether ``host`` is the lab's (:func:`lab_refusal` has no reason to refuse it)."""
return lab_refusal(host) is None
#: The address type of the SOCKS request the current thread last read (:meth:`Gateway._read_address`).
_REQUEST = threading.local()
class LabGuard:
"""What refuses a destination that is not the lab's and writes it down: one per gateway.
:meth:`admits` is asked with the destination as RECEIVED (``atyp`` is the SOCKS5 address type: 1 IPv4, 3 a name, 4 IPv6; ``protocol`` is ``"tcp"`` or
``"udp"``); ``target`` is where it would really go, as (host, port), when that is not the destination itself (a name a gateway maps to a local server): the lab's
decision is about the target. A refusal is recorded in :attr:`records` as a dict with ``t`` (seconds since ``t0``, the start of the gateway), ``atyp``,
``destination`` (as received), ``port``, ``protocol`` and ``reason`` (the rule that refused it). :meth:`write_evidence` leaves them, always, under
``$RUNNER_TEMP/invpw-evidence/<name>/``, with the interfaces of this host as the guard read them when it was made (:attr:`host_interfaces`) and how.
The interfaces are read ONCE, when the guard is made (a reading that fails raises there: the gateway is not made), and every decision is taken against
that reading: a refusal is a list append, synchronous, with no reading of the host."""
def __init__(self, name: str, t0: Optional[float] = None):
self.name = name
self.t0 = time.monotonic() if t0 is None else t0
#: Every refusal, in order.
self.records: List[dict] = []
#: The addresses of each interface of this host, read when the guard was made (raises if they cannot be read), and how they were read.
self.host_interfaces: Dict[str, List[str]] = _own_interfaces()
self.host_interfaces_read_by = _how_own_interfaces_are_read()
#: The same addresses as one set: what every decision of this guard is judged against.
self._own = {address for addresses in self.host_interfaces.values() for address in addresses}
self._lock = threading.Lock()
self._written = False
def admits(self, host: str, port: int, atyp: int, protocol: str, target: Optional[Tuple[str, int]] = None) -> bool:
reason = lab_refusal(host if target is None else target[0], self._own)
if reason is None:
return True
if target is not None and (target[0], target[1]) != (host, port):
reason = "mapped to %s:%d, and %s" % (target[0], target[1], reason)
self.refuse(host, port, atyp, protocol, reason=reason)
return False
def refuse(self, host: str, port: int, atyp: int, protocol: str, *, reason: str) -> None:
"""Write down a destination that was refused (by this guard's rule, or by the narrower rule of a subclass), with the ``reason``: which rule, one sentence."""
record = {"t": round(time.monotonic() - self.t0, 3), "atyp": atyp, "destination": host, "port": port, "protocol": protocol,
"reason": reason}
with self._lock:
self.records.append(record)
def refused(self, protocol: Optional[str] = None) -> List[Tuple[str, int]]:
"""Every refused destination as (destination as received, port), in order; of one protocol when asked."""
with self._lock:
return [(r["destination"], r["port"]) for r in self.records if protocol is None or r["protocol"] == protocol]
def evidence(self, extra: Optional[dict] = None) -> dict:
"""The record as it is written: the refusals, the interfaces of this host as read when the guard was made and how."""
with self._lock:
records = list(self.records)
return dict({"gateway": self.name, "refused": records,
"host_interfaces": {"read_by": self.host_interfaces_read_by, "read_at": "when the gateway was made",
"interfaces": self.host_interfaces}}, **(extra or {}))
def write_evidence(self, extra: Optional[dict] = None) -> Optional[pathlib.Path]:
"""Write the record, once (a gateway may be closed twice): the file written, or None off a runner (no ``$RUNNER_TEMP``) or when already written."""
runner_temp = os.environ.get("RUNNER_TEMP")
with self._lock:
if self._written:
return None
self._written = True
path = None
if runner_temp:
folder = pathlib.Path(runner_temp) / EVIDENCE_FOLDER / self.name / ("%d-%d" % (os.getpid(), int(time.time() * 1000)))
folder.mkdir(parents=True, exist_ok=True)
path = folder / "refused-destinations.json"
path.write_text(json.dumps(self.evidence(extra), indent=2), encoding="utf-8")
return path
class FakeStun:
"""A UDP STUN server that answers every binding request with ``mapped_ip``."""
@@ -363,12 +215,10 @@ class FakeStun:
class Gateway:
"""A SOCKS5 server. ``udp`` is ``"relay"`` or ``"refuse"`` (reply code 7)."""
#: Whether this gateway relays the CONNECTs that are not special (to the lab: it is hermetic): such a gateway declares ``tcp_exit`` as its exit
#: Whether a CONNECT that is not special is forwarded for real, past loopback: such a gateway declares ``tcp_exit`` as its exit
#: (``declare_exit``). A subclass that refuses everything but loopback (``tests/_doh_servers.DohGateway``) sets False: it cannot carry the
#: question of the exit anywhere, and the question is left to what answers it.
forwards_for_real = True
#: The name of the folder of the record of what this gateway refused under ``$RUNNER_TEMP/invpw-evidence/`` (a subclass may name its own).
evidence_name = "socks5-gateway"
def __init__(self, *, udp: str, tcp_exit: str, udp_exit: str,
user: Optional[str] = None, password: Optional[str] = None,
@@ -419,9 +269,6 @@ class Gateway:
self.associates = 0
#: When the gateway started: the origin of the times below.
self.t0 = time.monotonic()
#: What refuses (and records, and writes under ``$RUNNER_TEMP/invpw-evidence/<evidence_name>/`` when the gateway is closed) every destination that is
#: not the lab's, CONNECT or datagram: ``guard.records``, ``guard.refused()``.
self.guard = LabGuard(self.evidence_name, self.t0)
#: The same instant on the wall clock (seconds since the epoch), to compare with what a page reads from Date.now().
self.wall0 = time.time()
#: Every TCP connection the gateway accepted (a SOCKS handshake starts with one), as seconds from t0.
@@ -433,8 +280,6 @@ class Gateway:
#: Every datagram the relay carried out, as (host as sent, port, index in ``associations`` of the association it came
#: on, seconds from t0): which association carried a datagram, not only when it left.
self.datagram_via: List[Tuple[str, int, int, float]] = []
#: The association of the datagram that ``_route`` is routing, for the thread that routes it (``_route`` is called by the thread of the association).
self._dgram = threading.local()
#: Every datagram the relay carried out, as (host, port, payload).
self.datagrams: List[Tuple[str, int, bytes]] = []
#: The local port of the socket each granted association sends from: what a server behind the gateway sees as the port
@@ -442,8 +287,8 @@ class Gateway:
self.exit_ports: List[int] = []
#: A datagram the relay could not send (a socket that raised): said here and in the report of a test, never mute.
self.send_errors: List[str] = []
#: The hosts the relay forwards a datagram to (the fake STUN server aside), among the lab's; None: any host of the lab. It only narrows: a host
#: that is not the lab's is never forwarded (``guard``).
#: The hosts the relay forwards a datagram to (the fake STUN server aside); None: any host. A test that sends from an
#: address of this host keeps its lab closed: the browser's own background QUIC does not leave the machine.
self.forward_only_to: Optional[Set[str]] = None
self._listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
@@ -485,11 +330,6 @@ class Gateway:
except OSError:
pass
self.stun.close()
self.guard.write_evidence(self._evidence())
def _evidence(self) -> dict:
"""What a subclass adds to the record of the refusals written at the close (a dict of JSON values)."""
return {}
def __enter__(self) -> "Gateway":
return self
@@ -559,10 +399,7 @@ class Gateway:
@staticmethod
def _read_address(c: socket.socket) -> Tuple[str, int]:
"""The destination of a request, as received (the NAME for address type 3); its address type is left in :data:`_REQUEST` ``.atyp`` of the
thread that read it. A static method, as on main: a test that wraps it calls ``type(gateway)._read_address(c)``."""
atyp = _recv_exact(c, 1)[0]
_REQUEST.atyp = atyp
if atyp == 1:
host = socket.inet_ntoa(_recv_exact(c, 4))
elif atyp == 3:
@@ -605,12 +442,6 @@ class Gateway:
"""Where a CONNECT that is not a special one really goes. A subclass maps a name to a local server."""
return host, port
def _admits(self, host: str, port: int, atyp: int, protocol: str, target: Optional[Tuple[str, int]] = None) -> bool:
"""Whether the gateway carries a CONNECT (``protocol`` ``"tcp"``) or a datagram (``"udp"``) to ``host``:``port`` (as received; ``atyp`` is its SOCKS5
address type), or to ``target`` (host, port) when it is mapped elsewhere: only the lab's, and the rest is refused and recorded (``guard``). A subclass may narrow
it (never widen it: call this one first)."""
return self.guard.admits(host, port, atyp, protocol, target)
def _open_upstream(self, target: Tuple[str, int]) -> socket.socket:
"""The TCP connection of a CONNECT: from ``exit_host`` when ``tcp_from_exit``, else from wherever the system chooses."""
if not self.tcp_from_exit:
@@ -647,12 +478,8 @@ class Gateway:
if self.forwards_for_real and asks_the_world(self.server, host, port):
self._send(c, self._reply(2)) # not allowed: the exit of this gateway is declared, it is not asked of the internet
return
target = self._target(host, port)
if not self._admits(host, port, getattr(_REQUEST, "atyp", 3), "tcp", target):
self._send(c, self._reply(2)) # not allowed: the gateway carries nothing outside the lab
return
try:
up = self._open_upstream(target)
up = self._open_upstream(self._target(host, port))
except OSError:
self._send(c, self._reply(5))
return
@@ -709,15 +536,13 @@ class Gateway:
``target`` is the real address the datagram is sent to from the exit socket (``out_port`` is that socket's port);
``reported_as`` is the address the client is told the reply came from (None: the real source). A subclass may also
answer by itself with ``answer(host, port, data)``. By default the fake STUN server, by name or by number, is
mapped and everything else is forwarded when it is the lab's (``_admits``); a datagram to any other destination is dropped and recorded."""
mapped and everything else is forwarded for real."""
if (host, dport) in ((STUN_NAME, STUN_PORT), (STUN_NUMBER, STUN_PORT), (MEASURE_NUMBER, STUN_PORT)):
if not self.stun_answers:
return None
# A real server answers from the address it was asked at; the fake STUN server is mapped, so its reply is
# reported as from the asked address (only when that was a literal: a name has no address to report).
return self.stun.address, ((host, dport) if atyp == 1 else None)
if not self._admits(host, dport, atyp, "udp"):
return None # not the lab's: dropped, and recorded
if self.forward_only_to is not None and host not in self.forward_only_to:
return None
return (host, dport), None
@@ -782,7 +607,6 @@ class Gateway:
self.datagrams.append((host, dport, payload))
self.datagram_log.append((host, dport, atyp, time.monotonic() - self.t0))
self.datagram_via.append((host, dport, index, time.monotonic() - self.t0))
self._dgram.index = index
routed = self._route(host, dport, atyp, payload, out_port, answer)
if routed is None:
continue
@@ -861,15 +685,12 @@ def silent_udp(*, exit_ip: str = EXIT, user: Optional[str] = None, password: Opt
# A tiny TCP-only SOCKS5 server for the e2e tests (the fixture `socks5_tcp_only` of conftest.py makes one).
# ----------------------------------------------------------------------------------------------------------------
class Socks5TcpOnly:
"""Minimal SOCKS5: no-auth, CONNECT (TCP) relayed to the lab, UDP ASSOCIATE refused.
"""Minimal SOCKS5: no-auth, CONNECT (TCP) relayed, UDP ASSOCIATE refused.
Reproduces a residential TCP-only proxy: pages load over TCP, but WebRTC's
UDP path is dead - which (for a no-camera page in default_address_only mode)
is exactly what made the default-route probe fail and ICE return zero
candidates before Fix C.
Hermetic like :class:`Gateway`: a CONNECT to a destination that is not the lab's (:func:`is_lab_destination`) is refused with reply 2 and
recorded in :attr:`guard` (written under ``$RUNNER_TEMP/invpw-evidence/socks5-tcp-only/`` when the server is closed).
"""
def __init__(self, exit_ip: Optional[str] = None):
@@ -878,12 +699,10 @@ class Socks5TcpOnly:
self._srv.bind(("127.0.0.1", 0))
self._srv.listen(16)
self.port = self._srv.getsockname()[1]
#: It relays a CONNECT (to the lab), so it declares its exit (what a launch behind it is told: the lab's, unless a test gives another).
#: It relays a CONNECT for real, so it declares its exit (what a launch behind it is told: the lab's, unless a test gives another).
self.exit_ip = exit_ip or _lab_exit()
declare_exit(self.server, self.exit_ip)
self.udp_associate_attempts = 0
#: What refuses (and records) every CONNECT that is not the lab's.
self.guard = LabGuard("socks5-tcp-only")
self._stop = False
self._t = threading.Thread(target=self._serve, daemon=True)
self._t.start()
@@ -943,10 +762,6 @@ class Socks5TcpOnly:
conn.sendall(b"\x05\x02\x00\x01\x00\x00\x00\x00\x00\x00") # not allowed: the exit is declared, not asked of the internet
conn.close()
return
if not self.guard.admits(addr, port, atyp, "tcp"):
conn.sendall(b"\x05\x02\x00\x01\x00\x00\x00\x00\x00\x00") # not allowed: nothing outside the lab is carried
conn.close()
return
try:
upstream = socket.create_connection((addr, port), timeout=30)
except OSError:
@@ -986,4 +801,3 @@ class Socks5TcpOnly:
self._srv.close()
except Exception:
pass
self.guard.write_evidence()
-111
View File
@@ -1,111 +0,0 @@
"""The stack watchdog of the e2e tests: a Python thread that writes the stack of every thread of the process, holding the GIL.
``tests/conftest.py`` arms it for each e2e test and cancels it in the teardown. Once the threshold of a test is passed, and then every period until the
test ends, it appends one dump to the file it was given: ``Timeout (h:mm:ss)!`` (the time since the arming) and then, for every thread, ``Thread 0x... (most
recent call first):`` and its frames as `` File "...", line N in name``. Two identical dumps mean a stuck test, two different ones a slow test.
Why a Python thread and not ``faulthandler.dump_traceback_later``: that watchdog is a C thread, and it copies the frames of every thread WITHOUT the GIL
(``_Py_DumpTracebackThreads``, which CPython documents as "for debug purpose only ... after a segmentation fault, at fatal error") while the other threads
keep running and keep changing their frames. On Windows two full dumps of a pytest worker show it dead inside ``dump_frame`` of ``faulthandler_thread``,
reading a frame another thread was freeing. This thread takes ``sys._current_frames()`` with the GIL held, so a frame it reads cannot change under it.
One thread per process, started by the first ``arm`` and reused by every later test. It writes nothing to stdout or stderr. After ``cancel`` returns, nothing
more is written for that test: the dump is written under the lock that ``cancel`` takes.
Known limit: a thread that holds the GIL and never releases it (a C call that does not let go) keeps this thread from running, so it cannot write. That case
is pytest's ``faulthandler.enable()``, which writes only when the process dies. The 420 s limit of the run (``--timeout-method thread``) still names the test.
"""
from __future__ import annotations
import sys
import threading
import time
def _clock(seconds: float) -> str:
whole = int(seconds)
return "%d:%02d:%02d" % (whole // 3600, whole % 3600 // 60, whole % 60)
class StackWatchdog:
def __init__(self) -> None:
self._cond = threading.Condition()
self._thread: threading.Thread | None = None
self._armed = False
self._file = None
self._started = 0.0
self._period = 0.0
self._due = 0.0
@property
def thread(self) -> threading.Thread | None:
"""The one thread of the process (None until the first ``arm``)."""
return self._thread
def arm(self, nodeid: str, threshold_s: float, period_s: float | None = None, file=None) -> None:
"""From ``threshold_s`` seconds on, and then every ``period_s`` (the threshold by default), write the stacks of all threads to ``file`` until ``cancel``."""
period = threshold_s if period_s is None else period_s
with self._cond:
self._file = file
self._started = time.monotonic()
self._period = max(period, 0.0005)
self._due = self._started + threshold_s
self._armed = True
try:
file.write("\n--- %s ---\n" % nodeid)
file.flush()
except Exception:
pass
if self._thread is None or not self._thread.is_alive():
self._thread = threading.Thread(target=self._run, name="invpw-stack-watchdog", daemon=True)
self._thread.start()
self._cond.notify_all()
def cancel(self) -> None:
"""Nothing more is written for the armed test once this returns: a dump in progress finishes first, because it is written under the same lock."""
with self._cond:
self._armed = False
self._file = None
self._cond.notify_all()
def _run(self) -> None:
with self._cond:
while True:
if not self._armed:
self._cond.wait()
continue
left = self._due - time.monotonic()
if left > 0:
# Waiting lets go of the lock, so that a cancel or a new arm is never kept out by a watchdog with a short period.
self._cond.wait(left)
continue
self._write_one_dump()
self._due = time.monotonic() + self._period
def _write_one_dump(self) -> None:
mine = threading.get_ident()
names = {t.ident: t.name for t in threading.enumerate()}
out = ["Timeout (%s)!\n" % _clock(time.monotonic() - self._started)]
for ident, frame in sys._current_frames().items():
if ident == mine:
continue
name = names.get(ident)
out.append("\nThread 0x%016x%s (most recent call first):\n" % (ident, " [%s]" % name if name else ""))
while frame is not None:
out.append(' File "%s", line %d in %s\n' % (frame.f_code.co_filename, frame.f_lineno, frame.f_code.co_name))
frame = frame.f_back
try:
self._file.write("".join(out))
self._file.flush()
except Exception:
# A watchdog that fails the suite over its OWN problem is worse than the defect it is watching for.
pass
_the_watchdog = StackWatchdog()
arm = _the_watchdog.arm
cancel = _the_watchdog.cancel
def the_thread() -> threading.Thread | None:
return _the_watchdog.thread
-190
View File
@@ -1,190 +0,0 @@
"""The strace stand-in of the Linux font tests: the engine's directory as links, whose executable runs the real one under ``strace`` in the
engine's place (same pid, same process group), and what reads its log (who is the parent and who a content process) and cleans its group.
Used by tests/test_the_parent_reads_the_bundle_from_fontconfig_s_cache_linux_e2e.py. No test of its own, no browser."""
from __future__ import annotations
import os
import re
import shutil
import signal
import stat
import subprocess
import time
from pathlib import Path
import pytest
_SYSCALLS = ("execve,clone,clone3,fork,vfork,open,openat,stat,lstat,"
"newfstatat,statx,access,faccessat,faccessat2,readlink")
#: The network calls, traced only when a caller asks (``network=True``: scripts/ci_ab_host.py, NET_CALLS): the font tests do not.
_NET_SYSCALLS = "socket,connect,bind,sendto,sendmsg,sendmmsg"
#: The signals a trace with ``exit_status`` records (``-e signal=``): the ones that end a process or are sent to end it, with the sender (``si_pid``) and the faulting address
#: (``si_addr``). The lines they make (``1234 --- SIGSEGV {si_signo=SIGSEGV, ...} ---``) are evidence of a crash and never data of the comparison (scripts/ci_ab_host.py drops
#: them when it reads the log). strace stops the tracee at every signal whether it prints it or not, so printing changes nothing the browser does.
RECORDED_SIGNALS = "SIGSEGV,SIGBUS,SIGABRT,SIGILL,SIGFPE,SIGSYS,SIGTRAP,SIGTERM,SIGINT,SIGQUIT,SIGHUP"
def _strace_options(fd_paths: bool = False, exit_status: bool = False) -> str:
"""strace's own flags: quiet, follow forks, and die with the traced process
when this build knows --kill-on-exit; ``fd_paths`` adds ``-y``, which prints the path of every file descriptor
(``3</usr/share/fonts>``), so that a path relative to a directory descriptor is known; ``exit_status`` keeps the lines that say how each process ended
(``+++ exited with 0 +++``, ``+++ killed by SIGKILL +++``: ``-q`` and not ``-qq``) and records the fatal signals (``RECORDED_SIGNALS``)."""
help_text = subprocess.run([shutil.which("strace"), "-h"], capture_output=True,
text=True).stdout
return (("-f -q -e signal=%s -s 4096" % RECORDED_SIGNALS) if exit_status else "-f -qq -s 4096") + (" -y" if fd_paths else "") + (" --kill-on-exit" if "--kill-on-exit" in help_text else "")
def _require_strace_can_trace(tmp: Path) -> None:
"""strace needs ptrace: a container or yama can refuse it, and then the
failure is the environment's, said as such, not the launch's."""
probe = subprocess.run([shutil.which("strace"), "-o", str(tmp / "probe.log"), "true"],
capture_output=True, text=True)
if probe.returncode != 0:
pytest.fail("strace cannot trace here: %s" % (probe.stderr.strip() or probe.returncode),
pytrace=False)
def _stand_in(binary: str, tree: Path, log: Path, pidfile: Path, syscalls: str = _SYSCALLS,
timestamps: bool = False, fd_paths: bool = False, network: bool = False, exit_status: bool = False,
cores: bool = False) -> str:
"""A copy of the engine's directory made of links, whose executable runs
the real one under strace, in the engine's place.
The script writes its pid and execs strace: the pid stays, and so does the
process group its launcher gave it. The core spawns the engine as the
leader of a process group of its own (``posix_spawn`` with ``setpgroup=0``,
as Playwright's launcher does with ``detached: true``), so that group holds
strace and everything it traces, and ``_kill_group`` kills the group of the
pid (``os.getpgid``). The script used to exec ``setsid``: setsid(1) forks
when its caller leads a process group, its parent exited 0 at once, and the
core saw the engine exit during startup (candidate 44161687675).
``syscalls`` is what strace traces; ``timestamps`` adds ``-ttt`` (the epoch
seconds after each pid), which ``_LINE`` does not read: a caller that asks
for them strips them first (``test_the_parent_reads_the_bundle_from_fontconfig_s_cache_linux_e2e``);
``fd_paths`` adds ``-y`` (scripts/ci_ab_host.py reads the paths the tree touched, and knows a socket by its inode);
``network`` adds the network calls to ``syscalls`` (scripts/ci_ab_host.py reads the netlink sockets and the public destinations);
``cores`` lets the tree dump core (``ulimit -c unlimited``) and changes nothing else: the working directory stays the launcher's, so the paths the trace reads
are the same, and where the kernel writes the core is the job's ``kernel.core_pattern`` (scripts/ci_ab_host.py)."""
if network:
syscalls = syscalls + "," + _NET_SYSCALLS
real = Path(os.path.realpath(binary))
tree.mkdir()
for entry in real.parent.iterdir():
if entry.name != real.name:
(tree / entry.name).symlink_to(entry)
script = tree / real.name
cores_script = "ulimit -c unlimited\n" if cores else ""
script.write_text(
"#!/bin/sh\n"
"echo $$ > %s\n"
"%s"
'exec %s %s -o %s -e trace=%s %s "$@"\n'
% (pidfile, cores_script, shutil.which("strace"), _strace_options(fd_paths, exit_status) + (" -ttt" if timestamps else ""), log, syscalls, real))
script.chmod(script.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
return str(script)
_LINE = re.compile(r"^(\d+)\s+(\w+)\((.*)$")
# strace -f splits a call that another thread interrupts in two lines:
# "PID clone3({...} <unfinished ...>" and "PID <... clone3 resumed>) = CHILD".
_RESUMED = re.compile(r"^(\d+)\s+<\.\.\. (\w+) resumed>(.*)$")
_RESULT = re.compile(r"=\s+(\d+)\s*$")
def _roles(lines: list, real_binary: str):
"""``(role, argv_of)`` for a strace log read as lines: ``role(pid)`` is ``"parent"``, ``"content"`` or ``"other"`` (walking up the
clones to the process that executed the engine), ``argv_of`` maps a pid to the arguments of the last execve of the engine it made."""
parent_of = {}
argv_of = {}
for line in lines:
m = _LINE.match(line) or _RESUMED.match(line)
if not m:
continue
pid, call, rest = int(m.group(1)), m.group(2), m.group(3)
if call in ("clone", "clone3", "fork", "vfork"):
r = _RESULT.search(rest)
if r:
parent_of[int(r.group(1))] = pid
elif call == "execve" and real_binary in rest:
# The arguments are on the first line even when the result comes
# on a resumed one; the last execve of a process is what it runs.
argv_of[pid] = rest
def role(pid: int) -> str:
seen = set()
while pid not in seen:
seen.add(pid)
argv = argv_of.get(pid)
if argv is not None and real_binary in argv:
return "content" if "-contentproc" in argv else "parent"
if pid not in parent_of:
break
pid = parent_of[pid]
return "other"
return role, argv_of
def _group_of(pidfile: Path):
"""The process group of the stand-in, read from its living pid (``os.getpgid``); None when it is gone or wrote no pid."""
try:
return os.getpgid(int(pidfile.read_text().strip()))
except (OSError, ValueError):
return None
def _kill_group(pidfile: Path):
"""Kill the stand-in's process group: strace, the browser and its children. Returns the group killed, or None.
Looking for the stand-in's path in the command lines found nothing (strace
and its children carry the real binary's path), so the group is the handle:
the group of the stand-in's pid, not the pid taken as a group id. Never the
group of this test: a stand-in started inside it is killed alone."""
pgid = _group_of(pidfile)
if pgid is None:
return None
if pgid == os.getpgrp():
try:
os.kill(int(pidfile.read_text().strip()), signal.SIGKILL)
except (OSError, ValueError):
pass
return None
try:
os.killpg(pgid, signal.SIGKILL)
except OSError:
pass
return pgid
def _detached(argv: list, **kwargs) -> subprocess.Popen:
"""A process started as the core starts the engine: the leader of a process group of its own (``posix_spawn`` with
``setpgroup=0`` in ``invisible_core.juggler.connection._spawn_posix``)."""
return subprocess.Popen(argv, process_group=0, **kwargs)
def _group_members(pgid: int) -> list:
"""Pids still in the process group ``pgid``."""
members = []
for pid in os.listdir("/proc"):
if not pid.isdigit():
continue
try:
stat_line = Path("/proc/%s/stat" % pid).read_text()
except OSError:
continue
fields = stat_line.rsplit(")", 1)[1].split()
# fields: state ppid pgrp ...; a zombie is already dead.
if fields[0] != "Z" and int(fields[2]) == pgid:
members.append(int(pid))
return members
def _wait_for_exit(pgid: int, seconds: float = 30.0) -> list:
end = time.monotonic() + seconds
left = _group_members(pgid)
while left and time.monotonic() < end:
time.sleep(0.1)
left = _group_members(pgid)
return left
+6 -70
View File
@@ -93,15 +93,6 @@ def _attrs(data: bytes) -> Dict[int, bytes]:
return out
def is_deallocation(data: bytes) -> bool:
"""Whether a datagram is a TURN deallocation, by what it means (RFC 5766 section 7.1): a STUN Refresh (0x0004) whose LIFETIME (0x000D) is 0. A Refresh with a lifetime above 0, with
none, or any other message type, is not one. The one reading of it: the TURN server of the lab and the gateway of the lab both use it."""
if len(data) < 20 or struct.unpack("!I", data[4:8])[0] != MAGIC or struct.unpack("!H", data[:2])[0] != 0x0004:
return False
lifetime = _attrs(data).get(0x000D)
return lifetime is not None and len(lifetime) == 4 and struct.unpack("!I", lifetime)[0] == 0
def _attr(t: int, v: bytes) -> bytes:
return struct.pack("!HH", t, len(v)) + v + b"\x00" * (-len(v) % 4)
@@ -120,39 +111,11 @@ def _message(mtype: int, tid: bytes, attrs: bytes, key: Optional[bytes] = None)
return head + attrs + _attr(0x0008, mac)
def long_term_key(user: str) -> bytes:
"""The long-term credential key of RFC 5389 section 15.4: md5(username:realm:password)."""
return hashlib.md5(("%s:%s:%s" % (user, REALM, PASSWORD)).encode(), usedforsecurity=False).digest()
def integrity_valid(data: bytes, user: str) -> bool:
"""Whether the MESSAGE-INTEGRITY of a request is the HMAC-SHA1 under the long-term key of ``user`` (RFC 5389 section 15.4): over the message up to the
attribute, with the length field of the header set as if the message ended with that attribute (24 bytes more than what came before it). A request
with no MESSAGE-INTEGRITY, or a truncated one, is not valid."""
i = 20
while i + 4 <= len(data):
t, n = struct.unpack("!HH", data[i:i + 4])
if t == 0x0008:
if n != 20 or i + 24 > len(data):
return False
head = data[:2] + struct.pack("!H", i + 24 - 20) + data[4:20]
return hmac.compare_digest(hmac.new(long_term_key(user), head + data[20:i], hashlib.sha1).digest(), data[i + 4:i + 24])
i += 4 + ((n + 3) & ~3)
return False
class TurnServer:
"""UDP TURN server on 127.0.0.1. ``seen`` is every datagram as (source ip, source port, STUN type), in order;
``requests`` the same datagrams as (monotonic time, transaction id, STUN type, carries credentials): a retransmission has the
transaction id of the request it repeats, so the TRANSACTIONS of a road are the distinct ids (:meth:`transactions`);
``allocations`` the successful Allocates as (source ip, source port, username, time); ``deallocations`` the requests that END an allocation as (source ip, source
port, transaction id, time, index in ``allocations`` of the allocation they end, or None when that source has none): a deallocation is recognised by what it means, a
Refresh (0x0004) whose LIFETIME (0x000D) is 0 (RFC 5766 section 7.1), not by its type: a Refresh with a lifetime above 0 keeps the allocation and is not one. The server
answers it as it answers any Refresh; a retransmission is another datagram of the same transaction (:meth:`deallocation_transactions`).
A request that carries USERNAME is checked: its MESSAGE-INTEGRITY must be the HMAC under the long-term key of that user (``PASSWORD``).
A missing or wrong one is answered 401 with the realm and the nonce, makes no allocation, and is written in ``refused`` as
(source ip, source port, username, transaction id, time): a client with the wrong password never gets a relay here, as on a real server."""
``allocations`` the successful Allocates as (source ip, source port, username, time)."""
def __init__(self) -> None:
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
@@ -161,8 +124,6 @@ class TurnServer:
self.seen: List[Tuple[str, int, int]] = []
self.allocations: List[Tuple[str, int, str, float]] = []
self.requests: List[Tuple[float, bytes, int, bool]] = []
self.deallocations: List[Tuple[str, int, bytes, float, Optional[int]]] = []
self.refused: List[Tuple[str, int, str, bytes, float]] = []
self._closed = False
threading.Thread(target=self._serve, daemon=True).start()
@@ -174,17 +135,6 @@ class TurnServer:
first.setdefault(request[1], request)
return sorted(first.values(), key=lambda r: r[0])
def deallocation_transactions(self) -> List[Tuple[str, int, bytes, float, Optional[int]]]:
"""The first datagram of each deallocation transaction, in order: a retransmission of it is not another deallocation."""
first: Dict[bytes, Tuple[str, int, bytes, float, Optional[int]]] = {}
for record in list(self.deallocations):
first.setdefault(record[2], record)
return sorted(first.values(), key=lambda r: r[3])
def deallocation_tids(self) -> set:
"""The transaction ids (bytes) of every deallocation received: what ties its datagrams on the wire to the server's record of it."""
return {record[2] for record in list(self.deallocations)}
def close(self) -> None:
self._closed = True
self.sock.close()
@@ -198,40 +148,26 @@ class TurnServer:
if len(data) < 20 or struct.unpack("!I", data[4:8])[0] != MAGIC:
continue
mtype, tid = struct.unpack("!H", data[:2])[0], data[8:20]
attrs = _attrs(data)
if is_deallocation(data): # recorded BEFORE the request: whoever reads `requests` already knows which of them it ended
held = [i for i, a in enumerate(self.allocations) if a[:2] == (src[0], src[1])]
self.deallocations.append((src[0], src[1], tid, time.monotonic(), held[-1] if held else None))
self.seen.append((src[0], src[1], mtype))
attrs = _attrs(data)
self.requests.append((time.monotonic(), tid, mtype, 0x0008 in attrs and 0x0006 in attrs))
user_raw = attrs.get(0x0006)
if mtype in (0x0003, 0x0004, 0x0008, 0x0009) and user_raw is not None:
user = user_raw.decode(errors="replace")
if not integrity_valid(data, user): # the wrong password, or no MESSAGE-INTEGRITY: 401, no allocation
self.refused.append((src[0], src[1], user, tid, time.monotonic()))
self.sock.sendto(_message(mtype | 0x0110, tid, self._unauthorized()), src)
continue
if mtype == 0x0003: # Allocate
if 0x0008 not in attrs or 0x0006 not in attrs: # no credentials: 401 with a realm and a nonce
self.sock.sendto(_message(0x0113, tid, self._unauthorized()), src)
err = _attr(0x0009, b"\x00\x00\x04\x01Unauthorized") + _attr(0x0014, REALM.encode()) + _attr(0x0015, NONCE.encode())
self.sock.sendto(_message(0x0113, tid, err), src)
continue
user = attrs[0x0006].decode(errors="replace")
key = long_term_key(user)
key = hashlib.md5(("%s:%s:%s" % (user, REALM, PASSWORD)).encode(), usedforsecurity=False).digest()
body = (_attr(0x0016, _xor_addr(*RELAYED)) + _attr(0x0020, _xor_addr(src[0], src[1])) +
_attr(0x000D, struct.pack("!I", 600)))
self.allocations.append((src[0], src[1], user, time.monotonic()))
self.sock.sendto(_message(0x0103, tid, body, key), src)
elif mtype in (0x0004, 0x0008, 0x0009): # Refresh, CreatePermission, ChannelBind
user = attrs.get(0x0006, b"").decode(errors="replace")
key = long_term_key(user)
key = hashlib.md5(("%s:%s:%s" % (user, REALM, PASSWORD)).encode(), usedforsecurity=False).digest()
body = _attr(0x000D, struct.pack("!I", 600)) if mtype == 0x0004 else b""
self.sock.sendto(_message(mtype | 0x0100, tid, body, key), src)
@staticmethod
def _unauthorized() -> bytes:
"""The attributes of a 401: ERROR-CODE, the realm and the nonce of the long-term credential."""
return _attr(0x0009, b"\x00\x00\x04\x01Unauthorized") + _attr(0x0014, REALM.encode()) + _attr(0x0015, NONCE.encode())
# ── the gateway ────────────────────────────────────────────────────────────────
+20 -45
View File
@@ -12,7 +12,12 @@ Nothing here opens a browser; the unit test ``test_the_udp_line_helpers.py`` hol
from __future__ import annotations
import ipaddress
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple
from typing import Any, Callable, Dict, List, Optional, Sequence
#: How much slower than the first visit a later visit may load, in milliseconds, on the roads where UDP does not work. A
#: retail Firefox on a network that drops UDP loads the later visits as fast as the first (15 of 15 sessions, h2/h2/h2): an h3
#: attempt that waits for a timeout before it falls back to h2 would be seconds.
LOAD_MARGIN_MS = 1500
#: The visits of one page in one context, by kind of road. With NO proxy and the native DNS the retail is measured in loopback
#: and is exact: h2, h3, h3 over three visits. BEHIND A PROXY the names are resolved by DoH, the browser learns the Alt-Svc
@@ -157,7 +162,7 @@ def expected_protocols(road: str) -> str:
return ("h2 on the first visit, then h3 from a later visit on and h3 on every one after it, within %d visits "
"(retail with DoH and UDP free: h2/h2/h3 in 9 of 15, h2/h2/h2 in 4, h2/h3/h3 in 2, and h3 first in 3 of 15 in the "
"third run when the DNS answer carries the HTTPS record; this fixture has none: h2 first)" % visits)
return "h2 on every one of %d visits, with no attempt at h3 (retail with UDP dropped: h2/h2/h2 in 15 of 15)" % visits
return "h2 on every one of %d visits, as fast as the first (retail with UDP dropped: h2/h2/h2 in 15 of 15)" % visits
def no_https_record(host: str, doh: Any = None) -> List[str]:
@@ -180,62 +185,27 @@ def no_https_record(host: str, doh: Any = None) -> List[str]:
return problems
def relay_activity(gateway: Any) -> Tuple[int, int]:
"""What a SOCKS5 gateway of the tests has been asked for so far, as ``(UDP ASSOCIATE requests, datagrams its relay carried)``: the
requests answered or refused, the datagrams of every association. Taken twice (before the first visit, which is after the core's own
measurement of the gateway, and after the last), the difference is what the ENGINE asked of the relay while it visited the page."""
return int(gateway.associates), len(gateway.datagrams)
def h3_attempts(server: Any, gateway: Any = None, before: Optional[Tuple[int, int]] = None) -> List[str]:
"""What the test server (and, behind a SOCKS5 gateway, the gateway) says about a TRY at HTTP/3, as sentences; an empty list when nothing tried.
Behind a SOCKS5 gateway that is not coherent the engine does not carry UDP (nsSOCKSUDPIOLayer.cpp, ``StealthPutSocksUdpLayer``: the socket of an
HTTP/3 connection gets a layer that is ``Blocked``, no association is asked for): an engine that tried would ask the gateway for a UDP
ASSOCIATE (a refused one is a request too) or send a datagram to its relay, whether or not the datagram goes on to the server.
``gateway`` and ``before`` (:func:`relay_activity` taken before the first visit) add those two to the answer.
A retail Firefox on a network that drops UDP (and behind an HTTP proxy, which has no UDP at all) never tries HTTP/3: it reads h2 and
nothing is sent to the h3 port the Alt-Svc announces. An engine that TRIES sends its QUIC Initial there first, and then waits for
an answer that does not come before it falls back to h2: the wait is the tell, and the datagram is the attempt. The attempt is
read where it is born, as a datagram that reached the UDP port of ``server`` (``H3Server.udp_datagrams``, every datagram, with
or without a handshake), never as a duration: how long a fallback takes is the speed of the machine, whether it was tried is the engine."""
problems: List[str] = []
seen = list(getattr(server, "udp_datagrams", ()))
if seen:
problems.append("%d UDP datagrams reached the h3 port %s of the server, from %s: the engine tried HTTP/3 (and, where nothing answers, "
"waits for a timeout before the fallback to h2)" % (len(seen), getattr(server, "port", "?"), sorted(set(seen))))
if gateway is not None:
if before is None:
raise ValueError("a gateway is judged against what it had been asked before the first visit (relay_activity)")
associates, datagrams = (now - was for now, was in zip(relay_activity(gateway), before))
if associates:
problems.append("the engine asked the gateway for %d UDP ASSOCIATE while it visited the page: it tried to carry UDP (HTTP/3) "
"through a gateway that was not measured coherent" % associates)
if datagrams:
problems.append("%d datagrams went into the relay of the gateway while the page was visited: the engine tried HTTP/3 "
"through a gateway that was not measured coherent" % datagrams)
return problems
def judge_visits(road: str, protocols: Sequence[str]) -> List[str]:
def judge_visits(road: str, protocols: Sequence[str], walls_ms: Sequence[float]) -> List[str]:
"""What is wrong with the visits of one page on ``road``, as sentences; an empty list when nothing is.
``protocols`` is the ``nextHopProtocol`` of each visit, :func:`visits_for` entries. No duration is judged: that an h3 attempt
waited for a timeout is read as the attempt itself (:func:`h3_attempts`). The rules, from the retail:
``protocols`` is the ``nextHopProtocol`` of each visit and ``walls_ms`` the time ``page.goto`` took to the load event;
both have :func:`visits_for` entries. The rules, from the retail:
* ``direct``: exactly h2, h3, h3.
* ``socks5_coherent``: the first visit is h2 (the fixture is reached by an address: no HTTPS record exists, so nothing
tells the browser about h3 before the first connection; the retail itself reads h3 first when the DNS answer carries
the record, so this is a rule of the fixture, checked with :func:`no_https_record`); every later visit is h2 or h3, but once one is h3 all the following are (h3 never goes back to h2); and at
least one visit is h3 (it is NOT required at the second: h2/h2/h3 is the commonest retail sequence).
* the roads where UDP is dropped: h2 on every visit (and no attempt at h3: :func:`h3_attempts`, read by the test)."""
* the roads where UDP is dropped: h2 on every visit, and no visit loads more than :data:`LOAD_MARGIN_MS` slower than the
first (a fallback that waits for a timeout is a tell)."""
problems: List[str] = []
protocols = list(protocols)
protocols, walls_ms = list(protocols), list(walls_ms)
visits = visits_for(road)
said = "a retail Firefox reads %s on this road" % expected_protocols(road)
if len(protocols) != visits:
problems.append("%d protocols for %d visits: %s" % (len(protocols), visits, protocols))
if len(walls_ms) != visits:
problems.append("%d load times for %d visits: %s" % (len(walls_ms), visits, walls_ms))
if protocols and protocols[0] == "h3":
problems.append("visit 1 read h3: in this fixture nothing had told the browser yet that the server speaks h3 (no "
"name, no HTTPS record): something told it, or the fixture changed")
@@ -251,4 +221,9 @@ def judge_visits(road: str, protocols: Sequence[str]) -> List[str]:
problems.append("the protocols of the %d visits are %s, %s" % (visits, protocols, said))
elif protocols != ["h2"] * visits:
problems.append("the protocols of the %d visits are %s, %s" % (visits, protocols, said))
if len(walls_ms) == visits and road in _H2_ROADS:
for number in range(2, visits + 1):
if walls_ms[number - 1] > walls_ms[0] + LOAD_MARGIN_MS:
problems.append("visit %d loaded in %d ms against %d ms for visit 1 (more than %d ms slower): an h3 attempt "
"that waited for a timeout before the fallback" % (number, walls_ms[number - 1], walls_ms[0], LOAD_MARGIN_MS))
return problems
-27
View File
@@ -1,27 +0,0 @@
"""What a test that cannot get a WebGL context writes down, so that the red says why (a pure helper, no browser).
A page asks for a context and gets ``null``: the page learns nothing more unless it listens for ``webglcontextcreationerror`` on the canvas
before it asks (``statusMessage``). The probe of the test returns an object with ``unavailable: true`` and what it heard instead of ``null``;
``split_probe`` turns that into the old ``None`` (so that the assertion stays as it was) and the record of the attempt, and ``unavailable_message``
is the sentence of the assertion with both attempts appended.
"""
from __future__ import annotations
from typing import Any, Optional, Tuple
#: The pause, in milliseconds, between the first attempt and the second one (a diagnostic: the verdict is the first attempt's).
SECOND_ATTEMPT_AFTER_MS = 2000
UNAVAILABLE = "webgl is unavailable: a WebGL canvas cannot be read"
def split_probe(result: Any) -> Tuple[Optional[Any], Optional[dict]]:
"""``(got, first)``: ``got`` is what the test reads (``None`` when there was no context, exactly as the old probe returned), ``first`` the
record of the failed attempt (``None`` when a context was made)."""
if isinstance(result, dict) and result.get("unavailable") is True:
return None, result
return result, None
def unavailable_message(first: Optional[dict], second: Any) -> str:
"""The message of the assertion: the old sentence, then what the first attempt and the second one (2 s later) reported."""
return "%s | first: %r; second after 2 s: %r" % (UNAVAILABLE, first, second)
-56
View File
@@ -1,56 +0,0 @@
"""Every pytest process of a Windows job that keeps WER dumps lets Windows Error Reporting see its crash: the bit SEM_NOGPFAULTERRORBOX of its error mode is cleared.
A process whose error mode carries SEM_NOGPFAULTERRORBOX (0x0002) never invokes Windows Error Reporting when it dies from an unhandled exception, so the
LocalDumps key of python.exe that e2e.yml sets (a full dump into ``$RUNNER_TEMP/invpw-evidence/dumps/python``) is never read: the pytest controllers of the
runner are born with 0x0003 (SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX), and every child inherits the mode of its parent, so every xdist worker is born
with it too and a worker that crashes leaves no dump.
https://learn.microsoft.com/windows/win32/api/errhandlingapi/nf-errhandlingapi-seterrormode
``clear_for_wer_dumps()``: tests/conftest.py calls it in ``pytest_configure``, which the controller and every xdist worker run. It acts only when ALL of this
holds, so nothing changes on a developer's machine, on Linux, or in a job that did not set LocalDumps:
* the system is Windows;
* ``$INVPW_WER_DUMPS`` (the one variable the "Windows Error Reporting keeps a full dump..." step of each Windows job of e2e.yml exports to ``$GITHUB_ENV``) names an
existing folder: the folder the dumps go to.
It clears bit 0x0002 and keeps every other bit of the mode, and appends one line to ``error-mode.log`` in the parent of that folder (``invpw-evidence/dumps``, inside the evidence the job
uploads): ``pid <n> error mode born 0x<hex>, now 0x<hex>``, so the evidence shows the bit was cleared in every process. It writes nothing to stdout or stderr, and it
never raises: a failure is a line of that log, not a failed test.
"""
from __future__ import annotations
import os
import sys
from pathlib import Path
#: The variable the Windows jobs export: the folder LocalDumps of python.exe writes to.
ENV_VAR = "INVPW_WER_DUMPS"
LOG_NAME = "error-mode.log"
#: SEM_NOGPFAULTERRORBOX: the process is not reported to Windows Error Reporting.
SEM_NOGPFAULTERRORBOX = 0x0002
def clear_for_wer_dumps(environ=None) -> None:
environ = os.environ if environ is None else environ
if sys.platform != "win32":
return
folder = environ.get(ENV_VAR)
if not folder or not os.path.isdir(folder):
return
log = Path(folder).resolve().parent / LOG_NAME
try:
import ctypes
kernel32 = ctypes.WinDLL("kernel32")
kernel32.GetErrorMode.restype = ctypes.c_uint
kernel32.SetErrorMode.argtypes = [ctypes.c_uint]
kernel32.SetErrorMode.restype = ctypes.c_uint
born = kernel32.GetErrorMode()
kernel32.SetErrorMode(born & ~SEM_NOGPFAULTERRORBOX)
line = "pid %d error mode born 0x%04x, now 0x%04x\n" % (os.getpid(), born, kernel32.GetErrorMode())
except Exception as exc: # best effort: the evidence says what went wrong, the test run goes on
line = "pid %d error mode not cleared: %s: %s\n" % (os.getpid(), type(exc).__name__, exc)
try:
with open(log, "a", encoding="utf-8") as handle:
handle.write(line)
except OSError:
pass
-99
View File
@@ -1,99 +0,0 @@
"""What the window e2e tests share: a headed session of the product, and a wait on a condition of a page.
The sessions are HEADED on purpose. ``headless=True`` gives every session a display of its own (a fresh Xvfb on Linux, a fresh Win32 desktop on
Windows), so two of them never see each other; the focus and occlusion tests need two windows on ONE display, which is what two headed sessions of the
same run have (the Linux e2e runs under ``xvfb-run``). Both sessions use the same seed, so both windows are the same declared window and the second one
covers the first completely.
The first session is the one of the test's own thread; the second one lives in a thread of its own (``in_a_thread_of_its_own``, the pattern of
``test_popups_reach_the_client_e2e.py``): an open sync client keeps its asyncio loop marked as running in the thread that started it, and a second sync client
refuses to start there ("It looks like you are using Playwright Sync API inside the asyncio loop"). A sync client's objects belong to the thread that made
them, so everything the test does with the second session is handed to that thread (``run``).
"""
from __future__ import annotations
import contextlib
import queue
import threading
from typing import Any, Callable, Dict, Iterator, Optional
from _waits import Watch, watch
#: The seed only has to give two sessions the same window.
SEED = 21
#: The deadline of a wait for something that must happen, in seconds.
DEADLINE_S = 30
def launch(firefox_binary: str, *, extra_prefs: Optional[Dict[str, Any]] = None, pin: Optional[Dict[str, Any]] = None, headless: bool = False):
"""A session of the product (RFP off, the engine declared as the core launches it); ``extra_prefs`` and ``pin`` only where a test needs them."""
from invisible_playwright import InvisiblePlaywright
return InvisiblePlaywright(seed=SEED, binary_path=firefox_binary, headless=headless, locale="en-US", timezone="America/New_York",
extra_prefs=extra_prefs, pin=pin)
def wait_for_condition(page, sample: Callable[[], Any], done: Callable[[Any], Any], what: str, seconds: float = DEADLINE_S) -> Watch:
"""Until ``done(sample())``, reading the page between two looks. Red after ``seconds`` with what was seen on the way."""
result = watch(sample, done, seconds, lambda: page.wait_for_timeout(100))
assert result.ok, "%s; seen: %s" % (what, result.render())
return result
class SecondSession:
"""A session that lives in a thread of its own: ``run(fn)`` calls ``fn(session)`` in that thread and gives back its result or raises its error."""
def __init__(self) -> None:
self._jobs: "queue.Queue[Optional[tuple]]" = queue.Queue()
def run(self, fn: Callable[[Any], Any]) -> Any:
box: Dict[str, Any] = {}
done = threading.Event()
self._jobs.put((fn, box, done))
assert done.wait(300), "the second session did not answer within 300 s"
if "error" in box:
raise box["error"]
return box.get("value")
@contextlib.contextmanager
def in_a_thread_of_its_own(firefox_binary: str, *, extra_prefs: Optional[Dict[str, Any]] = None) -> Iterator[SecondSession]:
"""A second headed session on the same display, started and closed in a thread with no asyncio loop; the test keeps the first one in its own thread."""
handle = SecondSession()
up = threading.Event()
failure: Dict[str, BaseException] = {}
def serve() -> None:
try:
with launch(firefox_binary, extra_prefs=extra_prefs) as session:
up.set()
while True:
job = handle._jobs.get()
if job is None:
return
fn, box, done = job
try:
box["value"] = fn(session)
except BaseException as exc: # handed back to the test's thread by ``run``
box["error"] = exc
finally:
done.set()
except BaseException as exc: # the launch or the close of the session
failure["error"] = exc
finally:
up.set()
worker = threading.Thread(target=serve, name="second-session", daemon=True)
worker.start()
assert up.wait(300), "the second session did not start within 300 s"
if "error" in failure:
raise failure["error"]
try:
yield handle
finally:
handle._jobs.put(None)
worker.join(120)
assert not worker.is_alive(), "the second session did not close within 120 s"
if "error" in failure:
raise failure["error"]
-850
View File
@@ -1,850 +0,0 @@
"""What a client puts on the wire, read by a server of the lab: the TLS ClientHello, the HTTP/2 frames, the HTTP/1.1 request heads in wire order, and
what an HTTP/3 client says (QUIC transport parameters, the SETTINGS frame, the header order). No browser in here: every parser takes bytes, and the
unit tests (``test_wire_capture.py``, ``test_wire_capture_quic.py``) feed them a client of Python's ``ssl``, the ``h2`` library and ``aioquic``.
The use: the network A/B oracle (``scripts/ci_ab_network.py``) runs the same journey with two engines and compares what these servers saw, leaf by leaf.
* :func:`parse_client_hello` reads the record of a ClientHello with the standard library only: record and handshake version, the cipher suites in order,
the compression methods, the extensions in the order they were sent, and what is inside each of the known ones (supported_groups, signature_algorithms,
ALPN, key_share GROUPS, psk_key_exchange_modes, supported_versions, record_size_limit, ec_point_formats, ...). A GREASE value is written ``"GREASE"``.
What is random or secret per connection is NOT kept: the random, the session id, the bytes of a key share, the PSK identities and their ages, the
ECH config id, the encapsulated key. Only their lengths stay (a length is the shape of the hello, not a value of it).
* :func:`peek_client_hello` reads that record off a socket with ``MSG_PEEK`` until the whole record is buffered, so the same socket can then be handed to
``ssl`` as if nothing had been read (:func:`accept_with_hello`).
* :class:`FrameTap` reads the HTTP/2 frames of a connection from the raw bytes (``hyperframe``, which ``h2`` is made of): SETTINGS ids and values in order,
the WINDOW_UPDATEs, PRIORITY and PRIORITY_UPDATE, the priority fields of a HEADERS. :class:`H2Connection` is the server side (``h2``): it answers the
requests and writes down, per request, the pseudo-header order and every header name and value in the order they arrived.
* :class:`Http1Parser` keeps the request line and the header lines as they were written (the case, the order, the empty values); :func:`serve_http1` is
the server side, and the parser alone is what a tee in front of another server uses.
* :class:`WireServer` is one address and one port: TCP with TLS (HTTP/2 or HTTP/1.1 by the ALPN it offers) and, when asked, QUIC (HTTP/3 with
``aioquic``) on the same number, each connection written down.
Nothing here waits on a clock: a peek that is short of bytes is a poll with a deadline (a safety net, not a verdict), and every other wait is a blocking read.
"""
from __future__ import annotations
import socket
import socketserver
import ssl
import struct
import sys
import tempfile
import threading
import time
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Tuple
#: The longest ClientHello record a peek waits for. A hello with a post-quantum key share and an ECH payload is about 2 KB; 16 KB is the limit of a record.
MAX_HELLO_RECORD = 16384 + 5
#: The deadline of a peek, in seconds. A safety net: a client that sent half a hello and stopped, not a measure of anything.
PEEK_DEADLINE_S = 30.0
GREASE = "GREASE"
EXTENSION_NAMES = {
0: "server_name", 1: "max_fragment_length", 5: "status_request", 10: "supported_groups", 11: "ec_point_formats", 13: "signature_algorithms",
14: "use_srtp", 15: "heartbeat", 16: "alpn", 18: "signed_certificate_timestamp", 21: "padding", 22: "encrypt_then_mac", 23: "extended_master_secret",
27: "compress_certificate", 28: "record_size_limit", 34: "delegated_credentials", 35: "session_ticket", 41: "pre_shared_key", 42: "early_data",
43: "supported_versions", 44: "cookie", 45: "psk_key_exchange_modes", 49: "post_handshake_auth", 50: "signature_algorithms_cert", 51: "key_share",
17513: "application_settings", 17613: "application_settings_new", 65037: "encrypted_client_hello", 65281: "renegotiation_info",
}
#: The QUIC transport parameters by id (RFC 9000 18.2 and the extensions seen in browsers).
QUIC_PARAMETER_NAMES = {
0x00: "original_destination_connection_id", 0x01: "max_idle_timeout", 0x02: "stateless_reset_token", 0x03: "max_udp_payload_size",
0x04: "initial_max_data", 0x05: "initial_max_stream_data_bidi_local", 0x06: "initial_max_stream_data_bidi_remote",
0x07: "initial_max_stream_data_uni", 0x08: "initial_max_streams_bidi", 0x09: "initial_max_streams_uni", 0x0A: "ack_delay_exponent",
0x0B: "max_ack_delay", 0x0C: "disable_active_migration", 0x0D: "preferred_address", 0x0E: "active_connection_id_limit",
0x0F: "initial_source_connection_id", 0x10: "retry_source_connection_id", 0x11: "version_information", 0x20: "max_datagram_frame_size",
0x2AB2: "grease_quic_bit", 0x2AB1: "reset_stream_at", 0x3127: "initial_rtt", 0x1057: "google_connection_options", 0x4752: "google_version",
}
#: The parameters whose value is an identifier or a secret of the connection: only its length is kept.
QUIC_OPAQUE = {0x00, 0x02, 0x0D, 0x0F, 0x10}
H2_FRAME_TYPES = {0: "DATA", 1: "HEADERS", 2: "PRIORITY", 3: "RST_STREAM", 4: "SETTINGS", 5: "PUSH_PROMISE", 6: "PING", 7: "GOAWAY",
8: "WINDOW_UPDATE", 9: "CONTINUATION", 0x10: "PRIORITY_UPDATE"}
H2_PREFACE = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"
class NotAClientHello(ValueError):
"""The bytes are not one TLS record that holds a ClientHello."""
def is_grease(value: int) -> bool:
"""A GREASE value of RFC 8701: both bytes are the same and end in 0xa (0x0a0a, 0x1a1a ... 0xfafa)."""
return (value & 0x0F0F) == 0x0A0A and (value >> 8) == (value & 0xFF)
def _hex(value: int) -> str:
return GREASE if is_grease(value) else "0x%04x" % value
def _grease_quic(identifier: int) -> bool:
"""A reserved QUIC transport parameter id (31 * N + 27)."""
return identifier >= 27 and (identifier - 27) % 31 == 0
class _Reader:
"""A cursor over bytes that refuses to read past the end."""
def __init__(self, data: bytes) -> None:
self.data = data
self.at = 0
def left(self) -> int:
return len(self.data) - self.at
def take(self, n: int) -> bytes:
if n < 0 or self.at + n > len(self.data):
raise NotAClientHello("a field of %d bytes runs past the end (%d left)" % (n, self.left()))
out = self.data[self.at:self.at + n]
self.at += n
return out
def u8(self) -> int:
return self.take(1)[0]
def u16(self) -> int:
return struct.unpack("!H", self.take(2))[0]
def u24(self) -> int:
return int.from_bytes(self.take(3), "big")
def u32(self) -> int:
return struct.unpack("!I", self.take(4))[0]
def vec8(self) -> bytes:
return self.take(self.u8())
def vec16(self) -> bytes:
return self.take(self.u16())
def _u16_list(data: bytes) -> List[str]:
reader = _Reader(data)
out = []
while reader.left() >= 2:
out.append(_hex(reader.u16()))
return out
def _parse_extension(ext_type: int, data: bytes) -> Any:
"""What is inside one extension, without anything random: a value, a list, or a dict."""
reader = _Reader(data)
if ext_type == 0: # server_name
names = []
inner = _Reader(reader.vec16())
while inner.left():
kind = inner.u8()
names.append(inner.vec16().decode("ascii", "replace") if kind == 0 else "type%d" % kind)
return names[0] if len(names) == 1 else names
if ext_type == 5: # status_request
kind = reader.u8()
return {"type": kind, "responder_ids_length": len(reader.vec16()), "extensions_length": len(reader.vec16())}
if ext_type == 10: # supported_groups
return _u16_list(reader.vec16())
if ext_type == 11: # ec_point_formats
return list(reader.vec8())
if ext_type in (13, 34, 50): # signature_algorithms, delegated_credentials, signature_algorithms_cert
return _u16_list(reader.vec16())
if ext_type == 16: # alpn
inner = _Reader(reader.vec16())
out = []
while inner.left():
out.append(inner.vec8().decode("ascii", "replace"))
return out
if ext_type == 21: # padding
return {"length": len(data)}
if ext_type == 27: # compress_certificate
return _u16_list(reader.vec8())
if ext_type == 28: # record_size_limit
return reader.u16()
if ext_type == 35: # session_ticket
return {"length": len(data)}
if ext_type == 41: # pre_shared_key: how many, never what
identities = _Reader(reader.vec16())
count = 0
while identities.left():
identities.vec16()
identities.u32()
count += 1
binders = _Reader(reader.vec16())
lengths = []
while binders.left():
lengths.append(len(binders.vec8()))
return {"identities": count, "binder_lengths": lengths}
if ext_type == 42: # early_data
return True
if ext_type == 43: # supported_versions
return _u16_list(reader.vec8())
if ext_type == 45: # psk_key_exchange_modes
return list(reader.vec8())
if ext_type == 51: # key_share: the groups and the length of each key, never the key
shares = _Reader(reader.vec16())
out = []
while shares.left():
group = shares.u16()
out.append({"group": _hex(group), "key_length": len(shares.vec16())})
return out
if ext_type in (17513, 17613): # application_settings
inner = _Reader(reader.vec16())
out = []
while inner.left():
out.append(inner.vec8().decode("ascii", "replace"))
return out
if ext_type == 65037: # encrypted_client_hello: the suite and the lengths, never the config or the key
kind = reader.u8()
if kind != 0:
return {"type": kind, "length": len(data)}
kdf, aead = reader.u16(), reader.u16()
reader.u8()
return {"type": 0, "kdf": kdf, "aead": aead, "enc_length": len(reader.vec16()), "payload_length": len(reader.vec16())}
if ext_type == 65281: # renegotiation_info
return {"length": len(reader.vec8())}
return {"length": len(data)}
def parse_client_hello(record: bytes) -> Dict[str, Any]:
"""The ClientHello in ``record`` (a whole TLS record, header included), as the dict described at the top of this file. Raises NotAClientHello."""
try:
reader = _Reader(record)
content_type, record_version, length = reader.u8(), reader.u16(), reader.u16()
if content_type != 22:
raise NotAClientHello("the record is of type %d, not a handshake" % content_type)
if length > reader.left():
raise NotAClientHello("the record says %d bytes and %d came" % (length, reader.left()))
body = _Reader(reader.take(length))
if body.u8() != 1:
raise NotAClientHello("the handshake message is not a ClientHello")
hello = _Reader(body.take(body.u24()))
handshake_version = hello.u16()
hello.take(32) # the random: dropped
session_id = hello.vec8() # the session id: only its length
suites_raw = hello.vec16()
suites = [_hex(struct.unpack("!H", suites_raw[i:i + 2])[0]) for i in range(0, len(suites_raw) - 1, 2)]
compression = list(hello.vec8())
out: Dict[str, Any] = {
"record_version": "0x%04x" % record_version, "record_length": length, "handshake_version": "0x%04x" % handshake_version,
"session_id_length": len(session_id), "cipher_suites": suites, "compression_methods": compression,
}
order: List[str] = []
data: Dict[str, Any] = {}
lengths: Dict[str, int] = {}
grease = 0
extensions = _Reader(hello.vec16()) if hello.left() else _Reader(b"")
while extensions.left():
ext_type, ext_data = extensions.u16(), extensions.vec16()
if is_grease(ext_type):
order.append(GREASE)
grease += 1
continue
name = EXTENSION_NAMES.get(ext_type, "ext_%d" % ext_type)
order.append(name)
lengths[name] = len(ext_data)
try:
data[name] = _parse_extension(ext_type, ext_data)
except NotAClientHello:
data[name] = {"unparsed_length": len(ext_data)}
out["extension_order"] = order
out["extensions"] = data
out["extension_lengths"] = lengths
out["grease_extensions"] = grease
return out
except struct.error as exc:
raise NotAClientHello("a field is cut short: %s" % exc) from None
# ---------------------------------------------------------------------------------------------------------------- peeking at the socket
def _peek(sock: socket.socket, n: int, deadline_s: float) -> bytes:
"""Exactly ``n`` bytes from the front of the stream, left in it. Blocks until they are there (``MSG_WAITALL`` where the system takes it with
``MSG_PEEK``; elsewhere a poll with a deadline: a peek that is short of bytes returns at once, and the only way to wait is to look again)."""
flags = socket.MSG_PEEK | (0 if sys.platform == "win32" else getattr(socket, "MSG_WAITALL", 0))
end = time.monotonic() + deadline_s
sock.settimeout(deadline_s)
while True:
data = sock.recv(n, flags)
if len(data) >= n:
return data
if not data:
raise ConnectionError("the peer closed the connection before the ClientHello was complete")
if time.monotonic() >= end:
raise TimeoutError("the ClientHello did not arrive in %.0f s (%d of %d bytes)" % (deadline_s, len(data), n))
time.sleep(0.002)
def peek_client_hello(sock: socket.socket, deadline_s: float = PEEK_DEADLINE_S) -> bytes:
"""The record of the ClientHello at the front of the stream of ``sock``, with every byte of it still in the socket's buffer."""
head = _peek(sock, 5, deadline_s)
if head[0] != 22:
raise NotAClientHello("the first byte of the connection is %d, not a TLS handshake record" % head[0])
total = 5 + struct.unpack("!H", head[3:5])[0]
if total > MAX_HELLO_RECORD:
raise NotAClientHello("a record of %d bytes" % total)
return _peek(sock, total, deadline_s)[:total]
def accept_with_hello(conn: socket.socket, context: ssl.SSLContext, deadline_s: float = PEEK_DEADLINE_S) -> Tuple[Dict[str, Any], ssl.SSLSocket]:
"""Peek the ClientHello of ``conn``, parse it, then hand the same socket to ``ssl``: ``(hello, tls socket)``. The handshake sees every byte."""
hello = parse_client_hello(peek_client_hello(conn, deadline_s))
conn.settimeout(deadline_s)
return hello, context.wrap_socket(conn, server_side=True)
# ---------------------------------------------------------------------------------------------------------------------------------- HTTP/1.1
class Http1Parser:
"""The requests of one HTTP/1.1 connection, read from the bytes in the order they come. ``feed`` returns the requests that are complete (head and body).
A request is ``{"request_line": "GET /x HTTP/1.1", "method", "target", "version", "headers": [[name, value], ...], "body_length": n}``: the names with
the case they were sent with, in the order they were sent, an empty value kept. The body is skipped (``Content-Length`` and ``chunked``) and never kept."""
def __init__(self) -> None:
self._buf = bytearray()
self._pending: Optional[Dict[str, Any]] = None
self._body_left = 0
self._chunked = False
def feed(self, data: bytes) -> List[Dict[str, Any]]:
self._buf += data
done: List[Dict[str, Any]] = []
while True:
if self._pending is None:
end = self._buf.find(b"\r\n\r\n")
if end < 0:
return done
head = bytes(self._buf[:end]).decode("latin-1")
del self._buf[:end + 4]
lines = head.split("\r\n")
parts = lines[0].split(" ")
headers = []
for line in lines[1:]:
name, _sep, value = line.partition(":")
headers.append([name, value.strip(" \t")])
self._pending = {"request_line": lines[0], "method": parts[0], "target": parts[1] if len(parts) > 1 else "",
"version": parts[2] if len(parts) > 2 else "", "headers": headers, "body_length": 0}
lowered = {n.lower(): v for n, v in headers}
self._chunked = "chunked" in lowered.get("transfer-encoding", "").lower()
try:
self._body_left = int(lowered.get("content-length", "0") or 0)
except ValueError:
self._body_left = 0
if self._chunked:
if not self._skip_chunks():
return done
else:
take = min(self._body_left, len(self._buf))
del self._buf[:take]
self._body_left -= take
self._pending["body_length"] += take
if self._body_left:
return done
done.append(self._pending)
self._pending, self._chunked = None, False
def _skip_chunks(self) -> bool:
"""Consume chunks while they are whole; True when the terminating chunk and its trailer have been read."""
while True:
line_end = self._buf.find(b"\r\n")
if line_end < 0:
return False
try:
size = int(bytes(self._buf[:line_end]).split(b";")[0], 16)
except ValueError:
size = 0
if size == 0:
if self._buf.find(b"\r\n\r\n", line_end - 1) < 0 and not self._buf.startswith(b"0\r\n\r\n"):
return False
end = self._buf.find(b"\r\n\r\n")
del self._buf[:end + 4 if end >= 0 else len(self._buf)]
return True
if len(self._buf) < line_end + 2 + size + 2:
return False
self._pending["body_length"] += size
del self._buf[:line_end + 2 + size + 2]
def serve_http1(sock: Any, responder: Callable[[Dict[str, Any]], Tuple[int, List[Tuple[str, str]], bytes]],
on_request: Callable[[Dict[str, Any]], None], alt_svc: Optional[str] = None, close_after_response: bool = False,
on_answered: Optional[Callable[[Dict[str, Any]], None]] = None) -> None:
"""Serve the requests of a connection (a TLS socket, or a plain one) until the peer closes: each request is handed to ``on_request`` and answered by
``responder(request) -> (status, headers, body)``. With ``close_after_response`` the answer says ``Connection: close`` and the connection ends after it: the client
needs a new connection for its next request, and by then it has read the session ticket the server sent with the first answer. ``on_answered(request)`` is called once the
whole answer (head and body) has been handed to the socket, in the same thread and before the next request is read: the moment a client can have all of it."""
parser = Http1Parser()
while True:
data = sock.recv(65536)
if not data:
return
for request in parser.feed(data):
on_request(request)
status, headers, body = responder(dict(request, scheme="https", protocol="http/1.1"))
if alt_svc:
headers = list(headers) + [("alt-svc", alt_svc)]
lines = ["HTTP/1.1 %d %s" % (status, "OK" if status == 200 else "Status")]
lines += ["%s: %s" % (n, v) for n, v in headers if n.lower() not in ("content-length", "connection")]
lines.append("Content-Length: %d" % len(body))
if close_after_response:
lines.append("Connection: close")
sock.sendall(("\r\n".join(lines) + "\r\n\r\n").encode("latin-1") + body)
if on_answered is not None:
on_answered(request)
if close_after_response:
return
# ---------------------------------------------------------------------------------------------------------------------------------- HTTP/2
class FrameTap:
"""The HTTP/2 frames of one direction of a connection, parsed from the raw bytes as they come (the client's preface first)."""
def __init__(self) -> None:
self._buf = bytearray()
self._preface = False
self.frames: List[Dict[str, Any]] = []
def feed(self, data: bytes) -> List[Dict[str, Any]]:
from hyperframe.frame import Frame
self._buf += data
if not self._preface:
if len(self._buf) < len(H2_PREFACE):
return []
if bytes(self._buf[:len(H2_PREFACE)]) != H2_PREFACE:
raise ValueError("the connection does not start with the HTTP/2 preface")
del self._buf[:len(H2_PREFACE)]
self._preface = True
new = []
while len(self._buf) >= 9:
frame, length = Frame.parse_frame_header(memoryview(bytes(self._buf[:9])))
if len(self._buf) < 9 + length:
break
frame.parse_body(memoryview(bytes(self._buf[9:9 + length])))
del self._buf[:9 + length]
record = _frame_record(frame)
self.frames.append(record)
new.append(record)
return new
def _priority_fields(frame: Any) -> Dict[str, Any]:
return {"depends_on": frame.depends_on, "weight": frame.stream_weight + 1 if frame.stream_weight is not None else None,
"exclusive": bool(frame.exclusive)}
def _frame_record(frame: Any) -> Dict[str, Any]:
kind = type(frame).__name__
record: Dict[str, Any] = {"stream": frame.stream_id, "flags": sorted(frame.flags)}
if kind == "SettingsFrame":
record.update(type="SETTINGS", settings=[[int(k), v] for k, v in frame.settings.items()])
elif kind == "WindowUpdateFrame":
record.update(type="WINDOW_UPDATE", increment=frame.window_increment)
elif kind == "PriorityFrame":
record.update(type="PRIORITY", **_priority_fields(frame))
elif kind in ("HeadersFrame", "PushPromiseFrame", "ContinuationFrame"):
record["type"] = {"HeadersFrame": "HEADERS", "PushPromiseFrame": "PUSH_PROMISE", "ContinuationFrame": "CONTINUATION"}[kind]
if kind == "HeadersFrame" and "PRIORITY" in frame.flags:
record["priority"] = _priority_fields(frame)
elif kind == "DataFrame":
record.update(type="DATA", length=len(frame.data))
elif kind == "ExtensionFrame":
number = int(frame.type)
record["type"] = H2_FRAME_TYPES.get(number, "TYPE_%d" % number)
body = bytes(frame.body)
if number == 0x10 and len(body) >= 4: # PRIORITY_UPDATE (RFC 9218): the element and the priority field
record.update(element=struct.unpack("!I", body[:4])[0] & 0x7FFFFFFF, field=body[4:].decode("ascii", "replace"))
else:
record["length"] = len(body)
else:
record["type"] = {"PingFrame": "PING", "GoAwayFrame": "GOAWAY", "RstStreamFrame": "RST_STREAM"}.get(kind, kind)
return record
def summarize_frames(frames: List[Dict[str, Any]]) -> Dict[str, Any]:
"""What of a connection's frames is the shape of the CLIENT, not of the traffic: the first SETTINGS in order, the WINDOW_UPDATEs and the types of the
frames before the first request, every PRIORITY and PRIORITY_UPDATE, the priority fields of the HEADERS. What follows the first request (DATA, PING,
later window updates) depends on how much was sent and is only counted."""
first_headers = next((i for i, f in enumerate(frames) if f["type"] == "HEADERS"), len(frames))
before = frames[:first_headers]
settings = next((f["settings"] for f in frames if f["type"] == "SETTINGS" and "ACK" not in f["flags"]), None)
return {
"settings": settings,
"settings_ack_sent_by_client": any(f["type"] == "SETTINGS" and "ACK" in f["flags"] for f in frames),
"frame_types_before_the_first_request": [f["type"] for f in before],
"window_updates_before_the_first_request": [{"stream": f["stream"], "increment": f["increment"]} for f in before if f["type"] == "WINDOW_UPDATE"],
"priority": [{"stream": f["stream"], **{k: f[k] for k in ("depends_on", "weight", "exclusive")}} for f in frames if f["type"] == "PRIORITY"],
"priority_update": [{"stream": f["stream"], "element": f["element"], "field": f["field"]} for f in frames if f["type"] == "PRIORITY_UPDATE"],
"headers_priority": [dict(f["priority"], stream=f["stream"]) for f in frames if f["type"] == "HEADERS" and "priority" in f],
"frames_after_the_first_request": len(frames) - first_headers,
}
class H2Connection:
"""The server side of one HTTP/2 connection, with a tap on the frames. ``serve(sock)`` blocks until the peer closes. Each request is recorded as
``{"stream", "pseudo_order": [":method", ...], "header_names": [...], "headers": [[name, value], ...], "end_stream"}`` and answered by ``responder``."""
def __init__(self, responder: Callable[[Dict[str, Any]], Tuple[int, List[Tuple[str, str]], bytes]], alt_svc: Optional[str] = None,
clock: Callable[[], float] = time.monotonic) -> None:
import h2.config
import h2.connection
config = h2.config.H2Configuration(client_side=False, header_encoding=None, validate_inbound_headers=False, normalize_inbound_headers=False,
validate_outbound_headers=False, normalize_outbound_headers=False)
self.conn = h2.connection.H2Connection(config=config)
self.responder = responder
self.alt_svc = alt_svc
self.tap = FrameTap()
self.requests: List[Dict[str, Any]] = []
self._bodies: Dict[int, int] = {}
#: ``clock()`` is stamped on a request as ``written_t`` once its whole answer (headers, body, end of stream) has been written to the socket; the answers waiting for that are here.
self._clock = clock
self._unwritten: List[Dict[str, Any]] = []
def summary(self) -> Dict[str, Any]:
return dict(summarize_frames(self.tap.frames), requests=list(self.requests))
def serve(self, sock: Any) -> None:
import h2.events
import h2.exceptions
self.conn.initiate_connection()
sock.sendall(self.conn.data_to_send())
while True:
data = sock.recv(65536)
if not data:
return
try:
self.tap.feed(data)
events = self.conn.receive_data(data)
except (h2.exceptions.ProtocolError, ValueError):
out = self.conn.data_to_send()
if out:
sock.sendall(out)
return
for event in events:
if isinstance(event, h2.events.RequestReceived):
self._request(event)
if event.stream_ended is not None:
self._answer(event.stream_id)
elif isinstance(event, h2.events.DataReceived):
self._bodies[event.stream_id] = self._bodies.get(event.stream_id, 0) + len(event.data)
self.conn.acknowledge_received_data(event.flow_controlled_length, event.stream_id)
elif isinstance(event, h2.events.StreamEnded):
self._answer(event.stream_id)
elif isinstance(event, h2.events.ConnectionTerminated):
return
out = self.conn.data_to_send()
if out:
sock.sendall(out)
for request in self._unwritten:
request["written_t"] = round(self._clock(), 3)
self._unwritten.clear()
def _request(self, event: Any) -> None:
headers = [[_text(n), _text(v)] for n, v in event.headers]
self.requests.append({"stream": event.stream_id, "pseudo_order": [n for n, _v in headers if n.startswith(":")],
"header_names": [n for n, _v in headers if not n.startswith(":")], "headers": headers,
"end_stream": event.stream_ended is not None})
def _answer(self, stream_id: int) -> None:
request = next((r for r in self.requests if r["stream"] == stream_id and not r.get("answered")), None)
if request is None:
return
request["answered"] = True
self._unwritten.append(request)
fields = {n: v for n, v in request["headers"]}
status, headers, body = self.responder({"method": fields.get(":method", ""), "target": fields.get(":path", ""), "headers": request["headers"],
"scheme": "https", "protocol": "h2", "body_length": self._bodies.get(stream_id, 0)})
extra = [("alt-svc", self.alt_svc)] if self.alt_svc else []
out = [(":status", str(status))] + [(n.lower(), v) for n, v in list(headers) + extra if n.lower() != "content-length"]
out.append(("content-length", str(len(body))))
self.conn.send_headers(stream_id, out)
self.conn.send_data(stream_id, body, end_stream=True)
def _text(value: Any) -> str:
return value.decode("latin-1") if isinstance(value, (bytes, bytearray)) else str(value)
# ---------------------------------------------------------------------------------------------------------------------------------- QUIC / HTTP/3
def read_varint(data: bytes, at: int) -> Tuple[int, int]:
"""A QUIC variable-length integer at ``data[at:]``: ``(value, the index after it)``."""
first = data[at]
size = 1 << (first >> 6)
if at + size > len(data):
raise ValueError("a variable-length integer is cut short")
return int.from_bytes(bytes([first & 0x3F]) + data[at + 1:at + size], "big"), at + size
def parse_quic_transport_parameters(raw: bytes) -> List[Dict[str, Any]]:
"""The transport parameters a QUIC client sent, in the order it sent them. A reserved id (31 * N + 27) is ``"GREASE"`` and loses its value; an
identifier or a secret (connection ids, the reset token, the preferred address) keeps only its length; any other integer parameter its value."""
out: List[Dict[str, Any]] = []
at = 0
while at < len(raw):
identifier, at = read_varint(raw, at)
length, at = read_varint(raw, at)
value = raw[at:at + length]
if len(value) < length:
raise ValueError("a transport parameter is cut short")
at += length
if _grease_quic(identifier):
out.append({"id": GREASE, "length": length})
continue
entry: Dict[str, Any] = {"id": identifier, "name": QUIC_PARAMETER_NAMES.get(identifier, "param_%d" % identifier), "length": length}
if identifier not in QUIC_OPAQUE and 0 < length <= 8 and identifier not in (0x11,):
try:
entry["value"], end = read_varint(value, 0)
if end != length:
del entry["value"]
except ValueError:
pass
out.append(entry)
return out
H3_SETTING_NAMES = {0x01: "QPACK_MAX_TABLE_CAPACITY", 0x06: "MAX_FIELD_SECTION_SIZE", 0x07: "QPACK_BLOCKED_STREAMS", 0x08: "ENABLE_CONNECT_PROTOCOL",
0x33: "H3_DATAGRAM", 0x276: "H3_DATAGRAM_DRAFT04", 0x2B603742: "ENABLE_WEBTRANSPORT"}
def h3_settings(settings: Optional[Dict[int, int]]) -> Optional[List[List[Any]]]:
"""The SETTINGS frame of an HTTP/3 client as ``[[name, value], ...]``; a reserved identifier (0x1f * N + 0x21) is ``"GREASE"``."""
if settings is None:
return None
return [["GREASE" if (k >= 0x21 and (k - 0x21) % 0x1F == 0) else H3_SETTING_NAMES.get(int(k), "0x%x" % int(k)), v] for k, v in settings.items()]
# --------------------------------------------------------------------------------------------------------------------------- the lab server
PAGE = (b"<!doctype html><meta charset=utf-8><title>wire</title><link rel=stylesheet href=/wire.css><script src=/wire.js></script>"
b"<p>wire</p><img src=/wire.svg alt=''>")
def default_responder(request: Dict[str, Any]) -> Tuple[int, List[Tuple[str, str]], bytes]:
"""A small site: a page that loads a style, a script and an image, sets a cookie, and answers a POST."""
target = request["target"].split("?")[0]
if target == "/":
return 200, [("content-type", "text/html; charset=utf-8"), ("set-cookie", "wire=1; Path=/; SameSite=Lax"), ("cache-control", "no-store")], PAGE
if target == "/wire.css":
return 200, [("content-type", "text/css"), ("cache-control", "no-store")], b"p{color:#333}"
if target == "/wire.js":
return 200, [("content-type", "text/javascript"), ("cache-control", "no-store")], b"window.__wire = 1;"
if target == "/wire.svg":
return 200, [("content-type", "image/svg+xml"), ("cache-control", "no-store")], b"<svg xmlns='http://www.w3.org/2000/svg' width='1' height='1'/>"
return 200, [("content-type", "text/plain"), ("access-control-allow-origin", "*"), ("cache-control", "no-store")], b"ok"
class _Handler(socketserver.BaseRequestHandler):
def handle(self) -> None:
self.server.owner._connection(self.request) # type: ignore[attr-defined]
class _Server(socketserver.ThreadingTCPServer):
allow_reuse_address = sys.platform != "win32"
daemon_threads = True
class WireServer:
"""One TLS server (TCP) and, with ``h3=True``, a QUIC server on the same port number, each connection written down.
``alpn`` is what the server OFFERS (``["h2", "http/1.1"]``, or ``["http/1.1"]`` for a server that only speaks HTTP/1.1): the client's offer is the same
either way, and what it reads is the answer. ``phase()`` names the stage of the run a connection or a request belongs to, at the time it arrives.
``connections`` is the list of the TLS connections, each ``{"id", "phase", "tls": <ClientHello>, "alpn": <selected>, "http1": [requests]}`` or
``{..., "h2": <H2Connection>}``; ``quic`` the QUIC connections ``{"phase", "transport_parameters", "h3_settings", "requests"}``. :meth:`snapshot` is the
JSON of all of it."""
def __init__(self, address: str = "127.0.0.1", *, alpn: Tuple[str, ...] = ("h2", "http/1.1"), h3: bool = False,
responder: Callable[[Dict[str, Any]], Tuple[int, List[Tuple[str, str]], bytes]] = default_responder,
phase: Callable[[], str] = lambda: "-", dns_names: Tuple[str, ...] = ("wire.test",), close_after_response: bool = False) -> None:
from _doh_servers import make_certificate
from _ports import bind_tcp_and_hold_udp
self.address, self.alpn, self.responder, self.phase = address, tuple(alpn), responder, phase
#: HTTP/1.1 only: every answer says ``Connection: close`` and ends its connection (see :func:`serve_http1`).
self.close_after_response = close_after_response
self._t0 = time.monotonic()
self.connections: List[Dict[str, Any]] = []
self.quic: List[Dict[str, Any]] = []
self.refused: List[str] = []
self._lock = threading.Lock()
self._dir = tempfile.TemporaryDirectory()
certificate, key = make_certificate(Path(self._dir.name), dns_names=dns_names, ip_addresses=(address,))
self._tls = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
self._tls.load_cert_chain(str(certificate), str(key))
self._tls.set_alpn_protocols(list(self.alpn))
self._udp: Optional[socket.socket] = None
if h3:
self._tcp, self.port, self._udp = bind_tcp_and_hold_udp(address, lambda host, number: _Server((host, number), _Handler), socket_module=socket)
else:
self._tcp = _Server((address, 0), _Handler)
self.port = self._tcp.server_address[1]
self.alt_svc = 'h3=":%d"; ma=3600' % self.port if h3 else None
self._tcp.owner = self # type: ignore[attr-defined]
threading.Thread(target=self._tcp.serve_forever, daemon=True).start()
self._loop = None
if h3:
self._start_quic(certificate, key)
@property
def url(self) -> str:
return "https://%s:%d/" % (self.address, self.port)
# --- TCP ------------------------------------------------------------------------------------------------------------------------------
def _connection(self, sock: socket.socket) -> None:
record: Dict[str, Any] = {"phase": self.phase(), "tls": None, "alpn": None, "t": self._now()}
with self._lock:
record["id"] = len(self.connections)
self.connections.append(record)
tls = None
try:
hello, tls = accept_with_hello(sock, self._tls)
record["tls"] = hello
record["alpn"] = tls.selected_alpn_protocol() or "http/1.1"
tls.settimeout(60)
if record["alpn"] == "h2":
record["h2"] = connection = H2Connection(self.responder, self.alt_svc, clock=self._now)
connection.serve(tls)
else:
record["http1"] = []
arrived: List[Dict[str, Any]] = [] # the request being answered: a connection serves one at a time, and the mark goes on the record kept for it
def on_request(r: Dict[str, Any]) -> None:
arrived[:] = [dict(r, phase=self.phase(), t=self._now())]
record["http1"].append(arrived[0])
def on_answered(_request: Dict[str, Any]) -> None:
arrived[0]["written_t"] = self._now()
serve_http1(tls, self.responder, on_request, self.alt_svc, self.close_after_response, on_answered)
except (ssl.SSLError, OSError, ConnectionError, NotAClientHello, TimeoutError) as exc:
record["error"] = "%s: %s" % (type(exc).__name__, exc)
finally:
for s in (tls, sock):
try:
if s is not None:
s.close()
except OSError:
pass
def _now(self) -> float:
"""Seconds since the server started: when a connection or a request arrived (evidence for a run that differs from itself; never compared)."""
return round(time.monotonic() - self._t0, 3)
# --- QUIC -----------------------------------------------------------------------------------------------------------------------------
def _start_quic(self, certificate: Path, key: Path) -> None:
import asyncio
from aioquic.asyncio.protocol import QuicConnectionProtocol
from aioquic.asyncio.server import QuicServer
from aioquic.h3.connection import H3_ALPN, H3Connection
from aioquic.h3.events import HeadersReceived
from aioquic.quic.configuration import QuicConfiguration
from aioquic.quic.events import ProtocolNegotiated
server = self
class Protocol(QuicConnectionProtocol):
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
self._http: Optional[Any] = None
self._record: Dict[str, Any] = {}
def quic_event_received(self, event: Any) -> None:
if isinstance(event, ProtocolNegotiated):
self._http = H3Connection(self._quic)
raw = next((data for kind, data in (self._quic.tls.received_extensions or []) if kind in (0x39, 0xFFA5)), b"")
peer = self._quic._network_paths[0].addr
self._record = {"phase": server.phase(), "alpn": event.alpn_protocol, "peer": [peer[0], peer[1]],
"transport_parameters": parse_quic_transport_parameters(raw), "h3_settings": None, "requests": []}
with server._lock:
server.quic.append(self._record)
if self._http is None:
return
for http_event in self._http.handle_event(event):
if isinstance(http_event, HeadersReceived):
headers = [[_text(n), _text(v)] for n, v in http_event.headers]
self._record["h3_settings"] = h3_settings(self._http.received_settings)
request = {
"stream": http_event.stream_id, "pseudo_order": [n for n, _v in headers if n.startswith(":")],
"header_names": [n for n, _v in headers if not n.startswith(":")], "headers": headers,
"phase": server.phase(), "t": server._now()}
self._record["requests"].append(request)
fields = dict(headers)
status, out, body = server.responder({"method": fields.get(":method", ""), "target": fields.get(":path", ""), "headers": headers,
"scheme": "https", "protocol": "h3", "body_length": 0})
self._http.send_headers(http_event.stream_id, [(b":status", str(status).encode())] +
[(n.lower().encode(), v.encode()) for n, v in out if n.lower() != "content-length"] +
[(b"content-length", str(len(body)).encode())])
self._http.send_data(http_event.stream_id, body, end_stream=True)
self.transmit()
request["written_t"] = server._now() # the datagrams that carry the whole answer have left the socket
configuration = QuicConfiguration(is_client=False, alpn_protocols=H3_ALPN)
configuration.load_cert_chain(str(certificate), str(key))
self._loop = asyncio.new_event_loop()
started = threading.Event()
def run() -> None:
asyncio.set_event_loop(self._loop)
_transport, self._quic = self._loop.run_until_complete(self._loop.create_datagram_endpoint(
lambda: QuicServer(configuration=configuration, create_protocol=Protocol), sock=self._udp))
started.set()
try:
self._loop.run_forever()
finally:
# The loop is closed HERE, on its own thread, after the QUIC server (as tests/_h3_server.py does): a loop that is only stopped is closed
# later by the garbage collector on whatever thread it runs in, and on Windows the proactor's close then waits for ever.
self._quic.close()
for _ in range(3): # a few turns of the loop let the closing transport flush
self._loop.run_until_complete(asyncio.sleep(0))
self._loop.close()
self._thread = threading.Thread(target=run, daemon=True)
self._thread.start()
if not started.wait(30):
raise RuntimeError("the QUIC server did not start")
# --- what a test or the oracle reads --------------------------------------------------------------------------------------------------
def answered_at(self, path: str) -> Optional[float]:
"""When the server finished WRITING the answer to a request for ``path`` (the query is not part of it), whatever the transport it rode: seconds since the server started
(the scale of ``t``), or None while no such request has been answered in full. A request that has arrived but whose answer is not all written is not answered: the mark is
stamped after the last byte (HTTP/1.1, HTTP/2) or the last datagram (HTTP/3) is handed to the socket, in the one place that writes it."""
with self._lock:
connections = list(self.connections)
quic = list(self.quic)
marks: List[float] = []
for c in connections:
requests = [(r["target"], r) for r in list(c.get("http1") or [])]
if "h2" in c:
requests += [(dict(r["headers"]).get(":path", ""), r) for r in list(c["h2"].requests)]
marks += [r["written_t"] for target, r in requests if target.split("?")[0] == path and "written_t" in r]
for q in quic:
marks += [r["written_t"] for r in list(q["requests"]) if dict(r["headers"]).get(":path", "").split("?")[0] == path and "written_t" in r]
return min(marks) if marks else None
def snapshot(self) -> Dict[str, Any]:
with self._lock:
connections = list(self.connections)
quic = list(self.quic)
out: List[Dict[str, Any]] = []
for c in connections:
item = {"id": c["id"], "phase": c["phase"], "tls": c["tls"], "alpn": c["alpn"], "t": c.get("t")}
if "h2" in c:
item["h2"] = c["h2"].summary()
if "http1" in c:
item["http1"] = list(c["http1"])
if "error" in c:
item["error"] = c["error"]
out.append(item)
return {"connections": out, "quic": quic}
def close(self) -> None:
self._tcp.shutdown()
self._tcp.server_close()
if self._loop is not None and not self._loop.is_closed():
self._loop.call_soon_threadsafe(self._loop.stop)
self._thread.join(30)
self._dir.cleanup()
def __enter__(self) -> "WireServer":
return self
def __exit__(self, *exc: Any) -> None:
self.close()
Loaded 100 of 371 files, more files were not shown because too many files have changed in this diff. Show more