tests: the download left to Firefox keeps its evidence when slow, the shutdown ping is judged on the core's own grace

- test_a_context_without_download_options_is_left_to_firefox: the download reputation prefs are no longer switched off (a slow save is the product's); the seconds from the click to the file stay a junit property, and a save slower than 40 s (judged after the fact, never a verdict) keeps in invpw-evidence/download-left-to-firefox the test server's record, the client's requests, the Juggler wire and trace, and a MOZ_LOG of the download machinery
- _evidence_on_failure: keep(why) saves what the helper holds though the test passed; arm(moz_log=...) and note_records(...)
- test_the_shutdown_ping...: no patch of SENDER_GRACE nor of the session's safety net; the ping must be on the endpoint when the session has ended, within the core's 10 s grace
This commit is contained in:
feder-cr committed 2026-11-22 11:38:07 +01:00
1 parent 8f8a191e9b
commit bc6d861f62
3 files changed
+171 -72

No files matched your search

+42 -5
View File
@@ -7,6 +7,11 @@ the client's view of every request); when the body raises (an assertion included
body passes, it deletes it all. Off a runner (no ``RUNNER_TEMP``) nothing is copied. It changes no assertion, wait or deadline of the
test: it only listens.
A test that passed slowly may keep the evidence too: ``evidence.keep(why)`` saves what the helper holds at that moment (the same folder, a
``meta.json`` whose ``kept`` says why, judged after the fact and never a verdict). ``arm(moz_log=...)`` also starts the engine's own log
(``MOZ_LOG``, its file in the evidence), and ``note_records(name, state)`` adds a record the test keeps itself (``state.lock``,
``state.records``) as ``<name>.jsonl``.
The times written: ``t``, wall-clock seconds since the epoch (``time.time()``; the engine's own trace writes milliseconds in ``t``, its
``performance.timeOrigin + now``, also since the epoch), and ``m``, ``time.perf_counter()`` of the test process, finer on Windows (whose wall
clock ticks every 15 ms) and shared by the fake web's record, the client's log and the Juggler wire.
@@ -31,6 +36,8 @@ EVIDENCE_FOLDER = "invpw-evidence"
WIRE_LIMIT = 4000
#: The engine's trace: the variable `Trace.js` of the engine reads in the parent process (off without it).
TRACE_ENV = "INVISIBLE_JUGGLER_TRACE_DIR"
#: The base name of the engine's log file in the evidence (``MOZ_LOG_FILE``; the engine adds a suffix per process).
MOZ_LOG_BASE = "engine"
class FailureEvidence:
@@ -39,6 +46,9 @@ class FailureEvidence:
self.work = pathlib.Path(tempfile.mkdtemp(prefix="invpw-failure-evidence-"))
self.trace_dir = self.work / "juggler-engine-trace"
self.wire_path = self.work / "juggler-wire.jsonl"
self.moz_log_dir = self.work / "moz-log"
#: The records the test keeps itself, by name (``note_records``).
self.records = {}
#: What the client heard of each request (a list ``profile_p2.drive(client_log=...)`` fills).
self.client_log = []
#: The cells of the run, once it has returned (``note_cells``).
@@ -57,12 +67,21 @@ class FailureEvidence:
def note_cells(self, cells) -> None:
self.cells = cells
def arm(self) -> None:
def note_records(self, name: str, state) -> None:
"""A record the test keeps itself (``state.lock``, ``state.records``: a list of dicts), saved as ``<name>.jsonl``."""
self.records[name] = state
def arm(self, moz_log: str = "") -> None:
"""Before the browser under test is launched: the engine writes its trace, and the Juggler wire of this process is logged.
Armed after the other processes of the test were started, so that they do not inherit the variable."""
Armed after the other processes of the test were started, so that they do not inherit the variable. ``moz_log``, a value of
``MOZ_LOG`` (modules and levels), also starts the engine's own log into the evidence (a diagnostic no page reads: the core passes it)."""
self.trace_dir.mkdir(parents=True, exist_ok=True)
self._patch = pytest.MonkeyPatch()
self._patch.setenv(TRACE_ENV, str(self.trace_dir))
if moz_log:
self.moz_log_dir.mkdir(parents=True, exist_ok=True)
self._patch.setenv("MOZ_LOG", moz_log)
self._patch.setenv("MOZ_LOG_FILE", str(self.moz_log_dir / MOZ_LOG_BASE))
self._wire = open(self.wire_path, "w", encoding="utf-8")
try:
from invisible_core.juggler import connection
@@ -106,6 +125,14 @@ class FailureEvidence:
pass
# ---- the end ---------------------------------------------------------------------------------------------------------
def keep(self, why: str) -> None:
"""Saves what the helper holds now, though the test has not failed: a run judged after the fact as one to read (a step slower
than any healthy run). Not a verdict: nothing is raised and the test goes on. Never raises."""
try:
self._save(None, None, kept=why)
except Exception as problem:
sys.stderr.write("evidence: could not be kept: %r\n" % (problem,))
def __enter__(self) -> "FailureEvidence":
return self
@@ -125,7 +152,7 @@ class FailureEvidence:
shutil.rmtree(self.work, ignore_errors=True)
return False
def _save(self, exc_type, exc) -> None:
def _save(self, exc_type, exc, kept: str = "") -> None:
base = os.environ.get("RUNNER_TEMP")
if not base:
return
@@ -136,17 +163,27 @@ class FailureEvidence:
with state.lock:
records = list(state.records)
self._jsonl(target / "fakeweb-server-record.jsonl", records)
self._jsonl(target / "client-request-log.jsonl", self.client_log)
for name, state in self.records.items():
with state.lock:
records = list(state.records)
self._jsonl(target / ("%s.jsonl" % name), records)
self._jsonl(target / "client-request-log.jsonl", list(self.client_log))
if self.cells is not None:
(target / "cells.json").write_text(json.dumps(self.cells, indent=1, default=str), encoding="utf-8")
if self.wire_path.exists():
shutil.copyfile(self.wire_path, target / "juggler-wire.jsonl")
if self.trace_dir.exists():
shutil.copytree(self.trace_dir, target / "juggler-engine-trace", dirs_exist_ok=True)
meta = {"test": self.name, "failure": "%s: %s" % (exc_type.__name__, str(exc)[:1500]), "platform": sys.platform,
if self.moz_log_dir.exists():
shutil.copytree(self.moz_log_dir, target / "moz-log", dirs_exist_ok=True)
meta = {"test": self.name, "platform": sys.platform,
"machine": platform.machine(), "python": platform.python_version(), "saved_at": round(time.time(), 4),
"times": "t: wall-clock seconds since the epoch (the engine's trace: milliseconds, in t); m: time.perf_counter() of the test process, the scale shared by the server record, the client log and the wire",
"files": sorted(p.name for p in target.iterdir())}
if exc_type is not None:
meta["failure"] = "%s: %s" % (exc_type.__name__, str(exc)[:1500])
if kept:
meta["kept"] = kept
(target / "meta.json").write_text(json.dumps(meta, indent=1), encoding="utf-8")
self.saved_to = target
+114 -45
View File
@@ -29,6 +29,14 @@ of the engine series, hooks in `uriloader/exthandler/nsExternalHelperAppService.
wrapper's directory, so the silence of the second download is the absence of
the hook and not a page that never downloaded.
**A slow save is kept, not judged.** Firefox's own save of the last test has taken, on the runners, from about ten seconds to
more than eighty for the same bytes: that is the product (a user's download would wait as long), so nothing of it is switched
off. The seconds from the click to the file are recorded (a junit property), and a run slower than any healthy one
(``SLOW_SAVE_S``, judged after the fact, never a verdict) keeps what says where the time went, in
``$RUNNER_TEMP/invpw-evidence/download-left-to-firefox/`` (``tests/_evidence_on_failure.py``, the same on a failure): the requests
the test's server saw, with times; every request the client heard (request, response, requestfinished, requestfailed), with
times; the Juggler wire and the engine's Juggler trace; the engine's log of the download machinery (``DOWNLOAD_LOG``).
Why a page cares: a download that ends twice, or that lands in the wrong place,
is a script that waits for a file that never comes, and a context that was given
no options must behave as retail Firefox does.
@@ -38,20 +46,47 @@ from __future__ import annotations
import http.server
import os
import threading
import time
import types
import pytest
from _evidence_on_failure import FailureEvidence
from _waits import wait_until, watch
BODY = b"invisible download body\n" * 64
#: Seconds from the click to the file in Firefox's directory beyond which a run keeps its evidence: no healthy run comes near
#: it. Judged after the fact, never a verdict (the test's deadline is the `watch` below).
SLOW_SAVE_S = 40.0
#: The engine's log of the download machinery, kept in the evidence: the external helper (`nsExternalHelperAppService.cpp`,
#: `HelperAppService`), the URI loader that hands it the response (`URILoader`), the reputation check of a finished download
#: (`ApplicationReputation`) and the url-classifier it asks (`UrlClassifierDbService`, `UrlClassifierStreamUpdater`).
DOWNLOAD_LOG = ("HelperAppService:5,URILoader:5,ApplicationReputation:5,UrlClassifierDbService:5,UrlClassifierStreamUpdater:5,"
"timestamp,sync")
def _note(state, **fields):
"""One line of a record, on the clocks of the evidence (`t` wall, `m` perf_counter)."""
with state.lock:
state.records.append({"t": round(time.time(), 4), "m": round(time.perf_counter(), 6), **fields})
def _serve(record=None):
"""The site of the quick download. `record` (``.lock``, ``.records``), when given, gets every request the server saw and the
end of every answer it wrote, with times."""
def note(handler, what, **more):
if record is not None:
_note(record, what=what, method=handler.command, path=handler.path, peer=handler.client_address[1],
agent=handler.headers.get("User-Agent"), **more)
def _serve():
class H(http.server.BaseHTTPRequestHandler):
def log_message(self, *a):
pass
def do_GET(self):
note(self, "request")
if self.path.startswith("/file"):
self.send_response(200)
self.send_header("content-type", "application/octet-stream")
@@ -59,11 +94,13 @@ def _serve():
self.send_header("content-length", str(len(BODY)))
self.end_headers()
self.wfile.write(BODY)
note(self, "answered", bytes=len(BODY))
return
self.send_response(200)
self.send_header("content-type", "text/html")
self.end_headers()
self.wfile.write(b'<title>d</title><a id=dl href="/file">get</a>')
note(self, "answered")
srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), H)
srv.daemon_threads = True
@@ -80,6 +117,17 @@ def served():
srv.shutdown()
@pytest.fixture
def served_and_recorded():
"""The same site, and its record of every request (``.lock``, ``.records``), for the evidence of a slow run."""
record = types.SimpleNamespace(lock=threading.Lock(), records=[])
srv, url = _serve(record)
try:
yield url, record
finally:
srv.shutdown()
@pytest.mark.e2e
def test_a_clicked_download_is_reported_and_saved(firefox_binary, served, tmp_path):
from invisible_playwright import InvisiblePlaywright
@@ -247,7 +295,7 @@ def test_a_canceled_download_reports_once_as_canceled(firefox_binary, held_site)
@pytest.mark.e2e
def test_a_context_without_download_options_is_left_to_firefox(firefox_binary, served, tmp_path, record_property):
def test_a_context_without_download_options_is_left_to_firefox(firefox_binary, served_and_recorded, tmp_path, record_property):
"""The negative control of the interception: the same context, the same link, the same file.
With its options the download is taken (announced, saved in the wrapper's directory). After
@@ -255,53 +303,74 @@ def test_a_context_without_download_options_is_left_to_firefox(firefox_binary, s
`downloadFinished`, no `download` event of the client, and the file is where Firefox's own preference says."""
from invisible_playwright import InvisiblePlaywright
served, record = served_and_recorded
where = tmp_path / "firefox"
where.mkdir()
# Firefox's own path asks `ApplicationReputation` about a finished download before the saved file takes its name (`.bin` is a binary
# type), and that work is on the url-classifier, not on the download: on the runners this test took ~12 s or ~87 s for the same bytes.
# This test is about WHERE the file goes, so the check is not part of it: with these prefs Firefox saves what it was given.
prefs = {"browser.download.folderList": 2,
"browser.download.dir": str(where),
"browser.download.useDownloadDir": True,
"browser.safebrowsing.downloads.enabled": False,
"browser.safebrowsing.malware.enabled": False}
with InvisiblePlaywright(seed=4242, binary_path=firefox_binary, headless=True,
extra_prefs=prefs) as browser:
context = browser.new_context(accept_downloads=True)
page = context.new_page()
engine, ctx = _engine_side(context)
events = _record(engine.conn)
announced = []
page.on("download", lambda download: announced.append(download))
page.goto(served, timeout=30_000)
"browser.download.useDownloadDir": True}
with FailureEvidence("download-left-to-firefox") as evidence:
evidence.note_records("server-record", record)
client = types.SimpleNamespace(lock=threading.Lock(), records=[])
evidence.client_log = client.records
evidence.arm(moz_log=DOWNLOAD_LOG)
with InvisiblePlaywright(seed=4242, binary_path=firefox_binary, headless=True,
extra_prefs=prefs) as browser:
context = browser.new_context(accept_downloads=True)
page = context.new_page()
# what the client heard of every request, with times (it only listens)
page.on("request", lambda r: _note(client, what="request", url=r.url, navigation=r.is_navigation_request()))
page.on("response", lambda r: _note(client, what="response", url=r.url, status=r.status))
page.on("requestfinished", lambda r: _note(client, what="requestfinished", url=r.url))
page.on("requestfailed", lambda r: _note(client, what="requestfailed", url=r.url, failure=str(r.failure)))
engine, ctx = _engine_side(context)
events = _record(engine.conn)
announced = []
# the control: with its options the download is taken
with page.expect_download(timeout=30_000) as info:
page.click("#dl")
info.value.path()
assert wait_until(lambda: _of(events, "Browser.downloadFinished"), 60,
pump=lambda: page.wait_for_timeout(100)), events
assert len(_of(events, "Browser.downloadCreated")) == 1, events
assert len(_of(events, "Browser.downloadFinished")) == 1, events
downloads_dir = engine._downloads_dir(ctx.context_id)
saved_by_the_wrapper = sorted(os.listdir(downloads_dir))
assert len(saved_by_the_wrapper) == 1, saved_by_the_wrapper
assert os.listdir(str(where)) == [], "the taken download landed in Firefox's directory"
def on_download(download):
announced.append(download)
_note(client, what="download", url=download.url)
# the context loses its download options: Firefox's own path takes the download
engine.conn.send("Browser.setDownloadOptions",
{"browserContextId": ctx.context_id, "downloadOptions": None}, timeout=None)
# The click on a download Firefox keeps plans a navigation that never completes (nothing commits: the response is a download),
# so the click does not wait for it; the end of the test waits on the CONDITION, the file in Firefox's directory.
page.click("#dl", no_wait_after=True, timeout=30_000)
landed = where / "report.bin"
landing = watch(lambda: landed.exists() and landed.read_bytes() == BODY, bool, 120,
pump=lambda: page.wait_for_timeout(100))
# not a verdict: how long Firefox's own save took, so a slow run says whether it was the save or the close that was slow
record_property("seconds_until_the_file_landed", "%.1f" % landing.took)
assert landing.ok, os.listdir(str(where))
page.on("download", on_download)
page.goto(served, timeout=30_000)
assert len(_of(events, "Browser.downloadCreated")) == 1, "the engine took a download of a context with no options"
assert len(_of(events, "Browser.downloadFinished")) == 1, events
assert len(announced) == 1, announced
assert sorted(os.listdir(downloads_dir)) == saved_by_the_wrapper, "the wrapper's directory got a second file"
# the control: with its options the download is taken
with page.expect_download(timeout=30_000) as info:
page.click("#dl")
info.value.path()
assert wait_until(lambda: _of(events, "Browser.downloadFinished"), 60,
pump=lambda: page.wait_for_timeout(100)), events
assert len(_of(events, "Browser.downloadCreated")) == 1, events
assert len(_of(events, "Browser.downloadFinished")) == 1, events
downloads_dir = engine._downloads_dir(ctx.context_id)
saved_by_the_wrapper = sorted(os.listdir(downloads_dir))
assert len(saved_by_the_wrapper) == 1, saved_by_the_wrapper
assert os.listdir(str(where)) == [], "the taken download landed in Firefox's directory"
# the context loses its download options: Firefox's own path takes the download
engine.conn.send("Browser.setDownloadOptions",
{"browserContextId": ctx.context_id, "downloadOptions": None}, timeout=None)
# The click on a download Firefox keeps plans a navigation that never completes (nothing commits: the response is a download),
# so the click does not wait for it; the end of the test waits on the CONDITION, the file in Firefox's directory.
_note(client, what="click", target="#dl", download_options=None)
clicked = time.perf_counter()
page.click("#dl", no_wait_after=True, timeout=30_000)
landed = where / "report.bin"
landing = watch(lambda: landed.exists() and landed.read_bytes() == BODY, bool, 120,
pump=lambda: page.wait_for_timeout(100))
seconds_to_the_file = time.perf_counter() - clicked
_note(client, what="file-landed" if landing.ok else "file-not-landed", history=landing.history)
# not a verdict: how long Firefox's own save took, from the click to the file
record_property("seconds_until_the_file_landed", "%.1f" % seconds_to_the_file)
assert landing.ok, os.listdir(str(where))
assert len(_of(events, "Browser.downloadCreated")) == 1, "the engine took a download of a context with no options"
assert len(_of(events, "Browser.downloadFinished")) == 1, events
assert len(announced) == 1, announced
assert sorted(os.listdir(downloads_dir)) == saved_by_the_wrapper, "the wrapper's directory got a second file"
# The browser is closed, so its log and its trace are whole. A save slower than any healthy run is kept to be read, not judged.
slow = seconds_to_the_file > SLOW_SAVE_S
record_property("evidence_kept_for_a_slow_save", str(slow))
if slow:
evidence.keep("Firefox's own save took %.1f s from the click to the file (more than %.0f s)"
% (seconds_to_the_file, SLOW_SAVE_S))
@@ -16,6 +16,15 @@ What the test does. A session (seed 42, no proxy; the road of the session is dec
is opened and closed. The session ENDS (`_session_end.EndingPlaywright`: the reaper has finished, so the sender is finished or ended), then the test
reads what the endpoint received.
The grace is the product's own (invisible-core, `juggler/_profile.SENDER_GRACE`, 10 s), not one of the test. `Connection.close` returns when the browser
has exited (the sender is left running: `process.outlives_the_browser`) and starts the launch's reaper, `process.Reaper(tree, grace=SENDER_GRACE)`; from
there the reaper waits up to the grace for the tree to empty by itself, then ends what is left (the process group: SIGTERM, SIGKILL 5 s later; on
Windows the launch's job) and removes the session's profile. A sender still running at the end of the grace is killed and its ping is lost with the
profile: a user's close does the same. The sender is started by the browser during its own shutdown, so the grace counts what is left of its run
after the browser has gone (measured by the core: 0.6 s on Linux, 1.0 s on Windows). So the ping is asserted where the product puts it: on the
endpoint when the session has ended, with no wait of the test after it. The endpoint records a request before it answers, and the sender ends only
after the answer, so a ping that the sender delivered is on the record by then.
What it asserts:
* at least one request reached the endpoint with `User-Agent: pingsender/2.0`, a POST to a path of the telemetry protocol (`/submit/telemetry/...`),
with a body;
@@ -33,10 +42,7 @@ import threading
import pytest
import _session_end
from _session_end import EndingPlaywright
from _waits import wait_until
from invisible_core.juggler import _profile
pytestmark = pytest.mark.e2e
@@ -44,19 +50,6 @@ SERVER = "toolkit.telemetry.server"
UPLOAD = "datareporting.healthreport.uploadEnabled"
BACKGROUND_TASK_AGENT = "pingsender/2.0"
#: What the sender is given to end by itself: far beyond a cold start on a loaded runner (the core's own is `_profile.SENDER_GRACE`, 10 s,
#: and the reaper ends the sender once it is over, so a slow sender would lose its ping and the verdict would judge the machine).
SENDER_GRACE = 120.0
@pytest.fixture(autouse=True)
def the_sender_ends_by_itself(monkeypatch):
"""The verdict waits for the sender to end by itself. `_profile.SENDER_GRACE` is read at the call (`Connection.close` and
`SessionFiles.remove` name it through the module), so the patch takes effect; the wait ends when the sender does, never on the time. The
session's own safety net (`ensure_ended`) goes up with it, since it would otherwise end the wait at 30 s."""
monkeypatch.setattr(_profile, "SENDER_GRACE", SENDER_GRACE)
monkeypatch.setitem(_session_end.ensure_ended.__kwdefaults__, "timeout", SENDER_GRACE + 30.0)
class Endpoint:
"""A telemetry endpoint on 127.0.0.1 (a port the OS gives) that records every request and answers 200."""
@@ -107,15 +100,15 @@ def session(binary, endpoint, extra_prefs=None):
def test_the_shutdown_ping_is_sent_by_the_background_task_and_not_by_the_host_program(firefox_binary):
endpoint, elsewhere = Endpoint(), Endpoint()
stop = threading.Event()
try:
session(firefox_binary, endpoint)
# The session has ended; the request of the sender is on the endpoint, or it comes within the time a healthy run allows.
arrived = wait_until(lambda: endpoint.by_agent(BACKGROUND_TASK_AGENT), 60, lambda: stop.wait(0.25))
seen = [(r["method"], r["path"][:60], r["agent"], r["bytes"]) for r in endpoint.requests]
assert arrived, ("no request with `User-Agent: %s` reached the endpoint after the session ended; what it received: %s"
% (BACKGROUND_TASK_AGENT, seen))
# The session has ended: the sender has finished within the product's grace, or the reaper killed it and its ping is lost. Nothing is
# waited for after this point.
pings = endpoint.by_agent(BACKGROUND_TASK_AGENT)
seen = [(r["method"], r["path"][:60], r["agent"], r["bytes"]) for r in endpoint.requests]
assert pings, ("no request with `User-Agent: %s` had reached the endpoint when the session ended: the background task did not deliver "
"the shutdown ping within the core's grace (`SENDER_GRACE`, after which the reaper kills it); what the endpoint received: %s"
% (BACKGROUND_TASK_AGENT, seen))
assert all(r["method"] == "POST" and r["path"].startswith("/submit/telemetry/") and r["bytes"] > 0 for r in pings), pings
assert elsewhere.requests == [], "an endpoint the session was not pointed at received %s" % (elsewhere.requests,)