Compare commits

...
Author SHA1 Message Date
feder-cr dd86fede64 HUNT SCAFFOLDING, NEVER MERGED: the core is main with the typing branch merged in the job, a stop on a conflict 2026-11-14 01:43:39 +01:00
feder-cr 146d4b5769 HUNT SCAFFOLDING, NEVER MERGED: the engine hunt on the candidate with the key born in the past (no timer in PageAgent), stamps kept in memory and written once at the end, ours stamped, ours unstamped twin and stock, 60 runs per arm 2026-11-14 01:42:28 +01:00
feder-cr 035f4cd2ce HUNT SCAFFOLDING, NEVER MERGED: where a typed key's delay is born inside the engine, stamps in the Juggler of ours and of stock (parent receipt, content receipt, latency timer armed and fired, before the DOM event), per step p50 / p95 / max and the step that absorbed each short page gap 2026-11-13 23:42:30 +01:00
feder-cr d207618886 HUNT SCAFFOLDING, NEVER MERGED: typing hunt, the page's two clocks (handler performance.now and event.timeStamp) for keydown and keyup, and a fourth arm with the reader fix merged into the typing core and the wrapper from its branch 2026-11-13 20:26:21 +01:00
feder-cr 29a23d9157 HUNT SCAFFOLDING, NEVER MERGED: typing on absolute deadlines, core from PyPI against core from git against stock, alone and four at once, keydown and keyup seen by the page, and the typing e2e test under -n 4 2026-11-13 17:51:48 +01:00
feder-crandClaude Opus 5.5 a50a908ea7 HUNT SCAFFOLDING, NEVER MERGED: typing per key, planned / sent / seen by the page, ours against stock, Windows and Linux
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 15:18:08 +01:00
feder-crandClaude Opus 5.5 15572fa114 HUNT SCAFFOLDING, NEVER MERGED: measure the typing test against its plan, alone and under four workers, every run
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 15:17:05 +01:00
feder-crandClaude Opus 5.5 e31c28a2a7 HUNT SCAFFOLDING, NEVER MERGED: the measured values go into the assertion messages (xdist hides the prints)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 14:54:52 +01:00
feder-crandClaude Opus 5.5 5fa52df627 HUNT SCAFFOLDING, NEVER MERGED: flakes 1, 3 and 4 under four workers on Windows, with their timings printed
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 14:38:06 +01:00
feder-crandClaude Opus 5.5 224850a3e0 HUNT SCAFFOLDING, NEVER MERGED: networkidle on a page that moves, ours against stock Playwright Firefox, with the time of the replacement's request
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 14:25:23 +01:00
feder-crandClaude Opus 5.5 59cc42452c HUNT SCAFFOLDING, NEVER MERGED: the networkidle round on a page that moves, four at once on Windows, with the URL read again
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 13:58:46 +01:00
13 changed files with 1524 additions and 3 deletions

No files matched your search

@@ -0,0 +1,217 @@
# windows-flakes-engine60-hunt.yml - hunt scaffolding, never merged. Runs only on a push to a `hunt/windows-flakes-engine60**` branch.
# The engine is the CANDIDATE of oss-invisible/firefox_antidetect_patch run 43534660961 (latitude/firefox-64, the "key born in the past"
# fix: PageAgent._dispatchKeyEvent has no timer, the latency goes to tip.setNextKeyLatency), its asset-<leg> artifact, downloaded here
# with this job's token. Core = oss-invisible/core main with fix/typing-on-absolute-deadlines merged in the job, over the wheel, under a LOCAL seal made from
# the candidate's tree (as the candidate's own gate does). The Juggler of the candidate and of stock Playwright's Firefox is patched in its
# omni.ja (scripts/hunt_patch_omni.py): stamps kept in memory in both processes, written once at the end. Arms: ours (stamped), ours_plain
# (the same engine untouched, the twin that shows what the stamps cost) and stock (stamped). Windows: four processes at once, 60 runs per
# arm. Linux: alone, 60 runs per arm. Every command under timeout 300; cleanup never fails the job.
name: windows flakes engine60 hunt
on:
push:
branches: ['hunt/windows-flakes-engine60**']
permissions:
contents: read
actions: read
concurrency:
group: windows-flakes-engine60-hunt-${{ github.ref }}
cancel-in-progress: true
env:
GITHUB_TOKEN: ${{ github.token }}
CORE_REPO: "https://github.com/oss-invisible/core"
CORE_TYPING_BRANCH: "fix/typing-on-absolute-deadlines"
ENGINE_REPO: oss-invisible/firefox_antidetect_patch
ENGINE_RUN_ID: "43534660961"
# the candidate's engine needs the core under test as it is: no import-time pin repair, a pin mismatch only warns
INVISIBLE_CORE_AUTOFIX: "off"
INVISIBLE_CORE_PIN: "allow"
jobs:
hunt:
name: engine60 hunt ${{ matrix.os }}
runs-on: ${{ matrix.os }}
timeout-minutes: 180
strategy:
max-parallel: 1
fail-fast: false
matrix:
include:
- os: windows-2022
leg: win-x86_64
- os: ubuntu-24.04
leg: linux-x86_64
defaults:
run:
shell: bash
env:
PYTHONUNBUFFERED: "1"
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
with: { python-version: '3.11' }
# another repo's run: its artifacts need a token (a public repo's too). The default token first; the secret ENGINE_RUN_TOKEN
# (a token that can read the actions of that repo) if there is one.
- name: Download the candidate's engine (asset of the leg)
id: dl
continue-on-error: true
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
with:
name: asset-${{ matrix.leg }}
path: art
repository: ${{ env.ENGINE_REPO }}
run-id: ${{ env.ENGINE_RUN_ID }}
github-token: ${{ secrets.ENGINE_RUN_TOKEN || github.token }}
- name: Download the candidate's engine, second way (gh run download)
if: steps.dl.outcome != 'success'
env:
GH_TOKEN: ${{ secrets.ENGINE_RUN_TOKEN || github.token }}
run: |
set +e
timeout 300 gh run view "$ENGINE_RUN_ID" -R "$ENGINE_REPO" --json status,conclusion,headBranch,headSha 2>&1
timeout 300 gh api "repos/$ENGINE_REPO/actions/runs/$ENGINE_RUN_ID/artifacts" --jq '.artifacts[] | [.name,.size_in_bytes,.expired]|@tsv' 2>&1
mkdir -p art
timeout 300 gh run download "$ENGINE_RUN_ID" -R "$ENGINE_REPO" -n "asset-${{ matrix.leg }}" -D art 2>&1
ls -la art
set -- art/firefox-*-stealth-${{ matrix.leg }}.*
if [ "$#" -ne 1 ] || [ ! -e "$1" ]; then
echo "THE ENGINE OF RUN $ENGINE_RUN_ID COULD NOT BE DOWNLOADED with this job's token (artifact expired, build not finished, or the token cannot read another repo's artifacts). Add a secret ENGINE_RUN_TOKEN (read access to the actions of $ENGINE_REPO) and push again."
exit 1
fi
- name: Download the source-commit of the candidate (for the build id line)
continue-on-error: true
env:
GH_TOKEN: ${{ secrets.ENGINE_RUN_TOKEN || github.token }}
run: |
set +e
mkdir -p src-meta
timeout 300 gh run download "$ENGINE_RUN_ID" -R "$ENGINE_REPO" -n source-commit -D src-meta 2>&1 || echo "no source-commit artifact"
ls -la src-meta
exit 0
- name: Install
run: |
set -e
mkdir -p evidence
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)"
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
echo "stock: $STOCK_FF"
ls -la "$(dirname "$STOCK_FF")" | head -50
- name: Unpack the candidate's engine
run: |
set -e
mkdir -p ff
set -- art/firefox-*-stealth-${{ matrix.leg }}.*
[ "$#" -eq 1 ] && [ -e "$1" ] || { echo "ERROR: expected one firefox-*-stealth-${{ matrix.leg }} archive in art/, found: $*"; exit 1; }
A="$1"
echo "archive: $A"
case "$RUNNER_OS" in
Windows) timeout 300 python -c "import sys, zipfile; zipfile.ZipFile(sys.argv[1]).extractall('ff')" "$A"; EXE="$PWD/ff/firefox.exe";;
*) timeout 300 tar xzf "$A" -C ff; EXE="$PWD/ff/firefox";;
esac
[ -e "$EXE" ] || { echo "ERROR: firefox binary not found at $EXE"; exit 1; }
chmod +x "$EXE" 2>/dev/null || true
echo "FF=$EXE" >> "$GITHUB_ENV"
echo "ours: $EXE"
- name: Core from the branch over the wheel, a local seal from the candidate's tree, what is installed
run: |
set -e
# core main (the candidate's core_ref) with the typing branch merged in, built here; an explicit stop on a conflict
rm -rf "$RUNNER_TEMP/core-merged" && git clone --quiet "$CORE_REPO" "$RUNNER_TEMP/core-merged"
( cd "$RUNNER_TEMP/core-merged" && git fetch --quiet origin "$CORE_TYPING_BRANCH" && echo "core main head: $(git rev-parse HEAD)" && echo "typing head: $(git rev-parse FETCH_HEAD)" && git -c user.name=hunt -c user.email=hunt@invalid merge --no-edit FETCH_HEAD && echo "core merged head: $(git rev-parse HEAD)" ) || { echo "::error::core main and the typing branch do not merge cleanly"; exit 1; }
timeout 300 python -m pip install --quiet --force-reinstall --no-deps "$RUNNER_TEMP/core-merged"
timeout 300 python -m invisible_core seal --binary "$FF" --tag engine60-candidate -o "$PWD/evidence/engine.seal.json" | tee evidence/seal.txt
echo "INVISIBLE_SEAL_FILE=$PWD/evidence/engine.seal.json" >> "$GITHUB_ENV"
export INVISIBLE_SEAL_FILE="$PWD/evidence/engine.seal.json"
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; }
{
echo "engine run: $ENGINE_REPO $ENGINE_RUN_ID"
echo "engine archive: $(ls art | head -3 | tr '\n' ' ')"
for f in src-meta/*.txt; do
if [ -e "$f" ]; then echo "$(basename "$f"): $(cat "$f")"; fi
done
timeout 300 python - <<'PY'
from invisible_core.seal import read_engine_identity
import os
i = read_engine_identity(os.environ["FF"])
print("engine identity: Firefox %s, BuildID %s, platform BuildID %s, juggler layout %s, markers %s" % (
i.version, i.build_id, i.platform_build_id, i.juggler_layout, i.marked_entries))
PY
} 2>&1 | tee evidence/engine_id.txt
- name: Smoke, the candidate launches with the core under test and the page loads
run: |
set -e
timeout 300 python - <<'PY' 2>&1 | tee evidence/smoke.txt
from invisible_playwright import InvisiblePlaywright
import os
with InvisiblePlaywright(seed=2, binary_path=os.environ["FF"], headless=True) as b:
p = b.new_page()
p.goto("about:blank")
print("SMOKE ok", p.evaluate("navigator.userAgent"))
PY
grep -q "^SMOKE ok" evidence/smoke.txt
- name: Control arm, the candidate untouched (ours_plain)
run: |
set +e
bash scripts/hunt_engine_arm.sh ours_plain ours "$FF"
exit 0
- name: Patch the Juggler of both engines (omni.ja next to the executable), stamps for Page.dispatchKeyEvent
run: |
set -e
timeout 300 python scripts/hunt_patch_omni.py ours "$FF" 2>&1 | tee evidence/patch_ours.txt
timeout 300 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
grep -q "setNextKeyLatency(born).: 3" evidence/patch_ours.txt || { echo "the candidate's PageAgent is not the no-timer shape (three setNextKeyLatency(born) calls)"; exit 1; }
- name: Arms ours and stock with the stamps
env:
HUNT_STAMPS: "1"
run: |
set +e
bash scripts/hunt_engine_arm.sh ours 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"
exit 0
- name: Summary
if: always()
run: |
set +e
{
sed 's/^/ /' evidence/engine_id.txt 2>/dev/null
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"
exit 0
- name: Close every Firefox left
if: always()
continue-on-error: true
run: |
set +e
if [ "$RUNNER_OS" = "Windows" ]; then
timeout 300 taskkill //F //IM firefox.exe //T >/dev/null 2>&1
echo "left: $(timeout 300 tasklist 2>/dev/null | grep -ic firefox)"
else
timeout 300 pkill -9 -x firefox >/dev/null 2>&1
echo "left: $(pgrep -xc firefox 2>/dev/null)"
fi
exit 0
- name: Upload the evidence
if: always()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: windows-flakes-engine60-${{ 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
+29
View File
@@ -0,0 +1,29 @@
#!/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)
# 5 runs per invocation of hunt_typing.py, every invocation under `timeout 300`.
# alone: 12 invocations one after the other = 60 runs. loaded: 3 rounds of four at once = 4 processes, 12 invocations, 60 runs.
# 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"
export HUNT_RUNS=5
if [ "$HUNT_MODE" = "alone" ]; then
for n in 1 2 3 4 5 6 7 8 9 10 11 12; do
timeout 300 python -u scripts/hunt_typing.py "$engine" "$bin" >> "evidence/alone_${arm}.log" 2>&1
echo "arm $arm alone $n exit $?"
done
else
for round in 1 2 3; do
for c in 1 2 3 4; do
timeout 300 python -u scripts/hunt_typing.py "$engine" "$bin" >> "evidence/loaded_${arm}_$c.log" 2>&1 &
done
wait
echo "arm $arm loaded round $round done"
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
+319
View File
@@ -0,0 +1,319 @@
"""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: ours (the engine candidate under test, patched by scripts/hunt_patch_omni.py, core of fix/typing-on-absolute-deadlines), ours_plain
(the same engine untouched: what the page sees without the stamps, to show what they cost) and stock (stock Playwright Firefox, its Juggler
patched the same way).
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. In an engine WITHOUT a latency timer (the candidate under test) C3
and C4 are just before and just after tip.setNextKeyLatency(born) and there is no C4r; an engine WITH the timer (older) has C3 = timer
armed, C4 = its callback, and gets the "timer planned" / "timer excess" rows. "timestamp lag" = (h - event.timeStamp) - the latency sent:
how much more or less than the declared latency the event, born in the past, is older than the page's handler. Dwell error = (keyup -
keydown) seen by the page minus the planned dwell, on both page clocks (h handler, e event.timeStamp). The stock engine has no latency, 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 = ["ours", "stock", "ours_plain"]
STAMPED = ("ours", "stock")
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"))
# the stamps are written once, when a process ends (and the page's copy holds every key of the process so far): only the ones of
# THIS run's typing window are its own
w0, w1 = run["win"][0] - 100, run["win"][1] + 1000
stamps = {t: v for t, v in stamps.items() if w0 <= v[0]["wall"] <= w1}
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,
"C4>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 STAMPED 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 STAMPED:
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 STAMPED}
print("### dwell error: (keyup - keydown) seen by the page minus the planned dwell (ms)")
print()
print("| arm | clock | keys | abs p50 | abs p95 | abs max | signed p50 | signed min | signed max | runs with all keys seen |")
print("|---|---|---|---|---|---|---|---|---|---|")
for arm, runs in data.items():
seen = sum(1 for r in runs if r["run"].get("all_keys_seen"))
for clock, key in (("h (handler)", "dwell_err_h_ms"), ("e (event.timeStamp)", "dwell_err_e_ms")):
err = [x for r in runs for x in (r["run"].get(key) or [])]
ab = [abs(x) for x in err]
print("| %s | %s | %d | %s | %s | %s | %s | %s | %s | %d/%d |" % (
arm, clock, len(err), fmt(q(ab, .5)), fmt(q(ab, .95)), fmt(max(ab) if ab else None), fmt(q(err, .5)),
fmt(min(err) if err else None), fmt(max(err) if err else None), seen, len(runs)))
print()
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()
+76
View File
@@ -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()
+319
View File
@@ -0,0 +1,319 @@
"""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. 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.
Two shapes of PageAgent._dispatchKeyEvent are known: the one with a latency TIMER (`await new Promise(f => setTimeout(f, latency))`, the
engines before the "key born in the past" fix; stock has no latency at all) and the one WITHOUT a timer (the latency goes to the text
input processor with `tip.setNextKeyLatency(born)` just before the key). The patcher finds whichever is there.
Every stamp is a line
HUNTKEY <proc> <pid> <call> <tag> <wall_ms> <type> <urlencoded key> [extra]
and it is only KEPT IN MEMORY while keys are typed (an array push, nothing else: no dump(), no page access). It is written once, at the
end: dump() when the process shuts down ('quit-application' / 'xpcom-shutdown' observers) or, in the content process, when the page is
hidden (pagehide); and the content process also hands its lines to the page when the page's script asks for them, with
`window.dispatchEvent(new Event('hunt-flush'))` and then reads `window.__hs` (the listener is installed once per window, after the
first key). A Windows content process may have no stdout, so that is the way that always works.
P1 parent: Page.dispatchKeyEvent received (PageHandler.prototype['Page.dispatchKeyEvent'], wrapped)
C2 content: dispatchKeyEvent received (PageAgent.prototype._dispatchKeyEvent, wrapped)
C3 content: just before tip.setNextKeyLatency(born) (no-timer shape; extra latency=<ms>), or the latency timer armed (timer shape;
extra delay=<ms>)
C4 content: just after tip.setNextKeyLatency(born) (no-timer shape), or the timer's callback runs (timer shape)
C4r content: the await resumed (timer shape only)
C5 content: just before the DOM event is made (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;
let dumped = 0;
// written once: what has not been written yet goes out in ONE dump(); called at process end and when a page is hidden
const writeOut = () => {
if (dumped >= buf.length) return;
const lines = buf.slice(dumped);
dumped = buf.length;
try { dump(lines.map(l => 'HUNTKEY ' + l + '\n').join('')); } catch (e) {}
};
try {
const obs = { observe() { writeOut(); } };
Services.obs.addObserver(obs, 'quit-application');
Services.obs.addObserver(obs, 'xpcom-shutdown');
} catch (e) {}
const hooked = new WeakSet();
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) {}
},
// content process, once per window and after its first key: the page asks for the lines with a 'hunt-flush' event; pagehide writes
hook(win) {
try {
if (!win || hooked.has(win)) return;
hooked.add(win);
win.addEventListener('hunt-flush', () => {
try {
const w = win.wrappedJSObject;
w.__hs = new w.Array();
for (const l of buf) w.__hs.push(l);
} catch (e) {}
}, true);
win.addEventListener('pagehide', writeOut, true);
} catch (e) {}
},
writeOut,
};
})();
"""
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);
}
};
})();
// ---- 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);
try { __HK.hook(this._frameTree.mainFrame().domWindow()); } catch (e) {}
}
};
})();
// ---- HUNTKEY end ----
"""
MARK = "HUNTKEY begin"
# The latency TIMER of the engines before the "key born in the past" fix (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 no-timer shape: the latency is declared to the text input processor for the next key, once in each of the three ways in (the
# `tip.setNextKeyLatency(0)` of the finally is left alone). Stamped before and after, as statements of the same block.
BORN = re.compile(r"\btip\.setNextKeyLatency\(born\);")
BORN_NEW = ("__HK.stamp('content', 'C3', type, key, 'latency=' + born); tip.setNextKeyLatency(born); "
"__HK.stamp('content', 'C4', 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_born = BORN.subn(lambda _m: BORN_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)
# the timer (old engines) and setNextKeyLatency (new ones) are alternatives and stock has neither: not an error, only reported
anchors["latency timer"] = n_timer == 1
anchors["setNextKeyLatency(born)"] = n_born
anchors["tip calls"] = n_tip
if n_timer and n_born:
return None, dict(anchors, error="both a timer and setNextKeyLatency(born) in one function")
if n_tip < 1:
return None, anchors
if KIND == "ours" and not (n_born == 3 or n_timer == 1):
return None, dict(anchors, error="our engine has neither the latency timer nor three setNextKeyLatency(born) calls")
return text[:start] + body + text[end:] + "\n" + HELPER + CONTENT_WRAP, anchors
KIND = "ours" # set by main(): ours must have one of the two shapes of the latency, stock has neither
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():
global KIND
kind, exe = sys.argv[1], sys.argv[2]
KIND = kind
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()
+224
View File
@@ -0,0 +1,224 @@
"""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. The browser keeps its stamps in memory
while keys are typed and writes them once, when it ends (`browser.dom.window.dump.enabled` is passed for it): ours collects the lines from
the core's ProcessOutput reader AFTER the browser is closed (the "hk" field, so a run's line is printed once its browser has ended), stock's
stay in this process's log through DEBUG=pw:browser. The content process's lines are also asked of the page at the end of the run, with a
'hunt-flush' event on the window and a read of window.__hs ("hs"). Every arm launches with -purgecaches. HUNT_RUNS (default 5) = runs
per invocation. 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]
RUNS = int(os.environ.get("HUNT_RUNS", "5"))
def report(page, t_start, t_start_wall):
"""Read what the page saw and return the run's record (printed by emit(), for ours after its browser has ended)."""
keys = page.evaluate("__k")
ev = page.evaluate("__ev")
# the content process hands over its in-memory stamps when asked (the listener the patched PageAgent installs after the first key)
hs = page.evaluate("(() => { window.dispatchEvent(new Event('hunt-flush')); return window.__hs ? Array.from(window.__hs) : []; })()") if STAMPS else []
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)]
return {
"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,
}
def emit(rec):
print("HUNT-TYPING " + json.dumps(rec), 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(RUNS):
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)
emit(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(RUNS):
# 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)
rec = report(page, t_start, t_start_wall)
if STAMPS:
time.sleep(0.5) # the browser has ended and written its stamps once; the last lines are still on the pipe
rec["hk"] = list(HK)
emit(rec)
srv.shutdown()
+27
View File
@@ -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"))
+102
View File
@@ -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()
+16 -1
View File
@@ -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))
+8
View File
@@ -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