Skip to content

Clear the metadata directory cache before scanning installed records - #10797

Merged
danielhanchen merged 6 commits into
unslothai:mainfrom
xy200303:fix/manifest-metadata-cache
Sep 13, 2026
Merged

danielhanchen merged 6 commits into
unslothai:mainfrom
xy200303:fix/manifest-metadata-cache

Conversation

@xy200303

@xy200303 xy200303 commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

What

_installed_metadata_records enumerates installed distributions through importlib.metadata.distributions(), which caches each directory listing. A *.dist-info that appears after an earlier scan in the same process -- a manifest write, an interrupted uninstall -- therefore stayed invisible to verify_install. It saw only the healthy record and reported manifest_ok: True for 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_manifest writes the manifest, then creates a matching demo-2.0.dist-info whose METADATA is invalid UTF-8 (b"\xff\xfe"), and asserts manifest_ok is False with reason studio_install_metadata_conflict.

Before: 1 failed -- assert True is False at 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:

  • target test: 1 passed (was 1 failed)
  • tests/studio/install/test_install_manifest.py: 39 passed
  • tests/studio/install/: 3506 passed, 529 skipped

I 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_caches only 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 raised TypeError: 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, taking installed_versions, invalid_metadata_paths and verify_install down with it. The call now goes through an instance, which binds either shape, with a getattr for 3.9.

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.

Correction to the reproduction above

The listing cache is keyed on the scan directory's st_mtime, and creating a dist-info normally advances that mtime, so the cited test passes on main on 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 new test_a_metadata_record_added_since_the_last_scan_is_seen restores it with os.utime, which reproduces the staleness on every filesystem.

Why it matters in production

studio/install_python_stack.py:6645, :6772, :6826 and :6872 call importlib.invalidate_caches() right after a pip --force-reinstall or uninstall, then call install_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

interpreter before original patch now
3.9.25 no listing cache, fresh TypeError fresh
3.10.19 stale TypeError fresh
3.11.8 stale TypeError fresh
3.11.9 stale fresh fresh
3.12.2 stale TypeError fresh
3.12.3 stale fresh fresh
3.11.14, 3.12.12, 3.13.12, 3.14.3 stale fresh fresh
3.13.12t, 3.14.3t free-threaded stale fresh fresh

Detection is not widened, which matters because a false studio_install_metadata_conflict is auto-repairable in release builds and starts a full managed reinstall on launch:

  • 31 edge cases across 12 interpreters, byte-identical before and after. Covers duplicate records, missing, undecodable and nameless METADATA, a stem with no hyphen, .egg-info, pip ~ backups, case variants, underscore-vs-hyphen canonicalisation, unicode and 200-character names, an empty dist-info, a missing scan dir, the lib64 -> lib dedupe, an empty scan-path list widening to sys.path, and a zip on the scan path.
  • A healthy tree reports manifest_ok is True on four consecutive verify_install calls on every interpreter.
  • Repair converges rather than looping: healthy, conflict, healthy, healthy.
  • 6 scanning threads against 2 threads iterating 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.py 189 passed, unsloth_cli/tests 1405 passed. ruff check clean, scripts/run_ruff_format.py a byte-level fixed point, import-hoist and duplicate-definition lints clean. Cross-platform: test_install_manifest.py 43 passed on windows-latest (real NTFS, Python 3.12.10); ubuntu-latest and macos-15 results to follow.

Follow-ups, not in this PR

  1. missing_requirements uses bare distribution(name) with no path restriction and no invalidation, and runs inside verify_install before the invalidation, so one call can read two cache generations.
  2. _scan_payload_files and unsloth_cli/_studio_deps.py:472, an independent re-implementation of the same scan, never invalidate.
  3. No CI leg runs 3.10 or 3.9 despite PYTHON_FLOOR: '3.10' and requires-python = ">=3.9", and setup-python resolves '3.11' and '3.12' to the newest patch. That gap is what let this through.

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.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member

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.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 13, 2026
@danielhanchen

Copy link
Copy Markdown
Member

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

importlib.metadata memoises each directory listing against the scan directory's st_mtime. When that mtime does not move between two scans, a dist-info created in between stays invisible and a damaged install verifies as healthy.

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 tests/studio/install/test_install_manifest.py::test_malformed_matching_metadata_invalidates_the_manifest passes on main on XFS/ext4/APFS, both as a single test and as a whole file. The bug needs the mtime, as the cache key observes it, to be unchanged. Restoring it with os.utime reproduces it deterministically everywhere:

second scan conflict detected
before ['1.0'] False
after ['', '1.0'] True

Where it actually bites users

studio/install_python_stack.py:6645, :6772, :6826 and :6872 call importlib.invalidate_caches() right after a pip --force-reinstall or uninstall, then call install_manifest.installed_versions(name). That invalidation reaches this cache only through PathFinder's delegation, which gh-116811 added in 3.11.9 / 3.12.3 -- so on 3.10, on 3.11 before 3.11.9 and on 3.12 before 3.12.3 it does nothing for metadata and the repair loop reads a stale listing. Clearing the cache inside the scan, as this PR does, is what makes those four sites correct; it supersedes them rather than duplicating them.

What needed fixing

The class-level call crashes on exactly those interpreters. MetadataPathFinder.invalidate_caches only became a classmethod in 3.11.9 and 3.12.3 (gh-116811, backported as GH-116865 / GH-116864), never to 3.10 or 3.9. Measured on 12 interpreters against a synthetic site-packages, running the real module:

interpreter before the PR PR as submitted with 925f2d0
3.9.25 no listing cache, fresh TypeError fresh
3.10.19 stale TypeError fresh
3.11.8 stale TypeError fresh
3.11.9 stale fresh fresh
3.12.2 stale TypeError fresh
3.12.3 stale fresh fresh
3.11.14, 3.12.12, 3.13.12, 3.14.3 stale fresh fresh
3.13.12t, 3.14.3t (free-threaded) stale fresh fresh

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. scripts/lint_backend_python_floor.py runs vermin at -t=3.10 but only over studio/backend/** and unsloth_cli/**, and in any case this is a patch-level runtime semantic that no static check can detect.

The fix calls through an instance, which binds either shape, with a getattr for 3.9 (whose FastPath does no caching, so there is nothing to drop).

It does not widen detection

This matters because a false studio_install_metadata_conflict is expensive: preflight.rs:101 marks it auto-repairable in release builds, so use-tauri-backend.ts:302 starts a full managed reinstall on launch, and it also gates _repair_duplicate_core_metadata.

  • 31 edge cases x 12 interpreters, byte-identical before and after. Covers duplicate records, missing/undecodable/nameless METADATA, a stem with no hyphen, .egg-info, pip ~ backups, case variants, underscore-vs-hyphen canonicalisation, unicode and 200-character names, an empty dist-info, a missing scan dir, the lib64 -> lib dedupe, an empty scan-path list widening to sys.path, and a zip on the scan path.
  • A healthy tree stays healthy: manifest_ok is True on four consecutive verify_install calls, on every interpreter.
  • Repair converges, no loop: healthy -> studio_install_metadata_conflict -> healthy -> healthy.
  • Concurrency: 6 scanning threads against 2 threads iterating distributions(), 0 errors and one consistent result, on all 12 interpreters including both free-threaded builds.

Cost

Clearing the cache is global, and installed_version_probe(pkg, ("unsloth-zoo",)) does up to 4 scans, so it is not free:

site-packages size before after
50 packages 8.9 ms 10.5 ms
400 packages 66.4 ms 78.3 ms
2000 packages 347 ms 397 ms

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 added

The existing malformed-metadata test cannot fail on a nanosecond-granularity filesystem, so it is joined by four that can:

  • test_a_metadata_record_added_since_the_last_scan_is_seen -- restores the mtime, so the staleness reproduces on any filesystem. Fails before the PR.
  • test_the_metadata_scan_survives_a_pre_classmethod_invalidate_caches -- reproduces the pre-3.11.9 shape. Fails on the PR as submitted.
  • test_the_metadata_scan_survives_a_finder_without_invalidate_caches -- the 3.9 shape. Fails on the PR as submitted.
  • test_a_healthy_install_still_verifies_after_repeated_checks -- guards the false-positive direction.

Gates

tests/studio/install/ 4029 passed / 6 skipped, tests/python/test_install_python_stack.py 189 passed, unsloth_cli/tests 1405 passed / 6 skipped, ruff check clean, scripts/run_ruff_format.py a byte-level fixed point, verify_import_hoist.py and lint_duplicate_definitions.py clean, lint_backend_python_floor.py OK. Cross-platform staging CI is running test_install_manifest.py on ubuntu-latest, macos-15 and windows-latest, which is the only way to exercise real NTFS and APFS; I will follow up with those results.

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 reason string, so the Rust preflight and the TS frontend see identical input.

Left alone, deliberately

Three adjacent things are real but out of scope for a change that gates destructive repair:

  1. missing_requirements (install_manifest.py:505) uses bare distribution(name) with no path restriction and no invalidation, and runs at verify_install before the invalidation, so one verify_install can read two cache generations.
  2. _scan_payload_files and unsloth_cli/_studio_deps.py:472, an independent re-implementation of the same scan, never invalidate.
  3. No CI leg runs 3.10 or 3.9 despite PYTHON_FLOOR: '3.10' and requires-python = ">=3.9". That gap is what let this through and deserves its own PR.

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.
@danielhanchen

Copy link
Copy Markdown
Member

Cross-platform results are in. All three green, on real filesystems, with the four new tests genuinely executing rather than being skipped.

runner filesystem python result
ubuntu-latest ext4 3.12.14 43 passed in 4.00s
macos-15 (Apple Silicon) APFS 3.12.10 43 passed in 2.78s
windows-latest NTFS 3.12.10 43 passed in 5.92s

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. install_manifest.py is stdlib-only, so it could not have been excused that way in any case.

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:

  • FAT and HFS+ coarse granularity is simulated, not mounted. Unprivileged loopback mount was unavailable, so the mtime is quantised with os.utime instead. That is faithful because the cache key is literally os.stat(root).st_mtime, and the simulation only reproduces the bug when both scans land in one tick, which is the real trigger.
  • WSL is the Linux kernel over ext4 or 9p and is covered by the ubuntu-latest leg, not by a dedicated runner.

No GPU or browser axis applies. The module imports no torch, opens no socket and touches no frontend, and this diff changes no reason string, so the Rust preflight and the TS frontend receive identical input.

@danielhanchen

Copy link
Copy Markdown
Member

@codex security review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 13, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-13T14:49:21.032075Z b06a10d Manual request
🔒 Security Review ✅ Completed 2026-09-13T13:25:16.215954Z a9196c6 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: a9196c6b40

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

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".

@chatgpt-codex-connector

Copy link
Copy Markdown

🛡️ Codex Security Review

Security review completed. No security issues were found in this pull request.

Reviewed commit: a9196c6b40

View security finding report

Only the user who started this review can view the report in Codex.

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

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.
@danielhanchen

Copy link
Copy Markdown
Member

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: studio/src-tauri/src/preflight/managed.rs:442 spawns unsloth studio desktop-capabilities --json as a subprocess and reads studio_install_reason out of it. That is a fresh interpreter per launch, so it only ever performs a first scan, and a first scan has no cache that could be stale. The divergence this PR fixes needs a second scan in the same process after a mutation that left the directory mtime unmoved, which is the installer's pattern, not the preflight's.

Verified rather than assumed, one verify_install per process to mirror the subprocess probe, on 3.10.19, 3.12.12 and 3.13.12:

tree state before after
healthy None None
duplicate records studio_install_metadata_conflict studio_install_metadata_conflict
malformed METADATA studio_install_metadata_conflict studio_install_metadata_conflict
nameless record studio_install_metadata_conflict studio_install_metadata_conflict
pip ~ backup studio_install_metadata_conflict studio_install_metadata_conflict
package absent studio_install_damaged studio_install_damaged
no manifest studio_install_incomplete studio_install_incomplete

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 reason value, so there is no new string for the Rust or TS side to render.

Two smaller checks while I was in here. Instantiating MetadataPathFinder and calling the method emits no warning on 3.9, 3.10, 3.11.9, 3.12.12, 3.13.12 or 3.14.3, which matters because the attribute is a plain function on 3.10, a classmethod from 3.11.9, and inherited or absent on 3.9; a DeprecationWarning would have turned into a failure under a -W error config. And the comment passes are AST-gated: comment_tools.py check --strip-docstrings reports code unchanged on both files for both of them.

@danielhanchen

Copy link
Copy Markdown
Member

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.

studio/install_python_stack.py:6645 runs a --force-reinstall, then importlib.invalidate_caches(), then any(install_manifest.installed_versions(name)), and treats an empty answer as "no longer installed". I modelled exactly that sequence: scan once earlier in the process, replace demo-1.0.dist-info with demo-1.1.dist-info, leave the directory mtime where it was, call importlib.invalidate_caches(), rescan.

python before after
3.10.19 [''] ['1.1']
3.11.8 [''] ['1.1']
3.11.9 ['1.1'] ['1.1']
3.12.2 [''] ['1.1']
3.12.3 ['1.1'] ['1.1']
3.13.12 ['1.1'] ['1.1']

Truth on disk is 1.1 in every row. The split falls exactly on the gh-116811 boundary, which is the proof that importlib.invalidate_caches() is the thing failing: from 3.11.9 and 3.12.3 it delegates to MetadataPathFinder and the existing call already works, so the fix is a no-op there. Before those it is a no-op for metadata and the rescan answers from the pre-reinstall listing.

The answer is [''], not [], and that detail matters. The stale listing still names demo-1.0.dist-info, but that directory is gone, so its METADATA cannot be read, the path-stem fallback classifies it as a nameless matching record, and it comes back with an empty version. So on those interpreters a successful reinstall produced both failure modes at once: any(...) is false, so the installer reports the package missing and keeps looping, and metadata_conflict(['']) is true, so the same state reads as a metadata conflict. A healthy venv is described as damaged by a record that no longer exists.

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 (:6645, :6772, :6826, :6872) cannot fix themselves, because the API they are calling is the one that does not reach this cache on the affected releases.

Probe is installer_loop_probe.py in my scratch tree if anyone wants to re-run it; it needs no pip and no network, since install_manifest.py is stdlib-only.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: e52108205f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

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".

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 13, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 13, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 13, 2026
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.
@danielhanchen

Copy link
Copy Markdown
Member

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

runner filesystem result
ubuntu-latest ext4 43 passed
ubuntu-22.04 ext4 43 passed
ubuntu-24.04-arm ext4 (ARM64) 43 passed
macos-15 APFS (Apple Silicon) 43 passed
macos-26 APFS (Apple Silicon) 43 passed
macos-15-intel APFS (x86_64) 43 passed
windows-latest NTFS 43 passed
windows-2022 NTFS 43 passed
windows-11-arm NTFS (ARM64) no signal, see below

Eight legs give a verdict and all eight are green, including the platforms this change does not touch. windows-11-arm failed, and it is not this PR: it dies in pip install -r studio/backend/requirements/studio.txt with No matching distribution found for sqlite-vec==0.1.9, zero pytest lines, so it never reached the suite. sqlite-vec 0.1.9 publishes wheels only for macosx_10_6_x86_64, macosx_11_0_arm64, manylinux_2_17_aarch64, manylinux_2_17_x86_64 and win_amd64, with no sdist, so that pin cannot install on Windows ARM64 at any commit. publish-desktop-updater.yml:395 also shows the shipped targets are darwin-aarch64, linux-x86_64 and windows-x86_64, so Windows ARM64 is not a release platform. Flagging the pin as a separate finding, not fixing it here.

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 output

Equal output can hide a different route to the same answer, so I traced every line executed inside install_manifest and hashed the sequence, normalising away only the lines this PR adds. Seven tree states across 3.10.19, 3.12.12 and 3.13.12:

21 of 21 cells have a byte-identical route hash. Same functions, same branches, same order, same step counts (for example healthy 229 steps, no_manifest 36 steps, matching exactly on both sides).

AST, at statement level

Rather than "the dumps differ", enumerated which statements moved. Against merge base 8ee07d6ae, studio/install_manifest.py goes 389 to 391 statements:

  • added: If: if getattr(MetadataPathFinder, 'invalidate_caches', None) is not None:
  • added: Expr: MetadataPathFinder().invalidate_caches()
  • added: ImportFrom: from importlib.metadata import MetadataPathFinder, distributions
  • removed: ImportFrom: from importlib.metadata import distributions

All four inside _installed_metadata_records. Nothing else in the file moved. No subprocess, pip or uv invocation, shell command, environment variable, file write or network call is added or altered anywhere in the diff.

Updating from an old release cannot be affected

This was the question I most wanted a hard answer to, and it has one. unsloth_cli/_studio_deps.py:48-73 loads install_manifest.py by file path out of the managed venv's own site-packages, and caches it in _MANIFEST_LOADED for the process. studio is in the packaged include list (pyproject.toml:82), so each install ships its own copy.

So a user on v0.1.701-beta runs that release's own install_manifest.py for the whole of their update run. This change does not exist in those bytes and cannot alter that run. It takes effect only from the next process onward, where it is proven output-identical and route-identical for a fixed disk state.

For old state read by new code: MANIFEST_SCHEMA is still 1 and no schema, payload key, marker or reason string changed. One reviewer reproduced this specifically against the v0.1.701-beta manifest writer and found no new false-damage classification for consistent metadata. Shortcut refresh, auth provisioning and the bootstrap-password flow are untouched (unsloth_cli/commands/studio.py:3781, :1182). The preflight rule is unchanged: studio_install_ok != true still maps to stale, and release builds still allow repair; only the input to that rule could ever differ, and it does not for a fixed disk state.

The one qualification I will not round away

A reviewer injected an OSError from os.listdir and found that where the old code's warm cache masked the failure, the new code re-reads, CPython suppresses the error inside FastPath.children(), discovery returns nothing, and verify_install fail-opens to manifest_ok: True. I reproduced it, and then asked the question the report did not: what does the old code do when the failing scan is the first in the process?

case before after
first scan in a fresh process, listdir failing None None
scan 1 succeeds, scan 2 fails, same process studio_install_metadata_conflict None

Identical on the first row, and the first row is every UI and CLI entry point, since desktop-capabilities, verify-install and the setup fast path are each a fresh process. So the fail-open under enumeration failure is pre-existing, not introduced here; the old code was only accidentally immune when a prior scan in the same process had already succeeded. The change makes a repeat scan agree with what a cold process already did. The direction is fail-open (reports healthy), so it cannot cause a spurious reinstall. The underlying fail-open in verify_install is worth its own look and I have listed it as a follow-up.

One suggestion rejected, with evidence

Two reviewers suggested also calling importlib.invalidate_caches() to cover third-party metadata finders. Not doing it: Distribution._discover_resolvers consults only find_distributions on sys.meta_path entries, and none of the eight finders this repo registers (_VllmLoraTokenizerStubFinder, _BnbCudaSpecsPatchFinder, _CausalConv1dImportBlockerFinder, _VllmImportBlockerFinder, _TorchaoNF4AliasFinder, _TorchaoIntmmPatchFinder x2, _StubSubpackageFinder) defines it, so none can contribute a metadata record or hold a cache that needs dropping. It would also be a no-op for metadata on precisely the old releases that matter, while clearing the whole import system's caches on every scan.

One comment was wrong, now fixed

b06a10d5 corrects it. The comment claimed 3.9 "lacks it entirely", justifying the getattr. That is inaccurate: MetadataPathFinder has no own implementation on 3.9 but inherits a no-op from importlib.abc.MetaPathFinder, so the guard passes on every supported version, 3.9 included, and calls that no-op. Harmless and correct, because 3.9's FastPath does no mtime-keyed caching, but the stated reason was not true. Verified on 3.9 through 3.14. Comment only, AST unchanged at 391 statements.

Cost, and the honest bound on it

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. A reviewer correctly pointed out that any added cost can flip an enclosing deadline: the capability probe budget is 10 s, so a probe already at 9.995 s could cross it. That is true of any nonzero cost and there is no evidence of a practical regression on an install that was passing comfortably, but it is a real bound rather than zero, so I am stating it rather than claiming free.

Follow-ups, still not in this PR

  1. missing_requirements uses bare distribution(name) with no path restriction and no invalidation, and runs inside verify_install before the invalidation, so one call can read two cache generations.
  2. _scan_payload_files and unsloth_cli/_studio_deps.py:472, an independent re-implementation of the same scan, never invalidate.
  3. verify_install fail-opens to healthy when discovery returns nothing, which is how a transient enumeration failure reads as a good install.
  4. No CI leg runs 3.10 or 3.9 despite PYTHON_FLOOR: '3.10', which is the gap that let the original defect through.
  5. sqlite-vec==0.1.9 is uninstallable on Windows ARM64 (no wheel, no sdist).

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Delightful!

Reviewed commit: b06a10d5ce

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

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".

@danielhanchen
danielhanchen merged commit f29beb2 into unslothai:main Sep 13, 2026
1 check passed
@xy200303
xy200303 deleted the fix/manifest-metadata-cache branch September 14, 2026 02:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants