From 095ecb00842feb1c59f4e69843f4e4b0654f7682 Mon Sep 17 00:00:00 2001 From: Andrey Date: Tue, 24 Nov 2026 16:03:45 +0300 Subject: [PATCH] timecycle_pairs: close mkstemp fd on fdopen error, use published_mode, and restore mode before unlink (TIMECYCLE-PAIRS-STAGE-CLEANUP) --- tests/test_timecycle_pairs.py | 77 +++++++++++++++++++++++++++++++++++ tools/timecycle_pairs.py | 17 ++++++-- 2 files changed, 91 insertions(+), 3 deletions(-) diff --git a/tests/test_timecycle_pairs.py b/tests/test_timecycle_pairs.py index bad195838..2e622c933 100644 --- a/tests/test_timecycle_pairs.py +++ b/tests/test_timecycle_pairs.py @@ -8,6 +8,7 @@ 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")) @@ -161,6 +162,82 @@ class TimecyclePairsTests(unittest.TestCase): tp.main([os.path.join(tmp, "missing.rpf")]) self.assertEqual(cm.exception.code, 2) + def test_failed_replace_over_readonly_report_cleans_staging_file(self): + with tempfile.TemporaryDirectory() as td: + out_file = os.path.join(td, "report.json") + tp._write_json_atomic(out_file, {"test": 1}) + os.chmod(out_file, 0o444) + try: + with mock.patch.object(tp.os, "replace", side_effect=PermissionError("replace failed")): + with self.assertRaisesRegex(PermissionError, "replace failed"): + tp._write_json_atomic(out_file, {"test": 2}) + finally: + try: + os.chmod(out_file, 0o600) + except OSError: + pass + self.assertEqual([n for n in os.listdir(td) if n.startswith(".timecycle_pairs_")], []) + with open(out_file, encoding="utf-8") as f: + self.assertEqual(json.load(f), {"test": 1}) + + @unittest.skipUnless(os.name == "nt", "Windows enforces read-only file replace and unlink") + def test_windows_readonly_report_failure_cleans_staging_file(self): + with tempfile.TemporaryDirectory() as td: + out_file = os.path.join(td, "report.json") + tp._write_json_atomic(out_file, {"test": 1}) + os.chmod(out_file, 0o444) + try: + with self.assertRaises(PermissionError): + tp._write_json_atomic(out_file, {"test": 2}) + finally: + try: + os.chmod(out_file, 0o600) + except OSError: + pass + self.assertEqual([n for n in os.listdir(td) if n.startswith(".timecycle_pairs_")], []) + with open(out_file, encoding="utf-8") as f: + self.assertEqual(json.load(f), {"test": 1}) + + def test_fdopen_failure_closes_descriptor_and_cleans_staging_file(self): + with tempfile.TemporaryDirectory() as td: + out_file = os.path.join(td, "report.json") + real_mkstemp = tp.tempfile.mkstemp + real_close = os.close + created = [] + closed = [] + + def spy_mkstemp(*args, **kwargs): + fd, temp = real_mkstemp(*args, **kwargs) + created.append((fd, temp)) + return fd, temp + + def spy_close(fd): + closed.append(fd) + return real_close(fd) + + try: + with ( + mock.patch.object(tp.tempfile, "mkstemp", side_effect=spy_mkstemp), + mock.patch.object(tp.os, "fdopen", side_effect=OSError("fdopen failed")), + mock.patch.object(tp.os, "close", side_effect=spy_close), + ): + with self.assertRaisesRegex(OSError, "fdopen failed"): + tp._write_json_atomic(out_file, {"test": 1}) + self.assertEqual(len(created), 1) + self.assertIn(created[0][0], closed) + self.assertEqual([n for n in os.listdir(td) if n.startswith(".timecycle_pairs_")], []) + finally: + for fd, temp in created: + if fd not in closed: + try: + real_close(fd) + except OSError: + pass + try: + os.unlink(temp) + except OSError: + pass + class DirectoryReportTests(unittest.TestCase): diff --git a/tools/timecycle_pairs.py b/tools/timecycle_pairs.py index bf907b165..94c99b5bb 100644 --- a/tools/timecycle_pairs.py +++ b/tools/timecycle_pairs.py @@ -27,6 +27,7 @@ from collections import Counter, defaultdict ROOT = os.path.dirname(os.path.abspath(__file__)) if ROOT not in sys.path: sys.path.insert(0, ROOT) +from file_mode import published_mode # noqa: E402 import gamedata_index as gi # noqa: E402 from report_paths import same_report_path # noqa: E402 @@ -249,16 +250,26 @@ def summarize_documents(docs: list[tuple[str, bytes]]) -> dict: def _write_json_atomic(path: str, payload: dict) -> None: - parent = os.path.dirname(os.path.abspath(path)) or "." + out_abs = os.path.abspath(path) + parent = os.path.dirname(out_abs) or "." os.makedirs(parent, exist_ok=True) fd, tmp_path = tempfile.mkstemp(prefix=".timecycle_pairs_", suffix=".tmp", dir=parent) try: - with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as f: + try: + f = os.fdopen(fd, "w", encoding="utf-8", newline="\n") + except BaseException: + os.close(fd) + raise + with f: json.dump(payload, f, indent=1, sort_keys=True) f.write("\n") - os.replace(tmp_path, path) + f.flush() + os.fsync(f.fileno()) + os.chmod(tmp_path, published_mode(out_abs)) + os.replace(tmp_path, out_abs) except BaseException: try: + os.chmod(tmp_path, 0o600) os.unlink(tmp_path) except OSError: pass