Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.
Python cliconsumer-gpudpofine-tuningggufhuggingfacellmllmopslocal-ailocal-llmloralow-vrammachine-learningollamapeftpythonpytorchqlorasfttransformers
config: read soup.yaml with the same YAML limits as can manifests (#1827)
Alpamys Makazhan1d29d0fc7c5c
diff --git a/changelog.d/0.76.0/1827.changed.md b/changelog.d/0.76.0/1827.changed.mdnew file mode 100644index 00000000..34b59972--- /dev/null+++ b/changelog.d/0.76.0/1827.changed.md@@ -0,0 +1 @@+- soup.yaml and every other YAML file Soup reads are loaded under one set of limits (1 MiB, 100 levels of nesting, one node per byte plus 10,000 for anchors, aliases and merge keys; `soup ship`: 4 MiB); a file over a limit or one that cannot be read is refused with one line naming the file and the problem (#1827).diff --git a/docs/backends-and-ops.md b/docs/backends-and-ops.mdindex 7e690d10..983327a5 100644--- a/docs/backends-and-ops.md+++ b/docs/backends-and-ops.md@@ -665,6 +665,10 @@ a scripted or CI-driven sweep fails rather than reporting a grid of arms that eafor the same reason. A sweep whose swept knob is never applied produces arms that are allidentical, so there is no partially-useful result to preserve by continuing.+**Size limits.** A config file may be at most 1 MiB, nest mappings and lists at most 100 levels,+and expand through anchors, aliases and `<<` merge keys to at most one node per byte plus 10,000.+A file over a limit is refused with a message naming the file and the limit (`soup ship`: 4 MiB).+## Experiment Trackingdiff --git a/src/soup_cli/cans/unpack.py b/src/soup_cli/cans/unpack.pyindex c71b5717..6f894337 100644--- a/src/soup_cli/cans/unpack.py+++ b/src/soup_cli/cans/unpack.py@@ -7,18 +7,14 @@ import tarfilefrom pathlib import Pathfrom typing import Any-import yaml-from soup_cli.cans.schema import Manifestfrom soup_cli.utils.paths import is_under_cwd-from soup_cli.utils.yaml_limits import check_yaml_expanded_size+from soup_cli.utils.yaml_limits import MAX_CONFIG_BYTES, load_yaml_limited#: Largest ``manifest.yaml`` read into memory. A manifest holds a handful of#: short fields plus at most 64 attestations of <= 1 MiB each, so a real one is#: far below this.MAX_MANIFEST_BYTES = 16 * 1024 * 1024-#: Largest ``config.yaml`` read into memory; a training config is kilobytes.-MAX_CONFIG_BYTES = 1 * 1024 * 1024#: Most members ``extract_can`` will write. ``soup can pack`` writes four.MAX_EXTRACT_MEMBERS = 10_000#: Largest total declared size of the regular files ``extract_can`` writes.@@ -33,8 +29,8 @@ MAX_EXTRACT_BYTES = 8 * 1024 * 1024 * 1024def _read_text_member(tar: tarfile.TarFile, name: str, max_bytes: int,-) -> tuple[str, int]:- """Return ``(text, byte_length)`` of a regular UTF-8 member, size-capped."""+) -> str:+ """Return the text of a regular UTF-8 member, size-capped."""try:member = tar.getmember(name)except KeyError as exc:@@ -56,7 +52,7 @@ def _read_text_member(f"member '{name}' in can is too large (> {max_bytes} bytes)")try:- return raw.decode("utf-8"), len(raw)+ return raw.decode("utf-8")except UnicodeDecodeError as exc:raise ValueError(f"member '{name}' in can is not valid UTF-8: {exc}") from exc@@ -73,11 +69,10 @@ def inspect_can(path: str) -> Manifest:if not can_path.exists():raise FileNotFoundError(f"can not found: {path}")with tarfile.open(can_path, mode="r:gz") as tar:- manifest_text, manifest_bytes = _read_text_member(- tar, "manifest.yaml", MAX_MANIFEST_BYTES,- )- data = yaml.safe_load(manifest_text) or {}- check_yaml_expanded_size(data, "manifest.yaml", source_bytes=manifest_bytes)+ manifest_text = _read_text_member(tar, "manifest.yaml", MAX_MANIFEST_BYTES)+ data = load_yaml_limited(+ manifest_text, "manifest.yaml", max_bytes=MAX_MANIFEST_BYTES,+ ) or {}return Manifest(**data)@@ -89,9 +84,8 @@ def read_config(path: str) -> dict[str, Any]:if not can_path.exists():raise FileNotFoundError(f"can not found: {path}")with tarfile.open(can_path, mode="r:gz") as tar:- cfg_text, cfg_bytes = _read_text_member(tar, "config.yaml", MAX_CONFIG_BYTES)- data = yaml.safe_load(cfg_text) or {}- check_yaml_expanded_size(data, "config.yaml", source_bytes=cfg_bytes)+ cfg_text = _read_text_member(tar, "config.yaml", MAX_CONFIG_BYTES)+ data = load_yaml_limited(cfg_text, "config.yaml", max_bytes=MAX_CONFIG_BYTES) or {}if not isinstance(data, dict):raise ValueError("config.yaml must deserialise to a mapping")return datadiff --git a/src/soup_cli/cli.py b/src/soup_cli/cli.pyindex bed388c3..bec0fe8e 100644--- a/src/soup_cli/cli.py+++ b/src/soup_cli/cli.py@@ -828,15 +828,17 @@ def _mask_audit_args(command: str, args: list[str]) -> tuple[str, ...]:something else elsewhere. If the command does not resolve to a leaf,every credential option string of the app is masked. A resolutionfailure falls back to that widest set, never to the unmasked args.+ Whatever the tree yields, a long option whose name looks like a+ credential is masked by that name as well."""global _ALL_SECRET_OPTION_STRINGS- import click-from soup_cli.utils.argv_redaction import (+ all_long_option_strings,all_secret_option_strings,mask_secret_args,resolve_command,secret_option_strings,+ subcommands,)root = typer.main.get_command(app)@@ -845,14 +847,14 @@ def _mask_audit_args(command: str, args: list[str]) -> tuple[str, ...]:everything = _ALL_SECRET_OPTION_STRINGStry:resolved = resolve_command(root, [command, *args])- if isinstance(resolved, click.Group):+ if subcommands(resolved) is not None:secret_opts = everythingelse:app_wide_longs = frozenset(o for o in everything if o.startswith("--"))secret_opts = secret_option_strings(resolved) | app_wide_longsexcept Exception: # noqa: BLE001 — fall back to the widest masksecret_opts = everything- return mask_secret_args(args, secret_opts)+ return mask_secret_args(args, secret_opts, all_long_option_strings(root))def _emit_audit_event(argv: list[str], exit_code: int) -> None:diff --git a/src/soup_cli/commands/adapters.py b/src/soup_cli/commands/adapters.pyindex 23661e82..f65ec881 100644--- a/src/soup_cli/commands/adapters.py+++ b/src/soup_cli/commands/adapters.py@@ -1800,6 +1800,7 @@ def audit(# The schema is the single source of defaults; the audit module stays pure.try:from soup_cli.config.loader import load_config_from_string+ from soup_cli.utils.yaml_limits import MAX_CONFIG_BYTES, read_text_limited# The loader reports unknown keys through its own module-level Console,# which writes to STDOUT -- so `--json` emitted four lines of warning@@ -1807,12 +1808,20 @@ def audit(# A diagnostic about the config is not this command's output; stderr# is where it belongs, and it stays just as visible there.with contextlib.redirect_stdout(sys.stderr):- soup_config = load_config_from_string(config_path.read_text())+ soup_config = load_config_from_string(+ read_text_limited(+ config_path, f"Config file {config}", max_bytes=MAX_CONFIG_BYTES+ )+ )except yaml.YAMLError as exc:- console.print(f"[red]Could not parse {config}: {exc}[/]")+ console.print(+ f"[red]Could not parse {for_terminal(config)}: {for_terminal(str(exc))}[/]"+ )raise typer.Exit(1) from excexcept (SystemExit, Exception) as exc: # schema rejection prints its own- console.print(f"[red]Could not load {config}: {exc}[/]")+ console.print(+ f"[red]Could not load {for_terminal(config)}: {for_terminal(str(exc))}[/]"+ )raise typer.Exit(1) from exccfg = soup_config.model_dump()@@ -1941,4 +1950,3 @@ def check_cmd(raise typer.Exit(0)else:raise typer.Exit(2)-diff --git a/src/soup_cli/commands/deploy.py b/src/soup_cli/commands/deploy.pyindex 505c5f61..36df09f9 100644--- a/src/soup_cli/commands/deploy.py+++ b/src/soup_cli/commands/deploy.py@@ -727,15 +727,22 @@ def _auto_detect_template() -> Optional[str]:try:import yaml- with open(config_path, encoding="utf-8") as fh:- config = yaml.safe_load(fh)+ from soup_cli.utils.yaml_limits import (+ MAX_CONFIG_BYTES,+ YamlLimitError,+ load_yaml_file_limited,+ )++ config = load_yaml_file_limited(+ config_path, "soup.yaml", max_bytes=MAX_CONFIG_BYTES+ )if not isinstance(config, dict):return Nonedata_section = config.get("data", {})if isinstance(data_section, dict):fmt = data_section.get("format")return infer_chat_template(fmt)- except (yaml.YAMLError, OSError, KeyError, ImportError):+ except (yaml.YAMLError, YamlLimitError, OSError, KeyError, ImportError):return Nonereturn Nonediff --git a/src/soup_cli/commands/eval.py b/src/soup_cli/commands/eval.pyindex c51ba805..efcfbb77 100644--- a/src/soup_cli/commands/eval.py+++ b/src/soup_cli/commands/eval.py@@ -551,7 +551,8 @@ def judge(try:rubric_data = load_rubric(Path(rubric))except (FileNotFoundError, ValueError) as exc:- console.print(f"[red]{exc}[/]")+ # The message quotes the path it was given.+ console.print(f"[red]{for_terminal(str(exc))}[/]")raise typer.Exit(1)console.print(@@ -1270,7 +1271,7 @@ def gate_cmd(try:eval_suite = load_suite(suite)except (FileNotFoundError, ValueError) as exc:- console.print(f"[red]Cannot load suite:[/] {exc}")+ console.print(f"[red]Cannot load suite:[/] {for_terminal(str(exc))}")raise typer.Exit(EXIT_USAGE_ERROR) from exctry:diff --git a/src/soup_cli/commands/export.py b/src/soup_cli/commands/export.pyindex ef432474..2e37a46d 100644--- a/src/soup_cli/commands/export.py+++ b/src/soup_cli/commands/export.py@@ -1546,7 +1546,7 @@ def _export_torchao_cli(try:cfg_data = load_quant_config(quant_config)except (TypeError, ValueError, FileNotFoundError) as exc:- console.print(f"[red]{exc}[/]")+ console.print(f"[red]{for_terminal(str(exc))}[/]")raise typer.Exit(2)scheme_raw = cfg_data.get("scheme")diff --git a/src/soup_cli/commands/plan.py b/src/soup_cli/commands/plan.pyindex 785fc14e..58dc015b 100644--- a/src/soup_cli/commands/plan.py+++ b/src/soup_cli/commands/plan.py@@ -9,7 +9,6 @@ from __future__ import annotationsimport datetime as _dtimport typer-import yamlfrom rich.console import Consolefrom rich.markup import escapefrom rich.panel import Panel@@ -22,6 +21,7 @@ from soup_cli.utils.terraform_plan import (build_plan,write_state,)+from soup_cli.utils.yaml_limits import MAX_CONFIG_BYTES, load_yaml_file_limitedconsole = Console()@@ -42,8 +42,7 @@ def _load_yaml_config(path: str) -> dict:st = os.lstat(path)if _stat.S_ISLNK(st.st_mode):raise ValueError("config path must not be a symlink")- with open(path, encoding="utf-8") as fh:- data = yaml.safe_load(fh)+ data = load_yaml_file_limited(path, f"config {path!r}", max_bytes=MAX_CONFIG_BYTES)if not isinstance(data, dict):raise ValueError("config must parse to a dict")from soup_cli.config.unknown_keys import find_unknown_config_keys, format_unknown_keysdiff --git a/src/soup_cli/commands/push.py b/src/soup_cli/commands/push.pyindex 99743591..1d2eaa4b 100644--- a/src/soup_cli/commands/push.py+++ b/src/soup_cli/commands/push.py@@ -380,12 +380,17 @@ def _load_training_config(model_path: Path) -> dict:import yamlexcept ImportError:return {}+ from soup_cli.utils.yaml_limits import (+ MAX_CONFIG_BYTES,+ YamlLimitError,+ load_yaml_file_limited,+ )+try:- with open(path, encoding="utf-8") as fh:- data = yaml.safe_load(fh)+ data = load_yaml_file_limited(path, name, max_bytes=MAX_CONFIG_BYTES)if isinstance(data, dict):return data- except (yaml.YAMLError, OSError):+ except (yaml.YAMLError, YamlLimitError, OSError):continuereturn {}diff --git a/src/soup_cli/commands/recipes.py b/src/soup_cli/commands/recipes.pyindex 65f33ea0..572e7bd4 100644--- a/src/soup_cli/commands/recipes.py+++ b/src/soup_cli/commands/recipes.py@@ -245,6 +245,7 @@ def _configs_to_verify(config: Optional[str], templates: bool):parse is surfaced here rather than counted as an attach failure."""from soup_cli.config.loader import load_config_from_stringfrom soup_cli.utils.exit_codes import EXIT_USAGE_ERROR+ from soup_cli.utils.yaml_limits import MAX_CONFIG_BYTES, read_text_limitedpairs: list[tuple[str, str]] = []if config:@@ -253,7 +254,10 @@ def _configs_to_verify(config: Optional[str], templates: bool):err_console.print(f"[red]Config not found:[/] {for_terminal(config)}")raise typer.Exit(EXIT_USAGE_ERROR)try:- return [(path.name, load_config_from_string(path.read_text(encoding="utf-8")))]+ text = read_text_limited(+ path, f"Config file {config}", max_bytes=MAX_CONFIG_BYTES+ )+ return [(path.name, load_config_from_string(text))]except Exception as exc: # noqa: BLE001 --- any parse failure is an input errorfirst_line = str(exc).splitlines()[0] if str(exc) else ""err_console.print(diff --git a/src/soup_cli/commands/ship.py b/src/soup_cli/commands/ship.pyindex 3eae02b5..50a03c61 100644--- a/src/soup_cli/commands/ship.py+++ b/src/soup_cli/commands/ship.py@@ -271,7 +271,7 @@ def _parse_ship_config(path: str) -> "Tuple[SoupConfig, Optional[ShipConfig]]":try:text = _safe_read_text(path, "--config path", _MAX_CONFIG_BYTES)- cfg = load_config_from_string(text)+ cfg = load_config_from_string(text, max_bytes=_MAX_CONFIG_BYTES)except (ValueError, TypeError, yaml.YAMLError) as exc:_fail(f"--config: {exc}", _EXIT_USAGE)ship_cfg = cfg.eval.ship if cfg.eval is not None else Nonediff --git a/src/soup_cli/commands/train.py b/src/soup_cli/commands/train.pyindex b1b69040..52caddbb 100644--- a/src/soup_cli/commands/train.py+++ b/src/soup_cli/commands/train.py@@ -871,9 +871,11 @@ def train(console.print(f"[red]Invalid distributed launch:[/] {markup_escape(message)}")raise typer.Exit(1) from exc+ from soup_cli.utils.terminal import for_terminal+config_path = Path(config)if not config_path.exists():- console.print(f"[red]Config not found: {config_path}[/]")+ console.print(f"[red]Config not found: {for_terminal(config_path)}[/]")console.print("Run [bold]soup init[/] to create one.")raise typer.Exit(1)@@ -904,7 +906,8 @@ def train(config_path, schedule, trust_remote_code=trust_remote_code,)except (SweepTooShortError, LrSweepUnavailableError) as exc:- console.print(f"[red]{markup_escape(str(exc))}[/]")+ # The refusal can quote the config path and text from the file.+ console.print(f"[red]{for_terminal(str(exc))}[/]")raise typer.Exit(1) from exctry:save_lr_finder_report(lrs, losses_for_report, find_lr_output)@@ -915,7 +918,7 @@ def train(raise typer.Exit(0)# Load & validate config- console.print(f"[dim]Loading config from {config_path}...[/]")+ console.print(f"[dim]Loading config from {for_terminal(config_path)}...[/]")cfg = load_config(config_path,training_overrides=(@@ -1141,7 +1144,7 @@ def train(# Validate the suite path up-front (path containment + parse).load_suite(gate)except (FileNotFoundError, ValueError) as exc:- console.print(f"[red]Invalid --gate suite: {exc}[/]")+ console.print(f"[red]Invalid --gate suite: {for_terminal(str(exc))}[/]")raise typer.Exit(1) from exccfg.training.eval_gate = EvalGateConfig(enabled=True, suite=gate)console.print(f"[green]Eval gate enabled[/] with suite: {gate}")@@ -2599,7 +2602,9 @@ def _run_live_lr_sweep(from soup_cli.utils.lr_finder import LrSweepUnavailableError, SweepTooShortErrortry:- cfg = load_config(config_path)+ # The refusal below quotes the reason, so the loader hands it over+ # instead of printing its own line and exiting.+ cfg = load_config(config_path, raise_unreadable=True)except Exception as exc: # noqa: BLE001 — one refusal line, not a tracebackraise LrSweepUnavailableError(f"--find-lr: config load failed ({exc}); no LR report was written."diff --git a/src/soup_cli/config/loader.py b/src/soup_cli/config/loader.pyindex 360ad4e6..bb61d332 100644--- a/src/soup_cli/config/loader.py+++ b/src/soup_cli/config/loader.py@@ -12,6 +12,12 @@ from soup_cli.config.schema import SoupConfigfrom soup_cli.config.staged_fields import find_staged_config_fields, format_staged_fieldsfrom soup_cli.config.unknown_keys import find_unknown_config_keys, format_unknown_keysfrom soup_cli.utils.terminal import for_terminal+from soup_cli.utils.yaml_limits import (+ MAX_CONFIG_BYTES,+ YamlLimitError,+ load_yaml_file_limited,+ load_yaml_limited,+)console = Console()@@ -92,6 +98,64 @@ def _report_staged_fields(return None+#: Longest piece of text taken from the file that a refusal quotes.+_MAX_DETAIL_CHARS = 200+++def _refuse(message: str) -> None:+ """Print a one-line refusal and exit 1; the text may quote the file."""+ console.print(f"[red]{for_terminal(message)}[/]")+ raise SystemExit(1)+++def _clip(detail: str) -> str:+ """``detail`` on one line, cut to ``_MAX_DETAIL_CHARS`` with an ellipsis."""+ detail = " ".join(detail.split())+ if len(detail) <= _MAX_DETAIL_CHARS:+ return detail+ return detail[:_MAX_DETAIL_CHARS] + "..."+++def _read_config_file(path: Path, *, raise_unreadable: bool = False) -> object:+ """Load the YAML document at ``path``, or exit 1 naming what stopped it.++ A file over a limit, a directory, a file the OS will not let us read, bytes+ that are not UTF-8, a YAML syntax error and a value YAML cannot build (a+ date that does not exist) each get one line that names the file and the+ problem; text taken from the file is cut to ``_MAX_DETAIL_CHARS``. A+ missing file is left to the caller as ``FileNotFoundError``, and any other+ exception is passed on as itself.++ With ``raise_unreadable`` nothing is printed and nothing exits: the caller+ gets the exception itself (``YamlLimitError``, ``yaml.YAMLError``,+ ``UnicodeDecodeError``, ``OSError``) to report in its own words.+ """+ what = f"Config file {path}"+ if raise_unreadable:+ return load_yaml_file_limited(path, what, max_bytes=MAX_CONFIG_BYTES)+ if path.is_dir():+ _refuse(f"{what} is a directory, not a file")+ try:+ return load_yaml_file_limited(path, what, max_bytes=MAX_CONFIG_BYTES)+ except YamlLimitError as exc:+ _refuse(str(exc))+ except UnicodeDecodeError as exc:+ _refuse(f"{what} is not valid UTF-8: {exc.reason} at byte {exc.start}")+ except yaml.YAMLError as exc:+ mark = getattr(exc, "problem_mark", None)+ problem = getattr(exc, "problem", None)+ if mark is not None and problem:+ detail = f"{_clip(problem)} (line {mark.line + 1}, column {mark.column + 1})"+ else:+ detail = _clip(str(exc))+ _refuse(f"{what} is not valid YAML: {detail}")+ except FileNotFoundError:+ raise+ except OSError as exc:+ _refuse(f"{what} cannot be read: {exc.strerror or type(exc).__name__}")+ return None # pragma: no cover - _refuse always raises++def _build_config(raw: dict) -> SoupConfig:"""Construct ``SoupConfig``, printing each deprecated value once (#759).@@ -124,15 +188,24 @@ def load_config(path: "Path | str",*,training_overrides: dict | None = None,+ raise_unreadable: bool = False,) -> SoupConfig:"""Load a soup.yaml file and return validated SoupConfig.``training_overrides`` are merged into the YAML ``training:`` mapping*before* ``SoupConfig`` is constructed, so CLI flags that map ontotraining fields participate in the same cross-validators as YAML.++ The file is read under the limits of :mod:`soup_cli.utils.yaml_limits`+ (at most :data:`MAX_CONFIG_BYTES`, bounded nesting and alias expansion);+ a file over one of them exits 1 with a message naming the file and the+ limit, before anything walks the document. So does a file that cannot+ be read as YAML at all; see :func:`_read_config_file`. A caller that+ reports such a file in its own words passes ``raise_unreadable=True``+ and receives the exception instead; a config that reads but does not+ validate still exits 1 with the loader's message either way."""- path = Path(path)- raw = yaml.safe_load(path.read_text(encoding="utf-8"))+ raw = _read_config_file(Path(path), raise_unreadable=raise_unreadable)if raw is None:console.print("[red]Config file is empty[/]")@@ -176,13 +249,18 @@ def load_config(return config-def load_config_from_string(yaml_str: str) -> SoupConfig:+def load_config_from_string(yaml_str: str, *, max_bytes: "int | None" = None) -> SoupConfig:"""Parse a YAML string and return validated SoupConfig.Unlike load_config(), raises ValueError on errors instead of SystemExit,- making it suitable for API/UI usage.+ making it suitable for API/UI usage. The text is held to the same limits+ as a config file; crossing one raises+ :class:`~soup_cli.utils.yaml_limits.YamlLimitError`, a ``ValueError``.+ ``max_bytes`` replaces :data:`MAX_CONFIG_BYTES` for a caller that+ documents a size limit of its own."""- raw = yaml.safe_load(yaml_str)+ limit = MAX_CONFIG_BYTES if max_bytes is None else max_bytes+ raw = load_yaml_limited(yaml_str, "Config", max_bytes=limit)if raw is None:raise ValueError("Config is empty")if not isinstance(raw, dict):diff --git a/src/soup_cli/eval/gate.py b/src/soup_cli/eval/gate.pyindex ec1056a5..250eef87 100644--- a/src/soup_cli/eval/gate.py+++ b/src/soup_cli/eval/gate.py@@ -15,12 +15,12 @@ from pathlib import Pathfrom typing import Callable, Literal, Mapping, Optionalfrom urllib.parse import urlparse-import yamlfrom pydantic import BaseModel, Field, field_validatorfrom soup_cli import __version__from soup_cli.eval.results import newest_eval_rowsfrom soup_cli.utils.paths import atomic_write_text, is_under_cwd+from soup_cli.utils.yaml_limits import MAX_CONFIG_BYTES, load_yaml_file_limitedlogger = logging.getLogger(__name__)@@ -139,7 +139,9 @@ def load_suite(path: str) -> EvalSuite:)if not suite_path.exists():raise FileNotFoundError(f"eval-gate suite not found: {path}")- data = yaml.safe_load(suite_path.read_text(encoding="utf-8")) or {}+ data = load_yaml_file_limited(+ suite_path, f"eval-gate suite '{path}'", max_bytes=MAX_CONFIG_BYTES+ ) or {}suite = EvalSuite(**data)_require_gate_tasks(suite)return suitediff --git a/src/soup_cli/eval/judge.py b/src/soup_cli/eval/judge.pyindex 8118ee4b..eec806b5 100644--- a/src/soup_cli/eval/judge.py+++ b/src/soup_cli/eval/judge.py@@ -172,13 +172,14 @@ class JudgeResults:def load_rubric(path: Path) -> dict:"""Load a rubric YAML file with validation."""- import yaml+ from soup_cli.utils.yaml_limits import MAX_CONFIG_BYTES, load_yaml_file_limitedif not path.exists():raise FileNotFoundError(f"Rubric file not found: {path}")- with open(path, encoding="utf-8") as fh:- rubric = yaml.safe_load(fh)+ rubric = load_yaml_file_limited(+ path, f"Rubric file {path}", max_bytes=MAX_CONFIG_BYTES+ )if not isinstance(rubric, dict):raise ValueError("Rubric must be a YAML mapping")diff --git a/src/soup_cli/migrate/axolotl.py b/src/soup_cli/migrate/axolotl.pyindex 9b43a7cd..2a4ce8cc 100644--- a/src/soup_cli/migrate/axolotl.py+++ b/src/soup_cli/migrate/axolotl.py@@ -3,10 +3,9 @@from pathlib import Pathfrom typing import Any, Dict, List-import yaml-from soup_cli.config.schema import SFT_KERNEL_AWARE_TASKSfrom soup_cli.migrate.common import to_number+from soup_cli.utils.yaml_limits import MAX_CONFIG_BYTES, load_yaml_file_limited# Axolotl rl → Soup task mapping_RL_MAP = {@@ -50,8 +49,9 @@ def migrate_axolotl(config_path: Path) -> Dict[str, Any]:Returns a dict suitable for config_to_yaml(). Includes a ``_warnings``key with a list of human-readable migration notes."""- raw_text = config_path.read_text(encoding="utf-8")- raw = yaml.safe_load(raw_text)+ raw = load_yaml_file_limited(+ config_path, f"Config file {config_path}", max_bytes=MAX_CONFIG_BYTES+ )if not raw or not isinstance(raw, dict):raise ValueError("Config file is empty or not a valid YAML mapping")diff --git a/src/soup_cli/migrate/llamafactory.py b/src/soup_cli/migrate/llamafactory.pyindex 15acfa44..96baa30f 100644--- a/src/soup_cli/migrate/llamafactory.py+++ b/src/soup_cli/migrate/llamafactory.py@@ -3,9 +3,8 @@from pathlib import Pathfrom typing import Any, Dict, List-import yaml-from soup_cli.migrate.common import to_number+from soup_cli.utils.yaml_limits import MAX_CONFIG_BYTES, load_yaml_file_limited# LLaMA-Factory stage → Soup task mapping_STAGE_MAP = {@@ -46,8 +45,9 @@ def migrate_llamafactory(config_path: Path) -> Dict[str, Any]:Returns a dict suitable for config_to_yaml(). Includes a ``_warnings``key with a list of human-readable migration notes."""- raw_text = config_path.read_text(encoding="utf-8")- raw = yaml.safe_load(raw_text)+ raw = load_yaml_file_limited(+ config_path, f"Config file {config_path}", max_bytes=MAX_CONFIG_BYTES+ )if not raw or not isinstance(raw, dict):raise ValueError("Config file is empty or not a valid YAML mapping")diff --git a/src/soup_cli/utils/agent_forge.py b/src/soup_cli/utils/agent_forge.pyindex ba323382..c1c69a68 100644--- a/src/soup_cli/utils/agent_forge.py+++ b/src/soup_cli/utils/agent_forge.py@@ -520,9 +520,9 @@ def load_spec_file(spec_path: str) -> Mapping[str, Any]:with open(real, "r", encoding="utf-8") as fh:text = fh.read()if spec_path.lower().endswith((".yaml", ".yml")):- import yaml+ from soup_cli.utils.yaml_limits import load_yaml_limited- loaded = yaml.safe_load(text)+ loaded = load_yaml_limited(text, "spec file", max_bytes=_MAX_SPEC_BYTES)else:loaded = json.loads(text)if not isinstance(loaded, dict):diff --git a/src/soup_cli/utils/argv_redaction.py b/src/soup_cli/utils/argv_redaction.pyindex 03a2ee1c..e6af0837 100644--- a/src/soup_cli/utils/argv_redaction.py+++ b/src/soup_cli/utils/argv_redaction.py@@ -7,17 +7,26 @@ value-pattern layer only recognises a few token shapes (``hf_*``, ``sk-*``,NAME instead: any value-taking option whose long name contains ``token``,``key``, ``secret``, ``password``, ``passwd`` or ``credential`` has its valuereplaced with ``<redacted>``, unless the name is listed in-``NOT_SECRET_OPTIONS``.+``NOT_SECRET_OPTIONS``, and any option listed in ``SECRET_OPTIONS``.-Stdlib + click only: importing this module must stay cheap for the CLI.+The command tree is read by attribute (``commands``, ``params``, ``opts``),+never by class: Typer builds it from whichever click it was installed with,+and that is not always the ``click`` package this module could import. The+tree supplies the options a command declares, short aliases included;+:func:`mask_secret_args` also applies the same name rule to every long option+typed on the command line, so an option the tree did not yield is masked by+its name all the same.++Stdlib only: importing this module must stay cheap for the CLI."""from __future__ import annotationsimport re-from typing import Iterable, Sequence+from typing import TYPE_CHECKING, Iterable, Sequence-import click+if TYPE_CHECKING:+ import clickREDACTED = "<redacted>"@@ -31,6 +40,7 @@ NOT_SECRET_OPTIONS: frozenset[str] = frozenset({"--max-tokens", # generation length (an integer)"--max-new-tokens", # generation length (an integer)+ "--min-tokens", # a length threshold (an integer)"--num-assistant-tokens", # speculative-decoding draft length (an integer)"--num-speculative-tokens", # speculative-decoding draft length (an integer)"--tokenizer", # tokenizer repo id or local path@@ -43,34 +53,56 @@ NOT_SECRET_OPTIONS: frozenset[str] = frozenset()-def _long_names(option: click.Option) -> list[str]:- return [o for o in (*option.opts, *option.secondary_opts) if o.startswith("--")]+# Long option names that carry a credential although their name does not say+# so: a webhook URL is all that is needed to post to the channel.+SECRET_OPTIONS: frozenset[str] = frozenset({"--slack-url", "--discord-url"})+++def is_secret_name(name: str) -> bool:+ """Whether the long option ``name`` (``--like-this``) holds a credential."""+ if name in NOT_SECRET_OPTIONS:+ return False+ return name in SECRET_OPTIONS or bool(SECRET_NAME_RE.search(name[2:]))+++def _long_names(param: object) -> list[str]:+ """The ``--name`` strings of a parameter; an argument has none."""+ declared = (+ *(getattr(param, "opts", None) or ()),+ *(getattr(param, "secondary_opts", None) or ()),+ )+ return [o for o in declared if o.startswith("--")]-def _is_secret_option(option: click.Option) -> bool:- if option.is_flag or option.count:+def _is_secret_option(option: object) -> bool:+ if getattr(option, "is_flag", False) or getattr(option, "count", False):return Falselongs = _long_names(option)- if not any(SECRET_NAME_RE.search(name[2:]) for name in longs):+ if any(name in NOT_SECRET_OPTIONS for name in longs):return False- return not any(name in NOT_SECRET_OPTIONS for name in longs)+ return any(is_secret_name(name) for name in longs)def secret_option_strings(command: click.Command) -> frozenset[str]:"""Every option string (long and short) of ``command``'s credential options."""found: set[str] = set()for param in getattr(command, "params", None) or ():- if isinstance(param, click.Option) and _is_secret_option(param):+ if _is_secret_option(param):found.update(param.opts)return frozenset(found)+def subcommands(command: object) -> dict | None:+ """The name -> command mapping of a group, or ``None`` for a leaf command."""+ found = getattr(command, "commands", None)+ return found if isinstance(found, dict) else None++def iter_commands(command: click.Command) -> Iterable[click.Command]:"""Yield ``command`` and every command below it."""yield command- if isinstance(command, click.Group):- for sub in command.commands.values():- yield from iter_commands(sub)+ for sub in (subcommands(command) or {}).values():+ yield from iter_commands(sub)def all_secret_option_strings(root: click.Command) -> frozenset[str]:@@ -89,14 +121,14 @@ def resolve_command(root: click.Command, args: Sequence[str]) -> click.Command:"""current = roottokens = list(args)- while isinstance(current, click.Group):+ while (below := subcommands(current)) is not None:index = next((i for i, tok in enumerate(tokens) if not str(tok).startswith("-")),None,)if index is None:break- sub = current.commands.get(str(tokens[index]))+ sub = below.get(str(tokens[index]))if sub is None:breakcurrent = sub@@ -126,32 +158,73 @@ def _mask_short_bundle(tok: str, short_opts: set[str]) -> tuple[str, bool] | Nonreturn None-def mask_secret_args(args: Sequence[str], secret_opts: frozenset[str]) -> tuple[str, ...]:- """Return ``args`` with the value of every option in ``secret_opts`` masked.+def all_long_option_strings(root: click.Command) -> frozenset[str]:+ """Every ``--name`` any command of the tree declares, switches included."""+ found: set[str] = set()+ for command in iter_commands(root):+ for param in getattr(command, "params", None) or ():+ found.update(_long_names(param))+ return frozenset(found)+++def _starts_an_option(tok: str, known: frozenset[str] | set[str]) -> bool:+ """Whether ``tok``, found where a credential's value belongs, is an option instead.++ Only a long option the command tree declares, or one whose own name is a+ credential name, is read as an option there. Anything else is the value,+ even when it starts with ``--``.+ """+ if not tok.startswith("--"):+ return False+ name = tok.partition("=")[0]+ return name in known or is_secret_name(name)+++def mask_secret_args(+ args: Sequence[str],+ secret_opts: frozenset[str],+ known_opts: frozenset[str] = frozenset(),+) -> tuple[str, ...]:+ """Return ``args`` with the value of every credential option masked.++ An option is a credential option when it is in ``secret_opts`` (what the+ command tree declares, short aliases included) or when it is a long+ option whose name :func:`is_secret_name` accepts. The second rule needs+ no tree, so it also covers an option the tree did not yield; a switch+ with such a name hides the token after it, which costs nothing.Handles ``--opt value``, ``--opt=value``, ``-o value``, ``-oVALUE`` andbundled short options (``-xoVALUE`` / ``-xo VALUE``, where ``-x`` is a flagand ``-o`` takes the value). An option with no following value is kept as- is.+ is. The token after a credential option is its value and is masked, unless+ it is a long option in ``known_opts`` (every long option of the command+ tree) or ``secret_opts``, or has a credential name itself: then the option+ before it had no value and the scan continues from the new option, so a+ switch in front of a credential option cannot shift the mask off its value."""long_opts = {o for o in secret_opts if o.startswith("--")}+ known_longs = long_opts | known_optsshort_opts = {o for o in secret_opts if not o.startswith("--") and len(o) == 2}out: list[str] = []mask_next = Falsefor raw in args:tok = str(raw)if mask_next:- out.append(REDACTED)mask_next = False- continue+ if not _starts_an_option(tok, known_longs):+ out.append(REDACTED)+ continue+ # An option, not a value: the option before it had none, and this+ # one is scanned like any other.if tok in secret_opts:out.append(tok)mask_next = Truecontinue- if tok.startswith("--") and "=" in tok:- name = tok.split("=", 1)[0]- if name in long_opts:- out.append(f"{name}={REDACTED}")+ if tok.startswith("--"):+ name, has_value, _ = tok.partition("=")+ if name in long_opts or is_secret_name(name):+ out.append(f"{name}={REDACTED}" if has_value else tok)+ mask_next = not has_valuecontinueelif tok.startswith("-") and not tok.startswith("--") and len(tok) > 1:masked = _mask_short_bundle(tok, short_opts)diff --git a/src/soup_cli/utils/build_dag.py b/src/soup_cli/utils/build_dag.pyindex 345dc35c..37510e46 100644--- a/src/soup_cli/utils/build_dag.py+++ b/src/soup_cli/utils/build_dag.py@@ -378,8 +378,10 @@ def parse_build_yaml(text: object) -> BuildPlan:raise ValueError(f"build text exceeds {_MAX_FILE_BYTES} bytes")import yaml # lazy — keep CLI startup fast+ from soup_cli.utils.yaml_limits import load_yaml_limited+try:- data = yaml.safe_load(text)+ data = load_yaml_limited(text, "build text", max_bytes=_MAX_FILE_BYTES)except yaml.YAMLError as exc:raise ValueError(f"invalid YAML: {exc}") from excreturn parse_build_plan(data)diff --git a/src/soup_cli/utils/checklist_dsl.py b/src/soup_cli/utils/checklist_dsl.pyindex d2362eaf..8b5b458f 100644--- a/src/soup_cli/utils/checklist_dsl.py+++ b/src/soup_cli/utils/checklist_dsl.py@@ -37,6 +37,7 @@ from typing import Mapping, Optional, Sequenceimport yamlfrom soup_cli.utils.behavior_battery import contains_whole_word+from soup_cli.utils.yaml_limits import load_yaml_limited# Closed allowlist.CHECKLIST_KINDS = frozenset({"mft", "inv", "dir"})@@ -295,7 +296,7 @@ def load_checklist_spec(path: str) -> CheckListSpec:except OSError:passtry:- raw = yaml.safe_load(text)+ raw = load_yaml_limited(text, "spec file", max_bytes=_MAX_FILE_BYTES)except yaml.YAMLError as exc:raise ValueError(f"invalid YAML: {exc}") from excreturn parse_checklist_spec(raw)diff --git a/src/soup_cli/utils/data_mix.py b/src/soup_cli/utils/data_mix.pyindex f09015f1..3aa63f48 100644--- a/src/soup_cli/utils/data_mix.py+++ b/src/soup_cli/utils/data_mix.py@@ -764,10 +764,9 @@ def load_mix_recipe(path: str) -> Mapping[str, object]:raise ValueError(f"recipe exceeds {_MAX_RECIPE_BYTES} bytes cap (got {size})")- import yaml+ from soup_cli.utils.yaml_limits import load_yaml_file_limited- with open(real, "r", encoding="utf-8") as fh:- data = yaml.safe_load(fh)+ data = load_yaml_file_limited(real, "recipe", max_bytes=_MAX_RECIPE_BYTES)if not isinstance(data, Mapping):raise ValueError("recipe must be a YAML mapping at top level")data_block = data.get("data")diff --git a/src/soup_cli/utils/expectations.py b/src/soup_cli/utils/expectations.pyindex 698c1837..b4d550cd 100644--- a/src/soup_cli/utils/expectations.py+++ b/src/soup_cli/utils/expectations.py@@ -923,8 +923,10 @@ def parse_suite_yaml(text: object) -> SuiteSpec:raise ValueError(f"suite text exceeds {_MAX_FILE_BYTES} bytes")import yaml # lazy+ from soup_cli.utils.yaml_limits import load_yaml_limited+try:- data = yaml.safe_load(text)+ data = load_yaml_limited(text, "suite text", max_bytes=_MAX_FILE_BYTES)except yaml.YAMLError as exc:raise ValueError(f"invalid YAML: {exc}") from excreturn parse_suite_spec(data)diff --git a/src/soup_cli/utils/license_matrix.py b/src/soup_cli/utils/license_matrix.pyindex cf751c83..29a762c7 100644--- a/src/soup_cli/utils/license_matrix.py+++ b/src/soup_cli/utils/license_matrix.py@@ -332,9 +332,11 @@ def _license_from_frontmatter(path: str) -> Optional[str]:return Noneblock = body[:end]try:- import yaml # lazy — pyyaml is a core dep but keep import local+ from soup_cli.utils.yaml_limits import load_yaml_limited- meta = yaml.safe_load(block)+ meta = load_yaml_limited(+ block, "frontmatter", max_bytes=_MAX_FRONTMATTER_BYTES+ )except Exception: # noqa: BLE001 - any YAML error -> undeterminedreturn Noneif not isinstance(meta, dict):diff --git a/src/soup_cli/utils/mix_proxy.py b/src/soup_cli/utils/mix_proxy.pyindex c15ba858..f7942b01 100644--- a/src/soup_cli/utils/mix_proxy.py+++ b/src/soup_cli/utils/mix_proxy.py@@ -183,7 +183,12 @@ def _render_overlay_yaml("""import yaml # noqa: PLC0415- raw = yaml.safe_load(base_yaml_text)+ from soup_cli.utils.yaml_limits import ( # noqa: PLC0415+ MAX_CONFIG_BYTES,+ load_yaml_limited,+ )++ raw = load_yaml_limited(base_yaml_text, "base YAML", max_bytes=MAX_CONFIG_BYTES)if not isinstance(raw, dict):raise ValueError("base YAML must be a top-level mapping")data_block = raw.get("data")diff --git a/src/soup_cli/utils/ra_dit_run.py b/src/soup_cli/utils/ra_dit_run.pyindex 0f867c82..a5ca4ca4 100644--- a/src/soup_cli/utils/ra_dit_run.py+++ b/src/soup_cli/utils/ra_dit_run.py@@ -230,7 +230,7 @@ def _load_yaml_config(path: str) -> dict:"""import stat # noqa: PLC0415- import yaml # noqa: PLC0415+ from soup_cli.utils.yaml_limits import load_yaml_limited # noqa: PLC0415no_follow = getattr(os, "O_NOFOLLOW", 0)fd = os.open(path, os.O_RDONLY | no_follow)@@ -251,7 +251,7 @@ def _load_yaml_config(path: str) -> dict:except OSError:passraise- raw = yaml.safe_load(text)+ raw = load_yaml_limited(text, "config YAML", max_bytes=_MAX_YAML_BYTES)if not isinstance(raw, dict):raise ValueError("config YAML must be a top-level mapping")return rawdiff --git a/src/soup_cli/utils/recipe_dag.py b/src/soup_cli/utils/recipe_dag.pyindex ca51be7a..815df0c3 100644--- a/src/soup_cli/utils/recipe_dag.py+++ b/src/soup_cli/utils/recipe_dag.py@@ -189,8 +189,10 @@ def parse_recipe_yaml(text: str) -> RecipeDAG:raise ValueError(f"recipe text exceeds {_MAX_FILE_BYTES} bytes")import yaml # lazy import — keep CLI startup fast+ from soup_cli.utils.yaml_limits import load_yaml_limited+try:- data = yaml.safe_load(text)+ data = load_yaml_limited(text, "recipe text", max_bytes=_MAX_FILE_BYTES)except yaml.YAMLError as exc:raise ValueError(f"invalid YAML: {exc}") from excreturn parse_recipe(data)diff --git a/src/soup_cli/utils/save_formats.py b/src/soup_cli/utils/save_formats.pyindex b79e1b48..24c5e37d 100644--- a/src/soup_cli/utils/save_formats.py+++ b/src/soup_cli/utils/save_formats.py@@ -235,7 +235,7 @@ def load_quant_config(path: object) -> Mapping[str, Any]:* ``yaml.safe_load`` only* 256 KB size cap"""- import yaml+ from soup_cli.utils.yaml_limits import load_yaml_file_limitedvalidated_shape = validate_quant_config_path(path)_enforce_under_cwd_and_no_symlink(validated_shape, "quant_config")@@ -255,8 +255,9 @@ def load_quant_config(path: object) -> Mapping[str, Any]:f"quant_config too large ({size} bytes; "f"cap {_MAX_QUANT_CONFIG_BYTES})")- with open(validated_shape, encoding="utf-8") as fh:- data = yaml.safe_load(fh)+ data = load_yaml_file_limited(+ validated_shape, "quant_config", max_bytes=_MAX_QUANT_CONFIG_BYTES+ )if data is None:return {}if not isinstance(data, dict):diff --git a/src/soup_cli/utils/sweep_config.py b/src/soup_cli/utils/sweep_config.pyindex 196286d7..f88ffe73 100644--- a/src/soup_cli/utils/sweep_config.py+++ b/src/soup_cli/utils/sweep_config.py@@ -11,9 +11,8 @@ from dataclasses import dataclassfrom types import MappingProxyTypefrom typing import Any, Mapping, Tuple-import yaml-from soup_cli.utils.paths import is_under_cwd+from soup_cli.utils.yaml_limits import load_yaml_limited_VALID_STRATEGIES = frozenset({"grid", "random"})_MAX_PARAM_KEYS = 32@@ -59,7 +58,7 @@ def parse_sweep_yaml(text: str) -> SweepSpec:raise ValueError("sweep yaml contains NUL byte")if len(text.encode("utf-8")) > _MAX_FILE_BYTES:raise ValueError(f"sweep yaml exceeds {_MAX_FILE_BYTES} bytes")- data = yaml.safe_load(text)+ data = load_yaml_limited(text, "sweep yaml", max_bytes=_MAX_FILE_BYTES)if not isinstance(data, dict):raise ValueError("sweep yaml must be a mapping at the top level")strategy = data.get("strategy", "grid")diff --git a/src/soup_cli/utils/yaml_limits.py b/src/soup_cli/utils/yaml_limits.pyindex c0e6b2dd..44b89da0 100644--- a/src/soup_cli/utils/yaml_limits.py+++ b/src/soup_cli/utils/yaml_limits.py@@ -1,10 +1,24 @@-"""Expanded-size limit for documents loaded with ``yaml.safe_load``.+"""Size, nesting and expansion limits for documents loaded from YAML.-YAML anchors and aliases let a few hundred bytes of text describe a graph in-which one list is referenced many times over. ``yaml.safe_load`` keeps those-references shared, so the loaded object is small -- but anything that walks it-as a tree (``json.dumps``, ``model_dump``, a recursive validator) visits every-path, and the number of paths grows exponentially with the nesting depth.+Every YAML document Soup reads goes through :func:`load_yaml_limited` or+:func:`load_yaml_file_limited`. Both build the document exactly as+``yaml.safe_load`` does and raise :class:`YamlLimitError`, naming the document+and the limit, when it crosses one of three:++* **size** -- the source is at most ``max_bytes`` long, and a file is never+ read further than one byte past that;+* **nesting** -- collections nest at most :data:`MAX_YAML_NESTING` levels,+ whether written out or reached through aliases;+* **expansion** -- the loaded object has at most one node per source byte plus+ :data:`ALIAS_EXPANSION_SLACK`, and so have the pairs that merge keys (``<<``)+ copy into mappings while the document is being built.++The expansion rule exists because YAML anchors and aliases let a few hundred+bytes of text describe a graph in which one list is referenced many times over.+``yaml.safe_load`` keeps those references shared, so the loaded object is small+-- but anything that walks it as a tree (``json.dumps``, ``model_dump``, a+recursive validator) visits every path, and the number of paths grows+exponentially with the nesting depth.:func:`expanded_node_count` counts the nodes such a walk would visit withoutperforming it: a container's count is memoised by ``id()``, so a shared@@ -16,25 +30,50 @@ The limit is tied to the size of the source rather than fixed: a YAML documentwithout aliases needs at least one byte per node (``{a,b}`` is five bytes andfive nodes; nothing denser parses), so an alias-free document always passes:func:`check_yaml_expanded_size`, whatever legitimate content it carries. Only-aliases can make a document expand to more nodes than it has bytes, and with-the rule below the work done after loading stays proportional to the member-size, which the reader already caps.+aliases can make a document expand to more nodes than it has bytes. They do+it in two places: in the loaded object, which is measured after loading, and+in merge keys, where PyYAML copies the pairs of every merged mapping into the+mapping that names it before any object exists. The loader charges those+copies to the same allowance as they are made and stops at the first pair+past it, so the work done during and after loading stays proportional to the+source size, which the reader already caps."""from __future__ import annotations+import osfrom typing import Iterator+import yaml+#: Nodes allowed beyond one per source byte, so small documents (including the#: empty document, which loads as ``{}``) and modest alias reuse still load.ALIAS_EXPANSION_SLACK: int = 10_000-#: Nesting depth past which a document is treated as over the limit.+#: Largest training config read into memory, whether it is a ``soup.yaml`` on+#: disk, a config passed as text, or the ``config.yaml`` of a can. A training+#: config is kilobytes.+MAX_CONFIG_BYTES: int = 1 * 1024 * 1024++#: Levels of nested collections (mappings and sequences) a YAML document may+#: have. PyYAML builds nested collections by recursion, so this is what keeps a+#: document's stack use fixed whatever the interpreter's recursion limit is,+#: and it leaves every later walk of the loaded object shallow. Configs and+#: manifests nest fewer than ten levels.+MAX_YAML_NESTING: int = 100++#: Nesting depth past which the node counter treats any object as over the limit._MAX_DEPTH = 1000+_CONTAINERS = (dict, list, tuple)+_DONE = object()+class YamlLimitError(ValueError):+ """A YAML document is over its size, nesting or expansion limit."""++def _children(node: object) -> Iterator[object]:if isinstance(node, dict):for key, value in node.items():@@ -44,61 +83,76 @@ def _children(node: object) -> Iterator[object]:yield from node # type: ignore[misc]-def expanded_node_count(obj: object, *, limit: int) -> int:- """Return the number of nodes a tree walk of ``obj`` would visit.+def _measure(obj: object, *, limit: int) -> tuple[int, int]:+ """Return ``(nodes, depth)`` of ``obj`` walked as a tree.- One per scalar, ``1 + sum(children)`` per list / tuple, and- ``1 + sum(key + value)`` per dict. Returns ``limit + 1`` as soon as the- count is known to exceed ``limit``, on a reference cycle, or when nesting- is deeper than 1000 levels.+ ``nodes`` is one per scalar, ``1 + sum(children)`` per list / tuple and+ ``1 + sum(key + value)`` per dict; ``depth`` is the number of containers on+ the longest path, so a scalar is 0 and ``[[]]`` is 2. Both are memoised by+ ``id()``: a container reached again through a shared reference contributes+ its stored count and depth without being walked again, so levels that exist+ only through shared references are still measured.++ The walk is iterative. It stops with ``nodes == limit + 1`` as soon as the+ count is known to exceed ``limit`` or on a reference cycle; ``depth`` is+ then only a lower bound."""over = limit + 1- memo: dict[int, int] = {}- active: set[int] = set()-- def _known(node: object) -> int | None:- if not isinstance(node, (dict, list, tuple)):- return 1- key = id(node)- if key in memo:- return memo[key]- if key in active:- return over- return None-- first = _known(obj)- if first is not None:- return min(first, over)-- active.add(id(obj))+ if not isinstance(obj, _CONTAINERS):+ return min(1, over), 0++ nodes: dict[int, int] = {}+ depths: dict[int, int] = {}+ active: set[int] = {id(obj)}+ # A container, its remaining children, and [nodes so far, deepest child].stack: list[tuple[object, Iterator[object], list[int]]] = [- (obj, _children(obj), [1]),+ (obj, _children(obj), [1, 0]),]while stack:- node, children, total = stack[-1]+ node, children, state = stack[-1]child = next(children, _DONE)if child is _DONE:stack.pop()- active.discard(id(node))- memo[id(node)] = total[0]+ key = id(node)+ active.discard(key)+ depth = state[1] + 1+ nodes[key] = state[0]+ depths[key] = depthif not stack:- return total[0]- parent_total = stack[-1][2]- parent_total[0] += total[0]- if parent_total[0] > limit:- return over- continue- count = _known(child)- if count is None:- if len(stack) >= _MAX_DEPTH:- return over- active.add(id(child))- stack.append((child, _children(child), [1]))+ return state[0], depth+ parent = stack[-1][2]+ parent[0] += state[0]+ parent[1] = max(parent[1], depth)+ if parent[0] > limit:+ return over, parent[1]continue- total[0] += count- if total[0] > limit:- return over- return over # pragma: no cover - the loop always returns+ if not isinstance(child, _CONTAINERS):+ state[0] += 1+ else:+ key = id(child)+ if key in active:+ return over, state[1]+ if key not in nodes:+ active.add(key)+ stack.append((child, _children(child), [1, 0]))+ continue+ state[0] += nodes[key]+ state[1] = max(state[1], depths[key])+ if state[0] > limit:+ return over, state[1]+ return over, 0 # pragma: no cover - the loop always returns+++def expanded_node_count(obj: object, *, limit: int) -> int:+ """Return the number of nodes a tree walk of ``obj`` would visit.++ One per scalar, ``1 + sum(children)`` per list / tuple, and+ ``1 + sum(key + value)`` per dict. Returns ``limit + 1`` as soon as the+ count is known to exceed ``limit``, on a reference cycle, or when nesting+ is deeper than 1000 levels.+ """+ nodes, depth = _measure(obj, limit=limit)+ return limit + 1 if depth > _MAX_DEPTH else nodesdef check_expanded_nodes(obj: object, what: str, *, limit: int) -> None:@@ -107,15 +161,243 @@ def check_expanded_nodes(obj: object, what: str, *, limit: int) -> None:raise ValueError(f"{what} expands to more than {limit} nodes; refusing")+def _expansion_error(what: str, limit: int, source_bytes: int) -> YamlLimitError:+ return YamlLimitError(+ f"{what} expands to more than {limit} nodes from {source_bytes} "+ "bytes of YAML; refusing"+ )+++def _nesting_error(what: str) -> YamlLimitError:+ return YamlLimitError(+ f"{what} nests collections more than {MAX_YAML_NESTING} levels deep; refusing"+ )++def check_yaml_expanded_size(obj: object, what: str, *, source_bytes: int) -> None:- """Refuse ``obj`` when it has more nodes than its YAML source had bytes.+ """Refuse ``obj`` when it nests or expands past what its YAML source allows.- ``source_bytes`` is the length of the text ``obj`` was loaded from; the+ ``source_bytes`` is the length of the text ``obj`` was loaded from; the nodeallowance is that plus :data:`ALIAS_EXPANSION_SLACK` (see module docstring).+ Nesting is measured on the loaded object, so levels that exist only through+ aliases count towards :data:`MAX_YAML_NESTING` too."""limit = source_bytes + ALIAS_EXPANSION_SLACK- if expanded_node_count(obj, limit=limit) > limit:- raise ValueError(- f"{what} expands to more than {limit} nodes from {source_bytes} "- "bytes of YAML; refusing"+ nodes, depth = _measure(obj, limit=limit)+ if depth > MAX_YAML_NESTING:+ raise _nesting_error(what)+ if nodes > limit:+ raise _expansion_error(what, limit, source_bytes)+++class _TooDeepError(Exception):+ """Raised while parsing when collections nest past the limit."""+++class _MergeChainError(Exception):+ """Raised while building when merge keys chain past the limit."""+++class _MergeBudgetError(Exception):+ """Raised while building when merge keys copy more nodes than allowed."""+++_MERGE_TAG = "tag:yaml.org,2002:merge"+_VALUE_TAG = "tag:yaml.org,2002:value"+++class _LimitedLoader(yaml.SafeLoader):+ """``yaml.SafeLoader`` that bounds nesting and merge-key copies as it loads.++ The composer takes every event through ``get_event``, so counting+ collection starts and ends there bounds its recursion in the same pass that+ builds the document, without reading the text twice.++ ``flatten_mapping`` is the one place PyYAML copies nodes: a merge key puts+ the pairs of each mapping it names into the mapping that holds it. The+ version here builds the same pair list, charges two nodes per copied pair+ to ``node_budget`` before copying, and counts how deep merges chain.+ Sequences, sets, ``!!omap`` and ``!!pairs`` are built in one pass over+ their own node and copy nothing.+ """++ def __init__(self, stream: str | bytes, *, node_budget: int) -> None:+ super().__init__(stream)+ self._open_collections = 0+ self._node_budget = node_budget+ self._merge_depth = 0+ #: Nodes copied by merge keys so far.+ self.merged_nodes = 0++ def get_event(self) -> yaml.Event:+ event = super().get_event()+ if isinstance(event, yaml.CollectionStartEvent):+ self._open_collections += 1+ if self._open_collections > MAX_YAML_NESTING:+ raise _TooDeepError+ elif isinstance(event, yaml.CollectionEndEvent):+ self._open_collections -= 1+ return event++ def _merged_pairs(self, owner: yaml.MappingNode, source: yaml.Node) -> list:+ """The pairs ``source`` contributes to a merge, charged to the budget."""+ if not isinstance(source, yaml.MappingNode):+ raise yaml.constructor.ConstructorError(+ "while constructing a mapping",+ owner.start_mark,+ f"expected a mapping for merging, but found {source.id}",+ source.start_mark,+ )+ self.flatten_mapping(source)+ self.merged_nodes += 2 * len(source.value)+ if self.merged_nodes > self._node_budget:+ raise _MergeBudgetError+ return source.value++ def flatten_mapping(self, node: yaml.MappingNode) -> None:+ """As ``SafeConstructor.flatten_mapping``, step for step, with the copies counted."""+ self._merge_depth += 1+ if self._merge_depth > MAX_YAML_NESTING:+ raise _MergeChainError+ merged: list = []+ index = 0+ while index < len(node.value):+ key_node, value_node = node.value[index]+ if key_node.tag != _MERGE_TAG:+ if key_node.tag == _VALUE_TAG:+ key_node.tag = "tag:yaml.org,2002:str"+ index += 1+ continue+ # Taken out before the mappings it names are visited, as PyYAML does:+ # a mapping that names itself is then merged without this entry.+ del node.value[index]+ if isinstance(value_node, yaml.MappingNode):+ merged.extend(self._merged_pairs(node, value_node))+ elif isinstance(value_node, yaml.SequenceNode):+ parts = [self._merged_pairs(node, source) for source in value_node.value]+ # A later mapping in the list yields to an earlier one.+ for pairs in reversed(parts):+ merged.extend(pairs)+ else:+ raise yaml.constructor.ConstructorError(+ "while constructing a mapping",+ node.start_mark,+ "expected a mapping or list of mappings for merging, "+ f"but found {value_node.id}",+ value_node.start_mark,+ )+ if merged:+ node.value = merged + node.value+ self._merge_depth -= 1+++class YamlScalarError(yaml.constructor.ConstructorError, ValueError):+ """A scalar that reads as a YAML type but cannot be built, such as a date+ that does not exist. Both a ``yaml.YAMLError`` (it carries the position) and+ the ``ValueError`` the underlying conversion raised."""+++def _checked(name: str, build):+ def construct(self: _LimitedLoader, node: yaml.ScalarNode) -> object:+ try:+ return build(self, node)+ except ValueError as exc:+ reason = str(exc)+ except (KeyError, AttributeError, IndexError):+ # What the conversion raises for text an explicit tag puts in front+ # of it: `!!bool foo`, `!!timestamp foo`, `!!int ""`.+ reason = f"not a valid {name}"+ raise YamlScalarError(+ None, None, f"cannot build this value: {reason}", node.start_mark)++ return construct+++# The four safe constructors that convert text with a Python call that can refuse it.+for _name in ("bool", "int", "float", "timestamp"):+ _tag = f"tag:yaml.org,2002:{_name}"+ _LimitedLoader.add_constructor(+ _tag, _checked(_name, yaml.SafeLoader.yaml_constructors[_tag])+ )+++def _parse(source: str | bytes, what: str, *, source_bytes: int) -> object:+ """Build the single document in ``source`` as ``yaml.safe_load`` would."""+ limit = source_bytes + ALIAS_EXPANSION_SLACK+ # A SafeLoader subclass: the same tags and constructors as safe_load.+ loader = _LimitedLoader(source, node_budget=limit)+ try:+ return loader.get_single_data()+ except _TooDeepError:+ raise _nesting_error(what) from None+ except _MergeChainError:+ raise YamlLimitError(+ f"{what} chains merge keys more than {MAX_YAML_NESTING} levels deep; refusing"+ ) from None+ except _MergeBudgetError:+ raise _expansion_error(what, limit, source_bytes) from None+ except RecursionError:+ # Reached only when the caller's own stack is already deep.+ raise YamlLimitError(f"{what} is nested or chained too deeply to load; refusing") from None+ finally:+ loader.dispose()+++def _size_error(what: str, max_bytes: int) -> YamlLimitError:+ return YamlLimitError(f"{what} is larger than {max_bytes} bytes; refusing")+++def load_yaml_limited(source: str | bytes, what: str, *, max_bytes: int) -> object:+ """Load one YAML document from text, within the limits.++ Returns what ``yaml.safe_load(source)`` returns. Raises+ :class:`YamlLimitError` -- a ``ValueError`` whose message starts with+ ``what`` -- when the text is longer than ``max_bytes`` (UTF-8), nests+ collections more than :data:`MAX_YAML_NESTING` levels, or expands past the+ node allowance. A syntax error is still a ``yaml.YAMLError``,+ and a scalar that cannot be built is a :class:`YamlScalarError`.+ """+ if isinstance(source, str):+ source_bytes = len(source.encode("utf-8", "surrogatepass"))+ elif isinstance(source, bytes):+ source_bytes = len(source)+ else:+ raise TypeError(f"{what} must be str or bytes, got {type(source).__name__}")+ if source_bytes > max_bytes:+ raise _size_error(what, max_bytes)+ data = _parse(source, what, source_bytes=source_bytes)+ check_yaml_expanded_size(data, what, source_bytes=source_bytes)+ return data+++def read_text_limited(+ path: str | os.PathLike[str], what: str, *, max_bytes: int+) -> str:+ """Return the text of a UTF-8 file of at most ``max_bytes`` bytes.++ Reads at most ``max_bytes + 1`` bytes and raises :class:`YamlLimitError`+ naming ``what`` when the file is larger, so the whole of a larger file is+ never held in memory.+ """+ with open(path, "rb") as handle:+ raw = handle.read(max_bytes + 1)+ if len(raw) > max_bytes:+ raise _size_error(what, max_bytes)+ return raw.decode("utf-8")+++def load_yaml_file_limited(+ path: str | os.PathLike[str], what: str, *, max_bytes: int+) -> object:+ """Load one YAML document from a UTF-8 file, within the limits.++ The file is read with :func:`read_text_limited`, so ``max_bytes`` counts+ the bytes on disk and a larger file is refused without being held in+ memory. The result is what ``yaml.safe_load`` returns for the file's+ text: YAML treats CRLF, CR and LF line ends alike and skips a leading+ byte order mark. Raises as :func:`load_yaml_limited` does; ``OSError``+ and ``UnicodeDecodeError`` are passed on unchanged.+ """+ text = read_text_limited(path, what, max_bytes=max_bytes)+ return load_yaml_limited(text, what, max_bytes=max_bytes)diff --git a/tests/test_argv_redaction_bundled_shorts.py b/tests/test_argv_redaction_bundled_shorts.pyindex f88433d4..e344e0a2 100644--- a/tests/test_argv_redaction_bundled_shorts.py+++ b/tests/test_argv_redaction_bundled_shorts.py@@ -73,6 +73,13 @@ class TestTheExistingFormsStillWork:def test_form(self, argv, expected):assert mask_secret_args(argv, OPTS) == expected- def test_no_secret_options_means_no_masking(self):- argv = ["-xtSECRET", "--auth-token", "S"]- assert mask_secret_args(argv, frozenset()) == tuple(argv)+ def test_no_declared_options_leaves_short_bundles_and_masks_by_long_name(self):+ """A short letter means nothing without its command; a long name is read as typed."""+ argv = ["-xtSECRET", "--auth-token", "S", "--model", "m"]+ assert mask_secret_args(argv, frozenset()) == (+ "-xtSECRET",+ "--auth-token",+ "<redacted>",+ "--model",+ "m",+ )diff --git a/tests/test_argv_redaction_command_tree.py b/tests/test_argv_redaction_command_tree.pynew file mode 100644index 00000000..cb30fce8--- /dev/null+++ b/tests/test_argv_redaction_command_tree.py@@ -0,0 +1,470 @@+"""Credential options are found by reading the command tree, whatever built it."""++from __future__ import annotations++import pytest+import typer++from soup_cli.utils import argv_redaction+from soup_cli.utils.argv_redaction import (+ NOT_SECRET_OPTIONS,+ REDACTED,+ SECRET_OPTIONS,+ _long_names,+ all_secret_option_strings,+ is_secret_name,+ iter_commands,+ mask_secret_args,+ resolve_command,+ secret_option_strings,+ subcommands,+)++# ---------------------------------------------------------------------------+# A command tree whose classes share nothing with the importable click package,+# as Typer builds it when it carries its own copy.+# ---------------------------------------------------------------------------+++class _Option:+ def __init__(self, *opts, secondary=(), is_flag=False, count=False):+ self.opts = list(opts)+ self.secondary_opts = list(secondary)+ self.is_flag = is_flag+ self.count = count+++class _Argument:+ def __init__(self, name):+ self.opts = [name]+ self.secondary_opts = []+++class _Command:+ def __init__(self, name, params=()):+ self.name = name+ self.params = list(params)+++class _Group(_Command):+ def __init__(self, name, commands, params=()):+ super().__init__(name, params)+ self.commands = {command.name: command for command in commands}+++def tree():+ serve = _Command(+ "serve",+ [+ _Option("--model", "-m"),+ _Option("--api-key"),+ _Option("--tool-auth-token", "-t"),+ _Option("--use-auth-token", is_flag=True),+ _Option("--token-verbosity", "-v", count=True),+ _Option("--max-tokens"),+ _Option("--cache", secondary=["--no-key-cache"], is_flag=True),+ _Argument("token"),+ ],+ )+ generate = _Command("generate", [_Option("--api-key", "-k"), _Option("--rows")])+ data = _Group("data", [generate], [_Option("--data-secret")])+ return _Group("soup", [serve, data])+++def test_every_command_of_a_foreign_tree_is_visited(tree):+ assert [command.name for command in iter_commands(tree)] == [+ "soup",+ "serve",+ "data",+ "generate",+ ]+++def test_credential_options_of_a_foreign_tree_are_found(tree):+ assert all_secret_option_strings(tree) == {+ "--api-key",+ "--tool-auth-token",+ "-t",+ "-k",+ "--data-secret",+ }+++def test_only_value_taking_options_of_a_command_count(tree):+ """A switch, a counter, a listed non-credential name and an argument do not."""+ serve = tree.commands["serve"]+ assert secret_option_strings(serve) == {"--api-key", "--tool-auth-token", "-t"}+++def test_group_and_leaf_are_told_apart_by_their_subcommands(tree):+ data = tree.commands["data"]+ assert subcommands(tree) is tree.commands+ assert subcommands(data) is data.commands+ assert subcommands(tree.commands["serve"]) is None+ assert subcommands(_Group("empty", [])) == {}+++ ("args", "name"),+ [+ (["serve", "--api-key", "VALUE"], "serve"),+ (["--verbose", "data", "generate", "--rows", "3"], "generate"),+ (["data"], "data"),+ (["data", "no-such-command"], "data"),+ (["no-such-command"], "soup"),+ ([], "soup"),+ ],+)+def test_arguments_resolve_down_a_foreign_tree(tree, args, name):+ assert resolve_command(tree, args).name == name+++def test_values_are_masked_with_the_options_of_a_foreign_tree(tree):+ args = ["--model", "m", "--api-key", "VALUE-ONE", "--tool-auth-token=VALUE-TWO", "-t", "V3"]+ assert mask_secret_args(args, all_secret_option_strings(tree)) == (+ "--model",+ "m",+ "--api-key",+ REDACTED,+ f"--tool-auth-token={REDACTED}",+ "-t",+ REDACTED,+ )+++# ---------------------------------------------------------------------------+# The real command tree+# ---------------------------------------------------------------------------+++def cli(monkeypatch):+ import soup_cli.cli as cli_module++ monkeypatch.setattr(cli_module, "_ALL_SECRET_OPTION_STRINGS", None)+ return cli_module+++def test_the_real_tree_is_walked_and_has_credential_options(cli):+ root = typer.main.get_command(cli.app)+ assert sum(1 for _ in iter_commands(root)) > 200+ assert {"--api-key", "--auth-token", "--tool-auth-token"} <= all_secret_option_strings(root)+++def test_the_real_tree_masks_by_option_name(cli):+ args = ["--model", "m", "--api-key", "VALUE-ONE", "--tool-auth-token=VALUE-TWO"]+ assert cli._mask_audit_args("serve", args) == (+ "--model",+ "m",+ "--api-key",+ REDACTED,+ f"--tool-auth-token={REDACTED}",+ )+++def test_a_group_is_masked_with_every_option_of_the_app(cli):+ """`-t` is a credential option of some command, so a bare group masks it."""+ assert cli._mask_audit_args("data", ["-t", "VALUE"]) == ("-t", REDACTED)+++# ---------------------------------------------------------------------------+# The names typed are masked by the same rule, whatever the tree yields+# ---------------------------------------------------------------------------+++def test_an_empty_option_set_masks_by_the_names_on_the_command_line(cli, monkeypatch):+ monkeypatch.setattr(cli, "_ALL_SECRET_OPTION_STRINGS", frozenset())+ args = [+ "--model",+ "m",+ "--api-key",+ "VALUE-ONE",+ "--tool-auth-token=VALUE-TWO",+ "--max-tokens",+ "64",+ ]+ assert cli._mask_audit_args("serve", args) == (+ "--model",+ "m",+ "--api-key",+ REDACTED,+ f"--tool-auth-token={REDACTED}",+ "--max-tokens",+ "64",+ )+++ ("args", "expected"),+ [+ (["--api-key", "V"], ("--api-key", REDACTED)),+ (["--api-key=V"], (f"--api-key={REDACTED}",)),+ (["--api-key="], (f"--api-key={REDACTED}",)),+ (["--hf-token", "V", "next"], ("--hf-token", REDACTED, "next")),+ (["--password=V"], (f"--password={REDACTED}",)),+ (["--passwd", "V"], ("--passwd", REDACTED)),+ (["--client-secret", "V"], ("--client-secret", REDACTED)),+ (["--credential-file", "V"], ("--credential-file", REDACTED)),+ (["--API-KEY", "V"], ("--API-KEY", REDACTED)),+ (["--api-key", "-S1"], ("--api-key", REDACTED)),+ (["--api-key", "-"], ("--api-key", REDACTED)),+ (+ ["--api-key", "V1", "--auth-token", "V2"],+ ("--api-key", REDACTED, "--auth-token", REDACTED),+ ),+ (["--api-key"], ("--api-key",)),+ (["--slack-url", "https://example.invalid/hook/V"], ("--slack-url", REDACTED)),+ (["--discord-url=https://example.invalid/hook/V"], (f"--discord-url={REDACTED}",)),+ ],+)+def test_names_that_look_like_a_credential_have_their_value_masked(args, expected):+ assert mask_secret_args(args, frozenset()) == expected+++ "args",+ [+ ["serve", "--model", "m", "--port", "8000"],+ ["--max-tokens", "64"],+ ["--max-new-tokens=64"],+ ["--min-tokens", "5"],+ ["--base-url", "https://example.invalid/v1"],+ ["--tokenizer", "org/model"],+ ["--public-key", "key.pem"],+ ["--special-token", "<|im_end|>"],+ ["-t", "V"],+ ["--", "token"],+ ["token", "key", "secret"],+ [],+ ],+)+def test_other_arguments_are_kept_as_typed(args):+ assert mask_secret_args(args, frozenset()) == tuple(args)+++def test_names_and_tree_options_are_masked_together():+ """A declared short alias and an undeclared long name in one command line."""+ args = ["-t", "V1", "--api-key", "V2", "-x", "kept", "--port", "1"]+ assert mask_secret_args(args, frozenset({"--token", "-t"})) == (+ "-t",+ REDACTED,+ "--api-key",+ REDACTED,+ "-x",+ "kept",+ "--port",+ "1",+ )+++def test_a_single_dash_option_of_several_letters_is_masked_as_declared():+ """Not a long name and not a one-letter alias: only the tree can name it."""+ assert mask_secret_args(["-tok", "V", "x"], frozenset({"-tok"})) == ("-tok", REDACTED, "x")+++# ---------------------------------------------------------------------------+# A tree that can only partly be read+# ---------------------------------------------------------------------------+++class _Unreadable:+ """A parameter that exposes none of the attributes the walk reads."""+++def partly_readable(cli, monkeypatch):+ """`push` declares its credential option; nothing can be read from `serve`."""+ push = _Command("push", [_Option("--token", "-t"), _Option("--repo")])+ serve = _Command("serve", [_Unreadable(), _Unreadable()])+ root = _Group("soup", [push, serve])+ monkeypatch.setattr(typer.main, "get_command", lambda app: root)+ assert all_secret_option_strings(root) == {"--token", "-t"}+ return cli+++def test_an_option_the_tree_did_not_yield_is_still_masked(partly_readable):+ args = ["--model", "m", "--api-key", "VALUE-ONE", "--tool-auth-token=VALUE-TWO", "--port", "1"]+ assert partly_readable._mask_audit_args("serve", args) == (+ "--model",+ "m",+ "--api-key",+ REDACTED,+ f"--tool-auth-token={REDACTED}",+ "--port",+ "1",+ )+++def test_a_short_alias_the_tree_did_yield_is_masked(partly_readable):+ assert partly_readable._mask_audit_args("push", ["--repo", "u/m", "-t", "VALUE"]) == (+ "--repo",+ "u/m",+ "-t",+ REDACTED,+ )+++# ---------------------------------------------------------------------------+# The two lists and the real options agree+# ---------------------------------------------------------------------------+++def test_webhook_urls_are_credential_options_of_the_real_tree(cli):+ assert SECRET_OPTIONS == {"--slack-url", "--discord-url"}+ assert SECRET_OPTIONS <= all_secret_option_strings(typer.main.get_command(cli.app))+++def test_a_webhook_url_is_masked_for_a_real_command(cli):+ args = ["--slack-url", "https://example.invalid/hook/VALUE", "--discord-url=VALUE-TWO"]+ assert cli._mask_audit_args("train", args) == (+ "--slack-url",+ REDACTED,+ f"--discord-url={REDACTED}",+ )+++def test_a_length_threshold_is_not_a_credential_option(cli):+ assert "--min-tokens" in NOT_SECRET_OPTIONS+ assert "--min-tokens" not in all_secret_option_strings(typer.main.get_command(cli.app))+ assert cli._mask_audit_args("data", ["clean", "--min-tokens", "5"]) == (+ "clean",+ "--min-tokens",+ "5",+ )+++def test_no_real_switch_has_a_name_the_rule_would_mask(cli):+ """A switch takes no value, so masking by its name would hide the next argument."""+ unlisted = set()+ for command in iter_commands(typer.main.get_command(cli.app)):+ for param in getattr(command, "params", None) or ():+ if getattr(param, "is_flag", False) or getattr(param, "count", False):+ unlisted.update(name for name in _long_names(param) if is_secret_name(name))+ assert unlisted == set(), "list each in NOT_SECRET_OPTIONS"+++# ---------------------------------------------------------------------------+# A long option is never taken as the value of the option before it+# ---------------------------------------------------------------------------+++ ("args", "expected"),+ [+ (["--keep-key-cache", "--api-key", "S1"], ("--keep-key-cache", "--api-key", REDACTED)),+ (["--api-key", "--auth-token", "S1"], ("--api-key", "--auth-token", REDACTED)),+ (["--api-key", "--auth-token=S1"], ("--api-key", f"--auth-token={REDACTED}")),+ (["--hf-token", "--abc123"], ("--hf-token", REDACTED)),+ (["--hf-token", "--abc123", "next"], ("--hf-token", REDACTED, "next")),+ (["--hf-token=--abc123"], (f"--hf-token={REDACTED}",)),+ (["--api-key", "--model", "m"], ("--api-key", REDACTED, "m")),+ (["--use-token", "--", "S1"], ("--use-token", REDACTED, "S1")),+ (["--api-key", "--api-key", "--api-key", "S1"], ("--api-key",) * 3 + (REDACTED,)),+ # A single dash is never a long option, whatever its letters spell.+ (["--hf-token", "-my-key"], ("--hf-token", REDACTED)),+ (["--hf-token", "-my-key", "next"], ("--hf-token", REDACTED, "next")),+ (["--hf-token", "-my-key=S1"], ("--hf-token", REDACTED)),+ ],+)+def test_only_a_credential_named_option_is_read_as_an_option_without_a_tree(args, expected):+ """Anything else that follows a credential option is its value, dashes or not."""+ assert mask_secret_args(args, frozenset()) == expected+++ ("args", "expected"),+ [+ (["--token", "--repo", "u/m"], ("--token", "--repo", "u/m")),+ (["--token", "--repo=u/m"], ("--token", "--repo=u/m")),+ (["--token", "--abc123", "--repo", "u/m"], ("--token", REDACTED, "--repo", "u/m")),+ (["-t", "--abc123"], ("-t", REDACTED)),+ (["-t", "--token", "S1"], ("-t", "--token", REDACTED)),+ (["-xt", "--repo", "u/m"], ("-xt", "--repo", "u/m")),+ (["-t", "-S1"], ("-t", REDACTED)),+ ],+)+def test_a_long_option_the_tree_knows_is_read_as_an_option(args, expected):+ known = frozenset({"--token", "--repo"})+ assert mask_secret_args(args, frozenset({"--token", "-t"}), known) == expected+++def test_a_long_option_the_caller_lists_as_secret_is_read_as_an_option():+ """Listed in `secret_opts`, so an option, though its name says nothing about a credential."""+ secret_opts = frozenset({"--webhook", "--sink"})+ known = frozenset({"--repo"})+ assert mask_secret_args(["--webhook", "--sink", "S1"], secret_opts, known) == (+ "--webhook",+ "--sink",+ REDACTED,+ )+ assert mask_secret_args(["--webhook", "--sink=S1"], secret_opts, known) == (+ "--webhook",+ f"--sink={REDACTED}",+ )+++# ---------------------------------------------------------------------------+# A group of a foreign tree is masked with the short aliases of its commands+# ---------------------------------------------------------------------------+++def test_a_foreign_group_masks_the_short_alias_of_its_command(cli, monkeypatch):+ push = _Command("push", [_Option("--token", "-t"), _Option("--repo")])+ root = _Group("soup", [_Group("hub", [push])])+ monkeypatch.setattr(typer.main, "get_command", lambda app: root)+ assert cli._mask_audit_args("hub", ["-t", "VALUE", "--repo", "u/m"]) == (+ "-t",+ REDACTED,+ "--repo",+ "u/m",+ )+++def test_the_real_tree_tells_a_known_option_from_a_value_that_starts_with_dashes(cli):+ assert cli._mask_audit_args("serve", ["--api-key", "--model", "m"]) == (+ "--api-key",+ "--model",+ "m",+ )+ assert cli._mask_audit_args("serve", ["--api-key", "--abc123", "--model", "m"]) == (+ "--api-key",+ REDACTED,+ "--model",+ "m",+ )+++def test_every_long_option_of_a_tree_is_collected(tree):+ assert argv_redaction.all_long_option_strings(tree) == {+ "--model",+ "--api-key",+ "--tool-auth-token",+ "--use-auth-token",+ "--token-verbosity",+ "--max-tokens",+ "--cache",+ "--no-key-cache",+ "--rows",+ "--data-secret",+ }+++# ---------------------------------------------------------------------------+# A command that cannot be resolved is masked with every option of the app+# ---------------------------------------------------------------------------+++def test_a_failed_resolution_still_masks_short_aliases_and_long_names(cli, monkeypatch):+ def _fails(root, args):+ raise RuntimeError("the command could not be resolved")++ monkeypatch.setattr(argv_redaction, "resolve_command", _fails)+ assert cli._mask_audit_args("push", ["-t", "S3CRET", "--token", "V2", "--repo", "u/m"]) == (+ "-t",+ REDACTED,+ "--token",+ REDACTED,+ "--repo",+ "u/m",+ )diff --git a/tests/test_config_loader_limits.py b/tests/test_config_loader_limits.pynew file mode 100644index 00000000..1aeafb28--- /dev/null+++ b/tests/test_config_loader_limits.py@@ -0,0 +1,698 @@+"""soup.yaml is loaded under the same size, nesting and alias limits as a can's config."""++from __future__ import annotations++import os+import re+import sys++import pytest+import yaml+from typer.testing import CliRunner++from soup_cli.config import loader+from soup_cli.config.loader import load_config, load_config_from_string+from soup_cli.utils import yaml_limits+from soup_cli.utils.yaml_limits import (+ ALIAS_EXPANSION_SLACK,+ MAX_CONFIG_BYTES,+ MAX_YAML_NESTING,+ YamlLimitError,+)++_ANSI_RE = re.compile(r"\x1b\[[0-9;]*m")++_VALID = (+ "base: meta-llama/Llama-3.1-8B-Instruct\n"+ "task: sft\n"+ "data:\n"+ " train: ./data.jsonl\n"+ " format: alpaca\n"+ "training:\n"+ " epochs: 1\n"+ " lora:\n"+ " r: 8\n"+ " alpha: 16\n"+ "output: ./output\n"+)+++def _plain(text: str) -> str:+ """Rich colours numbers and wraps at the terminal width: undo both."""+ return " ".join(_ANSI_RE.sub("", text).split())+++# ---------------------------------------------------------------------------+# Configs named by the limit they sit under or cross+# ---------------------------------------------------------------------------+++def _config_of_size(size: int) -> str:+ """A valid config padded with a trailing comment to exactly ``size`` bytes."""+ padding = size - len(_VALID.encode()) - 2+ assert padding >= 0+ text = _VALID + "#" + "x" * padding + "\n"+ assert len(text.encode()) == size+ return text+++def _config_nested(levels: int) -> str:+ """The valid config plus one key whose value brings the nesting to ``levels``."""+ inner = levels - 1 # the root mapping is the first level+ return _VALID + "extra: " + "[" * inner + "]" * inner + "\n"+++def _config_with_alias_fan_out(levels: int) -> str:+ """The valid config plus lists that each reference the previous one ten times."""+ text = _VALID + "l0: &a0 [" + ", ".join(["x"] * 10) + "]\n"+ for index in range(1, levels + 1):+ text += f"l{index}: &a{index} [" + ", ".join([f"*a{index - 1}"] * 10) + "]\n"+ return text+++_WITH_MODEST_ALIASES = _VALID.replace(+ "base: meta-llama/Llama-3.1-8B-Instruct\n",+ "base: &name meta-llama/Llama-3.1-8B-Instruct\n",+).replace("output: ./output\n", "output: *name\n")+++def _expansion_message(what: str, text: str) -> str:+ size = len(text.encode())+ return (+ f"{what} expands to more than {size + ALIAS_EXPANSION_SLACK} nodes "+ f"from {size} bytes of YAML; refusing"+ )+++_SIZE_MESSAGE = f"is larger than {MAX_CONFIG_BYTES} bytes; refusing"+_NESTING_MESSAGE = f"nests collections more than {MAX_YAML_NESTING} levels deep; refusing"+++def in_tmp(tmp_path, monkeypatch):+ monkeypatch.chdir(tmp_path)+ return tmp_path+++def _refused(capsys, path="soup.yaml") -> str:+ """Load ``path``, require a clean exit 1, and return what was printed."""+ with pytest.raises(SystemExit) as raised:+ load_config(path)+ assert raised.value.code == 1+ captured = capsys.readouterr()+ assert "Traceback" not in captured.out + captured.err+ return _plain(captured.out)+++def test_the_limits_are_the_shared_ones():+ from soup_cli.cans import unpack++ assert MAX_CONFIG_BYTES == 1024 * 1024+ assert loader.MAX_CONFIG_BYTES is yaml_limits.MAX_CONFIG_BYTES+ assert unpack.MAX_CONFIG_BYTES is yaml_limits.MAX_CONFIG_BYTES+ assert MAX_YAML_NESTING == 100+ assert ALIAS_EXPANSION_SLACK == 10_000+++# ---------------------------------------------------------------------------+# load_config: a file, SystemExit(1) with a message+# ---------------------------------------------------------------------------+++class TestConfigFile:+ def test_config_exactly_at_the_size_limit_loads(self, in_tmp):+ (in_tmp / "soup.yaml").write_bytes(_config_of_size(MAX_CONFIG_BYTES).encode())+ assert load_config("soup.yaml").base == "meta-llama/Llama-3.1-8B-Instruct"++ def test_config_one_byte_over_the_size_limit_is_refused(self, in_tmp, capsys):+ (in_tmp / "soup.yaml").write_bytes(_config_of_size(MAX_CONFIG_BYTES + 1).encode())+ assert _refused(capsys) == f"Config file soup.yaml {_SIZE_MESSAGE}"++ def test_size_limit_is_the_one_the_loader_module_names(self, in_tmp, capsys, monkeypatch):+ monkeypatch.setattr(loader, "MAX_CONFIG_BYTES", len(_VALID.encode()) - 1)+ (in_tmp / "soup.yaml").write_bytes(_VALID.encode())+ expected = f"Config file soup.yaml is larger than {len(_VALID.encode()) - 1} bytes"+ assert expected in _refused(capsys)++ def test_config_nested_to_the_limit_is_not_refused_for_nesting(self, in_tmp, capsys):+ (in_tmp / "soup.yaml").write_text(_config_nested(MAX_YAML_NESTING), encoding="utf-8")+ output = _refused(capsys) # 'extra' is not a config key, so the load still stops+ assert "nests collections" not in output+ assert "Config validation error" in output+ assert "extra" in output++ def test_config_nested_one_level_past_the_limit_is_refused(self, in_tmp, capsys):+ (in_tmp / "soup.yaml").write_text(+ _config_nested(MAX_YAML_NESTING + 1), encoding="utf-8"+ )+ output = _refused(capsys)+ assert f"Config file soup.yaml {_NESTING_MESSAGE}" in output+ assert "Config validation error" not in output++ def test_config_nested_far_past_the_limit_is_refused_the_same_way(self, in_tmp, capsys):+ (in_tmp / "soup.yaml").write_text(_config_nested(20_000), encoding="utf-8")+ assert f"Config file soup.yaml {_NESTING_MESSAGE}" in _refused(capsys)++ def test_config_with_modest_alias_reuse_loads(self, in_tmp):+ (in_tmp / "soup.yaml").write_text(_WITH_MODEST_ALIASES, encoding="utf-8")+ config = load_config("soup.yaml")+ assert config.output == config.base == "meta-llama/Llama-3.1-8B-Instruct"++ def test_config_over_the_node_allowance_is_refused(self, in_tmp, capsys):+ text = _config_with_alias_fan_out(9)+ (in_tmp / "soup.yaml").write_bytes(text.encode())+ output = _refused(capsys)+ assert _expansion_message("Config file soup.yaml", text) in output+ assert "Config validation error" not in output++ def test_limits_are_checked_before_the_config_is_walked(self, in_tmp, capsys, monkeypatch):+ def _no_walk(*args, **kwargs):+ raise AssertionError("an over-limit config must not be walked")++ monkeypatch.setattr(loader, "find_unknown_config_keys", _no_walk)+ monkeypatch.setattr(loader, "_build_config", _no_walk)+ text = _config_with_alias_fan_out(9)+ (in_tmp / "soup.yaml").write_bytes(text.encode())+ assert _expansion_message("Config file soup.yaml", text) in _refused(capsys)++ def test_refusal_names_the_path_as_it_was_given(self, in_tmp, capsys):+ (in_tmp / "configs").mkdir()+ (in_tmp / "configs" / "run.yaml").write_text(+ _config_nested(MAX_YAML_NESTING + 1), encoding="utf-8"+ )+ output = _refused(capsys, in_tmp.joinpath("configs", "run.yaml").relative_to(in_tmp))+ assert "Config file configs" in output+ assert f"run.yaml {_NESTING_MESSAGE}" in output++ @pytest.mark.parametrize(+ "encode",+ [+ lambda text: text.encode(),+ lambda text: text.replace("\n", "\r\n").encode(),+ lambda text: b"\xef\xbb\xbf" + text.encode(),+ lambda text: b"\xef\xbb\xbf" + text.replace("\n", "\r\n").encode(),+ ],+ ids=["lf", "crlf", "bom", "bom-crlf"],+ )+ def test_line_ends_and_bom_load_the_same_config(self, in_tmp, encode):+ (in_tmp / "soup.yaml").write_bytes(encode(_VALID))+ assert load_config("soup.yaml") == load_config_from_string(_VALID)++ def test_non_ascii_utf8_config_loads(self, in_tmp):+ text = _VALID.replace("output: ./output\n", "output: ./sortie-été-☃\n")+ (in_tmp / "soup.yaml").write_bytes(text.encode("utf-8"))+ assert load_config("soup.yaml").output == "./sortie-été-☃"++ @pytest.mark.parametrize("text", ["", "\n\n", "# nothing but a comment\n"])+ def test_empty_config_keeps_its_message(self, in_tmp, capsys, text):+ (in_tmp / "soup.yaml").write_text(text, encoding="utf-8")+ assert _refused(capsys) == "Config file is empty"++ @pytest.mark.parametrize(+ ("text", "kind"), [("- a\n- b\n", "list"), ("just text\n", "str"), ("42\n", "int")]+ )+ def test_non_mapping_config_keeps_its_message(self, in_tmp, capsys, text, kind):+ (in_tmp / "soup.yaml").write_text(text, encoding="utf-8")+ assert _refused(capsys) == f"Config must be a YAML mapping, got {kind}"++ def test_unknown_key_refusal_is_unchanged(self, in_tmp, capsys):+ from soup_cli.config.unknown_keys import find_unknown_config_keys, format_unknown_keys++ text = _VALID + "trainning:\n epochs: 3\n"+ (in_tmp / "soup.yaml").write_text(text, encoding="utf-8")+ expected = format_unknown_keys(+ find_unknown_config_keys(yaml.safe_load(text)), include_deadline=False+ )+ assert _refused(capsys) == _plain(f"Config validation error: {expected}")++ def test_syntax_error_is_one_line_that_names_the_file_and_the_place(self, in_tmp, capsys):+ (in_tmp / "soup.yaml").write_text("base: [unclosed\ntask: }\n", encoding="utf-8")+ output = _refused(capsys)+ assert output == (+ "Config file soup.yaml is not valid YAML: "+ "expected ',' or ']', but got ':' (line 2, column 5)"+ )++ def test_bytes_that_are_not_utf8_are_one_line_that_names_the_file(self, in_tmp, capsys):+ (in_tmp / "soup.yaml").write_bytes(b"base: caf\xe9\n")+ assert _refused(capsys) == (+ "Config file soup.yaml is not valid UTF-8: invalid continuation byte at byte 9"+ )++ def test_a_directory_is_one_line_that_names_it(self, in_tmp, capsys):+ (in_tmp / "soup.yaml").mkdir()+ assert _refused(capsys) == "Config file soup.yaml is a directory, not a file"++ def test_a_date_that_does_not_exist_is_one_line_that_names_the_place(self, in_tmp, capsys):+ (in_tmp / "soup.yaml").write_text(_VALID + "extra: 2026-02-30\n", encoding="utf-8")+ assert _refused(capsys) == (+ "Config file soup.yaml is not valid YAML: cannot build this value: "+ "day is out of range for month (line 12, column 8)"+ )++ @pytest.mark.skipif(+ not hasattr(sys, "get_int_max_str_digits"), reason="no integer digit limit here"+ )+ def test_a_number_too_long_to_build_is_one_line_that_names_the_place(self, in_tmp, capsys):+ text = _VALID + "extra: " + "7" * 5000 + "\n"+ (in_tmp / "soup.yaml").write_text(text, encoding="utf-8")+ output = _refused(capsys)+ assert output.startswith(+ "Config file soup.yaml is not valid YAML: cannot build this value: "+ )+ assert output.endswith("(line 12, column 8)")++ @pytest.mark.parametrize(+ "line",+ [+ "base: *" + "a" * 5000,+ "base: !" + "t" * 5000 + " x",+ "base: [" + "x" * 5000 + "\ntask: }",+ ],+ ids=["alias-name", "tag-name", "flow-text"],+ )+ def test_text_quoted_from_the_file_is_cut_to_two_hundred_characters(self, in_tmp, capsys, line):+ (in_tmp / "soup.yaml").write_text(line + "\n", encoding="utf-8")+ output = _refused(capsys)+ prefix = "Config file soup.yaml is not valid YAML: "+ assert output.startswith(prefix)+ detail, _, place = output[len(prefix):].rpartition(" (line ")+ assert place.endswith(")") and "column" in place+ # Rich wraps the long word, so count it without the breaks.+ assert len(detail.replace(" ", "")) <= loader._MAX_DETAIL_CHARS + 3+ assert len(output) < 300++ @pytest.mark.parametrize(+ ("scalar", "name"),+ [("!!bool foo", "bool"), ("!!timestamp foo", "timestamp"), ('!!int ""', "int")],+ )+ def test_text_an_explicit_tag_cannot_convert_is_one_line_too(+ self, in_tmp, capsys, scalar, name+ ):+ (in_tmp / "soup.yaml").write_text(_VALID + f"extra: {scalar}\n", encoding="utf-8")+ assert _refused(capsys) == (+ "Config file soup.yaml is not valid YAML: cannot build this value: "+ f"not a valid {name} (line 12, column 8)"+ )++ def test_a_long_detail_ends_with_an_ellipsis_and_a_short_one_does_not(self):+ assert loader._MAX_DETAIL_CHARS == 200+ assert loader._clip("a b\n c") == "a b c"+ assert loader._clip("x" * 200) == "x" * 200+ assert loader._clip("x" * 201) == "x" * 200 + "..."++ def test_a_file_the_system_will_not_open_is_one_line_with_the_reason(+ self, in_tmp, capsys, monkeypatch+ ):+ def _denied(path, what, *, max_bytes):+ raise PermissionError(13, "Permission denied", str(path))++ monkeypatch.setattr(loader, "load_yaml_file_limited", _denied)+ assert _refused(capsys) == "Config file soup.yaml cannot be read: Permission denied"++ def test_an_error_that_is_not_about_the_file_is_passed_on_as_itself(self, in_tmp, monkeypatch):+ def _broken(path, what, *, max_bytes):+ raise ValueError("an internal mistake")++ monkeypatch.setattr(loader, "load_yaml_file_limited", _broken)+ with pytest.raises(ValueError, match="^an internal mistake$"):+ load_config("soup.yaml")++ def test_a_path_with_control_characters_and_markup_is_printed_escaped(+ self, capsys, monkeypatch+ ):+ def _over(path, what, *, max_bytes):+ raise YamlLimitError(f"{what} is larger than {max_bytes} bytes; refusing")++ monkeypatch.setattr(loader, "load_yaml_file_limited", _over)+ with pytest.raises(SystemExit):+ load_config("run\x1b[31m\x07[bold]x.yaml")+ printed = capsys.readouterr().out+ # Rich may add colour codes of its own, so compare the text without them: the+ # escape typed in the path is gone, what followed it is text, the tag is literal.+ assert "\x07" not in printed+ assert _plain(printed) == (+ f"Config file run[31m[bold]x.yaml is larger than {MAX_CONFIG_BYTES} bytes; refusing"+ )++ def test_missing_config_is_still_file_not_found(self, in_tmp):+ with pytest.raises(FileNotFoundError):+ load_config("absent.yaml")++ @pytest.mark.parametrize(+ ("content", "error"),+ [+ (b"base: [unclosed\ntask: }\n", yaml.YAMLError),+ (b"base: caf\xe9\n", UnicodeDecodeError),+ (b"extra: 2026-02-30\n", yaml.YAMLError),+ (b"#" + b"x" * MAX_CONFIG_BYTES, YamlLimitError),+ (("deep: " + "[" * MAX_YAML_NESTING + "]" * MAX_YAML_NESTING).encode(), YamlLimitError),+ ],+ ids=["syntax", "not-utf8", "date", "size", "nesting"],+ )+ def test_a_caller_that_asks_gets_the_exception_and_no_output(+ self, in_tmp, capsys, content, error+ ):+ (in_tmp / "soup.yaml").write_bytes(content)+ with pytest.raises(error):+ load_config("soup.yaml", raise_unreadable=True)+ captured = capsys.readouterr()+ assert captured.out == captured.err == ""++ def test_a_caller_that_asks_gets_the_os_error_for_a_directory(self, in_tmp, capsys):+ (in_tmp / "soup.yaml").mkdir()+ with pytest.raises(OSError):+ load_config("soup.yaml", raise_unreadable=True)+ assert capsys.readouterr().out == ""++ def test_asking_changes_nothing_for_a_config_that_reads(self, in_tmp, capsys):+ (in_tmp / "soup.yaml").write_text(_VALID, encoding="utf-8")+ assert load_config("soup.yaml", raise_unreadable=True) == load_config("soup.yaml")+ (in_tmp / "soup.yaml").write_text(_VALID + "trainning: {}\n", encoding="utf-8")+ with pytest.raises(SystemExit):+ load_config("soup.yaml", raise_unreadable=True)+ assert "Config validation error" in _plain(capsys.readouterr().out)++ def test_find_lr_words_an_unreadable_config_in_its_own_sentence(self, in_tmp):+ """It quotes the reason itself, so the loader hands the exception over."""+ from soup_cli.cli import app++ (in_tmp / "soup.yaml").write_text("base: m\ndata: [unclosed\n", encoding="utf-8")+ result = CliRunner().invoke(app, ["train", "--config", "soup.yaml", "--find-lr"])+ output = _plain(result.output)+ assert result.exit_code == 1, (result.output, repr(result.exception))+ assert "--find-lr: config load failed (while parsing a flow sequence" in output, output+ assert "data: [unclosed" in output, output+ assert "is not valid YAML" not in output, output++ @pytest.mark.parametrize(+ ("argv", "code", "also"),+ [+ (["bench", "train", "--config", "soup.yaml", "--steps", "4", "--warmup", "1"], 1, ""),+ (["doctor", "--config", "soup.yaml"], 2, "Config could not be loaded (see above)."),+ ],+ ids=["bench-train", "doctor"],+ )+ def test_a_command_that_calls_the_loader_plainly_shows_its_line_and_keeps_its_exit_code(+ self, in_tmp, argv, code, also+ ):+ from soup_cli.cli import app++ (in_tmp / "soup.yaml").write_text("base: m\ndata: [unclosed\n", encoding="utf-8")+ result = CliRunner().invoke(app, argv)+ output = _plain(result.output)+ assert result.exit_code == code, (result.output, repr(result.exception))+ assert "Config file soup.yaml is not valid YAML: expected ',' or ']'" in output, output+ assert "(line 3, column 1)" in output, output+ assert also in output, output+ assert "Traceback" not in output++ def test_training_overrides_still_reach_the_config(self, in_tmp):+ (in_tmp / "soup.yaml").write_text(_VALID, encoding="utf-8")+ assert load_config("soup.yaml", training_overrides={"epochs": 7}).training.epochs == 7+++# ---------------------------------------------------------------------------+# load_config_from_string: text from the API / UI, ValueError only+# ---------------------------------------------------------------------------+++class TestConfigText:+ def test_text_exactly_at_the_size_limit_loads(self):+ config = load_config_from_string(_config_of_size(MAX_CONFIG_BYTES))+ assert config.base == "meta-llama/Llama-3.1-8B-Instruct"++ def test_text_one_byte_over_the_size_limit_is_refused(self):+ with pytest.raises(YamlLimitError, match=rf"^Config {re.escape(_SIZE_MESSAGE)}$"):+ load_config_from_string(_config_of_size(MAX_CONFIG_BYTES + 1))++ def test_text_nested_to_the_limit_is_not_refused_for_nesting(self):+ with pytest.raises(ValueError, match="extra") as raised:+ load_config_from_string(_config_nested(MAX_YAML_NESTING))+ assert not isinstance(raised.value, YamlLimitError)++ def test_text_nested_one_level_past_the_limit_is_refused(self):+ with pytest.raises(YamlLimitError, match=rf"^Config {re.escape(_NESTING_MESSAGE)}$"):+ load_config_from_string(_config_nested(MAX_YAML_NESTING + 1))++ def test_text_nested_far_past_the_limit_is_a_value_error(self):+ """API and UI callers catch ValueError and nothing else."""+ with pytest.raises(ValueError, match=rf"^Config {re.escape(_NESTING_MESSAGE)}$"):+ load_config_from_string(_config_nested(20_000))++ def test_text_with_modest_alias_reuse_loads(self):+ config = load_config_from_string(_WITH_MODEST_ALIASES)+ assert config.output == config.base++ def test_text_over_the_node_allowance_is_refused(self):+ text = _config_with_alias_fan_out(9)+ with pytest.raises(YamlLimitError) as raised:+ load_config_from_string(text)+ assert str(raised.value) == _expansion_message("Config", text)++ def test_limits_are_checked_before_the_config_is_walked(self, monkeypatch):+ def _no_walk(*args, **kwargs):+ raise AssertionError("an over-limit config must not be walked")++ monkeypatch.setattr(loader, "find_unknown_config_keys", _no_walk)+ monkeypatch.setattr(loader, "_build_config", _no_walk)+ with pytest.raises(YamlLimitError, match="Config expands to more than"):+ load_config_from_string(_config_with_alias_fan_out(9))++ @pytest.mark.parametrize("text", ["", "\n", "# nothing but a comment\n"])+ def test_empty_text_keeps_its_message(self, text):+ with pytest.raises(ValueError, match=r"^Config is empty$"):+ load_config_from_string(text)++ def test_non_mapping_text_keeps_its_message(self):+ with pytest.raises(ValueError, match=r"^Config must be a YAML mapping, got list$"):+ load_config_from_string("- a\n- b\n")++ def test_syntax_error_is_still_a_yaml_error(self):+ with pytest.raises(yaml.YAMLError):+ load_config_from_string("base: [unclosed\ntask: }\n")++ def test_a_date_that_does_not_exist_is_still_a_value_error(self):+ with pytest.raises(ValueError, match="cannot build this value: day is out of range"):+ load_config_from_string(_VALID + "extra: 2026-02-30\n")+++class TestCallerWithItsOwnSizeLimit:+ def test_text_api_takes_the_callers_limit(self):+ text = _config_of_size(4096)+ assert load_config_from_string(text, max_bytes=4096).task == "sft"+ with pytest.raises(YamlLimitError, match=r"^Config is larger than 4095 bytes; refusing$"):+ load_config_from_string(text, max_bytes=4095)++ def test_ship_accepts_two_mebibytes_and_train_refuses_them(self, in_tmp):+ from soup_cli.cli import app+ from soup_cli.commands import ship++ assert ship._MAX_CONFIG_BYTES == 4 * 1024 * 1024+ (in_tmp / "soup.yaml").write_bytes(_config_of_size(2 * 1024 * 1024).encode())+ config, _ = ship._parse_ship_config("soup.yaml")+ assert config.base == "meta-llama/Llama-3.1-8B-Instruct"+ result = CliRunner().invoke(app, ["train", "--config", "soup.yaml", "--dry-run"])+ assert result.exit_code == 1, (result.output, repr(result.exception))+ assert f"Config file soup.yaml {_SIZE_MESSAGE}" in _plain(result.output)++ def test_ship_refuses_a_config_over_its_own_limit(self, in_tmp):+ import click++ from soup_cli.commands import ship++ (in_tmp / "soup.yaml").write_bytes(b"#" + b"x" * ship._MAX_CONFIG_BYTES)+ with pytest.raises(click.exceptions.Exit):+ ship._parse_ship_config("soup.yaml")++ def test_recipes_verify_reads_no_further_than_the_limit(self, in_tmp, capsys):+ import click++ from soup_cli.commands.recipes import _configs_to_verify++ (in_tmp / "soup.yaml").write_bytes(_config_of_size(MAX_CONFIG_BYTES + 1).encode())+ with pytest.raises(click.exceptions.Exit):+ _configs_to_verify("soup.yaml", False)+ captured = capsys.readouterr()+ assert f"Config file soup.yaml {_SIZE_MESSAGE}" in _plain(captured.out + captured.err)++ def test_adapters_audit_reads_no_further_than_the_limit(self, in_tmp):+ from soup_cli.cli import app++ (in_tmp / "adapter").mkdir()+ (in_tmp / "adapter" / "adapter_config.json").write_text("{}", encoding="utf-8")+ (in_tmp / "soup.yaml").write_bytes(_config_of_size(MAX_CONFIG_BYTES + 1).encode())+ result = CliRunner().invoke(app, ["adapters", "audit", "adapter", "--config", "soup.yaml"])+ assert result.exit_code == 1, (result.output, repr(result.exception))+ assert f"Config file soup.yaml {_SIZE_MESSAGE}" in _plain(result.output)+++# ---------------------------------------------------------------------------+# Commands that take --config print the refusal and exit 1+# ---------------------------------------------------------------------------+++_COMMANDS = [+ ["train", "--config", "soup.yaml", "--dry-run"],+ ["cost", "--config", "soup.yaml"],+ ["profile", "--config", "soup.yaml"],+]++_OVER_LIMIT = {+ "size": (lambda: _config_of_size(MAX_CONFIG_BYTES + 1), lambda text: _SIZE_MESSAGE),+ "nesting": (lambda: _config_nested(MAX_YAML_NESTING + 1), lambda text: _NESTING_MESSAGE),+ "aliases": (+ lambda: _config_with_alias_fan_out(9),+ lambda text: _expansion_message("", text).strip(),+ ),+}++[email protected]("argv", _COMMANDS, ids=[argv[0] for argv in _COMMANDS])[email protected]("limit", sorted(_OVER_LIMIT))+def test_command_prints_the_refusal_and_exits_1(in_tmp, argv, limit):+ from soup_cli.cli import app++ make_text, make_message = _OVER_LIMIT[limit]+ text = make_text()+ (in_tmp / "soup.yaml").write_bytes(text.encode())++ result = CliRunner().invoke(app, argv)++ output = _plain(result.output)+ assert result.exit_code == 1, (result.output, repr(result.exception))+ assert isinstance(result.exception, SystemExit), repr(result.exception)+ assert f"Config file soup.yaml {make_message(text)}" in output+ assert "Traceback" not in output++[email protected]("argv", _COMMANDS, ids=[argv[0] for argv in _COMMANDS])+def test_command_still_loads_a_config_at_the_size_limit(in_tmp, argv):+ from soup_cli.cli import app++ (in_tmp / "soup.yaml").write_bytes(_config_of_size(MAX_CONFIG_BYTES).encode())+ result = CliRunner().invoke(app, argv)+ output = _plain(result.output)+ assert "is larger than" not in output, output+ assert "refusing" not in output, output+++# ---------------------------------------------------------------------------+# Callers that take config text and catch ValueError+# ---------------------------------------------------------------------------++[email protected]("limit", ["nesting", "aliases"])+def test_web_ui_reports_the_refusal_as_an_invalid_config(limit):+ pytest.importorskip("fastapi")+ from fastapi.testclient import TestClient++ from soup_cli.ui.app import create_app, get_auth_token++ make_text, make_message = _OVER_LIMIT[limit]+ text = make_text()+ with TestClient(create_app()) as client:+ response = client.post(+ "/api/config/validate",+ json={"yaml": text},+ headers={"Authorization": f"Bearer {get_auth_token()}"},+ )+ assert response.status_code == 200, response.text+ assert response.json() == {"valid": False, "error": f"Config {make_message(text)}"}++[email protected]("limit", ["nesting", "aliases"])+def test_mcp_reports_the_refusal_as_an_invalid_config(in_tmp, limit):+ from soup_cli.mcp_server import registry++ make_text, _ = _OVER_LIMIT[limit]+ (in_tmp / "soup.yaml").write_bytes(make_text().encode())+ with pytest.raises(registry.McpToolError, match=r"invalid config \(YamlLimitError\)"):+ registry._load_config_under_cwd("soup.yaml")+++# ---------------------------------------------------------------------------+# A path with control characters reaches the terminal without them+# ---------------------------------------------------------------------------++#: CSI (U+009B) and DEL fit in a file name everywhere; ESC does not on Windows,+#: where the file system refuses every character below U+0020.+_CONTROLS = "\x9b\x7f" + ("" if os.name == "nt" else "\x1b")+_ODD_NAME = "run" + "31m".join(_CONTROLS) + "Z.yaml"+++ "argv",+ [+ ["train", "--config", _ODD_NAME, "--find-lr"],+ ["train", "--config", _ODD_NAME, "--dry-run"],+ ["adapters", "audit", "adapter", "--config", _ODD_NAME],+ ["cost", "--config", _ODD_NAME],+ ],+ ids=["train-find-lr", "train", "adapters-audit", "cost"],+)+def test_a_refusal_that_quotes_an_odd_path_carries_no_control_character(in_tmp, argv):+ from soup_cli.cli import app++ (in_tmp / "adapter").mkdir()+ (in_tmp / "adapter" / "adapter_config.json").write_text("{}", encoding="utf-8")+ (in_tmp / _ODD_NAME).write_text(_config_nested(MAX_YAML_NESTING + 1), encoding="utf-8")++ result = CliRunner().invoke(app, argv)++ # Rich may colour the line; those codes are its own, so they are set aside first.+ shown = _ANSI_RE.sub("", result.output)+ assert result.exit_code == 1, (result.output, repr(result.exception))+ assert _NESTING_MESSAGE in _plain(result.output), result.output+ assert not [char for char in shown if char in "\x1b\x7f\x9b"], repr(shown)+++def test_a_missing_config_with_an_odd_path_is_named_without_control_characters(in_tmp):+ from soup_cli.cli import app++ result = CliRunner().invoke(app, ["train", "--config", _ODD_NAME, "--dry-run"])+ shown = _ANSI_RE.sub("", result.output)+ assert result.exit_code == 1, (result.output, repr(result.exception))+ assert "Config not found: run" in _plain(result.output), result.output+ assert not [char for char in shown if char in "\x1b\x7f\x9b"], repr(shown)+++def test_adapters_audit_shows_a_syntax_error_as_written(in_tmp):+ """The quoted line holds a bracket; it is text, not markup."""+ from soup_cli.cli import app++ (in_tmp / "adapter").mkdir()+ (in_tmp / "adapter" / "adapter_config.json").write_text("{}", encoding="utf-8")+ (in_tmp / "soup.yaml").write_text("base: m\ndata: [unclosed\n", encoding="utf-8")+ result = CliRunner().invoke(app, ["adapters", "audit", "adapter", "--config", "soup.yaml"])+ output = _plain(result.output)+ assert result.exit_code == 1, (result.output, repr(result.exception))+ assert "Could not parse soup.yaml: while parsing a flow sequence" in output, output+ assert "data: [unclosed" in output, output+++ ("content", "line_start", "line_rest"),+ [+ ("base: m\ndata: [unclosed\n", "Could not parse run", "while parsing a flow sequence"),+ ("#" * (MAX_CONFIG_BYTES + 1), "Could not load run", "is larger than"),+ ],+ ids=["syntax-error", "over-size"],+)+def test_adapters_audit_shows_an_odd_config_path_and_its_message_without_control_characters(+ in_tmp, content, line_start, line_rest+):+ """Both audit refusal lines quote the path; the size refusal quotes it in its message too."""+ from soup_cli.cli import app++ (in_tmp / "adapter").mkdir()+ (in_tmp / "adapter" / "adapter_config.json").write_text("{}", encoding="utf-8")+ (in_tmp / _ODD_NAME).write_text(content, encoding="utf-8")++ result = CliRunner().invoke(app, ["adapters", "audit", "adapter", "--config", _ODD_NAME])++ shown = _ANSI_RE.sub("", result.output)+ assert result.exit_code == 1, (result.output, repr(result.exception))+ assert line_start in _plain(result.output), result.output+ assert line_rest in _plain(result.output), result.output+ assert not [char for char in shown if char in "\x1b\x7f\x9b"], repr(shown)diff --git a/tests/test_issue897_ui_yaml_body_cap.py b/tests/test_issue897_ui_yaml_body_cap.pyindex 6d4cdcbd..1e69f0e2 100644--- a/tests/test_issue897_ui_yaml_body_cap.py+++ b/tests/test_issue897_ui_yaml_body_cap.py@@ -4,6 +4,7 @@ import asynciofrom collections.abc import Iteratorimport pytest+import yamlfrom soup_cli.recipes.catalog import RECIPES@@ -45,9 +46,12 @@ def test_oversized_yaml_request_is_413_before_safe_load(def fail_if_called(*args: object, **kwargs: object) -> None:nonlocal calledcalled = True- raise AssertionError("yaml.safe_load must not parse an oversized request")+ raise AssertionError("an oversized request must not reach the YAML parser")- monkeypatch.setattr(loader.yaml, "safe_load", fail_if_called)+ # The config loader parses through the limited loader; nothing else may+ # parse the body either.+ monkeypatch.setattr(loader, "load_yaml_limited", fail_if_called)+ monkeypatch.setattr(yaml, "safe_load", fail_if_called)client, headers = ui_clientresponse = client.post(endpoint, json=payload, headers=headers) # type: ignore[attr-defined]diff --git a/tests/test_yaml_expanded_limit.py b/tests/test_yaml_expanded_limit.pyindex 174421fe..0578613b 100644--- a/tests/test_yaml_expanded_limit.py+++ b/tests/test_yaml_expanded_limit.py@@ -3,6 +3,7 @@from __future__ import annotationsimport io+import reimport tarfileimport time@@ -11,6 +12,7 @@ import yamlfrom soup_cli.utils.yaml_limits import (ALIAS_EXPANSION_SLACK,+ MAX_YAML_NESTING,check_expanded_nodes,check_yaml_expanded_size,expanded_node_count,@@ -41,6 +43,8 @@ def _write_can(path: str, members: dict[str, str]) -> None:tf.addfile(info, io.BytesIO(payload))+_ANSI_RE = re.compile(r"\x1b\[[0-9;]*m")+_PLAIN_MANIFEST = ("can_format_version: 1\nname: n\nauthor: a\ncreated_at: '2026-01-01'\n""base_hash: x\n"@@ -216,6 +220,68 @@ def test_small_alias_manifest_still_loads(tmp_path, monkeypatch):assert manifest.attestations[0]["predicateType"] == "p"+def _nested_attestation(levels: int) -> str:+ """An attestation whose ``deep`` value brings the manifest to ``levels``."""+ inner = levels - 3 # the manifest mapping, the attestations list, the statement+ return "_type: t\npredicateType: p\ndeep: " + "[" * inner + "]" * inner + "\n"+++def _nested_config(levels: int) -> str:+ inner = levels - 1 # the root mapping is the first level+ return "deep: " + "[" * inner + "]" * inner + "\n"+++def test_manifest_nested_to_the_limit_loads(tmp_path, monkeypatch):+ monkeypatch.chdir(tmp_path)+ from soup_cli.cans.unpack import inspect_can++ body = _nested_attestation(MAX_YAML_NESTING)+ _write_can("n.can", {"manifest.yaml": _manifest_with_attestation(body)})+ assert inspect_can("n.can").attestations[0]["predicateType"] == "p"+++def test_manifest_nested_one_level_past_the_limit_is_refused(tmp_path, monkeypatch):+ monkeypatch.chdir(tmp_path)+ from soup_cli.cans.unpack import inspect_can++ body = _nested_attestation(MAX_YAML_NESTING + 1)+ _write_can("n.can", {"manifest.yaml": _manifest_with_attestation(body)})+ with pytest.raises(+ ValueError,+ match=r"^manifest.yaml nests collections more than 100 levels deep; refusing$",+ ):+ inspect_can("n.can")+++def test_config_nested_to_the_limit_loads(tmp_path, monkeypatch):+ monkeypatch.chdir(tmp_path)+ from soup_cli.cans.unpack import read_config++ _write_can("c.can", {"config.yaml": _nested_config(MAX_YAML_NESTING)})+ assert list(read_config("c.can")) == ["deep"]+++def test_config_nested_one_level_past_the_limit_is_refused(tmp_path, monkeypatch):+ monkeypatch.chdir(tmp_path)+ from soup_cli.cans.unpack import read_config++ _write_can("c.can", {"config.yaml": _nested_config(MAX_YAML_NESTING + 1)})+ with pytest.raises(+ ValueError,+ match=r"^config.yaml nests collections more than 100 levels deep; refusing$",+ ):+ read_config("c.can")+++def test_can_member_nested_far_past_the_limit_is_refused_the_same_way(tmp_path, monkeypatch):+ monkeypatch.chdir(tmp_path)+ from soup_cli.cans.unpack import read_config++ _write_can("c.can", {"config.yaml": _nested_config(20_000)})+ with pytest.raises(ValueError, match="config.yaml nests collections more than 100"):+ read_config("c.can")++# ---------------------------------------------------------------------------# soup can run reads the config through the capped reader before anything else# ---------------------------------------------------------------------------@@ -281,3 +347,22 @@ def test_cli_run_yes_refuses_alias_amplified_config(tmp_path, monkeypatch):assert result.exit_code == 1, (result.output, repr(result.exception))assert "expands to more than" in " ".join(result.output.split())assert calls == []+++def test_cli_run_yes_refuses_config_nested_past_the_limit(tmp_path, monkeypatch):+ monkeypatch.chdir(tmp_path)+ from typer.testing import CliRunner++ from soup_cli.cli import app++ _, calls = _spawn_recorder(monkeypatch)+ members = {+ "manifest.yaml": _PLAIN_MANIFEST,+ "config.yaml": _nested_config(MAX_YAML_NESTING + 1),+ }+ _write_can("r.can", members)+ result = CliRunner().invoke(app, ["can", "run", "r.can", "--yes"])+ assert result.exit_code == 1, (result.output, repr(result.exception))+ output = " ".join(_ANSI_RE.sub("", result.output).split())+ assert "config.yaml nests collections more than 100 levels deep; refusing" in output+ assert calls == []diff --git a/tests/test_yaml_limits.py b/tests/test_yaml_limits.pynew file mode 100644index 00000000..c503ef6a--- /dev/null+++ b/tests/test_yaml_limits.py@@ -0,0 +1,664 @@+"""The limited YAML loader: one size, nesting and expansion rule for every reader."""++from __future__ import annotations++import json+import subprocess+import sys++import pytest+import yaml++from soup_cli.utils import yaml_limits+from soup_cli.utils.yaml_limits import (+ MAX_CONFIG_BYTES,+ MAX_YAML_NESTING,+ YamlLimitError,+ check_yaml_expanded_size,+ expanded_node_count,+ load_yaml_file_limited,+ load_yaml_limited,+)++# ---------------------------------------------------------------------------+# Documents named by the limit they sit under or cross+# ---------------------------------------------------------------------------+++def _flow_sequences(depth: int) -> str:+ return "[" * depth + "]" * depth+++def _flow_mappings(depth: int) -> str:+ return "{a: " * depth + "1" + "}" * depth+++def _block_sequences(depth: int) -> str:+ return "- " * depth + "x\n"+++def _block_mappings(depth: int) -> str:+ lines = [" " * level + "k:" for level in range(depth)]+ return "\n".join(lines) + " v\n"+++def _alternating(depth: int) -> str:+ """Mappings and sequences in turn: every collection counts as a level."""+ opened = "".join("[" if level % 2 else "{a: " for level in range(depth))+ closed = "".join("]" if level % 2 else "}" for level in reversed(range(depth)))+ return opened + ("" if depth % 2 == 0 else "1") + closed+++_NESTED_SPELLINGS = [+ _flow_sequences,+ _flow_mappings,+ _block_sequences,+ _block_mappings,+ _alternating,+]+++def _alias_chain(lists: int) -> str:+ """``lists`` single-item lists, each holding the one before it by alias.++ The text never nests more than two levels, but the loaded object nests+ ``lists + 1``: the root mapping plus every list in the chain.+ """+ doc = "l0: &a0 [x]\n"+ for index in range(1, lists):+ doc += f"l{index}: &a{index} [*a{index - 1}]\n"+ return doc+++def _alias_fan_out(levels: int) -> str:+ """Ten references per level: the node count grows tenfold with each one."""+ doc = "l0: &a0 [" + ", ".join(["x"] * 10) + "]\n"+ for index in range(1, levels + 1):+ doc += f"l{index}: &a{index} [" + ", ".join([f"*a{index - 1}"] * 10) + "]\n"+ return doc+++# ---------------------------------------------------------------------------+# Valid documents load exactly as yaml.safe_load loads them+# ---------------------------------------------------------------------------+++ "text",+ [+ "",+ "# only a comment\n",+ "a: 1\n",+ "- a\n- b\n",+ "plain scalar",+ "a: 2e-5\nb: 1e3\nc: 0x10\nd: 1_000\ne: yes\nf: ~\ng: 2026-01-01\n",+ "base: &b {r: 8, alpha: 16}\none:\n <<: *b\n r: 4\ntwo: *b\n",+ "text: |\n line one\n line two\n\nfolded: >-\n a\n b\n",+ 'q: "a\\tb"\ns: \'it\'\'s\'\n',+ "a: 1\n",+ "a: [1, [2, [3, {b: [4]}]]]\n",+ "name: café ☃\n",+ ],+)+def test_valid_document_loads_as_safe_load_does(text):+ assert load_yaml_limited(text, "doc", max_bytes=4096) == yaml.safe_load(text)+++def test_bytes_are_accepted_like_text():+ assert load_yaml_limited(b"a: [1, 2]\n", "doc", max_bytes=64) == {"a": [1, 2]}+++def test_anything_but_text_or_bytes_is_a_type_error():+ with pytest.raises(TypeError, match="doc must be str or bytes, got list"):+ load_yaml_limited(["a: 1"], "doc", max_bytes=64)+++def test_a_syntax_error_is_still_a_yaml_error():+ with pytest.raises(yaml.YAMLError):+ load_yaml_limited("a: [1, 2\nb: }", "doc", max_bytes=64)+++def test_every_refusal_is_a_value_error():+ assert issubclass(YamlLimitError, ValueError)+++# ---------------------------------------------------------------------------+# Size+# ---------------------------------------------------------------------------+++def test_text_exactly_at_the_size_limit_loads():+ text = "a: " + "x" * 61+ assert len(text.encode()) == 64+ assert load_yaml_limited(text, "doc", max_bytes=64) == {"a": "x" * 61}+++def test_text_one_byte_over_the_size_limit_is_refused():+ text = "a: " + "x" * 62+ assert len(text.encode()) == 65+ with pytest.raises(YamlLimitError, match=r"^doc is larger than 64 bytes; refusing$"):+ load_yaml_limited(text, "doc", max_bytes=64)+++def test_size_is_counted_in_bytes_not_characters():+ text = "a: " + "é" * 31 # 34 characters, 65 bytes+ assert len(text) == 34+ assert len(text.encode()) == 65+ with pytest.raises(YamlLimitError, match="doc is larger than 64 bytes"):+ load_yaml_limited(text, "doc", max_bytes=64)+ assert load_yaml_limited(text, "doc", max_bytes=65) == {"a": "é" * 31}+++def test_size_is_checked_before_anything_is_parsed(monkeypatch):+ def _no_parse(*args, **kwargs):+ raise AssertionError("an over-size document must not reach the parser")++ monkeypatch.setattr(yaml_limits, "_parse", _no_parse)+ with pytest.raises(YamlLimitError, match="is larger than 8 bytes"):+ load_yaml_limited("a: [1, 2, 3, 4]", "doc", max_bytes=8)+++def test_the_config_size_limit_is_one_mebibyte():+ assert MAX_CONFIG_BYTES == 1024 * 1024+++# ---------------------------------------------------------------------------+# Nesting+# ---------------------------------------------------------------------------+++def test_the_nesting_limit_is_one_hundred_levels():+ assert MAX_YAML_NESTING == 100++[email protected]("spelling", _NESTED_SPELLINGS)+def test_document_nested_exactly_to_the_limit_loads(spelling):+ text = spelling(MAX_YAML_NESTING)+ assert load_yaml_limited(text, "doc", max_bytes=10**6) == yaml.safe_load(text)++[email protected]("spelling", _NESTED_SPELLINGS)+def test_document_nested_one_level_past_the_limit_is_refused(spelling):+ text = spelling(MAX_YAML_NESTING + 1)+ with pytest.raises(+ YamlLimitError,+ match=r"^doc nests collections more than 100 levels deep; refusing$",+ ):+ load_yaml_limited(text, "doc", max_bytes=10**6)+++def test_sibling_collections_do_not_add_up_to_a_depth():+ text = "[" + ", ".join(["[[]]"] * 500) + "]"+ assert load_yaml_limited(text, "doc", max_bytes=8192) == [[[]]] * 500++[email protected]("spelling", [_flow_sequences, _block_sequences, _flow_mappings])+def test_document_nested_far_past_the_limit_gets_the_same_refusal(spelling):+ """Two hundred times the limit is refused exactly as one level past it."""+ text = spelling(20_000)+ with pytest.raises(YamlLimitError, match="doc nests collections more than 100 levels"):+ load_yaml_limited(text, "doc", max_bytes=1_000_000)+++def test_parsing_stops_at_the_limit_rather_than_after_the_document(monkeypatch):+ """The refusal comes from the event stream, before any object is built."""++ def _no_check(*args, **kwargs):+ raise AssertionError("an over-nested document must not be built first")++ monkeypatch.setattr(yaml_limits, "check_yaml_expanded_size", _no_check)+ with pytest.raises(YamlLimitError, match="nests collections more than 100 levels"):+ load_yaml_limited(_flow_sequences(MAX_YAML_NESTING + 1), "doc", max_bytes=4096)+++def test_nesting_reached_through_aliases_at_the_limit_loads():+ text = _alias_chain(MAX_YAML_NESTING - 1) # root mapping + 99 lists+ data = load_yaml_limited(text, "doc", max_bytes=10**6)+ assert data == yaml.safe_load(text)+++def test_nesting_reached_through_aliases_past_the_limit_is_refused():+ text = _alias_chain(MAX_YAML_NESTING) # root mapping + 100 lists+ with pytest.raises(YamlLimitError, match="doc nests collections more than 100 levels"):+ load_yaml_limited(text, "doc", max_bytes=10**6)+++def test_document_past_the_interpreter_limit_is_a_refusal_too(monkeypatch):+ """With the nesting limit lifted, the interpreter's own limit still ends as a refusal."""+ monkeypatch.setattr(yaml_limits, "MAX_YAML_NESTING", 10**9)+ with pytest.raises(+ YamlLimitError,+ match=r"^doc is nested or chained too deeply to load; refusing$",+ ):+ load_yaml_limited(_flow_sequences(5000), "doc", max_bytes=10**6)+++def test_document_rule_refuses_an_object_nested_past_the_limit():+ data: list = []+ for _ in range(MAX_YAML_NESTING):+ data = [data]+ with pytest.raises(YamlLimitError, match="doc nests collections more than 100 levels"):+ check_yaml_expanded_size(data, "doc", source_bytes=10**6)+++def test_document_rule_accepts_an_object_nested_to_the_limit():+ data: list = []+ for _ in range(MAX_YAML_NESTING - 1):+ data = [data]+ check_yaml_expanded_size(data, "doc", source_bytes=10**6)+++# ---------------------------------------------------------------------------+# The counter sees depth that only exists through shared references+# ---------------------------------------------------------------------------+++def test_counter_treats_a_shared_chain_past_its_depth_as_over_the_limit():+ data = yaml.safe_load(_alias_chain(1500))+ assert expanded_node_count(data, limit=10**9) == 10**9 + 1+++def test_counter_counts_a_shared_chain_within_its_depth_exactly():+ data = yaml.safe_load(_alias_chain(500))+ # Root: 1 + 500 keys. List k holds list k-1, so it expands to k + 2 nodes+ # (itself, the k lists inside it, and the one scalar at the bottom).+ assert expanded_node_count(data, limit=10**9) == 1 + 500 + sum(+ index + 2 for index in range(500)+ )+++# ---------------------------------------------------------------------------+# Expansion+# ---------------------------------------------------------------------------+++def test_modest_alias_reuse_loads():+ text = _alias_fan_out(2)+ assert load_yaml_limited(text, "doc", max_bytes=10**6) == yaml.safe_load(text)+++def test_alias_fan_out_past_the_node_allowance_is_refused():+ text = _alias_fan_out(9)+ allowance = len(text.encode()) + yaml_limits.ALIAS_EXPANSION_SLACK+ with pytest.raises(+ YamlLimitError,+ match=(+ rf"^doc expands to more than {allowance} nodes from "+ rf"{len(text.encode())} bytes of YAML; refusing$"+ ),+ ):+ load_yaml_limited(text, "doc", max_bytes=10**6)+++def test_self_referencing_alias_is_refused():+ with pytest.raises(YamlLimitError, match="doc expands to more than"):+ load_yaml_limited("a: &x [1, *x]\n", "doc", max_bytes=64)+++# ---------------------------------------------------------------------------+# Merge keys: the pairs they copy are charged to the node allowance as made+# ---------------------------------------------------------------------------+++def _merge_fan(copies: int, keys: int = 10) -> str:+ """One mapping of ``keys`` pairs merged ``copies`` times into another."""+ base = ", ".join(f"k{index}: {index}" for index in range(keys))+ return f"b: &b {{{base}}}\nm:\n <<: [" + ", ".join(["*b"] * copies) + "]\n"+++def _merge_ladder(steps: int) -> str:+ """Each mapping merges the one before it and adds a key of its own."""+ text = "m0: &m0 {k0: 0}\n"+ for index in range(1, steps + 1):+ text += f"m{index}: &m{index} {{<<: *m{index - 1}, k{index}: {index}}}\n"+ return text+++def _merge_chain(links: int) -> str:+ """The root merges the last of ``links`` mappings that each merge the one before."""+ text = "c0: &c0 {k: v}\n"+ for index in range(1, links):+ text += f"c{index}: &c{index} {{<<: *c{index - 1}}}\n"+ return text + f"<<: *c{links - 1}\n"+++def _allowance(text: str) -> int:+ return len(text.encode()) + yaml_limits.ALIAS_EXPANSION_SLACK+++ "text",+ [+ "a: &a {x: 1, y: 2}\nb:\n <<: *a\n y: 3\n",+ "a: &a {x: 1}\nb: &b {x: 2, y: 2}\nc:\n <<: [*a, *b]\n z: 3\n",+ "a: &a {x: 1}\nb: &b {<<: *a, y: 2}\nc: {<<: *b, z: 3}\n",+ "c:\n <<: {x: 1}\n <<: {x: 2, y: 2}\n",+ "c: {<<: {<<: {<<: {x: 1}, y: 2}, z: 3}}\n",+ "a: &a {}\nb: {<<: *a}\nc: {<<: []}\n",+ "c: {=: plain}\n",+ "a: &a {<<: *a, x: 1}\n",+ "a: &a {<<: [*a], x: 1}\n",+ "a: &a {x: 1, <<: *a, y: 2}\n",+ "a: &a {<<: *a, <<: *a, x: 1}\n",+ "a: &a {<<: *a}\n",+ "a: &a {x: 1}\nb: &b {<<: [*a, *b], y: 2}\n",+ "a: &a {x: 1}\nb: &b {y: 2, <<: [*b, *a], <<: *b}\n",+ "? ab\n: 1\n",+ ],+)+def test_merge_keys_load_as_safe_load_loads_them(text):+ assert load_yaml_limited(text, "doc", max_bytes=4096) == yaml.safe_load(text)+++ "text",+ ["a: {<<: 1}\n", "a: &a {x: 1}\nb: {<<: [*a, 2, 3]}\n", "b: {<<: [[1]]}\n"],+)+def test_a_merge_of_something_else_is_the_same_yaml_error(text):+ with pytest.raises(yaml.YAMLError) as expected:+ yaml.safe_load(text)+ with pytest.raises(yaml.YAMLError) as raised:+ load_yaml_limited(text, "doc", max_bytes=4096)+ assert type(raised.value) is type(expected.value)+ assert str(raised.value) == str(expected.value)+++def _copies_at_the_allowance(keys: int) -> int:+ """The most copies whose merged pairs (two nodes each) fit the allowance."""+ copies = 1+ while 2 * (copies + 1) * keys <= _allowance(_merge_fan(copies + 1, keys)):+ copies += 1+ return copies+++def _merge_fan_of_size(copies: int, keys: int, size: int) -> str:+ """``_merge_fan`` padded with a trailing comment to exactly ``size`` bytes."""+ text = _merge_fan(copies, keys)+ padding = size - len(text.encode())+ assert padding >= 2, padding+ text += "#" + "x" * (padding - 2) + "\n"+ assert len(text.encode()) == size+ return text+++#: 700 copies of a 10-pair mapping: 14,000 merged nodes (two per pair).+_COPIES, _KEYS = 700, 10+_MERGED = 2 * _COPIES * _KEYS+++def test_merged_nodes_equal_to_the_allowance_load():+ size = _MERGED - yaml_limits.ALIAS_EXPANSION_SLACK+ text = _merge_fan_of_size(_COPIES, _KEYS, size)+ assert _allowance(text) == _MERGED+ assert load_yaml_limited(text, "doc", max_bytes=10**6) == yaml.safe_load(text)+++def test_merged_nodes_one_past_the_allowance_are_refused():+ size = _MERGED - yaml_limits.ALIAS_EXPANSION_SLACK - 1+ text = _merge_fan_of_size(_COPIES, _KEYS, size)+ assert _allowance(text) == _MERGED - 1+ with pytest.raises(YamlLimitError) as raised:+ load_yaml_limited(text, "doc", max_bytes=10**6)+ assert str(raised.value) == (+ f"doc expands to more than {_MERGED - 1} nodes from {size} bytes of YAML; refusing"+ )+++def test_merged_pairs_exactly_at_the_node_allowance_load():+ copies = _copies_at_the_allowance(10)+ text = _merge_fan(copies)+ assert _allowance(text) - 2 * copies * 10 < 20 # within one merged mapping of it+ assert load_yaml_limited(text, "doc", max_bytes=10**6) == yaml.safe_load(text)+++def test_merged_pairs_one_mapping_past_the_node_allowance_are_refused():+ text = _merge_fan(_copies_at_the_allowance(10) + 1)+ with pytest.raises(YamlLimitError) as raised:+ load_yaml_limited(text, "doc", max_bytes=10**6)+ assert str(raised.value) == (+ f"doc expands to more than {_allowance(text)} nodes from "+ f"{len(text.encode())} bytes of YAML; refusing"+ )+++ "text",+ [_merge_fan(5000, keys=50), _merge_ladder(1500)],+ ids=["fan", "ladder"],+)+def test_merging_stops_at_the_first_pair_past_the_allowance(text):+ """Counted on the loader itself: nothing is copied beyond one more mapping."""+ budget = _allowance(text)+ loader = yaml_limits._LimitedLoader(text, node_budget=budget)+ try:+ with pytest.raises(yaml_limits._MergeBudgetError):+ loader.get_single_data()+ assert budget < loader.merged_nodes <= budget + 2 * 1500+ finally:+ loader.dispose()+++def test_merge_ladder_past_the_allowance_is_refused_by_name():+ with pytest.raises(YamlLimitError, match="^doc expands to more than"):+ load_yaml_limited(_merge_ladder(1500), "doc", max_bytes=10**6)+++def test_merge_chain_at_the_limit_loads():+ text = _merge_chain(MAX_YAML_NESTING - 1)+ assert load_yaml_limited(text, "doc", max_bytes=10**6) == yaml.safe_load(text)++[email protected]("links", [MAX_YAML_NESTING, 20_000])+def test_merge_chain_past_the_limit_is_refused(links):+ with pytest.raises(+ YamlLimitError,+ match=r"^doc chains merge keys more than 100 levels deep; refusing$",+ ):+ load_yaml_limited(_merge_chain(links), "doc", max_bytes=10**6)+++def test_a_mapping_that_merges_itself_is_charged_like_any_merge():+ """It loads as safe_load loads it, and its own pairs count towards the allowance."""+ text = "a: &a {<<: *a, x: 1, y: 2}\n"+ loader = yaml_limits._LimitedLoader(text, node_budget=10)+ try:+ assert loader.get_single_data() == yaml.safe_load(text) == {"a": {"x": 1, "y": 2}}+ assert loader.merged_nodes == 4+ finally:+ loader.dispose()+++ ("text", "reason"),+ [+ ("d: 2026-02-30\n", "day is out of range for month"),+ ("when:\n - 2026-13-01\n", "month must be in 1..12"),+ ],+)+def test_a_scalar_that_cannot_be_built_is_a_yaml_error_and_a_value_error(text, reason):+ with pytest.raises(ValueError, match=reason):+ yaml.safe_load(text)+ with pytest.raises(yaml_limits.YamlScalarError) as raised:+ load_yaml_limited(text, "doc", max_bytes=64)+ assert isinstance(raised.value, yaml.YAMLError)+ assert isinstance(raised.value, ValueError)+ assert raised.value.problem == f"cannot build this value: {reason}"+ assert raised.value.problem_mark.line == text.count("\n") - 1+++_MEASURE = """+import json, sys, time, tracemalloc+from soup_cli.utils.yaml_limits import YamlLimitError, load_yaml_limited+base = ", ".join(f"k{i}: {i}" for i in range(2000))+text = "b: &b {" + base + "}\\nm:\\n <<: [" + ", ".join(["*b"] * 4000) + "]\\n"+tracemalloc.start()+started = time.perf_counter()+try:+ load_yaml_limited(text, "doc", max_bytes=10**6)+ outcome = "loaded"+except YamlLimitError as exc:+ outcome = str(exc)+print(json.dumps({"bytes": len(text), "outcome": outcome,+ "seconds": time.perf_counter() - started,+ "peak": tracemalloc.get_traced_memory()[1]}))+"""+++def test_refusal_of_a_large_merge_stays_small_in_memory():+ """Eight million pairs asked for by 40 KB of text; the refusal keeps to a few MB."""+ done = subprocess.run(+ [sys.executable, "-W", "ignore", "-c", _MEASURE],+ capture_output=True,+ text=True,+ timeout=180,+ check=True,+ )+ report = json.loads(done.stdout.strip().splitlines()[-1])+ assert report["bytes"] < 64 * 1024+ assert report["outcome"].startswith("doc expands to more than"), report+ assert report["peak"] < 32 * 1024 * 1024, report+++# ---------------------------------------------------------------------------+# Files+# ---------------------------------------------------------------------------+++def test_file_exactly_at_the_size_limit_loads(tmp_path):+ path = tmp_path / "f.yaml"+ path.write_bytes(b"a: " + b"x" * 61)+ assert load_yaml_file_limited(path, "f.yaml", max_bytes=64) == {"a": "x" * 61}+++def test_file_one_byte_over_the_size_limit_is_refused(tmp_path):+ path = tmp_path / "f.yaml"+ path.write_bytes(b"a: " + b"x" * 62)+ with pytest.raises(YamlLimitError, match=r"^f.yaml is larger than 64 bytes; refusing$"):+ load_yaml_file_limited(path, "f.yaml", max_bytes=64)+++def test_file_read_never_asks_for_more_than_one_byte_past_the_limit(tmp_path, monkeypatch):+ path = tmp_path / "f.yaml"+ path.write_bytes(b"x" * 10_000)+ requested: list = []+ real_open = open++ class _Recording:+ def __init__(self, handle):+ self._handle = handle++ def __enter__(self):+ return self++ def __exit__(self, *exc_info):+ self._handle.close()++ def read(self, size=-1):+ requested.append(size)+ return self._handle.read(size)++ def _open(file, mode="r", *args, **kwargs):+ assert mode == "rb"+ return _Recording(real_open(file, mode, *args, **kwargs))++ monkeypatch.setattr(yaml_limits, "open", _open, raising=False)+ with pytest.raises(YamlLimitError, match="is larger than 64 bytes"):+ load_yaml_file_limited(path, "f.yaml", max_bytes=64)+ assert requested == [65]+++def test_file_size_limit_counts_the_bytes_on_disk(tmp_path):+ """CRLF line ends count as two bytes even though they load as one."""+ path = tmp_path / "f.yaml"+ path.write_bytes(b"a: 1\r\n" * 11) # 66 bytes, 55 once newlines are translated+ with pytest.raises(YamlLimitError, match="is larger than 64 bytes"):+ load_yaml_file_limited(path, "f.yaml", max_bytes=64)+++ "content",+ [+ b"a: 1\nb: [x, y]\n",+ b"a: 1\r\nb: [x, y]\r\n",+ b"\xef\xbb\xbfa: 1\nb: [x, y]\n",+ b"\xef\xbb\xbfa: 1\r\nb: [x, y]\r\n",+ b"a: 1\rb: [x, y]\r",+ ],+ ids=["lf", "crlf", "bom", "bom-crlf", "cr"],+)+def test_file_line_ends_and_bom_load_the_same_document(tmp_path, content):+ path = tmp_path / "f.yaml"+ path.write_bytes(content)+ assert load_yaml_file_limited(path, "f.yaml", max_bytes=4096) == {"a": 1, "b": ["x", "y"]}+++ "content",+ [+ b"t: |\r\n one\r\n two\r\n\r\nf: >\r\n a\r\n b\r\n",+ b'q: "one\r\n two"\r\n',+ b"p: one\r\n two\r\n",+ "name: café ☃\r\n".encode(),+ ],+ ids=["block-scalars", "double-quoted", "plain-multiline", "non-ascii"],+)+def test_file_is_decoded_exactly_as_read_text_decodes_it(tmp_path, content):+ path = tmp_path / "f.yaml"+ path.write_bytes(content)+ expected = yaml.safe_load(path.read_text(encoding="utf-8"))+ assert load_yaml_file_limited(path, "f.yaml", max_bytes=4096) == expected+++def test_file_that_is_not_utf8_is_still_a_decode_error(tmp_path):+ path = tmp_path / "f.yaml"+ path.write_bytes(b"a: \xff\xfe\n")+ with pytest.raises(UnicodeDecodeError):+ load_yaml_file_limited(path, "f.yaml", max_bytes=4096)+++def test_missing_file_is_still_file_not_found(tmp_path):+ with pytest.raises(FileNotFoundError):+ load_yaml_file_limited(tmp_path / "absent.yaml", "absent.yaml", max_bytes=4096)+++def test_file_over_the_nesting_limit_is_refused_by_name(tmp_path):+ path = tmp_path / "f.yaml"+ path.write_text(_block_mappings(MAX_YAML_NESTING + 1), encoding="utf-8")+ with pytest.raises(YamlLimitError, match="f.yaml nests collections more than 100 levels"):+ load_yaml_file_limited(path, "f.yaml", max_bytes=10**6)+++def test_file_over_the_node_allowance_is_refused_by_name(tmp_path):+ path = tmp_path / "f.yaml"+ path.write_text(_alias_fan_out(9), encoding="utf-8")+ with pytest.raises(YamlLimitError, match="f.yaml expands to more than"):+ load_yaml_file_limited(path, "f.yaml", max_bytes=10**6)+++ ("text", "name", "raised_by_pyyaml"),+ [+ ("a: !!bool foo\n", "bool", KeyError),+ ("a: !!bool ''\n", "bool", KeyError),+ ("a: !!timestamp foo\n", "timestamp", AttributeError),+ ('a: !!int ""\n', "int", IndexError),+ ('a: !!float ""\n', "float", IndexError),+ ],+)+def test_text_an_explicit_tag_cannot_convert_is_the_same_scalar_error(+ text, name, raised_by_pyyaml+):+ with pytest.raises(raised_by_pyyaml):+ yaml.safe_load(text)+ with pytest.raises(yaml_limits.YamlScalarError) as raised:+ load_yaml_limited(text, "doc", max_bytes=64)+ assert raised.value.problem == f"cannot build this value: not a valid {name}"+ assert (raised.value.problem_mark.line, raised.value.problem_mark.column) == (0, 3)+++ "text",+ ["a: !!bool yes\n", "a: !!int '12'\n", "a: !!float '1.5'\n", "a: !!timestamp 2026-01-02\n"],+)+def test_text_an_explicit_tag_can_convert_loads_as_before(text):+ assert load_yaml_limited(text, "doc", max_bytes=64) == yaml.safe_load(text)diff --git a/tests/test_yaml_reads_are_limited.py b/tests/test_yaml_reads_are_limited.pynew file mode 100644index 00000000..48e02973--- /dev/null+++ b/tests/test_yaml_reads_are_limited.py@@ -0,0 +1,658 @@+"""Every YAML document read under ``src/soup_cli`` goes through the limited loader.++Two halves. The source scan keeps ``utils/yaml_limits.py`` the only module that+can parse YAML: no other module may hold PyYAML except to write YAML or to+catch its error class, and each one that does is listed here with exactly the+attributes it uses. The reader table then drives each existing reader with a+document past the node allowance and one past the nesting limit, and checks+that the refusal comes out in that reader's own contract.+"""++from __future__ import annotations++import ast+import re+from pathlib import Path++import pytest+from typer.testing import CliRunner++from soup_cli.utils.yaml_limits import MAX_YAML_NESTING, YamlLimitError++SRC = Path(__file__).resolve().parents[1] / "src" / "soup_cli"++#: The one module that parses YAML.+LOADER_MODULE = "utils/yaml_limits.py"++#: What another module may take from PyYAML: writing, and the error class.+_NOT_PARSING = frozenset({"safe_dump", "dump", "YAMLError"})++#: Every other module that imports PyYAML, with the attributes it uses. A new+#: entry needs one of ``_NOT_PARSING``; reading YAML goes through LOADER_MODULE.+YAML_USERS = {+ "autopilot/generate_config.py": ("safe_dump",),+ "cans/pack.py": ("safe_dump",),+ "commands/adapters.py": ("YAMLError",),+ "commands/deploy.py": ("YAMLError",),+ "commands/push.py": ("YAMLError",),+ "commands/ship.py": ("YAMLError",),+ "commands/spectrum.py": ("safe_dump",),+ "commands/sweep.py": ("YAMLError",),+ "config/loader.py": ("YAMLError",),+ "migrate/common.py": ("dump",),+ "ui/app.py": ("dump",),+ "utils/adapter_branch.py": ("safe_dump",),+ "utils/build_dag.py": ("YAMLError",),+ "utils/checklist_dsl.py": ("YAMLError",),+ "utils/compile_tools.py": ("safe_dump",),+ "utils/expectations.py": ("YAMLError",),+ "utils/iterative_dpo.py": ("safe_dump",),+ "utils/local_rl.py": ("safe_dump",),+ "utils/loop_stages.py": ("safe_dump",),+ "utils/mix_proxy.py": ("safe_dump",),+ "utils/onboarding.py": ("safe_dump",),+ "utils/ra_dit_run.py": ("safe_dump",),+ "utils/recipe_dag.py": ("YAMLError",),+}++_YAML_PACKAGES = ("yaml", "ruamel")+++def _is_yaml_package(name: object) -> bool:+ return isinstance(name, str) and name.split(".")[0] in _YAML_PACKAGES+++def _yaml_uses(source: str) -> tuple[set[str], list[tuple[int, str]]]:+ """``(attributes, problems)`` for one module's use of a YAML package.++ ``attributes`` are the ``yaml.<name>`` accesses made through a plain+ ``import yaml`` (or ``import yaml as y``). ``problems`` is every other way+ of reaching the package, each of which could hide a parse: a from-import, a+ submodule import, ``ruamel``, a dynamic import by literal name, and any use+ of the module object that is not an attribute access (``y = yaml``,+ ``getattr(yaml, ...)``, passing it on).+ """+ tree = ast.parse(source)+ names: set[str] = set()+ problems: list[tuple[int, str]] = []+ for node in ast.walk(tree):+ if isinstance(node, ast.Import):+ for alias in node.names:+ if alias.name == "yaml":+ names.add(alias.asname or "yaml")+ elif _is_yaml_package(alias.name):+ problems.append((node.lineno, f"import {alias.name}"))+ elif isinstance(node, ast.ImportFrom) and _is_yaml_package(node.module):+ problems.append((node.lineno, f"from {node.module} import ..."))+ elif isinstance(node, ast.Call):+ target = node.func+ called = target.attr if isinstance(target, ast.Attribute) else getattr(target, "id", "")+ literal = node.args[0].value if node.args and isinstance(+ node.args[0], ast.Constant+ ) else None+ if called in ("import_module", "__import__") and _is_yaml_package(literal):+ problems.append((node.lineno, f"{called}({literal!r})"))++ attributes: set[str] = set()+ through_attribute: set[int] = set()+ for node in ast.walk(tree):+ if (+ isinstance(node, ast.Attribute)+ and isinstance(node.value, ast.Name)+ and node.value.id in names+ ):+ attributes.add(node.attr)+ through_attribute.add(id(node.value))+ for node in ast.walk(tree):+ if isinstance(node, ast.Name) and node.id in names and id(node) not in through_attribute:+ problems.append((node.lineno, f"bare use of {node.id}"))+ return attributes, sorted(problems)+++ ("source", "attribute"),+ [+ ("import yaml\nx = yaml.safe_load(t)\n", "safe_load"),+ ("import yaml\nx = yaml.load(t, Loader=None)\n", "load"),+ ("import yaml as y\nx = y.safe_load(t)\n", "safe_load"),+ ("import yaml\nfor d in yaml.safe_load_all(t):\n pass\n", "safe_load_all"),+ ("import yaml\nx = yaml.full_load(t)\n", "full_load"),+ ("import yaml\nx = yaml.unsafe_load(t)\n", "unsafe_load"),+ ("import yaml\nx = yaml.compose(t)\n", "compose"),+ ("import yaml\nfor e in yaml.parse(t):\n pass\n", "parse"),+ ("import yaml\nfor e in yaml.scan(t):\n pass\n", "scan"),+ ("import yaml\nx = yaml.SafeLoader(t).get_single_data()\n", "SafeLoader"),+ ("def f(t):\n import yaml\n return yaml.safe_load(t)\n", "safe_load"),+ ("import yaml\nloader = yaml.safe_load\nx = loader(t)\n", "safe_load"),+ ],+)+def test_scan_reports_each_parsing_attribute(source, attribute):+ attributes, problems = _yaml_uses(source)+ assert attributes == {attribute}+ assert not attributes <= _NOT_PARSING+ assert problems == []+++ ("source", "problem"),+ [+ ("from yaml import safe_load\nx = safe_load(t)\n", "from yaml import ..."),+ ("from yaml import safe_load as sl\nx = sl(t)\n", "from yaml import ..."),+ ("from yaml import *\nx = safe_load(t)\n", "from yaml import ..."),+ ("from yaml import SafeLoader\n", "from yaml import ..."),+ ("from yaml.loader import SafeLoader\n", "from yaml.loader import ..."),+ ("import yaml.loader\n", "import yaml.loader"),+ ("import yaml\ny = yaml\nx = y.safe_load(t)\n", "bare use of yaml"),+ ('import yaml\nx = getattr(yaml, "safe_load")(t)\n', "bare use of yaml"),+ ("import yaml\nx = helper(yaml, t)\n", "bare use of yaml"),+ ('import importlib\ny = importlib.import_module("yaml")\n', "import_module('yaml')"),+ (+ 'from importlib import import_module\ny = import_module("yaml")\n',+ "import_module('yaml')",+ ),+ ('y = __import__("yaml")\n', "__import__('yaml')"),+ ('y = __import__("yaml.loader")\n', "__import__('yaml.loader')"),+ ("import ruamel.yaml\n", "import ruamel.yaml"),+ ("from ruamel.yaml import YAML\n", "from ruamel.yaml import ..."),+ (+ 'import importlib\ny = importlib.import_module("ruamel.yaml")\n',+ "import_module('ruamel.yaml')",+ ),+ ],+)+def test_scan_reports_each_other_way_of_reaching_a_yaml_package(source, problem):+ assert [found for _, found in _yaml_uses(source)[1]] == [problem]+++ "source",+ [+ "import yaml\ntext = yaml.safe_dump(data)\n",+ "import yaml\ntext = yaml.dump(data)\n",+ "import yaml\ntry:\n pass\nexcept yaml.YAMLError:\n pass\n",+ "import yaml\ntry:\n pass\nexcept (yaml.YAMLError, OSError):\n pass\n",+ ],+)+def test_scan_accepts_writing_yaml_and_catching_its_error(source):+ attributes, problems = _yaml_uses(source)+ assert attributes <= _NOT_PARSING+ assert problems == []+++ "source",+ [+ "import json\nx = json.load(fh)\n",+ "x = config.load(t)\n",+ 'overlay_yaml = "a: 1"\nsize = len(overlay_yaml.encode())\n',+ '"""Uses ``yaml.safe_load`` semantics."""\n',+ 'y = importlib.import_module("json")\n',+ "y = importlib.import_module(name)\n",+ ],+)+def test_scan_ignores_what_is_not_a_yaml_package(source):+ assert _yaml_uses(source) == (set(), [])+++def test_no_module_but_the_limited_loader_can_parse_yaml():+ files = sorted(SRC.rglob("*.py"))+ assert len(files) > 300, "the scan did not find the package"+ found: dict[str, tuple[str, ...]] = {}+ offenders: list[str] = []+ for file in files:+ rel = file.relative_to(SRC).as_posix()+ if rel == LOADER_MODULE:+ continue+ attributes, problems = _yaml_uses(file.read_text(encoding="utf-8"))+ offenders.extend(f"{rel}:{line} {problem}" for line, problem in problems)+ offenders.extend(+ f"{rel}: yaml.{name}" for name in sorted(attributes - _NOT_PARSING)+ )+ if attributes:+ found[rel] = tuple(sorted(attributes))+ assert offenders == [], (+ "read YAML with soup_cli.utils.yaml_limits.load_yaml_limited / "+ "load_yaml_file_limited instead:\n" + "\n".join(offenders)+ )+ assert found == YAML_USERS, "YAML_USERS must list each module with the attributes it uses"+++def test_the_limited_loader_is_where_the_scan_expects_it():+ attributes, _ = _yaml_uses((SRC / LOADER_MODULE).read_text(encoding="utf-8"))+ assert "SafeLoader" in attributes+++# ---------------------------------------------------------------------------+# Each reader, driven with a document past a limit+# ---------------------------------------------------------------------------+++def _alias_fan_out(levels: int = 9) -> str:+ """Lists that each reference the previous one ten times."""+ text = "l0: &a0 [" + ", ".join(["x"] * 10) + "]\n"+ for index in range(1, levels + 1):+ text += f"l{index}: &a{index} [" + ", ".join([f"*a{index - 1}"] * 10) + "]\n"+ return text+++def _nested_past_the_limit() -> str:+ inner = MAX_YAML_NESTING # plus the root mapping: one level past the limit+ return "deep: " + "[" * inner + "]" * inner + "\n"+++_OVER_LIMIT = {+ "node-allowance": (_alias_fan_out, "expands to more than"),+ "nesting": (+ _nested_past_the_limit,+ f"nests collections more than {MAX_YAML_NESTING} levels deep",+ ),+}+++def _write(name: str, text: str) -> str:+ Path(name).write_bytes(text.encode("utf-8")) # no newline translation+ return name+++def _plan(text):+ from soup_cli.commands.plan import _load_yaml_config++ return _load_yaml_config(_write("soup.yaml", text))+++def _gate_suite(text):+ from soup_cli.eval.gate import load_suite++ return load_suite(_write("gate.yaml", text))+++def _rubric(text):+ from soup_cli.eval.judge import load_rubric++ return load_rubric(Path(_write("rubric.yaml", text)))+++def _axolotl(text):+ from soup_cli.migrate.axolotl import migrate_axolotl++ return migrate_axolotl(Path(_write("ax.yaml", text)))+++def _llamafactory(text):+ from soup_cli.migrate.llamafactory import migrate_llamafactory++ return migrate_llamafactory(Path(_write("lf.yaml", text)))+++def _agent_spec(text):+ from soup_cli.utils.agent_forge import load_spec_file++ return load_spec_file(_write("spec.yaml", text))+++def _build(text):+ from soup_cli.utils.build_dag import parse_build_yaml++ return parse_build_yaml(text)+++def _expectations(text):+ from soup_cli.utils.expectations import parse_suite_yaml++ return parse_suite_yaml(text)+++def _recipe_dag(text):+ from soup_cli.utils.recipe_dag import parse_recipe_yaml++ return parse_recipe_yaml(text)+++def _checklist(text):+ from soup_cli.utils.checklist_dsl import load_checklist_spec++ return load_checklist_spec(_write("checklist.yaml", text))+++def _mix_recipe(text):+ from soup_cli.utils.data_mix import load_mix_recipe++ return load_mix_recipe(_write("recipe.yaml", text))+++def _mix_proxy(text):+ from soup_cli.utils.mix_proxy import _render_overlay_yaml++ return _render_overlay_yaml(text, ("a.jsonl",), (1.0,))+++def _ra_dit(text):+ from soup_cli.utils.ra_dit_run import _load_yaml_config++ return _load_yaml_config(_write("ra.yaml", text))+++def _quant_config(text):+ from soup_cli.utils.save_formats import load_quant_config++ return load_quant_config(_write("quant.yaml", text))+++def _sweep(text):+ from soup_cli.utils.sweep_config import parse_sweep_yaml++ return parse_sweep_yaml(text)+++#: reader id -> (driver, how the refusal names the document)+_RAISING_READERS = {+ "commands/plan.py": (_plan, "config 'soup.yaml'"),+ "eval/gate.py": (_gate_suite, "eval-gate suite 'gate.yaml'"),+ "eval/judge.py": (_rubric, "Rubric file rubric.yaml"),+ "migrate/axolotl.py": (_axolotl, "Config file ax.yaml"),+ "migrate/llamafactory.py": (_llamafactory, "Config file lf.yaml"),+ "utils/agent_forge.py": (_agent_spec, "spec file"),+ "utils/build_dag.py": (_build, "build text"),+ "utils/expectations.py": (_expectations, "suite text"),+ "utils/recipe_dag.py": (_recipe_dag, "recipe text"),+ "utils/checklist_dsl.py": (_checklist, "spec file"),+ "utils/data_mix.py": (_mix_recipe, "recipe"),+ "utils/mix_proxy.py": (_mix_proxy, "base YAML"),+ "utils/ra_dit_run.py": (_ra_dit, "config YAML"),+ "utils/save_formats.py": (_quant_config, "quant_config"),+ "utils/sweep_config.py": (_sweep, "sweep yaml"),+}++[email protected]("limit", sorted(_OVER_LIMIT))[email protected]("reader", sorted(_RAISING_READERS))+def test_reader_refuses_a_document_past_the_limit(tmp_path, monkeypatch, reader, limit):+ monkeypatch.chdir(tmp_path)+ drive, what = _RAISING_READERS[reader]+ make_text, message = _OVER_LIMIT[limit]+ with pytest.raises(YamlLimitError) as raised:+ drive(make_text())+ assert str(raised.value).startswith(f"{what} {message}"), str(raised.value)+++# Readers whose contract is a fallback value rather than an exception: each is+# shown returning the real value first, so the fallback is the refusal at work.++[email protected]("limit", sorted(_OVER_LIMIT))+def test_deploy_template_detection_falls_back_past_the_limit(tmp_path, monkeypatch, limit):+ from soup_cli.commands.deploy import _auto_detect_template++ monkeypatch.chdir(tmp_path)+ base = "data:\n format: chatml\n"+ _write("soup.yaml", base)+ assert _auto_detect_template() is not None+ _write("soup.yaml", base + _OVER_LIMIT[limit][0]())+ assert _auto_detect_template() is None++[email protected]("limit", sorted(_OVER_LIMIT))+def test_push_training_config_falls_back_past_the_limit(tmp_path, monkeypatch, limit):+ from soup_cli.commands.push import _load_training_config++ monkeypatch.chdir(tmp_path)+ base = "base: some/model\n"+ _write("training_config.yaml", base)+ assert _load_training_config(tmp_path) == {"base": "some/model"}+ _write("training_config.yaml", base + _OVER_LIMIT[limit][0]())+ assert _load_training_config(tmp_path) == {}++[email protected]("limit", sorted(_OVER_LIMIT))+def test_license_frontmatter_falls_back_past_the_limit(tmp_path, monkeypatch, limit):+ from soup_cli.utils.license_matrix import _license_from_frontmatter++ monkeypatch.chdir(tmp_path)+ readme = str(tmp_path / "README.md")+ _write("README.md", "---\nlicense: mit\n---\nbody\n")+ assert _license_from_frontmatter(readme) == "mit"+ _write("README.md", "---\nlicense: mit\n" + _OVER_LIMIT[limit][0]() + "---\nbody\n")+ assert _license_from_frontmatter(readme) is None+++def test_every_routed_reader_has_a_case():+ """The table above and the modules that import the limited loader agree."""+ importers = set()+ for path in sorted(SRC.rglob("*.py")):+ rel = path.relative_to(SRC).as_posix()+ if rel == LOADER_MODULE:+ continue+ text = path.read_text(encoding="utf-8")+ if any(name in text for name in _LIMITED_READS):+ importers.add(rel)+ covered_elsewhere = {+ "config/loader.py", # tests/test_config_loader_limits.py+ "cans/unpack.py", # tests/test_yaml_expanded_limit.py+ "commands/adapters.py", # tests/test_config_loader_limits.py+ "commands/recipes.py", # tests/test_config_loader_limits.py+ "commands/deploy.py",+ "commands/push.py",+ "utils/license_matrix.py",+ }+ assert importers == set(_RAISING_READERS) | covered_elsewhere+++# ---------------------------------------------------------------------------+# Each reader's own size cap: one byte over it is refused in that reader's words+# ---------------------------------------------------------------------------++_LIMITED_READS = ("load_yaml_limited", "load_yaml_file_limited", "read_text_limited")+++def _comment_of(size: int) -> str:+ """A YAML document that is one comment, exactly ``size`` bytes long."""+ return "#" + "x" * (size - 2) + "\n"+++def _cap(module: str, name: str) -> int:+ import importlib++ return getattr(importlib.import_module(f"soup_cli.{module}"), name)+++#: reader id -> (module, name of its cap, how it words a file one byte over the cap)+_READER_CAPS = {+ "commands/plan.py": (+ "utils.yaml_limits", "MAX_CONFIG_BYTES",+ "config 'soup.yaml' is larger than {cap} bytes; refusing",+ ),+ "eval/gate.py": (+ "utils.yaml_limits", "MAX_CONFIG_BYTES",+ "eval-gate suite 'gate.yaml' is larger than {cap} bytes; refusing",+ ),+ "eval/judge.py": (+ "utils.yaml_limits", "MAX_CONFIG_BYTES",+ "Rubric file rubric.yaml is larger than {cap} bytes; refusing",+ ),+ "migrate/axolotl.py": (+ "utils.yaml_limits", "MAX_CONFIG_BYTES",+ "Config file ax.yaml is larger than {cap} bytes; refusing",+ ),+ "migrate/llamafactory.py": (+ "utils.yaml_limits", "MAX_CONFIG_BYTES",+ "Config file lf.yaml is larger than {cap} bytes; refusing",+ ),+ "utils/agent_forge.py": (+ "utils.agent_forge", "_MAX_SPEC_BYTES", "spec file exceeds {cap} bytes",+ ),+ "utils/build_dag.py": ("utils.build_dag", "_MAX_FILE_BYTES", "build text exceeds {cap} bytes"),+ "utils/expectations.py": (+ "utils.expectations", "_MAX_FILE_BYTES", "suite text exceeds {cap} bytes",+ ),+ "utils/recipe_dag.py": (+ "utils.recipe_dag", "_MAX_FILE_BYTES", "recipe text exceeds {cap} bytes",+ ),+ "utils/checklist_dsl.py": (+ "utils.checklist_dsl", "_MAX_FILE_BYTES", "spec file too large ({over} > {cap})",+ ),+ "utils/data_mix.py": (+ "utils.data_mix", "_MAX_RECIPE_BYTES", "recipe exceeds {cap} bytes cap",+ ),+ "utils/mix_proxy.py": (+ "utils.yaml_limits", "MAX_CONFIG_BYTES",+ "base YAML is larger than {cap} bytes; refusing",+ ),+ "utils/ra_dit_run.py": (+ "utils.ra_dit_run", "_MAX_YAML_BYTES", "config YAML exceeds {kib}KB cap",+ ),+ "utils/save_formats.py": (+ "utils.save_formats", "_MAX_QUANT_CONFIG_BYTES",+ "quant_config too large ({over} bytes; cap {cap})",+ ),+ "utils/sweep_config.py": (+ "utils.sweep_config", "_MAX_FILE_BYTES", "sweep yaml exceeds {cap} bytes",+ ),+}++_SIZE_WORDS = re.compile(r"larger than|exceeds|too large")+++def test_every_raising_reader_has_a_cap_case():+ assert set(_READER_CAPS) == set(_RAISING_READERS)++[email protected]("reader", sorted(_READER_CAPS))+def test_reader_refuses_a_document_one_byte_over_its_cap(tmp_path, monkeypatch, reader):+ monkeypatch.chdir(tmp_path)+ module, name, wording = _READER_CAPS[reader]+ cap = _cap(module, name)+ expected = wording.format(cap=cap, over=cap + 1, kib=cap // 1024)+ with pytest.raises(ValueError) as raised:+ _RAISING_READERS[reader][0](_comment_of(cap + 1))+ assert expected in str(raised.value), str(raised.value)++[email protected]("reader", sorted(_READER_CAPS))+def test_reader_does_not_refuse_a_document_exactly_at_its_cap_for_size(+ tmp_path, monkeypatch, reader+):+ monkeypatch.chdir(tmp_path)+ module, name, _ = _READER_CAPS[reader]+ try:+ _RAISING_READERS[reader][0](_comment_of(_cap(module, name)))+ except (ValueError, TypeError) as exc: # an empty document is not a valid one+ assert not _SIZE_WORDS.search(str(exc)), str(exc)+++def test_deploy_template_detection_falls_back_one_byte_over_its_cap(tmp_path, monkeypatch):+ from soup_cli.commands.deploy import _auto_detect_template+ from soup_cli.utils.yaml_limits import MAX_CONFIG_BYTES++ monkeypatch.chdir(tmp_path)+ base = "data:\n format: chatml\n"+ _write("soup.yaml", base + _comment_of(MAX_CONFIG_BYTES - len(base)))+ assert _auto_detect_template() is not None+ _write("soup.yaml", base + _comment_of(MAX_CONFIG_BYTES - len(base) + 1))+ assert _auto_detect_template() is None+++def test_push_training_config_falls_back_one_byte_over_its_cap(tmp_path, monkeypatch):+ from soup_cli.commands.push import _load_training_config+ from soup_cli.utils.yaml_limits import MAX_CONFIG_BYTES++ monkeypatch.chdir(tmp_path)+ base = "base: some/model\n"+ _write("training_config.yaml", base + _comment_of(MAX_CONFIG_BYTES - len(base)))+ assert _load_training_config(tmp_path) == {"base": "some/model"}+ _write("training_config.yaml", base + _comment_of(MAX_CONFIG_BYTES - len(base) + 1))+ assert _load_training_config(tmp_path) == {}+++def test_license_frontmatter_falls_back_one_byte_over_its_cap(tmp_path, monkeypatch):+ from soup_cli.utils import license_matrix++ monkeypatch.chdir(tmp_path)+ cap = license_matrix._MAX_FRONTMATTER_BYTES+ readme = str(tmp_path / "README.md")+ head, tail = "---\nlicense: mit\n", "---\nbody\n"+ _write("README.md", head + _comment_of(cap - len(head) - len(tail)) + tail)+ assert license_matrix._license_from_frontmatter(readme) == "mit"+ _write("README.md", head + _comment_of(cap - len(head) - len(tail) + 1) + tail)+ assert license_matrix._license_from_frontmatter(readme) is None+++#: Every call of the limited loader names its cap: a module constant, never a number.+_CAP_NAMES = {+ "cans/unpack.py": {"MAX_CONFIG_BYTES", "MAX_MANIFEST_BYTES"},+ "commands/adapters.py": {"MAX_CONFIG_BYTES"},+ "commands/deploy.py": {"MAX_CONFIG_BYTES"},+ "commands/plan.py": {"MAX_CONFIG_BYTES"},+ "commands/push.py": {"MAX_CONFIG_BYTES"},+ "commands/recipes.py": {"MAX_CONFIG_BYTES"},+ "config/loader.py": {"MAX_CONFIG_BYTES", "limit"},+ "eval/gate.py": {"MAX_CONFIG_BYTES"},+ "eval/judge.py": {"MAX_CONFIG_BYTES"},+ "migrate/axolotl.py": {"MAX_CONFIG_BYTES"},+ "migrate/llamafactory.py": {"MAX_CONFIG_BYTES"},+ "utils/agent_forge.py": {"_MAX_SPEC_BYTES"},+ "utils/build_dag.py": {"_MAX_FILE_BYTES"},+ "utils/checklist_dsl.py": {"_MAX_FILE_BYTES"},+ "utils/data_mix.py": {"_MAX_RECIPE_BYTES"},+ "utils/expectations.py": {"_MAX_FILE_BYTES"},+ "utils/license_matrix.py": {"_MAX_FRONTMATTER_BYTES"},+ "utils/mix_proxy.py": {"MAX_CONFIG_BYTES"},+ "utils/ra_dit_run.py": {"_MAX_YAML_BYTES"},+ "utils/recipe_dag.py": {"_MAX_FILE_BYTES"},+ "utils/save_formats.py": {"_MAX_QUANT_CONFIG_BYTES"},+ "utils/sweep_config.py": {"_MAX_FILE_BYTES"},+}+++def test_every_limited_read_names_its_cap():+ found: dict[str, set[str]] = {}+ for file in sorted(SRC.rglob("*.py")):+ rel = file.relative_to(SRC).as_posix()+ if rel == LOADER_MODULE:+ continue+ for node in ast.walk(ast.parse(file.read_text(encoding="utf-8"))):+ if not isinstance(node, ast.Call):+ continue+ called = getattr(node.func, "attr", None) or getattr(node.func, "id", None)+ if called not in _LIMITED_READS:+ continue+ caps = [keyword.value for keyword in node.keywords if keyword.arg == "max_bytes"]+ assert len(caps) == 1, f"{rel}:{node.lineno} must pass max_bytes by keyword"+ assert isinstance(caps[0], ast.Name), f"{rel}:{node.lineno} max_bytes must be a name"+ found.setdefault(rel, set()).add(caps[0].id)+ assert found == _CAP_NAMES+++# ---------------------------------------------------------------------------+# A reader's message quotes the path it was given: it is printed escaped+# ---------------------------------------------------------------------------++_ANSI_RE = re.compile(r"\x1b\[[0-9;]*m")+_MARKED = "[bold]x.yaml" # an opening tag Rich would otherwise consume++_VALID_CONFIG = (+ "base: meta-llama/Llama-3.1-8B-Instruct\ntask: sft\n"+ "data:\n train: ./data.jsonl\n format: alpaca\noutput: ./output\n"+)+++ "argv",+ [+ ["eval", "gate", "--suite", _MARKED],+ ["eval", "judge", "--rubric", _MARKED, "--target", "t.jsonl", "--model", "m"],+ ["train", "--config", "soup.yaml", "--gate", _MARKED, "--dry-run"],+ ["export", "--model", "./merged", "--format", "torchao", "--quant-config", _MARKED],+ ],+ ids=["eval-gate", "eval-judge", "train-gate", "export-quant-config"],+)+def test_command_prints_a_path_with_markup_as_typed(tmp_path, monkeypatch, argv):+ from soup_cli.cli import app++ monkeypatch.chdir(tmp_path)+ _write("soup.yaml", _VALID_CONFIG)+ _write("t.jsonl", '{"prompt": "p", "response": "r"}\n')+ Path("merged").mkdir()+ result = CliRunner().invoke(app, argv)+ output = " ".join(_ANSI_RE.sub("", result.output).split())+ assert result.exit_code != 0, output+ assert _MARKED in output, (output, repr(result.exception))