From 909411228431e163a00417363c0c5377741a141b Mon Sep 17 00:00:00 2001 From: Saksham Uboweja <76595406+SakshamUboweja@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:04:27 +0000 Subject: [PATCH 1/5] plugin: give each thread its own temporary launcher file A Hermes gateway runs every session's hooks as threads of one process. The launcher's temporary file was named by the process alone, so sessions whose first prompts wrote bin/te and bin/te.json together shared one file: the first rename took it and the others failed, each failure a line in errors.log. Name it by the thread too, and replace through the store's Windows retry, since Windows refuses to replace a file another thread is reading or replacing. --- tests/test_windows_launcher.py | 29 +++++++++++++++++++++++++++++ tokeneconomizer/plugin/paths.py | 9 +++++++-- 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/tests/test_windows_launcher.py b/tests/test_windows_launcher.py index c68800ed..f08623ee 100644 --- a/tests/test_windows_launcher.py +++ b/tests/test_windows_launcher.py @@ -63,3 +63,32 @@ def test_the_windows_launcher_runs_the_command_line(repo, tmp_path, monkeypatch) p = subprocess.run([git_sh() or "sh", ensure_launcher(env), "--cwd", repo, "config", "set", "spiral=off"], env=run_env, capture_output=True, text=True) assert p.returncode == 0, p.stderr + + +def test_sessions_that_write_the_launcher_at_once_from_one_process_do_not_collide( + tmp_path, monkeypatch): + """A Hermes gateway runs every session's hooks as threads of one process, and the first + prompts of several sessions write the launcher together. Named by the process alone, their + temporary files were one file: the first rename took it, and the rest failed, each failure a + line in errors.log.""" + import threading + monkeypatch.setattr(paths, "_WINDOWS", False) + together = threading.Barrier(4, timeout=10) + real = os.replace + + def replace(src, dst): + together.wait() # every writer is between its write and its rename + return real(src, dst) + monkeypatch.setattr(os, "replace", replace) + env, errors = _env(tmp_path), [] + + def write(): + try: + ensure_launcher(env) + except OSError as e: + errors.append(e) + threads = [threading.Thread(target=write) for _ in range(4)] + [t.start() for t in threads] + [t.join() for t in threads] + assert errors == [] + assert sorted(os.listdir(os.path.dirname(paths.launcher_path(env)))) == ["te"] diff --git a/tokeneconomizer/plugin/paths.py b/tokeneconomizer/plugin/paths.py index 7a541e59..019c474e 100644 --- a/tokeneconomizer/plugin/paths.py +++ b/tokeneconomizer/plugin/paths.py @@ -67,6 +67,8 @@ def ensure_launcher(env=None): changes, as an installed copy's path does across updates.""" import shlex import sys + import threading + from .store import _replace env = os.environ if env is None else env plugin = env.get("TE_PLUGIN_ROOT") target = os.path.join(plugin, "scripts", "te") if plugin else "" @@ -101,13 +103,16 @@ def ensure_launcher(env=None): except OSError: pass os.makedirs(os.path.dirname(launcher), exist_ok=True) - tmp = "%s.%d.tmp" % (launcher, os.getpid()) + # The thread too: one Hermes gateway runs its sessions' hooks as threads of one process, + # and two of them sharing a temporary file would rename it out from under each other. + tmp = "%s.%d.%d.tmp" % (launcher, os.getpid(), threading.get_ident()) # newline="\n": text mode on Windows would end each line with CRLF, and `sh` would pass # the trailing "\r" on as an argument. with open(tmp, "w", encoding="utf-8", newline="\n") as fh: fh.write(body) os.chmod(tmp, 0o700) - os.replace(tmp, launcher) + # Windows refuses to replace a file another thread is reading or replacing. + _replace(tmp, launcher) return path From a5f7052b7d8adcb09615038bbb1de66c3e1815ef Mon Sep 17 00:00:00 2001 From: Saksham Uboweja <76595406+SakshamUboweja@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:07:27 +0000 Subject: [PATCH 2/5] TEMP: Windows proof job for the launcher race (remove before PR) --- .github/workflows/launcher-race-proof.yml | 47 +++++++++++++++++++++++ .proof/stress.py | 22 +++++++++++ 2 files changed, 69 insertions(+) create mode 100644 .github/workflows/launcher-race-proof.yml create mode 100644 .proof/stress.py diff --git a/.github/workflows/launcher-race-proof.yml b/.github/workflows/launcher-race-proof.yml new file mode 100644 index 00000000..acbf3df4 --- /dev/null +++ b/.github/workflows/launcher-race-proof.yml @@ -0,0 +1,47 @@ +# Temporary: proves the launcher race fix on Windows. Removed before any PR. +name: launcher-race-proof +on: + push: + branches: [fix/launcher-thread-race] +permissions: + contents: read +jobs: + proof: + strategy: + fail-fast: false + matrix: + os: [windows-latest, ubuntu-latest] + python: ["3.10", "3.13"] + runs-on: ${{ matrix.os }} + timeout-minutes: 30 + defaults: + run: + shell: bash + steps: + - uses: actions/checkout@v5 + with: + fetch-depth: 0 + - uses: actions/setup-python@v6 + with: + python-version: ${{ matrix.python }} + - run: python -m pip install pytest + - name: old code from main + run: mkdir -p ../old && git archive d660b3e tokeneconomizer | tar -x -C ../old + - name: "stress: 4 threads write the launcher at once, 300 times" + run: | + python -I .proof/stress.py ../old 300 "before (main)" || true + python -I .proof/stress.py "$PWD" 300 "after, unique name only" noretry + python -I .proof/stress.py "$PWD" 300 "after (the fix)" + - name: "the CI test, 40 times, on main's code" + run: | + cp -r tokeneconomizer ../new + rm -rf tokeneconomizer && cp -r ../old/tokeneconomizer tokeneconomizer + f=0; for i in $(seq 40); do python -m pytest -q -p no:cacheprovider "tests/test_hermes_plugin.py::test_gateway_and_cron_sessions_in_two_repositories_fold_apart_through_the_real_dispatcher" >/dev/null 2>&1 || f=$((f+1)); done + echo "before (main): $f/40 failed" + rm -rf tokeneconomizer && cp -r ../new tokeneconomizer + - name: "the CI test, 40 times, with the fix" + run: | + f=0; for i in $(seq 40); do python -m pytest -q -p no:cacheprovider "tests/test_hermes_plugin.py::test_gateway_and_cron_sessions_in_two_repositories_fold_apart_through_the_real_dispatcher" >/dev/null 2>&1 || f=$((f+1)); done + echo "after (the fix): $f/40 failed"; test "$f" = 0 + - name: new regression test and launcher tests + run: python -m pytest -q -p no:cacheprovider tests/test_windows_launcher.py tests/test_hermes_plugin.py diff --git a/.proof/stress.py b/.proof/stress.py new file mode 100644 index 00000000..4bd2de1b --- /dev/null +++ b/.proof/stress.py @@ -0,0 +1,22 @@ +"""Run ensure_launcher from 4 threads at once, as a Hermes gateway does, N times; count errors.""" +import collections, os, sys, tempfile, threading +sys.path.insert(0, sys.argv[1]) +from tokeneconomizer.plugin import paths +if len(sys.argv) > 4 and sys.argv[4] == "noretry": + from tokeneconomizer.plugin import store + store._replace = os.replace # the unique name alone, without the Windows retry +if len(sys.argv) > 4 and sys.argv[4] == "windows": + paths._WINDOWS = True +plugin = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "plugin") +runs, fails, bad = int(sys.argv[2]), collections.Counter(), 0 +for _ in range(runs): + env = {"TE_PLUGIN_ROOT": os.path.abspath(plugin), "TOKENECONOMIZER_HOME": tempfile.mkdtemp()} + go, errs = threading.Barrier(4), [] + def w(): + go.wait() + try: paths.ensure_launcher(env) + except OSError as e: errs.append(type(e).__name__) + ts = [threading.Thread(target=w) for _ in range(4)] + [t.start() for t in ts]; [t.join() for t in ts] + bad += bool(errs); fails.update(errs) +print(f"{sys.argv[3]}: {bad}/{runs} runs had an error {dict(fails)}") From 6fea5677cacb592305cd25d06136fa7e92511fb9 Mon Sep 17 00:00:00 2001 From: Saksham Uboweja <76595406+SakshamUboweja@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:16:02 +0000 Subject: [PATCH 3/5] plugin: remove a launcher's temporary file when its write fails; let the race test survive a Windows retry --- tests/test_windows_launcher.py | 8 ++++++-- tokeneconomizer/plugin/paths.py | 16 +++++++++++----- 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/tests/test_windows_launcher.py b/tests/test_windows_launcher.py index f08623ee..84223788 100644 --- a/tests/test_windows_launcher.py +++ b/tests/test_windows_launcher.py @@ -73,11 +73,15 @@ def test_sessions_that_write_the_launcher_at_once_from_one_process_do_not_collid line in errors.log.""" import threading monkeypatch.setattr(paths, "_WINDOWS", False) - together = threading.Barrier(4, timeout=10) + together, first, lock = threading.Barrier(4, timeout=10), set(), threading.Lock() real = os.replace def replace(src, dst): - together.wait() # every writer is between its write and its rename + with lock: + waits = threading.get_ident() not in first + first.add(threading.get_ident()) + if waits: # every writer is between its write and its rename + together.wait() # (a retry on Windows renames again, unhindered) return real(src, dst) monkeypatch.setattr(os, "replace", replace) env, errors = _env(tmp_path), [] diff --git a/tokeneconomizer/plugin/paths.py b/tokeneconomizer/plugin/paths.py index 019c474e..2c2774f6 100644 --- a/tokeneconomizer/plugin/paths.py +++ b/tokeneconomizer/plugin/paths.py @@ -108,11 +108,17 @@ def ensure_launcher(env=None): tmp = "%s.%d.%d.tmp" % (launcher, os.getpid(), threading.get_ident()) # newline="\n": text mode on Windows would end each line with CRLF, and `sh` would pass # the trailing "\r" on as an argument. - with open(tmp, "w", encoding="utf-8", newline="\n") as fh: - fh.write(body) - os.chmod(tmp, 0o700) - # Windows refuses to replace a file another thread is reading or replacing. - _replace(tmp, launcher) + try: + with open(tmp, "w", encoding="utf-8", newline="\n") as fh: + fh.write(body) + os.chmod(tmp, 0o700) + # Windows refuses to replace a file another thread is reading or replacing. + _replace(tmp, launcher) + finally: + try: + os.unlink(tmp) + except FileNotFoundError: + pass return path From 1a31e2e6324ced7ab7af85f7ab499087fc26a2dc Mon Sep 17 00:00:00 2001 From: Saksham Uboweja <76595406+SakshamUboweja@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:16:02 +0000 Subject: [PATCH 4/5] TEMP: proof job also measures main + retry only, 100 runs of the CI test --- .github/workflows/launcher-race-proof.yml | 15 ++++++++------- .proof/stress.py | 4 ++++ 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/.github/workflows/launcher-race-proof.yml b/.github/workflows/launcher-race-proof.yml index acbf3df4..8713582d 100644 --- a/.github/workflows/launcher-race-proof.yml +++ b/.github/workflows/launcher-race-proof.yml @@ -30,18 +30,19 @@ jobs: - name: "stress: 4 threads write the launcher at once, 300 times" run: | python -I .proof/stress.py ../old 300 "before (main)" || true - python -I .proof/stress.py "$PWD" 300 "after, unique name only" noretry + python -I .proof/stress.py ../old 300 "main + retry only" retryonly || true + python -I .proof/stress.py "$PWD" 300 "after, unique name only" noretry || true python -I .proof/stress.py "$PWD" 300 "after (the fix)" - - name: "the CI test, 40 times, on main's code" + - name: "the CI test, 100 times, on main's code" run: | cp -r tokeneconomizer ../new rm -rf tokeneconomizer && cp -r ../old/tokeneconomizer tokeneconomizer - f=0; for i in $(seq 40); do python -m pytest -q -p no:cacheprovider "tests/test_hermes_plugin.py::test_gateway_and_cron_sessions_in_two_repositories_fold_apart_through_the_real_dispatcher" >/dev/null 2>&1 || f=$((f+1)); done - echo "before (main): $f/40 failed" + f=0; for i in $(seq 100); do python -m pytest -q -p no:cacheprovider "tests/test_hermes_plugin.py::test_gateway_and_cron_sessions_in_two_repositories_fold_apart_through_the_real_dispatcher" >/dev/null 2>&1 || f=$((f+1)); done + echo "before (main): $f/100 failed" rm -rf tokeneconomizer && cp -r ../new tokeneconomizer - - name: "the CI test, 40 times, with the fix" + - name: "the CI test, 100 times, with the fix" run: | - f=0; for i in $(seq 40); do python -m pytest -q -p no:cacheprovider "tests/test_hermes_plugin.py::test_gateway_and_cron_sessions_in_two_repositories_fold_apart_through_the_real_dispatcher" >/dev/null 2>&1 || f=$((f+1)); done - echo "after (the fix): $f/40 failed"; test "$f" = 0 + f=0; for i in $(seq 100); do python -m pytest -q -p no:cacheprovider "tests/test_hermes_plugin.py::test_gateway_and_cron_sessions_in_two_repositories_fold_apart_through_the_real_dispatcher" >/dev/null 2>&1 || f=$((f+1)); done + echo "after (the fix): $f/100 failed"; test "$f" = 0 - name: new regression test and launcher tests run: python -m pytest -q -p no:cacheprovider tests/test_windows_launcher.py tests/test_hermes_plugin.py diff --git a/.proof/stress.py b/.proof/stress.py index 4bd2de1b..69c5ee91 100644 --- a/.proof/stress.py +++ b/.proof/stress.py @@ -5,6 +5,10 @@ if len(sys.argv) > 4 and sys.argv[4] == "noretry": from tokeneconomizer.plugin import store store._replace = os.replace # the unique name alone, without the Windows retry +if len(sys.argv) > 4 and sys.argv[4] == "retryonly": + from tokeneconomizer.plugin import store + _real = os.replace + os.replace = lambda s, d: store._retrying(lambda: _real(s, d)) # main + a retry, nothing else if len(sys.argv) > 4 and sys.argv[4] == "windows": paths._WINDOWS = True plugin = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "plugin") From 424096f8a9568b4728bcf1a6b4c0c4127e30c4ce Mon Sep 17 00:00:00 2001 From: Saksham Uboweja <76595406+SakshamUboweja@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:31:31 +0000 Subject: [PATCH 5/5] Remove the temporary proof job --- .github/workflows/launcher-race-proof.yml | 48 ----------------------- .proof/stress.py | 26 ------------ 2 files changed, 74 deletions(-) delete mode 100644 .github/workflows/launcher-race-proof.yml delete mode 100644 .proof/stress.py diff --git a/.github/workflows/launcher-race-proof.yml b/.github/workflows/launcher-race-proof.yml deleted file mode 100644 index 8713582d..00000000 --- a/.github/workflows/launcher-race-proof.yml +++ /dev/null @@ -1,48 +0,0 @@ -# Temporary: proves the launcher race fix on Windows. Removed before any PR. -name: launcher-race-proof -on: - push: - branches: [fix/launcher-thread-race] -permissions: - contents: read -jobs: - proof: - strategy: - fail-fast: false - matrix: - os: [windows-latest, ubuntu-latest] - python: ["3.10", "3.13"] - runs-on: ${{ matrix.os }} - timeout-minutes: 30 - defaults: - run: - shell: bash - steps: - - uses: actions/checkout@v5 - with: - fetch-depth: 0 - - uses: actions/setup-python@v6 - with: - python-version: ${{ matrix.python }} - - run: python -m pip install pytest - - name: old code from main - run: mkdir -p ../old && git archive d660b3e tokeneconomizer | tar -x -C ../old - - name: "stress: 4 threads write the launcher at once, 300 times" - run: | - python -I .proof/stress.py ../old 300 "before (main)" || true - python -I .proof/stress.py ../old 300 "main + retry only" retryonly || true - python -I .proof/stress.py "$PWD" 300 "after, unique name only" noretry || true - python -I .proof/stress.py "$PWD" 300 "after (the fix)" - - name: "the CI test, 100 times, on main's code" - run: | - cp -r tokeneconomizer ../new - rm -rf tokeneconomizer && cp -r ../old/tokeneconomizer tokeneconomizer - f=0; for i in $(seq 100); do python -m pytest -q -p no:cacheprovider "tests/test_hermes_plugin.py::test_gateway_and_cron_sessions_in_two_repositories_fold_apart_through_the_real_dispatcher" >/dev/null 2>&1 || f=$((f+1)); done - echo "before (main): $f/100 failed" - rm -rf tokeneconomizer && cp -r ../new tokeneconomizer - - name: "the CI test, 100 times, with the fix" - run: | - f=0; for i in $(seq 100); do python -m pytest -q -p no:cacheprovider "tests/test_hermes_plugin.py::test_gateway_and_cron_sessions_in_two_repositories_fold_apart_through_the_real_dispatcher" >/dev/null 2>&1 || f=$((f+1)); done - echo "after (the fix): $f/100 failed"; test "$f" = 0 - - name: new regression test and launcher tests - run: python -m pytest -q -p no:cacheprovider tests/test_windows_launcher.py tests/test_hermes_plugin.py diff --git a/.proof/stress.py b/.proof/stress.py deleted file mode 100644 index 69c5ee91..00000000 --- a/.proof/stress.py +++ /dev/null @@ -1,26 +0,0 @@ -"""Run ensure_launcher from 4 threads at once, as a Hermes gateway does, N times; count errors.""" -import collections, os, sys, tempfile, threading -sys.path.insert(0, sys.argv[1]) -from tokeneconomizer.plugin import paths -if len(sys.argv) > 4 and sys.argv[4] == "noretry": - from tokeneconomizer.plugin import store - store._replace = os.replace # the unique name alone, without the Windows retry -if len(sys.argv) > 4 and sys.argv[4] == "retryonly": - from tokeneconomizer.plugin import store - _real = os.replace - os.replace = lambda s, d: store._retrying(lambda: _real(s, d)) # main + a retry, nothing else -if len(sys.argv) > 4 and sys.argv[4] == "windows": - paths._WINDOWS = True -plugin = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "plugin") -runs, fails, bad = int(sys.argv[2]), collections.Counter(), 0 -for _ in range(runs): - env = {"TE_PLUGIN_ROOT": os.path.abspath(plugin), "TOKENECONOMIZER_HOME": tempfile.mkdtemp()} - go, errs = threading.Barrier(4), [] - def w(): - go.wait() - try: paths.ensure_launcher(env) - except OSError as e: errs.append(type(e).__name__) - ts = [threading.Thread(target=w) for _ in range(4)] - [t.start() for t in ts]; [t.join() for t in ts] - bad += bool(errs); fails.update(errs) -print(f"{sys.argv[3]}: {bad}/{runs} runs had an error {dict(fails)}")