ci: the page oracle visits seed 0 twice on one profile (second launch under relaunch.), the final seeds have an A/A in four shards on their own jobs, and the e2e guard is sized from the shard

The dump launches seed 0 a second time on a profile folder a first launch used, in the wrapper's persistent context, and keeps that launch's items under the relaunch. prefix of the visit: the retail comparison never reads them, the A/A and the A/B hold them to equality, count them apart from the visit's floor, and are red when a side lacks them. The e2e reads AB_ORACLE_SEED_SET and AB_ORACLE_SHARD and sizes its hang guard from the seeds of its shard, the engine runs and the extra launches. e2e.yml has a touched step and two jobs (Linux and Windows) of four shards each for the A/A of the final set, run only when a pull request changes a file of the page oracle.
This commit is contained in:
feder-cr committed 2026-11-22 14:35:59 +01:00
1 parent 3fa1232011
commit f21523aba7
5 files changed
+654 -38

No files matched your search

+158
View File
@@ -738,3 +738,161 @@ jobs:
${{ runner.temp }}/host-e2e.xml
if-no-files-found: ignore
retention-days: 14
# ``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
# gate leg rests on: the published engine against itself on every seed, zero differences, before any A/B of the final set is accepted. Each shard is one test
# (tests/test_ab_oracle_e2e.py with AB_ORACLE_SEED_SET=final and AB_ORACLE_SHARD=i/4: its hang guard is sized from the shard's seeds) and the job refuses anything but that one test, passed.
# Seed 0 is in shard 1, and its second launch on a reused profile is part of that shard's A/A.
e2e-page-final-touched:
name: e2e (page oracle, is it touched)
needs: core-on-index
if: github.event_name == 'pull_request' && needs.core-on-index.outputs.available == 'true' && inputs.only != 'windows-control-a'
runs-on: ubuntu-24.04
timeout-minutes: 5
outputs:
touched: ${{ steps.touched.outputs.touched }}
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
with: { fetch-depth: 1 }
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
with: { python-version: '3.11' }
- name: Does the pull request change a file of the page oracle
id: touched
shell: bash
env:
BASE_SHA: ${{ github.event.pull_request.base.sha }}
run: python scripts/ci_ab_oracle.py touched "$BASE_SHA" | tee -a "$GITHUB_OUTPUT"
e2e-page-final:
name: e2e (page oracle, final seeds ${{ matrix.shard }}/4, linux)
needs: [core-on-index, e2e-page-final-touched]
if: needs.core-on-index.outputs.available == 'true' && needs.e2e-page-final-touched.outputs.touched == 'true'
runs-on: ubuntu-24.04
timeout-minutes: 40
strategy:
fail-fast: false
matrix:
shard: [1, 2, 3, 4]
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
with: { fetch-depth: 1 }
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
with: { python-version: '3.11' }
- name: Install wrapper + test deps (+ Playwright ONLY as a system tool)
run: |
python -m pip install --upgrade pip
python -m pip install ".[dev]"
python -m pip install "playwright==$(cat scripts/playwright_pin.txt)"
- name: 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
- 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 A/A on the final seeds of this shard
env:
PYTHONUNBUFFERED: "1"
AB_ORACLE_SEED_SET: final
AB_ORACLE_SHARD: ${{ matrix.shard }}/4
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-final-e2e.xml"
python - "$RUNNER_TEMP/page-final-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-final-${{ matrix.shard }}-${{ github.run_id }}-${{ github.run_attempt }}
path: |
${{ runner.temp }}/invpw-evidence
${{ runner.temp }}/page-final-e2e.xml
if-no-files-found: ignore
retention-days: 14
e2e-page-final-windows:
name: e2e (page oracle, final seeds ${{ matrix.shard }}/4, windows)
needs: [core-on-index, e2e-page-final-touched]
if: needs.core-on-index.outputs.available == 'true' && needs.e2e-page-final-touched.outputs.touched == 'true'
runs-on: windows-2022
timeout-minutes: 40
strategy:
fail-fast: false
matrix:
shard: [1, 2, 3, 4]
defaults:
run:
shell: bash
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
with: { fetch-depth: 1 }
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
with: { python-version: '3.11' }
- name: Install wrapper + test deps (+ Playwright ONLY as a system tool)
run: |
python -m pip install --upgrade pip
python -m pip install ".[dev]"
python -m pip install "playwright==$(cat scripts/playwright_pin.txt)"
- name: 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 A/A on the final seeds of this shard
env:
PYTHONUNBUFFERED: "1"
AB_ORACLE_SEED_SET: final
AB_ORACLE_SHARD: ${{ matrix.shard }}/4
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-final-e2e.xml"
python - "$RUNNER_TEMP/page-final-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-final-windows-${{ matrix.shard }}-${{ github.run_id }}-${{ github.run_attempt }}
path: |
${{ runner.temp }}/invpw-evidence
${{ runner.temp }}/page-final-e2e.xml
if-no-files-found: ignore
retention-days: 14
+71 -12
View File
@@ -39,6 +39,13 @@ exit 2 and the A/B is not run. Without a candidate (a pull request: the engine u
the published engine. Exit codes: 0 green, 1 red (a finding), 2 broken control or a run that could not run.
--limit N visits only the first N seeds of the set (the A/A of a pull request, which has a time budget per test).
THE SECOND LAUNCH. The visit of seed 0 (RELAUNCH_SEED) is also launched twice on ONE profile folder (the wrapper's persistent context, the profile a user
keeps between runs): the dump keeps the items of the second launch in that visit under the prefix `relaunch.`, next to the visit's own items (a fresh
profile), so the retail comparison of the host gate is never touched. They are compared apart: the visit must have them on both sides, and as many as the
floor (they are not counted in the visit's own leaves, so a page that dumped less cannot hide behind them). The A/A and the A/B hold them to equality like the rest.
python ci_ab_oracle.py touched BASE_SHA (prints touched=true|false: does a pull request change a file of this oracle; e2e.yml's final-set job reads it)
Writes, in --out: dump-<N>.json and dump-<N>-again.json (the published engine's items, twice), diff-a-a.json (the A/A),
and with a candidate dump-candidate.json and diff.json (the verdict, the compared leaves per visit, every difference).
"""
@@ -72,6 +79,9 @@ MIN_LEAVES = {1.0: 16439, 1.5: 16439}
#: or the one that reaches every value of every dimension the core declares.
SEED_SETS = ("candidate", "final")
SEED_SET = "candidate"
#: The seed whose visit is also launched twice on one profile folder, and the prefix its second launch's leaves have (scripts/ci_host_gate.py holds it).
RELAUNCH_SEED = 0
RELAUNCH = gate.RELAUNCH
#: A value in diff.json longer than this is replaced by its length and its sha256 (the full value is in the dumps).
CLIP = 400
#: How many differences one run prints; diff.json has all of them.
@@ -128,24 +138,43 @@ def select_visits(seed_set: str = SEED_SET, shard: str | None = None, path: Path
return mine
def relaunch_visits(visits) -> tuple:
"""The visits (dpr, seed) that are launched twice on one profile folder: the ones of RELAUNCH_SEED."""
return tuple(key for key in visits if key[1] == RELAUNCH_SEED)
def _bare(leaf: str) -> str:
"""The leaf without the prefix of the second launch: what exceptions.json names."""
return leaf[len(RELAUNCH):] if leaf.startswith(RELAUNCH) else leaf
def comparable(items: dict) -> dict:
"""The leaves of one visit that are held to equality: everything but diag."""
return {k: v for k, v in gate.leaves(items).items() if not gate.is_diag(k)}
"""The leaves of one visit that are held to equality: everything but diag (a second launch's leaves keep their prefix)."""
return {k: v for k, v in gate.leaves(items).items() if not gate.is_diag(_bare(k))}
def split_launches(leaves: dict) -> tuple:
"""(the leaves of the visit on a fresh profile, the leaves of the second launch)."""
first = {k: v for k, v in leaves.items() if not k.startswith(RELAUNCH)}
return first, {k: v for k, v in leaves.items() if k.startswith(RELAUNCH)}
def compare_visits(a: dict, b: dict, noise: list, min_leaves: dict | None = None,
expected: tuple | None = None) -> dict:
expected: tuple | None = None, relaunch: tuple | None = None) -> dict:
"""a and b map (dpr, seed) to the items of that visit (as the dump returns them).
Returns the report: {"verdict": "green"|"red", "problems": [str], "differences":
[{"seed", "dpr", "leaf", "a", "b", "what"}], "compared": {visit: leaves}, "excused": n}.
`noise` is the list of entries of exceptions.json's "noise". `min_leaves` maps a dpr to the
fewest leaves a visit of that dpr may compare; `expected` is the visits both sides must have
(default: every seed at every DPR of the host gate)."""
(default: every seed at every DPR of the host gate). `relaunch` is the visits that were launched twice on one profile (default: those of RELAUNCH_SEED among the expected ones): each side must have the
second launch's leaves (prefix `relaunch.`) in them, as many as the floor, counted apart (report["relaunch"]), and a side must not have them in a visit that
was not asked to."""
min_leaves = MIN_LEAVES if min_leaves is None else min_leaves
if expected is None:
expected = tuple((dpr, seed) for dpr in gate.DPRS for seed in gate.SEEDS)
problems, differences, compared, excused = [], [], {}, 0
relaunch = relaunch_visits(expected) if relaunch is None else relaunch
problems, differences, compared, excused, relaunched = [], [], {}, 0, {}
for side, visits in (("A", a), ("B", b)):
gone = [visit_name(*k) for k in expected if k not in visits]
if gone:
@@ -158,25 +187,35 @@ 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 = 0
count, again = 0, 0
floor = min_leaves.get(dpr, min(min_leaves.values(), default=0))
for leaf in sorted(set(la) | set(lb)):
if gate.matching(noise, leaf):
if gate.matching(noise, _bare(leaf)):
excused += 1
continue
count += 1
second = leaf.startswith(RELAUNCH)
count, again = count + (not second), again + second
va, vb = la.get(leaf, MISSING), lb.get(leaf, MISSING)
if va != vb:
differences.append({"seed": seed, "dpr": dpr, "leaf": leaf, "a": _clip(va), "b": _clip(vb),
"what": gate.describe(va, vb)})
compared[visit_name(dpr, seed)] = count
floor = min_leaves.get(dpr, min(min_leaves.values(), default=0))
if count < floor:
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:
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:
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
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,
"compared": compared, "excused": excused}
"compared": compared, "relaunch": relaunched, "excused": excused}
# -
@@ -202,8 +241,9 @@ def unpack(document: dict) -> dict:
return {(v["dpr"], v["seed"]): v["items"] for v in document["visits"]}
def judge(published: dict, candidate: dict, noise: list, extra_problems=(), expected: tuple | None = None) -> dict:
report = compare_visits(published, candidate, noise, expected=expected)
def judge(published: dict, candidate: dict, noise: list, extra_problems=(), expected: tuple | None = None,
relaunch: tuple | None = None) -> dict:
report = compare_visits(published, candidate, noise, expected=expected, relaunch=relaunch)
if extra_problems:
report["problems"] = list(extra_problems) + report["problems"]
report["verdict"] = "red"
@@ -219,6 +259,8 @@ def print_report(report: dict, published: str, other: str = CANDIDATE, title: st
print("compared %d visits, leaves per visit: %s; %d leaves excused as noise"
% (len(report["compared"]), ", ".join("%s %d" % kv for kv in sorted(report["compared"].items())) or "none",
report["excused"]))
if report.get("relaunch"):
print("second launch on a reused profile, leaves per visit: %s" % ", ".join("%s %d" % kv for kv in sorted(report["relaunch"].items())))
for d in report["differences"][:PRINT_LIMIT]:
print("DIFF seed %d dpr %s leaf %s: %s %s | %s %s" % (d["seed"], d["dpr"], d["leaf"], published,
json.dumps(d["a"], sort_keys=True)[:160],
@@ -297,6 +339,8 @@ def run_dump(binary: str, seal: Path | None, leg: str, out: Path, visits: list |
env.pop(name, None)
cmd = [sys.executable, str(Path(gate.__file__)), "dump", binary, "--leg", leg, "--out", str(out)]
if visits is not None:
if relaunch_visits(visits):
cmd += ["--relaunch-seed", str(RELAUNCH_SEED)]
cmd += ["--no-pin"] + [a for dpr, seed in visits for a in ("--visit", "%d:%s" % (seed, dpr))]
with tempfile.TemporaryDirectory(prefix="ab-oracle-cache-") as cache:
return subprocess.run(cmd, env=own_cache_env(env, cache), timeout=DUMP_TIMEOUT_S).returncode
@@ -425,6 +469,13 @@ def recompare(directory: Path, engine_tag: str, visits: list | None = None, a_a:
return 0 if report["verdict"] == "green" else 1
def touched(changed) -> bool:
"""Does a change to `changed` (paths of a pull request) touch a file of this oracle (scripts/ci_ab_pr_seeds.py holds the list)?"""
import ci_ab_pr_seeds as pr
return bool(pr.touches(changed, pr.ORACLES["AB_ORACLE_PR_SEEDS"][2]))
def main(argv=None) -> int:
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
sub = ap.add_subparsers(dest="cmd", required=True)
@@ -441,6 +492,8 @@ def main(argv=None) -> int:
r.add_argument("--limit", type=int, help="visit only the first N seeds of the set (the A/A of a pull request)")
r.add_argument("--published-binary", type=Path, help="use this binary for the published engine instead of fetching it")
r.add_argument("--published-seal", type=Path, help="with --published-binary: the seal of that engine")
t = sub.add_parser("touched", help="touched=true|false: does the pull request (BASE_SHA..HEAD) change a file of this oracle")
t.add_argument("base")
c = sub.add_parser("compare")
c.add_argument("directory", type=Path)
c.add_argument("--engine-tag", default=ENGINE_TAG)
@@ -449,6 +502,12 @@ def main(argv=None) -> int:
c.add_argument("--limit", type=int)
c.add_argument("--a-a", action="store_true", help="compare the two dumps of the published engine (the control)")
args = ap.parse_args(argv)
if args.cmd == "touched":
import ci_ab_pr_seeds as pr
sys.stdout.reconfigure(newline="\n") # the line goes to $GITHUB_OUTPUT: a carriage return would be part of the value
print("touched=%s" % ("true" if touched(pr.changed_files(args.base)) else "false"))
return 0
if args.cmd == "compare":
return recompare(args.directory, args.engine_tag, select_visits(args.seed_set, args.shard, limit=args.limit), args.a_a)
if args.published_seal and not args.published_binary:
+69 -19
View File
@@ -64,7 +64,9 @@ import base64
import fnmatch
import gzip
import json
import shutil
import sys
import tempfile
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
@@ -88,6 +90,16 @@ ANCHOR = "win-x86_64"
#: Keys under this prefix are information, never compared (see the module docstring).
DIAG = "diag."
#: The items of a visit's SECOND launch on a profile that a first launch already used (`--relaunch-seed`, the A/B oracle's) live under this prefix, next to the
#: items of the visit on a fresh profile: the retail comparison (`compare`) never reads a dump made without that option, and the oracle compares the two
#: sets of leaves apart. The diag. items of the second launch are not kept: what the page records about the host is information, never compared.
RELAUNCH = "relaunch."
def relaunch_items(items: dict) -> dict:
"""The items of a second launch as they are stored in the visit: every key under RELAUNCH, the diag. ones left out."""
return {RELAUNCH + k: v for k, v in items.items() if not is_diag(k)}
def is_diag(key: str) -> bool:
return key.startswith(DIAG)
@@ -375,49 +387,84 @@ def reference_zone(reference: Path) -> str:
return reference_items(reference, 1.0)["surface.intl"]["DateTimeFormat"]["timeZone"]
def visit_options(firefox: str, seed: int, dpr: float | None, zone: str) -> dict:
def visit_options(firefox: str, seed: int, dpr: float | None, zone: str, profile_dir: str | None = None) -> dict:
"""The launch of one (dpr, seed) visit. The DPR is PINNED in the persona
(screen.dpr), so the core declares a screen, a work area and a window made
at that scale. It used to be forced through
extra_prefs={"layout.css.devPixelsPerPx": ...} on whatever persona the seed
drew: a 100% persona at 1.5 read innerWidth 1920 inside an outerWidth of
1291 (run 41325657085), an identity no machine has, which the engine now
refuses to start with. With dpr None nothing is pinned: the seed's own persona decides the scale."""
refuses to start with. With dpr None nothing is pinned: the seed's own persona decides the scale.
With a profile_dir the launch is the wrapper's persistent context on that folder (the profile a user keeps between runs)."""
options = {"seed": seed, "binary_path": firefox, "headless": True, "show_cursor": False,
"locale": "en-US", "timezone": zone}
if dpr is not None:
options["pin"] = {"screen.dpr": dpr}
if profile_dir is not None:
options["profile_dir"] = str(profile_dir)
return options
def dump(firefox: str, leg: str, out: Path, reference: Path, timeout_ms: int = 180_000,
visits: list | None = None, pin_dpr: bool = True) -> int:
"""`visits` is [(dpr, seed)] (default: every seed of SEEDS at every DPR of DPRS, the DPR pinned). With pin_dpr
False the DPR is not pinned: it is the one the seed's persona has, and `dpr` of a visit only names the file and
the page's query."""
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."""
from invisible_playwright import InvisiblePlaywright
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))
return result
def second_launch(options: dict, port: int, dpr: float, timeout_ms: int, read=None) -> dict:
"""The page's result of a SECOND launch on a profile the first one used: the same options and the same seed, on a folder of this call
that is made, launched on once (what that launch leaves in it is the point: cookies, cache, prefs.js, the session seed), closed,
launched on again, and removed. A first launch that did not answer the format is what comes back, for the caller to refuse."""
read = read or read_page
profile = tempfile.mkdtemp(prefix="host-gate-profile-")
try:
with_profile = dict(options, profile_dir=profile)
first = read(with_profile, port, dpr, timeout_ms)
if first.get("format") != FORMAT:
return first
return read(with_profile, port, dpr, timeout_ms)
finally:
shutil.rmtree(profile, ignore_errors=True)
def dump(firefox: str, leg: str, out: Path, reference: Path, timeout_ms: int = 180_000,
visits: list | None = None, pin_dpr: bool = True, relaunch_seeds: tuple = ()) -> int:
"""`visits` is [(dpr, seed)] (default: every seed of SEEDS at every DPR of DPRS, the DPR pinned). With pin_dpr
False the DPR is not pinned: it is the one the seed's persona has, and `dpr` of a visit only names the file and
the page's query. A seed of `relaunch_seeds` is visited once more, launched twice on one profile folder, and the
items of that second launch are added to the visit under RELAUNCH (the visit's own items stay those of a fresh profile)."""
out.mkdir(parents=True, exist_ok=True)
server = ThreadingHTTPServer(("127.0.0.1", 0), _Page)
threading.Thread(target=server.serve_forever, daemon=True).start()
port = server.server_address[1]
zone = reference_zone(reference)
first_diag = None
try:
for dpr, seed in (visits if visits is not None else [(d, sd) for d in DPRS for sd in SEEDS]):
with InvisiblePlaywright(**visit_options(firefox, seed, dpr if pin_dpr else None, zone)) as browser:
page = browser.new_context().new_page()
# The same budget as the wait below: a cold Windows runner took
# more than goto's default 30 s to reach `load` on the first
# visit (candidate 42410156024), and passed locally 6/6.
page.goto("http://127.0.0.1:%d/?dpr%s" % (server.server_address[1], dpr),
timeout=timeout_ms)
page.wait_for_function("document.title === 'done'", timeout=timeout_ms)
result = page.evaluate("window.__hostGate")
if result.get("format") == FORMAT:
result["items"].update(drive_states(page.evaluate, page.mouse.move, page.mouse.click))
options = visit_options(firefox, seed, dpr if pin_dpr else None, zone)
result = read_page(options, port, dpr, timeout_ms)
if result.get("format") != FORMAT:
print("the page answered format %r, not %r" % (result.get("format"), FORMAT))
return 2
if seed in relaunch_seeds:
again = second_launch(options, port, dpr, timeout_ms)
if again.get("format") != FORMAT:
print("the second launch on a reused profile: the page answered format %r, not %r" % (again.get("format"), FORMAT))
return 2
result["items"].update(relaunch_items(again["items"]))
print("second launch of seed %d on a reused profile: %d items" % (seed, len(again["items"])))
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")
@@ -596,6 +643,8 @@ def main(argv=None) -> int:
help="visit this seed (repeatable; default: the host gate's own seeds at its own DPRs)")
d.add_argument("--no-pin", action="store_true",
help="do not pin the DPR: the seed's persona has its own (the DPR of --visit only names the file)")
d.add_argument("--relaunch-seed", action="append", type=int, default=[], metavar="SEED",
help="also launch this seed twice on one profile folder and keep the second launch's items under relaunch. (repeatable)")
c = sub.add_parser("compare")
c.add_argument("dumps", type=Path)
c.add_argument("--reference", type=Path, default=REFERENCE)
@@ -604,7 +653,8 @@ def main(argv=None) -> int:
visits = None
if args.visit:
visits = [(float(dpr), int(seed)) for seed, dpr in (v.split(":", 1) for v in args.visit)]
return dump(args.firefox, args.leg, args.out, args.reference, visits=visits, pin_dpr=not args.no_pin)
return dump(args.firefox, args.leg, args.out, args.reference, visits=visits, pin_dpr=not args.no_pin,
relaunch_seeds=tuple(args.relaunch_seed))
notes = []
failures = compare(args.dumps, args.reference, load_exceptions(), notes)
for n in notes:
+314 -2
View File
@@ -24,13 +24,16 @@ SMALL = {dpr: 6 for dpr in gate.DPRS}
def items(seed=11):
"""A visit of the page: nested objects, an image, a list, and a diag. value."""
return {
"""A visit of the page: nested objects, an image, a list, and a diag. value. The visit of seed 0 also has the second launch on a reused profile, under relaunch."""
out = {
"surface": {"navigator": {"hardwareConcurrency": 8 + seed % 3, "language": "en-US"}, "screen": {"width": 1920, "height": 1080}},
"text": {"fonts": ["Arial", "Segoe UI"]},
"blend": {"data": "AAEC", "enc": "png", "w": 1, "h": 1},
"diag.webgl": {"webgl2": True, "message": "llvmpipe"},
}
if seed == ab.RELAUNCH_SEED:
out.update(copy.deepcopy(gate.relaunch_items(out)))
return out
def visits():
@@ -658,3 +661,312 @@ def test_the_host_oracle_has_a_job_of_its_own_on_each_system_with_the_tools_it_t
import test_ab_host_e2e as host_e2e
assert host_e2e.TIMEOUT_S + 10 * 60 <= 45 * 60, "the test's own limit fits the job"
# --- the second launch of seed 0 on a reused profile (H7) -----------------------------------------------------------------------------------------
SEED0 = (1.0, ab.RELAUNCH_SEED)
def zero_visits():
"""Two visits: seed 0, which has the second launch's leaves, and seed 2, which has none."""
return {SEED0: items(0), (1.5, 2): items(2)}
def zero_run(a, b, noise=(), floor=SMALL):
return ab.compare_visits(a, b, list(noise), floor, expected=tuple(sorted(a)))
def test_only_seed_0_is_launched_twice_and_the_visit_of_it_is_the_one_that_has_the_second_launch():
assert ab.RELAUNCH_SEED == 0 and ab.relaunch_visits([(1.5, 2), (1.0, 0), (1.25, 6)]) == ((1.0, 0),)
assert ab.relaunch_visits([(1.5, 2)]) == ()
both = items(0)
assert sorted(k for k in both if k.startswith(gate.RELAUNCH)) == ["relaunch.blend", "relaunch.surface", "relaunch.text"], "the diag. item of the second launch is not kept"
assert not [k for k in items(2) if k.startswith(gate.RELAUNCH)]
def test_the_second_launch_of_two_equal_dumps_is_green_and_is_counted_apart_from_the_visit():
report = zero_run(zero_visits(), zero_visits())
assert report["verdict"] == "green" and report["problems"] == []
assert report["compared"] == {"dpr1.0_seed0": 6, "dpr1.5_seed2": 6}, "the visit's own leaves only: the second launch's do not fill the floor"
assert report["relaunch"] == {"dpr1.0_seed0": 6}
def test_a_leaf_that_differs_in_the_second_launch_only_is_red_and_carries_the_prefix_and_the_seed():
b = zero_visits()
b[SEED0]["relaunch.surface"]["navigator"]["language"] = "it-IT"
report = zero_run(zero_visits(), b)
assert report["verdict"] == "red" and len(report["differences"]) == 1
d = report["differences"][0]
assert (d["seed"], d["dpr"], d["leaf"], d["a"], d["b"]) == (0, 1.0, "relaunch.surface.navigator.language", "en-US", "it-IT")
def test_a_second_launch_that_is_missing_on_one_side_is_red_and_says_which():
b = zero_visits()
for k in [k for k in b[SEED0] if k.startswith(gate.RELAUNCH)]:
del b[SEED0][k]
report = zero_run(zero_visits(), b)
assert report["verdict"] == "red"
assert any(p.startswith("side B: the second launch of dpr1.0_seed0 on a reused profile has 0 leaves") for p in report["problems"]), report["problems"]
assert not any(p.startswith("side A:") for p in report["problems"])
def test_a_second_launch_that_both_sides_lack_is_red_not_green():
both = zero_visits()
for k in [k for k in both[SEED0] if k.startswith(gate.RELAUNCH)]:
del both[SEED0][k]
report = zero_run(both, copy.deepcopy(both))
assert report["verdict"] == "red" and report["differences"] == []
assert len([p for p in report["problems"] if "second launch" in p]) == 2
def test_a_second_launch_that_dumped_less_than_the_floor_is_red_even_when_the_visit_is_full():
both = zero_visits()
del both[SEED0]["relaunch.text"]
report = zero_run(both, copy.deepcopy(both))
assert report["verdict"] == "red" and report["compared"]["dpr1.0_seed0"] == 6
assert all("has 5 leaves under relaunch." in p and "fewer than the 6" in p for p in report["problems"]) and len(report["problems"]) == 2
def test_the_second_launch_does_not_make_up_for_a_visit_that_dumped_less():
both = zero_visits()
del both[SEED0]["text"]
report = zero_run(both, copy.deepcopy(both))
assert report["verdict"] == "red" and report["compared"]["dpr1.0_seed0"] == 5
assert report["problems"] == ["dpr1.0_seed0 compared 5 leaves, fewer than the 6 of the host gate's reference: the page dumped less than it should"]
def test_a_second_launch_in_a_visit_that_was_not_asked_to_have_one_is_red():
b = zero_visits()
b[(1.5, 2)].update(copy.deepcopy(gate.relaunch_items(items(2))))
report = zero_run(zero_visits(), b)
assert report["verdict"] == "red" and "side B has the second launch of dpr1.5_seed2 on a reused profile, which was not asked for" in report["problems"]
def test_a_noise_entry_names_a_leaf_of_the_second_launch_by_its_bare_name_and_diag_under_the_prefix_is_not_held():
b = zero_visits()
b[SEED0]["relaunch.surface"]["navigator"]["language"] = "it-IT"
b[SEED0]["relaunch.diag.webgl"] = {"message": "other"}
a = zero_visits()
a[SEED0]["relaunch.diag.webgl"] = {"message": "llvmpipe"}
noise = [{"keys": ["surface.navigator.language"], "why": "x"}]
report = zero_run(a, b, noise, floor={dpr: 5 for dpr in gate.DPRS})
assert report["verdict"] == "green" and report["differences"] == [] and report["relaunch"] == {"dpr1.0_seed0": 5}
assert zero_run(a, b, [], floor={dpr: 5 for dpr in gate.DPRS})["verdict"] == "red", "without the entry it is a difference"
def test_a_candidate_set_visit_list_with_seed_0_expects_the_second_launch_of_it_from_judge_run_and_the_files(tmp_path, monkeypatch, capsys):
monkeypatch.setattr(ab, "MIN_LEAVES", SMALL)
asked = ab.select_visits(limit=2)
assert [seed for _, seed in asked][0] == 0
full = {key: items(key[1]) for key in asked}
assert ab.judge(full, copy.deepcopy(full), [], expected=tuple(asked))["relaunch"] == {ab.visit_name(*asked[0]): 6}
lacking = copy.deepcopy(full)
for k in [k for k in lacking[asked[0]] if k.startswith(gate.RELAUNCH)]:
del lacking[asked[0]][k]
assert ab.judge(full, lacking, [], expected=tuple(asked))["verdict"] == "red"
ab.write_json(tmp_path / "dump-68.json", ab.pack("firefox-68", full))
ab.write_json(tmp_path / "dump-candidate.json", ab.pack("candidate", lacking))
assert ab.main(["compare", str(tmp_path), "--limit", "2"]) == 1
assert "second launch of dpr" in capsys.readouterr().out
def test_the_dump_is_asked_for_the_second_launch_only_when_seed_0_is_among_the_visits(tmp_path, monkeypatch):
calls = []
class Done:
returncode = 0
monkeypatch.setattr(ab.subprocess, "run", lambda cmd, env, timeout: calls.append(cmd) or Done())
ab.run_dump("ff", tmp_path / "s.json", "linux-x86_64", tmp_path / "o", [(1.5, 2), (1.0, 0)])
ab.run_dump("ff", tmp_path / "s.json", "linux-x86_64", tmp_path / "o", [(1.5, 2), (1.25, 6)])
ab.run_dump("ff", tmp_path / "s.json", "linux-x86_64", tmp_path / "o")
with_zero, without, grid = calls
assert with_zero[with_zero.index("--relaunch-seed") + 1] == "0" and with_zero.count("--relaunch-seed") == 1
assert "--relaunch-seed" not in without and "--relaunch-seed" not in grid, "the host gate's own grid and the other shards do not launch twice"
# the dump itself, with the browser replaced: which launches it makes, on which folder, and what it keeps
def _fake_read(log, answers=None):
"""A read_page that records the options of every launch and answers items that say which launch they came from."""
def read(options, port, dpr, timeout_ms):
n = len(log)
log.append(dict(options))
answer = (answers or {}).get(n)
if answer is not None:
return answer
return {"format": gate.FORMAT, "items": {"surface": {"launch": n}, "diag.webgl": {"launch": n}}}
return read
def _dump(tmp_path, monkeypatch, visits_asked, relaunch, log, answers=None):
monkeypatch.setattr(gate, "read_page", _fake_read(log, answers))
monkeypatch.setattr(gate, "reference_zone", lambda reference: "UTC")
return gate.dump("ff", "leg", tmp_path / "dump", tmp_path / "reference", visits=visits_asked, pin_dpr=False, relaunch_seeds=relaunch)
def test_the_dump_launches_seed_0_twice_on_one_profile_and_keeps_the_second_launch_under_its_own_prefix(tmp_path, monkeypatch, capsys):
log = []
assert _dump(tmp_path, monkeypatch, [(1.0, 0), (1.5, 2)], (0,), log) == 0
assert len(log) == 4
fresh, first, second, other = log
assert "profile_dir" not in fresh and "profile_dir" not in other, "the visit itself, and every other seed, are on a fresh profile as they always were"
assert first["profile_dir"] == second["profile_dir"] and first["seed"] == second["seed"] == 0 and first["timezone"] == second["timezone"] == "UTC"
assert not Path(first["profile_dir"]).exists(), "the profile folder is removed when the second launch is done"
zero = json.loads((tmp_path / "dump" / "leg_dpr1.0_seed0.json").read_text(encoding="utf-8"))["result"]["items"]
assert zero["surface"] == {"launch": 0}, "the visit's own items are those of the fresh profile"
assert zero["relaunch.surface"] == {"launch": 2}, "the second launch's, not the first's"
assert "relaunch.diag.webgl" not in zero and zero["diag.webgl"] == {"launch": 0}
two = json.loads((tmp_path / "dump" / "leg_dpr1.5_seed2.json").read_text(encoding="utf-8"))["result"]["items"]
assert not [k for k in two if k.startswith(gate.RELAUNCH)]
assert "second launch of seed 0 on a reused profile" in capsys.readouterr().out
def test_the_dump_without_a_seed_to_launch_twice_launches_each_visit_once_as_the_host_gate_always_did(tmp_path, monkeypatch):
log = []
assert _dump(tmp_path, monkeypatch, [(1.0, 0), (1.5, 2)], (), log) == 0
assert len(log) == 2 and all("profile_dir" not in o for o in log)
assert gate.visit_options("ff", 6, 1.25, "UTC") == {"seed": 6, "binary_path": "ff", "headless": True, "show_cursor": False, "locale": "en-US", "timezone": "UTC",
"pin": {"screen.dpr": 1.25}}
assert gate.visit_options("ff", 6, None, "UTC", "p")["profile_dir"] == "p"
@pytest.mark.parametrize("bad", [1, 2])
def test_a_launch_of_the_pair_that_does_not_answer_the_format_is_a_failed_dump_and_the_folder_is_removed(tmp_path, monkeypatch, capsys, bad):
log = [] # launch 0 is the visit on a fresh profile, 1 the first launch of the pair, 2 the second
rc = _dump(tmp_path, monkeypatch, [(1.0, 0)], (0,), log, answers={bad: {"format": "old", "items": {}}})
assert rc == 2 and len(log) == bad + 1
assert "format 'old'" in capsys.readouterr().out
assert not Path(log[-1]["profile_dir"]).exists()
assert not (tmp_path / "dump" / "leg_dpr1.0_seed0.json").exists(), "a visit with a broken second launch is not written as if it were whole"
def test_the_profile_folder_is_removed_when_a_launch_of_the_pair_raises(tmp_path):
seen = []
def read(options, port, dpr, timeout_ms):
seen.append(options["profile_dir"])
if len(seen) == 2:
raise RuntimeError("the second launch hung")
return {"format": gate.FORMAT, "items": {}}
with pytest.raises(RuntimeError, match="hung"):
gate.second_launch({"seed": 0}, 1, 1.0, 1000, read=read)
assert len(seen) == 2 and seen[0] == seen[1] and not Path(seen[0]).exists()
def test_a_launch_on_a_profile_opens_its_page_in_the_persistent_context_and_a_launch_without_one_in_a_new_context(monkeypatch):
"""With a profile_dir the wrapper hands back a BrowserContext, which has no new_context(): asking it for one fails, so the persistent launch must open the page in it."""
import types
class Page:
mouse = types.SimpleNamespace(move=lambda *a: None, click=lambda *a: None)
def goto(self, url, timeout):
self.url = url
def wait_for_function(self, expression, timeout):
pass
def evaluate(self, expression):
return {"format": gate.FORMAT, "items": {"surface": {}}}
class Context:
def new_page(self):
return Page()
class Browser:
def new_context(self):
return Context()
class Session:
def __init__(self, **options):
self.options = options
def __enter__(self):
return Context() if "profile_dir" in self.options else Browser()
def __exit__(self, *exc):
return False
monkeypatch.setitem(sys.modules, "invisible_playwright", types.SimpleNamespace(InvisiblePlaywright=Session))
monkeypatch.setattr(gate, "drive_states", lambda *a: {})
for options in ({"seed": 0}, {"seed": 0, "profile_dir": "p"}):
assert gate.read_page(options, 1234, 1.0, 1000)["format"] == gate.FORMAT
# --- the final set in shards (H4): the test's guard, the e2e.yml jobs, the touched step ---------------------------------------------------------------
def _e2e_module():
import test_ab_oracle_e2e as e2e
return e2e
def test_the_hang_guard_grows_with_the_seeds_the_engine_runs_and_the_second_launch():
e2e = _e2e_module()
base = e2e.budget_s(5, 2)
assert base == e2e.SETUP_S + 2 * (e2e.FIRST_SEED_S + 4 * e2e.NEXT_SEED_S)
assert e2e.budget_s(2, 2) < e2e.budget_s(3, 2) < base < e2e.budget_s(5, 3) and e2e.budget_s(5, 2, True) == base + 2 * e2e.RELAUNCH_S
assert e2e.budget_s(5, 3, True) < 50 * 60, "the gate's leg has 50 minutes: a guard past the job's own timeout guards nothing"
assert e2e.budget_s(5, 2, True) + 10 * 60 <= 40 * 60, "a shard's A/A fits the 40 minutes of its job with its setup"
def test_the_plan_reads_the_shard_the_set_and_whether_there_is_a_candidate_from_the_environment(tmp_path):
e2e = _e2e_module()
assert e2e.plan({}) == (2, 2, True), "a pull request that touches nothing: the first two seeds of the candidate set, seed 0 among them"
assert e2e.plan({"AB_ORACLE_PR_SEEDS": "5"}) == (5, 2, True) and e2e.plan({"AB_ORACLE_PR_SEEDS": "99"}) == (5, 2, True)
seal = tmp_path / "seal.json"
assert e2e.plan({"INVISIBLE_SEAL_FILE": str(seal), "AB_ORACLE_PR_SEEDS": "1"}) == (5, 3, True), "with a candidate every seed, whatever the limit"
sizes = [e2e.plan({"AB_ORACLE_SEED_SET": "final", "AB_ORACLE_SHARD": "%d/4" % i}) for i in (1, 2, 3, 4)]
assert sizes == [(5, 2, True), (5, 2, False), (5, 2, False), (5, 2, False)], "20 seeds in four shards of five; seed 0 is in the first"
assert e2e.plan({"AB_ORACLE_SEED_SET": "final", "AB_ORACLE_SHARD": "1/4", "AB_ORACLE_PR_SEEDS": "2"})[0] == 5, "the final set's A/A has no limit"
assert e2e.plan({"AB_ORACLE_SEED_SET": "final"})[0] == 20 and e2e.plan({"AB_ORACLE_SEED_SET": "final", "INVISIBLE_SEAL_FILE": "x"}) == (20, 3, True)
with pytest.raises(SystemExit):
e2e.plan({"AB_ORACLE_SEED_SET": "everything"})
with pytest.raises(SystemExit):
e2e.plan({"AB_ORACLE_SEED_SET": "final", "AB_ORACLE_SHARD": "5/4"})
def test_the_hang_guard_of_the_test_is_the_budget_of_this_run_and_the_subprocess_ends_before_the_worker_is_killed():
e2e = _e2e_module()
assert e2e.BUDGET_S == e2e.budget_s(*e2e.plan()) and e2e.TIMEOUT_S == e2e.BUDGET_S
mark = next(m for m in e2e.test_the_published_engine_repeats_itself_and_the_candidate_gives_the_same_bytes.pytestmark if m.name == "timeout")
assert mark.args == (e2e.BUDGET_S + 120,) and mark.kwargs == {"method": "thread"}
def test_the_files_of_the_final_shards_are_the_files_of_the_page_oracle_and_nothing_else_is():
assert ab.touched(["README.md", "scripts/ci_ab_oracle.py"]) and ab.touched(["tests/test_ab_oracle_e2e.py"]) and ab.touched(["scripts/host_gate/page/index.html"])
assert not ab.touched(["README.md", "src/invisible_playwright/launcher.py", "scripts/ci_ab_network.py", "tests/test_ab_host.py"]) and not ab.touched([])
def test_the_touched_step_prints_one_line_with_a_unix_end_for_the_output_file(monkeypatch, capsys):
monkeypatch.setattr(pr, "changed_files", lambda base: ["tests/test_ab_oracle_e2e.py"] if base == "base1" else ["README.md"])
assert ab.main(["touched", "base1"]) == 0
out = capsys.readouterr().out
assert out == "touched=true\n" and "\r" not in out
assert ab.main(["touched", "base2"]) == 0 and capsys.readouterr().out == "touched=false\n"
def test_the_final_set_has_jobs_of_its_own_in_four_shards_on_each_system_and_the_shared_jobs_do_not_grow():
root = Path(__file__).resolve().parents[1]
text = (root / ".github" / "workflows" / "e2e.yml").read_text(encoding="utf-8")
page = "tests/test_ab_oracle_e2e.py"
linux, windows, touched = _job(text, "e2e-page-final"), _job(text, "e2e-page-final-windows"), _job(text, "e2e-page-final-touched")
assert "runs-on: ubuntu-24.04" in linux and "runs-on: windows-2022" in windows and "xvfb-run -a" in linux
for body in (linux, windows):
assert "shard: [1, 2, 3, 4]" in body and "AB_ORACLE_SEED_SET: final" in body and "AB_ORACLE_SHARD: ${{ matrix.shard }}/4" in body
assert body.count(page) == 1 and "scripts/run_e2e.py" not in body and "timeout-minutes: 40" in body and "fail-fast: false" in body
assert "needs: [core-on-index, e2e-page-final-touched]" in body and "needs.e2e-page-final-touched.outputs.touched == 'true'" in body
assert "skipped\": 0" in body and '{"tests": 1, "failures": 0, "errors": 0, "skipped": 0}' in body, "one test, passed: a skipped one is red"
assert "matrix.shard" in body.split("name: invpw-evidence-page-final", 1)[1].split("path:", 1)[0], "four shards, four artifact names"
assert "scripts/ci_ab_oracle.py touched" in touched and "pull_request" in touched and "outputs:" in touched
shared_linux, shared_windows = _job(text, "e2e"), _job(text, "e2e-windows")
assert "AB_ORACLE_SEED_SET" not in shared_linux + shared_windows + _job(text, "e2e-windows-control-a"), "the shared jobs run the candidate set and do not grow"
def test_the_final_set_is_four_shards_of_five_that_reach_every_seed_once_and_seed_0_is_in_the_first():
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]
+42 -5
View File
@@ -32,12 +32,46 @@ ROOT = Path(__file__).resolve().parent.parent
SCRIPT = ROOT / "scripts" / "ci_ab_oracle.py"
sys.path.insert(0, str(ROOT / "scripts"))
from ci_ab_pr_seeds import pr_seed_count # noqa: E402
import ci_ab_oracle as ab # noqa: E402
TIMEOUT_S = 40 * 60
#: The seeds of the A/A on a pull request: the first two of the candidate set (4 launches of the page; the gate's leg runs the A/A on all of them), or every one
#: when the pull request touches the oracle (AB_ORACLE_PR_SEEDS, from the step of e2e.yml).
#: when the pull request touches the oracle (AB_ORACLE_PR_SEEDS, from the step of e2e.yml). The final set's A/A (AB_ORACLE_SEED_SET=final) visits every seed of its shard.
PR_SEEDS = 2
#: The hang guard of the test, sized from what it will run (the seeds of its shard, the engine runs, the second launch of seed 0). It is a safety net and never a verdict: a
#: shard of the final set is 5 seeds, the A/A of a pull request is 2, the gate's leg with a candidate is 5 in three engine runs, and one fixed number cannot be right for all of
#: them. These are estimates, not measurements: 120 s to start, then for each engine run 180 s for its first seed (a cold launch, which on Windows is the slowest), 100 s for each
#: next one and 200 s for the two extra launches of seed 0 on one profile; the first A/A of each kind says what they should be and they move with it.
SETUP_S, FIRST_SEED_S, NEXT_SEED_S, RELAUNCH_S = 120, 180, 100, 200
def budget_s(seeds: int, engine_runs: int, relaunch: bool = False) -> int:
"""Seconds the test may take for ``seeds`` seeds in ``engine_runs`` runs of an engine (the A/A is two, with a candidate three), with the second launch of seed 0 when ``relaunch``."""
return SETUP_S + engine_runs * (FIRST_SEED_S + (seeds - 1) * NEXT_SEED_S + (RELAUNCH_S if relaunch else 0))
def asked(environ=None) -> tuple:
"""(seed set, shard, candidate, visits) this run of the test makes, from the environment as the test reads it. The A/A of a pull request visits the first
PR_SEEDS seeds of the candidate set (or every one when the pull request touches the oracle); the final set's A/A, and any run with a candidate, visit every
seed of their shard: that is what they are for."""
env = os.environ if environ is None else environ
candidate = bool(env.get("INVISIBLE_SEAL_FILE"))
seed_set = env.get("AB_ORACLE_SEED_SET") or "candidate"
shard = env.get("AB_ORACLE_SHARD") or None
limit = None if candidate or seed_set == "final" else pr_seed_count("AB_ORACLE_PR_SEEDS", PR_SEEDS, env)
return seed_set, shard, candidate, ab.select_visits(seed_set, shard, limit=limit)
def plan(environ=None) -> tuple:
"""(seeds, engine runs, whether seed 0 is launched twice on a profile) of this run."""
_seed_set, _shard, candidate, visits = asked(environ)
return len(visits), 3 if candidate else 2, bool(ab.relaunch_visits(visits))
BUDGET_S = budget_s(*plan())
#: The subprocess ends by itself at BUDGET_S and says so; the guard of the worker comes after it.
TIMEOUT_S = BUDGET_S
def _out(tmp_path: Path) -> Path:
explicit = os.environ.get("AB_ORACLE_OUT")
@@ -57,8 +91,7 @@ def test_the_published_engine_repeats_itself_and_the_candidate_gives_the_same_by
candidate = bool(seal)
if candidate:
assert Path(seal).is_file(), "INVISIBLE_SEAL_FILE names no file: %r" % seal
seed_set = os.environ.get("AB_ORACLE_SEED_SET") or "candidate"
shard = os.environ.get("AB_ORACLE_SHARD") or None
seed_set, shard, _candidate, visits = asked()
out = _out(tmp_path)
out.mkdir(parents=True, exist_ok=True)
leg = "win-x86_64" if sys.platform == "win32" else "linux-x86_64"
@@ -66,7 +99,9 @@ def test_the_published_engine_repeats_itself_and_the_candidate_gives_the_same_by
if candidate:
command[4:4] = [binary, "--candidate-seal", seal]
else:
command += ["--published-binary", binary, "--limit", str(pr_seed_count("AB_ORACLE_PR_SEEDS", PR_SEEDS))]
command += ["--published-binary", binary]
if seed_set != "final":
command += ["--limit", str(len(visits))]
if shard:
command += ["--shard", shard]
done = subprocess.run(command, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=TIMEOUT_S)
@@ -76,6 +111,8 @@ def test_the_published_engine_repeats_itself_and_the_candidate_gives_the_same_by
assert done.returncode == 0, "the oracle is red:\n" + "\n".join(verdict[:60]) + "\n" + done.stderr[-1500:]
control = json.loads((out / "diff-a-a.json").read_text(encoding="utf-8"))
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"
names = sorted(p.name for p in out.glob("*.json"))
if candidate:
diff = json.loads((out / "diff.json").read_text(encoding="utf-8"))