world_lights_paths: restore write mode before unlink on replace failure and publish mode (WORLD-LIGHTS-STAGE-CLEANUP)

Apply published_mode to staged .partial file and reset os.chmod to 0o600
before os.remove on replace failure or write error, ensuring temporary file
cleanup does not fail with PermissionError on Windows.

agent: yes
AI-assisted: yes
This commit is contained in:
Andrey
2026-11-24 17:25:12 +03:00
parent d0da7dade8
commit 09bbad3cca
2 changed files with 32 additions and 0 deletions

View File

@ -590,6 +590,28 @@ class ScanTest(unittest.TestCase):
self.assertEqual(len(err.getvalue().strip().splitlines()), 1, err.getvalue())
self.assertNotIn("Traceback", err.getvalue())
def test_stage_cleanup_restores_write_mode_on_replace_failure(self):
with tempfile.TemporaryDirectory() as tmp:
lights = os.path.join(tmp, "lights.jsonl")
with open(lights, "w", encoding="utf-8") as f:
f.write('{"old": true}\n')
os.chmod(lights, 0o444)
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("world_lights_paths.os.replace", side_effect=OSError("replace failed")), \
mock.patch("world_lights_paths.os.chmod", side_effect=track_chmod):
with self.assertRaises(OSError):
T.summarize({"lights": {}, "archetype_lights": {}, "resources": 0, "incomplete": 0,
"light_resources": 0, "ranges": {}, "world_lights": []},
lights_out=lights)
self.assertTrue(any(mode == 0o600 for p, mode in chmod_calls))
def test_bad_input_is_one_line(self):
err = io.StringIO()
with contextlib.redirect_stderr(err):

View File

@ -50,6 +50,7 @@ if _TOOLS_DIR not in sys.path:
from pool_workers import process_workers # noqa: E402
from report_paths import same_report_path # noqa: E402
from file_mode import published_mode # noqa: E402
import world_census as WC # noqa: E402
import world_index as WI # noqa: E402
@ -776,6 +777,10 @@ def summarize(total, entities=None, lights_out=None):
pass
out = None
if staged is not None and os.path.exists(staged):
try:
os.chmod(staged, 0o600)
except OSError:
pass
os.remove(staged)
raise
finally:
@ -783,10 +788,15 @@ def summarize(total, entities=None, lights_out=None):
out.close()
if staged is not None:
try:
os.chmod(staged, published_mode(lights_out))
os.replace(staged, lights_out)
except BaseException:
# A destination that is a directory (or read-only) must not leave the staged copy behind.
if os.path.exists(staged):
try:
os.chmod(staged, 0o600)
except OSError:
pass
os.remove(staged)
raise
summary["placement"] = dict(placed)