Lock environments while preparing them #2439
All Vouch review confidence checks passed
Residual risk 0.35 = Change Risk (0.59) × (1 − Review Confidence (0.41)).
Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.59 · 650 lines diff across 8 files
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.02 · 1 substantive comment(s)
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size
diff_size
0.388
Shallow Review Depth
shallow_review_depth
0.344
Real PR Conversation Timeline
1 comments
"Review active on #2439"
general
weight: 0.35
cjames23
Motivation
I use a task runner to run Hatch scripts concurrently. Each of them is a separate
hatch runprocess, and when several start at once they can fail while Hatch prepares their environments. This currently requires some manual coordination, which is quite error-prone. This PR would be a huge improvement on that.The issue
Nothing coordinates Hatch processes that prepare the same environment. Each one reads and rewrites the metadata file that stores its dependency hash.
Problems arises also when running scripts from _different_ environments concurrently, if such environments depend on a same environment. For example, when using the
uvinstaller for multiple envs, everyhatch runalso prepares the internalhatch-uvenvironment when the project sets its dependencies, for example to require a newer uv. Whilehatch-uvor its metadata is missing or outdated, all the processes prepare it at once, and one of them can read its metadata while another is writing it:Another potential source of problems is the build environment, which is shared the same way in projects whose
dependenciesoroptional-dependenciesare dynamic. Every environment that installs the project reads the project's dependencies to compute its dependency hash, and when they are dynamic, reading them prepareshatch-buildfirst. Parallel runs of different environments therefore all preparehatch-buildat once.Processes preparing the same new environment collide in other ways too. Usually all but one get
A virtual environment already existsfromuv venv, which Hatch ignores, and then they all install the project and sync dependencies into the environment at the same time. If one of them fails, it removes the environment while the others are still using it.To reproduce, in a project that uses the
uvinstaller, sets dependencies forhatch-uvand has no environments yet, start the samehatch run <env>:python -c passin several processes at once.The fix
prepare_environmentnow holds a file lock for the environment during the whole preparation, from creation to the final metadata update. The lock file sits next to the environment's metadata file, so different environments are still prepared in parallel. A process that has to wait showsWaiting for another process to prepare environment: <name>.Pre-install and post-install commands run while the lock is held. If one of them runs Hatch for the same environment, that invocation must not wait for the lock, because the process holding it is waiting for the command to finish. To prevent this, the processes started under the lock inherit the lock through an environment variable that keeps track of locks held by ancestors, and a Hatch invocation that finds its environment's lock there proceeds without waiting.
Note that calling hatch in post-install seems to be common practice. Post-install commands run before the environment's own dependencies are installed, so projects call
hatch runin them to have those dependencies installed first, for examplepost-install-commands = ["hatch run pre-commit install"]. A GitHub code search finds several projects doing this for the environment being prepared, such as ultimate-notion, s3fetch and OpenDSSDirect.py. Without the inherited lock, they would all deadlock the first time the environment is created.filelockbecomes a direct dependency. It was already installed throughvirtualenv.Implementation note
The body of
prepare_environmentmoved unchanged to a private_prepare_environment_unlocked, whichprepare_environmentcalls inside the lock. Wrapping the body directly would add a level of nesting to a method that is already deeply nested and that the documentation renders to describe the environment life cycle. That section now renders_prepare_environment_unlocked, with a sentence saying it runs under the lock.To avoid the additional nesting, I also considered a decorator
@with_environment_lock, but ultimately settled with the solution in this PR.Let me know if you're fine with this choice or you prefer something else.
Not covered by this PR
Two more steps can still collide when different environments run in parallel:
hatch-buildthroughprepare_environment,prepare_build_environmentsyncs the additional build requirements, such as those of build hooks, and that sync is not locked.PythonManager.installis not locked either, so environments that need the same missing Python distribution can download it at the same time.AI disclosure
I used Claude Code (Opus 5, Extra effort) for this PR. It investigated the issue under my guidance, wrote the code, the tests and the changelog entry, and drafted a PR description. I reviewed the code, requested changes, such as the private method, variable renaming and comment fixes; I made sure the deadlock protection was necessary, reviewed tests and heavily edited the PR description. I understand the changes and can explain them without AI assistance.