Repository navigation
Clear the metadata directory cache before scanning installed records - #10797
Conversation
importlib.metadata caches each directory listing, so a dist-info that appeared after an earlier scan in the same process -- a manifest write, an interrupted uninstall -- stayed invisible. verify_install then saw only the healthy record, and a damaged install verified as healthy. The malformed-metadata fallback in _installed_metadata_records could never fire for such a record.
|
Confirmed this hits studio/install_manifest.py where _installed_metadata_records scans through a stale directory cache, so a dist-info written after an earlier scan in the same process is missed and the install still verifies as healthy. Will get this reviewed. |
MetadataPathFinder.invalidate_caches only became a classmethod in CPython 3.11.9 and 3.12.3 (gh-116811, backported as GH-116865 / GH-116864). It was never backported to 3.10, which was security-only by then, and 3.9 has no such method at all. Calling it on the CLASS therefore raises TypeError: MetadataPathFinder.invalidate_caches() missing 1 required positional argument: 'cls' on 3.10.*, on 3.11.0 through 3.11.8 and on 3.12.0 through 3.12.2. Nothing in _installed_metadata_records catches it, so installed_versions, invalid_metadata_paths and verify_install all died there instead of reading any metadata at all. Measured across 12 interpreters: the scan crashes on 3.9.25, 3.10.19, 3.11.8 and 3.12.2, and works from 3.11.9 and 3.12.3 onward. No CI leg runs 3.10 or 3.9, and setup-python resolves '3.11' / '3.12' to the newest patch, which is patched, so the matrix could not see this. Going through an instance binds either shape, so the call works on 3.9 through 3.14 including both free-threaded builds. The getattr covers 3.9, whose FastPath does no caching and so has nothing to drop. importlib.invalidate_caches() is not an alternative: it reaches this cache only through PathFinder's delegation, which the same patch added, so it silently no-ops on exactly the releases that need it. That is also why the installer's own importlib.invalidate_caches() calls before installed_versions() could not help, and why the scan clears the cache itself rather than trusting the caller. Tests: the existing malformed-metadata test depends on the scan directory's mtime advancing between the two scans, so it passes without the fix on any nanosecond-granularity filesystem. test_a_metadata_record_added_since_the_last_scan_is_seen restores the mtime instead, which reproduces the staleness on every filesystem. The two compatibility tests reproduce the pre-3.11.9 and the 3.9 shapes, and test_a_healthy_install_still_verifies_after_repeated_checks guards the other direction, since a false studio_install_metadata_conflict makes the desktop preflight start a full managed reinstall on launch. Verified: 31 edge cases x 12 interpreters give byte-identical results before and after this change, so detection is not widened for healthy trees.
|
Reviewed this end to end and pushed a fix to the branch (925f2d0). Summary of what I found and what I ran. The bug is real, and the PR diagnoses it correctly
One correction to the description: the cited reproduction is environment-specific. Creating a directory normally does advance the mtime on a nanosecond-granularity filesystem, so
Where it actually bites users
What needed fixingThe class-level call crashes on exactly those interpreters.
No CI leg runs 3.10 or 3.9, and The fix calls through an instance, which binds either shape, with a It does not widen detectionThis matters because a false
CostClearing the cache is global, and
Per probe on 3.12.12; about +10 to +20%, or +2 to +3 ms per scan at a realistic size. Acceptable against the desktop preflight's 10 second budget, but worth knowing. Tests addedThe existing malformed-metadata test cannot fail on a nanosecond-granularity filesystem, so it is joined by four that can:
Gates
No GPU, browser or UI axis applies here: the module imports no torch, opens no socket and touches no frontend, and this diff does not change any Left alone, deliberatelyThree adjacent things are real but out of scope for a change that gates destructive repair:
|
Comments and docstrings only, verified by comparing the AST of both revisions with docstrings blanked: identical for both files. 82 comment lines down to 76 in install_manifest.py, and the four new test docstrings cut roughly in half, keeping why the cache goes stale, why the call goes through an instance, and why the caller cannot do it instead.
|
Cross-platform results are in. All three green, on real filesystems, with the four new tests genuinely executing rather than being skipped.
43 is the full file with nothing skipped, and it matches the local count exactly. Worth stating explicitly because the per-OS harness has branches that rewrite a nonzero exit code when a test only failed for a missing dependency: I parsed the emitted log lines on each runner and none of those branches executed, so these are real passes and not a forgiven red. That completes the OS axis. Together with the 12-interpreter sweep in the description, the matrix that actually governs this code path is covered: Python patch version against the gh-116811 boundary, filesystem timestamp granularity, and OS. Two honest limits on the coverage, rather than implying more than was run:
No GPU or browser axis applies. The module imports no torch, opens no socket and touches no frontend, and this diff changes no |
|
@codex security review |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Codex Review: Didn't find any major issues. You're on a roll. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
🛡️ Codex Security ReviewSecurity review completed. No security issues were found in this pull request. Reviewed commit: Only the user who started this review can view the report in Codex. ℹ️ About Codex security reviews in GitHubThis is an experimental Codex feature. Security reviews are triggered when:
Once complete, Codex will leave suggestions, or a comment if no findings are found. |
Comments and docstrings only. comment_tools.py check --strip-docstrings passes on both files. install_manifest.py drops to 5 comment lines, and the four new test docstrings to one or two lines each, keeping why the cache goes stale, why the call goes through an instance, and why the caller cannot do it instead.
|
On UI evidence: I checked whether this PR changes what Studio shows, and it does not. Recording the reasoning rather than attaching a before/after pair, because a pair would be two identical images and would read as proof of something it did not test. Selection here is by visible effect, not by file path, so "it touches no frontend files" is not the argument. The argument is the call path. The UI reaches this code in exactly one way: Verified rather than assumed, one
Identical in all 21 cells, so the preflight disposition, the auto-repair decision and the frontend branch that consumes it cannot differ. The diff also adds no new Two smaller checks while I was in here. Instantiating |
|
Closing the loop on the production claim, because I had been asserting it from code reading rather than measurement. It reproduces, and it is worse than I described.
Truth on disk is 1.1 in every row. The split falls exactly on the gh-116811 boundary, which is the proof that The answer is That is the concrete user-visible consequence, and it is why the invalidation belongs in the scan rather than in the caller. The four call sites that currently invalidate before scanning ( Probe is |
|
Codex Review: Didn't find any major issues. Keep them coming! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
The comment claimed 3.9 lacks invalidate_caches entirely, which is wrong: MetadataPathFinder has no own implementation there, but inherits a no-op from importlib.abc.MetaPathFinder, so the getattr guard passes on every supported version and calls that no-op. Harmless and correct, because 3.9's FastPath does no mtime-keyed caching and so has nothing to drop, but the stated reason was inaccurate. Comment only; AST unchanged at 391 statements.
|
Ran a much harder verification pass on the "is this purely hardening" question, including five independent adversarial reviews. Short answer: for any fixed, readable on-disk state the behaviour is provably identical, and the update path from old releases cannot be affected at all. I am not going to call it "zero effect under every condition", because one narrow qualification turned up and it is more honest to state it than to round it away. Details below. Nine OS legs, run in parallel
Eight legs give a verdict and all eight are green, including the platforms this change does not touch. WSL is the Linux kernel over ext4 or 9p and is represented by the Linux legs; MLX is macOS-only and the Mac legs cover that host, though note this suite exercises the metadata scan, not MLX itself. Deterministic routing, not just equal outputEqual output can hide a different route to the same answer, so I traced every line executed inside 21 of 21 cells have a byte-identical route hash. Same functions, same branches, same order, same step counts (for example AST, at statement levelRather than "the dumps differ", enumerated which statements moved. Against merge base
All four inside Updating from an old release cannot be affectedThis was the question I most wanted a hard answer to, and it has one. So a user on v0.1.701-beta runs that release's own For old state read by new code: The one qualification I will not round awayA reviewer injected an
Identical on the first row, and the first row is every UI and CLI entry point, since One suggestion rejected, with evidenceTwo reviewers suggested also calling One comment was wrong, now fixed
Cost, and the honest bound on itPer Follow-ups, still not in this PR
|
|
Codex Review: Didn't find any major issues. Delightful! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
What
_installed_metadata_recordsenumerates installed distributions throughimportlib.metadata.distributions(), which caches each directory listing. A*.dist-infothat appears after an earlier scan in the same process -- a manifest write, an interrupted uninstall -- therefore stayed invisible toverify_install. It saw only the healthy record and reportedmanifest_ok: Truefor a damaged install, so the malformed-metadata fallback in that same function could never fire.Reproduction
tests/studio/install/test_install_manifest.py::test_malformed_matching_metadata_invalidates_the_manifestwrites the manifest, then creates a matchingdemo-2.0.dist-infowhoseMETADATAis invalid UTF-8 (b"\xff\xfe"), and assertsmanifest_ok is Falsewith reasonstudio_install_metadata_conflict.Before:
1 failed--assert True is Falseat line 210.After:
1 passed.Instrumenting the module made the disconnect explicit. Inside the test,
installed_versions("demo")returned['1.0']-- the malformed record missing entirely -- while a fresh process that created both records before the first scan returned['', '1.0']and correctly reported the conflict. The difference is only whether an earlier scan had already populated the cache.Fix
Call
MetadataPathFinder.invalidate_caches()before the scan, so a directory that appeared since an earlier scan is seen.Verification
A100-PCIE-40GB, torch 2.8.0+cu128, Python 3.12:
1 passed(was1 failed)tests/studio/install/test_install_manifest.py: 39 passedtests/studio/install/: 3506 passed, 529 skippedI searched issues and PRs for this and did not find an existing report.
Note
The other failure in that suite,
tests/studio/test_gpu_inference_smoke.py::test_gpu_generation_smoke, is an unrelated hang in the hub fetch; dealt with separately in #10796.Maintainer update (danielhanchen)
Took this over and pushed two commits: 925f2d0 (the compatibility fix plus tests) and a9196c6 (comment trim, comments and docstrings only, AST verified identical).
What changed from the original patch
MetadataPathFinder.invalidate_cachesonly became a classmethod in CPython 3.11.9 and 3.12.3 (gh-116811, backported as GH-116865 and GH-116864). It was never backported to 3.10, which was security-only by then, and 3.9 has no such method. Calling it on the class therefore raisedTypeError: missing 1 required positional argument: 'cls'on 3.10.*, on 3.11.0 through 3.11.8 and on 3.12.0 through 3.12.2, takinginstalled_versions,invalid_metadata_pathsandverify_installdown with it. The call now goes through an instance, which binds either shape, with agetattrfor 3.9.importlib.invalidate_caches()is not an alternative: it reaches this cache only throughPathFinder's delegation, which the same patch added, so it silently no-ops on exactly the releases that need it.Correction to the reproduction above
The listing cache is keyed on the scan directory's
st_mtime, and creating adist-infonormally advances that mtime, so the cited test passes onmainon any nanosecond-granularity filesystem (XFS, ext4, APFS), both alone and as a whole file. The bug needs the mtime to be unchanged between the two scans. The newtest_a_metadata_record_added_since_the_last_scan_is_seenrestores it withos.utime, which reproduces the staleness on every filesystem.Why it matters in production
studio/install_python_stack.py:6645,:6772,:6826and:6872callimportlib.invalidate_caches()right after apip --force-reinstallor uninstall, then callinstall_manifest.installed_versions(name). On the unpatched releases above that invalidation does nothing for metadata, so the repair loop reads a stale listing. Clearing the cache inside the scan is what makes those four sites correct.Verification
Detection is not widened, which matters because a false
studio_install_metadata_conflictis auto-repairable in release builds and starts a full managed reinstall on launch:METADATA, a stem with no hyphen,.egg-info, pip~backups, case variants, underscore-vs-hyphen canonicalisation, unicode and 200-character names, an emptydist-info, a missing scan dir, thelib64 -> libdedupe, an empty scan-path list widening tosys.path, and a zip on the scan path.manifest_ok is Trueon four consecutiveverify_installcalls on every interpreter.distributions(): 0 errors, one consistent result, on all 12 interpreters including both free-threaded builds.Cost of the global cache clear, per
installed_version_probe(up to 4 scans) on 3.12.12: 8.9 to 10.5 ms at 50 packages, 66.4 to 78.3 ms at 400, 347 to 397 ms at 2000. Roughly 10 to 20 percent, or 2 to 3 ms per scan at a realistic size.Suites:
tests/studio/install/4029 passed,tests/python/test_install_python_stack.py189 passed,unsloth_cli/tests1405 passed.ruff checkclean,scripts/run_ruff_format.pya byte-level fixed point, import-hoist and duplicate-definition lints clean. Cross-platform:test_install_manifest.py43 passed onwindows-latest(real NTFS, Python 3.12.10);ubuntu-latestandmacos-15results to follow.Follow-ups, not in this PR
missing_requirementsuses baredistribution(name)with no path restriction and no invalidation, and runs insideverify_installbefore the invalidation, so one call can read two cache generations._scan_payload_filesandunsloth_cli/_studio_deps.py:472, an independent re-implementation of the same scan, never invalidate.PYTHON_FLOOR: '3.10'andrequires-python = ">=3.9", andsetup-pythonresolves '3.11' and '3.12' to the newest patch. That gap is what let this through.