Skip to content

armgit / Soup

Public Imported from GitHub
0

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

fix(expect): refuse suite keys and argument names an expectation does not take (#1428) (#1461)

Srinivasan R8c10e2c634b4
diff --git a/changelog.d/0.75.1/1461.fixed.md b/changelog.d/0.75.1/1461.fixed.md
new file mode 100644
index 00000000..55c7d61f
--- /dev/null
+++ b/changelog.d/0.75.1/1461.fixed.md
@@ -0,0 +1,2 @@
+- **`soup expect` refuses suite keys and argument names an expectation does not take, instead of running it on its defaults (#1428 by @Srinivasan8888 in #1461).**
+ `parse_suite_spec` read only `name` and `args` and dropped every other key, and the dispatcher read arguments with `args.get(key, default)`, so the `min_tokens` / `max_tokens` example in `docs/compliance.md` (written beside `name` instead of under `args:`) and a misspelled argument such as `max_token` both ran `expect_token_length_between` on its defaults of 1 and 1,048,576 tokens and passed a 5000-token row with exit 0. A key beside `name` or an argument the expectation does not take is now refused when the suite loads (exit 3, before the data file is opened), with the key named and either "belongs under `args:`" or the nearest valid name; `min_tokens` / `max_tokens` / `threshold` are validated at parse time too. The `docs/compliance.md` example moves to the `args:` form. A suite that carried one of these keys now exits 3 on its next run, which is the point.
diff --git a/docs/compliance.md b/docs/compliance.md
index b4349392..c4752148 100644
--- a/docs/compliance.md
+++ b/docs/compliance.md
@@ -128,12 +128,16 @@ A minimal `expectations.yaml` for the second step:
expectations:
- name: expect_no_pii
- name: expect_token_length_between
- min_tokens: 1
- max_tokens: 512
+ args:
+ min_tokens: 1
+ max_tokens: 512
```
Supported names: `expect_no_pii`, `expect_token_length_between`,
`expect_no_refusal_pattern`, `expect_chosen_preferred_over_rejected_by_judge`.
+Arguments go under `args:`. An entry key other than `name` / `args`, or an
+argument the expectation does not take (`max_token`), is refused when the suite
+loads (exit 3), so a mistyped bound cannot silently run on the defaults.
Scanned fields per format:
- ChatML / tool-calling / audio: every `messages[].content` (string or text parts), tool-call arguments (per message and top-level `tool_calls`), and `tools[].function.description`.
diff --git a/src/soup_cli/utils/expectations.py b/src/soup_cli/utils/expectations.py
index 0161f3c5..fb210407 100644
--- a/src/soup_cli/utils/expectations.py
+++ b/src/soup_cli/utils/expectations.py
@@ -14,20 +14,12 @@ Composes with:
from __future__ import annotations
+import difflib
import math
import os
from dataclasses import dataclass
from typing import Any, Callable, List, Mapping, Optional, Sequence, Tuple
-# Closed allowlist — the 4 expectation kinds the v0.69.0 plan calls out.
-_SUPPORTED_EXPECTATIONS = (
- "expect_no_pii",
- "expect_token_length_between",
- "expect_no_refusal_pattern",
- "expect_chosen_preferred_over_rejected_by_judge",
-)
-SUPPORTED_EXPECTATIONS: frozenset = frozenset(_SUPPORTED_EXPECTATIONS)
-
# DoS caps + bounds for validators.
_MAX_NAME_LEN = 128
_MAX_DETAILS_PER_RESULT = 32
@@ -37,6 +29,19 @@ _MAX_FILE_BYTES = 1_048_576 # 1 MiB
_MIN_TOKEN_BOUND = 1
_MAX_TOKEN_BOUND = 1_048_576
+# Closed allowlist — the 4 expectation kinds the v0.69.0 plan calls out — mapped to
+# the arguments each one takes and their defaults. #1428: a suite key outside this
+# table is refused at parse time instead of running the expectation on its defaults.
+_EXPECTATION_ARGS: dict[str, dict[str, Any]] = {
+ "expect_no_pii": {},
+ "expect_token_length_between": {"min_tokens": 1, "max_tokens": _MAX_TOKEN_BOUND},
+ "expect_no_refusal_pattern": {},
+ "expect_chosen_preferred_over_rejected_by_judge": {"threshold": 0.7},
+}
+_SUPPORTED_EXPECTATIONS = tuple(_EXPECTATION_ARGS)
+SUPPORTED_EXPECTATIONS: frozenset = frozenset(_SUPPORTED_EXPECTATIONS)
+_ENTRY_KEYS = ("name", "args")
+
# JudgeFn signature: row mapping in, [0,1] score out (1.0 = chosen wins).
JudgeFn = Callable[[Mapping[str, Any]], float]
@@ -148,6 +153,16 @@ def _check_token_bound(value: object, *, field: str) -> int:
return value
+def _check_token_bounds(min_tokens: object, max_tokens: object) -> Tuple[int, int]:
+ low = _check_token_bound(min_tokens, field="min_tokens")
+ high = _check_token_bound(max_tokens, field="max_tokens")
+ if low > high:
+ raise ValueError(
+ f"min_tokens ({low}) must be <= max_tokens ({high})"
+ )
+ return low, high
+
+
# -----------------------------------------------------------------------------
# Row helpers & Format Extraction Rules
# -----------------------------------------------------------------------------
@@ -563,12 +578,7 @@ def expect_token_length_between(
max_tokens: int,
) -> ExpectationResult:
"""Fail when any row's token count (whitespace-split) is out of bounds."""
- low = _check_token_bound(min_tokens, field="min_tokens")
- high = _check_token_bound(max_tokens, field="max_tokens")
- if low > high:
- raise ValueError(
- f"min_tokens ({low}) must be <= max_tokens ({high})"
- )
+ low, high = _check_token_bounds(min_tokens, max_tokens)
materialised = _check_rows(rows)
num_violations = 0
details: List[str] = []
@@ -727,6 +737,47 @@ def expect_chosen_preferred_over_rejected_by_judge(
# -----------------------------------------------------------------------------
+def _key_repr(key: object) -> str:
+ # repr() spells control bytes out, so a hostile key cannot reach the terminal raw.
+ return repr(str(key)[:_MAX_NAME_LEN])
+
+
+def _validate_entry_keys(index: int, name: str, entry: Mapping[str, Any]) -> None:
+ extra = [key for key in entry if key not in _ENTRY_KEYS]
+ if not extra:
+ return
+ misplaced = [key for key in extra if key in _EXPECTATION_ARGS[name]]
+ if misplaced:
+ raise ValueError(
+ f"expectations[{index}]: {', '.join(map(_key_repr, misplaced))} "
+ f"must go under 'args:' for {name}, not beside 'name'"
+ )
+ raise ValueError(
+ f"expectations[{index}]: unknown key(s) {', '.join(map(_key_repr, extra))}; "
+ "an entry takes only 'name' and 'args'"
+ )
+
+
+def _validate_args(index: int, name: str, args: Mapping[str, Any]) -> None:
+ accepted = _EXPECTATION_ARGS[name]
+ unknown = [key for key in args if key not in accepted]
+ if unknown:
+ shown = _key_repr(unknown[0])
+ if not accepted:
+ raise ValueError(f"expectations[{index}]: {name} takes no arguments, got {shown}")
+ close = difflib.get_close_matches(str(unknown[0]), sorted(accepted), n=1)
+ hint = f" (did you mean {close[0]!r}?)" if close else ""
+ raise ValueError(
+ f"expectations[{index}]: {name} takes no argument {shown}{hint}; "
+ f"accepted: {', '.join(sorted(accepted))}"
+ )
+ merged = {**accepted, **args}
+ if name == "expect_token_length_between":
+ _check_token_bounds(merged["min_tokens"], merged["max_tokens"])
+ elif name == "expect_chosen_preferred_over_rejected_by_judge":
+ _check_threshold(merged["threshold"], field="threshold")
+
+
def parse_suite_spec(raw: Any) -> SuiteSpec:
"""Validate a suite dict and return a ``SuiteSpec``."""
if not isinstance(raw, dict):
@@ -748,9 +799,11 @@ def parse_suite_spec(raw: Any) -> SuiteSpec:
if not isinstance(entry, dict):
raise TypeError(f"expectations[{index}] must be a dict")
name = validate_expectation_name(entry.get("name", ""))
+ _validate_entry_keys(index, name, entry)
args = entry.get("args", {})
if not isinstance(args, dict):
raise TypeError(f"expectations[{index}].args must be a dict")
+ _validate_args(index, name, args)
items.append(ExpectationSpec(name=name, args=dict(args)))
return SuiteSpec(expectations=tuple(items))
@@ -808,14 +861,14 @@ def _dispatch_expectation(
bypassing ``_check_token_bound`` bool-rejection.
"""
name = spec.name
- args = dict(spec.args)
+ args = {**_EXPECTATION_ARGS.get(name, {}), **spec.args}
if name == "expect_no_pii":
return expect_no_pii(rows)
if name == "expect_token_length_between":
return expect_token_length_between(
rows,
- min_tokens=args.get("min_tokens", 1),
- max_tokens=args.get("max_tokens", _MAX_TOKEN_BOUND),
+ min_tokens=args["min_tokens"],
+ max_tokens=args["max_tokens"],
)
if name == "expect_no_refusal_pattern":
return expect_no_refusal_pattern(rows)
@@ -823,7 +876,7 @@ def _dispatch_expectation(
return expect_chosen_preferred_over_rejected_by_judge(
rows,
judge_fn=judge_fn,
- threshold=args.get("threshold", 0.7),
+ threshold=args["threshold"],
)
raise ValueError(f"unhandled expectation: {name!r}") # pragma: no cover
diff --git a/tests/test_issue1428_suite_unknown_keys.py b/tests/test_issue1428_suite_unknown_keys.py
new file mode 100644
index 00000000..080a840b
--- /dev/null
+++ b/tests/test_issue1428_suite_unknown_keys.py
@@ -0,0 +1,247 @@
+"""#1428: ``soup expect`` refuses suite keys and argument names an expectation does not take.
+
+Before this fix ``parse_suite_spec`` read ``name`` and ``args`` and dropped every other
+key, and ``_dispatch_expectation`` read arguments with ``args.get(key, default)``. The
+``docs/compliance.md`` example, which wrote ``min_tokens`` / ``max_tokens`` beside
+``name``, therefore ran with the defaults (1 .. 1,048,576 tokens) and passed a
+5000-token row. A misspelled argument did the same. The gate that ran was not the
+gate the user wrote, and nothing said so.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+from pathlib import Path
+
+import pytest
+from typer.testing import CliRunner
+
+from soup_cli.cli import app
+from soup_cli.utils import expectations
+from soup_cli.utils.expectations import parse_suite_yaml
+
+_ROOT = Path(__file__).resolve().parents[1]
+_COMPLIANCE_MD = _ROOT / "docs" / "compliance.md"
+_DATA_MD = _ROOT / "docs" / "data.md"
+
+# The docs/compliance.md example, verbatim as shipped before the fix (issue body).
+_SIBLING_FORM = (
+ "expectations:\n"
+ " - name: expect_no_pii\n"
+ " - name: expect_token_length_between\n"
+ " min_tokens: 1\n"
+ " max_tokens: 512\n"
+)
+_MISSPELLED = "expectations:\n - name: expect_token_length_between\n args: {max_token: 512}\n"
+_CONTROL = "expectations:\n - name: expect_token_length_between\n args: {max_tokens: 512}\n"
+_LONG_ROW = json.dumps({"text": "word " * 5000}) + "\n"
+
+
+def _plain(text: str) -> str:
+ return re.sub(r"\x1b\[[0-9;?]*[A-Za-z]", "", text)
+
+
+def _compliance_suite() -> str:
+ """The ``expectations.yaml`` block of docs/compliance.md, read from the file."""
+ blocks = re.findall(
+ r"```yaml\n(expectations:\n.*?)```", _COMPLIANCE_MD.read_text(encoding="utf-8"), re.S
+ )
+ assert len(blocks) == 1, blocks
+ return blocks[0]
+
+
+def _data_md_suite() -> str:
+ """The ``suite.yaml`` heredoc of docs/data.md (the ``args:`` form), read from the file."""
+ match = re.search(
+ r"^expectations:\n((?: - .*\n)+)EOF$", _DATA_MD.read_text(encoding="utf-8"), re.M
+ )
+ assert match is not None
+ return "expectations:\n" + match.group(1)
+
+
+def _run(tmp_path: Path, suite_text: str, row: str) -> tuple[int, str]:
+ (tmp_path / "data.jsonl").write_text(row, encoding="utf-8")
+ (tmp_path / "suite.yaml").write_text(suite_text, encoding="utf-8")
+ result = CliRunner().invoke(app, ["expect", "data.jsonl", "suite.yaml"])
+ return result.exit_code, _plain(result.output)
+
+
+class TestKeysBesideName:
+ def test_the_compliance_md_sibling_form_names_both_keys_and_args(self) -> None:
+ with pytest.raises(ValueError, match=r"expectations\[1\]") as info:
+ parse_suite_yaml(_SIBLING_FORM)
+ message = str(info.value)
+ assert "min_tokens" in message and "max_tokens" in message
+ assert "under 'args:'" in message
+
+ def test_judge_threshold_beside_name_is_refused(self) -> None:
+ text = (
+ "expectations:\n"
+ " - name: expect_chosen_preferred_over_rejected_by_judge\n"
+ " threshold: 0.9\n"
+ )
+ with pytest.raises(ValueError, match="threshold") as info:
+ parse_suite_yaml(text)
+ assert "under 'args:'" in str(info.value)
+
+ def test_a_key_that_is_no_argument_anywhere_is_refused(self) -> None:
+ text = "expectations:\n - name: expect_no_pii\n severity: high\n"
+ with pytest.raises(ValueError, match="severity") as info:
+ parse_suite_yaml(text)
+ assert "name" in str(info.value) and "args" in str(info.value)
+
+
+class TestUnknownArgumentNames:
+ def test_misspelled_argument_is_refused_with_the_nearest_name(self) -> None:
+ with pytest.raises(ValueError, match="max_token") as info:
+ parse_suite_yaml(_MISSPELLED)
+ assert "did you mean 'max_tokens'" in str(info.value)
+
+ def test_an_argument_on_an_expectation_taking_none_is_refused(self) -> None:
+ text = "expectations:\n - name: expect_no_pii\n args: {threshold: 0.5}\n"
+ with pytest.raises(ValueError, match="threshold") as info:
+ parse_suite_yaml(text)
+ assert "expect_no_pii" in str(info.value)
+
+ def test_the_first_unknown_argument_is_reported_by_index(self) -> None:
+ text = (
+ "expectations:\n"
+ " - name: expect_no_pii\n"
+ " - name: expect_token_length_between\n"
+ " args: {min_tokens: 1, max_tokenz: 5}\n"
+ )
+ with pytest.raises(ValueError, match=r"expectations\[1\]"):
+ parse_suite_yaml(text)
+
+
+class TestValuesAreCheckedAtParseTime:
+ def test_min_above_max_is_refused_before_any_data_is_read(self) -> None:
+ text = (
+ "expectations:\n"
+ " - name: expect_token_length_between\n"
+ " args: {min_tokens: 10, max_tokens: 5}\n"
+ )
+ with pytest.raises(ValueError, match="min_tokens"):
+ parse_suite_yaml(text)
+
+ def test_out_of_range_threshold_is_refused(self) -> None:
+ text = (
+ "expectations:\n"
+ " - name: expect_chosen_preferred_over_rejected_by_judge\n"
+ " args: {threshold: 1.5}\n"
+ )
+ with pytest.raises(ValueError, match="threshold"):
+ parse_suite_yaml(text)
+
+ def test_bool_token_bound_is_refused(self) -> None:
+ text = (
+ "expectations:\n - name: expect_token_length_between\n args: {max_tokens: true}\n"
+ )
+ with pytest.raises(TypeError, match="max_tokens"):
+ parse_suite_yaml(text)
+
+
+class TestControls:
+ def test_the_args_form_still_loads(self) -> None:
+ spec = parse_suite_yaml(_CONTROL)
+ assert dict(spec.expectations[0].args) == {"max_tokens": 512}
+
+ def test_no_args_expectations_still_load(self) -> None:
+ text = (
+ "expectations:\n"
+ " - name: expect_no_pii\n"
+ " - name: expect_no_refusal_pattern\n"
+ " - name: expect_token_length_between\n"
+ " args: {}\n"
+ )
+ assert [e.name for e in parse_suite_yaml(text).expectations] == [
+ "expect_no_pii",
+ "expect_no_refusal_pattern",
+ "expect_token_length_between",
+ ]
+
+ def test_the_docs_data_md_suite_still_loads(self) -> None:
+ spec = parse_suite_yaml(_data_md_suite())
+ assert len(spec.expectations) == 3
+
+ def test_every_supported_expectation_declares_its_arguments(self) -> None:
+ assert set(expectations._EXPECTATION_ARGS) == set(expectations.SUPPORTED_EXPECTATIONS)
+
+
+class TestSoupExpectCli:
+ def test_sibling_form_exits_3_before_the_data_is_opened(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ import soup_cli.commands.expect as expect_mod
+
+ def _never(_path: str) -> list:
+ raise AssertionError("the data file was opened before the suite was refused")
+
+ monkeypatch.setattr(expect_mod, "_load_jsonl_rows", _never)
+ monkeypatch.chdir(tmp_path)
+ code, out = _run(tmp_path, _SIBLING_FORM, _LONG_ROW)
+ assert code == 3, out
+ assert "min_tokens" in out and "args" in out
+
+ def test_misspelled_argument_exits_3(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ monkeypatch.chdir(tmp_path)
+ code, out = _run(tmp_path, _MISSPELLED, _LONG_ROW)
+ assert code == 3, out
+ assert "max_token" in out and "max_tokens" in out
+
+ def test_control_args_form_still_fails_the_long_row_with_exit_2(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ monkeypatch.chdir(tmp_path)
+ code, out = _run(tmp_path, _CONTROL, _LONG_ROW)
+ assert code == 2, out
+ assert "FAIL" in out
+
+ def test_control_no_args_suite_passes_a_clean_row(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ monkeypatch.chdir(tmp_path)
+ text = "expectations:\n - name: expect_no_pii\n - name: expect_no_refusal_pattern\n"
+ code, out = _run(tmp_path, text, '{"text": "a short clean row"}\n')
+ assert code == 0, out
+
+ def test_control_token_length_without_args_runs_on_its_default_bound(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ monkeypatch.chdir(tmp_path)
+ suite = "expectations:\n - name: expect_token_length_between\n"
+ code, out = _run(tmp_path, suite, _LONG_ROW)
+ assert code == 0, out
+
+ def test_a_terminal_escape_in_a_key_name_does_not_reach_the_terminal(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ monkeypatch.chdir(tmp_path)
+ # YAML's ``\e`` escape yields a real ESC byte in the key once parsed.
+ text = 'expectations:\n - name: expect_no_pii\n "\\e[2Jsev": 1\n'
+ (tmp_path / "data.jsonl").write_text('{"text": "x"}\n', encoding="utf-8")
+ (tmp_path / "suite.yaml").write_text(text, encoding="utf-8")
+ result = CliRunner().invoke(app, ["expect", "data.jsonl", "suite.yaml"])
+ assert result.exit_code == 3, result.output
+ assert "sev" in _plain(result.output) # the key is echoed ...
+ assert "\x1b[2J" not in result.output # ... but never as a raw control sequence
+
+
+class TestTheDocsExampleIsAGateThatGates:
+ def test_compliance_md_suite_fails_a_5000_token_row(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ monkeypatch.chdir(tmp_path)
+ code, out = _run(tmp_path, _compliance_suite(), _LONG_ROW)
+ assert code == 2, out
+ assert "FAIL" in out
+
+ def test_compliance_md_suite_passes_a_short_clean_row(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ monkeypatch.chdir(tmp_path)
+ code, out = _run(tmp_path, _compliance_suite(), '{"text": "a short clean row"}\n')
+ assert code == 0, out