Skip to content

fix(storage): overwrite an existing file in a file store on Windows - #1746

Open
Ramnath0521 wants to merge 2 commits into
datajoint:masterfrom
Ramnath0521:fix/issue-1744
Open

Ramnath0521 wants to merge 2 commits into
datajoint:masterfrom
Ramnath0521:fix/issue-1744

Conversation

@Ramnath0521

@Ramnath0521 Ramnath0521 commented Nov 23, 2026 •

Copy link
Copy Markdown

Closes #1744

Summary

StorageBackend.put_file on a file store could not overwrite an existing file on Windows, although it calls safe_copy(..., overwrite=True). safe_copy and safe_write finished with Path.rename, which raises FileExistsError on 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.

  • The temporary file has a unique, short name beside the target (.<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.
  • It is moved over the target with os.replace, which replaces an existing file on every OS.
  • It is removed in a finally, and a failed cleanup does not hide the original error.
  • On Windows, os.replace raises PermissionError while 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_write still 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_copy still skips an existing file unless overwrite=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_write losing the race, and put_file twice onto the same path in a file store. The overwrite, concurrent-writer, midway-failure and put_file tests fail on master. The whole tests/unit suite 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 check is clean. ruff format wants to join two string literals at an unrelated line in utils.py (the underscore warning in from_camel_case); I left that alone.

Notes

  • The eight-writer test failed with PermissionError on Windows until the retry was added, so the retry is needed for concurrent writers and not only for overwriting.
  • The change is not Windows-only: on POSIX the fixed temporary name was shared in the same way, and the new name and the cleanup apply there too.

🤖 Generated with Claude Code

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 dimitri-yatsenko left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 master and pass with the fix. On master the writers share one .copying / .saving file, and most of them fail with FileNotFoundError. I ran the two tests 30 times in a row with no failure. The overwrite and put_file tests pass on master on macOS, as expected, because rename replaces 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 PermissionError unchanged, 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.replace fails, and on KeyboardInterrupt.
  • 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: if unlink itself 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 contextlib at the top.

  • A small test that patches os.replace to raise PermissionError would 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 dimitri-yatsenko left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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, so safe_write can drop its temporary file and return without waiting.
  • When the deadline passes in safe_copy, a DataJointError that names the file and says another program has it open would be clearer than a bare PermissionError.
  • 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 dimitri-yatsenko left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Marking this as changes requested, for the two requests in my review above:

  1. A temporary file name whose length doesn't depend on the target's name, so target names of 234 to 247 characters keep working.
  2. Retrying os.replace on 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.

@dimitri-yatsenko

Copy link
Copy Markdown
Member

@Ramnath0521, a friendly reminder about the two changes requested in the review above:

  1. A temporary file name whose length doesn't depend on the target's name, so target names of 234 to 247 characters keep working.
  2. Retrying os.replace on Windows until a deadline of about two seconds, with exponential backoff and a random factor, instead of the fixed 0.45 s schedule.

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.

@dimitri-yatsenko

Copy link
Copy Markdown
Member

@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>
@Ramnath0521

Copy link
Copy Markdown
Author

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:

  • Short temporary name. It is now .{uuid.uuid4().hex[:16]}.tmp, so its length no longer depends on the target. The test records the name shutil.copyfile is given for a 104-character target and checks it is at most 24 characters.
  • Deadline with backoff. _replace retries os.replace on Windows until 2 seconds have passed, pausing 0.01 s and doubling up to 0.25 s, with a random factor of 0.5 to 1.5. It re-raises the last PermissionError unchanged. Off Windows it raises on the first attempt. I used a _IS_WINDOWS module constant so tests can switch it without changing os.name.
  • Copy that fails midway. Added your test as written (it needed from pathlib import Path).

Suggestions, also done:

  • Cleanup is in a finally and suppresses OSError from unlink, so the original error stays visible.
  • TestReplaceRetry patches os.replace, time and random inside datajoint.utils: one attempt and no sleep off Windows; success after three failures on Windows; at the deadline the original error is raised with a total pause between 1 and 2 seconds that grows each time; no temporary file is left in any case.
  • safe_write drops its temporary file and returns if the replace fails with PermissionError and the target exists by then (skip_if_taken). A test covers it.
  • The _replace_through_temp_file docstring says that after a hard crash a hidden .<16 hex digits>.tmp file stays behind in the destination folder.

I did not make the DataJointError that names the file when the deadline passes; a bare PermissionError keeps the error type the same as on other systems. Happy to add it if you prefer.

The unit suite passes on Windows 11 (1044 passed, 39 skipped), and the 15 tests in test_safe_write.py passed six runs in a row. I did not run the integration tests or macOS.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

StorageBackend.put_file cannot overwrite on Windows; concurrent writes share one temp file

2 participants