diff options
| -rw-r--r-- | tests/test_calibrated_texture_extra.py | 119 | ||||
| -rw-r--r-- | tools/calibrated_texture.py | 39 |
2 files changed, 153 insertions, 5 deletions
diff --git a/tests/test_calibrated_texture_extra.py b/tests/test_calibrated_texture_extra.py index 3367895e8..d76eb1747 100644 --- a/tests/test_calibrated_texture_extra.py +++ b/tests/test_calibrated_texture_extra.py | |||
| @@ -2157,6 +2157,125 @@ class TestExportFileAndCli(unittest.TestCase): | |||
| 2157 | with self.assertRaises(json.JSONDecodeError): | 2157 | with self.assertRaises(json.JSONDecodeError): |
| 2158 | ct.export_file(pool, 0, self.root / "u.dds", None, False, bad_json) | 2158 | ct.export_file(pool, 0, self.root / "u.dds", None, False, bad_json) |
| 2159 | 2159 | ||
| 2160 | def test_export_file_posix_link_permission_error_fails_safely_and_cleans(self): | ||
| 2161 | pool = ttpf.Pool(str(self.pool_path)) | ||
| 2162 | self.addCleanup(pool.close) | ||
| 2163 | out = self.root / "link_perm.dds" | ||
| 2164 | orig_move = ct._move_no_clobber | ||
| 2165 | |||
| 2166 | # 1. When os.link fails with PermissionError, re-raises safely without clobbering or falling back to replace | ||
| 2167 | with _fake_native_context(), \ | ||
| 2168 | mock.patch.object(ct, "_move_no_clobber", lambda s, d: orig_move(s, d, is_nt=False)), \ | ||
| 2169 | mock.patch("os.link", side_effect=PermissionError(1, "Operation not permitted")): | ||
| 2170 | with self.assertRaises(PermissionError): | ||
| 2171 | ct.export_file(pool, 0, out, None, False, self.profile) | ||
| 2172 | self.assertFalse(out.exists()) | ||
| 2173 | # Tempfile must be unlinked; no leaked temporary files in directory | ||
| 2174 | self.assertEqual(sorted(p.name for p in self.root.iterdir()), ["pool.ttpf", "profile.json"]) | ||
| 2175 | |||
| 2176 | # 2. When os.link fails with PermissionError and destination already exists, preserves destination intact | ||
| 2177 | out.write_bytes(b"EXISTING_DATA") | ||
| 2178 | with _fake_native_context(), \ | ||
| 2179 | mock.patch.object(ct, "_move_no_clobber", lambda s, d: orig_move(s, d, is_nt=False)), \ | ||
| 2180 | mock.patch("os.link", side_effect=PermissionError(1, "Operation not permitted")): | ||
| 2181 | with self.assertRaises(PermissionError): | ||
| 2182 | ct.export_file(pool, 0, out, None, False, self.profile) | ||
| 2183 | self.assertEqual(out.read_bytes(), b"EXISTING_DATA") | ||
| 2184 | self.assertEqual(sorted(p.name for p in self.root.iterdir()), ["link_perm.dds", "pool.ttpf", "profile.json"]) | ||
| 2185 | |||
| 2186 | def test_export_file_concurrent_destination_creation_rejects_and_cleans(self): | ||
| 2187 | pool = ttpf.Pool(str(self.pool_path)) | ||
| 2188 | self.addCleanup(pool.close) | ||
| 2189 | out = self.root / "race.dds" | ||
| 2190 | self.assertFalse(out.exists()) | ||
| 2191 | |||
| 2192 | orig_dds = ct.LocalDecoder.dds | ||
| 2193 | |||
| 2194 | def race_dds(self_dec, index, mips): | ||
| 2195 | # Concurrent actor creates the file while decoding is finishing | ||
| 2196 | out.write_bytes(b"CONCURRENT_WINNER") | ||
| 2197 | return orig_dds(self_dec, index, mips) | ||
| 2198 | |||
| 2199 | with _fake_native_context(), mock.patch.object(ct.LocalDecoder, "dds", race_dds): | ||
| 2200 | with self.assertRaises(FileExistsError): | ||
| 2201 | ct.export_file(pool, 0, out, None, False, self.profile) | ||
| 2202 | |||
| 2203 | # Destination was not overwritten and temporary file was removed | ||
| 2204 | self.assertEqual(out.read_bytes(), b"CONCURRENT_WINNER") | ||
| 2205 | self.assertEqual(sorted(p.name for p in self.root.iterdir()), ["pool.ttpf", "profile.json", "race.dds"]) | ||
| 2206 | |||
| 2207 | def test_export_file_concurrent_destination_creation_rejects_and_cleans_posix(self): | ||
| 2208 | pool = ttpf.Pool(str(self.pool_path)) | ||
| 2209 | self.addCleanup(pool.close) | ||
| 2210 | out = self.root / "race_posix.dds" | ||
| 2211 | self.assertFalse(out.exists()) | ||
| 2212 | orig_move = ct._move_no_clobber | ||
| 2213 | orig_dds = ct.LocalDecoder.dds | ||
| 2214 | |||
| 2215 | def race_dds(self_dec, index, mips): | ||
| 2216 | # Concurrent actor creates the file while decoding is finishing | ||
| 2217 | out.write_bytes(b"CONCURRENT_POSIX_WINNER") | ||
| 2218 | return orig_dds(self_dec, index, mips) | ||
| 2219 | |||
| 2220 | with _fake_native_context(), \ | ||
| 2221 | mock.patch.object(ct, "_move_no_clobber", lambda s, d: orig_move(s, d, is_nt=False)), \ | ||
| 2222 | mock.patch.object(ct.LocalDecoder, "dds", race_dds): | ||
| 2223 | with self.assertRaises(FileExistsError): | ||
| 2224 | ct.export_file(pool, 0, out, None, False, self.profile) | ||
| 2225 | |||
| 2226 | # Destination was not overwritten and temporary file was removed | ||
| 2227 | self.assertEqual(out.read_bytes(), b"CONCURRENT_POSIX_WINNER") | ||
| 2228 | self.assertEqual(sorted(p.name for p in self.root.iterdir()), ["pool.ttpf", "profile.json", "race_posix.dds"]) | ||
| 2229 | |||
| 2230 | def test_export_file_replacement_failure_cleans_temporary_file(self): | ||
| 2231 | pool = ttpf.Pool(str(self.pool_path)) | ||
| 2232 | self.addCleanup(pool.close) | ||
| 2233 | out = self.root / "replace_fail.dds" | ||
| 2234 | |||
| 2235 | with _fake_native_context(), \ | ||
| 2236 | mock.patch("replace_retry.replace", side_effect=OSError("simulated I/O write failure")): | ||
| 2237 | with self.assertRaisesRegex(OSError, "simulated I/O write failure"): | ||
| 2238 | ct.export_file(pool, 0, out, None, True, self.profile) | ||
| 2239 | |||
| 2240 | # Ensure no temporary files survived the exception | ||
| 2241 | self.assertEqual(sorted(p.name for p in self.root.iterdir()), ["pool.ttpf", "profile.json"]) | ||
| 2242 | |||
| 2243 | def test_rename_no_clobber_transient_retry_and_non_transient_error(self): | ||
| 2244 | src = self.root / "test_src.tmp" | ||
| 2245 | dst = self.root / "test_dst.dds" | ||
| 2246 | src.write_bytes(b"NEW") | ||
| 2247 | |||
| 2248 | # 1. Transient sharing violation (WinError 32) retries and succeeds once released | ||
| 2249 | calls = [] | ||
| 2250 | real_rename = os.rename | ||
| 2251 | |||
| 2252 | def flaky_rename(s, d): | ||
| 2253 | calls.append((s, d)) | ||
| 2254 | if len(calls) <= 2: | ||
| 2255 | err = PermissionError(13, "sharing violation") | ||
| 2256 | err.winerror = 32 | ||
| 2257 | raise err | ||
| 2258 | return real_rename(s, d) | ||
| 2259 | |||
| 2260 | with mock.patch("os.rename", side_effect=flaky_rename), mock.patch("time.sleep"): | ||
| 2261 | ct._rename_no_clobber(src, dst) | ||
| 2262 | self.assertEqual(len(calls), 3) | ||
| 2263 | self.assertEqual(dst.read_bytes(), b"NEW") | ||
| 2264 | |||
| 2265 | # 2. Non-transient PermissionError (WinError 1314 - privilege not held) fails immediately without retry | ||
| 2266 | src2 = self.root / "test_src2.tmp" | ||
| 2267 | dst2 = self.root / "test_dst2.dds" | ||
| 2268 | src2.write_bytes(b"DATA") | ||
| 2269 | non_transient = PermissionError(13, "privilege not held") | ||
| 2270 | non_transient.winerror = 1314 | ||
| 2271 | |||
| 2272 | with mock.patch("os.rename", side_effect=non_transient) as rename_mock, mock.patch("time.sleep") as sleep_mock: | ||
| 2273 | with self.assertRaises(PermissionError) as ctx: | ||
| 2274 | ct._rename_no_clobber(src2, dst2) | ||
| 2275 | self.assertEqual(ctx.exception.winerror, 1314) | ||
| 2276 | self.assertEqual(rename_mock.call_count, 1) | ||
| 2277 | sleep_mock.assert_not_called() | ||
| 2278 | |||
| 2160 | def test_ttpf_mips_cli_calibration_paths(self): | 2279 | def test_ttpf_mips_cli_calibration_paths(self): |
| 2161 | out = self.root / "cli.dds" | 2280 | out = self.root / "cli.dds" |
| 2162 | 2281 | ||
diff --git a/tools/calibrated_texture.py b/tools/calibrated_texture.py index 1168fae03..7845e5d53 100644 --- a/tools/calibrated_texture.py +++ b/tools/calibrated_texture.py | |||
| @@ -8,6 +8,7 @@ import os | |||
| 8 | from pathlib import Path | 8 | from pathlib import Path |
| 9 | import sys | 9 | import sys |
| 10 | import tempfile | 10 | import tempfile |
| 11 | import time | ||
| 11 | import zlib | 12 | import zlib |
| 12 | 13 | ||
| 13 | # `python -I` implies `-P`, so the script's directory is not on sys.path; the sibling modules are next to it. | 14 | # `python -I` implies `-P`, so the script's directory is not on sys.path; the sibling modules are next to it. |
| @@ -16,6 +17,7 @@ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) | |||
| 16 | import numpy as np | 17 | import numpy as np |
| 17 | import bcpack | 18 | import bcpack |
| 18 | import bcpack_tables | 19 | import bcpack_tables |
| 20 | import replace_retry | ||
| 19 | import ttpf_mips as ttpf | 21 | import ttpf_mips as ttpf |
| 20 | 22 | ||
| 21 | 23 | ||
| @@ -420,6 +422,34 @@ def local_bc3(symbols, profile): | |||
| 420 | return np.column_stack((low, high)).astype("<u8").tobytes() | 422 | return np.column_stack((low, high)).astype("<u8").tobytes() |
| 421 | 423 | ||
| 422 | 424 | ||
| 425 | def _rename_no_clobber(src, dst, *, seconds=None): | ||
| 426 | """Atomically move src to dst on Windows without overwriting, retrying transient sharing locks.""" | ||
| 427 | deadline = time.monotonic() + (replace_retry.RETRY_SECONDS if seconds is None else seconds) | ||
| 428 | delay = replace_retry.FIRST_DELAY | ||
| 429 | while True: | ||
| 430 | try: | ||
| 431 | return os.rename(src, dst) | ||
| 432 | except PermissionError as e: | ||
| 433 | if not replace_retry._transient(e) or time.monotonic() >= deadline: | ||
| 434 | raise | ||
| 435 | time.sleep(min(delay, max(0.0, deadline - time.monotonic()))) | ||
| 436 | delay = min(delay * 2, replace_retry.MAX_DELAY) | ||
| 437 | |||
| 438 | |||
| 439 | def _move_no_clobber(src, dst, *, is_nt=None): | ||
| 440 | """Move src to dst without overwriting dst, raising FileExistsError if dst exists. | ||
| 441 | |||
| 442 | On Windows, os.rename wraps MoveFileExW without MOVEFILE_REPLACE_EXISTING, which is an atomic | ||
| 443 | kernel operation that raises FileExistsError ([WinError 183]) if dst exists. | ||
| 444 | On POSIX, os.link atomically creates a hard link and raises FileExistsError (EEXIST) if dst exists. | ||
| 445 | If os.link fails for reasons other than destination existence, fail safely by re-raising the | ||
| 446 | original exception without non-atomic fallbacks, strictly preventing TOCTOU clobbering. | ||
| 447 | """ | ||
| 448 | if os.name == "nt" if is_nt is None else is_nt: | ||
| 449 | return _rename_no_clobber(src, dst) | ||
| 450 | return os.link(src, dst) | ||
| 451 | |||
| 452 | |||
| 423 | def export_file(pool, index, target, mips, force, profile): | 453 | def export_file(pool, index, target, mips, force, profile): |
| 424 | target = Path(target) | 454 | target = Path(target) |
| 425 | with open(profile, encoding="utf-8") as source: | 455 | with open(profile, encoding="utf-8") as source: |
| @@ -431,13 +461,12 @@ def export_file(pool, index, target, mips, force, profile): | |||
| 431 | with tempfile.NamedTemporaryFile(dir=target.parent, delete=False) as f: | 461 | with tempfile.NamedTemporaryFile(dir=target.parent, delete=False) as f: |
| 432 | tmp = Path(f.name) | 462 | tmp = Path(f.name) |
| 433 | try: | 463 | try: |
| 434 | f.write(data) | 464 | with f: |
| 435 | f.close() | 465 | f.write(data) |
| 436 | if force: | 466 | if force: |
| 437 | os.replace(tmp, target) | 467 | replace_retry.replace(tmp, target) |
| 438 | else: | 468 | else: |
| 439 | os.link(tmp, target) | 469 | _move_no_clobber(tmp, target) |
| 440 | finally: | 470 | finally: |
| 441 | f.close() | ||
| 442 | tmp.unlink(missing_ok=True) | 471 | tmp.unlink(missing_ok=True) |
| 443 | return 0 | 472 | return 0 |