← Back to Pull requests

Lock environments while preparing them #2439

Open
unknown opened this pull request with 650 lines diff across 8 files
View on GitHub
unknown unknown commented on Sep 19, 2026 00:52 UTC
Author

Motivation

I use a task runner to run Hatch scripts concurrently. Each of them is a separate hatch run process, 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 uv installer for multiple envs, every hatch run also prepares the internal hatch-uv environment when the project sets its dependencies, for example to require a newer uv. While hatch-uv or 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:

  File ".../hatch/env/virtual.py", line 124, in uv_path
    self.app.project.prepare_environment(uv_env, ...)
  File ".../hatch/project/core.py", line 256, in prepare_environment
    self.env_metadata.update_dependency_hash(environment, new_dep_hash)
  File ".../hatch/project/env.py", line 436, in _read
    return json.loads(metadata_file.read_text())
JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Another potential source of problems is the build environment, which is shared the same way in projects whose dependencies or optional-dependencies are dynamic. Every environment that installs the project reads the project's dependencies to compute its dependency hash, and when they are dynamic, reading them prepares hatch-build first. Parallel runs of different environments therefore all prepare hatch-build at once.

Processes preparing the same new environment collide in other ways too. Usually all but one get A virtual environment already exists from uv 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 uv installer, sets dependencies for hatch-uv and has no environments yet, start the same hatch run <env>:python -c pass in several processes at once.

The fix

prepare_environment now 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 shows Waiting 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 run in them to have those dependencies installed first, for example post-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.

filelock becomes a direct dependency. It was already installed through virtualenv.

Implementation note

The body of prepare_environment moved unchanged to a private _prepare_environment_unlocked, which prepare_environment calls 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:

  • After preparing hatch-build through prepare_environment, prepare_build_environment syncs the additional build requirements, such as those of build hooks, and that sync is not locked.

  • PythonManager.install is 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.

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: cjames23 Review duration: 104838m
    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
    0.59
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.02 · 1 substantive comment(s)
    0.02
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    40%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    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
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 40.9% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 59% (MEDIUM) · Higher = larger blast radius
    59%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 40.9% · Lower = rushed or shallow review
    40.9%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 34.8% · Safe to merge
    34.8%
    Repository