Python: fix DependencyWorkspace race on invalid leftover dir#7790
Merged
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Motivation
DependencyWorkspace._create_workspace_with_contentcrashes withOSError: [Errno 66] Directory not emptywhen the target cache directory already exists but is invalid (missing.venvorversion.txt, typically from a previous crashed build). The old logic triedos.rename(tmp_dir, final_dir)and only handled the race-loss case where another process had built a valid workspace at the destination — if the leftover was invalid, it re-raised.There are two underlying problems:
rename(2)semantics. On macOS,renameover a non-empty directory returnsENOTEMPTY(errno 66). Linux happens to allow it atomically, but macOS does not. Python's stdlib has no portable atomic-replace-directory primitive (renameat2(RENAME_EXCHANGE)is Linux-only and not exposed).cache_keysimultaneously could both reach the rename step, with one observing the other's half-built result.Summary
fcntl.flock(LOCK_EX)on.{cache_key}.lockfor the entire create operation. The lock is held acrossuv sync— intentional, since only one process should build the same workspace at a time._is_valid(final_dir)(another holder may have built it while we waited), thenshutil.rmtreeany invalid leftover so the subsequentos.renamealways targets a non-existent path.Test plan
test_get_or_create_recovers_from_invalid_leftoverseeds an invalidfinal_dirand verifiesget_or_createrebuilds rather than crashing.pytest tests/python/template/test_dependency_workspace.py— 18/18 pass.pytest tests/python/— 1441 passed, 6 skipped, 0 failed.