Files
playwright/scripts/ci_host_gate.py
feder-cr 887eb97bca Host gate: compare writes a junit with one testcase per invariant
--junit PATH writes the verdict of compare as xunit2: invariant:<name> for
each invariant and check:<name> for the other checks, classname
scripts.ci_host_gate (the path the hook tests name). A failed check is a
failure, a check with no dumps to look at is skipped.
2026-11-22 18:42:39 +01:00

1017 lines
53 KiB
Python

#!/usr/bin/env python3
"""CI host gate: what a page reads is a function of the declared identity and of
Firefox's code, never of the machine the browser runs on.
Two properties follow, and they are checked for every value the page dumps
(whole APIs, not a hand-picked list), so the gate needs no knowledge of where
the next leak will be:
1. HOST-INDEPENDENCE. The same identity on different hosts (the Windows and
Linux x86_64 legs) gives the same bytes.
2. RETAIL EQUALITY. A value that does not depend on the identity equals what
retail Firefox for Windows answers on the same page, at the same device
pixel ratio.
Values are compared leaf by leaf: an object the page reads (navigator, screen)
mixes fields the identity decides with fields it does not, and each is held to
its own property.
Which values depend on the identity is measured AND declared. Each leg visits
the page with several seeds at a fixed DPR; a value that changes with the seed
depends on the identity and is held to property 1 only. A value the identity
decides can still come out the same for every seed (16 cores, a 1920x1080
screen), so those are declared as well.
The only exceptions live in host_gate/exceptions.json, each with its reason:
- identity: values the declared identity decides; exempt from property 2,
never from property 1;
- noise: values that differ between two launches of retail itself;
- network: values the identity takes from the network (language and zone
from the egress IP), which CI without a proxy cannot reproduce;
- measurement: values that record how the reference was taken rather than
what Firefox answers (focus, on the hidden desktop retail ran on);
- known_defects: open divergences with the work that closes them. This list
only shrinks: an entry that no longer matches a difference fails the gate,
so it is removed when its fix lands.
Values under the diag. prefix are not held to either property. They are
information the page records about the host (diag.webgl: whether WebGL2 and
multisampling exist there and, when not, the message Firefox gives): the legs
legitimately differ on them and the retail reference does not record them.
compare() skips them by name; dump() prints them into the job log, so a run
tells why without its artifacts being downloaded.
Values under the ab. prefix are read for the A/B oracle: what a page reads of values a host may hold and the engine must never read
(ab.poison, with scripts/ci_poison_host.py) and, on the oracle's visits of seeds 0 and 63, the surfaces of every realm and window a page
can make (ab_visit). compare() skips them by name, as it skips diag.: the A/B compares them between the two engines.
Values under the state. prefix are the window in the states a page can drive
it to: state.normal, state.fullscreen (entered through a real click, a user
gesture) and state.after_fullscreen. The dump measures them after the page is
done (drive_states). Besides the two properties they are held to INVARIANTS:
relations between values that hold on every host, for every identity and
whatever the reference says, because a window that breaks them cannot exist
(an outer window smaller than its viewport, a fullscreen window off the
screen's origin). Each value can look plausible on its own; only the relation
shows the defect, so these are checked even where nothing else is.
This replaces ci_font_gate.py, which checked one surface (the font list) of
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
import argparse
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"
REFERENCE = HERE / "reference" / "firefox-159"
FORMAT = "host-gate/1"
#: DPRs the reference is recorded at, and the seeds visited at each. Three seeds
#: so that a value that depends on the identity is very unlikely to look
#: constant by chance.
DPRS = (1.0, 1.5)
SEEDS = (11, 12, 13)
#: The leg every other leg is compared with: the platform the identity claims.
ANCHOR = "win-x86_64"
#: Keys under this prefix are information, never compared (see the module docstring).
DIAG = "diag."
#: The items of a visit's SECOND launch on a profile that a first launch already used (`--relaunch-seed`, the A/B oracle's) live under this prefix, next to the
#: items of the visit on a fresh profile: the retail comparison (`compare`) never reads a dump made without that option, and the oracle compares the two
#: sets of leaves apart. The diag. items of the second launch are not kept: what the page records about the host is information, never compared.
RELAUNCH = "relaunch."
def relaunch_items(items: dict) -> dict:
"""The items of a second launch as they are stored in the visit: every key under RELAUNCH, the diag. ones left out."""
return {RELAUNCH + k: v for k, v in items.items() if not is_diag(k)}
def is_diag(key: str) -> bool:
return key.startswith(DIAG)
#: Keys under this prefix are read for the A/B oracle (scripts/ci_ab_oracle.py compares them between two engines on one machine). The host gate
#: does not hold them to either of its properties: the retail reference does not record them, and they are made on the oracle's machine
#: (a poisoned host, a launch in another locale), not on the gate's.
AB = "ab."
def is_ab(key: str) -> bool:
return key.startswith(AB)
def diag_lines(items: dict, before: dict | None = None) -> list:
"""The diag. leaves of one visit as 'key = value' lines; with before (an
earlier visit's diag leaves), only the keys whose value changed."""
now = {k: v for k, v in leaves(items).items() if is_diag(k)}
lines = [" %s = %s" % (k, json.dumps(v, sort_keys=True)) for k, v in now.items()
if before is None or before.get(k, "<missing>") != v]
return lines + [" %s = <missing>" % k for k in (before or {}) if k not in now]
def diag_report(visit: str, items: dict, first: dict | None) -> list:
"""What dump() prints for one visit: every diag. value on the leg's first
visit (first is None), then only what changed from it."""
if first is None:
return ["diag %s:" % visit] + (diag_lines(items) or [" (the page recorded no diag. keys)"])
changed = diag_lines(items, first)
return ["diag %s: %s" % (visit, "changed from the first visit:" if changed else "as the first visit")] + changed
# -
# States: the window driven to fullscreen and back with real input, and the
# relations its values must keep in every state.
STATE = "state."
#: The states drive_states measures, in the order it reaches them.
STATES = ("normal", "fullscreen", "after_fullscreen")
#: How long the page waits for fullscreenchange before recording 'timeout'.
STATE_TIMEOUT_MS = 5000
#: Retail equality for these namespaces waits for the reference to record them.
#: The firefox-159 reference was taken before the dump drove any state, so it has
#: no state.* key; until it has, a state.* value is held to host-independence and
#: to INVARIANTS only, and compare() notes it. The session that produces the
#: reference adds, to the items of each dpr<x>.json.gz, the three items
#: state.normal, state.fullscreen and state.after_fullscreen, shaped exactly as
#: drive_states returns them, by running drive_states on retail Firefox for
#: Windows on this page with evaluate = run the expression in the page, and move
#: and click = OS-level input at those viewport (CSS px) points, e.g. SendInput:
#: a click a script dispatches is not a user gesture and requestFullscreen
#: refuses it. From the first reference that has state.*, these values are
#: compared with retail like every other; the window geometry is declared
#: identity in exceptions.json, the rest (display-mode, fullscreenElement,
#: window.fullScreen, how the transition went) is held to retail.
REFERENCE_PENDING = (STATE,)
def drive_states(evaluate: Callable, move: Callable, click: Callable,
timeout_ms: int = STATE_TIMEOUT_MS) -> dict:
"""The page's window in each of STATES, as items {state.<name>: values}.
evaluate runs an expression in the page and returns its (awaited) value;
move and click are real input at a viewport point. In each state the mouse
moves twice and clicks on the middle of the viewport, so every value of the
state comes with the screen - client offsets of real mouse events.
Fullscreen is entered by clicking the page's button (its handler calls
requestFullscreen) and left with document.exitFullscreen(); each transition
records how it ended (fullscreenchange, fullscreenerror, timeout). Whatever
raises leaves {"error": ...} in the states not measured yet, which the
'measured' invariant reports.
"""
states = {}
def measure(name, transition=None):
evaluate("__hostGateStates.clear()")
w, h = evaluate("[innerWidth, innerHeight]")
x, y = w // 2, h // 2
move(x - 20, y)
move(x, y + 20)
click(x, y + 20)
values = evaluate("__hostGateStates.measure()")
if transition is not None:
values["transition"] = transition
states[name] = values
try:
button = evaluate("__hostGateStates.prepare()")
measure("normal")
evaluate("__hostGateStates.arm(%d)" % timeout_ms)
click(button["x"], button["y"])
measure("fullscreen", evaluate("__hostGateStates.wait()"))
evaluate("__hostGateStates.leave(%d)" % timeout_ms)
measure("after_fullscreen", evaluate("__hostGateStates.wait()"))
except Exception as e: # noqa: BLE001 - recorded, and failed by the 'measured' invariant
for name in STATES:
states.setdefault(name, {"error": "%s: %s" % (type(e).__name__, str(e)[:300])})
return {STATE + name: states[name] for name in STATES}
#: What a state is made of; the screen is {width, height, availWidth, availHeight}.
POSITION = ("innerWidth", "innerHeight", "outerWidth", "outerHeight", "screenX", "screenY",
"mozInnerScreenX", "mozInnerScreenY", "screen")
FIELDS = POSITION + ("display_mode_fullscreen", "fullscreen_element", "events")
def _measured(s, states):
if "error" in s:
return "not measured: %s" % s["error"]
missing = [f for f in FIELDS if f not in s]
missing += ["%s as a number" % f for f in POSITION[:-1]
if f in s and (isinstance(s[f], bool) or not isinstance(s[f], (int, float)))]
if not isinstance(s.get("screen"), dict) or not {"width", "height", "availWidth", "availHeight"} <= set(s["screen"]):
missing.append("screen.width/height/availWidth/availHeight")
if not isinstance(s.get("events"), dict):
missing.append("events as {type: [[dx, dy]]}")
return missing and "not measured: no %s" % ", ".join(missing)
def _transition(s, states):
t = s.get("transition")
if not isinstance(t, dict) or t.get("how") != "fullscreenchange" or not t.get("settled"):
return "the transition did not complete: %s" % json.dumps(t, sort_keys=True)
def _outer_holds_inner(s, states):
bad = ["outer%s %s < inner%s %s" % (d, s["outer" + d], d, s["inner" + d])
for d in ("Width", "Height") if s["outer" + d] < s["inner" + d]]
return "; ".join(bad)
def _is_the_screen(s, states):
w, h = s["screen"]["width"], s["screen"]["height"]
bad = ["%s %s" % (k, s[k]) for k, want in (("innerWidth", w), ("outerWidth", w),
("innerHeight", h), ("outerHeight", h)) if s[k] != want]
return bad and "%s, screen %sx%s (avail %sx%s)" % (", ".join(bad), w, h,
s["screen"]["availWidth"], s["screen"]["availHeight"])
def _at_origin(s, states):
bad = ["%s %s" % (k, s[k]) for k in ("screenX", "screenY", "mozInnerScreenX", "mozInnerScreenY") if s[k] != 0]
return ", ".join(bad)
def _declares(fullscreen):
def check(s, states):
bad = ["%s %s" % (k, json.dumps(s[k])) for k in ("display_mode_fullscreen", "fullscreen_element")
if s[k] is not fullscreen]
return ", ".join(bad)
return check
def _offset_matches(offset, inner_screen):
# MouseEvent.screenX and clientX are each rounded to a whole CSS px, while
# mozInnerScreenX is the viewport's exact offset, fractional when the DPR
# does not divide the window's device position (85.33 at 1.5): the
# difference of the two rounded values is then within 1 px of it. A whole
# offset has nothing to round and must match exactly.
if float(inner_screen).is_integer():
return offset == inner_screen
return abs(offset - inner_screen) <= 1
def _events_at_inner_screen(s, states):
if not any(s["events"].values()):
return "no mouse event was recorded"
inner = (s["mozInnerScreenX"], s["mozInnerScreenY"])
bad = ["%s (%s, %s)" % (typ, dx, dy) for typ, pairs in sorted(s["events"].items()) for dx, dy in pairs
if not (_offset_matches(dx, inner[0]) and _offset_matches(dy, inner[1]))]
return bad and "screen - client of %s, mozInnerScreen (%s, %s)" % (", ".join(bad), inner[0], inner[1])
def _screen_stays(s, states):
normal = states.get("normal")
if not isinstance(normal, dict) or not isinstance(normal.get("screen"), dict):
return None # the normal state's own 'measured' failure says why
bad = ["screen.%s %s (normal %s)" % (k, s["screen"][k], normal["screen"].get(k))
for k in ("width", "height") if s["screen"][k] != normal["screen"].get(k)]
return ", ".join(bad)
def _back_to_normal(s, states):
normal = states.get("normal")
if not isinstance(normal, dict) or _measured(normal, states):
return None # the normal state's own 'measured' failure says why
bad = ["%s %s (normal %s)" % (k, json.dumps(s[k]), json.dumps(normal[k])) for k in POSITION if s[k] != normal[k]]
return ", ".join(bad)
class Invariant(NamedTuple):
name: str
states: tuple
check: Callable # (state values, every state's values) -> failure message, or a false value
why: str
#: Every relation the states are held to, the only place they are declared.
#: 'measured' runs first: the others assume the state's fields are there.
INVARIANTS = (
Invariant("measured", STATES, _measured,
"a state the dump could not reach or read is a failure, never a silent pass"),
Invariant("transition", ("fullscreen", "after_fullscreen"), _transition,
"a real click is a user gesture, so retail enters and leaves fullscreen and the window then holds still; "
"a timeout or fullscreenerror means the window did not do what a user's does"),
Invariant("outer_holds_inner", STATES, _outer_holds_inner,
"the outer window contains the viewport: a smaller outer window cannot exist "
"(the defect it was written for: 1936x1048 outer under a 1920x1080 viewport in fullscreen)"),
Invariant("fullscreen_is_the_screen", ("fullscreen",), _is_the_screen,
"in fullscreen retail has no frame, toolbar or taskbar: viewport, window and screen are one rectangle "
"(a viewport at availHeight is a window that never really went fullscreen)"),
Invariant("fullscreen_at_origin", ("fullscreen",), _at_origin,
"a fullscreen window sits at the screen's origin and its viewport at the window's: "
"screenX/Y and mozInnerScreenX/Y are 0 (not a maximized window's -8/-8 and 85)"),
Invariant("fullscreen_declared", ("fullscreen",), _declares(True),
"the page entered fullscreen, so CSS (display-mode) and the DOM (fullscreenElement) say so"),
Invariant("not_fullscreen", ("normal", "after_fullscreen"), _declares(False),
"outside fullscreen neither CSS nor the DOM may claim it; it also keeps 'back_to_normal' "
"from passing with both states stuck in fullscreen"),
Invariant("events_at_inner_screen", STATES, _events_at_inner_screen,
"an event's screen point is its client point plus where the viewport sits on the screen, "
"which is mozInnerScreenX/Y: screen - client of every mouse event equals it"),
Invariant("screen_stays", ("fullscreen", "after_fullscreen"), _screen_stays,
"fullscreen changes the window, not the monitor: screen.width/height are the normal state's"),
Invariant("back_to_normal", ("after_fullscreen",), _back_to_normal,
"leaving fullscreen puts the window back as it was: every size and position is the normal state's"),
)
def check_invariants(states: dict) -> list:
"""Every broken invariant of one visit as (invariant, state, message).
states maps each of STATES to its values (None when the dump has none)."""
broken = []
for state in STATES:
s = states.get(state)
if not isinstance(s, dict):
s = {"error": "the dump has no %s%s" % (STATE, state)}
for inv in INVARIANTS:
if state not in inv.states:
continue
message = inv.check(s, states)
if message:
broken.append((inv, state, message))
if inv.name == "measured":
break
return broken
def visit_states(items: dict) -> dict:
return {name: items.get(STATE + name) for name in STATES}
def invariant_lines(visit: str, items: dict) -> list:
return ["invariant %s %s %s%s: %s (why: %s)" % (inv.name, visit, STATE, state, message, inv.why)
for inv, state, message in check_invariants(visit_states(items))]
# -
# Dump: one leg, every (dpr, seed) visit, the way the reference was measured:
# the page over http://127.0.0.1 (a secure context), en-US, the zone the retail
# reference reported (retail on Windows ignores TZ and answers the machine's),
# the device pixel ratio pinned in the persona, no drawn cursor.
class _Page(BaseHTTPRequestHandler):
def do_GET(self):
body = PAGE.read_bytes()
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.end_headers()
self.wfile.write(body)
def do_POST(self): # the page also posts its result; the dump reads it from the page
self.rfile.read(int(self.headers.get("Content-Length") or 0))
self.send_response(204)
self.end_headers()
def log_message(self, *args):
pass
def reference_items(reference: Path, dpr: float) -> dict | None:
"""Retail's items at one DPR, from dpr<x>.json.gz (or a plain dpr<x>.json)."""
for name in ("dpr%s.json.gz" % dpr, "dpr%s.json" % dpr):
path = reference / name
if path.is_file():
raw = path.read_bytes()
return json.loads(gzip.decompress(raw) if name.endswith(".gz") else raw)["items"]
return None
def reference_zone(reference: Path) -> str:
return reference_items(reference, 1.0)["surface.intl"]["DateTimeFormat"]["timeZone"]
def visit_options(firefox: str, seed: int, dpr: float | None, zone: str, profile_dir: str | None = None) -> dict:
"""The launch of one (dpr, seed) visit. The DPR is PINNED in the persona
(screen.dpr), so the core declares a screen, a work area and a window made
at that scale. It used to be forced through
extra_prefs={"layout.css.devPixelsPerPx": ...} on whatever persona the seed
drew: a 100% persona at 1.5 read innerWidth 1920 inside an outerWidth of
1291 (run 41325657085), an identity no machine has, which the engine now
refuses to start with. With dpr None nothing is pinned: the seed's own persona decides the scale.
With a profile_dir the launch is the wrapper's persistent context on that folder (the profile a user keeps between runs)."""
options = {"seed": seed, "binary_path": firefox, "headless": True, "show_cursor": False,
"locale": "en-US", "timezone": zone}
if dpr is not None:
options["pin"] = {"screen.dpr": dpr}
if profile_dir is not None:
options["profile_dir"] = str(profile_dir)
return options
#: Which launch of the dump is being made, for the name of the leaf a tab that died is recorded under (`crash.tab.<launch>`): the visit, the two launches of the pair on one profile,
#: the ab visit. Set with the probe's own label (`_mark`), so that the leaf and the evidence of the launch have one name.
_LAUNCH = ["visit"]
def _mark(seed, dpr, launch: str) -> None:
_LAUNCH[0] = launch
crash.mark(seed=seed, dpr=dpr, launch=launch)
class Steps:
"""Which step of a launch is being made, so that a tab that dies says WHERE: `step` is the last one begun, and `failed` the (step, error) of the last call of `wrap` that raised."""
def __init__(self, step: str = "launch") -> None:
self.step, self.failed = step, None
def wrap(self, name: str, fn: Callable) -> Callable:
def run(*args, **kwargs):
self.step = "%s %s" % (name, ", ".join(str(a)[:60] for a in args))
try:
return fn(*args, **kwargs)
except Exception as e: # noqa: BLE001 - noted, and raised again
self.failed = (self.step, e)
raise
return run
def leaves_of_crash(items: dict) -> dict:
"""{key: {"error", "step"}} of the items that record a tab that died or a session that was lost (also those of the second launch, under RELAUNCH)."""
out = {}
for key, value in items.items():
bare = key[len(RELAUNCH):] if key.startswith(RELAUNCH) else key
if bare.startswith(crash.TAB_PREFIX) and isinstance(value, dict):
out[key] = value
return out
def tab_crash_lines(visit: str, items: dict) -> list:
"""The tab crashes a visit's items hold, as the lines a dump prints."""
return ["TAB CRASH %s %s: %s, at the step %s" % (visit, k, v.get("error"), v.get("step")) for k, v in sorted(leaves_of_crash(items).items())]
def read_page(options: dict, port: int, dpr: float, timeout_ms: int) -> dict:
"""One launch: the page's result (with the states driven when the page answered the format), the browser closed. With a profile_dir in
`options` the wrapper hands back a persistent context, not a browser, and the page is opened in it.
A tab that died, or a session that was lost, while the page was read (the error says it: `crash.tab_lost`) is not an exception of the dump: it is the leaf
`crash.tab.<launch>` of this visit, with the error and the step, and the dump goes on. It used to be a `{"error": ...}` in each state the drive had not reached, which the
comparison read as a cascade of leaves that were missing (candidate run: «cannot find session» in every `state.*`)."""
from invisible_playwright import InvisiblePlaywright
launch, trace, result = _LAUNCH[0], Steps("new page"), None
with InvisiblePlaywright(**options) as browser:
try:
page = browser.new_page() if "profile_dir" in options else browser.new_context().new_page()
# The same budget as the wait below: a cold Windows runner took
# more than goto's default 30 s to reach `load` on the first
# visit (candidate 42410156024), and passed locally 6/6.
trace.step = "goto"
page.goto("http://127.0.0.1:%d/?dpr%s" % (port, dpr), timeout=timeout_ms)
trace.step = "wait for the page's result"
page.wait_for_function("document.title === 'done'", timeout=timeout_ms)
trace.step = "read the page's result"
result = page.evaluate("window.__hostGate")
if result.get("format") == FORMAT:
result["items"].update(drive_states(trace.wrap("evaluate", page.evaluate), trace.wrap("mouse move", page.mouse.move), trace.wrap("mouse click", page.mouse.click)))
if trace.failed is not None and crash.tab_lost(trace.failed[1]):
result["items"].update(crash.tab_crash_item(launch, "states: " + trace.failed[0], trace.failed[1]))
except Exception as e: # noqa: BLE001 - only a tab that died is recorded; anything else is raised as it always was
if not crash.tab_lost(e):
raise
result = {"format": FORMAT, "items": dict(result["items"]) if isinstance(result, dict) and isinstance(result.get("items"), dict) else {}}
result["items"].update(crash.tab_crash_item(launch, trace.step, e))
return result
def second_launch(options: dict, port: int, dpr: float, timeout_ms: int, read=None) -> dict:
"""The page's result of a SECOND launch on a profile the first one used: the same options and the same seed, on a folder of this call
that is made, launched on once (what that launch leaves in it is the point: cookies, cache, prefs.js, the session seed), closed,
launched on again, and removed. A first launch that did not answer the format is what comes back, for the caller to refuse."""
read = read or read_page
profile = tempfile.mkdtemp(prefix="host-gate-profile-")
try:
with_profile = dict(options, profile_dir=profile)
_mark(options.get("seed"), dpr, "relaunch-first")
first = read(with_profile, port, dpr, timeout_ms)
if first.get("format") != FORMAT:
return first
_mark(options.get("seed"), dpr, "relaunch-second")
again = read(with_profile, port, dpr, timeout_ms)
if again.get("format") == FORMAT: # a tab that died in the first launch is not lost because the second one was read
again["items"].update(leaves_of_crash(first.get("items") or {}))
return again
finally:
shutil.rmtree(profile, ignore_errors=True)
def dump(firefox: str, leg: str, out: Path, reference: Path, timeout_ms: int = 180_000,
visits: list | None = None, pin_dpr: bool = True, relaunch_seeds: tuple = (), ab: bool = False) -> int:
"""`visits` is [(dpr, seed)] (default: every seed of SEEDS at every DPR of DPRS, the DPR pinned). With pin_dpr
False the DPR is not pinned: it is the one the seed's persona has, and `dpr` of a visit only names the file and
the page's query. A seed of `relaunch_seeds` is visited once more, launched twice on one profile folder, and the
items of that second launch are added to the visit under RELAUNCH (the visit's own items stay those of a fresh profile).
With `ab`, the seeds of AB_SEEDS also get the extra visit of the A/B oracle (ab_visit): its leaves join the visit's items.
When the oracle that runs this dump names a folder for it (`AB_CRASH_DIR`, scripts/ci_ab_oracle.py), a probe sees how each launch's parent ends (scripts/ci_crash_evidence.py)
and writes it to `exits.json` there, whatever the dump's own result: a launch that did not end with 0 is red in the oracle, and what it left is saved in that folder."""
out.mkdir(parents=True, exist_ok=True)
crash_dir = os.environ.get(crash.CRASH_DIR_ENV)
probe = crash.start_probe(firefox, crash_dir) if crash_dir else None
server = ThreadingHTTPServer(("127.0.0.1", 0), _Page)
threading.Thread(target=server.serve_forever, daemon=True).start()
port = server.server_address[1]
zone = reference_zone(reference)
first_diag = None
try:
for dpr, seed in (visits if visits is not None else [(d, sd) for d in DPRS for sd in SEEDS]):
options = visit_options(firefox, seed, dpr if pin_dpr else None, zone)
_mark(seed, dpr, "visit")
result = read_page(options, port, dpr, timeout_ms)
if result.get("format") != FORMAT:
print("the page answered format %r, not %r" % (result.get("format"), FORMAT))
return 2
if seed in relaunch_seeds:
again = second_launch(options, port, dpr, timeout_ms)
if again.get("format") != FORMAT:
print("the second launch on a reused profile: the page answered format %r, not %r" % (again.get("format"), FORMAT))
return 2
result["items"].update(relaunch_items(again["items"]))
print("second launch of seed %d on a reused profile: %d items" % (seed, len(again["items"])))
if ab and seed in AB_SEEDS:
_mark(seed, dpr, "ab-visit")
result["items"].update(ab_visit(firefox, seed, zone, dpr if pin_dpr else None))
path = out / ("%s_dpr%s_seed%d.json" % (leg, dpr, seed))
path.write_text(json.dumps({"leg": leg, "dpr": dpr, "seed": seed, "result": result}),
encoding="utf-8")
print("dumped %s: %d items" % (path.name, len(result["items"])))
visit = "%s dpr %s seed %d" % (leg, dpr, seed)
for line in tab_crash_lines(visit, result["items"]):
print(line)
for line in diag_report(visit, result["items"], first_diag):
print(line)
# told here too, so the job log says it without the compare step
for line in invariant_lines(visit, result["items"]):
print(line)
sys.stdout.flush()
if first_diag is None:
first_diag = {k: v for k, v in leaves(result["items"]).items() if is_diag(k)}
finally:
server.shutdown()
if probe is not None:
crash.stop_probe()
probe.write()
for line in crash.exit_problems(probe.launches, "this dump", windows=leg.startswith("win")):
print("EXIT " + line)
return 0
# -
# The A/B oracle's extra visit: every realm and every kind of window a page can make, in a launch of another locale and in a context of yet
# another, on seeds 0 and 63. Its leaves are under ab. (see is_ab): scripts/ci_ab_oracle.py compares them between the two engines. It is a
# separate launch per seed, with its own server and its own functions: nothing here changes how the visits above are made.
#
# Seed 63 is the CONTROL of seed 0: an identity that is not seed 0's must read other values, so the same block on both must differ on at least
# AB_CONTROL_MIN ab. leaves (ab_control). A block that answered the same for two identities would pass an engine that ignores the identity.
AB_DIR = HERE / "ab"
AB_SEEDS = (0, 63)
AB_LAUNCH_LOCALE = "ja-JP"
#: (name of the context, what the context is made with). The first is the launch's own default context (locale ja-JP); the second overrides
#: both the language and the zone.
AB_CONTEXTS = (("launch", {}), ("context", {"locale": "de-DE", "timezone_id": "America/Lima"}))
AB_BUDGET_MS = 240_000
#: How many ab. leaves seed 63 must differ from seed 0 on. PROVISIONAL, from the core's prefs and not from a run: the two personas differ in their core
#: count (12 and 32), their GPU, their screen and their DPR, so hardwareConcurrency alone differs in every realm that must have read (top, cross-site
#: iframe, srcdoc iframe, worker, in each of the 2 contexts: 8 leaves) and the page-read GPU, the screen and the canvas leaves come on top of them.
#: The first run on GitHub prints the measured count (ab_control's line in the oracle's log, and ab-control.json): this number then moves to a safe
#: fraction of it, written here with the run it came from.
AB_CONTROL_MIN = 8
AB_CONTROL_NAMESPACES = tuple("%s%s." % (AB, name) for name, _ in AB_CONTEXTS)
_AB_TYPES = {".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8"}
#: A one-pixel GIF: what /ab/probe answers to a fetch and to an image alike.
_GIF = base64.b64decode("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")
class _AbSite(BaseHTTPRequestHandler):
"""The site of the ab visit: the files of scripts/host_gate/ab, /ab/probe (a pixel) and /ab/seen (the Accept-Language the server saw,
per context, by kind of request: `<Sec-Fetch-Dest>:<path>` -> the sorted distinct values)."""
def _send(self, status, content_type, body):
self.send_response(status)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self):
url = urlsplit(self.path)
ctx = (parse_qs(url.query).get("ctx") or [""])[0]
if url.path == "/ab/seen":
with self.server.ab_lock:
seen = {k: sorted(v) for k, v in self.server.ab_seen.get(ctx, {}).items()}
return self._send(200, "application/json", json.dumps(seen, sort_keys=True).encode())
if url.path.startswith("/ab/"):
with self.server.ab_lock:
kind = "%s:%s" % (self.headers.get("Sec-Fetch-Dest") or "none", url.path)
self.server.ab_seen.setdefault(ctx, {}).setdefault(kind, set()).add(self.headers.get("Accept-Language") or "<none>")
if url.path.startswith("/ab/probe"):
return self._send(200, "image/gif", _GIF)
name = url.path[len("/ab/"):] if url.path.startswith("/ab/") else ""
path = AB_DIR / name
if not name or "/" in name or "\\" in name or path.suffix not in _AB_TYPES or not path.is_file():
return self._send(404, "text/plain", b"not found")
return self._send(200, _AB_TYPES[path.suffix], path.read_bytes())
def log_message(self, *args):
pass
def ab_options(firefox: str, seed: int, dpr: float | None, zone: str) -> dict:
"""The launch of the ab visit: the host gate's own, in ja-JP."""
options = {"seed": seed, "binary_path": firefox, "headless": True, "show_cursor": False,
"locale": AB_LAUNCH_LOCALE, "timezone": zone}
if dpr is not None:
options["pin"] = {"screen.dpr": dpr}
return options
def ab_items(context: str, result, back) -> dict:
"""The items of one context of the ab visit: what the page recorded (ab.<context>.<step>...), what a page that came back from the history reads
again (ab.<context>.bfcache: whether it was restored from the back/forward cache is the engine's, not the identity's, and goes to diag.)."""
body = dict(result) if isinstance(result, dict) else {"result": result}
body["bfcache"] = back.get("data") if isinstance(back, dict) else back
return {AB + context: body, DIAG + AB + context: {"bfcache_persisted": back.get("persisted") if isinstance(back, dict) else None}}
def ab_visit(firefox: str, seed: int, zone: str, dpr: float | None = None, timeout_ms: int = AB_BUDGET_MS) -> dict:
"""Launch `firefox` with the seed in ja-JP, and read the ab site in its default context and in a context of de-DE and America/Lima;
returns {key: value} to add to the visit's items."""
from invisible_playwright import InvisiblePlaywright
server = ThreadingHTTPServer(("127.0.0.1", 0), _AbSite)
server.ab_seen, server.ab_lock = {}, threading.Lock()
threading.Thread(target=server.serve_forever, daemon=True).start()
base = "http://127.0.0.1:%d/ab/" % server.server_address[1]
items = {}
lost = None
try:
with InvisiblePlaywright(**ab_options(firefox, seed, dpr, zone)) as browser:
for name, options in AB_CONTEXTS:
context, step = None, "new context"
try:
context = browser.new_context(**options)
step = "new page"
page = context.new_page()
step = "goto surfaces"
page.goto(base + "surfaces.html?ctx=" + name, timeout=timeout_ms)
step = "wait for the page's result"
page.wait_for_function("document.title === 'ab-done'", timeout=timeout_ms)
step = "read the page's result"
result = page.evaluate("window.__abResult")
# away and back: the page that comes back reads again (pageshow), restored from the cache or loaded anew
step = "goto leave"
page.goto(base + "leave.html?ctx=" + name, timeout=timeout_ms)
step = "go back"
page.go_back(timeout=timeout_ms)
step = "wait for the page that came back"
page.wait_for_function("window.__abBf && window.__abBf.n >= 2", timeout=timeout_ms)
step = "read the page that came back"
back = page.evaluate("window.__abBf")
except Exception as e: # noqa: BLE001 - a tab that died is the leaf `crash.tab.ab-visit`; anything else is raised as it always was
if not crash.tab_lost(e):
raise
lost = crash.tab_crash_item("ab-visit", "%s (context %s)" % (step, name), e)
finally:
if context is not None:
try:
context.close()
except Exception: # noqa: BLE001 - closing a context whose tab died says nothing more
if lost is None:
raise
if lost is not None:
items.update(lost)
break
items.update(ab_items(name, result, back))
finally:
server.shutdown()
server.server_close()
return items
def ab_control(items_by_seed: dict, seeds: tuple = AB_SEEDS, minimum: int | None = None) -> dict:
"""The control of the ab visit: on how many leaves of the ab visit seeds[1] differs from seeds[0]. `items_by_seed` maps a seed to its items.
Returns {"status": "ok"|"too_few"|"not_visited", "differing", "compared", "minimum", "line"}; not_visited (a run that did not visit both,
the pull request's two seeds) is said, and the caller decides whether that is allowed."""
minimum = AB_CONTROL_MIN if minimum is None else minimum
a, b = seeds
mine = {}
for seed in seeds:
items = items_by_seed.get(seed)
mine[seed] = None if items is None else {k: v for k, v in leaves(items).items() if k.startswith(AB_CONTROL_NAMESPACES)}
if not mine[a] or not mine[b]:
missing = [s for s in seeds if not mine[s]]
return {"status": "not_visited", "differing": None, "compared": None, "minimum": minimum,
"line": "ab control: seed %s has no ab. leaves in this run" % " and ".join(map(str, missing))}
keys = sorted(set(mine[a]) | set(mine[b]))
differing = [k for k in keys if mine[a].get(k, "<missing>") != mine[b].get(k, "<missing>")]
status = "ok" if len(differing) >= minimum else "too_few"
return {"status": status, "differing": len(differing), "compared": len(keys), "minimum": minimum, "sample": differing[:12],
"line": "ab control: seed %d differs from seed %d on %d of %d ab. leaves (at least %d are required)%s"
% (b, a, len(differing), len(keys), minimum, "" if status == "ok" else ": an identity that is not seed %d's read the same" % a)}
#: The steps of the ab visit that must have read something in every context: a realm that answers `timeout` or an error says the page did not
#: read, and an A/B of two such answers compares nothing. The others (the service worker, the audio worklet, the popups) may be missing on a
#: host that has none of it; what they answered is compared like any leaf.
AB_REQUIRED_STEPS = ("top", "iframe_cross", "iframe_srcdoc", "worker", "accept_language")
def ab_coverage(items_by_seed: dict, seeds: tuple = AB_SEEDS) -> list:
"""What is missing from the ab visit of the seeds of this run that have one: [problem]. A seed of `seeds` that the run visited without an
ab visit, a context without its leaves, and a required step that did not read a dict are problems."""
problems = []
for seed in seeds:
items = items_by_seed.get(seed)
if items is None:
continue
for name, _ in AB_CONTEXTS:
body = items.get(AB + name)
if not isinstance(body, dict):
problems.append("seed %d: no %s%s leaves (the ab visit did not run, or the page recorded none)" % (seed, AB, name))
continue
for step in AB_REQUIRED_STEPS:
if not isinstance(body.get(step), dict):
problems.append("seed %d %s%s.%s: %s" % (seed, AB, name, step, json.dumps(body.get(step))[:160]))
return problems
# -
# Compare: every leg, every visit, against each other and against retail.
KINDS = ("identity", "noise", "network", "measurement", "known_defects")
def load_exceptions(path: Path = EXCEPTIONS) -> dict:
data = json.loads(path.read_text(encoding="utf-8"))
unknown = set(data) - set(KINDS)
if unknown:
raise SystemExit("exceptions.json: unknown kinds %s" % sorted(unknown))
for kind in KINDS:
for entry in data.get(kind, []):
if not entry.get("keys") or not entry.get("why"):
raise SystemExit("exceptions.json: every %s entry needs keys and why" % kind)
return data
def matching(entries: list, key: str, leg: str | None = None) -> list:
return [e for e in entries
if any(fnmatch.fnmatchcase(key, p) for p in e["keys"])
and (leg is None or not e.get("legs") or leg in e["legs"])]
def is_image(value) -> bool:
return isinstance(value, dict) and "data" in value and "enc" in value
def leaves(items: dict) -> dict:
"""Every value as a leaf with a dotted key; an image stays one value."""
out = {}
def walk(key, value):
if isinstance(value, dict) and value and not is_image(value):
for k, v in value.items():
walk("%s.%s" % (key, k), v)
else:
out[key] = value
for key, value in items.items():
walk(key, value)
return out
def describe(a, b) -> str:
"""A short account of a difference; for images, how many bytes differ."""
if isinstance(a, dict) and isinstance(b, dict) and "data" in a and "data" in b:
x, y = base64.b64decode(a["data"]), base64.b64decode(b["data"])
if len(x) != len(y) or (a.get("w"), a.get("h")) != (b.get("w"), b.get("h")):
return "image %sx%s vs %sx%s" % (a.get("w"), a.get("h"), b.get("w"), b.get("h"))
diff = [abs(p - q) for p, q in zip(x, y) if p != q]
return "image: %d of %d bytes differ, max delta %d" % (len(diff), len(x), max(diff, default=0))
text = lambda v: json.dumps(v, sort_keys=True)[:120]
return "%s vs %s" % (text(a), text(b))
def compare(dumps: Path, reference: Path, exceptions: dict, notes: list | None = None) -> list:
"""Every failure as one line. Empty means the gate passes. notes, when
given, receives what was not checked and why (REFERENCE_PENDING)."""
visits = {} # (leg, dpr, seed) -> items
failures = []
for path in sorted(dumps.glob("*.json")):
d = json.loads(path.read_text(encoding="utf-8"))
items = d["result"]["items"]
visits[(d["leg"], d["dpr"], d["seed"])] = {k: v for k, v in leaves(items).items() if not is_diag(k) and not is_ab(k)}
# the invariants: every leg, every visit, every state; no exception and no reference applies
failures += invariant_lines("%s dpr %s seed %d" % (d["leg"], d["dpr"], d["seed"]), items)
if not visits:
return ["no dumps in %s" % dumps]
legs = sorted({k[0] for k in visits})
refs = {}
pending = {} # dpr -> the REFERENCE_PENDING namespaces the reference does not record yet
for dpr in DPRS:
items = reference_items(reference, dpr)
if items is None:
return ["no retail reference for dpr %s in %s" % (dpr, reference)]
refs[dpr] = {k: v for k, v in leaves(items).items() if not is_diag(k) and not is_ab(k)}
pending[dpr] = tuple(p for p in REFERENCE_PENDING if not any(k.startswith(p) for k in refs[dpr]))
for p in pending[dpr]:
if notes is not None:
notes.append("the retail reference has no %s* at dpr %s: those values are held to "
"host-independence and the invariants, not to retail" % (p, dpr))
identity = exceptions.get("identity", [])
excusable = exceptions.get("noise", []) + exceptions.get("network", []) + exceptions.get("measurement", [])
known = exceptions.get("known_defects", [])
used = set()
def excused(key, leg):
if matching(excusable, key):
return True
hit = matching(known, key, leg)
for e in hit:
used.add(id(e))
return bool(hit)
for dpr in DPRS:
for leg in legs:
missing = [s for s in SEEDS if (leg, dpr, s) not in visits]
if missing:
failures.append("%s dpr %s: no dump for seeds %s" % (leg, dpr, missing))
present = [(leg, s) for leg in legs for s in SEEDS if (leg, dpr, s) in visits]
keys = sorted(set().union(*(visits[(l, dpr, s)].keys() for l, s in present)) | set(refs[dpr]))
for key in keys:
# 1. host-independence: for each seed, every leg gives the Windows
# leg's value. Windows is the anchor because it is the platform the
# identity claims: a leg that differs from it is the one that moved.
for seed in SEEDS:
values = {leg: visits[(leg, dpr, seed)].get(key, "<missing>")
for leg in legs if (leg, dpr, seed) in visits}
base = ANCHOR if ANCHOR in values else next(iter(values), None)
for leg, value in values.items():
if leg != base and value != values[base] and not excused(key, leg):
failures.append("host %s dpr %s seed %d: %s differs from %s: %s"
% (key, dpr, seed, leg, base, describe(value, values[base])))
# 1b. host-independence among the legs of one OS (two Linux
# distributions): a known defect excuses a difference from Windows,
# never one between two machines of the same system, whose libraries
# (FreeType, fontconfig, Mesa) are the host's and must not show.
for seed in SEEDS:
for family in sorted({l.split("-")[0] for l in legs}):
same_os = [l for l in legs if l.split("-")[0] == family and (l, dpr, seed) in visits]
for leg in same_os[1:]:
value = visits[(leg, dpr, seed)].get(key, "<missing>")
first = visits[(same_os[0], dpr, seed)].get(key, "<missing>")
if value != first and not matching(excusable, key):
failures.append("host %s dpr %s seed %d: %s differs from %s (same OS): %s"
% (key, dpr, seed, leg, same_os[0], describe(value, first)))
# 2. retail equality, for a value that is the same for every seed
if key.startswith(pending[dpr]):
continue
for leg in legs:
per_seed = [visits[(leg, dpr, s)].get(key, "<missing>")
for s in SEEDS if (leg, dpr, s) in visits]
if len({json.dumps(v, sort_keys=True) for v in per_seed}) != 1 or matching(identity, key):
continue # depends on the identity: property 1 only
retail = refs[dpr].get(key, "<missing>")
if per_seed[0] != retail and not excused(key, leg):
failures.append("retail %s dpr %s on %s: %s"
% (key, dpr, leg, describe(per_seed[0], retail)))
for e in known:
if id(e) not in used:
failures.append("known defect no longer seen, remove it from exceptions.json: %s (%s)"
% (e["keys"], e["why"]))
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)
d = sub.add_parser("dump")
d.add_argument("firefox")
d.add_argument("--leg", required=True)
d.add_argument("--out", type=Path, required=True)
d.add_argument("--reference", type=Path, default=REFERENCE)
d.add_argument("--visit", action="append", metavar="SEED:DPR",
help="visit this seed (repeatable; default: the host gate's own seeds at its own DPRs)")
d.add_argument("--ab", action="store_true",
help="the seeds of AB_SEEDS also get the A/B oracle's extra visit (ab. leaves)")
d.add_argument("--no-pin", action="store_true",
help="do not pin the DPR: the seed's persona has its own (the DPR of --visit only names the file)")
d.add_argument("--relaunch-seed", action="append", type=int, default=[], metavar="SEED",
help="also launch this seed twice on one profile folder and keep the second launch's items under relaunch. (repeatable)")
c = sub.add_parser("compare")
c.add_argument("dumps", type=Path)
c.add_argument("--reference", type=Path, default=REFERENCE)
c.add_argument("--junit", type=Path, help="also write the verdict as a junit (xunit2) file")
args = ap.parse_args(argv)
if args.cmd == "dump":
visits = None
if args.visit:
visits = [(float(dpr), int(seed)) for seed, dpr in (v.split(":", 1) for v in args.visit)]
return dump(args.firefox, args.leg, args.out, args.reference, visits=visits, pin_dpr=not args.no_pin,
relaunch_seeds=tuple(args.relaunch_seed), ab=args.ab)
notes = []
failures = compare(args.dumps, args.reference, load_exceptions(), notes)
for n in notes:
print("NOTE " + n)
for f in failures:
print("FAIL " + f)
if args.junit:
write_junit(args.junit, junit_cases(failures, len(list(args.dumps.glob("*.json")))))
print("HOST GATE %s: %d failures" % ("OK" if not failures else "FAILED", len(failures)))
return 1 if failures else 0
if __name__ == "__main__":
sys.exit(main())