From dd9ea653764299a15768d9b13b26ba3ca1dfaf89 Mon Sep 17 00:00:00 2001 From: Andrey Date: Tue, 24 Nov 2026 17:06:22 +0300 Subject: [PATCH] story_index: restore write mode before unlink on replace failure (STORY-INDEX-STAGE-CLEANUP) When publishing report output (CSV/JSON), if os.replace fails (for instance due to permission errors), resetting os.chmod to 0o600 ensures TemporaryDirectory cleanup does not fail on Windows with PermissionError. agent: yes AI-assisted: yes --- tests/test_story_index.py | 16 ++++++++++++++++ tools/story_index.py | 6 +++++- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/tests/test_story_index.py b/tests/test_story_index.py index 720441cbaa..956e5054e4 100644 --- a/tests/test_story_index.py +++ b/tests/test_story_index.py @@ -522,6 +522,22 @@ def test_output_cannot_overwrite_carved_input(self): self.assertEqual(p.returncode, 2) self.assertIn("output would overwrite an input file", p.stderr) + def test_stage_cleanup_restores_write_mode_on_replace_failure(self): + with tempfile.TemporaryDirectory() as tmp: + dest = os.path.join(tmp, "out.json") + chmod_calls = [] + real_chmod = os.chmod + + def track_chmod(p, mode, **kwargs): + chmod_calls.append((p, mode)) + return real_chmod(p, mode, **kwargs) + + with mock.patch("story_index.os.replace", side_effect=OSError("replace failed")), \ + mock.patch("story_index.os.chmod", side_effect=track_chmod): + with self.assertRaises(OSError): + story_index.write_output(dest, [], {}) + self.assertTrue(any(mode == 0o600 for p, mode in chmod_calls)) + if __name__ == "__main__": unittest.main() diff --git a/tools/story_index.py b/tools/story_index.py index 11abcb0df8..be0020df36 100644 --- a/tools/story_index.py +++ b/tools/story_index.py @@ -319,7 +319,11 @@ def write_output(path, rows, summary): # os.replace hands the destination the staged file's bits; give them the destination's mode # (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) + try: + os.replace(staged, dest) + except BaseException: + os.chmod(staged, 0o600) + raise def byte_count(text):