Opened 4 minutes ago

#37547 new Bug

FileBasedCache loses keys that are read while being overwritten on Windows

Reported by: Jonatha Oliveira Costa Owned by:
Component: Core (Cache system) Version: dev
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Trac: New ticket — component "Core (Cache system)", type "Bug", version "dev".

Summary:

FileBasedCache loses keys that are read while being overwritten on Windows

Description:

On Windows, a key of FileBasedCache that is read while another thread or process overwrites it can be reported as missing and then be deleted, although it was never deleted or expired.

set() writes a temporary file and calls file_move_safe(tmp_path, fname, allow_overwrite=True). os.rename() can't replace an existing file on Windows, so file_move_safe() falls back to copying: it opens the destination with O_TRUNC and writes the content in chunks. A get() that opens the file in that window reads an empty file; _is_expired() treats an empty file as expired and deletes it. Readers can also get PermissionError, and the writer FileNotFoundError, because Windows doesn't allow a file to be replaced or deleted while another handle has it open.

To reproduce (Windows only), with CACHES set to FileBasedCache:

import threading
from django.core.cache import cache

cache.set("k", 0, 3600)
stop = threading.Event()

def writer():
    n = 0
    while not stop.is_set():
        n += 1
        cache.set("k", n, 3600)

t = threading.Thread(target=writer)
t.start()
misses = errors = 0
for _ in range(20000):
    try:
        misses += cache.get("k") is None
    except Exception:
        errors += 1
stop.set()
t.join()
print(misses, errors)

On main (c896b3e536, Python 3.13, Windows 10 build 26200) three runs gave between 757 and 3501 misses and between 644 and 1371 PermissionError, and the writer thread dies on FileNotFoundError. On Linux os.rename() replaces the file atomically and the problem doesn't exist.

Where I hit it: sessions stored in a file-based cache during development on Windows. With one thread saving the session and another making requests, 11 to 13 out of 20 logins lost their session cookie.

What I measured as fixes, same loop:

approach misses read errors write errors
main 757–3501 644–1371 some
os.replace() in set() 0 up to 1231 about 40%
os.replace() and retries on both sides 0 0 the writer starves with 4 readers
rename with POSIX semantics, files opened as today 0 up to 1231 about 40%
rename with POSIX semantics, files opened with FILE_SHARE_DELETE 0 0 0

Only the last one works, with 1, 4 and 8 reader threads. It needs two things, both Windows-only and both through ctypes, as django/core/files/locks.py already does:

  • open cache files through open(..., opener=...) with an opener that calls CreateFileW with FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
  • replace the file with SetFileInformationByHandle(FileRenameInfoEx) and FILE_RENAME_FLAG_POSIX_SEMANTICS (Windows 10 1607+), falling back to file_move_safe() where that isn't supported.

Nothing changes on other platforms. I have a branch with this and tests (they fail on main on Windows), and I can open a PR if the approach is acceptable.

Related: #34209 fixed a race in has_key(); #20536 made the backend safe for concurrent processes on POSIX. file_move_safe() itself is being changed in #37225 and #37444, so the branch doesn't touch it.

Change History (0)

Note: See TracTickets for help on using tickets.
Back to Top