Compare commits

...
Author SHA1 Message Date
feder-cr b53112ee3b HUNT SCAFFOLDING, NEVER MERGED: the pipe-buffer hunt on Windows, ours_bigpipe (the core's two protocol pipes made with CreatePipe(None, 1 << 20) by a runtime patch in the hunt script), ours_normal and stock, interleaved in 3 rounds, 4 processes at once, 60 runs per arm; pipe sizes printed at every launch; S0>S1 and S1>S2 quantiles and a backlog table (bytes written and not yet read, from the stamps) for every S0>S1 over 30 ms 2026-11-14 04:52:27 +01:00
feder-cr 8ed22048ad HUNT SCAFFOLDING, NEVER MERGED: the send hop cut in pieces (S0 core decided, S1 os.write returned, S2 parent JS got the pipe message, S2b Dispatcher entry, S3 = P1), plus a ring of what the parent's Dispatcher ran on its main thread, listed around every hop over 30 ms; ours and stock, 60 runs per arm, the unstamped twin dropped 2026-11-14 03:14:51 +01:00
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 2208 additions and 3 deletions

No files matched your search

@@ -0,0 +1,233 @@
# windows-flakes-pipebuf-hunt.yml - hunt scaffolding, never merged. Runs only on a push to a `hunt/windows-flakes-pipebuf**` branch.
# The sendsplit hunt (stamps S0 core decided, S1 os.write returned, S2 the parent's JS got the pipe message, S2b, S3 = P1, plus the ring of what the
# parent's Dispatcher ran) with ONE thing varied on our side: the size of the two protocol pipes the core makes in `_spawn_windows`. Arms:
# ours_bigpipe (the first two `_winapi.CreatePipe` calls of the spawn made with `CreatePipe(None, 1 << 20)`, by a runtime patch in
# scripts/hunt_typing.py; handle inheritance, handle list and CRT fds are the core's own), ours_normal (the core as it is) and stock. The pipe
# sizes in effect (GetNamedPipeInfo on the handles, and an empirical probe) are printed at every launch. The summary adds, for every S0>S1 over 30 ms,
# the bytes written and not yet read by the engine at that moment, estimated from the stamps (ours arms).
# 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. Windows only: four processes at once, the
# three arms interleaved in 3 rounds, 60 runs per arm. Every command under timeout 300; cleanup never fails the job.
name: windows flakes pipebuf hunt
on:
push:
branches: ['hunt/windows-flakes-pipebuf**']
permissions:
contents: read
actions: read
concurrency:
group: windows-flakes-pipebuf-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: pipebuf 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
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"
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: Patch the Juggler of both engines (omni.ja next to the executable), stamps for Page.dispatchKeyEvent (S2, S2b, P1 and the ring)
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 "send-split points all patched" evidence/patch_ours.txt || { echo "the candidate's Juggler.js / Dispatcher.js did not take the send-split stamps"; exit 1; }
grep -E "send-split points|SKIPPED" evidence/patch_stock.txt || true
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; }
# a quick look before the long run: the runtime patch of the pipes applies (the core's spawn makes four CreatePipe calls, the first two are
# the protocol pipes) and the sizes in effect are printed; a FATAL line or no HUNT-PIPE line stops the job here, not after the hours.
- name: Pipe check, one launch per size
env:
HUNT_STAMPS: "1"
HUNT_RUNS: "1"
run: |
set +e
for big in 0 1; do
HUNT_ARM=check HUNT_BIGPIPE=$big timeout 300 python -u scripts/hunt_typing.py ours "$FF" > "evidence/pipecheck_$big.log" 2>&1
echo "pipecheck bigpipe=$big exit $?"
grep -a '^HUNT-PIPE' "evidence/pipecheck_$big.log"
if grep -aq '^HUNT-PIPE-FATAL' "evidence/pipecheck_$big.log" || ! grep -aq '^HUNT-PIPE {' "evidence/pipecheck_$big.log"; then
echo "::error::the pipe patch does not fit the core (bigpipe=$big)"
tail -30 "evidence/pipecheck_$big.log"
exit 1
fi
done
exit 0
- name: Arms ours_bigpipe, ours_normal and stock with the stamps, interleaved
env:
HUNT_STAMPS: "1"
run: |
set +e
bash scripts/hunt_engine_arm.sh "$FF" "$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|HUNT-PIPE-FATAL" 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-pipebuf-${{ 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
+41
View File
@@ -0,0 +1,41 @@
#!/usr/bin/env bash
# HUNT SCAFFOLDING, NEVER MERGED: the three arms of the pipe-buffer hunt, interleaved so a slow minute of the runner is spread over all of them.
# Usage: scripts/hunt_engine_arm.sh OURS_BINARY STOCK_BINARY (env: HUNT_STAMPS=1 for the patched engines)
# Arms: ours_bigpipe (the candidate, the core's two protocol pipes made with CreatePipe(None, 1 << 20)), ours_normal (the same, the core as it
# is), stock (stock Playwright's Firefox, DEBUG=pw:browser so its driver copies the browser's output into the log).
# Windows, 4 processes at once. 3 rounds; in each round the three arms run one after the other (the order rotates per round), each as 4 processes at
# once x 5 runs, every invocation of hunt_typing.py under `timeout 300`: 3 rounds x 4 x 5 = 60 runs per arm.
# The logs are evidence/loaded_<arm>_<n>.log, which scripts/hunt_engine_summary.py reads.
set +e
ours=$1
stock=$2
mkdir -p evidence
export HUNT_RUNS=5
for round in 1 2 3; do
case $round in
1) order="ours_bigpipe ours_normal stock";;
2) order="ours_normal stock ours_bigpipe";;
3) order="stock ours_bigpipe ours_normal";;
esac
for arm in $order; do
case $arm in
ours_bigpipe) engine=ours; bin=$ours; big=1;;
ours_normal) engine=ours; bin=$ours; big=0;;
stock) engine=stock; bin=$stock; big=0;;
esac
for c in 1 2 3 4; do
(
export HUNT_ARM="$arm" HUNT_BIGPIPE="$big"
if [ "$arm" = "stock" ]; then export DEBUG=pw:browser; fi
timeout 300 python -u scripts/hunt_typing.py "$engine" "$bin" >> "evidence/loaded_${arm}_$c.log" 2>&1
echo "arm $arm round $round process $c exit $?"
) &
done
wait
echo "arm $arm round $round done"
done
done
for arm in ours_bigpipe ours_normal stock; do
echo "arm $arm: HUNT-TYPING lines $(cat evidence/loaded_${arm}_[0-9]*.log 2>/dev/null | grep -ac '^HUNT-TYPING '), HUNTKEY lines in logs $(cat evidence/loaded_${arm}_[0-9]*.log 2>/dev/null | grep -ac 'HUNTKEY '), HUNT-PIPE lines $(cat evidence/loaded_${arm}_[0-9]*.log 2>/dev/null | grep -ac '^HUNT-PIPE ')"
done
exit 0
+681
View File
@@ -0,0 +1,681 @@
"""HUNT SCAFFOLDING, NEVER MERGED: the step summary of the send-split hunt (where the delay of a typed key is born between the client's
decision and the page's handler, with the hop "sent -> P1" cut in pieces).
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 (PIPE-BUFFER hunt): ours_bigpipe (the engine candidate under test, patched by scripts/hunt_patch_omni.py, core of fix/typing-on-absolute-deadlines,
the core's two protocol pipes made 1 MiB big by a runtime patch in scripts/hunt_typing.py), ours_normal (the same with the core's pipes as they are)
and stock (stock Playwright Firefox, its Juggler patched the same way). Windows, 4 processes at once.
What this hunt adds to the send-split summary, first in the output: per arm the quantiles of S0>S1 and S1>S2 (p50 / p95 / p99 / max, count over
LONG_MS), the page keydown gaps under GAP_MS, the dwell error, the pipe sizes in effect at launch (the "pipe" field of each run), and the BACKLOG
table: for every S0>S1 over LONG_MS in the two ours arms, the bytes written to the pipe and not yet read by the engine at that moment, estimated
from the stamps as the sum of the sizes of the Page.dispatchKeyEvent messages (S1's raw message, plus its terminating NUL) with S1 done and S2 not
yet. Only the key messages are stamped, so any other message in the pipe is not in the number (a lower bound); a message whose S2 is missing is
counted apart ("unknown") and left out of the sum. The moment is taken three ways: at S0 (the decision), at the start of the os.write call (S1pre,
the third item of the run's "s1" entries), and the peak between S0 and S1.
The points of one key event (a keydown or keyup command; tags in scripts/hunt_patch_omni.py and scripts/hunt_typing.py):
S0 the client decided (Keyboard.down, before the send; non-Shift keydowns only) "sent"
S1 os.write returned in invisible_core Connection._write (ours only: stock's write is in the node driver)
S2 the parent's JS got the pipe message (components/Juggler.js, nsIRemoteDebuggingPipeClient.receiveMessage)
S2b Dispatcher._dispatch entered (before its JSON.parse)
S3 = P1, PageHandler['Page.dispatchKeyEvent'] entered
C2 .. C5 the content process (latency declared, DOM event about to be made), h = the page's handler (performance.now())
Hops asked for: S0>S1 (core: from the decision to the write), S1>S2 (pipe, C++ reader thread, hand-over to the main thread), S2>S3 (the
parent's main thread up to the handler; S2>S2b and S2b>P1 are its two pieces), P1>C2 (parent to content process). Stock has no S1, so for it
S0>S2 is one hop (shown for both arms as "S0 to S2 (sum)" so they compare).
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 hop
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 hops minus the earlier key's). If the sends themselves were closer than GAP_MS the client is named instead.
Long hops: every S1>S2 (stock: S0>S2) and S2>S3 over LONG_MS (30) is listed with what the parent's main thread ran in its window, from the
ring the Dispatcher wrapper keeps for ALL inbound messages (D: method, id, the synchronous part's duration, the whole duration) and ALL
emitted events (E). An entry "occupies" the window when its synchronous part [t0, t1] overlaps it; an entry whose whole duration overlaps but
whose synchronous part does not is only in flight (awaiting, not on the thread) and is counted by method. Nothing listed means the thread
was held by something the ring does not see (content-to-parent channel messages, GC, the shell, another process's work), or the time was
spent outside the thread (the pipe, the OS scheduler).
"""
import glob
import json
import os
import re
import sys
from urllib.parse import unquote
GAP_MS = 150.0
LONG_MS = 30.0
ARMS = ["ours_bigpipe", "ours_normal", "stock"]
STAMPED = ("ours_bigpipe", "ours_normal", "stock")
OURS = ("ours_bigpipe", "ours_normal")
MODES = ["loaded"]
ORDER = ["sent", "S1", "S2", "S2b", "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 kv(extra):
"""'a=1 b=x' -> {'a': '1', 'b': 'x'}"""
out = {}
for part in (extra or "").split():
if "=" in part:
k, v = part.split("=", 1)
out[k] = v
return out
def message_of(raw):
"""The (type, key) of a Page.dispatchKeyEvent message, from the JSON text; (None, None) if it is not one."""
try:
d = json.loads(raw)
except ValueError:
return None, None
if d.get("method") != "Page.dispatchKeyEvent":
return None, None
p = d.get("params") or {}
return p.get("type"), p.get("key")
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()
s = {"proc": proc, "pid": int(pid), "call": int(call), "tag": tag, "wall": float(wall), "type": typ,
"key": unquote(key), "extra": extra or ""}
if tag in ("S2", "S2b") and s["extra"].startswith("msg="):
t, k = message_of(unquote(s["extra"][4:]))
if t is None:
return None
s["type"], s["key"] = t, k
return s
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):
"""-> (events, ring, anchors): the key events of one run in page order ({"page": (h, e), "tags": {tag: wall}, ...}), the parent's ring
entries (D and E) inside the run's typing window, and the A0 anchors of the parent's modules."""
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"))
for s in loose:
stamps.setdefault("%s %s %s %s" % (s["proc"], s["pid"], s["call"], s["tag"]) + repr(s["wall"]) + s["extra"], (s, "log"))
# one source per distinct stamp: 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"], s["extra"])
if k not in seen or src != "page":
seen[k] = (s, src)
anchors = [s for s, _src in seen.values() if s["tag"] == "A0"]
# 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
by, ring = {}, []
for s, src in seen.values():
if s["tag"] == "A0" or not (w0 <= s["wall"] <= w1):
continue
sources[(s["proc"], src)] = sources.get((s["proc"], src), 0) + 1
if s["tag"] in ("D", "E"):
f = kv(s["extra"])
ring.append({"tag": s["tag"], "t0": s["wall"], "m": f.get("m", "?"), "id": f.get("id"), "sync": float(f.get("sync", "nan")),
"total": float(f["total"]) if "total" in f else None, "t1": float(f.get("t1", "nan")),
"t2": float(f["t2"]) if "t2" in f else None, "len": f.get("len")})
continue
by.setdefault((s["tag"], s["type"], s["key"]), []).append(s)
# S1: ours, stamped by the client right after os.write, the message kept raw
for item in run.get("s1") or []:
wall, raw = item[0], item[1]
pre = item[2] if len(item) > 2 else None
t, k = message_of(raw)
if t is not None and w0 <= wall <= w1:
# the size on the pipe: the JSON as UTF-8 and the NUL the core adds
by.setdefault(("S1", t, k), []).append({"wall": wall, "extra": "", "pre": pre, "size": len(raw.encode("utf-8")) + 1})
for v in by.values():
v.sort(key=lambda s: s["wall"])
ring.sort(key=lambda r: r["t0"])
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,
"s1pre": None, "size": 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 == "S1":
ev["s1pre"], ev["size"] = lst[n].get("pre"), lst[n].get("size")
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()), ring, anchors
def chain(ev):
"""[(name, wall)] of the points 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
t = ev["tags"]
if "C3" in t and "C4" in t and ev["delay"] is not None:
out["timer planned"] = ev["delay"]
out["timer excess"] = (t["C4"] - t["C3"]) - ev["delay"]
if ev["latency"] is not None:
out["timestamp lag"] = (ev["h"] - ev["e"]) - ev["latency"]
if "P1" in t:
out["P1>h total"] = ev["h"] - t["P1"]
# sums that compare the arms (stock has no S1)
if ev["sent"] is not None and "S2" in t:
out["S0 to S2 (sum)"] = t["S2"] - ev["sent"]
if ev["sent"] is not None and "P1" in t:
out["S0 to S3 (sum)"] = t["P1"] - ev["sent"]
if "S2" in t and "P1" in t:
out["S2 to S3 (S2>P1)"] = t["P1"] - t["S2"]
return out
def hops(ev):
"""The hops a page gap is attributed to: S0>S1, S1>S2 (stock: S0>S2), S2>S3, P1>C2, C2>C5, C5>h. Only the present ones."""
t, out = ev["tags"], {}
sent = ev["sent"]
if sent is not None and "S1" in t:
out["S0>S1"] = t["S1"] - sent
elif sent is not None and "S2" in t:
out["S0>S2"] = t["S2"] - sent
if "S1" in t and "S2" in t:
out["S1>S2"] = t["S2"] - t["S1"]
if "S2" in t and "P1" in t:
out["S2>S3"] = t["P1"] - t["S2"]
if "P1" in t and "C2" in t:
out["P1>C2"] = t["C2"] - t["P1"]
if "C2" in t and "C5" in t:
out["C2>C5"] = t["C5"] - t["C2"]
if "C5" in t:
out["C5>h"] = ev["h"] - t["C5"]
return out
def load(evidence, mode, arm, sources):
"""-> list of runs, each {"run": json, "events": [...], "ring": [...], "anchors": [...]}"""
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
events, ring, anchors = build_events(r, loose, sources)
out.append({"run": r, "events": events, "ring": ring, "anchors": anchors})
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:]))
PRI = {"sent>S1": 0, "S1>S2": 1, "sent>S2": 1, "S2>S2b": 2, "S2b>P1": 3, "sent>P1": 3, "S2 to S3 (S2>P1)": 4, "S0 to S2 (sum)": 5,
"S0 to S3 (sum)": 6, "P1>C2": 7, "C2>C3": 8, "timer planned": 9, "C3>C4": 10, "timer excess": 11, "C4>C4r": 12, "C4r>C5": 13,
"C4>C5": 13, "C2>C5": 14, "C5>h": 15, "timestamp lag": 16, "P1>h total": 17}
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)
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.replace("sent", "S0"), " | ".join(cells)))
return lines
def overlaps(ring, a, b, own_from, own_to):
"""(occupying, inflight): ring entries whose synchronous part overlaps [a, b], and those only in flight over it; the key message that
is itself being delivered (a Page.dispatchKeyEvent entered between own_from and own_to) is left out."""
occ, fly = [], []
for r in ring:
if r["m"] == "Page.dispatchKeyEvent" and own_from - 0.5 <= r["t0"] <= own_to + 0.5:
continue
sync_end = r["t1"] if r["t1"] == r["t1"] else r["t0"]
if r["t0"] <= b and sync_end >= a:
occ.append(r)
elif r["tag"] == "D" and r["t2"] is not None and r["t0"] <= b and r["t2"] >= a:
fly.append(r)
return occ, fly
def long_hops(runs):
"""Rows for every S1>S2 (stock S0>S2) and S2>S3 over LONG_MS, with the parent's activity in the window."""
rows = []
for ri, r in enumerate(runs):
for ev in r["events"]:
t = ev["tags"]
wins = []
if "S1" in t and "S2" in t:
wins.append(("S1>S2", t["S1"], t["S2"]))
elif ev["sent"] is not None and "S2" in t and "S1" not in t:
wins.append(("S0>S2", ev["sent"], t["S2"]))
if "S2" in t and "P1" in t:
wins.append(("S2>S3", t["S2"], t["P1"]))
for name, a, b in wins:
if b - a > LONG_MS:
occ, fly = overlaps(r["ring"], a, b, t.get("S2", a), t.get("S2b", b))
rows.append((ri, ev, name, a, b, occ, fly))
return rows
def describe_entry(r, a):
if r["tag"] == "D":
return "%s id=%s sync=%.1f total=%s at %+.1f ms" % (r["m"], r["id"], r["sync"], fmt(r["total"]), r["t0"] - a)
return "event %s sync=%.1f at %+.1f ms" % (r["m"], r["sync"], r["t0"] - a)
def qrow(v):
"""'p50 / p95 / p99 / max / over LONG_MS (n)' of a list of ms, or '-'."""
if not v:
return "-"
return "%s / %s / %s / %s / %d (%d)" % (fmt(q(v, .5)), fmt(q(v, .95)), fmt(q(v, .99)), fmt(max(v)),
sum(1 for x in v if x > LONG_MS), len(v))
def hop_values(runs):
"""{name: [ms]} of the hops the pipe-buffer hunt asks for, over every run of an arm."""
out = {}
for r in runs:
for ev in r["events"]:
t = ev["tags"]
if ev["sent"] is not None and "S1" in t:
out.setdefault("S0>S1", []).append(t["S1"] - ev["sent"])
if ev["sent"] is not None and "S2" in t:
out.setdefault("S0>S2 (sum)", []).append(t["S2"] - ev["sent"])
if "S1" in t and "S2" in t:
out.setdefault("S1>S2 (every key command)", []).append(t["S2"] - t["S1"])
if ev["type"] == "keydown" and ev["key"] != "Shift":
out.setdefault("S1>S2 (non-Shift keydown)", []).append(t["S2"] - t["S1"])
if ev["s1pre"] is not None and "S1" in t:
out.setdefault("os.write call (S1pre>S1)", []).append(t["S1"] - ev["s1pre"])
if ev["sent"] is not None and ev["s1pre"] is not None:
out.setdefault("S0>S1pre (core before the write)", []).append(ev["s1pre"] - ev["sent"])
return out
def messages_of(events):
"""The key messages of one run that have S1: {"s1", "s2" (None if unstamped), "size", "ev"}."""
return [{"s1": ev["tags"]["S1"], "s2": ev["tags"].get("S2"), "size": ev["size"], "ev": ev}
for ev in events if "S1" in ev["tags"] and ev.get("size")]
def backlog_at(msgs, when, skip):
"""(bytes, messages, unknown): the messages other than `skip` with S1 done and S2 not yet at `when`; one without S2 is counted as unknown."""
size = n = unknown = 0
for m in msgs:
if m is skip or m["s1"] > when:
continue
if m["s2"] is None:
unknown += 1
elif m["s2"] > when:
size += m["size"]
n += 1
return size, n, unknown
def backlog_rows(runs):
"""-> (rows, all_at_write): a row per ours event with S0>S1 over LONG_MS; and, for every event with S1pre, the backlog at the start of its write."""
rows, every = [], []
for ri, r in enumerate(runs):
msgs = messages_of(r["events"])
pipe = r["run"].get("pipe") or {}
for m in msgs:
ev = m["ev"]
if ev["s1pre"] is not None:
every.append(backlog_at(msgs, ev["s1pre"], m)[0])
if ev["sent"] is None or m["s1"] - ev["sent"] <= LONG_MS:
continue
at_s0 = backlog_at(msgs, ev["sent"], m)
at_w = backlog_at(msgs, ev["s1pre"], m) if ev["s1pre"] is not None else None
# the peak between the decision and the end of the write: sampled at the decision and at every S1 / S2 of another message inside it
times = [ev["sent"], m["s1"]] + [x for o in msgs if o is not m for x in (o["s1"], o["s2"]) if x is not None and ev["sent"] <= x <= m["s1"]]
peak = max(backlog_at(msgs, x, m)[0] for x in times)
rows.append((ri, ev, m["s1"] - ev["sent"], (ev["s1pre"] - ev["sent"]) if ev["s1pre"] is not None else None,
(m["s1"] - ev["s1pre"]) if ev["s1pre"] is not None else None, at_s0, at_w, peak, pipe))
return rows, every
def pipebuf_section(data):
print("### S0>S1 and S1>S2 per arm (ms): p50 / p95 / p99 / max / over %d ms (n)" % LONG_MS)
print()
print("stock has no S1 (its write is made by the node driver): its hop is S0>S2, shown as the sum for every arm.")
print()
cols = {arm: hop_values(runs) for arm, runs in data.items() if arm in STAMPED}
names = []
for c in cols.values():
for k in c:
if k not in names:
names.append(k)
order = ["S0>S1", "S0>S1pre (core before the write)", "os.write call (S1pre>S1)", "S1>S2 (every key command)", "S1>S2 (non-Shift keydown)",
"S0>S2 (sum)"]
names.sort(key=lambda k: order.index(k) if k in order else 99)
print("| hop | " + " | ".join(cols) + " |")
print("|---|" + "---|" * len(cols))
for k in names:
print("| %s | %s |" % (k, " | ".join(qrow(c.get(k)) for c in cols.values())))
print()
print("### pipe sizes in effect at launch (what the runs printed: GetNamedPipeInfo on the core's two handles, and the probe of a pipe made with the same size)")
print()
print("| arm | runs with a pipe record | CreatePipe calls in the spawn | size asked (0 = default) | probe: bytes taken before a writer blocks | to_browser (flags / out / in / max) | from_browser (flags / out / in / max) |")
print("|---|---|---|---|---|---|---|")
for arm, runs in data.items():
recs = [r["run"].get("pipe") for r in runs if r["run"].get("pipe")]
if not recs:
print("| %s | 0 | - | - | - | not measured: its pipes are made by the node driver | - |" % arm)
continue
seen = {}
for p in recs:
def one(d):
return "error %s" % d["error"] if d and "error" in d else ("%s / %s / %s / %s" % tuple(d.get(x, "-") for x in ("flags", "out", "in", "max")) if d else "-")
key = (p.get("createpipe_calls"), p.get("asked"), p.get("probe_bytes"), one(p.get("to_browser")), one(p.get("from_browser")))
seen[key] = seen.get(key, 0) + 1
for (calls, asked, probe, tb, fb), n in sorted(seen.items(), key=lambda kv_: -kv_[1]):
print("| %s | %d | %s | %s | %s | %s | %s |" % (arm, n, calls, asked, probe, tb, fb))
print()
print("### backlog: for every S0>S1 over %d ms, the bytes written (S1 done) and not yet read by the engine (S2 not yet), from the stamps" % LONG_MS)
print()
print("Only Page.dispatchKeyEvent messages are stamped, so this is a lower bound of what is in the pipe. 'unknown' = other messages whose S2 is missing "
"(left out of the sum). at S0 = the decision, at write = the start of the os.write call, peak = the largest between S0 and the end of the write.")
print()
for arm in OURS:
if arm not in data:
continue
rows, every = backlog_rows(data[arm])
print("#### %s" % arm)
print()
print("backlog at the start of every write (all key commands, bytes) p50 / p95 / max (n): %s / %s / %s (%d); S0>S1 over %d ms: %d" % (
fmt(q(every, .5)), fmt(q(every, .95)), fmt(max(every) if every else None), len(every), LONG_MS, len(rows)))
print()
if not rows:
print("no S0>S1 over %d ms" % LONG_MS)
print()
continue
big = sum(1 for x in rows if x[7] >= 4096)
print("of them with a peak of 4096 bytes or more (the default size of an anonymous pipe): %d" % big)
print()
print("| run | key | S0>S1 | S0>S1pre | in os.write | at S0 bytes (msgs, unknown) | at write bytes (msgs, unknown) | peak bytes | pipe: asked / probe / to_browser out,in |")
print("|---|---|---|---|---|---|---|---|---|")
for ri, ev, tot, before, inwrite, a0, aw, peak, pipe in rows[:60]:
tb = pipe.get("to_browser") or {}
print("| %d | %s %s | %.1f | %s | %s | %d (%d, %d) | %s | %d | %s / %s / %s,%s |" % (
ri, ev["type"], ev["key"], tot, fmt(before), fmt(inwrite), a0[0], a0[1], a0[2],
"-" if aw is None else "%d (%d, %d)" % aw, peak, pipe.get("asked", "-"), pipe.get("probe_bytes", "-"), tb.get("out", "-"), tb.get("in", "-")))
if len(rows) > 60:
print("(%d more not listed)" % (len(rows) - 60))
print()
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("## pipe-buffer hunt (send-split stamps), %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()
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 "S2" in e["tags"] and "P1" in e["tags"] and "C2" in e["tags"] and "C5" in e["tags"])
s1 = sum(1 for e in evs if "S1" in e["tags"])
s2 = sum(1 for e in evs if "S2" in e["tags"])
s2b = sum(1 for e in evs if "S2b" in e["tags"])
p1 = sum(1 for e in evs if "P1" in e["tags"])
ring = sum(len(r["ring"]) for r in data[arm])
print("- %s: %d key events; with S1 %d, S2 %d, S2b %d, P1 %d, S2+P1+C2+C5 %d; ring entries in the typing windows %d" % (
arm, len(evs), s1, s2, s2b, p1, full, ring))
print()
pipebuf_section(data)
print("### clocks of the parent's modules (A0 stamps: every patched module says the anchor it uses)")
print()
for arm in STAMPED:
if arm not in data:
continue
spreads, shared, total = [], 0, 0
for r in data[arm]:
by_pid = {}
for a in r["anchors"]:
by_pid.setdefault(a["pid"], []).append(a)
for pid, lst in by_pid.items():
vals = []
for a in lst:
f = kv(a["extra"])
total += 1
shared += 1 if f.get("shared") == "true" else 0
try:
vals.append(float(f["anchor"]))
except (KeyError, ValueError):
pass
if len(vals) > 1:
spreads.append(max(vals) - min(vals))
print("- %s: %d module stamps, %d reused another module's anchor; anchor spread inside one process p50 / max %s / %s ms (%d processes)" % (
arm, total, shared, fmt(q(spreads, .5)), fmt(max(spreads) if spreads else None), len(spreads)))
print()
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("### hops of a %s command (ms): S0>S1 core, S1>S2 pipe + reader thread + main-thread hand-over, S2>S3 (=P1) parent main thread, P1>C2" % kind)
print()
print("\n".join(step_table(stamped, kind)))
print()
# which hop 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 = hops(a), hops(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 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 hop 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 hops | later key's hops |")
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()
# long hops and what the parent's main thread ran
for arm, runs in stamped.items():
rows = long_hops(runs)
print("### %s: hops over %d ms (S1>S2, S2>S3) and the parent's activity in their window" % (arm, LONG_MS))
print()
events_n = sum(1 for r in runs for e in r["events"] if "S2" in e["tags"])
print("key events with S2: %d; long hops: %d (S1>S2 %d, S0>S2 %d, S2>S3 %d)" % (
events_n, len(rows), sum(1 for x in rows if x[2] == "S1>S2"), sum(1 for x in rows if x[2] == "S0>S2"),
sum(1 for x in rows if x[2] == "S2>S3")))
print()
if not rows:
continue
print("| run | key | hop | ms | S2>S2b / S2b>S3 | occupying the thread (sync part overlaps) | in flight only |")
print("|---|---|---|---|---|---|---|")
for ri, ev, name, a, b, occ, fly in rows[:40]:
t = ev["tags"]
pieces = "%s / %s" % (fmt(t["S2b"] - t["S2"]) if "S2b" in t and "S2" in t else "-",
fmt(t["P1"] - t["S2b"]) if "S2b" in t and "P1" in t else "-")
occs = "; ".join(describe_entry(r, a) for r in occ[:8]) + (" (+%d)" % (len(occ) - 8) if len(occ) > 8 else "")
counts = {}
for r in fly:
counts[r["m"]] = counts.get(r["m"], 0) + 1
flies = ", ".join("%s x%d" % (k, v) for k, v in sorted(counts.items(), key=lambda kv_: -kv_[1]))
print("| %d | %s %s | %s | %.1f | %s | %s | %s |" % (ri, ev["type"], ev["key"], name, b - a, pieces, occs or "nothing in the ring", flies or "-"))
if len(rows) > 40:
print("(%d more not listed)" % (len(rows) - 40))
print()
# the parent's main-thread work, per method, in the typing windows: ours against stock
print("### the parent's inbound messages and emitted events in the typing windows (synchronous part, ms)")
print()
cols = {}
for arm, runs in stamped.items():
vals = {}
for r in runs:
for e in r["ring"]:
if e["sync"] == e["sync"]:
vals.setdefault(("event " if e["tag"] == "E" else "") + e["m"], []).append(e["sync"])
cols[arm] = vals
names = sorted({k for v in cols.values() for k in v}, key=lambda k: -max(max(v.get(k, [0])) for v in cols.values()))
if names:
print("| message / event | " + " | ".join("%s n / p50 / p95 / max" % a for a in cols) + " |")
print("|---|" + "---|" * len(cols))
for k in names[:14]:
cells = []
for arm in cols:
v = cols[arm].get(k)
cells.append("-" if not v else "%d / %s / %s / %s" % (len(v), fmt(q(v, .5)), fmt(q(v, .95)), fmt(max(v))))
print("| %s | %s |" % (k, " | ".join(cells)))
else:
print("no ring entries")
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()
+477
View File
@@ -0,0 +1,477 @@
"""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.
SEND-SPLIT hunt additions (the parent's side of the hop "sent -> P1"; S0 = the client decided, S1 = os.write returned in the core's
Connection._write, both stamped by scripts/hunt_typing.py; S3 = P1):
S2 parent: the pipe's message reached JS (components/Juggler.js, the nsIRemoteDebuggingPipeClient's receiveMessage, the first JS on the
parent's main thread after the C++ reader thread handed the message over), only for Page.dispatchKeyEvent; extra msg=<urlencoded JSON>
S2b parent: Dispatcher._dispatch entered (protocol/Dispatcher.js, before the JSON.parse), the same messages; extra msg=
D parent, EVERY inbound message (a ring buffer, 8192 entries, written once at the end): `<wall of entry> - - m=<method> id=<id>
sync=<ms of the synchronous part, entry to the first await> total=<ms until the answer was sent> t1=<wall at the end of the
synchronous part> t2=<wall at the end> len=<characters>`; written when the message finished
E parent, EVERY event Dispatcher._emitEvent sent to the client (the same ring): `m=<event> sync=<ms> t1=<wall at the end>`
A0 each patched module of a process says the anchor it calibrated (extra module=<file> anchor=<ms>); a module reuses the one an earlier
module of the same global left in globalThis.__HKANCHOR, so the stamps of Juggler.js, Dispatcher.js and PageHandler.js share one clock
when the modules share a global, and the summary shows the spread when they do not.
The three extra files are optional for stock (a Juggler that does not match is reported and left alone) and required for ours.
"""
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;
let shared = false;
try {
if (typeof globalThis.__HKANCHOR === 'number') {
anchor = globalThis.__HKANCHOR;
shared = true;
} else {
const t0 = clk();
const a = Date.now();
let b = a;
while (b === a && clk() - t0 < 30) b = Date.now();
anchor = b - clk();
globalThis.__HKANCHOR = anchor;
}
} 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) {}
// the ring of the parent's main-thread activity: written once at the end with the other lines, the oldest entries overwritten
const RING = 8192;
const ring = new Array(RING);
let ringN = 0;
let ringDumped = 0;
const writeRing = () => {
const from = Math.max(ringDumped, ringN - RING);
if (from >= ringN) return;
const lines = [];
for (let i = from; i < ringN; i++) lines.push('HUNTKEY ' + ring[i % RING] + '\n');
ringDumped = ringN;
try { dump(lines.join('')); } catch (e) {}
};
try {
const obs2 = { observe() { writeRing(); } };
Services.obs.addObserver(obs2, 'quit-application');
Services.obs.addObserver(obs2, 'xpcom-shutdown');
} catch (e) {}
const hooked = new WeakSet();
return {
now: wall,
// a message that arrived: only a key event is kept (raw, urlencoded: nothing is parsed here), the rest of the stamp is the clock
raw(tag, message) {
try {
if (typeof message !== 'string' || message.indexOf('Page.dispatchKeyEvent') < 0) return;
buf.push(['parent', pid, seq, tag, wall().toFixed(3), '-', '-', 'msg=' + encodeURIComponent(message)].join(' '));
} catch (e) {}
},
// one entry of the ring (a finished message or an emitted event)
ringPush(tag, t0, extra) {
try {
ring[ringN++ % RING] = ['parent', pid, 0, tag, t0.toFixed(3), '-', '-', extra].join(' ');
} catch (e) {}
},
module(name) {
try { buf.push(['parent', pid, 0, 'A0', wall().toFixed(3), '-', '-', 'module=' + name + ' anchor=' + anchor.toFixed(3) + ' shared=' + shared].join(' ')); } catch (e) {}
},
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"""
__HK.module('PageHandler.js');
(() => {
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 ----
"""
# Juggler.js: only the helper (S2 is stamped by the call put into receiveMessage), Dispatcher.js: S2b, the ring of every message and event
JUGGLER_TAIL = r"""
__HK.module('Juggler.js');
// ---- HUNTKEY end ----
"""
DISPATCHER_WRAP = r"""
__HK.module('Dispatcher.js');
(() => {
const proto = (typeof Dispatcher === 'function') ? Dispatcher.prototype : null;
if (!proto) return;
const origDispatch = proto._dispatch;
const origEmit = proto._emitEvent;
const reMethod = /"method"\s*:\s*"([^"]*)"/;
const reId = /"id"\s*:\s*(\d+)/;
if (typeof origDispatch === 'function') {
proto._dispatch = function(event) {
const t0 = __HK.now();
const data = event && event.data;
let method = '?', id = '?', len = 0;
try {
if (typeof data === 'string') {
len = data.length;
const m = reMethod.exec(data), i = reId.exec(data);
if (m) method = m[1];
if (i) id = i[1];
__HK.raw('S2b', data);
}
} catch (e) {}
const p = origDispatch.call(this, event); // the synchronous part (parse, check, the handler up to its first await) runs here
const t1 = __HK.now();
const done = () => {
const t2 = __HK.now();
__HK.ringPush('D', t0, 'm=' + method + ' id=' + id + ' sync=' + (t1 - t0).toFixed(3) + ' total=' + (t2 - t0).toFixed(3)
+ ' t1=' + t1.toFixed(3) + ' t2=' + t2.toFixed(3) + ' len=' + len);
};
try { p.then(done, done); } catch (e) { done(); }
return p;
};
}
if (typeof origEmit === 'function') {
proto._emitEvent = function(sessionId, eventName, params) {
const t0 = __HK.now();
try {
return origEmit.call(this, sessionId, eventName, params);
} finally {
const t1 = __HK.now();
__HK.ringPush('E', t0, 'm=' + eventName + ' sync=' + (t1 - t0).toFixed(3) + ' t1=' + t1.toFixed(3));
}
};
}
})();
// ---- 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
# the pipe client's receiveMessage in components/Juggler.js (juggler/components/Juggler.js:123 in the source tree)
RECV = re.compile(r"(receiveMessage\(message\)\s*\{)(\s*if \(this\.onmessage\))")
def patch_juggler(text):
n = len(re.findall(r"receiveMessage\(message\)", text))
anchors = {"pipe client receiveMessage(message)": n,
"nsIRemoteDebuggingPipeClient": "nsIRemoteDebuggingPipeClient" in text}
if MARK in text:
return text, dict(anchors, already=True)
if n != 1 or not anchors["nsIRemoteDebuggingPipeClient"]:
return None, anchors
new, k = RECV.subn(lambda m: m.group(1) + " __HK.raw('S2', message);" + m.group(2), text)
anchors["receiveMessage call patched"] = k
if k != 1:
return None, anchors
return new.rstrip("\n") + "\n" + HELPER + JUGGLER_TAIL, anchors
def patch_dispatcher(text):
anchors = {"class Dispatcher": bool(re.search(r"class Dispatcher", text)),
"async _dispatch(event)": bool(re.search(r"async _dispatch\(event\)", text)),
"JSON.parse(event.data)": "JSON.parse(event.data)" in text,
"_emitEvent": bool(re.search(r"_emitEvent\(", 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 + DISPATCHER_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, "Juggler.js": patch_juggler, "Dispatcher.js": patch_dispatcher}
# the files of the send-split hunt: required for ours, for stock only when its file matches
OPTIONAL_FOR_STOCK = {"Juggler.js", "Dispatcher.js"}
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 and KIND == "stock" and base in OPTIONAL_FOR_STOCK:
report["members"][name] = dict(anchors, skipped="no match in stock, left alone")
print("SKIPPED %s (stock): %s" % (name, json.dumps(anchors)))
continue
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 and KIND == "stock" and f in OPTIONAL_FOR_STOCK:
report["members"][p] = dict(anchors, skipped="no match in stock, left alone")
print("SKIPPED %s (stock): %s" % (p, json.dumps(anchors)))
continue
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"]
got = {k.rsplit("/", 1)[-1].rsplit("\\", 1)[-1] for k in members}
need = {"PageHandler.js", "PageAgent.js"} | (set() if kind == "stock" else OPTIONAL_FOR_STOCK)
if not need <= got:
raise SystemExit("expected %s, found %s" % (sorted(need), sorted(members)))
skipped = sorted(k for k, a in members.items() if a.get("skipped"))
print("send-split points %s" % ("stock: skipped " + ", ".join(skipped) if skipped else "all patched"))
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()
+360
View File
@@ -0,0 +1,360 @@
"""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. SEND-SPLIT hunt: ours also stamps S1 (os.write returned in the core's Connection._write for each Page.dispatchKeyEvent message,
kept raw in memory, field "s1": [wall ms, the JSON of the message]); S0 is the existing "sent_wall_ms" (Keyboard.down before the send). Stock has no S1:
its write is made by Playwright's node driver. 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").
PIPE-BUFFER hunt additions (Windows): ours runs in two arms that differ in one thing, the size of the two Juggler pipes the core makes in
`_spawn_windows`. HUNT_BIGPIPE=1 (arm ours_bigpipe): the first two `_winapi.CreatePipe` calls inside `_spawn_windows` (the browser's two protocol
pipes; the third is stdout, the fourth stdin) are made with `_winapi.CreatePipe(None, 1 << 20)` instead of `CreatePipe(0, 0)`. Nothing else of the spawn
is touched: the core still duplicates the browser's ends with inheritance, names them in the handle list, and wraps ITS ends into CRT fds with
msvcrt.open_osfhandle. HUNT_BIGPIPE=0 (arm ours_normal): the core as it is. At every launch the pipe sizes in effect are printed ("HUNT-PIPE" line and
the run's "pipe" field): GetNamedPipeInfo on the two handles the core keeps, and, once per process, an empirical probe of how many bytes a pipe
made with the same size takes before a writer blocks. Stock has no such pipes (its node driver makes them). S1 also keeps a "before os.write"
clock (third item of each "s1" entry), so a slow hop can be told from a slow write.
"""
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"
BIGPIPE = os.environ.get("HUNT_BIGPIPE") == "1"
BIG = 1 << 20
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 = []
S1 = []
HK = []
PIPE = {}
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),
"s1": [[t, d.decode("utf-8", "replace").rstrip("\x00"), pre] for t, d, pre in S1],
"pipe": dict(PIPE),
"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:
# S1: os.write returned in the core's Connection._write (after the write, nothing else done there: a clock read, then the message
# is kept raw in memory; the JSON is read only at the end). The module's `os` is replaced by a stand-in that forwards everything
# and stamps the one write of a Page.dispatchKeyEvent message.
import os as _os
from invisible_core.juggler import connection as _conn
class _OsStamp:
def __getattr__(self, name):
return getattr(_os, name)
@staticmethod
def write(fd, data):
pre = wall_ms()
n = _os.write(fd, data)
t = wall_ms()
if b"Page.dispatchKeyEvent" in data:
S1.append((round(t, 3), bytes(data), round(pre, 3)))
return n
_conn.os = _OsStamp()
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
# ---- the pipes of the browser's protocol: sizes in effect, and in the bigpipe arm the size asked for ---------------------------------
PIPE_DIAG = {"arm": os.environ.get("HUNT_ARM", ENGINE), "bigpipe": BIGPIPE}
if sys.platform != "win32":
if BIGPIPE:
print("HUNT-PIPE-FATAL the bigpipe arm is Windows only", flush=True)
sys.exit(3)
PIPE_DIAG["note"] = "not Windows: the pipes are os.pipe, not measured"
else:
import ctypes
import msvcrt
import _winapi
from ctypes import wintypes
from invisible_core.juggler import connection as _pc
_k32 = ctypes.WinDLL("kernel32", use_last_error=True)
_k32.GetNamedPipeInfo.argtypes = (wintypes.HANDLE, ctypes.POINTER(wintypes.DWORD), ctypes.POINTER(wintypes.DWORD),
ctypes.POINTER(wintypes.DWORD), ctypes.POINTER(wintypes.DWORD))
_k32.GetNamedPipeInfo.restype = wintypes.BOOL
def pipe_info(fd):
"""GetNamedPipeInfo on the handle behind a CRT fd: {flags, out, in, max} (bytes), or {"error": ...}."""
try:
h = msvcrt.get_osfhandle(fd)
flags, out, inn, mx = wintypes.DWORD(), wintypes.DWORD(), wintypes.DWORD(), wintypes.DWORD()
if not _k32.GetNamedPipeInfo(h, ctypes.byref(flags), ctypes.byref(out), ctypes.byref(inn), ctypes.byref(mx)):
return {"error": "GetNamedPipeInfo failed, winerror %d" % ctypes.get_last_error()}
return {"flags": flags.value, "out": out.value, "in": inn.value, "max": mx.value}
except Exception as exc: # a measurement must never stop the hunt
return {"error": repr(exc)}
def probe_capacity(size):
"""How many bytes a pipe made by CreatePipe(None, size) takes before a writer blocks: a thread writes 512-byte chunks into a
pipe nobody reads; what it completed when it has made no progress for 0.3 s is the capacity (to 512 bytes). Closed afterwards."""
r, w = _winapi.CreatePipe(None, size)
done = [0]
def writer():
chunk = b"x" * 512
try:
while done[0] < (64 << 20):
_winapi.WriteFile(w, chunk)
done[0] += 512
except OSError:
pass
t = threading.Thread(target=writer, daemon=True)
t.start()
last, still = -1, 0.0
t0 = time.perf_counter()
while still < 0.3 and time.perf_counter() - t0 < 20:
time.sleep(0.05)
if done[0] == last:
still += 0.05
else:
last, still = done[0], 0.0
got = done[0]
_winapi.CloseHandle(r) # the blocked write fails and the thread ends
t.join(2)
_winapi.CloseHandle(w)
return got
PIPE_DIAG["asked"] = BIG if BIGPIPE else 0
PIPE_DIAG["probe_bytes"] = probe_capacity(BIG if BIGPIPE else 0)
_real_create_pipe = _winapi.CreatePipe
_tl = threading.local()
def _create_pipe(attrs, size):
n = getattr(_tl, "n", None)
if n is None: # not inside the core's spawn: untouched
return _real_create_pipe(attrs, size)
_tl.n = n + 1
if BIGPIPE and n < 2: # the core's first two pipes are the two protocol directions
return _real_create_pipe(None, BIG)
return _real_create_pipe(attrs, size)
_winapi.CreatePipe = _create_pipe
_real_spawn = _pc._spawn_windows
def _spawn(executable, argv, env):
_tl.n = 0
try:
res = _real_spawn(executable, argv, env)
finally:
calls, _tl.n = _tl.n, None
to_browser, from_browser, _proc = res
PIPE.clear()
PIPE.update({"arm": PIPE_DIAG["arm"], "bigpipe": BIGPIPE, "createpipe_calls": calls, "asked": PIPE_DIAG["asked"],
"probe_bytes": PIPE_DIAG["probe_bytes"], "to_browser": pipe_info(to_browser), "from_browser": pipe_info(from_browser)})
print("HUNT-PIPE " + json.dumps(PIPE), flush=True)
if calls != 4:
print("HUNT-PIPE-FATAL the core's _spawn_windows made %d CreatePipe calls, expected 4: the patch no longer fits the core" % calls,
flush=True)
os._exit(3)
return res
_pc._spawn_windows = _spawn
print("HUNT-PIPE-PATCH " + json.dumps(PIPE_DIAG), flush=True)
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()
S1.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