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: refuse output paths that alias their inputs (#2018)

martinfc956c0947f2
diff --git a/changelog.d/0.76.0/2018.fixed.md b/changelog.d/0.76.0/2018.fixed.md
new file mode 100644
index 00000000..e843bd4e
--- /dev/null
+++ b/changelog.d/0.76.0/2018.fixed.md
@@ -0,0 +1,3 @@
+- Prevent `soup ingest`, `soup prune-prompt`, and `soup data best-of-n` from writing outputs that alias their input files, including hard-link aliases. (#1422 by @Martini147 in #2018)
+- Reject overlapping effective RA-DIT stage output directories before training starts.
+- Publish prune-prompt output atomically and validate best-of-n checkpoints before truncating incomplete journal tails.
diff --git a/docs/training.md b/docs/training.md
index d2e56d19..1b854b09 100644
--- a/docs/training.md
+++ b/docs/training.md
@@ -1964,6 +1964,8 @@ soup ra-dit -r retriever.yaml -g generator.yaml --plan-only
It trains the retriever, then **records** that trained retriever as the generator's paired retriever (writing its output dir into the generator's `training.ra_dit_retriever_model`) and trains the generator RAFT-style. The recorded retriever is the one used at deploy/serve time — stage-2 does not fuse the retriever weights. A plain `soup train` of a generator-stage config with no retriever model set **auto-links** the most-recent RA-DIT retriever run from the Registry; pass `--retriever-model <m>` to override.
+Both configs must write to different, non-nested output directories: `soup ra-dit` refuses a pair whose effective outputs (`output` plus `experiment_name`, exactly as the trainers build them) are equal or nested, so give each stage its own `output`, or give both stages different `experiment_name` values. The two shipped recipes both declare `output: ./output`, so setting an `experiment_name` on only one stage is not enough.
+
## Curriculum-Aware Training (BETA)
diff --git a/src/soup_cli/commands/data.py b/src/soup_cli/commands/data.py
index 385871df..4d6636eb 100644
--- a/src/soup_cli/commands/data.py
+++ b/src/soup_cli/commands/data.py
@@ -3543,7 +3543,10 @@ def best_of_n(
from soup_cli.utils import best_of_n_artifact as bon_artifact
from soup_cli.utils import best_of_n_checkpoint as bon_checkpoint
from soup_cli.utils.magpie import make_magpie_generate_fn
- from soup_cli.utils.paths import enforce_under_cwd_and_no_symlink
+ from soup_cli.utils.paths import (
+ enforce_under_cwd_and_no_symlink,
+ ensure_distinct_paths,
+ )
from soup_cli.utils.trust_remote import (
model_requires_trust_remote_code,
resolve_trust_remote_code,
@@ -3615,6 +3618,23 @@ def best_of_n(
if manifest_path:
enforce_under_cwd_and_no_symlink(manifest_path, "--manifest path")
paths.append(manifest_path)
+
+ ensure_distinct_paths(
+ [
+ ("--candidate-artifact", candidate_artifact),
+ ("--judgments", judgments),
+ ],
+ [
+ (field, path)
+ for field, path in (
+ ("--output", output),
+ ("--emit-pairs", emit_pairs),
+ ("--manifest", manifest_path),
+ )
+ if path
+ ],
+ )
+
if len({os.path.normcase(os.path.realpath(path)) for path in paths}) != len(paths):
raise ValueError("offline input and output paths must be distinct")
except (FileNotFoundError, OSError, TypeError, ValueError) as exc:
@@ -3751,6 +3771,20 @@ def best_of_n(
"prompt source, candidate artifact, and checkpoint paths "
"must be distinct"
)
+ ensure_distinct_paths(
+ [("--prompts", prompts)],
+ [
+ (field, path)
+ for field, path in (
+ ("--output", output),
+ ("--emit-pairs", emit_pairs),
+ ("--checkpoint", checkpoint_path),
+ ("--manifest", manifest_path),
+ ("--export-candidates", export_candidates),
+ )
+ if path
+ ],
+ )
except (FileNotFoundError, TypeError, ValueError) as exc:
console.print(f"[red]{_escape(str(exc))}[/]")
raise typer.Exit(2) from exc
diff --git a/src/soup_cli/commands/ingest.py b/src/soup_cli/commands/ingest.py
index f3bd4869..9d55e171 100644
--- a/src/soup_cli/commands/ingest.py
+++ b/src/soup_cli/commands/ingest.py
@@ -33,7 +33,7 @@ from soup_cli.utils.ingest_sources import (
resolve_auth_env,
validate_source_name,
)
-from soup_cli.utils.paths import is_under_cwd
+from soup_cli.utils.paths import atomic_write_lines, ensure_distinct_paths, is_under_cwd
from soup_cli.utils.terminal import for_terminal
console = Console()
@@ -164,6 +164,17 @@ def ingest(
)
raise typer.Exit(1)
+ # Refuse before anything is opened for writing: the default --output
+ # (traces.jsonl) is also a plausible --logs, and the write would empty it.
+ try:
+ ensure_distinct_paths(
+ [("--logs", str(logs_path))],
+ [("--output", str(output_path))],
+ )
+ except ValueError as exc:
+ console.print(f"[red]{escape(str(exc))}[/]")
+ raise typer.Exit(1) from exc
+
_print_pii_reminder(canonical)
auth_value = resolve_auth_env(canonical)
@@ -174,10 +185,16 @@ def ingest(
)
count = 0
- with open(output_path, "w", encoding="utf-8") as out_fh:
+
+ def _lines():
+ nonlocal count
for record in ingest_traces(source=canonical, path=str(logs_path)):
- out_fh.write(json.dumps(record.to_dict(), ensure_ascii=False) + "\n")
count += 1
+ yield json.dumps(record.to_dict(), ensure_ascii=False) + "\n"
+
+ # Streamed into a staging file; the target is replaced only after the export
+ # has been read completely, so a failed read leaves an earlier output intact.
+ atomic_write_lines(_lines(), str(output_path), field="--output")
console.print(
f"[green]Wrote {count} traces from {escape(canonical)} -> "
diff --git a/src/soup_cli/commands/ra_dit.py b/src/soup_cli/commands/ra_dit.py
index 775ddfb0..c40e47e0 100644
--- a/src/soup_cli/commands/ra_dit.py
+++ b/src/soup_cli/commands/ra_dit.py
@@ -63,7 +63,7 @@ def main(
) -> None:
"""Run (or plan) a two-stage RA-DIT pipeline."""
from soup_cli.utils.ra_dit_run import (
- resolve_retriever_for_generator,
+ load_ra_dit_configs,
run_ra_dit,
validate_ra_dit_config_path,
)
@@ -78,18 +78,29 @@ def main(
raise typer.Exit(2) from exc
if plan_only:
- # Preview the retriever link without touching the Registry write path.
+ try:
+ _, _, retriever_output, generator_output = load_ra_dit_configs(
+ retr_path,
+ gen_path,
+ )
+ except (TypeError, ValueError, FileNotFoundError) as exc:
+ console.print(f"[red]Invalid ra-dit config:[/] {escape(str(exc))}")
+ raise typer.Exit(2) from exc
+
if retriever_model is not None:
+ link_preview = f"manual override: {escape(retriever_model)}"
+ else:
link_preview = (
- f"manual override: {escape(retriever_model)}"
+ "auto-link to stage-1 output: "
+ f"{escape(retriever_output)}"
)
- else:
- resolved, advisory = resolve_retriever_for_generator(None)
- link_preview = escape(advisory)
+
console.print(
Panel(
f"[bold]Stage 1 (retriever):[/] {escape(retr_path)}\n"
+ f"[bold]Retriever output:[/] {escape(retriever_output)}\n"
f"[bold]Stage 2 (generator):[/] {escape(gen_path)}\n"
+ f"[bold]Generator output:[/] {escape(generator_output)}\n"
f"[bold]Retriever link:[/] {link_preview}\n"
f"[bold]Per-stage timeout:[/] {timeout}s",
title="soup ra-dit (plan-only)",
@@ -97,8 +108,8 @@ def main(
)
)
console.print(
- "[green]Plan-only mode — config paths validated. "
- "Drop --plan-only to run both stages.[/]"
+ "[green]Plan-only mode — config paths and output directories "
+ "validated. Drop --plan-only to run both stages.[/]"
)
return
diff --git a/src/soup_cli/utils/best_of_n_checkpoint.py b/src/soup_cli/utils/best_of_n_checkpoint.py
index 9155daaa..46045110 100644
--- a/src/soup_cli/utils/best_of_n_checkpoint.py
+++ b/src/soup_cli/utils/best_of_n_checkpoint.py
@@ -61,18 +61,18 @@ def _open_checkpoint(path: str):
try:
if not stat.S_ISREG(os.fstat(fd).st_mode):
raise ValueError("checkpoint must be a regular file")
- return os.fdopen(fd, "r", encoding="utf-8")
+ return os.fdopen(fd, "rb")
except Exception:
os.close(fd)
raise
def _discard_incomplete_tail(path: str) -> None:
- """Drop an uncommitted final JSONL fragment left by an interrupted append.
+ """Drop an uncommitted final fragment after committed records validate.
- ``append_checkpoint`` commits records with a trailing newline followed by
- ``fsync``. A final fragment without that newline is therefore never a
- committed record and can be discarded safely before validation.
+ ``append_checkpoint`` terminates each record with a newline and then
+ calls ``fsync``. ``load_checkpoint`` validates the committed prefix
+ before calling this helper to remove a final fragment without a newline.
"""
enforce_under_cwd_and_no_symlink(path, "--checkpoint path")
flags = os.O_RDWR | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_BINARY", 0)
@@ -107,38 +107,81 @@ def _discard_incomplete_tail(path: str) -> None:
def load_checkpoint(
path: str, *, digest: str, total: int
) -> list[tuple[dict, dict | None]]:
- """Validate a journal and return its exactly-once completed prompt prefix."""
- _discard_incomplete_tail(path)
+ """Validate committed records before discarding an incomplete final tail."""
entries: list[tuple[dict, dict | None]] = []
+ header_validated = False
+ incomplete_tail = False
+
with _open_checkpoint(path) as handle:
for line_number, raw in enumerate(handle, 1):
+ if not raw.endswith(b"\n"):
+ incomplete_tail = True
+ break
+
try:
- record = json.loads(raw)
- except json.JSONDecodeError as exc:
- raise ValueError(f"checkpoint has invalid JSON on line {line_number}") from exc
+ record = json.loads(raw.decode("utf-8"))
+ except (json.JSONDecodeError, UnicodeDecodeError) as exc:
+ raise ValueError(
+ f"checkpoint has invalid JSON on line {line_number}"
+ ) from exc
+
if line_number == 1:
- header = record.get("_best_of_n_checkpoint") if isinstance(record, dict) else None
+ header = (
+ record.get("_best_of_n_checkpoint")
+ if isinstance(record, dict)
+ else None
+ )
if not isinstance(header, dict):
raise ValueError("checkpoint header is missing")
if header.get("version") != _CHECKPOINT_VERSION:
raise ValueError("checkpoint version is not supported")
- if header.get("run_digest") != digest or header.get("total") != total:
- raise ValueError("checkpoint does not match prompts or run configuration")
+ if (
+ header.get("run_digest") != digest
+ or header.get("total") != total
+ ):
+ raise ValueError(
+ "checkpoint does not match prompts or run configuration"
+ )
+ header_validated = True
continue
- if not isinstance(record, dict) or record.get("index") != len(entries):
- raise ValueError("checkpoint prompt indexes must be sequential and exactly once")
- core = {key: value for key, value in record.items() if key != "entry_digest"}
+
+ if (
+ not isinstance(record, dict)
+ or record.get("index") != len(entries)
+ ):
+ raise ValueError(
+ "checkpoint prompt indexes must be sequential and exactly once"
+ )
+ core = {
+ key: value
+ for key, value in record.items()
+ if key != "entry_digest"
+ }
if record.get("entry_digest") != _record_digest(core):
- raise ValueError(f"checkpoint entry {len(entries)} has a digest mismatch")
+ raise ValueError(
+ f"checkpoint entry {len(entries)} has a digest mismatch"
+ )
sft = record.get("sft")
dpo = record.get("dpo")
- if not isinstance(sft, dict) or (dpo is not None and not isinstance(dpo, dict)):
- raise ValueError(f"checkpoint entry {len(entries)} is malformed")
+ if (
+ not isinstance(sft, dict)
+ or (dpo is not None and not isinstance(dpo, dict))
+ ):
+ raise ValueError(
+ f"checkpoint entry {len(entries)} is malformed"
+ )
entries.append((sft, dpo))
if len(entries) > total:
- raise ValueError("checkpoint contains more prompt groups than the input")
- if not entries and not os.path.getsize(path):
- raise ValueError("checkpoint is empty")
+ raise ValueError(
+ "checkpoint contains more prompt groups than the input"
+ )
+
+ if not header_validated:
+ raise ValueError("checkpoint is empty or has no committed header")
+
+ if incomplete_tail:
+ _discard_incomplete_tail(path)
+
return entries
diff --git a/src/soup_cli/utils/paths.py b/src/soup_cli/utils/paths.py
index 5594910f..e86bd374 100644
--- a/src/soup_cli/utils/paths.py
+++ b/src/soup_cli/utils/paths.py
@@ -201,6 +201,53 @@ def check_report_output_path(path: str, field: str = "--output") -> str:
return path
+def _same_file(first: str, second: str) -> bool:
+ """Whether two existing paths are one file, hard links included."""
+ try:
+ return os.path.samefile(first, second)
+ except (OSError, ValueError):
+ # A path that does not exist yet cannot be a hard link to anything.
+ return False
+
+
+def ensure_distinct_paths(
+ inputs: Iterable[tuple[str, str]],
+ outputs: Iterable[tuple[str, str]],
+ *,
+ reject_nested: bool = False,
+) -> None:
+ """Refuse outputs aliasing inputs, optionally including nested directories.
+
+ Items are (field, path) pairs. Identity uses normcase(realpath(...))
+ and samefile for existing paths, including hard links.
+ With reject_nested=True, neither path may contain the other.
+ Opens and creates nothing.
+ """
+ input_list = list(inputs)
+ for out_field, out_path in outputs:
+ out_identity = os.path.normcase(os.path.realpath(out_path))
+ for in_field, in_path in input_list:
+ in_identity = os.path.normcase(os.path.realpath(in_path))
+ if out_identity == in_identity or _same_file(out_path, in_path):
+ raise ValueError(
+ f"{out_field} {quote_path(out_path)} is the same file as "
+ f"{in_field} {quote_path(in_path)}; choose a different {out_field}"
+ )
+
+ if reject_nested:
+ try:
+ common = os.path.commonpath([in_identity, out_identity])
+ except ValueError:
+ # Paths on different drives cannot contain each other.
+ continue
+ if common in (in_identity, out_identity):
+ raise ValueError(
+ f"{out_field} {quote_path(out_path)} overlaps "
+ f"{in_field} {quote_path(in_path)}; "
+ "choose separate, non-nested output directories"
+ )
+
+
def atomic_write_text(
text: str,
output_path: str,
diff --git a/src/soup_cli/utils/prune_prompt.py b/src/soup_cli/utils/prune_prompt.py
index e29b96e3..20dd514a 100644
--- a/src/soup_cli/utils/prune_prompt.py
+++ b/src/soup_cli/utils/prune_prompt.py
@@ -27,9 +27,13 @@ import json
import math
import os
from dataclasses import dataclass
-from typing import Any, List, Optional, Sequence, Union
+from typing import Any, Iterator, List, Optional, Sequence, Union
-from soup_cli.utils.paths import is_under_cwd
+from soup_cli.utils.paths import (
+ atomic_write_lines,
+ ensure_distinct_paths,
+ is_under_cwd,
+)
# DoS caps
_MAX_SCAN_ROWS = 100_000
@@ -306,6 +310,11 @@ def prune_traces(
if not os.path.isfile(input_path):
raise FileNotFoundError(input_path)
+ ensure_distinct_paths(
+ [("--input", input_path)],
+ [("--output", output_path)],
+ )
+
# Resolve the tokenizer up front (fails fast on a bad name even on an
# empty input file) — None keeps the legacy character path.
tok = _resolve_tokenizer(tokenizer) if tokenizer is not None else None
@@ -361,25 +370,34 @@ def _prune_char_level(
rows_total: int,
threshold: float,
) -> PrunePromptReport:
- """Character-level prefix strip (the v0.63.0 default behaviour)."""
+ """Strip a character prefix and publish only a complete output."""
prefix = detect_common_prefix(prompts, min_frequency=threshold)
rows_pruned = 0
- with open(input_path, encoding="utf-8") as fh_in, \
- open(output_path, "w", encoding="utf-8") as fh_out:
- for line in fh_in:
- line = line.strip()
- if not line:
- continue
- try:
- row = json.loads(line)
- except json.JSONDecodeError:
- continue
- if not isinstance(row, dict):
- continue
- if prefix and isinstance(row.get("prompt"), str) and row["prompt"].startswith(prefix):
- row["prompt"] = row["prompt"][len(prefix):]
- rows_pruned += 1
- fh_out.write(json.dumps(row, ensure_ascii=False) + "\n")
+
+ def lines() -> Iterator[str]:
+ nonlocal rows_pruned
+ with open(input_path, encoding="utf-8") as fh_in:
+ for line in fh_in:
+ line = line.strip()
+ if not line:
+ continue
+ try:
+ row = json.loads(line)
+ except json.JSONDecodeError:
+ continue
+ if not isinstance(row, dict):
+ continue
+ if (
+ prefix
+ and isinstance(row.get("prompt"), str)
+ and row["prompt"].startswith(prefix)
+ ):
+ row["prompt"] = row["prompt"][len(prefix):]
+ rows_pruned += 1
+ yield json.dumps(row, ensure_ascii=False) + "\n"
+
+ atomic_write_lines(lines(), output_path, field="--output")
+
return PrunePromptReport(
prefix=prefix,
prefix_chars=len(prefix),
@@ -397,36 +415,38 @@ def _prune_token_level(
rows_total: int,
threshold: float,
) -> PrunePromptReport:
- """Token-aware prefix strip (v0.71.5 #205).
-
- The detected prefix is a list of token IDs; stripping a row decodes the
- REMAINING token IDs so the boundary is always a clean token break.
- """
- token_rows = [_encode(tok, p) for p in prompts]
- prefix_ids = detect_common_prefix_tokens(token_rows, min_frequency=threshold)
+ """Strip a token prefix and publish only a complete output."""
+ token_rows = [_encode(tok, prompt) for prompt in prompts]
+ prefix_ids = detect_common_prefix_tokens(
+ token_rows,
+ min_frequency=threshold,
+ )
prefix_text = tok.decode(prefix_ids) if prefix_ids else ""
plen = len(prefix_ids)
-
rows_pruned = 0
- with open(input_path, encoding="utf-8") as fh_in, \
- open(output_path, "w", encoding="utf-8") as fh_out:
- for line in fh_in:
- line = line.strip()
- if not line:
- continue
- try:
- row = json.loads(line)
- except json.JSONDecodeError:
- continue
- if not isinstance(row, dict):
- continue
- prompt = row.get("prompt")
- if prefix_ids and isinstance(prompt, str):
- ids = _encode(tok, prompt)
- if ids[:plen] == prefix_ids:
- row["prompt"] = tok.decode(ids[plen:])
- rows_pruned += 1
- fh_out.write(json.dumps(row, ensure_ascii=False) + "\n")
+
+ def lines() -> Iterator[str]:
+ nonlocal rows_pruned
+ with open(input_path, encoding="utf-8") as fh_in:
+ for line in fh_in:
+ line = line.strip()
+ if not line:
+ continue
+ try:
+ row = json.loads(line)
+ except json.JSONDecodeError:
+ continue
+ if not isinstance(row, dict):
+ continue
+ prompt = row.get("prompt")
+ if prefix_ids and isinstance(prompt, str):
+ ids = _encode(tok, prompt)
+ if ids[:plen] == prefix_ids:
+ row["prompt"] = tok.decode(ids[plen:])
+ rows_pruned += 1
+ yield json.dumps(row, ensure_ascii=False) + "\n"
+
+ atomic_write_lines(lines(), output_path, field="--output")
return PrunePromptReport(
prefix=prefix_text,
diff --git a/src/soup_cli/utils/ra_dit_run.py b/src/soup_cli/utils/ra_dit_run.py
index a5ca4ca4..647854db 100644
--- a/src/soup_cli/utils/ra_dit_run.py
+++ b/src/soup_cli/utils/ra_dit_run.py
@@ -34,6 +34,7 @@ import subprocess
import sys
import tempfile
from dataclasses import dataclass
+from pathlib import Path
from typing import Any, Callable, Optional, Tuple
_MIN_TIMEOUT_S = 60
@@ -50,6 +51,7 @@ __all__ = [
"resolve_retriever_for_generator",
"run_ra_dit",
"validate_ra_dit_config_path",
+ "load_ra_dit_configs",
]
@@ -289,6 +291,51 @@ def _run_train_subprocess(config_path: str, *, timeout_seconds: int) -> None:
)
+def _effective_output(config: dict, field: str) -> str:
+ """Resolve the output directory using the trainers' experiment convention."""
+ output = config.get("output")
+ if not isinstance(output, str) or not output:
+ raise ValueError(
+ f"{field} must declare a non-empty 'output' directory"
+ )
+
+ experiment_name = config.get("experiment_name")
+ if experiment_name:
+ if not isinstance(experiment_name, str):
+ raise ValueError(
+ f"{field} experiment_name must be a string"
+ )
+ return str(Path(output) / experiment_name)
+
+ return output
+
+
+def load_ra_dit_configs(
+ retriever_config: str,
+ generator_config: str,
+) -> tuple[dict, dict, str, str]:
+ """Load both recipes and reject overlapping effective output directories."""
+ from soup_cli.utils.paths import ensure_distinct_paths # noqa: PLC0415
+
+ retr_path = validate_ra_dit_config_path(
+ "--retriever-config", retriever_config
+ )
+ gen_path = validate_ra_dit_config_path(
+ "--generator-config", generator_config
+ )
+ retr_cfg = _load_yaml_config(retr_path)
+ gen_cfg = _load_yaml_config(gen_path)
+ retriever_output = _effective_output(retr_cfg, "--retriever-config")
+ generator_output = _effective_output(gen_cfg, "--generator-config")
+
+ ensure_distinct_paths(
+ [("--retriever-config output", retriever_output)],
+ [("--generator-config output", generator_output)],
+ reject_nested=True,
+ )
+ return retr_cfg, gen_cfg, retriever_output, generator_output
+
+
def run_ra_dit(
retriever_config: str,
generator_config: str,
@@ -315,28 +362,18 @@ def run_ra_dit(
TypeError / ValueError / FileNotFoundError: input validation.
RuntimeError: a training stage failed.
"""
- retr_path = _validate_config_path("retriever_config", retriever_config)
- gen_path = _validate_config_path("generator_config", generator_config)
timeout = _validate_timeout(timeout_seconds)
runner = _runner if _runner is not None else (
lambda p: _run_train_subprocess(p, timeout_seconds=timeout)
)
- retr_cfg = _load_yaml_config(retr_path)
- gen_cfg = _load_yaml_config(gen_path)
- retriever_output = retr_cfg.get("output")
- if not isinstance(retriever_output, str) or not retriever_output:
- raise ValueError(
- "retriever config must declare a non-empty 'output' directory"
- )
- generator_output = gen_cfg.get("output")
- if not isinstance(generator_output, str) or not generator_output:
- raise ValueError(
- "generator config must declare a non-empty 'output' directory"
- )
+ _, gen_cfg, retriever_output, generator_output = load_ra_dit_configs(
+ retriever_config,
+ generator_config,
+ )
# Stage 1 — train the retriever.
- runner(retr_path)
+ runner(retriever_config)
# Link: manual override wins; else the retriever's own output dir.
if retriever_model is not None:
diff --git a/tests/test_best_of_n_checkpoint_safety.py b/tests/test_best_of_n_checkpoint_safety.py
new file mode 100644
index 00000000..0df4ebdb
--- /dev/null
+++ b/tests/test_best_of_n_checkpoint_safety.py
@@ -0,0 +1,292 @@
+import json
+from pathlib import Path
+
+import pytest
+
+from soup_cli.utils.best_of_n_checkpoint import (
+ append_checkpoint,
+ initialise_checkpoint,
+ load_checkpoint,
+)
+from tests.conftest import strip_ansi
+
+
+ ("invalid_part", "message"),
+ [
+ ("run-digest", "does not match"),
+ ("total", "does not match"),
+ ("version", "version is not supported"),
+ ("entry-digest", "digest mismatch"),
+ ],
+)
+def test_invalid_checkpoint_keeps_incomplete_tail_unchanged(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ invalid_part: str,
+ message: str,
+) -> None:
+ monkeypatch.chdir(tmp_path)
+ checkpoint = Path("run.checkpoint.jsonl")
+ initialise_checkpoint(str(checkpoint), digest="expected-run", total=2)
+ append_checkpoint(
+ str(checkpoint),
+ index=0,
+ sft={"prompt": "Question", "output": "Answer"},
+ dpo=None,
+ )
+
+ records = [
+ json.loads(line)
+ for line in checkpoint.read_text(encoding="utf-8").splitlines()
+ ]
+ header = records[0]["_best_of_n_checkpoint"]
+ if invalid_part == "run-digest":
+ header["run_digest"] = "different-run"
+ elif invalid_part == "total":
+ header["total"] = 99
+ elif invalid_part == "version":
+ header["version"] = 999
+ else:
+ records[1]["entry_digest"] = "invalid-entry-digest"
+
+ committed = "".join(
+ json.dumps(record, sort_keys=True) + "\n"
+ for record in records
+ ).encode("utf-8")
+ original = committed + b'{"index":1,"sft":'
+ checkpoint.write_bytes(original)
+
+ with pytest.raises(ValueError, match=message):
+ load_checkpoint(
+ str(checkpoint),
+ digest="expected-run",
+ total=2,
+ )
+
+ assert checkpoint.read_bytes() == original
+ assert sorted(path.name for path in tmp_path.iterdir()) == [
+ checkpoint.name
+ ]
+
+
+def test_valid_checkpoint_recovers_incomplete_tail(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.chdir(tmp_path)
+ checkpoint = Path("run.checkpoint.jsonl")
+ sft = {"prompt": "Question", "output": "Answer"}
+ initialise_checkpoint(str(checkpoint), digest="expected-run", total=2)
+ append_checkpoint(
+ str(checkpoint),
+ index=0,
+ sft=sft,
+ dpo=None,
+ )
+ committed = checkpoint.read_bytes()
+ checkpoint.write_bytes(committed + b'{"index":1,"sft":')
+
+ entries = load_checkpoint(
+ str(checkpoint),
+ digest="expected-run",
+ total=2,
+ )
+
+ assert entries == [(sft, None)]
+ assert checkpoint.read_bytes() == committed
+
+ next_sft = {"prompt": "Next question", "output": "Next answer"}
+ append_checkpoint(
+ str(checkpoint),
+ index=1,
+ sft=next_sft,
+ dpo=None,
+ )
+
+ assert load_checkpoint(
+ str(checkpoint),
+ digest="expected-run",
+ total=2,
+ ) == [(sft, None), (next_sft, None)]
+
+ "content",
+ [
+ b"",
+ b'{"_best_of_n_checkpoint":',
+ (
+ b'{"_best_of_n_checkpoint":'
+ b'{"version":1,"run_digest":"expected-run","total":2}}'
+ ),
+ ],
+ ids=["empty", "partial-header", "header-without-newline"],
+)
+def test_checkpoint_without_committed_header_is_not_modified(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ content: bytes,
+) -> None:
+ monkeypatch.chdir(tmp_path)
+ checkpoint = Path("run.checkpoint.jsonl")
+ checkpoint.write_bytes(content)
+
+ with pytest.raises(ValueError, match="empty|header"):
+ load_checkpoint(
+ str(checkpoint),
+ digest="expected-run",
+ total=2,
+ )
+
+ assert checkpoint.read_bytes() == content
+
+
+ "committed_corruption",
+ [False, True],
+ ids=["incomplete-utf8-tail", "invalid-utf8-committed-record"],
+)
+def test_checkpoint_handles_interrupted_utf8_without_losing_committed_data(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ committed_corruption: bool,
+) -> None:
+ monkeypatch.chdir(tmp_path)
+ checkpoint = Path("run.checkpoint.jsonl")
+ sft = {"prompt": "Otázka", "output": "Odpoveď"}
+ initialise_checkpoint(str(checkpoint), digest="expected-run", total=2)
+ append_checkpoint(
+ str(checkpoint),
+ index=0,
+ sft=sft,
+ dpo=None,
+ )
+ committed = checkpoint.read_bytes()
+ fragment = b'{"index":1,"sft":{"prompt":"\xc3'
+ if committed_corruption:
+ fragment += b"\n"
+
+ original = committed + fragment
+ checkpoint.write_bytes(original)
+
+ if committed_corruption:
+ with pytest.raises(ValueError, match="invalid JSON on line 3"):
+ load_checkpoint(
+ str(checkpoint),
+ digest="expected-run",
+ total=2,
+ )
+ assert checkpoint.read_bytes() == original
+ else:
+ assert load_checkpoint(
+ str(checkpoint),
+ digest="expected-run",
+ total=2,
+ ) == [(sft, None)]
+ assert checkpoint.read_bytes() == committed
+
+ "existing_outputs",
+ [False, True],
+ ids=["new-outputs", "existing-outputs"],
+)
+def test_resume_rejects_invalid_checkpoint_without_changing_files(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ existing_outputs: bool,
+) -> None:
+ from typer.testing import CliRunner
+
+ from soup_cli.cli import app
+ from soup_cli.eval import judge
+ from soup_cli.utils import magpie
+
+ monkeypatch.chdir(tmp_path)
+ source = Path("prompts.jsonl")
+ source.write_bytes(b'{"prompt":"Explain gravity."}\n')
+
+ checkpoint = Path("run.checkpoint.jsonl")
+ initialise_checkpoint(
+ str(checkpoint),
+ digest="different-run",
+ total=1,
+ )
+ header = json.loads(checkpoint.read_text(encoding="utf-8"))
+ header["_best_of_n_checkpoint"]["version"] = 999
+ checkpoint.write_bytes(
+ (json.dumps(header) + "\n").encode("utf-8")
+ + b'{"index":0,"sft":{"prompt":"\xc3'
+ )
+
+ output_names = [
+ "selected.jsonl",
+ "pairs.jsonl",
+ "run.manifest.json",
+ ]
+ if existing_outputs:
+ for name in output_names:
+ Path(name).write_bytes(
+ f"Previous successful artifact: {name}\n".encode("utf-8")
+ )
+
+ generation_calls = []
+
+ def unexpected_generation(*args, **kwargs):
+ generation_calls.append((args, kwargs))
+ pytest.fail("Generation started before rejecting an invalid checkpoint")
+
+ def fake_sampler_factory(*args, **kwargs):
+ return unexpected_generation
+
+ monkeypatch.setattr(
+ judge,
+ "JudgeEvaluator",
+ lambda **kwargs: object(),
+ )
+ monkeypatch.setattr(
+ magpie,
+ "make_magpie_generate_fn",
+ fake_sampler_factory,
+ )
+
+ before = {
+ path.name: path.read_bytes()
+ for path in tmp_path.iterdir()
+ }
+
+ result = CliRunner().invoke(
+ app,
+ [
+ "data",
+ "best-of-n",
+ "--prompts",
+ str(source),
+ "--provider",
+ "ollama",
+ "--model",
+ "test-model",
+ "--judge",
+ "ollama://test-judge",
+ "--output",
+ "selected.jsonl",
+ "--emit-pairs",
+ "pairs.jsonl",
+ "--checkpoint",
+ str(checkpoint),
+ "--manifest",
+ "run.manifest.json",
+ "--resume",
+ ],
+ )
+ message = " ".join(strip_ansi(result.output).split())
+
+ after = {
+ path.name: path.read_bytes()
+ for path in tmp_path.iterdir()
+ }
+
+ assert result.exit_code == 2, (result.output, repr(result.exception))
+ assert "Invalid checkpoint" in message
+ assert "version is not supported" in message
+ assert generation_calls == []
+ assert after == before
diff --git a/tests/test_best_of_n_input_aliases.py b/tests/test_best_of_n_input_aliases.py
new file mode 100644
index 00000000..7b647897
--- /dev/null
+++ b/tests/test_best_of_n_input_aliases.py
@@ -0,0 +1,97 @@
+import os
+from pathlib import Path
+
+import pytest
+from typer.testing import CliRunner
+
+from soup_cli.cli import app
+from tests.conftest import strip_ansi
+
+
[email protected]("resume", [False, True], ids=["new-run", "resume"])
+ "output_option",
+ ["--output", "--emit-pairs", "--checkpoint", "--manifest"],
+)
+ "alias_kind",
+ [
+ "same-path",
+ "dot-alias",
+ pytest.param("hardlink", marks=pytest.mark.requires_hardlink),
+ "windows-case",
+ ],
+)
+def test_online_input_alias_is_rejected_without_writes(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ resume: bool,
+ output_option: str,
+ alias_kind: str,
+) -> None:
+ from soup_cli.eval import judge
+ from soup_cli.utils import magpie
+
+ monkeypatch.chdir(tmp_path)
+ source = Path("prompts.jsonl")
+ source.write_bytes(b'{"prompt":"Explain gravity."}')
+
+ alias = str(source)
+ if alias_kind == "dot-alias":
+ alias = "./prompts.jsonl"
+ elif alias_kind == "hardlink":
+ linked = Path("linked-prompts.jsonl")
+ linked.hardlink_to(source)
+ alias = str(linked)
+ elif alias_kind == "windows-case":
+ if os.name != "nt":
+ pytest.skip("Windows case-alias test")
+ alias = "PROMPTS.JSONL"
+ if not os.path.exists(alias) or not os.path.samefile(source, alias):
+ pytest.skip("Working directory is case-sensitive")
+
+ sampler_calls = []
+
+ def forbidden_sampler(*args, **kwargs):
+ sampler_calls.append((args, kwargs))
+ pytest.fail("Sampler constructed before rejecting an input alias")
+
+ monkeypatch.setattr(judge, "JudgeEvaluator", lambda **kwargs: object())
+ monkeypatch.setattr(magpie, "make_magpie_generate_fn", forbidden_sampler)
+
+ options = {
+ "--output": "selected.jsonl",
+ "--emit-pairs": "pairs.jsonl",
+ "--checkpoint": "run.checkpoint.jsonl",
+ "--manifest": "run.manifest.json",
+ }
+ options[output_option] = alias
+
+ arguments = [
+ "data",
+ "best-of-n",
+ "--prompts",
+ str(source),
+ "--provider",
+ "ollama",
+ "--model",
+ "test-model",
+ "--judge",
+ "ollama://test-judge",
+ ]
+ for option, value in options.items():
+ arguments.extend([option, value])
+ if resume:
+ arguments.append("--resume")
+
+ before = {path.name: path.read_bytes() for path in tmp_path.iterdir()}
+ result = CliRunner().invoke(app, arguments)
+ after = {path.name: path.read_bytes() for path in tmp_path.iterdir()}
+ message = " ".join(strip_ansi(result.output).split())
+
+ assert after == before
+ assert result.exit_code == 2, (result.output, repr(result.exception))
+ assert "--prompts" in message
+ assert output_option in message
+ assert "same file" in message
+ assert sampler_calls == []
diff --git a/tests/test_best_of_n_output_safety.py b/tests/test_best_of_n_output_safety.py
new file mode 100644
index 00000000..beb07849
--- /dev/null
+++ b/tests/test_best_of_n_output_safety.py
@@ -0,0 +1,245 @@
+from pathlib import Path
+
+import pytest
+from typer.testing import CliRunner
+
+from soup_cli.cli import app
+from tests.conftest import strip_ansi
+
+
[email protected]("plan_only", [True, False], ids=["plan", "live"])
+ "output_option",
+ ["--output", "--emit-pairs", "--checkpoint", "--manifest"],
+)
+ "alias",
+ ["prompts.jsonl", "./prompts.jsonl"],
+ ids=["same-path", "dot-alias"],
+)
+def test_best_of_n_rejects_output_aliasing_prompts_before_sampling(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ output_option: str,
+ alias: str,
+ plan_only: bool,
+) -> None:
+ from soup_cli.eval import judge
+ from soup_cli.utils import magpie
+
+ monkeypatch.chdir(tmp_path)
+ source = Path("prompts.jsonl")
+ original = b'{"prompt": "Explain gravity."}\n'
+ source.write_bytes(original)
+
+ sampler_calls = []
+
+ def fake_sampler_factory(*args, **kwargs):
+ sampler_calls.append((args, kwargs))
+ return lambda *args, **kwargs: "unused"
+
+ monkeypatch.setattr(
+ judge,
+ "JudgeEvaluator",
+ lambda **kwargs: object(),
+ )
+ monkeypatch.setattr(
+ magpie,
+ "make_magpie_generate_fn",
+ fake_sampler_factory,
+ )
+
+ options = {
+ "--output": "selected.jsonl",
+ "--emit-pairs": "pairs.jsonl",
+ "--checkpoint": "run.checkpoint.jsonl",
+ "--manifest": "run.manifest.json",
+ }
+ options[output_option] = alias
+
+ arguments = [
+ "data",
+ "best-of-n",
+ "--prompts",
+ "prompts.jsonl",
+ "--provider",
+ "ollama",
+ "--model",
+ "test-model",
+ "--judge",
+ "ollama://test-judge",
+ ]
+ if plan_only:
+ arguments.append("--plan-only")
+
+ for option, value in options.items():
+ arguments.extend([option, value])
+
+ result = CliRunner().invoke(app, arguments)
+ message = " ".join(strip_ansi(result.output).split())
+
+ assert source.read_bytes() == original
+ assert result.exit_code == 2, (result.output, repr(result.exception))
+ assert "--prompts" in message
+ assert output_option in message
+ assert "same file" in message
+ assert sampler_calls == []
+ assert sorted(path.name for path in tmp_path.iterdir()) == [
+ "prompts.jsonl"
+ ]
+
[email protected]("plan_only", [True, False], ids=["plan", "live"])
+ "output_option",
+ ["--output", "--emit-pairs", "--manifest"],
+)
+ "input_option",
+ ["--candidate-artifact", "--judgments"],
+)
+def test_offline_rejects_output_hardlink_before_indexing(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ input_option: str,
+ output_option: str,
+ plan_only: bool,
+) -> None:
+ from soup_cli.utils import best_of_n_stream
+
+ monkeypatch.chdir(tmp_path)
+ candidates = Path("candidates.jsonl")
+ judgments = Path("judgments.jsonl")
+ candidates.write_bytes(b"candidate input must remain unchanged\n")
+ judgments.write_bytes(b"judgment input must remain unchanged\n")
+
+ inputs = {
+ "--candidate-artifact": candidates,
+ "--judgments": judgments,
+ }
+ alias = Path("alias.jsonl")
+ alias.hardlink_to(inputs[input_option])
+
+ def unexpected_indexing(*args, **kwargs):
+ pytest.fail("Offline indexing started before rejecting an input alias")
+
+ monkeypatch.setattr(
+ best_of_n_stream,
+ "index_offline_artifacts",
+ unexpected_indexing,
+ )
+
+ options = {
+ "--candidate-artifact": str(candidates),
+ "--judgments": str(judgments),
+ "--output": "selected.jsonl",
+ "--emit-pairs": "pairs.jsonl",
+ "--manifest": "run.manifest.json",
+ }
+ options[output_option] = str(alias)
+
+ before = {
+ path.name: path.read_bytes()
+ for path in tmp_path.iterdir()
+ }
+ arguments = ["data", "best-of-n"]
+ if plan_only:
+ arguments.append("--plan-only")
+ for option, value in options.items():
+ arguments.extend([option, value])
+
+ result = CliRunner().invoke(app, arguments)
+ message = " ".join(strip_ansi(result.output).split())
+
+ after = {
+ path.name: path.read_bytes()
+ for path in tmp_path.iterdir()
+ }
+ assert after == before
+ assert result.exit_code == 2, (result.output, repr(result.exception))
+ assert input_option in message
+ assert output_option in message
+ assert "same file" in message
+
[email protected]("plan_only", [True, False], ids=["plan", "live"])
+ "output_option",
+ ["--export-candidates", "--checkpoint"],
+)
+ "alias_kind",
+ [
+ "same-path",
+ "dot-alias",
+ pytest.param("hardlink", marks=pytest.mark.requires_hardlink),
+ ],
+)
+def test_export_rejects_output_aliasing_prompts_before_sampling(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ output_option: str,
+ alias_kind: str,
+ plan_only: bool,
+) -> None:
+ from soup_cli.utils import magpie
+
+ monkeypatch.chdir(tmp_path)
+ source = Path("prompts.jsonl")
+ source.write_bytes(b'{"prompt": "Explain gravity."}\n')
+
+ if alias_kind == "hardlink":
+ alias_path = Path("alias.jsonl")
+ alias_path.hardlink_to(source)
+ alias = str(alias_path)
+ elif alias_kind == "dot-alias":
+ alias = "./prompts.jsonl"
+ else:
+ alias = "prompts.jsonl"
+
+ def unexpected_sampler(*args, **kwargs):
+ pytest.fail("Sampler constructed before rejecting an input alias")
+
+ monkeypatch.setattr(
+ magpie,
+ "make_magpie_generate_fn",
+ unexpected_sampler,
+ )
+
+ options = {
+ "--export-candidates": "candidates.jsonl",
+ "--checkpoint": "run.checkpoint.jsonl",
+ }
+ options[output_option] = alias
+
+ before = {
+ path.name: path.read_bytes()
+ for path in tmp_path.iterdir()
+ }
+ arguments = [
+ "data",
+ "best-of-n",
+ "--prompts",
+ "prompts.jsonl",
+ "--provider",
+ "ollama",
+ "--model",
+ "test-model",
+ ]
+ if plan_only:
+ arguments.append("--plan-only")
+ for option, value in options.items():
+ arguments.extend([option, value])
+
+ result = CliRunner().invoke(app, arguments)
+ message = " ".join(strip_ansi(result.output).split())
+
+ after = {
+ path.name: path.read_bytes()
+ for path in tmp_path.iterdir()
+ }
+ assert after == before
+ assert result.exit_code == 2, (result.output, repr(result.exception))
+ assert (
+ "must be distinct" in message
+ or "same file" in message
+ )
diff --git a/tests/test_distinct_output_paths.py b/tests/test_distinct_output_paths.py
new file mode 100644
index 00000000..8e779192
--- /dev/null
+++ b/tests/test_distinct_output_paths.py
@@ -0,0 +1,228 @@
+"""#1422: an output path that aliases an input must be refused before any write.
+
+Four commands (``ingest``, ``prune-prompt``, ``ra-dit`` and ``data best-of-n``)
+opened their output for writing without checking that it was not one of their
+inputs, so the write destroyed the input and the command still exited 0.
+
+``ensure_distinct_paths`` is the one shared check. It compares real paths
+(``normcase(realpath(...))``) and, for files that exist, ``os.path.samefile``,
+so a spelling of the input (``./x``, a case variant on Windows) and a hard link
+are refused as well as the identical string. It opens and creates nothing.
+
+This file covers the shared helper and soup ingest.
+Other commands have dedicated output-safety test modules.
+"""
+
+from __future__ import annotations
+
+import os
+
+import pytest
+from typer.testing import CliRunner
+
+from soup_cli.cli import app
+from soup_cli.utils.paths import ensure_distinct_paths
+from tests.conftest import strip_ansi
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
[email protected](autouse=True)
+def _in_tmp(tmp_path, monkeypatch):
+ # Soup refuses paths outside the working directory, so every test runs
+ # inside its own temporary directory and never touches the repository.
+ monkeypatch.chdir(tmp_path)
+
+
+def _write(name: str, text: str = "x\n") -> str:
+ # newline="" keeps the bytes exactly as given on Windows, so the
+ # byte-identical assertions below compare what was really written.
+ with open(name, "w", encoding="utf-8", newline="") as fh:
+ fh.write(text)
+ return name
+
+
+def _read(name: str) -> str:
+ with open(name, encoding="utf-8", newline="") as fh:
+ return fh.read()
+
+
+def _flat(output: str) -> str:
+ # Rich wraps long messages at the terminal width; flatten the lines so an
+ # assertion on a phrase does not depend on where the wrap fell.
+ return " ".join(strip_ansi(output).split())
+
+
+# ---------------------------------------------------------------------------
+# The shared helper
+# ---------------------------------------------------------------------------
+
+
+class TestEnsureDistinctPaths:
+ def test_same_string_is_refused_and_names_both_options(self):
+ # The plain case from the issue: --logs is also the default --output.
+ _write("a.jsonl")
+ with pytest.raises(ValueError) as info:
+ ensure_distinct_paths([("--logs", "a.jsonl")], [("--output", "a.jsonl")])
+ message = str(info.value)
+ # The operator must be told which two options collide.
+ assert "--logs" in message
+ assert "--output" in message
+
+ def test_dot_slash_spelling_is_refused(self):
+ # A different spelling of the same file must not slip past a string compare.
+ _write("a.jsonl")
+ with pytest.raises(ValueError):
+ ensure_distinct_paths([("--logs", "./a.jsonl")], [("--output", "a.jsonl")])
+
+ def test_a_missing_file_spelled_the_same_is_refused(self):
+ # Nothing exists yet, so samefile cannot help; the real-path compare must.
+ with pytest.raises(ValueError):
+ ensure_distinct_paths([("--logs", "no.jsonl")], [("--output", "no.jsonl")])
+
+ @pytest.mark.skipif(os.name != "nt", reason="case-insensitive file system")
+ def test_case_variant_is_refused_on_windows(self):
+ # On Windows Traces.jsonl and traces.jsonl are one file.
+ _write("Traces.jsonl")
+ with pytest.raises(ValueError):
+ ensure_distinct_paths(
+ [("--logs", "Traces.jsonl")], [("--output", "traces.jsonl")]
+ )
+
+ @pytest.mark.skipif(os.name != "nt", reason="case-insensitive file system")
+ def test_case_variant_of_a_path_that_does_not_exist_yet_is_refused_on_windows(self):
+ with pytest.raises(ValueError):
+ ensure_distinct_paths([("--logs", "Missing.jsonl")], [("--output", "missing.jsonl")])
+
+ @pytest.mark.skipif(os.name != "nt", reason="case-insensitive file system")
+ def test_nested_case_variant_of_a_missing_directory_is_refused_on_windows(self):
+ with pytest.raises(ValueError):
+ ensure_distinct_paths(
+ [("--retriever-config output", "out/R1/stage")],
+ [("--generator-config output", "out/r1")],
+ reject_nested=True,
+ )
+
+ @pytest.mark.requires_symlink
+ def test_symlinked_directory_alias_of_a_missing_output_is_refused(self):
+ os.mkdir("real")
+ os.symlink("real", "link", target_is_directory=True)
+ with pytest.raises(ValueError):
+ ensure_distinct_paths(
+ [("--retriever-config output", "real/r1")],
+ [("--generator-config output", "link/r1")],
+ reject_nested=True,
+ )
+ with pytest.raises(ValueError):
+ ensure_distinct_paths([("--logs", "real/in.jsonl")], [("--output", "link/in.jsonl")])
+ with pytest.raises(ValueError):
+ ensure_distinct_paths(
+ [("--retriever-config output", "link/r1")],
+ [("--generator-config output", "real/r1")],
+ reject_nested=True,
+ )
+ with pytest.raises(ValueError):
+ ensure_distinct_paths([("--logs", "link/in.jsonl")], [("--output", "real/in.jsonl")])
+
+ @pytest.mark.requires_hardlink
+ def test_hard_link_is_refused(self):
+ # A hard link has a different path but is the same file on disk, so only
+ # os.path.samefile catches it.
+ _write("a.jsonl")
+ os.link("a.jsonl", "b.jsonl")
+ with pytest.raises(ValueError):
+ ensure_distinct_paths([("--input", "a.jsonl")], [("--output", "b.jsonl")])
+
+ def test_distinct_paths_pass(self):
+ # The control: the check is about aliasing, not about every pair of paths.
+ _write("a.jsonl")
+ ensure_distinct_paths([("--logs", "a.jsonl")], [("--output", "b.jsonl")])
+
+ def test_the_check_writes_nothing(self):
+ # It is called before any open-for-write, so it must not create or
+ # change a file itself.
+ _write("a.jsonl", "keep\n")
+ ensure_distinct_paths([("--logs", "a.jsonl")], [("--output", "b.jsonl")])
+ assert _read("a.jsonl") == "keep\n"
+ assert not os.path.exists("b.jsonl")
+
+
+# ---------------------------------------------------------------------------
+# soup ingest
+# ---------------------------------------------------------------------------
+
+
+class TestIngestRefusesItsOwnInput:
+ def test_default_output_equal_to_logs_is_refused(self):
+ # The issue's first reproduction: without --output, the default
+ # traces.jsonl is also --logs. On main this left a 0-byte file and exit 0.
+ original = '{"id": "t1", "input": "hi", "output": "hello"}\n'
+ _write("traces.jsonl", original)
+ result = CliRunner().invoke(
+ app, ["ingest", "--source", "langfuse", "--logs", "traces.jsonl"]
+ )
+ assert result.exit_code != 0, result.output
+ out = _flat(result.output)
+ assert "--logs" in out
+ assert "--output" in out
+ # The input survives byte for byte.
+ assert _read("traces.jsonl") == original
+
+ def test_a_different_output_still_works(self):
+ # The control: a normal run is unchanged by the new check.
+ _write("in.jsonl", '{"id": "t1", "input": "hi", "output": "hello"}\n')
+ result = CliRunner().invoke(
+ app,
+ ["ingest", "--source", "langfuse", "--logs", "in.jsonl", "-o", "out.jsonl"],
+ )
+ assert result.exit_code == 0, result.output
+ assert os.path.getsize("out.jsonl") > 0
+
+ def test_dot_slash_spelling_of_logs_is_refused(self):
+ # The same file spelled ./traces.jsonl must be refused like traces.jsonl.
+ original = '{"id": "t1", "input": "hi", "output": "hello"}\n'
+ _write("traces.jsonl", original)
+ result = CliRunner().invoke(
+ app, ["ingest", "--source", "langfuse", "--logs", "./traces.jsonl"]
+ )
+ assert result.exit_code != 0, result.output
+ assert _read("traces.jsonl") == original
+
+ def test_explicit_output_equal_to_logs_is_refused(self):
+ # Not only the default output: -o pointing at --logs is the same bug.
+ original = '{"id": "t1", "input": "hi", "output": "hello"}\n'
+ _write("e.jsonl", original)
+ result = CliRunner().invoke(
+ app,
+ ["ingest", "--source", "langfuse", "--logs", "e.jsonl", "-o", "e.jsonl"],
+ )
+ assert result.exit_code != 0, result.output
+ assert _read("e.jsonl") == original
+
+ def test_a_logs_directory_leaves_an_existing_output_untouched(self):
+ # A read failure must never leave a truncated output behind: on main this
+ # emptied a good earlier traces.jsonl before the read failed.
+ good = '{"id": "t1", "input": "hi", "output": "hello"}\n'
+ _write("traces.jsonl", good)
+ os.mkdir("some_dir")
+ result = CliRunner().invoke(
+ app, ["ingest", "--source", "langfuse", "--logs", "some_dir"]
+ )
+ assert result.exit_code != 0
+ assert _read("traces.jsonl") == good
+
+ def test_a_non_utf8_export_leaves_an_existing_output_untouched(self):
+ # Same property for an export the reader cannot decode.
+ good = '{"id": "t1", "input": "hi", "output": "hello"}\n'
+ _write("traces.jsonl", good)
+ with open("bad.jsonl", "wb") as fh:
+ fh.write(b"\xff\xfe\x00 not utf-8\n")
+ result = CliRunner().invoke(
+ app, ["ingest", "--source", "langfuse", "--logs", "bad.jsonl"]
+ )
+ assert result.exit_code != 0
+ assert _read("traces.jsonl") == good
+ # The staging file of the atomic write must be cleaned up too.
+ assert [n for n in os.listdir(".") if n.startswith(".soup.")] == []
diff --git a/tests/test_prune_prompt_output_safety.py b/tests/test_prune_prompt_output_safety.py
new file mode 100644
index 00000000..e1f7c799
--- /dev/null
+++ b/tests/test_prune_prompt_output_safety.py
@@ -0,0 +1,271 @@
+import json
+from pathlib import Path
+
+import pytest
+from typer.testing import CliRunner
+
+from soup_cli.utils.prune_prompt import prune_traces
+from tests.conftest import strip_ansi
+
+
+class CharacterTokenizer:
+ """Deterministic tokenizer double; no model downloads required."""
+
+ def encode(
+ self,
+ text: str,
+ *,
+ add_special_tokens: bool = False,
+ ) -> list[int]:
+ return [ord(character) for character in text]
+
+ def decode(self, token_ids: list[int]) -> str:
+ return "".join(chr(token_id) for token_id in token_ids)
+
+
[email protected]("token_aware", [False, True], ids=["char", "token"])
[email protected]("path_alias", [False, True], ids=["same-path", "dot-alias"])
+def test_prune_rejects_input_as_output_without_changing_bytes(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ token_aware: bool,
+ path_alias: bool,
+) -> None:
+ monkeypatch.chdir(tmp_path)
+
+ source = Path("traces.jsonl")
+ original = (
+ '{"prompt": "SYSTEM: alpha", "output": "one"}\n'
+ '{"prompt": "SYSTEM: beta", "output": "two"}\n'
+ ).encode("utf-8")
+ source.write_bytes(original)
+
+ output_path = "./traces.jsonl" if path_alias else "traces.jsonl"
+ tokenizer = CharacterTokenizer() if token_aware else None
+
+ try:
+ with pytest.raises(ValueError):
+ prune_traces(
+ "traces.jsonl",
+ output_path=output_path,
+ min_frequency=1.0,
+ tokenizer=tokenizer,
+ )
+ finally:
+ assert source.read_bytes() == original, "Input data was modified"
+
[email protected]("output_path", ["traces.jsonl", "./traces.jsonl"])
+def test_prune_cli_rejects_input_as_output(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ output_path: str,
+) -> None:
+ from soup_cli.cli import app
+
+ monkeypatch.chdir(tmp_path)
+ source = Path("traces.jsonl")
+ original = (
+ '{"prompt": "SYSTEM: alpha", "output": "one"}\n'
+ '{"prompt": "SYSTEM: beta", "output": "two"}\n'
+ ).encode("utf-8")
+ source.write_bytes(original)
+
+ result = CliRunner().invoke(
+ app,
+ [
+ "prune-prompt",
+ "--input",
+ "traces.jsonl",
+ "--output",
+ output_path,
+ ],
+ )
+ message = " ".join(strip_ansi(result.output).split())
+
+ assert source.read_bytes() == original
+ assert result.exit_code == 1, (result.output, repr(result.exception))
+ assert "--input" in message
+ assert "--output" in message
+ assert "same file" in message
+
[email protected]("token_aware", [False, True], ids=["char", "token"])
+def test_prune_writes_distinct_output_without_changing_input(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ token_aware: bool,
+) -> None:
+ monkeypatch.chdir(tmp_path)
+ source = Path("traces.jsonl")
+ destination = Path("pruned.jsonl")
+ rows = [
+ {"prompt": "SYSTEM: alpha", "output": "one", "metadata": {"id": 1}},
+ {"prompt": "SYSTEM: beta", "output": "two", "metadata": {"id": 2}},
+ ]
+ original = (
+ "\n".join(json.dumps(row) for row in rows) + "\n"
+ ).encode("utf-8")
+ source.write_bytes(original)
+
+ tokenizer = CharacterTokenizer() if token_aware else None
+ report = prune_traces(
+ str(source),
+ output_path=str(destination),
+ min_frequency=1.0,
+ tokenizer=tokenizer,
+ )
+
+ assert source.read_bytes() == original
+ assert destination.is_file()
+ actual_rows = [
+ json.loads(line)
+ for line in destination.read_text(encoding="utf-8").splitlines()
+ ]
+ assert actual_rows == [
+ {"prompt": "alpha", "output": "one", "metadata": {"id": 1}},
+ {"prompt": "beta", "output": "two", "metadata": {"id": 2}},
+ ]
+ assert report.prefix == "SYSTEM: "
+ assert report.prefix_chars == len("SYSTEM: ")
+ assert report.rows_total == 2
+ assert report.rows_pruned == 2
+ assert report.min_frequency == 1.0
+
[email protected]("token_aware", [False, True], ids=["char", "token"])
+ "existing_output",
+ [False, True],
+ ids=["new-output", "existing-output"],
+)
+def test_prune_read_failure_does_not_publish_partial_output(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ token_aware: bool,
+ existing_output: bool,
+) -> None:
+ import builtins
+ from contextlib import contextmanager
+
+ from soup_cli.utils import prune_prompt
+
+ monkeypatch.chdir(tmp_path)
+ source = Path("traces.jsonl")
+ destination = Path("pruned.jsonl")
+ original_input = (
+ b'{"prompt": "SYSTEM alpha", "output": "one"}\n'
+ b'{"prompt": "SYSTEM beta", "output": "two"}\n'
+ )
+ original_output = b"Previous successful output\n"
+ source.write_bytes(original_input)
+ if existing_output:
+ destination.write_bytes(original_output)
+
+ expected_files = {path.name for path in tmp_path.iterdir()}
+ real_open = builtins.open
+ source_reads = 0
+
+ def interrupted_lines(handle):
+ yield next(handle)
+ raise OSError("Simulated failure during second input pass")
+
+ @contextmanager
+ def open_with_read_failure(file, mode="r", *args, **kwargs):
+ nonlocal source_reads
+ with real_open(file, mode, *args, **kwargs) as handle:
+ if Path(file).resolve() == source.resolve() and mode == "r":
+ source_reads += 1
+ if source_reads == 2:
+ yield interrupted_lines(handle)
+ return
+ yield handle
+
+ monkeypatch.setattr(
+ prune_prompt,
+ "open",
+ open_with_read_failure,
+ raising=False,
+ )
+
+ with pytest.raises(
+ OSError,
+ match="Simulated failure during second input pass",
+ ):
+ prune_prompt.prune_traces(
+ str(source),
+ output_path=str(destination),
+ min_frequency=1.0,
+ tokenizer=CharacterTokenizer() if token_aware else None,
+ )
+
+ assert source_reads == 2
+ assert source.read_bytes() == original_input
+ if existing_output:
+ assert destination.read_bytes() == original_output
+ else:
+ assert not destination.exists()
+ assert {path.name for path in tmp_path.iterdir()} == expected_files
+
[email protected]("token_aware", [False, True], ids=["char", "token"])
+ "existing_output",
+ [False, True],
+ ids=["new-output", "existing-output"],
+)
+def test_prune_replace_failure_preserves_output(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ token_aware: bool,
+ existing_output: bool,
+) -> None:
+ from soup_cli.utils import paths
+
+ monkeypatch.chdir(tmp_path)
+ source = Path("traces.jsonl")
+ destination = Path("pruned.jsonl")
+ original_input = (
+ b'{"prompt": "SYSTEM alpha", "output": "one"}\n'
+ b'{"prompt": "SYSTEM beta", "output": "two"}\n'
+ )
+ original_output = b"Previous successful output\n"
+ source.write_bytes(original_input)
+ if existing_output:
+ destination.write_bytes(original_output)
+
+ expected_files = {path.name for path in tmp_path.iterdir()}
+ replace_calls = []
+
+ def fail_replace(src, dst):
+ staged = Path(src)
+ replace_calls.append((staged, Path(dst)))
+ assert staged.resolve() != destination.resolve()
+ assert staged.parent.resolve() == destination.parent.resolve()
+ rows = [
+ json.loads(line)
+ for line in staged.read_text(encoding="utf-8").splitlines()
+ ]
+ assert rows == [
+ {"prompt": "alpha", "output": "one"},
+ {"prompt": "beta", "output": "two"},
+ ]
+ assert Path(dst).resolve() == destination.resolve()
+ raise OSError("Simulated output replacement failure")
+
+ with monkeypatch.context() as patch:
+ patch.setattr(paths.os, "replace", fail_replace)
+ with pytest.raises(
+ OSError,
+ match="Simulated output replacement failure",
+ ):
+ prune_traces(
+ str(source),
+ output_path=str(destination),
+ min_frequency=1.0,
+ tokenizer=CharacterTokenizer() if token_aware else None,
+ )
+
+ assert len(replace_calls) == 1
+ assert source.read_bytes() == original_input
+ if existing_output:
+ assert destination.read_bytes() == original_output
+ else:
+ assert not destination.exists()
+ assert {path.name for path in tmp_path.iterdir()} == expected_files
diff --git a/tests/test_ra_dit_input_safety.py b/tests/test_ra_dit_input_safety.py
new file mode 100644
index 00000000..0584170b
--- /dev/null
+++ b/tests/test_ra_dit_input_safety.py
@@ -0,0 +1,77 @@
+from pathlib import Path
+
+import pytest
+import yaml
+
+from soup_cli.utils.ra_dit_run import run_ra_dit
+
+
+ "fail_generator",
+ [False, True],
+ ids=["success", "generator-failure"],
+)
+def test_ra_dit_preserves_input_configs(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ fail_generator: bool,
+) -> None:
+ monkeypatch.chdir(tmp_path)
+ retriever = Path("retriever.yaml")
+ generator = Path("generator.yaml")
+
+ retriever.write_bytes(
+ b"# Original retriever config\n"
+ b"output: ./out/retriever\n"
+ b"training:\n"
+ b" ra_dit_stage: retriever\n"
+ )
+ generator.write_bytes(
+ b"# Original generator config\n"
+ b"output: ./out/generator\n"
+ b"training:\n"
+ b" ra_dit_stage: generator\n"
+ )
+ original_retriever = retriever.read_bytes()
+ original_generator = generator.read_bytes()
+ calls: list[Path] = []
+
+ def fake_runner(config_path: str) -> None:
+ path = Path(config_path)
+ calls.append(path)
+ if len(calls) == 1:
+ assert path.resolve() == retriever.resolve()
+ return
+
+ assert path.resolve() != generator.resolve()
+ assert path.resolve() != retriever.resolve()
+ config = yaml.safe_load(path.read_text(encoding="utf-8"))
+ assert (
+ config["training"]["ra_dit_retriever_model"]
+ == "./out/retriever"
+ )
+ if fail_generator:
+ raise RuntimeError("Simulated generator failure")
+
+ try:
+ if fail_generator:
+ with pytest.raises(RuntimeError, match="Simulated generator failure"):
+ run_ra_dit(
+ str(retriever),
+ str(generator),
+ _runner=fake_runner,
+ )
+ else:
+ result = run_ra_dit(
+ str(retriever),
+ str(generator),
+ _runner=fake_runner,
+ )
+ assert result.autolinked is True
+ finally:
+ assert retriever.read_bytes() == original_retriever
+ assert generator.read_bytes() == original_generator
+
+ assert len(calls) == 2
+ assert not calls[1].exists()
+ assert not calls[1].parent.exists()
diff --git a/tests/test_ra_dit_output_safety.py b/tests/test_ra_dit_output_safety.py
new file mode 100644
index 00000000..f381f179
--- /dev/null
+++ b/tests/test_ra_dit_output_safety.py
@@ -0,0 +1,380 @@
+from pathlib import Path
+
+import pytest
+import yaml
+
+from soup_cli.utils.paths import ensure_distinct_paths
+from soup_cli.utils.ra_dit_run import run_ra_dit
+from tests.conftest import strip_ansi
+
+
+def write_config(
+ path: Path,
+ output: str,
+ stage: str,
+ experiment_name: str | None = None,
+) -> None:
+ config = {
+ "output": output,
+ "training": {"ra_dit_stage": stage},
+ }
+ if experiment_name is not None:
+ config["experiment_name"] = experiment_name
+ path.write_text(yaml.safe_dump(config), encoding="utf-8")
+
+
+ ("retriever_output", "generator_output"),
+ [
+ ("./output", "./output"),
+ ("output", "./output"),
+ ("output", "unused/../output"),
+ ("output", "output/generator"),
+ ("output/retriever", "output"),
+ ],
+ ids=["equal", "dot-alias", "dotdot-alias", "generator-child", "retriever-child"],
+)
+def test_ra_dit_rejects_overlapping_outputs_before_training(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ retriever_output: str,
+ generator_output: str,
+) -> None:
+ monkeypatch.chdir(tmp_path)
+ Path("unused").mkdir()
+ retriever = Path("retriever.yaml")
+ generator = Path("generator.yaml")
+ write_config(retriever, retriever_output, "retriever")
+ write_config(generator, generator_output, "generator")
+
+ original = {
+ path.name: path.read_bytes()
+ for path in (retriever, generator)
+ }
+ calls = []
+
+ def fake_runner(config_path: str) -> None:
+ calls.append(config_path)
+
+ try:
+ with pytest.raises(ValueError) as error:
+ run_ra_dit(
+ str(retriever),
+ str(generator),
+ _runner=fake_runner,
+ )
+ message = str(error.value)
+ assert "--retriever-config" in message
+ assert "--generator-config" in message
+ finally:
+ assert calls == [], "Training started before rejecting overlapping outputs"
+ assert {
+ path.name: path.read_bytes()
+ for path in (retriever, generator)
+ } == original
+ assert not Path("output").exists()
+
+
+def test_ra_dit_compares_effective_experiment_outputs(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.chdir(tmp_path)
+ write_config(Path("retriever.yaml"), "./output", "retriever", "r1")
+ write_config(Path("generator.yaml"), "./output/r1", "generator")
+ calls = []
+
+ try:
+ with pytest.raises(ValueError):
+ run_ra_dit(
+ "retriever.yaml",
+ "generator.yaml",
+ _runner=calls.append,
+ )
+ finally:
+ assert calls == [], "Training started despite effective output collision"
+
+
+def test_ra_dit_links_effective_retriever_output(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.chdir(tmp_path)
+ write_config(Path("retriever.yaml"), "./output", "retriever", "r1")
+ write_config(Path("generator.yaml"), "./output", "generator", "g1")
+ seen = []
+
+ def fake_runner(config_path: str) -> None:
+ config = yaml.safe_load(
+ Path(config_path).read_text(encoding="utf-8")
+ )
+ seen.append(config)
+
+ result = run_ra_dit(
+ "retriever.yaml",
+ "generator.yaml",
+ _runner=fake_runner,
+ )
+
+ expected_retriever = (tmp_path / "output" / "r1").resolve()
+ expected_generator = (tmp_path / "output" / "g1").resolve()
+
+ assert len(seen) == 2
+ assert Path(result.retriever_output).resolve() == expected_retriever
+ assert Path(result.generator_output).resolve() == expected_generator
+ assert Path(result.retriever_model_used).resolve() == expected_retriever
+ assert (
+ Path(seen[1]["training"]["ra_dit_retriever_model"]).resolve()
+ == expected_retriever
+ )
+ assert result.autolinked is True
+
+ ("first", "second"),
+ [
+ ("models", "models"),
+ ("models", "./models"),
+ ("models", "models/generator"),
+ ("models/retriever", "models"),
+ ],
+ ids=["equal", "alias", "child", "parent"],
+)
+def test_directory_guard_rejects_overlap(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ first: str,
+ second: str,
+) -> None:
+ monkeypatch.chdir(tmp_path)
+
+ with pytest.raises(ValueError) as error:
+ ensure_distinct_paths(
+ [("--retriever-config output", first)],
+ [("--generator-config output", second)],
+ reject_nested=True,
+ )
+
+ assert "--retriever-config" in str(error.value)
+ assert "--generator-config" in str(error.value)
+ assert list(tmp_path.iterdir()) == []
+
+
+ ("first", "second"),
+ [
+ ("models/r1", "models/g1"),
+ ("models", "models-other"),
+ ("retriever", "generator"),
+ ],
+ ids=["siblings", "shared-string-prefix", "separate"],
+)
+def test_directory_guard_allows_separate_outputs(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ first: str,
+ second: str,
+) -> None:
+ monkeypatch.chdir(tmp_path)
+
+ ensure_distinct_paths(
+ [("--retriever-config output", first)],
+ [("--generator-config output", second)],
+ reject_nested=True,
+ )
+
+ assert list(tmp_path.iterdir()) == []
+
+
+def test_directory_guard_is_opt_in(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.chdir(tmp_path)
+
+ ensure_distinct_paths(
+ [("--input", "models")],
+ [("--output", "models/result.jsonl")],
+ )
+
+ assert list(tmp_path.iterdir()) == []
+
[email protected]("plan_only", [False, True], ids=["live", "plan"])
+ ("retriever_output", "generator_output"),
+ [
+ ("output", "./output"),
+ ("output", "output/generator"),
+ ("output/retriever", "output"),
+ ],
+ ids=["equal", "generator-child", "retriever-child"],
+)
+def test_cli_rejects_overlapping_outputs(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ plan_only: bool,
+ retriever_output: str,
+ generator_output: str,
+) -> None:
+ from typer.testing import CliRunner
+
+ from soup_cli.commands.ra_dit import app
+ from soup_cli.utils import ra_dit_run
+
+ monkeypatch.chdir(tmp_path)
+ write_config(Path("retriever.yaml"), retriever_output, "retriever")
+ write_config(Path("generator.yaml"), generator_output, "generator")
+ calls = []
+
+ def forbidden_train(*args, **kwargs):
+ calls.append((args, kwargs))
+ raise AssertionError("Training must not start")
+
+ monkeypatch.setattr(
+ ra_dit_run, "_run_train_subprocess", forbidden_train
+ )
+
+ args = [
+ "--retriever-config", "retriever.yaml",
+ "--generator-config", "generator.yaml",
+ ]
+ if plan_only:
+ args.append("--plan-only")
+
+ result = CliRunner().invoke(app, args)
+ message = " ".join(strip_ansi(result.output).split())
+
+ assert result.exit_code == 2, (result.output, result.exception)
+ assert "--retriever-config" in message
+ assert "--generator-config" in message
+ assert calls == []
+ assert not Path("output").exists()
+
+
+def test_plan_previews_effective_output_without_registry_or_training(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from typer.testing import CliRunner
+
+ from soup_cli.commands.ra_dit import app
+ from soup_cli.utils import ra_dit_run
+
+ monkeypatch.chdir(tmp_path)
+ write_config(Path("retriever.yaml"), "output", "retriever", "r1")
+ write_config(Path("generator.yaml"), "output", "generator", "g1")
+ calls = []
+
+ def forbidden_call(*args, **kwargs):
+ calls.append((args, kwargs))
+ raise AssertionError("Plan must not access Registry or start training")
+
+ monkeypatch.setattr(
+ ra_dit_run, "_run_train_subprocess", forbidden_call
+ )
+ monkeypatch.setattr(
+ ra_dit_run, "resolve_retriever_for_generator", forbidden_call
+ )
+
+ result = CliRunner().invoke(
+ app,
+ [
+ "--retriever-config", "retriever.yaml",
+ "--generator-config", "generator.yaml",
+ "--plan-only",
+ ],
+ )
+
+ assert result.exit_code == 0, (result.output, result.exception)
+ assert str(Path("output") / "r1") in strip_ansi(result.output)
+ assert str(Path("output") / "g1") in strip_ansi(result.output)
+ assert "auto-link to stage-1 output" in strip_ansi(result.output)
+ assert calls == []
+ assert not Path("output").exists()
+
[email protected]("plan_only", [False, True], ids=["live", "plan"])
+ "retriever_output,retriever_experiment,generator_output,generator_experiment",
+ [
+ ("output", "r1", "output/r1", None),
+ ("output", "r1", "output/r1", "g1"),
+ ("output/r1", "child", "output", "r1"),
+ ("output", "r1", "OUTPUT", "R1"),
+ ],
+ ids=[
+ "effective-equal",
+ "effective-generator-child",
+ "effective-retriever-child",
+ "windows-case",
+ ],
+)
+def test_cli_rejects_effective_output_overlap_without_writes(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ plan_only: bool,
+ retriever_output: str,
+ retriever_experiment: str,
+ generator_output: str,
+ generator_experiment: str | None,
+) -> None:
+ import os
+
+ from typer.testing import CliRunner
+
+ from soup_cli.commands.ra_dit import app
+ from soup_cli.utils import ra_dit_run
+
+ monkeypatch.chdir(tmp_path)
+ if generator_output == "OUTPUT":
+ if os.name != "nt":
+ pytest.skip("Windows case-alias test")
+ Path("output").mkdir()
+ if not os.path.exists("OUTPUT") or not os.path.samefile("output", "OUTPUT"):
+ pytest.skip("Working directory is case-sensitive")
+
+ for filename, output, stage, experiment in [
+ ("retriever.yaml", retriever_output, "retriever", retriever_experiment),
+ ("generator.yaml", generator_output, "generator", generator_experiment),
+ ]:
+ config = {
+ "output": output,
+ "training": {"ra_dit_stage": stage},
+ }
+ if experiment is not None:
+ config["experiment_name"] = experiment
+ Path(filename).write_text(yaml.safe_dump(config), encoding="utf-8")
+
+ calls = []
+
+ def forbidden_training(*args, **kwargs):
+ calls.append((args, kwargs))
+ pytest.fail("Training started before rejecting effective output overlap")
+
+ monkeypatch.setattr(ra_dit_run, "_run_train_subprocess", forbidden_training)
+
+ def snapshot() -> dict[str, bytes | None]:
+ return {
+ path.relative_to(tmp_path).as_posix(): (
+ path.read_bytes() if path.is_file() else None
+ )
+ for path in tmp_path.rglob("*")
+ }
+
+ before = snapshot()
+ arguments = [
+ "--retriever-config",
+ "retriever.yaml",
+ "--generator-config",
+ "generator.yaml",
+ ]
+ if plan_only:
+ arguments.append("--plan-only")
+
+ result = CliRunner().invoke(app, arguments)
+ message = " ".join(strip_ansi(result.output).split())
+
+ assert snapshot() == before
+ assert calls == []
+ assert result.exit_code == 2, (result.output, repr(result.exception))
+ assert "--retriever-config" in message
+ assert "--generator-config" in message
+ assert "same file" in message or "overlaps" in message
diff --git a/tests/test_trace_output_aliases.py b/tests/test_trace_output_aliases.py
new file mode 100644
index 00000000..9081a269
--- /dev/null
+++ b/tests/test_trace_output_aliases.py
@@ -0,0 +1,92 @@
+import os
+from pathlib import Path
+
+import pytest
+from typer.testing import CliRunner
+
+from soup_cli.cli import app
+from tests.conftest import strip_ansi
+
+
[email protected]("command", ["ingest", "prune-prompt"])
+ "alias_kind",
+ [
+ pytest.param("hardlink", marks=pytest.mark.requires_hardlink),
+ "windows-case",
+ "dotdot",
+ ],
+)
+def test_trace_command_rejects_input_alias_without_writes(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ command: str,
+ alias_kind: str,
+) -> None:
+ monkeypatch.chdir(tmp_path)
+ source = Path("traces.jsonl")
+ if command == "ingest":
+ original = b'{"id":"t1","input":"hi","output":"hello"}\n'
+ else:
+ original = (
+ b'{"prompt":"SYSTEM alpha","output":"one"}\n'
+ b'{"prompt":"SYSTEM beta","output":"two"}\n'
+ )
+ source.write_bytes(original)
+
+ if alias_kind == "hardlink":
+ linked = Path("linked-traces.jsonl")
+ linked.hardlink_to(source)
+ alias = str(linked)
+ elif alias_kind == "windows-case":
+ if os.name != "nt":
+ pytest.skip("Windows case-alias test")
+ alias = "TRACES.JSONL"
+ if not os.path.exists(alias) or not os.path.samefile(source, alias):
+ pytest.skip("Working directory is case-sensitive")
+ else:
+ Path("unused").mkdir()
+ alias = str(Path("unused") / ".." / source.name)
+
+ before_files = {
+ path.name: path.read_bytes()
+ for path in tmp_path.iterdir()
+ if path.is_file()
+ }
+ before_entries = {path.name for path in tmp_path.iterdir()}
+
+ if command == "ingest":
+ arguments = [
+ "ingest",
+ "--source",
+ "langfuse",
+ "--logs",
+ str(source),
+ "--output",
+ alias,
+ ]
+ input_option = "--logs"
+ else:
+ arguments = [
+ "prune-prompt",
+ "--input",
+ str(source),
+ "--output",
+ alias,
+ ]
+ input_option = "--input"
+
+ result = CliRunner().invoke(app, arguments)
+ message = " ".join(strip_ansi(result.output).split())
+
+ after_files = {
+ path.name: path.read_bytes()
+ for path in tmp_path.iterdir()
+ if path.is_file()
+ }
+ assert after_files == before_files
+ assert {path.name for path in tmp_path.iterdir()} == before_entries
+ assert result.exit_code == 1, (result.output, repr(result.exception))
+ assert input_option in message
+ assert "--output" in message
+ assert "same file" in message