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

Apply published_mode(destination) in _staged_entity_report before atomic replacement,
and restore write permission (0o600) before unlinking in finally block
when replace fails, preventing Windows PermissionError [WinError 5] and
stranded temporary files.

agent: yes
AI-assisted: yes
This commit is contained in:
Andrey
2026-11-24 17:58:01 +03:00
parent b9320a118d
commit 4822bcf9de
2 changed files with 32 additions and 5 deletions

View File

@ -942,6 +942,23 @@ class WorldIndexTest(unittest.TestCase):
# Every resource field emitted by parse_resource() for this map must have a matching CSV column.
self.assertEqual(set(json_row) - set(fieldnames), set())
def test_staged_entity_report_restores_write_mode_on_replace_failure(self):
chmod_calls = []
real_chmod = os.chmod
def track_chmod(p, mode, **kwargs):
chmod_calls.append((str(p), mode))
return real_chmod(p, mode, **kwargs)
out_path = os.path.join(self.dir, "entities.jsonl")
with mock.patch.object(WI.os, "replace", side_effect=OSError("replace failed")), \
mock.patch.object(WI.os, "chmod", side_effect=track_chmod):
with self.assertRaisesRegex(OSError, "replace failed"):
with WI._staged_entity_report(out_path):
pass
self.assertTrue(any(mode == 0o600 for _, mode in chmod_calls), chmod_calls)
def setUpModule():
# The tools' main() prints its summary JSON; keep it out of the test log (tests that check it redirect again).

View File

@ -39,6 +39,9 @@ import tempfile
import zlib
from contextlib import contextmanager
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from file_mode import published_mode
# -I keeps the script directory off sys.path, so add it explicitly before importing the sibling module.
_TOOLS_DIR = os.path.dirname(os.path.abspath(__file__))
if _TOOLS_DIR not in sys.path:
@ -788,15 +791,22 @@ def _staged_entity_report(path):
try:
with open(staged, "w", encoding="utf-8", newline="\n") as handle:
yield EntityRows(handle)
if mode is not None:
os.chmod(staged, mode & 0o777)
try:
os.chmod(staged, published_mode(destination))
except OSError:
pass
os.replace(staged, destination)
finally:
if os.path.exists(staged):
if os.name == "nt":
os.chmod(staged, stat.S_IWRITE)
try:
os.chmod(staged, 0o600)
except OSError:
pass
os.unlink(staged)
os.rmdir(directory)
try:
os.rmdir(directory)
except OSError:
pass
def main(argv=None):