Skip to content

Repair .venv_t5_* sidecars whose files are damaged - #7725

Merged
danielhanchen merged 16 commits into
mainfrom
fix-sidecar-file-integrity
Aug 2, 2026
Merged

danielhanchen merged 16 commits into
mainfrom
fix-sidecar-file-integrity

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Aug 1, 2026 •

Copy link
Copy Markdown
Member

Fixes #7715.

The .venv_t5_* sidecar targets were validated by three checks only: the directory is non-empty, the package directory exists, and .dist-info/METADATA carries the expected Version:. Nothing looked at file contents.

That predicate is the sole gate on the self-heal that already exists:

def _ensure_venv_dir(venv_dir, packages, label) -> bool:
    if _venv_dir_is_valid(venv_dir, packages):
        return True
    logger.warning("%s not found or incomplete at %s -- installing at runtime", label, venv_dir)
    shutil.rmtree(venv_dir, ignore_errors = True)
    ...

So a truncated or deleted file inside an otherwise-intact sidecar was neither detected nor repaired. activate_transformers_for_subprocess prepends the directory to sys.path anyway, and the export, inference or training worker then dies on import with an error that points at transformers rather than at a damaged install. A whole missing package directory was caught by the existence check; only sub-file damage slipped through.

The check

_sidecar_damaged_files compares each distribution's RECORD against the filesystem, with the semantics already settled for the update-time check in unsloth_cli/_studio_deps.py:

  • only shrinkage and disappearance count
  • .dist-info / .egg-info / .pyc and trailing-slash directory rows are skipped
  • rows with a blank size field keep their existence check
  • multiply-owned paths skip the size comparison but not the existence check
  • entries must resolve to a regular file, since an empty directory is commonly 4096 bytes and would otherwise clear a shrinkage test

Where it is wired in, and where it deliberately is not

Only at the three sites that can actually repair: _ensure_venv_dir, _ensure_venv_t5_latest_exists and ensure_latest_transformers_venv.

_latest_sidecar_intact keeps the cheap predicate. It is called from _config_model_types on the config-cache hit path, which check_upgrade_for_model reaches several times per POST /validate request. Scanning there would be per-request work with nothing to show for it, since that path routes rather than repairs.

An earlier revision of this description said damage on the latest tier would simply be caught one step later, as a named failure instead of an ImportError. That was wrong, and review caught it. Repairs run in the parent, so a worker child that finds the sidecar damaged logs "retry after the parent repairs the sidecar" and returns; but the parent's routing self-heal was gated on the same package-level predicate, which cannot see a truncated or deleted file. Nothing ever told the parent, so every retry failed forever. Reproduced through the pre-existing API alone:

scenario repairs worker retries failed healed
damage already present at startup, cold cache 0 5/5 no
damage appearing after a mapping was cached 0 5/5 no

The first case does not need a stale cache: a file truncated before the process starts is enough, so a cold boot onto a damaged sidecar deadlocks just as hard.

777d6461a closes it. The child leaves a marker inside the sidecar dir, and the routing self-heal consults the RECORD scan too, but only where a repair can follow it: on a config-cache miss, and outside the failure backoff window. Both limits are pinned by tests that fail the run if the scan is reached, so the hot path stays package level. The marker lives inside the sidecar, so the stage-and-swap that repairs it clears the marker by construction, and a scan finding the sidecar healthy drops a stale marker instead of acting on it. Each scenario then heals in a single repair.

A follow-up round caught a second hole in the same branch, fixed in 1bd4d3d6f. When the parent-side scan found damage and the repair then failed (offline, pip down, workers active), the backoff was recorded but the damage was not, so the next routing call re-evaluated with the package-level predicate, found nothing broken, and handed the damaged sidecar back for the rest of the window. Measured: 4 of 4 routing calls in the window served it, with nothing logged. A failed repair now leaves the same marker the child leaves, which drops that to 0 of 4 while the scan count stays 0, so the window still suppresses pip retries and still never repeats the scan.

A third round found two more ways the handoff was skipped, both fixed in fb2ee730a. The flag was written only on the worker-child branch, which sits below the offline bailout, so an offline child returned recording nothing; the swap-already-running branch had the same hole. Flagging once at the point the sidecar is known broken covers all three exits. Separately, _probe_tier caches per process and its hit path honoured only the kill switch, so a model that reached latest through a probe rather than the config mapping kept returning a cached latest after damage was known, never touching the path that performs the repair. It now falls through to a re-probe while a repair is outstanding.

This does change behaviour in one way worth naming: a synchronous several-hundred-MB reinstall can now be triggered by file damage, which it could not be before. That raises the cost of a false positive from the scan, which is why the zero-findings check below is the one that matters most. UNSLOTH_SKIP_SIDECAR_FILE_CHECK suppresses this path as well.

Scope: all distributions, not just the pinned ones

The sidecar is prepended to sys.path wholesale, so its regex/, requests/, urllib3/, certifi/ shadow the base install and a truncated regex/_regex_core.py breaks import transformers exactly as a damaged transformers/ does. The wider scope costs 4% more rows (7729 vs 7432) and catches cases the narrow one misses: with both a deleted regex/_regex_core.py and a truncated modeling_gemma3.py, all-distributions reports 2 findings and pinned-only reports 1.

Cost, and why there is no cache

Measured against the three live sidecars: 7948 RECORD rows, 22-30 ms each, zero findings. import transformers on the same box is 1.67-1.72 s, so one scan is about 1.3% of the import it immediately precedes, and it warms the dentries that import then needs. The cheap package and version checks still run first, so the common wrong-version case rejects without paying for a scan.

An mtime-marker fingerprint was considered and rejected: truncating a file under transformers/models/ does not change the sidecar's top-level mtime, so the marker would suppress exactly the damage being hunted. Walking every subdirectory's mtime costs the same as the stat scan.

UNSLOTH_SKIP_SIDECAR_FILE_CHECK=1 disables the scan, and every error path fails open (unreadable or absent RECORD, csv.Error, OSError on glob), because a false positive costs a multi-hundred-MB reinstall and a user hitting one should not have to wait for a release.

Duplicated rather than shared

The backend runs with studio/backend on sys.path and never imports unsloth_cli, which may be a different install entirely; there is no directory both can import from without adding one to the other's path. The subjects also differ: the CLI helper describes its own interpreter via importlib.metadata, this one a flat pip --target tree that no interpreter owns, so it globs *.dist-info directly. studio/backend/auth/terminal_prompt.py sets the precedent for exactly this, and the same wording is used so the pair stays greppable.

Verification

Positive control on a throwaway copy of a real sidecar (deleted afterwards; ~/.unsloth was never written):

clean copy  -> []
deleted     -> ['regex: regex/_regex_core.py is missing']
truncated   -> ['regex: regex/_regex_core.py is 512 bytes, expected 147374']
appended    -> []                                   # larger is not damage
dir instead -> ['regex: regex/_regex_core.py is not a regular file']

Zero findings across all three live sidecars. 340 passed in test_transformers_version.py + test_transformers_latest.py, ruff clean. Reverting only the one wiring line in _ensure_venv_dir fails test_ensure_venv_dir_wipes_and_reinstalls_a_damaged_sidecar and nothing else, so the wiring is load-bearing rather than incidental.

Not done, deliberately

studio/setup.sh's _target_has_pkg_version has the same blind spot and is left alone. The runtime path repairs automatically and covers users who never run unsloth studio update, and setup.sh:1145 already forces a sidecar reinstall whenever the base dependency pass runs, so the shell blind spot is only reachable on a fully up-to-date base install, which is the case this change now covers. A RECORD comparison in POSIX sh would mean a CSV parser in awk plus a stat per row over ~2500 rows per sidecar on every update, and a third copy of the predicate to keep in sync.

Two limits worth stating: all timings are warm, since the dentry cache cannot be dropped without root on a shared box; and _ensure_venv_dir repairs with --no-deps, so a repair triggered by damage in a transitive package produces a smaller sidecar than setup.sh builds, with the rest resolving from the base install. That is pre-existing behaviour of the repair path, not new here, and no real repair was executed to confirm the resulting tree imports.

danielhanchen and others added 2 commits August 1, 2026 10:29
The sidecar targets were validated by directory, package directory and
METADATA version only, so a truncated or deleted file inside an otherwise
intact sidecar passed. That predicate is the sole gate on the existing
wipe-and-reinstall in _ensure_venv_dir, so nothing detected the damage and
nothing repaired it; the export, inference or training worker then died on
import, pointing at transformers rather than at a damaged install.

Adds _sidecar_damaged_files, a RECORD-vs-filesystem comparison with the
same semantics as the update-time check in unsloth_cli/_studio_deps.py:
only shrinkage and disappearance count, .dist-info/.egg-info/.pyc and
directory rows are skipped, rows with a blank size keep their existence
check, multiply-owned paths skip the size comparison but not existence,
and entries must resolve to a regular file.

Wired in only at the three sites that can actually repair. The hot path
is left alone deliberately: _latest_sidecar_intact runs several times per
/validate request via _config_model_types, including on the config-cache
hit path, so a scan there would be per-request work with no repair to
show for it.

Scans every distribution in the sidecar rather than the pinned ones,
because the whole directory is prepended to sys.path, so a damaged regex
or urllib3 breaks the import exactly as a damaged transformers does. That
widening costs 4 percent more rows and catches cases the narrow scope
misses.

Measured on the three live sidecars: 7948 RECORD rows, 22-30 ms each,
zero findings. That is about 1.3 percent of the import it precedes, and
it warms the dentries that import then needs. UNSLOTH_SKIP_SIDECAR_FILE_CHECK=1
disables it, and every error path fails open, because a false positive
costs a multi-hundred-MB reinstall.

Duplicated rather than shared with the CLI helper: the backend never
imports unsloth_cli, and the subjects differ (an interpreter's own
environment versus a flat pip --target tree). Same precedent and wording
as auth/terminal_prompt.py.

Fixes #7715
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 1, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 70badd2444

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

recorded = int(row[2])
except ValueError:
recorded = None
target = root / rel

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Handle pip's escaped console-script RECORD paths

When a sidecar is installed through the supported pip fallback, pip install --target records generated console scripts as paths such as ../../bin/hf, even though it places them under <target>/bin. Joining that row directly to root therefore stats a path outside the sidecar and reports the script missing. Because transformers/huggingface_hub provide console scripts, an intact pip-built sidecar will be wiped and reinstalled on every activation, and may become unusable when the subsequent reinstall has no network access; these escaped script rows need to be mapped to the target layout or excluded.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct, and already fixed in 1c92811, which landed after the commit this review looked at (70badd2).

I reproduced it exactly as you describe: on a healthy pip install --target sidecar the scripts are present in <target>/bin while RECORD carries ../../bin/hf, and the scan reported idna: ../../bin/idna is missing. Your point about the reinstall is the sharper half, and it is what makes this worse than the bug the PR set out to fix: the repair reinstalls with the same pip, which writes the same rows, so it never converges.

Rows landing in bin/ or Scripts/ are excluded too. uv records bin/hf, which does resolve, but pip's --upgrade rmtree's a colliding directory in the target, so a later install into the same sidecar deletes an earlier package's scripts. Nothing is lost by excluding them: the sidecar is only ever prepended to sys.path, never put on PATH.

Worth noting why my own zero-false-positive measurement missed this. All three sidecars on the test machine are INSTALLER=uv, so the pip shape was never exercised; setup.sh's fast_install falls back to python -m pip whenever uv is absent or fails.

Comment on lines +1153 to +1155
re-routes a model. Sub-file damage is caught one step later instead, by
_ensure_venv_t5_latest_exists at worker activation, which repairs in a
parent and refuses with a named reason in a child."""

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Trigger latest-sidecar repair from the parent

When .venv_t5_latest has a truncated or deleted recorded file but retains its package directories and metadata, this package-only predicate returns true, so the parent never enters the self-heal branch in _overlay_transformers_dir. Worker activation later detects the damage in _ensure_venv_t5_latest_exists, but its multiprocessing.parent_process() guard explicitly refuses to repair from a child; consequently every inference/training worker retry fails indefinitely while waiting for a parent repair that is never triggered.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed, and it is worse than a degraded path: it is a permanent deadlock. Fixed in 777d646.

The child logs "retry after the parent repairs the sidecar" and returns, but nothing tells the parent. The routing self-heal in _overlay_transformers_dir was gated on _latest_sidecar_intact, which is package level and cannot see a truncated or deleted file, so the repair never fired.

I reproduced two ways in, driving only the pre-existing API:

scenario repairs worker retries failed healed
damage already present at startup, cold cache 0 5/5 no
damage appearing after a mapping was cached 0 5/5 no

The first one is worth naming: it does not need a stale cache at all. A file truncated before the process starts is enough, so a cold boot onto a damaged sidecar deadlocks just as hard.

The fix has the child leave a marker inside the sidecar dir, and has the routing self-heal consult the RECORD scan as well, but only where a repair can actually follow it: on a _config_mapping_cache miss, and outside the failure backoff window. Both constraints are pinned by tests that fail the run if the scan is reached (test_cached_mapping_hit_never_scans_the_sidecar, test_repair_backoff_window_never_repeats_the_scan), because the cached revalidation runs several times per request and had to stay package level. The marker lives inside the sidecar, so the stage-and-swap that repairs it clears the marker by construction, and a scan that finds the sidecar healthy drops a stale one rather than acting on it.

With the fix each scenario heals in a single repair. 268 tests pass; the 7 new ones fail on the parent commit.

One behaviour change worth stating plainly: a synchronous several-hundred-MB reinstall can now be triggered by file damage, which it could not before. That makes a false positive from the scan expensive, so I re-ran the scan against all three real sidecars on this machine in place and it reports zero findings on each (25-32 ms), with a positive control confirming it still catches a truncated and a deleted file. UNSLOTH_SKIP_SIDECAR_FILE_CHECK remains the escape hatch and now suppresses this path too, which test_file_check_kill_switch_suppresses_the_whole_handoff pins.

The scan failed CLOSED on a healthy pip-built sidecar. pip --target
installs through a temporary normal-scheme prefix and writes RECORD before
flattening, so console scripts are recorded as ../../bin/hf while the file
lands in <target>/bin. Resolved against the sidecar root those rows point
two levels above it and never exist, so a perfectly good sidecar reported
damage. The repair then reinstalls with the same pip, writes the same
rows, and finds the same damage: several hundred MB re-downloaded on every
activation, forever. That is worse than the behaviour this change set out
to fix, which never wiped a version-correct sidecar.

Rows landing in bin/ or Scripts/ are dropped too. uv records bin/hf, which
does resolve, but pip's --upgrade rmtree's a colliding directory in the
target, so a later install into the same sidecar deletes an earlier
package's scripts. Nothing is lost either way: the sidecar is only ever
prepended to sys.path, never put on PATH, so no script there is executed.

Absolute paths and drive letters go with them, for the same reason.

Missed originally because all three sidecars on the test machine were
uv-built (INSTALLER=uv), and uv writes in-target bin/ rows. setup.sh's
fast_install falls back to python -m pip whenever uv is absent or fails,
so the pip shape is reachable on any host without uv.

Verified: a healthy pip --target sidecar now reports nothing, the three
real uv sidecars still report nothing at 25-32 ms, and deleted or
truncated package files are still caught.
@danielhanchen

Copy link
Copy Markdown
Member Author

Pushed 1c92811 for a fail-closed bug in the scan that I had missed, found by review before this went anywhere.

pip install --target installs through a temporary normal-scheme prefix and writes RECORD before flattening it, so console scripts are recorded as ../../bin/hf (../../Scripts/hf.exe on Windows) while the file actually lands in <target>/bin. Resolved against the sidecar root those rows point two levels above it and never exist, so a perfectly healthy sidecar reported damage:

scripts present in target/bin: ['idna', 'normalizer']
_sidecar_damaged_files -> ['charset_normalizer: ../../bin/normalizer is missing',
                           'idna: ../../bin/idna is missing']

_ensure_venv_dir would then wipe and reinstall with the same pip, which writes the same rows, so it never converges: several hundred MB re-downloaded on every activation. That is worse than the behaviour this PR set out to fix, since the old predicate never wiped a version-correct sidecar.

Rows landing in bin/ or Scripts/ are dropped as well. uv records bin/hf, which does resolve, but pip's --upgrade rmtree's a colliding directory in the target, so a later install into the same sidecar deletes an earlier package's scripts. Nothing is lost either way, because the sidecar is only ever prepended to sys.path, never put on PATH.

Worth recording why the original zero-false-positive check did not catch this: all three sidecars on the test machine are uv-built (INSTALLER=uv), and uv writes in-target bin/ rows. setup.sh's fast_install falls back to python -m pip whenever uv is absent or fails, so the pip shape is reachable on any host without uv. The measurement was real but the sample was one installer wide.

Re-verified: healthy pip --target sidecar reports nothing; the three real uv sidecars still report nothing at 25-32 ms; deleted and truncated package files are still caught. Three regression tests added, and removing only the new skip fails exactly those two of them.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 1c92811683

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

A worker child that finds the latest sidecar damaged cannot repair it: repairs
run in the parent. It logged 'retry after the parent repairs the sidecar' and
returned, but nothing told the parent. The routing self-heal was gated on the
package-level _latest_sidecar_intact, which cannot see a truncated or deleted
file, so the repair never fired and every retry failed forever.

The child now leaves a marker inside the sidecar dir, and the routing self-heal
consults the RECORD scan as well, but only when a repair could actually follow:
on a _config_mapping_cache miss and outside the failure backoff window. The
cached hot path keeps the cheap package-level check it runs several times per
request, and the marker lives inside the sidecar so a successful swap clears it
by construction. A scan that finds the sidecar healthy drops a stale marker.

Reproduced both ways it deadlocks: damage already present at startup, and damage
appearing after a mapping was cached. Baseline repairs 0 and fails 5 of 5 worker
retries in each; with the fix each heals in one repair.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 1, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 80df4fa5f8

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

# and only on a _config_mapping_cache miss (once per process while the
# sidecar is healthy) -- never during the backoff window, where every
# routing call would otherwise re-pay it for an answer it cannot act on.
broken = not _latest_sidecar_intact() or (heal_due and not _latest_sidecar_undamaged())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep damaged latest sidecar unavailable during backoff

When the parent-side RECORD scan finds a truncated/deleted file and _ensure_venv_t5_latest_exists() fails (for example offline mode, pip failure, or active workers), _latest_repair_failed_at is set. On later routing calls inside the 5-minute backoff, heal_due is false and _latest_sidecar_intact() still returns true for package-level-intact sub-file damage, so this expression marks broken false and returns src, routing latest-only loads back into the known damaged sidecar instead of withholding it until a repair succeeds. Track that the previous failed attempt found file damage, or leave a repair marker, so the backoff suppresses pip retries without treating the sidecar as usable.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct, and reproduced. Fixed in 1bd4d3d.

The failure branch recorded the backoff but not the damage, so the next routing call re-evaluated with the package-level predicate, which cannot see a truncated file, found nothing broken, and handed the sidecar back. Measured on a parent process with a truncated recorded file and _install_to_dir forced to fail:

first call (repair attempted, fails): src=None  scans=2
during backoff: 4/4 calls served the DAMAGED sidecar; scans=0

So it was silent as well as wrong: no scan ran in the window, nothing logged, and latest-only models routed straight into a tier whose worker activation is known to fail for the full five minutes.

Your second suggestion is the one I took, since the marker already exists for the child handoff: a failed parent-side repair now leaves the same marker, which makes _latest_sidecar_intact false for the rest of the window. That withholds the sidecar while still suppressing pip retries, and because the marker check short-circuits the or before _latest_sidecar_undamaged, the window still never repeats the ~25 ms scan. Same measurement after:

during backoff: 0/4 calls served the DAMAGED sidecar; scans=0

Covered by test_backoff_window_keeps_the_damaged_sidecar_withheld, which also asserts the cheap predicate still reports the sidecar valid, so the test fails if the marker stops being the thing doing the work. It fails on the parent commit. The two deadlock scenarios still heal in one repair each, 351 tests pass, and the real sidecars on this machine still scan to zero findings.

When a parent-side scan found file damage and the repair then failed (offline,
pip down, workers active), the backoff was recorded but the damage was not. The
next routing call re-evaluated with the cheap package-level predicate, which
cannot see a truncated file, found nothing broken, and handed the known damaged
sidecar back. Every routing call for the whole five-minute window routed
latest-only models into a tier whose worker activation is known to fail.

The failed attempt now leaves the same marker a worker child leaves, so the
backoff suppresses pip retries without also declaring the sidecar usable. The
marker check is one is_file, so the window still never repeats the ~25 ms scan.

Measured before: 4 of 4 routing calls in the window returned the damaged
sidecar. After: 0 of 4, with the scan count still 0.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 1, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d272303abb

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

version = pin["version"]
packages = tuple(pin["packages"])
if _venv_dir_is_valid(_VENV_T5_LATEST_DIR, packages):
if _venv_dir_is_valid_and_undamaged(_VENV_T5_LATEST_DIR, packages):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Flag damaged latest sidecars before offline bailout

When a latest mapping was cached before the sidecar file was damaged and a worker is running with HF/transformers offline mode enabled, this new RECORD-level check can fail, but the offline branch immediately below returns before _request_latest_repair() runs. In that case the parent only revalidates the cached mapping with the cheap package-level predicate, never sees the truncated/deleted file, and keeps routing workers back to the damaged latest sidecar indefinitely instead of withholding it or falling back to a lower tier.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct, reproduced, fixed in fb2ee73.

The flag sat below the offline bailout, so an offline child returned having recorded nothing. Measured on a child with offline mode set and a truncated recorded file:

baseline: activation=False  marker_written=False
fixed:    activation=False  marker_written=True

Rather than add a second call in the offline branch, I moved the flagging up to the point where the sidecar is known broken, so every exit that leaves it unrepaired records it. That covers the swap-already-running branch too, which had the same hole and which your comment did not mention. test_every_unrepaired_exit_flags_the_damage walks all three bailouts (offline, child, swap running) and asserts each one leaves the marker and leaves _latest_sidecar_intact false; it fails on the parent commit.

# and a mapping cached before the damage keeps it off the scanning path
# entirely, so every worker retry would fail forever waiting for a repair
# nothing triggers.
_request_latest_repair()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Revalidate cached latest probes on repair requests

When a model reaches latest through _probe_tier (for example a tokenizer/config-saved-by-5.x probe) and that result is cached before the sidecar is damaged, this child-side marker still does not make the parent repair: the _probe_tier_cache hit path returns cached "latest" without checking _latest_sidecar_intact() or the marker, unlike the config-mapping cache path. Fresh evidence is the remaining probe-cache short-circuit for cached latest results, so the retry can keep spawning workers into the damaged sidecar even after the marker is written.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct, reproduced, fixed in fb2ee73.

The probe cache honoured only the kill switch, so a result cached while the sidecar was healthy kept returning latest after the damage was known. It matters for exactly the reason you give: a model that reaches latest this way never touches the config-mapping path, which is where the repair happens, so the retries have nothing to converge on.

baseline: cached probe on flagged sidecar -> 'latest'
fixed:    cached probe on flagged sidecar -> 'default'   (re-probed)

It now falls through to a re-probe when a repair is outstanding, which runs the ensure and repair path, mirroring how the kill switch already behaves there.

One note on the shape of the fix: I first gated the short-circuit on _latest_sidecar_intact() to match _config_model_types, and that broke test_cached_latest_probe_ignored_when_disabled, because with no pin present the predicate is false and a cached entry stopped short-circuiting for a reason unrelated to damage. Gating on the outstanding-repair marker instead is both narrower and cheaper (one is_file), and keeps that contract intact. Covered by test_cached_probe_result_does_not_survive_a_flagged_sidecar, which fails on the parent commit. 353 tests pass, and the real sidecars still scan to zero findings.

…probe cache

Two remaining ways the repair handoff was skipped.

The flag was written only on the worker-child branch, which sits below the
offline bailout, so an offline child returned without recording anything and the
parent kept revalidating with the package-level predicate that cannot see the
damage. The same held for a swap already in progress. Flag once at the point the
sidecar is known broken instead, so every exit that leaves it unrepaired records
it, and drop the per-branch calls.

_probe_tier caches its result for the process and its cache-hit path honoured
only the kill switch. A model that reached latest through a probe rather than
the config mapping therefore kept returning a cached latest after the damage was
known, never touching the config-mapping path that performs the repair, so
worker retries continued indefinitely. It now falls through to a re-probe when a
repair is outstanding, which runs the ensure and repair path.

Reproduced both against the parent commit: the offline child wrote no marker,
and a probe cached as latest still returned latest with the marker present.
After: the marker is written and the probe re-resolves off latest.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 1, 2026

@ErenAta16 ErenAta16 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pulled _sidecar_damaged_files out and drove it against a synthetic sidecar rather than reading it, because the cost of a false positive here is a several-hundred-megabyte reinstall and the comments make a lot of specific promises. Nearly all of them hold.

Behaviour matches the docstring, case by case

detected:
  truncated file            -> pkga/m.py is 40 bytes, expected 100
  missing file              -> pkga/m.py is missing
  directory in place of file-> pkga/m.py is not a regular file
  blank size + missing      -> pkga/m.py is missing

correctly silent:
  exact size            larger than recorded     blank size + present
  trailing-slash row    .pyc                     .dist-info/ row
  bin/ script           ../../bin/hf             absolute path
  comma in path (CSV-quoted)                     intact symlink

  broken symlink        -> reported missing

The multiply-owned semantics are exactly as written, which was the part I most expected to find loose:

two dists claim one path, file truncated -> silent      (size ambiguous)
two dists claim one path, file gone      -> reported for both owners

Suppressing the size comparison while keeping the existence check is a genuinely subtle distinction and it is implemented correctly.

Two ways an intact sidecar gets reported as damaged

The docstring commits to a policy:

Fails open everywhere. [...] an unreadable or absent RECORD -- and any other surprise -- reports nothing rather than guessing.

OSError and csv.Error honour that. A decoding surprise does not, because errors = "replace" prevents the exception that would have been caught:

A BOM at the start of RECORD. read_text(encoding="utf-8") keeps \ufeff, so it becomes part of the first row path:

RECORD: \xef\xbb\xbfpkga/m.py,sha256=x,100
file:   pkga/m.py, intact, exactly 100 bytes
result: ["pkga: \ufeffpkga/m.py is missing"]

Any invalid UTF-8 byte in a path. It becomes U+FFFD, so the path stops matching the file on disk:

RECORD row 1: pkga/m\xffy.py,sha256=x,100
RECORD row 2: pkga/m.py,sha256=x,100     (file intact, 100 bytes)
result: ["pkga: pkga/m\ufffdy.py is missing"]

Both wipe and reinstall a healthy sidecar. pip does not write a BOM, so this needs something to have rewritten RECORD -- a text editor on Windows is the obvious candidate, and the sidecar lives somewhere a user can reach. It is narrow, but it is the exact scenario the fail-open paragraph is about, and the fix is one word: encoding = "utf-8-sig" handles both BOM and no-BOM, and errors = "strict" inside the existing try would route a genuinely undecodable RECORD to the continue that already exists rather than to a false finding.

If errors = "replace" is deliberate -- so that one unreadable row does not lose the whole distribution -- then the replacement character is the signal, and skipping rows containing \ufffd would keep that intent without the false positive.

Smaller

UNSLOTH_SKIP_SIDECAR_FILE_CHECK is the right instinct given the cost of a false positive, and I would take the two cases above as an argument for mentioning it in the warning text the user actually sees, not only in the code. Someone hitting a bogus reinstall loop will not find an env var they have never heard of.

name = di.name.split("-")[0] handles a dotted distribution correctly (zope.interface-5.4.0.dist-info -> zope.interface), which I checked because it feeds the user-visible message.

The comment explaining why console scripts are skipped -- pip recording ../../bin/hf while uv records bin/hf, and the sidecar never being on PATH -- is the kind of thing that would otherwise be deleted as over-defensive in two years. Worth keeping.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 1, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6fb8f6e450

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

Comment on lines +2117 to +2121
except OSError:
# Multiple ownership makes the recorded SIZES ambiguous; it cannot
# explain the file being gone, so this branch runs for shared paths
# too.
found.append(f"{name}: {rel} is missing")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Distinguish missing files from transient stat errors

When UNSLOTH_STUDIO_HOME is on a filesystem that returns a transient OSError such as EIO, ESTALE, or EACCES while scanning any recorded file, this branch reports the file as missing. _venv_dir_is_valid_and_undamaged() then returns false and _ensure_venv_dir() deletes and reinstalls the entire sidecar, despite the stated fail-open behavior; catch FileNotFoundError as damage but treat other stat failures as an inconclusive scan.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct, reproduced, fixed in 68c3a1c. This is the most expensive false positive in the change, so thank you for it.

Forcing Path.stat to raise EIO on one recorded file, on the parent commit:

findings=['transformers: transformers/__init__.py is missing']

which fails _venv_dir_is_valid_and_undamaged and wipes a several-hundred-MB sidecar over a file that was never lost. FileNotFoundError and NotADirectoryError are now the only stat failures treated as damage; NotADirectoryError is in because a parent component being a file is the same tree damage seen one level up. Anything else leaves the row unjudged, on the principle that a scan which cannot see the disk must not condemn it.

Two tests, both failing on the parent: test_an_unreadable_file_is_not_reported_as_damage, and test_a_deleted_file_is_still_reported_as_damage as the counterpart, so narrowing the catch cannot quietly blind the scan. The three real sidecars on this machine still scan to zero findings, and the positive control still catches a truncated and a deleted file.

# and only on a _config_mapping_cache miss (once per process while the
# sidecar is healthy) -- never during the backoff window, where every
# routing call would otherwise re-pay it for an answer it cannot act on.
broken = not _latest_sidecar_intact() or (heal_due and not _latest_sidecar_undamaged())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Let the file-check kill switch bypass repair backoff

When a false-positive file finding has already produced the repair marker and the attempted reinstall fails, setting UNSLOTH_SKIP_SIDECAR_FILE_CHECK=1 during the five-minute backoff still leaves broken true from that marker while heal_due is false. The function consequently keeps returning None without running the now-disabled integrity check that would clear the marker, so the documented escape hatch cannot restore latest-tier routing until the entire backoff expires; allow this kill switch to revalidate and clear a file-damage marker immediately while retaining package-level validation.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct, reproduced, fixed in 68c3a1c.

The switch was read inside _sidecar_damaged_files only, so once a marker existed the routing predicate stayed false through it and, with the scan disabled, nothing ever reached the code that clears the marker. Measured on the parent, with the marker armed and a repair already failed:

kill switch set mid-backoff -> overlay=None

The marker only ever records a file-level finding, which is precisely what the switch turns off, so it is honoured in _latest_repair_requested too. Package-level validation is untouched, so a sidecar that is genuinely missing a package still routes away. After the fix the same sequence returns the overlay immediately.

Covered by test_kill_switch_frees_the_sidecar_mid_backoff, which asserts the marker is armed first so it cannot pass vacuously. It fails on the parent commit.

pin = _latest_pin_data()
if pin is None:
return False
return _venv_dir_is_valid_and_undamaged(_VENV_T5_LATEST_DIR, tuple(pin["packages"]))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Update latest-overlay fixtures for integrity validation

The existing latest-overlay tests still create only transformers/ plus a legacy pin, so this new package-and-RECORD validation treats their fixtures as damaged and starts a real runtime pip repair. On the reviewed commit, running test_transformers_version.py together with test_transformers_latest.py produces 2 failures (test_overlay_dir_for_latest and test_kill_switch_removes_provisioned_latest_from_routing) after attempting network installs; update those fixtures to include valid package metadata/RECORD data or mock the validator so the unit suite remains offline and deterministic.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I could not reproduce this one, so I have left the fixtures alone.

Running exactly the combination named, on the reviewed commit:

$ pytest tests/test_transformers_version.py tests/test_transformers_latest.py -q
353 passed in 28.71s

$ pytest ... -k 'test_overlay_dir_for_latest or test_kill_switch_removes_provisioned_latest_from_routing'
2 passed, 351 deselected in 9.88s

Both named tests pass, the pair is green, and the wall clock rules out a network install: 9.88s for the two, and the suite is no slower than before this PR.

The reason the fixtures are fine is that the new validation is reached only for a tier that is both pinned and being routed to. _overlay_transformers_dir returns early when latest_venv_pinned_version() is None, and _latest_sidecar_undamaged returns False on a missing pin without scanning, so a fixture carrying only transformers/ and a legacy pin never gets as far as the RECORD comparison. The scan is also gated behind _latest_sidecar_intact, which those fixtures do not satisfy in the first place.

If you have a specific invocation that does fail, including ordering or -p randomly state, I will happily take another look, but I would rather not change fixtures I cannot see failing.

…ill switch act at once

Two ways the integrity scan was harsher than intended.

The stat guard caught OSError whole, so EIO or ESTALE on a flaky mount, or
EACCES, read as 'is missing'. That is a false positive of the most expensive
kind: it fails the undamaged check and wipes and re-downloads a
several-hundred-MB sidecar over a file that was never lost. Only
FileNotFoundError and NotADirectoryError are evidence of damage now; anything
else leaves the row unjudged, since a scan that cannot see the disk must not
condemn it.

The kill switch was read inside the scan alone, so a marker already written by a
false positive kept the sidecar withheld and, with the scan disabled, nothing
ever reached the code that clears it. The documented escape hatch therefore did
nothing until the five-minute backoff expired. The marker only ever records a
file-level finding, which is exactly what the switch turns off, so it is
honoured there too.

Measured before: a stat raising EIO produced
['transformers: transformers/__init__.py is missing'], and setting the switch
mid-backoff still returned no overlay. After: no findings, and routing is
restored on the next call. A deleted file is still reported, and the three real
sidecars on this machine still scan to zero findings.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 1, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 998c2b5960

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

# repaired it, or a child lost the race with a swap and flagged the fresh
# dir) must not survive, or every routing call re-enters the self-heal
# branch forever.
_clear_latest_repair_request()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve repair markers after inconclusive scans

When a worker has already recorded definite damage but the parent's follow-up scan encounters EIO, ESTALE, EACCES, an unreadable RECORD, or another error that _sidecar_damaged_files() deliberately skips, the validator returns True as though the scan proved the sidecar healthy. This line then clears the only record of the known damage and returns the unrepaired sidecar to routing, potentially recreating the worker failure loop; the scan needs a distinct inconclusive result, and an existing marker should only be cleared after a fully conclusive clean scan.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct, and it was mine: the previous commit narrowed the stat guard so unreadable rows are skipped, which made an empty result ambiguous without saying so. Fixed in ef92360.

Reproduced with a marker recording real damage and Path.stat raising EIO on that file:

before: returned=True  marker_survived=False
after:  returned=False marker_survived=True

So it did exactly what you describe: erased the only record of proven damage and handed the unrepaired sidecar back to routing, which is the retry loop this PR exists to close.

The scan now reports whether it was conclusive (_sidecar_scan returns (findings, inconclusive); _sidecar_damaged_files stays a findings-only wrapper), and only a scan that read every row may retire a marker. I took the unreadable-RECORD case you mention as well, plus an unreadable dist-info listing and a malformed CSV. A RECORD that is simply absent is deliberately not inconclusive, since installs legitimately have none and treating that as a gap would make the common case permanently unprovable.

Fail-open is preserved where nothing was ever proven: an inconclusive scan with no marker still returns healthy, so a flaky mount alone never triggers a reinstall.

Two tests, both failing on the parent: test_an_inconclusive_scan_does_not_retire_proven_damage (with the repair forced to fail, so it observes the decision rather than a rebuild hiding it) and test_a_clean_scan_still_retires_a_stale_marker as the counterpart, so the fix cannot become 'never clear the marker'.

# fail, and a model that reaches latest this way never touches the config-mapping
# path that would repair it. Falling through re-probes, which runs the ensure and
# repair path instead.
if cached != "latest" or not (_latest_tier_disabled() or _latest_repair_requested()):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Revalidate cached latest probes when the pin disappears

When a model's probe result was cached as latest and .venv_t5_latest or only its pin marker is subsequently deleted, _latest_repair_requested() is false because the repair-marker path disappeared too, so this condition continues returning the cached tier without checking that it remains pinned or intact. Worker activation then short-circuits on pinned is None before _ensure_venv_t5_latest_exists() can signal anything, making every retry fail until the process or cache is reset. Fresh evidence beyond the earlier repair-request case is that deleting the pin makes it impossible for that request marker to exist; cached latest results also need package/pin revalidation.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct, reproduced, fixed in ef92360. The point that deleting the pin deletes the marker with it is exactly right, and it is why the previous round's marker-only gate could not cover this.

before: cached probe after the sidecar and pin are deleted -> 'latest'
after:  -> 'default' (re-probed)

An unpinned tier now re-probes alongside the kill switch and the repair marker.

One note on the fixture, since it is the reason I did not do this last round. test_cached_latest_probe_ignored_when_disabled held a cached latest with no pin ever created, and gating on the pin made it fail. That state cannot occur in production: _probe_tier_order only includes latest once pinned, so nothing can cache it unpinned in the first place. I pinned the tier in that test so it remains a test of the kill switch, which is its stated intent; its assertions are untouched. I would rather say that plainly than have it look like a test bent to fit the change.

Covered by test_a_cached_probe_does_not_survive_the_pin_being_deleted, which fails on the parent commit.

def _ensure_venv_dir(venv_dir: str, packages: tuple[str, ...], label: str) -> bool:
"""Ensure *venv_dir* exists with all *packages*. Install if missing."""
if _venv_dir_is_valid(venv_dir, packages):
if _venv_dir_is_valid_and_undamaged(venv_dir, packages):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Avoid repairing fixed sidecars while workers use them

When a fixed-tier sidecar has damage in a file that an existing worker has not needed yet, a parent-side tier probe or a second worker now reaches _ensure_venv_dir(), which deletes and reinstalls that live directory in place without the swap reservation or active-worker checks used for latest. An inference/training/export worker already using the same 530/550/510 overlay can therefore lazy-import while the directory is absent or only partially reinstalled and crash even though the detected damage may have been unrelated to its model; fixed-tier file repairs need to be staged or deferred while users of the overlay remain active.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The mechanism is real, but the word "now" is not: those call chains already reached it. I have left this for a follow-up rather than changing it here.

_ensure_venv_dir against this PR's merge-base is a one-line diff:

-    if _venv_dir_is_valid(venv_dir, packages):
+    if _venv_dir_is_valid_and_undamaged(venv_dir, packages):

The unguarded shutil.rmtree of the live directory, and both routes to it (a parent-side _probe_tier through _probe_tier_venvs, and activate_transformers_for_subprocess in a second worker), are byte-identical to main. They fire today whenever a fixed tier fails the package-level check.

What the PR does change is honest to state: the trigger widens, so a sidecar that is package-complete but file-damaged now also gets wiped. Where you are right is the narrow case where the damage is in a file the live worker never imports, which converts "keeps running" into "may crash on a later lazy import". Against that, the same damaged sidecar previously guaranteed an ImportError for every new worker on that tier with no self-heal at all, so it trades a certain failure for a repair with a disturbance window.

I am not fixing it in this PR because the right fix is not small and not obviously safe:

  • The swap reservation cannot simply be reused. It is single-slot and global, and _stage_and_swap_latest_venv calls _ensure_venv_dir on its staging dir while already holding it, so taking it there self-deadlocks unless it is made reentrant.
  • Staging and renaming three more overlays means three more .staging/.old trees and three more stranded-dir recovery paths.
  • Any deferral has to be stateless. A marker plus a routing withhold is precisely what deadlocked the latest tier earlier in this PR, and a deferral that returns False would make the tier unavailable for as long as any worker lives, which is worse than today.
  • A blanket child refusal would break fresh installs, since fixed tiers are legitimately provisioned in a worker on first use when setup.sh never created them.

For what it is worth, running this PR's scan against the three live fixed-tier sidecars on a real install gives zero findings on each, so there is no evidence of it wiping healthy overlays. Happy to open the deferral as its own PR.

danielhanchen and others added 2 commits August 1, 2026 23:37
…inned latest

Two consequences of narrowing the stat guard in the previous commit.

Skipping a row the scan could not read makes an empty result ambiguous: it can
mean nothing was proven rather than nothing is wrong. The validator reported
that as healthy, so a marker recording damage a worker had already proven was
cleared and the unrepaired sidecar went back to routing, which is the retry loop
this PR exists to close. The scan now reports whether it was conclusive, and
only a scan that actually read every row may retire a marker. An unreadable
RECORD or dist-info listing counts as inconclusive too; a RECORD that is simply
absent does not, since installs legitimately have none.

The cached probe check keyed on the repair marker alone, but deleting the pin
deletes the marker with it, so a probe cached as latest kept being returned
after the pin went away. Activation short-circuits on a missing pin before it
can signal anything, so every retry failed until the process restarted. An
unpinned tier now re-probes.

test_cached_latest_probe_ignored_when_disabled held a cached latest with no pin,
which the probe order means cannot occur, so it now pins the tier and stays a
test of the kill switch. Its assertions are unchanged.

Measured before: an EIO mid-scan cleared a marker covering real damage and
returned True, and a probe cached as latest still returned latest after the
sidecar and its pin were deleted. After: the marker survives and the probe
re-resolves. The three real sidecars still scan to zero findings.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 1, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c808c29d84

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

def _ensure_venv_dir(venv_dir: str, packages: tuple[str, ...], label: str) -> bool:
"""Ensure *venv_dir* exists with all *packages*. Install if missing."""
if _venv_dir_is_valid(venv_dir, packages):
if _venv_dir_is_valid_and_undamaged(venv_dir, packages):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Restore the ownership marker after fixed-sidecar repair

When UNSLOTH_STUDIO_HOME points to a custom location and the new file-integrity check triggers a fixed-tier repair, _ensure_venv_dir() removes .unsloth-studio-owned with the old directory but never recreates it. A later dependency update then reaches the ownership guards in studio/setup.sh:615-622 or studio/setup.ps1:2825-2832 and aborts because the successfully repaired sidecar now appears user-owned; recreate the ownership marker after rebuilding the directory.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct, reproduced, fixed in f5e4546.

I checked the guard actually applies to sidecar venvs rather than only to the prebuilt installs, and it does: setup.sh:1148/1158/1168 and setup.ps1:3622/3657/3692 assert ownership on the 5.3, 5.5 and 5.10 sidecars, and setup.sh:1151/1161/1171 are what write the marker. Adoption cannot rescue it, as you imply: _studio_owned_adoptable needs one of the UNSLOTH_*_PREBUILT_INFO.json files, and a venv has none, so an unmarked sidecar under a custom home is a hard setup_fail.

On a sidecar carrying the marker:

before: repair_ok=True  marker_present_after=False
after:  repair_ok=True  marker_present_after=True

Worth being straight about scope: this is pre-existing, not introduced here. _ensure_venv_dir already wiped whenever a package-level check failed, and that path is byte-identical to main. What this PR changes is that file damage now reaches the same wipe, which makes it markedly easier to hit, and the fix is two lines with no downside, so I would rather close it here than leave it for later. The rebuilt tree is Unsloth-owned by construction, so marking it is accurate rather than a workaround, and the write is best effort exactly as the shell does it: a missing marker costs a clear error on a later update, never a wrong deletion.

The latest tier gets this for free, since _stage_and_swap_latest_venv builds its staging dir through _ensure_venv_dir and the marker survives the rename. An extra dotfile is invisible to the RECORD scan, and the three real sidecars still report zero findings.

Covered by test_ensure_venv_dir_restores_the_studio_owned_marker, which fails with the single added line removed. 360 tests pass.

setup.sh and setup.ps1 write .unsloth-studio-owned beside each sidecar venv they
create, and under a custom UNSLOTH_STUDIO_HOME they refuse to touch a directory
without it rather than risk deleting something of the user's. The runtime rebuild
in _ensure_venv_dir removes the directory and never writes a new marker, so the
next dependency update aborts on a sidecar Studio itself had just repaired.
Adoption cannot cover the gap either: it requires a prebuilt-info file, which a
venv never has.

The rebuilt tree is ours by construction, so mark it. Pre-existing, since the
wipe already ran whenever a package-level check failed, but this PR reaches it
from file damage as well, which makes it markedly easier to hit.

Reproduced on a sidecar carrying the marker: before, a repair left
marker_present=False; after, True.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 2, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 3c7d886b27

ℹ️ 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 8f7374e into main Aug 2, 2026
42 checks passed
@danielhanchen
danielhanchen deleted the fix-sidecar-file-integrity branch August 2, 2026 07:43
danielhanchen added a commit to Anai-Guo/unsloth that referenced this pull request Aug 2, 2026
The RECORD-vs-filesystem integrity check this PR introduced is now on main,
so the branch carries no remaining difference.

unslothai#7725 built on the approach here and kept its core decisions: compare each
RECORD row against the filesystem, treat a file larger than recorded as a
packaging collision rather than damage, and leave a missing or unreadable
RECORD to the existing checks rather than guess. It also took the fix from
the follow-up commit on this branch, skipping out-of-tree script rows such
as ../../bin/hf that a --target install records but never resolves.

It differs in where the scan runs. _venv_dir_is_valid is reached from
_latest_sidecar_intact several times per validate request, so the scan sits
only at the sites that can actually repair, and the routing predicate stays
package level.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Damaged .venv_t5_* sidecar files are neither detected nor repaired

2 participants