Repository navigation
fix(storage): overwrite an existing file in a file store on Windows - #1746
Ramnath0521 wants to merge 2 commits into
Conversation
safe_copy and safe_write finished with Path.rename, which raises FileExistsError on Windows when the target exists, so put_file could not replace a file. They also wrote to a fixed temporary name that concurrent writers shared and that a failed write left behind. Both now write a uniquely named temporary file beside the target and move it over the target with os.replace, retrying briefly on Windows when another writer holds the target, and remove the temporary file on failure. Closes datajoint#1744 Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
dimitri-yatsenko
left a comment
There was a problem hiding this comment.
Thank you for the fix and the clear write-up, @Ramnath0521.
The diagnosis is right, and moving a uniquely named temporary file over the target with os.replace is the right approach. What I checked:
- The new tests ran and passed on all three Windows jobs (py3.10, py3.14, py3.15) on this head.
- On macOS, both concurrent-writer tests fail on
masterand pass with the fix. Onmasterthe writers share one.copying/.savingfile, and most of them fail withFileNotFoundError. I ran the two tests 30 times in a row with no failure. The overwrite andput_filetests pass onmasteron macOS, as expected, becauserenamereplaces the target there. - The file mode of the result is unchanged. It still follows the umask, both for a new file and when an existing file is replaced.
- The retry is bounded: 10 attempts with about 0.45 s of pauses in total. It runs only on Windows, and it re-raises the last
PermissionErrorunchanged, so a real permission problem still shows. On other systems the error is raised on the first attempt. - The temporary file is removed when the copy fails partway, when
os.replacefails, and onKeyboardInterrupt. - Both functions still create a missing destination folder first.
- The unit suite passes. The integration tests that use file stores pass. A one-off test that writes blobs, attachments and objects to a file store passed on MySQL and PostgreSQL.
One change before merge:
tests/unit/test_safe_write.py, test_a_failed_copy_leaves_no_temporary_file: this test also passes on master. shutil.copyfile opens the missing source before it creates the destination, so no temporary file is ever made and the new cleanup never runs. The test needs a copy that fails after the temporary file exists. For example, this one fails on master (it leaves dest.bin.copying) and passes on this branch:
def test_a_copy_that_fails_midway_leaves_no_temporary_file(self, tmp_path, monkeypatch):
utils = _utils()
src = tmp_path / "src.bin"
src.write_bytes(b"new")
dest = tmp_path / "dest.bin"
dest.write_bytes(b"old")
def fail_after_writing(src, dst):
Path(dst).write_bytes(b"partial")
raise OSError("disk full")
monkeypatch.setattr(utils.shutil, "copyfile", fail_after_writing)
with pytest.raises(OSError, match="disk full"):
utils.safe_copy(src, dest, overwrite=True)
assert dest.read_bytes() == b"old"
assert _leftovers(tmp_path) == []It needs from pathlib import Path at the top of the file. You can keep the existing test next to it or replace it.
Optional:
-
src/datajoint/utils.py, line 173: ifunlinkitself fails during cleanup, its error replaces the one that caused the failure. On Windows this can happen when another program still has the new file open. Ignoring errors from the cleanup step lets the caller see the original error:with contextlib.suppress(OSError): temp_file.unlink(missing_ok=True)
This needs
import contextlibat the top. -
A small test that patches
os.replaceto raisePermissionErrorwould pin the retry rules on every OS: one attempt on other systems, at most 10 on Windows, and no temporary file left after the last one.
dimitri-yatsenko
left a comment
There was a problem hiding this comment.
A second look at two details, the temporary file name and the retry pause. Two changes requested, and a few suggestions.
Requested: keep the temporary name short (src/datajoint/utils.py, line 161). .{dest.name}.{16 hex}.tmp adds 22 characters to the target's name; .copying and .saving added 8 and 7. File names are limited to 255 bytes, so a target name of 234 to 247 characters worked before and now fails with "File name too long". <filepath@> names are chosen by users, so this can happen. A name whose length doesn't depend on the target avoids it, for example .{uuid.uuid4().hex[:16]}.tmp. Keeping the uuid name, rather than tempfile.mkstemp, is the right call: mkstemp creates the file with mode 0600, which would make stored files unreadable to other users of a shared store.
Requested: retry until a deadline, with backoff (line 171). The pauses add up to about 0.45 s, on the same schedule for every writer. The usual cause of these Windows errors is antivirus or search indexing opening a file just written, and that often takes longer than half a second. Writers that collide also retry in step and can collide again. A deadline of about two seconds, with exponential backoff and a random factor, covers both.
Suggested: clean up in finally (line 172). After a successful os.replace the temporary file is gone, so an unconditional cleanup in finally does nothing on success, and the except BaseException branch goes away. Suppressing errors from the cleanup itself keeps the original error visible; otherwise a failed unlink (for example while another program still has the file open) replaces it.
Together, roughly:
_REPLACE_DEADLINE = 2.0 # seconds; the retry runs on Windows only
def _replace(temp_file, dest):
"""Move temp_file over dest, retrying on Windows while another process holds dest."""
deadline = time.monotonic() + _REPLACE_DEADLINE
pause = 0.01
while True:
try:
os.replace(temp_file, dest)
return
except PermissionError:
if os.name != "nt" or time.monotonic() + pause > deadline:
raise
time.sleep(pause * random.uniform(0.5, 1.5))
pause = min(pause * 2, 0.25)
def _replace_through_temp_file(dest, write):
temp_file = dest.with_name(f".{uuid.uuid4().hex[:16]}.tmp")
try:
write(temp_file)
_replace(temp_file, dest)
finally:
# Gone after a successful replace; after a failure, removing it must not hide the original error.
with contextlib.suppress(OSError):
temp_file.unlink(missing_ok=True)A test can patch time.sleep and time.monotonic to check the deadline without waiting.
Optional, here or in a follow-up:
safe_write(line 194) never overwrites, so it doesn't need the retry. It writes hash-addressed objects, and two processes storing the same content at the same moment race for the same path. If the replace fails and the file now exists, the other writer has already stored the same content, sosafe_writecan drop its temporary file and return without waiting.- When the deadline passes in
safe_copy, aDataJointErrorthat names the file and says another program has it open would be clearer than a barePermissionError. - After a hard crash (killed process, power loss), temporary files stay behind, as before. Garbage collection doesn't remove names that start with
.from the hash folders, so a sentence in the docstring would help whoever finds them.
dimitri-yatsenko
left a comment
There was a problem hiding this comment.
Marking this as changes requested, for the two requests in my review above:
- A temporary file name whose length doesn't depend on the target's name, so target names of 234 to 247 characters keep working.
- Retrying
os.replaceon Windows until a deadline of about two seconds, with exponential backoff and a random factor, instead of the fixed 0.45 s schedule.
The test that fails a copy partway, from my first review, is still needed too. The other points are suggestions.
|
@Ramnath0521, a friendly reminder about the two changes requested in the review above:
This fix is planned for 2.3.7. If the branch isn't updated before we prepare that release, we'll open a new PR that keeps your commits, makes these changes on top, and credits you as co-author, and close this one. Thanks again for the fix. |
|
@Ramnath0521, one more item I left out of the reminder above. The first review also asked for a test where a copy fails partway, checking that the existing file is left unchanged and no temporary file remains. That test is still needed along with the two code changes. |
…place retry The temporary file name no longer includes the destination's name, so a destination whose name is close to the 255-byte limit still works. The Windows retry of os.replace now runs until a two-second deadline with exponential backoff and a random factor, and re-raises the last PermissionError. The temporary file is removed in a finally block, and a failed cleanup no longer hides the original error. safe_write accepts a file that another writer stored first instead of failing. Adds tests for a copy that fails midway, the temporary name length, the retry rules on and off Windows, and safe_write losing the race. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
|
Thank you for the detailed review, and for running it on macOS and against the database stores. Sorry for the delay. Pushed in the commit "short temporary names and a deadline for the Windows replace retry". Requested:
Suggestions, also done:
I did not make the The unit suite passes on Windows 11 (1044 passed, 39 skipped), and the 15 tests in |
Closes #1744
Summary
StorageBackend.put_fileon afilestore could not overwrite an existing file on Windows, although it callssafe_copy(..., overwrite=True).safe_copyandsafe_writefinished withPath.rename, which raisesFileExistsErroron Windows when the target exists. Both also wrote to a fixed temporary name (<dest>.copying,<dest>.saving), so two writers of one path shared a file, and a failed or interrupted write left it behind.Change
src/datajoint/utils.py: both functions now go through one helper,_replace_through_temp_file..<16 hex digits>.tmp). It does not depend on the target's name, so a long target name still fits, and writers do not share it. It is created with the process's default mode, as before.os.replace, which replaces an existing file on every OS.finally, and a failed cleanup does not hide the original error.os.replaceraisesPermissionErrorwhile another thread or process (or antivirus or indexing) has the target open. The replace is retried until a 2-second deadline, with exponential backoff and a random factor, and the last error is re-raised unchanged. Anywhere else the error is raised at once.safe_writestill skips an existing file. If its replace fails and the target exists by then, another writer stored it first, so it returns without waiting.safe_copystill skips an existing file unlessoverwrite=True.Tests
tests/unit/test_safe_write.py(new, 15 tests): a new destination, overwriting, keeping an existing destination, a copy that fails before and midway (no temporary file left, the old file unchanged), the temporary name length, eight concurrent writers for both functions, the retry rules on and off Windows (patched clock, so no waiting),safe_writelosing the race, andput_filetwice onto the same path in afilestore. The overwrite, concurrent-writer, midway-failure andput_filetests fail onmaster. The wholetests/unitsuite passes on Windows 11 with Python 3.12 (1044 passed, 39 skipped); the integration tests need a database and I did not run them.ruff checkis clean.ruff formatwants to join two string literals at an unrelated line inutils.py(the underscore warning infrom_camel_case); I left that alone.Notes
PermissionErroron Windows until the retry was added, so the retry is needed for concurrent writers and not only for overwriting.🤖 Generated with Claude Code