From bd69e27e8883b91da4d34c4410958674ce490885 Mon Sep 17 00:00:00 2001 From: "congvc-bot[bot]" <3634010+congvc-bot[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:48:25 +0700 Subject: [PATCH 1/4] test(device-lock): red probes for whole-record publication (CHE-10242) --- .../admin_console/test_host_nack_races.py | 8 +- tests/unit/runtime/test_device_lock.py | 122 ++++++++++++++++++ 2 files changed, 128 insertions(+), 2 deletions(-) diff --git a/tests/unit/admin_console/test_host_nack_races.py b/tests/unit/admin_console/test_host_nack_races.py index 7b2deb7d6..de91bc0bb 100644 --- a/tests/unit/admin_console/test_host_nack_races.py +++ b/tests/unit/admin_console/test_host_nack_races.py @@ -371,12 +371,16 @@ def acquire(): thread.start() assert lease_created.wait(5) old_time = time.time() - DeviceExecutionLock._MALFORMED_LOCK_GRACE_SECONDS - 1 - os.utime(lock.path, (old_time, old_time)) + pending = list(lock.path.parent.glob(f"{lock.path.name}.*.tmp")) + assert pending + assert not lock.path.exists() + for record in pending: + os.utime(record, (old_time, old_time)) kills_while_locked = [] worker.kill.side_effect = lambda: kills_while_locked.append(lock._acquired) try: first_decision = await TaskQueueService.requeue_starting("r1") - file_kept_after_refusal = lock.path.exists() + file_kept_after_refusal = all(record.exists() for record in pending) allow_write.set() assert acquired.wait(5) assert lock._acquired diff --git a/tests/unit/runtime/test_device_lock.py b/tests/unit/runtime/test_device_lock.py index 87b5b0fba..91310ba15 100644 --- a/tests/unit/runtime/test_device_lock.py +++ b/tests/unit/runtime/test_device_lock.py @@ -733,3 +733,125 @@ def test_managed_avd_does_not_retry_occupied_device( broker_rpc.assert_called_once() readback.assert_not_called() sleep.assert_not_called() + + +# -- CHE-10242: records are published whole, so a paused writer keeps its place -- + + +def _age_publications(folder, prefix, seconds): + old = time.time() - seconds + for path in folder.iterdir(): + if path.name.startswith(prefix): + os.utime(path, (old, old)) + + +def _pausing_write(monkeypatch, marker): + """Block os.write for a payload holding ``marker``; return (entered, release).""" + entered, release = threading.Event(), threading.Event() + real_write = os.write + + def write(descriptor, payload): + if marker in payload: + entered.set() + assert release.wait(5) + return real_write(descriptor, payload) + + monkeypatch.setattr(os, "write", write) + return entered, release + + +def test_a_paused_writer_never_yields_two_owners(tmp_path, monkeypatch): + first = DeviceExecutionLock("emulator-5554", "first", session_id="s-first") + second = DeviceExecutionLock("emulator-5554", "second", session_id="s-second") + entered, release = _pausing_write(monkeypatch, first.token.encode()) + thread = threading.Thread(target=first._try_acquire_owner_lock_unguarded) + thread.start() + try: + assert entered.wait(5) + _age_publications( + tmp_path, first.path.name, DeviceExecutionLock._MALFORMED_LOCK_GRACE_SECONDS + 1 + ) + for _ in range(3): + if second._try_acquire_owner_lock_unguarded(): + break + finally: + release.set() + thread.join(5) + assert not thread.is_alive() + assert [first._acquired, second._acquired].count(True) == 1 + winner = first if first._acquired else second + assert json.loads(first.path.read_text())["token"] == winner.token + winner.release() + + +def test_a_paused_ticket_keeps_its_place(tmp_path, monkeypatch): + entered, release = _pausing_write(monkeypatch, b"paused-ticket") + tokens = [] + thread = threading.Thread( + target=lambda: tokens.append( + DeviceExecutionLock.reserve("probe", "d1", session_id="paused-ticket") + ) + ) + thread.start() + try: + assert entered.wait(5) + queue = tmp_path / "artemis-global-device.queue" + _age_publications(queue, "", DeviceExecutionLock._MALFORMED_LOCK_GRACE_SECONDS + 1) + DeviceExecutionLock.cleanup_stale_locks() + finally: + release.set() + thread.join(5) + assert not thread.is_alive() + (ticket,) = queue.glob("*.wait") + assert ticket.name == f"{ticket.name[:20]}-{tokens[0]}.wait" + assert ticket.name[:20].isdigit() + DeviceExecutionLock.cancel_reservation(tokens[0]) + + +def test_reentrant_acquire_by_the_same_token_still_succeeds(): + lock = DeviceExecutionLock("emulator-5554", "again") + assert lock._try_acquire_owner_lock_unguarded() + try: + assert lock._try_acquire_owner_lock_unguarded() + finally: + lock.release() + + +def test_hard_link_failure_falls_back_and_warns_once(monkeypatch, caplog): + def no_link(*_args, **_kwargs): + raise PermissionError("no hard links here") + + monkeypatch.setattr(os, "link", no_link) + monkeypatch.setattr(DeviceExecutionLock, "_link_warned", False) + with caplog.at_level("WARNING", logger="artemis.runtime.device_lock"): + for device in ("emulator-5554", "emulator-5556"): + lock = DeviceExecutionLock(device, "fallback") + assert lock._try_acquire_owner_lock_unguarded() + assert json.loads(lock.path.read_text())["token"] == lock.token + lock.release() + assert len([r for r in caplog.records if r.levelname == "WARNING"]) == 1 + + +def test_cleanup_removes_only_old_publication_temp_files(tmp_path): + queue = tmp_path / "artemis-global-device.queue" + queue.mkdir() + live = DeviceExecutionLock("emulator-5554", "live") + live.acquire() + ticket = DeviceExecutionLock.reserve("queued", "emulator-5556") + old_temp = tmp_path / "artemis-device-x.lock.aaaa.tmp" + old_queue_temp = queue / "0001-t.wait.bbbb.tmp" + fresh_temp = tmp_path / "artemis-device-y.lock.cccc.tmp" + for path in (old_temp, old_queue_temp, fresh_temp): + path.write_text("{}") + for path in (old_temp, old_queue_temp): + os.utime(path, (time.time() - 61, time.time() - 61)) + try: + DeviceExecutionLock.cleanup_stale_locks() + assert not old_temp.exists() + assert not old_queue_temp.exists() + assert fresh_temp.exists() + assert live.path.exists() + assert list(queue.glob(f"*-{ticket}.wait")) + finally: + live.release() + DeviceExecutionLock.cancel_reservation(ticket) From d1bf3d1c24c951c7d3631aa054441eae702202f0 Mon Sep 17 00:00:00 2001 From: "congvc-bot[bot]" <3634010+congvc-bot[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:54:18 +0700 Subject: [PATCH 2/4] fix(device-lock): publish lock and ticket records whole (CHE-10242) --- artemis/runtime/device_lock.py | 71 ++++++++++++++++++++++++++-------- 1 file changed, 55 insertions(+), 16 deletions(-) diff --git a/artemis/runtime/device_lock.py b/artemis/runtime/device_lock.py index b57f89b4d..7d2c2ca59 100644 --- a/artemis/runtime/device_lock.py +++ b/artemis/runtime/device_lock.py @@ -21,6 +21,7 @@ from dataclasses import dataclass from datetime import UTC, datetime import json +import logging import os from pathlib import Path import re @@ -32,6 +33,8 @@ from artemis.config.paths import get_temp_dir from artemis.runtime.process_probe import pid_is_alive +logger = logging.getLogger(__name__) + LEASE_HANDOFF_ENV = "ARTEMIS_DEVICE_LEASE_HANDOFF" MANAGED_AVD_ADMISSION_TIMEOUT_SECONDS = 2.0 @@ -90,6 +93,8 @@ class DeviceExecutionLock: """ _MALFORMED_LOCK_GRACE_SECONDS = 5.0 + _PUBLICATION_TEMP_MAX_AGE_SECONDS = 60.0 + _link_warned = False # one hard-link fallback warning per process _DEFAULT_POLL_INTERVAL_SECONDS = 0.1 QUEUE_TICKET_ENV = "ARTEMIS_DEVICE_QUEUE_TICKET" # CHE-5297: path of the DLP-1 broker's shared claim guard (flock), when composed. @@ -292,6 +297,45 @@ def _atomic_write_json(cls, path: Path, payload: dict) -> bool: cls._safe_unlink(temp_path) return True + @classmethod + def _publish_exclusive(cls, path: Path, payload: dict) -> bool: + """Create ``path`` with its whole record, or return False if it exists. + + The record is written to a temp file first and hard-linked into place, so + no reader (or stale-record reaper) ever sees an empty ``path``. No fsync: + the record only has to be whole for readers on this machine. + """ + data = json.dumps(payload, ensure_ascii=False).encode("utf-8") + temp_path = path.with_name(f"{path.name}.{uuid.uuid4().hex}.tmp") + fd = os.open(temp_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) + try: + try: + os.write(fd, data) + finally: + os.close(fd) + try: + os.link(temp_path, path) + except FileExistsError: + return False + except OSError: + if not DeviceExecutionLock._link_warned: + DeviceExecutionLock._link_warned = True + logger.warning( + "Hard links unavailable in %s; publishing lock records non-atomically", + path.parent, + ) + try: + fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY) + except FileExistsError: + return False + try: + os.write(fd, data) + finally: + os.close(fd) + return True + finally: + cls._safe_unlink(temp_path) + @classmethod def _ticket_targets_device( cls, @@ -416,15 +460,7 @@ def reserve( ) for _ in range(8): path = queue_dir / f"{time.time_ns():020d}-{token}.wait" - try: - fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY) - except FileExistsError: - continue - else: - try: - os.write(fd, json.dumps(payload, ensure_ascii=False).encode("utf-8")) - finally: - os.close(fd) + if cls._publish_exclusive(path, payload): return token raise DeviceBusyError("Could not reserve a position in the Artemis device queue.") @@ -722,9 +758,7 @@ def _try_acquire_owner_lock_unguarded(self) -> bool: ) if self._webusb_claim_alias is not None: owner_payload["webusb_claim_alias"] = self._webusb_claim_alias - try: - fd = os.open(self.path, os.O_CREAT | os.O_EXCL | os.O_WRONLY) - except FileExistsError: + if not self._publish_exclusive(self.path, owner_payload): current_owner = self._read_owner(self.path) if ( current_owner is not None @@ -738,10 +772,6 @@ def _try_acquire_owner_lock_unguarded(self) -> bool: return True self._remove_stale_lock() return False - try: - os.write(fd, json.dumps(owner_payload, ensure_ascii=False).encode("utf-8")) - finally: - os.close(fd) self._acquired = True return True @@ -1224,4 +1254,13 @@ def cleanup_stale_locks(cls, device_id: str | None = None) -> int: continue if cls._safe_unlink(path): removed += 1 + + # Temp records of a writer that died before linking them into place. + for folder in [lock_dir, *(d for d in lock_dir.glob("*.queue") if d.is_dir())]: + for path in folder.glob("*.tmp"): + try: + if time.time() - path.stat().st_mtime > cls._PUBLICATION_TEMP_MAX_AGE_SECONDS: + cls._safe_unlink(path) + except OSError: + continue return removed From 403acfc0d4caa719c5f96454563b51705136b935 Mon Sep 17 00:00:00 2001 From: "congvc-bot[bot]" <3634010+congvc-bot[bot]@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:47:59 +0700 Subject: [PATCH 3/4] fix(device-lock): complete short writes before publishing a record (CHE-10242) --- artemis/runtime/device_lock.py | 16 ++++++++++++++-- tests/unit/runtime/test_device_lock.py | 24 ++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/artemis/runtime/device_lock.py b/artemis/runtime/device_lock.py index 7d2c2ca59..7a954c99e 100644 --- a/artemis/runtime/device_lock.py +++ b/artemis/runtime/device_lock.py @@ -297,6 +297,15 @@ def _atomic_write_json(cls, path: Path, payload: dict) -> bool: cls._safe_unlink(temp_path) return True + @staticmethod + def _write_all(fd: int, data: bytes) -> None: + """Write all of ``data`` or raise; ``os.write`` may write fewer bytes.""" + while data: + written = os.write(fd, data) + if written <= 0: + raise OSError("short write while publishing lock record") + data = data[written:] + @classmethod def _publish_exclusive(cls, path: Path, payload: dict) -> bool: """Create ``path`` with its whole record, or return False if it exists. @@ -310,7 +319,7 @@ def _publish_exclusive(cls, path: Path, payload: dict) -> bool: fd = os.open(temp_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) try: try: - os.write(fd, data) + cls._write_all(fd, data) finally: os.close(fd) try: @@ -329,7 +338,10 @@ def _publish_exclusive(cls, path: Path, payload: dict) -> bool: except FileExistsError: return False try: - os.write(fd, data) + cls._write_all(fd, data) + except BaseException: + cls._safe_unlink(path) + raise finally: os.close(fd) return True diff --git a/tests/unit/runtime/test_device_lock.py b/tests/unit/runtime/test_device_lock.py index 91310ba15..bf89dd997 100644 --- a/tests/unit/runtime/test_device_lock.py +++ b/tests/unit/runtime/test_device_lock.py @@ -832,6 +832,30 @@ def no_link(*_args, **_kwargs): assert len([r for r in caplog.records if r.levelname == "WARNING"]) == 1 +def test_short_writes_are_completed_before_publication(monkeypatch): + real_write = os.write + monkeypatch.setattr(os, "write", lambda fd, data: real_write(fd, bytes(data)[:1])) + lock = DeviceExecutionLock("emulator-5554", "short-write") + assert lock._try_acquire_owner_lock_unguarded() + assert json.loads(lock.path.read_text())["token"] == lock.token + lock.release() + + +def test_a_failed_write_publishes_nothing(tmp_path, monkeypatch): + real_write = os.write + + def write_one_then_fail(fd, data): + if len(data) > 1: + return real_write(fd, bytes(data)[:1]) + return 0 + + monkeypatch.setattr(os, "write", write_one_then_fail) + target = tmp_path / "record.lock" + with pytest.raises(OSError): + DeviceExecutionLock._publish_exclusive(target, {"token": "x"}) + assert list(tmp_path.iterdir()) == [] + + def test_cleanup_removes_only_old_publication_temp_files(tmp_path): queue = tmp_path / "artemis-global-device.queue" queue.mkdir() From 1850fa384e04f744e882c5267a4c0e5eaf429405 Mon Sep 17 00:00:00 2001 From: "congvc-bot[bot]" <3634010+congvc-bot[bot]@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:38:19 +0700 Subject: [PATCH 4/4] fix(device-lock): drop broad BaseException handler to restore quality ratchet (CHE-10839) --- artemis/runtime/device_lock.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/artemis/runtime/device_lock.py b/artemis/runtime/device_lock.py index 7a954c99e..dba57b3aa 100644 --- a/artemis/runtime/device_lock.py +++ b/artemis/runtime/device_lock.py @@ -337,13 +337,14 @@ def _publish_exclusive(cls, path: Path, payload: dict) -> bool: fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY) except FileExistsError: return False + written = False try: cls._write_all(fd, data) - except BaseException: - cls._safe_unlink(path) - raise + written = True finally: os.close(fd) + if not written: + cls._safe_unlink(path) return True finally: cls._safe_unlink(temp_path)