ci: the host and network oracles close only after Glean has initialised, and their controls say why they broke

Run 45121964904 (the gate of the 69) had three red controls, none from the candidate:
- network, Linux: the published 68 exited with -11 in the exit-pings launch. It is Mozilla's race:
  a session closed before Glean initialised makes it start inside the shutdown, where glean.init can
  panic ("No database found"). That launch had no window, so Glean was always born in the shutdown.
  Every launch of the two oracles now waits, right after its first page, for
  <profile>/datareporting/glean/db/data.safe.bin (a condition read from the host; 60 s is a red
  safety limit). The launch's own work always sits between the condition and the close. The
  exit-pings launch opens a page and navigates once before it closes, and its wait for the
  data-policy pref (which never came) is gone. The host's bare launch, never compared, is removed.
  Each launch keeps the listing of datareporting/ as evidence.
- network, Windows: the subprocess timeout killed only the python child; the firefox grandchild
  held the pipe and pytest timed out without a word. crash.run_tree writes the output to files,
  kills the whole tree, and names the launch that was alive and for how long.
- host, Windows: the stock control never started (Playwright's Firefox was not installed) and was
  reported as "does not reach the platform provider". It now runs after a green A/A on every
  Windows run, pull requests included. The job installs the browser, a missing executable is said by
  name, and a stock that ran without reaching the provider prints its processes and modules. A
  read-only step prints lfsvc and the location consent keys.
This commit is contained in:
feder-cr committed 2026-11-23 11:02:42 +01:00
1 parent 6d42084c95
commit efa6d948fe
10 files changed
+1096 -260

No files matched your search

+28
View File
@@ -782,6 +782,10 @@ jobs:
python -m pip install --upgrade pip
python -m pip install ".[dev]"
python -m pip install "playwright==$(cat scripts/playwright_pin.txt)"
# The geolocation control of the host oracle runs on Playwright's own Firefox (`run_stock`, `ci_ab_host.py stock`) on every run: the binary is not in the image (run
# 45121964904: `Executable doesn't exist at ms-playwright/firefox-1532/firefox/firefox.exe`, and the oracle blamed the platform provider). The same python as the tests.
- name: Playwright's own Firefox (the control of the geolocation step)
run: python -m playwright install 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
@@ -802,6 +806,30 @@ jobs:
print(counts)
sys.exit(0 if counts == {"tests": 1, "failures": 0, "errors": 0, "skipped": 0} else 1)
PY
# What the Windows location provider needs, read only and printed when the control says the step does not reach it (the service, the consent of the location
# capability for the machine and for the user, its configuration): the runner's state, to be read next to the stock evidence of the oracle.
- name: The state of the Windows location service and of its consent (read only)
if: always()
shell: pwsh
run: |
$ErrorActionPreference = 'Continue'
"--- Get-Service lfsvc"
try { Get-Service lfsvc -ErrorAction Stop | Format-List * } catch { "lfsvc: not readable: $($_.Exception.Message)" }
foreach ($key in @(
'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\location',
'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\location',
'HKLM:\SYSTEM\CurrentControlSet\Services\lfsvc\Service\Configuration')) {
"--- $key"
if (-not (Test-Path -LiteralPath $key)) { "key absent: $key"; continue }
try { Get-ItemProperty -LiteralPath $key -ErrorAction Stop | Format-List * } catch { "not readable: $($_.Exception.Message)" }
foreach ($sub in @('NonPackaged')) {
$path = Join-Path $key $sub
if (Test-Path -LiteralPath $path) {
"--- $path"
try { Get-ItemProperty -LiteralPath $path -ErrorAction Stop | Format-List * } catch { "not readable: $($_.Exception.Message)" }
}
}
}
- name: The leg ran with the pinned GeoIP database
if: always()
run: |
+146 -79
View File
@@ -20,7 +20,7 @@ Three things are compared, over the whole trace:
time (a spare process is prelaunched after a delay and closed after a grace period);
* the files: every path the tree touched (opened, stat'ed, accessed, read as a link, executed), classified `ours` or `host`. ONE rule judges the host paths, in the A/A and in the
A/B, on Linux and on Windows, the system modules and the shortcut inventory included (`file_rule`): a path is red if and only if it is in ALL the measured launches (the warm-up and
the seeds) of one engine and in NO launch of the other (its idle and bare launches included). Every other path that is not in the same share of the launches of both engines is LISTED, not judged: the log and the file
the seeds) of one engine and in NO launch of the other (its idle launch included). Every other path that is not in the same share of the launches of both engines is LISTED, not judged: the log and the file
`not-judged-a-a.json` / `not-judged.json` of the artifact give, per path, in how many launches of how many each engine has it (measured and long) and the processes that touched it,
and mark `watch` the paths in at least half of the launches of one engine and in none of the other's. `ours` leaves the comparison as a class (OURS below: reading its own package is
not touching the host);
@@ -50,7 +50,7 @@ Only a separate `pingsender[.exe]` there is red. Behind a session proxy a direct
ACCEPTED LOSSES (the rule of the host paths trades them for a verdict that does not follow the machine's timing; for the 69):
* a path that one engine has in every measured launch and the other in only some of them is not red: always against sometimes is listed, never judged;
* a reading tied to one seed is not judged: no path is compared seed by seed;
* what happens only in the long launches (idle, bare) is only listed: judging it would take two idle launches per engine;
* what happens only in the long launch (idle) is only listed: judging it would take two idle launches per engine;
* the cause of the pingsender that starts in one launch of eight is not known: its paths are listed like the others, there is no rule and no preference for it;
* a pid that Windows reuses may attribute to the engine the tools of the oracle itself, among the processes that touched a path.
@@ -67,13 +67,13 @@ How the trace is taken:
are). Two canary files of the oracle's own, opened after the session starts and before it stops, must be in the trace: a session that did not
see them is red, not empty.
EVERY launch is also judged by how its parent ended (scripts/ci_crash_evidence.py): the warm-up, each measured seed, the idle and the bare launch alike. A root exit code other
EVERY launch is also judged by how its parent ended (scripts/ci_crash_evidence.py): the warm-up, each measured seed and the idle launch alike. A root exit code other
than 0, or one that was not seen, is a RED line that names the seed, the run side, the launch and the code; the verdict of a closed run is not "the trace is equal" alone. A launch
that did not end with 0 keeps what it left in `<footprint>.crash/<launch>/`, next to the footprint (the artifact): the last 100 lines of the strace log and the fatal signal lines of
the whole log (`--- SIGSEGV {si_addr=...} ---`: the trace records the fatal signals now, `tests/_strace_stand_in.py` RECORDED_SIGNALS, and the lines are dropped where the log is read, so they
are never data of the comparison), the core run through `gdb -batch` (`thread apply all bt`, the MOZ_CRASH reason, `info sharedlibrary`) with the build ids, the crash reporter's `.extra` and
the minidump names, and `said.txt` for every collector that found nothing. Cores are enabled in every launch (`ulimit -c unlimited` in the stand-in; the working directory is not touched, the
job's `kernel.core_pattern` decides where the kernel writes them: INVPW_CORE_DIR), and a crash watcher reads the crash folders in every launch, as it did in the bare one. On Windows the `.extra`
job's `kernel.core_pattern` decides where the kernel writes them: INVPW_CORE_DIR), and a crash watcher reads the crash folders in every launch. On Windows the `.extra`
files and the minidump names are collected the same way. `crash-probe` is the recorder's own test (one launch, its parent sent SIGSEGV; red is the right answer, tests/test_ab_host_crash_linux_e2e.py).
python ci_ab_host.py run <firefox> [--seal SEAL] --leg linux-x86_64 --out footprint.json [--seeds 11,12,13]
@@ -119,7 +119,7 @@ sys.path.insert(0, str(ROOT / "tests"))
import ci_ab_oracle as oracle # noqa: E402 (fetch_published, ENGINE_TAG)
import ci_host_gate as gate # noqa: E402 (SEEDS)
import ci_crash_evidence as crash # noqa: E402 (the exit code is red, and what a bad end left is saved)
from ci_crash_evidence import CrashWatcher, core_info, crash_report_dirs, scan_crash_files # noqa: E402,F401 (the bare launch's collectors, shared by every launch)
from ci_crash_evidence import CrashWatcher, crash_report_dirs # noqa: E402 (the collectors every launch shares)
FORMAT = "ab-host/2"
EXPECTED_FORMAT = "ab-host-expected/1"
@@ -523,19 +523,8 @@ def pingsender_destinations(fp: dict) -> list:
for e in fp.get("net") or [] if e.startswith(PINGSENDER_KIND + ": ")})
def _bare_summary(bare: dict | None) -> dict | None:
"""What the bare launch (never compared) says, for the report: how its parent ended, the crash reporter processes, the dump files, the cores."""
if not bare:
return None
crash = bare.get("crash") or {}
core = crash.get("core") or {}
return {"notified": (bare.get("notified") or {}).get("observed"), "parent_exits": crash.get("parent_exits"), "root_returncode": crash.get("root_returncode"),
"crash_processes": [(p["kind"], p["argv"]) for p in crash.get("crash_processes", [])], "dump_files": [f["name"] for f in crash.get("files", [])],
"cores": core.get("cores"), "core_pattern": core.get("core_pattern")}
#: THE RULE OF THE HOST PATHS, one for the A/A and the A/B, Linux and Windows, over every host path (the system modules and the shortcut inventory included). A path is
#: RED if and only if it is in ALL the measured launches (the warm-up and the seeds) of one engine and in NO launch of the other (its long idle and bare launches included). In
#: RED if and only if it is in ALL the measured launches (the warm-up and the seeds) of one engine and in NO launch of the other (its long idle launch included). In
#: the A/A that is a broken control, in the A/B a difference (the declared ones apply to it as they always did). Every other path that is not in all the launches of both engines is
#: LISTED, not judged (`file_rule`, the file `not-judged[-a-a].json` of the artifact, the log): the paths that are not in the same share of the launches of both engines, with in
#: how many launches of how many each engine has them and the processes that touched them; the ones in at least half of the launches of one engine and in none of the other's are
@@ -547,10 +536,10 @@ LISTED_IN_LOG = 50
def launches_of(fp: dict) -> list:
"""`[(name, measured, launch)]` of a footprint in the order of the run: the warm-up and the seeds (`measured`), then the idle and the bare launch (the long ones)."""
"""`[(name, measured, launch)]` of a footprint in the order of the run: the warm-up and the seeds (`measured`), then the idle launch (the long one)."""
out = [("warmup", True, fp["warmup"])] if fp.get("warmup") else []
out += [("s%s" % s["seed"], True, s) for s in fp.get("seeds", [])]
return out + [(name, False, fp[name]) for name in ("idle", "bare") if fp.get(name)]
return out + [(name, False, fp[name]) for name in ("idle",) if fp.get(name)]
def path_table(fps: list) -> dict:
@@ -1526,7 +1515,8 @@ def stock_control_problems(stock: dict) -> list:
problems += ["stock control: step %s (%s) failed: %s" % (st.get("n"), st.get("name"), st.get("error")) for st in seed.get("steps", []) if not st.get("ok")]
if not seed:
problems.append("stock control: the run made no footprint")
elif not location_utility_kinds(seed.get("kinds", {})):
elif seed.get("started", True) and not location_utility_kinds(seed.get("kinds", {})):
# only a stock Firefox that RAN says anything about the provider: one that never started (not installed, did not launch) is a different broken control
problems.append("stock control: stock Firefox did not start the Windows location utility process (-sandboxingKind %s) after getCurrentPosition with the "
"permission granted: the step does not reach the platform provider, so a candidate without that process proves nothing"
% LOCATION_UTILITY_KIND)
@@ -1625,7 +1615,6 @@ def judge(a: dict, b: dict, expected: list | None = None, a_a: bool = False, pla
return {"format": FORMAT, "mode": "a-a" if a_a else "a-b", "verdict": "red" if problems else "green", "problems": problems,
"differences": differences, "declared": declared, "ours": OURS, "tab": {"reason": TAB_REASON, "counts": tab},
"outside_tree": outside, "warmup": dict(warm, both=both), "idle": {side: _idle_summary(fp.get("idle")) for side, fp in (("A", a), ("B", b))}, "not_judged": not_judged,
"bare": {side: _bare_summary((fp.get("bare") or {}).get("bare")) for side, fp in (("A", a), ("B", b))},
"shortcuts": {side: _shortcuts_summary(((fp.get("idle") or {}).get("idle") or {}).get("shortcut_changes")) for side, fp in (("A", a), ("B", b))},
"stale": [e.get("id") for e in stale], "leaves": counts, "net": net}
@@ -1671,10 +1660,6 @@ def print_report(report: dict, a_name: str, b_name: str) -> None:
if shortcuts:
print("SHORTCUTS (the places of the shortcut code, before and after the idle launch; evidence) %s: %d new, %d changed, %d gone %s" % (
name, shortcuts["new"], shortcuts["changed"], shortcuts["gone"], json.dumps(shortcuts["files"])))
for side, name in (("A", a_name), ("B", b_name)):
bare = (report.get("bare") or {}).get(side)
if bare:
print("BARE (no client, no page; not compared) %s: %s" % (name, json.dumps(bare, sort_keys=True)))
for side, name in (("A", a_name), ("B", b_name)):
idle = (report.get("idle") or {}).get(side)
if idle:
@@ -1779,11 +1764,60 @@ def geolocation_step(browser, origin: str, declared: dict | None, n: int) -> dic
return step
def run_seed(binary: str, seed: int, work: Path, name: str | None = None, idle: bool = False, bare: bool = False, crash_with: int | None = None) -> dict:
"""One browser, one journey, one close, one trace. Returns the seed's footprint; `name` is the folder of its work (the warm-up has one of its own).
def wait_for_glean_of_launch(find_profile, seed: int, launch: str) -> str | None:
"""The wait of a launch with a page for Glean (`crash.wait_for_glean`), made right after its first page is opened: Glean is born once a window is open, and a session that
closes before it has initialised makes it start inside the shutdown, where the parent can end with -11 (a race of Mozilla's, the same in the retail browser; run 45121964904).
The wait is on the file Glean writes, not on a time. Returns the problem of the launch when the condition is not met in the safety limit of `crash.GLEAN_LIMIT_S` (the
verdict is red; the launch goes on and closes as it always did), None when it is."""
try:
waited = crash.wait_for_glean(find_profile())
except crash.GleanNotReady as e:
print("glean NOT ready (seed %d, launch %s): %s" % (seed, launch, e))
sys.stdout.flush()
return str(e)
print("glean ready after %.1f s (seed %d, launch %s)" % (waited, seed, launch))
sys.stdout.flush()
return None
`bare` is the old idle launch, kept as a case of its own and never compared: no client and no page, as the run 44988820319 made it (a crash reporter ran in it, on
both systems). It records how the browser ended and what a crash leaves (`crash_evidence`), on Linux with core dumps on, and waits as the idle launch does.
def datareporting_listing(profile) -> str:
"""The text of `<profile>/datareporting/` as a table, `path<TAB>size` (relative, `/`, sorted): what Glean and the data policy left in the profile of a launch. A read error
is a line of the table (`# error`), never a reason to stop: it is evidence, and the launch does not depend on it."""
lines = ["path\tsize"]
if profile is None:
return "\n".join(lines + ["# error\tthe profile of the launch was not found"]) + "\n"
root = Path(profile) / "datareporting"
rows, errors = [], []
def on_error(e):
errors.append("# error\t%s\t%s" % (e.filename, e.strerror or e))
if not root.is_dir():
errors.append("# error\t%s\tno such folder" % root.as_posix())
for folder, _dirs, files in os.walk(root, onerror=on_error):
for name in files:
path = Path(folder) / name
try:
rows.append((path.relative_to(root).as_posix(), path.stat().st_size))
except OSError as e:
errors.append("# error\t%s\t%s" % (path.as_posix(), e.strerror or e))
return "\n".join(lines + ["%s\t%d" % row for row in sorted(rows)] + sorted(errors)) + "\n"
def save_datareporting(profile, folder, launch: str, seed: int) -> None:
"""Saves the listing of `<profile>/datareporting/` as `<folder>/<launch>-<seed>.tsv` (evidence for the next time: it changes no verdict and is never a leaf of the footprint).
No folder, no file; a write that fails is said on the output."""
if not folder:
return
try:
Path(folder).mkdir(parents=True, exist_ok=True)
(Path(folder) / ("%s-%d.tsv" % (launch, seed))).write_text(datareporting_listing(profile), encoding="utf-8", newline="")
except OSError as e:
print("the list of datareporting could not be saved (seed %d, launch %s): %s" % (seed, launch, e))
def run_seed(binary: str, seed: int, work: Path, name: str | None = None, idle: bool = False, crash_with: int | None = None, datareporting_dir=None) -> dict:
"""One browser, one journey, one close, one trace. Returns the seed's footprint; `name` is the folder of its work (the warm-up has one of its own).
`idle` is the launch in which the exit pings MUST leave (see `run_engine`): no journey and no pref changed; the launch waits until the notification of the data
policy is recorded in its profile (the precondition of `canUpload`, seen in a file of the launch) and then closes; its footprint carries `idle` (what the wait saw).
@@ -1792,6 +1826,11 @@ def run_seed(binary: str, seed: int, work: Path, name: str | None = None, idle:
(`result["crash"]`, `crash.collect`: the strace tail with the signal line, the core through gdb, the build ids, the `.extra` and the minidump names). The cores are
enabled in every launch (`ulimit -c unlimited` in the stand-in, the working directory untouched) and a crash watcher reads the crash folders while any launch lives.
A launch with a page waits for Glean to have initialised right after its first page is opened (`wait_for_glean_of_launch`: Glean is born once a window is open, and a session
that closes before it has initialised makes it start inside the shutdown, where the parent can end with -11), so that the work of the launch is always between the condition and the
close; a condition that is not met is a problem of the launch (the verdict is red) and the launch goes on. Just before the close the list of `<profile>/datareporting/` is saved in
`datareporting_dir` (`save_datareporting`: evidence for the next time, never part of the footprint).
`crash_with` is the recorder's own test (`crash-probe`): the signal sent to the parent of the browser once it is up, to show that a launch that dies is red and keeps its evidence."""
from playwright.sync_api import sync_playwright
@@ -1800,6 +1839,7 @@ def run_seed(binary: str, seed: int, work: Path, name: str | None = None, idle:
windows = sys.platform == "win32"
seed_work = work / (name or "seed%d" % seed)
launch_name = name or "measured" # `name` is a loop variable of the journey below
seed_work.mkdir(parents=True)
exe, log, pidfile, pgid = binary, seed_work / "strace.log", seed_work / "stand-in.pid", None
trace = None
@@ -1816,7 +1856,7 @@ def run_seed(binary: str, seed: int, work: Path, name: str | None = None, idle:
from _strace_stand_in import _stand_in
exe = _stand_in(binary, seed_work / "engine", log, pidfile, syscalls=STRACE_CALLS, fd_paths=True, network=True, exit_status=True,
core_dir=seed_work if bare else None, cores=True)
cores=True)
origin_a, origin_o, stop_site = journey_site.start((0, 0))
geo_origin, stop_geo = start_geo_lab()
server, steps, root_pid = None, [], None
@@ -1825,8 +1865,12 @@ def run_seed(binary: str, seed: int, work: Path, name: str | None = None, idle:
shortcuts_before = snapshot_places(places) if places else None
before = set(Path(tempfile.gettempdir()).glob("invisible_profile_*"))
def profile_now():
"""The profile folder this launch made (None until it is there)."""
return (new_profiles(before) or [None])[0]
def crash_dirs():
new = sorted(set(Path(tempfile.gettempdir()).glob("invisible_profile_*")) - before)
new = new_profiles(before)
return crash_report_dirs(new[0] if new else None, windows)
started_at = time.time()
@@ -1842,18 +1886,20 @@ def run_seed(binary: str, seed: int, work: Path, name: str | None = None, idle:
pgid = _group_of(pidfile)
watcher = CrashWatcher(crash_dirs, ignore=already)
watcher.start()
with (contextlib.nullcontext() if (bare or crash_with is not None) else sync_playwright()) as p:
with (contextlib.nullcontext() if crash_with is not None else sync_playwright()) as p:
if crash_with is not None:
crash_the_parent(root_pid, server.process, crash_with) # the recorder's own test: the browser is up, its parent is sent a fatal signal
elif bare:
notified = wait_for_notification(profile_prefs_reader(before)) # nothing drives the bare browser: the launch the idle one was
elif idle:
# Run 44988820319: with no client and no page the notification was never recorded in 120 s on either system (no window, so no
# `sessionstore-windows-restored` for the policy to start from) and the launch had a crash reporter: the idle launch has the page of a launch, and nothing else.
browser = p.firefox.connect(server.ws_endpoint)
context = browser.new_context()
context.new_page()
glean = wait_for_glean_of_launch(profile_now, seed, launch_name)
if glean:
problems.append(glean)
notified = wait_for_notification(profile_prefs_reader(before))
save_datareporting(profile_now(), datareporting_dir, launch_name, seed)
context.close()
browser.close()
else:
@@ -1863,6 +1909,9 @@ def run_seed(binary: str, seed: int, work: Path, name: str | None = None, idle:
context.set_default_navigation_timeout(profile_p4.TIMEOUT_MS)
profile_p4.install_route(context)
page = context.new_page()
glean = wait_for_glean_of_launch(profile_now, seed, launch_name)
if glean:
problems.append(glean)
journey = profile_p4.Journey(context, page, origin_a, origin_o)
journey_site.STATE.begin_walk()
for n, (name, method) in enumerate(JOURNEY, 1):
@@ -1874,6 +1923,7 @@ def run_seed(binary: str, seed: int, work: Path, name: str | None = None, idle:
except Exception as exc: # noqa: BLE001 - recorded, and a step that failed is a problem of the run
steps.append({"n": n, "name": name, "ok": False, "error": str(exc).strip().splitlines()[0][:300] if str(exc).strip() else repr(exc)})
steps.append(geolocation_step(browser, geo_origin, GEO_DECLARED, len(JOURNEY) + 1))
save_datareporting(profile_now(), datareporting_dir, launch_name, seed)
context.close()
browser.close()
# The close: the run ends with the exit of the browser, and the trace is read after it.
@@ -1891,10 +1941,8 @@ def run_seed(binary: str, seed: int, work: Path, name: str | None = None, idle:
if idle:
result["idle"] = {"notified": notified, "shortcut_changes": diff_snapshots(shortcuts_before, snapshot_places(places)) if places else None}
watched, watcher = watcher.stop(), None
if bare:
result["bare"] = {"notified": notified, "crash": crash_evidence(watched, result, core_info(seed_work, binary) if not windows else None)}
bad, left = end_of_launch(close["root_returncode"], windows, seed, name or "measured", result.get("lifecycle"), binary, log, watched,
seed_work if bare else None, started_at)
bad, left = end_of_launch(close["root_returncode"], windows, seed, launch_name, result.get("lifecycle"), binary, log, watched,
started_at)
problems += bad
result["exit_problems"] = bad
if left:
@@ -1922,17 +1970,17 @@ def run_seed(binary: str, seed: int, work: Path, name: str | None = None, idle:
return result
def end_of_launch(code, windows: bool, seed: int, launch: str, lifecycle, binary: str, log, watched: dict, bare_dir, started_at: float, folders=None, run=subprocess.run) -> tuple:
def end_of_launch(code, windows: bool, seed: int, launch: str, lifecycle, binary: str, log, watched: dict, started_at: float, folders=None, run=subprocess.run) -> tuple:
"""How a launch ended, as the verdict reads it: `(problems, evidence)`. A root exit code other than 0 (or not seen) is a problem that names the seed, the launch and the
code (`crash.exit_problem`), and so is a process of the kind parent that the lifecycle says did not exit 0 when the root said nothing of it (Windows: the core's spawn
may be a launcher). A launch with a problem keeps what it left (`crash.collect`): the strace tail and the fatal signal lines, the cores through gdb with the build ids
(the folders of the job's core pattern, and the launch's own when it moved there: the bare one), the `.extra` and the minidump names the watcher read. A launch that
(the folders of the job's core pattern), the `.extra` and the minidump names the watcher read. A launch that
ended with 0 has none and costs nothing."""
bad = [x for x in [crash.exit_problem(code, windows, seed=seed, launch=launch)] + crash.parent_exit_problems(lifecycle, code, seed=seed, launch=launch) if x]
if not bad:
return [], None
if folders is None:
folders = [] if windows else crash.core_dirs() + ([bare_dir] if bare_dir else [])
folders = [] if windows else crash.core_dirs()
return bad, crash.collect(code, binary, strace_log=None if windows else log, watched=watched, windows=windows, core_folders=folders, since=started_at, run=run)
@@ -1962,20 +2010,6 @@ def crash_the_parent(root_pid: int, process, signum: int, limit_s: float = 60.0,
return pid
#: The crash evidence of the BARE launch (no client, no page: the launch of run 44988820319 that had a crash reporter): where a crash leaves its files.
CRASH_PROCESS = re.compile(r"crashreporter|minidump-analyzer", re.I)
def crash_evidence(watched: dict, fp: dict, core: dict | None = None) -> dict:
"""What the bare launch says about how the browser ended: the exit code or signal of its parent processes (from the lifecycle), every crash reporter or
minidump analyzer process with its command line, the `.dmp` names and `.extra` contents the watcher read, and the core dump if there is one."""
lifecycle = fp.get("lifecycle")
exits = [e["how"] for e in lifecycle or [] if e["event"] == "end" and e["kind"] == "parent"]
procs = [{"kind": p["label"], "argv": p.get("cmd") or p.get("exec")} for p in fp.get("processes", []) if CRASH_PROCESS.search(p["label"])]
return {"parent_exits": exits if lifecycle is not None else None, "root_returncode": (fp.get("close") or {}).get("root_returncode"), "crash_processes": procs,
"files": watched.get("files", []), "scans": watched.get("scans"), "core": core}
def shortcut_places(env=None) -> list:
"""`[(folder, recursive)]` of the places the shortcut code of Windows reads and writes (StartupOSIntegration.sys.mjs, nsWindowsShellService.cpp): the Start menu of the
user and of ProgramData (its Programs below it), the Desktop of the user and the Public one, the pinned taskbar shortcuts of the user (and ImplicitAppShortcuts) and every
@@ -2055,13 +2089,16 @@ def wait_for_notification(read, period=NOTIFY_PERIOD_S, limit_s=NOTIFY_LIMIT_S,
sleep(period)
def new_profiles(before: set) -> list:
"""The profile folders (`invisible_profile_*` of the temp root) that were not there before the launch, in order."""
return sorted(set(Path(tempfile.gettempdir()).glob("invisible_profile_*")) - before)
def profile_prefs_reader(before: set):
"""`read()` for `wait_for_notification`: the prefs.js of the profile the launch made (the `invisible_profile_*` folder of the run's temp root that was not
there before it)."""
root = Path(tempfile.gettempdir())
def read():
for folder in sorted(set(root.glob("invisible_profile_*")) - before):
for folder in new_profiles(before):
try:
return (folder / "prefs.js").read_text(encoding="utf-8", errors="replace")
except OSError:
@@ -2152,10 +2189,11 @@ def keep_crash(fp: dict, launch: str, crash_dir) -> None:
sys.stdout.flush()
def run_engine(binary: str, leg: str, seeds: list, label: str, crash_dir=None) -> dict:
def run_engine(binary: str, leg: str, seeds: list, label: str, crash_dir=None, datareporting_dir=None) -> dict:
"""The footprint document of one engine. A discarded WARM-UP launch first, of the first seed, then every seed's journey, one browser at a time.
Every launch (the warm-up, each seed, the idle and the bare ones) that does not end with 0 is a problem of the run, and what it left is kept in `crash_dir` (`keep_crash`).
Every launch (the warm-up, each seed and the idle one) that does not end with 0 is a problem of the run, and what it left is kept in `crash_dir` (`keep_crash`). The list of the
`datareporting` folder of each launch with a page is saved in `datareporting_dir` (`save_datareporting`).
The warm-up is a control of the experiment and not an excuse: what a machine does the first time it runs an engine (its files scanned, its caches
cold, a first-run behaviour of the engine) is in a launch that is not compared, whose trace is kept in the document (`warmup`) so that what it
@@ -2164,14 +2202,14 @@ def run_engine(binary: str, leg: str, seeds: list, label: str, crash_dir=None) -
work = Path(tempfile.mkdtemp(prefix="ab-host-"))
problems, out_seeds = [], []
try:
warm = run_seed(binary, seeds[0], work, name="warmup")
warm = run_seed(binary, seeds[0], work, name="warmup", datareporting_dir=datareporting_dir)
keep_crash(warm, "warmup", crash_dir)
problems += ["warm-up: %s" % p for p in warm.get("problems", [])]
problems += ["warm-up: seed %d: step %d (%s) failed: %s" % (seeds[0], st["n"], st["name"], st.get("error")) for st in warm["steps"] if not st["ok"]]
print("warm-up (seed %d, discarded): %s; %d host paths" % (seeds[0], json.dumps(warm["kinds"], sort_keys=True), len(warm["files"])))
sys.stdout.flush()
for seed in seeds:
fp = run_seed(binary, seed, work)
fp = run_seed(binary, seed, work, datareporting_dir=datareporting_dir)
keep_crash(fp, "seed%d" % seed, crash_dir)
out_seeds.append(fp)
for step in fp["steps"]:
@@ -2180,23 +2218,33 @@ def run_engine(binary: str, leg: str, seeds: list, label: str, crash_dir=None) -
print("seed %d: %s; %d host paths, %d net entries, %s" % (seed, json.dumps(fp["kinds"], sort_keys=True), len(fp["files"]),
len(fp.get("net") or []), json.dumps(fp.get("ours", {}), sort_keys=True)))
sys.stdout.flush()
idle = run_seed(binary, seeds[0], work, name="idle", idle=True)
idle = run_seed(binary, seeds[0], work, name="idle", idle=True, datareporting_dir=datareporting_dir)
keep_crash(idle, "idle", crash_dir)
problems += ["idle: %s" % p for p in idle.get("problems", [])]
print("idle (seed %d): %s; notification %s" % (seeds[0], json.dumps(idle["kinds"], sort_keys=True), json.dumps((idle.get("idle") or {}).get("notified"))))
sys.stdout.flush()
# The bare launch: the old idle launch (no client, no page), a case of its own that is never compared; what it records is evidence (`crash_evidence`).
bare = run_seed(binary, seeds[0], work, name="bare", bare=True)
keep_crash(bare, "bare", crash_dir)
problems += ["bare: %s" % p for p in bare.get("exit_problems", [])] # the bare launch is never compared, but how its parent ended is red like any other's
print("bare (seed %d, not compared): %s; %s" % (seeds[0], json.dumps(bare["kinds"], sort_keys=True), json.dumps(_bare_summary(bare.get("bare")))))
sys.stdout.flush()
finally:
shutil.rmtree(work, ignore_errors=True)
return {"format": FORMAT, "engine": label, "leg": leg, "platform": sys.platform, "seeds": out_seeds, "warmup": warm, "idle": idle, "bare": bare, "problems": problems,
return {"format": FORMAT, "engine": label, "leg": leg, "platform": sys.platform, "seeds": out_seeds, "warmup": warm, "idle": idle, "problems": problems,
"binary": os.path.basename(os.path.dirname(os.path.realpath(binary)))}
STOCK_NOT_INSTALLED = "the stock Firefox of Playwright is not installed: %s does not exist (the job must run `python -m playwright install firefox`)"
def stock_evidence(seed: dict) -> list:
"""What a stock Firefox that started but did not reach the location provider left, for the log: its processes by kind with their command, and the modules (the
DLLs of the host paths of the trace) the tree loaded, the location ones first. The document (`footprint-stock.json`) has all of it."""
lines = ["stock evidence: processes by kind: %s" % json.dumps(seed.get("kinds", {}), sort_keys=True)]
lines += ["stock evidence: process %s: %s" % (p.get("label"), p.get("cmd") or p.get("exec") or p.get("name")) for p in seed.get("processes", [])]
files = seed.get("files", [])
wanted = location_modules(files)
others = sorted({_base(f).lower() for f in files if f.lower().endswith(".dll")} - {_base(f).lower() for f in wanted})
lines.append("stock evidence: location modules loaded: %s" % (", ".join(_base(f) for f in wanted) or "none"))
lines.append("stock evidence: other modules loaded (%d): %s" % (len(others), ", ".join(others[:150])))
return lines
def run_stock(leg: str) -> dict:
"""The negative control of the geolocation step, Windows only: Playwright's own Firefox (`p.firefox.launch()`, as the fake web's stock control), with
no declared position, the same step, the same trace. It must start the Windows location utility process (`stock_control_problems`). The tree is the
@@ -2211,22 +2259,33 @@ def run_stock(leg: str) -> dict:
def document(result):
return {"format": FORMAT, "engine": "stock", "leg": leg, "platform": sys.platform, "stock": result}
def not_started(reason):
"""The control that never got a Firefox to run: `started` False, so the verdict names this reason and not the provider (run 45121964904: the binary of Playwright
was not installed in the job, and the oracle said that the step does not reach the provider on stock Firefox)."""
return document({"seed": 0, "steps": [], "kinds": {}, "files": [], "ours": {}, "trace": {"source": "etw+audit", "exited": False}, "started": False, "problems": [reason]})
try:
try:
trace.start()
except TraceError as e:
return document({"seed": 0, "steps": [], "kinds": {}, "files": [], "ours": {}, "trace": {"source": "etw+audit", "exited": False},
"problems": ["the trace of a Windows run could not be started (it needs an administrator): %s" % e]})
return not_started("the trace of a Windows run could not be started (it needs an administrator): %s" % e)
geo_origin, stop_geo = start_geo_lab()
try:
with sync_playwright() as p:
exe = p.firefox.executable_path
browser = p.firefox.launch(headless=True)
if not Path(exe).exists():
return not_started(STOCK_NOT_INSTALLED % exe)
try:
browser = p.firefox.launch(headless=True)
except Exception as exc: # noqa: BLE001 - the reason is the verdict's
return not_started("the stock Firefox of Playwright did not start: %s" % (str(exc).strip().splitlines() or [repr(exc)])[0][:300])
try:
steps.append(geolocation_step(browser, geo_origin, None, len(JOURNEY) + 1))
finally:
browser.close()
return document(_seed_result(exe, 0, work, steps, work / "none.log", trace, os.getpid(), True))
result = _seed_result(exe, 0, work, steps, work / "none.log", trace, os.getpid(), True)
result["started"] = True
return document(result)
except TraceError as e:
return document({"seed": 0, "steps": steps, "kinds": {}, "files": [], "ours": {}, "trace": {"exited": False},
"problems": ["the trace of the run could not be taken: %s" % e]})
@@ -2355,14 +2414,20 @@ def run_stock_control(leg: str, out: Path) -> dict | None:
print("=== negative control of the geolocation step: Playwright's own Firefox")
sys.stdout.flush()
rc = run_stock_subprocess(leg, out / "footprint-stock.json")
broken = ["the run of the stock control ended with %s" % rc] if rc != 0 or not (out / "footprint-stock.json").exists() else []
broken = ["the run of the stock control ended with %s (its own output is above)" % rc] if rc != 0 or not (out / "footprint-stock.json").exists() else []
stock = None
if not broken:
stock = read_json(out / "footprint-stock.json")
broken = stock_control_problems(stock)
if broken:
print("\n".join("FAIL " + b for b in broken))
print("BROKEN CONTROL: the geolocation step does not reach the platform provider on stock Firefox; the A/B says nothing")
seed = (stock or {}).get("stock") or {}
if seed and seed.get("started", True) and not location_utility_kinds(seed.get("kinds", {})):
# the claim of the step is kept; the proof that goes with it is what the tree that did start left
print("\n".join(stock_evidence(seed)))
print("BROKEN CONTROL: the geolocation step does not reach the platform provider on stock Firefox; the A/B says nothing")
else:
print("BROKEN CONTROL: the stock control did not run to the end (the reason is above); the A/B says nothing")
return None
print("GEOLOCATION CONTROL: stock Firefox started %s; modules: %s" % (
", ".join(location_utility_kinds(stock["stock"]["kinds"])), ", ".join(location_modules(stock["stock"]["files"])) or "-"))
@@ -2406,12 +2471,14 @@ def ab(candidate: str | None, candidate_seal: Path | None, leg: str, out: Path,
if control["verdict"] != "green":
print("BROKEN CONTROL: the published engine differs from itself on this machine; the A/B says nothing")
return 2
if not candidate:
return 0
# The control of the geolocation step is a control of the laboratory on Playwright's own Firefox and does not depend on a candidate: on Windows it runs after a
# green A/A on every run, a pull request included (run 45121964904, the gate of the series: it ran only with a candidate, and what it said there was never seen on a PR).
if _windows():
stock = run_stock_control(leg, out)
if stock is None:
return 2
if not candidate:
return 0
expected = load_expected(expected_file)
report = judge(first, read_json(out / runs[2][1]), expected=expected, a_a=False, also_68=[again])
write_verdict(out / "diff.json", report, "not-judged.json")
@@ -2485,7 +2552,7 @@ def main(argv=None) -> int:
if args.crash_with:
document = run_crash_probe(args.binary, args.leg, seeds[0], args.label, crash_dir, args.crash_with)
else:
document = run_engine(args.binary, args.leg, seeds, args.label, crash_dir)
document = run_engine(args.binary, args.leg, seeds, args.label, crash_dir, args.out.parent / (args.out.stem + ".datareporting"))
write_json(args.out, document)
return 0
if args.candidate and not args.candidate_seal:
+73 -39
View File
@@ -98,12 +98,6 @@ H3_VISITS = 5
#: The safety nets of a run, in seconds: a launch that does not come back, a run that does not end. Never a verdict.
RUN_TIMEOUT_S = 40 * 60
WAIT_S = 30
#: The pref the engine writes when it has told the user about its data reporting policy: from then on the shutdown sends its pings (TelemetryReportingPolicy.sys.mjs
#: ``_recordNotificationData``), by a background task of the engine that is a process of its own.
NOTIFIED_PREF = "datareporting.policy.dataSubmissionPolicyNotifiedTime"
#: How often the profile's prefs.js is read while the launch waits for it, and the safety net that ends a launch that never gets there (it is not a verdict: the transcript says
#: ``recorded: false`` and the A/A must agree on it).
PREF_POLL_S, PREF_LIMIT_S = 0.5, 120.0
#: How many times a lab is made again when two of its servers share a port number.
MAX_LAB_TRIES = 50
#: Whose categories a transcript holds under each seed.
@@ -1416,13 +1410,16 @@ def run_main(binary: str, seed: int, patch: Any) -> Dict[str, Any]:
trap = start_trap()
watcher = Watcher(match=("firefox", Path(binary).stem.lower())).start()
try:
crash.mark(seed=seed, launch="main")
with launch(binary, seed, lab, patch) as browser:
begin_launch(seed, "main")
session = launch(binary, seed, lab, patch)
with session as browser:
out["journey"] = guarded(lambda: walk_journey(browser, lab))
out.update(glean_ready(session, seed, "main")) # the journey opened its own pages: Glean is born; the rest of the work follows, then the close
out["https"] = {"h2": guarded(lambda: walk_https(browser, lab, "h2", lab.h2, H2_NAME)),
"h1": guarded(lambda: walk_https(browser, lab, "h1", lab.h1, H1_NAME))}
out["h3"] = guarded(lambda: walk_h3(browser, lab))
out["webrtc"] = guarded(lambda: walk_webrtc(browser, lab))
save_datareporting(session, seed, "main")
finally:
watcher.stop()
if trap is not None:
@@ -1476,11 +1473,13 @@ def run_idle(binary: str, seed: int, condition: str, patch: Any) -> Dict[str, An
rounds in a row leave what is not the sentinel unchanged."""
out: Dict[str, Any] = {}
with open_lab(attribute_in=("launch", "idle", "sentinel")) as lab:
crash.mark(seed=seed, launch="idle-" + condition)
with launch(binary, seed, lab, patch) as browser:
begin_launch(seed, "idle-" + condition)
session = launch(binary, seed, lab, patch)
with session as browser:
out["launch"] = lab.norm.walk(launch_data(lab)) # who asks what while the browser starts: the STUN Binding at launch is the core's measurement, not the browser's
lab.rec.set_phase("idle")
page = browser.new_context(ignore_https_errors=True).new_page()
out.update(glean_ready(session, seed, "idle-" + condition)) # Glean is born when a window opens: from here to the close there is the work of the launch
lab.rec.set_phase("sentinel.0")
page.goto("http://%s:%d/s/0" % (PAGE_NAME, lab.site.port), wait_until="load", timeout=60000)
rounds, converged, previous = 0, False, sentinel_signature(lab)
@@ -1494,28 +1493,13 @@ def run_idle(binary: str, seed: int, condition: str, patch: Any) -> Dict[str, An
converged = True
break
previous = now
save_datareporting(session, seed, "idle-" + condition)
out.update(destinations=lab.norm.walk(sentinel_signature(lab)))
if condition == "c2":
out.update(rounds=rounds, converged=converged)
return out
def wait_for_pref(prefs_js: Path, name: str, limit_s: float = PREF_LIMIT_S, period: float = PREF_POLL_S, sleep: Callable[[float], Any] = time.sleep,
now: Callable[[], float] = time.monotonic) -> bool:
"""True when ``user_pref("<name>", ...)`` is in the profile's prefs.js, read again every ``period`` seconds until it is or ``limit_s`` is over. Changes nothing in the profile."""
needle = 'user_pref("%s"' % name
end = now() + limit_s
while True:
try:
if needle in prefs_js.read_text(encoding="utf-8", errors="replace"):
return True
except OSError:
pass
if now() >= end:
return False
sleep(period)
def profile_of(token: Any, find: Optional[Callable[[Any], list]] = None) -> Optional[Path]:
"""The profile folder of a running session: the ``-profile`` argument of its parent process (the one that is not a ``-contentproc``)."""
if find is None:
@@ -1530,6 +1514,43 @@ def profile_of(token: Any, find: Optional[Callable[[Any], list]] = None) -> Opti
return None
#: The label of the run in progress (``run``): the line that names a launch says which engine run it belongs to.
RUN_LABEL = ""
def begin_launch(seed: int, launch_name: str) -> None:
"""Names the launch about to be made for the probe (``crash.mark``) and writes the line that says which launch is alive, and since when: the test that runs this oracle reads the
last one of these lines when the oracle does not end in time, and names the launch it was waiting for (run 45121964904, Windows: a firefox that did not exit held the pipe)."""
crash.mark(seed=seed, launch=launch_name)
print(crash.launch_line(seed, launch_name, RUN_LABEL))
sys.stdout.flush()
def glean_ready(session: Any, seed: int, launch_name: str) -> Dict[str, Any]:
"""Waits (inside the ``with`` of the launch, after a page is open and before the work of the launch) until Glean has initialised, so the close that follows is the one of a
browser that has finished starting: a close before that makes Glean start inside the shutdown, where its ``glean.init`` thread can die with the panic "No database found"
and the parent exits with -11 (Mozilla's race, the same in the retail browser: run 45121964904, the engine 68, Linux, launch ``exit-pings``). Glean is born when a window opens,
so without a page the condition never comes. The condition is read from the host, the engine and its prefs are untouched (``crash.wait_for_glean``). ``{}`` when it is ready;
``{"glean": {"error": ...}}`` when it is not, which ``transcript_errors`` sees and which is red: the launch goes on and is closed all the same (the exit of the ``with``), and what
it saw is kept."""
try:
waited = crash.wait_for_glean(profile_of(session._end_token))
except crash.GleanNotReady as exc:
return {"glean": {"error": "GleanNotReady: %s" % exc}}
print("glean ready after %.1f s (seed %d, launch %s)" % (waited, seed, launch_name))
sys.stdout.flush()
return {}
def save_datareporting(session: Any, seed: int, launch_name: str) -> None:
"""The last thing a launch does before its close: the list of ``<profile>/datareporting/`` goes to the evidence folder of the run (``crash.save_datareporting``), for the next time
a launch of the run dies. It changes nothing about the launch and nothing of what is compared, and a failure of it is not one of the launch."""
try:
crash.save_datareporting(profile_of(session._end_token))
except Exception: # noqa: BLE001 - evidence, never a verdict
pass
def outside_the_lab(lab: Lab, target: str) -> bool:
"""A CONNECT target that is neither the lab's own (loopback, the DoH, a server it runs, the egress endpoints) nor anything it serves: where an exit ping goes."""
import _doh_servers as ds
@@ -1541,30 +1562,40 @@ def outside_the_lab(lab: Lab, target: str) -> bool:
return not (ds.is_loopback(host) or known)
def exit_pings_summary(targets: List[str], recorded: bool, norm: Normalizer, openers: Optional[List[Optional[str]]] = None) -> Dict[str, Any]:
"""What the shutdown of an idle launch sent out of the lab: ``recorded`` (the pref was written, so the engine may send), and the CONNECTs towards names outside the lab, in the
form the proxy was asked them (a name, or an address), how many of each, and in the order they were first asked."""
return dict(connect_summary(targets, norm, openers), recorded=recorded)
def exit_pings_summary(targets: List[str], norm: Normalizer, openers: Optional[List[Optional[str]]] = None) -> Dict[str, Any]:
"""What the shutdown of a launch with a page sent out of the lab: the CONNECTs towards names outside the lab, in the form the proxy was asked them (a name, or an address), how
many of each, and in the order they were first asked."""
return connect_summary(targets, norm, openers)
def run_exit_pings(binary: str, seed: int, patch: Any) -> Dict[str, Any]:
"""An idle launch behind the lab's proxy with no pref changed: it waits until the engine has written ``NOTIFIED_PREF`` to the profile (or ``PREF_LIMIT_S`` is over: then
``recorded`` is false), closes, and records until the tree has exited, the pingsender of the shutdown included (``EndingPlaywright`` returns when the reaper has). What went
to the proxy towards a name outside the lab is the exit pings; the proxy refuses those CONNECTs itself (a SOCKS reply 4, host unreachable: nothing leaves the lab), and a
connection from the browser or from its pingsender that did not go to the proxy is in ``direct``, which is red on either side."""
"""A launch behind the lab's proxy with no pref changed: it opens a context and a page, waits until Glean has initialised, navigates to the sentinel page of the idle launches
until its ``load``, closes, and records until the tree has exited, the pingsender of the shutdown included (``EndingPlaywright`` returns when the reaper has). What went to the proxy towards a name outside the lab is the exit pings; the proxy
refuses those CONNECTs itself (a SOCKS reply 4, host unreachable: nothing leaves the lab), and a connection from the browser or from its pingsender that did not go to the proxy
is in ``direct``, which is red on either side.
The navigation sits between the condition and the close on purpose: the condition says that the database has been written (its file exists), not that the init thread of Glean
has finished, and that thread can still be half-way when the file appears: that is the window of the race. The page's load is real work of the launch after the condition, and
the stage ``exit`` begins after it.
It measures the exit pings of the close of a normal session (one page, Glean initialised). It does not measure the shutdown of a session with no window or one closed in its
first seconds, where Glean is born inside the shutdown: that is the road of Mozilla's race (run 45121964904, the engine 68, Linux), and it is on the list for after the 69, with
the sessions closed in the first seconds."""
from _leaks import Watcher
with open_lab(attribute_in=("exit",)) as lab:
trap = start_trap()
watcher = Watcher(match=("firefox", Path(binary).stem.lower())).start()
recorded = False
try:
crash.mark(seed=seed, launch="exit-pings")
begin_launch(seed, "exit-pings")
session = launch(binary, seed, lab, patch)
with session as browser:
lab.rec.set_phase("exit.wait")
profile = profile_of(session._end_token)
recorded = bool(profile) and wait_for_pref(profile / "prefs.js", NOTIFIED_PREF)
page = browser.new_context(ignore_https_errors=True).new_page()
glean = glean_ready(session, seed, "exit-pings")
lab.rec.set_phase("sentinel.0") # not under ``exit``: what the navigation asks of the proxy is not an exit ping
page.goto("http://%s:%d/s/0" % (PAGE_NAME, lab.site.port), wait_until="load", timeout=60000)
save_datareporting(session, seed, "exit-pings")
lab.rec.set_phase("exit")
lab.rec.set_phase("exit.end")
finally:
@@ -1572,7 +1603,8 @@ def run_exit_pings(binary: str, seed: int, patch: Any) -> Dict[str, Any]:
if trap is not None:
trap.__exit__(None, None, None)
pings = [e for e in lab.rec.of("exit", "connect") if outside_the_lab(lab, e["target"])]
out = exit_pings_summary([e["target"] for e in pings], recorded, lab.norm, [e.get("opener") for e in pings])
out = exit_pings_summary([e["target"] for e in pings], lab.norm, [e.get("opener") for e in pings])
out.update(glean)
out["direct"] = direct_report(lab, watcher, trap)
return out
@@ -1603,6 +1635,8 @@ def run(binary: str, label: str, seeds: Tuple[int, ...], out: Path) -> int:
_lab_egress.install(patch, work)
transcript: Dict[str, Any] = {"format": FORMAT, "label": label, "platform": sys.platform, "seeds": {}}
EVIDENCE.clear()
global RUN_LABEL
RUN_LABEL = label
for index, seed in enumerate(seeds):
print("=== %s: seed %d" % (label, seed))
sys.stdout.flush()
+180 -2
View File
@@ -12,7 +12,7 @@ evidence: run 45030727459 had a firefox-68 parent die with -11 (SIGSEGV) in a no
minidump list. Whatever a collector does not find is SAID (`said`), never left silent.
* `LaunchProbe`: the observer the page and network oracles use. They launch through the wrapper, which keeps the browser's process inside the core's `Connection`;
the probe wraps `Connection.__init__` and `Connection.close` (it reads the code after the close the launch already makes, and a watcher thread of the same
crash folders the host oracle's bare launch reads), so nothing about the launch changes: same environment, same prefs, same durations, same launch count.
crash folders that the host oracle's launches read too), so nothing about the launch changes: same environment, same prefs, same durations, same launch count.
Three more things the probe keeps, in EVERY launch and not only in a bad one:
* what the browser wrote (`stderr/<launch>.txt` in the crash folder): the core reads the browser's stdout and stderr (one pipe) through `ProcessOutput`, one reader for the whole life of
@@ -155,7 +155,7 @@ def parent_exit_problems(lifecycle, root_code, **who) -> list:
# -
# What a crash leaves: the folders, the files, the cores (the bare launch's collectors of scripts/ci_ab_host.py live here and are reused by every launch).
# What a crash leaves: the folders, the files, the cores (the collectors that scripts/ci_ab_host.py and the probe's launches share live here).
def crash_report_dirs(profile_dir, windows: bool) -> list:
"""The folders a crash leaves its `.dmp` and `.extra` in: the profile's `minidumps` and the `Crash Reports/pending` of the user's application data."""
@@ -759,6 +759,184 @@ def mark(**label) -> None:
PROBE.set_label(**label)
#: The file Glean's database writes on its first write, in the profile of a launch (the folder `db` is born when the database is opened, the file at the first write).
GLEAN_DB = Path("datareporting", "glean", "db", "data.safe.bin")
#: A safety net, not a measurement: the file is there at about +8 s in normal sessions, stock and ours (run 43649596941).
GLEAN_LIMIT_S = 60.0
class GleanNotReady(Exception):
"""Glean had not initialised (no database file in the profile) when the launch was to close."""
def wait_for_glean(profile: Path | None, limit_s: float = GLEAN_LIMIT_S, period: float = 0.25, sleep=time.sleep, now=time.monotonic) -> float:
"""The seconds waited until `GLEAN_DB` exists in `profile`, read again every `period` seconds; `GleanNotReady` when `limit_s` is over or the profile is not known.
Why: a session that closes before Glean has initialised normally makes Glean start inside the shutdown, where its `glean.init` thread can die with the panic "No database
found" and the parent exits with -11 (Mozilla's race, the same in the retail browser; the network A/A, Linux, run 45121964904). The oracles close only after this. It only
reads: nothing is written in the profile, and no preference of the browser changes."""
if profile is None:
raise GleanNotReady("Glean did not initialise in %g s: no %s in the profile of the launch: the profile of the launch is not known (the close would make it start inside the "
"shutdown, where it can crash: run 45121964904)" % (limit_s, GLEAN_DB.as_posix()))
target = Path(profile) / GLEAN_DB
start = now()
while not target.is_file():
waited = now() - start
if waited >= limit_s:
raise GleanNotReady("Glean did not initialise in %g s: no %s in the profile %s (the close would make it start inside the shutdown, where it can crash: run 45121964904)"
% (limit_s, GLEAN_DB.as_posix(), profile))
sleep(period)
return now() - start
#: Where a profile keeps what Glean and the data reporting policy write; its listing before the close is kept with the evidence of the launch (`save_datareporting`).
DATAREPORTING_DIR = "datareporting"
def datareporting_listing(profile) -> list:
"""The lines of the list of `<profile>/datareporting/`: `<path relative to it><TAB><size in bytes>` (a folder ends with `/` and has `-`), sorted. A line that starts with `# `
says what could not be read: the list never raises."""
if profile is None:
return ["# the profile of the launch is not known"]
root = Path(profile) / DATAREPORTING_DIR
if not root.is_dir():
return ["# %s is not a folder in the profile %s" % (DATAREPORTING_DIR, profile)]
rows, problems = [], []
for folder, names, files in os.walk(root, onerror=lambda e: problems.append("# cannot read %s: %s" % (getattr(e, "filename", "?"), e))):
base = Path(folder)
for name in names:
rows.append("%s/\t-" % (base / name).relative_to(root).as_posix())
for name in files:
path = base / name
try:
size = str(path.stat().st_size)
except OSError as exc:
size = "?"
problems.append("# cannot read the size of %s: %s" % (path.relative_to(root).as_posix(), exc))
rows.append("%s\t%s" % (path.relative_to(root).as_posix(), size))
return problems + sorted(rows)
def save_datareporting(profile) -> str | None:
"""Writes the list of `<profile>/datareporting/` of the launch the probe sees now, to `<crash dir>/datareporting/<NN>-<seed>-<launch>.tsv` (NN: the number of the launch, the
one of its file in `stderr/`), and returns the path as the evidence names it. None when no probe is installed or it has no folder. What it could not read is in the file; it
never raises. It is evidence for the next time a launch dies: it is not in the leaves that are compared."""
probe = PROBE
if probe is None or probe.crash_dir is None:
return None
try:
with probe._lock:
records = list(probe.records)
number = getattr(records[-1], "n", len(records)) if records else 0
name = "%02d-%s.tsv" % (number, _safe("-".join(str(v) for v in probe.label.values()) or "launch"))
folder = probe.crash_dir / DATAREPORTING_DIR
folder.mkdir(parents=True, exist_ok=True)
head = ["# launch %d: %s" % (number, ", ".join("%s %s" % kv for kv in probe.label.items()) or "not named"), "# path (relative to datareporting/)<TAB>size in bytes"]
(folder / name).write_text("\n".join(head + datareporting_listing(profile)) + "\n", encoding="utf-8", newline="\n")
return "%s/%s/%s" % (probe.crash_dir.name, DATAREPORTING_DIR, name)
except Exception: # noqa: BLE001 - the evidence never breaks a launch
return None
#: The line an oracle writes when it begins a launch (`launch_line`), and what reads it back (`last_launch`): the process that runs the oracle names, when the oracle does not end in
#: time, the launch that was alive.
LAUNCH_LINE = re.compile(r"^=== launch (?P<launch>\S+) seed (?P<seed>-?\d+) of (?P<label>.*?) began at (?P<at>\S+)\s*$", re.M)
def launch_line(seed, launch: str, label: str, at=None) -> str:
"""`=== launch <launch> seed <seed> of <label> began at <iso, UTC>`: what an oracle prints when `mark` names a launch."""
import datetime
at = at or datetime.datetime.now(datetime.timezone.utc)
return "=== launch %s seed %s of %s began at %s" % (launch, seed, label or "?", at.isoformat(timespec="seconds"))
def last_launch(text: str, now=None) -> dict | None:
"""The last launch line of `text` as {launch, seed, label, at, alive_s} (alive_s: seconds from `at` to `now`, None when `at` does not read), or None when there is none."""
import datetime
found = None
for found in LAUNCH_LINE.finditer(text or ""):
pass
if found is None:
return None
item = found.groupdict()
try:
began = datetime.datetime.fromisoformat(item["at"])
item["alive_s"] = ((now or datetime.datetime.now(datetime.timezone.utc)) - began).total_seconds()
except (ValueError, TypeError):
item["alive_s"] = None
return item
def kill_tree(pid: int) -> None:
"""Kills `pid` and everything that descends from it. With psutil the descendants are listed first (a parent that dies hides its children) and all are killed; without it
Windows has `taskkill /T /F` and Linux the process group (the child was started in its own session, `run_tree`)."""
try:
import psutil
except ImportError:
psutil = None
if psutil is not None:
try:
root = psutil.Process(pid)
victims = root.children(recursive=True) + [root]
except psutil.NoSuchProcess:
victims = []
for victim in victims:
with contextlib.suppress(psutil.Error):
victim.kill()
elif sys.platform == "win32":
subprocess.run(["taskkill", "/PID", str(pid), "/T", "/F"], capture_output=True, check=False)
if sys.platform != "win32":
import signal
with contextlib.suppress(OSError):
os.killpg(pid, signal.SIGKILL) # the group of the child, which is its own (start_new_session)
class TreeRun:
"""What `run_tree` saw: the code (None when the time ran out), the text of stdout and stderr, how long it ran and the launch line the oracle wrote last."""
def __init__(self, returncode, stdout: str, stderr: str, seconds: float, timed_out: bool) -> None:
self.returncode, self.stdout, self.stderr, self.seconds, self.timed_out = returncode, stdout, stderr, seconds, timed_out
self.launch = last_launch(stdout)
def timeout_message(self, who: str, limit_s: float) -> str:
"""The red of a run that did not end: the launch that was alive and for how long."""
if self.launch is None:
alive = "no launch had begun"
else:
alive = "the launch %s of seed %s (%s) was alive for %s s" % (self.launch["launch"], self.launch["seed"], self.launch["label"],
"%d" % self.launch["alive_s"] if self.launch["alive_s"] is not None else "?")
return "%s did not end within %d s: %s; its tree was killed" % (who, limit_s, alive)
def run_tree(command, out_dir, timeout_s: float, env=None, cwd=None, poll: float = 0.2) -> TreeRun:
"""Runs `command` with its output in FILES under `out_dir` (never a pipe), and at `timeout_s` kills the whole tree.
Why not `subprocess.run(capture_output=True, timeout=...)`: at the timeout it kills the child alone. The firefox that the child launched holds the write end of the pipe,
`communicate()` does not return until it exits, and the test went on to a pytest timeout 120 s later (run 45121964904, Windows, job.log 546-557). With files nothing waits
for a grandchild, and `kill_tree` ends them all."""
out_dir = Path(out_dir)
out_dir.mkdir(parents=True, exist_ok=True)
out_path, err_path = out_dir / "run-tree.stdout", out_dir / "run-tree.stderr"
start = time.monotonic()
with open(out_path, "wb") as out, open(err_path, "wb") as err:
extra = {"start_new_session": True} if sys.platform != "win32" else {}
child = subprocess.Popen(list(command), stdout=out, stderr=err, stdin=subprocess.DEVNULL, env=env, cwd=cwd, **extra)
timed_out = False
while child.poll() is None:
if time.monotonic() - start >= timeout_s:
timed_out = True
kill_tree(child.pid)
break
time.sleep(poll)
child.wait()
seconds = time.monotonic() - start
read = lambda path: path.read_bytes().decode("utf-8", "replace") # noqa: E731
return TreeRun(None if timed_out else child.returncode, read(out_path), read(err_path), seconds, timed_out)
def read_exits(path) -> dict | None:
"""The document a probe wrote, or None when there is none."""
try:
+3 -4
View File
@@ -47,7 +47,7 @@ def _require_strace_can_trace(tmp: Path) -> None:
def _stand_in(binary: str, tree: Path, log: Path, pidfile: Path, syscalls: str = _SYSCALLS,
timestamps: bool = False, fd_paths: bool = False, network: bool = False, exit_status: bool = False,
core_dir: Path | None = None, cores: bool = False) -> str:
cores: bool = False) -> str:
"""A copy of the engine's directory made of links, whose executable runs
the real one under strace, in the engine's place.
@@ -66,8 +66,7 @@ def _stand_in(binary: str, tree: Path, log: Path, pidfile: Path, syscalls: str =
``fd_paths`` adds ``-y`` (scripts/ci_ab_host.py reads the paths the tree touched, and knows a socket by its inode);
``network`` adds the network calls to ``syscalls`` (scripts/ci_ab_host.py reads the netlink sockets and the public destinations);
``cores`` lets the tree dump core (``ulimit -c unlimited``) and changes nothing else: the working directory stays the launcher's, so the paths the trace reads
are the same, and where the kernel writes the core is the job's ``kernel.core_pattern``; ``core_dir`` does that and moves the working directory to that folder, where a
plain ``core`` pattern writes (the bare launch of scripts/ci_ab_host.py)."""
are the same, and where the kernel writes the core is the job's ``kernel.core_pattern`` (scripts/ci_ab_host.py)."""
if network:
syscalls = syscalls + "," + _NET_SYSCALLS
real = Path(os.path.realpath(binary))
@@ -76,7 +75,7 @@ def _stand_in(binary: str, tree: Path, log: Path, pidfile: Path, syscalls: str =
if entry.name != real.name:
(tree / entry.name).symlink_to(entry)
script = tree / real.name
cores_script = ("ulimit -c unlimited\ncd %s\n" % core_dir) if core_dir else ("ulimit -c unlimited\n" if cores else "")
cores_script = "ulimit -c unlimited\n" if cores else ""
script.write_text(
"#!/bin/sh\n"
"echo $$ > %s\n"
+220 -68
View File
@@ -747,19 +747,19 @@ def with_warmup(fp, kinds=None, files=None, touched_by=None, spawned_by=None, se
def test_an_engine_run_makes_its_warm_up_launch_first_of_the_first_seed_then_its_measured_ones_and_the_idle_launch_last(tmp_path, monkeypatch):
calls = []
def fake_run_seed(binary, seed, work, name=None, idle=False, bare=False):
def fake_run_seed(binary, seed, work, name=None, idle=False, datareporting_dir=None):
calls.append((seed, name, idle))
return seed_footprint(seed)
monkeypatch.setattr(host, "run_seed", fake_run_seed)
monkeypatch.setattr(host.os.path, "realpath", lambda p: p)
doc = host.run_engine("ff", "linux-x86_64", [11, 12], "firefox-68")
assert calls == [(11, "warmup", False), (11, None, False), (12, None, False), (11, "idle", True), (11, "bare", False)]
assert doc["warmup"]["seed"] == 11 and [s["seed"] for s in doc["seeds"]] == [11, 12] and doc["idle"]["seed"] == 11 and doc["bare"]["seed"] == 11 and doc["problems"] == []
assert calls == [(11, "warmup", False), (11, None, False), (12, None, False), (11, "idle", True)], "no bare launch"
assert doc["warmup"]["seed"] == 11 and [s["seed"] for s in doc["seeds"]] == [11, 12] and doc["idle"]["seed"] == 11 and "bare" not in doc and doc["problems"] == []
def test_a_warm_up_that_failed_is_red_in_the_document_like_a_measured_launch(monkeypatch):
def fake_run_seed(binary, seed, work, name=None, idle=False, bare=False):
def fake_run_seed(binary, seed, work, name=None, idle=False, datareporting_dir=None):
fp = seed_footprint(seed)
if name == "warmup":
fp["problems"] = ["the file trace did not see the end canary file of the oracle"]
@@ -1282,7 +1282,7 @@ def test_the_journey_has_the_geolocation_step_after_its_own_steps_in_a_run():
source = Path(host.__file__).read_text(encoding="utf-8")
run_seed = source[source.index("def run_seed("):source.index("def _wait_for_tree_exit(")]
assert run_seed.index("for n, (name, method) in enumerate(JOURNEY, 1)") < run_seed.index("geolocation_step(browser, geo_origin, GEO_DECLARED, len(JOURNEY) + 1)")
assert run_seed.index("geolocation_step(") < run_seed.rindex("browser.close()")
assert run_seed.index("geolocation_step(") < run_seed.rindex("context.close()") # the close of the page launch
def test_the_lab_page_of_the_step_is_served_by_the_oracle_itself():
@@ -1297,7 +1297,7 @@ def test_the_lab_page_of_the_step_is_served_by_the_oracle_itself():
stop()
def test_a_windows_ab_runs_the_stock_control_after_the_candidate_and_before_the_verdict_and_a_broken_one_is_exit_2(tmp_path, monkeypatch):
def test_a_windows_ab_runs_the_stock_control_after_the_a_a_and_before_the_verdict_and_a_broken_one_is_exit_2(tmp_path, monkeypatch):
order = []
pub = fake_engine(tmp_path / "fetch", "pub")
cand = fake_engine(tmp_path / "checkout", "cand")
@@ -1332,7 +1332,121 @@ def test_a_windows_ab_runs_the_stock_control_after_the_candidate_and_before_the_
assert order[-2:] == [("stock", "windows-x86_64"), ("judge", "a-b")]
order.clear()
assert host.ab(None, None, "windows-x86_64", tmp_path / "o3", "firefox-68", [11]) == 0
assert ("stock", "windows-x86_64") not in order, "the A/A has no candidate: no control of the geolocation step"
assert order == [("run", "firefox-68"), ("run", "firefox-68 again"), ("judge", "a-a"), ("stock", "windows-x86_64")], "no candidate: the control of the geolocation step runs all the same"
def test_a_windows_run_with_no_candidate_runs_the_stock_control_after_a_green_a_a_and_a_broken_one_is_red(tmp_path, monkeypatch):
"""Run 45121964904 (the gate of the series): the control of the geolocation step ran only with a candidate, so a pull request never ran it."""
pub = fake_engine(tmp_path / "fetch", "pub")
monkeypatch.setattr(host, "_windows", lambda: True)
monkeypatch.setattr(host.oracle, "fetch_published", lambda tag, work: (pub, "pub-seal"))
monkeypatch.setattr(host, "print_report", lambda *a, **k: None)
seen = []
monkeypatch.setattr(host, "run_subprocess", lambda exe, seal, leg, out, label, seeds: host.write_json(out, footprint(label, platform="win32")) or 0)
monkeypatch.setattr(host, "judge", lambda a, b, **kw: {"verdict": "green", "problems": [], "not_judged": {}})
monkeypatch.setattr(host, "run_stock_control", lambda leg, out: seen.append(leg) or {"stock": True})
assert host.ab(None, None, "windows-x86_64", tmp_path / "o1", "firefox-68", [11]) == 0 and seen == ["windows-x86_64"]
monkeypatch.setattr(host, "run_stock_control", lambda leg, out: None)
assert host.ab(None, None, "windows-x86_64", tmp_path / "o2", "firefox-68", [11]) == 2, "a broken control is red with no candidate too"
monkeypatch.setattr(host, "_windows", lambda: False)
seen.clear()
monkeypatch.setattr(host, "run_stock_control", lambda leg, out: seen.append(leg) or {"stock": True})
assert host.ab(None, None, "linux-x86_64", tmp_path / "o3", "firefox-68", [11]) == 0 and seen == [], "Linux has no Windows location provider: no control"
def fake_playwright(monkeypatch, executable, launch=None):
"""`playwright.sync_api.sync_playwright` whose Firefox has this executable path (and, if given, this launch)."""
import types
from contextlib import contextmanager
class Firefox:
executable_path = str(executable)
def launch(self, **kw):
return launch()
@contextmanager
def sync_playwright():
yield types.SimpleNamespace(firefox=Firefox())
module = types.ModuleType("playwright.sync_api")
module.sync_playwright = sync_playwright
monkeypatch.setitem(sys.modules, "playwright", types.ModuleType("playwright"))
monkeypatch.setitem(sys.modules, "playwright.sync_api", module)
class FakeTrace:
def __init__(self, work):
pass
def start(self):
pass
def cleanup(self):
pass
def test_a_stock_firefox_that_is_not_installed_is_said_by_name_and_is_not_blamed_on_the_platform_provider(tmp_path, monkeypatch, capsys):
"""Run 45121964904: `Executable doesn't exist at ...firefox-1532...firefox.exe` ended the stock run and the oracle printed that the step does not reach the provider."""
missing = tmp_path / "ms-playwright" / "firefox-1532" / "firefox" / "firefox.exe"
fake_playwright(monkeypatch, missing)
monkeypatch.setattr(host, "WindowsTrace", FakeTrace)
monkeypatch.setattr(host, "start_geo_lab", lambda: ("http://127.0.0.1:1", lambda: None))
document = host.run_stock("windows-x86_64")
text = "\n".join(host.stock_control_problems(document))
assert "is not installed" in text and str(missing) in text and "python -m playwright install firefox" in text
assert "does not reach the platform provider" not in text and "did not start the Windows location utility" not in text
# and the control says the same on the output
out = tmp_path / "o"
out.mkdir()
monkeypatch.setattr(host, "run_stock_subprocess", lambda leg, path: host.write_json(path, document) or 0)
assert host.run_stock_control("windows-x86_64", out) is None
printed = capsys.readouterr().out
assert "is not installed" in printed and "does not reach the platform provider" not in printed and "BROKEN CONTROL" in printed
def test_a_stock_firefox_that_does_not_launch_says_why_and_one_that_ran_without_the_provider_leaves_its_evidence(tmp_path, monkeypatch, capsys):
exe = tmp_path / "firefox.exe"
exe.write_text("x")
def boom():
raise RuntimeError("BrowserType.launch: Timeout 180000ms exceeded.\nCall log: ...")
fake_playwright(monkeypatch, exe, launch=boom)
monkeypatch.setattr(host, "WindowsTrace", FakeTrace)
monkeypatch.setattr(host, "start_geo_lab", lambda: ("http://127.0.0.1:1", lambda: None))
problems = host.stock_control_problems(host.run_stock("windows-x86_64"))
assert problems == ["stock control: the stock Firefox of Playwright did not start: BrowserType.launch: Timeout 180000ms exceeded."]
# started, no provider: the claim is the same as ever, and the log has what the tree did
stock = a_stock(WIN_KINDS, files=["c:\\windows\\system32\\kernel32.dll", "c:\\windows\\system32\\ntdll.dll"])
stock["stock"]["processes"] = [{"label": "parent", "cmd": "firefox.exe -no-remote"}]
out = tmp_path / "o"
out.mkdir()
monkeypatch.setattr(host, "run_stock_subprocess", lambda leg, path: host.write_json(path, stock) or 0)
assert host.run_stock_control("windows-x86_64", out) is None
printed = capsys.readouterr().out
assert "did not start the Windows location utility process" in printed and "BROKEN CONTROL: the geolocation step does not reach the platform provider" in printed
assert "stock evidence: process parent: firefox.exe -no-remote" in printed and "kernel32.dll" in printed and "location modules loaded: none" in printed
def test_the_windows_host_job_installs_playwright_s_firefox_with_the_python_of_the_tests_before_the_oracle_runs():
"""Run 45121964904: the job did not install it and `run_stock` found no executable."""
root = Path(__file__).resolve().parents[1]
text = (root / ".github" / "workflows" / "e2e.yml").read_text(encoding="utf-8")
start = text.index("\n e2e-host-windows:\n")
job = text[start:text.index("\n # ``The page oracle``", start)]
assert "runs-on: windows-2022" in job and "-m pytest tests/test_ab_host_e2e.py" in job
install = job.index("python -m playwright install firefox")
assert job.index("actions/setup-python") < job.index('python -m pip install "playwright==') < install < job.index("-m pytest tests/test_ab_host_e2e.py")
assert job.count("playwright install") == 1
diagnostic = job[job.index(" - name: The state of the Windows location service"):]
diagnostic = diagnostic[:diagnostic.index(" - name: The leg ran")]
assert "if: always()" in diagnostic and "shell: pwsh" in diagnostic and "Get-Service lfsvc" in diagnostic and "Format-List" in diagnostic
for key in ("HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\CapabilityAccessManager\\ConsentStore\\location",
"HKCU:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\CapabilityAccessManager\\ConsentStore\\location",
"HKLM:\\SYSTEM\\CurrentControlSet\\Services\\lfsvc\\Service\\Configuration"):
assert key in diagnostic
assert not re.search(r"Set-|New-|Remove-|Start-Service|Stop-Service", diagnostic), "read only"
def test_the_stock_command_is_for_windows_only(tmp_path, monkeypatch, capsys):
@@ -1677,7 +1791,7 @@ def test_a_creator_pid_that_windows_reused_before_the_launch_is_not_in_its_tree(
# -
# The bare launch (no client, no page; never compared) and the evidence of how a browser ended and what a crash leaves; the creates of the host.
# The evidence of how a browser ended and what a crash leaves; the creates of the host.
def test_the_crash_files_are_read_when_they_appear_a_dmp_by_its_name_and_an_extra_by_its_content(tmp_path):
folder = tmp_path / "minidumps"
@@ -1686,14 +1800,14 @@ def test_the_crash_files_are_read_when_they_appear_a_dmp_by_its_name_and_an_extr
(folder / "a1b2.extra").write_text('{"MozCrashReason": "MOZ_CRASH(shutdown hang)", "ShutdownProgress": "profile-change-teardown", "CrashType": "SIGSEGV"}', encoding="utf-8")
(folder / "notes.txt").write_text("not a crash file", encoding="utf-8")
seen = {}
host.scan_crash_files([folder, tmp_path / "missing"], seen)
crash.scan_crash_files([folder, tmp_path / "missing"], seen)
files = sorted(seen.values(), key=lambda f: f["name"])
assert [f["name"] for f in files] == ["a1b2.dmp", "a1b2.extra"] and files[0]["size"] == 104 and "content" not in files[0]
assert "MozCrashReason" in files[1]["content"] and "ShutdownProgress" in files[1]["content"]
host.scan_crash_files([folder], seen)
crash.scan_crash_files([folder], seen)
assert "MozCrashReason" in seen[str(folder / "a1b2.extra")]["content"], "a file that did not change is not read again"
(folder / "a1b2.extra").write_text('{"MozCrashReason": "later", "more": "a file seen half written is read again when its size changes"}', encoding="utf-8")
host.scan_crash_files([folder], seen)
crash.scan_crash_files([folder], seen)
assert "later" in seen[str(folder / "a1b2.extra")]["content"]
@@ -1705,15 +1819,15 @@ def test_a_crash_file_seen_by_its_name_before_its_content_is_written_is_read_aga
extra = folder / "x.extra"
seen = {}
extra.write_bytes(b"")
host.scan_crash_files([folder], seen)
crash.scan_crash_files([folder], seen)
assert seen[str(extra)]["content"] == "" and seen[str(extra)]["size"] == 0
extra.write_bytes(b'{"CrashType": "SIG')
host.scan_crash_files([folder], seen)
crash.scan_crash_files([folder], seen)
assert seen[str(extra)]["content"] == '{"CrashType": "SIG'
extra.write_bytes(b'{"CrashType": "SIGSEGV"}')
host.scan_crash_files([folder], seen)
crash.scan_crash_files([folder], seen)
assert seen[str(extra)]["content"] == '{"CrashType": "SIGSEGV"}' and seen[str(extra)]["size"] == len(b'{"CrashType": "SIGSEGV"}')
host.scan_crash_files([folder], seen)
crash.scan_crash_files([folder], seen)
assert len(seen) == 1, "a complete file is one entry"
@@ -1741,20 +1855,6 @@ def test_the_crash_folders_are_the_profiles_minidumps_and_the_pending_reports_of
assert lin == [tmp_path / "home" / ".config" / "mozilla" / "firefox" / "Crash Reports" / "pending", tmp_path / "home" / ".mozilla" / "firefox" / "Crash Reports" / "pending"]
def test_the_crash_evidence_says_how_the_parent_ended_who_the_crash_reporters_are_and_what_files_the_crash_left():
fp = {"lifecycle": [{"event": "start", "kind": "parent", "line": 0, "how": ""}, {"event": "end", "kind": "crashreporter", "line": 5, "how": "exited 0"},
{"event": "end", "kind": "parent", "line": 9, "how": "killed by SIGSEGV"}],
"processes": [{"label": "parent", "exec": "firefox -profile /tmp/p"}, {"label": "crashreporter", "exec": "crashreporter --ping-cleanup /srv/lab/r/.config/mozilla/firefox/Crash Reports /tmp/p"},
{"label": "minidump-analyzer", "exec": "minidump-analyzer /tmp/p/minidumps/x.dmp"}], "close": {"root_returncode": -11}}
got = host.crash_evidence({"files": [{"name": "x.dmp", "size": 5}], "scans": 7}, fp, {"core_pattern": "core", "cores": ["core.123"], "backtraces": {"core.123": "#0 0x0 in ?? ()"}})
assert got["parent_exits"] == ["killed by SIGSEGV"] and got["root_returncode"] == -11
assert [p["kind"] for p in got["crash_processes"]] == ["crashreporter", "minidump-analyzer"] and "--ping-cleanup" in got["crash_processes"][0]["argv"]
assert got["files"] == [{"name": "x.dmp", "size": 5}] and got["core"]["cores"] == ["core.123"]
summary = host._bare_summary({"notified": {"observed": False}, "crash": got})
assert summary["parent_exits"] == ["killed by SIGSEGV"] and summary["dump_files"] == ["x.dmp"] and summary["cores"] == ["core.123"]
assert host.crash_evidence({}, {"processes": []})["parent_exits"] is None, "no lifecycle: it is not said that the parent ended well"
def test_a_linux_core_is_found_where_the_launch_ran_and_its_backtrace_is_asked_of_gdb(tmp_path, monkeypatch):
(tmp_path / "core.4242").write_bytes(b"\x7fELF")
(tmp_path / "other.txt").write_text("x", encoding="utf-8")
@@ -1764,15 +1864,15 @@ def test_a_linux_core_is_found_where_the_launch_ran_and_its_backtrace_is_asked_o
calls = []
monkeypatch.setattr(host.shutil, "which", lambda name: "/usr/bin/gdb")
got = host.core_info(tmp_path, "/e/firefox/firefox", run=lambda argv, **kw: calls.append(argv) or Done())
got = crash.core_info(tmp_path, "/e/firefox/firefox", run=lambda argv, **kw: calls.append(argv) or Done())
assert got["cores"] == ["core.4242"] and "ShutdownXPCOM" in got["backtraces"]["core.4242"]
assert calls == [["/usr/bin/gdb", "-batch", "-ex", "bt", "/e/firefox/firefox", str(tmp_path / "core.4242")]]
monkeypatch.setattr(host.shutil, "which", lambda name: None)
assert host.core_info(tmp_path, "/e/firefox/firefox")["backtraces"] == {"core.4242": "gdb is not installed"}
assert host.core_info(tmp_path / "empty-nowhere", "x")["cores"] == []
assert crash.core_info(tmp_path, "/e/firefox/firefox")["backtraces"] == {"core.4242": "gdb is not installed"}
assert crash.core_info(tmp_path / "empty-nowhere", "x")["cores"] == []
def test_the_stand_in_allows_core_dumps_in_every_launch_and_only_the_bare_one_moves_to_its_own_folder(tmp_path, monkeypatch):
def test_the_stand_in_allows_core_dumps_in_every_launch_and_a_folder_asked_for_is_where_it_moves_to(tmp_path, monkeypatch):
import _strace_stand_in as stand_in
class Help:
@@ -1787,9 +1887,6 @@ def test_the_stand_in_allows_core_dumps_in_every_launch_and_only_the_bare_one_mo
assert "ulimit" not in plain.read_text(encoding="utf-8"), "the font tests' stand-in is as it was"
every = Path(stand_in._stand_in(str(real), tmp_path / "t3", tmp_path / "l3", tmp_path / "p3", cores=True)).read_text(encoding="utf-8")
assert "ulimit -c unlimited\nexec " in every and "\ncd " not in every, "a measured launch may dump core and its working directory is the launcher's (the paths the trace reads are the same)"
cores = Path(stand_in._stand_in(str(real), tmp_path / "t2", tmp_path / "l2", tmp_path / "p2", core_dir=tmp_path / "cores"))
text = cores.read_text(encoding="utf-8")
assert "ulimit -c unlimited\ncd %s\nexec " % (tmp_path / "cores") in text
def create_event(pid, name, options):
@@ -1810,19 +1907,6 @@ def test_a_path_the_tree_asked_the_system_to_make_is_told_from_one_it_only_opene
{"path": "d:\\lab\\r\\old.tmp", "kinds": ["parent"], "how": ["OVERWRITE_IF"]}, {"path": "d:\\lab\\r\\x.lnk", "kinds": ["tab"], "how": ["CREATE"]}]
def test_the_report_carries_the_bare_launch_without_comparing_it(capsys):
a = footprint()
a["bare"] = {"seed": 11, "kinds": {"parent": 1, "crashreporter": 1}, "bare": {"notified": {"observed": False}, "crash": {
"parent_exits": ["exited 0"], "root_returncode": 0, "crash_processes": [{"kind": "crashreporter", "argv": "crashreporter --ping-cleanup /x /y"}], "files": [], "core": None}}}
b = footprint("again")
b["bare"] = {"seed": 11, "kinds": {"parent": 1}, "bare": {"notified": {"observed": False}, "crash": {"parent_exits": ["exited 0"], "root_returncode": 0, "crash_processes": [], "files": []}}}
report = judge(a, b, a_a=True)
assert report["verdict"] == "green", "the bare launch is evidence, not a leaf"
assert report["bare"]["A"]["crash_processes"] == [("crashreporter", "crashreporter --ping-cleanup /x /y")] and report["bare"]["B"]["crash_processes"] == []
host.print_report(report, "firefox-68", "firefox-68 again")
assert "BARE (no client, no page; not compared) firefox-68:" in capsys.readouterr().out
# -
# The places of the shortcut code, before and after the idle launch (Windows): the direct proof of whether the engine left a shortcut or a log on the host.
@@ -1894,11 +1978,11 @@ def test_a_launch_that_left_nothing_says_so_and_the_report_carries_the_summary_l
def with_system(fp, per_launch):
"""`per_launch`: {seed or "warmup"/"idle": [paths]}: the paths added to that launch's files."""
fp = copy.deepcopy(fp)
for key in ("warmup", "idle", "bare"):
for key in ("warmup", "idle"):
if key in per_launch and not fp.get(key):
fp[key] = seed_footprint(11)
launches = {s["seed"]: s for s in fp["seeds"]}
launches.update({k: fp[k] for k in ("warmup", "idle", "bare") if fp.get(k)})
launches.update({k: fp[k] for k in ("warmup", "idle") if fp.get(k)})
for key, add in per_launch.items():
launch = launches[key]
launch["files"] = sorted(set(launch["files"]) | set(add))
@@ -2100,35 +2184,25 @@ def test_a_fake_launch_that_died_with_minus_11_is_a_red_line_with_the_evidence_a
log = tmp_path / "strace.log"
log.write_text(CRASH_LOG, encoding="utf-8")
watched = {"files": [{"name": "u.extra", "dir": "d", "size": 9, "content": '{"CrashType": "SIGSEGV"}'}], "scans": 2}
problems, left = host.end_of_launch(-11, False, 11, "measured", [], "/e/firefox", log, watched, None, 0.0, folders=[], run=Run({}))
problems, left = host.end_of_launch(-11, False, 11, "measured", [], "/e/firefox", log, watched, 0.0, folders=[], run=Run({}))
assert problems == ["the parent process exited with code -11 (SIGSEGV): seed 11, launch measured"]
assert left["exit"] == {"code": -11, "text": "-11 (SIGSEGV)"} and left["strace"]["signals"][0][1].startswith("100 --- SIGSEGV")
assert left["crash_files"]["extra"][0]["name"] == "u.extra"
assert host.end_of_launch(0, False, 11, "measured", [], "/e/firefox", log, watched, None, 0.0, folders=[]) == ([], None)
problems, left = host.end_of_launch(None, False, 11, "idle", [], "/e/firefox", log, {}, None, 0.0, folders=[], run=Run({}))
assert host.end_of_launch(0, False, 11, "measured", [], "/e/firefox", log, watched, 0.0, folders=[]) == ([], None)
problems, left = host.end_of_launch(None, False, 11, "idle", [], "/e/firefox", log, {}, 0.0, folders=[], run=Run({}))
assert "not seen" in problems[0] and left is not None
windows, kept = host.end_of_launch(3221225477, True, 11, "bare", [], "D:\\e\\firefox.exe", None, {"files": []}, None, 0.0, run=Run({}))
assert "0xC0000005 (access violation)" in windows[0] and "launch bare" in windows[0] and kept["strace"] is None
def test_the_bare_launch_looks_in_its_own_folder_for_a_core_as_well(tmp_path, monkeypatch):
seen = {}
monkeypatch.setattr(host.crash, "collect", lambda code, binary, **kw: seen.update(kw) or {"exit": {}, "said": []})
monkeypatch.setattr(host.crash, "core_dirs", lambda *a, **k: [Path("/job/cores")])
host.end_of_launch(-11, False, 1, "bare", [], "b", tmp_path / "l", {}, tmp_path, 5.0)
assert seen["core_folders"] == [Path("/job/cores"), tmp_path] and seen["since"] == 5.0
windows, kept = host.end_of_launch(3221225477, True, 11, "idle", [], "D:\\e\\firefox.exe", None, {"files": []}, 0.0, run=Run({}))
assert "0xC0000005 (access violation)" in windows[0] and "launch idle" in windows[0] and kept["strace"] is None
def test_a_launch_that_did_not_end_with_0_is_in_the_verdict_of_the_run_named_by_side_seed_and_launch_whatever_launch_it_was(monkeypatch, tmp_path):
bad = crash.exit_problem(-11, False, seed=12, launch="measured")
def fake_run_seed(binary, seed, work, name=None, idle=False, bare=False):
def fake_run_seed(binary, seed, work, name=None, idle=False, datareporting_dir=None):
fp = seed_footprint(seed)
if name is None and seed == 12:
fp["problems"] = [bad]
fp["crash"] = {"exit": {"code": -11, "text": "-11 (SIGSEGV)"}, "said": ["no core file written"], "strace": None, "cores": None, "crash_files": {"dmp": [], "extra": []}}
if name == "bare":
fp["exit_problems"] = [crash.exit_problem(-6, False, seed=11, launch="bare")]
if name == "idle":
fp["problems"] = [crash.exit_problem(1, False, seed=11, launch="idle")]
return fp
@@ -2137,7 +2211,6 @@ def test_a_launch_that_did_not_end_with_0_is_in_the_verdict_of_the_run_named_by_
monkeypatch.setattr(host.os.path, "realpath", lambda p: p)
doc = host.run_engine("ff", "linux-x86_64", [11, 12], "firefox-68", tmp_path / "x.crash")
assert "idle: the parent process exited with code 1: seed 11, launch idle" in doc["problems"]
assert "bare: the parent process exited with code -6 (SIGABRT): seed 11, launch bare" in doc["problems"]
assert (tmp_path / "x.crash" / "seed12" / "crash.json").is_file()
assert (tmp_path / "x.crash" / "seed12" / "said.txt").read_text(encoding="utf-8") == "no core file written\n"
other = footprint()
@@ -2716,3 +2789,82 @@ def test_a_staged_ancestor_that_only_one_run_read_is_still_a_difference(monkeypa
a = with_files(footprint(), ["/srv/ci/work/_temp"], {"/srv/ci/work/_temp": ["forkserver"]}, {"/srv/ci/work/_temp": ["readlink"]})
report = judge(a, footprint("candidate"), expected=[])
assert report["verdict"] == "red" and {d["leaf"] for d in report["differences"]} == {"file./srv/ci/work/_temp"}
# -
# Glean: a launch with a page waits for it right after its first page, and the list of `datareporting` is saved before the close.
def test_the_wait_for_glean_reads_the_profile_of_the_launch_says_how_long_and_a_condition_not_met_is_a_problem_that_does_not_stop_the_launch(monkeypatch, capsys):
seen = []
class GleanNotReady(Exception):
pass
# `raising=False`: the names are the contract of scripts/ci_crash_evidence.py (`wait_for_glean(profile)` and `GleanNotReady`), written by the other half of this work
monkeypatch.setattr(host.crash, "GleanNotReady", GleanNotReady, raising=False)
monkeypatch.setattr(host.crash, "wait_for_glean", lambda profile: seen.append(profile) or 1.5, raising=False)
profile = Path("/tmp/invisible_profile_x")
assert host.wait_for_glean_of_launch(lambda: profile, 11, "measured") is None and seen == [profile]
assert "glean ready after 1.5 s (seed 11, launch measured)" in capsys.readouterr().out
def not_ready(profile):
raise GleanNotReady("Glean did not initialise in 60 s: no data.safe.bin")
monkeypatch.setattr(host.crash, "wait_for_glean", not_ready, raising=False)
assert host.wait_for_glean_of_launch(lambda: profile, 12, "idle") == "Glean did not initialise in 60 s: no data.safe.bin"
assert "glean NOT ready (seed 12, launch idle)" in capsys.readouterr().out
def test_run_seed_waits_for_glean_after_the_first_page_and_before_the_work_of_the_launch_in_the_measured_and_the_idle_launch_and_has_no_bare_launch():
source = inspect.getsource(host.run_seed)
measured = source[source.index(" else:\n browser = p.firefox.connect"):]
idle = source[source.index(" elif idle:"):source.index(" else:\n browser = p.firefox.connect")]
assert measured.index("page = context.new_page()") < measured.index("wait_for_glean_of_launch(") < measured.index("journey = profile_p4.Journey(") < measured.index("for n, (name, method) in enumerate(JOURNEY, 1)")
assert idle.index("context.new_page()") < idle.index("wait_for_glean_of_launch(") < idle.index("wait_for_notification(profile_prefs_reader(before))")
for part in (idle, measured):
assert part.index("save_datareporting(") < part.index("context.close()"), "the list is taken just before the close"
assert source.count("wait_for_glean_of_launch(") == 2
assert "bare" not in source and "bare" not in inspect.signature(host.run_seed).parameters
assert "close_after_glean" not in inspect.getsource(host), "the wait is not made at the close any more"
assert not [name for name in dir(host) if "bare" in name.lower()], "no bare launch is left in the oracle"
def test_the_list_of_datareporting_is_relative_sorted_with_sizes_and_a_read_error_is_a_line_of_the_file(tmp_path, monkeypatch):
profile = tmp_path / "invisible_profile_x"
(profile / "datareporting" / "glean" / "db").mkdir(parents=True)
(profile / "datareporting" / "glean" / "db" / "data.safe.bin").write_bytes(b"x" * 7)
(profile / "datareporting" / "state.json").write_text("{}", encoding="utf-8")
(profile / "datareporting" / "glean" / "pending_pings").mkdir()
assert host.datareporting_listing(profile) == "path\tsize\nglean/db/data.safe.bin\t7\nstate.json\t2\n"
host.save_datareporting(profile, tmp_path / "out" / "dr", "measured", 11)
assert (tmp_path / "out" / "dr" / "measured-11.tsv").read_text(encoding="utf-8") == "path\tsize\nglean/db/data.safe.bin\t7\nstate.json\t2\n"
assert host.datareporting_listing(tmp_path / "nowhere").startswith("path\tsize\n# error\t")
assert host.datareporting_listing(None) == "path\tsize\n# error\tthe profile of the launch was not found\n"
real = Path.stat
def broken(self, *a, **k):
if self.name == "state.json":
raise PermissionError(13, "Permission denied")
return real(self, *a, **k)
monkeypatch.setattr(Path, "stat", broken)
assert "# error\t" in host.datareporting_listing(profile) and "state.json" in host.datareporting_listing(profile)
host.save_datareporting(profile, None, "idle", 11) # no folder: nothing happens
def test_an_engine_run_hands_the_datareporting_folder_to_every_launch_and_the_run_command_puts_it_next_to_the_footprint(tmp_path, monkeypatch):
got = []
def fake_run_seed(binary, seed, work, name=None, idle=False, datareporting_dir=None):
got.append((name, datareporting_dir))
return seed_footprint(seed)
monkeypatch.setattr(host, "run_seed", fake_run_seed)
monkeypatch.setattr(host.os.path, "realpath", lambda p: p)
host.run_engine("ff", "linux-x86_64", [11], "firefox-68", None, tmp_path / "dr")
assert got == [("warmup", tmp_path / "dr"), (None, tmp_path / "dr"), ("idle", tmp_path / "dr")]
seen = {}
monkeypatch.setattr(host, "run_engine", lambda binary, leg, seeds, label, crash_dir=None, datareporting_dir=None: seen.update(crash=crash_dir, dr=datareporting_dir) or {"format": host.FORMAT, "problems": []})
(tmp_path / "o").mkdir()
host.main(["run", "ff", "--leg", "linux-x86_64", "--out", str(tmp_path / "o" / "footprint-68.json"), "--seeds", "11"])
assert seen["dr"] == tmp_path / "o" / "footprint-68.datareporting" and seen["crash"] == tmp_path / "o" / "footprint-68.crash"
+11 -11
View File
@@ -1,6 +1,6 @@
"""The host oracle judges a path by ONE rule, in the A/A and in the A/B, on Linux and on Windows, over every host path (the system modules and the shortcut inventory included):
red if and only if a path is in ALL the measured launches (the warm-up and the seeds) of one engine and in NO launch of the other (its long idle and bare launches included);
red if and only if a path is in ALL the measured launches (the warm-up and the seeds) of one engine and in NO launch of the other (its long idle launch included);
everything else that differs is listed, not judged (`report["not_judged"]`, the file `not-judged[-a-a].json` of the artifact), and the paths that are in at least half of the
launches of one engine and in none of the other's are marked `watch`.
@@ -42,7 +42,7 @@ def rebuild(doc: dict) -> dict:
launch["inventory"] = launch["inventory"] or []
launches[name] = launch
out = {"format": host.FORMAT, "engine": doc["engine"], "platform": doc["platform"], "problems": [], "seeds": [launches[n] for n in names if n.startswith("s")]}
out.update({k: launches[k] for k in ("warmup", "idle", "bare") if k in launches})
out.update({k: launches[k] for k in ("warmup", "idle") if k in launches})
return out
@@ -93,11 +93,11 @@ def test_the_declared_difference_of_a_real_linux_run_is_still_declared_and_not_r
# -
# The rule on built footprints: six measured launches (the warm-up and five seeds), then the idle and the bare launch.
# The rule on built footprints: six measured launches (the warm-up and five seeds), then the idle launch.
SEEDS = (1, 2, 3, 4, 5)
MEASURED = ("warmup",) + tuple("s%d" % s for s in SEEDS)
LONG = ("idle", "bare")
LONG = ("idle",)
KINDS = {"parent": 1, "tab/isForBrowser": 2, "gpu": 1}
BASE = ["/etc/fonts/fonts.conf", "/etc/hosts", "/usr/lib/x86_64-linux-gnu/libc.so.6"]
P = "/var/lib/probe/the-path"
@@ -162,9 +162,9 @@ def test_a_path_in_every_measured_launch_of_one_engine_and_in_one_launch_of_the_
def test_the_long_launches_of_the_other_engine_count_as_a_launch_of_it_and_a_path_only_a_long_launch_has_is_only_listed():
assert judge(built("A", only_in(MEASURED)), built("B", {"bare": [P]}), a_a=True)["verdict"] == "green"
assert judge(built("A", only_in(MEASURED)), built("B", {"idle": [P]}), a_a=True)["verdict"] == "green"
report = judge(built("A"), built("B", only_in(LONG)), a_a=True)
assert report["verdict"] == "green" and listed(report)[P]["B"] == {"measured": [0, 6], "long": [2, 2]}
assert report["verdict"] == "green" and listed(report)[P]["B"] == {"measured": [0, 6], "long": [1, 1]}
assert judge(built("A", only_in(LONG)), built("B"), a_a=True)["verdict"] == "green", "what the long launches of one engine alone do is not red either"
@@ -278,13 +278,13 @@ def test_the_not_judged_file_has_the_fields_of_each_entry(tmp_path, monkeypatch)
"footprint-68-again.json": built("firefox-68 again", only_in(MEASURED[1:5]), platform="win32"), "footprint-candidate.json": built("candidate", platform="win32")}
assert run_ab(tmp_path, monkeypatch, docs) == 0
a_a = json.loads((tmp_path / "o" / "not-judged-a-a.json").read_text(encoding="utf-8"))
assert a_a["launches"] == {"A": {"measured": 6, "long": 2}, "B": {"measured": 6, "long": 2}}
assert a_a["paths"] == [{"path": P, "watch": False, "A": {"measured": [5, 6], "long": [0, 2]}, "B": {"measured": [4, 6], "long": [0, 2]},
assert a_a["launches"] == {"A": {"measured": 6, "long": 1}, "B": {"measured": 6, "long": 1}}
assert a_a["paths"] == [{"path": P, "watch": False, "A": {"measured": [5, 6], "long": [0, 1]}, "B": {"measured": [4, 6], "long": [0, 1]},
"touched_by": {"A": ["rdd"], "B": ["parent"]}}]
a_b = json.loads((tmp_path / "o" / "not-judged.json").read_text(encoding="utf-8"))
assert a_b["launches"] == {"A": {"measured": 12, "long": 4}, "B": {"measured": 6, "long": 2}}, "the 68 is its two runs"
assert a_b["paths"] == [{"path": P, "watch": True, "A": {"measured": [9, 12], "long": [0, 4]}, "B": {"measured": [0, 6], "long": [0, 2]},
"touched_by": {"A": ["parent", "rdd"], "B": []}}], "9 of the 16 launches of the 68 and none of the candidate's"
assert a_b["launches"] == {"A": {"measured": 12, "long": 2}, "B": {"measured": 6, "long": 1}}, "the 68 is its two runs"
assert a_b["paths"] == [{"path": P, "watch": True, "A": {"measured": [9, 12], "long": [0, 2]}, "B": {"measured": [0, 6], "long": [0, 1]},
"touched_by": {"A": ["parent", "rdd"], "B": []}}], "9 of the 14 launches of the 68 and none of the candidate's"
def test_the_log_prints_the_not_judged_list_with_the_watched_paths_before_the_others(capsys):
+342 -53
View File
@@ -1174,30 +1174,6 @@ def _socks_connect_name(proxy_port: int, host: str, port: int):
TELEMETRY = "incoming.telemetry.mozilla.org:443"
def test_the_pref_wait_reads_the_profile_every_period_changes_nothing_and_ends_at_the_limit_with_not_recorded(tmp_path):
prefs = tmp_path / "prefs.js"
clock = {"t": 0.0}
polls = []
def sleep(period):
polls.append((clock["t"], period))
clock["t"] += period
if len(polls) == 3: # the engine writes the pref on the third look
prefs.write_text('user_pref("browser.startup.homepage_override.mstone", "x");\nuser_pref("%s", 1700000000000);\n' % ab.NOTIFIED_PREF, encoding="utf-8")
assert ab.wait_for_pref(prefs, ab.NOTIFIED_PREF, limit_s=120.0, period=0.5, sleep=sleep, now=lambda: clock["t"]) is True
assert polls == [(0.0, 0.5), (0.5, 0.5), (1.0, 0.5)], "the file did not exist for two looks (no file is not an error), and it is read every half second"
before = prefs.read_bytes()
clock["t"] = 0.0
assert ab.wait_for_pref(prefs, ab.NOTIFIED_PREF, sleep=lambda p: None, now=lambda: clock["t"]) is True and prefs.read_bytes() == before, "reading changes nothing"
other = tmp_path / "other" / "prefs.js"
other.parent.mkdir()
other.write_text('user_pref("datareporting.policy.firstRunURL", "x");\n', encoding="utf-8")
ticks = iter(range(0, 1000, 30))
assert ab.wait_for_pref(other, ab.NOTIFIED_PREF, limit_s=120.0, sleep=lambda p: None, now=lambda: float(next(ticks))) is False, "a launch that never gets there ends at the limit: not recorded"
assert ab.PREF_LIMIT_S == 120.0 and ab.PREF_POLL_S == 0.5
def test_the_profile_of_a_session_is_the_argument_of_its_parent_process_and_not_a_content_process():
class Proc:
def __init__(self, cmd):
@@ -1237,9 +1213,9 @@ def test_a_connect_target_is_outside_the_lab_when_it_is_neither_loopback_nor_a_s
assert not ab.outside_the_lab(lab, "127.0.0.1:%d" % lab.h1.port)
def _with_pings(t, targets, recorded=True, direct=None):
def _with_pings(t, targets, direct=None):
norm = ab.Normalizer({})
body = ab.exit_pings_summary(targets, recorded, norm)
body = ab.exit_pings_summary(targets, norm)
body["direct"] = direct if direct is not None else {"witness_tcp": [], "witness_udp": [], "watcher": [], "doh_direct": [], "resolver_trap": [], "blind": []}
for seed in t["seeds"].values():
seed["idle"]["exit_pings"] = copy.deepcopy(body)
@@ -1248,7 +1224,7 @@ def _with_pings(t, targets, recorded=True, direct=None):
def test_the_exit_pings_are_the_connects_to_the_proxy_towards_the_telemetry_host_and_they_are_compared_strictly():
three = [TELEMETRY] * 3
assert ab.exit_pings_summary(three, True, ab.Normalizer({})) == {"order": [TELEMETRY], "counts": {TELEMETRY: 3}, "recorded": True}
assert ab.exit_pings_summary(three, ab.Normalizer({})) == {"order": [TELEMETRY], "counts": {TELEMETRY: 3}}
green = compare(_with_pings(transcript("a"), three), _with_pings(transcript("b"), three))
assert green["verdict"] == "green"
# a different number
@@ -1257,11 +1233,11 @@ def test_the_exit_pings_are_the_connects_to_the_proxy_towards_the_telemetry_host
# a different form: the address instead of the name
form = compare(_with_pings(transcript("a"), three), _with_pings(transcript("b"), ["162.159.207.1:443"] * 3))
assert form["verdict"] == "red" and any("/idle/exit_pings/order/0" in d["path"] and d["b"] == "162.159.207.1:443" for d in form["differences"])
# recorded on one side only
one_sided = compare(_with_pings(transcript("a"), three), _with_pings(transcript("b"), [], recorded=False))
assert one_sided["verdict"] == "red" and any(d["path"].endswith("/idle/exit_pings/recorded") and d["a"] is True and d["b"] is False for d in one_sided["differences"])
# not recorded on both: the A/A agrees and the shutdown sent nothing
both = compare(_with_pings(transcript("a"), [], recorded=False), _with_pings(transcript("b"), [], recorded=False))
# no ping on one side only
one_sided = compare(_with_pings(transcript("a"), three), _with_pings(transcript("b"), []))
assert one_sided["verdict"] == "red" and any(d["path"].endswith("/idle/exit_pings/counts/" + TELEMETRY) for d in one_sided["differences"])
# no ping on both: the A/A agrees
both = compare(_with_pings(transcript("a"), []), _with_pings(transcript("b"), []))
assert both["verdict"] == "green"
# a ping that did not go to the proxy is red on either side, and when both do it
leak = {"witness_tcp": [], "witness_udp": [], "watcher": ["tcp firefox -> 162.159.207.1:443"], "doh_direct": [], "resolver_trap": [], "blind": []}
@@ -1270,7 +1246,7 @@ def test_the_exit_pings_are_the_connects_to_the_proxy_towards_the_telemetry_host
assert compare(_with_pings(transcript("a"), three, direct=leak), _with_pings(transcript("b"), three, direct=leak))["verdict"] == "red"
def test_the_exit_launch_waits_for_the_pref_then_closes_and_records_what_the_proxy_was_asked_until_the_tree_has_exited(tmp_path, monkeypatch):
def test_the_exit_launch_opens_a_page_waits_for_glean_then_closes_and_records_what_the_proxy_was_asked_until_the_tree_has_exited(tmp_path, monkeypatch):
import _leaks
profile = tmp_path / "profile"
@@ -1291,6 +1267,26 @@ def test_the_exit_launch_waits_for_the_pref_then_closes_and_records_what_the_pro
def stop(self):
order.append("watcher stopped")
class Page:
def __init__(self, lab):
self.lab = lab
def goto(self, url, **kwargs):
order.append("goto %s in stage %s %s" % (url.rsplit("/", 2)[-2:], self.lab.rec.phase, sorted(kwargs.items())))
self.lab.rec.event("connect", target="198.51.100.77:80") # what the navigation asks of the proxy: it is not an exit ping
class Browser:
def __init__(self, lab):
self.lab = lab
def new_context(self, **kwargs):
order.append("context %s" % sorted(kwargs.items()))
return self
def new_page(self):
order.append("page")
return Page(self.lab)
class Session:
_end_token = "token"
@@ -1299,8 +1295,7 @@ def test_the_exit_launch_waits_for_the_pref_then_closes_and_records_what_the_pro
def __enter__(self):
order.append("launched")
(profile / "prefs.js").write_text('user_pref("%s", 1);\n' % ab.NOTIFIED_PREF, encoding="utf-8")
return object()
return Browser(self.lab)
def __exit__(self, *exc):
order.append("closing in stage " + self.lab.rec.phase)
@@ -1315,32 +1310,32 @@ def test_the_exit_launch_waits_for_the_pref_then_closes_and_records_what_the_pro
monkeypatch.setattr(ab, "start_trap", lambda: None)
monkeypatch.setattr(ab, "profile_of", lambda token, find=None: profile)
monkeypatch.setattr(ab, "launch", lambda binary, seed, lab, patch: Session(lab))
monkeypatch.setattr(ab.crash, "wait_for_glean", lambda p, *a, **k: order.append("glean waited") or 8.0)
monkeypatch.setattr(ab, "save_datareporting", lambda profile, seed, launch_name: order.append("datareporting listed"))
out = ab.run_exit_pings("/ff/firefox", 11, object())
assert out["recorded"] is True and out["counts"] == {TELEMETRY: 3} and out["order"] == [TELEMETRY], "the DoH connection of the lab is not an exit ping"
assert out["direct"]["watcher"] == [] and out["direct"]["blind"] == []
assert order == ["launched", "closing in stage exit", "tree exited", "watcher stopped"]
# no pref ever: the launch ends at the limit and says so
(profile / "prefs.js").unlink()
monkeypatch.setattr(ab, "PREF_LIMIT_S", 0.0)
monkeypatch.setattr(ab, "wait_for_pref", lambda *a, **k: False)
assert out["counts"] == {TELEMETRY: 3} and out["order"] == [TELEMETRY], "the DoH connection of the lab is not an exit ping"
assert "recorded" not in out and out["direct"]["watcher"] == [] and out["direct"]["blind"] == []
assert order == ["launched", "context [('ignore_https_errors', True)]", "page", "glean waited", "goto ['s', '0'] in stage sentinel.0 [('timeout', 60000), ('wait_until', 'load')]",
"datareporting listed", "closing in stage exit", "tree exited", "watcher stopped"], "page, Glean, a navigation to its load, then the close: the navigation is not an exit ping"
# Glean never initialised: red, and the launch closes all the same
order.clear()
monkeypatch.setattr(ab.crash, "wait_for_glean", lambda p, *a, **k: (_ for _ in ()).throw(ab.crash.GleanNotReady("Glean did not initialise in 60 s")))
late = ab.run_exit_pings("/ff/firefox", 11, object())
assert late["glean"]["error"].startswith("GleanNotReady: Glean did not initialise in 60 s") and "tree exited" in order
assert ab.transcript_errors({"11": {"idle": {"exit_pings": late}}}) == ["seeds/11/idle/exit_pings/glean/error"]
class Quiet(Session):
def __enter__(self):
return object()
def __exit__(self, *exc):
return False
monkeypatch.setattr(ab, "launch", lambda binary, seed, lab, patch: Quiet(lab))
silent = ab.run_exit_pings("/ff/firefox", 11, object())
assert silent["recorded"] is False and silent["counts"] == {} and silent["order"] == []
def test_no_wait_for_the_policy_pref_is_left_in_the_network_oracle():
assert not any(hasattr(ab, name) for name in ("wait_for_pref", "PREF_POLL_S", "PREF_LIMIT_S", "NOTIFIED_PREF")), "the exit launch waits for Glean and for nothing else"
text = (ROOT / "scripts" / "ci_ab_network.py").read_text(encoding="utf-8")
assert "recorded=" not in text and 'recorded"' not in text and "wait_for_pref" not in text
def test_the_idle_category_of_the_first_seed_holds_the_exit_pings(monkeypatch):
monkeypatch.setattr(ab, "run_idle", lambda binary, seed, condition, patch: {"destinations": {}})
monkeypatch.setattr(ab, "run_exit_pings", lambda binary, seed, patch: {"recorded": True})
monkeypatch.setattr(ab, "run_exit_pings", lambda binary, seed, patch: {"counts": {}})
monkeypatch.setattr(ab, "run_main", lambda binary, seed, patch: {"journey": {}})
assert ab.walk_seed("ff", 11, True, object())["idle"] == {"c1": {"destinations": {}}, "c2": {"destinations": {}}, "exit_pings": {"recorded": True}}
assert ab.walk_seed("ff", 11, True, object())["idle"] == {"c1": {"destinations": {}}, "c2": {"destinations": {}}, "exit_pings": {"counts": {}}}
assert "idle" not in ab.walk_seed("ff", 12, False, object())
@@ -1783,3 +1778,297 @@ def test_the_engine_run_is_given_a_folder_for_what_a_launch_that_died_leaves_bes
monkeypatch.setattr(ab.subprocess, "run", lambda cmd, env, timeout: seen.append(env.get(crash.CRASH_DIR_ENV)) or Done())
assert ab.run_engine("ff", None, "firefox-68-again", (0,), tmp_path / "out" / "transcript-68-again.json") == 0
assert seen == [str(tmp_path / "out" / "transcript-68-again.crash")]
# ----------------------------------------------------------------------------------------------------------------- Glean before the close
def _glean_fakes(monkeypatch, tmp_path, waiter):
"""`run_idle` with a fake lab, a fake launch and a fake `wait_for_glean`: what happened, in order, is the list returned."""
import contextlib
order = []
profile = tmp_path / "profile"
class Page:
def goto(self, *a, **k):
order.append("goto")
def evaluate(self, *a, **k):
return None
class Context:
def new_page(self):
order.append("new_page")
return Page()
class Browser:
def new_context(self, **k):
return Context()
class Session:
_end_token = "token"
def __enter__(self):
order.append("launched")
return Browser()
def __exit__(self, *exc):
order.append("closed")
return False
class Lab:
class rec:
phase = ""
@staticmethod
def set_phase(name):
order.append("phase " + name)
class norm:
@staticmethod
def walk(x):
return x
class site:
port = 1
h1 = h2 = None
@contextlib.contextmanager
def open_lab(**k):
yield Lab
monkeypatch.setattr(ab, "open_lab", open_lab)
monkeypatch.setattr(ab, "launch", lambda binary, seed, lab, patch: Session())
monkeypatch.setattr(ab, "launch_data", lambda lab: {})
monkeypatch.setattr(ab, "sentinel_signature", lambda lab: {"connects": [], "dns": [], "udp": []})
monkeypatch.setattr(ab, "profile_of", lambda token, find=None: order.append("profile of " + token) or profile)
monkeypatch.setattr(ab.crash, "wait_for_glean", lambda p, *a, **k: order.append("glean waited in %s" % p.name) or waiter(p))
monkeypatch.setattr(ab, "save_datareporting", lambda session, seed, launch_name: order.append("datareporting listed"))
return order
@pytest.mark.parametrize("condition", ["c1", "c2"])
def test_an_idle_launch_waits_for_glean_before_it_closes_and_prints_when_it_was_ready(tmp_path, monkeypatch, capsys, condition):
order = _glean_fakes(monkeypatch, tmp_path, lambda p: 8.25)
out = ab.run_idle("/ff/firefox", 11, condition, object())
assert order.index("new_page") < order.index("glean waited in profile") < order.index("goto"), "Glean is born when a window opens: the condition comes after the page and before the work"
assert order[-2:] == ["datareporting listed", "closed"] and order.count("closed") == 1, "the list of datareporting is the last thing before the close"
assert "profile of token" in order and order.index("profile of token") < order.index("glean waited in profile")
assert "glean ready after 8.2 s (seed 11, launch idle-%s)" % condition in capsys.readouterr().out
assert ab.transcript_errors({"11": out}) == [] and "glean" not in out
def test_a_launch_whose_glean_never_initialised_is_a_red_error_of_the_transcript_and_the_browser_still_closes(tmp_path, monkeypatch):
def never(profile):
raise ab.crash.GleanNotReady("Glean did not initialise in 60 s: no data.safe.bin in the profile %s" % profile)
order = _glean_fakes(monkeypatch, tmp_path, never)
out = ab.run_idle("/ff/firefox", 11, "c1", object())
assert order[-1] == "closed" and order.count("closed") == 1 and "goto" in order, "the launch goes on and the close is the same: the exit of the `with`"
assert out["glean"]["error"].startswith("GleanNotReady: Glean did not initialise in 60 s"), out
assert "destinations" in out, "what the launch saw is kept: only the verdict is red"
assert ab.transcript_errors({"11": out}) == ["seeds/11/glean/error"]
def test_a_launch_without_a_known_profile_is_red_the_same_way_for_glean(tmp_path, monkeypatch):
real = ab.crash.wait_for_glean
order = _glean_fakes(monkeypatch, tmp_path, lambda p: 0.0)
monkeypatch.setattr(ab, "profile_of", lambda token, find=None: None)
monkeypatch.setattr(ab.crash, "wait_for_glean", real) # the real one: it knows what to say of a launch without a profile
out = ab.run_idle("/ff/firefox", 11, "c1", object())
assert "the profile of the launch is not known" in out["glean"]["error"] and order[-1] == "closed"
def test_the_main_launch_waits_for_glean_after_the_journey_and_before_the_rest_of_its_work(tmp_path, monkeypatch):
import _leaks
order = _glean_fakes(monkeypatch, tmp_path, lambda p: 3.0)
class Watcher:
def __init__(self, match=()):
pass
def start(self):
return self
def stop(self):
pass
monkeypatch.setattr(_leaks, "Watcher", Watcher)
monkeypatch.setattr(ab, "start_trap", lambda: None)
monkeypatch.setattr(ab, "direct_report", lambda lab, watcher, trap: {})
monkeypatch.setattr(ab, "wire_evidence", lambda lab: {})
for walker in ("walk_journey", "walk_h3", "walk_webrtc"):
monkeypatch.setattr(ab, walker, lambda *a, _w=walker, **k: order.append(_w) or {})
monkeypatch.setattr(ab, "walk_https", lambda *a, **k: order.append("walk_https") or {})
out = ab.run_main("/ff/firefox", 11, object())
assert order.index("walk_journey") < order.index("glean waited in profile") < order.index("walk_https") < order.index("walk_webrtc"), order
assert order[-2:] == ["datareporting listed", "closed"], order
assert "glean" not in out and "journey" in out
# ----------------------------------------------------------------------------------------------------------------- the guard that kills the whole tree
#: The oracle of the test: it writes the line of a launch, starts a grandchild that inherits its stdout and sleeps, and sleeps itself. The grandchild is the firefox that holds the pipe.
_TREE_CHILD = '''
import subprocess, sys, time
sys.path.insert(0, sys.argv[2])
import ci_crash_evidence as crash
print(crash.launch_line(11, "exit-pings", "firefox-68-again"), flush=True)
grandchild = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"])
open(sys.argv[1], "w").write(str(grandchild.pid))
print("the grandchild is alive", flush=True)
time.sleep(60)
'''
def _alive(pid):
import psutil
return psutil.pid_exists(pid) and psutil.Process(pid).status() != psutil.STATUS_ZOMBIE
def _wait_gone(pid, seconds=10.0):
end = time.monotonic() + seconds
while _alive(pid) and time.monotonic() < end:
time.sleep(0.1)
return not _alive(pid)
def _kill_if_alive(pid):
import psutil
try:
psutil.Process(pid).kill()
except psutil.Error:
pass
def _tree_command(tmp_path):
pidfile = tmp_path / "grandchild.pid"
return [sys.executable, "-u", "-c", _TREE_CHILD, str(pidfile), str(ROOT / "scripts")], pidfile
def test_the_old_guard_leaves_the_grandchild_alive_and_on_windows_does_not_even_return_at_the_timeout(tmp_path):
"""The defect, shown: `subprocess.run(capture_output=True, timeout=...)` kills the child alone. The grandchild lives; on Windows `run` then waits for the pipe it holds
(run 45121964904, Windows, job.log 546-557), here until we kill it."""
import subprocess
import threading
command, pidfile = _tree_command(tmp_path)
outcome = {}
def old():
try:
subprocess.run(command, capture_output=True, text=True, timeout=3)
except subprocess.TimeoutExpired:
outcome["timeout"] = True
thread = threading.Thread(target=old, daemon=True)
thread.start()
thread.join(3 + 5)
try:
assert pidfile.is_file(), "the child did not get to start its grandchild"
grandchild = int(pidfile.read_text())
assert _alive(grandchild), "the grandchild outlives the timeout of the old guard"
if sys.platform == "win32":
assert thread.is_alive(), "on Windows the old guard does not return: it waits for the pipe of the grandchild"
finally:
if pidfile.is_file():
_kill_if_alive(int(pidfile.read_text()))
thread.join(15)
def test_the_tree_guard_returns_at_the_timeout_kills_the_grandchild_and_names_the_launch_that_was_alive(tmp_path):
import ci_crash_evidence as crash
command, pidfile = _tree_command(tmp_path)
began = time.monotonic()
try:
run = crash.run_tree(command, tmp_path / "out", timeout_s=3)
spent = time.monotonic() - began
assert run.timed_out and run.returncode is None
assert spent < 3 + 5, "it returned a few seconds after the timeout, not when the grandchild would have ended (%.1f s)" % spent
grandchild = int(pidfile.read_text())
assert _wait_gone(grandchild), "the grandchild is dead: the tree was killed, not the child alone"
assert "the grandchild is alive" in run.stdout, "the output is kept, from a file"
message = run.timeout_message("the network oracle", 3)
assert message.startswith("the network oracle did not end within 3 s: the launch exit-pings of seed 11 (firefox-68-again) was alive for ")
assert message.endswith(" s; its tree was killed")
assert 2 <= run.launch["alive_s"] < 3 + 5
finally:
if pidfile.is_file():
_kill_if_alive(int(pidfile.read_text()))
def test_the_tree_guard_is_silent_when_the_run_ends_by_itself_and_keeps_stdout_stderr_and_the_code_apart(tmp_path):
import ci_crash_evidence as crash
run = crash.run_tree([sys.executable, "-c", "import sys; print('out'); print('err', file=sys.stderr); sys.exit(2)"], tmp_path / "out", timeout_s=30)
assert (run.returncode, run.timed_out, run.stdout.strip(), run.stderr.strip()) == (2, False, "out", "err")
assert run.launch is None and "no launch had begun" in run.timeout_message("the oracle", 30)
def test_the_launch_line_is_read_back_and_the_last_one_wins():
import datetime
import ci_crash_evidence as crash
at = datetime.datetime(2026, 11, 22, 10, 0, 0, tzinfo=datetime.timezone.utc)
text = "\n".join([crash.launch_line(11, "main", "firefox-68", at), "noise", crash.launch_line(12, "idle-c2", "firefox-68-again", at), "more noise"])
found = crash.last_launch(text, now=at + datetime.timedelta(seconds=95))
assert (found["launch"], found["seed"], found["label"], found["alive_s"]) == ("idle-c2", "12", "firefox-68-again", 95.0)
assert crash.last_launch("nothing here") is None
def test_the_oracle_names_each_launch_with_the_line_the_guard_reads(tmp_path, monkeypatch, capsys):
import ci_crash_evidence as crash
monkeypatch.setattr(ab, "RUN_LABEL", "firefox-68-again")
ab.begin_launch(13, "exit-pings")
found = crash.last_launch(capsys.readouterr().out)
assert (found["launch"], found["seed"], found["label"]) == ("exit-pings", "13", "firefox-68-again")
# ----------------------------------------------------------------------------------------------------------------- what the profile held in datareporting/ before the close
def test_the_listing_of_datareporting_is_relative_sorted_and_with_sizes_and_is_written_where_the_stderr_of_the_launches_go(tmp_path, monkeypatch):
import ci_crash_evidence as crash
profile = tmp_path / "profile"
(profile / "datareporting" / "glean" / "db").mkdir(parents=True)
(profile / "datareporting" / "glean" / "db" / "data.safe.bin").write_bytes(b"x" * 37)
(profile / "datareporting" / "glean" / "pending_pings").mkdir()
(profile / "datareporting" / "state.json").write_text("{}", encoding="utf-8")
rows = crash.datareporting_listing(profile)
assert [r.split("\t") for r in rows if not r.startswith("#")] == [["glean/", "-"], ["glean/db/", "-"], ["glean/db/data.safe.bin", "37"], ["glean/pending_pings/", "-"], ["state.json", "2"]]
crash_dir = tmp_path / "t.crash"
probe = crash.LaunchProbe("/e/firefox", crash_dir)
monkeypatch.setattr(crash, "PROBE", probe)
probe.records.extend(["first", "second", "third"]) # the launch being made is the last record: the number of its stderr file
probe.set_label(seed=11, launch="idle-c1")
written = crash.save_datareporting(profile)
assert written == "t.crash/datareporting/03-11-idle-c1.tsv"
text = (crash_dir / "datareporting" / "03-11-idle-c1.tsv").read_text(encoding="utf-8")
assert "glean/db/data.safe.bin" in text and "37" in text
def test_a_profile_that_cannot_be_read_is_said_in_the_file_and_never_raises(tmp_path, monkeypatch):
import ci_crash_evidence as crash
assert any("not known" in r for r in crash.datareporting_listing(None))
assert any("datareporting" in r and r.startswith("# ") for r in crash.datareporting_listing(tmp_path / "gone"))
monkeypatch.setattr(crash, "PROBE", None)
assert crash.save_datareporting(tmp_path) is None, "no probe, no folder: nothing is written"
def test_the_oracle_lists_datareporting_of_the_profile_of_the_session_and_never_raises(tmp_path, monkeypatch):
seen = []
monkeypatch.setattr(ab, "profile_of", lambda token, find=None: tmp_path)
monkeypatch.setattr(ab.crash, "save_datareporting", lambda profile: seen.append(profile))
class Session:
_end_token = "token"
ab.save_datareporting(Session(), 11, "main")
assert seen == [tmp_path]
monkeypatch.setattr(ab.crash, "save_datareporting", lambda profile: 1 / 0)
ab.save_datareporting(Session(), 11, "main") # a failure of the evidence is not a failure of the launch
+7 -4
View File
@@ -19,7 +19,6 @@ from __future__ import annotations
import json
import os
import subprocess
import sys
from pathlib import Path
@@ -31,6 +30,7 @@ ROOT = Path(__file__).resolve().parent.parent
SCRIPT = ROOT / "scripts" / "ci_ab_network.py"
sys.path.insert(0, str(ROOT / "scripts"))
import ci_ab_network as oracle # noqa: E402
import ci_crash_evidence as crash # noqa: E402
from ci_ab_pr_seeds import pr_seed_count # noqa: E402
#: The fewest leaves a comparison holds, per system. A minimal but complete run of ONE seed (one request on each road, tests/test_ab_network.py) holds about 670; a real one holds several times that. A floor of
@@ -43,8 +43,8 @@ FLOOR = {"linux": 500, "win32": 500}
#: has the two idle launches. The budget allows 220 s for the first seed of an engine run (145 s measured on Windows), 120 s for each next one, and 120 s to start, so that the guard plus the 10 minutes of the job's own steps fit its 40 minutes: 5 seeds
#: in an A/A are 30 minutes at most, expected about 18 on Linux and 22 on Windows (the exit-ping launch adds 1 to 2.3 minutes per engine run); with a candidate (three engine runs on every seed) 44 minutes at most.
SETUP_S, FIRST_SEED_S, NEXT_SEED_S = 120, 220, 120
#: The idle launch that waits for the engine to record that it told the user about its data reporting policy (60 s timer of the infobar, or the first-run tab) and then closes
#: to count the exit pings: 140 s at most per engine run (the wait has a limit of 120 s, then the launch and the shutdown), on the first seed only.
#: The launch that counts the exit pings (a page, the wait for Glean, one navigation, the close and the tree's exit), on the first seed only: 140 s at most per engine run, the
#: bound of the launch as it was before it had a page; to be recomputed from the launches measured with the page.
EXIT_PINGS_S = 140
@@ -88,8 +88,11 @@ def test_the_network_a_a_is_the_control_and_the_candidate_puts_on_the_wire_what_
command += ["--candidate", firefox_binary, "--candidate-seal", seal]
else:
command += ["--a-a", "--published-binary", firefox_binary, "--seeds", ",".join(str(s) for s in oracle.default_seeds()[:plan()[0]])]
done = subprocess.run(command, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=TIMEOUT_S)
# Output in files and the whole tree killed at the limit: `subprocess.run(capture_output=True, timeout=...)` killed the python child alone, the firefox grandchild held the pipe
# and pytest ended with its own timeout 120 s later and no word about the launch (run 45121964904, Windows, job.log 546-557).
done = crash.run_tree(command, out / "tree", TIMEOUT_S)
(out / "oracle.log").write_text(done.stdout + "\n--- stderr\n" + done.stderr, encoding="utf-8")
assert not done.timed_out, done.timeout_message("the network oracle", TIMEOUT_S) + ":\n" + "\n".join(done.stdout.splitlines()[-30:]) + "\n" + done.stderr[-1500:]
verdict = [line for line in done.stdout.splitlines() if line.startswith(("DIFF ", "FAIL ", "AB NETWORK", "ERROR "))]
control = out / "diff-a-a.json"
assert control.is_file(), "the A/A did not run to its end (exit %s):\n%s\n%s" % (done.returncode, "\n".join(verdict[:40]), done.stderr[-1500:])
+86
View File
@@ -0,0 +1,86 @@
"""A launch of the oracles closes only AFTER Glean has initialised (scripts/ci_crash_evidence.py: `wait_for_glean`).
Run 45121964904 (the network A/A, Linux, launch `exit-pings`): a session that closes before Glean has initialised normally makes Glean start inside the shutdown, where its
`glean.init` thread can die with the panic "No database found" and the parent exits with -11. It is Mozilla's race, the same in the retail browser. The oracles do not
change the engine or a preference: they wait for a CONDITION read from the host, the file the database writes on its first write (`datareporting/glean/db/data.safe.bin`;
the folder `db` is born when the database is opened, the file at the first write). In normal sessions, stock and ours, it is there at about +8 s (run 43649596941).
The clock and the sleep are fakes: nothing here sleeps.
"""
from __future__ import annotations
import sys
from pathlib import Path
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts"))
import ci_crash_evidence as crash # noqa: E402
pytestmark = pytest.mark.unit
class Clock:
"""A clock that only the fake sleep moves, and a record of how long the caller slept."""
def __init__(self, on_sleep=None):
self.t, self.on_sleep = 0.0, on_sleep
def now(self):
return self.t
def sleep(self, seconds):
self.t += seconds
if self.on_sleep:
self.on_sleep(self.t)
def test_it_does_not_return_while_the_database_file_is_missing_and_returns_when_it_appears(tmp_path):
profile = tmp_path / "profile"
profile.mkdir()
target = profile / crash.GLEAN_DB
def born(t): # the file is written about +8 s into the wait
if t >= 8.0 and not target.exists():
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(b"\x00")
clock = Clock(born)
waited = crash.wait_for_glean(profile, sleep=clock.sleep, now=clock.now)
assert 8.0 <= waited < 8.5 and clock.t == waited, "it slept until the file existed, then returned"
def test_with_the_file_already_there_it_returns_at_once(tmp_path):
target = tmp_path / crash.GLEAN_DB
target.parent.mkdir(parents=True)
target.write_bytes(b"\x00")
clock = Clock()
assert crash.wait_for_glean(tmp_path, sleep=clock.sleep, now=clock.now) == 0.0 and clock.t == 0.0
def test_the_folder_alone_is_not_enough_and_the_limit_is_red_with_the_reason(tmp_path):
(tmp_path / crash.GLEAN_DB).parent.mkdir(parents=True) # `db` is born when the database is opened: the file is the first write
clock = Clock()
with pytest.raises(crash.GleanNotReady) as caught:
crash.wait_for_glean(tmp_path, sleep=clock.sleep, now=clock.now)
message = str(caught.value)
assert "Glean did not initialise in 60 s" in message and "data.safe.bin" in message and str(tmp_path) in message and "45121964904" in message
assert 60.0 <= clock.t < 61.0, "it waited the whole limit and not more"
def test_the_limit_is_the_callers_and_a_launch_without_a_profile_is_red_at_once(tmp_path):
clock = Clock()
with pytest.raises(crash.GleanNotReady, match="did not initialise in 5 s"):
crash.wait_for_glean(tmp_path, limit_s=5.0, sleep=clock.sleep, now=clock.now)
clock = Clock()
with pytest.raises(crash.GleanNotReady, match="the profile of the launch is not known"):
crash.wait_for_glean(None, sleep=clock.sleep, now=clock.now)
assert clock.t == 0.0, "no profile, nothing to wait for"
def test_it_writes_nothing_in_the_profile(tmp_path):
before = sorted(p.relative_to(tmp_path).as_posix() for p in tmp_path.rglob("*"))
clock = Clock()
with pytest.raises(crash.GleanNotReady):
crash.wait_for_glean(tmp_path, limit_s=2.0, sleep=clock.sleep, now=clock.now)
assert sorted(p.relative_to(tmp_path).as_posix() for p in tmp_path.rglob("*")) == before