Skip to content

🐛 fix(seed): keep the embed update log intact when runs share app-data - #3786

Merged
gaborbernat merged 4 commits into
pypa:mainfrom
darrenhuai:fix/update-log-atomic-write
Dec 4, 2026
Merged

gaborbernat merged 4 commits into
pypa:mainfrom
darrenhuai:fix/update-log-atomic-write

Conversation

@darrenhuai

@darrenhuai darrenhuai commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

When several virtualenv runs share an app-data folder, a wheel downloaded by an earlier run can stop being usable offline even though it's still cached. This is main (c2cb0a1) on Linux with Python 3.14, which bundles pip 26.3. After the first command only the cached wheel can be used:

./
├── index/  # local index with pip 26.0.1
└── empty/  # local index with no wheels
$ PIP_INDEX_URL=file://$PWD/index virtualenv -q --app-data "$PWD/cache" --no-periodic-update --no-setuptools --pip 26.0.1 first
$ export PIP_INDEX_URL=file://$PWD/empty
$ for i in 1 2 3 4 5 6 7 8; do virtualenv -q --app-data "$PWD/cache" --no-setuptools --pip 26.0.1 env$i & done; wait
...
RuntimeError: seed failed due to failing to download wheels pip
$ cat cache/wheel/3.14/embed/4/unverified/pip.json
{
  "completed": null,
  "periodic": true,
  "started": "2026-12-02T01:27:16.243239Z",
  "versions": []
}
$ virtualenv -q --app-data "$PWD/cache" --no-setuptools --pip 26.0.1 after
...
RuntimeError: seed failed due to failing to download wheels pip
$ find cache/wheel/house -name '*.whl'
cache/wheel/house/unverified/bdb1b08f4274833d62c1aa29e20907365a2ceb950410df15fc9521bad440122b/pip-26.0.1-py3-none-any.whl

All eight parallel runs failed in that round, the fifth I tried, but it's a race, so most rounds are fine. I repeated the loop with the first run's log put back before each round, because an update isn't due again for an hour after one starts. On main, 8 of 160 runs failed on Linux and 8 of 80 on Windows. On this branch none did. It also started 20 updates in the 20 Linux rounds and 10 in the 10 Windows ones, where main started 31 and 17.

JSONStoreDisk.write truncates the log before filling it in, and JSONStoreDisk.read deletes a log that isn't valid JSON. A run that reads at the wrong moment can delete the log another run is still writing. It also sees an empty log, so handle_auto_update can write "versions": [] back, as above. Pinned wheels that were downloaded are only found through this log. handle_auto_update, add_wheel_to_update_log and _run_do_update also never take the store's lock, so one run can overwrite what another just recorded even if every read gets a complete file.

#1938 reported this race from pipenv's Windows CI in 2020 and suggested atomic writes. The reporter gave up on them because Windows can refuse to replace a file another process has open, so #1941 only ignored the error from the failed delete.

write() now works like the zipapp extraction from #3735, minus the fsync (the log is a cache, and main's write didn't sync it either): it writes a temporary file next to the log, moves it into place with os.replace, and removes the temporary file if any of that fails. On POSIX the temporary file first gets the group and mode of the log it replaces, which the write in place kept, so one user's umask can't lock the others out of a shared app-data. Where the system refuses that, for example for a group that isn't mapped inside a rootless container, the write goes ahead without it. The temporary name is longer than the log's, so on Windows it goes through windows_extended_path. Without that, a 255-character log path that works on main fails when long paths are off.

On Windows a replace can be refused while a reader has the log open, and a read can be refused during a replace. Both raise PermissionError, so there (and only there) I retry after 10 ms, up to 100 times for a replace and 10 times for a read. With one writer and three readers in a tight loop, 99% of these conflicts were over within 167 ms for replaces and 28 ms for reads (the longest took 212 and 104 ms).

With one process writing the log 2000 times through the store and three others loading it in a tight loop, readers on main deleted it 655 and 587 times in two runs on Linux, and 412 and 430 times on Windows. On this branch they never did, no write was refused, and none of the about 31,000 reads on Linux and 21,000 on Windows came back empty.

handle_auto_update and add_wheel_to_update_log now hold the store's lock from reading the log until writing it. _run_do_update reads it under the lock, downloads without the lock, and then holds it again from a second read until the write. None of them takes another lock meanwhile. handle_auto_update first reads the log without the lock, so a run with no update due doesn't need to create a lock file. If one is due, it reads the log again under the lock, so only one of the parallel runs starts the update. It releases the lock before trigger_update, because the update needs it too and an inline update (_VIRTUALENV_PERIODIC_UPDATE_INLINE=1) finishes before that call returns.

After its download, _run_do_update keeps every entry of the second read that it didn't take from the first one. So a wheel recorded meanwhile stays, and so does a pinned wheel that an overlapping update has logged as periodic since. If one of those is a rebuild of a wheel in its own list, the older entry is dropped, as add_wheel_to_update_log does. If two updates overlap, the one that finishes last still decides about the entries it read first, as on main, but it no longer drops what the other one added. The exception is a manual --upgrade-embed-wheels run that finishes during a periodic update: it wins as if it finished last. A wheel it marked manual meanwhile, or another build of that wheel from a custom index, stays manual and moves to the front of the log, so it skips the grace period. Main logged it as periodic again, or put the periodic update's older wheel ahead of it.

There are trade-offs:

  • On Windows a file that's really denied raises the same PermissionError, so a read-protected log now takes 0.1 to 0.15 s to count as missing, and writing a read-only log takes 1.2 to 1.7 s to fail. Both used to be immediate.
  • On Windows, if another program keeps the log open for longer than the retries, the write now fails after 1.1 to 1.6 s, and a run with an update due fails with seed failed due to failing to download wheels pip. Main wrote the log in place.
  • If you can't add files to the log's folder, the write fails right away, on Linux too. Main could still overwrite an existing log there. With an update due the lock file can't be created either. On Windows, filelock 4.3.1 then gives up with PermissionError after about 0.7 s, but 3.19.1 (the version used on Python 3.9) and 3.24.2 were still waiting after 15 s, with or without an existing log. Without a log, main failed at once there.
  • On Windows a read without the lock, like the one that picks the wheel to seed with, can still rarely miss the log while another run replaces it. That run then falls back to the bundled wheel or a download, so a pinned run can fail offline, but it writes nothing back.
  • A log that is a symlink is now replaced by a regular file instead of written through. The log also belongs to whoever wrote it last, where main kept its owner, and on Windows a permission set on the log file itself gives way to the ones it inherits from its folder.

The 22 new test cases use patched calls, threads and events to control the order instead of relying on timing. Of the 21 that run on Windows, 17 fail on main, six of them only because main doesn't use the sleep or os.replace they patch. Three of the other four cover the path limit, a run with no update due not needing the lock, and releasing the lock before the update, which only matter with this change. The fourth checks that a pin which an overlapping update logs as periodic stays in the log. Main already keeps it, and it also keeps the log's mode and group, which a POSIX-only test checks. I also undid each part of the fix separately, including each retry, lock and re-read, the mode copy and the merge, and at least one new test failed every time, on Windows or on Linux. read_dict.call_count goes from 1 to 2 in seven existing tests because _run_do_update now reads the log again under the lock. The malformed log tests from #3376 and #3383 pass unchanged. Four more cases cover a manual upgrade during a periodic update and fail without that part of the fix.

Thanks for contributing, make sure you address all the checklists (for details on how see development documentation)

  • ran the linter to address style issues (tox -e fix). Not through tox: I ran ruff 0.17.6 (check and format), simplint 0.14.7, flake8-lazy 0.11.0, codespell 2.4.3, typos 1.52.2 and docstrfmt 2.2.1, the versions pinned in .pre-commit-config.yaml, on an LF copy because my Windows checkout has CRLF line endings. ty check src/virtualenv (0.0.109) for Linux passes on 3.9 and 3.15.

  • wrote descriptive pull request text

  • ensured there are test(s) validating the fix

  • added a docs/changelog/+short-description.<type>.rst fragment for each user-facing change, or applied
    skip news

  • updated/extended the documentation (the docs don't describe how the log is written)

  • for changes to activation scripts, pyvenv.cfg, wheel downloads, app-data or release workflows: explained in the
    PR text which outside input the change handles, such as a path, a prompt or a downloaded file, and how it stops that
    input from running as code. See the
    security scope. The outside input is the app-data path and the log that other runs write there. The log is still only parsed as JSON, and UpdateLog.validate still checks its file names before they're used. Nothing from the log or the path is run as code. The temporary file gets a random name in the log's own folder and is opened with x, so it never reuses an existing file. On POSIX it only gets the mode and group the replaced log already had. Where wheels come from and how they're verified doesn't change.

  • ran tests on Python 3.9 and 3.15 (tox run -e 3.9,3.15). Not through tox: I ran tests/unit/app_data and tests/unit/seed/wheels on Windows with 3.9 and filelock 3.19.1, and the full suite (without --int) with 3.14 on Linux and Windows, where nothing fails that doesn't also fail on main. I couldn't run 3.15 here, so that's left to CI.

  • linked upstream issues beside any temporary interpreter overrides (none)

  • kept the PR in draft until CI passes

darrenhuai and others added 4 commits December 1, 2026 12:29
JSONStoreDisk.write truncated the update log in place. A concurrent run
could read it half written, treat it as invalid JSON and delete the log
the other run had just finished. The readers and writers also never took
the store's lock, so a run could write back a log without a wheel that
another run had recorded since. virtualenv finds downloaded pinned wheels
only through this log, so later offline runs failed although the wheel
was still cached.

Write the new log to a temporary file and replace the old one in one
step. On Windows, retry a read or a replace for a limited time when
another process has the file open. Hold the store's lock from reading
the log until writing it, and release it before starting an update. The
update reads the log again after its download, so it keeps wheels
recorded meanwhile. A run with no update due still only reads.
The update read the log without the lock before its download. On Windows
that read can miss the log while another run replaces it, and the update
then wrote the log back without its periodic and manual entries.

It also took the periodic and manual entries only from that first read.
When a periodic update finished during a manual one and logged a pinned
wheel as periodic, the manual update dropped it from the log, although
main kept it.

Read the log under the lock before the download too, and after it keep
every entry the update did not take from its first read. On POSIX, give
the replacement the group and mode of the log it replaces, as the write
in place did, so other users of a shared folder can still read it.
A manual --upgrade-embed-wheels run that finished while a periodic update
was downloading lost its pick: the periodic update logged the same wheel
as periodic again, so it waited out the grace period, or listed its own
older wheel first, so it won once that period passed.

The periodic update now treats a wheel another run marked manual
meanwhile as if that run finished last: the wheel stays manual and moves
to the front of the log. Entries match by wheel name, so another build
of the same wheel from a custom index counts too.
@gaborbernat gaborbernat added the bug label Dec 4, 2026
@gaborbernat
gaborbernat marked this pull request as ready for review December 4, 2026 17:26
@gaborbernat
gaborbernat merged commit 4d5e5ac into pypa:main Dec 4, 2026
76 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants