Compare commits

...
2 changed files with 263 additions and 0 deletions

No files matched your search

+127
View File
@@ -0,0 +1,127 @@
# newtab-linux-hunt.yml - hunt scaffolding, never merged. Runs only on a push to a `hunt/newtab-linux**` branch.
#
# The memory of the content processes with and without the option that turns the preloaded New Tab page off, on Linux. This job
# runs the option's e2e twice and the measure on Linux, on the Windows engine a run of the series repository built,
# with the round's core, and then measures the memory of the content processes with and without the option (five alternating
# rounds). The tests and the wrapper package are this branch's (the round's wrapper plus this file and one script).
name: newtab linux hunt
on:
push:
branches: ['hunt/newtab-linux**']
permissions:
contents: read
env:
GITHUB_TOKEN: ${{ github.token }}
GH_TOKEN: ${{ github.token }}
ENGINE_RUN_ID: '43203723323'
ENGINE_REPO: feder-cr/firefox_antidetect_patch
CORE_REF: cc2f0cd47901fdfd8d266baf723e9fefffa46aac
SEAL_TAG: firefox-63-candidate
INVISIBLE_CORE_AUTOFIX: 'off'
INVISIBLE_CORE_PIN: allow
# the ten runs were green in run 43208482426 (10 of 10); this push measures the memory, with two more runs as a check
E2E_RUNS: '2'
jobs:
hunt:
name: preload_newtab e2e and memory (ubuntu-24.04, engine of run 43203723323)
runs-on: ubuntu-24.04
timeout-minutes: 75
defaults:
run:
shell: bash
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
with: { fetch-depth: 1 }
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
with: { python-version: '3.11' }
- name: The round's core (from git), this branch's wrapper
run: |
CORE_GIT="git+https://github.com/feder-cr/invisible_core@$CORE_REF"
python -m pip install --quiet --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 - <<'PY'
import inspect, json
from importlib.metadata import distribution, version
from invisible_core import prefs
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("invisible-core", version("invisible-core"), "from", got, "| invisible-playwright", version("invisible-playwright"))
print("compose_session_prefs knows preload_newtab:", "preload_newtab" in inspect.signature(prefs.compose_session_prefs).parameters)
PY
- name: System deps (xvfb + Firefox runtime libs)
run: |
sudo apt-get update
sudo apt-get install -y xvfb
sudo "$(which python)" -m playwright install-deps firefox
- name: The Linux engine of the run
run: |
set -e
mkdir -p art ff
gh run download "$ENGINE_RUN_ID" --repo "$ENGINE_REPO" --name asset-linux-x86_64 --dir art
set -- art/firefox-*-stealth-linux-x86_64.tar.gz
[ "$#" -eq 1 ] && [ -e "$1" ] || { echo "expected one firefox-*-stealth-linux-x86_64.tar.gz in art/, found: $*"; exit 1; }
tar xzf "$1" -C ff
chmod +x ff/firefox
python -m invisible_core seal --binary "$PWD/ff/firefox" --tag "$SEAL_TAG" -o "$PWD/seal.json"
echo "FF_EXE=$PWD/ff/firefox" >> "$GITHUB_ENV"
echo "INVISIBLE_SEAL_FILE=$PWD/seal.json" >> "$GITHUB_ENV"
- name: The preload_newtab e2e, ten times
env:
PYTHONUNBUFFERED: "1"
run: |
export INVPW_BINARY_PATH="$FF_EXE" STEALTHFOX_E2E_BINARY="$FF_EXE"
mkdir -p evidence/e2e
pass=0; fail=0
for n in $(seq 1 "${E2E_RUNS:-10}"); do
log="evidence/e2e/run_$(printf '%02d' "$n").log"
set +e
xvfb-run -a python -m pytest tests/test_preload_newtab_turns_the_privileged_about_process_off_e2e.py -m e2e -o addopts= \
-p no:cacheprovider --timeout 300 -q -rA > "$log" 2>&1
code=$?
set -e
skipped=$(grep -cE "^SKIPPED " "$log" || true)
passed=$(grep -cE "^PASSED " "$log" || true)
if [ "$code" = "0" ] && [ "$skipped" = "0" ] && [ "$passed" = "2" ]; then pass=$((pass+1)); else fail=$((fail+1)); fi
echo "run $n: exit=$code passed=$passed skipped=$skipped $(tail -1 "$log")"
done
{
echo "## preload_newtab e2e on ubuntu-24.04 (engine of run $ENGINE_RUN_ID, core $CORE_REF, tests $GITHUB_SHA)"
echo
echo "| runs with 2 passed and no skip | runs red |"
echo "|---|---|"
echo "| $pass | $fail |"
echo
echo '```'
grep -hE "^(FAILED|ERROR|SKIPPED) " evidence/e2e/run_*.log | sort | uniq -c | sort -rn | head -20 || true
echo '```'
} | tee -a "$GITHUB_STEP_SUMMARY"
- name: Memory of the content processes, with and without the option (five alternating rounds)
if: always()
env:
PYTHONUNBUFFERED: "1"
run: |
set +e
xvfb-run -a python scripts/newtab_memory_probe.py --binary "$FF_EXE" --out evidence/memory --rounds 5 --seconds 10 \
2>&1 | tee evidence/memory.log
sed -n '/^## Content processes/,$p' evidence/memory.log >> "$GITHUB_STEP_SUMMARY"
- name: Close every Firefox left
if: always()
run: |
pkill -9 -f "$PWD/ff/firefox" || true
sleep 1
echo "left: $(pgrep -fc "$PWD/ff/firefox" || true)"
- name: Upload all the evidence
if: always()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: newtab-linux-hunt-${{ github.run_id }}
path: evidence
if-no-files-found: warn
retention-days: 14
+136
View File
@@ -0,0 +1,136 @@
"""Hunt scaffolding (never merged): the memory of the content processes, with and without ``preload_newtab=False``.
python scripts/newtab_memory_probe.py --binary PATH --out DIR [--rounds 5] [--seconds 10]
Alternating rounds (default first, then the option; the next round the other way round). Each run starts the engine with the
library, opens one page of a local site, waits, then reads every content process below this script: its remote type from the
engine's own log (``Setting remoteType of process <pid> to <type>``, ``MOZ_LOG=Process:5,timestamp,sync``) and its memory
(working set on Windows, resident set elsewhere; private bytes where the system gives them). Writes one JSON per run and a
summary in markdown on stdout.
"""
import argparse
import http.server
import json
import os
import re
import statistics
import sys
import threading
import time
TYPE = re.compile(r"(?:Setting remoteType of process (\d+) to (\S+)|Changing remoteType of process (\d+) from \S+ to (\S+))")
def serve():
class Handler(http.server.BaseHTTPRequestHandler):
def log_message(self, *args):
pass
def do_GET(self):
body = b"<!doctype html><title>plain</title><p>plain"
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
server.daemon_threads = True
threading.Thread(target=server.serve_forever, daemon=True).start()
return server
def types_from_log(base):
found = {}
folder, stem = os.path.split(base)
for name in os.listdir(folder):
if name.startswith(stem):
with open(os.path.join(folder, name), encoding="utf-8", errors="replace") as fh:
for m in TYPE.finditer(fh.read()): # the last type a process was given is the one it has
pid, kind = (m.group(1), m.group(2)) if m.group(1) else (m.group(3), m.group(4))
found[int(pid)] = kind.split("^")[0]
return found
def one_run(binary, out, label, option, seconds, url):
import psutil
from invisible_playwright import InvisiblePlaywright
base = os.path.join(out, "moz_" + label)
os.environ["MOZ_LOG"] = "Process:5,timestamp,sync"
os.environ["MOZ_LOG_FILE"] = base
rows = []
try:
with InvisiblePlaywright(seed=7, binary_path=binary, headless=True, humanize=False, locale="en-US",
timezone="America/New_York", **option) as browser:
page = browser.new_context().new_page()
page.goto(url)
time.sleep(seconds)
types = types_from_log(base)
for proc in psutil.Process(os.getpid()).children(recursive=True):
try:
cmd = proc.cmdline()
if "-contentproc" not in cmd or cmd[-1] != "tab":
continue
mem = proc.memory_full_info() if hasattr(proc, "memory_full_info") else proc.memory_info()
private = getattr(mem, "private", None) or getattr(mem, "uss", None)
rows.append({"pid": proc.pid, "type": types.get(proc.pid, "?"), "rss_mb": round(mem.rss / 1e6, 1),
"private_mb": round(private / 1e6, 1) if private else None})
except (psutil.Error, IndexError):
continue
finally:
os.environ.pop("MOZ_LOG", None)
os.environ.pop("MOZ_LOG_FILE", None)
record = {"label": label, "option": option, "seconds": seconds, "processes": sorted(rows, key=lambda r: r["type"]),
"total_rss_mb": round(sum(r["rss_mb"] for r in rows), 1),
"total_private_mb": round(sum(r["private_mb"] or 0 for r in rows), 1)}
with open(os.path.join(out, label + ".json"), "w", encoding="utf-8") as fh:
json.dump(record, fh, indent=1)
return record
def main(argv=None):
ap = argparse.ArgumentParser()
ap.add_argument("--binary", required=True)
ap.add_argument("--out", required=True)
ap.add_argument("--rounds", type=int, default=5)
ap.add_argument("--seconds", type=float, default=10.0)
args = ap.parse_args(argv)
os.makedirs(args.out, exist_ok=True)
server = serve()
url = "http://127.0.0.1:%d/plain" % server.server_address[1]
arms = [("default", {}), ("preload_off", {"preload_newtab": False})]
records = []
try:
for n in range(1, args.rounds + 1):
for name, option in (arms if n % 2 else arms[::-1]):
rec = one_run(args.binary, args.out, "%s_%d" % (name, n), option, args.seconds, url)
records.append(rec)
print("%-14s total rss %7.1f MB, private %7.1f MB: %s" % (
rec["label"], rec["total_rss_mb"], rec["total_private_mb"],
[(p["type"], p["rss_mb"]) for p in rec["processes"]]), flush=True)
finally:
server.shutdown()
print("\n## Content processes, with and without preload_newtab=False (%d rounds, %s s, one page of a site)\n"
% (args.rounds, args.seconds))
print("| arm | runs | total RSS MB (min-max, median) | total private MB (median) | processes by type (median MB) |")
print("|---|---|---|---|---|")
for name, _ in arms:
mine = [r for r in records if r["label"].startswith(name + "_")]
if not mine:
continue
rss = [r["total_rss_mb"] for r in mine]
private = [r["total_private_mb"] for r in mine]
by_type = {}
for r in mine:
for p in r["processes"]:
by_type.setdefault(p["type"], []).append(p["rss_mb"])
kinds = ", ".join("%s x%.1f %.0f" % (t, len(v) / len(mine), statistics.median(v)) for t, v in sorted(by_type.items()))
print("| %s | %d | %.0f-%.0f, %.0f | %.0f | %s |" % (name, len(mine), min(rss), max(rss), statistics.median(rss),
statistics.median(private), kinds))
return 0
if __name__ == "__main__":
sys.exit(main())