Merge 18f6225a (PR #555: the host oracle's rules, --junit, wrapper.e2e.ab_host_crash) into the integration for the candidates
This commit is contained in:
commit
abf62dfe08
22 files changed
+3669
-244
No files matched your search
+213
-3
@@ -175,8 +175,8 @@ jobs:
|
||||
ROOT_FILES: tests/test_a_proxy_that_cannot_carry_udp_leaks_nothing_direct_e2e.py
|
||||
ROOT_NODES: tests/test_the_whole_udp_chain_by_name_e2e.py::test_a_turn_srflx_by_name_arrives_through_the_relay_before_the_tick
|
||||
SANDBOX_FILES: tests/test_the_socket_process_is_sandboxed_e2e.py
|
||||
# The network and host oracles' A/A have jobs of their own (e2e-network, e2e-host and their Windows twins below): five seeds of them do not fit in this job's 40 minutes, and a measurement of what the engine does must not share the machine with other browsers.
|
||||
OWN_JOB_FILES: tests/test_ab_network_e2e.py tests/test_ab_host_e2e.py
|
||||
# The network, host and page oracles' A/A have jobs of their own (e2e-network, e2e-host, e2e-page and their Windows twins below): five seeds of them do not fit in this job's 40 minutes, and a measurement of what the engine does must not share the machine with other browsers.
|
||||
OWN_JOB_FILES: tests/test_ab_network_e2e.py tests/test_ab_host_e2e.py tests/test_ab_oracle_e2e.py tests/test_ab_host_crash_linux_e2e.py
|
||||
# The root ones are left out by name and run in the step below, as root: here, as the runner user, they errored. The sandbox one is left out
|
||||
# by name too and runs in its own step after them: it is red on a runner whose AppArmor refuses user namespaces to a normal user.
|
||||
run: |
|
||||
@@ -500,6 +500,18 @@ jobs:
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y xvfb
|
||||
sudo "$(which python)" -m playwright install-deps firefox
|
||||
# What a browser that did not end with 0 leaves is kept by the oracle (scripts/ci_crash_evidence.py): the core goes through gdb (every thread's backtrace, the MOZ_CRASH reason, the
|
||||
# libraries, with the build ids from elfutils). The kernel writes the core where its pattern says, so the pattern points at a folder of the job (INVPW_CORE_DIR); the launches
|
||||
# allow cores themselves (`ulimit -c unlimited` in the host oracle's stand-in, the soft limit raised to the hard one in the page and network oracles). Nothing here reaches a
|
||||
# launch that does not crash: no environment variable of the browser, no pref, no crash reporter option.
|
||||
- name: Cores of a browser that did not end with 0 (gdb, elfutils, where the kernel writes them)
|
||||
run: |
|
||||
sudo apt-get install -y gdb elfutils
|
||||
mkdir -p "$RUNNER_TEMP/cores"
|
||||
chmod 1777 "$RUNNER_TEMP/cores"
|
||||
sudo sysctl -w kernel.core_pattern="$RUNNER_TEMP/cores/core.%e.%p.%t"
|
||||
echo "INVPW_CORE_DIR=$RUNNER_TEMP/cores" >> "$GITHUB_ENV"
|
||||
cat /proc/sys/kernel/core_pattern
|
||||
- name: The security state (a fixed directory of the repository)
|
||||
shell: bash
|
||||
run: python scripts/ci_lab_security_state.py set --pin ci/security-state.pin.json
|
||||
@@ -615,7 +627,7 @@ jobs:
|
||||
needs: core-on-index
|
||||
if: needs.core-on-index.outputs.available == 'true' && inputs.only != 'windows-control-a'
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 45
|
||||
timeout-minutes: 65
|
||||
steps:
|
||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
with: { fetch-depth: 1 }
|
||||
@@ -639,6 +651,18 @@ jobs:
|
||||
# the host oracle traces the whole tree of the browser with strace
|
||||
sudo apt-get install -y strace
|
||||
sudo "$(which python)" -m playwright install-deps firefox
|
||||
# What a browser that did not end with 0 leaves is kept by the oracle (scripts/ci_crash_evidence.py): the core goes through gdb (every thread's backtrace, the MOZ_CRASH reason, the
|
||||
# libraries, with the build ids from elfutils). The kernel writes the core where its pattern says, so the pattern points at a folder of the job (INVPW_CORE_DIR); the launches
|
||||
# allow cores themselves (`ulimit -c unlimited` in the host oracle's stand-in, the soft limit raised to the hard one in the page and network oracles). Nothing here reaches a
|
||||
# launch that does not crash: no environment variable of the browser, no pref, no crash reporter option.
|
||||
- name: Cores of a browser that did not end with 0 (gdb, elfutils, where the kernel writes them)
|
||||
run: |
|
||||
sudo apt-get install -y gdb elfutils
|
||||
mkdir -p "$RUNNER_TEMP/cores"
|
||||
chmod 1777 "$RUNNER_TEMP/cores"
|
||||
sudo sysctl -w kernel.core_pattern="$RUNNER_TEMP/cores/core.%e.%p.%t"
|
||||
echo "INVPW_CORE_DIR=$RUNNER_TEMP/cores" >> "$GITHUB_ENV"
|
||||
cat /proc/sys/kernel/core_pattern
|
||||
- name: The security state (a fixed directory of the repository)
|
||||
shell: bash
|
||||
run: python scripts/ci_lab_security_state.py set --pin ci/security-state.pin.json
|
||||
@@ -660,6 +684,23 @@ jobs:
|
||||
print(counts)
|
||||
sys.exit(0 if counts == {"tests": 1, "failures": 0, "errors": 0, "skipped": 0} else 1)
|
||||
PY
|
||||
# The recorder's own test (wrapper.e2e.ab_host_crash): the engine is launched once under the oracle's stand-in, its parent is sent SIGSEGV with os.kill, and the test passes when the
|
||||
# oracle says RED and keeps the evidence (the code on the verdict line, strace's signal line, the core through gdb with its threads, the build ids). The red of the probe is the
|
||||
# right answer: it does not make this job red; a probe that says green for a launch that died does. After the A/A, so that it cannot reach a measurement.
|
||||
- name: The host oracle's recorder of a browser that dies (a parent sent SIGSEGV is red, with its gdb threads and its strace signal line)
|
||||
if: success() || failure()
|
||||
env:
|
||||
PYTHONUNBUFFERED: "1"
|
||||
run: |
|
||||
xvfb-run -a env -u PYTEST_ADDOPTS INVPW_BINARY_PATH="$FF" STEALTHFOX_E2E_BINARY="$FF" python -u -m pytest tests/test_ab_host_crash_linux_e2e.py -m e2e -o addopts= -o junit_family=xunit2 -p no:cacheprovider -p no:rerunfailures -rs -v --junitxml="$RUNNER_TEMP/host-crash-e2e.xml"
|
||||
python - "$RUNNER_TEMP/host-crash-e2e.xml" <<'PY'
|
||||
import sys, xml.etree.ElementTree as ET
|
||||
root = ET.parse(sys.argv[1]).getroot()
|
||||
suite = root if root.tag == "testsuite" else root.find("testsuite")
|
||||
counts = {k: int(suite.get(k, 0)) for k in ("tests", "failures", "errors", "skipped")}
|
||||
print(counts)
|
||||
sys.exit(0 if counts == {"tests": 1, "failures": 0, "errors": 0, "skipped": 0} else 1)
|
||||
PY
|
||||
- name: The leg ran with the pinned GeoIP database
|
||||
if: always()
|
||||
shell: bash
|
||||
@@ -674,6 +715,7 @@ jobs:
|
||||
path: |
|
||||
${{ runner.temp }}/invpw-evidence
|
||||
${{ runner.temp }}/host-e2e.xml
|
||||
${{ runner.temp }}/host-crash-e2e.xml
|
||||
if-no-files-found: ignore
|
||||
retention-days: 14
|
||||
|
||||
@@ -745,6 +787,162 @@ jobs:
|
||||
if-no-files-found: ignore
|
||||
retention-days: 14
|
||||
|
||||
# ``The page oracle``: the A/A of tests/test_ab_oracle_e2e.py (the page of the host gate over the persona seeds, the published engine against itself; the poison probe, the H7 second
|
||||
# launch of seed 0 and the ab. visits are part of its dumps) on its own job, Linux and Windows, as the network and host oracles have theirs. On a pull request that changes a
|
||||
# file of the oracle it visits all five seeds of the candidate set (scripts/ci_ab_pr_seeds.py): the test's own guard for that run is 120 s to start and, for each of the
|
||||
# two engine runs, 180 s for the first seed, 100 s for each next one and 200 s for the second launch of seed 0, 28 minutes (30 with the worker's margin), which took 38 minutes of
|
||||
# the shared Linux job (run 45030727459, 40 minutes, every test passed) and does not fit next to everything else. The shared jobs leave this file out (OWN_JOB_FILES above,
|
||||
# `own_job` in the Windows parts). 45 minutes for the job, as the host oracle's: the setup of the job plus the guard of the test with the margin of Windows. The same setup as the shared jobs.
|
||||
e2e-page:
|
||||
name: e2e (page oracle, linux)
|
||||
needs: core-on-index
|
||||
if: needs.core-on-index.outputs.available == 'true' && inputs.only != 'windows-control-a'
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 45
|
||||
steps:
|
||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
with: { fetch-depth: 1 }
|
||||
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
|
||||
with: { python-version: '3.11' }
|
||||
- name: How many seeds the A/A of each oracle visits (all of them when the pull request touches the oracle)
|
||||
if: github.event_name == 'pull_request'
|
||||
shell: bash
|
||||
env:
|
||||
BASE_SHA: ${{ github.event.pull_request.base.sha }}
|
||||
run: python scripts/ci_ab_pr_seeds.py "$BASE_SHA" >> "$GITHUB_ENV"
|
||||
- name: Install wrapper + test deps (+ Playwright ONLY as a system tool)
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
python -m pip install ".[dev]"
|
||||
python -m pip install "playwright==$(cat scripts/playwright_pin.txt)"
|
||||
- name: System deps (xvfb + Firefox runtime libs)
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y xvfb
|
||||
sudo "$(which python)" -m playwright install-deps firefox
|
||||
# What a browser that did not end with 0 leaves is kept by the oracle (scripts/ci_crash_evidence.py): the core goes through gdb (every thread's backtrace, the MOZ_CRASH reason, the
|
||||
# libraries, with the build ids from elfutils). The kernel writes the core where its pattern says, so the pattern points at a folder of the job (INVPW_CORE_DIR); the launches
|
||||
# allow cores themselves (`ulimit -c unlimited` in the host oracle's stand-in, the soft limit raised to the hard one in the page and network oracles). Nothing here reaches a
|
||||
# launch that does not crash: no environment variable of the browser, no pref, no crash reporter option.
|
||||
- name: Cores of a browser that did not end with 0 (gdb, elfutils, where the kernel writes them)
|
||||
run: |
|
||||
sudo apt-get install -y gdb elfutils
|
||||
mkdir -p "$RUNNER_TEMP/cores"
|
||||
chmod 1777 "$RUNNER_TEMP/cores"
|
||||
sudo sysctl -w kernel.core_pattern="$RUNNER_TEMP/cores/core.%e.%p.%t"
|
||||
echo "INVPW_CORE_DIR=$RUNNER_TEMP/cores" >> "$GITHUB_ENV"
|
||||
cat /proc/sys/kernel/core_pattern
|
||||
- name: The security state (a fixed directory of the repository)
|
||||
shell: bash
|
||||
run: python scripts/ci_lab_security_state.py set --pin ci/security-state.pin.json
|
||||
- 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)
|
||||
shell: bash
|
||||
run: python scripts/ci_lab_geoip.py build
|
||||
- name: Run the page oracle's A/A
|
||||
env:
|
||||
PYTHONUNBUFFERED: "1"
|
||||
run: |
|
||||
xvfb-run -a env -u PYTEST_ADDOPTS INVPW_BINARY_PATH="$FF" STEALTHFOX_E2E_BINARY="$FF" python -u -m pytest tests/test_ab_oracle_e2e.py -m e2e -o addopts= -o junit_family=xunit2 -p no:cacheprovider -p no:rerunfailures -rs -v --junitxml="$RUNNER_TEMP/page-e2e.xml"
|
||||
python - "$RUNNER_TEMP/page-e2e.xml" <<'PY'
|
||||
import sys, xml.etree.ElementTree as ET
|
||||
root = ET.parse(sys.argv[1]).getroot()
|
||||
suite = root if root.tag == "testsuite" else root.find("testsuite")
|
||||
counts = {k: int(suite.get(k, 0)) for k in ("tests", "failures", "errors", "skipped")}
|
||||
print(counts)
|
||||
sys.exit(0 if counts == {"tests": 1, "failures": 0, "errors": 0, "skipped": 0} else 1)
|
||||
PY
|
||||
- name: The leg ran with the pinned GeoIP database
|
||||
if: always()
|
||||
shell: bash
|
||||
run: |
|
||||
python scripts/ci_lab_geoip.py evidence --out "$(dirname "$GEOIP_USED_OUT")/geoip-evidence.json" > /dev/null
|
||||
python scripts/ci_lab_geoip.py verify --evidence "$(dirname "$GEOIP_USED_OUT")/geoip-evidence.json" --used "$GEOIP_USED_OUT"
|
||||
- name: Upload what the test saved
|
||||
if: always()
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
with:
|
||||
name: invpw-evidence-page-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
path: |
|
||||
${{ runner.temp }}/invpw-evidence
|
||||
${{ runner.temp }}/page-e2e.xml
|
||||
if-no-files-found: ignore
|
||||
retention-days: 14
|
||||
|
||||
e2e-page-windows:
|
||||
name: e2e (page oracle, windows)
|
||||
needs: core-on-index
|
||||
if: needs.core-on-index.outputs.available == 'true' && inputs.only != 'windows-control-a'
|
||||
runs-on: windows-2022
|
||||
timeout-minutes: 45
|
||||
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: How many seeds the A/A of each oracle visits (all of them when the pull request touches the oracle)
|
||||
if: github.event_name == 'pull_request'
|
||||
shell: bash
|
||||
env:
|
||||
BASE_SHA: ${{ github.event.pull_request.base.sha }}
|
||||
run: python scripts/ci_ab_pr_seeds.py "$BASE_SHA" >> "$GITHUB_ENV"
|
||||
- name: Install wrapper + test deps (+ Playwright ONLY as a system tool)
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
python -m pip install ".[dev]"
|
||||
python -m pip install "playwright==$(cat scripts/playwright_pin.txt)"
|
||||
- name: The security state (a fixed directory of the repository)
|
||||
shell: bash
|
||||
run: python scripts/ci_lab_security_state.py set --pin ci/security-state.pin.json
|
||||
- name: Fetch the published firefox binary
|
||||
run: echo "FF=$(cd "$RUNNER_TEMP" && python -m invisible_playwright fetch | tail -1)" >> "$GITHUB_ENV"
|
||||
- name: The GeoIP database (made by the repository, same bytes every run)
|
||||
run: python scripts/ci_lab_geoip.py build
|
||||
- name: Run the page oracle's A/A
|
||||
env:
|
||||
PYTHONUNBUFFERED: "1"
|
||||
run: |
|
||||
INVPW_BINARY_PATH="$FF" STEALTHFOX_E2E_BINARY="$FF" python -u -m pytest tests/test_ab_oracle_e2e.py -m e2e -o addopts= -o junit_family=xunit2 -p no:cacheprovider -p no:rerunfailures -rs -v --junitxml="$RUNNER_TEMP/page-e2e.xml"
|
||||
python - "$RUNNER_TEMP/page-e2e.xml" <<'PY'
|
||||
import sys, xml.etree.ElementTree as ET
|
||||
root = ET.parse(sys.argv[1]).getroot()
|
||||
suite = root if root.tag == "testsuite" else root.find("testsuite")
|
||||
counts = {k: int(suite.get(k, 0)) for k in ("tests", "failures", "errors", "skipped")}
|
||||
print(counts)
|
||||
sys.exit(0 if counts == {"tests": 1, "failures": 0, "errors": 0, "skipped": 0} else 1)
|
||||
PY
|
||||
- name: The leg ran with the pinned GeoIP database
|
||||
if: always()
|
||||
run: |
|
||||
python scripts/ci_lab_geoip.py evidence --out "$(dirname "$GEOIP_USED_OUT")/geoip-evidence.json" > /dev/null
|
||||
python scripts/ci_lab_geoip.py verify --evidence "$(dirname "$GEOIP_USED_OUT")/geoip-evidence.json" --used "$GEOIP_USED_OUT"
|
||||
- name: Close every Firefox left
|
||||
if: always()
|
||||
shell: pwsh
|
||||
run: |
|
||||
Get-Process firefox -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue
|
||||
"left: " + @(Get-Process firefox -ErrorAction SilentlyContinue).Count
|
||||
- name: Upload what the test saved
|
||||
if: always()
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
with:
|
||||
name: invpw-evidence-page-windows-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
path: |
|
||||
${{ runner.temp }}/invpw-evidence
|
||||
${{ runner.temp }}/page-e2e.xml
|
||||
if-no-files-found: ignore
|
||||
retention-days: 14
|
||||
|
||||
# ``The host oracle``: the A/A of tests/test_ab_host_e2e.py (the trace of a closed run, a warm-up launch and the measured ones of each engine) on its own job, Linux
|
||||
# and Windows. It measures what the engine does on the machine, so nothing else may run on it: in the shared job the other tests' browsers ran at the same time (the
|
||||
# report of run 44982522362 counts 150 to 1000 paths per seed opened by firefox.exe processes outside the tree on Windows), and the engine's own timers (the
|
||||
# telemetry notification flow that decides whether the pingsender is spawned at shutdown) raced with a loaded machine. One test, serial; 45 minutes for the job,
|
||||
# 35 for the test.
|
||||
|
||||
# ``The page oracle, final seeds``: the A/A of the 20 seeds of the `final` set of ci/persona-seeds.json (every value of every dimension the core declares), split in four
|
||||
# shards of five seeds, on a pull request that changes a file of the page oracle (scripts/ci_ab_pr_seeds.py holds the list; `ci_ab_oracle.py touched` reads it). The
|
||||
# shared jobs run the first seeds of the `candidate` set, or the five of it when the oracle is touched; they do not grow. This one is the control the final candidate's
|
||||
@@ -796,6 +994,18 @@ jobs:
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y xvfb
|
||||
sudo "$(which python)" -m playwright install-deps firefox
|
||||
# What a browser that did not end with 0 leaves is kept by the oracle (scripts/ci_crash_evidence.py): the core goes through gdb (every thread's backtrace, the MOZ_CRASH reason, the
|
||||
# libraries, with the build ids from elfutils). The kernel writes the core where its pattern says, so the pattern points at a folder of the job (INVPW_CORE_DIR); the launches
|
||||
# allow cores themselves (`ulimit -c unlimited` in the host oracle's stand-in, the soft limit raised to the hard one in the page and network oracles). Nothing here reaches a
|
||||
# launch that does not crash: no environment variable of the browser, no pref, no crash reporter option.
|
||||
- name: Cores of a browser that did not end with 0 (gdb, elfutils, where the kernel writes them)
|
||||
run: |
|
||||
sudo apt-get install -y gdb elfutils
|
||||
mkdir -p "$RUNNER_TEMP/cores"
|
||||
chmod 1777 "$RUNNER_TEMP/cores"
|
||||
sudo sysctl -w kernel.core_pattern="$RUNNER_TEMP/cores/core.%e.%p.%t"
|
||||
echo "INVPW_CORE_DIR=$RUNNER_TEMP/cores" >> "$GITHUB_ENV"
|
||||
cat /proc/sys/kernel/core_pattern
|
||||
- name: The security state (a fixed directory of the repository)
|
||||
shell: bash
|
||||
run: python scripts/ci_lab_security_state.py set --pin ci/security-state.pin.json
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
"format": "ab-host-expected/1",
|
||||
"differences": [
|
||||
{
|
||||
"id": "glxtest-69",
|
||||
"id": "gfxtest-69",
|
||||
"os": "linux",
|
||||
"category": "proc",
|
||||
"name": "glxtest",
|
||||
"name": "gfxtest",
|
||||
"published": "present",
|
||||
"candidate": "absent",
|
||||
"reason": "the 69 no longer spawns glxtest (commit 0e896e4ee1, glxtest never reads the host)"
|
||||
"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"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -27,5 +27,6 @@
|
||||
{"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."},
|
||||
{"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."},
|
||||
{"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)."},
|
||||
{"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 SET of host paths the tree touched, identical with no exception; 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)."}
|
||||
{"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 SET of host paths the tree touched, identical with no exception; 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)."},
|
||||
{"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)."}
|
||||
]
|
||||
+236
-113
@@ -59,7 +59,17 @@ How the trace is taken:
|
||||
are). Two canary files of the oracle's own, opened after the session starts and before it stops, must be in the trace: a session that did not
|
||||
see them is red, not empty.
|
||||
|
||||
EVERY launch is also judged by how its parent ended (scripts/ci_crash_evidence.py): the warm-up, each measured seed, the idle and the bare launch alike. A root exit code other
|
||||
than 0, or one that was not seen, is a RED line that names the seed, the run side, the launch and the code; the verdict of a closed run is not "the trace is equal" alone. A launch
|
||||
that did not end with 0 keeps what it left in `<footprint>.crash/<launch>/`, next to the footprint (the artifact): the last 100 lines of the strace log and the fatal signal lines of
|
||||
the whole log (`--- SIGSEGV {si_addr=...} ---`: the trace records the fatal signals now, `tests/_strace_stand_in.py` RECORDED_SIGNALS, and the lines are dropped where the log is read, so they
|
||||
are never data of the comparison), the core run through `gdb -batch` (`thread apply all bt`, the MOZ_CRASH reason, `info sharedlibrary`) with the build ids, the crash reporter's `.extra` and
|
||||
the minidump names, and `said.txt` for every collector that found nothing. Cores are enabled in every launch (`ulimit -c unlimited` in the stand-in; the working directory is not touched, the
|
||||
job's `kernel.core_pattern` decides where the kernel writes them: INVPW_CORE_DIR), and a crash watcher reads the crash folders in every launch, as it did in the bare one. On Windows the `.extra`
|
||||
files and the minidump names are collected the same way. `crash-probe` is the recorder's own test (one launch, its parent sent SIGSEGV; red is the right answer, tests/test_ab_host_crash_linux_e2e.py).
|
||||
|
||||
python ci_ab_host.py run <firefox> [--seal SEAL] --leg linux-x86_64 --out footprint.json [--seeds 11,12,13]
|
||||
python ci_ab_host.py crash-probe <firefox> --leg linux-x86_64 --out DIR
|
||||
python ci_ab_host.py compare A.json B.json --out diff.json [--a-a]
|
||||
python ci_ab_host.py ab [<candidate> --candidate-seal SEAL] --leg L --out DIR [--published-binary B [--published-seal S]]
|
||||
|
||||
@@ -67,7 +77,11 @@ How the trace is taken:
|
||||
candidate. Exit 0 green, 1 red, 2 the control is broken (A/A differs: what is compared is not stable, the A/B says nothing). Nothing here reads
|
||||
the clock for a verdict, and nothing excuses a difference: the A/A is green or the comparison is not stable.
|
||||
|
||||
Declared differences (ci/ab-host-expected.json) are applied to the A/B only, never to the A/A, by kind, and one that does not show is red as stale.
|
||||
Every engine run (the published engine, again, the candidate) is launched from the SAME absolute folder, `<RUNNER_TEMP>/ab-host/engine/firefox` (`staged_engine`: the package is copied
|
||||
there and removed after the run): the browser's processes read the link of every ancestor of the install folder, so where the engine sits would otherwise be a difference of the paths.
|
||||
|
||||
Declared differences (ci/ab-host-expected.json) are applied to the A/B only, never to the A/A, by kind, and one that does not show is red as stale. A declared `proc` difference covers the
|
||||
process kind and the file leaves whose only toucher on the published side is that kind (a leaf another process touched too is still a difference).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -96,6 +110,8 @@ sys.path.insert(0, str(HERE))
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
import ci_ab_oracle as oracle # noqa: E402 (fetch_published, ENGINE_TAG)
|
||||
import ci_host_gate as gate # noqa: E402 (SEEDS)
|
||||
import ci_crash_evidence as crash # noqa: E402 (the exit code is red, and what a bad end left is saved)
|
||||
from ci_crash_evidence import CrashWatcher, core_info, crash_report_dirs, scan_crash_files # noqa: E402,F401 (the bare launch's collectors, shared by every launch)
|
||||
|
||||
FORMAT = "ab-host/2"
|
||||
EXPECTED_FORMAT = "ab-host-expected/1"
|
||||
@@ -209,8 +225,12 @@ def _base(path: str) -> str:
|
||||
return re.split(r"[\\/]", path)[-1]
|
||||
|
||||
|
||||
#: The graphics probe the 68 spawns on Linux is called `gfxtest` (widget/gtk/GfxInfo.cpp:55 GFX_PROBE_BINARY; `gfxtest glx -f 18`), not `glxtest`: its kind is that name.
|
||||
GFX_PROBE = "gfxtest"
|
||||
|
||||
|
||||
def label_of_exec(path: str, argv: list, real: str) -> str:
|
||||
"""What a process that ran `path` with `argv` is called: the engine's kinds, `glxtest` (argv0 or `-glxtest`), else the
|
||||
"""What a process that ran `path` with `argv` is called: the engine's kinds, `glxtest` (argv0 or `-glxtest`), `gfxtest` (argv0 or the file it ran), else the
|
||||
program's name (lower case); a background task of the engine (`firefox.exe --backgroundtask pingsender ...`) is `backgroundtask/<name>`."""
|
||||
if "-contentproc" in argv:
|
||||
return kind_of(argv) # whatever path it was started by (the binary, /proc/self/exe)
|
||||
@@ -220,6 +240,8 @@ def label_of_exec(path: str, argv: list, real: str) -> str:
|
||||
return "backgroundtask/%s" % (argv[i + 1].lower() if i + 1 < len(argv) else "?")
|
||||
if any(a.lstrip("-") == "glxtest" for a in argv[1:]) or _base(argv[0] if argv else "").lower() == "glxtest":
|
||||
return "glxtest"
|
||||
if GFX_PROBE in (_base(path).lower(), _base(argv[0] if argv else "").lower()):
|
||||
return GFX_PROBE
|
||||
if path == real or _base(path).lower() == _base(real).lower():
|
||||
return "parent"
|
||||
return _base(path).lower() or path
|
||||
@@ -1042,8 +1064,12 @@ def net_by_kind(events, label_of) -> list:
|
||||
|
||||
|
||||
def _read_lines(log: Path):
|
||||
"""The lines of a strace log that are calls and exits. The signal lines (`1234 --- SIGSEGV {si_addr=...} ---`, recorded so that a crash can be told, tests/_strace_stand_in.py
|
||||
RECORDED_SIGNALS) are evidence of a bad end and never data of the comparison: they are dropped here, the one place the log is read for it."""
|
||||
with open(log, encoding="utf-8", errors="replace") as f:
|
||||
for line in f:
|
||||
if crash.SIGNAL_LINE.match(line):
|
||||
continue
|
||||
yield line.rstrip("\n")
|
||||
|
||||
|
||||
@@ -1149,6 +1175,18 @@ DISPOSITIONS = {0: "SUPERSEDE", 1: "OPEN", 2: "CREATE", 3: "OPEN_IF", 4: "OVERWR
|
||||
MAKING = (0, 2, 3, 4, 5)
|
||||
|
||||
|
||||
#: The Windows Overlay Filter (WOF) keeps a system file compressed (Compact OS) and serves its decompressed bytes from a cache; when they are not cached (the first access
|
||||
#: after the boot) the open of the file is followed by an open of its stream `<file>:WofCompressedData`, the compressed data of the SAME file. That stream is not a path the
|
||||
#: process chose: it is the file the process opened, read from where Windows keeps it. The footprint spells it as the file (the run 45043617981: 31 system paths only the first
|
||||
#: run of the 68 had, all `<file>:wofcompresseddata`, while every one of the files was opened by all three runs). Any other stream (`:Zone.Identifier`, ...) is a path of its own.
|
||||
WOF_STREAM = ":wofcompresseddata"
|
||||
|
||||
|
||||
def wof_base(name: str) -> str:
|
||||
"""`name` with the WOF compressed-data stream of a file taken off (the file itself), see WOF_STREAM; any other name is itself."""
|
||||
return name[:-len(WOF_STREAM)] if len(name) > len(WOF_STREAM) and name.lower().endswith(WOF_STREAM) else name
|
||||
|
||||
|
||||
def etw_files(path, pids=None, exits=None, order=None, dispositions=None) -> tuple:
|
||||
"""`({(pid, file name)}, events)` of the Create events a `tracerpt -of XML` file holds, for the processes in `pids` (every process when None). Read as a
|
||||
stream: the file has every open of the machine for the length of the run. With a list in `exits`, the process stops of the same file (Kernel-Process, event 2)
|
||||
@@ -1173,6 +1211,8 @@ def etw_files(path, pids=None, exits=None, order=None, dispositions=None) -> tup
|
||||
when = child.get("SystemTime", "")
|
||||
elif tag == "EventID":
|
||||
event_id = (child.text or "").strip()
|
||||
if name:
|
||||
name = wof_base(name)
|
||||
if exits is not None and event_id == "2" and "ExitCode" in data and data.get("ProcessID"):
|
||||
exits.append({"pid": _number(data["ProcessID"]), "code": _number(data["ExitCode"]), "time": when, "image": data.get("ImageName", "")})
|
||||
if name and pid is not None and (pids is None or pid in pids):
|
||||
@@ -1445,13 +1485,21 @@ def load_expected(path: Path = EXPECTED_FILE) -> list:
|
||||
return document["differences"]
|
||||
|
||||
|
||||
def _declared_covers(entry: dict, diff: dict) -> bool:
|
||||
"""A declared difference covers a difference of `proc.<name>` that is the published engine having it (count >= 1) and the candidate not
|
||||
having it: by kind."""
|
||||
if entry.get("category") != "proc" or diff["leaf"] != "proc." + entry["name"]:
|
||||
def _declared_covers(entry: dict, diff: dict, probe_seeds=()) -> bool:
|
||||
"""A declared difference covers, by kind (a `proc` entry, the name of the process):
|
||||
|
||||
* the leaf `proc.<name>` that is the published engine having it (count >= 1) and the candidate not having it;
|
||||
* a file leaf of a seed in `probe_seeds` (the seeds where that leaf above differs) that only the published engine has and whose ONLY toucher on that side is that kind:
|
||||
what a process the candidate no longer spawns alone touched goes with it. A leaf another process touched too stays a difference, and so does a leaf the
|
||||
candidate touches or one the candidate alone has."""
|
||||
if entry.get("category") != "proc":
|
||||
return False
|
||||
published, candidate = diff["a"], diff["b"]
|
||||
return (published != MISSING and published >= 1) and candidate == MISSING
|
||||
if diff["leaf"] == "proc." + entry["name"]:
|
||||
return (published != MISSING and published >= 1) and candidate == MISSING
|
||||
by = diff.get("by") or {}
|
||||
return (diff["category"] == "file" and diff["seed"] in probe_seeds and published != MISSING and candidate == MISSING
|
||||
and by.get("A") == [entry["name"]] and not by.get("B"))
|
||||
|
||||
|
||||
def warmup_only(fp: dict) -> dict | None:
|
||||
@@ -1615,8 +1663,9 @@ def judge(a: dict, b: dict, expected: list | None = None, a_a: bool = False, pla
|
||||
for entry in expected or []:
|
||||
if entry.get("os") != os_name:
|
||||
continue
|
||||
hit = [d for d in differences if _declared_covers(entry, d)]
|
||||
if not hit:
|
||||
probe_seeds = {d["seed"] for d in differences if d["leaf"] == "proc." + entry.get("name", "") and _declared_covers(entry, d)}
|
||||
hit = [d for d in differences if _declared_covers(entry, d, probe_seeds)]
|
||||
if not any(d["leaf"] == "proc." + entry.get("name", "") for d in hit):
|
||||
stale.append(entry)
|
||||
problems.append("the declared difference %r (%s) does not show in this run: it is stale, remove it"
|
||||
% (entry.get("id", entry.get("name")), entry.get("reason", "")))
|
||||
@@ -1791,14 +1840,20 @@ def geolocation_step(browser, origin: str, declared: dict | None, n: int) -> dic
|
||||
return step
|
||||
|
||||
|
||||
def run_seed(binary: str, seed: int, work: Path, name: str | None = None, idle: bool = False, bare: bool = False) -> dict:
|
||||
def run_seed(binary: str, seed: int, work: Path, name: str | None = None, idle: bool = False, bare: bool = False, crash_with: int | None = None) -> dict:
|
||||
"""One browser, one journey, one close, one trace. Returns the seed's footprint; `name` is the folder of its work (the warm-up has one of its own).
|
||||
|
||||
`bare` is the old idle launch, kept as a case of its own and never compared: no client and no page, as the run 44988820319 made it (a crash reporter ran in it, on
|
||||
both systems). It records how the browser ended and what a crash leaves (`crash_evidence`), on Linux with core dumps on, and waits as the idle launch does.
|
||||
|
||||
`idle` is the launch in which the exit pings MUST leave (see `run_engine`): no journey and no pref changed; the launch waits until the notification of the data
|
||||
policy is recorded in its profile (the precondition of `canUpload`, seen in a file of the launch) and then closes; its footprint carries `idle` (what the wait saw)."""
|
||||
policy is recorded in its profile (the precondition of `canUpload`, seen in a file of the launch) and then closes; its footprint carries `idle` (what the wait saw).
|
||||
|
||||
EVERY launch is judged by how its parent ended: a root exit code other than 0 is a problem of the launch (`crash.exit_problem`) and the launch keeps what it left
|
||||
(`result["crash"]`, `crash.collect`: the strace tail with the signal line, the core through gdb, the build ids, the `.extra` and the minidump names). The cores are
|
||||
enabled in every launch (`ulimit -c unlimited` in the stand-in, the working directory untouched) and a crash watcher reads the crash folders while any launch lives.
|
||||
|
||||
`crash_with` is the recorder's own test (`crash-probe`): the signal sent to the parent of the browser once it is up, to show that a launch that dies is red and keeps its evidence."""
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
from fakeweb import journey_site, profile_p4
|
||||
@@ -1822,7 +1877,7 @@ def run_seed(binary: str, seed: int, work: Path, name: str | None = None, idle:
|
||||
from _strace_stand_in import _stand_in
|
||||
|
||||
exe = _stand_in(binary, seed_work / "engine", log, pidfile, syscalls=STRACE_CALLS, fd_paths=True, network=True, exit_status=True,
|
||||
core_dir=seed_work if bare else None)
|
||||
core_dir=seed_work if bare else None, cores=True)
|
||||
origin_a, origin_o, stop_site = journey_site.start((0, 0))
|
||||
geo_origin, stop_geo = start_geo_lab()
|
||||
server, steps, root_pid = None, [], None
|
||||
@@ -1835,6 +1890,9 @@ def run_seed(binary: str, seed: int, work: Path, name: str | None = None, idle:
|
||||
new = sorted(set(Path(tempfile.gettempdir()).glob("invisible_profile_*")) - before)
|
||||
return crash_report_dirs(new[0] if new else None, windows)
|
||||
|
||||
started_at = time.time()
|
||||
already = crash.existing_crash_files(crash_dirs()) # the reports of earlier crashes are not this launch's
|
||||
|
||||
try:
|
||||
server = launch_server(headless=True, binary_path=exe, seed=seed, locale="en-US", timezone="Europe/Rome",
|
||||
launch_timeout_ms=180_000)
|
||||
@@ -1843,11 +1901,12 @@ def run_seed(binary: str, seed: int, work: Path, name: str | None = None, idle:
|
||||
from _strace_stand_in import _group_of
|
||||
|
||||
pgid = _group_of(pidfile)
|
||||
if bare:
|
||||
watcher = CrashWatcher(crash_dirs)
|
||||
watcher.start()
|
||||
with (contextlib.nullcontext() if bare else sync_playwright()) as p:
|
||||
if bare:
|
||||
watcher = CrashWatcher(crash_dirs, ignore=already)
|
||||
watcher.start()
|
||||
with (contextlib.nullcontext() if (bare or crash_with is not None) else sync_playwright()) as p:
|
||||
if crash_with is not None:
|
||||
crash_the_parent(root_pid, server.process, crash_with) # the recorder's own test: the browser is up, its parent is sent a fatal signal
|
||||
elif bare:
|
||||
notified = wait_for_notification(profile_prefs_reader(before)) # nothing drives the bare browser: the launch the idle one was
|
||||
elif idle:
|
||||
# Run 44988820319: with no client and no page the notification was never recorded in 120 s on either system (no window, so no
|
||||
@@ -1892,9 +1951,15 @@ def run_seed(binary: str, seed: int, work: Path, name: str | None = None, idle:
|
||||
result = _seed_result(binary, seed, seed_work, steps, log, trace, root_pid, windows, close)
|
||||
if idle:
|
||||
result["idle"] = {"notified": notified, "shortcut_changes": diff_snapshots(shortcuts_before, snapshot_places(places)) if places else None}
|
||||
watched, watcher = watcher.stop(), None
|
||||
if bare:
|
||||
result["bare"] = {"notified": notified, "crash": crash_evidence(watcher.stop(), result, core_info(seed_work, binary) if not windows else None)}
|
||||
watcher = None
|
||||
result["bare"] = {"notified": notified, "crash": crash_evidence(watched, result, core_info(seed_work, binary) if not windows else None)}
|
||||
bad, left = end_of_launch(close["root_returncode"], windows, seed, name or "measured", result.get("lifecycle"), binary, log, watched,
|
||||
seed_work if bare else None, started_at)
|
||||
problems += bad
|
||||
result["exit_problems"] = bad
|
||||
if left:
|
||||
result["crash"] = left
|
||||
except TraceError as e:
|
||||
result = {"seed": seed, "steps": steps, "kinds": {}, "files": [], "ours": {}, "trace": {"exited": False},
|
||||
"problems": ["the trace of the run could not be taken: %s" % e]}
|
||||
@@ -1918,98 +1983,50 @@ def run_seed(binary: str, seed: int, work: Path, name: str | None = None, idle:
|
||||
return result
|
||||
|
||||
|
||||
def end_of_launch(code, windows: bool, seed: int, launch: str, lifecycle, binary: str, log, watched: dict, bare_dir, started_at: float, folders=None, run=subprocess.run) -> tuple:
|
||||
"""How a launch ended, as the verdict reads it: `(problems, evidence)`. A root exit code other than 0 (or not seen) is a problem that names the seed, the launch and the
|
||||
code (`crash.exit_problem`), and so is a process of the kind parent that the lifecycle says did not exit 0 when the root said nothing of it (Windows: the core's spawn
|
||||
may be a launcher). A launch with a problem keeps what it left (`crash.collect`): the strace tail and the fatal signal lines, the cores through gdb with the build ids
|
||||
(the folders of the job's core pattern, and the launch's own when it moved there: the bare one), the `.extra` and the minidump names the watcher read. A launch that
|
||||
ended with 0 has none and costs nothing."""
|
||||
bad = [x for x in [crash.exit_problem(code, windows, seed=seed, launch=launch)] + crash.parent_exit_problems(lifecycle, code, seed=seed, launch=launch) if x]
|
||||
if not bad:
|
||||
return [], None
|
||||
if folders is None:
|
||||
folders = [] if windows else crash.core_dirs() + ([bare_dir] if bare_dir else [])
|
||||
return bad, crash.collect(code, binary, strace_log=None if windows else log, watched=watched, windows=windows, core_folders=folders, since=started_at, run=run)
|
||||
|
||||
|
||||
def browser_parent(root_pid: int, children=None) -> int:
|
||||
"""The pid of the browser's own parent process: under the stand-in the root is strace, whose child is the browser (a content process is not it)."""
|
||||
if children is None:
|
||||
import psutil
|
||||
|
||||
children = psutil.Process(root_pid).children
|
||||
for child in children():
|
||||
try:
|
||||
if "-contentproc" not in [str(a) for a in child.cmdline()]:
|
||||
return child.pid
|
||||
except Exception: # noqa: BLE001 - a child that is already gone
|
||||
continue
|
||||
raise RuntimeError("the root process %s has no browser parent to send the signal to" % root_pid)
|
||||
|
||||
|
||||
def crash_the_parent(root_pid: int, process, signum: int, limit_s: float = 60.0, kill=os.kill, parent=None, sleep=time.sleep, now=time.monotonic) -> int:
|
||||
"""The recorder's own test: `signum` is sent to the browser's parent process with `os.kill`, and the launch waits for the root to end (a limit of acquisition, never a
|
||||
verdict: what ended it is read from the code the close sees). Returns the pid it was sent to."""
|
||||
pid = parent if parent is not None else browser_parent(root_pid)
|
||||
kill(pid, signum)
|
||||
end = now() + limit_s
|
||||
while process.poll() is None and now() < end:
|
||||
sleep(0.1)
|
||||
return pid
|
||||
|
||||
|
||||
#: The crash evidence of the BARE launch (no client, no page: the launch of run 44988820319 that had a crash reporter): where a crash leaves its files.
|
||||
CRASH_PROCESS = re.compile(r"crashreporter|minidump-analyzer", re.I)
|
||||
|
||||
|
||||
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."""
|
||||
|
||||
def __init__(self, dirs_fn, period: float = 0.25) -> None:
|
||||
import threading
|
||||
|
||||
self.dirs_fn, self.period = dirs_fn, period
|
||||
self.seen: dict = {}
|
||||
self.scans = 0
|
||||
self._halt = threading.Event()
|
||||
self._thread = threading.Thread(target=self._run, name="ab-host-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()
|
||||
return {"files": sorted(self.seen.values(), key=lambda f: f["name"]), "scans": self.scans}
|
||||
|
||||
|
||||
def core_info(core_dir: Path, binary: str, run=subprocess.run) -> dict:
|
||||
"""What a Linux core dump of the bare 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
|
||||
the backtrace of each (`gdb -batch -ex bt`) when gdb is installed."""
|
||||
try:
|
||||
pattern = Path("/proc/sys/kernel/core_pattern").read_text(encoding="utf-8").strip()
|
||||
except OSError:
|
||||
pattern = None
|
||||
cores = sorted(p for p in Path(core_dir).glob("core*") if p.is_file())
|
||||
out = {"core_pattern": pattern, "cores": [c.name for c in cores], "backtraces": {}}
|
||||
gdb = shutil.which("gdb")
|
||||
for core in cores[:3]:
|
||||
if gdb:
|
||||
done = run([gdb, "-batch", "-ex", "bt", str(binary), str(core)], capture_output=True, text=True, errors="replace", timeout=180)
|
||||
out["backtraces"][core.name] = (done.stdout + done.stderr)[-8000:]
|
||||
else:
|
||||
out["backtraces"][core.name] = "gdb is not installed"
|
||||
return out
|
||||
|
||||
|
||||
def crash_evidence(watched: dict, fp: dict, core: dict | None = None) -> dict:
|
||||
"""What the bare launch says about how the browser ended: the exit code or signal of its parent processes (from the lifecycle), every crash reporter or
|
||||
minidump analyzer process with its command line, the `.dmp` names and `.extra` contents the watcher read, and the core dump if there is one."""
|
||||
@@ -2183,9 +2200,24 @@ def _seed_result(binary: str, seed: int, seed_work: Path, steps: list, log: Path
|
||||
return out
|
||||
|
||||
|
||||
def run_engine(binary: str, leg: str, seeds: list, label: str) -> dict:
|
||||
def keep_crash(fp: dict, launch: str, crash_dir) -> None:
|
||||
"""The evidence of a launch that did not end with 0 (`result["crash"]`) as files in the oracle's artifact, `<crash_dir>/<launch>/`, and said on the output."""
|
||||
if not fp.get("crash"):
|
||||
return
|
||||
where = None
|
||||
if crash_dir:
|
||||
where = Path(crash_dir) / launch
|
||||
crash.write_crash_files(fp["crash"], where)
|
||||
print("CRASH EVIDENCE %s (seed %s): exit %s; %s%s" % (launch, fp.get("seed"), fp["crash"]["exit"]["text"], "saved in %s" % where if where else "not saved (no folder)",
|
||||
"; NOT FOUND: " + " | ".join(fp["crash"]["said"]) if fp["crash"]["said"] else ""))
|
||||
sys.stdout.flush()
|
||||
|
||||
|
||||
def run_engine(binary: str, leg: str, seeds: list, label: str, crash_dir=None) -> dict:
|
||||
"""The footprint document of one engine. A discarded WARM-UP launch first, of the first seed, then every seed's journey, one browser at a time.
|
||||
|
||||
Every launch (the warm-up, each seed, the idle and the bare ones) that does not end with 0 is a problem of the run, and what it left is kept in `crash_dir` (`keep_crash`).
|
||||
|
||||
The warm-up is a control of the experiment and not an excuse: what a machine does the first time it runs an engine (its files scanned, its caches
|
||||
cold, a first-run behaviour of the engine) is in a launch that is not compared, whose trace is kept in the document (`warmup`) so that what it
|
||||
did and the measured launch did not stays visible, run to run (`warmup_only`). The order is the same in every run: the warm-up of an engine, then its
|
||||
@@ -2194,12 +2226,14 @@ def run_engine(binary: str, leg: str, seeds: list, label: str) -> dict:
|
||||
problems, out_seeds = [], []
|
||||
try:
|
||||
warm = run_seed(binary, seeds[0], work, name="warmup")
|
||||
keep_crash(warm, "warmup", crash_dir)
|
||||
problems += ["warm-up: %s" % p for p in warm.get("problems", [])]
|
||||
problems += ["warm-up: seed %d: step %d (%s) failed: %s" % (seeds[0], st["n"], st["name"], st.get("error")) for st in warm["steps"] if not st["ok"]]
|
||||
print("warm-up (seed %d, discarded): %s; %d host paths" % (seeds[0], json.dumps(warm["kinds"], sort_keys=True), len(warm["files"])))
|
||||
sys.stdout.flush()
|
||||
for seed in seeds:
|
||||
fp = run_seed(binary, seed, work)
|
||||
keep_crash(fp, "seed%d" % seed, crash_dir)
|
||||
out_seeds.append(fp)
|
||||
for step in fp["steps"]:
|
||||
if not step["ok"]:
|
||||
@@ -2208,11 +2242,14 @@ def run_engine(binary: str, leg: str, seeds: list, label: str) -> dict:
|
||||
len(fp.get("net") or []), json.dumps(fp.get("ours", {}), sort_keys=True)))
|
||||
sys.stdout.flush()
|
||||
idle = run_seed(binary, seeds[0], work, name="idle", idle=True)
|
||||
keep_crash(idle, "idle", crash_dir)
|
||||
problems += ["idle: %s" % p for p in idle.get("problems", [])]
|
||||
print("idle (seed %d): %s; notification %s" % (seeds[0], json.dumps(idle["kinds"], sort_keys=True), json.dumps((idle.get("idle") or {}).get("notified"))))
|
||||
sys.stdout.flush()
|
||||
# The bare launch: the old idle launch (no client, no page), a case of its own that is never compared; what it records is evidence (`crash_evidence`).
|
||||
bare = run_seed(binary, seeds[0], work, name="bare", bare=True)
|
||||
keep_crash(bare, "bare", crash_dir)
|
||||
problems += ["bare: %s" % p for p in bare.get("exit_problems", [])] # the bare launch is never compared, but how its parent ended is red like any other's
|
||||
print("bare (seed %d, not compared): %s; %s" % (seeds[0], json.dumps(bare["kinds"], sort_keys=True), json.dumps(_bare_summary(bare.get("bare")))))
|
||||
sys.stdout.flush()
|
||||
finally:
|
||||
@@ -2275,9 +2312,42 @@ def read_json(path: Path) -> dict:
|
||||
# -
|
||||
# The run of an engine as a subprocess (the seal a process runs under is read at import), and the orchestration.
|
||||
|
||||
def run_subprocess(binary: str, seal: Path | None, leg: str, out: Path, label: str, seeds: list) -> int:
|
||||
#: Where the engine under test is run from, whichever engine it is: `<RUNNER_TEMP>/ab-host/engine/firefox` (the temp root of the machine without it). The content processes and the
|
||||
#: forkserver call `realpath(<install>/omni.ja)` (Omnijar::ChildProcessInit -> XRE_GetFileFromPath -> nsToolkitProfileService.cpp realpath), which reads the link of EVERY ancestor of
|
||||
#: the install folder: the oracle sees `readlink /srv`, `/srv/lab/work`, ... for an engine that sits in the checkout and `readlink /tmp/ab-host-fetch-<random>/engines` for one
|
||||
#: that was fetched (run 45043617981: 10 leaves of that on each of 5 seeds). The place of the install is a variable of the experiment, so it is the same in the three runs of an
|
||||
#: A/B, and the ancestors of the package are the same leaves in each: nothing is normalised in the comparison.
|
||||
STAGE_ENGINE = ("ab-host", "engine")
|
||||
STAGE_PACKAGE = "firefox"
|
||||
|
||||
|
||||
def stage_dir(base=None) -> Path:
|
||||
"""The folder the engine under test is run from: the same absolute path for every engine and every run."""
|
||||
return Path(base or os.environ.get("RUNNER_TEMP") or tempfile.gettempdir()).joinpath(*STAGE_ENGINE) / STAGE_PACKAGE
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def staged_engine(binary: str, base=None):
|
||||
"""The whole package of `binary` (its folder, every file, links kept, the bytes as they are) copied to `stage_dir`, yielding the path of the binary there; the copy is
|
||||
removed when the run is over, so the next engine is staged at the very same path."""
|
||||
source = Path(os.path.abspath(binary))
|
||||
dest = stage_dir(base)
|
||||
shutil.rmtree(dest, ignore_errors=True)
|
||||
if dest.exists():
|
||||
raise OSError("the folder the engine is run from, %s, could not be emptied" % dest)
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copytree(source.parent, dest, symlinks=True)
|
||||
try:
|
||||
yield str(dest / source.name)
|
||||
finally:
|
||||
shutil.rmtree(dest, ignore_errors=True)
|
||||
|
||||
|
||||
def run_subprocess(binary: str, seal: Path | None, leg: str, out: Path, label: str, seeds: list, crash_with: str | None = None) -> int:
|
||||
"""`run` in a process of its own, with a cache folder and a temp root of its own: they are the run's, so what the engine does in them is `ours`
|
||||
(the cache of the bundle's fonts, the profile and the temp dirs of the launch) and the rest of the machine is the host's."""
|
||||
(the cache of the bundle's fonts, the profile and the temp dirs of the launch) and the rest of the machine is the host's.
|
||||
|
||||
`crash_with` (a signal name) makes the run the recorder's own test: one launch, whose parent is sent that signal (`crash-probe`)."""
|
||||
env = dict(os.environ, INVISIBLE_CORE_AUTOFIX="off", INVISIBLE_CORE_PIN="allow")
|
||||
if seal:
|
||||
env["INVISIBLE_SEAL_FILE"] = str(seal)
|
||||
@@ -2285,6 +2355,8 @@ def run_subprocess(binary: str, seal: Path | None, leg: str, out: Path, label: s
|
||||
env.pop(name, None)
|
||||
cmd = [sys.executable, "-u", str(Path(__file__).resolve()), "run", binary, "--leg", leg, "--out", str(out), "--label", label,
|
||||
"--seeds", ",".join(str(s) for s in seeds)]
|
||||
if crash_with:
|
||||
cmd += ["--crash-with", crash_with]
|
||||
try:
|
||||
with tempfile.TemporaryDirectory(prefix="ab-host-cache-") as cache, tempfile.TemporaryDirectory(prefix="ab-host-tmp-") as temp:
|
||||
env = oracle.own_cache_env(env, cache)
|
||||
@@ -2294,6 +2366,37 @@ def run_subprocess(binary: str, seal: Path | None, leg: str, out: Path, label: s
|
||||
return 124
|
||||
|
||||
|
||||
def run_crash_probe(binary: str, leg: str, seed: int, label: str, crash_dir=None, signame: str = "SIGSEGV") -> dict:
|
||||
"""The recorder's own test: ONE launch of the engine whose parent process is sent a fatal signal with `os.kill` once the browser is up. The footprint's problems must
|
||||
name the code (`exit_problem`) and `crash` must hold what the launch left (`keep_crash`): a recorder that does not turn this into a red line with its evidence is broken."""
|
||||
import signal
|
||||
|
||||
work = Path(tempfile.mkdtemp(prefix="ab-host-"))
|
||||
try:
|
||||
fp = run_seed(binary, seed, work, name="crash", crash_with=getattr(signal, signame))
|
||||
keep_crash(fp, "crash", crash_dir)
|
||||
finally:
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
return {"format": FORMAT, "engine": label, "leg": leg, "platform": sys.platform, "seeds": [], "probe": fp, "signal": signame, "problems": list(fp.get("problems", []))}
|
||||
|
||||
|
||||
def crash_probe(binary: str, leg: str, out: Path, seed: int, run=None) -> int:
|
||||
"""`crash-probe`: the engine is launched once, its parent is sent SIGSEGV, and this reports what the oracle says of it. 1 is RED, which is what a launch that dies must
|
||||
be (the e2e test asserts it, with the evidence); 0 means the recorder did not see the crash (the test fails on that); 2 the probe itself did not run."""
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
path = out / "footprint-crash.json"
|
||||
rc = (run or run_subprocess)(binary, None, leg, path, "crash probe", [seed], "SIGSEGV")
|
||||
if rc != 0 or not path.exists():
|
||||
print("FAIL the crash probe did not run: its process ended with %s" % rc)
|
||||
return 2
|
||||
document = read_json(path)
|
||||
for line in document["problems"]:
|
||||
print("FAIL " + line)
|
||||
exit_lines = [x for x in document["problems"] if x.startswith("the parent process exited with code")]
|
||||
print("AB HOST CRASH PROBE %s: %d problems, %d of them a parent that did not end with 0" % ("FAILED" if exit_lines else "OK", len(document["problems"]), len(exit_lines)))
|
||||
return 1 if exit_lines else 0
|
||||
|
||||
|
||||
def run_stock_subprocess(leg: str, out: Path) -> int:
|
||||
"""`stock` in a process of its own (its tree is the one of that process), with a temp root of its own."""
|
||||
env = dict(os.environ)
|
||||
@@ -2341,9 +2444,14 @@ def ab(candidate: str | None, candidate_seal: Path | None, leg: str, out: Path,
|
||||
runs.append((oracle.CANDIDATE, "footprint-candidate.json", candidate, candidate_seal))
|
||||
failed = []
|
||||
for label, name, exe, seal_file in runs:
|
||||
print("=== footprint with %s: %s" % (label, exe))
|
||||
print("=== footprint with %s: %s (run from %s)" % (label, exe, stage_dir()))
|
||||
sys.stdout.flush()
|
||||
rc = run_subprocess(exe, Path(seal_file) if seal_file else None, leg, out / name, label, seeds)
|
||||
try:
|
||||
with staged_engine(exe) as staged:
|
||||
rc = run_subprocess(staged, Path(seal_file) if seal_file else None, leg, out / name, label, seeds)
|
||||
except OSError as e:
|
||||
print("the engine of %s could not be staged: %s" % (label, e))
|
||||
rc = 125
|
||||
if rc != 0 or not (out / name).exists():
|
||||
failed.append("the run with %s ended with %s" % (label, rc))
|
||||
if failed:
|
||||
@@ -2384,6 +2492,7 @@ def main(argv=None) -> int:
|
||||
r.add_argument("--out", type=Path, required=True)
|
||||
r.add_argument("--label", default="engine")
|
||||
r.add_argument("--seeds", default=None, help="comma separated (default: ci/persona-seeds.json 'candidate', else the host gate's)")
|
||||
r.add_argument("--crash-with", choices=["SIGSEGV"], default=None, help="the recorder's own test: one launch, its parent sent this signal (see crash-probe)")
|
||||
k = sub.add_parser("stock", help="the negative control of the geolocation step (Windows): Playwright's own Firefox")
|
||||
k.add_argument("--leg", required=True)
|
||||
k.add_argument("--out", type=Path, required=True)
|
||||
@@ -2393,6 +2502,11 @@ def main(argv=None) -> int:
|
||||
c.add_argument("--out", type=Path)
|
||||
c.add_argument("--a-a", action="store_true", help="the control: no declared difference is applied; a difference is a broken control (exit 2)")
|
||||
c.add_argument("--expected", type=Path, default=EXPECTED_FILE)
|
||||
q = sub.add_parser("crash-probe", help="the recorder's own test: one launch whose parent is sent SIGSEGV; exit 1 (red, with the evidence) is the right answer")
|
||||
q.add_argument("binary")
|
||||
q.add_argument("--leg", required=True)
|
||||
q.add_argument("--out", type=Path, required=True)
|
||||
q.add_argument("--seed", type=int, default=None)
|
||||
x = sub.add_parser("ab", help="A/A, then with a candidate the published engine against it")
|
||||
x.add_argument("candidate", nargs="?")
|
||||
x.add_argument("--candidate-seal", type=Path, default=os.environ.get("INVISIBLE_SEAL_FILE"))
|
||||
@@ -2418,12 +2532,21 @@ def main(argv=None) -> int:
|
||||
return 3
|
||||
write_json(args.out, run_stock(args.leg))
|
||||
return 0
|
||||
if args.cmd == "crash-probe":
|
||||
if not sys.platform.startswith("linux"):
|
||||
print("the crash probe sends a signal to the parent of the browser: Linux only")
|
||||
return 3
|
||||
return crash_probe(args.binary, args.leg, args.out, args.seed if args.seed is not None else default_seeds()[0])
|
||||
seeds = [int(s) for s in args.seeds.split(",")] if args.seeds else default_seeds()
|
||||
if args.cmd == "run":
|
||||
if sys.platform.startswith("linux") and not shutil.which("strace"):
|
||||
print("needs strace (apt install strace): without it the processes and the files of the run are not seen")
|
||||
return 3
|
||||
document = run_engine(args.binary, args.leg, seeds, args.label)
|
||||
crash_dir = args.out.parent / (args.out.stem + ".crash") # footprint-68.json -> footprint-68.crash/<launch>/: what a launch that did not end with 0 left
|
||||
if args.crash_with:
|
||||
document = run_crash_probe(args.binary, args.leg, seeds[0], args.label, crash_dir, args.crash_with)
|
||||
else:
|
||||
document = run_engine(args.binary, args.leg, seeds, args.label, crash_dir)
|
||||
write_json(args.out, document)
|
||||
return 0
|
||||
if args.candidate and not args.candidate_seal:
|
||||
|
||||
@@ -43,6 +43,12 @@ whether it stopped by itself). Both record the destinations they saw; the A/A sa
|
||||
python ci_ab_network.py compare A.json B.json [--floor N] [--out diff.json] [--a-a]
|
||||
python ci_ab_network.py ab --out DIR [--candidate BIN --candidate-seal SEAL] [--published-binary B] [--a-a] [--floor N]
|
||||
|
||||
HOW EACH LAUNCH ENDS. Every browser a run launches (the main launch of each seed and the idle and exit-ping launches of the first) is seen by a probe
|
||||
(scripts/ci_crash_evidence.py: the exit code of the browser's parent after the close the launch already makes, and a watcher on the crash folders): the transcript carries them
|
||||
under ``exits``, outside the leaves that are compared, and a parent that did not end with 0, or whose code was not seen, or a run that recorded no launch, is a RED line that names
|
||||
the side, the seed, the launch and the code. What a launch that died left is kept beside the transcript (``transcript-68.json`` -> ``transcript-68.crash/``): the core through gdb with
|
||||
the build ids, the ``.extra`` and the minidump names, ``said.txt`` for what the collectors did not find. This oracle runs no strace (a trace would change the outcome it observes).
|
||||
|
||||
Exit codes: 0 green, 1 red (a finding), 2 broken control (the A/A is red) or a run that could not run.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
@@ -51,6 +57,7 @@ import argparse
|
||||
import collections
|
||||
import fnmatch
|
||||
import hashlib
|
||||
import itertools
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
@@ -67,9 +74,11 @@ from typing import Any, Callable, Dict, List, Optional, Tuple
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
import ci_crash_evidence as crash # noqa: E402 (how each launch's parent ended: a code other than 0 is red, and what it left is saved)
|
||||
|
||||
FORMAT = "ab-network/1"
|
||||
DIFF_FORMAT = "ab-network-diff/1"
|
||||
EVIDENCE_FORMAT = "ab-network-evidence/1"
|
||||
VOLATILE_FORMAT = "ab-network-volatile/1"
|
||||
VOLATILE_FILE = ROOT / "ci" / "ab-network-volatile.json"
|
||||
SEEDS_FILE = ROOT / "ci" / "persona-seeds.json"
|
||||
@@ -259,6 +268,17 @@ def _udp_attribution(la: Dict[str, Any], lb: Dict[str, Any]) -> Tuple[set, List[
|
||||
return paths, differences, unattributed
|
||||
|
||||
|
||||
def exit_lines(transcript: Dict[str, Any], label: str, side: str) -> List[str]:
|
||||
"""The red lines of the launches of one side that did not end with 0 (``exits``, which ``run`` writes: scripts/ci_crash_evidence.py). A transcript that has no ``exits``
|
||||
was not made by ``run`` and says nothing about it; one that has it and no launch in it is a run whose probe saw no browser, which is red."""
|
||||
exits = transcript.get("exits")
|
||||
if exits is None:
|
||||
return []
|
||||
if not exits.get("launches"):
|
||||
return ["the run %s recorded no launch (side %s): the probe did not see a browser, so how its browsers ended is not known" % (label, side)]
|
||||
return crash.exit_problems(exits["launches"], label, transcript.get("platform") == "win32", side=side)
|
||||
|
||||
|
||||
def compare_transcripts(a: Dict[str, Any], b: Dict[str, Any], volatile: List[Dict[str, str]], floor: int = 0,
|
||||
label_a: str = "A", label_b: str = "B") -> Dict[str, Any]:
|
||||
"""The verdict on two transcripts (the ``seeds`` of each, as ``run`` writes them).
|
||||
@@ -303,6 +323,7 @@ def compare_transcripts(a: Dict[str, Any], b: Dict[str, Any], volatile: List[Dic
|
||||
if len(compared) < floor:
|
||||
problems.append("only %d leaves were compared, fewer than the floor of %d: a run that saw less than it should passes anything" % (len(compared), floor))
|
||||
problems += ["a direct connection: " + d for d in direct]
|
||||
problems += exit_lines(a, label_a, "A") + exit_lines(b, label_b, "B")
|
||||
problems += invariants
|
||||
problems += ["the volatile entry %r matches no leaf of either transcript: it is stale, drop it" % p for p in stale]
|
||||
problems += ["%s: %s %s | %s %s" % (d["path"], label_a, json.dumps(d["a"], sort_keys=True)[:160], label_b, json.dumps(d["b"], sort_keys=True)[:160])
|
||||
@@ -568,6 +589,7 @@ class Recorder:
|
||||
self.phase = "launch"
|
||||
self.events: List[Dict[str, Any]] = []
|
||||
self._lock = threading.Lock()
|
||||
self._t0 = time.monotonic()
|
||||
self._sources: Dict[str, list] = {}
|
||||
self._marks: List[Tuple[str, Dict[str, int]]] = []
|
||||
|
||||
@@ -582,7 +604,7 @@ class Recorder:
|
||||
|
||||
def event(self, kind: str, **fields: Any) -> None:
|
||||
with self._lock:
|
||||
self.events.append(dict(fields, kind=kind, phase=self.phase))
|
||||
self.events.append(dict(fields, kind=kind, phase=self.phase, t=round(time.monotonic() - self._t0, 3)))
|
||||
|
||||
def of(self, phase_prefix: str, kind: str) -> List[Dict[str, Any]]:
|
||||
with self._lock:
|
||||
@@ -607,6 +629,7 @@ class RawTee:
|
||||
from _wire_capture import Http1Parser
|
||||
|
||||
self.rec, self.upstream, self.role, self._parser = rec, upstream_port, role, Http1Parser
|
||||
self._connections = itertools.count()
|
||||
self._listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
self._listener.bind(("127.0.0.1", 0))
|
||||
self._listener.listen(64)
|
||||
@@ -620,9 +643,9 @@ class RawTee:
|
||||
client, _ = self._listener.accept()
|
||||
except OSError:
|
||||
return
|
||||
threading.Thread(target=self._serve, args=(client,), daemon=True).start()
|
||||
threading.Thread(target=self._serve, args=(client, next(self._connections)), daemon=True).start()
|
||||
|
||||
def _serve(self, client: socket.socket) -> None:
|
||||
def _serve(self, client: socket.socket, connection: int) -> None:
|
||||
try:
|
||||
upstream = socket.create_connection(("127.0.0.1", self.upstream), timeout=WAIT_S)
|
||||
except OSError:
|
||||
@@ -639,7 +662,7 @@ class RawTee:
|
||||
if tap is not None:
|
||||
for request in tap.feed(data):
|
||||
self.rec.event("http", role=self.role, method=request["method"], target=request["target"], headers=request["headers"],
|
||||
body_length=request["body_length"])
|
||||
body_length=request["body_length"], connection=connection)
|
||||
sink.sendall(data)
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
@@ -1017,7 +1040,10 @@ class Lab:
|
||||
from _wire_capture import WireServer
|
||||
|
||||
phase = lambda: self.rec.phase # noqa: E731
|
||||
self.h1 = WireServer(self.host, alpn=("http/1.1",), phase=phase, dns_names=(H1_NAME,))
|
||||
# The HTTP/1.1 server ends each connection after its answer (``Connection: close``), so every request after the first rides a connection the browser opens when it already has the session
|
||||
# ticket the first answer carried: whether a resumed connection happens no longer follows how fast the pool opened a second connection while the first was still busy (A/A run
|
||||
# 45025164169, Linux: a resumed h1 connection on one seed of one run and on none of the five seeds of the other).
|
||||
self.h1 = WireServer(self.host, alpn=("http/1.1",), phase=phase, dns_names=(H1_NAME,), close_after_response=True)
|
||||
self.h2 = WireServer(self.host, alpn=("h2", "http/1.1"), phase=phase, dns_names=(H2_NAME,))
|
||||
self.h3 = WireServer(self.host, alpn=("h2", "http/1.1"), h3=True, phase=phase, dns_names=(H3_NAME,))
|
||||
for server, role in ((self.h1, "h1"), (self.h2, "h2"), (self.h3, "h3")):
|
||||
@@ -1249,7 +1275,8 @@ class Trusting:
|
||||
|
||||
|
||||
def launch(binary: str, seed: int, lab: Lab, patch: Any) -> Any:
|
||||
"""The browser of a launch behind the gateway of ``lab``, as the realness suite launches it (the exit is declared, nothing asks the internet)."""
|
||||
"""The browser of a launch behind the gateway of ``lab``, as the realness suite launches it (the exit is declared, nothing asks the internet). The caller names the launch
|
||||
for the probe that sees how its parent ends (``crash.mark``: ``main``, ``idle-c1``, ``exit-pings``)."""
|
||||
from invisible_core import _geo
|
||||
from _lab_egress import LAB_EGRESS_IP
|
||||
from _session_end import EndingPlaywright
|
||||
@@ -1389,6 +1416,7 @@ def run_main(binary: str, seed: int, patch: Any) -> Dict[str, Any]:
|
||||
trap = start_trap()
|
||||
watcher = Watcher(match=("firefox", Path(binary).stem.lower())).start()
|
||||
try:
|
||||
crash.mark(seed=seed, launch="main")
|
||||
with launch(binary, seed, lab, patch) as browser:
|
||||
out["journey"] = guarded(lambda: walk_journey(browser, lab))
|
||||
out["https"] = {"h2": guarded(lambda: walk_https(browser, lab, "h2", lab.h2, H2_NAME)),
|
||||
@@ -1401,9 +1429,40 @@ def run_main(binary: str, seed: int, patch: Any) -> Dict[str, Any]:
|
||||
trap.__exit__(None, None, None)
|
||||
out["lab"] = {"direct": direct_report(lab, watcher, trap), "resolver_trap_ran": trap is not None,
|
||||
"launch": lab.norm.walk(launch_data(lab))}
|
||||
EVIDENCE[str(seed)] = guarded(lambda: wire_evidence(lab))
|
||||
return out
|
||||
|
||||
|
||||
#: What each seed of this run saw, request by request, kept OUTSIDE the leaves that are compared (``transcript["evidence"]``, like ``exits``): the transcript folds a request into a count
|
||||
#: and drops the connection it rode and the moment it arrived, which is what a run that differs from itself needs to be explained (A/A run 45025164169, Windows: a request of step 15
|
||||
#: counted twice in one run and once in the other, and nothing in the transcript said which page sent it or when).
|
||||
EVIDENCE: Dict[str, Any] = {}
|
||||
|
||||
|
||||
def wire_evidence(lab: Lab) -> Dict[str, Any]:
|
||||
"""The requests the tees of the journey saw (when, on which connection of the tee, in which stage, the line and the referer) and the connections of the HTTPS servers (when, in which
|
||||
stage, whether the ClientHello resumes a session, and for HTTP/1.1 the requests it carried with their moments). Times are seconds since the lab started."""
|
||||
journey = []
|
||||
for e in lab.rec.of("journey", "http"):
|
||||
referer = next((v for n, v in e["headers"] if n.lower() == "referer"), None)
|
||||
journey.append({"t": e["t"], "connection": e["connection"], "phase": e["phase"], "request": "%s %s%s" % (e["method"], e["role"], lab.norm.text(e["target"])),
|
||||
"referer": lab.norm.text(referer) if referer else None})
|
||||
https: Dict[str, Any] = {}
|
||||
for role, server in (("h1", lab.h1), ("h2", lab.h2)):
|
||||
if server is None:
|
||||
continue
|
||||
connections = []
|
||||
for c in server.snapshot()["connections"]:
|
||||
item = {"id": c["id"], "t": c.get("t"), "phase": c["phase"], "alpn": c["alpn"], "resumed": _resumed(c["tls"] or {})}
|
||||
if "http1" in c:
|
||||
item["requests"] = [{"t": r.get("t"), "request": r["request_line"]} for r in c["http1"]]
|
||||
if "h2" in c:
|
||||
item["requests"] = len(c["h2"].get("requests") or [])
|
||||
connections.append(item)
|
||||
https[role] = connections
|
||||
return {"journey": journey, "https": https}
|
||||
|
||||
|
||||
def sentinel_signature(lab: Lab) -> Dict[str, Any]:
|
||||
"""What the lab has seen that is not the sentinel: the destinations, the names, the datagram targets."""
|
||||
sentinel = lambda t: lab.norm.text(t).endswith(":page") # noqa: E731
|
||||
@@ -1417,6 +1476,7 @@ def run_idle(binary: str, seed: int, condition: str, patch: Any) -> Dict[str, An
|
||||
rounds in a row leave what is not the sentinel unchanged."""
|
||||
out: Dict[str, Any] = {}
|
||||
with open_lab(attribute_in=("launch", "idle", "sentinel")) as lab:
|
||||
crash.mark(seed=seed, launch="idle-" + condition)
|
||||
with launch(binary, seed, lab, patch) as browser:
|
||||
out["launch"] = lab.norm.walk(launch_data(lab)) # who asks what while the browser starts: the STUN Binding at launch is the core's measurement, not the browser's
|
||||
lab.rec.set_phase("idle")
|
||||
@@ -1499,6 +1559,7 @@ def run_exit_pings(binary: str, seed: int, patch: Any) -> Dict[str, Any]:
|
||||
watcher = Watcher(match=("firefox", Path(binary).stem.lower())).start()
|
||||
recorded = False
|
||||
try:
|
||||
crash.mark(seed=seed, launch="exit-pings")
|
||||
session = launch(binary, seed, lab, patch)
|
||||
with session as browser:
|
||||
lab.rec.set_phase("exit.wait")
|
||||
@@ -1526,9 +1587,14 @@ def walk_seed(binary: str, seed: int, with_idle: bool, patch: Any) -> Dict[str,
|
||||
|
||||
|
||||
def run(binary: str, label: str, seeds: Tuple[int, ...], out: Path) -> int:
|
||||
"""One engine, every seed: the transcript JSON. The idle launches run on the first seed only (what an idle browser asks is the engine's, not the persona's)."""
|
||||
"""One engine, every seed: the transcript JSON. The idle launches run on the first seed only (what an idle browser asks is the engine's, not the persona's).
|
||||
|
||||
A probe sees how every launch's parent ends (scripts/ci_crash_evidence.py): ``exits`` of the transcript, outside the leaves that are compared; a code other than 0 is red in
|
||||
``compare_transcripts``, and what the launch left (the core through gdb, the build ids, the ``.extra`` and the minidump names; this oracle runs no strace) is saved in the folder
|
||||
``AB_CRASH_DIR`` names (``run_engine`` gives it one beside the transcript)."""
|
||||
import pytest
|
||||
|
||||
probe = crash.start_probe(binary, os.environ.get(crash.CRASH_DIR_ENV))
|
||||
patch = pytest.MonkeyPatch()
|
||||
work = Path(tempfile.mkdtemp(prefix="ab-network-run-"))
|
||||
try:
|
||||
@@ -1536,16 +1602,24 @@ def run(binary: str, label: str, seeds: Tuple[int, ...], out: Path) -> int:
|
||||
|
||||
_lab_egress.install(patch, work)
|
||||
transcript: Dict[str, Any] = {"format": FORMAT, "label": label, "platform": sys.platform, "seeds": {}}
|
||||
EVIDENCE.clear()
|
||||
for index, seed in enumerate(seeds):
|
||||
print("=== %s: seed %d" % (label, seed))
|
||||
sys.stdout.flush()
|
||||
transcript["seeds"][str(seed)] = walk_seed(binary, seed, index == 0, patch)
|
||||
crash.stop_probe()
|
||||
transcript["evidence"] = {"format": EVIDENCE_FORMAT, "seeds": dict(EVIDENCE)}
|
||||
transcript["exits"] = probe.document()
|
||||
probe.write()
|
||||
for line in crash.exit_problems(probe.launches, label, windows=sys.platform == "win32"):
|
||||
print("EXIT " + line)
|
||||
write_json(out, transcript)
|
||||
for path in transcript_errors(transcript["seeds"]):
|
||||
print("ERROR in the transcript at %s" % path)
|
||||
print("transcript written: %s (%d leaves)" % (out, len(flatten(transcript["seeds"]))))
|
||||
return 0
|
||||
finally:
|
||||
crash.stop_probe()
|
||||
patch.undo()
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
|
||||
@@ -1567,6 +1641,7 @@ def run_engine(binary: str, seal: Optional[str], label: str, seeds: Tuple[int, .
|
||||
env["INVISIBLE_SEAL_FILE"] = str(seal)
|
||||
for name in ("MOZ_LOG", "MOZ_LOG_FILE"):
|
||||
env.pop(name, None)
|
||||
env[crash.CRASH_DIR_ENV] = str(Path(out).parent / (Path(out).stem + ".crash")) # footprint-68.json -> transcript-68.crash/: what a launch that did not end with 0 left
|
||||
command = [sys.executable, "-u", str(Path(__file__).resolve()), "run", "--binary", binary, "--label", label, "--seeds", ",".join(map(str, seeds)), "--out", str(out)]
|
||||
print("=== run %s: %s (seal %s)" % (label, binary, seal or "the one this process has"))
|
||||
sys.stdout.flush()
|
||||
|
||||
+70
-15
@@ -48,6 +48,20 @@ keeps between runs): the dump keeps the items of the second launch in that visit
|
||||
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),
|
||||
@@ -67,6 +81,7 @@ 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
|
||||
|
||||
@@ -92,6 +107,9 @@ CLIP = 400
|
||||
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
|
||||
|
||||
@@ -163,6 +181,17 @@ def split_launches(leaves: dict) -> tuple:
|
||||
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).
|
||||
@@ -179,6 +208,7 @@ def compare_visits(a: dict, b: dict, noise: list, min_leaves: dict | None = 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:
|
||||
@@ -191,12 +221,21 @@ def compare_visits(a: dict, b: dict, noise: list, min_leaves: dict | None = None
|
||||
continue
|
||||
dpr, seed = key
|
||||
la, lb = comparable(a[key]), comparable(b[key])
|
||||
count, again = 0, 0
|
||||
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)
|
||||
@@ -204,21 +243,28 @@ def compare_visits(a: dict, b: dict, noise: list, min_leaves: dict | None = None
|
||||
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 count < floor:
|
||||
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:
|
||||
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:
|
||||
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,
|
||||
return {"verdict": "red" if problems else "green", "problems": problems, "differences": differences, "tab_crashes": crashes,
|
||||
"compared": compared, "relaunch": relaunched, "excused": excused}
|
||||
|
||||
|
||||
@@ -249,7 +295,8 @@ def judge(published: dict, candidate: dict, noise: list, extra_problems=(), expe
|
||||
relaunch: tuple | None = None) -> dict:
|
||||
report = compare_visits(published, candidate, noise, expected=expected, relaunch=relaunch)
|
||||
if extra_problems:
|
||||
report["problems"] = list(extra_problems) + report["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
|
||||
|
||||
@@ -334,6 +381,19 @@ def own_cache_env(env: dict, folder: str, platform: str | None = None) -> dict:
|
||||
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")
|
||||
@@ -365,12 +425,10 @@ def run(candidate: str, candidate_seal: Path, leg: str, out: Path, engine_tag: s
|
||||
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()
|
||||
try:
|
||||
rc = run_dump(exe, Path(seal_file), leg, target, visits)
|
||||
except subprocess.TimeoutExpired:
|
||||
rc = "timeout"
|
||||
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]))
|
||||
@@ -402,11 +460,8 @@ def _dump_visits(name: str, exe: str, seal_file, leg: str, visits: list, work: P
|
||||
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()
|
||||
try:
|
||||
rc = run_dump(exe, Path(seal_file) if seal_file else None, leg, target, visits)
|
||||
except subprocess.TimeoutExpired:
|
||||
rc = "timeout"
|
||||
problems = [] if rc == 0 else ["the dump with %s ended with %s" % (name, rc)]
|
||||
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
|
||||
|
||||
@@ -24,8 +24,8 @@ 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), this file and the seeds.
|
||||
SHARED = ("scripts/ci_ab_oracle.py", "scripts/ci_ab_pr_seeds.py", "scripts/persona_cover.py", "ci/persona-seeds.json")
|
||||
#: 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*",
|
||||
|
||||
@@ -0,0 +1,811 @@
|
||||
#!/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 the host oracle's bare launch reads), 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 bare launch's collectors of scripts/ci_ab_host.py live here and are reused by every launch).
|
||||
|
||||
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)
|
||||
|
||||
|
||||
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
|
||||
+182
-14
@@ -60,6 +60,12 @@ 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
|
||||
|
||||
@@ -68,15 +74,20 @@ 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"
|
||||
EXCEPTIONS = HERE / "exceptions.json"
|
||||
@@ -420,21 +431,79 @@ def visit_options(firefox: str, seed: int, dpr: float | None, zone: str, profile
|
||||
return options
|
||||
|
||||
|
||||
#: 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."""
|
||||
`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.*`)."""
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
launch, trace, result = _LAUNCH[0], Steps("new page"), None
|
||||
with InvisiblePlaywright(**options) as browser:
|
||||
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.
|
||||
page.goto("http://127.0.0.1:%d/?dpr%s" % (port, 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))
|
||||
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
|
||||
|
||||
|
||||
@@ -446,10 +515,15 @@ def second_launch(options: dict, port: int, dpr: float, timeout_ms: int, read=No
|
||||
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
|
||||
return read(with_profile, port, dpr, timeout_ms)
|
||||
_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)
|
||||
|
||||
@@ -460,8 +534,13 @@ def dump(firefox: str, leg: str, out: Path, reference: Path, timeout_ms: int = 1
|
||||
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."""
|
||||
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]
|
||||
@@ -470,6 +549,7 @@ def dump(firefox: str, leg: str, out: Path, reference: Path, timeout_ms: int = 1
|
||||
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))
|
||||
@@ -482,12 +562,15 @@ def dump(firefox: str, leg: str, out: Path, reference: Path, timeout_ms: int = 1
|
||||
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
|
||||
@@ -498,6 +581,11 @@ def dump(firefox: str, leg: str, out: Path, reference: Path, timeout_ms: int = 1
|
||||
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
|
||||
|
||||
|
||||
@@ -590,22 +678,44 @@ def ab_visit(firefox: str, seed: int, zone: str, dpr: float | None = None, timeo
|
||||
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 = browser.new_context(**options)
|
||||
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:
|
||||
context.close()
|
||||
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()
|
||||
@@ -808,6 +918,61 @@ 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)
|
||||
@@ -827,6 +992,7 @@ def main(argv=None) -> int:
|
||||
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
|
||||
@@ -840,6 +1006,8 @@ def main(argv=None) -> int:
|
||||
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
|
||||
|
||||
|
||||
+49
-10
@@ -12,7 +12,7 @@ same runner reads them. The engine's dumps are then held to the identity the cor
|
||||
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 per-user fonts, Linux ~/.local/share/fonts
|
||||
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
|
||||
@@ -63,7 +63,7 @@ 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"HKCU:\Software\Microsoft\Windows NT\CurrentVersion\Fonts"
|
||||
FONTS_KEY = r"HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts"
|
||||
FONT_VALUE = FAMILY + " (TrueType)"
|
||||
|
||||
Run = Callable[[list], tuple]
|
||||
@@ -326,10 +326,11 @@ def write_dependence(out: Path, summary: Path | None = None) -> dict | None:
|
||||
|
||||
#: 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 (run 45026082150: dark=false on both systems, and on Windows the
|
||||
#: per-user canary font not seen). 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}.
|
||||
IN_TRIAL = {"dark": ("linux", "windows"), "canary": ("windows",)}
|
||||
#: 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:
|
||||
@@ -399,6 +400,37 @@ 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)."""
|
||||
@@ -407,9 +439,13 @@ def control(out: Path, headless: bool = False) -> int:
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
probe = None
|
||||
error = None
|
||||
removed = []
|
||||
try:
|
||||
with sync_playwright() as p:
|
||||
browser = p.firefox.launch(headless=headless, firefox_user_prefs={"intl.regional_prefs.use_os_locales": True})
|
||||
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()
|
||||
@@ -423,7 +459,8 @@ def control(out: Path, headless: bool = False) -> int:
|
||||
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]}}
|
||||
"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))
|
||||
@@ -472,7 +509,9 @@ def _try(run: Run, cmd: list) -> str:
|
||||
|
||||
|
||||
def font_path_windows(env=None) -> Path:
|
||||
return Path((env or os.environ)["LOCALAPPDATA"]) / "Microsoft" / "Windows" / "Fonts" / FONT_FILE
|
||||
"""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:
|
||||
|
||||
@@ -19,16 +19,20 @@ _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 drops the signal lines."""
|
||||
(``+++ 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=none -s 4096" if exit_status else "-f -qq -s 4096") + (" -y" if fd_paths else "") + (" --kill-on-exit" if "--kill-on-exit" in help_text else "")
|
||||
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:
|
||||
@@ -43,7 +47,7 @@ def _require_strace_can_trace(tmp: Path) -> None:
|
||||
|
||||
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,
|
||||
core_dir: Path | None = None) -> str:
|
||||
core_dir: Path | None = None, 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.
|
||||
|
||||
@@ -61,7 +65,9 @@ def _stand_in(binary: str, tree: Path, log: Path, pidfile: Path, syscalls: str =
|
||||
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);
|
||||
``core_dir`` lets the tree dump core there (``ulimit -c unlimited``, and the working directory is that folder, where a plain ``core`` pattern writes)."""
|
||||
``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``; ``core_dir`` does that and moves the working directory to that folder, where a
|
||||
plain ``core`` pattern writes (the bare launch of scripts/ci_ab_host.py)."""
|
||||
if network:
|
||||
syscalls = syscalls + "," + _NET_SYSCALLS
|
||||
real = Path(os.path.realpath(binary))
|
||||
@@ -70,13 +76,13 @@ def _stand_in(binary: str, tree: Path, log: Path, pidfile: Path, syscalls: str =
|
||||
if entry.name != real.name:
|
||||
(tree / entry.name).symlink_to(entry)
|
||||
script = tree / real.name
|
||||
cores = "ulimit -c unlimited\ncd %s\n" % core_dir if core_dir else ""
|
||||
cores_script = ("ulimit -c unlimited\ncd %s\n" % core_dir) if core_dir else ("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, shutil.which("strace"), _strace_options(fd_paths, exit_status) + (" -ttt" if timestamps else ""), log, syscalls, real))
|
||||
% (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)
|
||||
|
||||
|
||||
+19
-7
@@ -363,9 +363,10 @@ class Http1Parser:
|
||||
|
||||
|
||||
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) -> None:
|
||||
on_request: Callable[[Dict[str, Any]], None], alt_svc: Optional[str] = None, close_after_response: bool = False) -> 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)``."""
|
||||
``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."""
|
||||
parser = Http1Parser()
|
||||
while True:
|
||||
data = sock.recv(65536)
|
||||
@@ -377,9 +378,13 @@ def serve_http1(sock: Any, responder: Callable[[Dict[str, Any]], Tuple[int, List
|
||||
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() != "content-length"]
|
||||
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 close_after_response:
|
||||
return
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------------------------------------- HTTP/2
|
||||
@@ -635,11 +640,14 @@ class WireServer:
|
||||
|
||||
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",)) -> None:
|
||||
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] = []
|
||||
@@ -668,7 +676,7 @@ class WireServer:
|
||||
|
||||
# --- TCP ------------------------------------------------------------------------------------------------------------------------------
|
||||
def _connection(self, sock: socket.socket) -> None:
|
||||
record: Dict[str, Any] = {"phase": self.phase(), "tls": None, "alpn": 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)
|
||||
@@ -683,7 +691,7 @@ class WireServer:
|
||||
connection.serve(tls)
|
||||
else:
|
||||
record["http1"] = []
|
||||
serve_http1(tls, self.responder, lambda r: record["http1"].append(dict(r, phase=self.phase())), self.alt_svc)
|
||||
serve_http1(tls, self.responder, lambda r: record["http1"].append(dict(r, phase=self.phase(), t=self._now())), self.alt_svc, self.close_after_response)
|
||||
except (ssl.SSLError, OSError, ConnectionError, NotAClientHello, TimeoutError) as exc:
|
||||
record["error"] = "%s: %s" % (type(exc).__name__, exc)
|
||||
finally:
|
||||
@@ -694,6 +702,10 @@ class WireServer:
|
||||
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
|
||||
@@ -773,7 +785,7 @@ class WireServer:
|
||||
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"]}
|
||||
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:
|
||||
|
||||
+853
-36
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,80 @@
|
||||
"""A browser whose parent dies is RED in the host oracle, with its evidence: the recorder's own test (e2e, Linux).
|
||||
|
||||
scripts/ci_ab_host.py `crash-probe` launches the engine ONCE under the same stand-in the oracle's launches have (strace of the tree, cores enabled, a crash watcher on the
|
||||
crash folders), sends SIGSEGV to the browser's parent process with `os.kill` once the browser is up, closes it as the oracle closes it, and reports what the oracle says of
|
||||
that launch. This test runs it and asserts that the answer is RED, and that what the launch left is in the oracle's artifact:
|
||||
|
||||
* the verdict line names the code the parent ended with (`the parent process exited with code ...: seed N, launch crash`) and the probe exits 1;
|
||||
* `strace-signals.txt` and `strace-tail.txt` hold the `--- SIGSEGV {...} ---` line of the strace log (which `-e signal=none` used to drop) and the last lines of the trace;
|
||||
* `gdb-core.*.txt` is the core run through `gdb -batch` (`thread apply all bt`: a list of threads), and `build-ids.txt` the build ids;
|
||||
* `said.txt` says what the collectors did not find (a crash reporter that wrote no `.extra` is said, never silent).
|
||||
|
||||
The red of the probe is the right answer, so it does not make the job red: the test PASSES when the oracle reports red with the evidence, and FAILS when the oracle reports
|
||||
green for a launch that died (a recorder that does not see it), when the evidence is missing, or when the probe did not run. A probe never changes the outcome it observes:
|
||||
the engine, its prefs, its environment and its crash reporter are the oracle's own; the one thing added is the signal.
|
||||
|
||||
Linux only (`linux_only` in ci/required-suites.json): a signal sent with `os.kill`, a core the kernel writes and gdb reads, and strace's signal line do not exist on Windows.
|
||||
The job installs strace, gdb and elfutils and points the kernel's core pattern at a folder (INVPW_CORE_DIR). Evidence is kept in $RUNNER_TEMP/invpw-evidence/ab-host-crash.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
SCRIPT = ROOT / "scripts" / "ci_ab_host.py"
|
||||
sys.path.insert(0, str(ROOT / "scripts"))
|
||||
TIMEOUT_S = 15 * 60 # the launch, the signal, the close and gdb over a core of a browser (the job has 65 minutes)
|
||||
|
||||
|
||||
def _evidence_dir(tmp_path: Path) -> Path:
|
||||
base = os.environ.get("AB_ORACLE_OUT")
|
||||
if base:
|
||||
return Path(base) / "ab-host-crash"
|
||||
runner = os.environ.get("RUNNER_TEMP")
|
||||
if runner:
|
||||
return Path(runner) / "invpw-evidence" / "ab-host-crash"
|
||||
return tmp_path / "ab-host-crash"
|
||||
|
||||
|
||||
@pytest.mark.timeout(TIMEOUT_S + 120, method="thread")
|
||||
def test_a_browser_whose_parent_is_sent_sigsegv_is_red_in_the_host_oracle_with_its_gdb_threads_and_its_strace_signal_line(tmp_path):
|
||||
assert sys.platform.startswith("linux"), "Linux only: the signal, the core and strace's signal line"
|
||||
binary = os.environ.get("INVPW_BINARY_PATH")
|
||||
assert binary and Path(binary).is_file(), "INVPW_BINARY_PATH must name the engine's binary, got %r" % binary
|
||||
for tool in ("strace", "gdb"):
|
||||
if shutil.which(tool) is None:
|
||||
pytest.fail("needs %s (apt install strace gdb elfutils): without it the evidence of a crash is not kept" % tool, pytrace=False)
|
||||
from _strace_stand_in import _require_strace_can_trace
|
||||
|
||||
_require_strace_can_trace(tmp_path)
|
||||
out = _evidence_dir(tmp_path)
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
done = subprocess.run([sys.executable, "-u", str(SCRIPT), "crash-probe", binary, "--leg", "linux-x86_64", "--out", str(out)],
|
||||
capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=TIMEOUT_S)
|
||||
(out / "crash-probe.log").write_text(done.stdout + "\n--- stderr\n" + done.stderr, encoding="utf-8")
|
||||
assert done.returncode != 2, "the probe did not run:\n" + done.stdout[-2000:] + done.stderr[-1500:]
|
||||
assert done.returncode == 1, "the oracle did NOT report red for a launch whose parent was killed by SIGSEGV (exit %d):\n%s" % (done.returncode, done.stdout[-2500:])
|
||||
fail = [line for line in done.stdout.splitlines() if line.startswith("FAIL the parent process exited with code")]
|
||||
assert len(fail) == 1 and re.search(r"seed \d+, launch crash", fail[0]), "the red line names the code, the seed and the launch:\n" + done.stdout[-2500:]
|
||||
assert "AB HOST CRASH PROBE FAILED" in done.stdout
|
||||
folder = out / "footprint-crash.crash" / "crash"
|
||||
names = sorted(p.name for p in folder.glob("*")) if folder.is_dir() else []
|
||||
assert {"strace-tail.txt", "strace-signals.txt", "said.txt", "crash.json", "build-ids.txt"} <= set(names), "the evidence of the launch is in the artifact: %s" % names
|
||||
signals = (folder / "strace-signals.txt").read_text(encoding="utf-8")
|
||||
assert re.search(r"--- SIGSEGV \{si_signo=SIGSEGV, si_code=SI_USER", signals), "the signal line of the strace log (who sent it and what it was):\n" + signals[:800]
|
||||
tail = (folder / "strace-tail.txt").read_text(encoding="utf-8")
|
||||
assert tail.strip() and "+++ " in tail, "the last lines of the trace, with how the processes ended:\n" + tail[-800:]
|
||||
gdb = sorted(folder.glob("gdb-core*.txt"))
|
||||
assert gdb, "no core was found and run through gdb; the collectors said: %s\n%s" % ((folder / "said.txt").read_text(encoding="utf-8"), done.stdout[-1500:])
|
||||
text = gdb[0].read_text(encoding="utf-8")
|
||||
assert re.search(r"Thread \d+ \(", text), "gdb's `thread apply all bt` lists the threads:\n" + text[:1500]
|
||||
assert "Build ID" in (folder / "build-ids.txt").read_text(encoding="utf-8")
|
||||
@@ -865,6 +865,150 @@ def test_the_tee_writes_down_each_request_head_as_it_was_written_and_changes_no_
|
||||
assert events[1]["headers"] == [["Host", "h"], ["Content-Length", "3"], ["Accept", "*/*"]]
|
||||
|
||||
|
||||
def test_the_tee_says_which_connection_carried_each_request_and_when_so_that_a_run_that_differs_from_itself_can_be_explained():
|
||||
"""A/A run 45025164169 (Windows): a request of step 15 counted twice in one run and once in the other, and the transcript, which folds a request into a count, could not say which page sent it
|
||||
or when. The tee knows the connection each head came on (its own number, in the order they were accepted) and the moment, and the request summary still leaves both out."""
|
||||
rec = ab.Recorder()
|
||||
server = _http_server()
|
||||
tee = ab.RawTee(rec, server.server_address[1], "A")
|
||||
try:
|
||||
first = socket.create_connection(("127.0.0.1", tee.port), timeout=60)
|
||||
first.sendall(b"GET /one HTTP/1.1\r\nHost: h\r\nReferer: http://h/\r\n\r\n")
|
||||
_read_response(first, b"/one")
|
||||
second = socket.create_connection(("127.0.0.1", tee.port), timeout=60)
|
||||
second.sendall(b"GET /two HTTP/1.1\r\nHost: h\r\n\r\n")
|
||||
_read_response(second, b"/two")
|
||||
first.sendall(b"GET /three HTTP/1.1\r\nHost: h\r\n\r\n")
|
||||
_read_response(first, b"/three")
|
||||
first.close()
|
||||
second.close()
|
||||
finally:
|
||||
tee.close()
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
events = rec.of("launch", "http")
|
||||
assert [(e["target"], e["connection"]) for e in events] == [("/one", 0), ("/two", 1), ("/three", 0)]
|
||||
assert [e["t"] for e in events] == sorted(e["t"] for e in events) and all(isinstance(e["t"], float) for e in events)
|
||||
summary = ab.request_summary(events, ab.Normalizer())
|
||||
assert sorted(summary) == ["GET A/one", "GET A/three", "GET A/two"] and "connection" not in json.dumps(summary) and '"t"' not in json.dumps(summary)
|
||||
|
||||
|
||||
def _client_context():
|
||||
import ssl
|
||||
|
||||
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
|
||||
context.check_hostname, context.verify_mode = False, ssl.CERT_NONE
|
||||
context.set_alpn_protocols(["http/1.1"])
|
||||
return context
|
||||
|
||||
|
||||
def _http1_round(server, context, session=None, watch_end=False):
|
||||
"""One request on a new TLS connection to ``server`` (a session belongs to the context that made it): ``(answer, the session the client holds, whether the server ended the connection after the answer)``.
|
||||
The end is watched only when asked: a connection read to its unclean end (no close_notify) makes OpenSSL refuse to resume its session, which is a fact about this client and not the browser's."""
|
||||
raw = socket.create_connection((server.address, server.port), timeout=60)
|
||||
tls = context.wrap_socket(raw, server_hostname="wire.test", session=session)
|
||||
tls.settimeout(60)
|
||||
try:
|
||||
tls.sendall(b"GET /wire.css HTTP/1.1\r\nHost: wire.test\r\n\r\n")
|
||||
answer = b""
|
||||
while b"p{color" not in answer:
|
||||
chunk = tls.recv(4096)
|
||||
assert chunk, "closed before the answer: %r" % answer
|
||||
answer += chunk
|
||||
session, ended = tls.session, None
|
||||
if watch_end:
|
||||
tls.settimeout(5)
|
||||
try:
|
||||
ended = tls.recv(4096) == b""
|
||||
except socket.timeout:
|
||||
ended = False
|
||||
except OSError:
|
||||
ended = True
|
||||
return answer, session, ended
|
||||
finally:
|
||||
tls.close()
|
||||
|
||||
|
||||
def test_an_http1_server_that_ends_each_connection_after_its_answer_makes_every_next_request_a_resumed_connection_by_construction():
|
||||
"""A/A run 45025164169 (Linux): the HTTP/1.1 site had a resumed connection on one seed of one run and on none of the five of the other, because whether a second connection opened while the
|
||||
first was still busy, before it had read the session ticket, is the pool's race. A server that says ``Connection: close`` and ends the connection leaves the client no choice: its next request
|
||||
rides a new connection, opened after the answer (and the ticket that came with it) was read, so it offers the session. The default stays keep-alive, for every other user of the server."""
|
||||
with wc.WireServer(alpn=("http/1.1",), dns_names=("wire.test",), close_after_response=True) as server:
|
||||
context = _client_context()
|
||||
answer, held, _ = _http1_round(server, context)
|
||||
assert b"Connection: close" in answer
|
||||
assert held is not None and held.has_ticket, "the first answer carries the ticket the next connection offers"
|
||||
_http1_round(server, context, session=held)
|
||||
_answer, _held, ended = _http1_round(server, context, watch_end=True)
|
||||
assert ended is True, "the server ends the connection after its answer"
|
||||
snapshot = server.snapshot()
|
||||
first, second, third = snapshot["connections"]
|
||||
assert not ab._resumed(first["tls"]) and ab._resumed(second["tls"]), "the second connection of the walk offers the session of the first"
|
||||
assert [len(c["http1"]) for c in snapshot["connections"]] == [1, 1, 1]
|
||||
wire = {"connections": [{"alpn": c["alpn"], "tls": c["tls"], "http1": [{k: r[k] for k in ("request_line", "headers", "body_length")} for r in c["http1"]]}
|
||||
for c in snapshot["connections"]], "quic": []}
|
||||
folded = ab.fold_wire(ab.Normalizer().walk(wire))
|
||||
assert len(folded["resumed_connections"]) == 1 and len(folded["connections"]) == 1, "one fresh fingerprint and one resumed one, as the oracle folds them"
|
||||
with wc.WireServer(alpn=("http/1.1",), dns_names=("wire.test",)) as keep_alive:
|
||||
answer, _held, ended = _http1_round(keep_alive, _client_context(), watch_end=True)
|
||||
assert b"Connection: close" not in answer and not ended, "without the option the connection stays open"
|
||||
|
||||
|
||||
def test_the_lab_ends_the_connections_of_its_http1_site_and_only_those():
|
||||
with ab.Lab(wire=True, host="127.0.0.1") as lab:
|
||||
assert lab.h1.close_after_response is True
|
||||
assert lab.h2.close_after_response is False and lab.h3.close_after_response is False
|
||||
|
||||
|
||||
def test_the_evidence_of_a_seed_keeps_the_requests_of_the_journey_with_their_connection_and_referer_and_the_connections_of_the_https_site_with_their_moment_and_resumption():
|
||||
from fakeweb import journey_site
|
||||
|
||||
with ab.Lab(journey=True, wire=True, host="127.0.0.1") as lab:
|
||||
journey_site.STATE.set_step(15)
|
||||
port_a = int(lab.origin_a.rsplit(":", 1)[1])
|
||||
sock, code = _socks_connect(lab.gateway.port, "127.0.0.1", port_a)
|
||||
assert code == 0
|
||||
sock.sendall(b"GET /release?id=lpabc123 HTTP/1.1\r\nHost: journey-a.test:%d\r\nReferer: http://journey-a.test:%d/account\r\n\r\n" % (port_a, port_a))
|
||||
_read_response(sock, b"ok")
|
||||
sock.close()
|
||||
lab.rec.set_phase("https.h1.v1")
|
||||
context = _client_context()
|
||||
_answer, held, _ended = _http1_round(lab.h1, context)
|
||||
_http1_round(lab.h1, context, session=held)
|
||||
evidence = ab.wire_evidence(lab)
|
||||
(request,) = evidence["journey"]
|
||||
assert request["phase"] == "journey.15" and request["connection"] == 0 and isinstance(request["t"], float)
|
||||
assert request["request"] == "GET A/release?id=lp<TOK>" and request["referer"] == "http://journey-a.test:A/account"
|
||||
first, second = evidence["https"]["h1"]
|
||||
assert (first["resumed"], second["resumed"]) == (False, True) and first["phase"] == second["phase"] == "https.h1.v1"
|
||||
assert first["requests"][0]["request"] == "GET /wire.css HTTP/1.1" and second["t"] >= first["t"]
|
||||
assert evidence["https"]["h2"] == []
|
||||
json.dumps(evidence)
|
||||
|
||||
|
||||
def test_a_run_writes_what_each_seed_saw_request_by_request_outside_the_leaves_that_are_compared(tmp_path, monkeypatch):
|
||||
import _lab_egress
|
||||
import ci_crash_evidence as crash
|
||||
|
||||
def walk_seed(binary, seed, with_idle, patch):
|
||||
ab.EVIDENCE[str(seed)] = {"journey": [{"t": 1.5, "connection": 3, "phase": "journey.15", "request": "GET A/release?id=lp<TOK>", "referer": "http://journey-a.test:A/"}], "https": {}}
|
||||
return {"journey": {}}
|
||||
|
||||
monkeypatch.setattr(ab, "walk_seed", walk_seed)
|
||||
monkeypatch.setattr(_lab_egress, "install", lambda patch, work: None)
|
||||
monkeypatch.setenv(crash.CRASH_DIR_ENV, str(tmp_path / "t.crash"))
|
||||
try:
|
||||
assert ab.run("/e/firefox", "firefox-68", (11, 12), tmp_path / "t.json") == 0
|
||||
finally:
|
||||
crash.stop_probe()
|
||||
document = json.loads((tmp_path / "t.json").read_text(encoding="utf-8"))
|
||||
assert document["evidence"]["format"] == ab.EVIDENCE_FORMAT and sorted(document["evidence"]["seeds"]) == ["11", "12"]
|
||||
assert document["evidence"]["seeds"]["11"]["journey"][0]["connection"] == 3
|
||||
other = json.loads(json.dumps(document))
|
||||
other["evidence"]["seeds"]["11"]["journey"][0]["t"] = 99.0
|
||||
assert compare(document, other)["differences"] == [] and compare(document, other)["leaves"] == compare(document, document)["leaves"], "evidence is never compared"
|
||||
|
||||
|
||||
def _socks_connect(proxy_port: int, host: str, port: int):
|
||||
"""A SOCKS5 CONNECT by address, no authentication: ``(socket, reply code)``."""
|
||||
sock = socket.create_connection(("127.0.0.1", proxy_port), timeout=60)
|
||||
@@ -1539,3 +1683,100 @@ def test_a_candidate_that_differs_from_a_sound_control_is_red_and_the_a_a_alone_
|
||||
args[2] = str(tmp_path / "aa")
|
||||
assert ab.main(args) == 0 and [c[2] for c in calls] == ["firefox-68", "firefox-68-again"]
|
||||
assert ab.main(_ab_args(tmp_path)) == 2, "neither a candidate nor --a-a: nothing to run"
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------- how each launch's parent ended
|
||||
def exits_of(*codes, platform=None):
|
||||
"""The `exits` a run writes (scripts/ci_crash_evidence.py): one launch per code, named as the oracle names its launches."""
|
||||
names = [("main", 11), ("idle-c1", 11), ("idle-c2", 11), ("exit-pings", 11), ("main", 12)]
|
||||
return {"format": "launch-exits/1", "launches": [{"n": n + 1, "label": {"seed": names[n][1], "launch": names[n][0]}, "pid": 100 + n, "returncode": code}
|
||||
for n, code in enumerate(codes)]}
|
||||
|
||||
|
||||
def test_a_transcript_whose_launches_all_ended_with_0_is_green_with_or_without_the_record():
|
||||
a, b = transcript("a"), transcript("b")
|
||||
a["exits"], b["exits"] = exits_of(0, 0, 0, 0, 0), exits_of(0, 0, 0, 0, 0)
|
||||
assert compare(a, b)["verdict"] == "green" and compare(a, transcript("b"))["verdict"] == "green"
|
||||
assert "exits" not in ab.flatten(a["seeds"]) and not any(p.startswith("exits") for p in ab.flatten(a))
|
||||
|
||||
|
||||
def test_a_launch_that_died_is_red_and_names_the_side_the_seed_the_launch_and_the_code_on_either_side():
|
||||
a, b = transcript("firefox-68"), transcript("firefox-68-again")
|
||||
a["exits"], b["exits"] = exits_of(0, 0, 0, 0, 0), exits_of(0, 0, -11, 0, 0)
|
||||
b["platform"] = "linux"
|
||||
report = compare(a, b)
|
||||
assert report["verdict"] == "red" and report["differences"] == [], "the leaves are equal: the launch is what is red"
|
||||
[line] = report["problems"]
|
||||
for part in ("code -11 (SIGSEGV)", "run firefox-68-again", "side B", "seed 11", "launch idle-c2"):
|
||||
assert part in line, part
|
||||
swapped = compare(b, a)
|
||||
assert "side A" in swapped["problems"][0] and "run firefox-68-again" in swapped["problems"][0]
|
||||
windows = transcript("candidate")
|
||||
windows["platform"] = "win32"
|
||||
windows["exits"] = exits_of(3221225477)
|
||||
assert "0xC0000005 (access violation)" in compare(transcript("firefox-68"), windows)["problems"][0]
|
||||
|
||||
|
||||
def test_a_run_that_recorded_no_launch_is_red_because_its_probe_did_not_see_a_browser():
|
||||
a, b = transcript("a"), transcript("b")
|
||||
a["exits"], b["exits"] = exits_of(0), {"format": "launch-exits/1", "launches": []}
|
||||
report = compare(a, b)
|
||||
assert report["verdict"] == "red" and "recorded no launch (side B)" in report["problems"][0]
|
||||
|
||||
|
||||
def test_the_run_writes_how_every_launch_ended_into_the_transcript_and_prints_the_one_that_died(tmp_path, monkeypatch, capsys):
|
||||
import os
|
||||
|
||||
import ci_crash_evidence as crash
|
||||
import _lab_egress
|
||||
|
||||
def walk_seed(binary, seed, with_idle, patch):
|
||||
for code, launch in ((0, "main"), (-11, "idle-c1")) if with_idle else ((0, "main"),):
|
||||
crash.mark(seed=seed, launch=launch)
|
||||
from invisible_core.juggler.connection import Connection
|
||||
|
||||
class Process:
|
||||
pid = 4242
|
||||
|
||||
def poll(self):
|
||||
return code
|
||||
|
||||
def terminate(self):
|
||||
pass
|
||||
|
||||
to_r, to_w = os.pipe()
|
||||
from_r, from_w = os.pipe()
|
||||
conn = Connection(to_w, from_r, Process())
|
||||
conn.close()
|
||||
os.close(from_w)
|
||||
os.close(to_r)
|
||||
return {"journey": {}}
|
||||
|
||||
monkeypatch.setattr(ab, "walk_seed", walk_seed)
|
||||
monkeypatch.setattr(_lab_egress, "install", lambda patch, work: None)
|
||||
monkeypatch.setenv(crash.CRASH_DIR_ENV, str(tmp_path / "t.crash"))
|
||||
try:
|
||||
assert ab.run("/e/firefox", "firefox-68", (11, 12), tmp_path / "t.json") == 0
|
||||
finally:
|
||||
crash.stop_probe()
|
||||
document = json.loads((tmp_path / "t.json").read_text(encoding="utf-8"))
|
||||
assert [(x["label"]["seed"], x["label"]["launch"], x["returncode"]) for x in document["exits"]["launches"]] == [(11, "main", 0), (11, "idle-c1", -11), (12, "main", 0)]
|
||||
assert "EXIT the parent process exited with code" in capsys.readouterr().out
|
||||
assert (tmp_path / "t.crash" / "exits.json").is_file() and (tmp_path / "t.crash" / "02-11-idle-c1" / "crash.json").is_file()
|
||||
other = transcript("firefox-68-again")
|
||||
other["exits"] = exits_of(0, 0, 0)
|
||||
document["platform"] = "linux"
|
||||
assert compare(document, other)["verdict"] == "red"
|
||||
|
||||
|
||||
def test_the_engine_run_is_given_a_folder_for_what_a_launch_that_died_leaves_beside_its_transcript(tmp_path, monkeypatch):
|
||||
import ci_crash_evidence as crash
|
||||
|
||||
seen = []
|
||||
|
||||
class Done:
|
||||
returncode = 0
|
||||
|
||||
monkeypatch.setattr(ab.subprocess, "run", lambda cmd, env, timeout: seen.append(env.get(crash.CRASH_DIR_ENV)) or Done())
|
||||
assert ab.run_engine("ff", None, "firefox-68-again", (0,), tmp_path / "out" / "transcript-68-again.json") == 0
|
||||
assert seen == [str(tmp_path / "out" / "transcript-68-again.crash")]
|
||||
+599
-13
@@ -8,6 +8,7 @@ from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
@@ -15,6 +16,7 @@ import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts"))
|
||||
import ci_ab_oracle as ab # noqa: E402
|
||||
import ci_crash_evidence as crash # noqa: E402
|
||||
import ci_host_gate as gate # noqa: E402
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
@@ -205,6 +207,16 @@ def write_gate_dump(directory, engine_visits):
|
||||
for (dpr, seed), its in engine_visits.items():
|
||||
(directory / ("leg_dpr%s_seed%d.json" % (dpr, seed))).write_text(
|
||||
json.dumps({"leg": "leg", "dpr": dpr, "seed": seed, "result": {"format": gate.FORMAT, "items": its}}), encoding="utf-8")
|
||||
write_exits(0)
|
||||
|
||||
|
||||
def write_exits(code, launches=1):
|
||||
"""What the probe of the dump process writes where the oracle told it (`AB_CRASH_DIR`): how each launch's parent ended."""
|
||||
where = os.environ.get(crash.CRASH_DIR_ENV)
|
||||
if where:
|
||||
Path(where).mkdir(parents=True, exist_ok=True)
|
||||
(Path(where) / "exits.json").write_text(json.dumps({"format": crash.FORMAT, "launches": [
|
||||
{"n": n + 1, "label": {"seed": 0, "dpr": 1.0, "launch": "visit"}, "pid": 100 + n, "returncode": code} for n in range(launches)]}), encoding="utf-8")
|
||||
|
||||
|
||||
def test_the_visits_read_back_from_the_gate_s_dump_and_from_the_packed_file(tmp_path):
|
||||
@@ -236,7 +248,8 @@ def test_a_run_writes_the_three_files_and_is_green_when_the_engines_agree(tmp_pa
|
||||
rc = _fake_run(tmp_path, monkeypatch, candidate=visits())
|
||||
out = capsys.readouterr().out
|
||||
assert rc == 0 and "AB ORACLE OK" in out
|
||||
assert sorted(p.name for p in (tmp_path / "out").iterdir()) == ["diff.json", "dump-68.json", "dump-candidate.json"]
|
||||
assert sorted(p.name for p in (tmp_path / "out").iterdir() if p.is_file()) == ["diff.json", "dump-68.json", "dump-candidate.json"]
|
||||
assert sorted(p.name for p in (tmp_path / "out" / "crash").iterdir()) == ["candidate", "firefox-68"], "how each engine's browsers ended is in the artifact, a folder per run"
|
||||
diff = json.loads((tmp_path / "out" / "diff.json").read_text(encoding="utf-8"))
|
||||
assert diff["verdict"] == "green" and diff["engine"] == "firefox-68" and diff["differences"] == []
|
||||
|
||||
@@ -446,7 +459,8 @@ def test_the_a_a_alone_runs_the_published_engine_twice_and_is_green_when_it_repe
|
||||
out = capsys.readouterr().out
|
||||
assert rc == 0 and "AB ORACLE A/A OK" in out
|
||||
assert [c[0] for c in calls] == ["pub", "pub"] and all(c[1] is None and len(c[3]) == 2 for c in calls)
|
||||
assert sorted(p.name for p in (tmp_path / "out").iterdir()) == ["diff-a-a.json", "dump-68-again.json", "dump-68.json"]
|
||||
assert sorted(p.name for p in (tmp_path / "out").iterdir() if p.is_file()) == ["diff-a-a.json", "dump-68-again.json", "dump-68.json"]
|
||||
assert sorted(p.name for p in (tmp_path / "out" / "crash").iterdir()) == ["firefox-68", "firefox-68-again"]
|
||||
diff = json.loads((tmp_path / "out" / "diff-a-a.json").read_text(encoding="utf-8"))
|
||||
assert diff["verdict"] == "green" and diff["control"] is True and len(diff["visits"]) == 2
|
||||
|
||||
@@ -477,7 +491,8 @@ def test_with_a_candidate_the_a_a_comes_first_and_the_a_b_is_against_the_first_d
|
||||
out = capsys.readouterr().out
|
||||
assert rc == 0 and "AB ORACLE A/A OK" in out and "AB ORACLE OK" in out
|
||||
assert [(c[0], c[1]) for c in calls] == [("pub", None), ("pub", None), ("cand", str(tmp_path / "cand.seal.json"))]
|
||||
assert sorted(p.name for p in (tmp_path / "out").iterdir()) == ["diff-a-a.json", "diff.json", "dump-68-again.json", "dump-68.json", "dump-candidate.json"]
|
||||
assert sorted(p.name for p in (tmp_path / "out").iterdir() if p.is_file()) == ["diff-a-a.json", "diff.json", "dump-68-again.json", "dump-68.json", "dump-candidate.json"]
|
||||
assert sorted(p.name for p in (tmp_path / "out" / "crash").iterdir()) == ["candidate", "firefox-68", "firefox-68-again"]
|
||||
|
||||
|
||||
def test_with_a_candidate_that_differs_the_a_b_is_red_exit_1_not_a_broken_control(tmp_path, monkeypatch, capsys):
|
||||
@@ -559,7 +574,7 @@ def test_a_pull_request_that_touches_the_files_of_one_oracle_runs_every_seed_of_
|
||||
assert got == dict(DEFAULT, **{only: 5}), got
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", ["scripts/ci_ab_oracle.py", "scripts/persona_cover.py", "ci/persona-seeds.json", "scripts/ci_ab_pr_seeds.py"])
|
||||
@pytest.mark.parametrize("path", ["scripts/ci_ab_oracle.py", "scripts/ci_crash_evidence.py", "scripts/persona_cover.py", "ci/persona-seeds.json", "scripts/ci_ab_pr_seeds.py"])
|
||||
def test_what_the_oracles_share_runs_every_seed_of_all_of_them(path):
|
||||
assert pr.pr_seed_counts([path], every=5) == ALL
|
||||
|
||||
@@ -614,14 +629,14 @@ def _job(text, name):
|
||||
def test_the_e2e_workflow_runs_the_step_on_a_pull_request_in_the_jobs_that_run_the_oracles_and_the_e2e_tests_read_its_variables():
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
text = (root / ".github" / "workflows" / "e2e.yml").read_text(encoding="utf-8")
|
||||
legs = {name: _job(text, name) for name in ("e2e", "e2e-windows-control-a", "e2e-windows", "e2e-network", "e2e-network-windows", "e2e-host", "e2e-host-windows")}
|
||||
legs = {name: _job(text, name) for name in ("e2e", "e2e-windows-control-a", "e2e-windows", "e2e-network", "e2e-network-windows", "e2e-host", "e2e-host-windows", "e2e-page", "e2e-page-windows")}
|
||||
step = (' - name: How many seeds the A/A of each oracle visits (all of them when the pull request touches the oracle)\n'
|
||||
" if: github.event_name == 'pull_request'\n shell: bash\n env:\n BASE_SHA: ${{ github.event.pull_request.base.sha }}\n"
|
||||
' run: python scripts/ci_ab_pr_seeds.py "$BASE_SHA" >> "$GITHUB_ENV"\n')
|
||||
assert [name for name, body in legs.items() if step in body] == ["e2e", "e2e-windows", "e2e-network", "e2e-network-windows", "e2e-host", "e2e-host-windows"], "the jobs that run the oracles' tests, and only those"
|
||||
for name in ("e2e", "e2e-windows", "e2e-network", "e2e-network-windows", "e2e-host", "e2e-host-windows"):
|
||||
assert [name for name, body in legs.items() if step in body] == ["e2e", "e2e-windows", "e2e-network", "e2e-network-windows", "e2e-host", "e2e-host-windows", "e2e-page", "e2e-page-windows"], "the jobs that run the oracles' tests, and only those"
|
||||
for name in ("e2e", "e2e-windows", "e2e-network", "e2e-network-windows", "e2e-host", "e2e-host-windows", "e2e-page", "e2e-page-windows"):
|
||||
assert legs[name].index("actions/setup-python") < legs[name].index(step) < legs[name].index("Fetch the published firefox binary")
|
||||
assert text.count("run: python scripts/ci_ab_pr_seeds.py") == 6 and "uses:" not in step
|
||||
assert text.count("run: python scripts/ci_ab_pr_seeds.py") == 8 and "uses:" not in step
|
||||
for variable, source in (("AB_ORACLE_PR_SEEDS", "test_ab_oracle_e2e.py"), ("AB_NETWORK_PR_SEEDS", "test_ab_network_e2e.py"), ("AB_HOST_PR_SEEDS", "test_ab_host_e2e.py")):
|
||||
assert 'pr_seed_count("%s"' % variable in (root / "tests" / source).read_text(encoding="utf-8")
|
||||
assert variable in pr.ORACLES
|
||||
@@ -640,7 +655,8 @@ def test_the_network_oracle_has_a_job_of_its_own_on_each_system_and_the_shared_j
|
||||
shared_linux, shared_windows = _job(text, "e2e"), _job(text, "e2e-windows")
|
||||
assert "OWN_JOB_FILES: " + network in shared_linux and "$ROOT_FILES $SANDBOX_FILES $OWN_JOB_FILES" in shared_linux
|
||||
host_file = "tests/test_ab_host_e2e.py"
|
||||
assert "OWN_JOB_FILES: %s %s" % (network, host_file) in shared_linux
|
||||
page_file = "tests/test_ab_oracle_e2e.py"
|
||||
assert "OWN_JOB_FILES: %s %s %s" % (network, host_file, page_file) in shared_linux
|
||||
# The Windows parts take their files from the rows wrapper.e2e.suite.windows.N of ci/required-suites.json (one partition with the candidate's
|
||||
# gate); the oracles' files are in none of those rows (tests/test_the_e2e_suite_is_accounted_for.py names them as excluded: their own jobs).
|
||||
assert 'wrapper.e2e.suite.windows.${{ matrix.part }}' in shared_windows
|
||||
@@ -648,7 +664,7 @@ def test_the_network_oracle_has_a_job_of_its_own_on_each_system_and_the_shared_j
|
||||
|
||||
rows = json.loads((root / "ci" / "required-suites.json").read_text(encoding="utf-8"))
|
||||
suite_entries = [t for r in rows if r["id"].startswith("wrapper.e2e.suite.") for t in r["tests"]]
|
||||
assert not [t for t in suite_entries if t.split("::")[0] in (network, host_file)]
|
||||
assert not [t for t in suite_entries if t.split("::")[0] in (network, host_file, page_file, "tests/test_ab_host_crash_linux_e2e.py")]
|
||||
assert network not in _job(text, "e2e-windows-control-a")
|
||||
# the budget of the test itself fits the job: 5 seeds, two engine runs, with its own setup
|
||||
import test_ab_network_e2e as network_e2e
|
||||
@@ -661,13 +677,73 @@ def test_the_host_oracle_has_a_job_of_its_own_on_each_system_with_the_tools_it_t
|
||||
text = (root / ".github" / "workflows" / "e2e.yml").read_text(encoding="utf-8")
|
||||
linux, windows = _job(text, "e2e-host"), _job(text, "e2e-host-windows")
|
||||
assert "runs-on: ubuntu-24.04" in linux and "runs-on: windows-2022" in windows
|
||||
for body in (linux, windows):
|
||||
assert body.count("tests/test_ab_host_e2e.py") == 1 and "scripts/run_e2e.py" not in body and "timeout-minutes: 45" in body and "needs: core-on-index" in body
|
||||
for body, minutes in ((linux, 65), (windows, 45)):
|
||||
assert body.count("tests/test_ab_host_e2e.py") == 1 and "scripts/run_e2e.py" not in body and "timeout-minutes: %d" % minutes in body and "needs: core-on-index" in body
|
||||
assert " - name: Run the host oracle's A/A\n" in body and "skipped\": 0" in body
|
||||
assert "apt-get install -y strace" in linux and "xvfb-run -a" in linux, "Linux traces the tree with strace"
|
||||
import test_ab_host_e2e as host_e2e
|
||||
import test_ab_host_crash_linux_e2e as crash_e2e
|
||||
|
||||
assert host_e2e.TIMEOUT_S + 10 * 60 <= 45 * 60, "the test's own limit fits the job"
|
||||
assert host_e2e.TIMEOUT_S + crash_e2e.TIMEOUT_S + 10 * 60 <= 65 * 60, "the A/A and the recorder's own test, one after the other, fit the Linux job"
|
||||
assert host_e2e.TIMEOUT_S + 10 * 60 <= 45 * 60, "the test's own limit fits the Windows job"
|
||||
|
||||
|
||||
def test_the_linux_jobs_of_the_three_oracles_install_gdb_and_elfutils_and_point_the_kernel_s_core_pattern_at_a_folder_of_the_job():
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
text = (root / ".github" / "workflows" / "e2e.yml").read_text(encoding="utf-8")
|
||||
for name in ("e2e-network", "e2e-host", "e2e-page", "e2e-page-final"):
|
||||
body = _job(text, name)
|
||||
step = body[body.index(" - name: Cores of a browser that did not end with 0"):]
|
||||
step = step[:step.index(" - name: The security state")]
|
||||
assert "apt-get install -y gdb elfutils" in step and 'sysctl -w kernel.core_pattern="$RUNNER_TEMP/cores/core.%e.%p.%t"' in step, name
|
||||
assert 'INVPW_CORE_DIR=$RUNNER_TEMP/cores' in step, name
|
||||
assert body.index("System deps (xvfb") < body.index("Cores of a browser") < body.index("Fetch the published firefox binary"), "after the apt update, before any launch"
|
||||
assert "MOZ_CRASHREPORTER" not in body and "extra_prefs" not in step, "no environment variable of the browser, no pref, no crash reporter option"
|
||||
for name in ("e2e-network-windows", "e2e-host-windows", "e2e-page-windows", "e2e-page-final-windows"):
|
||||
assert "Cores of a browser" not in _job(text, name), "Windows reads the `.extra` and the minidump names: no core, no gdb"
|
||||
|
||||
|
||||
def test_the_recorders_own_test_runs_in_the_host_job_after_the_a_a_and_is_left_out_of_the_shared_job_and_has_its_own_linux_row():
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
text = (root / ".github" / "workflows" / "e2e.yml").read_text(encoding="utf-8")
|
||||
crash_file = "tests/test_ab_host_crash_linux_e2e.py"
|
||||
host_job = _job(text, "e2e-host")
|
||||
assert host_job.index("Run the host oracle's A/A") < host_job.index("The host oracle's recorder of a browser that dies") < host_job.index("The leg ran with the pinned GeoIP database")
|
||||
step = host_job[host_job.index(" - name: The host oracle's recorder"):host_job.index(" - name: The leg ran with the pinned GeoIP database")]
|
||||
assert step.count(crash_file) == 1 and "if: success() || failure()" in step and "xvfb-run -a" in step and '{"tests": 1, "failures": 0, "errors": 0, "skipped": 0}' in step
|
||||
assert "host-crash-e2e.xml" in host_job.split("Upload what the test saved")[1]
|
||||
shared = _job(text, "e2e")
|
||||
assert crash_file not in _job(text, "e2e-host-windows") and crash_file in shared.split("OWN_JOB_FILES: ")[1].splitlines()[0]
|
||||
rows = {r["id"]: r for r in json.loads((root / "ci" / "required-suites.json").read_text(encoding="utf-8"))}
|
||||
row = rows["wrapper.e2e.ab_host_crash"]
|
||||
assert row["os"] == ["linux"] and row["linux_only"].strip() and row["tests"] == [crash_file] and row["min_tests"] == 1 and row["exact"] is True and row["marker"] == "e2e"
|
||||
assert rows["wrapper.e2e.ab_host"]["min_tests"] == 1 and rows["wrapper.e2e.ab_host"]["tests"] == ["tests/test_ab_host_e2e.py"], "the A/A is still the one test of its row"
|
||||
|
||||
|
||||
def test_the_page_oracle_has_a_job_of_its_own_on_each_system_and_the_shared_jobs_leave_its_file_out():
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
text = (root / ".github" / "workflows" / "e2e.yml").read_text(encoding="utf-8")
|
||||
page = "tests/test_ab_oracle_e2e.py"
|
||||
code = lambda job: "\n".join(line for line in job.splitlines() if not line.lstrip().startswith("#")) # the comment that follows the last job is the next one's
|
||||
linux, windows = code(_job(text, "e2e-page")), code(_job(text, "e2e-page-windows"))
|
||||
assert "name: e2e (page oracle, linux)" in linux and "name: e2e (page oracle, windows)" in windows
|
||||
assert "runs-on: ubuntu-24.04" in linux and "runs-on: windows-2022" in windows
|
||||
for body in (linux, windows):
|
||||
assert body.count(page) == 1 and "scripts/run_e2e.py" not in body and "timeout-minutes: 45" in body and "needs: core-on-index" in body
|
||||
assert "AB_ORACLE_SEED_SET" not in body, "the A/A of a pull request, not a shard of the final seeds (those have their own jobs)"
|
||||
assert " - name: Run the page oracle's A/A\n" in body and "skipped\": 0" in body, "the job refuses a skipped test: one test, passed"
|
||||
assert "xvfb-run -a" in linux
|
||||
shared_linux, shared_windows = _job(text, "e2e"), _job(text, "e2e-windows")
|
||||
assert page in shared_linux.split("OWN_JOB_FILES: ")[1].splitlines()[0] and 'wrapper.e2e.suite.windows.${{ matrix.part }}' in shared_windows
|
||||
import json
|
||||
|
||||
rows = json.loads((root / "ci" / "required-suites.json").read_text(encoding="utf-8"))
|
||||
assert not [t for r in rows if r["id"].startswith("wrapper.e2e.suite.") for t in r["tests"] if t.split("::")[0] == page], "the page oracle's file is in no row of the shared suite"
|
||||
assert page not in _job(text, "e2e-windows-control-a")
|
||||
import test_ab_oracle_e2e as page_e2e
|
||||
|
||||
# the A/A of a pull request that touches the oracle: 5 seeds, two engine runs, the second launch of seed 0; the guard of the test plus its margin fits the job with the setup
|
||||
assert page_e2e.budget_s(5, 2, True) + 120 + 12 * 60 <= 45 * 60, "the test's own limit fits the job"
|
||||
|
||||
|
||||
# --- the second launch of seed 0 on a reused profile (H7) -----------------------------------------------------------------------------------------
|
||||
@@ -977,3 +1053,513 @@ def test_the_final_set_is_four_shards_of_five_that_reach_every_seed_once_and_see
|
||||
parts = [ab.select_visits("final", "%d/4" % i) for i in (1, 2, 3, 4)]
|
||||
assert [len(p) for p in parts] == [5, 5, 5, 5] and [seed for _, seed in parts[0]][0] == 0
|
||||
assert [i + 1 for i, p in enumerate(parts) if ab.relaunch_visits(p)] == [1]
|
||||
|
||||
|
||||
# --- a launch whose parent did not end with 0 is red in the page oracle (scripts/ci_crash_evidence.py) --------------------------------------------------
|
||||
|
||||
def a_launch_through_the_core(code, folder=None):
|
||||
"""A launch as the core makes it: a `Connection` over two pipes whose process ended with `code`, closed as the wrapper closes it."""
|
||||
from invisible_core.juggler.connection import Connection
|
||||
|
||||
class Process:
|
||||
pid = 4242
|
||||
|
||||
def poll(self):
|
||||
return code
|
||||
|
||||
def terminate(self):
|
||||
pass
|
||||
|
||||
to_r, to_w = os.pipe()
|
||||
from_r, from_w = os.pipe()
|
||||
conn = Connection(to_w, from_r, Process())
|
||||
conn.close()
|
||||
os.close(from_w)
|
||||
os.close(to_r)
|
||||
|
||||
|
||||
def test_a_dump_with_a_launch_that_died_is_red_and_names_the_side_the_seed_the_launch_and_the_code(tmp_path, monkeypatch, capsys):
|
||||
calls = []
|
||||
|
||||
def fake_dump(binary, seal, leg, out, visits_asked):
|
||||
write_gate_dump(out, {key: items(key[1]) for key in visits_asked})
|
||||
if len(calls) == 1: # the second dump of the published engine: its launch of seed 12 died
|
||||
where = Path(os.environ[crash.CRASH_DIR_ENV])
|
||||
(where / "exits.json").write_text(json.dumps({"format": crash.FORMAT, "launches": [
|
||||
{"n": 1, "label": {"seed": 11, "dpr": 1.0, "launch": "visit"}, "returncode": 0},
|
||||
{"n": 2, "label": {"seed": 12, "dpr": 1.5, "launch": "visit"}, "returncode": -11, "evidence": "crash/firefox-68-again/02-12-1.5-visit"}]}), encoding="utf-8")
|
||||
calls.append(binary)
|
||||
return 0
|
||||
|
||||
monkeypatch.setattr(ab, "run_dump", fake_dump)
|
||||
monkeypatch.setattr(ab, "MIN_LEAVES", SMALL)
|
||||
rc = ab.run_ab("linux-x86_64", tmp_path / "out", "firefox-68", ("pub", None), None, None, ab.select_visits(limit=2))
|
||||
out = capsys.readouterr().out
|
||||
assert rc == 2 and "BROKEN CONTROL" in out
|
||||
line = [x for x in out.splitlines() if x.startswith("FAIL the parent process exited with code")]
|
||||
assert len(line) == 1
|
||||
for part in ("code -11 (SIGSEGV)", "run firefox-68-again", "side B", "seed 12", "dpr 1.5", "launch visit", "(evidence: crash/firefox-68-again/02-12-1.5-visit)"):
|
||||
assert part in line[0], part
|
||||
diff = json.loads((tmp_path / "out" / "diff-a-a.json").read_text(encoding="utf-8"))
|
||||
assert diff["verdict"] == "red" and diff["differences"] == [], "the dumps are equal: it is the launch that is red"
|
||||
|
||||
|
||||
def test_a_dump_whose_probe_wrote_nothing_is_red_and_an_a_b_with_a_candidate_that_died_is_red_not_a_broken_control(tmp_path, monkeypatch, capsys):
|
||||
calls = []
|
||||
|
||||
def fake_dump(binary, seal, leg, out, visits_asked):
|
||||
write_gate_dump(out, {key: items(key[1]) for key in visits_asked})
|
||||
where = Path(os.environ[crash.CRASH_DIR_ENV])
|
||||
if len(calls) == 0:
|
||||
(where / "exits.json").unlink()
|
||||
calls.append(binary)
|
||||
return 0
|
||||
|
||||
monkeypatch.setattr(ab, "run_dump", fake_dump)
|
||||
monkeypatch.setattr(ab, "MIN_LEAVES", SMALL)
|
||||
rc = ab.run_ab("linux-x86_64", tmp_path / "out", "firefox-68", ("pub", None), "cand", tmp_path / "s.json", ab.select_visits(limit=2))
|
||||
out = capsys.readouterr().out
|
||||
assert rc == 2 and "left no record of how its browsers ended" in out and "the probe did not see them" in out
|
||||
|
||||
def fake_again(binary, seal, leg, out, visits_asked):
|
||||
write_gate_dump(out, {key: items(key[1]) for key in visits_asked})
|
||||
if binary == "cand":
|
||||
write_exits(-6)
|
||||
return 0
|
||||
|
||||
monkeypatch.setattr(ab, "run_dump", fake_again)
|
||||
rc = ab.run_ab("linux-x86_64", tmp_path / "out2", "firefox-68", ("pub", None), "cand", tmp_path / "s.json", ab.select_visits(limit=2))
|
||||
out = capsys.readouterr().out
|
||||
assert rc == 1 and "BROKEN CONTROL" not in out and "code -6 (SIGABRT): run candidate, side B" in out
|
||||
assert json.loads((tmp_path / "out2" / "diff.json").read_text(encoding="utf-8"))["verdict"] == "red"
|
||||
|
||||
|
||||
def test_the_published_engine_dump_of_a_run_that_died_is_red_in_the_old_run_too(tmp_path, monkeypatch, capsys):
|
||||
def fake_dump(binary, seal, leg, out, visits_asked):
|
||||
write_gate_dump(out, {key: items(key[1]) for key in visits_asked})
|
||||
write_exits(-11 if binary == "cand" else 0, launches=2)
|
||||
return 0
|
||||
|
||||
monkeypatch.setattr(ab, "run_dump", fake_dump)
|
||||
monkeypatch.setattr(ab, "MIN_LEAVES", SMALL)
|
||||
rc = ab.run("cand", tmp_path / "cand.seal.json", "linux-x86_64", tmp_path / "out", "firefox-68", published=("pub", tmp_path / "pub.seal.json"), visits=list(VISITS))
|
||||
out = capsys.readouterr().out
|
||||
assert rc == 1 and out.count("FAIL the parent process exited with code -11") == 2 and "run candidate, side B" in out
|
||||
|
||||
|
||||
def test_the_dump_process_names_each_launch_and_writes_how_it_ended_where_the_oracle_said(tmp_path, monkeypatch, capsys):
|
||||
"""The dump of the page, with the browser replaced by launches through the core's own `Connection` (no browser): the probe sees each one, the labels come from the dump
|
||||
(the visit, and the two launches of the pair on one profile), and `exits.json` is there whatever the dump says of the page."""
|
||||
codes = iter([0, 0, -11])
|
||||
|
||||
def read(options, port, dpr, timeout_ms):
|
||||
a_launch_through_the_core(next(codes))
|
||||
return {"format": gate.FORMAT, "items": {"surface": {"x": 1}}}
|
||||
|
||||
monkeypatch.setattr(gate, "read_page", read)
|
||||
monkeypatch.setattr(gate, "reference_zone", lambda reference: "UTC")
|
||||
monkeypatch.setenv(crash.CRASH_DIR_ENV, str(tmp_path / "crash"))
|
||||
try:
|
||||
assert gate.dump("/e/firefox", "linux-x86_64", tmp_path / "dump", tmp_path / "reference", visits=[(1.0, 0)], pin_dpr=False, relaunch_seeds=(0,)) == 0
|
||||
finally:
|
||||
crash.stop_probe()
|
||||
exits = crash.read_exits(tmp_path / "crash" / "exits.json")
|
||||
assert [(x["label"]["launch"], x["returncode"]) for x in exits["launches"]] == [("visit", 0), ("relaunch-first", 0), ("relaunch-second", -11)]
|
||||
assert [x["label"]["seed"] for x in exits["launches"]] == [0, 0, 0]
|
||||
assert "EXIT the parent process exited with code -11 (SIGSEGV): run this dump, side A, seed 0, dpr 1.0, launch relaunch-second" in capsys.readouterr().out
|
||||
assert (tmp_path / "crash" / "03-0-1.0-relaunch-second" / "crash.json").is_file() and not (tmp_path / "crash" / "01-0-1.0-visit").exists()
|
||||
|
||||
|
||||
def test_a_dump_that_was_not_given_a_folder_installs_no_probe_and_launches_as_the_host_gate_always_did(tmp_path, monkeypatch):
|
||||
from invisible_core.juggler.connection import Connection
|
||||
|
||||
before = (Connection.__init__, Connection.close)
|
||||
monkeypatch.delenv(crash.CRASH_DIR_ENV, raising=False)
|
||||
seen = []
|
||||
monkeypatch.setattr(gate, "read_page", lambda *a: seen.append((Connection.__init__, Connection.close)) or {"format": gate.FORMAT, "items": {}})
|
||||
monkeypatch.setattr(gate, "reference_zone", lambda reference: "UTC")
|
||||
assert gate.dump("ff", "leg", tmp_path / "dump", tmp_path / "reference", visits=[(1.0, 2)], pin_dpr=False) == 0
|
||||
assert seen == [before] and not (tmp_path / "dump" / "exits.json").exists()
|
||||
|
||||
|
||||
def test_the_dump_of_an_oracle_run_is_given_its_own_folder_for_the_probe_and_the_environment_is_put_back(tmp_path, monkeypatch):
|
||||
seen = []
|
||||
|
||||
def fake_dump(binary, seal, leg, out, visits_asked):
|
||||
seen.append(os.environ.get(crash.CRASH_DIR_ENV))
|
||||
write_gate_dump(out, {key: items(key[1]) for key in visits_asked})
|
||||
return 0
|
||||
|
||||
monkeypatch.setattr(ab, "run_dump", fake_dump)
|
||||
monkeypatch.delenv(crash.CRASH_DIR_ENV, raising=False)
|
||||
rc, problems = ab.dump_with_exits("firefox-68-again", "pub", None, "linux-x86_64", [(1.0, 0)], tmp_path / "t", tmp_path / "out")
|
||||
assert rc == 0 and problems == [] and seen == [str(tmp_path / "out" / "crash" / "firefox-68-again")]
|
||||
assert crash.CRASH_DIR_ENV not in os.environ, "the variable is the dump's, not the run's"
|
||||
monkeypatch.setattr(ab, "run_dump", lambda *a: (_ for _ in ()).throw(ab.subprocess.TimeoutExpired("x", 1)))
|
||||
rc, problems = ab.dump_with_exits("firefox-68", "pub", None, "linux-x86_64", [(1.0, 0)], tmp_path / "t", tmp_path / "out")
|
||||
assert rc == "timeout" and problems == [], "a dump that timed out is red already (the dump ended with timeout); its missing record is not said twice"
|
||||
|
||||
|
||||
# --- what every launch leaves, a tab that died, a core with a parent that ended with 0 (scripts/ci_crash_evidence.py, scripts/ci_host_gate.py) ---------------------------------
|
||||
|
||||
class ProcessOf:
|
||||
pid = 4242
|
||||
|
||||
def __init__(self, code):
|
||||
self.code = code
|
||||
|
||||
def poll(self):
|
||||
return self.code
|
||||
|
||||
def terminate(self):
|
||||
pass
|
||||
|
||||
|
||||
class Tools:
|
||||
"""`subprocess.run` that answers `gdb` with a backtrace and keeps what it was asked; every other tool of the evidence is not installed."""
|
||||
|
||||
def __init__(self):
|
||||
self.calls = []
|
||||
|
||||
def __call__(self, argv, **kw):
|
||||
self.calls.append(argv)
|
||||
|
||||
class Done:
|
||||
stdout, stderr = "#0 0x00007f in mozilla::dom::ContentChild::Crash ()\n", ""
|
||||
|
||||
return Done()
|
||||
|
||||
which = staticmethod(lambda name: "/usr/bin/gdb" if name == "gdb" else None)
|
||||
|
||||
|
||||
def a_launch(probe, code, label, text=b"", during=None):
|
||||
"""A launch as `launch` makes it: the reader of the browser's output first (`ProcessOutput`, over a pipe the browser writes on), then the `Connection`, closed as the wrapper closes it."""
|
||||
from invisible_core.juggler.connection import Connection, ProcessOutput
|
||||
|
||||
probe.set_label(**label)
|
||||
to_r, to_w = os.pipe()
|
||||
from_r, from_w = os.pipe()
|
||||
out_r, out_w = os.pipe()
|
||||
output = ProcessOutput(os.fdopen(out_r, "rb"))
|
||||
conn = Connection(to_w, from_r, ProcessOf(code))
|
||||
conn.output = output
|
||||
os.write(out_w, text)
|
||||
os.close(out_w)
|
||||
output.settle()
|
||||
if during:
|
||||
during()
|
||||
conn.close()
|
||||
os.close(from_w)
|
||||
os.close(to_r)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def probe_of(tmp_path):
|
||||
made = []
|
||||
|
||||
def make(**kw):
|
||||
tools = Tools()
|
||||
probe = crash.LaunchProbe("/e/firefox", tmp_path / "out" / "crash", windows=False, folders=[], core_folders=[tmp_path / "cores"], run=tools, which=tools.which, **kw)
|
||||
(tmp_path / "cores").mkdir(exist_ok=True)
|
||||
probe.tools = tools
|
||||
made.append(probe.install())
|
||||
return probe
|
||||
|
||||
yield make
|
||||
for probe in made:
|
||||
probe.uninstall()
|
||||
|
||||
|
||||
def test_what_the_browser_wrote_is_saved_for_every_launch_even_when_all_of_them_end_with_0(tmp_path, probe_of):
|
||||
probe = probe_of()
|
||||
lines = b"".join(b"line %d of the browser\n" % n for n in range(1, 301)) # the core's own reader keeps the last 200
|
||||
a_launch(probe, 0, {"seed": 11, "dpr": 1.0, "launch": "visit"}, lines)
|
||||
a_launch(probe, 0, {"seed": 12, "dpr": 1.5, "launch": "visit"}, b"[GFX1-]: a warning on stderr\n")
|
||||
exits = probe.write()
|
||||
folder = tmp_path / "out" / "crash"
|
||||
assert sorted(p.name for p in (folder / "stderr").iterdir()) == ["01-11-1.0-visit.txt", "02-12-1.5-visit.txt"]
|
||||
first = (folder / "stderr" / "01-11-1.0-visit.txt").read_text(encoding="utf-8")
|
||||
assert "line 1 of the browser\n" in first and "line 300 of the browser\n" in first
|
||||
assert "[GFX1-]: a warning on stderr" in (folder / "stderr" / "02-12-1.5-visit.txt").read_text(encoding="utf-8")
|
||||
document = crash.read_exits(exits)
|
||||
assert [x["returncode"] for x in document["launches"]] == [0, 0] and all(x["stderr"].startswith("crash/stderr/") for x in document["launches"])
|
||||
assert not [p for p in folder.iterdir() if p.is_dir() and p.name != "stderr"], "a green launch leaves no evidence folder: only its output"
|
||||
assert crash.exits_of_run(folder, "firefox-68", False) == [], "green stays green"
|
||||
|
||||
|
||||
def test_the_tee_gives_the_reader_the_same_lines_and_the_probe_a_copy():
|
||||
from invisible_core.juggler.connection import ProcessOutput
|
||||
|
||||
class Stream:
|
||||
def __init__(self):
|
||||
self.lines = iter([b"one\n", b"two\n", b""])
|
||||
|
||||
def readline(self):
|
||||
return next(self.lines)
|
||||
|
||||
record = crash.OutputRecord(1, {}, 0.0)
|
||||
output = ProcessOutput(crash.OutputTee(Stream(), record))
|
||||
output.settle()
|
||||
assert output.tail() == ["one", "two"] and record.text() == "one\ntwo\n"
|
||||
|
||||
|
||||
def test_a_launch_whose_output_the_probe_could_not_keep_is_red_not_silent(tmp_path):
|
||||
from invisible_core.juggler.connection import Connection
|
||||
|
||||
probe = crash.LaunchProbe("/e/firefox", tmp_path / "out" / "crash", windows=False, folders=[], core_folders=[tmp_path / "cores"]).install(Connection, output=None)
|
||||
try:
|
||||
a_launch(probe, 0, {"seed": 1, "launch": "visit"}, b"said something\n")
|
||||
finally:
|
||||
probe.uninstall()
|
||||
probe.write()
|
||||
lines = crash.exits_of_run(tmp_path / "out" / "crash", "candidate", False)
|
||||
assert len(lines) == 2 and "could not save what its browsers wrote" in lines[0] and "did not save what the browser of launch 1 wrote" in lines[1]
|
||||
assert not (tmp_path / "out" / "crash" / "stderr").exists()
|
||||
|
||||
|
||||
def test_a_launch_that_ended_while_starting_still_has_its_output_in_the_artifact(tmp_path, probe_of):
|
||||
from invisible_core.juggler.connection import ProcessOutput
|
||||
|
||||
probe = probe_of()
|
||||
probe.set_label(seed=3, dpr=1.0, launch="visit")
|
||||
out_r, out_w = os.pipe()
|
||||
output = ProcessOutput(os.fdopen(out_r, "rb")) # `launch` raised after this: no Connection was made over it
|
||||
os.write(out_w, b"Gtk-WARNING: cannot open display\n")
|
||||
os.close(out_w)
|
||||
output.settle()
|
||||
probe.write()
|
||||
document = crash.read_exits(tmp_path / "out" / "crash" / "exits.json")
|
||||
assert document["launches"] == [] and [x["label"]["seed"] for x in document["launches_without_connection"]] == [3]
|
||||
assert "cannot open display" in (tmp_path / "out" / "crash" / "stderr" / "01-3-1.0-visit-no-connection.txt").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def test_the_core_of_a_content_process_goes_through_gdb_though_the_parent_ended_with_0_and_is_red(tmp_path, probe_of):
|
||||
probe = probe_of()
|
||||
cores = tmp_path / "cores"
|
||||
a_launch(probe, 0, {"seed": 11, "dpr": 1.0, "launch": "visit"}, b"fine\n")
|
||||
a_launch(probe, 0, {"seed": 12, "dpr": 1.5, "launch": "visit"}, b"[Child 77] ###!!! ABORT: tab\n", during=lambda: (cores / "core.Web Content.77.1700000000").write_bytes(b"\x7fELF"))
|
||||
a_launch(probe, 0, {"seed": 13, "dpr": 1.0, "launch": "visit"}, b"fine\n")
|
||||
probe.write()
|
||||
launches = crash.read_exits(tmp_path / "out" / "crash" / "exits.json")["launches"]
|
||||
assert [x["cores"] for x in launches] == [[], ["core.Web Content.77.1700000000"], []], "a core is one launch's: the next launch does not get it again"
|
||||
gdb = [c for c in probe.tools.calls if c[0].endswith("gdb")]
|
||||
assert len(gdb) == 1 and all(command in gdb[0] for command in crash.GDB_COMMANDS)
|
||||
saved = tmp_path / "out" / launches[1]["evidence"] / "gdb-core.Web_Content.77.1700000000.txt"
|
||||
assert "ContentChild::Crash" in saved.read_text(encoding="utf-8")
|
||||
lines = crash.exits_of_run(tmp_path / "out" / "crash", "candidate", False)
|
||||
assert len(lines) == 1 and "a process of the browser crashed while the parent ended with 0" in lines[0] and "seed 12" in lines[0] and "core core.Web Content.77" in lines[0]
|
||||
assert "(evidence: crash/02-12-1.5-visit)" in lines[0] and "run candidate" in lines[0]
|
||||
|
||||
|
||||
def test_a_missing_core_is_said_where_it_was_looked_for_and_never_left_silent(tmp_path, probe_of, monkeypatch):
|
||||
monkeypatch.setenv(crash.CORE_DIR_ENV, str(tmp_path / "cores"))
|
||||
probe = probe_of()
|
||||
a_launch(probe, 0, {"seed": 11, "dpr": 1.0, "launch": "visit"})
|
||||
a_launch(probe, -11, {"seed": 12, "dpr": 1.0, "launch": "visit"})
|
||||
probe.write()
|
||||
green, died = crash.read_exits(tmp_path / "out" / "crash" / "exits.json")["launches"]
|
||||
assert "no core file written since the launch began, in %s" % (tmp_path / "cores") in green["core_said"]
|
||||
assert "no core file written since the launch began" in " | ".join(died["said"]), "and the launch that died says it too, in its evidence"
|
||||
monkeypatch.setenv(crash.CORE_DIR_ENV, "/job/cores")
|
||||
assert "the kernel does not write into INVPW_CORE_DIR, so a core would not have been seen there" in crash.core_said([Path("/job/cores")], "|/usr/share/apport/apport %p", False)
|
||||
assert "no core folder to look in" in crash.core_said([], "core", False) and "not seen" in crash.core_said([], "core", False)
|
||||
assert "Windows" in crash.core_said([], None, True)
|
||||
|
||||
|
||||
# the tab that died: a visit whose session was lost is a leaf of its own, and the comparison is red with that line first
|
||||
|
||||
def a_browser(monkeypatch, fail_on=None, error="Page.evaluate: cannot find session"):
|
||||
"""`invisible_playwright.InvisiblePlaywright` as a fake whose page answers the host gate's page and the states, and raises `error` at the call whose text contains `fail_on`."""
|
||||
import types
|
||||
|
||||
answers = {"window.__hostGate": {"format": gate.FORMAT, "items": {"surface": {"x": 1}}}, "__hostGateStates.prepare()": {"x": 5, "y": 6},
|
||||
"[innerWidth, innerHeight]": [100, 80], "__hostGateStates.measure()": {"innerWidth": 100}}
|
||||
|
||||
class Mouse:
|
||||
def move(self, *a):
|
||||
pass
|
||||
|
||||
def click(self, *a):
|
||||
pass
|
||||
|
||||
class Page:
|
||||
mouse = Mouse()
|
||||
|
||||
def goto(self, url, timeout=None):
|
||||
if fail_on == "goto":
|
||||
raise RuntimeError("Page.goto: Target page, context or browser has been closed")
|
||||
|
||||
def wait_for_function(self, expression, timeout=None):
|
||||
pass
|
||||
|
||||
def evaluate(self, expression):
|
||||
if fail_on and fail_on in expression:
|
||||
raise RuntimeError(error)
|
||||
return json.loads(json.dumps(answers.get(expression)))
|
||||
|
||||
class Browser:
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc):
|
||||
return False
|
||||
|
||||
def new_context(self):
|
||||
return self
|
||||
|
||||
def new_page(self):
|
||||
return Page()
|
||||
|
||||
module = types.ModuleType("invisible_playwright")
|
||||
module.InvisiblePlaywright = lambda **options: Browser()
|
||||
monkeypatch.setitem(sys.modules, "invisible_playwright", module)
|
||||
|
||||
|
||||
def test_a_session_lost_during_the_states_is_the_leaf_crash_tab_with_the_error_and_the_step(monkeypatch):
|
||||
a_browser(monkeypatch, fail_on="__hostGateStates.measure()")
|
||||
gate._LAUNCH[0] = "visit"
|
||||
result = gate.read_page({"seed": 12}, 1, 1.5, 1000)
|
||||
leaf = result["items"]["crash.tab.visit"]
|
||||
assert result["format"] == gate.FORMAT and "cannot find session" in leaf["error"] and leaf["step"] == "states: evaluate __hostGateStates.measure()"
|
||||
assert result["items"]["surface"] == {"x": 1}, "what the page had read before the tab died is kept"
|
||||
assert gate.tab_crash_lines("leg dpr 1.5 seed 12", result["items"]) == ["TAB CRASH leg dpr 1.5 seed 12 crash.tab.visit: %s, at the step states: evaluate __hostGateStates.measure()" % leaf["error"]]
|
||||
|
||||
|
||||
def test_a_tab_that_died_before_the_page_answered_is_the_leaf_alone_and_the_dump_goes_on(monkeypatch):
|
||||
a_browser(monkeypatch, fail_on="goto")
|
||||
gate._LAUNCH[0] = "relaunch-second"
|
||||
try:
|
||||
result = gate.read_page({"seed": 0}, 1, 1.0, 1000)
|
||||
finally:
|
||||
gate._LAUNCH[0] = "visit"
|
||||
assert list(result["items"]) == ["crash.tab.relaunch-second"] and result["items"]["crash.tab.relaunch-second"]["step"] == "goto"
|
||||
|
||||
|
||||
def test_an_error_that_is_not_a_lost_tab_is_still_raised_as_it_always_was(monkeypatch):
|
||||
a_browser(monkeypatch, fail_on="__hostGateStates.measure()", error="the page threw a TypeError")
|
||||
gate._LAUNCH[0] = "visit"
|
||||
result = gate.read_page({"seed": 12}, 1, 1.5, 1000)
|
||||
assert "crash.tab.visit" not in result["items"] and "error" in result["items"]["state.normal"], "the states say it, as before"
|
||||
a_browser(monkeypatch, fail_on="window.__hostGate", error="the page threw a TypeError")
|
||||
with pytest.raises(RuntimeError, match="TypeError"):
|
||||
gate.read_page({"seed": 12}, 1, 1.5, 1000)
|
||||
|
||||
|
||||
def test_the_second_launch_keeps_the_tab_that_died_in_the_first():
|
||||
seen = iter([{"format": gate.FORMAT, "items": {"crash.tab.relaunch-first": {"error": "cannot find session", "step": "goto"}}}, {"format": gate.FORMAT, "items": {"surface": {"x": 1}}}])
|
||||
got = gate.second_launch({"seed": 0}, 1, 1.0, 1000, read=lambda *a: next(seen))
|
||||
assert got["items"]["crash.tab.relaunch-first"]["step"] == "goto" and got["items"]["surface"] == {"x": 1}
|
||||
|
||||
|
||||
def test_the_ab_visit_records_the_tab_that_died_and_goes_no_further(monkeypatch):
|
||||
import types
|
||||
|
||||
log = []
|
||||
|
||||
class Page:
|
||||
def goto(self, url, timeout=None):
|
||||
pass
|
||||
|
||||
def go_back(self, timeout=None):
|
||||
raise RuntimeError("Page.goBack: cannot find session")
|
||||
|
||||
def wait_for_function(self, expression, timeout=None):
|
||||
pass
|
||||
|
||||
def evaluate(self, expression):
|
||||
return {"top": 1} if expression == "window.__abResult" else {"n": 2, "persisted": False, "data": 1}
|
||||
|
||||
class Context:
|
||||
def new_page(self):
|
||||
return Page()
|
||||
|
||||
def close(self):
|
||||
log.append("closed")
|
||||
raise RuntimeError("Context.close: Target closed") # closing the context of a dead tab says nothing more
|
||||
|
||||
class Browser:
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc):
|
||||
return False
|
||||
|
||||
def new_context(self, **options):
|
||||
return Context()
|
||||
|
||||
module = types.ModuleType("invisible_playwright")
|
||||
module.InvisiblePlaywright = lambda **options: Browser()
|
||||
monkeypatch.setitem(sys.modules, "invisible_playwright", module)
|
||||
got = gate.ab_visit("ff", 0, "UTC", 1.0, timeout_ms=10)
|
||||
assert list(got) == ["crash.tab.ab-visit"] and got["crash.tab.ab-visit"]["step"] == "go back (context launch)" and log == ["closed"]
|
||||
|
||||
|
||||
def a_visit_where_the_tab_died(error="Page.evaluate: cannot find session"):
|
||||
"""The visit as the dead side dumped it: what the page read before, the leaf of the crash, and the states the drive did not reach, each `{"error": ...}`."""
|
||||
its = items(12)
|
||||
its.update(crash.tab_crash_item("visit", "states: evaluate __hostGateStates.measure()", RuntimeError(error)))
|
||||
for name in gate.STATES:
|
||||
its[gate.STATE + name] = {"error": "RuntimeError: " + error}
|
||||
return its
|
||||
|
||||
|
||||
def test_a_visit_whose_tab_died_is_red_with_the_tab_crash_first_and_no_cascade_of_missing_leaves():
|
||||
a, b = visits(), visits()
|
||||
for side in (a, b):
|
||||
for key in side:
|
||||
for name in gate.STATES:
|
||||
side[key][gate.STATE + name] = {"innerWidth": 1920, "innerHeight": 1000, "screen": {"width": 1920}}
|
||||
b[(1.5, 12)] = a_visit_where_the_tab_died()
|
||||
report = run(a, b)
|
||||
assert report["verdict"] == "red"
|
||||
assert report["problems"][0].startswith("TAB CRASH side B seed 12 dpr 1.5 launch visit at step states: evaluate __hostGateStates.measure()")
|
||||
assert "cannot find session" in report["problems"][0] and "are not compared" in report["problems"][0]
|
||||
assert report["differences"] == [] and len(report["problems"]) == 1, "no leaf of the dead visit is listed: the cascade is one line"
|
||||
assert "<missing>" not in json.dumps(report) and report["tab_crashes"][0]["launch"] == "visit"
|
||||
|
||||
|
||||
def test_the_leaf_alone_makes_the_comparison_red_though_every_other_leaf_is_equal():
|
||||
a, b = visits(), visits()
|
||||
b[(1.0, 11)].update(crash.tab_crash_item("visit", "goto", RuntimeError("Target page, context or browser has been closed")))
|
||||
report = run(a, b)
|
||||
assert report["verdict"] == "red" and report["differences"] == [] and len(report["problems"]) == 1
|
||||
assert report["problems"][0] == "TAB CRASH side B seed 11 dpr 1.0 launch visit at step goto: RuntimeError: Target page, context or browser has been closed"
|
||||
assert run(visits(), visits())["verdict"] == "green", "and without the leaf the same dumps are green"
|
||||
|
||||
|
||||
def test_a_tab_that_died_on_the_published_side_is_named_on_side_a_and_a_second_launch_that_died_is_named_by_its_launch():
|
||||
a, b = {(1.0, 0): items(0)}, {(1.0, 0): items(0)}
|
||||
a[(1.0, 0)].update(crash.tab_crash_item("visit", "goto", RuntimeError("cannot find session")))
|
||||
b[(1.0, 0)].update({gate.RELAUNCH + k: v for k, v in crash.tab_crash_item("relaunch-second", "goto", RuntimeError("cannot find session")).items()})
|
||||
problems = ab.compare_visits(a, b, [], SMALL, expected=((1.0, 0),))["problems"]
|
||||
assert problems[0].startswith("TAB CRASH side A seed 0 dpr 1.0 launch visit") and problems[1].startswith("TAB CRASH side B seed 0 dpr 1.0 launch relaunch-second")
|
||||
|
||||
|
||||
def test_the_tab_crash_comes_before_the_exit_of_the_dump_it_left_and_before_the_leaves():
|
||||
b = visits()
|
||||
b[(1.5, 12)] = a_visit_where_the_tab_died()
|
||||
b[(1.0, 13)]["surface"]["navigator"]["language"] = "it-IT"
|
||||
report = ab.judge(visits(), b, [], extra_problems=["the dump with candidate ended with 1"], expected=VISITS)
|
||||
assert report["verdict"] == "red"
|
||||
assert report["problems"][0].startswith("TAB CRASH") and report["problems"][1] == "the dump with candidate ended with 1"
|
||||
assert report["problems"][-1].startswith("seed 13 dpr 1.0 surface.navigator.language"), "the differences stay the last lines"
|
||||
|
||||
|
||||
def test_a_dump_prints_the_tab_crash_and_writes_the_visit_with_its_leaf(tmp_path, monkeypatch, capsys):
|
||||
monkeypatch.delenv(crash.CRASH_DIR_ENV, raising=False)
|
||||
monkeypatch.setattr(gate, "read_page", lambda *a: {"format": gate.FORMAT, "items": a_visit_where_the_tab_died()})
|
||||
monkeypatch.setattr(gate, "reference_zone", lambda reference: "UTC")
|
||||
assert gate.dump("ff", "linux-x86_64", tmp_path / "dump", tmp_path / "reference", visits=[(1.5, 12)], pin_dpr=False) == 0
|
||||
assert "TAB CRASH linux-x86_64 dpr 1.5 seed 12 crash.tab.visit: RuntimeError: Page.evaluate: cannot find session" in capsys.readouterr().out
|
||||
written = json.loads((tmp_path / "dump" / "linux-x86_64_dpr1.5_seed12.json").read_text(encoding="utf-8"))
|
||||
assert written["result"]["items"]["crash.tab.visit"]["step"].startswith("states:")
|
||||
|
||||
|
||||
def test_every_page_oracle_job_uploads_the_folder_where_the_oracle_keeps_what_each_launch_left_whatever_the_result():
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
text = (root / ".github" / "workflows" / "e2e.yml").read_text(encoding="utf-8")
|
||||
for name in ("e2e-page", "e2e-page-windows", "e2e-page-final", "e2e-page-final-windows"):
|
||||
body = _job(text, name)
|
||||
step = body[body.index(" - name: Upload what the test saved"):]
|
||||
assert "if: always()" in step and "${{ runner.temp }}/invpw-evidence\n" in step, "%s: the evidence folder (ab-oracle/crash/<run>/stderr, exits.json, gdb files) is uploaded green or red" % name
|
||||
assert "RUNNER_TEMP" in (root / "tests" / "test_ab_oracle_e2e.py").read_text(encoding="utf-8") and '"invpw-evidence" / "ab-oracle"' in (root / "tests" / "test_ab_oracle_e2e.py").read_text(encoding="utf-8")
|
||||
@@ -37,6 +37,7 @@ pytestmark = pytest.mark.e2e
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
SCRIPT = ROOT / "scripts" / "ci_ab_oracle.py"
|
||||
sys.path.insert(0, str(ROOT / "scripts"))
|
||||
import ci_crash_evidence as crash # noqa: E402
|
||||
import ci_host_gate as gate # noqa: E402
|
||||
import ci_poison_host as poison # noqa: E402
|
||||
from ci_ab_pr_seeds import pr_seed_count # noqa: E402
|
||||
@@ -116,6 +117,18 @@ def _check_ab_visit_and_poison(out: Path, candidate: bool) -> None:
|
||||
assert not read, "the engine read the poisoned host:\n" + "\n".join(read)
|
||||
|
||||
|
||||
def _check_what_every_launch_left(out: Path, candidate: bool) -> None:
|
||||
"""The artifact of a green run holds what each browser wrote: a file per launch of each engine run (`crash/<run>/stderr/`), whatever the launch's end was. A run that
|
||||
saved none would leave the next crash to be inferred."""
|
||||
runs = sorted(p.parent.name for p in (out / "crash").glob("*/exits.json"))
|
||||
assert len(runs) == (3 if candidate else 2), "a record of how the browsers ended for each engine run: %s" % runs
|
||||
for run in runs:
|
||||
launches = crash.read_exits(out / "crash" / run / "exits.json")["launches"]
|
||||
assert launches, "the run %s recorded no launch" % run
|
||||
for launch in launches:
|
||||
assert launch.get("stderr") and (out / "crash" / launch["stderr"]).is_file(), "the run %s did not save what the browser of launch %s wrote" % (run, launch.get("n"))
|
||||
|
||||
|
||||
def _out(tmp_path: Path) -> Path:
|
||||
explicit = os.environ.get("AB_ORACLE_OUT")
|
||||
if explicit:
|
||||
@@ -156,6 +169,7 @@ def test_the_published_engine_repeats_itself_and_the_candidate_gives_the_same_by
|
||||
assert control["verdict"] == "green" and control["differences"] == [] and control["problems"] == [] and len(control["compared"]) == len(control["visits"]) >= 1
|
||||
assert len(control["visits"]) == len(visits), "every seed of the shard is visited: %s" % control["visits"]
|
||||
assert sorted(control["relaunch"]) == sorted(ab.visit_name(*key) for key in ab.relaunch_visits(visits)), "seed 0 is launched twice on one profile, whichever shard has it"
|
||||
_check_what_every_launch_left(out, candidate)
|
||||
_check_ab_visit_and_poison(out, candidate)
|
||||
names = sorted(p.name for p in out.glob("*.json") if not p.name.startswith("poison-"))
|
||||
if candidate:
|
||||
|
||||
@@ -461,3 +461,70 @@ def test_a_known_defect_of_linux_covers_every_linux_leg_of_the_gate():
|
||||
for e in scoped:
|
||||
if any(leg.startswith("linux-") for leg in e["legs"]):
|
||||
assert sorted(leg for leg in e["legs"] if leg.startswith("linux-")) == linux, e
|
||||
|
||||
|
||||
# The junit of the compare step: one testcase per invariant, by the name the hook tests spell.
|
||||
|
||||
def junit_of(tmp_path, items, retail=None, legs=None, make_dumps=True):
|
||||
import xml.etree.ElementTree as ET
|
||||
if make_dumps:
|
||||
dumps, ref = write(tmp_path, items, retail or {}, legs)
|
||||
else:
|
||||
dumps, ref = tmp_path / "dumps", tmp_path / "ref"
|
||||
dumps.mkdir(parents=True)
|
||||
ref.mkdir(parents=True)
|
||||
out = tmp_path / "gate-junit" / "host-gate.xml"
|
||||
from unittest import mock
|
||||
with mock.patch.object(gate, "load_exceptions", lambda: {}): # the repository's own list is not the subject here
|
||||
rc = gate.main(["compare", str(dumps), "--reference", str(ref), "--junit", str(out)])
|
||||
cases = {}
|
||||
for tc in ET.parse(out).getroot().iter("testcase"):
|
||||
assert tc.get("classname") == "scripts.ci_host_gate" # the judge reads it as scripts/ci_host_gate.py
|
||||
kids = [k.tag for k in tc]
|
||||
cases[tc.get("name")] = "failed" if "failure" in kids else "skipped" if "skipped" in kids else "passed"
|
||||
return rc, cases
|
||||
|
||||
|
||||
def test_the_junit_has_one_testcase_per_invariant_with_the_name_the_hooks_spell(tmp_path):
|
||||
rc, cases = junit_of(tmp_path, lambda leg, seed: {})
|
||||
assert rc == 0
|
||||
assert {"invariant:" + inv.name for inv in gate.INVARIANTS} <= set(cases)
|
||||
assert "invariant:fullscreen_is_the_screen" in cases
|
||||
assert set(cases.values()) == {"passed"}
|
||||
assert gate.JUNIT_CLASSNAME.replace(".", "/") + ".py" == "scripts/ci_host_gate.py"
|
||||
|
||||
|
||||
def test_the_junit_fails_the_invariant_that_broke_and_only_it_and_its_check(tmp_path):
|
||||
items = lambda leg, seed: retail_states(fullscreen=XVFB_FULLSCREEN) if leg.startswith("linux") else {}
|
||||
rc, cases = junit_of(tmp_path, items)
|
||||
assert rc == 1
|
||||
failed = {n for n, s in cases.items() if s == "failed"}
|
||||
assert {"invariant:fullscreen_is_the_screen", "invariant:fullscreen_declared"} <= failed
|
||||
assert cases["invariant:measured"] == "passed" and cases["invariant:back_to_normal"] == "passed"
|
||||
|
||||
|
||||
def test_the_junit_fails_a_host_difference_and_a_retail_difference(tmp_path):
|
||||
rc, cases = junit_of(tmp_path, lambda leg, seed: {"surface.x": leg}, {"surface.x": "win-x86_64"})
|
||||
assert rc == 1 and cases["check:host_independence"] == "failed"
|
||||
rc, cases = junit_of(tmp_path / "r", lambda leg, seed: {"surface.y": 1}, {"surface.y": 2})
|
||||
assert rc == 1 and cases["check:retail_equality"] == "failed" and cases["check:host_independence"] == "passed"
|
||||
|
||||
|
||||
def test_the_junit_skips_what_it_could_not_look_at_never_passes_it(tmp_path):
|
||||
rc, cases = junit_of(tmp_path, None, make_dumps=False)
|
||||
assert rc == 1
|
||||
assert cases["check:dumps_complete"] == "failed"
|
||||
assert all(s == "skipped" for n, s in cases.items() if n != "check:dumps_complete")
|
||||
assert "invariant:fullscreen_is_the_screen" in cases
|
||||
|
||||
|
||||
def test_the_junit_is_xunit2_with_the_counts_of_its_cases(tmp_path):
|
||||
import xml.etree.ElementTree as ET
|
||||
items = lambda leg, seed: retail_states(fullscreen=BUG_FULLSCREEN)
|
||||
junit_of(tmp_path, items)
|
||||
root = ET.parse(tmp_path / "gate-junit" / "host-gate.xml").getroot()
|
||||
suite = root.find("testsuite")
|
||||
cases = list(suite.iter("testcase"))
|
||||
assert root.tag == "testsuites" and int(suite.get("tests")) == len(cases)
|
||||
assert int(suite.get("failures")) == len([c for c in cases if c.find("failure") is not None]) == 3
|
||||
assert all(c.find("failure").text for c in cases if c.find("failure") is not None)
|
||||
+122
-10
@@ -158,6 +158,7 @@ def test_stock_firefox_that_read_the_poison_is_a_sound_control():
|
||||
|
||||
@pytest.mark.parametrize("change, requirement", [
|
||||
({"offsets": [-420, -420]}, "timezone"),
|
||||
({"dark": False}, "dark"),
|
||||
({"canary": {"with": [100, 100], "without": [100, 100], "present": False}}, "canary"),
|
||||
({"audio": {"sampleRate": 48000, "maxChannelCount": 2}}, "audio"),
|
||||
({"generic": [30.5, 216.0, 216.0]}, "generic"),
|
||||
@@ -299,7 +300,7 @@ def test_windows_verify_names_each_value_that_is_not_in_force(tmp_path):
|
||||
font = tmp_path / poison.FONT_FILE
|
||||
font.write_bytes(poison.canary_font())
|
||||
right = Fake({"tzutil /g": poison.WINDOWS_ZONE, "(Get-Culture).Name": "ja-JP", "Get-WinUserLanguageList": "ja-JP",
|
||||
"AppsUseLightTheme": "0", "SystemUsesLightTheme": "0", "Get-ItemProperty -Path 'HKCU:\\Software\\Microsoft\\Windows NT": str(font)})
|
||||
"AppsUseLightTheme": "0", "SystemUsesLightTheme": "0", "Get-ItemProperty -Path 'HKLM:\\SOFTWARE\\Microsoft\\Windows NT": str(font)})
|
||||
assert poison.verify_windows(right, {"font": str(font)}) == []
|
||||
wrong = Fake()
|
||||
problems = poison.verify_windows(wrong, {"font": str(font)})
|
||||
@@ -560,7 +561,7 @@ def test_the_e2e_writes_the_dependence_before_it_asserts_anything_on_a_poisoned_
|
||||
|
||||
def windows_answers(font, **override):
|
||||
answers = {"tzutil /g": poison.WINDOWS_ZONE, "(Get-Culture).Name": "ja-JP", "Get-WinUserLanguageList": "ja",
|
||||
"AppsUseLightTheme": "0", "SystemUsesLightTheme": "0", "Get-ItemProperty -Path 'HKCU:\\Software\\Microsoft\\Windows NT": str(font)}
|
||||
"AppsUseLightTheme": "0", "SystemUsesLightTheme": "0", "Get-ItemProperty -Path 'HKLM:\\SOFTWARE\\Microsoft\\Windows NT": str(font)}
|
||||
answers.update(override)
|
||||
return Fake(answers)
|
||||
|
||||
@@ -632,16 +633,33 @@ def test_the_realm_hashes_a_png_without_its_per_launch_chunk_and_the_site_withou
|
||||
|
||||
|
||||
# -
|
||||
# In trial: measured and told, not required (run 45026082150: stock read no dark scheme on either system and, on Windows, did not see the per-user canary).
|
||||
# In trial: measured and told, not required. Nothing is in trial now (the two causes of run 45026082150 are taken away); the mechanism stays, with the old
|
||||
# values set by the test.
|
||||
|
||||
def test_the_scheme_and_the_windows_canary_are_in_trial_everything_else_stays_required():
|
||||
assert poison.IN_TRIAL == {"dark": ("linux", "windows"), "canary": ("windows",)}
|
||||
assert set(poison.REQUIRED) >= {"timezone", "language", "canary", "audio", "generic"}
|
||||
TRIAL = {"dark": ("linux", "windows"), "canary": ("windows",)}
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def trial(monkeypatch):
|
||||
monkeypatch.setattr(poison, "IN_TRIAL", dict(TRIAL))
|
||||
|
||||
|
||||
def test_nothing_is_in_trial_now_and_every_requirement_is_required_on_both_systems():
|
||||
assert poison.IN_TRIAL == {}
|
||||
assert set(poison.REQUIRED) == {"timezone", "dark", "canary", "audio", "generic", "language"}
|
||||
light = dict(STOCK, dark=False)
|
||||
unseen = dict(STOCK, canary={"with": [72, 122.6], "without": [72, 122.6], "present": False})
|
||||
for system in ("linux", "windows"):
|
||||
assert [n for n, _ in poison.control_failures(light, system)] == ["dark"] and poison.control_trials(light, system) == []
|
||||
assert [n for n, _ in poison.control_failures(unseen, system)] == ["canary"]
|
||||
|
||||
|
||||
def test_the_scheme_and_the_windows_canary_can_be_put_in_trial_and_everything_else_stays_required(trial):
|
||||
assert poison.in_trial("dark", "linux") and poison.in_trial("dark", "windows") and poison.in_trial("canary", "windows")
|
||||
assert not poison.in_trial("canary", "linux") and not poison.in_trial("timezone", "windows") and not poison.in_trial("language", "linux")
|
||||
|
||||
|
||||
def test_a_scheme_stock_did_not_read_is_not_a_broken_control_but_is_told():
|
||||
def test_a_scheme_stock_did_not_read_is_not_a_broken_control_but_is_told(trial):
|
||||
light = dict(STOCK, dark=False)
|
||||
for system in ("linux", "windows"):
|
||||
assert poison.control_failures(light, system) == []
|
||||
@@ -649,20 +667,23 @@ def test_a_scheme_stock_did_not_read_is_not_a_broken_control_but_is_told():
|
||||
assert poison.control_trials(STOCK, "linux") == [] and poison.control_trials(None, "linux") == []
|
||||
|
||||
|
||||
def test_the_windows_canary_is_in_trial_and_the_linux_one_is_required():
|
||||
def test_the_windows_canary_is_in_trial_and_the_linux_one_is_required(trial):
|
||||
unseen = dict(STOCK, canary={"with": [72, 122.6], "without": [72, 122.6], "present": False})
|
||||
assert poison.control_failures(unseen, "windows") == [] and [n for n, _ in poison.control_trials(unseen, "windows")] == ["canary"]
|
||||
assert [n for n, _ in poison.control_failures(unseen, "linux")] == ["canary"] and poison.control_trials(unseen, "linux") == []
|
||||
|
||||
|
||||
def test_what_stays_required_stays_red_on_windows_too():
|
||||
def test_what_stays_required_stays_red_on_windows_too(trial):
|
||||
bad = dict(STOCK, dark=False, offsets=[-420, -420], intl_locale="en-US", date_full="x", canary={"present": False})
|
||||
assert sorted(n for n, _ in poison.control_failures(bad, "windows")) == ["language", "timezone"]
|
||||
|
||||
|
||||
def test_the_control_writes_the_trials_to_its_file_and_to_the_summary(tmp_path, monkeypatch, capsys):
|
||||
def test_the_control_writes_the_trials_to_its_file_and_to_the_summary(tmp_path, monkeypatch, capsys, trial):
|
||||
import types
|
||||
|
||||
launched = {}
|
||||
make_playwright_firefox(tmp_path)
|
||||
|
||||
class Page:
|
||||
def goto(self, url):
|
||||
pass
|
||||
@@ -682,7 +703,10 @@ def test_the_control_writes_the_trials_to_its_file_and_to_the_summary(tmp_path,
|
||||
pass
|
||||
|
||||
class Firefox:
|
||||
executable_path = firefox_path(tmp_path)
|
||||
|
||||
def launch(self, **options):
|
||||
launched.update(options)
|
||||
return Browser()
|
||||
|
||||
class Manager:
|
||||
@@ -709,3 +733,91 @@ def test_the_control_writes_the_trials_to_its_file_and_to_the_summary(tmp_path,
|
||||
text = summary.read_text(encoding="utf-8")
|
||||
assert "Verdict: **green**" in text and "not read, in trial (dark)" in text
|
||||
assert "IN TRIAL, not required (dark)" in capsys.readouterr().out
|
||||
assert launched["executable_path"] != firefox_path(tmp_path) and Path(launched["executable_path"]).name == "firefox"
|
||||
assert report["reference"]["taken_out_of_playwright_cfg"] == ['pref("ui.systemUsesDarkTheme", 0);']
|
||||
|
||||
|
||||
# -
|
||||
# The reference is a Playwright Firefox that reads the machine's scheme: its cfg forces ui.systemUsesDarkTheme to 0 (widget/nsXPLookAndFeel.cpp reads a pref before the system).
|
||||
|
||||
CFG = """// A neighbour
|
||||
// Use light theme by default.
|
||||
pref("ui.systemUsesDarkTheme", 0);
|
||||
|
||||
// Do not use system colors - they are affected by themes.
|
||||
pref("ui.use_standins_for_native_colors", true);
|
||||
pref("toolkit.shutdown.fastShutdownStage", 3);
|
||||
"""
|
||||
|
||||
|
||||
def firefox_path(tmp_path):
|
||||
return str(tmp_path / "pw" / "firefox" / "firefox")
|
||||
|
||||
|
||||
def make_playwright_firefox(tmp_path, cfg=CFG):
|
||||
folder = tmp_path / "pw" / "firefox"
|
||||
(folder / "defaults").mkdir(parents=True, exist_ok=True)
|
||||
(folder / "firefox").write_bytes(b"binary")
|
||||
(folder / "playwright.cfg").write_bytes(cfg.encode("utf-8"))
|
||||
(folder / "defaults" / "kept.js").write_bytes(b"kept")
|
||||
return folder
|
||||
|
||||
|
||||
def test_the_reference_is_a_copy_without_the_pref_that_forces_the_scheme_and_with_everything_else(tmp_path):
|
||||
folder = make_playwright_firefox(tmp_path)
|
||||
work = tmp_path / "work"
|
||||
work.mkdir()
|
||||
exe, removed = poison.reference_firefox(str(folder / "firefox"), work)
|
||||
copy = Path(exe).parent
|
||||
assert copy != folder and Path(exe).name == "firefox" and Path(exe).read_bytes() == b"binary" and (copy / "defaults" / "kept.js").read_bytes() == b"kept"
|
||||
cfg = (copy / "playwright.cfg").read_text(encoding="utf-8")
|
||||
assert removed == ['pref("ui.systemUsesDarkTheme", 0);'] and "systemUsesDarkTheme" not in cfg
|
||||
assert 'pref("ui.use_standins_for_native_colors", true);' in cfg and 'pref("toolkit.shutdown.fastShutdownStage", 3);' in cfg
|
||||
assert "systemUsesDarkTheme" in (folder / "playwright.cfg").read_text(encoding="utf-8"), "Playwright's own install is not touched"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("line", ['lockPref("ui.systemUsesDarkTheme", 0);', ' defaultPref("ui.systemUsesDarkTheme", 1);'])
|
||||
def test_the_pref_is_taken_out_whatever_way_the_cfg_sets_it(tmp_path, line):
|
||||
folder = make_playwright_firefox(tmp_path, CFG + line + "\n")
|
||||
work = tmp_path / "work"
|
||||
work.mkdir()
|
||||
exe, removed = poison.reference_firefox(str(folder / "firefox"), work)
|
||||
assert len(removed) == 2 and "systemUsesDarkTheme" not in (Path(exe).parent / "playwright.cfg").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def test_a_reference_that_would_not_differ_from_playwright_s_firefox_is_refused(tmp_path):
|
||||
folder = make_playwright_firefox(tmp_path, 'pref("toolkit.shutdown.fastShutdownStage", 3);\n')
|
||||
work = tmp_path / "work"
|
||||
work.mkdir()
|
||||
with pytest.raises(RuntimeError, match="does not force ui.systemUsesDarkTheme"):
|
||||
poison.reference_firefox(str(folder / "firefox"), work)
|
||||
(folder / "playwright.cfg").unlink()
|
||||
with pytest.raises(RuntimeError, match="no playwright.cfg"):
|
||||
poison.reference_firefox(str(folder / "firefox"), tmp_path / "other")
|
||||
|
||||
|
||||
def test_the_control_launches_the_reference_and_not_playwright_s_install():
|
||||
source = (ROOT / "scripts" / "ci_poison_host.py").read_text(encoding="utf-8")
|
||||
assert "p.firefox.launch(executable_path=executable," in source and "reference_firefox(p.firefox.executable_path" in source
|
||||
# the control is headed, and so are the engines of the oracle (a hidden desktop, the core's _headless.py), never `-headless`
|
||||
assert "headless=headless" in source and "def control(out: Path, headless: bool = False)" in source
|
||||
|
||||
|
||||
# -
|
||||
# The canary of Windows is machine-wide: the Fonts folder of the system and HKLM.
|
||||
|
||||
def test_the_windows_canary_goes_to_the_fonts_folder_of_the_system_and_to_hklm():
|
||||
assert poison.FONTS_KEY.startswith("HKLM:")
|
||||
assert poison.font_path_windows({"SystemRoot": "X:" + chr(92) + "Sys"}) == Path("X:" + chr(92) + "Sys") / "Fonts" / poison.FONT_FILE
|
||||
assert poison.font_path_windows({"WINDIR": "X:" + chr(92) + "Win"}) == Path("X:" + chr(92) + "Win") / "Fonts" / poison.FONT_FILE
|
||||
|
||||
|
||||
def test_windows_apply_registers_the_canary_under_hklm_and_undo_removes_that_value(tmp_path, no_session):
|
||||
fake = Fake()
|
||||
state = poison.apply_windows(fake, font_dir=tmp_path)
|
||||
assert any("HKLM:" in line and poison.FONT_VALUE in line and "New-ItemProperty" in line for line in fake.text())
|
||||
assert not any("HKCU:" in line and poison.FONT_VALUE in line for line in fake.text())
|
||||
fake.calls.clear()
|
||||
poison.undo_windows(state, fake)
|
||||
assert any("Remove-ItemProperty" in line and "HKLM:" in line and poison.FONT_VALUE in line for line in fake.text())
|
||||
assert not (tmp_path / poison.FONT_FILE).exists()
|
||||
@@ -23,11 +23,14 @@ RUNS_PYTEST = {
|
||||
"e2e.yml#network-windows": " - name: Run the network oracle's A/A\n",
|
||||
"e2e.yml#host": " - name: Run the host oracle's A/A\n",
|
||||
"e2e.yml#host-windows": " - name: Run the host oracle's A/A\n",
|
||||
"e2e.yml#page": " - name: Run the page oracle's A/A\n",
|
||||
"e2e.yml#page-windows": " - name: Run the page oracle's A/A\n",
|
||||
}
|
||||
|
||||
|
||||
JOBS = {"e2e.yml": "e2e", "e2e.yml#windows": "e2e-windows", "e2e.yml#control-a": "e2e-windows-control-a", "e2e.yml#network": "e2e-network",
|
||||
"e2e.yml#network-windows": "e2e-network-windows", "e2e.yml#host": "e2e-host", "e2e.yml#host-windows": "e2e-host-windows"}
|
||||
"e2e.yml#network-windows": "e2e-network-windows", "e2e.yml#host": "e2e-host", "e2e.yml#host-windows": "e2e-host-windows",
|
||||
"e2e.yml#page": "e2e-page", "e2e.yml#page-windows": "e2e-page-windows"}
|
||||
|
||||
|
||||
def _scope(name):
|
||||
|
||||
@@ -25,12 +25,15 @@ RUNS_PYTEST = {
|
||||
"e2e.yml#network-windows": " - name: Run the network oracle's A/A\n",
|
||||
"e2e.yml#host": " - name: Run the host oracle's A/A\n",
|
||||
"e2e.yml#host-windows": " - name: Run the host oracle's A/A\n",
|
||||
"e2e.yml#page": " - name: Run the page oracle's A/A\n",
|
||||
"e2e.yml#page-windows": " - name: Run the page oracle's A/A\n",
|
||||
"fakeweb.yml": " - name: Profile P2, stock first and ours second",
|
||||
}
|
||||
|
||||
|
||||
JOBS = {"e2e.yml": "e2e", "e2e.yml#windows": "e2e-windows", "e2e.yml#control-a": "e2e-windows-control-a", "e2e.yml#network": "e2e-network",
|
||||
"e2e.yml#network-windows": "e2e-network-windows", "e2e.yml#host": "e2e-host", "e2e.yml#host-windows": "e2e-host-windows"}
|
||||
"e2e.yml#network-windows": "e2e-network-windows", "e2e.yml#host": "e2e-host", "e2e.yml#host-windows": "e2e-host-windows",
|
||||
"e2e.yml#page": "e2e-page", "e2e.yml#page-windows": "e2e-page-windows"}
|
||||
|
||||
|
||||
def _scope(name):
|
||||
@@ -53,7 +56,7 @@ def test_the_security_state_is_set_once_before_the_step_that_runs_the_tests(name
|
||||
assert text.index(SET) < text.index(pytest_step), "%s sets the security state after the tests started" % name
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", ["e2e.yml", "e2e.yml#windows", "e2e.yml#control-a", "e2e.yml#network", "e2e.yml#network-windows", "e2e.yml#host", "e2e.yml#host-windows", "fakeweb.yml"])
|
||||
@pytest.mark.parametrize("name", ["e2e.yml", "e2e.yml#windows", "e2e.yml#control-a", "e2e.yml#network", "e2e.yml#network-windows", "e2e.yml#host", "e2e.yml#host-windows", "e2e.yml#page", "e2e.yml#page-windows", "fakeweb.yml"])
|
||||
def test_the_security_state_is_set_before_the_engine_is_fetched(name):
|
||||
text = _scope(name)
|
||||
assert FETCH in text, "the fetch step of %s moved: update this test with it" % name
|
||||
|
||||
@@ -53,6 +53,8 @@ EXCLUDED = {
|
||||
(_BOTH, "wrapper.e2e.ab_network: the network oracle has its own row and job (e2e-network-* in e2e.yml)"),
|
||||
"tests/test_ab_host_e2e.py":
|
||||
(_BOTH, "wrapper.e2e.ab_host: the host oracle has its own row and job (e2e-host-* in e2e.yml)"),
|
||||
"tests/test_ab_host_crash_linux_e2e.py":
|
||||
(_BOTH, "wrapper.e2e.ab_host_crash: the host oracle's recorder on a launch that dies on purpose has its own row (Linux only) and runs in the host oracle's job"),
|
||||
"tests/test_a_proxy_that_cannot_carry_udp_leaks_nothing_direct_e2e.py":
|
||||
(_BOTH, "wrapper.e2e.udp.exit: the lab's exit is an address held on lo as root (Linux only), run in the root step"),
|
||||
"tests/test_the_whole_udp_chain_by_name_e2e.py::test_a_turn_srflx_by_name_arrives_through_the_relay_before_the_tick":
|
||||
@@ -89,7 +91,7 @@ EXCLUDED = {
|
||||
(("windows",), "skips on Windows: the Linux text path"),
|
||||
}
|
||||
#: Changed by hand, together with the list above: an exclusion is a test the candidate does not run, and it may not be added in silence.
|
||||
EXCLUDED_COUNT = 20
|
||||
EXCLUDED_COUNT = 21
|
||||
|
||||
|
||||
@functools.lru_cache(maxsize=None)
|
||||
|
||||
Reference in new issue
Block a user