Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.
Python cliconsumer-gpudpofine-tuningggufhuggingfacellmllmopslocal-ailocal-llmloralow-vrammachine-learningollamapeftpythonpytorchqlorasfttransformers
fix: soup init and the MCP plan snapshot refuse links at their write target (#1553)
Alpamys Makazhan4e3ab348994d
diff --git a/changelog.d/0.75.1/1553.fixed.md b/changelog.d/0.75.1/1553.fixed.mdnew file mode 100644index 00000000..3c533ae9--- /dev/null+++ b/changelog.d/0.75.1/1553.fixed.md@@ -0,0 +1,2 @@+- **`soup init` refuses a symbolic link, junction or other reparse point at the config path it writes, and MCP planning creates the config snapshot's run directory fresh (#1553).**+ `soup init` wrote the starter config with a plain write that follows a link at the target (`soup.yaml` or `--output`), and a dangling link even skipped the overwrite prompt. It now refuses a symbolic link, junction or other reparse point there before prompting or running the wizard, naming the path, matching the link refusal the other config writers apply, and it creates or opens the file without following a link that appears there afterwards: nothing is written through such a link and nothing is created at its target. Ordinary paths, including ones outside the working directory or reached through a linked parent directory, behave as before. Following #1492, `train_start` under `soup mcp serve` now also checks the run directory `.soup/mcp-runs/<run_id>` itself, creates it with `exist_ok=False`, and creates `config.yaml` exclusively (`O_EXCL`) without following a link, refusing the plan with a path-free error when the run directory or the file already exists or is a link.diff --git a/docs/commands.md b/docs/commands.mdindex 0f0a2a7f..3d1b698f 100644--- a/docs/commands.md+++ b/docs/commands.md@@ -500,7 +500,7 @@ mutating tools (`train_start`, `export`) are gated behind `--allow-mutating`**Execution Security & Boundaries:**- **Flag Safety:** `--allow-execute` is default-off and dangerous. `--allow-mutating` alone can NEVER trigger subprocess execution.- **One-Time Confirmation Tokens:** Authorization requires a server-issued random token. Client confirmation is UX-only; security relies entirely on the server-side token state.-- **Subprocess Isolation:** Execution runs the Soup CLI as an isolated subprocess (`shell=False`, `stdin=DEVNULL`, `cwd` pinned to server startup directory). Child stdout/stderr is redirected to `.soup/mcp-runs/<run_id>.log` to avoid corrupting the MCP JSON-RPC stdio stream. Planning (`train_start` config snapshot) and execution are refused if `.soup` or `.soup/mcp-runs` is a symbolic link or junction, or if a hard link exists at the run log path.+- **Subprocess Isolation:** Execution runs the Soup CLI as an isolated subprocess (`shell=False`, `stdin=DEVNULL`, `cwd` pinned to server startup directory). Child stdout/stderr is redirected to `.soup/mcp-runs/<run_id>.log` to avoid corrupting the MCP JSON-RPC stdio stream. Planning (`train_start` config snapshot) and execution are refused if `.soup` or `.soup/mcp-runs` is a symbolic link or junction, or if a hard link exists at the run log path. Planning also refuses a link or anything already present at the run directory `.soup/mcp-runs/<run_id>`: the snapshot is written only into a run directory the plan has just created, with `config.yaml` created exclusively and without following a link.- **Concurrency & Disconnects:** Enforces 1 active execution at a time, gated on a persisted run whose process is still alive — so a **restarted** server does not launch a second training while a child from a previous server is still running, and a stale record whose process is gone never blocks execution. A `launching` record (committed before the child process exists, pid not yet written) blocks restart capacity too: it is indistinguishable from "about to spawn", so treating it as live is the safe direction after a crash in that window. If a server crash leaves that row behind, `soup mcp runs reconcile --expunge-launching` removes rows older than five minutes and prints every removed `run_id`; use `--older-than-seconds N` to choose another positive threshold. The command refuses the whole operation if any candidate records a PID that is still alive. Launches run in background (fire-and-forget). Disconnecting the MCP client does not terminate an already-running subprocess.- **Config Snapshotting & Input Revalidation:** At plan time (`train_start`), the validated config is snapshotted to `.soup/mcp-runs/<run_id>/config.yaml`, and execution uses this snapshot rather than the original mutable config path. External protected inputs (such as datasets and model/checkpoint directories or files) are not frozen in the snapshot; instead, their content digests (computed via SHA-256 for regular files, or deterministic recursive content hashing over sorted relative file paths for directory trees, bounded by file-count and total-byte safety limits) are recorded at plan time and revalidated immediately before spawn. Modifying an external protected input between plan and execute invalidates the token. Modifying the original config path after planning has no effect because execution strictly uses the snapshotted config. Snapshotting freezes only the configuration itself, not external filesystem assets.- **Every Local Input Is Pinned:** A train plan pins every local file or directory the run reads (model, datasets, reward/teacher/PRM models, reward `.py` files, unlearning sets); an input outside the working directory is refused at plan time, and an input that did not exist at plan time must still not exist at execution.diff --git a/src/soup_cli/commands/init.py b/src/soup_cli/commands/init.pyindex d6251b5b..a5d3a8d8 100644--- a/src/soup_cli/commands/init.py+++ b/src/soup_cli/commands/init.py@@ -1,5 +1,9 @@"""soup init — interactive project setup wizard."""+import errno+import os+import stat+import tempfilefrom pathlib import Pathimport typer@@ -8,10 +12,106 @@ from rich.panel import Panelfrom rich.prompt import Promptfrom soup_cli.templates import list_templates, load_template+from soup_cli.utils.paths import open_no_follow, refuse_linked_dirs+from soup_cli.utils.terminal import for_terminalconsole = Console()+def _print_link_refusal(output: str) -> None:+ console.print(+ f"[red]{for_terminal(output)} is a symbolic link, junction or other reparse "+ "point; soup init does not write through it.[/]\n"+ "Remove it or choose a different --output."+ )+++def _refuse_link_at(output: str) -> None:+ """Exit 1 when the starter config path is a symbolic link, junction or other reparse point.++ Only the target itself is inspected (``stop_at`` is its own parent); the+ directories above it are where the user chose to write.+ """+ output_path = Path(output)+ try:+ refuse_linked_dirs(output_path, stop_at=output_path.parent)+ except OSError as exc:+ if exc.errno != errno.ELOOP:+ raise+ _print_link_refusal(output)+ raise typer.Exit(1) from exc+++def _create_by_rename(output: str, config_text: str) -> None:+ """Create ``output`` on Windows without following anything that appears there.++ On Windows an exclusive create (``O_CREAT | O_EXCL``) still follows a+ dangling symbolic link and creates the link's target. A rename does not:+ ``os.rename`` fails on Windows when anything, a link or junction included,+ exists at the destination. So the config is written to a staging file next+ to ``output`` and renamed into place; mode and bytes match a direct write.+ """+ parent = os.path.dirname(os.path.abspath(output))+ fd, staging = tempfile.mkstemp(prefix=".soup-init.", suffix=".tmp", dir=parent)+ try:+ with os.fdopen(fd, "w", encoding="utf-8") as handle:+ handle.write(config_text)+ os.rename(staging, output)+ except BaseException:+ try:+ os.unlink(staging)+ except OSError:+ pass+ raise+++def _write_config(output: str, config_text: str) -> None:+ """Write ``config_text`` to ``output`` without following a link there.++ Nothing is created or written through a link that appears at ``output``+ after :func:`_refuse_link_at` checked it:++ * a new file is created exclusively: ``O_CREAT | O_EXCL`` with+ ``O_NOFOLLOW`` through ``open_no_follow`` on POSIX, and+ :func:`_create_by_rename` on Windows;+ * an existing file is opened without ``O_CREAT`` through ``open_no_follow``+ (``O_NOFOLLOW`` on POSIX, an lstat/fstat cross-check on Windows), so a+ dangling link swapped in for it cannot get its target created, and it is+ truncated only after that check has passed, so a refused open leaves a+ link's target untouched.++ A failure is reported as the link refusal when the target is a link by+ then, and as itself otherwise. Mode, truncation and newline handling match+ the ``Path.write_text`` this replaces.+ """+ creating = not os.path.lexists(output)+ try:+ if creating and os.name == "nt":+ _create_by_rename(output, config_text)+ return+ flags = os.O_WRONLY | getattr(os, "O_BINARY", 0)+ if creating:+ flags |= os.O_CREAT | os.O_EXCL+ fd = open_no_follow(output, flags, 0o666)+ except OSError as exc:+ if exc.errno != errno.ELOOP:+ # The target may have changed after the check: refuse it if it is+ # a link now, otherwise report the original error.+ _refuse_link_at(output)+ raise+ _print_link_refusal(output)+ raise typer.Exit(1) from exc+ try:+ # O_TRUNC semantics: only a regular file is truncated.+ if stat.S_ISREG(os.fstat(fd).st_mode):+ os.ftruncate(fd, 0)+ except OSError:+ os.close(fd)+ raise+ with os.fdopen(fd, "w", encoding="utf-8") as handle:+ handle.write(config_text)++def _template_help_string() -> str:"""v0.40.1 Part D / H4 — generate help dynamically from the registry sothe list never drifts away from `templates/manifest.json`.@@ -41,6 +141,7 @@ def init():"""Create a new soup.yaml config interactively or from a template."""output_path = Path(output)+ _refuse_link_at(output)if output_path.exists() and not force:overwrite = typer.confirm(f"{output_path} already exists. Overwrite?")@@ -57,7 +158,7 @@ def init(else:config_text = _interactive_wizard()- output_path.write_text(config_text, encoding="utf-8")+ _write_config(output, config_text)console.print(Panel(f"[bold green]Config saved to {output_path}[/]\n\n"diff --git a/src/soup_cli/mcp_server/execution.py b/src/soup_cli/mcp_server/execution.pyindex ddd6c1fa..c8daae13 100644--- a/src/soup_cli/mcp_server/execution.py+++ b/src/soup_cli/mcp_server/execution.py@@ -7,6 +7,7 @@ import hashlibimport jsonimport loggingimport os+import reimport secretsimport statimport subprocess@@ -17,7 +18,6 @@ from pathlib import Pathfrom soup_cli.experiment.tracker import ExperimentTracker, generate_run_idfrom soup_cli.utils.paths import (- atomic_write_text,enforce_under_cwd_and_no_symlink,open_no_follow,refuse_linked_dirs,@@ -41,6 +41,10 @@ _STATUS_RUNNING = "running"# in between leaves a row stuck here with no pid to check liveness against._STATUS_LAUNCHING = "launching"+# A run id names one directory under .soup/mcp-runs: no separator, no "." or+# "..", no NUL. generate_run_id() always matches (run_YYYYMMDD_HHMMSS_<hex>).+_SNAPSHOT_RUN_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}")+class ExecutionError(ValueError):"""Safe execution failure intended for translation to an MCP tool error."""@@ -186,6 +190,18 @@ def digest_file(return ProtectedFile(path=real, digest=digest)+def _snapshot_refusal(exc: OSError) -> str:+ """The path-free reason a plan-time config snapshot could not be written."""+ if exc.errno == errno.ELOOP:+ return (+ "cannot plan: config snapshot directory or file is a "+ "symbolic link or junction"+ )+ if exc.errno == errno.EEXIST:+ return "cannot plan: config snapshot directory or file already exists"+ return f"cannot plan: could not write the config snapshot ({type(exc).__name__})"++class ExecutionManager:"""Per-stdio-server plan store, one-job cap, and subprocess watcher."""@@ -200,18 +216,40 @@ class ExecutionManager:return generate_run_id()def snapshot_config(self, run_id: str, content: str) -> str:- """Write the exact validated config content to .soup/mcp-runs/<run_id>/config.yaml."""- run_dir = Path(self.cwd) / ".soup" / "mcp-runs" / run_id+ """Write the exact validated config content to .soup/mcp-runs/<run_id>/config.yaml.++ Nothing is written through a link or into a directory this call did not+ create. ``.soup``, ``.soup/mcp-runs`` and the run directory itself are+ refused when one of them is a symbolic link or junction (#1211); the run+ directory must not exist yet and is created here; and ``config.yaml`` is+ created with ``O_EXCL`` through :func:`open_no_follow`, which inspects the+ parent directories again at open time. Every refusal is a path-free+ :class:`ExecutionError`. A process with concurrent write access inside+ ``.soup`` can still race these checks; that is the same window the run+ log open in :meth:`execute` accepts.+ """+ if not isinstance(run_id, str) or not _SNAPSHOT_RUN_ID.fullmatch(run_id):+ raise ExecutionError("cannot plan: invalid run id for the config snapshot")+ runs_root = Path(self.cwd) / ".soup" / "mcp-runs"+ run_dir = runs_root / run_id+ snapshot_file = run_dir / "config.yaml"try:- refuse_linked_dirs(run_dir.parent, stop_at=self.cwd)+ refuse_linked_dirs(run_dir, stop_at=self.cwd)+ runs_root.mkdir(parents=True, exist_ok=True)+ # Check again now that the parents exist, so the run directory is+ # never created through a link that replaced one of them meanwhile.+ refuse_linked_dirs(runs_root, stop_at=self.cwd)+ run_dir.mkdir()+ snapshot_fd = open_no_follow(+ snapshot_file,+ os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_BINARY", 0),+ 0o600,+ check_parent=True,+ )+ with os.fdopen(snapshot_fd, "w", encoding="utf-8") as handle:+ handle.write(content)except OSError as exc:- raise ExecutionError(- "cannot plan: config snapshot directory or file is a "- "symbolic link or junction"- ) from exc- run_dir.mkdir(parents=True, exist_ok=True)- snapshot_file = str(run_dir / "config.yaml")- atomic_write_text(content, snapshot_file, field="config snapshot")+ raise ExecutionError(_snapshot_refusal(exc)) from excreturn os.path.realpath(snapshot_file)def issue(diff --git a/tests/test_init_output_link.py b/tests/test_init_output_link.pynew file mode 100644index 00000000..d5ca141f--- /dev/null+++ b/tests/test_init_output_link.py@@ -0,0 +1,367 @@+"""`soup init` refuses a symbolic link, junction or other reparse point at the starter config path.++The other config writers reach the file through the shared helpers in+``soup_cli.utils.paths``, which refuse a link at the write target. ``soup init``+wrote with ``Path.write_text``, which follows one, so a ``soup.yaml`` link sent+the starter config wherever the link pointed (a dangling link even skipped the+overwrite prompt). Every test here drives the real command through+``CliRunner``. Ordinary targets, including ones outside the working directory+and ones reached through a linked parent directory, keep their previous+behaviour.+"""++from __future__ import annotations++import errno+import os+import stat+from pathlib import Path++import pytest+from typer.testing import CliRunner++from soup_cli.cli import app+from soup_cli.templates import load_template+from tests.conftest import strip_ansi++runner = CliRunner()++#: Wide enough that Rich never folds a temp-directory path across lines.+WIDE = {"COLUMNS": "1000"}++ORIGINAL = "content that soup init must leave alone\n"++REFUSAL = "is a symbolic link, junction or other reparse point"+++def _plain(text: str) -> str:+ return " ".join(strip_ansi(text).split())+++def _init(*args: str, **kwargs):+ return runner.invoke(app, ["init", *args], env=WIDE, **kwargs)+++def _control(tmp_path: Path, template: str) -> Path:+ """A file written the way ``soup init`` wrote before: ``Path.write_text``."""+ control = tmp_path / "control.yaml"+ control.write_text(load_template(template), encoding="utf-8")+ return control+++def _just_before_writing(monkeypatch, path: Path, change) -> list:+ """Call ``change()`` in the last moment before ``path`` is created or opened.++ A new file is created with ``os.open`` on POSIX and by renaming a staging+ file onto ``path`` on Windows; an existing file is opened with ``os.open``.+ Both calls are hooked, so the change lands right before whichever one runs.+ The returned list is non-empty once ``change()`` has run.+ """+ changed = []+ real_open = os.open+ real_rename = os.rename++ def change_once(target):+ if os.fspath(target) == str(path) and not changed:+ changed.append(True)+ change()++ def open_hook(file, flags, *args, **kwargs):+ change_once(file)+ return real_open(file, flags, *args, **kwargs)++ def rename_hook(src, dst, *args, **kwargs):+ change_once(dst)+ return real_rename(src, dst, *args, **kwargs)++ monkeypatch.setattr(os, "open", open_hook)+ monkeypatch.setattr(os, "rename", rename_hook)+ return changed+++class TestALinkAtTheOutputPath:+ @pytest.mark.requires_symlink+ def test_force_does_not_write_through_a_file_symlink(self, tmp_path):+ victim = tmp_path / "victim.txt"+ victim.write_text(ORIGINAL, encoding="utf-8")+ link = tmp_path / "soup.yaml"+ os.symlink(str(victim), str(link))++ result = _init("--template", "chat", "--output", str(link), "--force")++ assert result.exit_code == 1, (result.output, repr(result.exception))+ out = _plain(result.output)+ assert str(link) in out+ assert REFUSAL in out+ assert victim.read_text(encoding="utf-8") == ORIGINAL+ assert os.path.islink(link)++ @pytest.mark.requires_symlink+ def test_refused_before_the_overwrite_prompt(self, tmp_path):+ victim = tmp_path / "victim.txt"+ victim.write_text(ORIGINAL, encoding="utf-8")+ link = tmp_path / "soup.yaml"+ os.symlink(str(victim), str(link))++ result = _init("--template", "chat", "--output", str(link), input="y\n")++ assert result.exit_code == 1, (result.output, repr(result.exception))+ out = _plain(result.output)+ assert REFUSAL in out+ assert "Overwrite?" not in out+ assert victim.read_text(encoding="utf-8") == ORIGINAL++ @pytest.mark.requires_symlink+ def test_refused_before_the_wizard_runs(self, tmp_path):+ victim = tmp_path / "victim.txt"+ victim.write_text(ORIGINAL, encoding="utf-8")+ link = tmp_path / "soup.yaml"+ os.symlink(str(victim), str(link))++ result = _init("--output", str(link), "--force")++ assert result.exit_code == 1, (result.output, repr(result.exception))+ out = _plain(result.output)+ assert REFUSAL in out+ assert "Soup Config Wizard" not in out+ assert victim.read_text(encoding="utf-8") == ORIGINAL++ @pytest.mark.requires_symlink+ def test_dangling_symlink_creates_nothing(self, tmp_path):+ missing = tmp_path / "created-through-the-link.yaml"+ link = tmp_path / "soup.yaml"+ os.symlink(str(missing), str(link))++ result = _init("--template", "chat", "--output", str(link))++ assert result.exit_code == 1, (result.output, repr(result.exception))+ assert REFUSAL in _plain(result.output)+ assert not os.path.lexists(missing)++ @pytest.mark.skipif(os.name != "nt", reason="Windows junctions only exist on Windows")+ def test_junction_at_the_output_path_is_refused(self, tmp_path):+ import _winapi++ elsewhere = tmp_path / "elsewhere"+ elsewhere.mkdir()+ junction = tmp_path / "soup.yaml"+ _winapi.CreateJunction(str(elsewhere), str(junction))++ result = _init("--template", "chat", "--output", str(junction), "--force")++ assert result.exit_code == 1, (result.output, repr(result.exception))+ out = _plain(result.output)+ assert str(junction) in out+ assert REFUSAL in out+ assert not any(elsewhere.iterdir())++ @pytest.mark.requires_symlink+ def test_link_placed_after_the_first_check_is_refused(self, tmp_path, monkeypatch):+ """The write itself does not follow a link, whenever the link appeared."""+ import soup_cli.commands.init as init_module++ victim = tmp_path / "victim.txt"+ victim.write_text(ORIGINAL, encoding="utf-8")+ link = tmp_path / "soup.yaml"+ real_load_template = init_module.load_template++ def load_then_link(name):+ text = real_load_template(name)+ os.symlink(str(victim), str(link))+ return text++ monkeypatch.setattr(init_module, "load_template", load_then_link)+ result = _init("--template", "chat", "--output", str(link))++ assert result.exit_code == 1, (result.output, repr(result.exception))+ assert REFUSAL in _plain(result.output)+ assert victim.read_text(encoding="utf-8") == ORIGINAL++ @pytest.mark.requires_symlink+ def test_link_placed_just_before_the_file_is_created_leaves_its_target_intact(+ self, tmp_path, monkeypatch+ ):+ victim = tmp_path / "victim.txt"+ victim.write_text(ORIGINAL, encoding="utf-8")+ link = tmp_path / "soup.yaml"++ changed = _just_before_writing(+ monkeypatch, link, lambda: os.symlink(str(victim), str(link))+ )+ result = _init("--template", "chat", "--output", str(link))+ monkeypatch.undo()++ assert changed, "the write never reached the call that creates the file"+ assert result.exit_code == 1, (result.output, repr(result.exception))+ assert REFUSAL in _plain(result.output)+ assert victim.read_text(encoding="utf-8") == ORIGINAL++ @pytest.mark.requires_symlink+ def test_dangling_link_placed_just_before_the_file_is_created_creates_nothing(+ self, tmp_path, monkeypatch+ ):+ """An exclusive create still follows a dangling link on Windows; this one must not."""+ missing = tmp_path / "created-through-the-link.yaml"+ link = tmp_path / "soup.yaml"++ changed = _just_before_writing(+ monkeypatch, link, lambda: os.symlink(str(missing), str(link))+ )+ result = _init("--template", "chat", "--output", str(link))+ monkeypatch.undo()++ assert changed, "the write never reached the call that creates the file"+ assert result.exit_code == 1, (result.output, repr(result.exception))+ assert REFUSAL in _plain(result.output)+ assert not os.path.lexists(missing)+ assert os.path.islink(link)++ @pytest.mark.requires_symlink+ def test_existing_file_swapped_for_a_link_just_before_the_open_leaves_its_target_intact(+ self, tmp_path, monkeypatch+ ):+ """No truncation happens before the open-time link check has passed."""+ victim = tmp_path / "victim.txt"+ victim.write_text(ORIGINAL, encoding="utf-8")+ output = tmp_path / "soup.yaml"+ output.write_text("# the user's own config\n", encoding="utf-8")++ def swap():+ os.unlink(output)+ os.symlink(str(victim), str(output))++ changed = _just_before_writing(monkeypatch, output, swap)+ result = _init("--template", "chat", "--output", str(output), "--force")+ monkeypatch.undo()++ assert changed, "the write never reached the call that opens the file"+ assert result.exit_code == 1, (result.output, repr(result.exception))+ assert REFUSAL in _plain(result.output)+ assert victim.read_text(encoding="utf-8") == ORIGINAL++ @pytest.mark.requires_symlink+ def test_existing_file_swapped_for_a_dangling_link_just_before_the_open_creates_nothing(+ self, tmp_path, monkeypatch+ ):+ """An existing file is opened without O_CREAT, so a dangling link's target is never made."""+ missing = tmp_path / "created-through-the-link.yaml"+ output = tmp_path / "soup.yaml"+ output.write_text("# the user's own config\n", encoding="utf-8")++ def swap():+ os.unlink(output)+ os.symlink(str(missing), str(output))++ changed = _just_before_writing(monkeypatch, output, swap)+ result = _init("--template", "chat", "--output", str(output), "--force")+ monkeypatch.undo()++ assert changed, "the write never reached the call that opens the file"+ assert result.exit_code == 1, (result.output, repr(result.exception))+ assert REFUSAL in _plain(result.output)+ assert not os.path.lexists(missing)+++class TestOtherErrorsAreReportedAsThemselves:+ def test_missing_parent_directory_is_not_reported_as_a_link(self, tmp_path):+ output = tmp_path / "missing" / "soup.yaml"++ result = _init("--template", "chat", "--output", str(output))++ assert result.exit_code == 1, (result.output, repr(result.exception))+ assert isinstance(result.exception, FileNotFoundError), repr(result.exception)+ out = _plain(result.output)+ assert REFUSAL not in out+ assert "symbolic link" not in out+ assert not (tmp_path / "missing").exists()++ def test_an_error_inspecting_the_target_is_not_reported_as_a_link(+ self, tmp_path, monkeypatch+ ):+ import soup_cli.commands.init as init_module++ def unreadable(path, *, stop_at=None):+ raise PermissionError(errno.EACCES, "Permission denied", str(path))++ monkeypatch.setattr(init_module, "refuse_linked_dirs", unreadable)+ result = _init("--template", "chat", "--output", str(tmp_path / "soup.yaml"))++ assert result.exit_code == 1, (result.output, repr(result.exception))+ assert isinstance(result.exception, PermissionError), repr(result.exception)+ assert REFUSAL not in _plain(result.output)+ assert not (tmp_path / "soup.yaml").exists()+++class TestOrdinaryPathsAreUnchanged:+ def test_new_file_is_byte_identical_to_the_previous_writer(self, tmp_path):+ output = tmp_path / "soup.yaml"++ result = _init("--template", "chat", "--output", str(output))++ assert result.exit_code == 0, (result.output, repr(result.exception))+ assert output.read_bytes() == _control(tmp_path, "chat").read_bytes()+ assert not os.path.islink(output)+ assert "Config saved to" in _plain(result.output)+ assert sorted(p.name for p in tmp_path.iterdir()) == ["control.yaml", "soup.yaml"]++ def test_new_file_gets_the_same_permissions_as_before(self, tmp_path):+ output = tmp_path / "soup.yaml"++ result = _init("--template", "chat", "--output", str(output))++ assert result.exit_code == 0, (result.output, repr(result.exception))+ control = _control(tmp_path, "chat")+ assert stat.S_IMODE(output.stat().st_mode) == stat.S_IMODE(control.stat().st_mode)++ def test_force_replaces_a_longer_regular_file_completely(self, tmp_path):+ output = tmp_path / "soup.yaml"+ output.write_text("# old\n" * 20_000, encoding="utf-8")++ result = _init("--template", "chat", "--output", str(output), "--force")++ assert result.exit_code == 0, (result.output, repr(result.exception))+ assert output.read_bytes() == _control(tmp_path, "chat").read_bytes()++ def test_null_device_is_still_a_valid_output(self):+ """Only a regular file is truncated, as O_TRUNC did; a device is written as before."""+ result = _init("--template", "chat", "--output", os.devnull, "--force")++ assert result.exit_code == 0, (result.output, repr(result.exception))+ assert "Config saved to" in _plain(result.output)++ def test_confirmed_overwrite_of_a_regular_file_still_works(self, tmp_path):+ output = tmp_path / "soup.yaml"+ output.write_text(ORIGINAL, encoding="utf-8")++ result = _init("--template", "chat", "--output", str(output), input="y\n")++ assert result.exit_code == 0, (result.output, repr(result.exception))+ assert "Overwrite?" in _plain(result.output)+ assert output.read_bytes() == _control(tmp_path, "chat").read_bytes()++ @pytest.mark.requires_symlink+ def test_a_symlinked_parent_directory_is_not_refused(self, tmp_path):+ """Only the target is inspected: a linked directory above it is the user's layout."""+ real = tmp_path / "real"+ real.mkdir()+ linked = tmp_path / "linked"+ os.symlink(str(real), str(linked), target_is_directory=True)++ result = _init("--template", "chat", "--output", str(linked / "soup.yaml"))++ assert result.exit_code == 0, (result.output, repr(result.exception))+ assert (real / "soup.yaml").read_bytes() == _control(tmp_path, "chat").read_bytes()++ @pytest.mark.skipif(os.name != "nt", reason="Windows junctions only exist on Windows")+ def test_a_junctioned_parent_directory_is_not_refused(self, tmp_path):+ import _winapi++ real = tmp_path / "real"+ real.mkdir()+ junction = tmp_path / "junction"+ _winapi.CreateJunction(str(real), str(junction))++ result = _init("--template", "chat", "--output", str(junction / "soup.yaml"))++ assert result.exit_code == 0, (result.output, repr(result.exception))+ assert (real / "soup.yaml").read_bytes() == _control(tmp_path, "chat").read_bytes()diff --git a/tests/test_mcp_snapshot_run_directory.py b/tests/test_mcp_snapshot_run_directory.pynew file mode 100644index 00000000..43861e6f--- /dev/null+++ b/tests/test_mcp_snapshot_run_directory.py@@ -0,0 +1,285 @@+"""MCP plan time: the config snapshot's run directory is checked and created fresh.++``ExecutionManager.snapshot_config`` writes ``.soup/mcp-runs/<run_id>/config.yaml``.+#1492 refuses a symbolic link or junction at ``.soup`` and ``.soup/mcp-runs``;+these tests cover the run directory itself, a directory that already exists+there, a link that replaces a parent directory while the snapshot is being+created, and the snapshot file, which is created exclusively without following+a link. Ordinary planning writes the same bytes as before.+"""++from __future__ import annotations++import errno+import os+import stat+from pathlib import Path++import pytest++import soup_cli.mcp_server.execution as execution_module+from soup_cli.mcp_server.execution import ExecutionError, ExecutionManager+from soup_cli.mcp_server.registry import McpToolError, build_registry+from soup_cli.utils.paths import atomic_write_text++RUN_ID = "run_20260101_000000_0123abcd"+CONTENT = "base: Qwen/Qwen2.5-0.5B\ntask: sft\ndata:\n train: data.jsonl\n"+LINK_REFUSAL = "symbolic link or junction"+EXISTS_REFUSAL = "already exists"+++def _manager(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> ExecutionManager:+ monkeypatch.chdir(tmp_path)+ (tmp_path / "data.jsonl").write_text('{"text": "example"}\n', encoding="utf-8")+ (tmp_path / "soup.yaml").write_text(CONTENT, encoding="utf-8")+ return ExecutionManager()+++def _train_start(manager: ExecutionManager, monkeypatch: pytest.MonkeyPatch):+ """The real ``train_start`` handler, planning under the fixed ``RUN_ID``."""+ monkeypatch.setattr(manager, "allocate_run_id", lambda: RUN_ID)+ for tool in build_registry(allow_mutating=True, allow_execute=True, execution=manager):+ if tool.name == "train_start":+ return tool.handler+ raise KeyError("train_start")+++def _runs(tmp_path: Path) -> Path:+ return tmp_path / ".soup" / "mcp-runs"+++def _files_under(root: Path) -> list[Path]:+ return [path for path in root.rglob("*") if path.is_file()]+++class TestALinkAtTheRunDirectory:+ @pytest.mark.requires_symlink+ def test_directory_symlink_at_the_run_directory_is_refused(self, tmp_path, monkeypatch):+ manager = _manager(tmp_path, monkeypatch)+ elsewhere = tmp_path / "elsewhere"+ elsewhere.mkdir()+ _runs(tmp_path).mkdir(parents=True)+ os.symlink(str(elsewhere), str(_runs(tmp_path) / RUN_ID), target_is_directory=True)++ with pytest.raises(ExecutionError, match=LINK_REFUSAL) as excinfo:+ manager.snapshot_config(RUN_ID, CONTENT)+ assert not any(elsewhere.iterdir())+ assert str(elsewhere) not in str(excinfo.value)+ assert "elsewhere" not in str(excinfo.value)++ handler = _train_start(manager, monkeypatch)+ with pytest.raises(McpToolError, match=LINK_REFUSAL):+ handler({"config": "soup.yaml"})+ assert not any(elsewhere.iterdir())++ @pytest.mark.requires_symlink+ def test_dangling_symlink_at_the_run_directory_is_refused(self, tmp_path, monkeypatch):+ manager = _manager(tmp_path, monkeypatch)+ missing = tmp_path / "not-created"+ _runs(tmp_path).mkdir(parents=True)+ os.symlink(str(missing), str(_runs(tmp_path) / RUN_ID), target_is_directory=True)++ with pytest.raises(ExecutionError, match=LINK_REFUSAL):+ manager.snapshot_config(RUN_ID, CONTENT)+ assert not os.path.lexists(missing)++ @pytest.mark.skipif(os.name != "nt", reason="Windows junctions only exist on Windows")+ def test_junction_at_the_run_directory_is_refused(self, tmp_path, monkeypatch):+ import _winapi++ manager = _manager(tmp_path, monkeypatch)+ elsewhere = tmp_path / "elsewhere"+ elsewhere.mkdir()+ _runs(tmp_path).mkdir(parents=True)+ _winapi.CreateJunction(str(elsewhere), str(_runs(tmp_path) / RUN_ID))++ with pytest.raises(ExecutionError, match=LINK_REFUSAL) as excinfo:+ manager.snapshot_config(RUN_ID, CONTENT)+ assert not any(elsewhere.iterdir())+ assert str(elsewhere) not in str(excinfo.value)++ handler = _train_start(manager, monkeypatch)+ with pytest.raises(McpToolError, match=LINK_REFUSAL):+ handler({"config": "soup.yaml"})+ assert not any(elsewhere.iterdir())+++class TestSomethingAlreadyAtTheRunDirectory:+ def test_existing_directory_is_refused_and_left_alone(self, tmp_path, monkeypatch):+ manager = _manager(tmp_path, monkeypatch)+ run_dir = _runs(tmp_path) / RUN_ID+ run_dir.mkdir(parents=True)+ (run_dir / "notes.txt").write_text("keep\n", encoding="utf-8")++ with pytest.raises(ExecutionError, match=EXISTS_REFUSAL) as excinfo:+ manager.snapshot_config(RUN_ID, CONTENT)+ assert not (run_dir / "config.yaml").exists()+ assert sorted(p.name for p in run_dir.iterdir()) == ["notes.txt"]+ assert str(tmp_path) not in str(excinfo.value)++ handler = _train_start(manager, monkeypatch)+ with pytest.raises(McpToolError, match=EXISTS_REFUSAL):+ handler({"config": "soup.yaml"})+ assert not (run_dir / "config.yaml").exists()++ def test_existing_file_at_the_run_directory_is_refused(self, tmp_path, monkeypatch):+ manager = _manager(tmp_path, monkeypatch)+ _runs(tmp_path).mkdir(parents=True)+ (_runs(tmp_path) / RUN_ID).write_text("keep\n", encoding="utf-8")++ with pytest.raises(ExecutionError, match=EXISTS_REFUSAL):+ manager.snapshot_config(RUN_ID, CONTENT)+ assert (_runs(tmp_path) / RUN_ID).read_text(encoding="utf-8") == "keep\n"+++class TestALinkThatAppearsWhileTheSnapshotIsCreated:+ @pytest.mark.requires_symlink+ def test_parent_replaced_after_the_first_check(self, tmp_path, monkeypatch):+ """A link swapped in after the run path was checked creates nothing in its target."""+ manager = _manager(tmp_path, monkeypatch)+ runs = _runs(tmp_path)+ runs.mkdir(parents=True)+ elsewhere = tmp_path / "elsewhere"+ elsewhere.mkdir()+ real_refuse = execution_module.refuse_linked_dirs+ swapped = []++ def refuse_then_swap(path, *, stop_at=None):+ real_refuse(path, stop_at=stop_at)+ if not swapped:+ swapped.append(path)+ runs.rmdir()+ os.symlink(str(elsewhere), str(runs), target_is_directory=True)++ monkeypatch.setattr(execution_module, "refuse_linked_dirs", refuse_then_swap)+ with pytest.raises(ExecutionError, match=LINK_REFUSAL):+ manager.snapshot_config(RUN_ID, CONTENT)+ assert swapped+ assert not any(elsewhere.iterdir())++ @pytest.mark.requires_symlink+ def test_parent_replaced_just_before_the_snapshot_is_opened(self, tmp_path, monkeypatch):+ """The open re-checks the parent directories: nothing is written through the link."""+ manager = _manager(tmp_path, monkeypatch)+ runs = _runs(tmp_path)+ elsewhere = tmp_path / "elsewhere"+ (elsewhere / RUN_ID).mkdir(parents=True)+ real_open = execution_module.open_no_follow+ swapped = []++ def swap_then_open(path, *args, **kwargs):+ if not swapped:+ swapped.append(path)+ os.rename(str(runs), str(tmp_path / "moved-runs"))+ os.symlink(str(elsewhere), str(runs), target_is_directory=True)+ return real_open(path, *args, **kwargs)++ monkeypatch.setattr(execution_module, "open_no_follow", swap_then_open)+ with pytest.raises(ExecutionError, match=LINK_REFUSAL):+ manager.snapshot_config(RUN_ID, CONTENT)+ assert swapped+ assert _files_under(elsewhere) == []++ def test_snapshot_file_created_by_someone_else_is_not_overwritten(+ self, tmp_path, monkeypatch+ ):+ manager = _manager(tmp_path, monkeypatch)+ real_open = execution_module.open_no_follow+ other = "written: elsewhere\n"+ created = []++ def create_then_open(path, *args, **kwargs):+ if not created:+ created.append(path)+ Path(path).write_text(other, encoding="utf-8")+ return real_open(path, *args, **kwargs)++ monkeypatch.setattr(execution_module, "open_no_follow", create_then_open)+ with pytest.raises(ExecutionError, match=EXISTS_REFUSAL):+ manager.snapshot_config(RUN_ID, CONTENT)+ assert created+ snapshot = _runs(tmp_path) / RUN_ID / "config.yaml"+ assert snapshot.read_text(encoding="utf-8") == other+++class TestAnyOtherWriteFailure:+ def test_is_reported_by_type_without_a_path(self, tmp_path, monkeypatch):+ manager = _manager(tmp_path, monkeypatch)+ full_disk = str(tmp_path / ".soup" / "mcp-runs" / RUN_ID / "config.yaml")++ def no_space(*args, **kwargs):+ raise OSError(errno.ENOSPC, "No space left on device", full_disk)++ monkeypatch.setattr(execution_module, "open_no_follow", no_space)+ expected = "cannot plan: could not write the config snapshot (OSError)"++ with pytest.raises(ExecutionError) as excinfo:+ manager.snapshot_config(RUN_ID, CONTENT)+ assert str(excinfo.value) == expected+ assert str(tmp_path) not in str(excinfo.value)++ monkeypatch.setattr(manager, "allocate_run_id", lambda: RUN_ID + "b")+ handler = None+ for tool in build_registry(allow_mutating=True, allow_execute=True, execution=manager):+ if tool.name == "train_start":+ handler = tool.handler+ with pytest.raises(McpToolError) as tool_error:+ handler({"config": "soup.yaml"})+ assert str(tool_error.value) == expected+++class TestTheRunIdIsOnePathComponent:+ """The snapshot path is built from the run id, so it must not walk anywhere."""++ @pytest.mark.parametrize("run_id", ["", ".", "..", "nested/run", "../run", "run\x00x"])+ def test_run_id_that_is_not_one_path_component_is_refused(+ self, tmp_path, monkeypatch, run_id+ ):+ manager = _manager(tmp_path, monkeypatch)++ with pytest.raises(ExecutionError, match="invalid run id"):+ manager.snapshot_config(run_id, CONTENT)+ assert not (tmp_path / ".soup").exists()++ def test_run_id_cannot_place_the_snapshot_outside_the_working_directory(+ self, tmp_path, monkeypatch+ ):+ manager = _manager(tmp_path, monkeypatch)+ outside = tmp_path.parent / f"{tmp_path.name}-outside"++ with pytest.raises(ExecutionError, match="invalid run id"):+ manager.snapshot_config(f"../../../{outside.name}", CONTENT)+ assert not outside.exists()+++class TestOrdinaryPlanning:+ def test_snapshot_is_written_as_before(self, tmp_path, monkeypatch):+ manager = _manager(tmp_path, monkeypatch)++ path = manager.snapshot_config(RUN_ID, CONTENT)++ expected = _runs(tmp_path) / RUN_ID / "config.yaml"+ assert path == os.path.realpath(expected)+ assert not os.path.islink(expected)+ # The bytes the previous writer (atomic_write_text) produced.+ control = atomic_write_text(CONTENT, str(tmp_path / "control.yaml"))+ assert Path(path).read_bytes() == Path(control).read_bytes()+ assert stat.S_IMODE(os.stat(path).st_mode) == stat.S_IMODE(os.stat(control).st_mode)++ def test_each_plan_gets_its_own_run_directory(self, tmp_path, monkeypatch):+ manager = _manager(tmp_path, monkeypatch)+ handler = None+ for tool in build_registry(allow_mutating=True, allow_execute=True, execution=manager):+ if tool.name == "train_start":+ handler = tool.handler+ assert handler is not None++ first = handler({"config": "soup.yaml"})+ second = handler({"config": "soup.yaml"})++ assert first["confirmation_token"] != second["confirmation_token"]+ run_dirs = sorted(_runs(tmp_path).iterdir())+ assert len(run_dirs) == 2+ for run_dir in run_dirs:+ snapshot = run_dir / "config.yaml"+ assert snapshot.read_text(encoding="utf-8") == CONTENT