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(layer-stream): validate SOUP_LAYER_STREAM_STRIPE_DIRS early in train, dry-run, and doctor (#1613) (#1628)

Nariman Abdikarim4b34d2c93e6f
diff --git a/changelog.d/0.75.1/1628.fixed.md b/changelog.d/0.75.1/1628.fixed.md
new file mode 100644
index 00000000..022a92db
--- /dev/null
+++ b/changelog.d/0.75.1/1628.fixed.md
@@ -0,0 +1 @@
+- Layer streaming validates `SOUP_LAYER_STREAM_STRIPE_DIRS` early during `soup train` startup and `--dry-run`, refusing missing folders, bad syntax, and same-volume stripes before loading datasets or prompting, and `soup doctor` now reports stripe roots under System Resources (#1613 by @Nari-Ab in #1628).
diff --git a/docs/performance-and-quantization.md b/docs/performance-and-quantization.md
index c7d21eb9..eb497482 100644
--- a/docs/performance-and-quantization.md
+++ b/docs/performance-and-quantization.md
@@ -820,8 +820,9 @@ no `\\?\` or `\\.\` spelling, no control characters), already exist as a folder
not mounted is never mistaken for an empty one), not be a symlink, not lie inside or contain the
primary cache root or another entry, sit on a different volume from the primary root and from
every other entry, and classify as NVMe (`training.stream_disk_kind` overrides a wrong probe); the
-list holds at most 6 folders. The bytes are exactly the ones the single-drive cache holds, so
-striping changes the speed, not the result.
+list holds at most 6 folders. The checks that need no disk probe run when `soup train` or
+`--dry-run` starts, and `soup doctor` lists each entry, with `--disk` for the NVMe rule. The bytes
+are exactly the ones the single-drive cache holds, so striping changes the speed, not the result.
Stripe folders are outside the home/cwd/tmp containment the primary cache has, by design — a
second drive is never under `$HOME`. What that containment gave is enforced directly instead.
diff --git a/src/soup_cli/commands/doctor.py b/src/soup_cli/commands/doctor.py
index ba8496b2..4cf39d5f 100644
--- a/src/soup_cli/commands/doctor.py
+++ b/src/soup_cli/commands/doctor.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import os
import platform
import re
import sys
@@ -119,8 +120,10 @@ def doctor(
# MLX (Apple Silicon) check
_check_mlx()
+ issues: list[str] = []
+
# Resources check
- _check_resources(probe_disk=disk)
+ _check_resources(probe_disk=disk, issues=issues)
# Dependencies table
table = Table(title="Dependencies")
@@ -129,8 +132,6 @@ def doctor(
table.add_column("Installed", justify="center")
table.add_column("Min Version")
table.add_column("Status")
-
- issues: list[str] = []
# Actionable install specs for the trailing "Fix all" line. Only entries
# that are actually missing or out of range land here — never the full
# required set, and never a bare per-package floor for an extra group.
@@ -916,13 +917,13 @@ def _get_ram_gb() -> str:
return "Unknown"
-def _check_resources(probe_disk: bool = False):
+def _check_resources(probe_disk: bool = False, issues: list[str] | None = None):
"""Check RAM and Disk space and display info."""
import shutil
table = Table(title="System Resources")
table.add_column("Resource", style="bold")
- table.add_column("Value")
+ table.add_column("Value", overflow="fold")
table.add_row("RAM", _get_ram_gb())
@@ -959,6 +960,53 @@ def _check_resources(probe_disk: bool = False):
}.get(kind, "[yellow]Unknown[/] — layer streaming will refuse the disk tier")
table.add_row("Disk type", verdict)
+ stripe_var = os.environ.get("SOUP_LAYER_STREAM_STRIPE_DIRS")
+ if stripe_var:
+ from soup_cli.utils.layer_shard import resolve_cache_root
+ from soup_cli.utils.stripe_roots import (
+ STRIPE_DIRS_ENV,
+ iter_early_stripe_roots,
+ parse_stripe_dirs,
+ )
+ from soup_cli.utils.terminal import for_terminal
+
+ stripe_entries = parse_stripe_dirs(stripe_var)
+ primary = resolve_cache_root()
+ has_refused = False
+
+ for entry, resolved, reason in iter_early_stripe_roots(primary, stripe_entries):
+ row_label = "Stripe root"
+ if reason is not None:
+ has_refused = True
+ row_val = f"{for_terminal(entry)} — [red]Refused[/]: {for_terminal(reason)}"
+ elif probe_disk:
+ from soup_cli.utils.layer_stream import detect_disk_kind
+
+ try:
+ kind = detect_disk_kind(resolved)
+ except Exception: # noqa: BLE001
+ kind = "unknown"
+ if kind != "nvme":
+ has_refused = True
+ reason_disk = (
+ "the disk tier streams from NVMe only, and this volume classifies "
+ f"as {kind!r}. If the probe is wrong, "
+ "training.stream_disk_kind overrides it."
+ )
+ refused_msg = for_terminal(reason_disk)
+ row_val = f"{for_terminal(entry)} — [red]Refused[/]: {refused_msg}"
+ else:
+ row_val = f"{for_terminal(entry)} — [green]NVMe[/]"
+ else:
+ row_val = f"{for_terminal(entry)} — [green]OK[/]"
+ table.add_row(row_label, row_val)
+
+ if has_refused and issues is not None:
+ issues.append(
+ f"{STRIPE_DIRS_ENV}: one or more stripe roots are refused "
+ "(see System Resources above)"
+ )
+
console.print(table)
console.print()
diff --git a/src/soup_cli/commands/train.py b/src/soup_cli/commands/train.py
index dfddad34..46a1e374 100644
--- a/src/soup_cli/commands/train.py
+++ b/src/soup_cli/commands/train.py
@@ -1602,6 +1602,23 @@ def train(
"[dim] to soup.yaml for 2-5x faster training.[/]"
)
+ # #1613: cheap stripe roots validation ahead of confirmation, --dry-run,
+ # dataset loading, and run creation.
+ from soup_cli.utils.stripe_roots import STRIPE_DIRS_ENV
+
+ if getattr(getattr(cfg, "training", None), "stream_layers", False) and os.environ.get(
+ STRIPE_DIRS_ENV
+ ):
+ from soup_cli.utils.errors import format_friendly_error
+ from soup_cli.utils.layer_shard import resolve_cache_root
+ from soup_cli.utils.stripe_roots import StripeRootError, validate_early_stripe_roots
+
+ try:
+ validate_early_stripe_roots(resolve_cache_root())
+ except StripeRootError as exc:
+ format_friendly_error(exc)
+ raise typer.Exit(1) from exc
+
if not dry_run and not yes:
if not typer.confirm("Start training?", default=True):
console.print("[yellow]Cancelled.[/]")
diff --git a/src/soup_cli/utils/errors.py b/src/soup_cli/utils/errors.py
index ce69fe93..6d66cb2f 100644
--- a/src/soup_cli/utils/errors.py
+++ b/src/soup_cli/utils/errors.py
@@ -226,6 +226,16 @@ ERROR_MAP = [
"if you trust the model source."
),
),
+ # Layer streaming stripe roots
+ (
+ "StripeRootError",
+ None,
+ (
+ "Fix or remove the invalid entry in SOUP_LAYER_STREAM_STRIPE_DIRS, "
+ "reconnect the drive, or unset the variable to train using the primary "
+ "cache root only."
+ ),
+ ),
]
diff --git a/src/soup_cli/utils/layer_shard.py b/src/soup_cli/utils/layer_shard.py
index 529167d0..cdd0e087 100644
--- a/src/soup_cli/utils/layer_shard.py
+++ b/src/soup_cli/utils/layer_shard.py
@@ -693,6 +693,13 @@ def _resolve_cache_root(cache_dir: Optional[str], is_under: Any) -> str:
return default_layer_stream_cache_dir()
+def resolve_cache_root(cache_dir: Optional[str] = None) -> str:
+ """Cache ROOT only (explicit arg > env override > default). No side effects."""
+ from soup_cli.utils.paths import is_under
+
+ return _resolve_cache_root(cache_dir, is_under)
+
+
def resolve_shard_dir(model: str, cache_dir: Optional[str] = None) -> str:
"""Per-model shard dir (explicit arg > env override > default).
diff --git a/src/soup_cli/utils/stripe_roots.py b/src/soup_cli/utils/stripe_roots.py
index fb7ce2a6..b86ab4f8 100644
--- a/src/soup_cli/utils/stripe_roots.py
+++ b/src/soup_cli/utils/stripe_roots.py
@@ -16,7 +16,7 @@ import hashlib
import os
import stat
from dataclasses import dataclass
-from typing import Callable, List, Mapping, Optional, Sequence, Tuple
+from typing import Callable, Iterator, List, Mapping, Optional, Sequence, Tuple
from soup_cli.utils.config_bounds import (
DEFAULT_STREAM_READ_AHEAD,
@@ -133,64 +133,130 @@ def volume_of(path: str) -> int:
return int(os.stat(_nearest_existing(path)).st_dev)
-def validate_stripe_root(entry: str, *, primary_root: str, accepted: Sequence[str] = ()) -> str:
- """Syntax, existence, symlink and overlap rules; returns the entry's realpath.
+def check_stripe_root(
+ entry: str,
+ *,
+ primary_root: str,
+ accepted: Sequence[str] = (),
+) -> Tuple[Optional[str], Optional[str]]:
+ """Syntax, existence, symlink and overlap rules; returns ``(resolved, reason)``.
- The distinct-volume and NVMe rules live in :func:`resolve_stripe_roots`, which the setup
- path runs once. The sharder calls this one to bound its own writes without paying the
- ~9 s disk-kind probe a second time.
+ If valid, returns ``(resolved_realpath, None)``.
+ If invalid, returns ``(None, reason)`` where ``reason`` does NOT contain the
+ environment variable or entry prefix.
"""
- where = f"{STRIPE_DIRS_ENV} entry {entry!r}"
- # C0, DEL and C1: 0x9B alone is a complete CSI introducer on some terminals.
if any(ord(ch) < 0x20 or 0x7F <= ord(ch) <= 0x9F for ch in entry):
- raise StripeRootError(f"{where}: contains control characters")
+ return None, "contains control characters"
if os.name == "nt" and entry.replace("/", "\\").startswith(_DEVICE_NAMESPACE_PREFIXES):
- # realpath keeps such a prefix, and the overlap rule would then compare it with the
- # primary as if it were another drive — a folder inside the primary passed.
- raise StripeRootError(
- f"{where}: a device-namespace path is not accepted; name the folder by its drive "
- f"letter or UNC share"
+ return None, (
+ "a device-namespace path is not accepted; name the folder by its drive "
+ "letter or UNC share"
)
expanded = os.path.expanduser(entry)
if not os.path.isabs(expanded):
- raise StripeRootError(f"{where}: must be an absolute path")
+ return None, "must be an absolute path"
if os.name == "nt" and not os.path.splitdrive(expanded)[0]:
- # isabs() accepts a path that starts with a separator but names no drive; the folder
- # it means would then depend on the drive of the current directory.
- raise StripeRootError(f"{where}: must name a drive letter or a UNC share")
+ return None, "must name a drive letter or a UNC share"
if os.path.islink(expanded):
- raise StripeRootError(f"{where}: must not be a symlink")
+ return None, "must not be a symlink"
if not os.path.isdir(expanded):
- raise StripeRootError(
- f"{where}: must be an existing directory. Soup creates only its per-model folder "
- f"inside a stripe root, never the root itself, so a drive that is not mounted "
- f"cannot be mistaken for an empty one. Reconnect the drive, or remove this entry "
+ return None, (
+ "must be an existing directory. Soup creates only its per-model folder "
+ "inside a stripe root, never the root itself, so a drive that is not mounted "
+ "cannot be mistaken for an empty one. Reconnect the drive, or remove this entry "
f"(unset {STRIPE_DIRS_ENV} to re-shard to one root)."
)
resolved = os.path.realpath(expanded)
primary = os.path.realpath(os.path.expanduser(primary_root))
if is_under(resolved, primary) or is_under(primary, resolved):
- raise StripeRootError(f"{where}: overlaps the primary layer-stream cache root {primary}")
+ return None, f"overlaps the primary layer-stream cache root {primary}"
for other in accepted:
if is_under(resolved, other) or is_under(other, resolved):
- raise StripeRootError(f"{where}: overlaps another stripe root, {other}")
+ return None, f"overlaps another stripe root, {other}"
+ return resolved, None
+
+
+def validate_stripe_root(entry: str, *, primary_root: str, accepted: Sequence[str] = ()) -> str:
+ """Syntax, existence, symlink and overlap rules; returns the entry's realpath.
+
+ The distinct-volume and NVMe rules live in :func:`resolve_stripe_roots`, which the setup
+ path runs once. The sharder calls this one to bound its own writes without paying the
+ ~9 s disk-kind probe a second time.
+ """
+ resolved, reason = check_stripe_root(entry, primary_root=primary_root, accepted=accepted)
+ if reason is not None:
+ raise StripeRootError(f"{STRIPE_DIRS_ENV} entry {entry!r}: {reason}")
+ assert resolved is not None
return resolved
-def resolve_stripe_roots(
+def iter_early_stripe_roots(
+ primary_root: str,
+ entries: Sequence[str],
+) -> Iterator[Tuple[str, Optional[str], Optional[str]]]:
+ """Validate stripe root entries early, yielding ``(entry, resolved, reason)``.
+
+ ``resolved`` is the resolved canonical path when valid, or ``None``.
+ ``reason`` is the refusal message without environment variable prefix when invalid,
+ or ``None``.
+ """
+ accepted: List[str] = []
+ primary_canonical = os.path.realpath(os.path.expanduser(primary_root))
+ owners = {volume_of(primary_canonical): f"the primary cache root {primary_canonical}"}
+
+ for idx, entry in enumerate(entries):
+ if len(entries) > MAX_STRIPE_DIRS and idx >= MAX_STRIPE_DIRS:
+ yield (
+ entry,
+ None,
+ (
+ f"names {len(entries)} folders; at most {MAX_STRIPE_DIRS} "
+ f"(training.stream_read_ahead stops at {MAX_STREAM_READ_AHEAD}, "
+ f"and every drive needs a staging slot of its own)"
+ ),
+ )
+ continue
+
+ resolved, reason = check_stripe_root(
+ entry, primary_root=primary_canonical, accepted=accepted
+ )
+ if reason is not None:
+ yield (entry, None, reason)
+ continue
+
+ assert resolved is not None
+ volume = volume_of(resolved)
+ if volume in owners:
+ yield (
+ entry,
+ None,
+ (
+ f"on the same volume as {owners[volume]}. "
+ f"Two roots on one drive read no faster than one and cost a staging slot."
+ ),
+ )
+ continue
+
+ owners[volume] = f"stripe root {resolved}"
+ accepted.append(resolved)
+ yield (entry, resolved, None)
+
+
+def validate_early_stripe_roots(
primary_root: str,
*,
- disk_kind: Callable[[str], str],
environ: Optional[Mapping[str, str]] = None,
) -> Tuple[str, ...]:
- """The validated stripe roots, or ``()`` when the variable is unset or blank.
+ """Syntax, existence, count cap, symlink, overlap and same-volume rules.
- ``disk_kind`` maps a path to ``nvme`` / ``ssd`` / ``hdd`` / ``unknown``; the setup path
- passes ``resolve_disk_kind(...).kind`` so ``training.stream_disk_kind`` overrides the probe
- here exactly as it does for the primary cache.
+ Runs early in the CLI (``soup train``, ``--dry-run``) before expensive dataset
+ loading or run creation. Omits the ~9 s NVMe disk-kind probe, which stays in
+ :func:`resolve_stripe_roots` on the setup path.
"""
env = os.environ if environ is None else environ
entries = parse_stripe_dirs(env.get(STRIPE_DIRS_ENV))
+ if not entries:
+ return ()
if len(entries) > MAX_STRIPE_DIRS:
raise StripeRootError(
f"{STRIPE_DIRS_ENV} names {len(entries)} folders; at most {MAX_STRIPE_DIRS} "
@@ -198,15 +264,32 @@ def resolve_stripe_roots(
f"needs a staging slot of its own)"
)
accepted: List[str] = []
- owners = {volume_of(primary_root): f"the primary cache root {primary_root}"} if entries else {}
- for entry in entries:
- resolved = validate_stripe_root(entry, primary_root=primary_root, accepted=accepted)
- volume = volume_of(resolved)
- if volume in owners:
- raise StripeRootError(
- f"{STRIPE_DIRS_ENV} entry {entry!r}: on the same volume as {owners[volume]}. "
- f"Two roots on one drive read no faster than one and cost a staging slot."
- )
+ for entry, resolved, reason in iter_early_stripe_roots(primary_root, entries):
+ if reason is not None:
+ raise StripeRootError(f"{STRIPE_DIRS_ENV} entry {entry!r}: {reason}")
+ assert resolved is not None
+ accepted.append(resolved)
+ return tuple(accepted)
+
+
+def resolve_stripe_roots(
+ primary_root: str,
+ *,
+ disk_kind: Callable[[str], str],
+ environ: Optional[Mapping[str, str]] = None,
+) -> Tuple[str, ...]:
+ """The validated stripe roots, or ``()`` when the variable is unset or blank.
+
+ ``disk_kind`` maps a path to ``nvme`` / ``ssd`` / ``hdd`` / ``unknown``; the setup path
+ passes ``resolve_disk_kind(...).kind`` so ``training.stream_disk_kind`` overrides the probe
+ here exactly as it does for the primary cache.
+ """
+ env = os.environ if environ is None else environ
+ entries = parse_stripe_dirs(env.get(STRIPE_DIRS_ENV))
+ if not entries:
+ return ()
+ accepted = validate_early_stripe_roots(primary_root, environ=env)
+ for entry, resolved in zip(entries, accepted):
kind = disk_kind(resolved)
if kind != "nvme":
raise StripeRootError(
@@ -214,9 +297,7 @@ def resolve_stripe_roots(
f"this volume classifies as {kind!r}. If the probe is wrong, "
f"training.stream_disk_kind overrides it."
)
- owners[volume] = f"stripe root {resolved}"
- accepted.append(resolved)
- return tuple(accepted)
+ return accepted
def layer_roots_for(n_layers: int, n_roots: int) -> Tuple[int, ...]:
diff --git a/tests/test_issue1613_early_stripe_roots.py b/tests/test_issue1613_early_stripe_roots.py
new file mode 100644
index 00000000..02b8f12d
--- /dev/null
+++ b/tests/test_issue1613_early_stripe_roots.py
@@ -0,0 +1,340 @@
+"""#1613 — Early validation for SOUP_LAYER_STREAM_STRIPE_DIRS.
+
+Pinned by this suite:
+- A CliRunner test of soup train with stream_layers: true and the variable naming
+ a folder that does not exist: exit code 1, output contains "must be an existing
+ directory", does not contain "Loaded:" or "Run ID", and ExperimentTracker.start_run
+ was not called.
+- The same config with --dry-run: the same refusal, and no "Config valid" line.
+- A same-volume entry is refused at the same early point.
+- When stream_layers is off/unset in config, the variable is not checked.
+- soup doctor with the variable set to a missing folder prints a row that names
+ the entry and the rule; with the variable unset the output is unchanged.
+- soup doctor with --disk probes each stripe root and reports NVMe.
+- soup doctor never prints raw control characters from an entry.
+- soup doctor count cap reports MAX_STREAM_READ_AHEAD.
+- soup doctor refuses a stripe root on the same volume as the primary cache root.
+- Output assertions go through ANSI-strip and whitespace-collapse helper, and pass
+ with FORCE_COLOR=1.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import re
+from io import StringIO
+from unittest.mock import MagicMock
+
+import pytest
+from rich.console import Console
+from typer.testing import CliRunner
+
+from soup_cli.cli import app
+from soup_cli.utils.config_bounds import MAX_STREAM_READ_AHEAD
+from soup_cli.utils.stripe_roots import (
+ MAX_STRIPE_DIRS,
+ STRIPE_DIRS_ENV,
+ StripeRootError,
+ iter_early_stripe_roots,
+ validate_early_stripe_roots,
+)
+
+_ANSI = re.compile(r"\x1b\[[0-9;?]*[ -/]*[@-~]")
+
+
+def _plain(text: str | None) -> str:
+ """Rich colours per character and wraps, so compare stripped + collapsed."""
+ return " ".join(_ANSI.sub("", text or "").replace("│", " ").split())
+
+
+def _doctor_resources_raw(monkeypatch, *, probe_disk: bool = False) -> str:
+ from soup_cli.commands import doctor
+
+ out = StringIO()
+ monkeypatch.setattr(doctor, "console", Console(file=out, width=400, color_system=None))
+ doctor._check_resources(probe_disk=probe_disk)
+ return out.getvalue()
+
+
+def _write_streaming_config(tmp_path, **kwargs) -> str:
+ cfg = tmp_path / "soup.yaml"
+ cfg.write_text(
+ "base: smollm2-135m\n"
+ "task: sft\n"
+ "backend: transformers\n"
+ "data:\n"
+ " train: /dev/null\n"
+ "training:\n"
+ " stream_layers: true\n"
+ " batch_size: 1\n"
+ )
+ return str(cfg)
+
+
+class TestCliRunnerEarlyRefusal:
+ @pytest.mark.parametrize("dry_run", [False, True], ids=["train", "dry-run"])
+ def test_missing_stripe_folder_is_refused_early(self, tmp_path, monkeypatch, dry_run):
+ from soup_cli.experiment.tracker import ExperimentTracker
+
+ start_run_mock = MagicMock()
+ monkeypatch.setattr(ExperimentTracker, "start_run", start_run_mock)
+
+ missing_name = "missing_stripe_folder"
+ missing_dir = str(tmp_path / missing_name)
+ monkeypatch.setenv(STRIPE_DIRS_ENV, missing_dir)
+ monkeypatch.setenv("FORCE_COLOR", "1")
+
+ cfg_file = _write_streaming_config(tmp_path)
+ args = ["train", "--config", cfg_file]
+ if dry_run:
+ args.append("--dry-run")
+ else:
+ args.append("--yes")
+
+ result = CliRunner().invoke(app, args)
+ output = _plain(result.output)
+
+ assert result.exit_code == 1, (result.output, repr(result.exception))
+ assert "must be an existing directory" in output, output
+ assert missing_name in output.replace(" ", ""), output
+ assert "Loaded:" not in output, output
+ assert "Run ID" not in output, output
+ assert "Config valid" not in output, output
+ assert "StripeRootError:" not in output, output
+ assert not start_run_mock.called
+
+ def test_same_volume_entry_refused_at_same_early_point(self, tmp_path, monkeypatch):
+ from soup_cli.experiment.tracker import ExperimentTracker
+
+ start_run_mock = MagicMock()
+ monkeypatch.setattr(ExperimentTracker, "start_run", start_run_mock)
+
+ cache_dir = tmp_path / "cache_dir"
+ cache_dir.mkdir()
+ monkeypatch.setenv("SOUP_LAYER_STREAM_CACHE_DIR", str(cache_dir))
+
+ stripe_dir = tmp_path / "stripe_same_vol"
+ stripe_dir.mkdir()
+ monkeypatch.setenv(STRIPE_DIRS_ENV, str(stripe_dir))
+ monkeypatch.setenv("FORCE_COLOR", "1")
+
+ cfg_file = _write_streaming_config(tmp_path)
+ result = CliRunner().invoke(app, ["train", "--config", cfg_file, "--yes"])
+ output = _plain(result.output)
+
+ assert result.exit_code == 1, (result.output, repr(result.exception))
+ assert "same volume as the primary cache root" in output, output
+ assert "Loaded:" not in output, output
+ assert "Run ID" not in output, output
+ assert not start_run_mock.called
+
+ def test_unset_variable_does_not_fail_at_early_check(self, tmp_path, monkeypatch):
+ """With the variable unset, the early check is bypassed completely."""
+ monkeypatch.delenv(STRIPE_DIRS_ENV, raising=False)
+ cfg_file = _write_streaming_config(tmp_path)
+
+ result = CliRunner().invoke(app, ["train", "--config", cfg_file, "--dry-run"])
+ output = _plain(result.output)
+
+ assert "must be an existing directory" not in output
+ assert "same volume as the primary" not in output
+
+ def test_variable_is_not_checked_when_stream_layers_is_off(self, tmp_path, monkeypatch):
+ missing = str(tmp_path / "does-not-exist-xyz")
+ monkeypatch.setenv(STRIPE_DIRS_ENV, missing)
+ cfg = tmp_path / "soup.yaml"
+ cfg.write_text(
+ "base: smollm2-135m\ntask: sft\nbackend: transformers\n"
+ "data:\n train: /dev/null\ntraining:\n batch_size: 1\n"
+ )
+ result = CliRunner().invoke(app, ["train", "--config", str(cfg), "--dry-run"])
+ output = _plain(result.output)
+ assert "Dry run" in output, (output, repr(result.exception))
+ assert "must be an existing directory" not in output, output
+
+ def test_dry_run_with_a_real_dataset_stops_at_the_refusal(self, tmp_path, monkeypatch):
+ data = tmp_path / "train.jsonl"
+ data.write_text(
+ "".join(
+ json.dumps({"instruction": f"q{idx}", "input": "", "output": f"a{idx}"}) + "\n"
+ for idx in range(4)
+ ),
+ encoding="utf-8",
+ )
+ cfg = tmp_path / "soup.yaml"
+ cfg.write_text(
+ "base: smollm2-135m\ntask: sft\nbackend: transformers\n"
+ f"data:\n train: {data.as_posix()}\n"
+ "training:\n stream_layers: true\n batch_size: 1\n",
+ encoding="utf-8",
+ )
+ monkeypatch.setenv(STRIPE_DIRS_ENV, str(tmp_path / "missing_stripe_folder"))
+ monkeypatch.chdir(tmp_path)
+
+ result = CliRunner().invoke(app, ["train", "--config", str(cfg), "--dry-run"])
+ output = _plain(result.output)
+
+ assert result.exit_code == 1, (result.output, repr(result.exception))
+ assert "must be an existing directory" in output, output
+ assert "validating data" not in output, output
+ assert "Config valid" not in output, output
+
+
+class TestDoctorStripeOutput:
+ def test_doctor_names_a_missing_stripe_folder_and_the_rule(self, tmp_path, monkeypatch):
+ missing = str(tmp_path / "does-not-exist-xyz")
+ monkeypatch.setenv(STRIPE_DIRS_ENV, missing)
+ output = _plain(_doctor_resources_raw(monkeypatch))
+ assert missing in output, output
+ assert "must be an existing directory" in output, output
+
+ def test_doctor_output_unchanged_when_variable_unset(self, monkeypatch):
+ monkeypatch.delenv(STRIPE_DIRS_ENV, raising=False)
+ output_unset = _plain(_doctor_resources_raw(monkeypatch))
+ assert "Stripe root" not in output_unset
+
+ def test_doctor_disk_flag_probes_each_stripe_root(self, tmp_path, monkeypatch):
+ import soup_cli.utils.stripe_roots as stripe_roots
+
+ folder = tmp_path / "stripe"
+ folder.mkdir()
+ monkeypatch.setenv(STRIPE_DIRS_ENV, str(folder))
+ real = os.path.realpath(str(folder))
+ monkeypatch.setattr(
+ stripe_roots, "volume_of", lambda p: 2 if os.path.realpath(p) == real else 1
+ )
+ probed = []
+
+ def fake_kind(path):
+ probed.append(path)
+ return "nvme"
+
+ monkeypatch.setattr("soup_cli.utils.layer_stream.detect_disk_kind", fake_kind)
+ output = _plain(_doctor_resources_raw(monkeypatch, probe_disk=True))
+ assert real in probed, probed
+ assert f"Stripe root {folder} — NVMe" in output, output
+
+ def test_doctor_never_prints_a_control_character_of_an_entry(self, tmp_path, monkeypatch):
+ monkeypatch.setenv(STRIPE_DIRS_ENV, str(tmp_path / "stripe\x1b[31mred"))
+ raw = _doctor_resources_raw(monkeypatch)
+ assert "\x1b" not in raw, ascii(raw)
+ assert "contains control characters" in _plain(raw), raw
+
+ def test_doctor_count_cap_names_the_real_read_ahead_limit(self, tmp_path, monkeypatch):
+ entries = [str(tmp_path / f"s{n}") for n in range(MAX_STRIPE_DIRS + 1)]
+ monkeypatch.setenv(STRIPE_DIRS_ENV, os.pathsep.join(entries))
+ output = _plain(_doctor_resources_raw(monkeypatch))
+ assert f"stops at {MAX_STREAM_READ_AHEAD}," in output, output
+
+ def test_doctor_refuses_a_stripe_folder_on_the_primary_volume(self, tmp_path, monkeypatch):
+ (tmp_path / "cache").mkdir()
+ (tmp_path / "stripe").mkdir()
+ monkeypatch.setenv("SOUP_LAYER_STREAM_CACHE_DIR", str(tmp_path / "cache"))
+ monkeypatch.setenv(STRIPE_DIRS_ENV, str(tmp_path / "stripe"))
+ output = _plain(_doctor_resources_raw(monkeypatch))
+ assert "on the same volume as the primary cache root" in output, output
+
+ def test_doctor_disk_flag_refuses_a_stripe_root_that_is_not_nvme(self, tmp_path, monkeypatch):
+ import soup_cli.utils.stripe_roots as stripe_roots
+ from soup_cli.commands import doctor
+
+ folder = tmp_path / "stripe"
+ folder.mkdir()
+ monkeypatch.setenv(STRIPE_DIRS_ENV, str(folder))
+ real = os.path.realpath(str(folder))
+ monkeypatch.setattr(
+ stripe_roots, "volume_of", lambda p: 2 if os.path.realpath(p) == real else 1
+ )
+ monkeypatch.setattr("soup_cli.utils.layer_stream.detect_disk_kind", lambda path: "ssd")
+ out = StringIO()
+ monkeypatch.setattr(doctor, "console", Console(file=out, width=400, color_system=None))
+ issues = []
+ doctor._check_resources(probe_disk=True, issues=issues)
+ output = _plain(out.getvalue())
+ assert f"Stripe root {folder} — Refused" in output, output
+ assert "classifies as 'ssd'" in output, output
+ assert len(issues) == 1 and STRIPE_DIRS_ENV in issues[0], issues
+
+ def test_doctor_records_an_issue_for_a_refused_entry_without_disk(self, tmp_path, monkeypatch):
+ from soup_cli.commands import doctor
+
+ missing = str(tmp_path / "does-not-exist-xyz")
+ monkeypatch.setenv(STRIPE_DIRS_ENV, missing)
+ out = StringIO()
+ monkeypatch.setattr(doctor, "console", Console(file=out, width=400, color_system=None))
+ issues = []
+ doctor._check_resources(probe_disk=False, issues=issues)
+ assert "must be an existing directory" in _plain(out.getvalue()), out.getvalue()
+ assert len(issues) == 1 and STRIPE_DIRS_ENV in issues[0], issues
+
+
+class TestValidateEarlyStripeRootsUnit:
+ def test_unset_and_empty_return_empty_tuple(self):
+ assert validate_early_stripe_roots("/primary", environ={}) == ()
+ assert validate_early_stripe_roots("/primary", environ={STRIPE_DIRS_ENV: ""}) == ()
+
+ def test_missing_directory_raises_stripe_root_error(self, tmp_path):
+ missing = str(tmp_path / "gone")
+ with pytest.raises(StripeRootError, match="must be an existing directory"):
+ validate_early_stripe_roots(str(tmp_path), environ={STRIPE_DIRS_ENV: missing})
+
+ def test_too_many_entries_refused(self, tmp_path):
+ entries = [str(tmp_path / f"s{n}") for n in range(MAX_STRIPE_DIRS + 1)]
+ with pytest.raises(StripeRootError, match=f"at most {MAX_STRIPE_DIRS}"):
+ validate_early_stripe_roots(
+ str(tmp_path), environ={STRIPE_DIRS_ENV: os.pathsep.join(entries)}
+ )
+
+ def test_same_volume_as_primary_refused(self, tmp_path):
+ cache = tmp_path / "cache"
+ cache.mkdir()
+ stripe = tmp_path / "stripe"
+ stripe.mkdir()
+ with pytest.raises(StripeRootError, match="same volume as the primary cache root"):
+ validate_early_stripe_roots(str(cache), environ={STRIPE_DIRS_ENV: str(stripe)})
+
+ def test_distinct_volumes_accepted_without_disk_probe(self, tmp_path, monkeypatch):
+ import soup_cli.utils.stripe_roots as mod
+
+ cache = tmp_path / "cache"
+ cache.mkdir()
+ stripe1 = tmp_path / "stripe1"
+ stripe1.mkdir()
+ stripe2 = tmp_path / "stripe2"
+ stripe2.mkdir()
+
+ ids = {
+ os.path.realpath(str(cache)): 1,
+ os.path.realpath(str(stripe1)): 2,
+ os.path.realpath(str(stripe2)): 3,
+ }
+ monkeypatch.setattr(mod, "volume_of", lambda p: ids[os.path.realpath(p)])
+
+ result = validate_early_stripe_roots(
+ str(cache),
+ environ={STRIPE_DIRS_ENV: f"{stripe1}{os.pathsep}{stripe2}"},
+ )
+ assert result == (os.path.realpath(str(stripe1)), os.path.realpath(str(stripe2)))
+
+ def test_iter_early_stripe_roots_helper(self, tmp_path):
+ cache = tmp_path / "cache"
+ cache.mkdir()
+ stripe = tmp_path / "stripe"
+ stripe.mkdir()
+
+ results = list(
+ iter_early_stripe_roots(
+ str(cache), [str(stripe), str(tmp_path / "nonexistent")]
+ )
+ )
+ assert len(results) == 2
+ # stripe on same volume
+ assert results[0][0] == str(stripe)
+ assert results[0][1] is None
+ assert "on the same volume" in results[0][2]
+
+ # nonexistent
+ assert results[1][0] == str(tmp_path / "nonexistent")
+ assert results[1][1] is None
+ assert "must be an existing directory" in results[1][2]