From 8d0c2788642b1194ca3f31b3eb5d32a0a0f83cf9 Mon Sep 17 00:00:00 2001 From: kirigayakazima <46666711+kirigayakazima@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:20:45 +0800 Subject: [PATCH 1/2] REPLACE-RETRY-LOCK-VIOLATION-AND-SECONDS-VALIDATION --- tests/test_replace_retry_bounds.py | 98 ++++++++++++++++++++++++++++++ tools/replace_retry.py | 10 ++- 2 files changed, 105 insertions(+), 3 deletions(-) create mode 100644 tests/test_replace_retry_bounds.py diff --git a/tests/test_replace_retry_bounds.py b/tests/test_replace_retry_bounds.py new file mode 100644 index 0000000000..59c20f3887 --- /dev/null +++ b/tests/test_replace_retry_bounds.py @@ -0,0 +1,98 @@ +"""Tests for ERROR_LOCK_VIOLATION retry and seconds validation in tools/replace_retry.py.""" +import errno +import os +import sys +import tempfile +import unittest +from unittest import mock + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(ROOT, "tools")) + +import replace_retry # noqa: E402 + + +def _win_perm_error(winerror): + err = PermissionError(errno.EACCES, f"mock transient error {winerror}") + err.winerror = winerror + return err + + +class ReplaceRetryBoundsTests(unittest.TestCase): + def test_retries_lock_violation_winerror_33(self): + with tempfile.TemporaryDirectory() as tmp: + src = os.path.join(tmp, "src.tmp") + dst = os.path.join(tmp, "dst.txt") + with open(src, "w", encoding="utf-8", newline="\n") as f: + f.write("updated") + with open(dst, "w", encoding="utf-8", newline="\n") as f: + f.write("original") + + real_replace = os.replace + calls = [] + + def fake_replace(s, d): + calls.append((s, d)) + if len(calls) <= 2: + raise _win_perm_error(33) + return real_replace(s, d) + + with mock.patch.object(replace_retry.os, "replace", fake_replace), \ + mock.patch.object(replace_retry.time, "sleep") as sleep_mock: + replace_retry.replace(src, dst) + + self.assertEqual(len(calls), 3) + self.assertEqual(sleep_mock.call_count, 2) + with open(dst, encoding="utf-8") as f: + self.assertEqual(f.read(), "updated") + + def test_rejects_invalid_seconds_before_calling_replace(self): + invalid_values = ( + float("nan"), + float("inf"), + float("-inf"), + -0.5, + True, + False, + "1", + ) + for bad in invalid_values: + with self.subTest(seconds=bad): + calls = [] + + def guarded_replace(s, d): + calls.append((s, d)) + if len(calls) > 1: + raise AssertionError("replace loop did not terminate") + return None + + with mock.patch.object(replace_retry.os, "replace", guarded_replace), \ + mock.patch.object(replace_retry.time, "sleep") as sleep_mock: + with self.assertRaises(ValueError): + replace_retry.replace("a", "b", seconds=bad) + + self.assertEqual(calls, []) + sleep_mock.assert_not_called() + + def test_zero_seconds_attempts_once_without_sleeping(self): + calls = [] + err = _win_perm_error(32) + + def fail_once(s, d): + calls.append((s, d)) + if len(calls) > 1: + raise AssertionError("seconds=0 must attempt os.replace at most once") + raise err + + with mock.patch.object(replace_retry.os, "replace", fail_once), \ + mock.patch.object(replace_retry.time, "sleep") as sleep_mock: + with self.assertRaises(PermissionError) as caught: + replace_retry.replace("a", "b", seconds=0) + + self.assertIs(caught.exception, err) + self.assertEqual(len(calls), 1) + sleep_mock.assert_not_called() + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/replace_retry.py b/tools/replace_retry.py index 0dd54cd3a3..36625673fe 100644 --- a/tools/replace_retry.py +++ b/tools/replace_retry.py @@ -1,17 +1,18 @@ """os.replace() that rides out the short windows in which Windows refuses to rename a file it has just seen written. -On Windows, os.replace raises PermissionError (winerror 5 or 32) while another process holds the source or the +On Windows, os.replace raises PermissionError (winerror 5, 32, or 33) while another process holds the source or the destination open without share-delete: a virus scanner, the search indexer, a cloud-sync client on Documents. The hold lasts milliseconds to a few seconds, so the rename is tried again for a bounded time and only then re-raised. Elsewhere, and for every other error, this is os.replace. """ +import math import os import time RETRY_SECONDS = 5.0 FIRST_DELAY = 0.01 MAX_DELAY = 0.25 -_TRANSIENT_WINERRORS = (5, 32) # ERROR_ACCESS_DENIED, ERROR_SHARING_VIOLATION +_TRANSIENT_WINERRORS = (5, 32, 33) # ERROR_ACCESS_DENIED, ERROR_SHARING_VIOLATION, ERROR_LOCK_VIOLATION def _transient(error): @@ -21,7 +22,10 @@ def _transient(error): def replace(src, dst, *, seconds=None): """os.replace(src, dst), retried with a doubling delay for `seconds` (default RETRY_SECONDS) on a transient Windows PermissionError; the last error is raised once the time is up.""" - deadline = time.monotonic() + (RETRY_SECONDS if seconds is None else seconds) + budget = RETRY_SECONDS if seconds is None else seconds + if isinstance(budget, bool) or not isinstance(budget, (int, float)) or not math.isfinite(budget) or budget < 0: + raise ValueError(f"seconds must be a finite non-negative number, got {seconds!r}") + deadline = time.monotonic() + budget delay = FIRST_DELAY while True: try: From f478f4c6b88000fb6bb6b6021f4a0d3d7eb579c0 Mon Sep 17 00:00:00 2001 From: kirigayakazima <46666711+kirigayakazima@users.noreply.github.com> Date: Fri, 27 Nov 2026 20:01:37 +0800 Subject: [PATCH 2/2] replace_retry: convert math.isfinite OverflowError to ValueError --- tests/test_replace_retry_bounds.py | 2 ++ tools/replace_retry.py | 8 +++++++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/tests/test_replace_retry_bounds.py b/tests/test_replace_retry_bounds.py index 59c20f3887..41c3e1078b 100644 --- a/tests/test_replace_retry_bounds.py +++ b/tests/test_replace_retry_bounds.py @@ -52,6 +52,8 @@ def test_rejects_invalid_seconds_before_calling_replace(self): float("inf"), float("-inf"), -0.5, + 10**1000, + -10**1000, True, False, "1", diff --git a/tools/replace_retry.py b/tools/replace_retry.py index 36625673fe..94db78ec35 100644 --- a/tools/replace_retry.py +++ b/tools/replace_retry.py @@ -23,7 +23,13 @@ def replace(src, dst, *, seconds=None): """os.replace(src, dst), retried with a doubling delay for `seconds` (default RETRY_SECONDS) on a transient Windows PermissionError; the last error is raised once the time is up.""" budget = RETRY_SECONDS if seconds is None else seconds - if isinstance(budget, bool) or not isinstance(budget, (int, float)) or not math.isfinite(budget) or budget < 0: + if isinstance(budget, bool) or not isinstance(budget, (int, float)): + raise ValueError(f"seconds must be a finite non-negative number, got {seconds!r}") + try: + finite = math.isfinite(budget) + except OverflowError: + finite = False + if not finite or budget < 0: raise ValueError(f"seconds must be a finite non-negative number, got {seconds!r}") deadline = time.monotonic() + budget delay = FIRST_DELAY