Skip to content

The agent that grows with you

fix(browser): the Windows holder lock retries only contention, for at most 30 s

Tekniumf518c50a61f3
diff --git a/tests/tools/test_browser_launcher_holders_lock.py b/tests/tools/test_browser_launcher_holders_lock.py
new file mode 100644
index 00000000000..633335f6f74
--- /dev/null
+++ b/tests/tools/test_browser_launcher_holders_lock.py
@@ -0,0 +1,47 @@
+"""The Windows holder lock (``tools/browser_launcher_holders.records_lock``) retries only lock contention, and only
+for a bounded time: a lock leaked by a hung process fails the caller with a clear error instead of hanging it,
+and any other ``msvcrt`` error surfaces at once."""
+
+from __future__ import annotations
+
+import errno
+import os
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+from tools import browser_launcher_holders as holders
+
+
[email protected]("code", sorted({errno.EACCES, errno.EDEADLK, getattr(errno, "EDEADLOCK", errno.EDEADLK)}))
+def test_contention_is_retried_until_the_deadline_then_fails_naming_the_dir(code, tmp_path):
+ busy = OSError(code, "locked by another process")
+ assert holders.nt_lock_failure(busy, tmp_path, expired=False) is None
+ failure = holders.nt_lock_failure(busy, tmp_path, expired=True)
+ assert isinstance(failure, TimeoutError) and str(tmp_path) in str(failure)
+
+
[email protected]("code", [errno.EBADF, errno.EINVAL, errno.EIO])
+def test_any_other_lock_error_is_raised_at_once(code, tmp_path):
+ broken = OSError(code, "not a contention")
+ assert holders.nt_lock_failure(broken, tmp_path, expired=False) is broken
+
+
+def test_a_lock_held_by_a_hung_process_times_out(tmp_path, monkeypatch):
+ holder = subprocess.Popen(
+ [sys.executable, "-c", "import msvcrt, os, sys\n"
+ "fd = os.open(sys.argv[1], os.O_RDWR | os.O_CREAT, 0o600)\n"
+ "msvcrt.locking(fd, msvcrt.LK_LOCK, 1)\nprint('held', flush=True)\nsys.stdin.readline()\n",
+ str(Path(tmp_path, holders._LOCK_NAME))],
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
+ try:
+ assert holder.stdout.readline().strip() == "held"
+ monkeypatch.setattr(holders, "_NT_LOCK_TIMEOUT_S", 0.0)
+ with pytest.raises(TimeoutError), holders.records_lock(tmp_path):
+ pass
+ finally:
+ holder.communicate("\n", timeout=30)
+ assert os.path.exists(tmp_path / holders._LOCK_NAME)
diff --git a/tools/browser_launcher_holders.py b/tools/browser_launcher_holders.py
index 4f8844d7537..be91540c203 100644
--- a/tools/browser_launcher_holders.py
+++ b/tools/browser_launcher_holders.py
@@ -14,9 +14,11 @@ missed. Siblings late-import the facade (its ``_pid_alive`` / ``_start_time`` ar
from __future__ import annotations
import contextlib
+import errno
import json
import logging
import os
+import time
from pathlib import Path
from typing import Iterator, Optional
@@ -25,6 +27,37 @@ logger = logging.getLogger(__name__)
_LOCK_NAME = ".holders.lock"
+# msvcrt.locking reports a lock another process holds as EDEADLOCK (LK_LOCK, after its own ~10 s of retries)
+# or EACCES (LK_NBLCK); anything else is a real error.
+_NT_LOCK_CONTENDED = frozenset({errno.EACCES, errno.EDEADLK, getattr(errno, "EDEADLOCK", errno.EDEADLK)})
+_NT_LOCK_TIMEOUT_S = 30.0
+
+
+def nt_lock_failure(exc: OSError, records: Path, expired: bool) -> Optional[OSError]:
+ """What a failed ``msvcrt.locking`` attempt means: None to retry (the lock is held and time is left), else
+ the error to raise. Bounded, so a lock leaked by a hung process fails the caller instead of hanging it."""
+ if exc.errno not in _NT_LOCK_CONTENDED:
+ return exc
+ if expired:
+ return TimeoutError(f"browser launcher state {records} stayed locked for {_NT_LOCK_TIMEOUT_S:.0f} s")
+ return None
+
+
+def _lock_nt(fd: int, records: Path) -> None:
+ import msvcrt
+ deadline = time.monotonic() + _NT_LOCK_TIMEOUT_S
+ while True:
+ try:
+ msvcrt.locking(fd, msvcrt.LK_LOCK, 1)
+ return
+ except OSError as exc:
+ failure = nt_lock_failure(exc, records, time.monotonic() >= deadline)
+ if failure is exc:
+ raise
+ if failure is not None:
+ raise failure from exc
+
+
@contextlib.contextmanager
def records_lock(records: Path) -> Iterator[None]:
"""Exclusive, cross-process lock on ``records`` (the profile's private launcher state dir). Never nested:
@@ -33,13 +66,7 @@ def records_lock(records: Path) -> Iterator[None]:
fd = os.open(records / _LOCK_NAME, flags, 0o600)
try:
if os.name == "nt":
- import msvcrt
- while True:
- try:
- msvcrt.locking(fd, msvcrt.LK_LOCK, 1) # retries for ~10 s, then raises
- break
- except OSError:
- continue
+ _lock_nt(fd, records)
else:
import fcntl # windows-footgun: ok — the nt branch above
fcntl.flock(fd, fcntl.LOCK_EX)