Skip to content

Use os.replace when moving the downloaded file into the cache (Windows FileExistsError race) - #620

Open
hazelxue wants to merge 1 commit into
openai:mainfrom
hazelxue:fix/cache-replace-windows
Open

hazelxue wants to merge 1 commit into
openai:mainfrom
hazelxue:fix/cache-replace-windows

Conversation

@hazelxue

Copy link
Copy Markdown

read_file_cached writes the download to a .tmp file and then os.renames it onto the cache path. On Windows os.rename fails if the target already exists, so when several processes populate an empty cache at the same time, every process except the first raises:

FileExistsError: [WinError 183] Cannot create a file when that file already exists: '...\9b5ad71b...a4.<uuid>.tmp' -> '...\9b5ad71b...a4'

With a user-set TIKTOKEN_CACHE_DIR the except OSError branch re-raises, so this surfaces to callers; the losing processes also leave their .tmp files behind. On Linux/macOS os.rename overwrites silently, which is why it only shows up on Windows.

I hit it running a test suite with pytest-xdist (llama-index sets TIKTOKEN_CACHE_DIR), and it reproduces outside of that: 6 processes calling tiktoken.get_encoding("cl100k_base") against an empty cache dir on Windows 11 / Python 3.12 / tiktoken 0.14.0 gives 1 ok and 5 FileExistsError on every run.

os.replace is atomic and overwrites on every platform, so this just switches to it. The added test simulates another process finishing first (it writes the cache file inside the patched read_file) and fails with FileExistsError on Windows without the change.

On Windows os.rename raises FileExistsError if the target exists, so when
several processes populate an empty cache at the same time every process
but the first fails (and leaves its .tmp file behind). With a user-set
TIKTOKEN_CACHE_DIR the error is re-raised to the caller. os.replace is
atomic on every platform and overwrites the target.

@mangeshraut712 mangeshraut712 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

os.replace is the right call here: it is atomic on POSIX and on Windows guarantees replacement semantics, where os.rename raises FileExistsError when the destination exists. The race test (both processes writing the same cache path, one losing the rename) reproduces the reported failure on Windows and the NoLeftOverTmp check pins the cleanup invariant. Small, correct, and well tested.

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.

2 participants