Compare commits

...
Author SHA1 Message Date
feder-cr 4cb910cb44 ci: the hunt runs on candidate 43785139398 with core 74018f83 2026-11-16 02:24:16 +01:00
feder-cr f7cb7fc03e ci: a hunt that repeats the Control+A file with the protocol trace on the Windows binary of an engine candidate, named by two files of the branch
The candidate's run and core_ref are read from ci/candidate-run.txt and ci/candidate-core-ref.txt (TODO until the launch: the job refuses it first); scripts/hunt_candidate_binary.py downloads asset-win-x86_64, extracts and seals it as the gate of the candidate does, and checks the core installed is core_ref. 320 traced runs, four copies a round, windows-2022 only.
2026-11-16 02:23:01 +01:00
7 changed files with 1014 additions and 0 deletions

No files matched your search

@@ -0,0 +1,111 @@
# ─────────────────────────────────────────────────────────────────────────────
# candidate-control-a-hunt.yml - a MEASUREMENT, not a gate: the Control+A file of the
# e2e (tests/test_control_a_selects_all_in_a_field_e2e.py, 20 tests: 5 ways to press
# the shortcut x 2 fields x the in-process browser and the stock client), run again and
# again with the protocol trace of scripts/hunt_trace_plugin.py, on the Windows binary of
# an ENGINE CANDIDATE and not on the published one. The rare red it looks for is
# `Page.set_content: the caller's world never appeared for frame mainframe-N - did you
# call install()? Worlds seen: ['']`.
#
# The candidate is named by two files of this branch, written when the hunt is launched:
# ci/candidate-run.txt the id of the candidate's run of `release` in oss-invisible/firefox_antidetect_patch
# ci/candidate-core-ref.txt the core_ref that run was gated with
# Both say TODO until then, and the first step of the job refuses TODO. The binary is the
# artifact asset-win-x86_64 of that run, extracted as the gate of the candidate does and
# sealed as firefox-N-candidate (scripts/hunt_candidate_binary.py says how).
#
# ROUNDS OF FOUR COPIES, not `-n 4`: four pytest processes at once, each on the whole
# file (what a `--dist loadfile` worker of the gate does), so that every browser lives
# the same 10 tests per mode, in the same order, as in the gate (scripts/hunt_ctrla_rounds.py
# says why). Rounds follow until 320 test runs are recorded (4 rounds). A red copy never
# stops the others; the verdict is only that 320 traces and the junit files are there.
#
# It runs on a push to its own branch only.
# ─────────────────────────────────────────────────────────────────────────────
name: candidate-control-a-hunt
on:
push:
branches: [hunt/candidate-control-a]
permissions:
contents: read
actions: read
# A hunt has a group of its own, unique to the run: a newer push never cancels
# a measurement that is half done (tests/test_ci_runs_once_per_commit.py).
concurrency:
group: ${{ github.workflow }}-${{ github.run_id }}
cancel-in-progress: false
env:
# reads the artifacts and the log of the candidate's run (the engine repository is public)
GH_TOKEN: ${{ github.token }}
GITHUB_TOKEN: ${{ github.token }}
# the core of the candidate, not the one the wrapper pins: the pair is mismatched on purpose, as the gate of the candidate runs it
INVISIBLE_CORE_PIN: allow
INVISIBLE_CORE_AUTOFIX: "off"
jobs:
candidate-control-a-windows:
name: candidate-control-a (windows)
runs-on: windows-2022
timeout-minutes: 60
defaults:
run:
shell: bash
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
with: { fetch-depth: 1 }
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
with: { python-version: '3.11' }
# TODO in either file ends the job here, in seconds, with the reason.
- name: The candidate is named (ci/candidate-run.txt, ci/candidate-core-ref.txt)
run: python scripts/hunt_candidate_binary.py check
- name: Install the core of the candidate, the wrapper and the test deps
run: |
set -e
CORE_GIT="git+https://github.com/oss-invisible/core@$(python scripts/hunt_candidate_binary.py core-ref)"
python -m pip install --upgrade pip
python -m pip install --quiet "$CORE_GIT"
python -m pip install --quiet ".[dev]"
python -m pip install --quiet --force-reinstall "$CORE_GIT"
python -m pip install --quiet "playwright==$(cat scripts/playwright_pin.txt)"
python scripts/hunt_candidate_binary.py verify-core
- name: The binary of the candidate (asset-win-x86_64), sealed
run: python scripts/hunt_candidate_binary.py fetch --leg win-x86_64 --dest "$RUNNER_TEMP/candidate"
- name: The GeoIP database (made by the repository, same bytes every run)
run: python scripts/ci_lab_geoip.py build --pin ci/geoip.json
- name: The Control+A file in rounds of four copies, with the protocol trace
timeout-minutes: 45
env:
PYTHONUNBUFFERED: "1"
run: python -u scripts/hunt_ctrla_rounds.py --binary "$FF" --out-dir "$RUNNER_TEMP/ctrla-hunt" --min-runs 320 --copies 4 --budget-min 28
- name: Close every Firefox left
if: always()
shell: pwsh
run: |
Get-Process firefox -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue
"left: " + @(Get-Process firefox -ErrorAction SilentlyContinue).Count
- name: The summary of the red and the green runs
if: always()
run: |
mkdir -p "$RUNNER_TEMP/ctrla-hunt"
cp "$RUNNER_TEMP/candidate/candidate.json" "$RUNNER_TEMP/ctrla-hunt/" || true
python scripts/hunt_ctrla_summary.py "$RUNNER_TEMP/ctrla-hunt/trace" --max-reds 30 | tee "$RUNNER_TEMP/ctrla-hunt/summary.txt" || true
- name: Upload the traces, the junit and the logs
if: always()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: candidate-control-a-windows-${{ github.run_id }}-${{ github.run_attempt }}
path: ${{ runner.temp }}/ctrla-hunt
if-no-files-found: warn
retention-days: 14
# The verdict is only that the files are there: a red test is what the hunt is for.
- name: Verdict (320 traces and the junit files are there)
if: always()
run: |
traces=$(ls "$RUNNER_TEMP/ctrla-hunt/trace"/*.json 2>/dev/null | wc -l)
junits=$(ls "$RUNNER_TEMP/ctrla-hunt/junit"/*.xml 2>/dev/null | wc -l)
echo "trace files: $traces, junit files: $junits"
[ "$traces" -ge 320 ] && [ "$junits" -gt 0 ]
+1
View File
@@ -0,0 +1 @@
74018f83c0b59fdaeff9e494426529331f8f7e60
+1
View File
@@ -0,0 +1 @@
43785139398
+199
View File
@@ -0,0 +1,199 @@
#!/usr/bin/env python3
"""The engine of an ENGINE CANDIDATE for a hunt, instead of the published one.
A candidate is a run of the `release` workflow of oss-invisible/firefox_antidetect_patch (kind=candidate): it builds both legs and
uploads each as the artifact `asset-<leg>`. A hunt branch names the run in two one-line files, written when the hunt is launched:
ci/candidate-run.txt the id of that run
ci/candidate-core-ref.txt the ref of oss-invisible/core the candidate was gated with (its `core_ref` input)
Both hold `TODO` until then, and every command here refuses `TODO` first, so a push before the launch fails at once and says why.
python scripts/hunt_candidate_binary.py check # both files are filled in: exit 1 and a message if not
python scripts/hunt_candidate_binary.py core-ref # prints the core ref
python scripts/hunt_candidate_binary.py verify-core # the installed core IS the git install of that ref (as gate.yml asserts)
python scripts/hunt_candidate_binary.py seal-tag # prints the tag the candidate is sealed under, firefox-N-candidate
python scripts/hunt_candidate_binary.py fetch --leg win-x86_64 --dest DIR
# downloads asset-<leg>, extracts it, seals the binary, exports the env
`fetch` does what the gate of the candidate does with its own artifact (gate.yml of the engine repository): the one
`firefox-*-stealth-<leg>.*` archive of the artifact is extracted (zip on Windows, tar.gz on Linux), and
`python -m invisible_core seal --binary <exe> --tag <seal tag>` writes the seal the wrapper's launch is checked under, and DEST/candidate.json
says which run, core ref, seal tag and bytes the hunt ran on. It then writes to
$GITHUB_ENV (when set) and prints: FF and INVPW_BINARY_PATH (the binary) and INVISIBLE_SEAL_FILE (the seal).
The seal tag is the one the plan job of the candidate's run printed (`seal_tag=firefox-N-candidate`); when that log cannot be read it is
the last published `firefox-N` tag plus one, which is how the plan makes it, and the line says so.
Needs the GitHub CLI with GH_TOKEN (the engine repository is public: the token of the workflow reads its artifacts and logs).
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import re
import subprocess
import sys
import zipfile
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
ENGINE_REPO = "oss-invisible/firefox_antidetect_patch"
CORE_URL = "https://github.com/oss-invisible/core"
RUN_FILE = ROOT / "ci" / "candidate-run.txt"
CORE_FILE = ROOT / "ci" / "candidate-core-ref.txt"
LEGS = ("win-x86_64", "linux-x86_64")
class Refused(Exception):
"""What the hunt cannot start without; the message is the whole explanation."""
def _line(path: Path, what: str) -> str:
try:
text = path.read_text(encoding="utf-8")
except OSError as exc:
raise Refused("%s cannot be read: %s" % (path.relative_to(ROOT).as_posix(), exc))
lines = [line.strip() for line in text.splitlines() if line.strip()]
if len(lines) != 1:
raise Refused("%s must hold exactly one line (%s), it holds %d" % (path.relative_to(ROOT).as_posix(), what, len(lines)))
if lines[0] == "TODO":
raise Refused("%s says TODO: this hunt has no candidate yet. Write %s there, commit and push again."
% (path.relative_to(ROOT).as_posix(), what))
return lines[0]
def run_id() -> str:
value = _line(RUN_FILE, "the id of the candidate's run of the release workflow of %s" % ENGINE_REPO)
if not re.fullmatch(r"[0-9]{6,}", value):
raise Refused("ci/candidate-run.txt must be a run id (digits only), it says %r" % value)
return value
def core_ref() -> str:
value = _line(CORE_FILE, "the core_ref the candidate was gated with (a branch, a tag or a 40-character sha of oss-invisible/core)")
if not re.fullmatch(r"[A-Za-z0-9._/-]+", value) or value.startswith(("-", "/")):
raise Refused("ci/candidate-core-ref.txt must be one ref of the core, it says %r" % value)
return value
def _gh(*args: str) -> str:
done = subprocess.run(["gh", *args], capture_output=True, text=True, encoding="utf-8", errors="replace")
if done.returncode:
raise Refused("gh %s failed: %s" % (" ".join(args[:3]), (done.stderr or done.stdout).strip()[:400]))
return done.stdout
def seal_tag(run: str) -> str:
try:
jobs = json.loads(_gh("api", "repos/%s/actions/runs/%s/jobs?per_page=100" % (ENGINE_REPO, run)))["jobs"]
plan = next(j["id"] for j in jobs if j["name"] == "plan")
log = _gh("api", "--allow-escape-sequences", "repos/%s/actions/jobs/%s/logs" % (ENGINE_REPO, plan))
found = re.findall(r"seal_tag=(firefox-[0-9]+-candidate)\b", log)
if found:
print("seal tag %s (the plan job of run %s)" % (found[-1], run), file=sys.stderr)
return found[-1]
raise Refused("the plan job's log has no seal_tag line")
except (Refused, StopIteration, KeyError, ValueError) as exc:
print("::warning::the seal tag could not be read from run %s (%s); using the last published tag plus one" % (run, exc), file=sys.stderr)
rows = subprocess.run(["git", "ls-remote", "--tags", "--refs", "https://github.com/%s" % ENGINE_REPO, "refs/tags/firefox-*"],
capture_output=True, text=True, check=True).stdout.splitlines()
numbers = [int(m.group(1)) for line in rows for m in [re.search(r"refs/tags/firefox-([0-9]+)$", line)] if m]
if not numbers:
raise Refused("no firefox-N tag in %s: the number of the candidate is unknown" % ENGINE_REPO)
return "firefox-%d-candidate" % (max(numbers) + 1)
def verify_core(ref: str) -> None:
"""The installed core is the git install of exactly `ref` (the assertion of gate.yml), read after importing the wrapper."""
from importlib.metadata import distribution, version
if re.fullmatch(r"[0-9a-f]{40}", ref):
want = ref
else:
rows = [line.split() for line in subprocess.run(["git", "ls-remote", CORE_URL, ref, ref + "^{}"], capture_output=True, text=True,
check=True).stdout.splitlines() if line.strip()]
peeled = [sha for sha, name in rows if name.endswith("^{}")] # an annotated tag: its commit, not the tag object
want = (peeled or [sha for sha, _ in rows] or [""])[0]
import invisible_playwright # noqa: F401 - the import-time pin repair runs here, as under pytest
raw = distribution("invisible-core").read_text("direct_url.json")
got = (json.loads(raw).get("vcs_info") or {}).get("commit_id") if raw else None
print("core under test: %s from %s" % (version("invisible-core"), got or "the index"))
if not want or got != want:
raise Refused("THE CORE UNDER TEST IS NOT %s: installed %s from %s, the ref is %s"
% (ref, version("invisible-core"), got or "the index", want or "not a ref of the core"))
def fetch(leg: str, dest: Path) -> dict:
run = run_id()
tag = seal_tag(run)
dest.mkdir(parents=True, exist_ok=True)
art = dest / "art"
_gh("run", "download", run, "-R", ENGINE_REPO, "-n", "asset-%s" % leg, "-D", str(art))
archives = sorted(art.glob("firefox-*-stealth-%s.*" % leg))
if len(archives) != 1:
raise Refused("expected one firefox-*-stealth-%s archive in the artifact asset-%s of run %s, found: %s"
% (leg, leg, run, [p.name for p in archives] or sorted(p.name for p in art.iterdir())))
ff = dest / "ff"
ff.mkdir(exist_ok=True)
if leg.startswith("win"):
with zipfile.ZipFile(archives[0]) as z:
z.extractall(ff)
exe = ff / "firefox.exe"
else:
subprocess.run(["tar", "xzf", str(archives[0]), "-C", str(ff)], check=True)
exe = ff / "firefox"
if exe.exists():
exe.chmod(exe.stat().st_mode | 0o111)
if not exe.exists():
raise Refused("the archive %s has no %s at its root" % (archives[0].name, exe.name))
seal = dest / "candidate.seal.json"
subprocess.run([sys.executable, "-m", "invisible_core", "seal", "--binary", str(exe), "--tag", tag, "-o", str(seal)], check=True)
record = {"engine_repo": ENGINE_REPO, "run_id": run, "core_ref": core_ref(), "seal_tag": tag, "leg": leg, "archive": archives[0].name,
"archive_sha256": hashlib.sha256(archives[0].read_bytes()).hexdigest(),
"binary_sha256": hashlib.sha256(exe.read_bytes()).hexdigest()}
(dest / "candidate.json").write_text(json.dumps(record, indent=2), encoding="utf-8")
env = {"FF": exe.resolve().as_posix(), "INVPW_BINARY_PATH": exe.resolve().as_posix(), "INVISIBLE_SEAL_FILE": seal.resolve().as_posix()}
target = os.environ.get("GITHUB_ENV")
if target:
with open(target, "a", encoding="utf-8", newline="\n") as handle:
handle.writelines("%s=%s\n" % kv for kv in env.items())
for key, value in env.items():
print("%s=%s" % (key, value))
print("candidate run %s, archive %s, sealed as %s" % (run, archives[0].name, tag), file=sys.stderr)
return env
def main(argv=None) -> int:
parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0], formatter_class=argparse.RawDescriptionHelpFormatter)
sub = parser.add_subparsers(dest="command", required=True)
sub.add_parser("check")
sub.add_parser("core-ref")
sub.add_parser("verify-core")
sub.add_parser("seal-tag")
f = sub.add_parser("fetch")
f.add_argument("--leg", choices=LEGS, required=True)
f.add_argument("--dest", required=True, type=Path)
args = parser.parse_args(argv)
try:
if args.command == "check":
print("candidate run %s, core ref %s" % (run_id(), core_ref()))
elif args.command == "core-ref":
print(core_ref())
elif args.command == "verify-core":
verify_core(core_ref())
elif args.command == "seal-tag":
print(seal_tag(run_id()))
else:
fetch(args.leg, args.dest)
except Refused as exc:
print("::error::%s" % exc)
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
+115
View File
@@ -0,0 +1,115 @@
#!/usr/bin/env python3
"""A MEASUREMENT, not a gate: the Control+A file, run again and again with the protocol trace, until there are enough runs.
python scripts/hunt_ctrla_rounds.py --binary "$FF" --out-dir out [--min-runs 300] [--copies 4] [--budget-min 28]
One ROUND starts COPIES pytest processes at once, each on the whole file tests/test_control_a_selects_all_in_a_field_e2e.py (20 tests: 10 for
the in-process browser, 10 for the stock client), each with its own junit, its own log and its own tag (`r<round>c<copy>`), loaded with
`-p scripts.hunt_trace_plugin` (one JSON per test in `<out-dir>/trace`). Rounds follow each other until `--min-runs` test runs have been
recorded or the time budget is spent (no round is started after it). No round ever stops the others: a copy that is red, hangs or dies is
only a copy that wrote what it wrote, and the exit code is non-zero only when the hunt could not start (no binary) or recorded nothing.
Why COPIES in parallel and not `-n 4 --dist loadfile` or `-n 4 --dist load`: under `loadfile` a file goes to ONE worker, so a single file
would run on one worker and the other three would be idle, which is not four at once; under `load` the 20 tests of the file are scattered
over four workers and each builds the module-scoped `browser` fixture for itself, so every browser sees about 5 tests instead of the 10 it
sees in the gate, in another order: the question of this hunt (what a browser that has served pages before does with the next one) would
be asked of a different browser. A copy is what a `loadfile` worker is in the gate: the whole file, in file order, one browser per mode;
four copies are the four browsers at once of the gate (the cap of this project is four browsers).
Layout of `--out-dir`: `trace/` (the JSON of the plugin), `junit/` (one XML per copy), `logs/` (the output of each copy).
"""
from __future__ import annotations
import argparse
import os
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
TEST_FILE = "tests/test_control_a_selects_all_in_a_field_e2e.py"
#: A test that hangs ends its copy at this many seconds (pytest-timeout, thread method as in the gate), not the job.
TEST_DEADLINE_S = 300
#: A copy that is still alive after this long is killed: a whole file takes a couple of minutes.
COPY_DEADLINE_S = 15 * 60
def command(junit):
return [
sys.executable, "-u", "-m", "pytest",
"-m", "e2e", "-o", "addopts=",
"-p", "no:rerunfailures", "-p", "no:cacheprovider",
"-p", "scripts.hunt_trace_plugin",
"-o", "junit_family=xunit2", "--junitxml=%s" % junit,
"--timeout", str(TEST_DEADLINE_S), "--timeout-method", "thread",
"-v", "--tb=short",
TEST_FILE,
]
def environment(binary, trace_dir, tag):
env = {k: v for k, v in os.environ.items() if k != "PYTEST_ADDOPTS"}
env.update({
"PYTHONUNBUFFERED": "1",
"INVPW_BINARY_PATH": binary,
"STEALTHFOX_E2E_BINARY": binary,
"HUNT_TRACE_DIR": str(trace_dir),
"HUNT_TRACE_TAG": tag,
})
return env
def recorded(trace_dir):
return sum(1 for _ in Path(trace_dir).glob("*.json"))
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0], formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--binary", default=os.environ.get("INVPW_BINARY_PATH") or os.environ.get("FF"),
help="the engine of invisible_playwright (default: $INVPW_BINARY_PATH, then $FF)")
parser.add_argument("--out-dir", default="ctrla-hunt", help="where trace/, junit/ and logs/ are written")
parser.add_argument("--min-runs", type=int, default=300, help="stop after the round that reaches this many test runs (default 300)")
parser.add_argument("--copies", type=int, default=4, help="pytest processes at once in a round (default 4: the browsers of the gate)")
parser.add_argument("--budget-min", type=float, default=28.0, help="no new round after this many minutes (default 28)")
args = parser.parse_args(argv)
if not args.binary or not Path(args.binary).exists():
print("::error::the engine is needed: --binary, or $INVPW_BINARY_PATH / $FF (%r)" % args.binary, flush=True)
return 2
out = Path(args.out_dir).resolve()
trace, junit, logs = out / "trace", out / "junit", out / "logs"
for directory in (trace, junit, logs):
directory.mkdir(parents=True, exist_ok=True)
started = time.monotonic()
number = 0
while recorded(trace) < args.min_runs:
if number and time.monotonic() - started > args.budget_min * 60:
print("budget of %.0f min spent: no new round" % args.budget_min, flush=True)
break
number += 1
round_started = time.monotonic()
procs = []
for copy in range(1, args.copies + 1):
tag = "r%02dc%d" % (number, copy)
log = open(logs / (tag + ".log"), "w", encoding="utf-8", newline="\n")
proc = subprocess.Popen(command(junit / (tag + ".xml")), cwd=str(ROOT), env=environment(args.binary, trace, tag),
stdout=log, stderr=subprocess.STDOUT)
procs.append((tag, proc, log))
codes = {}
for tag, proc, log in procs:
try:
codes[tag] = proc.wait(timeout=max(1.0, COPY_DEADLINE_S - (time.monotonic() - round_started)))
except subprocess.TimeoutExpired:
proc.kill()
codes[tag] = "killed"
log.close()
print("round %d: %.0f s, %d run(s) recorded so far, exit codes %s" % (
number, time.monotonic() - round_started, recorded(trace), codes), flush=True)
total = recorded(trace)
print("%d round(s), %d test run(s) recorded in %s" % (number, total, trace), flush=True)
return 0 if total else 1
if __name__ == "__main__":
sys.exit(main())
+224
View File
@@ -0,0 +1,224 @@
#!/usr/bin/env python3
"""The summary of a Control+A hunt: the JSON of scripts/hunt_trace_plugin.py, read and put in two piles, red and green.
python scripts/hunt_ctrla_summary.py DIR [DIR ...] [--around MS] [--top N] [--max-reds N]
DIR is a folder (or several: the artefact of each job) holding the files the plugin wrote, however deep. It prints
* the count per system and mode of the browser fixture (in-process, stock-client): how many passed and how many were red;
* for each red (up to --max-reds): the test, the first line of its failure and the sequence of events of the world, the context and the
navigation of ITS page around `set_content`: what the engine said (event), what the server sent (send / reply / error) and the marks of
the plugin (install, caller_context, set_content), with the ms counted from the start of `set_content` (negative: before it). A context is
named by its world: main (the page's own, empty name), aux (`__ctx_aux__`, the utility world) and caller (`__ctx_caller__`, the one
`set_content` waits for); an id is resolved to its world from the creation event;
* the sequence that is typical of the greens, per mode (the most frequent ones, --top), in the same words and with the times of the first
test that had it, so that a red is read against what a green does.
Nothing here decides: the exit code is 1 only when no JSON is found. The red ones are the ones whose outcome is `failed` or `error`.
"""
from __future__ import annotations
import argparse
import json
import sys
from collections import Counter
from pathlib import Path
#: What the sequence is made of: the events of the worlds, the contexts, the frames and the navigations; the commands that make a world or run
#: in one; the marks of the plugin.
_EVENT = {
"Page.navigationStarted", "Page.navigationCommitted", "Page.navigationAborted", "Page.sameDocumentNavigation", "Page.eventFired",
"Page.frameAttached", "Page.frameDetached", "Runtime.executionContextsCleared", "Runtime.executionContextCreated",
"Runtime.executionContextDestroyed", "Browser.attachedToTarget", "Browser.detachedFromTarget",
}
_COMMAND = {"Page.setInitScripts", "Runtime.evaluate", "Runtime.callFunction", "Page.navigate", "Page.close", "Browser.newPage"}
_WORLD = {"": "main", "__ctx_aux__": "aux", "__ctx_caller__": "caller"}
_RED = ("failed", "error")
def load(directories):
tests = []
for directory in directories:
for path in sorted(Path(directory).rglob("*.json")):
try:
data = json.loads(path.read_text(encoding="utf-8"))
except (OSError, ValueError):
continue
if isinstance(data, dict) and "events" in data and "nodeid" in data:
data["_file"] = path.name
tests.append(data)
return tests
def _session_of(row):
"""The session a row belongs to: its own, or for a target that attaches the one it announces."""
_, _, method, detail, _, session = row
if method in ("Browser.attachedToTarget", "Browser.detachedFromTarget"):
return (detail or {}).get("sessionId") or session
return session
def _world_names(rows):
"""executionContextId -> world, from the creation events of this test (every connection: the ids are unique to a session)."""
out = {}
for _, kind, method, detail, _, _ in rows:
if kind == "event" and method == "Runtime.executionContextCreated":
out[str(detail.get("executionContextId"))] = _WORLD.get(detail.get("world"), detail.get("world"))
return out
def _word(row, worlds):
"""One row as a short word: what it is and what tells it apart (the world, the frame is left out: the session is already one page)."""
_, kind, method, detail, _, _ = row
detail = detail or {}
short = method.replace("Page.", "").replace("Runtime.", "").replace("Browser.", "")
parts = []
if method == "Runtime.executionContextCreated":
parts.append(_WORLD.get(detail.get("world"), detail.get("world")))
elif method == "Runtime.executionContextDestroyed":
parts.append(worlds.get(str(detail.get("executionContextId")), "unknown ctx"))
elif method in ("Runtime.evaluate", "Runtime.callFunction"):
parts.append("in " + worlds.get(str(detail.get("executionContextId")), "?"))
if detail.get("expression"):
parts.append(detail["expression"][:40])
elif method == "Page.setInitScripts" and kind == "send":
parts.append("+".join(_WORLD.get(w[0], str(w[0])) for w in detail.get("worlds") or []) or "none")
elif method.startswith("Page.navigation") and detail.get("url"):
parts.append(detail["url"][:40])
elif method == "Page.eventFired":
parts.append(detail.get("name"))
elif method in ("caller_context.start", "caller_context.error", "set_content.start", "install.start"):
if detail.get("worlds") is not None:
parts.append("worlds known: [%s]" % ", ".join(w.split("=")[0] for w in detail["worlds"]))
if detail.get("error"):
parts.append(detail["error"][:60])
elif method == "set_content.error" and detail.get("error"):
parts.append(detail["error"][:60])
prefix = {"send": "-> ", "reply": "<- ", "error": "<-ERR ", "event": "", "mark": "## "}[kind]
word = prefix + short
if kind == "event" and detail.get("replay"):
word += " (replayed)"
if kind == "error":
parts.append(str(detail.get("error", ""))[:60])
elif kind == "reply" and detail.get("ms") is not None:
parts.append("%s ms" % detail["ms"])
return "%s(%s)" % (word, " ".join(str(p) for p in parts if p is not None and p != "")) if parts else word
def _interesting(row):
_, kind, method, _, _, _ = row
if kind == "event":
return method in _EVENT
if kind in ("send", "reply", "error"):
return method in _COMMAND
return kind == "mark" and (method.startswith(("install.", "caller_context.", "set_content.")))
def _sequence(test):
"""(session, rows of that page that matter, anchor ms): the page is the one of the `set_content` mark; the anchor is its start."""
rows = test["events"]
anchor_row = next((r for r in rows if r[1] == "mark" and r[2] == "set_content.start"), None) or next((r for r in rows if r[1] == "mark" and r[2] == "caller_context.start"), None) # the world is asked for by others too
if anchor_row is None:
return None, [], None, {}
session = anchor_row[5]
worlds = _world_names(rows)
mine = [r for r in rows if _interesting(r) and (_session_of(r) == session or r[1] == "mark" and r[5] == session)]
return session, mine, anchor_row[0], worlds
def _fold(words):
"""Consecutive repeats collapse: [word, ms of the first, count]."""
folded = []
for word, ms in words:
if folded and folded[-1][0] == word:
folded[-1][2] += 1
else:
folded.append([word, ms, 1])
return folded
def _words(test):
got = _sequence(test)
session, rows, anchor, worlds = got
if session is None and not rows:
return None
return [(_word(r, worlds), round(r[0] - anchor, 1)) for r in rows]
def _print_sequence(folded, indent=" "):
for word, ms, count in folded:
print("%s%+10.1f ms %s%s" % (indent, ms, word, " x%d" % count if count > 1 else ""))
def _first_line(test):
for text in (test.get("failure") or {}).values():
for line in str(text).splitlines():
if line.startswith("E ") and ("Error" in line or "error" in line):
return line[1:].strip()[:200]
return str(text).strip().splitlines()[0][:200] if str(text).strip() else ""
return ""
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0], formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("directories", nargs="+", help="folders with the JSON of the plugin (searched however deep)")
parser.add_argument("--around", type=float, default=None, metavar="MS",
help="show only the rows from this many ms before set_content (default: the whole life of the page)")
parser.add_argument("--top", type=int, default=3, help="how many green sequences to show per mode (default 3)")
parser.add_argument("--max-reds", type=int, default=10, help="how many red tests to show in detail (default 10)")
args = parser.parse_args(argv)
tests = load(args.directories)
if not tests:
print("no JSON of the plugin under %s" % ", ".join(args.directories))
return 1
counts = Counter((t.get("system"), t.get("mode"), "red" if t["outcome"] in _RED else t["outcome"]) for t in tests)
print("== %d test runs" % len(tests))
for system, mode in sorted({(s, m) for s, m, _ in counts}, key=str):
row = {k: v for (s, m, k), v in counts.items() if (s, m) == (system, mode)}
print(" %-8s %-13s %s" % (system, mode, ", ".join("%s %d" % (k, v) for k, v in sorted(row.items()))))
hooks = sorted({e for t in tests for e in t.get("hook_errors") or []})
if hooks:
print("== hooks that could not be installed (the trace is partial):")
for e in hooks:
print(" " + e)
reds = [t for t in tests if t["outcome"] in _RED]
print("\n== %d red" % len(reds))
for test in reds[:args.max_reds]:
print("\n-- %s [%s, %s, pid %s, #%s]\n %s" % (test["nodeid"], test.get("system"), test.get("mode"), test.get("pid"),
test.get("sequence"), _first_line(test)))
words = _words(test)
if words is None:
print(" (no set_content and no caller_context in this test: the failure is not where the hunt looks)")
continue
if args.around is not None:
words = [w for w in words if w[1] >= -args.around]
print(" page session %s; ms from the start of set_content (events of THIS page; ## = a mark of the plugin):" % _sequence(test)[0])
_print_sequence(_fold(words))
if len(reds) > args.max_reds:
print("\n(%d more red not shown: --max-reds)" % (len(reds) - args.max_reds))
greens = [t for t in tests if t["outcome"] == "passed"]
print("\n== typical sequence of the %d green, per mode" % len(greens))
for mode in sorted({t.get("mode") for t in greens}, key=str):
groups = {}
for test in (t for t in greens if t.get("mode") == mode):
words = _words(test)
if words is None:
continue
if args.around is not None:
words = [w for w in words if w[1] >= -args.around]
folded = _fold(words)
slot = groups.setdefault(tuple((w, c) for w, _, c in folded), [0, folded])
slot[0] += 1
ranked = sorted(groups.values(), key=lambda item: -item[0])
print("\n-- mode %s: %d distinct sequence(s)" % (mode, len(ranked)))
for n, folded in ranked[:args.top]:
print(" x%d (times of the first test with it):" % n)
_print_sequence(folded)
return 0
if __name__ == "__main__":
sys.exit(main())
+363
View File
@@ -0,0 +1,363 @@
"""A pytest plugin for a HUNT, never for a gate: the protocol trace of every test it runs, one JSON per test.
python -m pytest -m e2e -p scripts.hunt_trace_plugin tests/test_control_a_selects_all_in_a_field_e2e.py
(run from the root of the repository, or with it on PYTHONPATH; the plugin is loaded with `-p` and is not in tests/conftest.py, so no other
run sees it.) Where the JSON go: `$HUNT_TRACE_DIR` (default `hunt-trace`); `$HUNT_TRACE_TAG` is a label of the run (the round, the copy) that is
written into every file name and every JSON.
Why it exists. `Page.set_content` failed, rarely, with "the caller's world never appeared for frame mainframe-N - did you call install()?
Worlds seen: ['']" (tests/test_control_a_selects_all_in_a_field_e2e.py). The message is raised by `InjectedScript.caller_context` of
invisible_core (juggler/injected.py) after 30 s of waiting for the context named `__ctx_caller__` of that frame, and the one thing that makes
that context exist is `InjectedScript.install()`, which sends `Page.setInitScripts` with a script per world (`__ctx_aux__`, `__ctx_caller__`
with worldKind "caller"): the engine creates the world when a document is created in the frame. `install()` is called once, in
`PageDispatcher._build`, after the events the page missed are replayed. This plugin records what the browser said and what the server said
to it, with times, so that a red run says in which order they happened.
What it records, per test (a time is `time.perf_counter()` in this process, written as ms from the start of the test):
* events the engine sent (heard by a listener of every `Connection`, registered at its birth): Page.navigationStarted / navigationCommitted /
navigationAborted / sameDocumentNavigation / frameAttached / frameDetached / eventFired, Runtime.executionContextsCleared /
executionContextCreated / executionContextDestroyed (frameId, world name, id), Browser.attachedToTarget / detachedFromTarget; the ones
delivered again to a page built after them (`BrowserDispatcher.replay`) carry `replay: true`;
* the commands the server sent (`Connection.send_placed`, wrapped on the CLASS, passing everything through): the command, its reduced
parameters (the worlds of `Page.setInitScripts`, the context of a `Runtime.evaluate`, the start of its expression) and its reply or error
with the time it took;
* marks: the phases of the test, `InjectedScript.install` (start, end), `InjectedScript.caller_context` (start, end or error, with the worlds
known for the frame at that moment), and `FrameDispatcher.op_set_content` (start, end or error), which is where `set_content` goes;
* the outcome of each phase of the test and the text of its failure.
Both modes of the `browser` fixture are traced: the in-process one and the stock-client one, because in both the server (JugglerServer) runs
in THIS process, on its own threads, and its `Connection` is the one hooked. What the stock client (the driver, a node process) says to
it is not seen; what the server does is. Nothing of src/ is touched: the hooks are installed at run time on the classes, and a hook that cannot
be installed (a name that moved) says so in the JSON (`hook_errors`) and the test goes on.
"""
from __future__ import annotations
import json
import os
import platform
import re
import threading
import time
import pytest
#: Events kept, by method; the rest of what the engine says (network, console, screencast) is not what this hunt asks.
_EVENTS = {
"Page.navigationStarted": ("frameId", "navigationId"),
"Page.navigationCommitted": ("frameId", "navigationId", "url"),
"Page.navigationAborted": ("frameId", "navigationId", "errorText"),
"Page.sameDocumentNavigation": ("frameId", "url"),
"Page.eventFired": ("frameId", "name"),
"Page.frameAttached": ("frameId", "parentFrameId"),
"Page.frameDetached": ("frameId",),
"Runtime.executionContextsCleared": (),
"Runtime.executionContextCreated": ("executionContextId",),
"Runtime.executionContextDestroyed": ("executionContextId",),
"Browser.attachedToTarget": (),
"Browser.detachedFromTarget": ("sessionId",),
}
#: Parameters kept of a command; a long text is cut.
_COMMAND_KEYS = ("frameId", "executionContextId", "url", "worldName", "name", "targetId", "browserContextId")
_CUT = 90
_FAILURE_CUT = 4000
_lock = threading.Lock()
_events: list = [] # [perf_counter, kind, method, detail, connection, session]
_state = {"connections": 0, "test": None, "hook_errors": [], "installed": False}
_replaying = threading.local()
def _now():
return time.perf_counter()
def _add(kind, method, detail, conn=None, session=None):
try:
row = (_now(), kind, method, detail, conn, session)
with _lock:
_events.append(row)
except Exception: # a recorder never costs the test
pass
def _cut(value):
text = str(value)
return text if len(text) <= _CUT else text[:_CUT] + "..."
def _event_detail(method, params):
params = params if isinstance(params, dict) else {}
out = {k: params[k] for k in _EVENTS[method] if params.get(k) is not None}
if method == "Runtime.executionContextCreated":
aux = params.get("auxData") or {}
out["frameId"] = aux.get("frameId")
out["world"] = aux.get("name") or ""
elif method == "Browser.attachedToTarget":
info = params.get("targetInfo") or {}
out.update({k: info[k] for k in ("targetId", "type", "url") if info.get(k) is not None})
if params.get("sessionId"):
out["sessionId"] = params["sessionId"]
if getattr(_replaying, "on", False):
out["replay"] = True
return out
def _command_detail(method, params):
params = params if isinstance(params, dict) else {}
out = {k: _cut(params[k]) for k in _COMMAND_KEYS if params.get(k) is not None}
if method == "Page.setInitScripts":
out["worlds"] = [[s.get("worldName"), s.get("worldKind"), len(s.get("script") or "")]
for s in params.get("scripts") or [] if isinstance(s, dict)]
for key in ("expression", "functionDeclaration"):
if params.get(key):
out[key] = _cut(params[key])
return out
# ---------------------------------------------------------------- the hooks on the classes
def _hook_connection():
"""Every Connection hears its events through one listener, registered when it is built (before its reader thread starts, so the first
events are not missed), and every command goes through `send_placed`, wrapped on the class."""
from invisible_core.juggler import connection as module
base, cls = module.EventListeners, module.Connection
original_init = base.__init__
original_send = cls.send_placed
def init(self, *args, **kwargs):
original_init(self, *args, **kwargs)
with _lock:
_state["connections"] += 1
label = "c%d" % _state["connections"]
self._hunt_label = label
def listen(method, params, session, _label=label):
if method in _EVENTS:
_add("event", method, _event_detail(method, params), _label, session)
self.add_listener(listen)
def send_placed(self, method, params=None, session=None, timeout=30.0):
label = getattr(self, "_hunt_label", None)
_add("send", method, _command_detail(method, params), label, session)
started = _now()
try:
answer = original_send(self, method, params, session, timeout)
except BaseException as failure:
_add("error", method, {"error": _cut(failure), "ms": round((_now() - started) * 1000, 1)}, label, session)
raise
_add("reply", method, {"ms": round((_now() - started) * 1000, 1)}, label, session)
return answer
base.__init__ = init
cls.send_placed = send_placed
def _worlds_of(injected, frame_id):
try:
return sorted("%s=%s" % (n or "''", v) for (f, n), v in list(injected.contexts.items()) if f == frame_id)
except Exception as failure:
return ["(unreadable: %s)" % failure]
def _hook_injected():
from invisible_core.juggler import injected as module
cls = module.InjectedScript
install, caller_context = cls.install, cls.caller_context
def label(self):
return getattr(self.c, "_hunt_label", None)
def hooked_install(self):
_add("mark", "install.start", {}, label(self), self.session)
try:
return install(self)
except BaseException as failure:
_add("mark", "install.error", {"error": _cut(failure)}, label(self), self.session)
raise
finally:
_add("mark", "install.end", {}, label(self), self.session)
def hooked_caller_context(self, frame_id, *args, **kwargs):
_add("mark", "caller_context.start", {"frameId": frame_id, "worlds": _worlds_of(self, frame_id)}, label(self), self.session)
try:
context = caller_context(self, frame_id, *args, **kwargs)
except BaseException as failure:
_add("mark", "caller_context.error",
{"frameId": frame_id, "error": _cut(failure), "worlds": _worlds_of(self, frame_id)}, label(self), self.session)
raise
_add("mark", "caller_context.end", {"frameId": frame_id, "executionContextId": context}, label(self), self.session)
return context
cls.install = hooked_install
cls.caller_context = hooked_caller_context
def _hook_server():
from invisible_playwright._juggler import server as module
frame_cls = module.FrameDispatcher
set_content = frame_cls.op_set_content
browser_cls = module.BrowserDispatcher
replay = browser_cls.replay
def hooked_set_content(self, params):
injected = getattr(self, "injected", None)
session = getattr(injected, "session", None)
conn = getattr(getattr(injected, "c", None), "_hunt_label", None)
frame_id = getattr(self, "frame_id", None)
detail = {"frameId": frame_id, "worlds": _worlds_of(injected, frame_id) if injected is not None else None,
"delivered": getattr(getattr(injected, "c", None), "delivered", None)}
_add("mark", "set_content.start", detail, conn, session)
try:
result = set_content(self, params)
except BaseException as failure:
_add("mark", "set_content.error", {"frameId": frame_id, "error": _cut(failure)}, conn, session)
raise
_add("mark", "set_content.end", {"frameId": frame_id}, conn, session)
return result
def hooked_replay(self, session, deliver):
_replaying.on = True
try:
return replay(self, session, deliver)
finally:
_replaying.on = False
frame_cls.op_set_content = hooked_set_content
browser_cls.replay = hooked_replay
def _install_hooks():
if _state["installed"]:
return
_state["installed"] = True
for hook in (_hook_connection, _hook_injected, _hook_server):
try:
hook()
except Exception as failure: # the hunt goes on without that part, and says so
_state["hook_errors"].append("%s: %s: %s" % (hook.__name__, type(failure).__name__, failure))
# ---------------------------------------------------------------- the tests
def pytest_configure(config):
_install_hooks()
def _safe(name):
return re.sub(r"[^A-Za-z0-9._-]+", "_", name)[-120:]
class _Current:
def __init__(self, item):
self.item = item
self.start = _now()
with _lock:
self.first = len(_events)
self.phases = {}
self.failure = {}
def _mode(item):
callspec = getattr(item, "callspec", None)
params = getattr(callspec, "params", {}) if callspec else {}
return params.get("browser") # "in-process" or "stock-client" (the fixture's param)
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_protocol(item, nextitem):
current = _state["test"] = _Current(item)
_add("mark", "test.start", {"nodeid": item.nodeid})
try:
yield
finally:
_add("mark", "test.end", {})
try:
_write(current)
except Exception as failure:
_state["hook_errors"].append("write: %s: %s" % (type(failure).__name__, failure))
_state["test"] = None
def _phase_marks(phase):
_add("mark", "test.%s.start" % phase, {})
outcome = yield
_add("mark", "test.%s.end" % phase, {"raised": outcome.excinfo is not None})
@pytest.hookimpl(hookwrapper=True, tryfirst=True)
def pytest_runtest_setup(item):
yield from _phase_marks("setup")
@pytest.hookimpl(hookwrapper=True, tryfirst=True)
def pytest_runtest_call(item):
yield from _phase_marks("call")
@pytest.hookimpl(hookwrapper=True, tryfirst=True)
def pytest_runtest_teardown(item):
yield from _phase_marks("teardown")
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
current = _state["test"]
if current is None:
return
report = outcome.get_result()
current.phases[call.when] = report.outcome
if report.outcome in ("failed",) or (report.outcome == "skipped" and call.when == "setup"):
text = str(report.longrepr)
current.failure[call.when] = text if len(text) <= _FAILURE_CUT else text[:_FAILURE_CUT] + "\n..."
def _verdict(phases):
if phases.get("setup") == "failed" or phases.get("teardown") == "failed":
return "error"
if phases.get("call") == "failed":
return "failed"
if phases.get("setup") == "skipped" or phases.get("call") == "skipped":
return "skipped"
return "passed" if phases.get("call") == "passed" else "unknown"
_sequence = {"n": 0}
def _write(current):
with _lock:
rows = list(_events[current.first:])
_sequence["n"] += 1
number = _sequence["n"]
base = current.start
events = [[round((t - base) * 1000, 2), kind, method, detail, conn, session]
for t, kind, method, detail, conn, session in rows]
item = current.item
tag = os.environ.get("HUNT_TRACE_TAG", "")
payload = {
"nodeid": item.nodeid,
"mode": _mode(item),
"outcome": _verdict(current.phases),
"phases": current.phases,
"failure": current.failure,
"tag": tag,
"system": platform.system(),
"pid": os.getpid(),
"sequence": number,
"hook_errors": list(_state["hook_errors"]),
"columns": ["ms_from_test_start", "kind", "method", "detail", "connection", "session"],
"events": events,
}
out = os.environ.get("HUNT_TRACE_DIR", "hunt-trace")
os.makedirs(out, exist_ok=True)
name = "%s%s-%04d-%s.json" % (_safe(tag) + "-" if tag else "", os.getpid(), number, _safe(item.nodeid.split("::", 1)[-1]))
with open(os.path.join(out, name), "w", encoding="utf-8", newline="\n") as handle:
json.dump(payload, handle, indent=1, default=str)
handle.write("\n")