From 692b65cb10b7474f469ececbbd820af6a9081f2d Mon Sep 17 00:00:00 2001 From: djrolfes Date: Tue, 24 Nov 2026 14:50:22 +0100 Subject: [PATCH] story_index: make the staging file deletable when a replace fails The staged report carries the destination's bits, so on Windows a failed os.replace over a read-only report leaves a read-only stage the TemporaryDirectory cleanup refuses to delete, masking the real error with a cleanup failure. The cleanup now makes the staged file writable before deleting and lets one delete failure go, so the caller reports the replace; a successful publish is unchanged, and the prior report stays byte-for-byte intact on failure. Same shape as navmesh_index's and bvh_index's staging cleanup. Regression test in the style of the failed-replace tests there: mocks the replace as failing over a 0o444 report and fails against the old code on the made-deletable assertion. Synthetic archives only; no game data. Claimed in the coordination issue as STORY-INDEX-STAGE-CLEANUP (issue #14). AI-assisted. --- tests/test_story_index.py | 33 +++++++++++++++++++++++++++++++++ tools/story_index.py | 17 ++++++++++++++--- 2 files changed, 47 insertions(+), 3 deletions(-) diff --git a/tests/test_story_index.py b/tests/test_story_index.py index 720441cbaa..38f684e680 100644 --- a/tests/test_story_index.py +++ b/tests/test_story_index.py @@ -336,6 +336,39 @@ def failing_dump(obj, f, **kwargs): self.assertEqual(f.read(), prior) self.assertEqual(sorted(os.listdir(self.root)), before) + def test_failed_replace_of_read_only_report_makes_stage_deletable(self): + """A failed replace over a read-only report still cleans the stage: the staged file has the + read-only destination's bits, so the cleanup makes it deletable before deleting, and one + delete failure is swallowed instead of masking the replace error (Windows behavior).""" + out = os.path.join(self.root, "out.json") + with open(out, "w", encoding="utf-8") as f: + f.write('{"prior": true}') + with open(out, "rb") as f: + prior = f.read() + os.chmod(out, 0o444) + self.addCleanup(lambda: os.path.exists(out) and os.chmod(out, 0o600)) + made_writable = [] + real_chmod = os.chmod + + def chmod(staged_path, mode, *args, **kwargs): + if isinstance(staged_path, str) and os.path.basename(staged_path).startswith("story_index") \ + and mode == 0o600: + made_writable.append(staged_path) + return real_chmod(staged_path, mode, *args, **kwargs) + + with self.assertRaises(OSError) as raised: + with mock.patch.object(story_index.os, "replace", side_effect=OSError("replace denied")), \ + mock.patch.object(story_index.os, "chmod", chmod): + story_index.write_output(out, [{"offset": 0x100, "stored": 8, "size": 9, + "signature": "psin", "version": None, "count": 1, + "detail": ""}], {"files": 1}) + self.assertIn("replace denied", str(raised.exception)) + self.assertEqual(len(made_writable), 1) # the stage was made deletable + with open(out, "rb") as f: + self.assertEqual(f.read(), prior) # the prior report is untouched + self.assertEqual([n for n in os.listdir(self.root) if n.startswith("story_index")], []) + self.assertNotIn(".tmp", " ".join(os.listdir(self.root))) # no staging directory stranded + def test_cli(self): out = os.path.join(self.root, "cli.json") p = subprocess.run([sys.executable, "-I", TOOL, self.rpf, out, "--quiet"], diff --git a/tools/story_index.py b/tools/story_index.py index 11abcb0df8..294c253f9d 100644 --- a/tools/story_index.py +++ b/tools/story_index.py @@ -31,6 +31,7 @@ import tempfile import time import zlib +from contextlib import suppress # -I keeps the script directory off sys.path; add it back so the sibling helpers are importable. sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) @@ -296,7 +297,9 @@ def write_output(path, rows, summary): The stage lives in a private TemporaryDirectory under the destination's parent, so os.replace only ever renames within one filesystem. A late failure closes the stage and leaves any prior - report byte-for-byte intact. The destination is resolved first, so a report path that is a + report byte-for-byte intact; the staged file is made deletable first, so a read-only report on + Windows cannot strand the stage or mask the error with a cleanup failure. The destination is + resolved first, so a report path that is a symlink is published through to its target the way open(..., "w") did before. Because os.replace unlinks the previous report file only at the destination name, other hard links to it keep the previous contents. @@ -304,8 +307,9 @@ def write_output(path, rows, summary): ext = os.path.splitext(path)[1].lower() dest = os.path.realpath(path) parent = os.path.dirname(dest) - with tempfile.TemporaryDirectory(dir=parent) as staging: - staged = os.path.join(staging, "story_index" + ext) + stage_dir = tempfile.TemporaryDirectory(dir=parent) + try: + staged = os.path.join(stage_dir.name, "story_index" + ext) if ext == ".json": with open(staged, "w", encoding="utf-8", newline="\n") as f: json.dump({"summary": summary, "files": rows}, f, indent=1) @@ -320,6 +324,13 @@ def write_output(path, rows, summary): # (an existing report's, or what open() would have made for a new file) so perms are stable. os.chmod(staged, published_mode(dest)) os.replace(staged, dest) + finally: + # On a failed replace the staged file carries the destination's bits, which a read-only report + # makes read-only: Windows then refuses the delete and the cleanup error masks the real one. + # Make it deletable first and let one delete failure go, so the caller reports the replace. + with suppress(OSError): + os.chmod(staged, 0o600) + stage_dir.cleanup() def byte_count(text):