Compare commits
36
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
467e336d34 | ||
|
|
8c28ab5c3d | ||
|
|
b348f39020 | ||
|
|
9a9d031343 | ||
|
|
d5865ab772 | ||
|
|
d0aca88a20 | ||
|
|
210796b7e8 | ||
|
|
dbb3203c93 | ||
|
|
4598c3f76c | ||
|
|
c4caddd937 | ||
|
|
9db36f3d64 | ||
|
|
e6afb39601 | ||
|
|
0b948cacfa | ||
|
|
cc6825266d | ||
|
|
8e552da446 | ||
|
|
4e1d09ff3e | ||
|
|
3384a2302b | ||
|
|
3f76fb8f6c | ||
|
|
c9dcb637bc | ||
|
|
3f551a84ce | ||
|
|
bbcb581cbc | ||
|
|
66a3590073 | ||
|
|
f30b218f83 | ||
|
|
9370052c26 | ||
|
|
f047fed9cd | ||
|
|
a749e03a00 | ||
|
|
5fce8645bd | ||
|
|
55c3ad68ff | ||
|
|
d7678e66f9 | ||
|
|
2179e69895 | ||
|
|
4cb7c77d92 | ||
|
|
a0917adc01 | ||
|
|
2d1884333e | ||
|
|
47d28358d1 | ||
|
|
77aa0bba37 | ||
|
|
f51d85bb5f |
No files matched your search
@@ -0,0 +1,230 @@
|
||||
# HUNT ONLY, never merged. The close of 4 browsers together on Windows, WITHOUT any deadline of the hunt, on the candidate 43843317541
|
||||
# (latitude/firefox-65, series 05522a48bdd8), core 0e35e35 (oss-invisible/core, fix/stroke-on-own-clock: close() waits for the browser's real
|
||||
# exit, `process.BROWSER_EXIT_LIMIT` = 80 s), wrapper 274fdc28 (release/0.53.0).
|
||||
# The earlier close hunts raised the deadlines of Connection.close and of the Reaper in the hunt itself (HUNT_CLOSE_TIMEOUT). Here nothing is
|
||||
# raised: scripts/hunt_candidate.py replaces those wrappers with stamps that only measure (and refuses to start when HUNT_CLOSE_TIMEOUT is
|
||||
# set); HUNTCLOSEARGS prints what Connection.close and the Reaper received.
|
||||
# Arms (a job each, the real Firefox in a job of its own): ours = cand4close (4 browsers in one process, idle until the session is 75 s old,
|
||||
# closed together), retail = retail4close (the official Firefox 159, 4 together, closed by its window 70 s after the first load).
|
||||
# Reported: how many browsers were terminated or killed instead of exiting by themselves (expected zero) and the exit code of every process
|
||||
# of each tree, and the close() duration (p50, p95, max) for ours and for retail.
|
||||
name: candidate close hunt
|
||||
on:
|
||||
push:
|
||||
branches: [hunt/published-latency]
|
||||
paths: [.github/workflows/candidate-close-hunt.yml]
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
concurrency:
|
||||
group: candidate-close-hunt
|
||||
cancel-in-progress: true
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
jobs:
|
||||
hunt:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
max-parallel: 2
|
||||
matrix:
|
||||
include:
|
||||
- { os: windows-2022, part: ours, arms: "cand4close" }
|
||||
- { os: windows-2022, part: retail, arms: "retail4close" }
|
||||
runs-on: ${{ matrix.os }}
|
||||
timeout-minutes: 90
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
env:
|
||||
PYTHONUNBUFFERED: "1"
|
||||
PART: ${{ matrix.part }}
|
||||
ONLY_ARMS: ${{ matrix.arms }}
|
||||
ROUNDS: "6"
|
||||
HUNT_CAND_CLOSE: "1"
|
||||
steps:
|
||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
with: { fetch-depth: 1 }
|
||||
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
|
||||
with: { python-version: "3.12" }
|
||||
- name: A venv (psutil; for ours also the core 0e35e35, the wrapper 274fdc28 and stock Playwright's driver)
|
||||
run: |
|
||||
P="$RUNNER_TEMP/after/Scripts/python"
|
||||
python -m venv "$RUNNER_TEMP/after"
|
||||
"$P" -m pip install -q --upgrade pip
|
||||
"$P" -m pip install -q psutil
|
||||
if [ "$PART" = ours ]; then
|
||||
"$P" -m pip install -q "invisible-playwright==0.52.1" websockets "playwright==$(cat scripts/playwright_pin.txt)"
|
||||
"$P" -m pip install -q --force-reinstall "git+https://github.com/oss-invisible/core@0e35e35f4a1017234c8cc51858c829de6f23ffc8"
|
||||
"$P" -m pip install -q --no-deps --force-reinstall "git+https://github.com/oss-invisible/playwright@274fdc2812e471f14039b2bef7e034efeae68a47"
|
||||
"$P" -c "
|
||||
import importlib.metadata as m, json
|
||||
for n in ('invisible-core', 'invisible-playwright'):
|
||||
d = m.distribution(n); u = json.loads(d.read_text('direct_url.json') or '{}')
|
||||
print(n, d.version, u.get('vcs_info', {}).get('commit_id'))
|
||||
import invisible_core.process as p
|
||||
print('BROWSER_EXIT_LIMIT', p.BROWSER_EXIT_LIMIT, 'SENDER_GRACE', __import__('invisible_core.juggler._profile', fromlist=['x']).SENDER_GRACE)
|
||||
"
|
||||
"$P" -m playwright install firefox
|
||||
fi
|
||||
echo "PY_AFTER=$P" >> "$GITHUB_ENV"
|
||||
- name: The engine of the candidate 43843317541, sealed for this run
|
||||
if: matrix.part == 'ours'
|
||||
run: |
|
||||
RUN=43843317541
|
||||
# The run's own state is printed, and the series is checked: a push before the build is green fails here, with the artifacts it lacks.
|
||||
gh run view "$RUN" -R oss-invisible/firefox_antidetect_patch --json status,conclusion,headSha,headBranch || true
|
||||
SHA=$(gh run view "$RUN" -R oss-invisible/firefox_antidetect_patch --json headSha --jq .headSha)
|
||||
case "$SHA" in 05522a48bdd8*) ;; *) echo "the run $RUN is not the series 05522a48bdd8 ($SHA)"; exit 1 ;; esac
|
||||
gh api "repos/oss-invisible/firefox_antidetect_patch/actions/runs/$RUN/artifacts" --jq '.artifacts[] | "artifact \(.name) \(.size_in_bytes) expired=\(.expired)"' | head -20
|
||||
mkdir -p "$RUNNER_TEMP/eng" && cd "$RUNNER_TEMP/eng"
|
||||
gh run download "$RUN" -R oss-invisible/firefox_antidetect_patch -n asset-win-x86_64 -D .
|
||||
unzip -q ./*.zip -d ff
|
||||
FF="$(cd ff && pwd -W)/firefox.exe"
|
||||
ls -l "$FF"; sha256sum "$FF"
|
||||
echo "FF_AFTER=$FF" >> "$GITHUB_ENV"
|
||||
cd "$GITHUB_WORKSPACE"
|
||||
"$PY_AFTER" -m invisible_core seal --binary "$FF" --tag firefox-65-candidate -o "$RUNNER_TEMP/seal.json"
|
||||
echo "INVISIBLE_SEAL_FILE=$RUNNER_TEMP/seal.json" >> "$GITHUB_ENV"
|
||||
- name: The retail Firefox 159.0 en-US (official)
|
||||
if: matrix.part == 'retail'
|
||||
run: |
|
||||
B=https://archive.mozilla.org/pub/firefox/releases/159.0/win64/en-US/
|
||||
R="$RUNNER_TEMP/retail"
|
||||
mkdir -p "$R"
|
||||
curl -fsSL --retry 3 -o "$R/package.exe" "${B}Firefox%20Setup%20159.0.exe"
|
||||
sha256sum "$R/package.exe"
|
||||
if command -v 7z > /dev/null 2>&1; then SZ=7z; else SZ="/c/Program Files/7-Zip/7z.exe"; fi
|
||||
"$SZ" x "$R/package.exe" -o"$R/win" -y > /dev/null
|
||||
FF="$R/win/core/firefox.exe"
|
||||
ls -l "$FF"; sha256sum "$FF"
|
||||
echo "FF_RETAIL=$FF" >> "$GITHUB_ENV"
|
||||
- name: Six rounds
|
||||
continue-on-error: true
|
||||
timeout-minutes: 70
|
||||
run: |
|
||||
set +e
|
||||
S=scripts/hunt_candidate.py
|
||||
if [ -n "$HUNT_CLOSE_TIMEOUT" ]; then echo "HUNT_CLOSE_TIMEOUT is set: this hunt raises no deadline"; exit 1; fi
|
||||
# What an arm prints: its HUNT lines, each tagged with the arm.
|
||||
keep() { grep --line-buffered -E '^HUNT(ROW|SLOW|PROBE|EVAL|SHUT|SURVIVOR|BGTASK|ALIVE|PARENTS|CLOSEARGS)' | sed -u -E "s/^(HUNT[A-Z]+) /\1 [$1] /"; }
|
||||
# A limit per arm: the arm's python writes its pid (HUNT_PIDFILE) and a watchdog kills that tree when the limit comes, printing the crash row.
|
||||
limit_of() {
|
||||
case "$1" in
|
||||
cand4close) echo 720 ;; retail4close) echo 400 ;; *) echo 400 ;;
|
||||
esac
|
||||
}
|
||||
kill_arm() {
|
||||
local pid
|
||||
for pid in $(cat "$HUNT_PIDFILE" 2>/dev/null); do taskkill //T //F //PID "$pid" > /dev/null 2>&1; done
|
||||
}
|
||||
run_arm() {
|
||||
local lim wd
|
||||
lim=$(limit_of "$1")
|
||||
export HUNT_PIDFILE="$RUNNER_TEMP/arm.pid" HUNT_ARM="$1" HUNT_LIMIT_S="$lim"
|
||||
: > "$HUNT_PIDFILE"
|
||||
rm -f "$RUNNER_TEMP/arm.done" "$HUNT_PIDFILE.fault"
|
||||
(
|
||||
exec > /dev/null
|
||||
sleep "$lim" > /dev/null 2>&1
|
||||
[ -e "$RUNNER_TEMP/arm.done" ] && exit 0
|
||||
echo "HUNTROW [$1] {\"arm\": \"$1\", \"round\": \"$2\", \"crash\": \"arm timed out after $lim s\"}" | tee -a "$RUNNER_TEMP/rows.log" >&2
|
||||
kill_arm
|
||||
) &
|
||||
wd=$!
|
||||
case "$1" in
|
||||
# 4 browsers in one process, idle until the session is 75 s old, then closed together. The shutdown log of the engine on (the
|
||||
# same preferences retail gets in its profile), nothing else, no timeout of the hunt.
|
||||
cand4close) HUNT_NCLOSE=1 HUNT_NCSHUT=1 HUNT_SESSION_S=75 "$PY_AFTER" $S inproc 4 "$2" "$FF_AFTER" 2>&1 | keep cand4close ;;
|
||||
retail4close) "$PY_AFTER" $S retail 4 "$2" "$FF_RETAIL" 70 2>&1 | keep retail4close ;;
|
||||
esac
|
||||
: > "$RUNNER_TEMP/arm.done"
|
||||
kill "$wd" > /dev/null 2>&1
|
||||
if [ -s "$HUNT_PIDFILE.fault" ]; then sed "s/^/HUNTALIVE [$1] fault: /" "$HUNT_PIDFILE.fault" | head -120; fi
|
||||
taskkill //F //IM firefox.exe //T > /dev/null 2>&1
|
||||
}
|
||||
read -ra ARMS <<< "$ONLY_ARMS"
|
||||
N=${#ARMS[@]}
|
||||
for r in $(seq 0 $((${ROUNDS:-6}-1))); do
|
||||
for k in $(seq 0 $((N-1))); do
|
||||
if [ "$SECONDS" -gt 3780 ]; then echo "time guard: no new arm after $SECONDS s"; break 2; fi
|
||||
a=${ARMS[$(( (k + r) % N ))]}; run_arm "$a" "r$r" | tee -a "$RUNNER_TEMP/rows.log"
|
||||
done
|
||||
done
|
||||
true
|
||||
- name: The table
|
||||
if: always()
|
||||
run: |
|
||||
python - "$RUNNER_TEMP/rows.log" <<'PY'
|
||||
import collections, json, re, sys
|
||||
rows, cargs = {}, []
|
||||
for line in open(sys.argv[1], encoding="utf-8"):
|
||||
m = re.match(r"HUNTROW \[(\w+)\] (.*)", line.strip())
|
||||
if m:
|
||||
rows.setdefault(m.group(1), []).append(json.loads(m.group(2)))
|
||||
continue
|
||||
m = re.match(r"HUNTCLOSEARGS \[(\w+)\] (.*)", line.strip())
|
||||
if m:
|
||||
cargs.append((m.group(1), json.loads(m.group(2))))
|
||||
def q(v, p):
|
||||
v = sorted(x for x in v if x is not None)
|
||||
return v[min(len(v) - 1, int(p * len(v)))] if v else None
|
||||
def trio(v):
|
||||
v = [x for x in v if x is not None]
|
||||
return "p50 %s p95 %s max %s (n %d)" % (q(v, .5), q(v, .95), max(v, default=None), len(v))
|
||||
def exits_of(r):
|
||||
c = collections.Counter()
|
||||
for x in r:
|
||||
for _pid, kind, rc, _ms in x.get("x_exits") or []:
|
||||
c[(kind, rc)] += 1
|
||||
return dict(sorted(c.items(), key=lambda kv: (kv[0][0], str(kv[0][1]))))
|
||||
# What the core was given: no deadline of the hunt anywhere. `effective_timeout` None = Connection.close's own limit (BROWSER_EXIT_LIMIT).
|
||||
seen = collections.Counter()
|
||||
for arm, a in cargs:
|
||||
if a.get("what") == "Connection.close" and a.get("mine"):
|
||||
seen[(arm, "Connection.close", "asked %s" % (a.get("asked"),), "effective %s" % (a.get("effective_timeout"),), "limit when None %s" % (a.get("limit_when_none"),))] += 1
|
||||
elif a.get("what") == "Reaper.__init__":
|
||||
seen[(arm, "Reaper", "grace %s" % (a.get("grace"),), "timeout %s" % (a.get("timeout"),))] += 1
|
||||
for k, n in sorted(seen.items()):
|
||||
print("HUNTCLOSE2ARGS %dx %s" % (n, " | ".join(k)))
|
||||
for arm in ("cand4close",):
|
||||
allr = rows.get(arm, [])
|
||||
r = [x for x in allr if "crash" not in x]
|
||||
if not allr:
|
||||
continue
|
||||
ended = [x for x in r if x.get("x_browser_ended")]
|
||||
print("HUNTCLOSE2 ours %s | browsers closed %d (crash rows %d, close errors %d, errors before the close %d) | TERMINATED OR KILLED instead of exiting by themselves: %d of %d | by cause: a browser process that is not the shutdown-ping sender was still alive when the core ended the tree %d, the launcher terminated by Connection.close %d, the wait for the browser's exit answered False %d | the sender (or its task) still alive after the reaper's grace and ended %d | the engine's own parent exit code (core_process_returncode) %s"
|
||||
% (arm, len(r), len(allr) - len(r), sum(1 for x in r if x.get("close_error")), sum(1 for x in r if x.get("error_before_close")), len(ended), len(r),
|
||||
sum(1 for x in r if x.get("x_left_nonsender")), sum(1 for x in r if x.get("x_conn_terminate")),
|
||||
sum(1 for x in r if any(w["ret"] is False for w in x.get("x_wait_browser_gone") or [])), sum(1 for x in r if x.get("x_left_sender")),
|
||||
dict(collections.Counter(str(x.get("core_process_returncode")) for x in r))))
|
||||
print("HUNTCLOSE2EXITS ours %s | exit code of every process of every tree (kind, code): count -> %s | the parents' codes by the hunt's own wait (one entry per parent process seen): %s" % (arm, exits_of(r), dict(collections.Counter(str(v.get("rc")) for x in r for v in (x.get("parent_exits") or {}).values()))))
|
||||
print("HUNTCLOSE2TIME ours %s | close() ms (the user's call to its return) %s | Connection.close returned, ms from the call %s | the real parent gone %s | the reaper finished %s | session s at close p50 %s"
|
||||
% (arm, trio([x.get("close_ms") for x in r]), trio([x.get("nc_conn_return") for x in r]), trio([x.get("nc_parent") for x in r]), trio([x.get("nc_reaper") for x in r]),
|
||||
q([x.get("session_s_at_close") for x in r], .5)))
|
||||
for x in r:
|
||||
print("HUNTCLOSE2ROW ours %s %s | close() %s ms | ended %s | left non-sender %s sender %s | exit codes %s | ends %s"
|
||||
% (arm, x.get("tag"), x.get("close_ms"), x.get("x_browser_ended"), x.get("x_left_nonsender"), x.get("x_left_sender"),
|
||||
dict(collections.Counter("%s:%s" % (k, rc) for _p, k, rc, _m in x.get("x_exits") or [])),
|
||||
[(e["after_ms"], e["dur_ms"], e["sent"]) for e in x.get("x_end_calls") or []]))
|
||||
for arm in ("retail4close",):
|
||||
allr = rows.get(arm, [])
|
||||
r = [x for x in allr if "crash" not in x]
|
||||
if not allr:
|
||||
continue
|
||||
print("HUNTCLOSE2 retail %s | browsers closed %d (crash rows %d) | killed by the hunt after 120 s %d | exited before the close %d | the close command's own code %s | exit codes of every process of every tree (kind, code): count -> %s"
|
||||
% (arm, len(r), len(allr) - len(r), sum(1 for x in r if x.get("close_timeout")), sum(1 for x in r if x.get("exited_before_close")),
|
||||
dict(collections.Counter(str((x.get("close_cmd") or [None])[0]) for x in r)), exits_of(r)))
|
||||
print("HUNTCLOSE2TIME retail %s | close() = the close command to the main process gone, ms %s | to the whole tree gone (the sender included) %s | session s p50 %s"
|
||||
% (arm, trio([x.get("close_main_ms") for x in r]), trio([x.get("close_ms") for x in r]), q([x.get("session_s") for x in r], .5)))
|
||||
PY
|
||||
grep -h "HUNTSLOWCLOSE" "$RUNNER_TEMP/rows.log" | cut -c1-1200 || true
|
||||
grep -h "HUNTSURVIVOR" "$RUNNER_TEMP/rows.log" | sed -E 's/"pid": [0-9]+, //' | sort -u | head -20 || true
|
||||
- name: Close every Firefox left
|
||||
if: always()
|
||||
run: |
|
||||
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
|
||||
echo done
|
||||
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
if: always()
|
||||
with: { name: "candidate-close-${{ matrix.part }}-${{ github.run_id }}", path: "${{ runner.temp }}/rows.log" }
|
||||
@@ -0,0 +1,174 @@
|
||||
# HUNT ONLY, never merged. WHY Browser.close() returns 0.5 to 2.6 s AFTER the core's Connection.close has, when 4 browsers of one Python process
|
||||
# close together on Windows. Probes only: no fix and no deadline raised (the script refuses to start with HUNT_CLOSE_TIMEOUT set).
|
||||
# The measured facts (run 43853094169, candidate-close-hunt.yml, cand4close, 24 closes): Connection.close returns at the browser's exit in 24 of 24;
|
||||
# in 9 of 24 Browser.close() returns 0.56 to 2.6 s later; the late returns look serialized across the 4 browsers (in a round all four were ~2.3 s late,
|
||||
# returning almost together; in three cases the delay equals another browser's EngineTree.end, waiting for its pingsender). The hypothesis to prove or
|
||||
# refute: the OTHER browsers' reapers (process scans, polling waits, psutil calls) hold the GIL or a shared lock and starve the thread that must deliver
|
||||
# the close's reply. Whatever the stacks show is reported.
|
||||
# Pins: engine = candidate run 43843317541 (series 05522a48bdd8), wrapper = oss-invisible/playwright at 30ee9e59 (release/0.53.0: after_the_reapers, Server.after_reapers), core = oss-invisible/core at 8c5e9dbd
|
||||
# (fix/stroke-on-own-clock, with #287: Reaper.then on a finished reaper runs the step on the non-daemon continuation thread invisible-reaper-then).
|
||||
# This round is the one WITH the fix: the verdict line HUNTCWVERDICT is PASS when no close of `together` returns more than 0.5 s after Connection.close.
|
||||
# Scenario of cand4close: 4 browsers in one process, idle until the session is 75 s old, closed together; the shutdown log of the engine on.
|
||||
# Arms (a job each, max-parallel 2): together = the 4 closes at once (as cand4close), sequential = the same 4 browsers, each close awaited before the next.
|
||||
# scripts/hunt_candidate_closewhy.py (imports scripts/hunt_candidate.py and scripts/hunt_published_latency.py, edits neither) puts around the close path of the
|
||||
# wrapper and of the core: wall-clock stamps with the thread's name; the stacks of ALL threads every 20 ms between the first Connection.close return and the
|
||||
# last Browser.close() return; the duration and thread of every reaper step; every psutil call counted per thread and call site. The table is printed in
|
||||
# each job's log; the third job (compare) prints together against sequential. The raw stamps and samples, and the readable files made from them
|
||||
# (report.txt, stamps.tsv, samples.txt), are the artifact of each job.
|
||||
name: candidate closewhy hunt
|
||||
on:
|
||||
push:
|
||||
branches: [hunt/published-latency]
|
||||
paths: [.github/workflows/candidate-closewhy-hunt.yml]
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
concurrency:
|
||||
group: candidate-closewhy-hunt
|
||||
cancel-in-progress: true
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
jobs:
|
||||
hunt:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
max-parallel: 2
|
||||
matrix:
|
||||
include:
|
||||
- { os: windows-2022, part: together }
|
||||
- { os: windows-2022, part: sequential }
|
||||
runs-on: ${{ matrix.os }}
|
||||
timeout-minutes: 90
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
env:
|
||||
PYTHONUNBUFFERED: "1"
|
||||
PART: ${{ matrix.part }}
|
||||
ROUNDS: "6"
|
||||
HUNT_NCLOSE: "1"
|
||||
HUNT_NCSHUT: "1"
|
||||
HUNT_SESSION_S: "75"
|
||||
HUNT_CW_MODE: ${{ matrix.part }}
|
||||
steps:
|
||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
with: { fetch-depth: 1 }
|
||||
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
|
||||
with: { python-version: "3.12" }
|
||||
- name: A venv (psutil, the core 8c5e9dbd, the wrapper 30ee9e59 and stock Playwright's driver)
|
||||
run: |
|
||||
P="$RUNNER_TEMP/after/Scripts/python"
|
||||
python -m venv "$RUNNER_TEMP/after"
|
||||
"$P" -m pip install -q --upgrade pip
|
||||
"$P" -m pip install -q psutil
|
||||
"$P" -m pip install -q "invisible-playwright==0.52.1" websockets "playwright==$(cat scripts/playwright_pin.txt)"
|
||||
"$P" -m pip install -q --force-reinstall "git+https://github.com/oss-invisible/core@8c5e9dbda105dc2a153085db25f9aaf839245e20"
|
||||
"$P" -m pip install -q --no-deps --force-reinstall "git+https://github.com/oss-invisible/playwright@30ee9e597c5434e4f1a17020fc2cea82ab303262"
|
||||
"$P" -c "
|
||||
import importlib.metadata as m, json
|
||||
for n in ('invisible-core', 'invisible-playwright'):
|
||||
d = m.distribution(n); u = json.loads(d.read_text('direct_url.json') or '{}')
|
||||
print(n, d.version, u.get('vcs_info', {}).get('commit_id'))
|
||||
import invisible_core.process as p
|
||||
print('BROWSER_EXIT_LIMIT', p.BROWSER_EXIT_LIMIT, 'SENDER_GRACE', __import__('invisible_core.juggler._profile', fromlist=['x']).SENDER_GRACE)
|
||||
"
|
||||
"$P" -m playwright install firefox
|
||||
echo "PY_AFTER=$P" >> "$GITHUB_ENV"
|
||||
echo "HUNT_CW_DIR=$RUNNER_TEMP/closewhy-$PART" >> "$GITHUB_ENV"
|
||||
- name: The engine of the candidate 43843317541, sealed for this run
|
||||
run: |
|
||||
RUN=43843317541
|
||||
# The run's own state is printed, and the series is checked: a push before the build is green fails here, with the artifacts it lacks.
|
||||
gh run view "$RUN" -R oss-invisible/firefox_antidetect_patch --json status,conclusion,headSha,headBranch || true
|
||||
SHA=$(gh run view "$RUN" -R oss-invisible/firefox_antidetect_patch --json headSha --jq .headSha)
|
||||
case "$SHA" in 05522a48bdd8*) ;; *) echo "the run $RUN is not the series 05522a48bdd8 ($SHA)"; exit 1 ;; esac
|
||||
# `head` closing the pipe early kills `gh` with SIGPIPE (exit 141 under pipefail): the listing is only printed, it never fails the step.
|
||||
gh api "repos/oss-invisible/firefox_antidetect_patch/actions/runs/$RUN/artifacts" --jq '.artifacts[] | "artifact \(.name) \(.size_in_bytes) expired=\(.expired)"' | head -20 || true
|
||||
mkdir -p "$RUNNER_TEMP/eng" && cd "$RUNNER_TEMP/eng"
|
||||
gh run download "$RUN" -R oss-invisible/firefox_antidetect_patch -n asset-win-x86_64 -D .
|
||||
unzip -q ./*.zip -d ff
|
||||
FF="$(cd ff && pwd -W)/firefox.exe"
|
||||
ls -l "$FF"; sha256sum "$FF"
|
||||
echo "FF_AFTER=$FF" >> "$GITHUB_ENV"
|
||||
cd "$GITHUB_WORKSPACE"
|
||||
"$PY_AFTER" -m invisible_core seal --binary "$FF" --tag firefox-65-candidate -o "$RUNNER_TEMP/seal.json"
|
||||
echo "INVISIBLE_SEAL_FILE=$RUNNER_TEMP/seal.json" >> "$GITHUB_ENV"
|
||||
- name: Six rounds
|
||||
continue-on-error: true
|
||||
timeout-minutes: 70
|
||||
run: |
|
||||
set +e
|
||||
S=scripts/hunt_candidate_closewhy.py
|
||||
if [ -n "$HUNT_CLOSE_TIMEOUT" ]; then echo "HUNT_CLOSE_TIMEOUT is set: this hunt raises no deadline"; exit 1; fi
|
||||
mkdir -p "$HUNT_CW_DIR"
|
||||
# What a round prints: its HUNT lines, each tagged with the arm. The probes' own files (the raw stamps and samples) go to $HUNT_CW_DIR.
|
||||
keep() { grep --line-buffered -E '^HUNT(ROW|SLOW|PROBE|EVAL|SHUT|SURVIVOR|BGTASK|ALIVE|PARENTS|CLOSEARGS|CW[A-Z]+)' | sed -u -E "s/^(HUNT[A-Z]+) /\1 [$1] /"; }
|
||||
# A limit per round: the round's python writes its pid (HUNT_PIDFILE) and a watchdog kills that tree when the limit comes, printing the crash row.
|
||||
LIMIT=720
|
||||
kill_arm() {
|
||||
local pid
|
||||
for pid in $(cat "$HUNT_PIDFILE" 2>/dev/null); do taskkill //T //F //PID "$pid" > /dev/null 2>&1; done
|
||||
}
|
||||
run_arm() {
|
||||
local wd
|
||||
export HUNT_PIDFILE="$RUNNER_TEMP/arm.pid" HUNT_ARM="$1" HUNT_LIMIT_S="$LIMIT"
|
||||
: > "$HUNT_PIDFILE"
|
||||
rm -f "$RUNNER_TEMP/arm.done" "$HUNT_PIDFILE.fault"
|
||||
(
|
||||
exec > /dev/null
|
||||
sleep "$LIMIT" > /dev/null 2>&1
|
||||
[ -e "$RUNNER_TEMP/arm.done" ] && exit 0
|
||||
echo "HUNTROW [$1] {\"arm\": \"$1\", \"round\": \"$2\", \"crash\": \"round timed out after $LIMIT s\"}" | tee -a "$RUNNER_TEMP/rows.log" >&2
|
||||
kill_arm
|
||||
) &
|
||||
wd=$!
|
||||
# 4 browsers in one process, idle until the session is 75 s old, then closed (HUNT_CW_MODE: together, or one after another).
|
||||
# The shutdown log of the engine on (the same preferences as the close hunt), nothing raised, no timeout of the hunt.
|
||||
"$PY_AFTER" $S run inproc 4 "$2" "$FF_AFTER" 2>&1 | keep "$1"
|
||||
: > "$RUNNER_TEMP/arm.done"
|
||||
kill "$wd" > /dev/null 2>&1
|
||||
if [ -s "$HUNT_PIDFILE.fault" ]; then sed "s/^/HUNTALIVE [$1] fault: /" "$HUNT_PIDFILE.fault" | head -120; fi
|
||||
taskkill //F //IM firefox.exe //T > /dev/null 2>&1
|
||||
}
|
||||
for r in $(seq 0 $((${ROUNDS:-6}-1))); do
|
||||
if [ "$SECONDS" -gt 3780 ]; then echo "time guard: no new round after $SECONDS s"; break; fi
|
||||
run_arm "cw-$PART" "r$r" | tee -a "$RUNNER_TEMP/rows.log"
|
||||
done
|
||||
true
|
||||
- name: The table
|
||||
if: always()
|
||||
run: |
|
||||
python scripts/hunt_candidate_closewhy.py report "$HUNT_CW_DIR" "$RUNNER_TEMP/rows.log" || true
|
||||
ls -l "$HUNT_CW_DIR" "$HUNT_CW_DIR/readable" 2>/dev/null || true
|
||||
- name: Close every Firefox left
|
||||
if: always()
|
||||
run: |
|
||||
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
|
||||
echo done
|
||||
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
if: always()
|
||||
with:
|
||||
name: "candidate-closewhy-${{ matrix.part }}-${{ github.run_id }}"
|
||||
path: |
|
||||
${{ runner.temp }}/closewhy-${{ matrix.part }}
|
||||
${{ runner.temp }}/rows.log
|
||||
compare:
|
||||
needs: hunt
|
||||
if: always()
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
with: { fetch-depth: 1 }
|
||||
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
|
||||
with: { python-version: "3.12" }
|
||||
- name: Together against sequential
|
||||
run: |
|
||||
mkdir -p art
|
||||
gh run download "$GITHUB_RUN_ID" -R "$GITHUB_REPOSITORY" -D art -p 'candidate-closewhy-*' || true
|
||||
find art -name 'closewhy-*.jsonl' | head -20 || true
|
||||
python scripts/hunt_candidate_closewhy.py compare art
|
||||
@@ -0,0 +1,201 @@
|
||||
# HUNT ONLY, never merged. IndexedDB at the quit, on Windows, the same 4-together scenario as the close hunt, on the candidate 43843317541
|
||||
# (latitude/firefox-65, series 05522a48bdd8), core 0e35e35, wrapper 274fdc28.
|
||||
# MOZ_LOG=IndexedDB:5,sync,timestamp with a file per process (MOZ_LOG_FILE=<dir>/ff-%PID.log), for ours (cand4idb: 4 browsers in one process, closed
|
||||
# when the session is 75 s old) and for the real Firefox 159 (retail4idb: 4 together, closed by their window 70 s after the first load), and the
|
||||
# Remote Settings client's own log (services.settings.loglevel=debug) in both, as in the earlier hunts. Goal: which Remote Settings readwrite
|
||||
# transactions are open at the quit and how long each lasts (ours spends about 2 s longer in profile-before-change, held by the blocker
|
||||
# "RemoteSettingsClient - finish IDB access."), and the census of the processes of each browser at its close, to see which process types differ
|
||||
# between ours and retail (ours shows 7 content/tab processes against retail's 5): command line type, birth, parent.
|
||||
# Nothing is raised or changed in the product (HUNT_CLOSE_TIMEOUT is refused), the stamps of the close hunt are in (scripts/hunt_candidate.py).
|
||||
# The logs are gzipped after each arm and uploaded: the IndexedDB log's shape is read by scripts/hunt_candidate_idb.py without assuming it, with a
|
||||
# sample of the raw lines printed, so a second reading can be made from the artifact without another run.
|
||||
name: candidate idb hunt
|
||||
on:
|
||||
push:
|
||||
branches: [hunt/published-latency]
|
||||
paths: [.github/workflows/candidate-idb-hunt.yml]
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
concurrency:
|
||||
group: candidate-idb-hunt
|
||||
cancel-in-progress: true
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
jobs:
|
||||
hunt:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
max-parallel: 2
|
||||
matrix:
|
||||
include:
|
||||
- { os: windows-2022, part: ours, arms: "cand4idb" }
|
||||
- { os: windows-2022, part: retail, arms: "retail4idb" }
|
||||
runs-on: ${{ matrix.os }}
|
||||
timeout-minutes: 90
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
env:
|
||||
PYTHONUNBUFFERED: "1"
|
||||
PART: ${{ matrix.part }}
|
||||
ONLY_ARMS: ${{ matrix.arms }}
|
||||
ROUNDS: "4"
|
||||
HUNT_CAND_CLOSE: "1"
|
||||
HUNT_CAND_IDB: "1"
|
||||
HUNT_RS: "1"
|
||||
steps:
|
||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
with: { fetch-depth: 1 }
|
||||
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
|
||||
with: { python-version: "3.12" }
|
||||
- name: A venv (psutil; for ours also the core 0e35e35, the wrapper 274fdc28 and stock Playwright's driver)
|
||||
run: |
|
||||
P="$RUNNER_TEMP/after/Scripts/python"
|
||||
python -m venv "$RUNNER_TEMP/after"
|
||||
"$P" -m pip install -q --upgrade pip
|
||||
"$P" -m pip install -q psutil
|
||||
if [ "$PART" = ours ]; then
|
||||
"$P" -m pip install -q "invisible-playwright==0.52.1" websockets "playwright==$(cat scripts/playwright_pin.txt)"
|
||||
"$P" -m pip install -q --force-reinstall "git+https://github.com/oss-invisible/core@0e35e35f4a1017234c8cc51858c829de6f23ffc8"
|
||||
"$P" -m pip install -q --no-deps --force-reinstall "git+https://github.com/oss-invisible/playwright@274fdc2812e471f14039b2bef7e034efeae68a47"
|
||||
"$P" -c "
|
||||
import importlib.metadata as m, json
|
||||
for n in ('invisible-core', 'invisible-playwright'):
|
||||
d = m.distribution(n); u = json.loads(d.read_text('direct_url.json') or '{}')
|
||||
print(n, d.version, u.get('vcs_info', {}).get('commit_id'))
|
||||
import invisible_core.process as p
|
||||
print('BROWSER_EXIT_LIMIT', p.BROWSER_EXIT_LIMIT, 'SENDER_GRACE', __import__('invisible_core.juggler._profile', fromlist=['x']).SENDER_GRACE)
|
||||
"
|
||||
"$P" -m playwright install firefox
|
||||
fi
|
||||
echo "PY_AFTER=$P" >> "$GITHUB_ENV"
|
||||
- name: The engine of the candidate 43843317541, sealed for this run
|
||||
if: matrix.part == 'ours'
|
||||
run: |
|
||||
RUN=43843317541
|
||||
# The run's own state is printed, and the series is checked: a push before the build is green fails here, with the artifacts it lacks.
|
||||
gh run view "$RUN" -R oss-invisible/firefox_antidetect_patch --json status,conclusion,headSha,headBranch || true
|
||||
SHA=$(gh run view "$RUN" -R oss-invisible/firefox_antidetect_patch --json headSha --jq .headSha)
|
||||
case "$SHA" in 05522a48bdd8*) ;; *) echo "the run $RUN is not the series 05522a48bdd8 ($SHA)"; exit 1 ;; esac
|
||||
gh api "repos/oss-invisible/firefox_antidetect_patch/actions/runs/$RUN/artifacts" --jq '.artifacts[] | "artifact \(.name) \(.size_in_bytes) expired=\(.expired)"' | head -20
|
||||
mkdir -p "$RUNNER_TEMP/eng" && cd "$RUNNER_TEMP/eng"
|
||||
gh run download "$RUN" -R oss-invisible/firefox_antidetect_patch -n asset-win-x86_64 -D .
|
||||
unzip -q ./*.zip -d ff
|
||||
FF="$(cd ff && pwd -W)/firefox.exe"
|
||||
ls -l "$FF"; sha256sum "$FF"
|
||||
echo "FF_AFTER=$FF" >> "$GITHUB_ENV"
|
||||
cd "$GITHUB_WORKSPACE"
|
||||
"$PY_AFTER" -m invisible_core seal --binary "$FF" --tag firefox-65-candidate -o "$RUNNER_TEMP/seal.json"
|
||||
echo "INVISIBLE_SEAL_FILE=$RUNNER_TEMP/seal.json" >> "$GITHUB_ENV"
|
||||
- name: The retail Firefox 159.0 en-US (official)
|
||||
if: matrix.part == 'retail'
|
||||
run: |
|
||||
B=https://archive.mozilla.org/pub/firefox/releases/159.0/win64/en-US/
|
||||
R="$RUNNER_TEMP/retail"
|
||||
mkdir -p "$R"
|
||||
curl -fsSL --retry 3 -o "$R/package.exe" "${B}Firefox%20Setup%20159.0.exe"
|
||||
sha256sum "$R/package.exe"
|
||||
if command -v 7z > /dev/null 2>&1; then SZ=7z; else SZ="/c/Program Files/7-Zip/7z.exe"; fi
|
||||
"$SZ" x "$R/package.exe" -o"$R/win" -y > /dev/null
|
||||
FF="$R/win/core/firefox.exe"
|
||||
ls -l "$FF"; sha256sum "$FF"
|
||||
echo "FF_RETAIL=$FF" >> "$GITHUB_ENV"
|
||||
- name: Four rounds
|
||||
continue-on-error: true
|
||||
timeout-minutes: 70
|
||||
run: |
|
||||
set +e
|
||||
S=scripts/hunt_candidate.py
|
||||
if [ -n "$HUNT_CLOSE_TIMEOUT" ]; then echo "HUNT_CLOSE_TIMEOUT is set: this hunt raises no deadline"; exit 1; fi
|
||||
# What an arm prints: its HUNT lines, each tagged with the arm.
|
||||
keep() { grep --line-buffered -E '^HUNT(ROW|SLOW|PROBE|EVAL|SHUT|SURVIVOR|BGTASK|ALIVE|PARENTS|CLOSEARGS)' | sed -u -E "s/^(HUNT[A-Z]+) /\1 [$1] /"; }
|
||||
# A limit per arm: the arm's python writes its pid (HUNT_PIDFILE) and a watchdog kills that tree when the limit comes, printing the crash row.
|
||||
limit_of() {
|
||||
case "$1" in
|
||||
cand4idb) echo 720 ;; retail4idb) echo 400 ;; *) echo 400 ;;
|
||||
esac
|
||||
}
|
||||
kill_arm() {
|
||||
local pid
|
||||
for pid in $(cat "$HUNT_PIDFILE" 2>/dev/null); do taskkill //T //F //PID "$pid" > /dev/null 2>&1; done
|
||||
}
|
||||
run_arm() {
|
||||
local lim wd
|
||||
lim=$(limit_of "$1")
|
||||
export HUNT_PIDFILE="$RUNNER_TEMP/arm.pid" HUNT_ARM="$1" HUNT_LIMIT_S="$lim" HUNT_MOZLOG_DIR="$RUNNER_TEMP/mozlog/$2-$1"
|
||||
: > "$HUNT_PIDFILE"
|
||||
rm -f "$RUNNER_TEMP/arm.done" "$HUNT_PIDFILE.fault"
|
||||
(
|
||||
exec > /dev/null
|
||||
sleep "$lim" > /dev/null 2>&1
|
||||
[ -e "$RUNNER_TEMP/arm.done" ] && exit 0
|
||||
echo "HUNTROW [$1] {\"arm\": \"$1\", \"round\": \"$2\", \"crash\": \"arm timed out after $lim s\"}" | tee -a "$RUNNER_TEMP/rows.log" >&2
|
||||
kill_arm
|
||||
) &
|
||||
wd=$!
|
||||
case "$1" in
|
||||
# 4 browsers in one process, idle until the session is 75 s old, then closed together. The shutdown log of the engine on (the
|
||||
# same preferences retail gets in its profile), nothing else, no timeout of the hunt.
|
||||
cand4idb) HUNT_NCLOSE=1 HUNT_NCSHUT=1 HUNT_SESSION_S=75 "$PY_AFTER" $S inproc 4 "$2" "$FF_AFTER" 2>&1 | keep cand4idb ;;
|
||||
retail4idb) "$PY_AFTER" $S retail 4 "$2" "$FF_RETAIL" 70 2>&1 | keep retail4idb ;;
|
||||
esac
|
||||
: > "$RUNNER_TEMP/arm.done"
|
||||
kill "$wd" > /dev/null 2>&1
|
||||
if [ -s "$HUNT_PIDFILE.fault" ]; then sed "s/^/HUNTALIVE [$1] fault: /" "$HUNT_PIDFILE.fault" | head -120; fi
|
||||
taskkill //F //IM firefox.exe //T > /dev/null 2>&1
|
||||
# The logs of this arm, compressed (they are text; the artifact keeps them for a second reading).
|
||||
find "$HUNT_MOZLOG_DIR" -type f -name 'ff-*' ! -name '*.gz' -exec gzip -f {} + > /dev/null 2>&1
|
||||
echo "mozlog $2-$1: $(find "$HUNT_MOZLOG_DIR" -type f 2>/dev/null | wc -l) files, $(du -sk "$HUNT_MOZLOG_DIR" 2>/dev/null | cut -f1) KB"
|
||||
}
|
||||
read -ra ARMS <<< "$ONLY_ARMS"
|
||||
N=${#ARMS[@]}
|
||||
for r in $(seq 0 $((${ROUNDS:-6}-1))); do
|
||||
for k in $(seq 0 $((N-1))); do
|
||||
if [ "$SECONDS" -gt 3780 ]; then echo "time guard: no new arm after $SECONDS s"; break 2; fi
|
||||
a=${ARMS[$(( (k + r) % N ))]}; run_arm "$a" "r$r" | tee -a "$RUNNER_TEMP/rows.log"
|
||||
done
|
||||
done
|
||||
true
|
||||
- name: The table
|
||||
if: always()
|
||||
run: |
|
||||
python - "$RUNNER_TEMP/rows.log" <<'PY'
|
||||
import collections, json, re, sys
|
||||
rows = {}
|
||||
for line in open(sys.argv[1], encoding="utf-8"):
|
||||
m = re.match(r"HUNTROW \[(\w+)\] (.*)", line.strip())
|
||||
if m:
|
||||
rows.setdefault(m.group(1), []).append(json.loads(m.group(2)))
|
||||
def q(v, p):
|
||||
v = sorted(x for x in v if x is not None)
|
||||
return v[min(len(v) - 1, int(p * len(v)))] if v else None
|
||||
def trio(v):
|
||||
v = [x for x in v if x is not None]
|
||||
return "p50 %s p95 %s max %s (n %d)" % (q(v, .5), q(v, .95), max(v, default=None), len(v))
|
||||
# Where the 2 s is: the close -> the quit (the first "Starting phase" line), the quit -> the main process gone (profile-before-change and
|
||||
# what follows), and the blocker of the Remote Settings client, per arm.
|
||||
for arm, a in sorted(rows.items()):
|
||||
r = [x for x in a if "crash" not in x]
|
||||
print("HUNTIDBTIME %-11s browsers %d (crash rows %d) | close -> quit ms %s | quit -> main process gone ms %s | close -> main gone ms %s | RS finish-IDB blocker done at quit+ms %s | RS writes at the close %s"
|
||||
% (arm, len(r), len(a) - len(r), trio([x.get("a_close_to_quit_ms") for x in r]), trio([x.get("b_quit_to_main_gone_ms") for x in r]),
|
||||
trio([x.get("close_to_main_gone_ms") for x in r]), trio([x.get("rs_idb_done_q_ms") for x in r]), dict(collections.Counter(str(x.get("rs_write_kinds_at_close")) for x in r))))
|
||||
for x in r:
|
||||
ph = x.get("phases") or {}
|
||||
print("HUNTIDBPHASE %-11s %s | profile-before-change starts at quit+ms %s finishes %s | pending blockers at the parent's exit %s"
|
||||
% (arm, x.get("tag"), (ph.get("profile-before-change") or [None, None])[0], (ph.get("profile-before-change") or [None, None])[1], x.get("pending_blockers")))
|
||||
PY
|
||||
python scripts/hunt_candidate_idb.py "$RUNNER_TEMP/rows.log" "$RUNNER_TEMP/mozlog" | cut -c1-1500
|
||||
grep -h "HUNTSLOWCLOSE" "$RUNNER_TEMP/rows.log" | cut -c1-1200 || true
|
||||
- name: Close every Firefox left
|
||||
if: always()
|
||||
run: |
|
||||
taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true
|
||||
echo done
|
||||
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
if: always()
|
||||
with: { name: "candidate-idb-rows-${{ matrix.part }}-${{ github.run_id }}", path: "${{ runner.temp }}/rows.log" }
|
||||
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
if: always()
|
||||
with: { name: "candidate-idb-mozlog-${{ matrix.part }}-${{ github.run_id }}", path: "${{ runner.temp }}/mozlog", retention-days: 7 }
|
||||
@@ -0,0 +1,511 @@
|
||||
# HUNT ONLY, never merged. Criterion 1b, the final measure of the MOUSE, on the candidate 43843317541 (latitude/firefox-65, series
|
||||
# 05522a48bdd8): what the page saw (mousemove, mousedown, mouseup, event.timeStamp and the handler's clock, with clientX/clientY) against the plan
|
||||
# the client sent, in three configurations: Windows "one" (1 browser per process, 4 processes at once), Windows "inproc4" (4 browsers in one
|
||||
# process), Linux "one". Core = 0e35e35 (oss-invisible/core, fix/stroke-on-own-clock: the path of the pointer is a stroke, `Actions.walk`),
|
||||
# wrapper = release/0.53.0 (274fdc28).
|
||||
# The plan: every Page.dispatchMouseEvent the core's client sends, with its `stroke` and `at`, recorded around the product by
|
||||
# scripts/hunt_candidate.py (HUNT_CAND_MOUSE=1: Stroke.send, Actions._mouse_event outside a stroke, Actions.walk, the press settle). Nothing in
|
||||
# a test, nothing changes what the product does. Joined to the page's events by the identity of the browser's core connection (exact), and
|
||||
# each page move to the plan point it is by its coordinates. Reported per configuration, three lines: (a) pauses = page gaps over the plan's by
|
||||
# more than 50 ms, (b) bursts = points the plan spaces by 8 ms or more that the page saw less than 2 ms apart, (c) the settle before the press.
|
||||
name: candidate typing hunt
|
||||
on:
|
||||
push:
|
||||
branches: [hunt/published-latency]
|
||||
paths: [.github/workflows/candidate-typing-hunt.yml]
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
concurrency:
|
||||
group: candidate-typing-hunt
|
||||
cancel-in-progress: true
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
jobs:
|
||||
hunt:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
max-parallel: 2
|
||||
matrix:
|
||||
include:
|
||||
- { os: windows-2022, arms: "one inproc4" }
|
||||
- { os: ubuntu-24.04, arms: "one" }
|
||||
runs-on: ${{ matrix.os }}
|
||||
timeout-minutes: 90
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
env:
|
||||
PYTHONUNBUFFERED: "1"
|
||||
ONLY_ARMS: ${{ matrix.arms }}
|
||||
ROUNDS: "6"
|
||||
HUNT_CAND_MOUSE: "1"
|
||||
steps:
|
||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
with: { fetch-depth: 1 }
|
||||
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
|
||||
with: { python-version: "3.12" }
|
||||
- name: A venv with the core 0e35e35 (the path of the pointer is a stroke) and the wrapper 274fdc28 (release/0.53.0), and stock Playwright
|
||||
run: |
|
||||
if [ "$RUNNER_OS" = "Windows" ]; then BIN=Scripts; else BIN=bin; fi
|
||||
P="$RUNNER_TEMP/after/$BIN/python"
|
||||
python -m venv "$RUNNER_TEMP/after"
|
||||
"$P" -m pip install -q --upgrade pip
|
||||
"$P" -m pip install -q "invisible-playwright==0.52.1" psutil websockets "playwright==$(cat scripts/playwright_pin.txt)"
|
||||
"$P" -m pip install -q --force-reinstall "git+https://github.com/oss-invisible/core@0e35e35f4a1017234c8cc51858c829de6f23ffc8"
|
||||
"$P" -m pip install -q --no-deps --force-reinstall "git+https://github.com/oss-invisible/playwright@274fdc2812e471f14039b2bef7e034efeae68a47"
|
||||
"$P" -c "
|
||||
import importlib.metadata as m, json
|
||||
for n in ('invisible-core', 'invisible-playwright'):
|
||||
d = m.distribution(n); u = json.loads(d.read_text('direct_url.json') or '{}')
|
||||
print(n, d.version, u.get('vcs_info', {}).get('commit_id'))
|
||||
import invisible_core.juggler._stroke as s, invisible_core.juggler.actions as a
|
||||
print('stroke client:', s.__name__, 'Actions.walk:', hasattr(a.Actions, 'walk'))
|
||||
"
|
||||
if [ "$RUNNER_OS" = "Linux" ]; then sudo apt-get update -q && sudo apt-get install -y -q xvfb; "$P" -m playwright install --with-deps firefox; else "$P" -m playwright install firefox; fi
|
||||
echo "PY_AFTER=$P" >> "$GITHUB_ENV"
|
||||
- name: The engine of the candidate 43843317541, sealed for this run
|
||||
run: |
|
||||
RUN=43843317541
|
||||
# The run's own state is printed, and the series is checked: a push before the build is green fails here, with the artifacts it lacks.
|
||||
gh run view "$RUN" -R oss-invisible/firefox_antidetect_patch --json status,conclusion,headSha,headBranch || true
|
||||
SHA=$(gh run view "$RUN" -R oss-invisible/firefox_antidetect_patch --json headSha --jq .headSha)
|
||||
case "$SHA" in 05522a48bdd8*) ;; *) echo "the run $RUN is not the series 05522a48bdd8 ($SHA)"; exit 1 ;; esac
|
||||
gh api "repos/oss-invisible/firefox_antidetect_patch/actions/runs/$RUN/artifacts" --jq '.artifacts[] | "artifact \(.name) \(.size_in_bytes) expired=\(.expired)"' | head -20 || true
|
||||
mkdir -p "$RUNNER_TEMP/eng" && cd "$RUNNER_TEMP/eng"
|
||||
if [ "$RUNNER_OS" = "Windows" ]; then
|
||||
gh run download "$RUN" -R oss-invisible/firefox_antidetect_patch -n asset-win-x86_64 -D .
|
||||
unzip -q ./*.zip -d ff
|
||||
FF="$(cd ff && pwd -W)/firefox.exe"
|
||||
else
|
||||
gh run download "$RUN" -R oss-invisible/firefox_antidetect_patch -n asset-linux-x86_64 -D .
|
||||
mkdir ff && tar -xzf ./*.tar.gz -C ff
|
||||
FF="$(find "$PWD/ff" -maxdepth 2 -type f -name firefox | head -1)"
|
||||
fi
|
||||
ls -l "$FF"; sha256sum "$FF"
|
||||
echo "FF_AFTER=$FF" >> "$GITHUB_ENV"
|
||||
cd "$GITHUB_WORKSPACE"
|
||||
"$PY_AFTER" -m invisible_core seal --binary "$FF" --tag firefox-65-candidate -o "$RUNNER_TEMP/seal.json"
|
||||
echo "INVISIBLE_SEAL_FILE=$RUNNER_TEMP/seal.json" >> "$GITHUB_ENV"
|
||||
- name: Six rounds, the arms in rotating order
|
||||
continue-on-error: true
|
||||
timeout-minutes: 70
|
||||
run: |
|
||||
set +e
|
||||
S=scripts/hunt_candidate.py
|
||||
# What an arm prints: its HUNT lines, each tagged with the arm.
|
||||
keep() { grep --line-buffered -E '^HUNT(ROW|SLOW|PROBE|EVAL|SHUT|SURVIVOR|BGTASK)' | sed -u -E "s/^(HUNT[A-Z]+) /\1 [$1] /"; }
|
||||
# The retail arms: N browsers, round, seconds after the first load before the normal close (Linux headed under xvfb).
|
||||
retail() {
|
||||
if [ -z "$FF_RETAIL" ]; then echo "HUNTROW {\"arm\": \"retail\", \"crash\": \"no retail Firefox\"}"; return; fi
|
||||
if [ "$RUNNER_OS" = "Linux" ]; then
|
||||
# A window manager in the virtual display, so the retail browser can be closed as a person closes it (wmctrl ->
|
||||
# _NET_CLOSE_WINDOW -> WM_DELETE_WINDOW); without one only a signal is left, which is not a normal quit.
|
||||
xvfb-run -a -s "-screen 0 1280x1024x24" sh -c 'openbox > /dev/null 2>&1 & sleep 1; exec "$0" "$@"' "$PY_AFTER" $S retail "$1" "$2" "$FF_RETAIL" "$3" 2>&1
|
||||
else
|
||||
"$PY_AFTER" $S retail "$1" "$2" "$FF_RETAIL" "$3" 2>&1
|
||||
fi
|
||||
}
|
||||
# A limit per arm, shorter than the step's: 4 times what the arm should take, at most 12 minutes. The arm's python writes its pid
|
||||
# (HUNT_PIDFILE, one line per process) and a watchdog kills that tree when the limit comes, printing the crash row; the next
|
||||
# arm then runs. The watchdog's output is kept off the arm's pipe (a sleep left behind must not hold the tee).
|
||||
limit_of() {
|
||||
local e
|
||||
case "$1" in
|
||||
solo|nclose20) e=30 ;; shut20) e=30 ;; inproc4|inproc4quiet|inproc4tz|inproc4px|stock|nclose20x4) e=35 ;;
|
||||
one|remote|retail1|retail4) e=45 ;; shut70|nclose75) e=85 ;; nclose75x4) e=95 ;; late|retail4late) e=100 ;;
|
||||
shut180|retail1long) e=200 ;; *) e=100 ;;
|
||||
esac
|
||||
echo $(( e * 4 > 720 ? 720 : e * 4 ))
|
||||
}
|
||||
kill_arm() {
|
||||
local pid
|
||||
for pid in $(cat "$HUNT_PIDFILE" 2>/dev/null); do
|
||||
if [ "$RUNNER_OS" = "Windows" ]; then taskkill //T //F //PID "$pid" > /dev/null 2>&1; else pkill -9 -P "$pid" > /dev/null 2>&1; kill -9 "$pid" > /dev/null 2>&1; fi
|
||||
done
|
||||
}
|
||||
run_arm() {
|
||||
local lim wd
|
||||
lim=$(limit_of "$1")
|
||||
export HUNT_PIDFILE="$RUNNER_TEMP/arm.pid" HUNT_ARM="$1" HUNT_LIMIT_S="$lim"
|
||||
: > "$HUNT_PIDFILE"
|
||||
rm -f "$RUNNER_TEMP/arm.done" "$HUNT_PIDFILE.fault"
|
||||
(
|
||||
exec > /dev/null
|
||||
sleep "$lim" > /dev/null 2>&1
|
||||
[ -e "$RUNNER_TEMP/arm.done" ] && exit 0
|
||||
echo "HUNTROW [$1] {\"arm\": \"$1\", \"round\": \"$2\", \"crash\": \"arm timed out after $lim s\"}" | tee -a "$RUNNER_TEMP/rows.log" >&2
|
||||
kill_arm
|
||||
) &
|
||||
wd=$!
|
||||
case "$1" in
|
||||
inproc4) "$PY_AFTER" $S inproc 4 "$2" "$FF_AFTER" 2>&1 | keep inproc4 ;;
|
||||
inproc4quiet) HUNT_NO_SAMPLER=1 "$PY_AFTER" $S inproc 4 "$2" "$FF_AFTER" 2>&1 | keep inproc4quiet ;;
|
||||
inproc4tz) HUNT_TIMEZONE=Europe/Rome "$PY_AFTER" $S inproc 4 "$2" "$FF_AFTER" 2>&1 | keep inproc4tz ;;
|
||||
inproc4px) HUNT_PROXY=1 "$PY_AFTER" $S inproc 4 "$2" "$FF_AFTER" 2>&1 | keep inproc4px ;;
|
||||
late) HUNT_TYPE_LATE_S=60 "$PY_AFTER" $S inproc 4 "$2" "$FF_AFTER" 2>&1 | keep late ;;
|
||||
solo) "$PY_AFTER" $S inproc 1 "$2" "$FF_AFTER" 2>&1 | keep solo ;;
|
||||
remote) "$PY_AFTER" $S remote 4 "$2" "$FF_AFTER" 2>&1 | keep remote ;;
|
||||
stock) "$PY_AFTER" $S stock 4 "$2" 2>&1 | keep stock ;;
|
||||
one) for k in 0 1 2 3; do "$PY_AFTER" $S inproc 1 "$2-$k" "$FF_AFTER" > "$RUNNER_TEMP/one-$k.log" 2>&1 & done; wait
|
||||
cat "$RUNNER_TEMP"/one-*.log | keep one ;;
|
||||
shut20) HUNT_SHUT=1 HUNT_SESSION_S=20 "$PY_AFTER" $S inproc 1 "$2" "$FF_AFTER" 2>&1 | keep shut20 ;;
|
||||
shut70) HUNT_SHUT=1 HUNT_SESSION_S=70 "$PY_AFTER" $S inproc 1 "$2" "$FF_AFTER" 2>&1 | keep shut70 ;;
|
||||
shut180) HUNT_SHUT=1 HUNT_SESSION_S=180 "$PY_AFTER" $S inproc 1 "$2" "$FF_AFTER" 2>&1 | keep shut180 ;;
|
||||
nclose20) HUNT_NCLOSE=1 HUNT_SESSION_S=20 "$PY_NEXT" $S inproc 1 "$2" "$FF_AFTER" 2>&1 | keep nclose20 ;;
|
||||
nclose75) HUNT_NCLOSE=1 HUNT_SESSION_S=75 "$PY_NEXT" $S inproc 1 "$2" "$FF_AFTER" 2>&1 | keep nclose75 ;;
|
||||
nclose20x4) HUNT_NCLOSE=1 HUNT_SESSION_S=20 "$PY_NEXT" $S inproc 4 "$2" "$FF_AFTER" 2>&1 | keep nclose20x4 ;;
|
||||
nclose75x4) HUNT_NCLOSE=1 HUNT_SESSION_S=75 "$PY_NEXT" $S inproc 4 "$2" "$FF_AFTER" 2>&1 | keep nclose75x4 ;;
|
||||
retail1) retail 1 "$2" 20 | keep retail1 ;;
|
||||
retail1long) retail 1 "$2" 180 | keep retail1long ;;
|
||||
retail4) retail 4 "$2" 20 | keep retail4 ;;
|
||||
retail4late) retail 4 "$2" 70 | keep retail4late ;;
|
||||
esac
|
||||
: > "$RUNNER_TEMP/arm.done"
|
||||
kill "$wd" > /dev/null 2>&1
|
||||
if [ "$RUNNER_OS" = "Windows" ]; then taskkill //F //IM firefox.exe //T > /dev/null 2>&1; else pkill -9 -f firefox > /dev/null 2>&1; fi
|
||||
}
|
||||
# The full list (the default when the focused one below is removed):
|
||||
# inproc4 inproc4quiet inproc4tz inproc4px late solo one remote stock retail1 retail4 retail4late
|
||||
# The shutdown hunt: why our engine on Windows does not exit within the core's 5 s after a long session. shut20/70/180 are
|
||||
# ours (one browser per process, idle until the session is 20/70/180 s old, then closed, the engine's shutdown log timed),
|
||||
# the retail ones are the real Firefox closed by its window after 20 s / 70 s (4 together) / 180 s.
|
||||
# shut20 shut70 shut180 retail1 retail4late retail1long (the shutdown hunt of the run before)
|
||||
# The close of the core with a reaper (venv "next", git main of the core and the wrapper's fix branch), 1 browser and 4 in one
|
||||
# process, closed after 20 s / 75 s of session, against the real Firefox closed by its window, and ours as published (shut70).
|
||||
ARMS=(nclose20 nclose75 nclose20x4 nclose75x4 retail1 retail4late shut70)
|
||||
if [ -n "$ONLY_ARMS" ]; then read -ra ARMS <<< "$ONLY_ARMS"; fi
|
||||
N=${#ARMS[@]}
|
||||
for r in $(seq 0 $((${ROUNDS:-6}-1))); do
|
||||
for k in $(seq 0 $((N-1))); do
|
||||
if [ "$SECONDS" -gt 3780 ]; then echo "time guard: no new arm after $SECONDS s"; break 2; fi
|
||||
a=${ARMS[$(( (k + r) % N ))]}; run_arm "$a" "r$r" | tee -a "$RUNNER_TEMP/rows.log"
|
||||
done
|
||||
done
|
||||
true
|
||||
- name: The table
|
||||
if: always()
|
||||
run: |
|
||||
python - "$RUNNER_TEMP/rows.log" <<'PY'
|
||||
import json, re, sys, statistics
|
||||
rows = {}
|
||||
for line in open(sys.argv[1], encoding="utf-8"):
|
||||
m = re.match(r"HUNTROW \[(\w+)\] (.*)", line.strip())
|
||||
if m:
|
||||
rows.setdefault(m.group(1), []).append(json.loads(m.group(2)))
|
||||
def q(v, p):
|
||||
v = sorted(x for x in v if x is not None)
|
||||
return v[min(len(v) - 1, int(p * len(v)))] if v else None
|
||||
def cnt(v):
|
||||
c = {}
|
||||
for x in v:
|
||||
c[str(x)] = c.get(str(x), 0) + 1
|
||||
return dict(sorted(c.items(), key=lambda kv: -kv[1])[:8])
|
||||
def trio(v):
|
||||
return "p50 %s p95 %s max %s" % (q(v, .5), q(v, .95), max((x for x in v if x is not None), default=None))
|
||||
for arm in ("inproc4", "inproc4quiet", "inproc4tz", "inproc4px", "late", "solo", "one", "remote", "stock", "shut20", "shut70", "shut180", "nclose20", "nclose75", "nclose20x4", "nclose75x4"):
|
||||
if not rows.get(arm):
|
||||
continue
|
||||
r = [x for x in rows.get(arm, []) if "crash" not in x]
|
||||
crashes = len(rows.get(arm, [])) - len(r)
|
||||
ev =[e for x in r for e in x["eval_ms"]]
|
||||
gr = [g for x in r for g in x["goto_req_ms"]]
|
||||
print("HUNTLAUNCHSPLIT %-12s ms: launch() %s | new_context %s | new_page %s | first_load %s | to_first_load p50 %s p95 %s | Firefox parent CPU s p50: launch() %s new_context %s new_page %s first_load %s"
|
||||
% (arm, trio([x.get("enter_ms") for x in r]), trio([x.get("ctx_ms") for x in r]), trio([x.get("new_page_ms") for x in r]), trio([x.get("first_load_ms") for x in r]),
|
||||
q([x.get("to_first_load_ms") for x in r], .5), q([x.get("to_first_load_ms") for x in r], .95),
|
||||
q([x.get("enter_cpu_s") for x in r], .5), q([x.get("ctx_cpu_s") for x in r], .5), q([x.get("new_page_cpu_s") for x in r], .5), q([x.get("first_load_cpu_s") for x in r], .5)))
|
||||
print("HUNTTABLE %-12s browsers %3d crashes %d | launch ms p50 %s p95 %s | close ms p50 %s p95 %s | eval ms p50 %s p95 %s max %s >300ms %d of %d | goto->request ms p50 %s p90 %s max %s | cpu s/browser p50 %s"
|
||||
% (arm, len(r), crashes, q([x["launch_ms"] for x in r], .5), q([x["launch_ms"] for x in r], .95), q([x["close_ms"] for x in r], .5), q([x["close_ms"] for x in r], .95),
|
||||
q(ev, .5), q(ev, .95), max(ev) if ev else None, sum(1 for e in ev if e > 300), len(ev), q(gr, .5), q(gr, .9), max((g for g in gr if g is not None), default=None),
|
||||
q([x["cpu_s_per_browser"] for x in r], .5)))
|
||||
ty = [x.get("typing") or {} for x in r]
|
||||
ok = [t for t in ty if "slip_abs_max" in t]
|
||||
errs = [t.get("error") for t in ty if t.get("error")]
|
||||
print("HUNTTYPING %-12s typed %d of %d | key slip vs plan: p50 of browsers %s, max %s | keys over 100 ms %d of %d | compressions %d | mouse: longest gap %s ms, bursts <2 ms %d, clicks %d | errors %s"
|
||||
% (arm, len(ok), len(ty), q([t["slip_abs_p50"] for t in ok], .5), max((t["slip_abs_max"] for t in ok), default=None),
|
||||
sum(t["keys_over_100ms"] for t in ok), sum(t["keys_planned"] for t in ok), sum(t["compressions"] for t in ok),
|
||||
max((t["mouse_gap_max"] or 0 for t in ty if "mousemoves" in t), default=None), sum(t.get("mouse_bursts_under_2ms", 0) for t in ty),
|
||||
sum(t.get("clicks", 0) for t in ty), errs[:2]))
|
||||
# Where the slip is born, per key (detail = planned, sent, answered, timeStamp, handler; ms from the first send).
|
||||
det = [d for t in ok for d in t.get("detail") or []]
|
||||
late_c = [d[1] - d[0] for d in det]
|
||||
rt = [d[2] - d[1] for d in det]
|
||||
birth = [d[3] - d[1] for d in det]
|
||||
hts = [h for t in ok for h in t.get("handler_minus_ts") or []]
|
||||
print("HUNTKEYCLOCKS %-12s on event.timeStamp: keys over 100 ms %d, max %s, compressions %d | on the handler: keys over 100 ms %d, max %s | handler - timeStamp p50 %s p95 %s max %s | matched %d of %d | machine CPU busy %% during typing p50 %s max %s"
|
||||
% (arm, sum(t["keys_over_100ms"] for t in ok), max((t["slip_abs_max"] for t in ok), default=None), sum(t["compressions"] for t in ok),
|
||||
sum(t.get("h_keys_over_100ms", 0) for t in ok), max((t.get("h_slip_abs_max", 0) for t in ok), default=None),
|
||||
q(hts, .5), q(hts, .95), max(hts, default=None), sum(1 for t in ok if t.get("detail")), len(ok),
|
||||
q([t.get("machine_cpu_busy_pct") for t in ty], .5), max((t.get("machine_cpu_busy_pct") or 0 for t in ty), default=None)))
|
||||
if det:
|
||||
print("HUNTKEYSPLIT %-12s client send vs plan: keys over 100 ms %d, p50 %s max %s | client send -> send_async returned p50 %s p95 %s max %s | client send -> event.timeStamp p50 %s p95 %s max %s"
|
||||
% (arm, sum(1 for x in late_c if abs(x) > 100), q(late_c, .5), max(late_c), q(rt, .5), q(rt, .95), max(rt), q(birth, .5), q(birth, .95), max(birth)))
|
||||
worst = sorted(((abs((t["detail"][i][3] - t["detail"][0][3]) - t["detail"][i][0]), t["detail"][max(0, i - 1):i + 1]) for t in ok if t.get("detail")
|
||||
for i in range(len(t["detail"]))), key=lambda w: -w[0])[:4]
|
||||
for slip, pair in worst:
|
||||
print("HUNTKEYWORST %-12s timeStamp slip %.0f ms | previous and this key [planned, sent, answered, timeStamp, handler]: %s" % (arm, slip, pair))
|
||||
# The mouse the page saw before and at the first click: the path (the gaps between consecutive mousemoves up to the press, on
|
||||
# event.timeStamp and, h_, on the handler), the click's dwell (mousedown -> mouseup) against the core's planned dwell (plan_click
|
||||
# of the persona of the seed, nonce 1 = the first click of page 0: exact). The path's own plan is the wrapper cursor's and is
|
||||
# judged by its gaps; the dwell on timeStamp differs from the plan by the difference of the two events' `latency` draws (<= 28 ms).
|
||||
for arm in ("inproc4", "one", "remote"):
|
||||
ty = [x.get("typing") or {} for x in rows.get(arm, []) if "crash" not in x]
|
||||
mt = [t for t in ty if "mv_n" in t]
|
||||
if not mt:
|
||||
continue
|
||||
for pre, name in (("", "event.timeStamp"), ("h_", "handler")):
|
||||
def g(k):
|
||||
return [t.get(pre + k) for t in mt]
|
||||
def mx(k):
|
||||
return max((v for v in g(k) if v is not None), default=None)
|
||||
slips = [abs(v) for v in g("click_dwell_slip") if v is not None]
|
||||
print("HUNTMOUSE %-8s on %-15s browsers %d | path: moves p50 %s, median gap p50 %s ms, longest gap p50 %s max %s | gaps over 100 ms %d | compressions %d | click dwell p50 %s vs plan p50 %s: slip p50 %s, |slip| p50 %s max %s | press settle (last move -> press) p50 %s vs plan p50 %s"
|
||||
% (arm, name, len(mt), q(g("mv_n"), .5), q(g("mv_gap_med"), .5), q(g("mv_gap_max"), .5), mx("mv_gap_max"),
|
||||
sum(v or 0 for v in g("mv_gaps_over_100ms")), sum(v or 0 for v in g("mv_compressions")), q(g("click_dwell"), .5),
|
||||
q([t.get("click_dwell_plan") for t in mt], .5), q(g("click_dwell_slip"), .5), q(slips, .5), max(slips, default=None),
|
||||
q(g("press_settle"), .5), q([t.get("press_settle_plan") for t in mt], .5)))
|
||||
# The mouse against the plan of the stroke client (Page.dispatchMouseEvent through Stroke.send, paired with the browser by the identity of
|
||||
# its core connection: exact, else "unpaired"). Per page mousemove, the nearest plan point after shifting the page's clock onto the
|
||||
# plan's; the gap criterion (the page's gap over the planned gap, by more than 100 ms), bursts (page events within 2 ms where the plan
|
||||
# spaces them), the longest gap (in the plan or not), the compressions (frame coalescing or born close together), the settle.
|
||||
for arm in ("inproc4", "one", "remote"):
|
||||
ty = [x.get("typing") or {} for x in rows.get(arm, []) if "crash" not in x]
|
||||
if not any("mp_pairing" in t for t in ty):
|
||||
continue
|
||||
print("HUNTMOUSEPAIR %-8s browsers %d | paired exactly %d, unpaired %d | client mouse events p50 %s"
|
||||
% (arm, len(ty), sum(1 for t in ty if str(t.get("mp_pairing", "")).startswith("exact")), sum(1 for t in ty if t.get("mp_pairing") == "unpaired"),
|
||||
q([t.get("mp_client_events") for t in ty], .5)))
|
||||
for pre, name in (("", "event.timeStamp"), ("h_", "handler")):
|
||||
mp = [t for t in ty if pre + "mp_gap_excess_max" in t]
|
||||
if not mp:
|
||||
continue
|
||||
comps = [c for t in mp for c in t.get(pre + "mp_compressions") or []]
|
||||
print("HUNTMOUSEPLAN %-8s on %-15s browsers %d | offset to the nearest plan point |ms| p50 %s max %s | gap excess over 100 ms: %d gaps in %d browsers, max excess %s | bursts %d | page moves p50 %s of plan moves p50 %s"
|
||||
% (arm, name, len(mp), q([t[pre + "mp_off_abs_p50"] for t in mp], .5), max(t[pre + "mp_off_abs_max"] for t in mp), sum(t[pre + "mp_gap_viol"] for t in mp),
|
||||
sum(1 for t in mp if t[pre + "mp_gap_viol"]), max(t[pre + "mp_gap_excess_max"] for t in mp), sum(t[pre + "mp_bursts"] for t in mp),
|
||||
q([t.get(pre + "mv_n") for t in mp], .5), q([t.get(pre + "mp_plan_moves") for t in mp], .5)))
|
||||
print("HUNTMOUSELONG %-8s on %-15s longest page gap of each browser: p50 %s max %s ms | its planned gap p50 %s | in the plan (excess <= 100 ms) %d of %d | the plan's own longest gap p50 %s max %s"
|
||||
% (arm, name, q([t[pre + "mp_longest_gap"] for t in mp], .5), max(t[pre + "mp_longest_gap"] for t in mp), q([t[pre + "mp_longest_gap_planned"] for t in mp], .5),
|
||||
sum(1 for t in mp if t[pre + "mp_longest_gap_in_plan"]), len(mp), q([t[pre + "mp_plan_max_gap"] for t in mp], .5), max(t[pre + "mp_plan_max_gap"] for t in mp)))
|
||||
print("HUNTMOUSECOMP %-8s on %-15s compressions %d: %s | examples %s"
|
||||
% (arm, name, len(comps), cnt(c["class"] for c in comps), [(c["prev_gap"], c["gap"], c["plan_points_between"], c["planned_gap"]) for c in comps[:4]]))
|
||||
st = [t for t in mp if pre + "mp_settle_page" in t]
|
||||
print("HUNTMOUSESETTLE %-8s on %-15s settle (last page mousemove -> mousedown) p50 %s min %s max %s ms vs plan p50 %s | the client's own (last move sent -> press sent) p50 %s | last page move is a coalesced one (plan moves after its point > 0): %d of %d | the press against its planned instant p50 %s max %s ms"
|
||||
% (arm, name, q([t[pre + "mp_settle_page"] for t in st], .5), min((t[pre + "mp_settle_page"] for t in st), default=None), max((t[pre + "mp_settle_page"] for t in st), default=None),
|
||||
q([t.get("press_settle_plan") for t in st], .5), q([t.get(pre + "mp_settle_client") for t in st], .5),
|
||||
sum(1 for t in st if t[pre + "mp_last_page_move_plan_moves_after"] > 0), len(st), q([t[pre + "mp_press_offset"] for t in st], .5),
|
||||
max((t[pre + "mp_press_offset"] for t in st), default=None)))
|
||||
# ---- CRITERION 1b, THE FINAL MEASURE: the mouse the page saw against the plan the client sent (scripts/hunt_candidate.py). The plan is every
|
||||
# Page.dispatchMouseEvent of the core's client (`stroke`, `at`); each page mousemove is joined to the plan point it is by its coordinates.
|
||||
# Three lines per configuration, on event.timeStamp (the criterion) and on the handler's clock: (a) pauses, (b) bursts, (c) the settle.
|
||||
M1B_OS = {"win32": "Windows", "linux": "Linux"}
|
||||
for arm in ("one", "inproc4"):
|
||||
rr = [x for x in rows.get(arm, []) if "crash" not in x]
|
||||
ty = [x.get("typing") or {} for x in rr]
|
||||
if not ty:
|
||||
continue
|
||||
osn = M1B_OS.get(rr[0].get("os"), rr[0].get("os"))
|
||||
print("HUNTM1B %-7s %-8s browsers %d | paired exactly with the client's plan %d | plan events p50 %s (with stroke and at: %d of %d, single commands outside a stroke: %d) | walks [planned, delivered] p50 browser: %s | errors %s"
|
||||
% (osn, arm, len(ty), sum(1 for t in ty if t.get("m1b_pairing") == "exact"), q([t.get("m1b_plan_events") for t in ty], .5),
|
||||
sum(t.get("m1b_plan_tagged", 0) for t in ty), sum(t.get("m1b_plan_events", 0) for t in ty), sum(t.get("m1b_plan_single", 0) for t in ty),
|
||||
cnt(str(t.get("m1b_walks")) for t in ty), cnt(t.get("error") for t in ty if t.get("error"))))
|
||||
for pre, name in (("m1b_", "event.timeStamp"), ("m1b_h_", "handler")):
|
||||
mp = [t for t in ty if pre + "pauses50" in t]
|
||||
if not mp:
|
||||
print("HUNTM1B-none %-7s %-8s on %-15s no browser analysed | notes %s | matched by %s" % (osn, arm, name, cnt(t.get(pre + "note") for t in ty if t.get(pre + "note")), cnt(t.get(pre + "match") for t in ty)))
|
||||
continue
|
||||
worst = sorted((w for t in mp for w in t[pre + "pause_worst"]), key=lambda w: -(w[0] - w[1]))[:3]
|
||||
print("HUNTM1B-a-pauses %-7s %-8s on %-15s | page gaps over the plan's gap by > 50 ms: %d (in %d of %d browsers), max excess %s ms | by > 100 ms: %d | worst [page gap, plan gap] %s | page moves p50 %s joined by %s, unmatched %d"
|
||||
% (osn, arm, name, sum(t[pre + "pauses50"] for t in mp), sum(1 for t in mp if t[pre + "pauses50"]), len(mp), max(t[pre + "pause_max"] for t in mp),
|
||||
sum(t[pre + "pauses100"] for t in mp), [w[:2] for w in worst], q([t[pre + "page_moves"] for t in mp], .5), cnt(t[pre + "match"] for t in mp),
|
||||
sum(t.get(pre + "unmatched", 0) for t in mp)))
|
||||
ex = [e for t in mp for e in t[pre + "burst_examples"]][:3]
|
||||
print("HUNTM1B-b-bursts %-7s %-8s on %-15s | points the plan spaces by >= 8 ms that the page saw < 2 ms apart: %d of %d such pairs (in %d of %d browsers) | examples [page gap, plan gap] %s"
|
||||
% (osn, arm, name, sum(t[pre + "bursts"] for t in mp), sum(t[pre + "pairs8"] for t in mp), sum(1 for t in mp if t[pre + "bursts"]), len(mp), [e[:2] for e in ex]))
|
||||
st = [t for t in mp if t.get(pre + "settle_page") is not None]
|
||||
dr = [t[pre + "settle_drawn"] for t in st if t.get(pre + "settle_drawn") is not None]
|
||||
diff = [t[pre + "settle_page"] - t[pre + "settle_drawn"] for t in st if t.get(pre + "settle_drawn") is not None]
|
||||
pl = [t[pre + "settle_page_from_last_planned"] for t in st if t.get(pre + "settle_page_from_last_planned") is not None]
|
||||
print("HUNTM1B-c-settle %-7s %-8s on %-15s | last move -> mousedown, browsers %d: the plan's (the pause the core drew) p50 %s min %s max %s ms | slept p50 %s | the client's (last move sent -> press sent) p50 %s min %s max %s | the page's p50 %s min %s max %s | page - plan p50 %s max %s | the page's from the move joined to the last plan move p50 %s (seen in %d) | last page move had plan moves after it: %d of %d | press against its planned instant p50 %s max %s"
|
||||
% (osn, arm, name, len(st), q(dr, .5), min(dr, default=None), max(dr, default=None), q([t.get(pre + "settle_slept") for t in st], .5),
|
||||
q([t[pre + "settle_client"] for t in st], .5), min((t[pre + "settle_client"] for t in st), default=None), max((t[pre + "settle_client"] for t in st), default=None),
|
||||
q([t[pre + "settle_page"] for t in st], .5), min((t[pre + "settle_page"] for t in st), default=None), max((t[pre + "settle_page"] for t in st), default=None),
|
||||
q(diff, .5), max(diff, default=None), q(pl, .5), len(pl), sum(1 for t in st if t[pre + "last_page_move_plan_moves_after"] > 0), len(st),
|
||||
q([t[pre + "press_offset"] for t in st], .5), max((abs(t[pre + "press_offset"]) for t in st), default=None)))
|
||||
# One line per browser, to read the distribution and to find the round.
|
||||
for x in rr:
|
||||
t = x.get("typing") or {}
|
||||
if "m1b_pauses50" in t:
|
||||
print("HUNTM1BROW %-7s %-8s %s | plan events %s, page moves %s | pauses>50 %s max %s | bursts %s of %s | settle plan %s client %s page %s"
|
||||
% (osn, arm, x.get("tag"), t.get("m1b_plan_events"), t.get("m1b_page_moves"), t["m1b_pauses50"], t["m1b_pause_max"], t["m1b_bursts"], t["m1b_pairs8"],
|
||||
t.get("m1b_settle_drawn"), t.get("m1b_settle_client"), t.get("m1b_settle_page")))
|
||||
# The retail Firefox 159: from the process start to the first page loaded (the onload beacon at the server), to the first
|
||||
# visible top-level window, the normal close to every process of the tree gone, the session and the parent's CPU.
|
||||
for arm in ("retail1", "retail4", "retail4late", "retail1long"):
|
||||
all_r = rows.get(arm, [])
|
||||
r = [x for x in all_r if "crash" not in x]
|
||||
if not all_r:
|
||||
continue
|
||||
print("HUNTRETAIL %-12s browsers %d crashes %d %s | start->load ms %s | start->window ms %s (no window: %d) | close->tree gone ms %s (timeouts %d) | close->main process gone ms p50 %s p95 %s | session s p50 %s | parent CPU s p50 %s p95 %s, at load p50 %s | tree CPU s at close p50 %s | exited before close %d | close cmd rc %s | last to exit %s"
|
||||
% (arm, len(r), len(all_r) - len(r), [x.get("crash") for x in all_r if "crash" in x][:1], trio([x.get("start_to_load_ms") for x in r]),
|
||||
trio([x.get("start_to_window_ms") for x in r]), sum(1 for x in r if x.get("start_to_window_ms") is None),
|
||||
trio([x.get("close_ms") for x in r]), sum(1 for x in r if x.get("close_timeout")),
|
||||
q([x.get("close_main_ms") for x in r], .5), q([x.get("close_main_ms") for x in r], .95), q([x.get("session_s") for x in r], .5),
|
||||
q([x.get("parent_cpu_s") for x in r], .5), q([x.get("parent_cpu_s") for x in r], .95), q([x.get("cpu_at_load_s") for x in r], .5),
|
||||
q([x.get("tree_cpu_at_close_s") for x in r], .5), sum(1 for x in r if x.get("exited_before_close")),
|
||||
sorted({str((x.get("close_cmd") or [None])[0]) for x in r}), sorted({(x.get("last_exits") or [["?"]])[0][0] for x in r})))
|
||||
# The path of one evaluate, segment by segment (p50/p95 ms, over the traced browser of every round).
|
||||
segs, missing, trace_n = {}, {}, {}
|
||||
for line in open(sys.argv[1], encoding="utf-8"):
|
||||
m = re.match(r"HUNTEVAL \[(\w+)\] (.*)", line.strip())
|
||||
if m:
|
||||
d = json.loads(m.group(2))
|
||||
trace_n[m.group(1)] = trace_n.get(m.group(1), 0) + 1
|
||||
for name, vals in d["segs"].items():
|
||||
if isinstance(vals, list):
|
||||
segs.setdefault(m.group(1), {}).setdefault(name, []).extend(vals)
|
||||
elif name == "missing":
|
||||
missing[m.group(1)] = missing.get(m.group(1), 0) + vals
|
||||
names = ("call_to_send", "send_to_pickup", "pickup_to_pipe", "pipe_to_reply_read", "read_to_ready", "ready_to_reply", "reply_to_loop", "dispatch", "resolve_to_return", "total")
|
||||
for arm, s in sorted(segs.items()):
|
||||
print("HUNTEVALSPLIT %-12s traced browsers %d, evaluates %d, incomplete %d, engine commands per evaluate p50 %s | p50/p95 ms: %s"
|
||||
% (arm, trace_n[arm], len(s.get("total", [])), missing.get(arm, 0), q(s.get("cmds", []), .5),
|
||||
" | ".join("%s %s/%s" % (n, q(s.get(n, []), .5), q(s.get(n, []), .95)) for n in names)))
|
||||
# ---- The close of the core with a reaper (nclose arms): each step, ms from the user's close() call (p50/p95/max over every
|
||||
# close), the steps between them, and the close of the other arms next to it (same job, same rounds).
|
||||
NC = ("nclose20", "nclose75", "nclose20x4", "nclose75x4")
|
||||
for arm in NC:
|
||||
r = [x for x in rows.get(arm, []) if "crash" not in x]
|
||||
if not rows.get(arm):
|
||||
continue
|
||||
def d(a, b):
|
||||
return [x[b] - x[a] for x in r if x.get(a) is not None and x.get(b) is not None]
|
||||
print("HUNTNCLOSE %-11s closes %d crashes %d, connection found by %s | from the close() call: (0) Connection.close entered %s | (i) pipe closed by the core %s | (ii) engine EOF seen by the reader %s | (iii) real parent exited %s | Connection.close returned %s | (iv) close() returned %s | (v) reaper finished %s (not finished %d)"
|
||||
% (arm, len(r), len(rows[arm]) - len(r), sorted({str(x.get("nc_mapped")) for x in r}), trio([x.get("nc_entry") for x in r]), trio([x.get("nc_pipe") for x in r]),
|
||||
trio([x.get("nc_eof") for x in r]), trio([x.get("nc_parent") for x in r]), trio([x.get("nc_conn_return") for x in r]), trio([x.get("nc_return") for x in r]),
|
||||
trio([x.get("nc_reaper") for x in r]), sum(1 for x in r if x.get("nc_reaper_finished") is False)))
|
||||
print("HUNTNCLOSESTEPS %-11s steps ms: call->entry %s | entry->pipe closed %s | pipe closed->engine EOF %s | engine EOF->parent exit %s | parent exit->Connection.close returned %s | Connection.close returned->close() returned %s | close() returned->reaper finished %s"
|
||||
% (arm, trio([x.get("nc_entry") for x in r]), trio(d("nc_entry", "nc_pipe")), trio(d("nc_pipe", "nc_eof")), trio(d("nc_eof", "nc_parent")),
|
||||
trio(d("nc_parent", "nc_conn_return")), trio(d("nc_conn_return", "nc_return")), trio(d("nc_return", "nc_reaper"))))
|
||||
for arm in NC + ("shut70", "retail1", "retail4late"):
|
||||
r = [x for x in rows.get(arm, []) if "crash" not in x]
|
||||
if r:
|
||||
print("HUNTCLOSECMP %-11s close() ms %s | n %d" % (arm, trio([x.get("nc_return", x.get("close_ms")) if arm in NC else x.get("close_ms") for x in r]), len(r)))
|
||||
# ---- The shutdown hunt. Two numbers per close: (a) the close -> the quit (the first "Starting phase" line of the engine's
|
||||
# AsyncShutdown log after the close started: Services.startup.quit has run), (b) the quit -> the main process gone (and the
|
||||
# whole tree gone). Then the phases and the blockers by name, with their time against the quit (the time held in (b)).
|
||||
SH = ("shut20", "shut70", "shut180", "retail1", "retail4late", "retail1long")
|
||||
probes, shut, bgt = {}, {}, {}
|
||||
for line in open(sys.argv[1], encoding="utf-8"):
|
||||
m = re.match(r"HUNTPROBE \[(\w+)\] (.*)", line.strip())
|
||||
if m:
|
||||
d = json.loads(m.group(2))
|
||||
probes.setdefault((m.group(1), d["name"]), []).append(d["ms"])
|
||||
continue
|
||||
m = re.match(r"HUNTBGTASK \[(\w+)\] (.*)", line.strip())
|
||||
if m:
|
||||
bgt.setdefault(m.group(1), []).append(json.loads(m.group(2)))
|
||||
continue
|
||||
m = re.match(r"HUNTSHUT \[(\w+)\] (.*)", line.strip())
|
||||
if m:
|
||||
d = json.loads(m.group(2))
|
||||
shut.setdefault(m.group(1), {}).setdefault((d["round"], d["tag"]), []).append((d["t_ms"], d.get("q_ms"), d["line"]))
|
||||
def pmx(arm, name):
|
||||
v = probes.get((arm, name), [])
|
||||
return "%s/%s" % (q(v, .5), max(v) if v else None)
|
||||
for arm in SH:
|
||||
if not rows.get(arm):
|
||||
continue
|
||||
r = [x for x in rows[arm] if "crash" not in x]
|
||||
print("HUNTSHUTCLOSE %-11s closes %d crashes %d | session s at close p50 %s | close ms %s | (a) close->quit ms %s | (b) quit->main gone ms %s | (b) quit->tree gone ms %s | (c) real parent gone->tree gone ms %s | close->real parent gone p50 %s | quit not seen %d | Connection.close p50/max %s | EngineTree.end %s | EngineTree.wait_job_empty %s | SessionFiles.remove %s"
|
||||
% (arm, len(r), len(rows[arm]) - len(r), q([x.get("session_s_at_close", x.get("session_s")) for x in r], .5), trio([x.get("close_ms") for x in r]),
|
||||
trio([x.get("a_close_to_quit_ms") for x in r]), trio([x.get("b_quit_to_main_gone_ms") for x in r]), trio([x.get("b_quit_to_tree_gone_ms") for x in r]),
|
||||
trio([x.get("c_main_to_tree_gone_ms") for x in r]), q([x.get("close_to_main_gone_ms") for x in r], .5), sum(1 for x in r if x.get("a_close_to_quit_ms") is None),
|
||||
pmx(arm, "Connection.close"), pmx(arm, "EngineTree.end"), pmx(arm, "EngineTree.wait_job_empty"), pmx(arm, "SessionFiles.remove")))
|
||||
# The background tasks (firefox --backgroundtask ..., the shutdown-ping sender): per close how many, when born against the close
|
||||
# start, how long they lived and how they ended.
|
||||
for arm in SH:
|
||||
r = [x for x in rows.get(arm, []) if "crash" not in x]
|
||||
if not r:
|
||||
continue
|
||||
ts = bgt.get(arm, [])
|
||||
per = {}
|
||||
for t in ts:
|
||||
per[(t["round"], t["tag"])] = per.get((t["round"], t["tag"]), 0) + 1
|
||||
counts = [per.get((x.get("round"), x.get("tag")), 0) for x in r]
|
||||
ended = {}
|
||||
for t in ts:
|
||||
k = re.sub(r"rc=-?\d+", "rc=N", t["ended_by"])
|
||||
ended[k] = ended.get(k, 0) + 1
|
||||
print("HUNTBGSUM %-11s closes %d | tasks %d, per close p50 %s max %s, closes with none %d | born ms against the close p50 %s p95 %s | life ms p50 %s p95 %s max %s | ended by: %s | ended inside the core's cleanup %d | attributed by ancestry %d, assumed %d | parent pids %s | cmd %s"
|
||||
% (arm, len(r), len(ts), q(counts, .5), max(counts, default=None), sum(1 for c in counts if c == 0), q([t["born_ms"] for t in ts], .5), q([t["born_ms"] for t in ts], .95),
|
||||
q([t["life_ms"] for t in ts], .5), q([t["life_ms"] for t in ts], .95), max((t["life_ms"] for t in ts if t["life_ms"] is not None), default=None),
|
||||
ended, sum(1 for t in ts if t.get("ended_in")), sum(1 for t in ts if t["attrib"] != "assumed"), sum(1 for t in ts if t["attrib"] == "assumed"),
|
||||
sorted({str(x.get("parent_pids") or x.get("parent_pid")) for x in r})[:3], [" ".join(t["cmd"][1:4])[:70] for t in ts[:1]]))
|
||||
phase_re = re.compile(r"(Starting|Finished) phase (\S+)")
|
||||
add_re = re.compile(r"Adding blocker (.+) for phase (\S+)")
|
||||
done_re = re.compile(r"Completed blocker (.+) for phase (\S+)")
|
||||
for arm in SH:
|
||||
closes = shut.get(arm, {})
|
||||
if not closes:
|
||||
continue
|
||||
ph, bl = {}, {}
|
||||
for key, ls in closes.items():
|
||||
for t_ms, qv, text in ls:
|
||||
m = phase_re.search(text)
|
||||
if m and qv is not None and t_ms >= 0:
|
||||
ph.setdefault(m.group(2), {"Starting": [], "Finished": []})[m.group(1)].append(qv)
|
||||
continue
|
||||
m = add_re.search(text)
|
||||
if m:
|
||||
bl.setdefault((m.group(2), m.group(1)), {"add": set(), "done": {}})["add"].add(key)
|
||||
continue
|
||||
m = done_re.search(text)
|
||||
if m and qv is not None:
|
||||
bl.setdefault((m.group(2), m.group(1)), {"add": set(), "done": {}})["done"][key] = qv
|
||||
for phase, v in sorted(ph.items(), key=lambda kv: q(kv[1]["Starting"], .5) if kv[1]["Starting"] else 1e12):
|
||||
print("HUNTPHASE %-11s %-34s closes %d | starts at quit+ms p50 %s max %s | finished at quit+ms p50 %s p95 %s max %s (finished in %d)"
|
||||
% (arm, phase, len(v["Starting"]), q(v["Starting"], .5), max(v["Starting"], default=None), q(v["Finished"], .5), q(v["Finished"], .95),
|
||||
max(v["Finished"], default=None), len(v["Finished"])))
|
||||
ranked = sorted(bl.items(), key=lambda kv: -(max(kv[1]["done"].values()) if kv[1]["done"] else 1e12))[:40]
|
||||
for (phase, name), v in ranked:
|
||||
done = list(v["done"].values())
|
||||
print("HUNTBLOCKER %-11s %-30s %-40s added in %d of %d closes, completed in %d, never completed in %d | completed at quit+ms (held in b) p50 %s p95 %s max %s"
|
||||
% (arm, phase, name[:40], len(v["add"]), len(closes), len(done), len(v["add"] - set(v["done"])), q(done, .5), q(done, .95), max(done, default=None)))
|
||||
# The lines of the close with the longest (b), in order: the raw story.
|
||||
slow = sorted((x for x in rows[arm] if "crash" not in x), key=lambda x: -(x.get("b_quit_to_main_gone_ms") or x.get("close_ms") or 0))[:1]
|
||||
for x in slow:
|
||||
for t_ms, qv, text in closes.get((x["round"], x["tag"]), [])[:150]:
|
||||
print("HUNTSHUTRAW %-11s %s %s | close%+.0f ms quit%+.0f ms | %s" % (arm, x["round"], x["tag"], t_ms, qv if qv is not None else float("nan"), text[:140]))
|
||||
PY
|
||||
python - "$RUNNER_TEMP/rows.log" <<'PY2'
|
||||
import json, re, sys
|
||||
probes = {}
|
||||
for line in open(sys.argv[1], encoding="utf-8"):
|
||||
m = re.match(r"HUNTPROBE \[(\w+)\] (.*)", line.strip())
|
||||
if m:
|
||||
d = json.loads(m.group(2)); probes.setdefault((m.group(1), d["name"]), []).append(d)
|
||||
def q(v, p):
|
||||
v = sorted(v); return v[min(len(v) - 1, int(p * len(v)))] if v else None
|
||||
for (arm, name), ds in sorted(probes.items()):
|
||||
ms = [d["ms"] for d in ds]
|
||||
line = "HUNTPROBESUM %-12s %-34s n %3d | ms p50 %s p95 %s max %s" % (arm, name, len(ds), q(ms, .5), q(ms, .95), max(ms))
|
||||
if name == "geo._family_lock":
|
||||
w = [d["extra"]["waited_ms"] for d in ds]
|
||||
line += " | held by: %s | waited p50 %s p95 %s max %s" % (sorted({d["thread"] for d in ds})[:4], q(w, .5), q(w, .95), max(w))
|
||||
print(line)
|
||||
PY2
|
||||
grep -h "HUNTSURVIVOR" "$RUNNER_TEMP/rows.log" | sed -E 's/"pid": [0-9]+, //' | sort -u | head -20 || true
|
||||
grep -h "HUNTSLOW" "$RUNNER_TEMP/rows.log" | cut -c1-900 || true
|
||||
# The geo helpers of the first launch of the first round (the first arm, inproc4, all four browsers): what prepare_session_geo
|
||||
# spent its time on (t = seconds from the start of that process, ms = how long, thread).
|
||||
grep -hE "HUNTPROBE \[inproc4\] .*\"round\": \"r0\".*\"name\": \"(geo\.|download\.|geoip_db\.|_geoip_db\.|udp_exit\.|requests\.)" "$RUNNER_TEMP/rows.log" | cut -c1-260 | head -150 || true
|
||||
- name: Close every Firefox left
|
||||
if: always()
|
||||
run: |
|
||||
if [ "$RUNNER_OS" = "Windows" ]; then taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true; else pkill -9 -f firefox > /dev/null 2>&1 || true; fi
|
||||
echo done
|
||||
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
if: always()
|
||||
with: { name: "candidate-typing-${{ matrix.os }}-${{ github.run_id }}", path: "${{ runner.temp }}/rows.log" }
|
||||
@@ -0,0 +1,766 @@
|
||||
# HUNT ONLY, never merged. The shutdown-ping sender (`firefox --backgroundtask pingsender ...`) and the machine's resolver, in the wrapper's OWN
|
||||
# e2e lab, the WHOLE suite wrapper.e2e.context.egress as the candidate's gate runs it on Linux (job gate / wrapper.e2e.context.egress: one
|
||||
# pytest process, the files and the marker the judge lists in ci/required-suites.json, root through `sudo -H -E env -u PYTEST_ADDOPTS -u
|
||||
# XDG_RUNTIME_DIR INVPW_REQUIRE_TRAP=1`, the resolver trap and the gateway fixtures of tests/_leaks.py and tests/_doh_servers.py, the GeoIP
|
||||
# database of scripts/ci_lab_geoip.py, the engine copied to /opt where root can run it, the seal of the binary), untouched, 5 runs per arm.
|
||||
# Hypothesis: CROSS-TEST CONTAMINATION. A sender of a context_only test (no launch proxy: native telemetry lookups are allowed there) outlives
|
||||
# its test and resolves incoming.telemetry.mozilla.org while the NEXT test (launch_and_context, the trap counting) runs: the next test is
|
||||
# charged. Proved or refuted per native query: which sender (pid, birth, death), which kind of session (the stealth contexts of its prefs.js),
|
||||
# which test its session belongs to (the test running when its profile was born) and which test was running when it asked.
|
||||
# Arms (a job each): cand = wrapper release/0.53.0 (its tests), core 74018f83, the engine of the candidate 43785139398, sealed as the gate
|
||||
# seals it; pub = the wrapper tag v0.52.1 (its tests), the published invisible-playwright 0.52.1 + invisible-core 64.73.0 on the engine they fetch.
|
||||
# Probes around the tests, none of them in the tests: MOZ_LOG=sync,timestamp,nsHostResolver:5,TRR:5 and MOZ_LOG_FILE=<dir>/ff-%PID.log put
|
||||
# explicitly after `sudo env` (the engine and the sender inherit them; the watcher checks the sender's environment and the files); a root
|
||||
# watcher (scripts/hunt_pingsender_dns.py) that polls every 20 ms for a pingsender process and at first sight copies its profile's prefs.js,
|
||||
# reads its route and environment and follows its end; the tests' own start and end instants from a pytest plugin (scripts/hunt_testtimes.py,
|
||||
# `-p`, no test touched).
|
||||
# Attribution of EVERY native DNS query from the network side (root): bpftrace on udp_sendmsg/udpv6_sendmsg (instant, pid, tid, thread name,
|
||||
# local port of each datagram to port 53; fallback `ss -u -a -p` polling when it cannot attach), tcpdump (name asked, local port), joined on the
|
||||
# local port and the time; the watcher snapshots every process of the engine (type, parents, profile, birth, end), every profile (prefs, birth,
|
||||
# removal) and a wall-clock/monotonic anchor. "The table" prints one HUNTQ line per query (who, which session and test, with or without a launch
|
||||
# proxy, when against the close of the session and the birth and end of its sender) and a HUNTQSUM per arm.
|
||||
name: pingsender dns hunt
|
||||
on:
|
||||
push:
|
||||
branches: [hunt/published-latency]
|
||||
paths: [.github/workflows/pingsender-dns-hunt.yml, scripts/hunt_pingsender_dns.py, scripts/hunt_testtimes.py]
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
concurrency:
|
||||
group: pingsender-dns-hunt
|
||||
cancel-in-progress: true
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
jobs:
|
||||
hunt:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
max-parallel: 2
|
||||
matrix:
|
||||
arm: [cand, pub]
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 120
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
env:
|
||||
PYTHONUNBUFFERED: "1"
|
||||
RUNS: "5"
|
||||
ARM: ${{ matrix.arm }}
|
||||
steps:
|
||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
with: { fetch-depth: 1 }
|
||||
- name: Checkout the wrapper of the candidate arm (release/0.53.0, its tests)
|
||||
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
with:
|
||||
repository: oss-invisible/playwright
|
||||
ref: release/0.53.0
|
||||
path: wcand
|
||||
fetch-depth: 1
|
||||
- name: Checkout the wrapper of the published arm (tag v0.52.1, its tests)
|
||||
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
with:
|
||||
repository: oss-invisible/playwright
|
||||
ref: v0.52.1
|
||||
path: wpub
|
||||
fetch-depth: 1
|
||||
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
|
||||
with: { python-version: "3.11" }
|
||||
# The GeoIP database is made by the repository (the same bytes every run), as the gate does: without it the core asks GitHub on every call.
|
||||
- name: The GeoIP database (made by the repository)
|
||||
working-directory: wcand
|
||||
run: python scripts/ci_lab_geoip.py build --pin ci/geoip.json
|
||||
- name: Linux system deps (Firefox runtime libs, a virtual display), psutil for the watcher
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y xvfb
|
||||
python -m pip install --quiet psutil "playwright==$(cat wcand/scripts/playwright_pin.txt)"
|
||||
sudo "$(which python)" -m playwright install-deps firefox
|
||||
- name: bpftrace and tcpdump (the network side of the attribution)
|
||||
continue-on-error: true
|
||||
run: sudo apt-get install -y bpftrace tcpdump
|
||||
- name: The venv of the arm (cand - core 74018f83 from git and the wrapper of release/0.53.0 with its dev extra; pub - the published packages)
|
||||
run: |
|
||||
export INVISIBLE_CORE_AUTOFIX=off INVISIBLE_CORE_PIN=allow
|
||||
python -m venv "$RUNNER_TEMP/venv"
|
||||
V="$RUNNER_TEMP/venv/bin/python"
|
||||
"$V" -m pip install --quiet --upgrade pip
|
||||
if [ "$ARM" = cand ]; then
|
||||
CORE_GIT="git+https://github.com/oss-invisible/core@74018f83c0b59fdaeff9e494426529331f8f7e60"
|
||||
"$V" -m pip install --quiet "$CORE_GIT"
|
||||
(cd wcand && "$V" -m pip install --quiet ".[dev]")
|
||||
"$V" -m pip install --quiet --force-reinstall "$CORE_GIT"
|
||||
else
|
||||
"$V" -m pip install --quiet "invisible-playwright[dev]==0.52.1"
|
||||
fi
|
||||
"$V" -c "
|
||||
import importlib.metadata as m, json
|
||||
for n in ('invisible-core', 'invisible-playwright'):
|
||||
d = m.distribution(n); u = json.loads(d.read_text('direct_url.json') or '{}')
|
||||
print(n, d.version, u.get('vcs_info', {}).get('commit_id') or 'the index')
|
||||
"
|
||||
echo "PY=$V" >> "$GITHUB_ENV"
|
||||
# The engine goes where root can run it (a path of root's that everyone can read), as the gate does for its root legs.
|
||||
- name: The engine of the arm (cand - the candidate 43785139398, sealed as the gate seals it; pub - the one the published packages fetch)
|
||||
run: |
|
||||
export INVISIBLE_CORE_AUTOFIX=off INVISIBLE_CORE_PIN=allow
|
||||
sudo rm -rf /opt/ff
|
||||
if [ "$ARM" = cand ]; then
|
||||
mkdir -p "$RUNNER_TEMP/eng" && cd "$RUNNER_TEMP/eng"
|
||||
gh run download 43785139398 -R oss-invisible/firefox_antidetect_patch -n asset-linux-x86_64 -D .
|
||||
mkdir ff && tar -xzf ./*.tar.gz -C ff
|
||||
FF="$(find "$PWD/ff" -maxdepth 2 -type f -name firefox | head -1)"
|
||||
sudo cp -a "$(dirname "$FF")" /opt/ff
|
||||
BIN=/opt/ff/firefox
|
||||
else
|
||||
SRC="$(cd "$RUNNER_TEMP" && "$PY" -m invisible_playwright fetch | tail -1)"
|
||||
sudo cp -a "$(dirname "$SRC")" /opt/ff
|
||||
BIN="/opt/ff/$(basename "$SRC")"
|
||||
fi
|
||||
sudo chown -R root:root /opt/ff
|
||||
sudo chmod -R go+rX /opt/ff
|
||||
ls -l "$BIN"; sha256sum "$BIN"
|
||||
echo "BIN=$BIN" >> "$GITHUB_ENV"
|
||||
if [ "$ARM" = cand ]; then "$PY" -m invisible_core seal --binary "$BIN" --tag firefox-65-candidate -o "$RUNNER_TEMP/gate.seal.json"; fi
|
||||
- name: The watcher (root, the whole job) and the runs of the whole suite
|
||||
continue-on-error: true
|
||||
timeout-minutes: 100
|
||||
run: |
|
||||
set +e
|
||||
OUT="$RUNNER_TEMP/out"; mkdir -p "$OUT/junit" "$OUT/moz" "$OUT/pytest" "$OUT/times"; chmod -R 777 "$OUT"
|
||||
: > "$OUT/watch.jsonl"; : > "$OUT/runs.jsonl"
|
||||
# The network side (root): which process owns the socket that sends each DNS query. bpftrace on udp_sendmsg / udpv6_sendmsg gives, for every
|
||||
# datagram to port 53, the instant (CLOCK_MONOTONIC ns; the watcher writes anchors that turn it into wall clock), pid (thread group), tid, thread
|
||||
# name and the local port; tcpdump gives the name asked and the local port. The join is in "The table".
|
||||
DNS="$OUT/dns"; mkdir -p "$DNS"; chmod 777 "$DNS"
|
||||
cat > "$DNS/q.bt" <<'BT'
|
||||
BEGIN { printf("B %llu start\n", nsecs); }
|
||||
kprobe:udp_sendmsg, kprobe:udpv6_sendmsg
|
||||
{
|
||||
@sk[tid] = arg0;
|
||||
@mh[tid] = arg1;
|
||||
@t0[tid] = nsecs;
|
||||
}
|
||||
kretprobe:udp_sendmsg, kretprobe:udpv6_sendmsg
|
||||
/@sk[tid] != 0/
|
||||
{
|
||||
$sk = (struct sock *)@sk[tid];
|
||||
$m = (struct msghdr *)@mh[tid];
|
||||
$dp = $sk->__sk_common.skc_dport;
|
||||
$nm = (struct sockaddr_in *)$m->msg_name;
|
||||
if ($nm != 0) { $dp = $nm->sin_port; }
|
||||
if ($dp == 0x3500) {
|
||||
printf("Q %llu %d %d %s %d 53\n", @t0[tid], pid, tid, comm, $sk->__sk_common.skc_num);
|
||||
}
|
||||
delete(@sk[tid]); delete(@mh[tid]); delete(@t0[tid]);
|
||||
}
|
||||
END { clear(@sk); clear(@mh); clear(@t0); }
|
||||
BT
|
||||
cat > "$DNS/q-simple.bt" <<'BT'
|
||||
BEGIN { printf("B %llu start\n", nsecs); }
|
||||
kprobe:udp_sendmsg, kprobe:udpv6_sendmsg
|
||||
{
|
||||
$sk = (struct sock *)arg0;
|
||||
$m = (struct msghdr *)arg1;
|
||||
$dp = $sk->__sk_common.skc_dport;
|
||||
$nm = (struct sockaddr_in *)$m->msg_name;
|
||||
if ($nm != 0) { $dp = $nm->sin_port; }
|
||||
if ($dp == 0x3500) {
|
||||
printf("Q %llu %d %d %s %d 53\n", nsecs, pid, tid, comm, $sk->__sk_common.skc_num);
|
||||
}
|
||||
}
|
||||
BT
|
||||
cat > "$DNS/x.bt" <<'BT'
|
||||
BEGIN { printf("B %llu start\n", nsecs); }
|
||||
tracepoint:syscalls:sys_enter_execve
|
||||
{
|
||||
printf("X %llu %d %d ", nsecs, pid, ((struct task_struct *)curtask)->real_parent->tgid);
|
||||
join(args->argv);
|
||||
}
|
||||
BT
|
||||
{ uname -r; ls -l /sys/kernel/btf/vmlinux; sudo bpftrace --version; tcpdump --version 2>&1 | head -1; } > "$DNS/info.txt" 2>&1; cat "$DNS/info.txt"
|
||||
BPF_OK=0; : > "$DNS/status.txt"
|
||||
for variant in "q.bt:-B line" "q.bt:" "q-simple.bt:-B line" "q-simple.bt:"; do
|
||||
f="${variant%%:*}"; opt="${variant#*:}"
|
||||
if [ -n "$opt" ]; then
|
||||
sudo bpftrace $opt "$DNS/$f" > "$DNS/bpf-q.log" 2> "$DNS/bpf-q.err" &
|
||||
else
|
||||
sudo stdbuf -oL bpftrace "$DNS/$f" > "$DNS/bpf-q.log" 2> "$DNS/bpf-q.err" &
|
||||
fi
|
||||
BPFPID=$!
|
||||
for _ in $(seq 1 75); do
|
||||
grep -q '^B ' "$DNS/bpf-q.log" 2>/dev/null && break
|
||||
sudo kill -0 "$BPFPID" 2>/dev/null || break
|
||||
sleep 0.2
|
||||
done
|
||||
if grep -q '^B ' "$DNS/bpf-q.log" 2>/dev/null; then BPF_OK=1; echo "bpf=attached script=$f opt='$opt'" >> "$DNS/status.txt"; break; fi
|
||||
echo "bpf=not attached script=$f opt='$opt': $(head -c 300 "$DNS/bpf-q.err" | tr '\n' ' ')" >> "$DNS/status.txt"
|
||||
sudo pkill -INT -x bpftrace; sleep 1
|
||||
done
|
||||
sudo bpftrace -B line "$DNS/x.bt" > "$DNS/bpf-x.log" 2> "$DNS/bpf-x.err" &
|
||||
sleep 1
|
||||
if grep -q '^B ' "$DNS/bpf-x.log" 2>/dev/null; then echo "exec trace=attached" >> "$DNS/status.txt"; else echo "exec trace=not attached: $(head -c 200 "$DNS/bpf-x.err" | tr '\n' ' ')" >> "$DNS/status.txt"; fi
|
||||
sudo tcpdump -Z root -i any -n -tt -l -s 200 'udp port 53' > "$DNS/tcpdump.txt" 2> "$DNS/tcpdump.err" &
|
||||
sudo tcpdump -Z root -i any -n -s 200 -U -w "$DNS/dns.pcap" 'port 53' 2> "$DNS/tcpdump-pcap.err" &
|
||||
for _ in $(seq 1 25); do grep -q listening "$DNS/tcpdump.err" 2>/dev/null && break; sleep 0.2; done
|
||||
if grep -q listening "$DNS/tcpdump.err" 2>/dev/null; then echo "tcpdump=listening" >> "$DNS/status.txt"; else echo "tcpdump=not listening: $(head -c 200 "$DNS/tcpdump.err" | tr '\n' ' ')" >> "$DNS/status.txt"; fi
|
||||
if [ "$BPF_OK" != 1 ]; then
|
||||
echo "FALLBACK: bpftrace did not attach; the owner of each socket comes from ss -u -a -p polling" >> "$DNS/status.txt"
|
||||
sudo "$(which python)" scripts/hunt_pingsender_dns.py sockpoll "$DNS/ss.jsonl" > "$DNS/ss.out" 2>&1 &
|
||||
fi
|
||||
cat "$DNS/status.txt"
|
||||
sudo "$(which python)" scripts/hunt_pingsender_dns.py watch "$OUT/watch.jsonl" "$OUT/prefs" > "$OUT/watch.out" 2>&1 &
|
||||
sleep 2; cat "$OUT/watch.out"
|
||||
(ss -lntup 2>/dev/null || netstat -lntup 2>/dev/null) || echo "no ss or netstat on this runner"
|
||||
if [ "$ARM" = cand ]; then WDIR=wcand; else WDIR=wpub; fi
|
||||
# The files and the marker of the suite, from the judge of the checkout, as the gate asks it (--with-marker).
|
||||
( cd "$WDIR" && python scripts/ci_verdict.py args --required ci/required-suites.json --suite wrapper.e2e.context.egress --os linux --with-marker ) | tr -d '\r' > "$OUT/args.txt"
|
||||
cat "$OUT/args.txt"; mapfile -t SELECT < "$OUT/args.txt"
|
||||
# One pytest process, the gate's command for this suite: the same options, root through sudo -H -E, the environment of the gate; the
|
||||
# hunt adds MOZ_LOG and MOZ_LOG_FILE (explicit after `sudo env`, so sudo cannot drop them), a plugin that times the tests, and a timeout.
|
||||
one_run() {
|
||||
local i="$1" py bin logd junit times rc t0 t1 nlog
|
||||
logd="$OUT/moz/$ARM-$i"; mkdir -p "$logd"; chmod 777 "$logd"
|
||||
junit="$OUT/junit/$ARM-$i.xml"; times="$OUT/times/$ARM-$i.jsonl"; : > "$times"; chmod 666 "$times"
|
||||
ENVV=(INVPW_REQUIRE_TRAP=1 "PATH=$PATH" PYTHONUNBUFFERED=1 "PYTHONPATH=$GITHUB_WORKSPACE/scripts" "HUNT_TESTTIMES=$times"
|
||||
"INVPW_BINARY_PATH=$BIN" "STEALTHFOX_E2E_BINARY=$BIN"
|
||||
"MOZ_LOG=sync,timestamp,nsHostResolver:5,TRR:5" "MOZ_LOG_FILE=$logd/ff-%PID.log")
|
||||
if [ "$ARM" = cand ]; then ENVV+=(INVISIBLE_CORE_AUTOFIX=off INVISIBLE_CORE_PIN=allow "INVISIBLE_SEAL_FILE=$RUNNER_TEMP/gate.seal.json"); fi
|
||||
t0=$(date +%s%3N)
|
||||
( cd "$WDIR" && sudo -H -E env -u PYTEST_ADDOPTS -u XDG_RUNTIME_DIR "${ENVV[@]}" timeout 1500 "$PY" -m pytest "${SELECT[@]}" \
|
||||
-o addopts='' -o junit_family=xunit2 -q -p no:cacheprovider -p no:rerunfailures -p hunt_testtimes -rs --junitxml="$junit" ) > "$OUT/pytest/$ARM-$i.txt" 2>&1
|
||||
rc=$?
|
||||
t1=$(date +%s%3N)
|
||||
nlog=$(ls "$logd" | wc -l)
|
||||
printf '{"arm":"%s","i":%d,"t0":%s,"t1":%s,"rc":%d,"junit":"%s","logd":"%s","times":"%s","moz_files":%d}\n' "$ARM" "$i" "$t0" "$t1" "$rc" "$junit" "$logd" "$times" "$nlog" >> "$OUT/runs.jsonl"
|
||||
echo "== $ARM run $i rc=$rc ($(( (t1 - t0) / 1000 )) s), MOZ_LOG files $nlog"; tail -n 8 "$OUT/pytest/$ARM-$i.txt" | cut -c1-300
|
||||
sudo pkill -9 -f "/opt/ff" > /dev/null 2>&1
|
||||
}
|
||||
for i in $(seq 0 $((RUNS-1))); do
|
||||
if [ "$SECONDS" -gt 5400 ]; then echo "time guard: no new run after $SECONDS s"; break; fi
|
||||
one_run "$i"
|
||||
done
|
||||
sudo pkill -INT -x bpftrace > /dev/null 2>&1
|
||||
sudo pkill -INT -x tcpdump > /dev/null 2>&1
|
||||
sudo pkill -f "hunt_pingsender_dns.py sockpoll" > /dev/null 2>&1
|
||||
sleep 2
|
||||
sudo pkill -TERM -f "hunt_pingsender_dns.py watch" > /dev/null 2>&1
|
||||
sleep 1
|
||||
true
|
||||
- name: Safety (resolv.conf, firefox left)
|
||||
if: always()
|
||||
run: |
|
||||
ls -l /etc/resolv.conf; head -5 /etc/resolv.conf
|
||||
sudo pkill -9 -f "/opt/ff" > /dev/null 2>&1 || true
|
||||
echo done
|
||||
- name: The table
|
||||
if: always()
|
||||
run: |
|
||||
python - "$RUNNER_TEMP/out" <<'PY'
|
||||
import calendar, collections, glob, json, os, re, sys, xml.etree.ElementTree as ET
|
||||
out = sys.argv[1]
|
||||
TEL = "incoming.telemetry.mozilla.org"
|
||||
def jl(p):
|
||||
return [json.loads(l) for l in open(p, encoding="utf-8") if l.strip()] if os.path.exists(p) else []
|
||||
runs, watch = jl(out + "/runs.jsonl"), jl(out + "/watch.jsonl")
|
||||
seen = [w for w in watch if w["event"] == "seen"]
|
||||
ends = {w["pid"]: w for w in watch if w["event"] == "end"}
|
||||
def q(v, p):
|
||||
v = sorted(x for x in v if x is not None)
|
||||
return v[min(len(v) - 1, int(p * len(v)))] if v else None
|
||||
def cnt(v):
|
||||
return dict(collections.Counter(str(x) for x in v).most_common(8))
|
||||
QRE = re.compile(r"([A-Za-z0-9_.\-]+)/(\d+) \((\w+)\)")
|
||||
TSRE = re.compile(r"^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\.(\d+)")
|
||||
def log_time(line):
|
||||
m = TSRE.match(line)
|
||||
return calendar.timegm(__import__("time").strptime(m.group(1), "%Y-%m-%d %H:%M:%S")) * 1000 + int(m.group(2)[:3].ljust(3, "0")) if m else None
|
||||
def short(n):
|
||||
return n.split("::", 1)[-1][:70]
|
||||
def kind_of(s):
|
||||
v = (s.get("prefs") or {}).get("network.trr.stealth.contexts")
|
||||
if not s.get("prefs"):
|
||||
return "no prefs copy"
|
||||
return "context_only (no launch proxy)" if v in (None, '""', "") else "launch proxy (%s)" % v
|
||||
arm_tot = collections.Counter()
|
||||
shown = 0
|
||||
arm = runs[0]["arm"] if runs else "?"
|
||||
senders_all, cross_total, own_total = [], 0, 0
|
||||
os.makedirs(out + "/sender-logs", exist_ok=True)
|
||||
for run in runs:
|
||||
# The tests of this run, with their instants (the plugin) and their outcome.
|
||||
T = collections.OrderedDict()
|
||||
for e in jl(run["times"]):
|
||||
t = T.setdefault(e["nodeid"], {"start": None, "finish": None, "bad": False})
|
||||
if e["event"] == "start":
|
||||
t["start"] = e["t"]
|
||||
elif e["event"] == "finish":
|
||||
t["finish"] = e["t"]
|
||||
elif e["event"] == "phase" and e["outcome"] == "failed":
|
||||
t["bad"] = True
|
||||
order = list(T)
|
||||
for k, n in enumerate(order):
|
||||
if T[n]["finish"] is None:
|
||||
T[n]["finish"] = T[order[k + 1]]["start"] if k + 1 < len(order) else run["t1"]
|
||||
def test_at(t):
|
||||
for n in order:
|
||||
if T[n]["start"] is not None and T[n]["start"] <= t <= (T[n]["finish"] or 0) + 2:
|
||||
return n
|
||||
return None
|
||||
# What the junit says of each failing test, and the native queries the trap counted for it.
|
||||
msgs = {}
|
||||
try:
|
||||
for tc in ET.parse(run["junit"]).getroot().iter("testcase"):
|
||||
for f in list(tc.findall("failure")) + list(tc.findall("error")):
|
||||
msgs[tc.get("name")] = (f.get("message") or "") + "\n" + (f.text or "")
|
||||
except (OSError, ET.ParseError):
|
||||
pass
|
||||
def msg_of(nodeid):
|
||||
nm = nodeid.split("::", 1)[-1]
|
||||
return next((m for k, m in msgs.items() if k == nm or nm.endswith(k)), None)
|
||||
snd = [s for s in seen if run["t0"] <= s["seen"] <= run["t1"] + 3000]
|
||||
rows_here = []
|
||||
for s in snd:
|
||||
born_test = test_at(s["born"])
|
||||
owner = test_at(s["profile_oldest_mtime_ms"]) if s.get("profile_oldest_mtime_ms") else None
|
||||
files = glob.glob("%s/ff--*.%d.log*" % (run["logd"], s["pid"]))
|
||||
times, lines = [], []
|
||||
for fn in files:
|
||||
for ln in open(fn, encoding="utf-8", errors="replace"):
|
||||
if TEL in ln:
|
||||
lines.append(ln.rstrip()[:240])
|
||||
tt = log_time(ln)
|
||||
if tt:
|
||||
times.append(tt)
|
||||
first = min(times) if times else None
|
||||
info = {"pid": s["pid"], "kind": kind_of(s), "born_test": born_test, "owner": owner or born_test, "lookup_t": first, "lookup_test": test_at(first) if first else None,
|
||||
"lookup_lines": len(lines), "sample": lines[:2], "born": s["born"], "end": (ends.get(s["pid"]) or {}).get("lifetime_ms"),
|
||||
"moz_files": len(files), "env_moz_log": bool(s.get("env_moz_log")), "route": (s.get("route") or {}).get("proxy_present"),
|
||||
"crossed": (test_at(s["born"] + (ends.get(s["pid"]) or {}).get("lifetime_ms", 0)) != born_test) if born_test else None}
|
||||
rows_here.append(info)
|
||||
senders_all.append(info)
|
||||
for fn in files:
|
||||
os.system("gzip -c '%s' > '%s/%s-%d-%s.gz'" % (fn, out + "/sender-logs", run["arm"], run["i"], os.path.basename(fn)))
|
||||
for n in order:
|
||||
failed = T[n]["bad"]
|
||||
asked = []
|
||||
if failed and msg_of(n):
|
||||
tail = msg_of(n).split("asked the resolver of the machine", 1)[-1]
|
||||
asked = [a for a in QRE.findall(tail)]
|
||||
tel = [a for a in asked if a[0].rstrip(".") == TEL]
|
||||
mine = [r for r in rows_here if r["lookup_test"] == n and r["lookup_lines"]]
|
||||
own = [r for r in mine if r["owner"] == n]
|
||||
other = [r for r in mine if r["owner"] != n]
|
||||
cross_total += len(other)
|
||||
own_total += len(own)
|
||||
if failed or other:
|
||||
shown += 1
|
||||
print("HUNTCROSS %-4s run %d %-70s %s | trap counted native queries %d (telemetry host %d: %s) | MOZ_LOG lookups of the telemetry host while it ran: from its OWN session %d, from a DIFFERENT test's session %d | %s"
|
||||
% (run["arm"], run["i"], short(n), "FAILED" if failed else "passed", len(asked), len(tel), [a[2] for a in tel][:3], len(own), len(other),
|
||||
[(r["pid"], r["kind"], "owner " + short(r["owner"] or "?"), "born in " + short(r["born_test"] or "?"), "sender lived %s ms" % r["end"]) for r in other][:3]))
|
||||
arm_tot["runs"] += 1
|
||||
arm_tot["tests"] += len(order)
|
||||
arm_tot["failed"] += sum(1 for n in order if T[n]["bad"])
|
||||
arm_tot["trap_native_tel"] += sum(1 for n in order if T[n]["bad"] and msg_of(n) and TEL in msg_of(n).split("asked the resolver of the machine", 1)[-1])
|
||||
ss = senders_all
|
||||
print("HUNTCROSSSUM %-4s runs %d, tests %d, failed %d (failures naming the telemetry host in the trap's list: %d) | senders seen %d, by kind %s | senders whose own log names the telemetry host %d | those asked while a test of ANOTHER session ran: %d, while their own session's test ran: %d | senders that outlived their test (died in another test) %d"
|
||||
% (arm, arm_tot["runs"], arm_tot["tests"], arm_tot["failed"], arm_tot["trap_native_tel"], len(ss), cnt(r["kind"] for r in ss), sum(1 for r in ss if r["lookup_lines"]),
|
||||
cross_total, own_total, sum(1 for r in ss if r["crossed"])))
|
||||
print("HUNTCROSSLOG %-4s MOZ_LOG reached the sender in %d of %d | log files p50 %s | sender lifetime ms p50 %s max %s | route present %d | prefs copy mtime vs birth p50 %s"
|
||||
% (arm, sum(1 for r in ss if r["env_moz_log"]), len(ss), q([r["moz_files"] for r in ss], .5), q([r["end"] for r in ss], .5), max((r["end"] or 0 for r in ss), default=None),
|
||||
sum(1 for r in ss if r["route"]), q([s.get("prefs_copy_mtime_vs_birth_ms") for s in seen], .5)))
|
||||
for r in [r for r in ss if r["lookup_lines"]][:8]:
|
||||
print("HUNTCROSSSENDER %-4s pid %s %s | owner %s | born in %s | asked in %s | log %s" % (arm, r["pid"], r["kind"], short(r["owner"] or "?"), short(r["born_test"] or "?"), short(r["lookup_test"] or "?"), r["sample"]))
|
||||
# Every log file of every process, not only the senders': which pids wrote one, and which name the telemetry host, when, in which test.
|
||||
sender_pids = {s["pid"] for s in seen}
|
||||
for run in runs:
|
||||
files = sorted(glob.glob(run["logd"] + "/*"))
|
||||
names = [os.path.basename(f) for f in files]
|
||||
pid_of = lambda b: int((re.search(r"ff--(?:main|child)\.(\d+)", b) or re.search(r"ff-(\d+)", b)).group(1)) if re.search(r"ff-", b) else None
|
||||
print("HUNTALLLOGS %-4s run %d | files %d | names %s | of a seen sender pid %d | sizes p50 %s" % (run["arm"], run["i"], len(files), names[:6], sum(1 for b in names if pid_of(b) in sender_pids),
|
||||
q([os.path.getsize(f) for f in files], .5)))
|
||||
for fn in files:
|
||||
hits = []
|
||||
for ln in open(fn, encoding="utf-8", errors="replace"):
|
||||
if TEL in ln:
|
||||
hits.append(ln.rstrip()[:200])
|
||||
if hits:
|
||||
first = log_time(hits[0])
|
||||
print("HUNTALLTEL %-4s run %d %s | %d lines | sender %s | first at %s ms (run t0 %s) | %s" % (run["arm"], run["i"], os.path.basename(fn), len(hits), pid_of(os.path.basename(fn)) in sender_pids,
|
||||
first, run["t0"], hits[:2]))
|
||||
# ===== Every native DNS query, attributed from the network side: who sent it, which session, when ============================================
|
||||
# The kernel's view: bpftrace on udp_sendmsg/udpv6_sendmsg gives (instant, pid, tid, thread name, local port) of every datagram to port 53,
|
||||
# tcpdump gives (instant, local port, name asked); they are joined on the local port and the time. The watcher's records give the process
|
||||
# (type, parents, profile), the profile's session (prefs, birth, end), the sender of the session (birth, end). The tests' instants give the test.
|
||||
import bisect
|
||||
import time as _time
|
||||
dns = out + "/dns"
|
||||
def text_of(p):
|
||||
try:
|
||||
return open(p, encoding="utf-8", errors="replace").read()
|
||||
except OSError:
|
||||
return ""
|
||||
status = text_of(dns + "/status.txt").strip().replace("\n", "; ") or "no status file"
|
||||
anch = sorted((w["mono"], w["wall"]) for w in watch if w["event"] == "anchor")
|
||||
anch_m = [a[0] for a in anch]
|
||||
def wall_of(mono):
|
||||
if not anch:
|
||||
return None
|
||||
k = bisect.bisect_left(anch_m, mono)
|
||||
k = min(range(max(0, k - 1), min(len(anch), k + 1)), key=lambda j: abs(anch[j][0] - mono))
|
||||
return anch[k][1] + (mono - anch[k][0]) / 1e6
|
||||
BQ = re.compile(r"^Q (\d+) (\d+) (\d+) (.*) (\d+) (\d+)\s*$")
|
||||
BX = re.compile(r"^X (\d+) (\d+) (\d+) (.*)$")
|
||||
owners, execs = [], collections.defaultdict(list)
|
||||
for ln in text_of(dns + "/bpf-q.log").splitlines():
|
||||
m = BQ.match(ln)
|
||||
if m and wall_of(int(m.group(1))) is not None:
|
||||
owners.append({"t": wall_of(int(m.group(1))), "pid": int(m.group(2)), "tid": int(m.group(3)), "comm": m.group(4), "sport": int(m.group(5)), "src": "bpf"})
|
||||
for ln in text_of(dns + "/bpf-x.log").splitlines():
|
||||
m = BX.match(ln)
|
||||
if m and wall_of(int(m.group(1))) is not None:
|
||||
execs[int(m.group(2))].append({"t": wall_of(int(m.group(1))), "ppid": int(m.group(3)), "argv": m.group(4)[:200]})
|
||||
n_bpf = len(owners)
|
||||
for w in jl(dns + "/ss.jsonl"):
|
||||
if w.get("event") == "ssq":
|
||||
owners.append({"t": w["t"], "pid": w["pid"], "tid": None, "comm": w["comm"], "sport": w["sport"], "src": "ss"})
|
||||
owners.sort(key=lambda o: o["t"])
|
||||
by_sport = collections.defaultdict(list)
|
||||
for o in owners:
|
||||
by_sport[o["sport"]].append(o)
|
||||
TD = re.compile(r"^(\d+\.\d+) (\S+)\s+(In|Out)\s+IP6? (\S+)\.(\d+) > (\S+)\.(\d+): (\d+)\S* (?:\[[^\]]*\] )?(\w+)\? (\S+) \((\d+)\)")
|
||||
tq, unparsed, tcp_lines = [], [], 0
|
||||
for ln in text_of(dns + "/tcpdump.txt").splitlines():
|
||||
tcp_lines += 1
|
||||
m = TD.match(ln)
|
||||
if not m:
|
||||
if "?" in ln:
|
||||
unparsed.append(ln[:160])
|
||||
continue
|
||||
if m.group(7) != "53":
|
||||
continue
|
||||
tq.append({"t": float(m.group(1)) * 1000, "dir": m.group(3), "sport": int(m.group(5)), "dst": m.group(6), "txid": m.group(8), "qtype": m.group(9), "qname": m.group(10).rstrip(".")})
|
||||
# The same datagram appears twice on lo with -i any (Out and In): one query.
|
||||
tq.sort(key=lambda x: x["t"])
|
||||
uniq = []
|
||||
for x in tq:
|
||||
if any(y["sport"] == x["sport"] and y["txid"] == x["txid"] and y["qname"] == x["qname"] and y["qtype"] == x["qtype"] and y["dst"] == x["dst"] and abs(y["t"] - x["t"]) < 20 for y in uniq[-12:]):
|
||||
continue
|
||||
uniq.append(x)
|
||||
used = set()
|
||||
rows_q = []
|
||||
for x in uniq:
|
||||
best = None
|
||||
for o in by_sport.get(x["sport"], []):
|
||||
if id(o) in used:
|
||||
continue
|
||||
d = abs(o["t"] - x["t"])
|
||||
if d <= 1500 and (best is None or d < best[0]):
|
||||
best = (d, o)
|
||||
if best:
|
||||
used.add(id(best[1]))
|
||||
rows_q.append((x, best[1] if best else None, best[0] if best else None))
|
||||
for o in owners:
|
||||
if id(o) not in used and o["src"] == "bpf":
|
||||
rows_q.append(({"t": o["t"], "sport": o["sport"], "dst": "?", "qtype": "?", "qname": "?(no tcpdump line)", "txid": "?"}, o, None))
|
||||
rows_q.sort(key=lambda r: r[0]["t"])
|
||||
# The watcher's records: processes (with their updates and ends), profiles (prefs, end), by pid and by profile.
|
||||
PR = collections.defaultdict(list)
|
||||
cur = {}
|
||||
for w in watch:
|
||||
ev = w["event"]
|
||||
if ev == "proc":
|
||||
r = dict(w, end=None)
|
||||
PR[w["pid"]].append(r)
|
||||
cur[(w["pid"], w["born"])] = r
|
||||
elif ev == "pupd" and (w["pid"], w["born"]) in cur:
|
||||
cur[(w["pid"], w["born"])].update(comm=w["comm"], ptype=w["ptype"], head=w["head"], tail=w["tail"])
|
||||
elif ev == "pend" and (w["pid"], w["born"]) in cur:
|
||||
cur[(w["pid"], w["born"])]["end"] = w["ended"]
|
||||
PF = {}
|
||||
for w in watch:
|
||||
if w["event"] == "prof":
|
||||
PF.setdefault(w["profile"], {"born": w["born"], "first": w["first"], "prefs": None, "gone": None})["prefs"] = w["prefs"]
|
||||
elif w["event"] == "pgone" and w["profile"] in PF:
|
||||
PF[w["profile"]]["gone"] = w["t"]
|
||||
PF[w["profile"]]["gone_seen"] = True
|
||||
by_prof = collections.defaultdict(list)
|
||||
for pl in PR.values():
|
||||
for r in pl:
|
||||
if r.get("profile"):
|
||||
by_prof[r["profile"]].append(r)
|
||||
def find_proc(pid, t):
|
||||
for r in PR.get(pid, []):
|
||||
if r["seen"] - 150 <= t and (r["end"] is None or t <= r["end"] + 150):
|
||||
return r
|
||||
return None
|
||||
def run_of(t):
|
||||
return next((r for r in runs if r["t0"] <= t <= r["t1"] + 3000), None)
|
||||
TT = {}
|
||||
def tests_of(run):
|
||||
if run["i"] in TT:
|
||||
return TT[run["i"]]
|
||||
T = collections.OrderedDict()
|
||||
for e in jl(run["times"]):
|
||||
t = T.setdefault(e["nodeid"], {"start": None, "finish": None})
|
||||
if e["event"] == "start":
|
||||
t["start"] = e["t"]
|
||||
elif e["event"] == "finish":
|
||||
t["finish"] = e["t"]
|
||||
order = list(T)
|
||||
for k, n in enumerate(order):
|
||||
if T[n]["finish"] is None:
|
||||
T[n]["finish"] = T[order[k + 1]]["start"] if k + 1 < len(order) else run["t1"]
|
||||
TT[run["i"]] = (T, order)
|
||||
return TT[run["i"]]
|
||||
def test_of(t):
|
||||
run = run_of(t)
|
||||
if not run:
|
||||
return None
|
||||
T, order = tests_of(run)
|
||||
for n in order:
|
||||
if T[n]["start"] is not None and T[n]["start"] <= t <= (T[n]["finish"] or 0) + 2:
|
||||
return n
|
||||
return None
|
||||
def proxy_of(prof, procs):
|
||||
pf = (PF.get(prof) or {}).get("prefs")
|
||||
routes = [r.get("route_proxy") for r in procs if r.get("route_present")]
|
||||
if pf is None and not routes:
|
||||
return "?", "no prefs, no route"
|
||||
ctx = (pf or {}).get("network.trr.stealth.contexts")
|
||||
ptp = (pf or {}).get("network.proxy.type")
|
||||
yes = "*" in str(ctx) or any(routes) or ptp == "1" # "*,6" = launch proxy; "6" = context-only (no launch proxy); empty = none
|
||||
return ("yes" if yes else "no"), "ctx=%s proxytype=%s route=%s" % (ctx, ptp, routes[:1] or "-")
|
||||
def sess_of(prof):
|
||||
"""The session of a profile: its test (the one running when it was born), its close (the main browser's end, else the directory's), its senders."""
|
||||
pl = by_prof.get(prof, [])
|
||||
mains = sorted((r for r in pl if r["ptype"] == "main"), key=lambda r: r["seen"])
|
||||
close = mains[0]["end"] if mains else None
|
||||
close_src = "main browser exit" if close is not None else None
|
||||
if close is None and (PF.get(prof) or {}).get("gone"):
|
||||
close, close_src = PF[prof]["gone"], "profile dir removed"
|
||||
born = (PF.get(prof) or {}).get("born") or (mains[0]["seen"] if mains else None)
|
||||
proxy, why = proxy_of(prof, pl)
|
||||
return {"test": test_of(born) if born else None, "born": born, "close": close, "close_src": close_src, "proxy": proxy, "why": why,
|
||||
"senders": sorted((r for r in pl if r["ptype"] == "pingsender"), key=lambda r: r["seen"]), "main": mains[0] if mains else None}
|
||||
SESS = {}
|
||||
def sess(prof):
|
||||
if prof not in SESS:
|
||||
SESS[prof] = sess_of(prof)
|
||||
return SESS[prof]
|
||||
def rel(v):
|
||||
return "none" if v is None else "%+d" % round(v)
|
||||
hq_rows = []
|
||||
for x, o, dj in rows_q:
|
||||
t = x["t"]
|
||||
run = run_of(t)
|
||||
row = {"arm": arm, "run": run["i"] if run else None, "t": round(t, 1), "hhmmss": _time.strftime("%H:%M:%S", _time.gmtime(t / 1000)) + ".%03d" % (t % 1000),
|
||||
"qname": x["qname"], "qtype": x["qtype"], "dst": x["dst"], "sport": x["sport"], "pid": o["pid"] if o else None, "tid": o["tid"] if o else None,
|
||||
"comm": o["comm"] if o else None, "owner_src": o["src"] if o else None, "join_dt_ms": round(dj) if dj is not None else None}
|
||||
pr = find_proc(o["pid"], t) if o else None
|
||||
row["proc_found"] = bool(pr)
|
||||
if pr:
|
||||
row["ptype"], row["pcomm"], row["ppid"] = pr["ptype"], pr["comm"], pr["ppid"]
|
||||
row["chain"] = [(c["pid"], c["ptype"]) for c in pr.get("chain", [])[:4]]
|
||||
row["head"] = pr.get("head")
|
||||
row["tail"] = pr.get("tail")
|
||||
row["alive_ms"] = round(t - pr["seen"])
|
||||
row["profile"] = pr.get("profile")
|
||||
elif o and execs.get(o["pid"]):
|
||||
ex = execs[o["pid"]][-1]
|
||||
row["ptype"] = "unseen-by-watcher:" + os.path.basename(ex["argv"].split(" ")[0])
|
||||
row["argv"] = ex["argv"][:120]
|
||||
row["profile"] = None
|
||||
elif o:
|
||||
row["ptype"] = "other:" + (o["comm"] or "?")
|
||||
row["profile"] = None
|
||||
else:
|
||||
row["ptype"] = "unattributed"
|
||||
row["profile"] = None
|
||||
S = sess(row["profile"]) if row["profile"] else None
|
||||
row["session_test"] = S["test"] if S else None
|
||||
row["launch_proxy"] = S["proxy"] if S else "n/a"
|
||||
row["proxy_signals"] = S["why"] if S else None
|
||||
row["test_at"] = test_of(t)
|
||||
row["since_close_ms"] = round(t - S["close"]) if S and S["close"] is not None else None
|
||||
row["close_src"] = S["close_src"] if S else None
|
||||
snd = []
|
||||
if S:
|
||||
for s in S["senders"][:3]:
|
||||
snd.append({"pid": s["pid"], "born": round(t - s["seen"]), "end": round(t - s["end"]) if s["end"] is not None else None, "self": bool(pr and s is pr)})
|
||||
row["senders"] = snd
|
||||
row["phase"] = "nosession" if not S else ("session-open-at-end" if S["close"] is None else ("before_close" if t < S["close"] else "after_close"))
|
||||
hq_rows.append(row)
|
||||
with open(out + "/huntq.jsonl", "w", encoding="utf-8") as f:
|
||||
for r in hq_rows:
|
||||
f.write(json.dumps(r, default=str) + "\n")
|
||||
print("HUNTQDIAG %-4s status [%s] | bpf datagrams to :53 %d, ss records %d, exec records %d | tcpdump lines %d, queries %d (unparsed %d) | rows %d, with a pid %d, process known to the watcher %d, no pid %d, bpf datagram without a tcpdump line %d | anchors %d | sample unparsed %s"
|
||||
% (arm, status, n_bpf, len(owners) - n_bpf, sum(len(v) for v in execs.values()), tcp_lines, len(uniq), len(unparsed), len(hq_rows), sum(1 for r in hq_rows if r["pid"]),
|
||||
sum(1 for r in hq_rows if r["proc_found"]), sum(1 for r in hq_rows if not r["pid"]), sum(1 for r in hq_rows if r["qname"].startswith("?")), len(anch), unparsed[:2]))
|
||||
def fmt(r):
|
||||
sn = ",".join("%d%s:b%s/e%s" % (s["pid"], "[self]" if s["self"] else "", "%+d" % s["born"], rel(s["end"])) for s in r["senders"]) or "none"
|
||||
return ("HUNTQ arm=%s run=%s t=%.0f at=%s qname=%s qtype=%s sport=%s pid=%s tid=%s thread=\"%s\" type=%s comm=\"%s\" chain=%s profile=%s session_test=%s launch_proxy=%s [%s] test_running=%s since_close_ms=%s (%s) phase=%s senders(pid:ms_from_birth/ms_from_end)=%s src=%s"
|
||||
% (r["arm"], r["run"], r["t"], r["hhmmss"], r["qname"], r["qtype"], r["sport"], r["pid"], r["tid"], r["comm"], r["ptype"], r.get("pcomm"), r.get("chain"),
|
||||
os.path.basename(r["profile"]) if r["profile"] else None, short(r["session_test"] or "?") if r["session_test"] or r["profile"] else None, r["launch_proxy"], r["proxy_signals"],
|
||||
short(r["test_at"] or "?"), rel(r["since_close_ms"]), r["close_src"], r["phase"], sn, r["owner_src"]))
|
||||
tel_rows = [r for r in hq_rows if r["qname"].rstrip(".") == TEL]
|
||||
other_rows = [r for r in hq_rows if r["qname"].rstrip(".") != TEL]
|
||||
for r in tel_rows:
|
||||
print(fmt(r))
|
||||
for r in other_rows[:150]:
|
||||
print(fmt(r))
|
||||
if len(other_rows) > 150:
|
||||
print("HUNTQMORE %-4s %d more queries of other names in huntq.jsonl (uploaded)" % (arm, len(other_rows) - 150))
|
||||
cnt_sum = collections.Counter((r["qname"], r["ptype"], r["launch_proxy"], r["phase"]) for r in hq_rows)
|
||||
print("HUNTQSUM %-4s total %d (telemetry host %d) | by (qname, process type, session launch proxy, before/after close): %s"
|
||||
% (arm, len(hq_rows), len(tel_rows), "; ".join("(%s, %s, proxy=%s, %s)=%d" % (k[0], k[1], k[2], k[3], v) for k, v in cnt_sum.most_common(80))))
|
||||
cnt_run = collections.Counter((r["run"], r["ptype"]) for r in tel_rows)
|
||||
print("HUNTQTEL %-4s telemetry-host queries by (run, type): %s | sessions of those with a launch proxy %d, without %d, unknown %d"
|
||||
% (arm, dict(cnt_run), sum(1 for r in tel_rows if r["launch_proxy"] == "yes"), sum(1 for r in tel_rows if r["launch_proxy"] == "no"), sum(1 for r in tel_rows if r["launch_proxy"] not in ("yes", "no"))))
|
||||
# ===== The MOZ_LOG side: every lookup of the telemetry host in every process's own log, native or TRR, attributed by pid ======================
|
||||
# Files: ff--main.<pid>.log.moz_log (a parent or background-task process), ff--child.<pid>.log.child-N.moz_log (a child process). The line
|
||||
# names its own process kind and thread: `[Parent 10037: Socket Thread]: D/nsHostResolver Resolving host [...]`.
|
||||
LOGPROC = re.compile(r"\[(\w+) (\d+): ([^\]]*)\]: (.*)$")
|
||||
MOZ_PID = (re.compile(r"ff--(?:main|child)\.(\d+)"), re.compile(r"ff-(\d+)"))
|
||||
DEC = re.compile(r"skip|bypass|exclu|not us|disabl|fallback|mode|confirm|blocklist|proxy|allow", re.I)
|
||||
def moz_pid_of(base):
|
||||
for rx in MOZ_PID:
|
||||
m = rx.search(base)
|
||||
if m:
|
||||
return int(m.group(1))
|
||||
return None
|
||||
def templ_of(msg):
|
||||
s = re.sub(r"0x[0-9a-fA-F]+", "P", msg)
|
||||
s = re.sub(r"\[[^\]]*\]", "[..]", s)
|
||||
s = re.sub(r"\d+", "N", s)
|
||||
return s[:95]
|
||||
def ctx_of(prof):
|
||||
pf = (PF.get(prof) or {}).get("prefs")
|
||||
return str((pf or {}).get("network.trr.stealth.contexts", "?")) if pf is not None else "?"
|
||||
mozl = [] # one per native lookup (a "Calling getaddrinfo" line for the telemetry host)
|
||||
per_pid = {} # (arm, run, pid) -> counters
|
||||
templ = collections.Counter()
|
||||
for run in runs:
|
||||
for fn in sorted(glob.glob(run["logd"] + "/*")):
|
||||
base = os.path.basename(fn)
|
||||
fpid = moz_pid_of(base)
|
||||
recs = []
|
||||
for ln in open(fn, encoding="utf-8", errors="replace"):
|
||||
hit = TEL in ln
|
||||
if not hit and not ("TRR" in ln and DEC.search(ln)):
|
||||
continue
|
||||
if not hit and len(recs) > 3000:
|
||||
continue
|
||||
tm = log_time(ln)
|
||||
mm = LOGPROC.search(ln)
|
||||
if tm is None or not mm:
|
||||
continue
|
||||
msg = mm.group(4)
|
||||
mod = re.match(r"[A-Z]/(\w+)", msg)
|
||||
mod = mod.group(1) if mod else "?"
|
||||
if hit and "Calling getaddrinfo" in msg:
|
||||
kind = "native"
|
||||
elif hit and "lookup completed" in msg:
|
||||
kind = "native-done"
|
||||
elif hit and (mod == "TRR" or "TRR Resolve" in msg or "TRR::SendHTTPRequest" in msg or "TRRQuery" in msg or "TrrLookup" in msg):
|
||||
kind = "trr"
|
||||
elif hit:
|
||||
kind = "resolver"
|
||||
else:
|
||||
kind = "context"
|
||||
recs.append({"t": tm, "kind": kind, "proc": mm.group(1), "pid": int(mm.group(2)), "thread": mm.group(3), "msg": msg[:230], "mod": mod})
|
||||
hits = [r for r in recs if r["kind"] != "context"]
|
||||
if not hits:
|
||||
continue
|
||||
pid = fpid or hits[0]["pid"]
|
||||
pr = find_proc(pid, hits[0]["t"])
|
||||
c = per_pid.setdefault((run["arm"], run["i"], pid), {"native": 0, "trr": 0, "resolver": 0, "done": 0, "pr": pr, "proc": hits[0]["proc"], "file": base})
|
||||
for r in hits:
|
||||
templ[(pr["ptype"] if pr else "log:" + r["proc"], r["mod"], templ_of(r["msg"]))] += 1
|
||||
k = {"native": "native", "trr": "trr", "resolver": "resolver"}.get(r["kind"], "done")
|
||||
c[k] += 1
|
||||
for r in hits:
|
||||
if r["kind"] != "native":
|
||||
continue
|
||||
near = [x for x in recs if x is not r and abs(x["t"] - r["t"]) <= 250 and x["kind"] in ("context", "trr", "resolver")][:6]
|
||||
prof = pr.get("profile") if pr else None
|
||||
S = sess(prof) if prof else None
|
||||
mozl.append({"arm": run["arm"], "run": run["i"], "t": r["t"], "pid": pid, "ptype": pr["ptype"] if pr else "unseen", "logproc": r["proc"], "thread": r["thread"],
|
||||
"profile": prof, "session_test": S["test"] if S else None, "proxy": S["proxy"] if S else "n/a", "ctx": ctx_of(prof) if prof else "?",
|
||||
"test_at": test_of(r["t"]), "since_close": round(r["t"] - S["close"]) if S and S["close"] is not None else None, "line": r["msg"],
|
||||
"near": [(round(x["t"] - r["t"]), x["kind"], x["msg"][:150]) for x in near], "file": base})
|
||||
mozl.sort(key=lambda r: r["t"])
|
||||
with open(out + "/huntl.jsonl", "w", encoding="utf-8") as f:
|
||||
for r in mozl:
|
||||
f.write(json.dumps(r, default=str) + "\n")
|
||||
for r in mozl:
|
||||
print("HUNTL arm=%s run=%s t=%.0f at=%s pid=%s type=%s log_process=%s thread=\"%s\" session_test=%s launch_proxy=%s ctx=%s test_running=%s since_close_ms=%s | %s | near(ms,kind,line)=%s"
|
||||
% (r["arm"], r["run"], r["t"], _time.strftime("%H:%M:%S", _time.gmtime(r["t"] / 1000)) + ".%03d" % (r["t"] % 1000), r["pid"], r["ptype"], r["logproc"], r["thread"],
|
||||
short(r["session_test"] or "?"), r["proxy"], r["ctx"], short(r["test_at"] or "?"), rel(r["since_close"]), r["line"][:200], r["near"][:4]))
|
||||
agg = collections.defaultdict(collections.Counter)
|
||||
for (a, ri, pid), c in per_pid.items():
|
||||
pr = c["pr"]
|
||||
prof = pr.get("profile") if pr else None
|
||||
key = (pr["ptype"] if pr else "log:" + c["proc"], "proxy=" + (sess(prof)["proxy"] if prof else "n/a"), "ctx=" + (ctx_of(prof) if prof else "?"))
|
||||
agg[key]["processes"] += 1
|
||||
agg[key]["with a native lookup"] += 1 if c["native"] else 0
|
||||
agg[key]["native lookups"] += c["native"]
|
||||
agg[key]["TRR lines"] += c["trr"]
|
||||
agg[key]["other resolver lines"] += c["resolver"]
|
||||
for k, v in sorted(agg.items(), key=lambda kv: -kv[1]["processes"]):
|
||||
print("HUNTLSUM %-4s %s | %s" % (arm, k, dict(v)))
|
||||
for (pt, mod, tp), n in templ.most_common(30):
|
||||
print("HUNTLTEMPL %-4s %-12s %-14s x%-4d %s" % (arm, pt, mod, n, tp))
|
||||
# Failing tests by EXACT node id (the junit's classname and name are rebuilt from the node id: no truncated name mixes the variants).
|
||||
def junit_of(run):
|
||||
d = {}
|
||||
try:
|
||||
for tc in ET.parse(run["junit"]).getroot().iter("testcase"):
|
||||
for f in list(tc.findall("failure")) + list(tc.findall("error")):
|
||||
d[(tc.get("classname"), tc.get("name"))] = (f.get("message") or "") + "\n" + (f.text or "")
|
||||
except (OSError, ET.ParseError):
|
||||
pass
|
||||
return d
|
||||
for run in runs:
|
||||
T, order = tests_of(run)
|
||||
jd = junit_of(run)
|
||||
for n in order:
|
||||
parts = n.split("::")
|
||||
want = (parts[0][:-3].replace("/", ".") + "".join("." + c for c in parts[1:-1]), parts[-1])
|
||||
msg = jd.get(want)
|
||||
if msg is None:
|
||||
continue
|
||||
a, b = T[n]["start"], (T[n]["finish"] or 0) + 2
|
||||
asked = QRE.findall(msg.split("asked the resolver of the machine", 1)[-1]) if "asked the resolver of the machine" in msg else []
|
||||
nat = [r for r in mozl if r["run"] == run["i"] and a <= r["t"] <= b]
|
||||
ker = [r for r in hq_rows if r["run"] == run["i"] and r["qname"].rstrip(".") == TEL and a <= r["t"] <= b]
|
||||
print("HUNTFAIL %-4s run %d %s | trap counted (name, port, proto) %s | MOZ_LOG native lookups of the telemetry host in its window %d: %s | kernel-side queries of the telemetry host in its window %d: %s"
|
||||
% (run["arm"], run["i"], n, [(x[0], x[1], x[2]) for x in asked][:8], len(nat),
|
||||
[(r["pid"], r["ptype"], r["logproc"], "session " + short(r["session_test"] or "?"), "proxy " + r["proxy"], "ctx " + str(r["ctx"]), "+%d ms into the test" % round(r["t"] - a)) for r in nat][:6],
|
||||
len(ker), [(r["pid"], r["ptype"], "session " + short(r["session_test"] or "?"), "proxy " + r["launch_proxy"], "sport %s" % r["sport"], "+%d ms into the test" % round(r["t"] - a)) for r in ker][:6]))
|
||||
PY
|
||||
- name: Readable outputs (written as root under sudo)
|
||||
if: always()
|
||||
run: |
|
||||
sudo tar -czf "$RUNNER_TEMP/out/moz-logs.tgz" -C "$RUNNER_TEMP/out" moz || true
|
||||
sudo chmod -R a+rX "$RUNNER_TEMP/out" || true
|
||||
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
if: always()
|
||||
with:
|
||||
name: "pingsender-dns-${{ matrix.arm }}-${{ github.run_id }}"
|
||||
path: |
|
||||
${{ runner.temp }}/out/runs.jsonl
|
||||
${{ runner.temp }}/out/watch.jsonl
|
||||
${{ runner.temp }}/out/watch.out
|
||||
${{ runner.temp }}/out/args.txt
|
||||
${{ runner.temp }}/out/junit
|
||||
${{ runner.temp }}/out/times
|
||||
${{ runner.temp }}/out/pytest
|
||||
${{ runner.temp }}/out/prefs
|
||||
${{ runner.temp }}/out/sender-logs
|
||||
${{ runner.temp }}/out/dns
|
||||
${{ runner.temp }}/out/huntq.jsonl
|
||||
${{ runner.temp }}/out/huntl.jsonl
|
||||
${{ runner.temp }}/out/moz-logs.tgz
|
||||
@@ -0,0 +1,556 @@
|
||||
# HUNT ONLY, never merged. The PUBLISHED packages against stock Playwright and against the real Firefox, same job, alternated rounds,
|
||||
# Windows and Linux (Linux under xvfb for the headed retail arms): invisible-playwright 0.52.1 + invisible-core 64.73.0 on the engine
|
||||
# firefox-64. Measurement only.
|
||||
# Arms: inproc4 (4 browsers in one process, no timezone, no proxy), inproc4quiet (the same with the hunt's own samplers off),
|
||||
# inproc4tz (timezone given), inproc4px (through a local proxy), late (typing 60 s after the last launch), solo (one browser alone on
|
||||
# the machine), one (1 browser per process, 4 processes at once), remote (launch_server), stock (Playwright's Firefox),
|
||||
# retail1 / retail4 / retail4late (the official Firefox 159, headed, no Playwright: 1 browser, 4 together closed 20 s after their
|
||||
# first load, 4 together closed 70 s after it).
|
||||
# This push is the shutdown hunt (arms shut20 shut70 shut180 retail1 retail4late retail1long, 4 rounds, about 11 minutes a round on
|
||||
# Windows, about 45 minutes in all); the full list is in a comment in the run step. The earlier estimate for the full list: about 8
|
||||
# minutes a round on Windows (late about 90 s, retail4late about 100 s, the other arms 15-45 s), six rounds, about 50
|
||||
# minutes against the 70 of the step; the loop starts no arm after 63 minutes.
|
||||
# This push: Remote Settings log (services.settings.loglevel=debug) from birth to close, ours (ncshut75x4, ncshut150x4: 4 together, closed
|
||||
# at 75 s and 150 s of session, close deadline 60 s) and retail (retail4late at 70 s, retail4x150 at 150 s), and the exit probe with the
|
||||
# firefox processes left at +1 s and +10 s; Windows only, 4 rounds: about 22 minutes for `ours`, 18 for `retail`.
|
||||
# This push: ncshut75x4 (4 together, closed at 75 s of session, the close deadline and the reaper's own at 60 s in this hunt only: the wrapper
|
||||
# that widens them was never installed in the earlier runs, see install_close_stamps) against retail4late; Windows, 4 rounds. HUNTCLOSEARGS
|
||||
# prints the timeout each Connection.close and each Reaper received.
|
||||
name: published latency hunt
|
||||
on:
|
||||
push:
|
||||
branches: [hunt/published-latency]
|
||||
paths: [scripts/hunt_published_latency.py, .github/workflows/published-latency-hunt.yml]
|
||||
permissions:
|
||||
contents: read
|
||||
concurrency:
|
||||
group: published-latency-hunt
|
||||
cancel-in-progress: true
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
jobs:
|
||||
hunt:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
max-parallel: 4
|
||||
matrix:
|
||||
os: [windows-2022]
|
||||
# The real Firefox in a job of its own: twice a Windows runner running it with ours was lost ("lost communication",
|
||||
# runs 43769962892 and 43777096307, no log left), and ours went with it.
|
||||
part: [ours, retail]
|
||||
include:
|
||||
- part: ours
|
||||
arms: "ncshut75x4"
|
||||
- part: retail
|
||||
arms: "retail4late"
|
||||
runs-on: ${{ matrix.os }}
|
||||
timeout-minutes: 90
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
env:
|
||||
PYTHONUNBUFFERED: "1"
|
||||
ONLY_ARMS: ${{ matrix.arms }}
|
||||
steps:
|
||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
with: { fetch-depth: 1 }
|
||||
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
|
||||
with: { python-version: '3.12' }
|
||||
- name: A venv from PyPI (0.52.1) and stock Playwright
|
||||
run: |
|
||||
if [ "$RUNNER_OS" = "Windows" ]; then BIN=Scripts; else BIN=bin; fi
|
||||
python -m venv "$RUNNER_TEMP/after"
|
||||
"$RUNNER_TEMP/after/$BIN/python" -m pip install -q --upgrade pip
|
||||
"$RUNNER_TEMP/after/$BIN/python" -m pip install -q "invisible-playwright==0.52.1" psutil websockets "playwright==$(cat scripts/playwright_pin.txt)"
|
||||
"$RUNNER_TEMP/after/$BIN/python" -c "import importlib.metadata as m; print('after', m.version('invisible-playwright'), m.version('invisible-core'))"
|
||||
if [ "$RUNNER_OS" = "Linux" ]; then sudo apt-get update -q && sudo apt-get install -y -q xvfb xdotool wmctrl openbox; "$RUNNER_TEMP/after/$BIN/python" -m playwright install --with-deps firefox; else "$RUNNER_TEMP/after/$BIN/python" -m playwright install firefox; fi
|
||||
echo "PY_AFTER=$RUNNER_TEMP/after/$BIN/python" >> "$GITHUB_ENV"
|
||||
- name: A third venv, "next" (core and wrapper from git, the close that hands the rest to a reaper)
|
||||
run: |
|
||||
if [ "$RUNNER_OS" = "Windows" ]; then BIN=Scripts; else BIN=bin; fi
|
||||
N="$RUNNER_TEMP/next/$BIN/python"
|
||||
python -m venv "$RUNNER_TEMP/next"
|
||||
"$N" -m pip install -q --upgrade pip
|
||||
# The wrapper's own dependencies first (its pin pulls invisible-core 64.73.0), then the core from git main, then the wrapper
|
||||
# from its branch with --no-deps so the pin cannot pull the published core back.
|
||||
"$N" -m pip install -q "invisible-playwright==0.52.1" psutil websockets
|
||||
"$N" -m pip install -q --force-reinstall "git+https://github.com/oss-invisible/core@main"
|
||||
"$N" -m pip install -q --no-deps --force-reinstall "git+https://github.com/oss-invisible/playwright@fix/close-hands-the-files-to-the-reaper"
|
||||
"$N" -c "
|
||||
import importlib.metadata as m, json
|
||||
for n in ('invisible-core', 'invisible-playwright'):
|
||||
d = m.distribution(n)
|
||||
u = json.loads(d.read_text('direct_url.json') or '{}')
|
||||
print('next', n, d.version, u.get('url'), u.get('vcs_info', {}).get('requested_revision'), u.get('vcs_info', {}).get('commit_id'))
|
||||
import invisible_core.process as p
|
||||
print('next has the reaper:', hasattr(p, 'Reaper'))
|
||||
"
|
||||
echo "PY_NEXT=$N" >> "$GITHUB_ENV"
|
||||
- name: The engine the venv fetches
|
||||
run: |
|
||||
echo "FF_AFTER=$(cd "$RUNNER_TEMP" && "$PY_AFTER" -m invisible_playwright fetch | tail -1)" >> "$GITHUB_ENV"
|
||||
- name: The retail Firefox 159.0 en-US (official, for the reference arms)
|
||||
continue-on-error: true
|
||||
run: |
|
||||
B=https://archive.mozilla.org/pub/firefox/releases/159.0
|
||||
R="$RUNNER_TEMP/retail"
|
||||
mkdir -p "$R"
|
||||
if [ "$RUNNER_OS" = "Windows" ]; then
|
||||
D="$B/win64/en-US/"; F="Firefox%20Setup%20159.0.exe"
|
||||
else
|
||||
D="$B/linux-x86_64/en-US/"; F="firefox-159.0.tar.xz"
|
||||
fi
|
||||
echo "the files of $D:"
|
||||
curl -fsSL --retry 3 "$D" | grep -o 'href="[^"]*"' | grep -iE 'firefox' | head -20
|
||||
curl -fsSL --retry 3 -o "$R/package.bin" "$D$F"
|
||||
ls -l "$R/package.bin"
|
||||
sha256sum "$R/package.bin"
|
||||
if [ "$RUNNER_OS" = "Windows" ]; then
|
||||
if command -v 7z > /dev/null 2>&1; then SZ=7z; else SZ="/c/Program Files/7-Zip/7z.exe"; fi
|
||||
cp "$R/package.bin" "$R/package.exe"
|
||||
"$SZ" x "$R/package.exe" -o"$R/win" -y > /dev/null
|
||||
FF="$R/win/core/firefox.exe"
|
||||
else
|
||||
tar -xJf "$R/package.bin" -C "$R"
|
||||
FF="$R/firefox/firefox"
|
||||
fi
|
||||
ls -l "$FF"
|
||||
sha256sum "$FF"
|
||||
echo "FF_RETAIL=$FF" >> "$GITHUB_ENV"
|
||||
- name: Six rounds, the arms in rotating order
|
||||
continue-on-error: true
|
||||
env:
|
||||
HUNT_PROBES: "1"
|
||||
ROUNDS: "4"
|
||||
timeout-minutes: 70
|
||||
run: |
|
||||
set +e
|
||||
S=scripts/hunt_published_latency.py
|
||||
# What an arm prints: its HUNT lines, each tagged with the arm.
|
||||
keep() { grep --line-buffered -E '^HUNT(ROW|SLOW|PROBE|EVAL|SHUT|SURVIVOR|BGTASK|ALIVE|EXITPROBE|PARENTS|CLOSEARGS)' | sed -u -E "s/^(HUNT[A-Z]+) /\1 [$1] /"; }
|
||||
# The retail arms: N browsers, round, seconds after the first load before the normal close (Linux headed under xvfb).
|
||||
retail() {
|
||||
if [ -z "$FF_RETAIL" ]; then echo "HUNTROW {\"arm\": \"retail\", \"crash\": \"no retail Firefox\"}"; return; fi
|
||||
if [ "$RUNNER_OS" = "Linux" ]; then
|
||||
# A window manager in the virtual display, so the retail browser can be closed as a person closes it (wmctrl ->
|
||||
# _NET_CLOSE_WINDOW -> WM_DELETE_WINDOW); without one only a signal is left, which is not a normal quit.
|
||||
xvfb-run -a -s "-screen 0 1280x1024x24" sh -c 'openbox > /dev/null 2>&1 & sleep 1; exec "$0" "$@"' "$PY_AFTER" $S retail "$1" "$2" "$FF_RETAIL" "$3" 2>&1
|
||||
else
|
||||
"$PY_AFTER" $S retail "$1" "$2" "$FF_RETAIL" "$3" 2>&1
|
||||
fi
|
||||
}
|
||||
# A limit per arm, shorter than the step's: 4 times what the arm should take, at most 12 minutes. The arm's python writes its pid
|
||||
# (HUNT_PIDFILE, one line per process) and a watchdog kills that tree when the limit comes, printing the crash row; the next
|
||||
# arm then runs. The watchdog's output is kept off the arm's pipe (a sleep left behind must not hold the tee).
|
||||
limit_of() {
|
||||
local e
|
||||
case "$1" in
|
||||
solo|nclose20) e=30 ;; shut20) e=30 ;; inproc4|inproc4quiet|inproc4tz|inproc4px|stock|nclose20x4) e=35 ;;
|
||||
one|remote|retail1|retail4) e=45 ;; shut70|nclose75) e=85 ;; nclose75x4) e=95 ;; late|retail4late) e=100 ;;
|
||||
shut180|retail1long|ncshut75x4) e=200 ;; ncshut150x4|retail4x150) e=250 ;; exitprobe_after|exitprobe_next) e=25 ;; *) e=100 ;;
|
||||
esac
|
||||
echo $(( e * 4 > 720 ? 720 : e * 4 ))
|
||||
}
|
||||
kill_arm() {
|
||||
local pid
|
||||
for pid in $(cat "$HUNT_PIDFILE" 2>/dev/null); do
|
||||
if [ "$RUNNER_OS" = "Windows" ]; then taskkill //T //F //PID "$pid" > /dev/null 2>&1; else pkill -9 -P "$pid" > /dev/null 2>&1; kill -9 "$pid" > /dev/null 2>&1; fi
|
||||
done
|
||||
}
|
||||
run_arm() {
|
||||
local lim wd
|
||||
lim=$(limit_of "$1")
|
||||
export HUNT_PIDFILE="$RUNNER_TEMP/arm.pid" HUNT_ARM="$1" HUNT_LIMIT_S="$lim"
|
||||
: > "$HUNT_PIDFILE"
|
||||
rm -f "$RUNNER_TEMP/arm.done" "$HUNT_PIDFILE.fault"
|
||||
(
|
||||
exec > /dev/null
|
||||
sleep "$lim" > /dev/null 2>&1
|
||||
# The arm ended on its own: nothing to report, nothing to kill (killing the sleep of this watchdog used to let it get
|
||||
# here, and the "timed out" rows of the run 43783310128 were that, not a hang).
|
||||
[ -e "$RUNNER_TEMP/arm.done" ] && exit 0
|
||||
echo "HUNTROW [$1] {\"arm\": \"$1\", \"round\": \"$2\", \"crash\": \"arm timed out after $lim s\"}" | tee -a "$RUNNER_TEMP/rows.log" >&2
|
||||
kill_arm
|
||||
) &
|
||||
wd=$!
|
||||
case "$1" in
|
||||
inproc4) "$PY_AFTER" $S inproc 4 "$2" "$FF_AFTER" 2>&1 | keep inproc4 ;;
|
||||
inproc4quiet) HUNT_NO_SAMPLER=1 "$PY_AFTER" $S inproc 4 "$2" "$FF_AFTER" 2>&1 | keep inproc4quiet ;;
|
||||
inproc4tz) HUNT_TIMEZONE=Europe/Rome "$PY_AFTER" $S inproc 4 "$2" "$FF_AFTER" 2>&1 | keep inproc4tz ;;
|
||||
inproc4px) HUNT_PROXY=1 "$PY_AFTER" $S inproc 4 "$2" "$FF_AFTER" 2>&1 | keep inproc4px ;;
|
||||
late) HUNT_TYPE_LATE_S=60 "$PY_AFTER" $S inproc 4 "$2" "$FF_AFTER" 2>&1 | keep late ;;
|
||||
solo) "$PY_AFTER" $S inproc 1 "$2" "$FF_AFTER" 2>&1 | keep solo ;;
|
||||
remote) "$PY_AFTER" $S remote 4 "$2" "$FF_AFTER" 2>&1 | keep remote ;;
|
||||
stock) "$PY_AFTER" $S stock 4 "$2" 2>&1 | keep stock ;;
|
||||
one) for k in 0 1 2 3; do "$PY_AFTER" $S inproc 1 "$2-$k" "$FF_AFTER" > "$RUNNER_TEMP/one-$k.log" 2>&1 & done; wait
|
||||
cat "$RUNNER_TEMP"/one-*.log | keep one ;;
|
||||
shut20) HUNT_SHUT=1 HUNT_SESSION_S=20 "$PY_AFTER" $S inproc 1 "$2" "$FF_AFTER" 2>&1 | keep shut20 ;;
|
||||
shut70) HUNT_SHUT=1 HUNT_SESSION_S=70 "$PY_AFTER" $S inproc 1 "$2" "$FF_AFTER" 2>&1 | keep shut70 ;;
|
||||
shut180) HUNT_SHUT=1 HUNT_SESSION_S=180 "$PY_AFTER" $S inproc 1 "$2" "$FF_AFTER" 2>&1 | keep shut180 ;;
|
||||
nclose20) HUNT_NCLOSE=1 HUNT_SESSION_S=20 "$PY_NEXT" $S inproc 1 "$2" "$FF_AFTER" 2>&1 | keep nclose20 ;;
|
||||
nclose75) HUNT_NCLOSE=1 HUNT_SESSION_S=75 "$PY_NEXT" $S inproc 1 "$2" "$FF_AFTER" 2>&1 | keep nclose75 ;;
|
||||
nclose20x4) HUNT_NCLOSE=1 HUNT_SESSION_S=20 "$PY_NEXT" $S inproc 4 "$2" "$FF_AFTER" 2>&1 | keep nclose20x4 ;;
|
||||
nclose75x4) HUNT_NCLOSE=1 HUNT_SESSION_S=75 "$PY_NEXT" $S inproc 4 "$2" "$FF_AFTER" 2>&1 | keep nclose75x4 ;;
|
||||
exitprobe_after) "$PY_AFTER" $S exitprobe-outer "$2" "$FF_AFTER" after 2>&1 | keep exitprobe_after ;;
|
||||
exitprobe_next) "$PY_NEXT" $S exitprobe-outer "$2" "$FF_AFTER" next 2>&1 | keep exitprobe_next ;;
|
||||
ncshut75x4) HUNT_NCLOSE=1 HUNT_NCSHUT=1 HUNT_RS=1 HUNT_SESSION_S=75 HUNT_CLOSE_TIMEOUT=60 "$PY_NEXT" $S inproc 4 "$2" "$FF_AFTER" 2>&1 | keep ncshut75x4 ;;
|
||||
ncshut150x4) HUNT_NCLOSE=1 HUNT_NCSHUT=1 HUNT_RS=1 HUNT_SESSION_S=150 HUNT_CLOSE_TIMEOUT=60 "$PY_NEXT" $S inproc 4 "$2" "$FF_AFTER" 2>&1 | keep ncshut150x4 ;;
|
||||
retail1) retail 1 "$2" 20 | keep retail1 ;;
|
||||
retail1long) retail 1 "$2" 180 | keep retail1long ;;
|
||||
retail4) retail 4 "$2" 20 | keep retail4 ;;
|
||||
retail4late) HUNT_RS=1 retail 4 "$2" 70 | keep retail4late ;;
|
||||
retail4x150) HUNT_RS=1 retail 4 "$2" 150 | keep retail4x150 ;;
|
||||
esac
|
||||
: > "$RUNNER_TEMP/arm.done"
|
||||
kill "$wd" > /dev/null 2>&1
|
||||
if [ -s "$HUNT_PIDFILE.fault" ]; then sed "s/^/HUNTALIVE [$1] fault: /" "$HUNT_PIDFILE.fault" | head -120; fi
|
||||
if [ "$RUNNER_OS" = "Windows" ]; then taskkill //F //IM firefox.exe //T > /dev/null 2>&1; else pkill -9 -f firefox > /dev/null 2>&1; fi
|
||||
}
|
||||
# The full list (the default when the focused one below is removed):
|
||||
# inproc4 inproc4quiet inproc4tz inproc4px late solo one remote stock retail1 retail4 retail4late
|
||||
# The shutdown hunt: why our engine on Windows does not exit within the core's 5 s after a long session. shut20/70/180 are
|
||||
# ours (one browser per process, idle until the session is 20/70/180 s old, then closed, the engine's shutdown log timed),
|
||||
# the retail ones are the real Firefox closed by its window after 20 s / 70 s (4 together) / 180 s.
|
||||
# shut20 shut70 shut180 retail1 retail4late retail1long (the shutdown hunt of the run before)
|
||||
# The close of the core with a reaper (venv "next", git main of the core and the wrapper's fix branch), 1 browser and 4 in one
|
||||
# process, closed after 20 s / 75 s of session, against the real Firefox closed by its window, and ours as published (shut70).
|
||||
ARMS=(nclose20 nclose75 nclose20x4 nclose75x4 retail1 retail4late shut70)
|
||||
if [ -n "$ONLY_ARMS" ]; then read -ra ARMS <<< "$ONLY_ARMS"; fi
|
||||
N=${#ARMS[@]}
|
||||
for r in $(seq 0 $((${ROUNDS:-6}-1))); do
|
||||
for k in $(seq 0 $((N-1))); do
|
||||
if [ "$SECONDS" -gt 3780 ]; then echo "time guard: no new arm after $SECONDS s"; break 2; fi
|
||||
a=${ARMS[$(( (k + r) % N ))]}; run_arm "$a" "r$r" | tee -a "$RUNNER_TEMP/rows.log"
|
||||
done
|
||||
done
|
||||
true
|
||||
- name: The table
|
||||
if: always()
|
||||
run: |
|
||||
python - "$RUNNER_TEMP/rows.log" <<'PY'
|
||||
import json, re, sys, statistics
|
||||
rows = {}
|
||||
for line in open(sys.argv[1], encoding="utf-8"):
|
||||
m = re.match(r"HUNTROW \[(\w+)\] (.*)", line.strip())
|
||||
if m:
|
||||
rows.setdefault(m.group(1), []).append(json.loads(m.group(2)))
|
||||
def q(v, p):
|
||||
v = sorted(x for x in v if x is not None)
|
||||
return v[min(len(v) - 1, int(p * len(v)))] if v else None
|
||||
def cnt(v):
|
||||
c = {}
|
||||
for x in v:
|
||||
c[str(x)] = c.get(str(x), 0) + 1
|
||||
return dict(sorted(c.items(), key=lambda kv: -kv[1])[:8])
|
||||
def trio(v):
|
||||
return "p50 %s p95 %s max %s" % (q(v, .5), q(v, .95), max((x for x in v if x is not None), default=None))
|
||||
for arm in ("inproc4", "inproc4quiet", "inproc4tz", "inproc4px", "late", "solo", "one", "remote", "stock", "shut20", "shut70", "shut180", "nclose20", "nclose75", "nclose20x4", "nclose75x4", "ncshut75x4", "ncshut150x4"):
|
||||
if not rows.get(arm):
|
||||
continue
|
||||
r = [x for x in rows.get(arm, []) if "crash" not in x]
|
||||
crashes = len(rows.get(arm, [])) - len(r)
|
||||
ev =[e for x in r for e in x["eval_ms"]]
|
||||
gr = [g for x in r for g in x["goto_req_ms"]]
|
||||
print("HUNTLAUNCHSPLIT %-12s ms: launch() %s | new_context %s | new_page %s | first_load %s | to_first_load p50 %s p95 %s | Firefox parent CPU s p50: launch() %s new_context %s new_page %s first_load %s"
|
||||
% (arm, trio([x.get("enter_ms") for x in r]), trio([x.get("ctx_ms") for x in r]), trio([x.get("new_page_ms") for x in r]), trio([x.get("first_load_ms") for x in r]),
|
||||
q([x.get("to_first_load_ms") for x in r], .5), q([x.get("to_first_load_ms") for x in r], .95),
|
||||
q([x.get("enter_cpu_s") for x in r], .5), q([x.get("ctx_cpu_s") for x in r], .5), q([x.get("new_page_cpu_s") for x in r], .5), q([x.get("first_load_cpu_s") for x in r], .5)))
|
||||
print("HUNTTABLE %-12s browsers %3d crashes %d | launch ms p50 %s p95 %s | close ms p50 %s p95 %s | eval ms p50 %s p95 %s max %s >300ms %d of %d | goto->request ms p50 %s p90 %s max %s | cpu s/browser p50 %s"
|
||||
% (arm, len(r), crashes, q([x["launch_ms"] for x in r], .5), q([x["launch_ms"] for x in r], .95), q([x["close_ms"] for x in r], .5), q([x["close_ms"] for x in r], .95),
|
||||
q(ev, .5), q(ev, .95), max(ev) if ev else None, sum(1 for e in ev if e > 300), len(ev), q(gr, .5), q(gr, .9), max((g for g in gr if g is not None), default=None),
|
||||
q([x["cpu_s_per_browser"] for x in r], .5)))
|
||||
ty = [x.get("typing") or {} for x in r]
|
||||
ok = [t for t in ty if "slip_abs_max" in t]
|
||||
errs = [t.get("error") for t in ty if t.get("error")]
|
||||
print("HUNTTYPING %-12s typed %d of %d | key slip vs plan: p50 of browsers %s, max %s | keys over 100 ms %d of %d | compressions %d | mouse: longest gap %s ms, bursts <2 ms %d, clicks %d | errors %s"
|
||||
% (arm, len(ok), len(ty), q([t["slip_abs_p50"] for t in ok], .5), max((t["slip_abs_max"] for t in ok), default=None),
|
||||
sum(t["keys_over_100ms"] for t in ok), sum(t["keys_planned"] for t in ok), sum(t["compressions"] for t in ok),
|
||||
max((t["mouse_gap_max"] or 0 for t in ty if "mousemoves" in t), default=None), sum(t.get("mouse_bursts_under_2ms", 0) for t in ty),
|
||||
sum(t.get("clicks", 0) for t in ty), errs[:2]))
|
||||
# Where the slip is born, per key (detail = planned, sent, answered, timeStamp, handler; ms from the first send).
|
||||
det = [d for t in ok for d in t.get("detail") or []]
|
||||
late_c = [d[1] - d[0] for d in det]
|
||||
rt = [d[2] - d[1] for d in det]
|
||||
birth = [d[3] - d[1] for d in det]
|
||||
hts = [h for t in ok for h in t.get("handler_minus_ts") or []]
|
||||
print("HUNTKEYCLOCKS %-12s on event.timeStamp: keys over 100 ms %d, max %s, compressions %d | on the handler: keys over 100 ms %d, max %s | handler - timeStamp p50 %s p95 %s max %s | matched %d of %d | machine CPU busy %% during typing p50 %s max %s"
|
||||
% (arm, sum(t["keys_over_100ms"] for t in ok), max((t["slip_abs_max"] for t in ok), default=None), sum(t["compressions"] for t in ok),
|
||||
sum(t.get("h_keys_over_100ms", 0) for t in ok), max((t.get("h_slip_abs_max", 0) for t in ok), default=None),
|
||||
q(hts, .5), q(hts, .95), max(hts, default=None), sum(1 for t in ok if t.get("detail")), len(ok),
|
||||
q([t.get("machine_cpu_busy_pct") for t in ty], .5), max((t.get("machine_cpu_busy_pct") or 0 for t in ty), default=None)))
|
||||
if det:
|
||||
print("HUNTKEYSPLIT %-12s client send vs plan: keys over 100 ms %d, p50 %s max %s | client send -> engine answer p50 %s p95 %s max %s | client send -> event.timeStamp p50 %s p95 %s max %s"
|
||||
% (arm, sum(1 for x in late_c if abs(x) > 100), q(late_c, .5), max(late_c), q(rt, .5), q(rt, .95), max(rt), q(birth, .5), q(birth, .95), max(birth)))
|
||||
worst = sorted(((abs((t["detail"][i][3] - t["detail"][0][3]) - t["detail"][i][0]), t["detail"][max(0, i - 1):i + 1]) for t in ok if t.get("detail")
|
||||
for i in range(len(t["detail"]))), key=lambda w: -w[0])[:4]
|
||||
for slip, pair in worst:
|
||||
print("HUNTKEYWORST %-12s timeStamp slip %.0f ms | previous and this key [planned, sent, answered, timeStamp, handler]: %s" % (arm, slip, pair))
|
||||
# The retail Firefox 159: from the process start to the first page loaded (the onload beacon at the server), to the first
|
||||
# visible top-level window, the normal close to every process of the tree gone, the session and the parent's CPU.
|
||||
for arm in ("retail1", "retail4", "retail4late", "retail1long"):
|
||||
all_r = rows.get(arm, [])
|
||||
r = [x for x in all_r if "crash" not in x]
|
||||
if not all_r:
|
||||
continue
|
||||
print("HUNTRETAIL %-12s browsers %d crashes %d %s | start->load ms %s | start->window ms %s (no window: %d) | close->tree gone ms %s (timeouts %d) | close->main process gone ms p50 %s p95 %s | session s p50 %s | parent CPU s p50 %s p95 %s, at load p50 %s | tree CPU s at close p50 %s | exited before close %d | close cmd rc %s | last to exit %s"
|
||||
% (arm, len(r), len(all_r) - len(r), [x.get("crash") for x in all_r if "crash" in x][:1], trio([x.get("start_to_load_ms") for x in r]),
|
||||
trio([x.get("start_to_window_ms") for x in r]), sum(1 for x in r if x.get("start_to_window_ms") is None),
|
||||
trio([x.get("close_ms") for x in r]), sum(1 for x in r if x.get("close_timeout")),
|
||||
q([x.get("close_main_ms") for x in r], .5), q([x.get("close_main_ms") for x in r], .95), q([x.get("session_s") for x in r], .5),
|
||||
q([x.get("parent_cpu_s") for x in r], .5), q([x.get("parent_cpu_s") for x in r], .95), q([x.get("cpu_at_load_s") for x in r], .5),
|
||||
q([x.get("tree_cpu_at_close_s") for x in r], .5), sum(1 for x in r if x.get("exited_before_close")),
|
||||
sorted({str((x.get("close_cmd") or [None])[0]) for x in r}), sorted({(x.get("last_exits") or [["?"]])[0][0] for x in r})))
|
||||
# The path of one evaluate, segment by segment (p50/p95 ms, over the traced browser of every round).
|
||||
segs, missing, trace_n = {}, {}, {}
|
||||
for line in open(sys.argv[1], encoding="utf-8"):
|
||||
m = re.match(r"HUNTEVAL \[(\w+)\] (.*)", line.strip())
|
||||
if m:
|
||||
d = json.loads(m.group(2))
|
||||
trace_n[m.group(1)] = trace_n.get(m.group(1), 0) + 1
|
||||
for name, vals in d["segs"].items():
|
||||
if isinstance(vals, list):
|
||||
segs.setdefault(m.group(1), {}).setdefault(name, []).extend(vals)
|
||||
elif name == "missing":
|
||||
missing[m.group(1)] = missing.get(m.group(1), 0) + vals
|
||||
names = ("call_to_send", "send_to_pickup", "pickup_to_pipe", "pipe_to_reply_read", "read_to_ready", "ready_to_reply", "reply_to_loop", "dispatch", "resolve_to_return", "total")
|
||||
for arm, s in sorted(segs.items()):
|
||||
print("HUNTEVALSPLIT %-12s traced browsers %d, evaluates %d, incomplete %d, engine commands per evaluate p50 %s | p50/p95 ms: %s"
|
||||
% (arm, trace_n[arm], len(s.get("total", [])), missing.get(arm, 0), q(s.get("cmds", []), .5),
|
||||
" | ".join("%s %s/%s" % (n, q(s.get(n, []), .5), q(s.get(n, []), .95)) for n in names)))
|
||||
# ---- The close of the core with a reaper (nclose arms): each step, ms from the user's close() call (p50/p95/max over every
|
||||
# close), the steps between them, and the close of the other arms next to it (same job, same rounds).
|
||||
NC = ("nclose20", "nclose75", "nclose20x4", "nclose75x4", "ncshut75x4", "ncshut150x4")
|
||||
for arm in NC:
|
||||
r = [x for x in rows.get(arm, []) if "crash" not in x]
|
||||
if not rows.get(arm):
|
||||
continue
|
||||
def d(a, b):
|
||||
return [x[b] - x[a] for x in r if x.get(a) is not None and x.get(b) is not None]
|
||||
print("HUNTNCLOSE %-11s closes %d crashes %d, connection found by %s | from the close() call: (0) Connection.close entered %s | (i) pipe closed by the core %s | (ii) engine EOF seen by the reader %s | (iii) real parent exited %s | Connection.close returned %s | (iv) close() returned %s | (v) reaper finished %s (not finished %d)"
|
||||
% (arm, len(r), len(rows[arm]) - len(r), sorted({str(x.get("nc_mapped")) for x in r}), trio([x.get("nc_entry") for x in r]), trio([x.get("nc_pipe") for x in r]),
|
||||
trio([x.get("nc_eof") for x in r]), trio([x.get("nc_parent") for x in r]), trio([x.get("nc_conn_return") for x in r]), trio([x.get("nc_return") for x in r]),
|
||||
trio([x.get("nc_reaper") for x in r]), sum(1 for x in r if x.get("nc_reaper_finished") is False)))
|
||||
print("HUNTNCLOSESTEPS %-11s steps ms: call->entry %s | entry->pipe closed %s | pipe closed->engine EOF %s | engine EOF->parent exit %s | parent exit->Connection.close returned %s | Connection.close returned->close() returned %s | close() returned->reaper finished %s"
|
||||
% (arm, trio([x.get("nc_entry") for x in r]), trio(d("nc_entry", "nc_pipe")), trio(d("nc_pipe", "nc_eof")), trio(d("nc_eof", "nc_parent")),
|
||||
trio(d("nc_parent", "nc_conn_return")), trio(d("nc_conn_return", "nc_return")), trio(d("nc_return", "nc_reaper"))))
|
||||
for arm in NC + ("shut70", "retail1", "retail4late"):
|
||||
r = [x for x in rows.get(arm, []) if "crash" not in x]
|
||||
if r:
|
||||
print("HUNTCLOSECMP %-11s close() ms %s | n %d" % (arm, trio([x.get("nc_return", x.get("close_ms")) if arm in NC else x.get("close_ms") for x in r]), len(r)))
|
||||
# ---- ncshut75x4 against retail4late: where ours loses time. (a) close -> quit, (b) quit -> real parent gone, (c) parent gone ->
|
||||
# tree gone; the tree at the close by type; the CPU of the tree between the close and the parent's exit (more work or more waiting:
|
||||
# slow closes, parent exit over 4.9 s, against the fast ones).
|
||||
# ---- Remote Settings: when the first sync starts (ms from the launch), what is in progress at the close instant, and the blocker
|
||||
# "RemoteSettingsClient - finish IDB access." (completed at ms after the quit). Parsed from the client's debug log, see rs_report.
|
||||
for arm in ("ncshut75x4", "ncshut150x4", "retail4late", "retail4x150"):
|
||||
r = [x for x in rows.get(arm, []) if "crash" not in x and "rs_lines" in x]
|
||||
if not r:
|
||||
continue
|
||||
busy = [x for x in r if x.get("rs_busy")]
|
||||
kinds = {"sync": sum(1 for x in r if x["rs_busy_at_close"]["syncs"]), "dump import": sum(1 for x in r if x["rs_busy_at_close"]["dumps"]),
|
||||
"poll": sum(1 for x in r if x["rs_busy_at_close"]["poll"]), "bundle": sum(1 for x in r if x["rs_busy_at_close"]["bundle"]),
|
||||
"attachment": sum(1 for x in r if x["rs_busy_at_close"]["attachment_recent"])}
|
||||
print("HUNTRS %-12s closes %d | first poll start ms from launch %s | first sync start %s | collections synced p50 %s max %s | RS lines p50 %s, after the close p50 %s | closes with RS work in progress at the close %d of %d, by kind %s | that work lasts (ms after the close) %s, never ended in %d | finish-IDB blocker completed at quit+ms %s (completed in %d, after the exit %d)"
|
||||
% (arm, len(r), trio([x.get("rs_first_poll_ms") for x in r]), trio([x.get("rs_first_sync_ms") for x in r]), q([x.get("rs_collections_n") for x in r], .5),
|
||||
max((x.get("rs_collections_n") or 0 for x in r), default=None), q([x.get("rs_lines") for x in r], .5), q([x.get("rs_lines_after_close") for x in r], .5),
|
||||
len(busy), len(r), kinds, trio([x.get("rs_busy_lasts_ms") for x in busy]), sum(1 for x in busy if x.get("rs_busy_never_ended")),
|
||||
trio([x.get("rs_idb_done_q_ms") for x in r]), sum(1 for x in r if x.get("rs_idb_done_q_ms") is not None), sum(1 for x in r if x.get("rs_idb_done_after_exit"))))
|
||||
ids = {}
|
||||
for x in r:
|
||||
for kind in ("syncs", "dumps"):
|
||||
for k in x["rs_busy_at_close"][kind]:
|
||||
ids[(kind, k)] = ids.get((kind, k), 0) + 1
|
||||
print("HUNTRSBUSY %-12s in progress at the close (closes): %s | collections synced (first browser): %s"
|
||||
% (arm, sorted(ids.items(), key=lambda kv: -kv[1])[:12], (r[0].get("rs_collections") or [])[:25]))
|
||||
# WHICH write is in progress at the close, by kind and collection, and how long before the close it had started.
|
||||
wr = {}
|
||||
for x in r:
|
||||
for w in x.get("rs_writes_at_close") or []:
|
||||
wr.setdefault((w["kind"], w["id"]), []).append(w["started_ms_before_close"])
|
||||
print("HUNTRSWRITE %-12s writes in progress at the close: %d of %d closes had one | %s"
|
||||
% (arm, sum(1 for x in r if x.get("rs_writes_at_close")), len(r),
|
||||
"; ".join("%s %s in %d closes, started before the close p50 %s max %s ms" % (k, i, len(v), q(v, .5), max(v)) for (k, i), v in sorted(wr.items(), key=lambda kv: -len(kv[1]))[:14])))
|
||||
# The two paths of the first sync (ms of session age), the push HELLO, the last write's end against the close, and the OS idle
|
||||
# of the session (GetLastInputInfo: the idle service reads the same clock; its own "idle" notification is not observable here).
|
||||
print("HUNTRSPATHS %-12s path A (update timer, trigger=timer) first start %s | path B (idle tasks -> init -> push -> trigger=startup) first start %s | Initialize Remote Settings at %s | push notification at %s | other triggers %s | last write/poll end against the close ms %s | OS idle at launch p50 %s, at close p50 %s ms"
|
||||
% (arm, trio([x.get("rs_path_A_ms") for x in r]), trio([x.get("rs_path_B_ms") for x in r]), trio([x.get("rs_init_ms") for x in r]), trio([x.get("rs_push_ms") for x in r]),
|
||||
sorted({k for x in r for k in (x.get("rs_trigger_first_ms") or {}) if k not in ("timer", "startup")}), trio([x.get("rs_last_write_end_vs_close_ms") for x in r]),
|
||||
q([x.get("os_idle_ms_at_launch") for x in r], .5), q([x.get("os_idle_ms_at_close") for x in r], .5)))
|
||||
for x in r:
|
||||
print("HUNTRSBROWSER %-12s %s %s | A %s B %s init %s push %s first sync %s ms | collections %s | writes at close %s | last end vs close %s ms | finish-IDB at quit+%s ms | parent exit %s ms"
|
||||
% (arm, x.get("round"), x.get("tag"), x.get("rs_path_A_ms"), x.get("rs_path_B_ms"), x.get("rs_init_ms"), x.get("rs_push_ms"), x.get("rs_first_sync_ms"),
|
||||
x.get("rs_collections_n"), [(w["kind"], w["id"], w["started_ms_before_close"], w["ends_ms_after_close"]) for w in x.get("rs_writes_at_close") or []][:4],
|
||||
x.get("rs_last_write_end_vs_close_ms"), x.get("rs_idb_done_q_ms"), x.get("nc_parent", x.get("close_main_ms"))))
|
||||
# The gaps between the phases of the shutdown (finish of one -> start of the next), ms, over every close.
|
||||
for arm in ("ncshut75x4", "ncshut150x4", "retail4late", "retail4x150"):
|
||||
r = [x for x in rows.get(arm, []) if "crash" not in x and x.get("phases")]
|
||||
if not r:
|
||||
continue
|
||||
gaps = {}
|
||||
for x in r:
|
||||
seq = sorted(((v[0], v[1], k) for k, v in x["phases"].items() if v[0] is not None), key=lambda t: t[0])
|
||||
for (s0, f0, k0), (s1, f1, k1) in zip(seq, seq[1:]):
|
||||
if f0 is not None:
|
||||
gaps.setdefault((k0, k1), []).append(round(s1 - f0, 1))
|
||||
print("HUNTPHASEGAP %-12s phase finish -> next phase start, ms p50/max (closes): %s"
|
||||
% (arm, " | ".join("%s->%s %s/%s (%d)" % (a, b, q(v, .5), max(v), len(v)) for (a, b), v in sorted(gaps.items(), key=lambda kv: -(q(kv[1], .5) or 0))[:10])))
|
||||
for arm in ("ncshut75x4", "ncshut150x4", "retail4late", "retail4x150"):
|
||||
r = [x for x in rows.get(arm, []) if "crash" not in x]
|
||||
if not r:
|
||||
continue
|
||||
def pe(x):
|
||||
return x.get("nc_parent") if x.get("nc_parent") is not None else x.get("close_main_ms")
|
||||
slow = [x for x in r if (pe(x) or 0) > 4900]
|
||||
fast = [x for x in r if pe(x) is not None and pe(x) <= 4900]
|
||||
types = {}
|
||||
for x in r:
|
||||
for k, v in (x.get("tree_types") or {}).items():
|
||||
types.setdefault(k, []).append(v)
|
||||
print("HUNTNCSHUT %-11s closes %d | parent exit after the close ms %s | over 4.9 s: %d of %d | (a) close->quit ms %s | (b) quit->parent exit ms %s | (c) parent exit->tree gone ms %s | contexts p50 %s pages p50 %s | tree at the close, p50 per type %s | processes p50 %s"
|
||||
% (arm, len(r), trio([pe(x) for x in r]), len(slow), len(r), trio([x.get("a_close_to_quit_ms") for x in r]), trio([x.get("b_quit_to_main_gone_ms") for x in r]),
|
||||
trio([x.get("c_main_to_tree_gone_ms") for x in r]), q([x.get("ncontexts") for x in r], .5), q([x.get("npages") for x in r], .5),
|
||||
{k: q(v, .5) for k, v in sorted(types.items())}, q([x.get("tree_procs") for x in r], .5)))
|
||||
print("HUNTTREECPU %-11s CPU s of the tree: close->parent exit, all %s | slow closes %s | fast closes %s || close->tree gone, all %s | slow %s | fast %s"
|
||||
% (arm, trio([x.get("tree_cpu_to_parent_exit_s") for x in r]), trio([x.get("tree_cpu_to_parent_exit_s") for x in slow]),
|
||||
trio([x.get("tree_cpu_to_parent_exit_s") for x in fast]), trio([x.get("tree_cpu_to_tree_gone_s") for x in r]),
|
||||
trio([x.get("tree_cpu_to_tree_gone_s") for x in slow]), trio([x.get("tree_cpu_to_tree_gone_s") for x in fast])))
|
||||
# The exit codes of the parents (the engine and a launcher stub, when the core spawns one): the core's own process object, and psutil's wait on
|
||||
# each process classified parent (readable on Windows for any process).
|
||||
for arm in ("ncshut75x4",):
|
||||
r = [x for x in rows.get(arm, []) if "crash" not in x]
|
||||
if r:
|
||||
pe_rc = [(pid, v.get("rc")) for x in r for pid, v in (x.get("parent_exits") or {}).items()]
|
||||
print("HUNTPARENTEXIT %-11s closes %d | the core's process returncode %s | parents per close %s | psutil exit codes of the parents %s | parent exit after the close ms (psutil wait) p50 %s max %s"
|
||||
% (arm, len(r), cnt(x.get("core_process_returncode") for x in r), cnt(len(x.get("parent_exits") or {}) for x in r), cnt(rc for _p, rc in pe_rc),
|
||||
q([v.get("after_snapshot_ms") for x in r for v in (x.get("parent_exits") or {}).values()], .5),
|
||||
max((v.get("after_snapshot_ms") or 0 for x in r for v in (x.get("parent_exits") or {}).values()), default=None)))
|
||||
# The interpreter's exit after a raise before close() (venvs "after" = published 64.73.0 and "next" = core main + reaper).
|
||||
for arm in ("exitprobe_after", "exitprobe_next"):
|
||||
r = [x for x in rows.get(arm, []) if "crash" not in x]
|
||||
if rows.get(arm):
|
||||
print("HUNTEXITPROBE %-15s runs %d | raised %d | timed out %d | exit after the raise ms %s | return codes %s | firefox processes left at the exit p50 %s max %s | +1 s p50 %s max %s | +10 s p50 %s max %s, kinds at +10 s %s"
|
||||
% (arm, len(r), sum(1 for x in r if x.get("raised")), sum(1 for x in r if x.get("timed_out")), trio([x.get("exit_after_raise_ms") for x in r]),
|
||||
sorted({str(x.get("returncode")) for x in r}), q([x.get("firefox_left_after_exit") for x in r], .5), max((x.get("firefox_left_after_exit") or 0 for x in r), default=None),
|
||||
q([x.get("ff_left_1s") for x in r], .5), max((x.get("ff_left_1s") or 0 for x in r), default=None), q([x.get("ff_left_10s") for x in r], .5),
|
||||
max((x.get("ff_left_10s") or 0 for x in r), default=None), sorted({k for x in r for k in x.get("ff_left_kinds_10s") or []})))
|
||||
# ---- The shutdown hunt. Two numbers per close: (a) the close -> the quit (the first "Starting phase" line of the engine's
|
||||
# AsyncShutdown log after the close started: Services.startup.quit has run), (b) the quit -> the main process gone (and the
|
||||
# whole tree gone). Then the phases and the blockers by name, with their time against the quit (the time held in (b)).
|
||||
SH = ("shut20", "shut70", "shut180", "retail1", "retail4late", "retail1long", "ncshut75x4", "ncshut150x4", "retail4x150")
|
||||
probes, shut, bgt = {}, {}, {}
|
||||
for line in open(sys.argv[1], encoding="utf-8"):
|
||||
m = re.match(r"HUNTPROBE \[(\w+)\] (.*)", line.strip())
|
||||
if m:
|
||||
d = json.loads(m.group(2))
|
||||
probes.setdefault((m.group(1), d["name"]), []).append(d["ms"])
|
||||
continue
|
||||
m = re.match(r"HUNTBGTASK \[(\w+)\] (.*)", line.strip())
|
||||
if m:
|
||||
bgt.setdefault(m.group(1), []).append(json.loads(m.group(2)))
|
||||
continue
|
||||
m = re.match(r"HUNTSHUT \[(\w+)\] (.*)", line.strip())
|
||||
if m:
|
||||
d = json.loads(m.group(2))
|
||||
shut.setdefault(m.group(1), {}).setdefault((d["round"], d["tag"]), []).append((d["t_ms"], d.get("q_ms"), d["line"]))
|
||||
def pmx(arm, name):
|
||||
v = probes.get((arm, name), [])
|
||||
return "%s/%s" % (q(v, .5), max(v) if v else None)
|
||||
for arm in SH:
|
||||
if not rows.get(arm):
|
||||
continue
|
||||
r = [x for x in rows[arm] if "crash" not in x]
|
||||
print("HUNTSHUTCLOSE %-11s closes %d crashes %d | session s at close p50 %s | close ms %s | (a) close->quit ms %s | (b) quit->main gone ms %s | (b) quit->tree gone ms %s | (c) real parent gone->tree gone ms %s | close->real parent gone p50 %s | quit not seen %d | Connection.close p50/max %s | EngineTree.end %s | EngineTree.wait_job_empty %s | SessionFiles.remove %s"
|
||||
% (arm, len(r), len(rows[arm]) - len(r), q([x.get("session_s_at_close", x.get("session_s")) for x in r], .5), trio([x.get("close_ms") for x in r]),
|
||||
trio([x.get("a_close_to_quit_ms") for x in r]), trio([x.get("b_quit_to_main_gone_ms") for x in r]), trio([x.get("b_quit_to_tree_gone_ms") for x in r]),
|
||||
trio([x.get("c_main_to_tree_gone_ms") for x in r]), q([x.get("close_to_main_gone_ms") for x in r], .5), sum(1 for x in r if x.get("a_close_to_quit_ms") is None),
|
||||
pmx(arm, "Connection.close"), pmx(arm, "EngineTree.end"), pmx(arm, "EngineTree.wait_job_empty"), pmx(arm, "SessionFiles.remove")))
|
||||
# The background tasks (firefox --backgroundtask ..., the shutdown-ping sender): per close how many, when born against the close
|
||||
# start, how long they lived and how they ended.
|
||||
for arm in SH:
|
||||
r = [x for x in rows.get(arm, []) if "crash" not in x]
|
||||
if not r:
|
||||
continue
|
||||
ts = bgt.get(arm, [])
|
||||
per = {}
|
||||
for t in ts:
|
||||
per[(t["round"], t["tag"])] = per.get((t["round"], t["tag"]), 0) + 1
|
||||
counts = [per.get((x.get("round"), x.get("tag")), 0) for x in r]
|
||||
ended = {}
|
||||
for t in ts:
|
||||
k = re.sub(r"rc=-?\d+", "rc=N", t["ended_by"])
|
||||
ended[k] = ended.get(k, 0) + 1
|
||||
print("HUNTBGSUM %-11s closes %d | tasks %d, per close p50 %s max %s, closes with none %d | born ms against the close p50 %s p95 %s | life ms p50 %s p95 %s max %s | ended by: %s | ended inside the core's cleanup %d | attributed by ancestry %d, assumed %d | parent pids %s | cmd %s"
|
||||
% (arm, len(r), len(ts), q(counts, .5), max(counts, default=None), sum(1 for c in counts if c == 0), q([t["born_ms"] for t in ts], .5), q([t["born_ms"] for t in ts], .95),
|
||||
q([t["life_ms"] for t in ts], .5), q([t["life_ms"] for t in ts], .95), max((t["life_ms"] for t in ts if t["life_ms"] is not None), default=None),
|
||||
ended, sum(1 for t in ts if t.get("ended_in")), sum(1 for t in ts if t["attrib"] != "assumed"), sum(1 for t in ts if t["attrib"] == "assumed"),
|
||||
sorted({str(x.get("parent_pids") or x.get("parent_pid")) for x in r})[:3], [" ".join(t["cmd"][1:4])[:70] for t in ts[:1]]))
|
||||
phase_re = re.compile(r"(Starting|Finished) phase (\S+)")
|
||||
add_re = re.compile(r"Adding blocker (.+) for phase (\S+)")
|
||||
done_re = re.compile(r"Completed blocker (.+) for phase (\S+)")
|
||||
for arm in SH:
|
||||
closes = shut.get(arm, {})
|
||||
if not closes:
|
||||
continue
|
||||
ph, bl = {}, {}
|
||||
for key, ls in closes.items():
|
||||
for t_ms, qv, text in ls:
|
||||
m = phase_re.search(text)
|
||||
if m and qv is not None and t_ms >= 0:
|
||||
ph.setdefault(m.group(2), {"Starting": [], "Finished": []})[m.group(1)].append(qv)
|
||||
continue
|
||||
m = add_re.search(text)
|
||||
if m:
|
||||
bl.setdefault((m.group(2), m.group(1)), {"add": set(), "done": {}})["add"].add(key)
|
||||
continue
|
||||
m = done_re.search(text)
|
||||
if m and qv is not None:
|
||||
bl.setdefault((m.group(2), m.group(1)), {"add": set(), "done": {}})["done"][key] = qv
|
||||
for phase, v in sorted(ph.items(), key=lambda kv: q(kv[1]["Starting"], .5) if kv[1]["Starting"] else 1e12):
|
||||
print("HUNTPHASE %-11s %-34s closes %d | starts at quit+ms p50 %s max %s | finished at quit+ms p50 %s p95 %s max %s (finished in %d)"
|
||||
% (arm, phase, len(v["Starting"]), q(v["Starting"], .5), max(v["Starting"], default=None), q(v["Finished"], .5), q(v["Finished"], .95),
|
||||
max(v["Finished"], default=None), len(v["Finished"])))
|
||||
ranked = sorted(bl.items(), key=lambda kv: -(max(kv[1]["done"].values()) if kv[1]["done"] else 1e12))[:40]
|
||||
for (phase, name), v in ranked:
|
||||
done = list(v["done"].values())
|
||||
print("HUNTBLOCKER %-11s %-30s %-40s added in %d of %d closes, completed in %d, never completed in %d | completed at quit+ms (held in b) p50 %s p95 %s max %s"
|
||||
% (arm, phase, name[:40], len(v["add"]), len(closes), len(done), len(v["add"] - set(v["done"])), q(done, .5), q(done, .95), max(done, default=None)))
|
||||
# The lines of the close with the longest (b), in order: the raw story.
|
||||
slow = sorted((x for x in rows[arm] if "crash" not in x), key=lambda x: -(x.get("b_quit_to_main_gone_ms") or x.get("close_ms") or 0))[:1]
|
||||
for x in slow:
|
||||
for t_ms, qv, text in closes.get((x["round"], x["tag"]), [])[:150]:
|
||||
print("HUNTSHUTRAW %-11s %s %s | close%+.0f ms quit%+.0f ms | %s" % (arm, x["round"], x["tag"], t_ms, qv if qv is not None else float("nan"), text[:140]))
|
||||
PY
|
||||
python - "$RUNNER_TEMP/rows.log" <<'PY2'
|
||||
import json, re, sys
|
||||
probes = {}
|
||||
for line in open(sys.argv[1], encoding="utf-8"):
|
||||
m = re.match(r"HUNTPROBE \[(\w+)\] (.*)", line.strip())
|
||||
if m:
|
||||
d = json.loads(m.group(2)); probes.setdefault((m.group(1), d["name"]), []).append(d)
|
||||
def q(v, p):
|
||||
v = sorted(v); return v[min(len(v) - 1, int(p * len(v)))] if v else None
|
||||
for (arm, name), ds in sorted(probes.items()):
|
||||
ms = [d["ms"] for d in ds]
|
||||
line = "HUNTPROBESUM %-12s %-34s n %3d | ms p50 %s p95 %s max %s" % (arm, name, len(ds), q(ms, .5), q(ms, .95), max(ms))
|
||||
if name == "geo._family_lock":
|
||||
w = [d["extra"]["waited_ms"] for d in ds]
|
||||
line += " | held by: %s | waited p50 %s p95 %s max %s" % (sorted({d["thread"] for d in ds})[:4], q(w, .5), q(w, .95), max(w))
|
||||
print(line)
|
||||
PY2
|
||||
grep -h "HUNTSURVIVOR" "$RUNNER_TEMP/rows.log" | sed -E 's/"pid": [0-9]+, //' | sort -u | head -20 || true
|
||||
grep -h "HUNTSLOW\b" "$RUNNER_TEMP/rows.log" | cut -c1-900 || true
|
||||
grep -h "HUNTSLOWCLOSE" "$RUNNER_TEMP/rows.log" | cut -c1-1100 | head -40 || true
|
||||
grep -h "HUNTALIVE" "$RUNNER_TEMP/rows.log" | cut -c1-500 | head -80 || true
|
||||
grep -h "HUNTPARENTS" "$RUNNER_TEMP/rows.log" | cut -c1-1500 | head -12 || true
|
||||
grep -h "HUNTCLOSEARGS" "$RUNNER_TEMP/rows.log" | sed -E 's/^HUNTCLOSEARGS \[[a-z0-9]+\] //; s/"conn": [0-9]+, //; s/"(round|arm)": "?[a-z0-9]*"?, //g' | cut -c1-300 | sort | uniq -c | sort -rn | head -20 || true
|
||||
# The geo helpers of the first launch of the first round (the first arm, inproc4, all four browsers): what prepare_session_geo
|
||||
# spent its time on (t = seconds from the start of that process, ms = how long, thread).
|
||||
grep -hE "HUNTPROBE \[inproc4\] .*\"round\": \"r0\".*\"name\": \"(geo\.|download\.|geoip_db\.|_geoip_db\.|udp_exit\.|requests\.)" "$RUNNER_TEMP/rows.log" | cut -c1-260 | head -150 || true
|
||||
- name: Close every Firefox left
|
||||
if: always()
|
||||
run: |
|
||||
if [ "$RUNNER_OS" = "Windows" ]; then taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true; else pkill -9 -f firefox > /dev/null 2>&1 || true; fi
|
||||
echo done
|
||||
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
if: always()
|
||||
with: { name: "published-latency-${{ matrix.os }}-${{ matrix.part }}-${{ github.run_id }}", path: "${{ runner.temp }}/rows.log" }
|
||||
@@ -0,0 +1,611 @@
|
||||
"""HUNT ONLY, never merged. The driver of the three candidate hunts (mouse 1b, the close of 4 browsers together, IndexedDB at quit).
|
||||
|
||||
It runs `hunt_published_latency.py` (imported, never edited, so the workflow that watches that file does not start) with the
|
||||
probes of these hunts put around it. Nothing here is inside a test and nothing changes what the product does: every wrapper calls
|
||||
the real function and only records.
|
||||
|
||||
python hunt_candidate.py ARM N_BROWSERS ROUND [binary] (the arguments of hunt_published_latency.py)
|
||||
python hunt_candidate.py retail N ROUND FIREFOX_BINARY [close_after_s]
|
||||
|
||||
Switches (environment):
|
||||
HUNT_CAND_MOUSE=1 the mouse the page saw against the plan the client sent (round 1, criterion 1b). The plan is every
|
||||
Page.dispatchMouseEvent the core's client sends, with its `stroke` and `at`, recorded at the three places a mouse
|
||||
event leaves: `Stroke.send` (a path, a click: each carries `stroke` and `at`), `Actions._mouse_event` outside a
|
||||
stroke (an explicit move, press or release: no stroke, no `at`), and `Actions.walk` (the planned instants handed
|
||||
to the pacer, and how many were delivered); and the pause `Actions._settle_before_press` draws and sleeps.
|
||||
The page's side is what hunt_published_latency.py already records: every mousemove, mousedown, mouseup with
|
||||
event.timeStamp (and the handler's clock). The two are joined by the identity of the browser's core connection.
|
||||
HUNT_CAND_CLOSE=1 the close of the core as it is (round 2): the steps stamped as before, NOTHING raised (no deadline of the hunt:
|
||||
`Connection.close` gets what the caller gave, the reaper what it was built with), what the core ended
|
||||
(terminate / kill / job end), and the exit code and the exit instant of every process of each browser's tree.
|
||||
HUNT_CAND_IDB=1 (round 3) MOZ_LOG=IndexedDB:5,sync,timestamp and MOZ_LOG_FILE=<dir>/ff-%PID.log for ours and for retail, the
|
||||
census of every process of each browser at its close (command line, process type, birth).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
import hunt_published_latency as H # noqa: E402 (the scripts directory is first on the path when this file is run)
|
||||
|
||||
import psutil # noqa: E402
|
||||
|
||||
_TL = threading.local()
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------------------------------------
|
||||
# Round 1: the plan the client sent
|
||||
# ---------------------------------------------------------------------------------------------------------------------------------
|
||||
#: One dict per Page.dispatchMouseEvent: conn (id of the core connection), sid / p_stroke / p_at (what went on the wire), at, before,
|
||||
#: after (client wall ms: before the command left, after send_async returned), type, x, y, via ("stroke" | "single").
|
||||
M_PLAN = []
|
||||
#: One dict per Actions.walk: conn, start, end (wall ms), planned (events handed in), delivered (returned), t_ms (their instants).
|
||||
M_WALKS = []
|
||||
#: One dict per press settle: conn, start, end (wall ms), pause_ms (what plan_press_settle drew).
|
||||
M_SETTLES = []
|
||||
|
||||
|
||||
def install_mouse_probe():
|
||||
from invisible_core.juggler import _behaviour, _stroke, actions
|
||||
real_send = _stroke.Stroke.send
|
||||
if not getattr(real_send, "_m1b", False):
|
||||
def send(self, method, params, at_ms, *a, **k):
|
||||
if method != "Page.dispatchMouseEvent":
|
||||
return real_send(self, method, params, at_ms, *a, **k)
|
||||
if not k.get("paced"):
|
||||
self.hold_until(at_ms) # the wait for its instant, so `before` is the instant the command leaves
|
||||
before = time.time() * 1000
|
||||
try:
|
||||
return real_send(self, method, params, at_ms, *a, **k)
|
||||
finally:
|
||||
M_PLAN.append({"conn": id(self._c), "sid": self.id, "type": params.get("type"), "x": params.get("x"), "y": params.get("y"),
|
||||
"at": float(at_ms or 0.0), "p_stroke": params.get("stroke"), "p_at": params.get("at"),
|
||||
"buttons": params.get("buttons"), "click": params.get("clickCount"),
|
||||
"before": before, "after": time.time() * 1000, "via": "stroke"})
|
||||
send._m1b = True
|
||||
_stroke.Stroke.send = send
|
||||
real_event = actions.Actions._mouse_event
|
||||
if not getattr(real_event, "_m1b", False):
|
||||
def _mouse_event(self, event_type, point, *a, **k):
|
||||
if self._stroke is not None:
|
||||
return real_event(self, event_type, point, *a, **k) # leaves through Stroke.send: recorded there
|
||||
before = time.time() * 1000
|
||||
try:
|
||||
return real_event(self, event_type, point, *a, **k)
|
||||
finally:
|
||||
M_PLAN.append({"conn": id(self.c), "sid": None, "type": event_type, "x": point[0], "y": point[1], "at": None,
|
||||
"p_stroke": None, "p_at": None, "buttons": k.get("buttons"), "click": k.get("click_count"),
|
||||
"before": before, "after": time.time() * 1000, "via": "single"})
|
||||
_mouse_event._m1b = True
|
||||
actions.Actions._mouse_event = _mouse_event
|
||||
real_walk = actions.Actions.walk
|
||||
if not getattr(real_walk, "_m1b", False):
|
||||
def walk(self, events, *a, **k):
|
||||
evs = list(events)
|
||||
start, delivered = time.time() * 1000, None
|
||||
try:
|
||||
delivered = real_walk(self, evs, *a, **k)
|
||||
return delivered
|
||||
finally:
|
||||
M_WALKS.append({"conn": id(self.c), "start": start, "end": time.time() * 1000, "planned": len(evs), "delivered": delivered,
|
||||
"t_ms": [round(float(getattr(e, "t_ms", 0.0)), 1) for e in evs[:400]]})
|
||||
walk._m1b = True
|
||||
actions.Actions.walk = walk
|
||||
real_plan = _behaviour.plan_press_settle
|
||||
if not getattr(real_plan, "_m1b", False):
|
||||
def plan_press_settle(*a, **k):
|
||||
v = real_plan(*a, **k)
|
||||
_TL.pause = v
|
||||
return v
|
||||
plan_press_settle._m1b = True
|
||||
_behaviour.plan_press_settle = plan_press_settle
|
||||
real_settle = actions.Actions._settle_before_press
|
||||
if not getattr(real_settle, "_m1b", False):
|
||||
def _settle_before_press(self):
|
||||
_TL.pause = None
|
||||
start = time.time() * 1000
|
||||
try:
|
||||
return real_settle(self)
|
||||
finally:
|
||||
M_SETTLES.append({"conn": id(self.c), "start": start, "end": time.time() * 1000, "pause_ms": getattr(_TL, "pause", None)})
|
||||
_settle_before_press._m1b = True
|
||||
actions.Actions._settle_before_press = _settle_before_press
|
||||
|
||||
|
||||
def _instants(plan):
|
||||
"""The planned wall instant of each event: its stroke's start on the client's clock plus its `at`. A stroke's start is the smallest
|
||||
`before - at` of its events (an event that left on time gives it exactly, a late one only an upper bound); an event outside a stroke
|
||||
has no `at`, it is planned when it is sent."""
|
||||
t0 = {}
|
||||
for e in plan:
|
||||
if e["sid"] is not None and e["at"] is not None:
|
||||
d = e["before"] - e["at"]
|
||||
t0[e["sid"]] = min(t0.get(e["sid"], d), d)
|
||||
return [(t0[e["sid"]] + e["at"]) if e["sid"] is not None and e["at"] is not None else e["before"] for e in plan]
|
||||
|
||||
|
||||
def match_moves(pages, moves):
|
||||
"""Join each page mousemove to the plan move it is. `pages` = [(page clock, clientX, clientY)], `moves` = [(planned instant, event)].
|
||||
By COORDINATES when the page reported them (the hunt's page does): in order, each page move to the plan move of the forward window
|
||||
that is nearest in space (within 3 px), ties inside a pixel to the one nearest in time after the clock shift; this does not let a
|
||||
late event pass for an on-time one, which a join by nearest time does (a move delayed by 90 ms is nearest to the plan point 90 ms
|
||||
later). Without coordinates, or when fewer than 80% join: by nearest time. Returns (the page clock's shift onto the plan's, the
|
||||
plan index of each page move or None, how)."""
|
||||
import bisect
|
||||
import math
|
||||
pm = [t for t, _e in moves]
|
||||
times = [t for t, _x, _y in pages]
|
||||
sh = H._align(times, pm)
|
||||
|
||||
def by_time(shift):
|
||||
out = []
|
||||
for t in times:
|
||||
x = t - shift
|
||||
k = bisect.bisect_left(pm, x)
|
||||
out.append(min((j for j in (k - 1, k) if 0 <= j < len(pm)), key=lambda j: abs(x - pm[j])))
|
||||
return out
|
||||
def place(shift):
|
||||
js, j0 = [], 0
|
||||
for t, x, y in pages:
|
||||
win = range(j0, min(len(pm), j0 + 60))
|
||||
dist = {j: math.hypot(x - moves[j][1]["x"], y - moves[j][1]["y"]) for j in win}
|
||||
if not dist or min(dist.values()) > 3.0:
|
||||
js.append(None)
|
||||
continue
|
||||
best = min(dist.values())
|
||||
j = min((j for j in win if dist[j] <= best + 0.75), key=lambda j: abs((t - shift) - pm[j]))
|
||||
js.append(j)
|
||||
j0 = j + 1
|
||||
return js
|
||||
|
||||
def offsets(js):
|
||||
return [t - pm[j] for t, j in zip(times, js) if j is not None]
|
||||
if all(x is not None and y is not None for _t, x, y in pages):
|
||||
js = place(sh)
|
||||
ok = offsets(js)
|
||||
if len(ok) >= 0.8 * len(pages):
|
||||
sh2 = sorted(ok)[len(ok) // 2]
|
||||
js2 = place(sh2)
|
||||
if len(offsets(js2)) >= 0.8 * len(pages):
|
||||
return sh2, js2, "xy"
|
||||
return sh, by_time(sh), "time"
|
||||
|
||||
|
||||
def m1b_analyse(ev, plan, settles, i, prefix):
|
||||
"""The page's mousemove / mousedown / mouseup (`ev`: [type, timeStamp clock, handler clock], `i` picks the clock) against the plan
|
||||
the client sent (`plan`: its mouse events in the order sent, `settles`: the presses' settle pauses).
|
||||
|
||||
The page does not see every plan point (the frame coalesces mousemoves), and its clock is not the client's: each page move is
|
||||
joined to the plan move it is (by its coordinates, `match_moves`) and the page's clock is shifted onto the plan's by the median
|
||||
offset of those joins. Then, over the path up to the first press:
|
||||
a pauses page gap between two consecutive page moves minus the planned gap between their plan points: over 50 ms (and 100);
|
||||
b bursts two consecutive page moves less than 2 ms apart whose plan points are 8 ms or more apart;
|
||||
c settle last move -> mousedown: the pause the core drew (plan_press_settle) and slept, the client's own interval (last move
|
||||
sent -> press sent), the page's interval (last page move -> mousedown, and from the page move joined to the last
|
||||
plan move when the page saw it)."""
|
||||
out = {}
|
||||
inst = _instants(plan)
|
||||
moves = sorted(((t, e) for t, e in zip(inst, plan) if e["type"] == "mousemove"), key=lambda r: r[0])
|
||||
downs = sorted(((t, e) for t, e in zip(inst, plan) if e["type"] == "mousedown"), key=lambda r: r[0])
|
||||
ups = sorted(((t, e) for t, e in zip(inst, plan) if e["type"] == "mouseup"), key=lambda r: r[0])
|
||||
pm = [t for t, _e in moves]
|
||||
if downs:
|
||||
keep = [(t, e) for t, e in moves if t <= downs[0][0] + 1]
|
||||
moves, pm = keep, [t for t, _e in keep]
|
||||
pdown = sorted(x[i] for x in ev if x[0] == "mousedown")
|
||||
pup = sorted(x[i] for x in ev if x[0] == "mouseup")
|
||||
first_down = pdown[0] if pdown else None
|
||||
pages = sorted(((x[i], x[3] if len(x) > 4 else None, x[4] if len(x) > 4 else None) for x in ev
|
||||
if x[0] == "mousemove" and (first_down is None or x[i] <= first_down)), key=lambda r: r[0])
|
||||
out[prefix + "plan_moves"] = len(pm)
|
||||
out[prefix + "page_moves"] = len(pages)
|
||||
if len(pages) < 3 or len(pm) < 3:
|
||||
out[prefix + "note"] = "too few: page %d, plan %d" % (len(pages), len(pm))
|
||||
return out
|
||||
sh, js, how = match_moves(pages, moves)
|
||||
out[prefix + "match"] = how
|
||||
out[prefix + "unmatched"] = sum(1 for j in js if j is None)
|
||||
page = [t for (t, _x, _y), j in zip(pages, js) if j is not None]
|
||||
js = [j for j in js if j is not None]
|
||||
if len(page) < 3:
|
||||
out[prefix + "note"] = "too few matched: page %d of %d" % (len(page), len(pages))
|
||||
return out
|
||||
pg = [b - a for a, b in zip(page, page[1:])]
|
||||
plg = [pm[js[k + 1]] - pm[js[k]] for k in range(len(pg))]
|
||||
excess = [a - b for a, b in zip(pg, plg)]
|
||||
order = sorted(range(len(pg)), key=lambda k: -excess[k])[:3]
|
||||
out[prefix + "shift_ms"] = round(sh, 1)
|
||||
out[prefix + "pairs"] = len(pg)
|
||||
out[prefix + "pauses50"] = sum(1 for e in excess if e > 50)
|
||||
out[prefix + "pauses100"] = sum(1 for e in excess if e > 100)
|
||||
out[prefix + "pause_max"] = round(max(excess), 1)
|
||||
out[prefix + "pause_worst"] = [[round(pg[k], 1), round(plg[k], 1), k] for k in order]
|
||||
out[prefix + "pairs8"] = sum(1 for b in plg if b >= 8)
|
||||
out[prefix + "bursts"] = sum(1 for a, b in zip(pg, plg) if a < 2 and b >= 8)
|
||||
out[prefix + "burst_examples"] = [[round(a, 2), round(b, 1), k] for k, (a, b) in enumerate(zip(pg, plg)) if a < 2 and b >= 8][:4]
|
||||
out[prefix + "plan_pairs8"] = sum(1 for a, b in zip(pm, pm[1:]) if b - a >= 8)
|
||||
out[prefix + "plan_max_gap"] = round(max(b - a for a, b in zip(pm, pm[1:])), 1)
|
||||
if first_down is not None and downs:
|
||||
d_t, d_e = downs[0]
|
||||
last_e = moves[-1][1]
|
||||
drawn = [s for s in settles if s["end"] <= d_e["before"] + 2.0]
|
||||
s = drawn[-1] if drawn else None
|
||||
out[prefix + "settle_drawn"] = round(s["pause_ms"], 1) if s and s["pause_ms"] is not None else None
|
||||
out[prefix + "settle_slept"] = round(s["end"] - s["start"], 1) if s else None
|
||||
out[prefix + "settle_client"] = round(d_e["before"] - last_e["before"], 1)
|
||||
out[prefix + "settle_page"] = round(first_down - page[-1], 1)
|
||||
seen_last = [k for k, j in enumerate(js) if j == len(pm) - 1]
|
||||
out[prefix + "settle_page_from_last_planned"] = round(first_down - page[seen_last[-1]], 1) if seen_last else None
|
||||
out[prefix + "last_page_move_plan_moves_after"] = len(pm) - 1 - js[-1]
|
||||
out[prefix + "press_offset"] = round((first_down - sh) - d_t, 1)
|
||||
if ups and pup:
|
||||
out[prefix + "dwell_plan"] = round(ups[0][0] - d_t, 1)
|
||||
out[prefix + "dwell_page"] = round(pup[0] - first_down, 1) if pup[0] >= first_down else None
|
||||
return out
|
||||
|
||||
|
||||
ORIG_MOUSE_REPORT = H.mouse_report
|
||||
|
||||
|
||||
def mouse_report(ev, dwell_plan, settle_plan=None, conn_id=None):
|
||||
out = ORIG_MOUSE_REPORT(ev, dwell_plan, settle_plan, conn_id)
|
||||
plan = [e for e in M_PLAN if conn_id is not None and e["conn"] == conn_id]
|
||||
walks = [w for w in M_WALKS if conn_id is not None and w["conn"] == conn_id]
|
||||
settles = [s for s in M_SETTLES if conn_id is not None and s["conn"] == conn_id]
|
||||
out["m1b_pairing"] = "exact" if plan else "unpaired"
|
||||
out["m1b_plan_events"] = len(plan)
|
||||
out["m1b_plan_tagged"] = sum(1 for e in plan if e["p_stroke"] is not None)
|
||||
out["m1b_plan_single"] = sum(1 for e in plan if e["via"] == "single")
|
||||
out["m1b_walks"] = [[w["planned"], w["delivered"]] for w in walks]
|
||||
if not plan:
|
||||
return out
|
||||
for prefix, i in (("m1b_", 1), ("m1b_h_", 2)):
|
||||
out.update(m1b_analyse(ev, plan, settles, i, prefix))
|
||||
out["m1b_raw"] = {
|
||||
"plan": [[e["sid"], e["type"], e["x"], e["y"], e["p_at"], round(e["before"], 1), round(e["after"], 1), e["via"]] for e in plan],
|
||||
"page": [[x[0], round(x[1], 1), round(x[2], 1)] + list(x[3:5]) for x in ev if x[0] in ("mousemove", "mousedown", "mouseup", "click")],
|
||||
"walks": walks, "settles": settles}
|
||||
return out
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------------------------------------
|
||||
# Round 2: the close as the product does it, only stamped
|
||||
# ---------------------------------------------------------------------------------------------------------------------------------
|
||||
#: id(CloseRec) -> what the core did in this close (see x_fields); id(EngineTree) -> its CloseRec.
|
||||
X = {}
|
||||
TREE_REC = {}
|
||||
|
||||
|
||||
def _new_x():
|
||||
return {"end_calls": [], "conn_terminate": [], "wbg": []}
|
||||
|
||||
|
||||
def _describe(proc):
|
||||
"""A process the core is about to end: its pid, its type by command line, and whether it is one the browser starts to outlive
|
||||
itself (the shutdown-ping sender or its background task: `process.outlives_the_browser`, by command line). sender None = the command
|
||||
line could not be read (the process had gone)."""
|
||||
from invisible_core import process as pmod
|
||||
try:
|
||||
cmd = proc.cmdline()
|
||||
except Exception: # noqa: BLE001
|
||||
cmd = None
|
||||
if not cmd:
|
||||
return {"pid": getattr(proc, "pid", None), "kind": "?", "sender": None}
|
||||
kind = "ff:" + cmd[-1] if "-contentproc" in cmd else ("ff:backgroundtask" if pmod.outlives_the_browser(cmd) else "ff:parent")
|
||||
return {"pid": proc.pid, "kind": kind, "sender": bool(pmod.outlives_the_browser(cmd))}
|
||||
|
||||
|
||||
def install_clean_close_stamps():
|
||||
"""The steps of a close of the core, stamped, WITHOUT changing what it does. Replaces the hunt's `install_close_stamps`, whose
|
||||
wrappers raised the deadlines (`HUNT_CLOSE_TIMEOUT`: Connection.close's timeout and the Reaper's): none is raised here, and the
|
||||
hunt refuses to start with that variable set. Wrapped, each calling the real function:
|
||||
Connection.__init__ / close, the `os` of connection.py (close of the write end, the empty read), Reaper.run (the steps, as before)
|
||||
Connection.close the arguments it received and the limit it ends up with (HUNTCLOSEARGS)
|
||||
EngineTree.end / _wait / wait_browser_gone, EngineJob.terminate, the launcher's terminate / kill, psutil.Process.terminate / kill
|
||||
inside end: what the core ended, when, and which of it is a sender"""
|
||||
import importlib
|
||||
import types
|
||||
cmod = importlib.import_module("invisible_core.juggler.connection")
|
||||
pmod = importlib.import_module("invisible_core.process")
|
||||
pc = time.perf_counter
|
||||
if not getattr(cmod, "_hunt_os", False):
|
||||
proxy = types.ModuleType("os")
|
||||
proxy.__dict__.update(os.__dict__)
|
||||
real_close, real_read = os.close, os.read
|
||||
|
||||
def close(fd):
|
||||
c = H.FD_WRITE.pop(fd, None)
|
||||
if c is not None:
|
||||
r = H.CONN_REC.get(id(c))
|
||||
if r is not None and r.t_pipe is None:
|
||||
r.t_pipe = pc()
|
||||
else:
|
||||
c = H.FD_READ.pop(fd, None)
|
||||
if c is not None:
|
||||
r = H.CONN_REC.get(id(c))
|
||||
if r is not None and r.t_reader_end is None:
|
||||
r.t_reader_end = pc()
|
||||
return real_close(fd)
|
||||
|
||||
def read(fd, n):
|
||||
data = real_read(fd, n)
|
||||
if not data:
|
||||
c = H.FD_READ.get(fd)
|
||||
if c is not None:
|
||||
r = H.CONN_REC.get(id(c))
|
||||
if r is not None and r.t_eof is None:
|
||||
r.t_eof = pc()
|
||||
return data
|
||||
proxy.close, proxy.read = close, read
|
||||
cmod.os = proxy
|
||||
cmod._hunt_os = True
|
||||
real_init = cmod.Connection.__init__
|
||||
if not getattr(real_init, "_hunt_ncs", False):
|
||||
def __init__(self, *a, **k):
|
||||
to_b = k.get("to_browser", a[0] if a else None)
|
||||
from_b = k.get("from_browser", a[1] if len(a) > 1 else None)
|
||||
H.FD_WRITE[to_b], H.FD_READ[from_b] = self, self # before the reader thread starts
|
||||
H.CONNS.append(self)
|
||||
real_init(self, *a, **k)
|
||||
__init__._hunt_ncs = True
|
||||
cmod.Connection.__init__ = __init__
|
||||
real_close_m = cmod.Connection.close
|
||||
if not getattr(real_close_m, "_hunt_ncs", False):
|
||||
def close_m(self, *a, **k):
|
||||
rec = H.CONN_REC.get(id(self))
|
||||
mine = rec is not None and rec.t_entry is None
|
||||
if mine:
|
||||
rec.t_entry = pc()
|
||||
X.setdefault(id(rec), _new_x())
|
||||
tree = getattr(getattr(self, "_process", None), "tree", None)
|
||||
if tree is not None:
|
||||
TREE_REC[id(tree)] = rec
|
||||
_TL.rec = rec
|
||||
effective = a[0] if a else k.get("timeout")
|
||||
print("HUNTCLOSEARGS " + json.dumps({**H.ARM_CTX, "what": "Connection.close", "conn": id(self) % 100000, "mine": mine,
|
||||
"asked": [list(a), dict(k)], "effective_timeout": effective,
|
||||
"limit_when_none": getattr(pmod, "BROWSER_EXIT_LIMIT", None)}), flush=True)
|
||||
try:
|
||||
return real_close_m(self, *a, **k)
|
||||
finally:
|
||||
if mine:
|
||||
rec.t_conn_return = pc()
|
||||
_TL.rec = None
|
||||
close_m._hunt_ncs = True
|
||||
cmod.Connection.close = close_m
|
||||
real_run = pmod.Reaper.run
|
||||
if not getattr(real_run, "_hunt_ncs", False):
|
||||
def run(self):
|
||||
try:
|
||||
return real_run(self)
|
||||
finally:
|
||||
self.t_done = pc()
|
||||
run._hunt_ncs = True
|
||||
pmod.Reaper.run = run
|
||||
real_rinit = pmod.Reaper.__init__
|
||||
if not getattr(real_rinit, "_hunt_ncs", False):
|
||||
def r_init(self, *a, **k):
|
||||
real_rinit(self, *a, **k)
|
||||
print("HUNTCLOSEARGS " + json.dumps({**H.ARM_CTX, "what": "Reaper.__init__", "grace": self.grace, "timeout": self.timeout}), flush=True)
|
||||
r_init._hunt_ncs = True
|
||||
pmod.Reaper.__init__ = r_init
|
||||
real_end = pmod.EngineTree.end
|
||||
if not getattr(real_end, "_hunt_ncs", False):
|
||||
def end(self, *a, **k):
|
||||
ctx = {"t0": pc(), "grace": k.get("grace", a[0] if a else 0.0), "timeout": k.get("timeout", a[1] if len(a) > 1 else 5.0),
|
||||
"waits": [], "job_terminate": [], "kills": []}
|
||||
_TL.end = (self, ctx)
|
||||
try:
|
||||
ctx["sent"] = real_end(self, *a, **k)
|
||||
return ctx["sent"]
|
||||
finally:
|
||||
_TL.end = None
|
||||
ctx["t1"] = pc()
|
||||
rec = TREE_REC.get(id(self))
|
||||
if rec is not None:
|
||||
X.setdefault(id(rec), _new_x())["end_calls"].append(ctx)
|
||||
end._hunt_ncs = True
|
||||
pmod.EngineTree.end = end
|
||||
real_wait = pmod.EngineTree._wait
|
||||
if not getattr(real_wait, "_hunt_ncs", False):
|
||||
def _wait(self, procs, timeout):
|
||||
left = real_wait(self, procs, timeout)
|
||||
cur = getattr(_TL, "end", None)
|
||||
if cur is not None and cur[0] is self:
|
||||
cur[1]["waits"].append({"timeout": timeout, "in": len(procs), "t": pc(), "left": [_describe(p) for p in left]})
|
||||
return left
|
||||
_wait._hunt_ncs = True
|
||||
pmod.EngineTree._wait = _wait
|
||||
real_wbg = pmod.EngineTree.wait_browser_gone
|
||||
if not getattr(real_wbg, "_hunt_ncs", False):
|
||||
def wait_browser_gone(self, deadline):
|
||||
t = pc()
|
||||
ret = real_wbg(self, deadline)
|
||||
rec = TREE_REC.get(id(self))
|
||||
if rec is not None:
|
||||
X.setdefault(id(rec), _new_x())["wbg"].append({"ret": ret, "t0": t, "t1": pc(), "deadline_in_s": round(deadline - time.monotonic(), 2)})
|
||||
return ret
|
||||
wait_browser_gone._hunt_ncs = True
|
||||
pmod.EngineTree.wait_browser_gone = wait_browser_gone
|
||||
real_jt = pmod.EngineJob.terminate
|
||||
if not getattr(real_jt, "_hunt_ncs", False):
|
||||
def job_terminate(self):
|
||||
cur = getattr(_TL, "end", None)
|
||||
if cur is not None:
|
||||
cur[1]["job_terminate"].append(pc())
|
||||
return real_jt(self)
|
||||
job_terminate._hunt_ncs = True
|
||||
pmod.EngineJob.terminate = job_terminate
|
||||
|
||||
def wrap_proc(cls, name, what):
|
||||
real = getattr(cls, name, None)
|
||||
if real is None or getattr(real, "_hunt_ncs", False):
|
||||
return
|
||||
|
||||
def call(self, *a, **k):
|
||||
rec = getattr(_TL, "rec", None)
|
||||
cur = getattr(_TL, "end", None)
|
||||
if rec is not None:
|
||||
X.setdefault(id(rec), _new_x())["conn_terminate"].append({"what": what, "t": pc(), "pid": getattr(self, "pid", None)})
|
||||
elif cur is not None:
|
||||
cur[1]["kills"].append({"what": what, "t": pc(), "pid": getattr(self, "pid", None)})
|
||||
return real(self, *a, **k)
|
||||
call._hunt_ncs = True
|
||||
setattr(cls, name, call)
|
||||
for cls, what in ((getattr(cmod, "_WindowsProcess", None), "launcher"), (subprocess.Popen, "popen")):
|
||||
if cls is not None:
|
||||
wrap_proc(cls, "terminate", what + ".terminate")
|
||||
wrap_proc(cls, "kill", what + ".kill")
|
||||
wrap_proc(psutil.Process, "terminate", "psutil.terminate")
|
||||
wrap_proc(psutil.Process, "kill", "psutil.kill")
|
||||
real_fields = H.CloseRec.fields
|
||||
if not getattr(real_fields, "_hunt_ncs", False):
|
||||
def fields(self):
|
||||
d = real_fields(self)
|
||||
try:
|
||||
d.update(x_fields(self))
|
||||
except Exception as exc: # noqa: BLE001
|
||||
d["x_error"] = "%s: %s" % (type(exc).__name__, str(exc)[:200])
|
||||
return d
|
||||
fields._hunt_ncs = True
|
||||
H.CloseRec.fields = fields
|
||||
|
||||
|
||||
def x_fields(rec):
|
||||
"""What the core did in the close of `rec`, as row fields: the ends it made (what was left when it ended, which of it was a sender),
|
||||
the launcher's terminate, the waits for the browser's exit and their answers."""
|
||||
x = X.get(id(rec)) or _new_x()
|
||||
|
||||
def ms(t):
|
||||
return round((t - rec.t_call) * 1000, 1) if rec.t_call is not None else None
|
||||
ends, left_nonsender, left_sender, left_unknown = [], set(), set(), set()
|
||||
for c in x["end_calls"]:
|
||||
waits = []
|
||||
for w in c["waits"]:
|
||||
waits.append({"timeout": w["timeout"], "in": w["in"], "after_ms": ms(w["t"]), "left": w["left"]})
|
||||
for p in w["left"]:
|
||||
(left_sender if p["sender"] else left_nonsender if p["sender"] is False else left_unknown).add((p["pid"], p["kind"]))
|
||||
ends.append({"after_ms": ms(c["t0"]), "dur_ms": round((c["t1"] - c["t0"]) * 1000, 1), "grace": c["grace"], "timeout": c["timeout"],
|
||||
"sent": c.get("sent"), "waits": waits, "job_terminate_after_ms": [ms(t) for t in c["job_terminate"]],
|
||||
"kills": [{"what": k["what"], "pid": k["pid"], "after_ms": ms(k["t"])} for k in c["kills"]]})
|
||||
conn_term = [{"what": c["what"], "pid": c["pid"], "after_ms": ms(c["t"])} for c in x["conn_terminate"]]
|
||||
wbg = [{"ret": w["ret"], "after_ms": ms(w["t0"]), "dur_ms": round((w["t1"] - w["t0"]) * 1000, 1)} for w in x["wbg"]]
|
||||
return {"x_wall_call": round(rec.wall_call, 1) if rec.wall_call else None, "x_end_calls": ends, "x_conn_terminate": conn_term,
|
||||
"x_wait_browser_gone": wbg,
|
||||
"x_browser_ended": bool(left_nonsender or conn_term or any(w["ret"] is False for w in wbg)),
|
||||
"x_left_nonsender": sorted(left_nonsender), "x_left_sender": sorted(left_sender), "x_left_unknown": sorted(left_unknown)}
|
||||
|
||||
|
||||
class TreeWatch2(H.TreeWatch):
|
||||
"""The hunt's TreeWatch, and for every process of the tree as it was just before the close: its exit code and the instant it was
|
||||
found gone (a thread each; psutil gives the code of any process on Windows), and its census (command line, type, parent, birth)."""
|
||||
|
||||
def __init__(self, main_pid):
|
||||
self.census = []
|
||||
self.exits_all = {}
|
||||
super().__init__(main_pid)
|
||||
# The process the core spawned may be gone (a launcher that handed over): the tree is then the core's own list of it (the launch's
|
||||
# job on Windows), the same one `Connection.close` waits on.
|
||||
try:
|
||||
rec = next((r for r in H.CONN_REC.values() if r.pid == main_pid), None)
|
||||
tree = getattr(getattr(getattr(rec, "conn", None), "_process", None), "tree", None)
|
||||
for p in (tree.members() if tree is not None else []):
|
||||
if p.pid not in self.procs:
|
||||
self._add(p)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
self.census_error = "%s: %s" % (type(exc).__name__, str(exc)[:160])
|
||||
# The waits start now, BEFORE the close is asked for: a wait holds the process's handle, so the exit code of a process that is gone
|
||||
# a moment later is still read (a process looked up after its exit has no code to give).
|
||||
for pid, v in list(self.procs.items()):
|
||||
threading.Thread(target=self._wait_one, args=(pid, v[0], v[1]), daemon=True, name="hunt-exitwait").start()
|
||||
self.t_ready = H.now_ms()
|
||||
|
||||
def _add(self, p):
|
||||
known = p.pid in self.procs
|
||||
super()._add(p)
|
||||
if known or p.pid not in self.procs:
|
||||
return
|
||||
try:
|
||||
cmd = p.cmdline()
|
||||
self.census.append({"pid": p.pid, "ppid": p.ppid(), "name": p.name(), "kind": self.procs[p.pid][1], "cmd": " ".join(cmd)[:400],
|
||||
"created_ms": round(p.create_time() * 1000), "late": getattr(self, "t_ready", None) is not None})
|
||||
except psutil.Error:
|
||||
pass
|
||||
|
||||
def _wait_one(self, pid, p, kind):
|
||||
try:
|
||||
rc = p.wait(timeout=125)
|
||||
except psutil.TimeoutExpired:
|
||||
rc = "timeout"
|
||||
except psutil.Error:
|
||||
rc = None
|
||||
self.exits_all[pid] = {"kind": kind, "rc": rc, "t": H.now_ms()}
|
||||
|
||||
def fields(self):
|
||||
d = super().fields()
|
||||
d["x_t_ready"] = round(self.t_ready, 1)
|
||||
d["x_exits"] = [[pid, v["kind"], v["rc"], round(v["t"] - self.t_snap, 1)] for pid, v in sorted(self.exits_all.items(), key=lambda kv: kv[1]["t"])]
|
||||
d["x_census"] = self.census
|
||||
d["x_census_error"] = getattr(self, "census_error", None)
|
||||
return d
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------------------------------------
|
||||
# Round 3: MOZ_LOG for IndexedDB, and the census
|
||||
# ---------------------------------------------------------------------------------------------------------------------------------
|
||||
def install_moz_log():
|
||||
d = os.path.normpath(os.environ.get("HUNT_MOZLOG_DIR") or os.path.join(os.environ.get("RUNNER_TEMP") or os.getcwd(), "mozlog"))
|
||||
os.makedirs(d, exist_ok=True)
|
||||
# The engine and the retail Firefox both inherit this process's environment (the core lets MOZ_LOG and MOZ_LOG_FILE through:
|
||||
# environment.MOZ_DIAGNOSTICS). %PID is Firefox's own: one file per process, named by its pid (the parent's and each child's).
|
||||
os.environ["MOZ_LOG"] = "IndexedDB:5,sync,timestamp"
|
||||
os.environ["MOZ_LOG_FILE"] = os.path.join(d, "ff-%PID.log")
|
||||
print("HUNTCLOSEARGS " + json.dumps({**H.ARM_CTX, "what": "moz_log", "MOZ_LOG": os.environ["MOZ_LOG"], "MOZ_LOG_FILE": os.environ["MOZ_LOG_FILE"]}), flush=True)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------------------------------------
|
||||
def main():
|
||||
if os.environ.get("HUNT_PIDFILE"):
|
||||
with open(os.environ["HUNT_PIDFILE"], "a", encoding="utf-8", newline="\n") as f:
|
||||
f.write("%d\n" % os.getpid())
|
||||
H.ARM_CTX.update({"arm": os.environ.get("HUNT_ARM"), "round": sys.argv[3] if len(sys.argv) > 3 else None})
|
||||
if os.environ.get("HUNT_CAND_MOUSE") == "1":
|
||||
# The page of the hunt (its own, served by the hunt's server) also reports where each mouse event was: clientX, clientY. The plan's
|
||||
# points carry coordinates, so a page event is joined to the point it is, not to the point nearest in time.
|
||||
before = H.TYPE_PAGE
|
||||
H.TYPE_PAGE = before.replace(b"__ev.push([t,performance.timeOrigin+e.timeStamp,T()])",
|
||||
b"__ev.push([t,performance.timeOrigin+e.timeStamp,T(),e.clientX,e.clientY])")
|
||||
if H.TYPE_PAGE == before:
|
||||
sys.exit("the hunt's page changed: its event list no longer matches")
|
||||
real_key_probe = H.install_key_probe
|
||||
|
||||
def install_key_probe():
|
||||
real_key_probe()
|
||||
install_mouse_probe()
|
||||
H.install_key_probe = install_key_probe
|
||||
H.mouse_report = mouse_report
|
||||
if os.environ.get("HUNT_CAND_CLOSE") == "1":
|
||||
if os.environ.get("HUNT_CLOSE_TIMEOUT"):
|
||||
sys.exit("HUNT_CLOSE_TIMEOUT is set: this hunt raises no deadline")
|
||||
H.install_close_stamps = install_clean_close_stamps
|
||||
H.TreeWatch = TreeWatch2
|
||||
if os.environ.get("HUNT_CAND_IDB") == "1":
|
||||
install_moz_log()
|
||||
H.start_alive_watchdog()
|
||||
if sys.argv[1] == "retail":
|
||||
H.retail_main(int(sys.argv[2]), sys.argv[3], sys.argv[4], float(sys.argv[5]) if len(sys.argv) > 5 else 20.0)
|
||||
sys.exit(0)
|
||||
asyncio.run(H.main(sys.argv[1], int(sys.argv[2]), sys.argv[3], sys.argv[4] if len(sys.argv) > 4 else None))
|
||||
# The interpreter now waits for the non-daemon threads (the core's reaper is one): if it is still here in 5 s, say what holds it.
|
||||
late = threading.Timer(5.0, H.print_alive, args=("5s-after-main-returned", False))
|
||||
late.daemon = True
|
||||
late.start()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,177 @@
|
||||
"""HUNT ONLY, never merged. The report of the IndexedDB hunt: from the rows of the arms (rows.log) and the MOZ_LOG files of every process
|
||||
(MOZ_LOG=IndexedDB:5,sync,timestamp, MOZ_LOG_FILE=<dir>/ff-%PID.log, one file per process, gzipped after each arm), per browser:
|
||||
|
||||
* the transactions of the IndexedDB log: how many, by mode, which were open at the quit (started before it, not completed by it), for how
|
||||
long they had been open and when each completed against the quit (the time the blocker "RemoteSettingsClient - finish IDB access."
|
||||
holds profile-before-change), and whether the log says they are on the Remote Settings database;
|
||||
* the census of the browser's processes at the close (type by command line, `-contentproc ... <type>`), ours against retail: which process
|
||||
types differ, with their command lines.
|
||||
|
||||
python hunt_candidate_idb.py ROWS_LOG MOZLOG_DIR
|
||||
|
||||
The IndexedDB lines are not assumed to have one shape: a transaction is whatever carries `T[<n>]` in the same file, its mode the first of
|
||||
readonly / readwrite / readwriteflush / versionchange / cleanup its lines name, its completion the first line that says complete / abort /
|
||||
commit, and the raw first lines of the transactions that matter, and a sample of the log, are printed so the reading can be checked."""
|
||||
from __future__ import annotations
|
||||
|
||||
import calendar
|
||||
import collections
|
||||
import glob
|
||||
import gzip
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
LINE = re.compile(r"^(\d{4})-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)\.(\d+) UTC - \[(\w+) (\d+): ([^\]]*)\]: (\w)/(\S+) (.*)$")
|
||||
TX = re.compile(r"\bT\[(\d+)\]")
|
||||
MODE = re.compile(r"\b(readwriteflush|readwrite|readonly|versionchange|cleanup)\b", re.I)
|
||||
COMPLETE = re.compile(r"\b(complete|completed|aborted|abort|committed|commit)\b", re.I)
|
||||
DB_END = re.compile(r"(finished database work|DB End)", re.I)
|
||||
ID_OF = re.compile(r"IndexedDB ([^:\s]+):")
|
||||
RS = re.compile(r"remote-settings|RemoteSettings", re.I)
|
||||
FILE_PID = (re.compile(r"ff--(?:main|child)\.(\d+)"), re.compile(r"ff-(\d+)"))
|
||||
|
||||
|
||||
def opened(path):
|
||||
return gzip.open(path, "rt", encoding="utf-8", errors="replace") if path.endswith(".gz") else open(path, encoding="utf-8", errors="replace")
|
||||
|
||||
|
||||
def pid_of(name):
|
||||
for rx in FILE_PID:
|
||||
m = rx.search(name)
|
||||
if m:
|
||||
return int(m.group(1))
|
||||
return None
|
||||
|
||||
|
||||
def parse(path):
|
||||
"""The IndexedDB lines of one file: (epoch ms, process kind, pid, thread, message)."""
|
||||
out = []
|
||||
with opened(path) as f:
|
||||
for raw in f:
|
||||
m = LINE.match(raw.rstrip("\r\n"))
|
||||
if not m or "IndexedDB" not in m.group(12):
|
||||
continue
|
||||
y, mo, d, h, mi, s, us = (int(m.group(k)) for k in range(1, 8))
|
||||
t = calendar.timegm((y, mo, d, h, mi, s)) * 1000 + int(str(m.group(7))[:3].ljust(3, "0"))
|
||||
out.append((t, m.group(8), int(m.group(9)), m.group(10), m.group(13)))
|
||||
return out
|
||||
|
||||
|
||||
def transactions(lines):
|
||||
"""Group the lines by `T[n]` (and the id string of the factory that logged them)."""
|
||||
tx = collections.OrderedDict()
|
||||
rs_ids = {ID_OF.search(x).group(1) for _t, _k, _p, _th, x in lines if RS.search(x) and ID_OF.search(x)}
|
||||
for t, kind, pid, th, x in lines:
|
||||
m = TX.search(x)
|
||||
if not m:
|
||||
continue
|
||||
ident = ID_OF.search(x)
|
||||
key = (ident.group(1) if ident else "?", int(m.group(1)))
|
||||
d = tx.setdefault(key, {"id": key[0], "serial": key[1], "start": t, "last": t, "mode": None, "complete": None, "db_end": None,
|
||||
"first": x, "rs": bool(ident and ident.group(1) in rs_ids) or bool(RS.search(x)), "n": 0, "kind": kind, "pid": pid})
|
||||
d["n"] += 1
|
||||
d["last"] = t
|
||||
if d["mode"] is None:
|
||||
mm = MODE.search(x)
|
||||
if mm:
|
||||
d["mode"] = mm.group(1).lower()
|
||||
if d["complete"] is None and COMPLETE.search(x):
|
||||
d["complete"] = t
|
||||
if d["db_end"] is None and DB_END.search(x):
|
||||
d["db_end"] = t
|
||||
if RS.search(x):
|
||||
d["rs"] = True
|
||||
return list(tx.values())
|
||||
|
||||
|
||||
def template(x):
|
||||
x = re.sub(r"0x[0-9a-fA-F]+", "P", x)
|
||||
x = re.sub(r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F-]+", "ID", x)
|
||||
return re.sub(r"\d+", "N", x)[:110]
|
||||
|
||||
|
||||
def q(v, p):
|
||||
v = sorted(x for x in v if x is not None)
|
||||
return v[min(len(v) - 1, int(p * len(v)))] if v else None
|
||||
|
||||
|
||||
def main(rows_log, mozdir):
|
||||
rows = {}
|
||||
for line in open(rows_log, encoding="utf-8"):
|
||||
m = re.match(r"HUNTROW \[(\w+)\] (.*)", line.strip())
|
||||
if m:
|
||||
rows.setdefault(m.group(1), []).append(json.loads(m.group(2)))
|
||||
files = {}
|
||||
for path in glob.glob(os.path.join(mozdir, "**", "ff-*"), recursive=True):
|
||||
files.setdefault(pid_of(os.path.basename(path)), []).append(path)
|
||||
print("HUNTIDBFILES moz_log files %d for %d pids under %s" % (sum(len(v) for v in files.values()), len(files), mozdir))
|
||||
sample_done = set()
|
||||
per_arm_held, per_arm_open = collections.defaultdict(list), collections.defaultdict(list)
|
||||
census = collections.defaultdict(list)
|
||||
for arm, rs in sorted(rows.items()):
|
||||
for r in rs:
|
||||
if "crash" in r:
|
||||
continue
|
||||
tag = r.get("tag")
|
||||
census_rows = r.get("x_census") or []
|
||||
kinds = collections.Counter(c["kind"] for c in census_rows)
|
||||
census[arm].append((tag, kinds, census_rows))
|
||||
quit_t = r["close_wall_ms"] + r["a_close_to_quit_ms"] if r.get("close_wall_ms") is not None and r.get("a_close_to_quit_ms") is not None else None
|
||||
exit_t = r["close_wall_ms"] + r["close_to_main_gone_ms"] if r.get("close_wall_ms") is not None and r.get("close_to_main_gone_ms") is not None else None
|
||||
pids = [c["pid"] for c in census_rows]
|
||||
mine = [(pid, p) for pid in pids for p in files.get(pid, [])]
|
||||
lines_all = []
|
||||
per_pid = {}
|
||||
for pid, path in mine:
|
||||
ls = parse(path)
|
||||
per_pid[pid] = per_pid.get(pid, 0) + len(ls)
|
||||
lines_all += ls
|
||||
if arm not in sample_done and lines_all:
|
||||
sample_done.add(arm)
|
||||
top = collections.Counter(template(x) for _t, _k, _p, _th, x in lines_all).most_common(15)
|
||||
for t, k, p, th, x in lines_all[:12]:
|
||||
print("HUNTIDBSAMPLE %s %s pid %d [%s: %s] %s" % (arm, tag, p, k, th, x[:200]))
|
||||
for tpl, n in top:
|
||||
print("HUNTIDBTEMPLATE %s %5d %s" % (arm, n, tpl))
|
||||
print("HUNTIDBFILES %s %s | processes %d, with a log %d, IndexedDB lines per pid %s | quit at %s, parent exit at %s (ms after the close: %s, %s)"
|
||||
% (arm, tag, len(pids), sum(1 for p in pids if p in files), dict(sorted(per_pid.items())), "known" if quit_t else "not seen", "known" if exit_t else "not seen",
|
||||
r.get("a_close_to_quit_ms"), r.get("close_to_main_gone_ms")))
|
||||
txs = transactions(sorted(lines_all))
|
||||
bymode = collections.Counter(t["mode"] or "?" for t in txs)
|
||||
open_q = [t for t in txs if quit_t and t["start"] <= quit_t and (t["complete"] is None or t["complete"] > quit_t)]
|
||||
rw = [t for t in open_q if (t["mode"] or "").startswith("readwrite")]
|
||||
held = [(max(t["complete"], t["db_end"] or 0) - quit_t) if t["complete"] else None for t in rw]
|
||||
ended_held = [h for h in held if h is not None]
|
||||
if rw:
|
||||
per_arm_held[arm].append(max(ended_held) if ended_held else None)
|
||||
per_arm_open[arm].append(len(rw))
|
||||
print("HUNTIDBTX %s %s | transactions %d by mode %s | open at the quit %d (readwrite %d, on the Remote Settings database per the log %d) | readwrite open at quit: completed after the quit at ms %s, never completed in the log %d | log ends at quit%+.0f ms"
|
||||
% (arm, tag, len(txs), dict(bymode), len(open_q), len(rw), sum(1 for t in rw if t["rs"]), sorted(round(h) for h in ended_held)[:12],
|
||||
sum(1 for h in held if h is None), (max((t[0] for t in lines_all), default=0) - quit_t) if quit_t and lines_all else float("nan")))
|
||||
for t in rw[:6]:
|
||||
print("HUNTIDBRW %s %s pid %d T[%d] id %s mode %s rs %s | open for %.0f ms before the quit | completed %s ms after the quit | %d lines | first: %s"
|
||||
% (arm, tag, t["pid"], t["serial"], t["id"][:12], t["mode"], t["rs"], quit_t - t["start"],
|
||||
round(t["complete"] - quit_t) if t["complete"] else None, t["n"], t["first"][:160]))
|
||||
# The Remote Settings client's own view of the same quit (services.settings.loglevel=debug).
|
||||
print("HUNTIDBRS %s %s | writes at close %s | busy for ms after the close %s | finish-IDB blocker done at quit+ms %s (after the parent's exit: %s)"
|
||||
% (arm, tag, r.get("rs_write_kinds_at_close"), r.get("rs_busy_lasts_ms"), r.get("rs_idb_done_q_ms"), r.get("rs_idb_done_after_exit")))
|
||||
for arm in sorted(per_arm_held):
|
||||
print("HUNTIDBHELD %s browsers with a readwrite transaction open at the quit: %d of %d | the last of them completes after the quit at ms p50 %s max %s"
|
||||
% (arm, len(per_arm_held[arm]), len(rows.get(arm, [])), q(per_arm_held[arm], .5), max((h for h in per_arm_held[arm] if h is not None), default=None)))
|
||||
# The census: the processes of a browser at its close, by type, ours against retail.
|
||||
types = sorted({k for a in census.values() for _tag, c, _r in a for k in c})
|
||||
for arm, a in sorted(census.items()):
|
||||
n = len(a)
|
||||
print("HUNTCENSUS %-12s browsers %d | processes per browser p50 %s | by type (p50 per browser, max): %s"
|
||||
% (arm, n, q([sum(c.values()) for _t, c, _r in a], .5), {k: (q([c.get(k, 0) for _t, c, _r in a], .5), max(c.get(k, 0) for _t, c, _r in a)) for k in types}))
|
||||
for arm, a in sorted(census.items()):
|
||||
for tag, c, rr in a[:1]:
|
||||
for p in sorted(rr, key=lambda p: (p["kind"], p["created_ms"])):
|
||||
print("HUNTCENSUSPROC %-12s %s pid %d ppid %d %-14s born +%.1fs | %s" % (arm, tag, p["pid"], p["ppid"], p["kind"], (p["created_ms"] - min(x["created_ms"] for x in rr)) / 1000,
|
||||
re.sub(r"-(?:prefsHandle|prefMapHandle|jsInitHandle|parentBuildID|appDir|[A-Za-z]*Handle)\s+\S+", "", p["cmd"])[:230]))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(sys.argv[1], sys.argv[2])
|
||||
@@ -0,0 +1,406 @@
|
||||
"""HUNT ONLY, never merged: a watcher for the shutdown-ping sender (`firefox --backgroundtask pingsender ...`), run as root beside the
|
||||
wrapper's own e2e lab (tests/test_nothing_leaves_but_the_proxy_e2e.py).
|
||||
|
||||
python hunt_pingsender_dns.py watch OUT_JSONL PREFS_DIR
|
||||
|
||||
Every 20 ms it looks for a `firefox` process whose command line has `--backgroundtask` and `pingsender`. At first sight, per sender:
|
||||
* its profile dir, taken from the saved-telemetry-pings path in its command line (`<profile>/saved-telemetry-pings/<file>`);
|
||||
* a copy of that profile's prefs.js (kept in PREFS_DIR), with network.trr.stealth.contexts, network.trr.uri (set yes/no),
|
||||
network.trr.mode, network.trr.excluded-domains and network.proxy.type read from the copy, and the copy's mtime against the sender's birth;
|
||||
* the route it received: STEALTHFOX_PINGSENDER_ROUTE from its environment (present, proxy record present, type/scheme/host/port;
|
||||
credentials are never printed) and whether MOZ_LOG / MOZ_LOG_FILE reached it;
|
||||
and when it ends (its lifetime). One JSON line per event in OUT_JSONL: "seen" and "end".
|
||||
|
||||
Also, for the attribution of every native DNS query to the process that sent it (the table step joins the kernel's view, bpftrace on
|
||||
udp_sendmsg and tcpdump, with these records by pid and by time), the same loop snapshots EVERY process of the engine (its exe under
|
||||
HUNT_ENGINE_DIR, /opt/ff): one "proc" event at first sight (pid, ppid, birth, comm, the head and the tail of the command line, the ancestors,
|
||||
the process type, the profile: its own -profile or the saved-telemetry-pings path, else its parent's, the route it received), one "pupd" ~0.5 s
|
||||
later (the comm and the command line a child sets after it starts), one "pend" when it ends; per profile one "prof" event (its birth, the
|
||||
prefs of interest read from prefs.js and user.js, re-read until they appear) and one "pgone" when the directory disappears; every 2 s an
|
||||
"anchor" (wall clock ms against CLOCK_MONOTONIC ns, the clock bpftrace's nsecs uses).
|
||||
|
||||
python hunt_pingsender_dns.py sockpoll OUT_JSONL
|
||||
|
||||
The fallback when bpftrace cannot attach: polls `ss -H -u -a -n -p` and records (local port, pid, comm, peer port 53) the first time it sees each.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import traceback
|
||||
|
||||
import psutil
|
||||
|
||||
INTEREST = ("network.trr.stealth.contexts", "network.trr.uri", "network.trr.mode", "network.trr.excluded-domains", "network.proxy.type")
|
||||
ROUTE_VAR = "STEALTHFOX_PINGSENDER_ROUTE"
|
||||
SECRET = re.compile(r"user|pass|auth|cred|secret|token|key", re.I)
|
||||
LOCK = threading.Lock()
|
||||
ENGINE = os.environ.get("HUNT_ENGINE_DIR", "/opt/ff")
|
||||
|
||||
|
||||
def now_ms():
|
||||
return time.time() * 1000
|
||||
|
||||
|
||||
def emit(path, rec):
|
||||
with LOCK, open(path, "a", encoding="utf-8") as f:
|
||||
f.write(json.dumps(rec) + "\n")
|
||||
|
||||
|
||||
def read_prefs(path):
|
||||
try:
|
||||
text = open(path, encoding="utf-8", errors="replace").read()
|
||||
except OSError:
|
||||
return None
|
||||
out = {}
|
||||
for name in INTEREST:
|
||||
m = re.search(r'user_pref\("%s", (.*)\);' % re.escape(name), text)
|
||||
out[name] = m.group(1)[:160] if m else None
|
||||
return out
|
||||
|
||||
|
||||
def sanitize_route(raw):
|
||||
"""What the sender received, without secrets: the record is there or not, its keys, and its type/scheme/host/port style fields."""
|
||||
if raw is None:
|
||||
return {"present": False}
|
||||
try:
|
||||
route = json.loads(raw)
|
||||
except ValueError:
|
||||
return {"present": True, "json": False, "length": len(raw)}
|
||||
proxy = route.get("proxy") if isinstance(route, dict) else None
|
||||
out = {"present": True, "json": True, "keys": sorted(route) if isinstance(route, dict) else None, "proxy_present": bool(proxy)}
|
||||
if isinstance(proxy, dict):
|
||||
out["proxy_keys"] = sorted(proxy)
|
||||
safe = {}
|
||||
for k, v in proxy.items():
|
||||
if SECRET.search(k):
|
||||
continue
|
||||
if isinstance(v, str):
|
||||
v = re.sub(r"//[^/@]*@", "//", v)
|
||||
if isinstance(v, (str, int, bool)) or v is None:
|
||||
safe[k] = v
|
||||
out["proxy"] = safe
|
||||
prefs = route.get("prefs") if isinstance(route, dict) else None
|
||||
if isinstance(prefs, dict):
|
||||
out["prefs_n"] = len(prefs)
|
||||
out["prefs_of_interest"] = {k: prefs.get(k) for k in INTEREST if k in prefs}
|
||||
else:
|
||||
out["prefs_n"] = None
|
||||
return out
|
||||
|
||||
|
||||
def profile_from(cmd):
|
||||
"""The profile dir from the path of a saved telemetry ping in the command line: `<profile>/saved-telemetry-pings/<file>`."""
|
||||
for a in cmd:
|
||||
m = re.search(r"^(.*?)[/\\]saved-telemetry-pings[/\\]", a)
|
||||
if m:
|
||||
return m.group(1)
|
||||
for i, a in enumerate(cmd):
|
||||
if a in ("-profile", "--profile") and i + 1 < len(cmd):
|
||||
return cmd[i + 1]
|
||||
return None
|
||||
|
||||
|
||||
|
||||
|
||||
def read_profile_prefs(profile):
|
||||
"""The prefs of interest of a profile: prefs.js, then user.js on top of it (the file Firefox applies last wins)."""
|
||||
merged = {}
|
||||
for name in ("prefs.js", "user.js"):
|
||||
got = read_prefs(os.path.join(profile, name))
|
||||
for k, v in (got or {}).items():
|
||||
if v is not None or k not in merged:
|
||||
merged[k] = v
|
||||
return merged
|
||||
|
||||
|
||||
def oldest_mtime(profile):
|
||||
try:
|
||||
return round(min(e.stat().st_mtime for e in os.scandir(profile) if e.is_file()) * 1000, 1)
|
||||
except (OSError, ValueError, TypeError):
|
||||
return None
|
||||
|
||||
|
||||
def brief(cmd):
|
||||
out = []
|
||||
for a in cmd:
|
||||
a = re.sub(r"\?.*", "", a)
|
||||
a = re.sub(r"//[^/@\s]*@", "//", a)
|
||||
out.append(a[:110])
|
||||
return out
|
||||
|
||||
|
||||
CHILD_ARG = {"tab": "content", "socket": "socket", "gpu": "gpu", "rdd": "rdd", "utility": "utility", "forkserver": "forkserver", "vr": "vr"}
|
||||
COMM_TYPE = (("isolated web", "content"), ("web content", "content"), ("privileged cont", "content"), ("webextensions", "content"),
|
||||
("isolated servic", "content"), ("socket process", "socket"), ("gpu process", "gpu"), ("rdd process", "rdd"),
|
||||
("utility process", "utility"), ("forkserver", "forkserver"))
|
||||
|
||||
|
||||
def classify(cmd, comm):
|
||||
"""The process type: pingsender and other background tasks, the Gecko child types (from the thread name the child sets, else from the
|
||||
last argument of -contentproc), the main browser (it carries -profile)."""
|
||||
low = [a.lstrip("-").lower() for a in cmd[1:]]
|
||||
if "backgroundtask" in low:
|
||||
i = low.index("backgroundtask")
|
||||
name = low[i + 1] if i + 1 < len(low) else "?"
|
||||
return "pingsender" if name == "pingsender" else "backgroundtask:" + name
|
||||
c = (comm or "").lower()
|
||||
for k, v in COMM_TYPE:
|
||||
if c.startswith(k):
|
||||
return v
|
||||
if "contentproc" in low:
|
||||
return CHILD_ARG.get(low[-1], "child:" + low[-1][:20])
|
||||
if "forkserver" in low:
|
||||
return "forkserver"
|
||||
if "profile" in low or "no-remote" in low or "juggler-pipe" in low or "headless" in low:
|
||||
return "main"
|
||||
return "firefox:" + (comm or "?")
|
||||
|
||||
|
||||
def follow(p, rec, out):
|
||||
while True:
|
||||
try:
|
||||
if not p.is_running() or p.status() == psutil.STATUS_ZOMBIE:
|
||||
break
|
||||
except psutil.Error:
|
||||
break
|
||||
time.sleep(0.01)
|
||||
ended = now_ms()
|
||||
emit(out, {"event": "end", "pid": rec["pid"], "ended": round(ended, 1), "lifetime_ms": round(ended - rec["born"], 1)})
|
||||
|
||||
|
||||
def capture_sender(p, cmd, out, prefs_dir):
|
||||
"""The record of a pingsender at first sight (as in the earlier hunts: its prefs copy, its route, its profile's birth)."""
|
||||
try:
|
||||
born = p.create_time() * 1000
|
||||
except psutil.Error:
|
||||
return
|
||||
seen = now_ms()
|
||||
rec = {"event": "seen", "pid": p.pid, "ppid": p.ppid(), "born": round(born, 1), "seen": round(seen, 1),
|
||||
"cmd": [re.sub(r"[?&=].*", "", a)[:90] for a in cmd[:5]]}
|
||||
try:
|
||||
env = p.environ()
|
||||
rec["route"] = sanitize_route(env.get(ROUTE_VAR))
|
||||
rec["env_moz_log"] = env.get("MOZ_LOG")
|
||||
rec["env_moz_log_file"] = bool(env.get("MOZ_LOG_FILE"))
|
||||
except psutil.Error as exc:
|
||||
rec["route"] = {"error": type(exc).__name__}
|
||||
profile = profile_from(cmd)
|
||||
rec["profile"] = profile
|
||||
src = os.path.join(profile, "prefs.js") if profile else None
|
||||
try:
|
||||
st = os.stat(src)
|
||||
dst = os.path.join(prefs_dir, "prefs-sender-%d.js" % p.pid)
|
||||
shutil.copy2(src, dst)
|
||||
rec["prefs_copy_mtime_vs_birth_ms"] = round(st.st_mtime * 1000 - born, 1)
|
||||
rec["prefs_copy_taken_after_birth_ms"] = round(now_ms() - born, 1)
|
||||
rec["prefs"] = read_prefs(dst)
|
||||
except (OSError, TypeError) as exc:
|
||||
rec["prefs"] = None
|
||||
rec["prefs_error"] = "%s %s" % (type(exc).__name__, src)
|
||||
rec["profile_oldest_mtime_ms"] = oldest_mtime(profile) if profile else None
|
||||
emit(out, rec)
|
||||
threading.Thread(target=follow, args=(p, rec, out), daemon=True).start()
|
||||
|
||||
|
||||
def chain_of(ppid, live):
|
||||
"""The ancestors, nearest first (pid, comm, process type), from what the watcher already knows, else from /proc."""
|
||||
chain, pid = [], ppid
|
||||
for _ in range(6):
|
||||
if not pid or pid <= 1:
|
||||
break
|
||||
r = live.get(pid)
|
||||
if r is not None:
|
||||
chain.append({"pid": pid, "comm": r["comm"], "ptype": r["ptype"]})
|
||||
pid = r["ppid"]
|
||||
continue
|
||||
try:
|
||||
q = psutil.Process(pid)
|
||||
chain.append({"pid": pid, "comm": q.name(), "ptype": "outside:" + os.path.basename(q.exe() or "")})
|
||||
pid = q.ppid()
|
||||
except psutil.Error:
|
||||
break
|
||||
return chain
|
||||
|
||||
|
||||
def snapshot(p, live):
|
||||
"""One engine process at first sight: who it is, its parents, its profile (its own, else the nearest ancestor's), the route it received."""
|
||||
born = p.create_time() * 1000
|
||||
cmd = p.cmdline()
|
||||
comm = p.name()
|
||||
ppid = p.ppid()
|
||||
rec = {"event": "proc", "pid": p.pid, "ppid": ppid, "born": round(born, 1), "seen": round(now_ms(), 1), "comm": comm,
|
||||
"exe": os.path.basename(p.exe() or ""), "argc": len(cmd), "head": brief(cmd[:6]), "tail": brief(cmd[-3:]),
|
||||
"ptype": classify(cmd, comm)}
|
||||
rec["chain"] = chain_of(ppid, live)
|
||||
profile = profile_from(cmd)
|
||||
via = "own" if profile else None
|
||||
if profile is None:
|
||||
for c in rec["chain"]:
|
||||
r = live.get(c["pid"])
|
||||
if r is not None and r.get("profile"):
|
||||
profile, via = r["profile"], "ancestor %d" % c["pid"]
|
||||
break
|
||||
rec["profile"], rec["profile_via"] = profile, via
|
||||
try:
|
||||
route = sanitize_route(p.environ().get(ROUTE_VAR))
|
||||
rec["route_present"] = route.get("present")
|
||||
rec["route_proxy"] = route.get("proxy_present")
|
||||
except psutil.Error:
|
||||
rec["route_present"] = None
|
||||
return rec, cmd
|
||||
|
||||
|
||||
class Profiles:
|
||||
"""Per profile: its birth, the prefs of interest (re-read every 0.5 s for 4 s, or until the stealth contexts pref shows), its disappearance."""
|
||||
|
||||
def __init__(self, out):
|
||||
self.out, self.items = out, {}
|
||||
|
||||
def see(self, path, born_hint):
|
||||
if not path or path in self.items:
|
||||
return
|
||||
self.items[path] = {"born": oldest_mtime(path) or born_hint, "first": now_ms(), "next": 0.0, "vals": None, "done": False, "gone": False}
|
||||
self.poll(now_ms())
|
||||
|
||||
def poll(self, now):
|
||||
for path, st in self.items.items():
|
||||
if st["gone"]:
|
||||
continue
|
||||
if not os.path.isdir(path):
|
||||
st["gone"] = True
|
||||
emit(self.out, {"event": "pgone", "profile": path, "t": round(now, 1)})
|
||||
continue
|
||||
if st["done"] or now < st["next"]:
|
||||
continue
|
||||
st["next"] = now + 500
|
||||
vals = read_profile_prefs(path)
|
||||
if vals != st["vals"]:
|
||||
st["vals"] = vals
|
||||
emit(self.out, {"event": "prof", "profile": path, "born": st["born"], "first": round(st["first"], 1), "t": round(now, 1), "prefs": vals})
|
||||
if (vals or {}).get("network.trr.stealth.contexts") is not None or now - st["first"] > 4000:
|
||||
st["done"] = True
|
||||
|
||||
|
||||
def anchor(out):
|
||||
a = time.monotonic_ns()
|
||||
w = time.time() * 1000
|
||||
b = time.monotonic_ns()
|
||||
emit(out, {"event": "anchor", "wall": round(w, 3), "mono": (a + b) // 2, "err_ns": b - a})
|
||||
|
||||
|
||||
def watch(out, prefs_dir):
|
||||
state = {"live": {}, "procs": {}, "ignore": set(), "last_anchor": 0.0}
|
||||
profiles = Profiles(out)
|
||||
os.makedirs(prefs_dir, exist_ok=True)
|
||||
anchor(out)
|
||||
print("watching the engine's processes under %s (pingsender senders in full)" % ENGINE, flush=True)
|
||||
while True:
|
||||
try:
|
||||
sweep(out, prefs_dir, state, profiles)
|
||||
except Exception:
|
||||
traceback.print_exc()
|
||||
sys.stdout.flush()
|
||||
sys.stderr.flush()
|
||||
time.sleep(0.02)
|
||||
|
||||
|
||||
def sweep(out, prefs_dir, state, profiles):
|
||||
"""One pass of the watcher (the state outlives it): ends, the second look, the new engine processes, the profiles."""
|
||||
live, procs, ignore = state["live"], state["procs"], state["ignore"]
|
||||
now = now_ms()
|
||||
if now - state["last_anchor"] > 2000:
|
||||
anchor(out)
|
||||
state["last_anchor"] = now
|
||||
try:
|
||||
pids = set(psutil.pids())
|
||||
except psutil.Error:
|
||||
pids = set()
|
||||
# Ends, and the one look at the comm and the command line a child sets after it starts.
|
||||
for pid in list(live):
|
||||
r, p = live[pid], procs[pid]
|
||||
try:
|
||||
gone = pid not in pids or not p.is_running() or p.status() == psutil.STATUS_ZOMBIE
|
||||
except psutil.Error:
|
||||
gone = True
|
||||
if gone:
|
||||
emit(out, {"event": "pend", "pid": pid, "born": r["born"], "ended": round(now_ms(), 1)})
|
||||
del live[pid], procs[pid]
|
||||
elif not r.get("refreshed") and now - r["seen"] > 500:
|
||||
r["refreshed"] = True
|
||||
try:
|
||||
cmd, comm = p.cmdline(), p.name()
|
||||
ptype = classify(cmd, comm)
|
||||
except psutil.Error:
|
||||
continue
|
||||
if comm != r["comm"] or ptype != r["ptype"]:
|
||||
r["comm"], r["ptype"] = comm, ptype
|
||||
emit(out, {"event": "pupd", "pid": pid, "born": r["born"], "comm": comm, "ptype": ptype, "head": brief(cmd[:6]), "tail": brief(cmd[-3:])})
|
||||
ignore &= pids
|
||||
# New engine processes, parents first (a child's profile is its parent's).
|
||||
for pid in sorted(pids - set(live) - ignore):
|
||||
try:
|
||||
p = psutil.Process(pid)
|
||||
exe = p.exe()
|
||||
age = now / 1000 - p.create_time()
|
||||
except psutil.Error:
|
||||
continue
|
||||
if not exe.startswith(ENGINE):
|
||||
# A process between fork and exec still shows its parent's exe: look again for a second before dismissing it.
|
||||
if age > 1.0:
|
||||
ignore.add(pid)
|
||||
continue
|
||||
try:
|
||||
rec, cmd = snapshot(p, live)
|
||||
except psutil.Error:
|
||||
continue
|
||||
live[pid], procs[pid] = rec, p
|
||||
profiles.see(rec["profile"], rec["born"])
|
||||
emit(out, rec)
|
||||
if rec["ptype"] == "pingsender":
|
||||
try:
|
||||
capture_sender(p, cmd, out, prefs_dir)
|
||||
except psutil.Error:
|
||||
pass
|
||||
profiles.poll(now_ms())
|
||||
|
||||
|
||||
SS_RE = re.compile(r"^\S+\s+\d+\s+\d+\s+(\S+):(\d+)\s+(\S+):(\d+)\s+users:\(\((.*)\)\)\s*$")
|
||||
SS_USER = re.compile(r'"([^"]*)",pid=(\d+),fd=(\d+)')
|
||||
|
||||
|
||||
def sockpoll(out):
|
||||
"""The fallback of the bpftrace attribution: the owner of every UDP socket whose peer port is 53, from `ss`, as fast as ss runs."""
|
||||
seen = set()
|
||||
print("polling ss -H -u -a -n -p", flush=True)
|
||||
while True:
|
||||
try:
|
||||
text = subprocess.run(["ss", "-H", "-u", "-a", "-n", "-p"], capture_output=True, text=True, timeout=5).stdout
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
time.sleep(0.05)
|
||||
continue
|
||||
t = now_ms()
|
||||
for line in text.splitlines():
|
||||
m = SS_RE.match(line.strip())
|
||||
if not m or m.group(4) != "53":
|
||||
continue
|
||||
for comm, pid, fd in SS_USER.findall(m.group(5)):
|
||||
key = (m.group(2), pid, fd)
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
emit(out, {"event": "ssq", "t": round(t, 1), "sport": int(m.group(2)), "pid": int(pid), "comm": comm, "fd": int(fd), "peer": m.group(3)})
|
||||
time.sleep(0.002)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if sys.argv[1] == "sockpoll":
|
||||
sockpoll(sys.argv[2])
|
||||
else:
|
||||
watch(sys.argv[2], sys.argv[3])
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,27 @@
|
||||
"""HUNT ONLY: a pytest plugin (`-p hunt_testtimes`, with this directory on PYTHONPATH) that writes, for every test of a run, when it started and
|
||||
when each phase ended (wall clock, ms), one JSON line per event, to the file named by HUNT_TESTTIMES. It touches no test and no fixture:
|
||||
the lab's own file is run as it is, and the instants say which test was running when a process of a session did something."""
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
|
||||
_OUT = os.environ.get("HUNT_TESTTIMES")
|
||||
|
||||
|
||||
def _emit(rec):
|
||||
if _OUT:
|
||||
with open(_OUT, "a", encoding="utf-8") as f:
|
||||
f.write(json.dumps(rec) + "\n")
|
||||
|
||||
|
||||
def pytest_runtest_logstart(nodeid, location):
|
||||
_emit({"event": "start", "nodeid": nodeid, "t": round(time.time() * 1000, 1)})
|
||||
|
||||
|
||||
def pytest_runtest_logreport(report):
|
||||
_emit({"event": "phase", "nodeid": report.nodeid, "when": report.when, "outcome": report.outcome, "start": round(report.start * 1000, 1),
|
||||
"stop": round(report.stop * 1000, 1)})
|
||||
|
||||
|
||||
def pytest_runtest_logfinish(nodeid, location):
|
||||
_emit({"event": "finish", "nodeid": nodeid, "t": round(time.time() * 1000, 1)})
|
||||
Reference in new issue
Block a user