Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ff91f92dd9 | ||
|
|
fd380b9660 | ||
|
|
48368461fc | ||
|
|
76fe33a8fc | ||
|
|
56c6c43d2d | ||
|
|
037f614721 | ||
|
|
6761bd4b43 | ||
|
|
224850a3e0 | ||
|
|
59cc42452c |
No files matched your search
@@ -0,0 +1,141 @@
|
||||
# windows-flakes-hunt.yml - hunt scaffolding, never merged. Runs only on a push to a `hunt/windows-flakes-reader**` branch.
|
||||
# Why the pipe reader thread of our process is late: the two listeners that start a thread (Lifecycle._settle's Timer, the adoption of a
|
||||
# new target) are the slow ones in every earlier trace. Arms, same machine, four processes at once, alternated: plain Thread.start
|
||||
# against a Thread.start that does not wait for the new thread to be scheduled (scripts/hunt_threads.py).
|
||||
name: windows flakes hunt
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ['hunt/windows-flakes-reader**']
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: windows-flakes-reader-hunt-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
|
||||
jobs:
|
||||
hunt:
|
||||
name: reader delay hunt ${{ matrix.os }}
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
max-parallel: 1
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [windows-2022, ubuntu-24.04]
|
||||
timeout-minutes: 90
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
|
||||
with: { python-version: '3.11' }
|
||||
- name: Install
|
||||
run: |
|
||||
set -e
|
||||
python -m pip install --quiet --upgrade pip
|
||||
python -m pip install --quiet ".[dev]"
|
||||
python -m pip install --quiet "playwright==$(cat scripts/playwright_pin.txt)"
|
||||
echo "FF=$(cd "$RUNNER_TEMP" && python -m invisible_playwright fetch | tail -1)" >> "$GITHUB_ENV"
|
||||
python scripts/ci_lab_geoip.py build
|
||||
if [ "$RUNNER_OS" = "Linux" ]; then python -m playwright install --with-deps firefox; else python -m playwright install firefox; fi
|
||||
python scripts/hunt_trace_inside.py
|
||||
python scripts/hunt_trace_gate.py
|
||||
python -c "import sys, os; print(sys.version); print('cpus', os.cpu_count())"
|
||||
- name: Plain and nowait, four at once each, alternated, five rounds
|
||||
env:
|
||||
PYTHONUNBUFFERED: "1"
|
||||
run: |
|
||||
set +e
|
||||
mkdir -p evidence
|
||||
# the plain round trip alone, ours then stock (Windows; Linux already measured in 43453630396)
|
||||
if [ "$RUNNER_OS" = "Windows" ]; then
|
||||
for engine in ours stock; do timeout 300 python -u scripts/hunt_rtt.py $engine "$FF" >> evidence/rtt_alone.log 2>&1; done
|
||||
grep -ah "^HUNT-RTT" evidence/rtt_alone.log | tee -a "$GITHUB_STEP_SUMMARY"
|
||||
fi
|
||||
for n in 1 2 3 4 5; do
|
||||
if [ $((n % 2)) -eq 1 ]; then arms="plain nowait"; else arms="nowait plain"; fi
|
||||
for arm in $arms; do
|
||||
for c in 1 2 3 4; do
|
||||
HUNT_THREAD_ARM=$arm HUNT_THREAD_TRACE="$PWD/evidence/threads_${arm}_${n}_$c.jsonl" HUNT_INSIDE_TRACE="$PWD/evidence/inside_${arm}_${n}_$c.jsonl" \
|
||||
python -u scripts/hunt_netidle.py ours "$FF" > "evidence/${arm}_${n}_$c.log" 2>&1 &
|
||||
done
|
||||
wait
|
||||
echo "round $n arm $arm done"
|
||||
done
|
||||
done
|
||||
cat > evidence/summary.py <<'PY'
|
||||
import collections, glob, json, os
|
||||
def rows(pattern):
|
||||
out = []
|
||||
for f in sorted(glob.glob(pattern)):
|
||||
for line in open(f, encoding="utf-8", errors="replace"):
|
||||
if line.strip():
|
||||
out.append(json.loads(line))
|
||||
return out
|
||||
def pct(v, q):
|
||||
v = sorted(v)
|
||||
return v[min(len(v) - 1, int(len(v) * q))] if v else 0
|
||||
for arm in ("plain", "nowait"):
|
||||
print("## arm", arm)
|
||||
missed = total = 0
|
||||
for f in glob.glob("evidence/%s_*.log" % arm):
|
||||
for line in open(f, encoding="utf-8", errors="replace"):
|
||||
if line.startswith("HUNT-ROW "):
|
||||
r = json.loads(line[9:]); total += 1; missed += (not r["landed_at_return"])
|
||||
print("networkidle rows", total, "not on /landed at return", missed)
|
||||
inside = [r for r in rows("evidence/inside_%s_*.jsonl" % arm) if r["kind"] == "listener"]
|
||||
by = collections.defaultdict(list)
|
||||
for r in inside:
|
||||
by[(r["fn"], r["ev"])].append(r["ms"])
|
||||
for k, v in sorted(by.items(), key=lambda kv: -sum(kv[1]))[:8]:
|
||||
print(" listener %-52s n %4d p95 %5d max %5d sum %6d" % ("%s %s" % k, len(v), pct(v, .95), max(v), sum(v)))
|
||||
print(" listener total ms >= 20:", sum(r["ms"] for r in inside), "calls", len(inside))
|
||||
allrows = rows("evidence/threads_%s_*.jsonl" % arm)
|
||||
starts = [r for r in allrows if r["kind"] == "Thread.start"]
|
||||
reader = [r for r in starts if "_read_loop" in r["caller"]]
|
||||
ms = [r["ms"] for r in reader]
|
||||
print(" Thread.start by the reader: n %d p50 %.1f p95 %.1f max %.1f sum %.0f" % (len(ms), pct(ms, .5), pct(ms, .95), max(ms or [0]), sum(ms)))
|
||||
others = [r["ms"] for r in starts if "_read_loop" not in r["caller"]]
|
||||
print(" Thread.start by others (>= 1 ms): n %d p95 %.1f max %.1f" % (len(others), pct(others, .95), max(others or [0])))
|
||||
for kind in ("canary", "gc", "gate wait"):
|
||||
v = [r["ms"] for r in allrows if r["kind"] == kind]
|
||||
print(" %-10s n %4d p95 %6.1f max %7.1f sum %7.0f" % (kind, len(v), pct(v, .95), max(v or [0]), sum(v)))
|
||||
# per slow listener (same process: same file suffix), how much of its time lies inside what
|
||||
inside_ms = 0.0
|
||||
cover = collections.Counter()
|
||||
slow = 0
|
||||
for f in glob.glob("evidence/inside_%s_*.jsonl" % arm):
|
||||
tf = f.replace("inside_", "threads_")
|
||||
st = rows(tf) if os.path.exists(tf) else []
|
||||
for r in [x for x in rows(f) if x["kind"] == "listener"]:
|
||||
lo, hi = r["t"], r["t"] + r["ms"] / 1000
|
||||
inside_ms += r["ms"]
|
||||
for kind in ("Thread.start", "canary", "gc", "gate wait"):
|
||||
for x in st:
|
||||
if x["kind"] != kind or ("_read_loop" not in x.get("caller", "_read_loop") and kind == "Thread.start"):
|
||||
continue
|
||||
xlo, xhi = x["t"], x["t"] + x["ms"] / 1000
|
||||
cover[kind] += max(0.0, min(hi, xhi) - max(lo, xlo)) * 1000
|
||||
print(" of the slow listeners' %.0f ms:" % inside_ms, ", ".join("%s %.0f ms" % kv for kv in sorted(cover.items())))
|
||||
PY
|
||||
{ python evidence/summary.py; } | tee -a "$GITHUB_STEP_SUMMARY"
|
||||
- name: Close every Firefox left
|
||||
if: always()
|
||||
shell: pwsh
|
||||
run: |
|
||||
Get-Process firefox -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue
|
||||
"left: " + @(Get-Process firefox -ErrorAction SilentlyContinue).Count
|
||||
- name: Upload the evidence
|
||||
if: always()
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
with:
|
||||
name: reader-delay-${{ github.run_id }}
|
||||
path: evidence
|
||||
if-no-files-found: warn
|
||||
retention-days: 14
|
||||
@@ -0,0 +1,83 @@
|
||||
"""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 hunt_threads # noqa: F401 HUNT_THREAD_ARM=plain|nowait, before anything starts a thread
|
||||
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,29 @@
|
||||
"""HUNT SCAFFOLDING, NEVER MERGED: the plain round trip, 200 x page.evaluate("1"), ours against stock. Usage: hunt_rtt.py ours|stock [binary]"""
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
|
||||
ENGINE = sys.argv[1]
|
||||
|
||||
|
||||
def run(page):
|
||||
page.goto("data:text/html,<p>x</p>")
|
||||
t = []
|
||||
for _ in range(200):
|
||||
t0 = time.perf_counter()
|
||||
page.evaluate("1")
|
||||
t.append((time.perf_counter() - t0) * 1000)
|
||||
t.sort()
|
||||
print("HUNT-RTT " + json.dumps({"engine": ENGINE, "p50": round(t[100], 2), "p95": round(t[190], 2), "max": round(t[-1], 2)}), flush=True)
|
||||
|
||||
|
||||
if ENGINE == "stock":
|
||||
from playwright.sync_api import sync_playwright
|
||||
with sync_playwright() as p:
|
||||
b = p.firefox.launch(headless=True)
|
||||
run(b.new_page())
|
||||
b.close()
|
||||
else:
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
with InvisiblePlaywright(seed=2, binary_path=sys.argv[2], headless=True) as browser:
|
||||
run(browser.new_page())
|
||||
@@ -0,0 +1,83 @@
|
||||
"""HUNT SCAFFOLDING, NEVER MERGED: how long does threading.Thread.start take, and what if it did not wait for the new thread.
|
||||
|
||||
Imported first by hunt_netidle.py. $HUNT_THREAD_ARM picks the arm:
|
||||
plain the real Thread.start, stamped: every call of 1 ms or more, and every call made by the pipe reader thread, is a line
|
||||
(wall clock, the caller's thread name, the target) in $HUNT_THREAD_TRACE;
|
||||
nowait the same stamp, but Thread.start does not block on `self._started.wait()` (3.11 body, minus its last line): the caller
|
||||
returns as soon as the OS thread exists, instead of when it has been scheduled and has taken the GIL.
|
||||
Both arms also write, to the same file: a canary (a daemon thread that sleeps 5 ms in a loop and writes every oversleep of 20 ms or more:
|
||||
a stall of the whole process, GIL or CPU, whoever causes it) and every garbage collection of 20 ms or more.
|
||||
Nothing else changes between the arms. The reader thread starts a thread inside two listeners: `Lifecycle._settle` (a threading.Timer,
|
||||
under the lifecycle lock, on every load) and the adoption of a new target (`BrowserDispatcher`, a thread per `Browser.attachedToTarget`).
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
|
||||
ARM = os.environ.get("HUNT_THREAD_ARM", "")
|
||||
OUT = os.environ.get("HUNT_THREAD_TRACE")
|
||||
_real_start = threading.Thread.start
|
||||
|
||||
|
||||
def _row(**r):
|
||||
if OUT:
|
||||
with open(OUT, "a", encoding="utf-8") as fh:
|
||||
print(json.dumps(r), file=fh)
|
||||
|
||||
|
||||
def _nowait(self):
|
||||
if not self._initialized:
|
||||
raise RuntimeError("thread.__init__() not called")
|
||||
if self._started.is_set():
|
||||
raise RuntimeError("threads can only be started once")
|
||||
with threading._active_limbo_lock:
|
||||
threading._limbo[self] = self
|
||||
try:
|
||||
threading._start_new_thread(self._bootstrap, ())
|
||||
except Exception:
|
||||
with threading._active_limbo_lock:
|
||||
del threading._limbo[self]
|
||||
raise
|
||||
|
||||
|
||||
def _stamped(self):
|
||||
caller = threading.current_thread().name
|
||||
t0 = time.time()
|
||||
try:
|
||||
return (_nowait if ARM == "nowait" else _real_start)(self)
|
||||
finally:
|
||||
ms = (time.time() - t0) * 1000
|
||||
if ms >= 1 or "_read_loop" in caller:
|
||||
target = getattr(self, "_target", None)
|
||||
_row(kind="Thread.start", caller=caller[:60], target=getattr(target, "__qualname__", type(self).__name__)[:60],
|
||||
ms=round(ms, 2), t=round(t0, 4))
|
||||
|
||||
|
||||
def _canary():
|
||||
while True:
|
||||
wall, t0 = time.time(), time.perf_counter()
|
||||
time.sleep(0.005)
|
||||
over = (time.perf_counter() - t0 - 0.005) * 1000
|
||||
if over >= 20:
|
||||
_row(kind="canary", ms=round(over, 1), t=round(wall, 4))
|
||||
|
||||
|
||||
_gc_started = {}
|
||||
|
||||
|
||||
def _gc_callback(phase, info):
|
||||
if phase == "start":
|
||||
_gc_started["t"] = (time.time(), time.perf_counter())
|
||||
elif "t" in _gc_started:
|
||||
wall, t0 = _gc_started.pop("t")
|
||||
ms = (time.perf_counter() - t0) * 1000
|
||||
if ms >= 20:
|
||||
_row(kind="gc", ms=round(ms, 1), t=round(wall, 4), generation=info.get("generation"))
|
||||
|
||||
|
||||
if ARM in ("plain", "nowait"):
|
||||
threading.Thread.start = _stamped
|
||||
import gc
|
||||
gc.callbacks.append(_gc_callback)
|
||||
_real_start(threading.Thread(target=_canary, daemon=True, name="hunt-canary"))
|
||||
@@ -0,0 +1,24 @@
|
||||
"""HUNT SCAFFOLDING, NEVER MERGED: stamp how long the engine's reader waits for the events gate (BrowserDispatcher.gated_dispatch).
|
||||
|
||||
Patches the installed invisible_playwright server module: every wait of 20 ms or more for `gate.acquire` is a line (wall clock, the event) in
|
||||
$HUNT_THREAD_TRACE, kind "gate wait". Run once after the install: python scripts/hunt_trace_gate.py
|
||||
"""
|
||||
import importlib.util
|
||||
import io
|
||||
|
||||
path = importlib.util.find_spec("invisible_playwright._juggler.server").origin
|
||||
s = io.open(path, encoding="utf-8").read()
|
||||
old = """ got = gate.acquire(timeout=owner.GATE_WAIT_S) if waiting else gate.acquire(blocking=False)
|
||||
"""
|
||||
new = """ _hg0 = time.time()
|
||||
got = gate.acquire(timeout=owner.GATE_WAIT_S) if waiting else gate.acquire(blocking=False)
|
||||
_hgdt = time.time() - _hg0
|
||||
if _hgdt >= 0.02:
|
||||
import json as _hj, os as _ho
|
||||
if _ho.environ.get("HUNT_THREAD_TRACE"):
|
||||
with open(_ho.environ["HUNT_THREAD_TRACE"], "a", encoding="utf-8") as _hf:
|
||||
print(_hj.dumps({"kind": "gate wait", "ev": method, "ms": round(_hgdt * 1000, 1), "t": round(_hg0, 4), "got": bool(got)}), file=_hf)
|
||||
"""
|
||||
assert s.count(old) == 1, "gated_dispatch"
|
||||
io.open(path, "w", encoding="utf-8", newline=chr(10)).write(s.replace(old, new, 1))
|
||||
print("patched", path)
|
||||
@@ -0,0 +1,150 @@
|
||||
"""HUNT SCAFFOLDING, NEVER MERGED: where the time goes between our pipe reader and the lifecycle.
|
||||
|
||||
Patches the installed invisible_core: every listener call in Connection.dispatch_event that takes 20 ms or more, and every wait of
|
||||
Lifecycle._on_event for the lifecycle's lock of 20 ms or more, is written (wall clock) to $HUNT_INSIDE_TRACE with the listener's name,
|
||||
the event and the thread that held the lock. Run once after the install: python scripts/hunt_trace_inside.py
|
||||
"""
|
||||
import importlib.util
|
||||
import io
|
||||
|
||||
path = importlib.util.find_spec("invisible_core.juggler.connection").origin
|
||||
s = io.open(path, encoding="utf-8").read()
|
||||
old = """ for fn in subscribers:
|
||||
try:
|
||||
fn(method, params, session)
|
||||
except Exception as failure:
|
||||
"""
|
||||
new = """ for fn in subscribers:
|
||||
try:
|
||||
_ht0 = time.time()
|
||||
fn(method, params, session)
|
||||
_hdt = time.time() - _ht0
|
||||
if _hdt >= 0.02:
|
||||
_hunt_inside(kind="listener", fn=getattr(fn, "__qualname__", repr(fn))[:120], ev=method, ms=round(_hdt * 1000), t=round(_ht0, 4))
|
||||
except Exception as failure:
|
||||
"""
|
||||
assert s.count(old) == 1, "dispatch_event"
|
||||
s = s.replace(old, new, 1)
|
||||
if "\nimport time\n" not in s:
|
||||
s = s.replace("\nimport json\n", "\nimport json\nimport time\n", 1)
|
||||
s = s.rstrip(chr(10)) + '''
|
||||
|
||||
|
||||
def _hunt_inside(**row):
|
||||
import json as _j, os as _o
|
||||
path = _o.environ.get("HUNT_INSIDE_TRACE")
|
||||
if path:
|
||||
with open(path, "a", encoding="utf-8") as fh:
|
||||
print(_j.dumps(row), file=fh)
|
||||
'''
|
||||
io.open(path, "w", encoding="utf-8", newline=chr(10)).write(s)
|
||||
print("patched", path)
|
||||
|
||||
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:
|
||||
import time as _hti
|
||||
_hw0 = _hti.time()
|
||||
self._cv.acquire()
|
||||
_hwait = _hti.time() - _hw0
|
||||
self._cv.release()
|
||||
if _hwait >= 0.02:
|
||||
from invisible_core.juggler.connection import _hunt_inside
|
||||
_hunt_inside(kind="lifecycle lock wait", ev=method, ms=round(_hwait * 1000), t=round(_hw0, 4), holder=getattr(self, "_hunt_holder", None))
|
||||
with self._cv:
|
||||
"""
|
||||
assert s.count(old) == 1, "_on_event"
|
||||
s = s.replace(old, new, 1)
|
||||
old = """ if self.announce is not None:
|
||||
self.announce(what, frame_id, url, **detail)
|
||||
"""
|
||||
new = """ if self.announce is not None:
|
||||
import time as _hta
|
||||
_ha0 = _hta.time()
|
||||
self.announce(what, frame_id, url, **detail)
|
||||
_hadt = _hta.time() - _ha0
|
||||
if _hadt >= 0.02:
|
||||
from invisible_core.juggler.connection import _hunt_inside
|
||||
_hunt_inside(kind="announce under the lifecycle lock", ev=what, ms=round(_hadt * 1000), t=round(_ha0, 4),
|
||||
fn=getattr(self.announce, "__qualname__", "?"))
|
||||
"""
|
||||
assert s.count(old) == 1, "_tell"
|
||||
s = s.replace(old, new, 1)
|
||||
old = """ self._cv = threading.Condition()
|
||||
"""
|
||||
new = """ self._cv = _HuntCondition()
|
||||
"""
|
||||
assert s.count(old) == 1, "_cv"
|
||||
s = s.replace(old, new, 1)
|
||||
s = s.rstrip(chr(10)) + """
|
||||
|
||||
|
||||
import atexit as _hatexit
|
||||
import sys as _hsys
|
||||
import threading as _hthreading
|
||||
import time as _htime
|
||||
|
||||
_HUNT_MAX = {}
|
||||
|
||||
|
||||
def _hunt_record(holder, held):
|
||||
import os as _o
|
||||
m = _HUNT_MAX.get(holder)
|
||||
_HUNT_MAX[holder] = (max(held, m[0]) if m else held, (m[1] if m else 0) + 1, (m[2] if m else 0.0) + held)
|
||||
if held >= 0.02 and _o.environ.get("HUNT_INSIDE_TRACE"):
|
||||
from invisible_core.juggler.connection import _hunt_inside
|
||||
_hunt_inside(kind="lifecycle lock held", fn=holder, ms=round(held * 1000), t=round(_htime.time(), 4))
|
||||
|
||||
|
||||
def _hunt_dump():
|
||||
import json as _j, os as _o
|
||||
path = _o.environ.get("HUNT_LOCK_MAX")
|
||||
if path:
|
||||
with open(path, "a", encoding="utf-8") as fh:
|
||||
for k, (mx, n, tot) in sorted(_HUNT_MAX.items(), key=lambda kv: -kv[1][0]):
|
||||
print(_j.dumps({"holder": k, "max_ms": round(mx * 1000), "count": n, "total_ms": round(tot * 1000)}), file=fh)
|
||||
|
||||
|
||||
_hatexit.register(_hunt_dump)
|
||||
|
||||
|
||||
class _HuntCondition(_hthreading.Condition):
|
||||
# How long the lifecycle's lock is HELD, outermost holds only, per holder (the function that took it); the waits inside
|
||||
# Condition.wait are not held time.
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self._hdepth = 0
|
||||
self._hsince = 0.0
|
||||
self._hholder = None
|
||||
|
||||
def __enter__(self):
|
||||
r = super().__enter__()
|
||||
self._hdepth += 1
|
||||
if self._hdepth == 1:
|
||||
f = _hsys._getframe(1)
|
||||
self._hholder = "%s:%d" % (f.f_code.co_qualname, f.f_lineno)
|
||||
self._hsince = _htime.time()
|
||||
return r
|
||||
|
||||
def __exit__(self, *a):
|
||||
self._hdepth -= 1
|
||||
if self._hdepth == 0:
|
||||
_hunt_record(self._hholder, _htime.time() - self._hsince)
|
||||
return super().__exit__(*a)
|
||||
|
||||
def wait(self, timeout=None):
|
||||
holder = self._hholder
|
||||
_hunt_record(holder, _htime.time() - self._hsince)
|
||||
depth = self._hdepth
|
||||
try:
|
||||
return super().wait(timeout)
|
||||
finally:
|
||||
self._hdepth = depth
|
||||
self._hholder = holder
|
||||
self._hsince = _htime.time()
|
||||
"""
|
||||
io.open(path, "w", encoding="utf-8", newline=chr(10)).write(s)
|
||||
print("patched", path)
|
||||
@@ -0,0 +1,52 @@
|
||||
"""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 the file named by $HUNT_LC_TRACE. 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)) + '''
|
||||
|
||||
|
||||
def _hunt_lc(**row):
|
||||
import json as _j, os as _o, time as _t
|
||||
path = _o.environ.get("HUNT_LC_TRACE")
|
||||
if not path:
|
||||
return
|
||||
row["t"] = round(_t.time(), 4)
|
||||
try:
|
||||
with open(path, "a", encoding="utf-8") as fh:
|
||||
print(_j.dumps(row, default=str), file=fh)
|
||||
except Exception:
|
||||
pass
|
||||
'''
|
||||
io.open(path, "w", encoding="utf-8", newline=chr(10)).write(s)
|
||||
print("patched", path)
|
||||
@@ -0,0 +1,42 @@
|
||||
"""HUNT SCAFFOLDING, NEVER MERGED: stamp the moment the browser pipe delivers a /landed request, in the core and in stock Playwright.
|
||||
|
||||
Ours: invisible_core.juggler.connection _read_loop, on every chunk read from the browser. Stock: Playwright's PipeTransport2._dispatch in
|
||||
the driver's coreBundle.js, on every chunk. A chunk that carries "requestWillBeSent" and "/landed" writes a wall-clock time (seconds) to the
|
||||
file named by $HUNT_PIPE_TRACE. Run once after the install: python scripts/hunt_trace_pipes.py
|
||||
"""
|
||||
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
|
||||
with open(os.environ["HUNT_PIPE_TRACE"], "a") as _hf:
|
||||
print("%.4f" % _ht.time(), file=_hf)
|
||||
"""
|
||||
assert s.count(old) == 1, "core _read_loop"
|
||||
io.open(path, "w", encoding="utf-8", newline=chr(10)).write(s.replace(old, new, 1))
|
||||
print("patched", path)
|
||||
|
||||
pw = os.path.dirname(importlib.util.find_spec("playwright").origin)
|
||||
bundle = os.path.join(pw, "driver", "package", "lib", "coreBundle.js")
|
||||
s = io.open(bundle, encoding="utf-8").read()
|
||||
old = r""" _dispatch(buffer) {
|
||||
let end = buffer.indexOf("\0");
|
||||
"""
|
||||
new = r""" _dispatch(buffer) {
|
||||
if (process.env.HUNT_PIPE_TRACE && buffer.includes("requestWillBeSent") && buffer.includes("/landed"))
|
||||
require("fs").appendFileSync(process.env.HUNT_PIPE_TRACE, (Date.now() / 1000).toFixed(4) + "\n");
|
||||
let end = buffer.indexOf("\0");
|
||||
"""
|
||||
assert s.count(old) >= 1, "stock _dispatch" # two NUL-delimited transports in the bundle: both stamped
|
||||
io.open(bundle, "w", encoding="utf-8", newline=chr(10)).write(s.replace(old, new))
|
||||
print("patched", bundle)
|
||||
@@ -0,0 +1,97 @@
|
||||
"""HUNT SCAFFOLDING, NEVER MERGED: one typed address, three times per key: planned, sent (before the keydown command), seen by the page.
|
||||
|
||||
Usage: python scripts/hunt_typing.py ours|stock [binary]. Both type the same plan (persona of seed 2, typing nonce 1, the plan the core's
|
||||
keyboard draws for a session's first field): ours through press_sequentially (the core keyboard), stock as down / sleep(dwell) / up /
|
||||
sleep(gap) through stock Playwright's keyboard. One JSON line per run with the three series in wall-clock milliseconds.
|
||||
"""
|
||||
import http.server
|
||||
import json
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
|
||||
from invisible_core.juggler._behaviour import TypingPersona, plan_typing
|
||||
|
||||
ENGINE = sys.argv[1]
|
||||
TEXT = "someone@example.com"
|
||||
PLAN = plan_typing(TEXT, TypingPersona.from_seed(2), nonce=1)
|
||||
SENT = []
|
||||
PAGE = (b"<!doctype html><html><body><input id=f><script>window.__k=[];document.addEventListener('keydown',"
|
||||
b"e=>__k.push([e.key, performance.timeOrigin + performance.now()]),true);</script></body></html>")
|
||||
|
||||
|
||||
class H(http.server.BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/html")
|
||||
self.send_header("Content-Length", str(len(PAGE)))
|
||||
self.end_headers()
|
||||
self.wfile.write(PAGE)
|
||||
|
||||
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()
|
||||
url = "http://127.0.0.1:%d/" % srv.server_address[1]
|
||||
|
||||
|
||||
def report(page, t_start):
|
||||
keys = page.evaluate("__k")
|
||||
planned, t = [], 0.0
|
||||
for dwell, gap in PLAN:
|
||||
planned.append(round(t))
|
||||
t += dwell + gap
|
||||
print("HUNT-TYPING " + json.dumps({
|
||||
"engine": ENGINE, "planned_ms": planned,
|
||||
"sent_ms": [round(x * 1000 - SENT[0] * 1000) for x in SENT if True],
|
||||
"page_ms": [round(v - keys[0][1]) for k, v in keys if k != "Shift"],
|
||||
"page_keys": [k for k, v in keys], "send_offset_ms": round((SENT[0] - t_start) * 1000) if SENT else None,
|
||||
}), flush=True)
|
||||
|
||||
|
||||
if ENGINE == "stock":
|
||||
from playwright.sync_api import sync_playwright
|
||||
with sync_playwright() as p:
|
||||
b = p.firefox.launch(headless=True)
|
||||
page = b.new_page()
|
||||
for _ in range(5):
|
||||
SENT.clear()
|
||||
page.goto(url)
|
||||
page.click("#f")
|
||||
t_start = time.time()
|
||||
for (dwell, gap), ch in zip(PLAN, TEXT):
|
||||
SENT.append(time.time())
|
||||
if ch == "@":
|
||||
page.keyboard.down("Shift")
|
||||
page.keyboard.down(ch)
|
||||
time.sleep(dwell / 1000)
|
||||
page.keyboard.up(ch)
|
||||
if ch == "@":
|
||||
page.keyboard.up("Shift")
|
||||
time.sleep(gap / 1000)
|
||||
report(page, t_start)
|
||||
b.close()
|
||||
else:
|
||||
from invisible_core.juggler import keyboard as kb
|
||||
real_down = kb.Keyboard.down
|
||||
|
||||
def down(self, key, *a, **k):
|
||||
if key != "Shift":
|
||||
SENT.append(time.time())
|
||||
return real_down(self, key, *a, **k)
|
||||
|
||||
kb.Keyboard.down = down
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
for _ in range(5):
|
||||
# a fresh browser per run: the plan is the one of the session's first field (typing nonce 1)
|
||||
with InvisiblePlaywright(seed=2, binary_path=sys.argv[2], headless=True) as browser:
|
||||
SENT.clear()
|
||||
page = browser.new_page()
|
||||
page.goto(url)
|
||||
t_start = time.time()
|
||||
page.locator("#f").press_sequentially(TEXT)
|
||||
report(page, t_start)
|
||||
srv.shutdown()
|
||||
@@ -161,6 +161,14 @@ def test_networkidle_is_reached_on_the_page_that_replaced_ours(page, site, path)
|
||||
for i in range(ROUNDS):
|
||||
_goto(page, "%s%s?n=%d" % (site, path, i), wait_until="networkidle",
|
||||
timeout=15_000)
|
||||
if not page.url.endswith("/landed"):
|
||||
u1 = page.url
|
||||
try:
|
||||
href = page.evaluate("location.href")
|
||||
except Exception as e:
|
||||
href = "ERR " + str(e)[:120]
|
||||
time.sleep(2)
|
||||
print("HUNT-NETIDLE round=%d url=%s href=%s url_after_2s=%s" % (i, u1, href, page.url), flush=True)
|
||||
assert page.url.endswith("/landed"), page.url
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user