Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d56c473f22 | ||
|
|
987b935727 | ||
|
|
08b35a6adb | ||
|
|
5f7946f05f | ||
|
|
fc9161f812 |
No files matched your search
@@ -0,0 +1,146 @@
|
||||
# windows-flakes-locks-hunt.yml - hunt scaffolding, never merged. Runs only on a push to a `hunt/windows-flakes-locks**` branch.
|
||||
# With no Thread.start left on the core's pipe reader (wrapper fc9161f + core fix/no-thread-started-on-the-reader), single events still wait
|
||||
# up to about 1 s between the pipe read (invisible_core/juggler/connection.py _read_loop) and Lifecycle._on_event. WHERE on the reader path?
|
||||
# Windows only, 15 rounds x 4 processes at once, in two passes of the same job:
|
||||
# 1. CONTROL, no patcher at all: old (the wrapper of main + invisible-core==63.68.0) and new (this checkout + the core of that branch),
|
||||
# only the networkidle misses, defect vs not yet asked, from the server times in the HUNT-ROW lines of hunt_netidle.py.
|
||||
# 2. STAMPED, the new arm only, patched: every in-process stamp (lifecycle, pipe, and the rows below) is a list in memory written ONCE at
|
||||
# process exit, nothing is opened or written on the reader during the run. On the READER thread only the patcher
|
||||
# (scripts/hunt_trace_locks.py) times: (a) every listener call of Connection.dispatch_event, (b) gated_dispatch's wait on the events
|
||||
# gate, (c) every lock the reader takes or waits on (rows from 5 ms), (d) per message, wall against the thread's CPU time (GIL
|
||||
# starvation). The summary prints the control counts first, then cuts the interval pipe -> lifecycle of every /landed over 100 ms by item.
|
||||
name: windows flakes locks hunt
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ['hunt/windows-flakes-locks**']
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: windows-flakes-locks-hunt-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
PYTHONUNBUFFERED: "1"
|
||||
|
||||
jobs:
|
||||
hunt:
|
||||
name: locks hunt windows
|
||||
runs-on: windows-2022
|
||||
timeout-minutes: 150
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
- name: The wrapper of main, for the old arm of the control
|
||||
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
with:
|
||||
ref: main
|
||||
path: old
|
||||
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
|
||||
with: { python-version: '3.11' }
|
||||
- name: Two environments, old and new
|
||||
run: |
|
||||
set -e
|
||||
OLDPY="$RUNNER_TEMP/venv-old/Scripts/python.exe"
|
||||
NEWPY="$RUNNER_TEMP/venv-new/Scripts/python.exe"
|
||||
echo "OLDPY=$OLDPY" >> "$GITHUB_ENV"
|
||||
echo "NEWPY=$NEWPY" >> "$GITHUB_ENV"
|
||||
echo "old wrapper: $(git -C old rev-parse HEAD) new wrapper: $(git rev-parse HEAD)"
|
||||
CORE_SHA="$(timeout 300 git ls-remote https://github.com/oss-invisible/core.git refs/heads/fix/no-thread-started-on-the-reader)"
|
||||
echo "core branch: $CORE_SHA"
|
||||
test -n "$CORE_SHA" || { echo "the core branch is not on GitHub"; exit 1; }
|
||||
|
||||
timeout 300 python -m venv "$RUNNER_TEMP/venv-old"
|
||||
timeout 300 "$OLDPY" -m pip install --quiet --upgrade pip
|
||||
# OLD: the wrapper of main (the checkout in old/, whose pyproject pins invisible_core==63.68.0) and that exact core
|
||||
timeout 300 "$OLDPY" -m pip install --quiet "./old[dev]" "invisible-core==63.68.0"
|
||||
timeout 300 "$OLDPY" -m pip install --quiet "playwright==$(cat scripts/playwright_pin.txt)"
|
||||
|
||||
timeout 300 python -m venv "$RUNNER_TEMP/venv-new"
|
||||
timeout 300 "$NEWPY" -m pip install --quiet --upgrade pip
|
||||
timeout 300 "$NEWPY" -m pip install --quiet ".[dev]"
|
||||
timeout 300 "$NEWPY" -m pip install --quiet "playwright==$(cat scripts/playwright_pin.txt)"
|
||||
# NEW: the core of the branch over the wheel the wrapper pulled in
|
||||
timeout 300 "$NEWPY" -m pip install --quiet --force-reinstall --no-deps "invisible-core @ git+https://github.com/oss-invisible/core.git@fix/no-thread-started-on-the-reader"
|
||||
|
||||
for py in "$OLDPY" "$NEWPY"; do
|
||||
echo "== $py"
|
||||
"$py" -m pip list 2>/dev/null | grep -iE "^(invisible|playwright)" || true
|
||||
"$py" -c "import invisible_core, invisible_playwright as w; print('core', invisible_core.__version__, invisible_core.__file__); print('wrapper', w.__file__)"
|
||||
done
|
||||
- name: Browsers, the lab GeoIP database, the binaries of both cores
|
||||
run: |
|
||||
set -e
|
||||
timeout 300 "$NEWPY" scripts/ci_lab_geoip.py build
|
||||
echo "FF_OLD=$(cd "$RUNNER_TEMP" && timeout 300 "$OLDPY" -m invisible_playwright fetch | tail -1)" >> "$GITHUB_ENV"
|
||||
echo "FF_NEW=$(cd "$RUNNER_TEMP" && timeout 300 "$NEWPY" -m invisible_playwright fetch | tail -1)" >> "$GITHUB_ENV"
|
||||
- name: CONTROL, no patcher at all - old and new, four processes at once per arm, fifteen rounds, the order of the arms alternating
|
||||
run: |
|
||||
set +e
|
||||
mkdir -p evidence
|
||||
echo "binaries: old=$FF_OLD new=$FF_NEW"
|
||||
for n in $(seq 1 15); do
|
||||
if [ $((n % 2)) -eq 1 ]; then ORDER="old new"; else ORDER="new old"; fi
|
||||
for arm in $ORDER; do
|
||||
if [ "$arm" = old ]; then PY="$OLDPY"; BINARY="$FF_OLD"; else PY="$NEWPY"; BINARY="$FF_NEW"; fi
|
||||
for c in 1 2 3 4; do
|
||||
timeout 300 "$PY" -u scripts/hunt_netidle.py ours "$BINARY" > "evidence/control_${arm}_${n}_$c.log" 2>&1 &
|
||||
done
|
||||
wait
|
||||
taskkill //F //T //IM firefox.exe > /dev/null 2>&1 || true
|
||||
done
|
||||
echo "control round $n done ($ORDER)"
|
||||
done
|
||||
exit 0
|
||||
- name: The stamps (pipe chunk, lifecycle event) and the timing of the reader's path, in the new environment only
|
||||
run: |
|
||||
set -e
|
||||
timeout 300 "$NEWPY" scripts/hunt_trace_pipes.py
|
||||
timeout 300 "$NEWPY" scripts/hunt_trace_lifecycle.py
|
||||
timeout 300 "$NEWPY" scripts/hunt_trace_locks.py
|
||||
# the patched modules import and the hooks are in place, before fifteen rounds are spent on them
|
||||
"$NEWPY" -c "import invisible_core._hunt_locks as h, invisible_core.juggler.connection as c, invisible_core.juggler.lifecycle, invisible_core.juggler.injected, invisible_core.juggler.instance, invisible_playwright._juggler.server as s; assert c.Connection.dispatch_event is h._core_dispatch_event; assert getattr(s.PageDispatcher.__init__, '_hunt_wrapped', False) and getattr(s.BrowserDispatcher.__init__, '_hunt_wrapped', False); print('hooks ok')"
|
||||
- name: STAMPED - the new arm, four processes at once, fifteen rounds
|
||||
run: |
|
||||
set +e
|
||||
for n in $(seq 1 15); do
|
||||
for c in 1 2 3 4; do
|
||||
HUNT_LOCKS_TRACE="evidence/locks_new_${n}_$c.jsonl" timeout 300 "$NEWPY" -u scripts/hunt_netidle.py ours "$FF_NEW" "evidence/lc_new_${n}_$c.jsonl" "evidence/pipe_new_${n}_$c.txt" \
|
||||
> "evidence/netidle_new_${n}_$c.log" 2>&1 &
|
||||
done
|
||||
wait
|
||||
taskkill //F //T //IM firefox.exe > /dev/null 2>&1 || true
|
||||
echo "stamped round $n done"
|
||||
done
|
||||
exit 0
|
||||
- name: Step summary
|
||||
if: always()
|
||||
run: |
|
||||
set +e
|
||||
{
|
||||
timeout 300 "$NEWPY" scripts/hunt_locks_summary.py windows-2022 evidence 100
|
||||
echo
|
||||
echo "### Tracebacks and errors in the netidle logs"
|
||||
echo '```'
|
||||
grep -ahE "Traceback|Error" evidence/control_*.log evidence/netidle_*.log | cut -c1-160 | sort | uniq -c | sort -rn | head -12
|
||||
echo '```'
|
||||
} 2>&1 | tee -a "$GITHUB_STEP_SUMMARY"
|
||||
exit 0
|
||||
- name: Close every Firefox left
|
||||
if: always()
|
||||
run: |
|
||||
taskkill //F //T //IM firefox.exe > /dev/null 2>&1 || true
|
||||
exit 0
|
||||
- name: Upload the evidence
|
||||
if: always()
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
with:
|
||||
name: windows-flakes-locks-${{ github.run_id }}
|
||||
path: evidence
|
||||
if-no-files-found: warn
|
||||
retention-days: 14
|
||||
@@ -0,0 +1,482 @@
|
||||
"""HUNT SCAFFOLDING, NEVER MERGED: the runtime that scripts/hunt_trace_locks.py copies into the installed invisible_core as
|
||||
invisible_core/_hunt_locks.py. It times, on the connection's READER thread only, where a message spends the time between the pipe read and
|
||||
the lifecycle:
|
||||
|
||||
(a) every listener call of Connection.dispatch_event (row k=lst: name, event, wall ms, cpu ms),
|
||||
(b) the wrapper's gated_dispatch wait on the events gate (row k=gate, with who held it),
|
||||
(c) every lock / condition the reader takes or waits on; a wait of 5 ms or more is a row k=lock (name, ms, holder, where it was taken),
|
||||
(d) per message: wall against CPU time of the thread (row k=msg), so wall - cpu - lock waits - gate = time off the CPU (GIL, preemption).
|
||||
|
||||
One JSON line per row, to $HUNT_LOCKS_TRACE (one file per process), WRITTEN ONCE, at process exit (atexit): during the run every row is only
|
||||
appended to a list in memory, there is no file open, no write and no thread of the hunt's own on the run. The rows of everything small are not written but are counted in a
|
||||
{"k": "totals"} row written at the end (and the rows of the messages of a chunk that carries /landed are all written). Times in rows are
|
||||
time.time() of the END of the span, "ms" its length (time.perf_counter()), so a row is [t - ms/1000, t] on the wall clock of the other stamps.
|
||||
Nothing here may break the engine: every hook swallows its own failure.
|
||||
"""
|
||||
import atexit
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
|
||||
LOCK_ROW_MS = 5.0 # a wait this long or longer is a row
|
||||
LST_ROW_MS = 0.5 # a listener call this long or longer is a row (all of them in a /landed chunk)
|
||||
MSG_ROW_MS = 1.0 # a message this long or longer is a row (all of them in a /landed chunk)
|
||||
GATE_ROW_MS = 1.0
|
||||
|
||||
_pc = time.perf_counter
|
||||
READERS: set = set()
|
||||
_TL = threading.local()
|
||||
ROWS: list = []
|
||||
TOTALS: dict = {} # item -> [n, sum ms, max ms]
|
||||
MSGS = {"n": 0, "wall_ms": 0.0, "cpu_ts_ms": 0.0, "cpu_cyc_ms": 0.0, "chunks": 0, "bytes": 0}
|
||||
_state = {"started": False, "cyc_per_s": None, "pid": os.getpid()}
|
||||
|
||||
|
||||
# ── cpu time of the calling thread ────────────────────────────────────────────────────────────────────────────────────────────────
|
||||
# time.thread_time() on Windows is GetThreadTimes: accounted per scheduler tick (~15.6 ms), too coarse for a message. The cycle counter
|
||||
# of the thread (QueryThreadCycleTime) is exact; its rate is measured once, in short slices, taking the best slice (a slice that was
|
||||
# not preempted), because the cycles tick only while the thread runs.
|
||||
_cycles = None
|
||||
if sys.platform == "win32":
|
||||
try:
|
||||
import ctypes
|
||||
_k32 = ctypes.windll.kernel32
|
||||
_k32.GetCurrentThread.restype = ctypes.c_void_p
|
||||
_k32.QueryThreadCycleTime.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_ulonglong)]
|
||||
_k32.QueryThreadCycleTime.restype = ctypes.c_int
|
||||
_cyc_box = threading.local()
|
||||
|
||||
def _cycles():
|
||||
box = getattr(_cyc_box, "v", None)
|
||||
if box is None:
|
||||
box = _cyc_box.v = ctypes.c_ulonglong()
|
||||
_k32.QueryThreadCycleTime(_k32.GetCurrentThread(), ctypes.byref(box))
|
||||
return box.value
|
||||
except Exception:
|
||||
_cycles = None
|
||||
|
||||
|
||||
def _calibrate():
|
||||
"""cycles per second of a thread that runs, from the best of 25 slices of about 3 ms of busy work. None if there is no counter."""
|
||||
if _cycles is None:
|
||||
return None
|
||||
best = 0.0
|
||||
for _ in range(25):
|
||||
c0, t0 = _cycles(), _pc()
|
||||
while _pc() - t0 < 0.003:
|
||||
pass
|
||||
c1, t1 = _cycles(), _pc()
|
||||
if t1 > t0 and c1 > c0:
|
||||
best = max(best, (c1 - c0) / (t1 - t0))
|
||||
return best or None
|
||||
|
||||
|
||||
def _cpu_ms_cycles(c0, c1):
|
||||
rate = _state["cyc_per_s"]
|
||||
if _cycles is None or not rate:
|
||||
return None
|
||||
return (c1 - c0) / rate * 1000.0
|
||||
|
||||
|
||||
def _mark_cpu():
|
||||
return (time.thread_time(), _cycles() if _cycles is not None else 0)
|
||||
|
||||
|
||||
# ── rows and totals ────────────────────────────────────────────────────────────────────────────────────────────────────────────────
|
||||
def _path():
|
||||
return os.environ.get("HUNT_LOCKS_TRACE")
|
||||
|
||||
|
||||
def _row(**r):
|
||||
if _path():
|
||||
ROWS.append(r)
|
||||
|
||||
|
||||
def _count(item, ms):
|
||||
t = TOTALS.get(item)
|
||||
if t is None:
|
||||
TOTALS[item] = [1, ms, ms]
|
||||
else:
|
||||
t[0] += 1
|
||||
t[1] += ms
|
||||
if ms > t[2]:
|
||||
t[2] = ms
|
||||
|
||||
|
||||
def flush(final=True):
|
||||
"""Once, at exit: every row, then the totals."""
|
||||
path = _path()
|
||||
if not path:
|
||||
return
|
||||
try:
|
||||
n = len(ROWS)
|
||||
batch = ROWS[:n]
|
||||
del ROWS[:n]
|
||||
lines = [json.dumps(r, default=str) for r in batch]
|
||||
if final:
|
||||
lines.append(json.dumps({"k": "totals", "pid": _state["pid"], "cyc_per_s": _state["cyc_per_s"], "msgs": MSGS,
|
||||
"items": {k: [v[0], round(v[1], 3), round(v[2], 3)] for k, v in TOTALS.items()}}))
|
||||
if lines:
|
||||
with open(path, "a", encoding="utf-8") as fh:
|
||||
fh.write("\n".join(lines) + "\n")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _start():
|
||||
"""From the thread that builds a Connection, never from the reader: the CPU calibration, and the one write at exit."""
|
||||
if _state["started"] or not _path():
|
||||
return
|
||||
_state["started"] = True
|
||||
try:
|
||||
_state["cyc_per_s"] = _calibrate()
|
||||
atexit.register(flush)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _on_reader():
|
||||
return threading.get_ident() in READERS
|
||||
|
||||
|
||||
def _ev():
|
||||
return getattr(_TL, "method", None)
|
||||
|
||||
|
||||
def _site(frame):
|
||||
try:
|
||||
return "%s:%d" % (os.path.basename(frame.f_code.co_filename), frame.f_lineno)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
# ── a lock that says who holds it and how long the reader waited for it ────────────────────────────────────────────────────────────
|
||||
class Timed:
|
||||
"""Stands in for a Lock, RLock or Condition (what they have of acquire / release / with / wait / notify). It delegates to the real one."""
|
||||
|
||||
def __init__(self, real, name, quiet=False):
|
||||
self._real = real
|
||||
self._name = name
|
||||
self._quiet = quiet
|
||||
self._depth = 0
|
||||
self.owner_name = None
|
||||
self.owner_t = 0.0
|
||||
self.owner_site = None
|
||||
|
||||
# who holds it now (read without a lock: a hint, and said so)
|
||||
def _snap(self):
|
||||
n = self.owner_name
|
||||
if n is None:
|
||||
return None
|
||||
return (n, self.owner_t, self.owner_site)
|
||||
|
||||
def _mark(self, frame):
|
||||
self._depth += 1
|
||||
self.owner_name = threading.current_thread().name
|
||||
self.owner_t = _pc()
|
||||
self.owner_site = _site(frame)
|
||||
|
||||
def _waited(self, kind, ms, snap, got=True):
|
||||
"""Called on the reader only. The events gate (quiet) is timed by gate_end instead."""
|
||||
if self._quiet:
|
||||
return
|
||||
_TL.lock_ms = getattr(_TL, "lock_ms", 0.0) + ms
|
||||
_count("%s:%s" % (kind, self._name), ms)
|
||||
if ms >= LOCK_ROW_MS and not self._quiet:
|
||||
held_ms = None
|
||||
if snap is not None:
|
||||
held_ms = round((_pc() - snap[1]) * 1000, 1)
|
||||
_row(k="lock", op=kind, name=self._name, ms=round(ms, 3), t=round(time.time(), 4), ev=_ev(), got=got,
|
||||
holder=snap[0] if snap else None, held_at=snap[2] if snap else None, held_so_far_ms=held_ms)
|
||||
|
||||
def acquire(self, *args, **kw):
|
||||
frame = sys._getframe(1)
|
||||
return self._acq(args, kw, frame)
|
||||
|
||||
def _acq(self, args, kw, frame):
|
||||
try:
|
||||
reader = threading.get_ident() in READERS
|
||||
except Exception:
|
||||
reader = False
|
||||
if reader:
|
||||
snap = self._snap()
|
||||
t0 = _pc()
|
||||
ok = self._real.acquire(*args, **kw)
|
||||
ms = (_pc() - t0) * 1000.0
|
||||
if ok:
|
||||
self._mark(frame)
|
||||
try:
|
||||
self._waited("lock", ms, snap, ok)
|
||||
except Exception:
|
||||
pass
|
||||
return ok
|
||||
ok = self._real.acquire(*args, **kw)
|
||||
if ok:
|
||||
self._mark(frame)
|
||||
return ok
|
||||
|
||||
def release(self):
|
||||
if self._depth > 0:
|
||||
self._depth -= 1
|
||||
if self._depth == 0:
|
||||
self.owner_name = None
|
||||
return self._real.release()
|
||||
|
||||
def __enter__(self):
|
||||
self._acq((), {}, sys._getframe(1))
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc):
|
||||
self.release()
|
||||
return None
|
||||
|
||||
def locked(self):
|
||||
return self._real.locked()
|
||||
|
||||
def _is_owned(self):
|
||||
return self._real._is_owned()
|
||||
|
||||
# Condition
|
||||
def wait(self, timeout=None):
|
||||
depth = self._depth
|
||||
self._depth = 0
|
||||
self.owner_name = None
|
||||
reader = _on_reader()
|
||||
snap = None
|
||||
t0 = _pc()
|
||||
try:
|
||||
return self._real.wait(timeout)
|
||||
finally:
|
||||
ms = (_pc() - t0) * 1000.0
|
||||
self._depth = depth
|
||||
self.owner_name = threading.current_thread().name
|
||||
self.owner_t = _pc()
|
||||
self.owner_site = _site(sys._getframe(1))
|
||||
if reader:
|
||||
try:
|
||||
# a wait is a pause the caller asked for; it is counted apart, and not into the lock waits of the message
|
||||
_count("wait:%s" % self._name, ms)
|
||||
if ms >= LOCK_ROW_MS and not self._quiet:
|
||||
_row(k="lock", op="wait", name=self._name, ms=round(ms, 3), t=round(time.time(), 4), ev=_ev(), got=True,
|
||||
holder=snap, held_at=None, held_so_far_ms=None)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def wait_for(self, predicate, timeout=None):
|
||||
endtime = None
|
||||
waittime = timeout
|
||||
result = predicate()
|
||||
while not result:
|
||||
if waittime is not None:
|
||||
if endtime is None:
|
||||
endtime = time.monotonic() + waittime
|
||||
else:
|
||||
waittime = endtime - time.monotonic()
|
||||
if waittime <= 0:
|
||||
break
|
||||
self.wait(waittime)
|
||||
result = predicate()
|
||||
return result
|
||||
|
||||
def notify(self, n=1):
|
||||
return self._real.notify(n)
|
||||
|
||||
def notify_all(self):
|
||||
return self._real.notify_all()
|
||||
|
||||
notifyAll = notify_all
|
||||
|
||||
def __getattr__(self, name):
|
||||
return getattr(self._real, name)
|
||||
|
||||
|
||||
def timed(real, name, quiet=False):
|
||||
if isinstance(real, Timed):
|
||||
return real
|
||||
return Timed(real, name, quiet)
|
||||
|
||||
|
||||
def hook_class(cls, names, prefix=""):
|
||||
"""After cls.__init__, each attribute of `names` that exists on the instance is replaced by a Timed over the real object."""
|
||||
original = cls.__init__
|
||||
if getattr(original, "_hunt_wrapped", False):
|
||||
return
|
||||
|
||||
def __init__(self, *a, **k):
|
||||
original(self, *a, **k)
|
||||
try:
|
||||
for n in names:
|
||||
v = self.__dict__.get(n)
|
||||
if v is not None and not isinstance(v, Timed):
|
||||
self.__dict__[n] = Timed(v, prefix + n)
|
||||
except Exception:
|
||||
pass
|
||||
__init__._hunt_wrapped = True
|
||||
__init__.__qualname__ = original.__qualname__
|
||||
cls.__init__ = __init__
|
||||
|
||||
|
||||
def timed_fn(fn, name):
|
||||
"""A function whose duration, on the reader, is counted as `name` (a row from 1 ms)."""
|
||||
def wrapper(*a, **k):
|
||||
if not _on_reader():
|
||||
return fn(*a, **k)
|
||||
t0 = _pc()
|
||||
try:
|
||||
return fn(*a, **k)
|
||||
finally:
|
||||
ms = (_pc() - t0) * 1000.0
|
||||
_count(name, ms)
|
||||
if ms >= 1.0:
|
||||
_row(k="io", name=name, ms=round(ms, 3), t=round(time.time(), 4), ev=_ev())
|
||||
return wrapper
|
||||
|
||||
|
||||
# ── the connection ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────
|
||||
def _listener_name(fn):
|
||||
try:
|
||||
owner = getattr(fn, "__self__", None)
|
||||
q = getattr(fn, "__qualname__", None) or getattr(fn, "__name__", None) or repr(fn)
|
||||
if owner is not None and "." not in q:
|
||||
q = "%s.%s" % (type(owner).__name__, q)
|
||||
return q
|
||||
except Exception:
|
||||
return "?"
|
||||
|
||||
|
||||
def _core_dispatch_event(self, method, params, session):
|
||||
"""Connection.dispatch_event with each listener timed on the reader. Same loop as the core's."""
|
||||
self.delivered += 1
|
||||
with self._listeners_lock:
|
||||
subscribers = list(self._listeners)
|
||||
reader = _on_reader()
|
||||
if reader:
|
||||
_TL.method = method
|
||||
verbose = getattr(_TL, "verbose", False)
|
||||
for fn in subscribers:
|
||||
if reader:
|
||||
t0 = _pc()
|
||||
u0, c0 = _mark_cpu()
|
||||
try:
|
||||
fn(method, params, session)
|
||||
except Exception as failure:
|
||||
if len(self.handler_errors) < 32:
|
||||
self.handler_errors.append("%s: %s" % (method, failure))
|
||||
if reader:
|
||||
try:
|
||||
ms = (_pc() - t0) * 1000.0
|
||||
u1, c1 = _mark_cpu()
|
||||
name = _listener_name(fn)
|
||||
_count("lst:" + name, ms)
|
||||
_TL.lst_ms = getattr(_TL, "lst_ms", 0.0) + ms
|
||||
if ms >= LST_ROW_MS or verbose:
|
||||
cyc = _cpu_ms_cycles(c0, c1)
|
||||
_row(k="lst", name=name, ev=method, ms=round(ms, 3), t=round(time.time(), 4),
|
||||
cpu_ts=round((u1 - u0) * 1000, 3), cpu_cyc=None if cyc is None else round(cyc, 3))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _wrap_deliver(orig):
|
||||
def _deliver(self, raw):
|
||||
if not _on_reader():
|
||||
return orig(self, raw)
|
||||
_TL.lock_ms = 0.0
|
||||
_TL.gate_ms = 0.0
|
||||
_TL.lst_ms = 0.0
|
||||
_TL.method = None
|
||||
t0 = _pc()
|
||||
u0, c0 = _mark_cpu()
|
||||
try:
|
||||
return orig(self, raw)
|
||||
finally:
|
||||
try:
|
||||
wall = (_pc() - t0) * 1000.0
|
||||
u1, c1 = _mark_cpu()
|
||||
cpu_ts = (u1 - u0) * 1000.0
|
||||
cyc = _cpu_ms_cycles(c0, c1)
|
||||
MSGS["n"] += 1
|
||||
MSGS["wall_ms"] += wall
|
||||
MSGS["cpu_ts_ms"] += cpu_ts
|
||||
if cyc is not None:
|
||||
MSGS["cpu_cyc_ms"] += cyc
|
||||
landed = b"/landed" in raw and b"requestWillBeSent" in raw
|
||||
if wall >= MSG_ROW_MS or landed or getattr(_TL, "verbose", False):
|
||||
_row(k="msg", t=round(time.time(), 4), ms=round(wall, 3), cpu_ts=round(cpu_ts, 3),
|
||||
cpu_cyc=None if cyc is None else round(cyc, 3), lock=round(_TL.lock_ms, 3), gate=round(_TL.gate_ms, 3),
|
||||
lst=round(_TL.lst_ms, 3), ev=_ev(), landed=landed, n=len(raw))
|
||||
except Exception:
|
||||
pass
|
||||
return _deliver
|
||||
|
||||
|
||||
def chunk_begin():
|
||||
return _pc()
|
||||
|
||||
|
||||
def on_chunk(chunk, t_begin):
|
||||
"""In _read_loop, right after the pipe read (and the older stamp of /landed): every message of a chunk with /landed is written."""
|
||||
try:
|
||||
if not _on_reader():
|
||||
READERS.add(threading.get_ident())
|
||||
MSGS["chunks"] += 1
|
||||
MSGS["bytes"] += len(chunk)
|
||||
landed = b"requestWillBeSent" in chunk and b"/landed" in chunk
|
||||
_TL.verbose = landed
|
||||
if landed:
|
||||
io_ms = (_pc() - t_begin) * 1000.0
|
||||
_count("hunt_pipe_stamp", io_ms)
|
||||
_row(k="chunk", t=round(time.time(), 4), n=len(chunk), stamp_ms=round(io_ms, 3))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def gate_begin():
|
||||
return _pc()
|
||||
|
||||
|
||||
def gate_end(t0, gate, got, waiting, snap=None):
|
||||
"""In gated_dispatch, after `gate.acquire`: the reader's wait for the events gate."""
|
||||
try:
|
||||
if not _on_reader():
|
||||
return
|
||||
ms = (_pc() - t0) * 1000.0
|
||||
_TL.gate_ms = getattr(_TL, "gate_ms", 0.0) + ms
|
||||
_count("gate", ms)
|
||||
if ms >= GATE_ROW_MS:
|
||||
holder = snap
|
||||
_row(k="gate", t=round(time.time(), 4), ms=round(ms, 3), ev=_ev(), got=bool(got), waiting=bool(waiting),
|
||||
holder=holder[0] if holder else None, held_at=holder[2] if holder else None,
|
||||
held_so_far_ms=round((t0 - holder[1]) * 1000, 1) if holder else None)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def gate_snap(gate):
|
||||
try:
|
||||
return gate._snap()
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def hook_connection(cls):
|
||||
"""Called at the end of invisible_core.juggler.connection with the Connection class."""
|
||||
cls.dispatch_event = _core_dispatch_event
|
||||
cls._deliver = _wrap_deliver(cls._deliver)
|
||||
original = cls.__init__
|
||||
|
||||
def __init__(self, *a, **k):
|
||||
original(self, *a, **k)
|
||||
try:
|
||||
for n in ("_lock", "_write_lock", "_listeners_lock"):
|
||||
v = self.__dict__.get(n)
|
||||
if v is not None and not isinstance(v, Timed):
|
||||
self.__dict__[n] = Timed(v, "Connection." + n)
|
||||
READERS.add(self._reader.ident)
|
||||
_start()
|
||||
except Exception:
|
||||
pass
|
||||
__init__._hunt_wrapped = True
|
||||
cls.__init__ = __init__
|
||||
@@ -0,0 +1,366 @@
|
||||
"""HUNT SCAFFOLDING, NEVER MERGED: the step summary of windows-flakes-locks-hunt.yml.
|
||||
|
||||
Usage: python scripts/hunt_locks_summary.py <label> <evidence dir> [threshold ms, default 100]
|
||||
|
||||
Per process of the arm `new` it reads
|
||||
evidence/netidle_new_<round>_<proc>.log HUNT-ROW lines (the server's time of /landed, landed_t),
|
||||
evidence/pipe_new_<round>_<proc>.txt when the core's pipe reader read the chunk that carries /landed,
|
||||
evidence/lc_new_<round>_<proc>.jsonl when the lifecycle applied Network.requestWillBeSent of /landed,
|
||||
evidence/locks_new_<round>_<proc>.jsonl the rows of scripts/hunt_locks_runtime.py (listeners, locks, gate, messages, totals).
|
||||
For every /landed whose pipe -> lifecycle is over the threshold it cuts the interval [pipe, lifecycle] into the items below and prints markdown:
|
||||
(a) the listener calls of Connection.dispatch_event (the part of a listener that is not a lock or gate wait is its "own" time),
|
||||
(b) the wait of gated_dispatch on the events gate (with the holder it saw when it began to wait),
|
||||
(c) the waits of the reader on every lock / condition that was timed (rows of 5 ms or more),
|
||||
(d) per message, wall against CPU: wall - cpu - lock waits - gate = off the CPU (the GIL, or the OS not running the thread),
|
||||
and the rest: time outside any _deliver (buffer, split) and inside a message but outside a listener (decode).
|
||||
Then the totals per item over every process, and the longest stalls of the reader whether or not they sit in a delayed interval.
|
||||
The stamps and rows are lists in memory written once at process exit, so a process that did not exit normally has no stamp file.
|
||||
|
||||
FIRST of all, the CONTROL: evidence/control_<arm>_<round>_<proc>.log (arms old and new, run with no patcher at all) gives, per arm, the
|
||||
misses of networkidle (not on /landed when goto returned) split into "defect" (the server got /landed BEFORE goto returned) and
|
||||
"not yet asked" (the page had not asked for it yet), from the server times in the HUNT-ROW lines only.
|
||||
"""
|
||||
import glob
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
import hunt_noreader_summary as base # noqa: E402
|
||||
|
||||
ARM = "new"
|
||||
|
||||
|
||||
def read_locks(path):
|
||||
rows = []
|
||||
if os.path.exists(path):
|
||||
with open(path, errors="replace") as f:
|
||||
for line in f:
|
||||
try:
|
||||
rows.append(json.loads(line))
|
||||
except ValueError:
|
||||
pass
|
||||
return rows
|
||||
|
||||
|
||||
def ov(row, a, b):
|
||||
"""Seconds of the row's span [t - ms, t] inside [a, b]."""
|
||||
end = row["t"]
|
||||
start = end - row["ms"] / 1000.0
|
||||
return max(0.0, min(end, b) - max(start, a))
|
||||
|
||||
|
||||
def cpu_of(row):
|
||||
c = row.get("cpu_cyc")
|
||||
return c if c is not None else (row.get("cpu_ts") or 0.0)
|
||||
|
||||
|
||||
def breakdown(rows, p, l):
|
||||
"""The interval [p, l] cut into items. Everything in ms."""
|
||||
iv = (l - p) * 1000.0
|
||||
out = {"interval": iv, "gate": 0.0, "lock": 0.0, "cpu": 0.0, "off": 0.0, "outside": 0.0, "msg_other": 0.0, "stamp_io": 0.0, "lc_io": 0.0,
|
||||
"locks": {}, "listeners": {}, "gates": [], "io": {}}
|
||||
in_msgs = 0.0
|
||||
for r in rows:
|
||||
k = r["k"]
|
||||
if k == "totals" or "t" not in r or r.get("ms") is None and k != "chunk":
|
||||
continue
|
||||
if k == "msg":
|
||||
o = ov(r, p, l)
|
||||
if o <= 0:
|
||||
continue
|
||||
frac = o / (r["ms"] / 1000.0)
|
||||
wall = r["ms"]
|
||||
cpu = cpu_of(r)
|
||||
off = max(0.0, wall - cpu - r["lock"] - r["gate"])
|
||||
in_msgs += o * 1000.0
|
||||
out["gate"] += frac * r["gate"]
|
||||
out["lock"] += frac * r["lock"]
|
||||
out["cpu"] += frac * min(cpu, wall)
|
||||
out["off"] += frac * off
|
||||
out["msg_other"] += frac * max(0.0, wall - r["lst"])
|
||||
elif k == "lock":
|
||||
o = ov(r, p, l) * 1000.0
|
||||
if o > 0:
|
||||
d = out["locks"].setdefault((r["op"], r["name"]), {"ms": 0.0, "n": 0, "holders": {}})
|
||||
d["ms"] += o
|
||||
d["n"] += 1
|
||||
h = "%s at %s" % (r.get("holder"), r.get("held_at"))
|
||||
d["holders"][h] = d["holders"].get(h, 0) + 1
|
||||
elif k == "gate":
|
||||
o = ov(r, p, l) * 1000.0
|
||||
if o > 0:
|
||||
out["gates"].append((o, r))
|
||||
elif k == "io":
|
||||
o = ov(r, p, l) * 1000.0
|
||||
if o > 0:
|
||||
out["io"][r["name"]] = out["io"].get(r["name"], 0.0) + o
|
||||
elif k == "chunk":
|
||||
# the stamp's own file write, which sits between the pipe read and the first message
|
||||
out["stamp_io"] += r.get("stamp_ms", 0.0)
|
||||
# listeners, with what is nested in them (a lock or gate wait or the stamp write inside the call) taken out
|
||||
nested = [r for r in rows if r["k"] in ("lock", "gate", "io") and "t" in r and r.get("ms") is not None]
|
||||
for r in rows:
|
||||
if r["k"] != "lst":
|
||||
continue
|
||||
o = ov(r, p, l)
|
||||
if o <= 0:
|
||||
continue
|
||||
a = max(r["t"] - r["ms"] / 1000.0, p)
|
||||
b = min(r["t"], l)
|
||||
inner = sum(ov(n, a, b) for n in nested if n["t"] >= a and n["t"] - n["ms"] / 1000.0 <= b) * 1000.0
|
||||
own = max(0.0, o * 1000.0 - inner)
|
||||
frac = o / (r["ms"] / 1000.0)
|
||||
d = out["listeners"].setdefault((r["name"]), {"own": 0.0, "total": 0.0, "n": 0, "cpu": 0.0, "events": {}})
|
||||
d["own"] += own
|
||||
d["total"] += o * 1000.0
|
||||
d["n"] += 1
|
||||
d["cpu"] += frac * cpu_of(r)
|
||||
d["events"][r["ev"]] = d["events"].get(r["ev"], 0) + 1
|
||||
out["outside"] = max(0.0, iv - in_msgs)
|
||||
out["lc_io"] = out["io"].get("hunt_lc_write", 0.0)
|
||||
return out
|
||||
|
||||
|
||||
def dominant(b):
|
||||
cand = {}
|
||||
if b["gate"] > 0:
|
||||
cand["gate"] = b["gate"]
|
||||
for (op, name), d in b["locks"].items():
|
||||
cand["%s %s" % (op, name)] = d["ms"]
|
||||
for name, d in b["listeners"].items():
|
||||
cand["listener %s (own)" % name] = d["own"]
|
||||
cand["inside a message, outside a listener (decode, ends_waits)"] = max(0.0, b["msg_other"] - sum(d["total"] for d in b["listeners"].values()))
|
||||
cand["outside any message (buffer, split, stamp write)"] = b["outside"]
|
||||
name = max(cand, key=lambda k: cand[k])
|
||||
return name, cand[name]
|
||||
|
||||
|
||||
def collect():
|
||||
out = []
|
||||
logs = sorted(glob.glob(os.path.join(EV, "netidle_%s_*.log" % ARM)))
|
||||
for log in logs:
|
||||
tag = os.path.basename(log)[len("netidle_"):-len(".log")]
|
||||
pipes = base.read_pipe(os.path.join(EV, "pipe_%s.txt" % tag))
|
||||
lcs = base.read_lc(os.path.join(EV, "lc_%s.jsonl" % tag))
|
||||
locks = read_locks(os.path.join(EV, "locks_%s.jsonl" % tag))
|
||||
out.append({"tag": tag, "rows": base.read_rows(log), "pipes": pipes, "lcs": lcs, "locks": locks})
|
||||
return out
|
||||
|
||||
|
||||
def miss_counts(prefix, arm):
|
||||
"""(rows, misses, defect, not yet asked, goto errors, processes with no row, processes, misses by path) of control_<arm>_*.log."""
|
||||
rows = []
|
||||
dead = 0
|
||||
logs = sorted(glob.glob(os.path.join(EV, "%s_%s_*.log" % (prefix, arm))))
|
||||
for log in logs:
|
||||
got = base.read_rows(log)
|
||||
if not got:
|
||||
dead += 1
|
||||
rows.extend(got)
|
||||
miss = [r for r in rows if not r["landed_at_return"]]
|
||||
defect = [r for r in miss if r.get("landed_t") is not None and r["landed_t"] < r["t1"]]
|
||||
by = {}
|
||||
for r in miss:
|
||||
by[r["path"]] = by.get(r["path"], 0) + 1
|
||||
return len(rows), len(miss), len(defect), len(miss) - len(defect), sum(r["error"] is not None for r in rows), dead, len(logs), by
|
||||
|
||||
|
||||
def control():
|
||||
print("### CONTROL, no patcher at all: networkidle misses, old against new")
|
||||
print()
|
||||
print("Fifteen rounds x four processes per arm, the order of the arms alternating, from the HUNT-ROW lines of `hunt_netidle.py` only. A miss is "
|
||||
"a row that was not on /landed when goto returned: a **defect** when the server got /landed before goto returned, **not yet asked** when "
|
||||
"the page had not asked for it yet.")
|
||||
print()
|
||||
print("| arm | misses | defect | not yet asked | rows | goto errors | processes with no row | misses by path |")
|
||||
print("|---|---|---|---|---|---|---|---|")
|
||||
for arm in ("old", "new"):
|
||||
n, m, d, ny, err, dead, nlogs, by = miss_counts("control", arm)
|
||||
print("| %s | %d | %d | %d | %d | %d | %d of %d | %s |" % (
|
||||
arm, m, d, ny, n, err, dead, nlogs, ", ".join("%s %d" % kv for kv in sorted(by.items())) or "-"))
|
||||
n, m, d, ny, err, dead, nlogs, by = miss_counts("netidle", ARM)
|
||||
print("| %s, stamped (the patched pass, for comparison only) | %d | %d | %d | %d | %d | %d of %d | %s |" % (
|
||||
ARM, m, d, ny, n, err, dead, nlogs, ", ".join("%s %d" % kv for kv in sorted(by.items())) or "-"))
|
||||
print()
|
||||
print("Expected 1200 rows per arm (4 processes x 15 rounds x 20 rows).")
|
||||
print()
|
||||
|
||||
|
||||
def main(label, threshold):
|
||||
procs = collect()
|
||||
print("## %s" % label)
|
||||
print()
|
||||
control()
|
||||
print("## The stamped pass: where the time goes between the pipe and the lifecycle")
|
||||
print()
|
||||
n_rows = n_landed = n_both = 0
|
||||
delayed = []
|
||||
p2ls = []
|
||||
for pr in procs:
|
||||
for r in pr["rows"]:
|
||||
n_rows += 1
|
||||
srv = r.get("landed_t")
|
||||
if srv is None:
|
||||
continue
|
||||
n_landed += 1
|
||||
p = base.nearest(pr["pipes"], srv)
|
||||
l = base.nearest(pr["lcs"], p) if p is not None else None
|
||||
if p is None or l is None:
|
||||
continue
|
||||
n_both += 1
|
||||
p2l = (l - p) * 1000.0
|
||||
p2ls.append(p2l)
|
||||
if p2l > threshold:
|
||||
delayed.append((pr, r, p, l, p2l))
|
||||
with_totals = sum(any(x["k"] == "totals" for x in pr["locks"]) for pr in procs)
|
||||
print("Arm `%s`: %d processes (%d with a totals row, %d with lock rows), %d rows, %d with /landed on the server, %d with the pipe and the lifecycle stamp, "
|
||||
"**%d with pipe -> lifecycle over %g ms**." % (
|
||||
ARM, len(procs), with_totals, sum(bool(pr["locks"]) for pr in procs), n_rows, n_landed, n_both, len(delayed), threshold))
|
||||
print()
|
||||
print("pipe -> lifecycle over every row: p50 %s ms, p95 %s ms, max %s ms." % (
|
||||
base.fmt(base.pct(p2ls, 0.5)), base.fmt(base.pct(p2ls, 0.95)), base.fmt(max(p2ls) if p2ls else None)))
|
||||
|
||||
# ── the delayed events ────────────────────────────────────────────────────────────────────────────────────────────────────────
|
||||
print()
|
||||
print("### every /landed whose pipe -> lifecycle is over %g ms, the interval cut by item (ms)" % threshold)
|
||||
print()
|
||||
print("Resource view, a partition of the messages the reader handled inside the interval: gate (b) + locks (c) + on CPU + off CPU (d) = time inside "
|
||||
"messages; `outside` is the rest of the interval (no `_deliver` running). `off CPU` is wall - cpu - lock waits - gate, i.e. the GIL or the OS "
|
||||
"not running the thread.")
|
||||
print()
|
||||
hist = {}
|
||||
details = []
|
||||
if not delayed:
|
||||
print("None.")
|
||||
else:
|
||||
print("| process | path #round | goto ms | pipe -> lifecycle | gate | locks | on CPU | off CPU | outside | dominant item (ms) |")
|
||||
print("|---|---|---|---|---|---|---|---|---|---|")
|
||||
for pr, r, p, l, p2l in delayed:
|
||||
b = breakdown(pr["locks"], p, l)
|
||||
name, ms = dominant(b)
|
||||
hist[name] = hist.get(name, 0) + 1
|
||||
details.append((pr, r, b))
|
||||
print("| %s | %s #%d | %d | %.0f | %.0f | %.0f | %.0f | %.0f | %.0f | %s (%.0f) |" % (
|
||||
pr["tag"], r["path"], r["round"], r["goto_ms"], p2l, b["gate"], b["lock"], b["cpu"], b["off"], b["outside"], name, ms))
|
||||
print()
|
||||
print("### dominant item over the delayed events")
|
||||
print()
|
||||
print("| item | delayed events |")
|
||||
print("|---|---|")
|
||||
for k, v in sorted(hist.items(), key=lambda kv: -kv[1]):
|
||||
print("| %s | %d |" % (k, v))
|
||||
print()
|
||||
print("### the delayed events one by one (the first 25): what ran on the reader in the interval, items of 1 ms or more")
|
||||
for pr, r, b in details[:25]:
|
||||
print()
|
||||
print("**%s, %s #%d**: interval %.0f ms; gate %.0f, locks %.0f, on CPU %.0f, off CPU %.0f, outside any message %.0f, "
|
||||
"decode/ends_waits %.0f, lifecycle stamp write %.1f, pipe stamp write %.1f" % (
|
||||
pr["tag"], r["path"], r["round"], b["interval"], b["gate"], b["lock"], b["cpu"], b["off"], b["outside"],
|
||||
max(0.0, b["msg_other"] - sum(d["total"] for d in b["listeners"].values())), b["lc_io"], b["stamp_io"]))
|
||||
items = []
|
||||
for (op, name), d in b["locks"].items():
|
||||
holders = ", ".join("%s x%d" % (h, c) for h, c in sorted(d["holders"].items(), key=lambda kv: -kv[1])[:2])
|
||||
items.append((d["ms"], "- %s `%s`: %.1f ms in %d wait(s); held by %s" % (op, name, d["ms"], d["n"], holders)))
|
||||
for name, d in b["listeners"].items():
|
||||
ev = ", ".join("%s x%d" % kv for kv in sorted(d["events"].items(), key=lambda kv: -kv[1])[:3])
|
||||
items.append((d["total"], "- listener `%s`: %.1f ms in %d call(s) (own %.1f, cpu %.1f); events: %s" % (
|
||||
name, d["total"], d["n"], d["own"], d["cpu"], ev)))
|
||||
for o, g in b["gates"]:
|
||||
items.append((o, "- gate: %.1f ms, got=%s, holder when it began to wait: %s at %s (held %s ms so far); event %s" % (
|
||||
o, g.get("got"), g.get("holder"), g.get("held_at"), g.get("held_so_far_ms"), g.get("ev"))))
|
||||
for nme, o in b["io"].items():
|
||||
items.append((o, "- instrumentation `%s`: %.1f ms" % (nme, o)))
|
||||
for _, line in sorted(items, key=lambda it: -it[0]):
|
||||
print(line)
|
||||
if not items:
|
||||
print("- nothing of 1 ms or more is on the reader in this interval")
|
||||
if len(details) > 25:
|
||||
print()
|
||||
print("(%d more delayed events not listed)" % (len(details) - 25))
|
||||
|
||||
# ── totals per item ───────────────────────────────────────────────────────────────────────────────────────────────────────────
|
||||
items = {}
|
||||
msgs = {"n": 0, "wall_ms": 0.0, "cpu_ts_ms": 0.0, "cpu_cyc_ms": 0.0, "chunks": 0, "bytes": 0}
|
||||
for pr in procs:
|
||||
for r in pr["locks"]:
|
||||
if r["k"] != "totals":
|
||||
continue
|
||||
for k, v in r["items"].items():
|
||||
d = items.setdefault(k, [0, 0.0, 0.0])
|
||||
d[0] += v[0]
|
||||
d[1] += v[1]
|
||||
d[2] = max(d[2], v[2])
|
||||
for k in msgs:
|
||||
msgs[k] += r["msgs"].get(k, 0)
|
||||
rowcount = {}
|
||||
for pr in procs:
|
||||
for r in pr["locks"]:
|
||||
if r["k"] in ("lock", "gate", "io") and r.get("ms") is not None:
|
||||
key = {"lock": "%s:%s" % ("wait" if r.get("op") == "wait" else "lock", r.get("name")), "gate": "gate", "io": r.get("name")}[r["k"]]
|
||||
rowcount[key] = rowcount.get(key, 0) + 1
|
||||
print()
|
||||
print("### totals per item, every process of the arm, every message the reader handled (ms)")
|
||||
print()
|
||||
print("`lock:` = a wait to take it, `wait:` = a Condition.wait on the reader (a pause the code asked for), `lst:` = a listener call (it holds the lock "
|
||||
"waits and the gate wait inside it), `gate` = gated_dispatch's wait, `hunt_pipe_stamp` = the pipe stamp's append to a list in memory.")
|
||||
print()
|
||||
print("| item | n | sum | mean | max | rows of the wait kind (5 ms+; gate, io 1 ms+) |")
|
||||
print("|---|---|---|---|---|---|")
|
||||
for k, (n, s, mx) in sorted(items.items(), key=lambda kv: -kv[1][1])[:45]:
|
||||
print("| %s | %d | %.1f | %.3f | %.1f | %s |" % (k, n, s, s / max(n, 1), mx, rowcount.get(k, "-")))
|
||||
print()
|
||||
print("### off the CPU, per message (d)")
|
||||
print()
|
||||
cpu_total = msgs["cpu_cyc_ms"] if msgs["cpu_cyc_ms"] else msgs["cpu_ts_ms"]
|
||||
print("Messages handled: %d (%d chunks, %d bytes). Wall in `_deliver`: %.1f ms; CPU of the reader thread: %.1f ms by the cycle counter (%.1f ms by "
|
||||
"time.thread_time, ticks of about 15.6 ms on Windows). CPU / wall = %.3f." % (
|
||||
msgs["n"], msgs["chunks"], msgs["bytes"], msgs["wall_ms"], msgs["cpu_cyc_ms"], msgs["cpu_ts_ms"],
|
||||
(cpu_total / msgs["wall_ms"]) if msgs["wall_ms"] else 0.0))
|
||||
stalls = []
|
||||
off_big = 0
|
||||
for pr in procs:
|
||||
for r in pr["locks"]:
|
||||
if r["k"] == "msg":
|
||||
off = max(0.0, r["ms"] - cpu_of(r) - r["lock"] - r["gate"])
|
||||
if off >= 5.0:
|
||||
off_big += 1
|
||||
stalls.append((r["ms"], off, pr["tag"], r))
|
||||
print()
|
||||
print("Messages of 1 ms or more written as rows: %d; of them %d spent 5 ms or more off the CPU outside lock and gate waits." % (len(stalls), off_big))
|
||||
print()
|
||||
print("### the longest messages of the reader (any time, delayed or not)")
|
||||
print()
|
||||
print("| process | message ms | event | on CPU | locks | gate | listeners | off CPU | landed |")
|
||||
print("|---|---|---|---|---|---|---|---|---|")
|
||||
for ms, off, tag, r in sorted(stalls, key=lambda x: -x[0])[:20]:
|
||||
print("| %s | %.1f | %s | %.1f | %.1f | %.1f | %.1f | %.1f | %s |" % (tag, ms, r.get("ev"), min(cpu_of(r), ms), r["lock"], r["gate"], r["lst"], off, r["landed"]))
|
||||
print()
|
||||
print("### every lock wait of 5 ms or more, by lock (any time)")
|
||||
print()
|
||||
by = {}
|
||||
for pr in procs:
|
||||
for r in pr["locks"]:
|
||||
if r["k"] == "lock":
|
||||
d = by.setdefault((r["op"], r["name"]), {"n": 0, "ms": 0.0, "max": 0.0, "holders": {}})
|
||||
d["n"] += 1
|
||||
d["ms"] += r["ms"]
|
||||
d["max"] = max(d["max"], r["ms"])
|
||||
h = "%s at %s" % (r.get("holder"), r.get("held_at"))
|
||||
d["holders"][h] = d["holders"].get(h, 0) + 1
|
||||
if not by:
|
||||
print("None: the reader never waited 5 ms or more for a lock.")
|
||||
else:
|
||||
print("| op | lock | waits | sum ms | max ms | holder when the wait began |")
|
||||
print("|---|---|---|---|---|---|")
|
||||
for (op, name), d in sorted(by.items(), key=lambda kv: -kv[1]["ms"]):
|
||||
print("| %s | %s | %d | %.0f | %.0f | %s |" % (op, name, d["n"], d["ms"], d["max"],
|
||||
", ".join("%s x%d" % (h, c) for h, c in sorted(d["holders"].items(), key=lambda kv: -kv[1])[:3])))
|
||||
print()
|
||||
print("The instrumentation runs on the reader too, but it only appends to lists in memory (nothing is opened or written until the process exits); "
|
||||
"compare the stamped pass's misses with the control's above to see whether it changes the result.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
EV = sys.argv[2]
|
||||
main(sys.argv[1], float(sys.argv[3]) if len(sys.argv) > 3 else 100.0)
|
||||
@@ -0,0 +1,82 @@
|
||||
"""HUNT SCAFFOLDING, NEVER MERGED: goto(networkidle) on pages that replace themselves after load, ours against stock Playwright Firefox.
|
||||
|
||||
Usage: python scripts/hunt_netidle.py ours|stock [binary]. Prints one JSON line per round: the URL when goto returned, how long goto took, and
|
||||
when the server saw the request of /landed relative to goto's return (negative = the replacement was already on the wire when goto said idle).
|
||||
"""
|
||||
import http.server
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
|
||||
ENGINE = sys.argv[1]
|
||||
if len(sys.argv) > 3:
|
||||
os.environ["HUNT_LC_TRACE"] = sys.argv[3]
|
||||
if len(sys.argv) > 4:
|
||||
os.environ["HUNT_PIPE_TRACE"] = sys.argv[4]
|
||||
REQS = []
|
||||
|
||||
|
||||
def _page(ms, cross):
|
||||
target = "location.origin.replace('127.0.0.1','localhost')+'/landed'" if cross else "'/landed'"
|
||||
return ("<!doctype html><html><body><p id=p>first</p><script>addEventListener('load', () => setTimeout(() => "
|
||||
"location.replace(%s), %d))</script></body></html>" % (target, ms)).encode()
|
||||
|
||||
|
||||
PAGES = {"/landed": b"<!doctype html><html><body><p id=p>landed</p></body></html>"}
|
||||
for ms in (0, 50):
|
||||
PAGES["/r%d" % ms] = _page(ms, False)
|
||||
PAGES["/x%d" % ms] = _page(ms, True)
|
||||
|
||||
|
||||
class H(http.server.BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
REQS.append((time.time(), self.path))
|
||||
body = PAGES.get(self.path.split("?")[0], PAGES["/landed"])
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/html; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
|
||||
srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), H)
|
||||
srv.daemon_threads = True
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
site = "http://127.0.0.1:%d" % srv.server_address[1]
|
||||
|
||||
|
||||
def rounds(page, Error):
|
||||
for path in ("/r0", "/r50", "/x0", "/x50"):
|
||||
for i in range(5):
|
||||
t0 = time.time()
|
||||
err = None
|
||||
try:
|
||||
page.goto("%s%s?n=%d" % (site, path, i), wait_until="networkidle", timeout=15000)
|
||||
except Error as e:
|
||||
err = str(e).splitlines()[0][:100]
|
||||
t1 = time.time()
|
||||
url = page.url
|
||||
landed = [t for t, p in REQS if p.startswith("/landed") and t >= t0]
|
||||
print("HUNT-ROW " + json.dumps({
|
||||
"engine": ENGINE, "path": path, "round": i, "landed_at_return": url.endswith("/landed"), "goto_ms": round((t1 - t0) * 1000),
|
||||
"landed_request_ms_from_return": round((landed[0] - t1) * 1000) if landed else None, "error": err,
|
||||
"t0": round(t0, 4), "t1": round(t1, 4), "landed_t": round(landed[0], 4) if landed else None}), flush=True)
|
||||
|
||||
|
||||
if ENGINE == "stock":
|
||||
from playwright.sync_api import sync_playwright, Error
|
||||
with sync_playwright() as p:
|
||||
b = p.firefox.launch(headless=True)
|
||||
rounds(b.new_page(), Error)
|
||||
b.close()
|
||||
else:
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
from invisible_playwright.sync_api import Error
|
||||
with InvisiblePlaywright(seed=4321, binary_path=sys.argv[2], headless=True) as browser:
|
||||
rounds(browser.new_page(), Error)
|
||||
srv.shutdown()
|
||||
@@ -0,0 +1,162 @@
|
||||
"""HUNT SCAFFOLDING, NEVER MERGED: the step summary of windows-flakes-noreader-hunt.yml.
|
||||
|
||||
Usage: python scripts/hunt_noreader_summary.py <label> <evidence dir>
|
||||
|
||||
Per arm (old, new) and per process it reads evidence/netidle_<arm>_<round>_<proc>.log (HUNT-ROW json lines of scripts/hunt_netidle.py),
|
||||
evidence/pipe_<arm>_<round>_<proc>.txt (the time, seconds, the core's pipe reader read a chunk with the /landed request) and
|
||||
evidence/lc_<arm>_<round>_<proc>.jsonl (the lifecycle's events, Network.requestWillBeSent among them). For every row that has a /landed
|
||||
request on the server it takes the nearest pipe stamp and then the nearest lifecycle stamp of /landed, and prints markdown:
|
||||
- per arm the misses (not on /landed when goto returned) split into "defect" (the server got /landed BEFORE goto returned) and
|
||||
"not yet asked" (the page had not asked for /landed yet), with server->pipe and pipe->lifecycle in ms for each defect miss;
|
||||
- per arm p50 / p95 / max of server->pipe and pipe->lifecycle over every row of every round.
|
||||
"""
|
||||
import glob
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
ARMS = ("old", "new")
|
||||
NEAR = 3.0 # seconds: a stamp farther than this from the request it is matched to is not its stamp
|
||||
|
||||
|
||||
def read_rows(log):
|
||||
rows = []
|
||||
with open(log, errors="replace") as f:
|
||||
for line in f:
|
||||
if line.startswith("HUNT-ROW "):
|
||||
try:
|
||||
rows.append(json.loads(line[len("HUNT-ROW "):]))
|
||||
except ValueError:
|
||||
pass
|
||||
return rows
|
||||
|
||||
|
||||
def read_pipe(path):
|
||||
out = []
|
||||
if os.path.exists(path):
|
||||
with open(path, errors="replace") as f:
|
||||
for line in f:
|
||||
try:
|
||||
out.append(float(line.strip()))
|
||||
except ValueError:
|
||||
pass
|
||||
return out
|
||||
|
||||
|
||||
def read_lc(path):
|
||||
"""Times of the lifecycle's Network.requestWillBeSent events of /landed."""
|
||||
out = []
|
||||
if os.path.exists(path):
|
||||
with open(path, errors="replace") as f:
|
||||
for line in f:
|
||||
try:
|
||||
r = json.loads(line)
|
||||
except ValueError:
|
||||
continue
|
||||
if str(r.get("ev", "")).endswith("requestWillBeSent") and "/landed" in str(r.get("url") or ""):
|
||||
out.append(r["t"])
|
||||
return out
|
||||
|
||||
|
||||
def nearest(stamps, at):
|
||||
best = None
|
||||
for s in stamps:
|
||||
if abs(s - at) <= NEAR and (best is None or abs(s - at) < abs(best - at)):
|
||||
best = s
|
||||
return best
|
||||
|
||||
|
||||
def pct(vals, q):
|
||||
v = sorted(vals)
|
||||
if not v:
|
||||
return None
|
||||
return v[min(len(v) - 1, int(round(q * (len(v) - 1))))]
|
||||
|
||||
|
||||
def fmt(x):
|
||||
return "-" if x is None else "%.1f" % x
|
||||
|
||||
|
||||
def collect(ev, arm):
|
||||
"""Every row of the arm, with s2p (server -> pipe) and p2l (pipe -> lifecycle) in ms, None when a stamp is missing, and its miss kind."""
|
||||
out = []
|
||||
dead = 0
|
||||
logs = sorted(glob.glob(os.path.join(ev, "netidle_%s_*.log" % arm)))
|
||||
for log in logs:
|
||||
rows = read_rows(log)
|
||||
if not rows:
|
||||
dead += 1
|
||||
tag = os.path.basename(log)[len("netidle_"):-len(".log")]
|
||||
pipes = read_pipe(os.path.join(ev, "pipe_%s.txt" % tag))
|
||||
lcs = read_lc(os.path.join(ev, "lc_%s.jsonl" % tag))
|
||||
for r in rows:
|
||||
srv = r.get("landed_t")
|
||||
r["tag"] = tag
|
||||
r["s2p"] = r["p2l"] = None
|
||||
if srv is not None:
|
||||
p = nearest(pipes, srv)
|
||||
if p is not None:
|
||||
r["s2p"] = (p - srv) * 1000
|
||||
l = nearest(lcs, p)
|
||||
if l is not None:
|
||||
r["p2l"] = (l - p) * 1000
|
||||
r["miss"] = not r["landed_at_return"]
|
||||
r["kind"] = None
|
||||
if r["miss"]:
|
||||
r["kind"] = "defect" if (srv is not None and srv < r["t1"]) else "not yet asked"
|
||||
out.append(r)
|
||||
return out, dead, len(logs)
|
||||
|
||||
|
||||
def netidle(ev):
|
||||
data = {arm: collect(ev, arm) for arm in ARMS}
|
||||
print("### network idle rows: misses (not on /landed when goto returned) out of the rows made")
|
||||
print()
|
||||
print("A miss is a **defect** when the server got /landed before goto returned, **not yet asked** when the page had not asked for it yet.")
|
||||
print()
|
||||
print("| arm | misses | defect | not yet asked | rows | goto errors | processes with no row | misses by path |")
|
||||
print("|---|---|---|---|---|---|---|---|")
|
||||
for arm in ARMS:
|
||||
rows, dead, nlogs = data[arm]
|
||||
miss = [r for r in rows if r["miss"]]
|
||||
by = {}
|
||||
for r in miss:
|
||||
by[r["path"]] = by.get(r["path"], 0) + 1
|
||||
print("| %s | %d | %d | %d | %d | %d | %d of %d | %s |" % (
|
||||
arm, len(miss), sum(r["kind"] == "defect" for r in miss), sum(r["kind"] == "not yet asked" for r in miss), len(rows),
|
||||
sum(r["error"] is not None for r in rows), dead, nlogs, ", ".join("%s %d" % kv for kv in sorted(by.items())) or "-"))
|
||||
print()
|
||||
print("Expected 1200 rows per arm (4 processes x 15 rounds x 20 rows).")
|
||||
|
||||
print()
|
||||
print("### defect misses: server -> pipe and pipe -> lifecycle, ms")
|
||||
for arm in ARMS:
|
||||
defects = [r for r in data[arm][0] if r["kind"] == "defect"]
|
||||
print()
|
||||
print("**%s**: %d defect misses" % (arm, len(defects)))
|
||||
if defects:
|
||||
print()
|
||||
print("| process | path | goto ms | server -> pipe | pipe -> lifecycle |")
|
||||
print("|---|---|---|---|---|")
|
||||
for r in defects:
|
||||
print("| %s | %s #%d | %d | %s | %s |" % (r["tag"], r["path"], r["round"], r["goto_ms"], fmt(r["s2p"]), fmt(r["p2l"])))
|
||||
|
||||
print()
|
||||
print("### server -> pipe and pipe -> lifecycle over every row of every round, ms")
|
||||
print()
|
||||
print("| arm | step | rows with both stamps | p50 | p95 | max |")
|
||||
print("|---|---|---|---|---|---|")
|
||||
for arm in ARMS:
|
||||
rows = data[arm][0]
|
||||
for name, key in (("server -> pipe", "s2p"), ("pipe -> lifecycle", "p2l")):
|
||||
vals = [r[key] for r in rows if r[key] is not None]
|
||||
print("| %s | %s | %d | %s | %s | %s |" % (arm, name, len(vals), fmt(pct(vals, 0.5)), fmt(pct(vals, 0.95)), fmt(max(vals) if vals else None)))
|
||||
print()
|
||||
print("Rows without a /landed request on the server, or whose pipe or lifecycle stamp is missing, are left out of the percentiles.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
label, evidence = sys.argv[1], sys.argv[2]
|
||||
print("## %s" % label)
|
||||
print()
|
||||
netidle(evidence)
|
||||
@@ -0,0 +1,66 @@
|
||||
"""HUNT SCAFFOLDING, NEVER MERGED: patch the installed invisible_core lifecycle to trace what decides networkidle.
|
||||
|
||||
Every event the lifecycle applies (Page.* and Network.*) and every networkidle it gives is written as a JSON line, with time.time(),
|
||||
to a list in memory, written ONCE at process exit (atexit) to the file named by $HUNT_LC_TRACE (no file is opened or written on the reader
|
||||
during the run). Run once after the install: python scripts/hunt_trace_lifecycle.py
|
||||
"""
|
||||
import importlib.util
|
||||
import io
|
||||
|
||||
path = importlib.util.find_spec("invisible_core.juggler.lifecycle").origin
|
||||
s = io.open(path, encoding="utf-8").read()
|
||||
old = """ def _on_event(self, method: str, p: dict) -> None:
|
||||
with self._cv:
|
||||
"""
|
||||
new = """ def _on_event(self, method: str, p: dict) -> None:
|
||||
with self._cv:
|
||||
if method.startswith(("Page.", "Network.")):
|
||||
_hunt_lc(ev=method, frame=p.get("frameId"), nav=p.get("navigationId"), url=(p.get("url") or "")[:90],
|
||||
rid=p.get("requestId"), name=p.get("name"), open=len(self._open),
|
||||
states={k: sorted(v.states) for k, v in self.frames.items()})
|
||||
"""
|
||||
assert s.count(old) == 1, "_on_event"
|
||||
s = s.replace(old, new, 1)
|
||||
old = """ for f in waiting:
|
||||
f.states.add(state)
|
||||
self._tell(state, f.id)
|
||||
"""
|
||||
new = """ for f in waiting:
|
||||
if state == "networkidle":
|
||||
_hunt_lc(ev="GIVE networkidle", frame=f.id, nav=f.navigation, url=(f.url or "")[:90], open=len(self._open),
|
||||
quiet=round(quiet_for, 3))
|
||||
f.states.add(state)
|
||||
self._tell(state, f.id)
|
||||
"""
|
||||
assert s.count(old) == 1, "_settle"
|
||||
s = s.replace(old, new, 1)
|
||||
s = s.rstrip(chr(10)) + '''
|
||||
|
||||
|
||||
_HUNT_LC = []
|
||||
|
||||
|
||||
def _hunt_lc(**row):
|
||||
import os as _o, time as _t
|
||||
if not _o.environ.get("HUNT_LC_TRACE"):
|
||||
return
|
||||
row["t"] = round(_t.time(), 4)
|
||||
_HUNT_LC.append(row)
|
||||
|
||||
|
||||
def _hunt_lc_dump():
|
||||
import json as _j, os as _o
|
||||
path = _o.environ.get("HUNT_LC_TRACE")
|
||||
if path and _HUNT_LC:
|
||||
try:
|
||||
with open(path, "w", encoding="utf-8") as fh:
|
||||
fh.write("".join(_j.dumps(r, default=str) + chr(10) for r in _HUNT_LC))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
import atexit as _hunt_atexit
|
||||
_hunt_atexit.register(_hunt_lc_dump)
|
||||
'''
|
||||
io.open(path, "w", encoding="utf-8", newline=chr(10)).write(s)
|
||||
print("patched", path)
|
||||
@@ -0,0 +1,107 @@
|
||||
"""HUNT SCAFFOLDING, NEVER MERGED: time the reader's path in the installed invisible_core and invisible_playwright.
|
||||
|
||||
Run once per venv, AFTER scripts/hunt_trace_pipes.py and scripts/hunt_trace_lifecycle.py (it builds on their stamps):
|
||||
python scripts/hunt_trace_locks.py
|
||||
It copies scripts/hunt_locks_runtime.py into the core as invisible_core/_hunt_locks.py and patches, by exact text (an assert if the text
|
||||
is not there once):
|
||||
core connection.py Connection.dispatch_event (each listener timed), Connection._deliver (wall against CPU), the locks of the
|
||||
connection, and the chunk hook in _read_loop;
|
||||
core lifecycle.py Lifecycle._cv;
|
||||
core injected.py InjectedScript._contexts_changed;
|
||||
core instance.py Browser._sessions_ready, _buffer_lock;
|
||||
wrapper server.py the events gate (who holds it, how long gated_dispatch waits), PageDispatcher._close_lock / _held_lock /
|
||||
_frames_lock / _announce_lock, BrowserDispatcher._sessions_ready / _buffer_lock / _targets_lock / _pages_ready.
|
||||
Rows go to $HUNT_LOCKS_TRACE, one JSON file per process, written once at exit (see the head of hunt_locks_runtime.py).
|
||||
"""
|
||||
import importlib.util
|
||||
import io
|
||||
import os
|
||||
import shutil
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
|
||||
def origin(name):
|
||||
return importlib.util.find_spec(name).origin
|
||||
|
||||
|
||||
def read(path):
|
||||
return io.open(path, encoding="utf-8").read()
|
||||
|
||||
|
||||
def write(path, text):
|
||||
io.open(path, "w", encoding="utf-8", newline=chr(10)).write(text)
|
||||
|
||||
|
||||
def once(text, old, new, what):
|
||||
assert text.count(old) == 1, "%s: expected the text once, found %d" % (what, text.count(old))
|
||||
return text.replace(old, new, 1)
|
||||
|
||||
|
||||
IMPORT = "\n\nfrom invisible_core import _hunt_locks as _hunt_h # HUNT\n"
|
||||
|
||||
# ── the runtime, inside the core ──────────────────────────────────────────────────────────────────────────────────────────────────
|
||||
conn_path = origin("invisible_core.juggler.connection")
|
||||
core_dir = os.path.dirname(os.path.dirname(conn_path))
|
||||
shutil.copyfile(os.path.join(HERE, "hunt_locks_runtime.py"), os.path.join(core_dir, "_hunt_locks.py"))
|
||||
print("copied the runtime to", os.path.join(core_dir, "_hunt_locks.py"))
|
||||
|
||||
# ── core: connection ──────────────────────────────────────────────────────────────────────────────────────────────────────────────
|
||||
s = read(conn_path)
|
||||
assert "_HUNT_PIPE.append" in s, "run scripts/hunt_trace_pipes.py first"
|
||||
s = once(s, """ if not chunk:
|
||||
break
|
||||
if b"requestWillBeSent" in chunk and b"/landed" in chunk and os.environ.get("HUNT_PIPE_TRACE"):
|
||||
""", """ if not chunk:
|
||||
break
|
||||
_hunt_t0 = _hunt_h.chunk_begin()
|
||||
if b"requestWillBeSent" in chunk and b"/landed" in chunk and os.environ.get("HUNT_PIPE_TRACE"):
|
||||
""", "core _read_loop (before the stamp)")
|
||||
s = once(s, """ _HUNT_PIPE.append(_ht.time())
|
||||
""", """ _HUNT_PIPE.append(_ht.time())
|
||||
_hunt_h.on_chunk(chunk, _hunt_t0)
|
||||
""", "core _read_loop (after the stamp)")
|
||||
for needle in ("for fn in subscribers:", "fn(method, params, session)", "with self._listeners_lock:", "self.delivered += 1"):
|
||||
assert needle in s, "core dispatch_event changed: " + needle
|
||||
s = s.rstrip(chr(10)) + IMPORT + "_hunt_h.hook_connection(Connection)\n"
|
||||
write(conn_path, s)
|
||||
print("patched", conn_path)
|
||||
|
||||
# ── core: lifecycle, injected, instance ─────────────────────────────────────────────────────────────────────────────────────────────
|
||||
path = origin("invisible_core.juggler.lifecycle")
|
||||
s = read(path)
|
||||
assert "_HUNT_LC = []" in s, "run scripts/hunt_trace_lifecycle.py first"
|
||||
s = s.rstrip(chr(10)) + IMPORT + '_hunt_h.hook_class(Lifecycle, ["_cv"], "Lifecycle.")\n'
|
||||
write(path, s)
|
||||
print("patched", path)
|
||||
|
||||
path = origin("invisible_core.juggler.injected")
|
||||
s = read(path)
|
||||
assert "class InjectedScript" in s
|
||||
s = s.rstrip(chr(10)) + IMPORT + '_hunt_h.hook_class(InjectedScript, ["_contexts_changed"], "InjectedScript.")\n'
|
||||
write(path, s)
|
||||
print("patched", path)
|
||||
|
||||
path = origin("invisible_core.juggler.instance")
|
||||
s = read(path)
|
||||
assert "class Browser" in s
|
||||
s = s.rstrip(chr(10)) + IMPORT + '_hunt_h.hook_class(Browser, ["_sessions_ready", "_buffer_lock"], "core.Browser.")\n'
|
||||
write(path, s)
|
||||
print("patched", path)
|
||||
|
||||
# ── wrapper: server.py ──────────────────────────────────────────────────────────────────────────────────────────────────────────────
|
||||
path = origin("invisible_playwright._juggler.server")
|
||||
s = read(path)
|
||||
s = once(s, " gate = threading.RLock()\n",
|
||||
' gate = _hunt_h.timed(threading.RLock(), "events_gate", quiet=True)\n', "wrapper gate")
|
||||
s = once(s, """ got = gate.acquire(timeout=owner.GATE_WAIT_S) if waiting else gate.acquire(blocking=False)
|
||||
""", """ _hg = (_hunt_h.gate_begin(), _hunt_h.gate_snap(gate))
|
||||
got = gate.acquire(timeout=owner.GATE_WAIT_S) if waiting else gate.acquire(blocking=False)
|
||||
_hunt_h.gate_end(_hg[0], gate, got, waiting, _hg[1])
|
||||
""", "wrapper gated_dispatch")
|
||||
assert "class PageDispatcher(" in s and "class BrowserDispatcher(" in s
|
||||
s = s.rstrip(chr(10)) + IMPORT + (
|
||||
'_hunt_h.hook_class(PageDispatcher, ["_close_lock", "_held_lock", "_frames_lock", "_announce_lock"], "PageDispatcher.")\n'
|
||||
'_hunt_h.hook_class(BrowserDispatcher, ["_sessions_ready", "_buffer_lock", "_targets_lock", "_pages_ready"], "BrowserDispatcher.")\n')
|
||||
write(path, s)
|
||||
print("patched", path)
|
||||
@@ -0,0 +1,47 @@
|
||||
"""HUNT SCAFFOLDING, NEVER MERGED: stamp the moment the browser pipe delivers a /landed request, in the installed invisible_core.
|
||||
|
||||
invisible_core.juggler.connection _read_loop, on every chunk read from the browser. A chunk that carries "requestWillBeSent" and "/landed"
|
||||
appends a wall-clock time (seconds) to a list in memory; the list is written ONCE, at process exit (atexit), to the file named by $HUNT_PIPE_TRACE
|
||||
(no file is opened or written on the reader during the run). Run once per venv after the install: python scripts/hunt_trace_pipes.py
|
||||
(only the core part of the original in the trace worktree: the arms here are ours only).
|
||||
"""
|
||||
import importlib.util
|
||||
import io
|
||||
import os
|
||||
|
||||
path = importlib.util.find_spec("invisible_core.juggler.connection").origin
|
||||
s = io.open(path, encoding="utf-8").read()
|
||||
old = """ chunk = os.read(self._from_browser, 65536)
|
||||
if not chunk:
|
||||
break
|
||||
"""
|
||||
new = """ chunk = os.read(self._from_browser, 65536)
|
||||
if not chunk:
|
||||
break
|
||||
if b"requestWillBeSent" in chunk and b"/landed" in chunk and os.environ.get("HUNT_PIPE_TRACE"):
|
||||
import time as _ht
|
||||
_HUNT_PIPE.append(_ht.time())
|
||||
"""
|
||||
assert s.count(old) == 1, "core _read_loop"
|
||||
s = s.replace(old, new, 1).rstrip(chr(10)) + '''
|
||||
|
||||
|
||||
_HUNT_PIPE = []
|
||||
|
||||
|
||||
def _hunt_pipe_dump():
|
||||
import os as _o
|
||||
path = _o.environ.get("HUNT_PIPE_TRACE")
|
||||
if path and _HUNT_PIPE:
|
||||
try:
|
||||
with open(path, "w") as fh:
|
||||
fh.write("".join("%.4f" % t + chr(10) for t in _HUNT_PIPE))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
import atexit as _hunt_atexit
|
||||
_hunt_atexit.register(_hunt_pipe_dump)
|
||||
'''
|
||||
io.open(path, "w", encoding="utf-8", newline=chr(10)).write(s)
|
||||
print("patched", path)
|
||||
@@ -33,6 +33,7 @@ import contextlib
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import queue
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
@@ -3414,9 +3415,10 @@ class PageDispatcher(Dispatcher):
|
||||
# is a command whose answer only that same read loop can deliver.
|
||||
# Doing it here would block the reader waiting for a message the
|
||||
# reader is the one who has to receive.
|
||||
threading.Thread(
|
||||
target=self._announce_file_chooser, args=(params,),
|
||||
daemon=True).start()
|
||||
# ⛔ AND NOT STARTED HERE EITHER: `Thread.start` waits for the new thread to run, and this is the reader.
|
||||
# The browser's thread starter does it (`_ThreadStarter`).
|
||||
self.context.browser.thread_starter.start(
|
||||
target=self._announce_file_chooser, args=(params,))
|
||||
elif method == "Page.crashed":
|
||||
self.emit("crash")
|
||||
# ⛔ `Page.frameAttached` / `Page.frameDetached` ARE NOT READ HERE: the
|
||||
@@ -4777,6 +4779,51 @@ NO_OVERRIDE = "no-override"
|
||||
NO_OVERRIDE_OPTIONS = ("colorScheme", "reducedMotion", "forcedColors")
|
||||
|
||||
|
||||
class _ThreadStarter:
|
||||
"""The ONE long-lived thread that starts the other threads the engine's events ask for.
|
||||
|
||||
⛔ NO `Thread.start` ON THE CONNECTION'S READER THREAD. `Thread.start` does not return until the new thread is running
|
||||
(`self._started.wait()`), and on Windows under load that wait is milliseconds long: it was the larger part of the reader's delay, and
|
||||
every millisecond the reader is late is a millisecond a `networkidle` quiet is measured late (7 misses in 400 with four browsers at
|
||||
once, none in 400 when the start did not wait). A listener that runs on the reader and needs work done elsewhere hands it to `start`
|
||||
here: a `Thread` that is only BUILT on the reader (building waits for nothing) goes into a queue, and this thread starts it.
|
||||
|
||||
It starts threads and does not run the work itself, on purpose: an adoption waits for the engine as long as the engine takes (a popup
|
||||
whose destination never answers is waited for without a limit), and a worker that ran it would hold every later adoption behind it,
|
||||
`new_page()` included. Each piece of work keeps the thread of its own and the name it always had.
|
||||
"""
|
||||
|
||||
def __init__(self, on_error: Callable[[str], None]) -> None:
|
||||
self._queue: "queue.SimpleQueue" = queue.SimpleQueue()
|
||||
self._on_error = on_error
|
||||
self._stopped = False
|
||||
self._thread = threading.Thread(target=self._run, daemon=True, name="invpw-thread-starter")
|
||||
self._thread.start()
|
||||
|
||||
def start(self, **thread_arguments: Any) -> None:
|
||||
"""Called from any thread, the reader's included: builds the thread and queues it. Never waits."""
|
||||
if self._stopped:
|
||||
return
|
||||
self._queue.put(threading.Thread(daemon=True, **thread_arguments))
|
||||
|
||||
def stop(self) -> None:
|
||||
self._stopped = True
|
||||
self._queue.put(None)
|
||||
|
||||
def _run(self) -> None:
|
||||
while True:
|
||||
thread = self._queue.get()
|
||||
if thread is None:
|
||||
return
|
||||
try:
|
||||
thread.start()
|
||||
except Exception as failure:
|
||||
try:
|
||||
self._on_error("%s could not be started: %s" % (thread.name, failure))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
class BrowserDispatcher(Dispatcher):
|
||||
TYPE = "Browser"
|
||||
METHODS = {"newContext": "op_new_context", "close": "op_close",
|
||||
@@ -4965,6 +5012,9 @@ class BrowserDispatcher(Dispatcher):
|
||||
# subscriber seeing an event before this one records the session, and
|
||||
# recording earlier can only shorten the window in which `session_for`
|
||||
# is waiting for something that has already arrived.
|
||||
self._starter = _ThreadStarter(
|
||||
lambda why: conn.handler_errors.append(why) if len(conn.handler_errors) < 32 else None)
|
||||
conn.add_close_listener(self._starter.stop)
|
||||
conn.add_listener(self._route_browser_event)
|
||||
# The last step of starting the browser, under what is left of the
|
||||
# caller's `launch(timeout=)` (`Connection.startup_send`), not a
|
||||
@@ -4988,6 +5038,11 @@ class BrowserDispatcher(Dispatcher):
|
||||
# the target map): recorded for its session, never built into a page.
|
||||
self._adopt_enabled = True
|
||||
|
||||
@property
|
||||
def thread_starter(self) -> "_ThreadStarter":
|
||||
"""The one thread that starts threads on behalf of the engine's reader (`_ThreadStarter`)."""
|
||||
return self._starter
|
||||
|
||||
def require_interception(self, what: str) -> None:
|
||||
"""Refuse a route this browser cannot honour, instead of ignoring it.
|
||||
|
||||
@@ -5189,11 +5244,10 @@ class BrowserDispatcher(Dispatcher):
|
||||
else:
|
||||
self._strays += 1
|
||||
number = popup_number(None, self._strays)
|
||||
thread = threading.Thread(
|
||||
self._starter.start(
|
||||
target=self._adopt_target,
|
||||
args=(target_id, session_id, browser_context_id, opener, number),
|
||||
daemon=True, name="invpw-adopt-%s" % target_id[:8])
|
||||
thread.start()
|
||||
name="invpw-adopt-%s" % target_id[:8])
|
||||
|
||||
# ── the states of an adoption: the ONLY places a record changes state. Each is one method so that a test can stop the adoption thread
|
||||
# between any two of them and deliver an event of the engine there.
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
"""No thread is started on the engine connection's reader thread.
|
||||
|
||||
`Thread.start` does not return until the new thread is running. On the reader that wait is the reader's own delay: measured on Windows with
|
||||
four browsers at once, it was 75% of the reader's lag, and it made `networkidle` miss 7 times in 400 (none in 400 once the start no longer
|
||||
waited). Two listeners of this package started a thread from the reader: `Browser.attachedToTarget` (one thread per adoption) and
|
||||
`Page.fileChooserOpened` (one thread to announce the chooser). Both now hand the thread to the browser's ONE long-lived starter
|
||||
(`_ThreadStarter`, made with the browser), which starts it.
|
||||
|
||||
NO BROWSER HERE: the real dispatchers over a scripted Juggler connection, and every event of the engine delivered FROM A THREAD OF ITS OWN
|
||||
(the reader's stand-in), the way the connection delivers them. `Thread.start` is replaced by a recorder of the thread that called it.
|
||||
|
||||
`Page.eventFired(load)` goes through the core's lifecycle, which started a `threading.Timer` for the silence of `networkidle` until the core
|
||||
made one thread of deadlines for the connection (`DeadlineClock`): that case is skipped with a core that does not have it.
|
||||
|
||||
Known-bad input: the thread started in `_spawn_adoption` / `_route_juggler_event` -> two starts from the reader (the adoption and the
|
||||
chooser), named in the failure.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import queue
|
||||
import threading
|
||||
|
||||
import pytest
|
||||
|
||||
from invisible_core.juggler.connection import EventListeners
|
||||
from invisible_playwright._juggler import remote
|
||||
from invisible_playwright._juggler.server import LocalUtilsDispatcher
|
||||
|
||||
from test_every_order_of_the_events_of_a_popup_gives_one_page_event import FRAME, SESSION, TARGET, _wait
|
||||
from test_no_event_of_any_family_is_lost_by_the_hand_over import ChooserEngine
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
READER = "the-engine-reader"
|
||||
|
||||
|
||||
class _Reader:
|
||||
"""A thread that delivers the events it is handed, one at a time and in order, as the connection's reader does."""
|
||||
|
||||
def __init__(self):
|
||||
self._work: "queue.Queue" = queue.Queue()
|
||||
self.thread = threading.Thread(target=self._run, name=READER, daemon=True)
|
||||
self.thread.start()
|
||||
|
||||
def _run(self):
|
||||
while True:
|
||||
job = self._work.get()
|
||||
if job is None:
|
||||
return
|
||||
fn, done = job
|
||||
try:
|
||||
fn()
|
||||
finally:
|
||||
done.set()
|
||||
|
||||
def deliver(self, fn):
|
||||
done = threading.Event()
|
||||
self._work.put((fn, done))
|
||||
assert done.wait(10), "the reader is stuck inside a listener"
|
||||
|
||||
def stop(self):
|
||||
self._work.put(None)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def starts(monkeypatch):
|
||||
"""Every `Thread.start` from now on, as (the name of the thread that called it, the name of the thread started)."""
|
||||
calls = []
|
||||
original = threading.Thread.start
|
||||
|
||||
def recording(self):
|
||||
calls.append((threading.current_thread().name, self.name))
|
||||
return original(self)
|
||||
monkeypatch.setattr(threading.Thread, "start", recording)
|
||||
return calls
|
||||
|
||||
|
||||
def _from_reader(starts):
|
||||
return [c for c in starts if c[0] == READER]
|
||||
|
||||
|
||||
def _a_popup_is_announced(conn, reader, browser, context_id, opener_target):
|
||||
reader.deliver(lambda: conn.attach(opener_target, context_id))
|
||||
reader.deliver(conn.frame)
|
||||
reader.deliver(conn.commit)
|
||||
reader.deliver(conn.ready)
|
||||
assert _wait(lambda: browser._page_targets.get(TARGET) is not None, 5), "the popup was never announced (%s)" % (conn.handler_errors,)
|
||||
|
||||
|
||||
def _world(starts):
|
||||
server = remote._SharedServer()
|
||||
browser_type = remote.SharedBrowserType(server)
|
||||
LocalUtilsDispatcher(server)
|
||||
conn = ChooserEngine()
|
||||
browser = remote.SharedBrowserDispatcher(server, browser_type, conn, "firefox/1")
|
||||
context = server.object(server.handle({"guid": browser.guid, "method": "newContext", "params": {}})["context"]["guid"])
|
||||
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
|
||||
opener_target = next(t for t in conn.sessions if t != TARGET)
|
||||
return server, conn, browser, context, opener_target
|
||||
|
||||
|
||||
def test_an_attached_target_and_a_file_chooser_start_no_thread_on_the_reader(starts):
|
||||
server, conn, browser, context, opener_target = _world(starts)
|
||||
reader = _Reader()
|
||||
chooser = []
|
||||
try:
|
||||
del starts[:]
|
||||
_a_popup_is_announced(conn, reader, browser, context.context_id, opener_target)
|
||||
assert [c[1] for c in starts if c[1].startswith("invpw-adopt-")], "the adoption never started (%s)" % (starts,)
|
||||
page = browser._page_targets[TARGET]
|
||||
original_emit = type(page).emit
|
||||
|
||||
def spy(self, method, params=None):
|
||||
if method == "fileChooser":
|
||||
chooser.append(params)
|
||||
return original_emit(self, method, params)
|
||||
type(page).emit = spy
|
||||
try:
|
||||
reader.deliver(lambda: conn.dispatch_event(
|
||||
"Page.fileChooserOpened", {"element": {"objectId": "input-1"}, "executionContextId": "e"}, SESSION))
|
||||
assert _wait(lambda: chooser, 5), "the chooser never reached the client (%s)" % (conn.handler_errors,)
|
||||
finally:
|
||||
type(page).emit = original_emit
|
||||
assert _from_reader(starts) == [], "the reader started %s" % (_from_reader(starts),)
|
||||
assert conn.handler_errors == []
|
||||
finally:
|
||||
reader.stop()
|
||||
server.shutdown()
|
||||
|
||||
|
||||
@pytest.mark.skipif(not hasattr(EventListeners, "deadlines"), reason="the installed core still starts a Timer for the silence of networkidle")
|
||||
def test_a_load_delivered_on_the_reader_starts_no_thread(starts):
|
||||
server, conn, browser, context, opener_target = _world(starts)
|
||||
reader = _Reader()
|
||||
try:
|
||||
_a_popup_is_announced(conn, reader, browser, context.context_id, opener_target)
|
||||
del starts[:]
|
||||
reader.deliver(lambda: conn.dispatch_event("Page.eventFired", {"frameId": FRAME, "name": "load"}, SESSION))
|
||||
assert _from_reader(starts) == [], "the reader started %s" % (_from_reader(starts),)
|
||||
assert conn.handler_errors == []
|
||||
finally:
|
||||
reader.stop()
|
||||
server.shutdown()
|
||||
|
||||
|
||||
def test_the_starter_of_a_browser_ends_with_its_connection(starts):
|
||||
server, conn, browser, context, opener_target = _world(starts)
|
||||
try:
|
||||
starter = browser.thread_starter
|
||||
starter.start(target=lambda: None, name="invpw-test-started")
|
||||
assert _wait(lambda: ("invpw-thread-starter", "invpw-test-started") in starts, 3)
|
||||
conn.announce_closed()
|
||||
starter._thread.join(5)
|
||||
assert not starter._thread.is_alive(), "the starter outlived the connection"
|
||||
starter.start(target=lambda: None, name="invpw-test-after-the-end") # after the end: nothing is started, nothing raises
|
||||
assert all(c[1] != "invpw-test-after-the-end" for c in starts)
|
||||
finally:
|
||||
server.shutdown()
|
||||
Reference in new issue
Block a user