Skip to content

armgit / Soup

Public Imported from GitHub
0

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

docs: every documented soup invocation names a real command path and real flags, and a guard keeps it so (#1465) (#1578)

Srinivasan R730b13a98d4d
diff --git a/README.ar.md b/README.ar.md
index 79b5df5e..d2e6f320 100644
--- a/README.ar.md
+++ b/README.ar.md
@@ -1,4 +1,4 @@
-<!-- synced-from: README.md sha256:2c81448b707086960939bd1512e493ea4a0248aac5d073ad388f6260c1352537 -->
+<!-- synced-from: README.md sha256:ad8f9dd91ca5fd56ff6bda0b6b1c1efe26b4ab7e464bbf5bb8dca4faab55b810 -->
<p align="center">🌍 <a href="README.md">English</a> | <a href="README.tr.md">Türkçe</a> | <strong>العربية</strong> | <a href="README.ja.md">日本語</a></p>
<p align="center">
@@ -283,7 +283,7 @@ Alpaca وShareGPT وChatML وأزواج التفضيلات (DPO / ORPO / SimPO /
```bash
soup train --config soup.yaml # درّب (SFT/DPO/GRPO/PPO/KTO/ORPO/SimPO/IPO/...)
-soup infer --model ./output --input prompts.jsonl # استدلال دُفعي
+soup infer --model ./output --input prompts.jsonl --output results.jsonl # استدلال دُفعي
soup chat --model ./output # دردشة تفاعلية
soup serve --model ./output # خادم API متوافق مع OpenAI
soup ui # لوحة متصفح محلية
diff --git a/README.ja.md b/README.ja.md
index 4225ddfc..6313a73f 100644
--- a/README.ja.md
+++ b/README.ja.md
@@ -1,4 +1,4 @@
-<!-- synced-from: README.md sha256:2c81448b707086960939bd1512e493ea4a0248aac5d073ad388f6260c1352537 -->
+<!-- synced-from: README.md sha256:ad8f9dd91ca5fd56ff6bda0b6b1c1efe26b4ab7e464bbf5bb8dca4faab55b810 -->
<p align="center">🌍 <a href="README.md">English</a> | <a href="README.tr.md">Türkçe</a> | <a href="README.ar.md">العربية</a> | <strong>日本語</strong></p>
<p align="center">
@@ -282,7 +282,7 @@ Alpaca、ShareGPT、ChatML、選好ペア(DPO / ORPO / SimPO / IPO / KTO)、
```bash
soup train --config soup.yaml # 学習(SFT/DPO/GRPO/PPO/KTO/ORPO/SimPO/IPO/...)
-soup infer --model ./output --input prompts.jsonl # バッチ推論
+soup infer --model ./output --input prompts.jsonl --output results.jsonl # バッチ推論
soup chat --model ./output # 対話型チャット
soup serve --model ./output # OpenAI 互換 API サーバー
soup ui # ローカルのブラウザダッシュボード
diff --git a/README.md b/README.md
index d4647ba7..8ec5a8fa 100644
--- a/README.md
+++ b/README.md
@@ -286,7 +286,7 @@ interleaving, vocab expansion, document ingestion), are in
```bash
soup train --config soup.yaml # train (SFT/DPO/GRPO/PPO/KTO/ORPO/SimPO/IPO/...)
-soup infer --model ./output --input prompts.jsonl # batch inference
+soup infer --model ./output --input prompts.jsonl --output results.jsonl # batch inference
soup chat --model ./output # interactive chat
soup serve --model ./output # OpenAI-compatible API server
soup ui # local browser dashboard
diff --git a/README.tr.md b/README.tr.md
index 11840ff0..ea8ea0fb 100644
--- a/README.tr.md
+++ b/README.tr.md
@@ -1,4 +1,4 @@
-<!-- synced-from: README.md sha256:2c81448b707086960939bd1512e493ea4a0248aac5d073ad388f6260c1352537 -->
+<!-- synced-from: README.md sha256:ad8f9dd91ca5fd56ff6bda0b6b1c1efe26b4ab7e464bbf5bb8dca4faab55b810 -->
<p align="center">🌍 <a href="README.md">English</a> | <strong>Türkçe</strong> | <a href="README.ar.md">العربية</a> | <a href="README.ja.md">日本語</a></p>
<p align="center">
@@ -289,7 +289,7 @@ akış, parçalama, iç içe geçirme, sözcük dağarcığı genişletme, belge
```bash
soup train --config soup.yaml # eğitin (SFT/DPO/GRPO/PPO/KTO/ORPO/SimPO/IPO/...)
-soup infer --model ./output --input prompts.jsonl # toplu çıkarım
+soup infer --model ./output --input prompts.jsonl --output results.jsonl # toplu çıkarım
soup chat --model ./output # etkileşimli sohbet
soup serve --model ./output # OpenAI uyumlu API sunucusu
soup ui # yerel tarayıcı panosu
diff --git a/changelog.d/0.75.1/1578.fixed.md b/changelog.d/0.75.1/1578.fixed.md
new file mode 100644
index 00000000..09d025bf
--- /dev/null
+++ b/changelog.d/0.75.1/1578.fixed.md
@@ -0,0 +1 @@
+- **Every documented `soup` invocation names a real command path and real flags, and a guard keeps it so (#1465 by @Srinivasan8888 in #1578).** Five documented commands named a flag or command path the CLI refuses and one recipe description named an option no command has: `soup loop watch --max-iter` is `--max-iterations`; `soup serve ... --spec-tokens` is `--num-speculative-tokens`; `soup --verbose eval --model ...` is `soup eval benchmark ...`; `--no-telemetry` is a global option and goes before the command (`soup --no-telemetry train ...`); `soup adapters blame` has no `--live`; the `online-dpo-smollm2-135m` description points at `training.online_dpo_judge`. Sixteen more documented lines were missing a required option or carried an extra argument (`soup data pii` / `decontaminate` / `augment` take `--input`; `soup infer` needs `--output`; `soup eval custom` needs `--model` and `soup eval human` both `--model-a` / `--model-b`; `soup serve --reasoning-parser` needs `--model`; a second adapter needs its own `--adapters`; `soup runs list` is `soup runs`; `soup recipes search --tag mlx` is `soup recipes search mlx`) and are corrected. `docs/data.md` now says that `soup data decontaminate --benchmarks` records labels only and that `--benchmark-file` is what filters, since no benchmark corpora are bundled; its examples pass one. A test walks every `soup ...` line (aligned columns, `VAR=value` prefixes and backslash continuations included) and every `` `soup ...` `` span in `docs/*.md` and `README.md`, plus every recipe description, against the live Click tree: a flag or command path that does not exist, or a subcommand a group does not have, fails CI. Whether a line also carries every required option is not checked. (The standalone sweep config was #1475.)
diff --git a/docs/backends-and-ops.md b/docs/backends-and-ops.md
index 8090dbbe..9c8aba95 100644
--- a/docs/backends-and-ops.md
+++ b/docs/backends-and-ops.md
@@ -115,7 +115,7 @@ training:
alpha: 32
```
-MLX backend supports SFT. `backend: mlx` with `task: dpo` or `task: grpo` is refused when the config is loaded, with an error naming the task — upstream `mlx-lm` ships no DPO/GRPO training helper, so those wrappers exist only as a backstop for callers that bypass config validation. Requires `mlx-lm >= 0.31.3`. Use `soup recipes search --tag mlx` for ready-made Apple Silicon configs.
+MLX backend supports SFT. `backend: mlx` with `task: dpo` or `task: grpo` is refused when the config is loaded, with an error naming the task — upstream `mlx-lm` ships no DPO/GRPO training helper, so those wrappers exist only as a backstop for callers that bypass config validation. Requires `mlx-lm >= 0.31.3`. Use `soup recipes search mlx` for ready-made Apple Silicon configs.
#### Optimizers and schedules
@@ -377,7 +377,7 @@ LLM training generates massive checkpoint files. Soup automatically manages an S
```bash
# List all historical training runs
-soup runs list
+soup runs
# Compare two differing experiments side-by-side
soup runs compare run_202611... run_202612...
@@ -596,7 +596,7 @@ Soup shows friendly error messages by default (2-3 lines with a fix suggestion).
soup --verbose train --config soup.yaml
# Works with any command
-soup --verbose eval --model ./output --benchmarks mmlu
+soup --verbose eval benchmark --model ./output --benchmarks mmlu
```
> **Note:** `--verbose` is a global flag — it must go **before** the command name, not after.
@@ -724,7 +724,7 @@ zero telemetry network requests.
You can also explicitly disable telemetry for a specific invocation using the `--no-telemetry` flag:
```bash
-soup train --config soup.yaml --no-telemetry
+soup --no-telemetry train --config soup.yaml
```
When enabled, telemetry performs a synchronous fire-and-forget HTTP POST with a 1-second connect and read timeout (DNS resolution excluded) on command exit. The anonymous identifier is stored at `~/.soup/telemetry_id`; deleting `~/.soup/telemetry_id` regenerates it on the next opt-in. See [Privacy Policy](#privacy-policy) for details.
diff --git a/docs/commands.md b/docs/commands.md
index 6454acee..14e95c66 100644
--- a/docs/commands.md
+++ b/docs/commands.md
@@ -28,8 +28,8 @@ soup train --config soup.yaml --push-as user/repo Auto-push each checkpoint to
soup train --config soup.yaml --push-as user/repo --hf-resume Resume from latest HF checkpoint branch (not with training.relora_steps)
soup train --config soup.yaml --find-lr LR range finder: write recommended LR JSON
soup train --config soup.yaml --cloud modal|lambda --gpu a100 Render a cloud GPU controller (plan-only; --cloud-submit submits live)
-soup infer --model ./output --input p.jsonl [--batch-size N] Batch inference; default batch size is 1; fp16/bf16 batching may not be bit-exact with batch size 1
-soup infer --model ./output --input p.jsonl --cuda-graphs Experimental CUDA graph decode (Qwen2/Llama, one GPU, PyTorch >= 2.14; batch size 1 only)
+soup infer --model ./output --input p.jsonl --output out.jsonl [--batch-size N] Batch inference; default batch size is 1; fp16/bf16 batching may not be bit-exact with batch size 1
+soup infer --model ./output --input p.jsonl --output out.jsonl --cuda-graphs Experimental CUDA graph decode (Qwen2/Llama, one GPU, PyTorch >= 2.14; batch size 1 only)
soup infer --task asr --model <whisper|adapter> --input a.jsonl --output o.jsonl [--audio-dir d --asr-language en --asr-task transcribe|translate] Whisper transcription + WER/CER
soup chat --model ./output Interactive chat
soup infer|chat|diff ... --device cpu|cuda|cuda:N|mps Pick where the model loads (see below)
@@ -60,12 +60,12 @@ soup agent eval --spec api.yaml --predictions p.jsonl Score predicted tool-call
soup agent eval --spec api.yaml --predictions p.jsonl --sandbox Execute each tool-call in the RLVR sandbox: ok/tool_error/timeout/arg_error
soup eval benchmark --model ./output Evaluate on standard benchmarks
soup eval aider --model openai/gpt-4.1 --output ./aider-results --exercises-dir ./polyglot-benchmark Run Aider Polyglot in Docker
-soup eval custom --tasks eval.jsonl Custom eval tasks from JSONL
+soup eval custom --model ./output --tasks eval.jsonl Custom eval tasks from JSONL
soup eval judge --target resp.jsonl LLM-as-a-judge evaluation
soup eval auto --config soup.yaml Auto-eval from config
soup eval compare <run1> <run2> Compare eval results
soup eval leaderboard Local model leaderboard
-soup eval human --input p.jsonl Human A/B evaluation
+soup eval human --model-a ./a --model-b ./b --input p.jsonl Human A/B evaluation
soup eval gate --suite gate.yaml Run eval-gate suite standalone
soup eval quant-check --before X --after Y --tasks t.jsonl Before/after quantization eval (OK/MINOR/MAJOR verdict)
soup eval design <data> --goal "..." Draft an eval suite from training data + goal
@@ -153,7 +153,7 @@ soup data forge --docs ./docs --hub modelscope --teacher owner/name Pre-fetch t
soup data score --input rows.jsonl Composite quality scorecard (PII + keyword triage + lang + edu)
soup data score --input rows.jsonl --benchmark-file benchmark.jsonl --threshold 0.8 Score with real n-gram comparison texts
soup data score ... -b gsm8k --benchmark-file benchmark.jsonl Labels are validated only, not corpus selectors; all file texts are compared
-soup data decontaminate --input rows.jsonl --benchmarks mmlu,gsm8k Drop benchmark-overlap rows
+soup data decontaminate --input rows.jsonl --benchmark-file benchmarks.jsonl Drop rows overlapping the benchmark texts in that file
soup data toxicity --input rows.jsonl -o tox.jsonl Flag abuse-keyword matches (heuristic)
soup data langdetect --input rows.jsonl -o tagged.jsonl Tag each row with language code
soup data pii --input rows.jsonl -o pii.jsonl Flag rows containing email/phone/SSN/credit-card
@@ -173,12 +173,12 @@ soup adapters checkout <name> Restore a snapshotted branch's c
soup adapters diff <a> <b> Per-layer ΔW Frobenius diff + effective-rank drift
soup loop init <model> --eval <s> --baseline <b> [--pre-wired] Create .soup/loop.yaml (data flywheel; --pre-wired = real stages)
soup loop status Counters + status + pre_wired flag
-soup loop watch [--detach] [--max-iter N] [--pre-wired] [--pack-cans] Harvest → train → gate → deploy daemon (pre-wired stages + Soup Can packing)
+soup loop watch [--detach] [--max-iterations N] [--pre-wired] [--pack-cans] Harvest → train → gate → deploy daemon (pre-wired stages + Soup Can packing)
soup loop pause Atomic status flip: pause watch daemon at next iteration boundary
soup loop resume Atomic status flip: resume a paused loop
soup loop canary <adapter> --traffic 5% Route keyed serve traffic to a loaded adapter; watch auto-rolls back on MAJOR
soup loop replay [<iter-id>] [--extract <dir>] Replay / unpack a recorded iteration manifest
-soup serve --model m --adapters chat=./c code=./d Multi-adapter serving
+soup serve --model m --adapters chat=./c --adapters code=./d Multi-adapter serving
soup migrate --from llamafactory config.yaml Import config from LLaMA-Factory
soup migrate --from axolotl config.yml Import config from Axolotl
soup migrate --from unsloth notebook.ipynb Import config from Unsloth notebook
@@ -262,7 +262,7 @@ soup bench infer <model> --p50 --p95 Bench with tail-latency percentile
soup bench infer <model> --cuda-graphs Bench with experimental CUDA graph decode
soup bench train --config soup.yaml --steps 20 --warmup 3 -o bench-train.json Timed SFT steps; exits 1 when the model was not training (#836)
soup bench <model> --backend auto Auto-detect transformers/mlx backend (v0.53.9)
-soup serve --reasoning-parser deepseek-r1 Strip <think> blocks from responses (v0.53.9)
+soup serve --model ./output --reasoning-parser deepseek-r1 Strip <think> blocks from responses (v0.53.9)
soup doctor [--nccl] [--disk] [--config F] Check environment (optionally check NCCL bandwidth, media type; --disk ~9s cold / ~2.4s warm).
--config also reports which settings that config switches on (a `false` or unset value is not reported; `seed: 0` is) that its task/backend does not read (#755, #1330); exits 2 if it cannot be read, and exits 1 when a required core dependency is missing, or when any installed package is beyond its declared ceiling — core or [train] (#828, #874).
soup monitor NVIDIA / Apple Silicon GPU monitor: util / temp / VRAM / power
diff --git a/docs/compliance.md b/docs/compliance.md
index 18b59c92..e82ef1af 100644
--- a/docs/compliance.md
+++ b/docs/compliance.md
@@ -35,8 +35,8 @@ template header documents which ones apply. The steps below are the common path.
## 2. Clean the data before training
```bash
-soup data pii ./data/train.jsonl # flag emails / phones / SSNs / MRNs
-soup data decontaminate ./data/train.jsonl # drop public-benchmark overlap
+soup data pii --input ./data/train.jsonl # flag emails / phones / SSNs / MRNs
+soup data decontaminate --input ./data/train.jsonl --benchmark-file benchmarks.jsonl # drop benchmark overlap
```
## 3. Train with a reproducibility receipt (+ Annex XI / energy for the EU)
diff --git a/docs/data.md b/docs/data.md
index c765379d..61a57eea 100644
--- a/docs/data.md
+++ b/docs/data.md
@@ -25,7 +25,7 @@
- [Semantic dedup (`soup data dedup --semantic`)](#semantic-dedup-soup-data-dedup---semantic)
- [Dataset Sanitization & Repair (`soup data clean`)](#dataset-sanitization--repair-soup-data-clean)
- [Topic map (`soup data topics`)](#topic-map-soup-data-topics)
-- [Canaries (`soup data canary insertcheck`)](#canaries-soup-data-canary-insertcheck)
+- [Canaries (`soup data canary insert|check`)](#canaries-soup-data-canary-insertcheck)
- [Data Recipe DAG](#data-recipe-dag)
- [Data Mixing Optimizer (BETA)](#data-mixing-optimizer-beta)
- [AOT Tokenization with `soup data preprocess`](#aot-tokenization-with-soup-data-preprocess)
@@ -515,19 +515,19 @@ Augment an existing dataset using an LLM — rephrase for diversity, translate f
```bash
# Rephrase each example N times for more diversity
-soup data augment ./data/train.jsonl --strategy rephrase --count 3 \
+soup data augment --input ./data/train.jsonl --strategy rephrase --count 3 \
--output ./data/train_augmented.jsonl
# Translate into multiple languages
-soup data augment ./data/train.jsonl --strategy translate --lang es,fr,de \
+soup data augment --input ./data/train.jsonl --strategy translate --lang es,fr,de \
--output ./data/train_multilingual.jsonl
# Style transfer (formal / casual / technical / etc.)
-soup data augment ./data/train.jsonl --strategy style --styles formal,casual \
+soup data augment --input ./data/train.jsonl --strategy style --styles formal,casual \
--output ./data/train_styled.jsonl
# Local provider (Ollama, loopback-only) — pick the model + base URL
-soup data augment ./data/train.jsonl --strategy rephrase --count 2 \
+soup data augment --input ./data/train.jsonl --strategy rephrase --count 2 \
--provider ollama --model qwen2.5:0.5b --output ./data/train_local.jsonl
```
@@ -1096,7 +1096,7 @@ soup data pii --input training.jsonl --output pii_flagged.jsonl
soup data toxicity --input training.jsonl --output tox_flagged.jsonl --threshold 0.1
soup data langdetect --input training.jsonl --output tagged.jsonl
soup data educational --input training.jsonl --output scored.jsonl
-soup data decontaminate --input training.jsonl --benchmarks mmlu,gsm8k,humaneval --output clean.jsonl
+soup data decontaminate --input training.jsonl --benchmark-file benchmarks.jsonl --benchmarks mmlu,gsm8k,humaneval --output clean.jsonl
```
`data score` shows decontamination as **not run**, not a measured zero, unless
diff --git a/docs/evaluation.md b/docs/evaluation.md
index cdd3c87d..692401bc 100644
--- a/docs/evaluation.md
+++ b/docs/evaluation.md
@@ -6,7 +6,7 @@
**Contents:**
-- [Post-train X-rays (`soup probe`, `soup adapters blame --live`)](#post-train-x-rays-soup-probe-soup-adapters-blame---live)
+- [Post-train X-rays (`soup probe`, `soup adapters blame`)](#post-train-x-rays-soup-probe-soup-adapters-blame)
- [Pre-flight Decision (`soup advise`)](#pre-flight-decision-soup-advise)
- [Eval Design Pipeline (`soup eval design / discover / lock / coverage`)](#eval-design-pipeline-soup-eval-design--discover--lock--coverage)
- [Run-vs-run Regression (`soup eval against`)](#run-vs-run-regression-soup-eval-against)
@@ -25,7 +25,7 @@
---
-## Post-train X-rays (`soup probe`, `soup adapters blame --live`)
+## Post-train X-rays (`soup probe`, `soup adapters blame`)
Five surfaces that extend `soup diagnose` from 6 failure modes to 10. Mechanistic interpretability has been research-grade for years; v0.66.0 ships the wiring CLI-first so anyone can probe their FT without the SaaS unit-economics tax.
diff --git a/docs/performance-and-quantization.md b/docs/performance-and-quantization.md
index 07a7482a..fd9407a6 100644
--- a/docs/performance-and-quantization.md
+++ b/docs/performance-and-quantization.md
@@ -958,7 +958,7 @@ Coverage:
```bash
soup train --config soup.yaml --trust-remote-code
-soup infer --model my-org/custom-arch-model --input prompts.jsonl --trust-remote-code
+soup infer --model my-org/custom-arch-model --input prompts.jsonl --output out.jsonl --trust-remote-code
soup export --model ./adapter --format gguf --trust-remote-code
```
diff --git a/docs/serving-and-export.md b/docs/serving-and-export.md
index ad4ca25d..54530f0b 100644
--- a/docs/serving-and-export.md
+++ b/docs/serving-and-export.md
@@ -403,7 +403,7 @@ forward pass; on a small target it is frequently a *slowdown*.
```bash
# Transformers backend — uses HF assisted generation
-soup serve --model ./output --speculative-decoding small-draft-model --spec-tokens 5
+soup serve --model ./output --speculative-decoding small-draft-model --num-speculative-tokens 5
# vLLM backend — uses vLLM native speculative decoding
soup serve --model ./output --backend vllm --speculative-decoding small-draft-model
@@ -504,7 +504,7 @@ The first request with a given prefix warms the cache; subsequent requests skip
Switch the active adapter at runtime without restarting the server:
```bash
-soup serve --model base-model --adapters chat=./chat-adapter code=./code-adapter
+soup serve --model base-model --adapters chat=./chat-adapter --adapters code=./code-adapter
```
```bash
diff --git a/src/soup_cli/recipes/catalog.py b/src/soup_cli/recipes/catalog.py
index 57c28ba9..0f41a3e0 100644
--- a/src/soup_cli/recipes/catalog.py
+++ b/src/soup_cli/recipes/catalog.py
@@ -2128,7 +2128,7 @@ output: ./output
size="135M",
tags=("smollm", "smollm2", "online_dpo", "judge", "rlhf", "tiny", "edge"),
description="SmolLM2 135M Online DPO — on-policy generation judged by a "
- "pairwise LLM judge (point --online-dpo-judge at a local ollama model)",
+ "pairwise LLM judge (point training.online_dpo_judge at a local ollama model)",
yaml_str="""\
base: HuggingFaceTB/SmolLM2-135M-Instruct
task: online_dpo
diff --git a/src/soup_cli/utils/blame.py b/src/soup_cli/utils/blame.py
index aa02c9f0..4058f314 100644
--- a/src/soup_cli/utils/blame.py
+++ b/src/soup_cli/utils/blame.py
@@ -256,7 +256,7 @@ class RowInfluence:
@dataclass(frozen=True)
class BlameResult:
- """End-to-end blame result for ``soup adapters blame --live``."""
+ """End-to-end blame result for ``soup adapters blame`` with live probes."""
adapter_dir: str
dataset_path: str
diff --git a/tests/test_issue1465_documented_invocations_exist.py b/tests/test_issue1465_documented_invocations_exist.py
new file mode 100644
index 00000000..b1dbe277
--- /dev/null
+++ b/tests/test_issue1465_documented_invocations_exist.py
@@ -0,0 +1,375 @@
+"""#1465: every ``soup ...`` invocation written in the docs resolves in the live Click tree.
+
+#979's guard checked ``soup train`` flags in two files. Eight documented invocations in
+other files named a flag or a command path the CLI refuses (``--spec-tokens``,
+``--max-iter``, ``soup eval --model``, a global option placed after the command), and
+one recipe description named ``--online-dpo-judge``, an option no command has. This
+generalises the walk to every invocation line in ``docs/*.md`` and ``README.md`` and to
+every recipe description.
+
+What counts as an invocation: a line that starts with ``soup`` (an optional ``$ ``
+prompt allowed), continued across backslash line breaks, with the two-space description
+tail that ``docs/commands.md`` appends dropped. Quoted strings are blanked first, so a
+flag inside ``--eval-command "soup eval ... --model x"`` belongs to the quoted command,
+not to the one being checked. Lines whose command path carries documentation notation
+(``<cmd>``, ``infer|chat|diff``, ``...``, ``[...]``) are syntax, not a command, and are
+skipped; flags after a resolved command are always checked.
+
+Resolution follows Click: global options (``--verbose``, ``--log-level debug``) are
+accepted only before the command and consume their value; a group that runs on its own
+(``soup ship``, ``soup runs``) is checked against its own options; a group that routes a
+bare argument to a default subcommand (``soup bench ./m``, ``soup advise d.jsonl``) is
+accepted when one of its subcommands takes every flag used; a pass-through command
+(``soup llama gguf-split``, ``ignore_unknown_options``) has no flag check; a bare group
+(``soup eval``) prints help and is fine. A boolean flag's ``--no-*`` spelling counts.
+"""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+
+import click
+import pytest
+import typer
+
+from soup_cli.cli import app
+from soup_cli.recipes.catalog import RECIPES
+
+_ROOT = Path(__file__).resolve().parents[1]
+_DOC_FILES = sorted((_ROOT / "docs").glob("*.md")) + [_ROOT / "README.md"]
+_NOTATION = re.compile(r"[<>|\[\]{}\u2026]|\.\.\.")
+#: `VAR=value soup ...` lines are invocations too (docs/backends-and-ops.md:715).
+_LINE = re.compile(r"^\s*(\$ )?(?:[A-Z_][A-Z0-9_]*=\S+ )*soup\s")
+_PREFIX = re.compile(r"^(\$ )?(?:[A-Z_][A-Z0-9_]*=\S+ )*")
+#: a backtick span that is a `soup ...` invocation, unless the prose says "not `soup ...`"
+_INLINE = re.compile(r"(?<!not )`(soup [^`\n]+)`")
+_QUOTED = re.compile(r"\"[^\"\n]*\"|'[^'\n]*'")
+#: the whole option token, so `--config_file` is checked as itself, not as `--config`
+_FLAG = re.compile(r"^--[A-Za-z0-9_-]+")
+#: an aligned column that is a bare word (a subcommand or a positional), then a flag
+#: or a path; the lowercase start keeps description tails such as `Implies
+#: --allow-mutating` out (review of #1578)
+_BARE_THEN_ARG = re.compile(r"[a-z]\S* (?:--?[A-Za-z]|\.{0,2}/)")
+# Groups that route a bare argument to a default subcommand. ``soup bench ./m`` does it
+# in its Click class (``parse_args`` override, detected below); ``soup advise d.jsonl``
+# does it in the entry point (``cli._rewrite_advise_argv``), which the Click tree cannot
+# show, so it is named here and a test pins that the rewrite still exists.
+_ARGV_REWRITTEN_GROUPS = {"advise"}
+
+
+def _cli() -> click.Group:
+ return typer.main.get_command(app)
+
+
+def _options(cmd: click.Command) -> set[str]:
+ opts: set[str] = {"--help"}
+ for param in cmd.params:
+ if isinstance(param, click.Option):
+ opts.update(o for o in param.opts if o.startswith("--"))
+ opts.update(o for o in param.secondary_opts if o.startswith("--"))
+ return opts
+
+
+def _all_options(cmd: click.Command) -> set[str]:
+ """Every --option anywhere in the tree (for recipe descriptions)."""
+ found = _options(cmd)
+ if isinstance(cmd, click.Group):
+ for sub in cmd.commands.values():
+ found |= _all_options(sub)
+ return found
+
+
+def invocations(markdown: str) -> list[tuple[int, str]]:
+ """(line number, full invocation) for every ``soup ...`` line, continuations joined."""
+ lines = markdown.splitlines()
+ out: list[tuple[int, str]] = []
+ i = 0
+ while i < len(lines):
+ if _LINE.match(lines[i]):
+ parts: list[str] = []
+ j = i
+ while True:
+ raw = lines[j].rstrip()
+ continued = raw.endswith("\\")
+ if continued:
+ raw = raw[:-1]
+ # two or more spaces end the invocation (a description or comment
+ # follows) unless the next column is itself a flag: aligned columns such
+ # as `soup chat --model ./output` keep their flags (review of #1578)
+ segments = re.split(r" +", raw.strip())
+ kept = [segments[0]]
+ for segment in segments[1:]:
+ if not segment.startswith(("-", "[-")) and not _BARE_THEN_ARG.match(
+ segment
+ ):
+ break
+ kept.append(segment)
+ parts.append(" ".join(kept))
+ if not continued or j + 1 >= len(lines):
+ break
+ j += 1
+ out.append((i + 1, _PREFIX.sub("", " ".join(parts).strip())))
+ i = j
+ i += 1
+ return out
+
+
+def inline_invocations(markdown: str) -> list[tuple[int, str]]:
+ """(line number, invocation) for every backtick span that starts with ``soup ``:
+ headings, contents entries and prose name flags too (the issue's own ``--live``
+ site was a heading plus its contents entry)."""
+ out: list[tuple[int, str]] = []
+ for lineno, line in enumerate(markdown.splitlines(), start=1):
+ for match in _INLINE.finditer(line):
+ out.append((lineno, match.group(1).strip()))
+ return out
+
+
+def _routes_a_default_subcommand(group: click.Group) -> bool:
+ overridden = type(group).parse_args is not click.Group.parse_args and (
+ type(group).parse_args is not typer.core.TyperGroup.parse_args
+ )
+ return overridden or group.name in _ARGV_REWRITTEN_GROUPS
+
+
+def check_invocation(invocation: str, root: click.Group) -> str | None:
+ """``None`` when the invocation resolves and every flag exists, else the reason."""
+ tokens = _QUOTED.sub('""', _PREFIX.sub("", invocation.strip())).split()
+ if not tokens or tokens[0] != "soup":
+ return None
+ root_params = {o: p for p in root.params if isinstance(p, click.Option) for o in p.opts}
+ i = 1
+ # global options, only before the command; a valued one consumes its value
+ while i < len(tokens) and tokens[i].startswith("-"):
+ flag = tokens[i].split("=", 1)[0]
+ param = root_params.get(flag)
+ if param is None:
+ return f"unknown global option {flag}"
+ i += 1
+ if not param.is_flag and "=" not in tokens[i - 1]:
+ i += 1
+ cmd: click.Command = root
+ while isinstance(cmd, click.Group) and i < len(tokens):
+ name = tokens[i]
+ if _NOTATION.search(name):
+ if cmd is not root and _routes_a_default_subcommand(cmd):
+ i += 1 # `soup bench <model> --backend auto`: the placeholder is the routed
+ break # argument, and the flags after it are still checked
+ return None # documentation notation, not a runnable command path
+ sub = cmd.commands.get(name)
+ if sub is None:
+ break
+ cmd = sub
+ i += 1
+ rest = tokens[i:]
+ flags = [m.group(0) for t in rest for m in [_FLAG.match(t.strip("[]"))] if m]
+ if isinstance(cmd, click.Group):
+ if cmd is root:
+ return f"no command {rest[0]!r}" if rest else None
+ if not rest:
+ return None # a bare group prints its help
+ positional = [t for t in rest if not t.startswith("-")]
+ if not positional and all(f in _options(cmd) for f in flags):
+ return None # `soup llama --help`: the group's own options, nothing routed
+ if _options(cmd) - {"--help"}:
+ # a group that runs on its own (invoke_without_command). None of them
+ # declares a positional argument, so the first token that is neither an
+ # option nor an option's value must be a subcommand: `soup runs list`
+ # exits 2 ("No such command 'list'") while `soup runs` lists the runs.
+ first = _first_bare_token(rest, cmd)
+ if first is not None:
+ sub = cmd.commands.get(first)
+ if sub is None:
+ return f"{cmd.name}: no subcommand {first!r}"
+ split = rest.index(first)
+ before = [
+ m.group(0) for t in rest[:split] for m in [_FLAG.match(t.strip("[]"))] if m
+ ]
+ unknown = [f for f in before if f not in _options(cmd)]
+ if unknown:
+ return f"{cmd.name}: unknown option(s) {unknown}"
+ after = rest[split + 1 :]
+ sub_flags = [m.group(0) for t in after for m in [_FLAG.match(t.strip("[]"))] if m]
+ unknown = [f for f in sub_flags if f not in _options(sub)]
+ return f"{sub.name}: unknown option(s) {unknown}" if unknown else None
+ candidates = [cmd]
+ elif _routes_a_default_subcommand(cmd):
+ candidates = list(cmd.commands.values())
+ else:
+ return f"{cmd.name}: is a command group; {rest[0]!r} is not one of its subcommands"
+ if any(all(f in _options(c) for f in flags) for c in candidates):
+ return None
+ return f"{cmd.name}: no subcommand takes {flags}"
+ settings = cmd.context_settings or {}
+ if settings.get("ignore_unknown_options") or settings.get("allow_extra_args"):
+ return None
+ unknown = [f for f in flags if f not in _options(cmd)]
+ return f"{cmd.name}: unknown option(s) {unknown}" if unknown else None
+
+
+def _first_bare_token(rest: list[str], cmd: click.Command) -> str | None:
+ """The first token of ``rest`` that is neither one of ``cmd``'s options nor the
+ value a valued option consumes (bracketed ``[--output v.json]`` included)."""
+ params = {o: p for p in cmd.params if isinstance(p, click.Option) for o in p.opts}
+ i = 0
+ while i < len(rest):
+ token = rest[i].strip("[]")
+ if token.startswith("-"):
+ param = params.get(token.split("=", 1)[0])
+ i += 1
+ if param is not None and not param.is_flag and "=" not in token:
+ i += 1 # its value
+ continue
+ return rest[i]
+ return None
+
+
+def _problems(markdown: str, root: click.Group) -> list[tuple[int, str, str]]:
+ return [
+ (lineno, inv, reason)
+ for lineno, inv in invocations(markdown) + inline_invocations(markdown)
+ for reason in [check_invocation(inv, root)]
+ if reason is not None
+ ]
+
+
[email protected]("path", _DOC_FILES, ids=lambda p: p.name)
+def test_every_documented_invocation_resolves_in_the_live_cli(path: Path) -> None:
+ problems = _problems(path.read_text(encoding="utf-8"), _cli())
+ assert not problems, "\n".join(
+ f"{path.name}:{lineno}: {reason}\n {inv[:160]}" for lineno, inv, reason in problems
+ )
+
+
+def test_the_file_check_reads_both_lines_and_inline_spans() -> None:
+ """The per-file test only sees what ``_problems`` hands it."""
+ text = "soup chat --modell ./output\nSee `soup serve --kv-cache-typo` below.\n"
+ reasons = [reason for _, _, reason in _problems(text, _cli())]
+ assert len(reasons) == 2, reasons
+ assert "--modell" in reasons[0] and "--kv-cache-typo" in reasons[1], reasons
+
+
+def test_the_guard_cannot_pass_vacuously() -> None:
+ """Dropping README.md, a wrong docs path or an empty file list all passed before
+ (review of #1578): pin the inputs and a floor on what was seen."""
+ assert _ROOT / "README.md" in _DOC_FILES
+ assert len(_DOC_FILES) >= 10, [p.name for p in _DOC_FILES]
+ texts = [p.read_text(encoding="utf-8") for p in _DOC_FILES]
+ lines = sum(len(invocations(t)) for t in texts)
+ spans = sum(len(inline_invocations(t)) for t in texts)
+ assert lines >= 900, lines # 944 on 2026-10-04
+ assert spans >= 400, spans # 423 on 2026-10-04
+
+
+def test_recipe_descriptions_name_only_real_options() -> None:
+ live = _all_options(_cli())
+ bad = {
+ name: [f for f in re.findall(r"--[a-zA-Z][a-zA-Z0-9-]*", meta.description) if f not in live]
+ for name, meta in RECIPES.items()
+ }
+ bad = {name: flags for name, flags in bad.items() if flags}
+ assert not bad, bad
+
+
+# --- the guard must be able to fail: each issue case, in memory -------------------------
+
+ "line,fragment",
+ [
+ ("soup serve --model ./output --speculative-decoding d --spec-tokens 5", "--spec-tokens"),
+ ("soup loop watch [--detach] [--max-iter N]", "--max-iter"),
+ ("soup train --config soup.yaml --no-telemetry", "--no-telemetry"),
+ ("soup --verbose eval --model ./output --benchmarks mmlu", "is a command group"),
+ ("soup train --config soup.yaml --minillm-enabled", "--minillm-enabled"), # #979's case
+ ("soup adapters blame ./a --live", "--live"),
+ ("soup --verbos train --config soup.yaml", "unknown global option"),
+ ("soup trian --config soup.yaml", "no command"),
+ ("soup runs shwo abc123", "no subcommand"),
+ ("soup runs list", "no subcommand"),
+ ("soup bench <model> --backendd auto", "--backendd"),
+ ("SOUP_TELEMETRY=1 soup train --confg soup.yaml", "--confg"),
+ ("soup train --config_file soup.yaml", "--config_file"),
+ ("soup runs --bogus show abc123", "--bogus"),
+ ],
+)
+def test_the_guard_flags_each_documented_mistake(line: str, fragment: str) -> None:
+ reason = check_invocation(line, _cli())
+ assert reason is not None and fragment in reason, reason
+
+
+ "line",
+ [
+ "soup --no-telemetry train --config soup.yaml",
+ "soup --log-level debug runs show <id>",
+ "soup recipes verify --no-templates",
+ "soup merge --adapter ./output --save-format 4bit --no-double-quant",
+ "soup ship --evidence ev.json --output v.json",
+ 'soup advise data.jsonl --goal "make it concise" --probe',
+ "soup bench ./output --num-prompts 5",
+ "soup llama gguf-split --merge a.gguf b.gguf out.gguf",
+ 'soup adapters bisect a b --eval-command "soup eval benchmark --model x --tasks y"',
+ "soup eval",
+ "soup infer|chat|diff ... --device cpu",
+ "soup --verbose <command>",
+ "soup adapters {merge,pr,bisect}",
+ "soup data \u2026",
+ "soup runs --limit 5 show abc123",
+ "soup recipes search mlx",
+ "soup bench <model> --backend auto",
+ "SOUP_TELEMETRY=1 soup train --config soup.yaml",
+ ],
+)
+def test_real_or_notational_lines_do_not_trip_the_guard(line: str) -> None:
+ assert check_invocation(line, _cli()) is None
+
+
+ "markdown,expected",
+ [
+ ("soup chat --model ./output # talk to your model",
+ ["soup chat --model ./output"]),
+ ("soup data pii --input training.jsonl --output pii_flagged.jsonl",
+ ["soup data pii --input training.jsonl --output pii_flagged.jsonl"]),
+ ("soup loop watch [--detach] [--max-iter N] Watch the loop",
+ ["soup loop watch [--detach] [--max-iter N]"]),
+ ("SOUP_TELEMETRY=1 soup train --config soup.yaml", ["soup train --config soup.yaml"]),
+ ("$ soup train --config a.yaml \\\n --resume", ["soup train --config a.yaml --resume"]),
+ ("soup eval benchmark --model ./output # evaluate",
+ ["soup eval benchmark --model ./output"]),
+ ("soup data inspect ./data/train.jsonl # dataset stats",
+ ["soup data inspect ./data/train.jsonl"]),
+ ("soup probe harm meta-llama/Llama-3-8B --evidence activations.json",
+ ["soup probe harm meta-llama/Llama-3-8B --evidence activations.json"]),
+ ("soup mcp serve --allow-execute Implies --allow-mutating; enables x",
+ ["soup mcp serve --allow-execute"]),
+ ],
+)
+def test_aligned_columns_prefixes_and_continuations_keep_their_flags(markdown, expected) -> None:
+ assert [inv for _, inv in invocations(markdown)] == expected
+
+
+def test_inline_spans_are_collected_except_after_not() -> None:
+ text = (
+ "## KV cache (`soup serve --kv-cache-type`)\n"
+ "Use the export command (not `soup deploy airgap-bundle`); see `soup chat`.\n"
+ )
+ assert [inv for _, inv in inline_invocations(text)] == [
+ "soup serve --kv-cache-type", "soup chat"
+ ]
+
+
+def test_the_advise_exception_is_backed_by_the_entry_point_rewrite() -> None:
+ from soup_cli import cli
+
+ assert callable(cli._rewrite_advise_argv)
+ assert _routes_a_default_subcommand(_cli().commands["advise"])
+ assert _routes_a_default_subcommand(_cli().commands["bench"])
+ assert not _routes_a_default_subcommand(_cli().commands["eval"])
+
+
+def test_the_recipe_check_flags_the_issue_option() -> None:
+ live = _all_options(_cli())
+ assert "--online-dpo-judge" not in live
+ assert "--trust-remote-code" in live