Skip to content

armgit / Soup

Public Imported from GitHub
0

Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.

fix: keep the previous artifact when reward synth or adapter fuse fails (#1454)

Younes Beriane1a67520c0766
diff --git a/changelog.d/0.75.1/1454.fixed.md b/changelog.d/0.75.1/1454.fixed.md
new file mode 100644
index 00000000..7c09ff8c
--- /dev/null
+++ b/changelog.d/0.75.1/1454.fixed.md
@@ -0,0 +1,14 @@
+- **A failed adapter merge or reward-verifier replace could destroy the only
+ good copy on disk (#1450 by @drakeo338 in #1454).** `merge_adapter_to_dense` (shared
+ by `soup shrink` and `soup draft distill`) deleted `out_dir` before swapping
+ the newly merged model in, so a failure between the two steps — a lock held
+ on the staging dir, disk full — left neither the old nor the new model.
+ `soup reward synth -o reward.py --force` had the same shape: it overwrote
+ the existing verifier with the candidate before calibrating it, then deleted
+ the file outright on refusal or error, destroying a previously working
+ verifier. `merge_adapter_to_dense` now moves the previous artifact aside
+ instead of deleting it, and restores it if the replacement does not make it
+ all the way to accepted. `soup reward synth` instead writes the candidate to
+ a temp sibling and never touches `-o` until it is accepted, so there is
+ nothing to move aside or restore on a refusal or error — the previous
+ verifier is simply never disturbed.
diff --git a/src/soup_cli/commands/draft.py b/src/soup_cli/commands/draft.py
index f115ffc0..d7b46cc5 100644
--- a/src/soup_cli/commands/draft.py
+++ b/src/soup_cli/commands/draft.py
@@ -286,9 +286,10 @@ def _resolve_trust(model_id: str, requested: bool = False) -> bool:
def _guard_output_target(output: str, *, force: bool) -> None:
"""Refuse a destructive ``-o`` that would delete cwd or unrelated content.
- ``merge_adapter_to_dense`` does ``rmtree(out_dir)`` then ``os.replace``, so
- ``-o`` must not be cwd itself and must not be a pre-existing directory that
- isn't already a Soup draft (contains ``config.json``) unless ``--force``.
+ ``merge_adapter_to_dense`` renames an existing ``out_dir`` aside and swaps
+ the merged model in, so ``-o`` must not be cwd itself and must not be a
+ pre-existing directory that isn't already a Soup draft (contains
+ ``config.json``) unless ``--force``.
"""
resolved = os.path.realpath(output)
if resolved == os.path.realpath(os.getcwd()):
diff --git a/src/soup_cli/commands/reward.py b/src/soup_cli/commands/reward.py
index 7233c66c..4c5aaa55 100644
--- a/src/soup_cli/commands/reward.py
+++ b/src/soup_cli/commands/reward.py
@@ -17,6 +17,7 @@ from __future__ import annotations
import json
import math
import os
+import tempfile
from dataclasses import asdict
from typing import NoReturn, Optional
@@ -185,18 +186,40 @@ def synth(
except (ValueError, OSError) as exc:
_fail(str(exc))
- # Write, then LOAD it back through the real reward-loader path (round-trip
- # validation) and calibrate the loaded callable.
- atomic_write_text(result.source, output)
+ # Never touch ``output`` until the candidate has been loaded back and
+ # calibrated: write it to a fresh temp sibling instead, and os.replace
+ # that sibling onto ``output`` only once calibration accepts it. A
+ # refusal, a calibration error, or a crash (Ctrl-C / SIGKILL) at any
+ # point before that final os.replace leaves ``output`` byte-identical to
+ # what it was — there is nothing to restore, because nothing at
+ # ``output`` was ever moved or overwritten.
+ parent = os.path.dirname(os.path.abspath(output)) or "."
+ os.makedirs(parent, exist_ok=True)
+ try:
+ fd, candidate_path = tempfile.mkstemp(
+ prefix=".soup.reward-candidate.", suffix=".py", dir=parent
+ )
+ except OSError as exc:
+ _fail(f"could not create candidate verifier: {exc}")
+ try:
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
+ fh.write(result.source)
+ except OSError as exc:
+ _cleanup(candidate_path)
+ _fail(f"could not write candidate verifier: {exc}")
+
+ # LOAD the candidate back through the real reward-loader path (round-trip
+ # validation, from its own temp path — ``output`` is untouched) and
+ # calibrate the loaded callable.
try:
from soup_cli.trainer.rewards import load_reward_fn
- reward_fn = load_reward_fn(output)
+ reward_fn = load_reward_fn(candidate_path)
golds = rs.extract_golds(rows, field=field)
negatives = rs.perturb_negatives(golds, result.kind)
report = rs.calibrate(reward_fn, golds, negatives, kind=result.kind,
min_discrimination=min_discrimination)
- except Exception as exc: # noqa: BLE001 — clean up the partial artifact
- _cleanup(output)
+ except Exception as exc: # noqa: BLE001 — clean up the candidate only
+ _cleanup(candidate_path)
_fail(f"calibration failed: {exc}")
# Write the diagnostic report (path already validated up front) for BOTH the
@@ -209,20 +232,35 @@ def synth(
console.print(f"[yellow]Warning: could not write report: {escape(str(exc))}[/]")
if report.refused:
- _cleanup(output)
+ _cleanup(candidate_path)
console.print(Panel(
escape(report.reason),
title="[bold red]verifier refused (not emitted)[/]", border_style="red"))
raise typer.Exit(2)
+ # Accepted: atomically swap the calibrated candidate onto ``output`` —
+ # the only moment the previous verifier, if any, is replaced. Guard this
+ # too: a failure here (disk full, a lock held on ``output``) must not
+ # leave the candidate orphaned or crash with a raw traceback.
+ try:
+ enforce_under_cwd_and_no_symlink(output, "output path")
+ os.replace(candidate_path, output)
+ except (OSError, ValueError) as exc:
+ _cleanup(candidate_path)
+ _fail(f"could not replace '{output}': {exc}")
+
console.print(_render_report_panel(report, result.kind, output))
raise typer.Exit(0)
-def _cleanup(path: str) -> None:
- """Remove a just-written artifact; best-effort (never masks the real error)."""
+def _cleanup(candidate_path: str) -> None:
+ """Best-effort removal of a candidate verifier that was refused or failed
+ calibration. ``output`` was never touched, so there is nothing to restore
+ — only the temp candidate needs to go. Never masks the real error (a
+ failed calibration / refusal) that is about to be reported.
+ """
try:
- os.remove(path)
+ os.remove(candidate_path)
except OSError:
pass
diff --git a/src/soup_cli/utils/adapter_fuse.py b/src/soup_cli/utils/adapter_fuse.py
index 9d3f5db9..a7bcbc74 100644
--- a/src/soup_cli/utils/adapter_fuse.py
+++ b/src/soup_cli/utils/adapter_fuse.py
@@ -46,8 +46,21 @@ def merge_adapter_to_dense(
for ``out_dir``. An in-place ``save_pretrained`` over a just-loaded model
directory fails on Windows (error 1224 — the source ``.safetensors`` is
still memory-mapped by the loaded weights), so the temp-dir swap is the
- cross-platform-safe path, and it also makes the destination replacement
- atomic.
+ cross-platform-safe path. A pre-existing ``out_dir`` is renamed aside
+ rather than deleted, and only removed once the staged model has taken
+ its place; if the final swap itself then fails (disk full, a lock held
+ on the staging dir), the renamed-aside copy is put back before the error
+ propagates. If that restore also fails, neither artifact is deleted:
+ both the previous model (at the renamed-aside path) and the newly merged
+ model (at the staging path) are left on disk and named in the raised
+ error, so a failure here can never destroy the last complete copy —
+ worst case it leaves two, at paths the caller can recover by hand.
+ If renaming the previous model aside fails in the first place, ``out_dir``
+ is left unchanged, the staging dir is kept, and the raised error names it.
+
+ Guarantee: whichever way the swap ends, ``out_dir`` is never left holding
+ a partial model, and a complete copy of the previous model and/or of the
+ newly merged model always survives on disk at a path the caller is told.
``out_dir`` is re-validated immediately before the swap: the training
subprocess that produced ``adapter_dir`` may have run for hours, so the
@@ -90,30 +103,82 @@ def merge_adapter_to_dense(
parent = os.path.dirname(os.path.abspath(out_dir)) or "."
os.makedirs(parent, exist_ok=True)
staging = tempfile.mkdtemp(prefix=".fuse_", dir=parent)
+ backup: str | None = None
+ keep_staging = False
try:
try:
merged.save_pretrained(staging)
tokenizer.save_pretrained(staging)
finally:
# Drop every reference so Windows releases the out_dir mmap before
- # we remove it; otherwise rmtree(out_dir) also hits error 1224.
+ # we rename it aside; otherwise the rename also hits error 1224.
del merged, base, tokenizer
gc.collect()
release_cuda()
# Re-validate the swap target IMMEDIATELY before the destructive
- # rmtree/replace — the model load + merge + save above took minutes, a
+ # rename/replace — the model load + merge + save above took minutes, a
# real window in which a junction/symlink could be planted at out_dir
# (the entry-time check is now stale). enforce_* refuses symlinks AND
- # Windows reparse points, so rmtree cannot be redirected outside cwd.
+ # Windows reparse points, so the rename cannot be redirected outside cwd.
enforce_under_cwd_and_no_symlink(out_dir, "fused output dir")
if os.path.isdir(out_dir):
- shutil.rmtree(out_dir)
- os.replace(staging, out_dir)
+ # Rename the previous model ASIDE instead of deleting it. The
+ # actual swap below can still fail (AV/indexer holding the
+ # staging dir, disk full), and until it succeeds the old model
+ # is the only good copy there is.
+ backup = os.path.join(
+ parent, f".{os.path.basename(os.path.normpath(out_dir))}.old-{os.getpid()}"
+ )
+ try:
+ os.replace(out_dir, backup)
+ except OSError as backup_exc:
+ # Renaming the previous model aside failed (the same AV /
+ # indexer lock the swap below guards against), so out_dir was
+ # never touched and still holds the old model. Staging is now
+ # the only copy of the new merge: keep it and name it.
+ keep_staging = True
+ raise RuntimeError(
+ f"failed to move the previous model at '{out_dir}' aside "
+ f"({backup_exc!r}); it is unchanged, and the newly merged "
+ f"model is intact at '{staging}' — move it into place "
+ f"manually"
+ ) from backup_exc
+ try:
+ os.replace(staging, out_dir)
+ except BaseException as swap_exc:
+ # The swap itself failed: put the previous model straight back
+ # before anything else runs, so this failure never leaves
+ # neither copy in place.
+ if backup is not None:
+ try:
+ os.replace(backup, out_dir)
+ except OSError as restore_exc:
+ # The restore ALSO failed: out_dir now holds neither
+ # copy. Do not guess which of staging/backup to keep —
+ # keep both on disk and name them in the error, so the
+ # outer handler below must not rmtree(staging) either.
+ keep_staging = True
+ raise RuntimeError(
+ f"failed to swap the merged model into '{out_dir}' "
+ f"({swap_exc!r}), and restoring the previous model "
+ f"from '{backup}' also failed ({restore_exc!r}); "
+ f"the previous model is intact at '{backup}' and the "
+ f"newly merged model is intact at '{staging}' — move "
+ f"one of them into place manually"
+ ) from restore_exc
+ backup = None
+ raise
+ if backup is not None:
+ shutil.rmtree(backup, ignore_errors=True)
except BaseException:
# A half-written staging dir (disk full, interrupted save) must not be
# orphaned next to the model — it would silently accumulate a full
- # model's worth of bytes per failed run.
- shutil.rmtree(staging, ignore_errors=True)
+ # model's worth of bytes per failed run. But if the swap AND the
+ # restore both failed above, staging is the only copy of the new
+ # model left anywhere: keep it, and let the RuntimeError above name
+ # it instead of deleting it here.
+ if not keep_staging:
+ shutil.rmtree(staging, ignore_errors=True)
raise
diff --git a/tests/test_issue1450_atomic_replace.py b/tests/test_issue1450_atomic_replace.py
new file mode 100644
index 00000000..e55e72e3
--- /dev/null
+++ b/tests/test_issue1450_atomic_replace.py
@@ -0,0 +1,509 @@
+"""#1450 — a failed replace must never delete the last good copy.
+
+Two call sites used to remove the old artifact before the new one was known
+to be valid and in place:
+
+* ``merge_adapter_to_dense`` (shared by ``soup shrink`` and ``soup draft
+ distill``) used to ``shutil.rmtree(out_dir)`` then ``os.replace(staging,
+ out_dir)``; its ``except BaseException`` handler deleted ``staging`` too, so
+ a failure between those two calls left neither copy. It now renames
+ ``out_dir`` aside instead of deleting it, restores that backup if the swap
+ fails, and — if the restore itself also fails — keeps both the backup and
+ the staged model on disk rather than guessing which one to delete.
+* ``soup reward synth -o reward.py --force`` overwrote the existing verifier
+ with the candidate BEFORE calibrating it, then deleted the file on refusal
+ or error — destroying the user's previous, working verifier. It now writes
+ the candidate to a ``.soup.reward-candidate.*.py`` temp sibling, loads and
+ calibrates THAT file, and ``os.replace``s it onto ``-o`` only once
+ calibration accepts it. ``-o`` is never moved, overwritten or otherwise
+ touched before that final replace, so a refusal, a calibration error, or a
+ crash at any point before it leaves the previous verifier exactly as it
+ was — there is nothing to restore.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import shutil
+import sys
+import types
+from pathlib import Path
+
+import pytest
+
+
+def _write_jsonl(path: Path, rows):
+ path.write_text("\n".join(json.dumps(r) for r in rows), encoding="utf-8")
+
+
+# ---------------------------------------------------------------------------
+# reward.py synth — --force must not destroy the previous verifier
+# ---------------------------------------------------------------------------
+class TestRewardSynthForceKeepsPreviousOnFailure:
+ def _runner(self):
+ from typer.testing import CliRunner
+ return CliRunner()
+
+ def test_refusal_leaves_previous_verifier_byte_identical(self, tmp_path, monkeypatch):
+ from soup_cli.commands.reward import app
+
+ monkeypatch.chdir(tmp_path)
+ previous = (
+ "# my working verifier\n"
+ "def reward_fn(completions, **kw):\n"
+ " return [1.0 for _ in completions]\n"
+ )
+ Path("reward.py").write_text(previous, encoding="utf-8")
+
+ # A huge tolerance makes every reference AND every perturbed negative
+ # (gold + 9999) accept -> discrimination below the default floor ->
+ # REFUSED (exit 2). This must not touch the existing --force target.
+ _write_jsonl(Path("refs.jsonl"), [{"answer": str(i)} for i in range(4)])
+ res = self._runner().invoke(app, [
+ "synth", "refs.jsonl", "-o", "reward.py",
+ "--force", "--tolerance", "10000",
+ ])
+
+ assert res.exit_code == 2, (res.output, repr(res.exception))
+ assert Path("reward.py").exists(), "the previous verifier was deleted on refusal"
+ assert Path("reward.py").read_text(encoding="utf-8") == previous, (
+ "the previous verifier's bytes changed on a refused --force replace"
+ )
+ leftover = list(tmp_path.glob(".soup.reward-candidate.*.py"))
+ assert not leftover, f"orphaned candidate file(s) left behind: {leftover}"
+
+ def test_calibration_error_leaves_previous_verifier_byte_identical(
+ self, tmp_path, monkeypatch
+ ):
+ from soup_cli.commands.reward import app
+
+ monkeypatch.chdir(tmp_path)
+ previous = "# my working verifier\ndef reward_fn(completions, **kw):\n return [1.0]\n"
+ Path("reward.py").write_text(previous, encoding="utf-8")
+
+ # Make calibrate() raise so the command takes the "calibration failed"
+ # (exit 1) branch instead of the "refused" (exit 2) branch — both
+ # branches call _cleanup(candidate_path), never touching ``output``.
+ from soup_cli.utils import reward_synth as rs
+
+ def _boom(*a, **kw):
+ raise RuntimeError("boom")
+
+ monkeypatch.setattr(rs, "calibrate", _boom)
+
+ _write_jsonl(Path("refs.jsonl"), [{"answer": "4"}, {"answer": "6"}])
+ res = self._runner().invoke(app, [
+ "synth", "refs.jsonl", "-o", "reward.py", "--force",
+ ])
+
+ assert res.exit_code == 1, (res.output, repr(res.exception))
+ assert Path("reward.py").exists(), (
+ "the previous verifier was deleted on a calibration error"
+ )
+ assert Path("reward.py").read_text(encoding="utf-8") == previous
+ leftover = list(tmp_path.glob(".soup.reward-candidate.*.py"))
+ assert not leftover, f"orphaned candidate file(s) left behind: {leftover}"
+
+ def test_crash_mid_calibration_leaves_previous_verifier_and_no_orphan_candidate(
+ self, tmp_path, monkeypatch
+ ):
+ """Simulates a crash partway through the load-back + calibrate step
+ (an abrupt worker failure, not a clean "calibration refused" result):
+ under the old "move old file aside, write candidate in place" design
+ this left the candidate sitting at ``reward.py`` with the real
+ previous verifier hidden under its backup name until a human
+ recovered it by hand. Under the temp-sibling design ``output`` is
+ never moved or written to before the final ``os.replace``, so it
+ survives untouched, and the single ``except Exception`` around the
+ whole load+calibrate block still reaches ``_cleanup`` to remove the
+ orphaned candidate temp file."""
+ from soup_cli.commands.reward import app
+
+ monkeypatch.chdir(tmp_path)
+ previous = "# my working verifier\ndef reward_fn(completions, **kw):\n return [1.0]\n"
+ Path("reward.py").write_text(previous, encoding="utf-8")
+
+ from soup_cli.utils import reward_synth as rs
+
+ def _crash(*a, **kw):
+ raise MemoryError("worker crashed mid-calibration")
+
+ monkeypatch.setattr(rs, "calibrate", _crash)
+
+ _write_jsonl(Path("refs.jsonl"), [{"answer": "4"}, {"answer": "6"}])
+ res = self._runner().invoke(app, [
+ "synth", "refs.jsonl", "-o", "reward.py", "--force",
+ ])
+
+ assert res.exit_code == 1, (res.output, repr(res.exception))
+ assert Path("reward.py").exists(), (
+ "the previous verifier was deleted by a crash mid-calibration"
+ )
+ assert Path("reward.py").read_text(encoding="utf-8") == previous
+ leftover = list(tmp_path.glob(".soup.reward-candidate.*.py"))
+ assert not leftover, f"orphaned candidate file(s) left behind: {leftover}"
+
+ def test_candidate_write_failure_leaves_previous_verifier_untouched(
+ self, tmp_path, monkeypatch
+ ):
+ """The candidate is written to its own temp sibling, never to
+ ``output``. If that write fails (disk full, a permission error),
+ ``output`` was never touched in the first place — nothing to
+ restore, and no backup file to orphan."""
+ from soup_cli.commands.reward import app
+
+ monkeypatch.chdir(tmp_path)
+ previous = "# my working verifier\ndef reward_fn(completions, **kw):\n return [1.0]\n"
+ Path("reward.py").write_text(previous, encoding="utf-8")
+
+ import os as os_module
+
+ real_fdopen = os_module.fdopen
+
+ def _boom(fd, mode="r", *a, **kw):
+ # Only the candidate write ("w") is poisoned — _read_jsonl's own
+ # os.fdopen(fd, "r", ...) of refs.jsonl must keep working.
+ if mode == "w":
+ os_module.close(fd)
+ raise OSError(28, "No space left on device")
+ return real_fdopen(fd, mode, *a, **kw)
+
+ monkeypatch.setattr(os_module, "fdopen", _boom)
+
+ _write_jsonl(Path("refs.jsonl"), [{"answer": "4"}, {"answer": "6"}])
+ res = self._runner().invoke(app, [
+ "synth", "refs.jsonl", "-o", "reward.py", "--force",
+ ])
+
+ assert res.exit_code == 1, (res.output, repr(res.exception))
+ assert Path("reward.py").exists(), (
+ "the previous verifier was deleted on a failed candidate write"
+ )
+ assert Path("reward.py").read_text(encoding="utf-8") == previous
+ leftover = list(tmp_path.glob(".soup.reward-candidate.*.py"))
+ assert not leftover, f"orphaned candidate file(s) left behind: {leftover}"
+
+ def test_accepted_replace_still_writes_the_new_verifier(self, tmp_path, monkeypatch):
+ """The fix must not break the ordinary accepted path."""
+ from soup_cli.commands.reward import app
+
+ monkeypatch.chdir(tmp_path)
+ Path("reward.py").write_text("# stale\n", encoding="utf-8")
+ _write_jsonl(Path("refs.jsonl"), [{"answer": "4"}, {"answer": "6"}])
+
+ res = self._runner().invoke(app, [
+ "synth", "refs.jsonl", "-o", "reward.py", "--force",
+ ])
+
+ assert res.exit_code == 0, (res.output, repr(res.exception))
+ new_source = Path("reward.py").read_text(encoding="utf-8")
+ assert "stale" not in new_source
+ assert "reward_fn" in new_source
+ leftover = list(tmp_path.glob(".soup.reward-candidate.*.py"))
+ assert not leftover, f"orphaned candidate file(s) left behind: {leftover}"
+
+ def test_final_replace_failure_leaves_previous_verifier_and_no_orphan(
+ self, tmp_path, monkeypatch
+ ):
+ """The very last step — ``os.replace(candidate_path, output)`` on an
+ ACCEPTED candidate — must also be guarded. A lock held on ``output``
+ or a disk-full error at that exact point used to propagate as a raw
+ ``OSError`` traceback; it must instead exit cleanly (1), leave
+ ``output`` untouched, and clean up the now-useless candidate."""
+ from soup_cli.commands.reward import app
+
+ monkeypatch.chdir(tmp_path)
+ previous = "# my working verifier\ndef reward_fn(completions, **kw):\n return [1.0]\n"
+ Path("reward.py").write_text(previous, encoding="utf-8")
+
+ import os as os_module
+
+ real_replace = os_module.replace
+
+ def _replace_fails(src, dst, *a, **kw):
+ if os.path.basename(src).startswith(".soup.reward-candidate."):
+ raise OSError(28, "No space left on device")
+ return real_replace(src, dst, *a, **kw)
+
+ monkeypatch.setattr(os_module, "replace", _replace_fails)
+
+ _write_jsonl(Path("refs.jsonl"), [{"answer": "4"}, {"answer": "6"}])
+ res = self._runner().invoke(app, [
+ "synth", "refs.jsonl", "-o", "reward.py", "--force",
+ ])
+
+ assert res.exit_code == 1, (res.output, repr(res.exception))
+ assert res.exception is None or isinstance(res.exception, SystemExit), (
+ "a failed final replace must exit cleanly, not raise an uncaught OSError"
+ )
+ assert Path("reward.py").exists(), (
+ "the previous verifier was deleted by a failed final replace"
+ )
+ assert Path("reward.py").read_text(encoding="utf-8") == previous
+ leftover = list(tmp_path.glob(".soup.reward-candidate.*.py"))
+ assert not leftover, f"orphaned candidate file(s) left behind: {leftover}"
+
+
+# ---------------------------------------------------------------------------
+# adapter_fuse.merge_adapter_to_dense — a failed swap must not delete out_dir
+# ---------------------------------------------------------------------------
+class _Merged:
+ def save_pretrained(self, path):
+ Path(path).joinpath("model.safetensors").write_bytes(b"NEW")
+
+
+class _Base:
+ @staticmethod
+ def from_pretrained(*a, **kw):
+ return _Base()
+
+
+class _Peft:
+ @staticmethod
+ def from_pretrained(*a, **kw):
+ obj = _Peft()
+ obj.merge_and_unload = lambda: _Merged() # noqa: E731
+ return obj
+
+
+class _Tok:
+ @staticmethod
+ def from_pretrained(*a, **kw):
+ return _Tok()
+
+ def save_pretrained(self, path):
+ Path(path).joinpath("tokenizer.json").write_bytes(b"NEW")
+
+
+def _fake_train_stack(monkeypatch):
+ fake_tf = types.ModuleType("transformers")
+ fake_tf.AutoModelForCausalLM = _Base
+ fake_tf.AutoTokenizer = _Tok
+ fake_peft = types.ModuleType("peft")
+ fake_peft.PeftModel = _Peft
+ monkeypatch.setitem(sys.modules, "transformers", fake_tf)
+ monkeypatch.setitem(sys.modules, "peft", fake_peft)
+
+
+def _fresh_adapter_and_out(tmp_path):
+ adapter = tmp_path / "adapter"
+ adapter.mkdir()
+ out = tmp_path / "out"
+ out.mkdir()
+ for name in ("config.json", "model.safetensors", "tokenizer.json"):
+ (out / name).write_bytes(b"OLD")
+ return adapter, out
+
+
+class TestMergeAdapterToDenseSurvivesAFailedSwap:
+ def test_out_dir_survives_when_os_replace_raises(self, tmp_path, monkeypatch):
+ """A real-world failure: an antivirus scanner or search indexer holds
+ the staging dir just long enough that the final os.replace raises.
+ Before the fix, the destination was already rmtree'd by then, and the
+ except-handler deleted the staging copy too — both copies gone."""
+ from soup_cli.utils import adapter_fuse
+
+ monkeypatch.chdir(tmp_path)
+ _fake_train_stack(monkeypatch)
+ adapter, out = _fresh_adapter_and_out(tmp_path)
+
+ real_replace = adapter_fuse.os.replace
+
+ def _replace_fails(src, dst, *a, **kw):
+ if os.path.basename(src).startswith(".fuse_"):
+ raise PermissionError(5, "Access is denied")
+ return real_replace(src, dst, *a, **kw)
+
+ monkeypatch.setattr(adapter_fuse.os, "replace", _replace_fails)
+
+ with pytest.raises(PermissionError):
+ adapter_fuse.merge_adapter_to_dense(
+ base_model="base", adapter_dir=str(adapter), out_dir="out"
+ )
+
+ # The swap failed but the rename-back succeeded (only os.replace of a
+ # ``.fuse_*`` source was poisoned above): out/ must hold the ORIGINAL
+ # bytes, restored, with nothing left behind — no leftover staging
+ # dir and no leftover ``.old-`` backup. A test that merely asked for
+ # "old survives OR a copy landed somewhere" would still pass even if
+ # the restore-on-failure block were deleted outright (the untouched
+ # staging dir alone would satisfy it), so both conditions are
+ # asserted together.
+ assert (out / "config.json").read_bytes() == b"OLD"
+ assert (out / "model.safetensors").read_bytes() == b"OLD"
+ assert (out / "tokenizer.json").read_bytes() == b"OLD"
+ leftover = list(tmp_path.glob(".fuse_*")) + list(tmp_path.glob(".out.old-*"))
+ assert not leftover, f"orphaned staging/backup dir(s) left behind: {leftover}"
+
+ def test_out_dir_survives_when_rmtree_is_reintroduced_and_fails_partway(
+ self, tmp_path, monkeypatch
+ ):
+ """Regression guard for the original bug shape: the pre-fix code
+ called ``shutil.rmtree(out_dir)`` directly, and a version of that
+ call which fails after deleting only SOME files left ``out_dir``
+ half-destroyed with no backup to restore. The fixed implementation
+ must never call ``shutil.rmtree`` on ``out_dir`` at all — it renames
+ it aside instead — so poisoning rmtree for that exact path must have
+ no effect on an otherwise-successful merge."""
+ from soup_cli.utils import adapter_fuse
+
+ monkeypatch.chdir(tmp_path)
+ _fake_train_stack(monkeypatch)
+ adapter, out = _fresh_adapter_and_out(tmp_path)
+ out_real = str(out.resolve())
+
+ real_rmtree = shutil.rmtree
+ poisoned_calls = []
+
+ def _rmtree_partial_then_raise(path, *a, **kw):
+ if os.path.realpath(path) == out_real:
+ poisoned_calls.append(path)
+ # Simulate the old failure mode: delete one file, then blow up
+ # before the rest (and before any replacement is in place).
+ victim = os.path.join(path, "config.json")
+ if os.path.exists(victim):
+ os.remove(victim)
+ raise OSError(13, "Permission denied (partial rmtree)")
+ return real_rmtree(path, *a, **kw)
+
+ # adapter_fuse does ``import shutil`` locally inside the function body
+ # (heavy imports stay function-local there); that binds the same
+ # cached module object, so patching the shutil module directly here
+ # reaches it.
+ monkeypatch.setattr(shutil, "rmtree", _rmtree_partial_then_raise)
+
+ adapter_fuse.merge_adapter_to_dense(
+ base_model="base", adapter_dir=str(adapter), out_dir="out"
+ )
+
+ assert not poisoned_calls, (
+ "merge_adapter_to_dense called shutil.rmtree(out_dir) directly — "
+ "the destination must be renamed aside, never rmtree'd"
+ )
+ # The fake save_pretrained()s only write model.safetensors /
+ # tokenizer.json (no config.json) — a successful merge replaces
+ # out_dir with exactly the staged content, so config.json from the
+ # old model is gone and must not be asserted here.
+ assert (out / "model.safetensors").read_bytes() == b"NEW"
+ assert (out / "tokenizer.json").read_bytes() == b"NEW"
+ leftover = list(tmp_path.glob(".fuse_*")) + list(tmp_path.glob(".out.old-*"))
+ assert not leftover, f"orphaned staging/backup dir(s) left behind: {leftover}"
+
+ def test_both_swap_and_restore_fail_keeps_both_copies_and_names_both_paths(
+ self, tmp_path, monkeypatch
+ ):
+ """The double-failure path the issue calls out explicitly: the swap
+ AND the rename-back both fail. Neither ``backup`` nor ``staging`` may
+ be deleted then — the code must not guess which one holds the good
+ copy — and the raised error must name both paths so a human can
+ recover by hand.
+
+ Mutation check: this is what catches ``if not keep_staging:`` being
+ replaced by ``if True:`` at the bottom of the function — that
+ mutation makes the ``except BaseException`` handler always
+ ``rmtree(staging)``, which would delete the *only* surviving copy in
+ this exact scenario. Without this test, that mutation still leaves
+ the other tests in this file green.
+ """
+ from soup_cli.utils import adapter_fuse
+
+ monkeypatch.chdir(tmp_path)
+ _fake_train_stack(monkeypatch)
+ adapter, out = _fresh_adapter_and_out(tmp_path)
+
+ real_replace = adapter_fuse.os.replace
+
+ def _replace_fails_both(src, dst, *a, **kw):
+ name = os.path.basename(src)
+ if name.startswith(".fuse_") or ".old-" in name:
+ raise PermissionError(5, "Access is denied")
+ return real_replace(src, dst, *a, **kw)
+
+ monkeypatch.setattr(adapter_fuse.os, "replace", _replace_fails_both)
+
+ with pytest.raises(RuntimeError) as excinfo:
+ adapter_fuse.merge_adapter_to_dense(
+ base_model="base", adapter_dir=str(adapter), out_dir="out"
+ )
+
+ message = str(excinfo.value)
+ staging_dirs = list(tmp_path.glob(".fuse_*"))
+ backup_dirs = list(tmp_path.glob(".out.old-*"))
+ assert len(staging_dirs) == 1, f"staging dir missing or duplicated: {staging_dirs}"
+ assert len(backup_dirs) == 1, f"backup dir missing or duplicated: {backup_dirs}"
+ assert str(backup_dirs[0]) in message, "error does not name the backup path"
+ assert str(staging_dirs[0]) in message, "error does not name the staging path"
+
+ # Both copies must be complete, not partially written or removed.
+ assert (backup_dirs[0] / "config.json").read_bytes() == b"OLD"
+ assert (backup_dirs[0] / "model.safetensors").read_bytes() == b"OLD"
+ assert (staging_dirs[0] / "model.safetensors").read_bytes() == b"NEW"
+ assert not out.exists(), "out_dir should be absent — neither replace landed there"
+
+ def test_backup_rename_failure_keeps_old_model_and_new_staging(
+ self, tmp_path, monkeypatch
+ ):
+ """The rename that moves the previous model aside can hit the same
+ lock as the swap. out_dir is then untouched, so the new merge in
+ staging is the only copy of it and must not be deleted."""
+ from soup_cli.utils import adapter_fuse
+
+ monkeypatch.chdir(tmp_path)
+ _fake_train_stack(monkeypatch)
+ adapter, out = _fresh_adapter_and_out(tmp_path)
+
+ real_replace = adapter_fuse.os.replace
+
+ def _backup_fails(src, dst, *a, **kw):
+ if ".old-" in os.path.basename(dst):
+ raise PermissionError(5, "Access is denied")
+ return real_replace(src, dst, *a, **kw)
+
+ monkeypatch.setattr(adapter_fuse.os, "replace", _backup_fails)
+
+ with pytest.raises(RuntimeError) as excinfo:
+ adapter_fuse.merge_adapter_to_dense(
+ base_model="base", adapter_dir=str(adapter), out_dir="out"
+ )
+
+ assert (out / "model.safetensors").read_bytes() == b"OLD"
+ staging_dirs = list(tmp_path.glob(".fuse_*"))
+ assert len(staging_dirs) == 1, f"staging dir missing: {staging_dirs}"
+ assert (staging_dirs[0] / "model.safetensors").read_bytes() == b"NEW"
+ assert str(staging_dirs[0]) in str(excinfo.value)
+ assert not list(tmp_path.glob(".out.old-*"))
+
+ @pytest.mark.skipif(sys.platform != "win32", reason="Windows-only file-lock semantics")
+ def test_out_dir_survives_an_open_handle_on_model_safetensors(self, tmp_path, monkeypatch):
+ """Windows-only: another process (a viewer, a server, an antivirus
+ scan) holds ``out_dir/model.safetensors`` open, so the rename-aside
+ fails. The old model must be untouched and the merged model kept at
+ the staging path the error names."""
+ from soup_cli.utils import adapter_fuse
+
+ monkeypatch.chdir(tmp_path)
+ _fake_train_stack(monkeypatch)
+ adapter, out = _fresh_adapter_and_out(tmp_path)
+
+ handle = open(out / "model.safetensors", "rb")
+ try:
+ # Windows refuses to rename a directory that holds an open file, so
+ # the rename-aside fails: a RuntimeError that names the staged model.
+ with pytest.raises(RuntimeError, match="move the previous model") as excinfo:
+ adapter_fuse.merge_adapter_to_dense(
+ base_model="base", adapter_dir=str(adapter), out_dir="out"
+ )
+ finally:
+ handle.close()
+
+ # The old model is complete and untouched ...
+ for name in ("config.json", "model.safetensors", "tokenizer.json"):
+ assert (out / name).read_bytes() == b"OLD"
+ # ... and the merged model survives at the path the error names.
+ staging_dirs = list(tmp_path.glob(".fuse_*"))
+ assert len(staging_dirs) == 1, staging_dirs
+ assert (staging_dirs[0] / "model.safetensors").read_bytes() == b"NEW"
+ assert staging_dirs[0].name in str(excinfo.value)
+ assert not list(tmp_path.glob(".out.old-*"))
+