Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
035f4cd2ce | ||
|
|
d207618886 | ||
|
|
29a23d9157 | ||
|
|
a50a908ea7 | ||
|
|
15572fa114 | ||
|
|
e31c28a2a7 | ||
|
|
5fa52df627 | ||
|
|
224850a3e0 | ||
|
|
59cc42452c |
No files matched your search
@@ -0,0 +1,108 @@
|
||||
# windows-flakes-engine-hunt.yml - hunt scaffolding, never merged. Runs only on a push to a `hunt/windows-flakes-engine**` branch.
|
||||
# Where is a typed key's delay born inside the engine? The Juggler of our engine and of stock Playwright's Firefox is patched in its omni.ja
|
||||
# (scripts/hunt_patch_omni.py) to stamp every Page.dispatchKeyEvent: parent receipt, content receipt, latency timer armed and fired, just
|
||||
# before the DOM event; the page adds its handler time and the event's timeStamp. Typing core = branch fix/typing-on-absolute-deadlines
|
||||
# (the "git" arm of windows-flakes-typing-hunt.yml). Arms: git and stock with the stamps, git_plain and stock_plain with the engine
|
||||
# untouched (what the stamps cost). Windows: four processes at once, 20 runs per arm. Linux: alone, 20 runs per arm.
|
||||
name: windows flakes engine hunt
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ['hunt/windows-flakes-engine**']
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: windows-flakes-engine-hunt-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
CORE_GIT: "git+https://github.com/oss-invisible/core@fix/typing-on-absolute-deadlines"
|
||||
|
||||
jobs:
|
||||
hunt:
|
||||
name: engine hunt ${{ matrix.os }}
|
||||
runs-on: ${{ matrix.os }}
|
||||
timeout-minutes: 120
|
||||
strategy:
|
||||
max-parallel: 1
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [windows-2022, ubuntu-24.04]
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
env:
|
||||
PYTHONUNBUFFERED: "1"
|
||||
steps:
|
||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
|
||||
with: { python-version: '3.11' }
|
||||
- name: Install
|
||||
run: |
|
||||
set -e
|
||||
timeout 300 python -m pip install --quiet --upgrade pip
|
||||
timeout 300 python -m pip install --quiet ".[dev]"
|
||||
timeout 300 python -m pip install --quiet "playwright==$(cat scripts/playwright_pin.txt)"
|
||||
echo "FF=$(cd "$RUNNER_TEMP" && timeout 300 python -m invisible_playwright fetch | tail -1)" >> "$GITHUB_ENV"
|
||||
timeout 300 python scripts/ci_lab_geoip.py build
|
||||
if [ "$RUNNER_OS" = "Linux" ]; then timeout 300 python -m playwright install --with-deps firefox; else timeout 300 python -m playwright install firefox; fi
|
||||
STOCK_FF="$(python -c "from playwright.sync_api import sync_playwright as s; p = s().start(); print(p.firefox.executable_path); p.stop()" | tail -1)"
|
||||
echo "STOCK_FF=$STOCK_FF" >> "$GITHUB_ENV"
|
||||
if [ "$RUNNER_OS" = "Windows" ]; then echo "HUNT_MODE=loaded" >> "$GITHUB_ENV"; else echo "HUNT_MODE=alone" >> "$GITHUB_ENV"; fi
|
||||
mkdir -p evidence
|
||||
echo "ours: $FF"; echo "stock: $STOCK_FF"
|
||||
ls -la "$(dirname "$STOCK_FF")" | head -50
|
||||
- name: Arm git, the core from the branch
|
||||
run: |
|
||||
set -e
|
||||
timeout 300 python -m pip install --quiet --force-reinstall --no-deps "$CORE_GIT"
|
||||
timeout 300 python scripts/hunt_typing_core.py | tee evidence/core_git.txt
|
||||
grep -q "(_due): True" evidence/core_git.txt || { echo "the branch's keyboard is not the one installed"; exit 1; }
|
||||
- name: Control arms, the engines untouched (git_plain, stock_plain)
|
||||
run: |
|
||||
set +e
|
||||
bash scripts/hunt_engine_arm.sh git_plain ours "$FF"
|
||||
bash scripts/hunt_engine_arm.sh stock_plain stock "$STOCK_FF"
|
||||
- name: Patch the Juggler of both engines (omni.ja next to the executable), stamps for Page.dispatchKeyEvent
|
||||
run: |
|
||||
set -e
|
||||
timeout 600 python scripts/hunt_patch_omni.py ours "$FF" 2>&1 | tee evidence/patch_ours.txt
|
||||
timeout 600 python scripts/hunt_patch_omni.py stock "$STOCK_FF" 2>&1 | tee evidence/patch_stock.txt
|
||||
grep -q "^PATCHED" evidence/patch_ours.txt && grep -q "^PATCHED" evidence/patch_stock.txt
|
||||
- name: Arms git and stock with the stamps
|
||||
env:
|
||||
HUNT_STAMPS: "1"
|
||||
run: |
|
||||
set +e
|
||||
bash scripts/hunt_engine_arm.sh git ours "$FF"
|
||||
# the stock driver copies the browser's output into its own log only with this
|
||||
DEBUG=pw:browser bash scripts/hunt_engine_arm.sh stock stock "$STOCK_FF"
|
||||
- name: Summary
|
||||
if: always()
|
||||
run: |
|
||||
set +e
|
||||
{
|
||||
sed 's/^/ /' evidence/core_git.txt 2>/dev/null
|
||||
timeout 300 python scripts/hunt_engine_summary.py evidence "$RUNNER_OS"
|
||||
echo
|
||||
echo '```'
|
||||
grep -ahE "Traceback|Error" evidence/alone_*.log evidence/loaded_*.log | sort | uniq -c | head -20
|
||||
echo '```'
|
||||
} | 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: windows-flakes-engine-${{ matrix.os }}-${{ github.run_id }}
|
||||
path: evidence
|
||||
if-no-files-found: warn
|
||||
retention-days: 14
|
||||
@@ -0,0 +1,178 @@
|
||||
# windows-flakes-typing-hunt.yml - hunt scaffolding, never merged. Runs only on a push to a `hunt/windows-flakes-typing**` branch.
|
||||
# Typing on absolute deadlines: four arms (pypi = core 63.68.0 from PyPI; git = core from branch fix/typing-on-absolute-deadlines; both = that
|
||||
# core with origin/fix/no-thread-started-on-the-reader merged into it, plus the wrapper from oss-invisible/playwright@fix/no-thread-started-on-the-reader,
|
||||
# in its own venv; stock = stock Playwright), each x20 alone and x20 under four concurrent processes, per key planned / sent / seen by the page
|
||||
# (keydown and keyup, on two clocks: performance.now() in the handler and event.timeStamp); and the e2e test
|
||||
# test_a_store_that_answers_the_focus_does_not_eat_the_text x20 under `-n 4 --dist loadfile` for the three core arms. Every command is under `timeout 300`.
|
||||
name: windows flakes typing hunt
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ['hunt/windows-flakes-typing**']
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: windows-flakes-typing-hunt-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
CORE_GIT: "git+https://github.com/oss-invisible/core@fix/typing-on-absolute-deadlines"
|
||||
CORE_PYPI: "invisible-core==63.68.0"
|
||||
CORE_REPO: "https://github.com/oss-invisible/core"
|
||||
CORE_TYPING_BRANCH: "fix/typing-on-absolute-deadlines"
|
||||
READER_BRANCH: "fix/no-thread-started-on-the-reader"
|
||||
WRAPPER_GIT: "git+https://github.com/oss-invisible/playwright@fix/no-thread-started-on-the-reader"
|
||||
# Three e2e files that load the machine while the typing test runs (one per xdist worker with `--dist loadfile`).
|
||||
LOAD_FILES: "tests/test_a_click_waits_for_the_navigation_it_plans_e2e.py tests/test_a_mouse_click_makes_one_mousemove_on_its_point_e2e.py tests/test_a_pointer_event_is_handled_before_the_call_returns_e2e.py"
|
||||
TYPING_TEST: "tests/test_a_field_is_typed_after_a_pause.py::test_a_store_that_answers_the_focus_does_not_eat_the_text"
|
||||
|
||||
jobs:
|
||||
hunt:
|
||||
name: typing hunt ${{ matrix.os }}
|
||||
runs-on: ${{ matrix.os }}
|
||||
timeout-minutes: 180
|
||||
strategy:
|
||||
max-parallel: 1
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [windows-2022, ubuntu-24.04]
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
env:
|
||||
PYTHONUNBUFFERED: "1"
|
||||
steps:
|
||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
|
||||
with: { python-version: '3.11' }
|
||||
- name: Install
|
||||
run: |
|
||||
set -e
|
||||
timeout 300 python -m pip install --quiet --upgrade pip
|
||||
timeout 300 python -m pip install --quiet ".[dev]"
|
||||
timeout 300 python -m pip install --quiet "playwright==$(cat scripts/playwright_pin.txt)"
|
||||
echo "FF=$(cd "$RUNNER_TEMP" && timeout 300 python -m invisible_playwright fetch | tail -1)" >> "$GITHUB_ENV"
|
||||
timeout 300 python scripts/ci_lab_geoip.py build
|
||||
if [ "$RUNNER_OS" = "Linux" ]; then timeout 300 python -m playwright install --with-deps firefox; else timeout 300 python -m playwright install firefox; fi
|
||||
mkdir -p evidence
|
||||
- name: Arm pypi, the core from the index
|
||||
run: |
|
||||
set -e
|
||||
timeout 300 python -m pip install --quiet --force-reinstall --no-deps "$CORE_PYPI"
|
||||
timeout 300 python scripts/hunt_typing_core.py | tee evidence/core_pypi.txt
|
||||
- name: Arm pypi, typing per key, alone x20 and four at once x20
|
||||
run: |
|
||||
set +e
|
||||
export HUNT_ARM=pypi
|
||||
for n in 1 2 3 4; do timeout 300 python -u scripts/hunt_typing.py ours "$FF" >> "evidence/alone_pypi.log" 2>&1; done
|
||||
for c in 1 2 3 4; do timeout 300 python -u scripts/hunt_typing.py ours "$FF" > "evidence/loaded_pypi_$c.log" 2>&1 & done
|
||||
wait
|
||||
- name: Arm stock, typing per key, alone x20 and four at once x20
|
||||
run: |
|
||||
set +e
|
||||
export HUNT_ARM=stock
|
||||
for n in 1 2 3 4; do timeout 300 python -u scripts/hunt_typing.py stock "$FF" >> "evidence/alone_stock.log" 2>&1; done
|
||||
for c in 1 2 3 4; do timeout 300 python -u scripts/hunt_typing.py stock "$FF" > "evidence/loaded_stock_$c.log" 2>&1 & done
|
||||
wait
|
||||
- name: Test, core from the index, x20 under -n 4 --dist loadfile with three other e2e files
|
||||
run: |
|
||||
set +e
|
||||
for n in $(seq 1 20); do
|
||||
INVPW_BINARY_PATH="$FF" STEALTHFOX_E2E_BINARY="$FF" timeout 300 python -m pytest "$TYPING_TEST" $LOAD_FILES -n 4 --dist loadfile \
|
||||
-m e2e -o addopts='' -o junit_family=xunit2 -q -p no:cacheprovider -p no:rerunfailures -rs \
|
||||
--junitxml="evidence/test_pypi_$n.xml" > "evidence/test_pypi_$n.log" 2>&1
|
||||
echo "pypi run $n exit $?"
|
||||
done
|
||||
- name: Arm git, the core from the branch installed over the wheel
|
||||
run: |
|
||||
set -e
|
||||
timeout 300 python -m pip install --quiet --force-reinstall --no-deps "$CORE_GIT"
|
||||
timeout 300 python scripts/hunt_typing_core.py | tee evidence/core_git.txt
|
||||
grep -q "(_due): True" evidence/core_git.txt || { echo "the branch's keyboard is not the one installed"; exit 1; }
|
||||
- name: Arm git, typing per key, alone x20 and four at once x20
|
||||
run: |
|
||||
set +e
|
||||
export HUNT_ARM=git
|
||||
for n in 1 2 3 4; do timeout 300 python -u scripts/hunt_typing.py ours "$FF" >> "evidence/alone_git.log" 2>&1; done
|
||||
for c in 1 2 3 4; do timeout 300 python -u scripts/hunt_typing.py ours "$FF" > "evidence/loaded_git_$c.log" 2>&1 & done
|
||||
wait
|
||||
- name: Test, core from git, x20 under -n 4 --dist loadfile with three other e2e files
|
||||
run: |
|
||||
set +e
|
||||
for n in $(seq 1 20); do
|
||||
INVPW_BINARY_PATH="$FF" STEALTHFOX_E2E_BINARY="$FF" timeout 300 python -m pytest "$TYPING_TEST" $LOAD_FILES -n 4 --dist loadfile \
|
||||
-m e2e -o addopts='' -o junit_family=xunit2 -q -p no:cacheprovider -p no:rerunfailures -rs \
|
||||
--junitxml="evidence/test_git_$n.xml" > "evidence/test_git_$n.log" 2>&1
|
||||
echo "git run $n exit $?"
|
||||
done
|
||||
- name: Arm both, the core with the reader fix merged in, and the wrapper from its branch, in a venv of their own
|
||||
run: |
|
||||
set -eo pipefail
|
||||
T="$(cygpath -m "$RUNNER_TEMP" 2>/dev/null || echo "$RUNNER_TEMP")"
|
||||
git clone --quiet "$CORE_REPO" "$T/core_both"
|
||||
(
|
||||
cd "$T/core_both"
|
||||
git checkout --quiet "$CORE_TYPING_BRANCH"
|
||||
echo "core typing head: $(git rev-parse HEAD) ($CORE_TYPING_BRANCH)"
|
||||
echo "core reader head: $(git rev-parse "origin/$READER_BRANCH") ($READER_BRANCH)"
|
||||
if ! git -c user.name=hunt -c user.email=hunt@invalid merge --no-edit "origin/$READER_BRANCH"; then
|
||||
echo "MERGE CONFLICT: $READER_BRANCH does not merge into $CORE_TYPING_BRANCH"; git status --short; exit 1
|
||||
fi
|
||||
echo "core merged head: $(git rev-parse HEAD)"
|
||||
) | tee evidence/heads_both.txt
|
||||
echo "wrapper head: $(git ls-remote "${WRAPPER_GIT#git+}" 2>/dev/null | head -1 | cut -f1) ($READER_BRANCH)" | tee -a evidence/heads_both.txt
|
||||
# a venv of its own: the main environment keeps the hunt's own wrapper for every other arm
|
||||
python -m venv "$T/venv_both"
|
||||
if [ -x "$T/venv_both/Scripts/python.exe" ]; then BP="$T/venv_both/Scripts/python.exe"; else BP="$T/venv_both/bin/python"; fi
|
||||
echo "BOTH_PY=$BP" >> "$GITHUB_ENV"
|
||||
timeout 300 "$BP" -m pip install --quiet --upgrade pip
|
||||
timeout 300 "$BP" -m pip install --quiet ".[dev]"
|
||||
timeout 300 "$BP" -m pip install --quiet "playwright==$(cat scripts/playwright_pin.txt)"
|
||||
timeout 300 "$BP" -m pip install --quiet --force-reinstall --no-deps "$WRAPPER_GIT"
|
||||
timeout 300 "$BP" -m pip install --quiet --force-reinstall --no-deps "$T/core_both"
|
||||
timeout 300 "$BP" scripts/hunt_typing_core.py | tee evidence/core_both.txt
|
||||
grep -q "(_due): True" evidence/core_both.txt || { echo "the merged core's keyboard is not the one installed"; exit 1; }
|
||||
- name: Arm both, typing per key, alone x20 and four at once x20
|
||||
run: |
|
||||
set +e
|
||||
export HUNT_ARM=both
|
||||
for n in 1 2 3 4; do timeout 300 "$BOTH_PY" -u scripts/hunt_typing.py ours "$FF" >> "evidence/alone_both.log" 2>&1; done
|
||||
for c in 1 2 3 4; do timeout 300 "$BOTH_PY" -u scripts/hunt_typing.py ours "$FF" > "evidence/loaded_both_$c.log" 2>&1 & done
|
||||
wait
|
||||
- name: Test, both, x20 under -n 4 --dist loadfile with three other e2e files
|
||||
run: |
|
||||
set +e
|
||||
# `-o pythonpath=` empties the checkout's pythonpath = src, so the venv's wrapper (the branch's) is the one the test imports
|
||||
for n in $(seq 1 20); do
|
||||
INVPW_BINARY_PATH="$FF" STEALTHFOX_E2E_BINARY="$FF" timeout 300 "$BOTH_PY" -m pytest "$TYPING_TEST" $LOAD_FILES -n 4 --dist loadfile -m e2e -o addopts='' -o pythonpath= -o junit_family=xunit2 -q -p no:cacheprovider -p no:rerunfailures -rs --junitxml="evidence/test_both_$n.xml" > "evidence/test_both_$n.log" 2>&1
|
||||
echo "both run $n exit $?"
|
||||
done
|
||||
- name: Summary
|
||||
if: always()
|
||||
run: |
|
||||
set +e
|
||||
{
|
||||
sed 's/^/ /' evidence/core_pypi.txt evidence/core_git.txt evidence/heads_both.txt evidence/core_both.txt 2>/dev/null
|
||||
timeout 300 python scripts/hunt_typing_summary.py evidence "$RUNNER_OS"
|
||||
echo
|
||||
echo '```'
|
||||
grep -ahE "Traceback|Error" evidence/alone_*.log evidence/loaded_*.log | sort | uniq -c | head
|
||||
echo '```'
|
||||
} | 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: windows-flakes-typing-${{ matrix.os }}-${{ github.run_id }}
|
||||
path: evidence
|
||||
if-no-files-found: warn
|
||||
retention-days: 14
|
||||
@@ -0,0 +1,25 @@
|
||||
#!/usr/bin/env bash
|
||||
# HUNT SCAFFOLDING, NEVER MERGED: one arm of the engine hunt.
|
||||
# Usage: scripts/hunt_engine_arm.sh ARM ours|stock BINARY (env: HUNT_MODE=alone|loaded, HUNT_STAMPS=1 for a patched engine, DEBUG=pw:browser for stock's)
|
||||
# alone: four runs of hunt_typing.py one after the other (x5 each = 20 runs); loaded: four at once (x5 each = 20 runs, four processes).
|
||||
# The logs are evidence/alone_<arm>.log or evidence/loaded_<arm>_<n>.log, which scripts/hunt_engine_summary.py reads.
|
||||
set +e
|
||||
arm=$1
|
||||
engine=$2
|
||||
bin=$3
|
||||
mkdir -p evidence
|
||||
export HUNT_ARM="$arm"
|
||||
if [ "$HUNT_MODE" = "alone" ]; then
|
||||
for n in 1 2 3 4; do
|
||||
timeout 600 python -u scripts/hunt_typing.py "$engine" "$bin" >> "evidence/alone_${arm}.log" 2>&1
|
||||
echo "arm $arm alone $n exit $?"
|
||||
done
|
||||
else
|
||||
for c in 1 2 3 4; do
|
||||
timeout 600 python -u scripts/hunt_typing.py "$engine" "$bin" > "evidence/loaded_${arm}_$c.log" 2>&1 &
|
||||
done
|
||||
wait
|
||||
echo "arm $arm loaded done"
|
||||
fi
|
||||
echo "arm $arm: HUNT-TYPING lines $(cat evidence/*_${arm}.log evidence/*_${arm}_[0-9]*.log 2>/dev/null | grep -ac '^HUNT-TYPING '), HUNTKEY lines in logs $(cat evidence/*_${arm}.log evidence/*_${arm}_[0-9]*.log 2>/dev/null | grep -ac 'HUNTKEY ')"
|
||||
exit 0
|
||||
@@ -0,0 +1,299 @@
|
||||
"""HUNT SCAFFOLDING, NEVER MERGED: the step summary of the engine hunt (where a typed key's delay is born inside the engine).
|
||||
|
||||
Usage: python scripts/hunt_engine_summary.py EVIDENCE_DIR OS_NAME
|
||||
Reads EVIDENCE_DIR/{alone,loaded}_<arm>*.log: the HUNT-TYPING lines of scripts/hunt_typing.py (one per run) and, for the stock arm, the
|
||||
HUNTKEY lines the Playwright driver copied into the same log (DEBUG=pw:browser), put into the run whose typing window holds them.
|
||||
Arms: git (core of fix/typing-on-absolute-deadlines, engine patched by scripts/hunt_patch_omni.py), stock (stock Playwright Firefox, its
|
||||
Juggler patched the same way), git_plain and stock_plain (the same, engine untouched: what the page sees without the stamps, to show what
|
||||
the stamps cost).
|
||||
|
||||
The stamps of one key event (a keydown or keyup command; tags in scripts/hunt_patch_omni.py) are joined to the page's event of the same
|
||||
(type, key, n-th time) and to the client's send (keydown, not Shift). Between two consecutive PRESENT tags of
|
||||
|
||||
sent -> P1 -> C2 -> C3 -> C4 -> C4r -> C5 -> h (h = performance.now() in the page's handler)
|
||||
|
||||
there is one step, named "A>B"; the steps add up exactly to sent -> h. "timer excess" = (C3>C4) - the delay planned (C3's delay=).
|
||||
"timestamp lag" = (h - event.timeStamp) - planned latency: how much longer than planned the event, born at the top of the function,
|
||||
waited for the page's handler. The stock engine has no latency timer, so its chain is sent, P1, C2, C5, h.
|
||||
|
||||
A page gap is the time between the handlers of two consecutive keydowns that are not Shift. For every page gap under GAP_MS (150) the
|
||||
step that absorbed the delay is the one where the earlier key took longer than the later one by the most: the page gap equals the send
|
||||
gap plus the later key's steps minus the earlier key's, so (earlier - later) per step is what shortened it. If the sends themselves were
|
||||
closer than GAP_MS the client is named instead.
|
||||
"""
|
||||
import glob
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
GAP_MS = 150.0
|
||||
ARMS = ["git", "stock", "git_plain", "stock_plain"]
|
||||
MODES = ["alone", "loaded"]
|
||||
ORDER = ["sent", "P1", "C2", "C3", "C4", "C4r", "C5", "h"]
|
||||
LINE = re.compile(r"(\S+) (\d+) (\d+) (\S+) ([\d.]+) (\S+) (\S+)(?: (.*))?$")
|
||||
|
||||
|
||||
def q(v, f):
|
||||
v = sorted(v)
|
||||
return v[min(len(v) - 1, int(len(v) * f))] if v else None
|
||||
|
||||
|
||||
def fmt(x):
|
||||
return "-" if x is None else ("%.1f" % x if isinstance(x, float) else str(x))
|
||||
|
||||
|
||||
def parse_stamp(text):
|
||||
i = text.find("HUNTKEY ")
|
||||
if i >= 0:
|
||||
text = text[i + 8:]
|
||||
m = LINE.match(text.strip())
|
||||
if not m:
|
||||
return None
|
||||
proc, pid, call, tag, wall, typ, key, extra = m.groups()
|
||||
from urllib.parse import unquote
|
||||
return {"proc": proc, "pid": int(pid), "call": int(call), "tag": tag, "wall": float(wall), "type": typ,
|
||||
"key": unquote(key), "extra": extra or ""}
|
||||
|
||||
|
||||
def read_log(path):
|
||||
runs, loose = [], []
|
||||
with open(path, encoding="utf-8", errors="replace") as f:
|
||||
for line in f:
|
||||
if line.startswith("HUNT-TYPING "):
|
||||
try:
|
||||
runs.append(json.loads(line[len("HUNT-TYPING "):]))
|
||||
except ValueError:
|
||||
pass
|
||||
elif "HUNTKEY " in line:
|
||||
s = parse_stamp(line)
|
||||
if s:
|
||||
loose.append(s)
|
||||
return runs, loose
|
||||
|
||||
|
||||
def build_events(run, loose, sources):
|
||||
"""The key events of one run: {(type, key, n): {"page": (h, e), "tags": {tag: wall}, ...}}, in page order."""
|
||||
stamps = {}
|
||||
for text in list(run.get("hk") or []):
|
||||
s = parse_stamp(text)
|
||||
if s:
|
||||
stamps[text.strip()] = (s, "pipe")
|
||||
for text in list(run.get("hs") or []):
|
||||
s = parse_stamp(text)
|
||||
if s:
|
||||
stamps.setdefault(text.strip(), (s, "page"))
|
||||
w0, w1 = run["win"][0] - 100, run["win"][1] + 1000
|
||||
for s in loose:
|
||||
if w0 <= s["wall"] <= w1:
|
||||
stamps.setdefault("%s %s %s %s" % (s["proc"], s["pid"], s["call"], s["tag"]) + repr(s["wall"]), (s, "log"))
|
||||
# one source per distinct stamp (same proc, pid, call, tag, wall): the pipe or log copy wins over the page's
|
||||
seen = {}
|
||||
for text, (s, src) in stamps.items():
|
||||
k = (s["proc"], s["pid"], s["tag"], s["wall"], s["type"], s["key"])
|
||||
if k not in seen or src != "page":
|
||||
seen[k] = (s, src)
|
||||
by = {}
|
||||
for s, src in seen.values():
|
||||
sources[(s["proc"], src)] = sources.get((s["proc"], src), 0) + 1
|
||||
by.setdefault((s["tag"], s["type"], s["key"]), []).append(s)
|
||||
for v in by.values():
|
||||
v.sort(key=lambda s: s["wall"])
|
||||
events, count = {}, {}
|
||||
nonshift_down = 0
|
||||
for typ, key, h, e in run.get("ev") or []:
|
||||
n = count.get((typ, key), 0)
|
||||
count[(typ, key)] = n + 1
|
||||
ev = {"type": typ, "key": key, "n": n, "h": h, "e": e, "tags": {}, "delay": None, "latency": None, "sent": None}
|
||||
for tag in ORDER[1:-1]:
|
||||
lst = by.get((tag, typ, key)) or []
|
||||
if n < len(lst):
|
||||
ev["tags"][tag] = lst[n]["wall"]
|
||||
if tag == "C3":
|
||||
m = re.search(r"delay=([\d.]+)", lst[n]["extra"])
|
||||
ev["delay"] = float(m.group(1)) if m else None
|
||||
if tag == "C2":
|
||||
m = re.search(r"latency=([\d.]+)", lst[n]["extra"])
|
||||
ev["latency"] = float(m.group(1)) if m else None
|
||||
if typ == "keydown" and key != "Shift":
|
||||
ev["nonshift_index"] = nonshift_down
|
||||
nonshift_down += 1
|
||||
events[(typ, key, n)] = ev
|
||||
sent = run.get("sent_wall_ms") or []
|
||||
if len(sent) == nonshift_down:
|
||||
for ev in events.values():
|
||||
if "nonshift_index" in ev:
|
||||
ev["sent"] = sent[ev["nonshift_index"]]
|
||||
return list(events.values())
|
||||
|
||||
|
||||
def chain(ev):
|
||||
"""[(name, wall)] of the tags present, in order, ending at the page's handler."""
|
||||
pts = []
|
||||
if ev["sent"] is not None:
|
||||
pts.append(("sent", ev["sent"]))
|
||||
for tag in ORDER[1:-1]:
|
||||
if tag in ev["tags"]:
|
||||
pts.append((tag, ev["tags"][tag]))
|
||||
pts.append(("h", ev["h"]))
|
||||
return pts
|
||||
|
||||
|
||||
def steps(ev):
|
||||
pts = chain(ev)
|
||||
out = {}
|
||||
for (a, ta), (b, tb) in zip(pts, pts[1:]):
|
||||
out["%s>%s" % (a, b)] = tb - ta
|
||||
if "C3" in ev["tags"] and "C4" in ev["tags"] and ev["delay"] is not None:
|
||||
out["timer planned"] = ev["delay"]
|
||||
out["timer excess"] = (ev["tags"]["C4"] - ev["tags"]["C3"]) - ev["delay"]
|
||||
if ev["latency"] is not None:
|
||||
out["timestamp lag"] = (ev["h"] - ev["e"]) - ev["latency"]
|
||||
if "P1" in ev["tags"]:
|
||||
out["P1>h total"] = ev["h"] - ev["tags"]["P1"]
|
||||
return out
|
||||
|
||||
|
||||
def load(evidence, mode, arm, sources):
|
||||
"""-> list of runs, each {"run": json, "events": [...]}"""
|
||||
out = []
|
||||
paths = glob.glob(os.path.join(evidence, "%s_%s.log" % (mode, arm))) + glob.glob(os.path.join(evidence, "%s_%s_[0-9]*.log" % (mode, arm)))
|
||||
for path in sorted(paths):
|
||||
runs, loose = read_log(path)
|
||||
for r in runs:
|
||||
if "win" not in r:
|
||||
continue
|
||||
out.append({"run": r, "events": build_events(r, loose, sources)})
|
||||
return out
|
||||
|
||||
|
||||
def gaps_of(events):
|
||||
d = [e for e in events if e["type"] == "keydown" and e["key"] != "Shift"]
|
||||
return list(zip(d, d[1:]))
|
||||
|
||||
|
||||
def step_table(data_by_arm, kind):
|
||||
names = []
|
||||
cols = {}
|
||||
for arm, runs in data_by_arm.items():
|
||||
vals = {}
|
||||
for r in runs:
|
||||
for ev in r["events"]:
|
||||
if ev["type"] != kind:
|
||||
continue
|
||||
for k, v in steps(ev).items():
|
||||
vals.setdefault(k, []).append(v)
|
||||
cols[arm] = vals
|
||||
for k in vals:
|
||||
if k not in names:
|
||||
names.append(k)
|
||||
pri = {"sent>P1": 0, "P1>C2": 1, "C2>C3": 2, "timer planned": 3, "C3>C4": 4, "timer excess": 5, "C4>C4r": 6, "C4r>C5": 7,
|
||||
"C2>C5": 8, "C5>h": 9, "timestamp lag": 10, "P1>h total": 11}
|
||||
names.sort(key=lambda k: pri.get(k, 99))
|
||||
lines = ["| step (ms) | " + " | ".join("%s p50 / p95 / max (n)" % a for a in cols) + " |",
|
||||
"|---|" + "---|" * len(cols)]
|
||||
for k in names:
|
||||
cells = []
|
||||
for arm in cols:
|
||||
v = cols[arm].get(k)
|
||||
cells.append("-" if not v else "%s / %s / %s (%d)" % (fmt(q(v, .5)), fmt(q(v, .95)), fmt(max(v)), len(v)))
|
||||
lines.append("| %s | %s |" % (k, " | ".join(cells)))
|
||||
return lines
|
||||
|
||||
|
||||
def main():
|
||||
evidence, os_name = sys.argv[1], sys.argv[2]
|
||||
for mode in MODES:
|
||||
sources, data = {}, {}
|
||||
for arm in ARMS:
|
||||
d = load(evidence, mode, arm, sources if arm in ("git", "stock") else {})
|
||||
if d:
|
||||
data[arm] = d
|
||||
if not data:
|
||||
continue
|
||||
print("## engine hunt, %s, %s" % (os_name, mode))
|
||||
print()
|
||||
print("runs per arm: " + ", ".join("%s %d" % (a, len(r)) for a, r in data.items()))
|
||||
print()
|
||||
print("stamps by where they came from (process, source): " + (", ".join(
|
||||
"%s/%s %d" % (p, s, n) for (p, s), n in sorted(sources.items())) or "none"))
|
||||
print()
|
||||
# coverage
|
||||
for arm in ("git", "stock"):
|
||||
if arm in data:
|
||||
evs = [e for r in data[arm] for e in r["events"]]
|
||||
full = sum(1 for e in evs if "P1" in e["tags"] and "C2" in e["tags"] and "C5" in e["tags"])
|
||||
print("- %s: %d key events, %d with P1, C2 and C5" % (arm, len(evs), full))
|
||||
print()
|
||||
# page gaps, every arm
|
||||
print("### page keydown gaps under %d ms (handler clock)" % GAP_MS)
|
||||
print()
|
||||
print("| arm | runs | runs with a gap under %d | gaps under %d / gaps | smallest gap p50 / min | planned gap min |" % (GAP_MS, GAP_MS))
|
||||
print("|---|---|---|---|---|---|")
|
||||
for arm, runs in data.items():
|
||||
short = total = with_short = 0
|
||||
mins = []
|
||||
plan = []
|
||||
for r in runs:
|
||||
gs = [(b["h"] - a["h"]) for a, b in gaps_of(r["events"])]
|
||||
if gs:
|
||||
mins.append(min(gs))
|
||||
total += len(gs)
|
||||
n = sum(1 for g in gs if g < GAP_MS)
|
||||
short += n
|
||||
with_short += 1 if n else 0
|
||||
if r["run"].get("plan_min_keydown_gap_ms") is not None:
|
||||
plan.append(r["run"]["plan_min_keydown_gap_ms"])
|
||||
print("| %s | %d | %d | %d / %d | %s / %s | %s |" % (arm, len(runs), with_short, short, total, fmt(q(mins, .5)),
|
||||
fmt(min(mins) if mins else None), fmt(min(plan) if plan else None)))
|
||||
print()
|
||||
stamped = {a: r for a, r in data.items() if a in ("git", "stock")}
|
||||
for kind in ("keydown", "keyup"):
|
||||
if stamped:
|
||||
print("### steps of a %s command (ms)" % kind)
|
||||
print()
|
||||
print("\n".join(step_table(stamped, kind)))
|
||||
print()
|
||||
# which step absorbed it
|
||||
for arm, runs in stamped.items():
|
||||
rows, counts = [], {}
|
||||
for ri, r in enumerate(runs):
|
||||
for a, b in gaps_of(r["events"]):
|
||||
gap = b["h"] - a["h"]
|
||||
if gap >= GAP_MS:
|
||||
continue
|
||||
sa, sb = steps(a), steps(b)
|
||||
sendgap = (b["sent"] - a["sent"]) if a["sent"] is not None and b["sent"] is not None else None
|
||||
names = [k for k in sa if ">" in k and k != "P1>h total" and k in sb]
|
||||
if sendgap is not None and sendgap < GAP_MS:
|
||||
who, amount = "client send", sendgap
|
||||
elif names and sendgap is not None:
|
||||
who = max(names, key=lambda k: sa[k] - sb[k])
|
||||
amount = sa[who] - sb[who]
|
||||
else:
|
||||
who, amount = "unstamped", None
|
||||
counts[who] = counts.get(who, 0) + 1
|
||||
rows.append((ri, a["key"], b["key"], sendgap, gap, who, amount,
|
||||
{k: sa[k] for k in names}, {k: sb[k] for k in names}))
|
||||
print("### %s: page gaps under %d ms and the step that absorbed them" % (arm, GAP_MS))
|
||||
print()
|
||||
if not rows:
|
||||
print("none")
|
||||
print()
|
||||
continue
|
||||
print("culprit counts: " + ", ".join("%s %d" % (k, v) for k, v in sorted(counts.items(), key=lambda kv: -kv[1])))
|
||||
print()
|
||||
print("| run | keys | send gap | page gap | absorbed by (earlier - later) | earlier key's steps | later key's steps |")
|
||||
print("|---|---|---|---|---|---|---|")
|
||||
for ri, ka, kb, sg, gap, who, amount, sa, sb in rows[:60]:
|
||||
print("| %d | %s>%s | %s | %s | %s %s | %s | %s |" % (
|
||||
ri, ka, kb, fmt(sg), fmt(gap), who, fmt(amount),
|
||||
" ".join("%s=%s" % (k, fmt(v)) for k, v in sa.items()),
|
||||
" ".join("%s=%s" % (k, fmt(v)) for k, v in sb.items())))
|
||||
if len(rows) > 60:
|
||||
print("(%d more not listed)" % (len(rows) - 60))
|
||||
print()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,76 @@
|
||||
"""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 sys
|
||||
import threading
|
||||
import time
|
||||
|
||||
ENGINE = sys.argv[1]
|
||||
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.monotonic(), 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.monotonic()
|
||||
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.monotonic()
|
||||
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}), 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,283 @@
|
||||
"""HUNT SCAFFOLDING, NEVER MERGED: put time stamps into the Juggler of an engine, to see where a typed key's delay is born.
|
||||
|
||||
Usage: python scripts/hunt_patch_omni.py ours|stock ENGINE_EXE [--dry-run]
|
||||
|
||||
ENGINE_EXE is the browser executable (what `python -m invisible_playwright fetch` prints last, or stock Playwright's
|
||||
`firefox.executable_path`). The Juggler lives in the omni.ja that sits NEXT TO the executable (the GRE one), not in browser/omni.ja:
|
||||
ours as `modules/juggler/{protocol/PageHandler.js,content/PageAgent.js}`, stock Playwright's as
|
||||
`chrome/juggler/content/{protocol/PageHandler.js,content/PageAgent.js}`. A tree that ships it loose (modules/juggler/ on disk) is patched
|
||||
in place. The first run keeps `omni.ja.orig` (or `<file>.orig`) next to what it changed.
|
||||
|
||||
What goes in (one block appended to each of the two files, plus two edits inside PageAgent._dispatchKeyEvent). Every stamp is a line
|
||||
|
||||
HUNTKEY <proc> <pid> <call> <tag> <wall_ms> <type> <urlencoded key> [extra]
|
||||
|
||||
written with dump() when the call has ended (buffered until then, so the dump's own cost is not inside the interval being measured) and,
|
||||
for the content process, also pushed into `window.__hs` of the page's main window (a Windows content process may have no stdout):
|
||||
|
||||
P1 parent: Page.dispatchKeyEvent received (PageHandler.prototype['Page.dispatchKeyEvent'], wrapped)
|
||||
C2 content: dispatchKeyEvent received (PageAgent.prototype._dispatchKeyEvent, wrapped)
|
||||
C3 content: latency timer armed, extra delay=<ms> (the `await new Promise(f => setTimeout(f, latency))` of _dispatchKeyEvent)
|
||||
C4 content: the timer's callback runs
|
||||
C4r content: the await resumed
|
||||
C5 content: just before the DOM event is dispatched (tip.keydown / tip.keyup / tip.commitCompositionWith)
|
||||
C6 content: _dispatchKeyEvent returned
|
||||
P7 parent: the handler is about to answer
|
||||
|
||||
`wall_ms` is the wall clock with sub-millisecond digits: Date.now() read on the tick it changes, once per process, as an anchor for
|
||||
ChromeUtils.now() (monotonic, microseconds). dump() needs `browser.dom.window.dump.enabled` (off in a release build): the caller passes it.
|
||||
The stock engine has no latency, so it has P1, C2, C5, C6, P7 only.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import sys
|
||||
import zipfile
|
||||
|
||||
HELPER = r"""
|
||||
// ---- HUNTKEY begin: hunt scaffolding, never merged ----
|
||||
const __HK = (() => {
|
||||
const clk = () => { try { return ChromeUtils.now(); } catch (e) { return NaN; } };
|
||||
let anchor = NaN;
|
||||
try {
|
||||
const t0 = clk();
|
||||
const a = Date.now();
|
||||
let b = a;
|
||||
while (b === a && clk() - t0 < 30) b = Date.now();
|
||||
anchor = b - clk();
|
||||
} catch (e) {}
|
||||
const wall = () => (anchor === anchor) ? anchor + clk() : Date.now();
|
||||
let pid = 0;
|
||||
try { pid = Services.appinfo.processID; } catch (e) {}
|
||||
const buf = [];
|
||||
let seq = 0;
|
||||
return {
|
||||
stamp(proc, tag, type, key, extra) {
|
||||
try {
|
||||
if (tag === 'P1' || tag === 'C2') seq++;
|
||||
buf.push([proc, pid, seq, tag, wall().toFixed(3), type, encodeURIComponent(String(key)), extra || ''].join(' '));
|
||||
} catch (e) {}
|
||||
},
|
||||
flush(win) {
|
||||
if (!buf.length) return;
|
||||
const lines = buf.splice(0);
|
||||
try { dump(lines.map(l => 'HUNTKEY ' + l + '\n').join('')); } catch (e) {}
|
||||
if (!win) return;
|
||||
try {
|
||||
const w = win.wrappedJSObject;
|
||||
if (!w.__hs) w.__hs = new w.Array();
|
||||
for (const l of lines) w.__hs.push(l);
|
||||
} catch (e) {}
|
||||
},
|
||||
};
|
||||
})();
|
||||
"""
|
||||
|
||||
PARENT_WRAP = r"""
|
||||
(() => {
|
||||
const name = 'Page.dispatchKeyEvent';
|
||||
const proto = (typeof PageHandler === 'function') ? PageHandler.prototype : null;
|
||||
const orig = proto && proto[name];
|
||||
if (typeof orig !== 'function') return;
|
||||
proto[name] = async function(params) {
|
||||
const t = params && params.type, k = params && params.key;
|
||||
__HK.stamp('parent', 'P1', t, k, 'latency=' + (params && params.latency));
|
||||
try {
|
||||
return await orig.call(this, params);
|
||||
} finally {
|
||||
__HK.stamp('parent', 'P7', t, k);
|
||||
__HK.flush(null);
|
||||
}
|
||||
};
|
||||
})();
|
||||
// ---- HUNTKEY end ----
|
||||
"""
|
||||
|
||||
CONTENT_WRAP = r"""
|
||||
(() => {
|
||||
const proto = (typeof PageAgent === 'function') ? PageAgent.prototype : null;
|
||||
const orig = proto && proto._dispatchKeyEvent;
|
||||
if (typeof orig !== 'function') return;
|
||||
proto._dispatchKeyEvent = async function(params) {
|
||||
const t = params && params.type, k = params && params.key;
|
||||
__HK.stamp('content', 'C2', t, k, 'latency=' + (params && params.latency));
|
||||
try {
|
||||
return await orig.call(this, params);
|
||||
} finally {
|
||||
__HK.stamp('content', 'C6', t, k);
|
||||
let win = null;
|
||||
try { win = this._frameTree.mainFrame().domWindow(); } catch (e) {}
|
||||
__HK.flush(win);
|
||||
}
|
||||
};
|
||||
})();
|
||||
// ---- HUNTKEY end ----
|
||||
"""
|
||||
|
||||
MARK = "HUNTKEY begin"
|
||||
|
||||
# The latency timer of PageAgent._dispatchKeyEvent (juggler/content/PageAgent.js:940-941 in the source tree): a single statement under
|
||||
# `if (latency > 0)`, so it is replaced by a block.
|
||||
TIMER = re.compile(r"await new Promise\(\s*f\s*=>\s*setTimeout\(\s*f\s*,\s*latency\s*\)\s*\);")
|
||||
TIMER_NEW = ("{ __HK.stamp('content', 'C3', type, key, 'delay=' + latency); "
|
||||
"await new Promise(f => setTimeout(() => { __HK.stamp('content', 'C4', type, key); f(); }, latency)); "
|
||||
"__HK.stamp('content', 'C4r', type, key); }")
|
||||
# The ways the function hands the event to the TextInputProcessor (PageAgent.js:944, 947, 951 in the source tree).
|
||||
TIP = re.compile(r"\btip\.(keydown|keyup|commitCompositionWith)\(")
|
||||
FUNC = re.compile(r"async _dispatchKeyEvent\(\{[^}]*\}\)\s*\{")
|
||||
NEXT_METHOD = re.compile(r"\n (?:async )?[A-Za-z_]\w*\(")
|
||||
|
||||
|
||||
def patch_page_handler(text):
|
||||
anchors = {"class PageHandler": bool(re.search(r"\bclass PageHandler\b", text)),
|
||||
"Page.dispatchKeyEvent": "['Page.dispatchKeyEvent']" in text}
|
||||
if MARK in text:
|
||||
return text, dict(anchors, already=True)
|
||||
if not all(anchors.values()):
|
||||
return None, anchors
|
||||
return text.rstrip("\n") + "\n" + HELPER + PARENT_WRAP, anchors
|
||||
|
||||
|
||||
def patch_page_agent(text):
|
||||
anchors = {"class PageAgent": bool(re.search(r"\bclass PageAgent\b", text))}
|
||||
m = FUNC.search(text)
|
||||
anchors["_dispatchKeyEvent"] = bool(m)
|
||||
if MARK in text:
|
||||
return text, dict(anchors, already=True)
|
||||
if not (anchors["class PageAgent"] and m):
|
||||
return None, anchors
|
||||
n = NEXT_METHOD.search(text, m.end())
|
||||
start, end = m.start(), (n.start() if n else len(text))
|
||||
body = text[start:end]
|
||||
body, n_timer = TIMER.subn(lambda _m: TIMER_NEW, body)
|
||||
body, n_tip = TIP.subn(
|
||||
lambda t: "(__HK.stamp('content', 'C5', type, key, '%s'), tip).%s(" % (t.group(1), t.group(1)), body)
|
||||
# stock has no `latency`: its absence is not an error, only reported
|
||||
anchors["latency timer"] = n_timer == 1
|
||||
anchors["tip calls"] = n_tip
|
||||
if n_tip < 1:
|
||||
return None, anchors
|
||||
return text[:start] + body + text[end:] + "\n" + HELPER + CONTENT_WRAP, anchors
|
||||
|
||||
|
||||
JOBS = {"PageHandler.js": patch_page_handler, "PageAgent.js": patch_page_agent}
|
||||
|
||||
|
||||
def rewrite_jar(path, replacements):
|
||||
"""Write `path` again with `replacements` (name -> bytes): the same members in the same order, stored ones stored and deflated ones
|
||||
deflated, as a plain zip (Firefox reads both that and Mozilla's optimized layout; the core's open_jar reads both too)."""
|
||||
from invisible_core.jar import open_jar
|
||||
jar = open_jar(path)
|
||||
tmp = path + ".hunt.tmp"
|
||||
with zipfile.ZipFile(tmp, "w") as z:
|
||||
for name, (method, _c, _u, _l) in jar._entries.items():
|
||||
info = zipfile.ZipInfo(name, date_time=(2020, 1, 1, 0, 0, 0))
|
||||
info.compress_type = zipfile.ZIP_STORED if method == 0 else zipfile.ZIP_DEFLATED
|
||||
info.external_attr = 0o644 << 16
|
||||
z.writestr(info, replacements[name] if name in replacements else jar.read(name), compresslevel=6)
|
||||
return tmp
|
||||
|
||||
|
||||
def verify_jar(old, new, changed):
|
||||
"""Every member of the new jar is the old one's, byte for byte, except `changed`; same names."""
|
||||
from invisible_core.jar import open_jar
|
||||
a, b = open_jar(old), open_jar(new)
|
||||
assert a.names() == b.names(), "member names differ: %s" % sorted(a.names() ^ b.names())[:5]
|
||||
for name in sorted(a.names()):
|
||||
same = a.read(name) == b.read(name)
|
||||
if name in changed:
|
||||
assert not same, "%s was not changed" % name
|
||||
else:
|
||||
assert same, "%s changed" % name
|
||||
|
||||
|
||||
def patch_omni(path, dry_run):
|
||||
from invisible_core.jar import open_jar
|
||||
jar = open_jar(path)
|
||||
found = {}
|
||||
for name in sorted(jar.names()):
|
||||
base = name.rsplit("/", 1)[-1]
|
||||
if base in JOBS and "juggler" in name:
|
||||
found[name] = base
|
||||
if not found:
|
||||
return None
|
||||
report = {"omni": path, "members": {}}
|
||||
replacements = {}
|
||||
for name, base in found.items():
|
||||
new, anchors = JOBS[base](jar.read(name).decode("utf-8"))
|
||||
report["members"][name] = anchors
|
||||
if new is None:
|
||||
raise SystemExit("ANCHOR MISSING in %s %s: %s" % (path, name, json.dumps(anchors)))
|
||||
if not anchors.get("already"):
|
||||
replacements[name] = new.encode("utf-8")
|
||||
report["changed"] = sorted(replacements)
|
||||
if replacements and not dry_run:
|
||||
tmp = rewrite_jar(path, replacements)
|
||||
verify_jar(path, tmp, set(replacements))
|
||||
if not os.path.exists(path + ".orig"):
|
||||
shutil.copy2(path, path + ".orig")
|
||||
os.replace(tmp, path)
|
||||
report["written"] = os.path.getsize(path)
|
||||
return report
|
||||
|
||||
|
||||
def patch_loose(root, dry_run):
|
||||
report = {"loose": root, "members": {}, "changed": []}
|
||||
for dirpath, _dirs, files in os.walk(os.path.join(root, "modules", "juggler")):
|
||||
for f in files:
|
||||
if f in JOBS:
|
||||
p = os.path.join(dirpath, f)
|
||||
with open(p, encoding="utf-8") as fh:
|
||||
new, anchors = JOBS[f](fh.read())
|
||||
report["members"][p] = anchors
|
||||
if new is None:
|
||||
raise SystemExit("ANCHOR MISSING in %s: %s" % (p, json.dumps(anchors)))
|
||||
if not anchors.get("already"):
|
||||
report["changed"].append(p)
|
||||
if not dry_run:
|
||||
if not os.path.exists(p + ".orig"):
|
||||
shutil.copy2(p, p + ".orig")
|
||||
with open(p, "w", encoding="utf-8", newline="\n") as fh:
|
||||
fh.write(new)
|
||||
return report if report["members"] else None
|
||||
|
||||
|
||||
def main():
|
||||
kind, exe = sys.argv[1], sys.argv[2]
|
||||
dry = "--dry-run" in sys.argv
|
||||
root = os.path.dirname(os.path.abspath(exe))
|
||||
reports = []
|
||||
# the GRE omni.ja next to the executable first; browser/omni.ja only to say it was looked at
|
||||
for rel in ("omni.ja", os.path.join("browser", "omni.ja")):
|
||||
p = os.path.join(root, rel)
|
||||
if os.path.exists(p):
|
||||
r = patch_omni(p, dry)
|
||||
print("looked in %s: %s" % (p, "juggler found" if r else "no juggler"))
|
||||
if r:
|
||||
reports.append(r)
|
||||
if not reports:
|
||||
r = patch_loose(root, dry)
|
||||
print("looked at the loose tree %s: %s" % (root, "juggler found" if r else "no juggler"))
|
||||
if r:
|
||||
reports.append(r)
|
||||
if not reports:
|
||||
raise SystemExit("no Juggler PageHandler.js / PageAgent.js in any omni.ja or loose tree under %s" % root)
|
||||
for r in reports:
|
||||
print(json.dumps(r, indent=1))
|
||||
members = r["members"]
|
||||
if len(members) != 2:
|
||||
raise SystemExit("expected PageHandler.js and PageAgent.js, found %s" % sorted(members))
|
||||
if kind == "ours":
|
||||
# the engine must still be the one the seal describes (the juggler stays in it with its stealth markers)
|
||||
from invisible_core.seal import JUGGLER_MIN_MARKED, read_engine_identity
|
||||
ident = read_engine_identity(exe)
|
||||
print("engine identity after the patch: juggler_present=%s marked=%s layout=%s" % (
|
||||
ident.juggler_present, ident.marked_entries, ident.juggler_layout))
|
||||
if not dry:
|
||||
assert ident.juggler_present and ident.marked_entries >= JUGGLER_MIN_MARKED, "the patched engine lost its markers"
|
||||
print("PATCHED" if not dry else "DRY RUN")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,211 @@
|
||||
"""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]. HUNT_ARM names the arm in the output (core from PyPI, core from git, both, stock).
|
||||
The page stamps every keydown and keyup twice: "h" = performance.timeOrigin + performance.now() read in the handler, "e" = performance.timeOrigin
|
||||
+ event.timeStamp (the moment the event was made). Dwell error and the smallest keydown gap are reported on both clocks. 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, plus the page's
|
||||
keyup times and, per run: slip at the last key (page against plan), the smallest gap between two keydowns the page saw, and each key's
|
||||
dwell (keyup - keydown, seen by the page) against the planned dwell.
|
||||
|
||||
ENGINE HUNT additions: HUNT_STAMPS=1 means the engine was patched by scripts/hunt_patch_omni.py, so the browser prints HUNTKEY lines
|
||||
(`browser.dom.window.dump.enabled` is passed for it); ours collects them from the core's ProcessOutput reader (the "hk" field), stock's
|
||||
stay in this process's log through DEBUG=pw:browser. Both also return the lines the content process left in window.__hs ("hs"). Every
|
||||
arm launches with -purgecaches. The JSON also carries what the summary needs to put the stamps next to the page's events: the wall clock
|
||||
(calibrated, sub-millisecond) of each send ("sent_wall_ms"), the page's ordered events ("ev": type, key, handler clock, event clock, all
|
||||
absolute ms) and the window of the typing ("win").
|
||||
"""
|
||||
import os
|
||||
import http.server
|
||||
import json
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
|
||||
from invisible_core.juggler._behaviour import TypingPersona, plan_typing
|
||||
|
||||
ENGINE = sys.argv[1]
|
||||
STAMPS = os.environ.get("HUNT_STAMPS") == "1"
|
||||
DUMP_PREF = {"browser.dom.window.dump.enabled": True}
|
||||
TEXT = "someone@example.com"
|
||||
PLAN = plan_typing(TEXT, TypingPersona.from_seed(2), nonce=1)
|
||||
SENT = []
|
||||
SENT_W = []
|
||||
HK = []
|
||||
|
||||
|
||||
def _anchor():
|
||||
"""wall clock = anchor + perf_counter(), the anchor taken on the tick time.time() changes (its granularity can be 15 ms on Windows)"""
|
||||
t0 = time.perf_counter()
|
||||
a = time.time()
|
||||
while time.time() == a and time.perf_counter() - t0 < 0.05:
|
||||
pass
|
||||
return time.time() - time.perf_counter()
|
||||
|
||||
|
||||
ANCHOR = _anchor()
|
||||
|
||||
|
||||
def wall_ms():
|
||||
return (ANCHOR + time.perf_counter()) * 1000
|
||||
|
||||
|
||||
def mark():
|
||||
SENT.append(time.time())
|
||||
SENT_W.append(round(wall_ms(), 3))
|
||||
|
||||
|
||||
PAGE = (b"<!doctype html><html><body><input id=f><script>window.__k=[];window.__u=[];document.addEventListener('keydown',"
|
||||
b"e=>__k.push([e.key, performance.timeOrigin + performance.now(), performance.timeOrigin + e.timeStamp]),true);"
|
||||
b"document.addEventListener('keyup',"
|
||||
b"e=>__u.push([e.key, performance.timeOrigin + performance.now(), performance.timeOrigin + e.timeStamp]),true);"
|
||||
b"window.__ev=[];for(const t of ['keydown','keyup'])document.addEventListener(t,"
|
||||
b"e=>__ev.push([t, e.key, performance.timeOrigin + performance.now(), performance.timeOrigin + e.timeStamp]),true);"
|
||||
b"</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, t_start_wall):
|
||||
if STAMPS:
|
||||
time.sleep(0.5) # the browser's last HUNTKEY lines travel on a pipe of their own
|
||||
keys = page.evaluate("__k")
|
||||
ev = page.evaluate("__ev")
|
||||
hs = page.evaluate("window.__hs ? Array.from(window.__hs) : []")
|
||||
ups = page.evaluate("__u")
|
||||
planned, t = [], 0.0
|
||||
for dwell, gap in PLAN:
|
||||
planned.append(round(t))
|
||||
t += dwell + gap
|
||||
downs = [x for x in keys if x[0] != "Shift"]
|
||||
releases = [x for x in ups if x[0] != "Shift"]
|
||||
# clock index into a [key, handler clock, event clock] triple: 1 = "h" (handler), 2 = "e" (event.timeStamp)
|
||||
page_ms = [round(x[1] - downs[0][1]) for x in downs] if downs else []
|
||||
page_ms_e = [round(x[2] - downs[0][2]) for x in downs] if downs else []
|
||||
# a key's dwell: its keyup after its keydown, matched by order (the same key never overlaps itself in a plan)
|
||||
dwell_h, dwell_e, err_h, err_e = [], [], [], []
|
||||
if len(downs) == len(releases) == len(PLAN):
|
||||
for d, u, (planned_dwell, _gap) in zip(downs, releases, PLAN):
|
||||
dwell_h.append(round(u[1] - d[1], 1))
|
||||
dwell_e.append(round(u[2] - d[2], 1))
|
||||
err_h.append(round((u[1] - d[1]) - planned_dwell, 1))
|
||||
err_e.append(round((u[2] - d[2]) - planned_dwell, 1))
|
||||
plan_gaps = [planned[i + 1] - planned[i] for i in range(len(planned) - 1)]
|
||||
gaps_h = [page_ms[i + 1] - page_ms[i] for i in range(len(page_ms) - 1)]
|
||||
gaps_e = [page_ms_e[i + 1] - page_ms_e[i] for i in range(len(page_ms_e) - 1)]
|
||||
print("HUNT-TYPING " + json.dumps({
|
||||
"engine": ENGINE, "arm": os.environ.get("HUNT_ARM", ENGINE), "planned_ms": planned,
|
||||
"sent_ms": [round(x * 1000 - SENT[0] * 1000) for x in SENT if True],
|
||||
"page_ms": page_ms, "page_ms_e": page_ms_e,
|
||||
"page_keys": [x[0] for x in keys], "send_offset_ms": round((SENT[0] - t_start) * 1000) if SENT else None,
|
||||
"keyup_ms": [round(x[1] - downs[0][1]) for x in releases] if downs else [],
|
||||
"keyup_ms_e": [round(x[2] - downs[0][2]) for x in releases] if downs else [],
|
||||
"planned_dwell_ms": [round(d, 1) for d, g in PLAN],
|
||||
"dwell_h_ms": dwell_h, "dwell_e_ms": dwell_e, "dwell_err_h_ms": err_h, "dwell_err_e_ms": err_e,
|
||||
"slip_last_ms": (page_ms[-1] - planned[-1]) if len(page_ms) == len(planned) else None,
|
||||
"slip_last_e_ms": (page_ms_e[-1] - planned[-1]) if len(page_ms_e) == len(planned) else None,
|
||||
"min_keydown_gap_h_ms": min(gaps_h) if gaps_h else None,
|
||||
"min_keydown_gap_e_ms": min(gaps_e) if gaps_e else None,
|
||||
"plan_min_keydown_gap_ms": min(plan_gaps) if plan_gaps else None,
|
||||
"all_keys_seen": len(downs) == len(PLAN) and len(releases) == len(PLAN),
|
||||
"sent_wall_ms": list(SENT_W), "ev": [[t, k, round(h, 3), round(e, 3)] for t, k, h, e in ev], "hs": hs, "hk": list(HK),
|
||||
"win": [round(t_start_wall, 3), round(wall_ms(), 3)], "stamps": STAMPS,
|
||||
}), flush=True)
|
||||
|
||||
|
||||
if ENGINE == "stock":
|
||||
from playwright.sync_api import sync_playwright
|
||||
with sync_playwright() as p:
|
||||
kw = {"headless": True, "args": ["-purgecaches"]}
|
||||
if STAMPS:
|
||||
kw["firefox_user_prefs"] = DUMP_PREF
|
||||
b = p.firefox.launch(**kw)
|
||||
page = b.new_page()
|
||||
for _ in range(5):
|
||||
SENT.clear()
|
||||
SENT_W.clear()
|
||||
page.goto(url)
|
||||
page.click("#f")
|
||||
t_start = time.time()
|
||||
t_start_wall = wall_ms()
|
||||
for (dwell, gap), ch in zip(PLAN, TEXT):
|
||||
mark()
|
||||
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, t_start_wall)
|
||||
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":
|
||||
mark()
|
||||
return real_down(self, key, *a, **k)
|
||||
|
||||
kb.Keyboard.down = down
|
||||
if STAMPS:
|
||||
# the browser's output is read by the core's one reader (ProcessOutput); it keeps the last 200 lines only, so the HUNTKEY ones are
|
||||
# also copied out as they arrive
|
||||
from invisible_core.juggler import connection as conn
|
||||
|
||||
def pump(self):
|
||||
try:
|
||||
for raw in iter(self._stream.readline, b""):
|
||||
text = raw.decode("utf-8", "replace").rstrip("\r\n")
|
||||
i = text.find("HUNTKEY ")
|
||||
if i >= 0:
|
||||
HK.append(text[i + 8:])
|
||||
with self._cv:
|
||||
if text.strip():
|
||||
self._lines.append(text)
|
||||
if conn._READY in text:
|
||||
self._ready = True
|
||||
self._cv.notify_all()
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
finally:
|
||||
with self._cv:
|
||||
self._eof = True
|
||||
self._cv.notify_all()
|
||||
|
||||
conn.ProcessOutput._pump = pump
|
||||
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)
|
||||
kw = {"seed": 2, "binary_path": sys.argv[2], "headless": True, "extra_args": ["-purgecaches"]}
|
||||
if STAMPS:
|
||||
kw["extra_prefs"] = DUMP_PREF
|
||||
with InvisiblePlaywright(**kw) as browser:
|
||||
SENT.clear()
|
||||
SENT_W.clear()
|
||||
HK.clear()
|
||||
page = browser.new_page()
|
||||
page.goto(url)
|
||||
t_start = time.time()
|
||||
t_start_wall = wall_ms()
|
||||
page.locator("#f").press_sequentially(TEXT)
|
||||
report(page, t_start, t_start_wall)
|
||||
srv.shutdown()
|
||||
@@ -0,0 +1,27 @@
|
||||
"""HUNT SCAFFOLDING, NEVER MERGED: print which invisible-core and which invisible-playwright are installed (version, where each came from,
|
||||
whether the keyboard sends on absolute deadlines), so the step summary says which arm ran what. Run with the interpreter of the arm."""
|
||||
import importlib.metadata as m
|
||||
import json
|
||||
import pathlib
|
||||
|
||||
import invisible_core
|
||||
import invisible_playwright
|
||||
from invisible_core.juggler import keyboard
|
||||
|
||||
|
||||
def source(name):
|
||||
d = m.distribution(name)
|
||||
direct = pathlib.Path(str(d._path)) / "direct_url.json"
|
||||
info = json.loads(direct.read_text()) if direct.exists() else None
|
||||
if info and info.get("vcs_info"):
|
||||
return d.version, info["vcs_info"]
|
||||
return d.version, ("local dir " + info["url"]) if info else "index"
|
||||
|
||||
|
||||
v, src = source("invisible-core")
|
||||
print("invisible-core", v, "from", invisible_core.__file__)
|
||||
print("source:", json.dumps(src))
|
||||
v, src = source("invisible-playwright")
|
||||
print("invisible-playwright", v, "from", invisible_playwright.__file__)
|
||||
print("wrapper source:", json.dumps(src))
|
||||
print("keyboard sends on absolute deadlines (_due):", hasattr(keyboard.Keyboard, "_due"))
|
||||
@@ -0,0 +1,102 @@
|
||||
"""HUNT SCAFFOLDING, NEVER MERGED: the step summary of the typing hunt.
|
||||
|
||||
Usage: python scripts/hunt_typing_summary.py EVIDENCE_DIR OS_NAME
|
||||
Reads EVIDENCE_DIR/{alone,loaded}_<arm>*.log (HUNT-TYPING lines of scripts/hunt_typing.py) and EVIDENCE_DIR/test_<arm>_*.xml (junit of the
|
||||
typing e2e test under -n 4) and prints one table per OS: per arm and mode, p50 / max of the slip at the last key, p50 / min of the smallest
|
||||
keydown gap, p50 / p95 of the dwell error (absolute, and the signed p50) and the planned smallest gap, the last three on both page clocks
|
||||
(h = performance.now() in the handler, e = event.timeStamp), and the test's pass count per core arm.
|
||||
"""
|
||||
import glob
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
ARMS = ["pypi", "git", "both", "stock"]
|
||||
MODES = ["alone", "loaded"]
|
||||
|
||||
|
||||
def q(v, f):
|
||||
v = sorted(v)
|
||||
return v[min(len(v) - 1, int(len(v) * f))] if v else None
|
||||
|
||||
|
||||
def runs(evidence, mode, arm):
|
||||
out = []
|
||||
for path in sorted(glob.glob(os.path.join(evidence, "%s_%s*.log" % (mode, arm)))):
|
||||
with open(path, encoding="utf-8", errors="replace") as f:
|
||||
for line in f:
|
||||
if line.startswith("HUNT-TYPING "):
|
||||
try:
|
||||
out.append(json.loads(line[len("HUNT-TYPING "):]))
|
||||
except ValueError:
|
||||
pass
|
||||
return out
|
||||
|
||||
|
||||
def row(evidence, mode, arm):
|
||||
r = runs(evidence, mode, arm)
|
||||
|
||||
def col(key):
|
||||
return [x[key] for x in r if x.get(key) is not None]
|
||||
|
||||
def flat(key):
|
||||
out = []
|
||||
for x in r:
|
||||
out.extend(x.get(key) or [])
|
||||
return out
|
||||
|
||||
slip = col("slip_last_ms")
|
||||
gap_h, gap_e = col("min_keydown_gap_h_ms"), col("min_keydown_gap_e_ms")
|
||||
plan_gap = col("plan_min_keydown_gap_ms")
|
||||
err_h, err_e = flat("dwell_err_h_ms"), flat("dwell_err_e_ms")
|
||||
abs_h, abs_e = [abs(e) for e in err_h], [abs(e) for e in err_e]
|
||||
incomplete = sum(1 for x in r if not x.get("all_keys_seen"))
|
||||
f = lambda v: "-" if v is None else str(v)
|
||||
return "| %s | %d | %d | %s | %s | %s | %s | %s | %s | %s | %s | %s | %s | %s | %s | %s |" % (
|
||||
mode, len(r), incomplete, f(q(slip, .5)), f(max(slip) if slip else None),
|
||||
f(q(gap_h, .5)), f(min(gap_h) if gap_h else None), f(q(gap_e, .5)), f(min(gap_e) if gap_e else None),
|
||||
f(q(abs_h, .5)), f(q(abs_h, .95)), f(q(err_h, .5)), f(q(abs_e, .5)), f(q(abs_e, .95)), f(q(err_e, .5)),
|
||||
f(min(plan_gap) if plan_gap else None))
|
||||
|
||||
|
||||
def tests(evidence, arm):
|
||||
passed = total = 0
|
||||
for path in glob.glob(os.path.join(evidence, "test_%s_*.xml" % arm)):
|
||||
try:
|
||||
root = ET.parse(path).getroot()
|
||||
except ET.ParseError:
|
||||
continue
|
||||
for case in root.iter("testcase"):
|
||||
if "test_a_store_that_answers_the_focus_does_not_eat_the_text" not in (case.get("name") or ""):
|
||||
continue
|
||||
total += 1
|
||||
if not any(c.tag in ("failure", "error", "skipped") for c in case):
|
||||
passed += 1
|
||||
return passed, total
|
||||
|
||||
|
||||
def main():
|
||||
evidence, os_name = sys.argv[1], sys.argv[2]
|
||||
print("## typing hunt (%s)" % os_name)
|
||||
print("Slip = page (handler clock) minus plan at the last key; gap = smallest gap between two keydowns the page saw; dwell error = "
|
||||
"(keyup - keydown) seen by the page minus the planned dwell. h = performance.now() read in the handler, e = event.timeStamp. "
|
||||
"Times in ms.")
|
||||
for arm in ARMS:
|
||||
print()
|
||||
print("### arm: %s" % arm)
|
||||
print("| mode | runs | runs with missing keys | slip p50 | slip max | min gap p50 (h) | min gap min (h) | min gap p50 (e) "
|
||||
"| min gap min (e) | dwell err abs p50 (h) | dwell err abs p95 (h) | dwell err signed p50 (h) | dwell err abs p50 (e) "
|
||||
"| dwell err abs p95 (e) | dwell err signed p50 (e) | planned min gap |")
|
||||
print("|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|")
|
||||
for mode in MODES:
|
||||
print(row(evidence, mode, arm))
|
||||
print()
|
||||
print("### test_a_store_that_answers_the_focus_does_not_eat_the_text, x20 under `-n 4 --dist loadfile` with 3 other e2e files")
|
||||
for arm in ["pypi", "git", "both"]:
|
||||
p, t = tests(evidence, arm)
|
||||
print("- core %s: %d passed of %d" % (arm, p, t))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -348,6 +348,21 @@ def test_a_store_that_answers_the_focus_does_not_eat_the_text(firefox_binary, st
|
||||
took = time.monotonic() - started
|
||||
value = page.input_value("#store")
|
||||
events = page.evaluate("__events")
|
||||
_keys = [round(t) for k, t in events if k == "keydown"]
|
||||
import json as _hj, os as _ho
|
||||
if _ho.environ.get("HUNT_OUT"):
|
||||
_plan = plan_typing(TEXT, TypingPersona.from_seed(seed), nonce=1)
|
||||
_plan_span = sum(a + b for a, b in _plan[:-1])
|
||||
_focus_all = [round(t) for k, t in events if k == "focus"]
|
||||
with open(_ho.environ["HUNT_OUT"], "a") as _hf:
|
||||
print(_hj.dumps({"how": how, "took": round(took, 3), "pause": round(pause, 3), "plan_span_ms": round(_plan_span),
|
||||
"key_span_ms": (_keys[-1] - _keys[0]) if _keys else None, "keys": len(_keys),
|
||||
"focus": _focus_all, "first_key": _keys[0] if _keys else None,
|
||||
"last_focus_to_first_key_ms": (_keys[0] - _focus_all[-1]) if _keys and _focus_all else None}), file=_hf)
|
||||
_focus = [round(t) for k, t in events if k == "focus"]
|
||||
print("HUNT-TYPE how=%s took=%.2f pause=%.3f bound=%.2f focus=%r key_gaps=%r" % (
|
||||
how, took, pause, 2 * pause + ANSWER_MS / 1000 + 0.4 * len(TEXT), _focus,
|
||||
[b - a for a, b in zip(([_focus[0]] if _focus else []) + _keys, _keys)]), flush=True)
|
||||
assert value == TEXT, "the field holds %r after %s" % (value, how)
|
||||
focus = next(t for k, t in events if k == "focus")
|
||||
first = next(t for k, t in events if k == "keydown")
|
||||
@@ -357,4 +372,4 @@ def test_a_store_that_answers_the_focus_does_not_eat_the_text(firefox_binary, st
|
||||
# The pause is a pause, not a stall: one hesitation (restarted once, by
|
||||
# the store's write) on top of the typing itself.
|
||||
assert took < 2 * pause + ANSWER_MS / 1000 + 0.4 * len(TEXT), (
|
||||
"%s took %.1f s" % (how, took))
|
||||
"%s took %.1f s HUNT pause=%.3f focus=%r keys=%r" % (how, took, pause, _focus, _keys))
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -78,8 +78,11 @@ def page(firefox_binary):
|
||||
def test_reads_after_the_isolated_page_answer(page, site):
|
||||
for i in range(ROUNDS):
|
||||
page.goto("%s/isolated?i=%d" % (site, i), wait_until="domcontentloaded")
|
||||
assert page.evaluate("self.crossOriginIsolated") is True, (
|
||||
"the engine did not isolate the page: this round tests nothing")
|
||||
_h = page.evaluate("({coi: self.crossOriginIsolated, path: location.pathname, now: performance.now(), "
|
||||
"load: performance.getEntriesByType('navigation')[0]?.loadEventEnd})")
|
||||
print("HUNT-ISOLATED round=%d %r" % (i, _h), flush=True)
|
||||
assert _h["coi"] is True, (
|
||||
"the engine did not isolate the page: this round tests nothing HUNT %r" % (_h,))
|
||||
# The read on the isolated page is what builds the script that went
|
||||
# stale; without it the bug never showed.
|
||||
assert page.locator("#p").inner_text(timeout=10_000) in ("isolated", "plain")
|
||||
|
||||
@@ -67,6 +67,10 @@ def test_the_first_datagram_does_not_wait_for_a_handshake(local_https_page, monk
|
||||
t_pc = result["t_pc"] / 1000.0
|
||||
granted = [a for a in gateway.associations if a[1] is not None]
|
||||
first = next((t for host, port, _atyp, t in gateway.datagram_log if host == STUN_NUMBER), None)
|
||||
print("HUNT-STUN t_pc=%.3f first=%s associations=%r srflx=%s" % (
|
||||
t_pc - gateway.wall0, None if first is None else round(first, 3),
|
||||
[(a[0] if len(a) > 0 else None, None if a[1] is None else round(a[1], 3)) for a in gateway.associations],
|
||||
result.get("t_srflx") and round(result["t_srflx"] / 1000.0 - gateway.wall0, 3)), flush=True)
|
||||
assert granted, "the proxy was never asked for an association"
|
||||
# the first association of the gateway is the core's own UDP probe, made before the browser exists: it is no pool
|
||||
# association of the engine, and counting it made this test pass with an engine that asked for none
|
||||
|
||||
Reference in new issue
Block a user