pgchangeling 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pgchangeling/cover.py ADDED
@@ -0,0 +1,123 @@
1
+ """Branch coverage of the original while a tape is recorded.
2
+
3
+ A tape proves only the calls it holds. This measures how much of the original those calls
4
+ ran: coverage.py in branch mode, scoped to the recorded modules, switched on only inside
5
+ recorded calls (plus the module's import, so its `def` lines count as run). Code that the
6
+ workload runs outside a recorded call does not count, because the tape does not drive it.
7
+
8
+ coverage.py is an optional extra; `CoverageProbe` raises `CoverageMissing` without it.
9
+ Calls made on a thread other than the one that started recording are measured only when
10
+ coverage.py traces that thread (it does with its `sysmon` core, Python 3.12 and later).
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import os
17
+ import sys
18
+ import tempfile
19
+ import threading
20
+ from collections.abc import Iterator, Sequence
21
+ from contextlib import contextmanager
22
+ from pathlib import Path
23
+ from typing import Any
24
+
25
+
26
+ class CoverageMissing(RuntimeError):
27
+ """coverage.py is not installed."""
28
+
29
+
30
+ def coverage_path(tape: Path | str) -> Path:
31
+ """Where the coverage of `tape` goes: `shadow/suite.jsonl` -> `shadow/suite.coverage.json`."""
32
+ p = Path(tape)
33
+ return p.with_name(p.stem + ".coverage.json") if p.suffix else p.with_name(
34
+ p.name + ".coverage.json")
35
+
36
+
37
+ def scope_of(targets: Sequence[str]) -> list[str]:
38
+ """The modules of `module:qualname` targets, in first-seen order."""
39
+ out: list[str] = []
40
+ for t in targets:
41
+ mod = t.partition(":")[0]
42
+ if mod and mod not in out:
43
+ out.append(mod)
44
+ return out
45
+
46
+
47
+ def _short(path: str) -> str:
48
+ """`path` relative to the longest sys.path entry that holds it, so the report does not
49
+ depend on where the original was installed."""
50
+ full = os.path.abspath(path)
51
+ best = ""
52
+ for entry in sys.path:
53
+ root = os.path.abspath(entry or os.getcwd())
54
+ if full.startswith(root + os.sep) and len(root) > len(best):
55
+ best = root
56
+ return os.path.relpath(full, best).replace(os.sep, "/") if best else full
57
+
58
+
59
+ class CoverageProbe:
60
+ """coverage.py over `scope` (module or package names), on only inside `during()`."""
61
+
62
+ def __init__(self, scope: Sequence[str]) -> None:
63
+ try:
64
+ import coverage
65
+ except ImportError as exc:
66
+ raise CoverageMissing(
67
+ "--coverage needs coverage.py; install it in the interpreter that records "
68
+ "(pip install coverage)") from exc
69
+ self.scope = list(scope)
70
+ self.version = str(coverage.__version__)
71
+ self._cov = coverage.Coverage(branch=True, source_pkgs=self.scope, data_file=None,
72
+ config_file=False, messages=False)
73
+ self._lock = threading.Lock()
74
+ self._active = 0
75
+
76
+ @contextmanager
77
+ def during(self) -> Iterator[None]:
78
+ """Measure inside the block. Nested and concurrent blocks share one measurement."""
79
+ with self._lock:
80
+ self._active += 1
81
+ if self._active == 1:
82
+ self._cov.start()
83
+ try:
84
+ yield
85
+ finally:
86
+ with self._lock:
87
+ self._active -= 1
88
+ if self._active == 0:
89
+ self._cov.stop()
90
+
91
+ def report(self) -> dict[str, Any]:
92
+ """Lines and branches run, overall and per file, with what never ran."""
93
+ fd, tmp = tempfile.mkstemp(suffix=".json")
94
+ os.close(fd)
95
+ try:
96
+ self._cov.json_report(outfile=tmp, ignore_errors=True)
97
+ raw = json.loads(Path(tmp).read_text(encoding="utf-8"))
98
+ finally:
99
+ os.unlink(tmp)
100
+ files: dict[str, Any] = {}
101
+ lines = [0, 0]
102
+ branches = [0, 0]
103
+ for name, data in sorted(raw.get("files", {}).items(), key=lambda kv: _short(kv[0])):
104
+ s = data["summary"]
105
+ fl = [int(s["covered_lines"]), int(s["num_statements"])]
106
+ fb = [int(s.get("covered_branches", 0)), int(s.get("num_branches", 0))]
107
+ lines = [lines[0] + fl[0], lines[1] + fl[1]]
108
+ branches = [branches[0] + fb[0], branches[1] + fb[1]]
109
+ files[_short(name)] = {
110
+ "lines": fl, "branches": fb,
111
+ "missing_lines": sorted(int(n) for n in data.get("missing_lines", [])),
112
+ "missing_branches": sorted([int(a), int(b)]
113
+ for a, b in data.get("missing_branches", [])),
114
+ }
115
+ return {"tool": f"coverage.py {self.version} --branch", "scope": self.scope,
116
+ "lines": lines, "branches": branches, "files": files}
117
+
118
+
119
+ def write_report(path: Path | str, report: dict[str, Any]) -> None:
120
+ Path(path).write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
121
+
122
+
123
+ __all__ = ["CoverageMissing", "CoverageProbe", "coverage_path", "scope_of", "write_report"]
@@ -0,0 +1,263 @@
1
+ """`shadow/verification.json`: what was measured about a port, kept next to its tapes.
2
+
3
+ `write` fills in what can be computed (each tape's sha256, its calls, and how many the
4
+ port matched, by replaying it or from a saved replay report), merges coverage reports and a
5
+ mutation report, and keeps every field a person wrote. `check` recomputes the same numbers
6
+ and fails when a tape's hash or counts no longer agree with the file. Both validate the
7
+ file against `verification.schema.json`, which ships with the package.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import datetime as _dt
13
+ import hashlib
14
+ import json
15
+ import re
16
+ from collections.abc import Mapping, Sequence
17
+ from pathlib import Path
18
+ from typing import Any
19
+
20
+ ROLES = ("suite", "random", "holdout", "edge", "fuzz")
21
+ SCHEMA_PATH = Path(__file__).with_name("verification.schema.json")
22
+
23
+
24
+ def schema() -> dict[str, Any]:
25
+ data: dict[str, Any] = json.loads(SCHEMA_PATH.read_text(encoding="utf-8"))
26
+ return data
27
+
28
+
29
+ # --- a small validator for the parts of JSON Schema the contract uses -----------------------
30
+
31
+ _TYPES: dict[str, tuple[type, ...]] = {
32
+ "object": (dict,), "array": (list,), "string": (str,), "integer": (int,),
33
+ "number": (int, float), "boolean": (bool,), "null": (type(None),)}
34
+
35
+
36
+ def _type_ok(value: Any, name: str) -> bool:
37
+ if isinstance(value, bool) and name in ("integer", "number"):
38
+ return False
39
+ return isinstance(value, _TYPES[name])
40
+
41
+
42
+ def validate(doc: Any, sch: Mapping[str, Any] | None = None, path: str = "$") -> list[str]:
43
+ """Every way `doc` breaks the schema, as `path: problem` lines; empty when it fits."""
44
+ sch = schema() if sch is None else sch
45
+ errors: list[str] = []
46
+ want = sch.get("type")
47
+ if want is not None:
48
+ names = [want] if isinstance(want, str) else list(want)
49
+ if not any(_type_ok(doc, n) for n in names):
50
+ return [f"{path}: expected {' or '.join(names)}, got {type(doc).__name__}"]
51
+ if "enum" in sch and doc not in sch["enum"]:
52
+ errors.append(f"{path}: {doc!r} is not one of {sch['enum']}")
53
+ if "pattern" in sch and isinstance(doc, str) and not re.search(sch["pattern"], doc):
54
+ errors.append(f"{path}: {doc!r} does not match {sch['pattern']}")
55
+ if isinstance(doc, dict):
56
+ for key in sch.get("required", []):
57
+ if key not in doc:
58
+ errors.append(f"{path}: missing {key!r}")
59
+ props = sch.get("properties", {})
60
+ extra = sch.get("additionalProperties", True)
61
+ for key, value in doc.items():
62
+ if key in props:
63
+ errors += validate(value, props[key], f"{path}.{key}")
64
+ elif isinstance(extra, dict):
65
+ errors += validate(value, extra, f"{path}.{key}")
66
+ elif extra is False:
67
+ errors.append(f"{path}: unexpected {key!r}")
68
+ if isinstance(doc, list) and "items" in sch:
69
+ for i, item in enumerate(doc):
70
+ errors += validate(item, sch["items"], f"{path}[{i}]")
71
+ return errors
72
+
73
+
74
+ # --- measuring tapes ------------------------------------------------------------------------
75
+
76
+ def sha256(path: Path | str) -> str:
77
+ h = hashlib.sha256()
78
+ with open(path, "rb") as f:
79
+ for block in iter(lambda: f.read(1 << 20), b""):
80
+ h.update(block)
81
+ return h.hexdigest()
82
+
83
+
84
+ def count_calls(path: Path | str) -> int:
85
+ from . import load_tape
86
+
87
+ return len(load_tape(path))
88
+
89
+
90
+ def matched_from_report(report: Mapping[str, Any]) -> tuple[int, int]:
91
+ """(calls, matched) from the JSON a replay writes with `--out`."""
92
+ calls = int(report["calls"])
93
+ failed = sum(len(g.get("results", [])) for g in report.get("groups", []))
94
+ return calls, calls - failed
95
+
96
+
97
+ def matched_by_replay(tape: Path, command: Sequence[str], cwd: Path,
98
+ timeout_s: float = 30.0) -> tuple[int, int]:
99
+ from . import Adapter, load_tape, replay
100
+
101
+ results = replay(load_tape(tape), Adapter(command, cwd=cwd, timeout_s=timeout_s))
102
+ return len(results), sum(r.ok for r in results)
103
+
104
+
105
+ def role_of(path: Path | str) -> str | None:
106
+ """The role a tape's name gives: `shadow/holdout.jsonl` is a holdout tape."""
107
+ stem = Path(path).stem.lower()
108
+ for role in ROLES:
109
+ if stem == role or stem.startswith(role + "-") or stem.startswith(role + "_"):
110
+ return role
111
+ return None
112
+
113
+
114
+ def measure(root: Path, tapes: Sequence[Path], *, roles: Mapping[str, str] | None = None,
115
+ command: Sequence[str] | None = None, reports: Mapping[str, Path] | None = None,
116
+ timeout_s: float = 30.0) -> list[dict[str, Any]]:
117
+ """One entry per tape: file (relative to `root`), role, sha256, calls and, when a replay
118
+ command or report is given, matched."""
119
+ roles = dict(roles or {})
120
+ reports = dict(reports or {})
121
+ out: list[dict[str, Any]] = []
122
+ for tape in tapes:
123
+ full = tape if tape.is_absolute() else root / tape
124
+ rel = full.resolve().relative_to(root.resolve()).as_posix()
125
+ role = roles.get(rel) or roles.get(full.name) or role_of(full)
126
+ if role is None:
127
+ raise ValueError(f"{rel}: give its role with --role {full.name}=<"
128
+ + "|".join(ROLES) + ">")
129
+ entry: dict[str, Any] = {"file": rel, "role": role, "sha256": sha256(full),
130
+ "calls": count_calls(full)}
131
+ report = reports.get(rel) or reports.get(full.name)
132
+ if report is not None:
133
+ calls, matched = matched_from_report(json.loads(Path(report).read_text("utf-8")))
134
+ if calls != entry["calls"]:
135
+ raise ValueError(f"{rel}: the report has {calls} calls, the tape "
136
+ f"{entry['calls']}")
137
+ entry["matched"] = matched
138
+ elif command:
139
+ _, entry["matched"] = matched_by_replay(full, command, root, timeout_s)
140
+ out.append(entry)
141
+ return out
142
+
143
+
144
+ # --- coverage and mutation ------------------------------------------------------------------
145
+
146
+ def merge_coverage(reports: Mapping[str, Mapping[str, Any]],
147
+ old: Mapping[str, Any] | None = None) -> dict[str, Any]:
148
+ """The `coverage` field from per-tape coverage reports (keyed by role): what all the
149
+ tapes ran together, and each tape alone. A line counts as run when any tape ran it."""
150
+ old = dict(old or {})
151
+ first = next(iter(reports.values()))
152
+ files: dict[str, dict[str, Any]] = {}
153
+ for rep in reports.values():
154
+ for name, f in rep.get("files", {}).items():
155
+ cur = files.setdefault(name, {
156
+ "lines": f["lines"][1], "branches": f["branches"][1],
157
+ "missing_lines": {int(n) for n in f["missing_lines"]},
158
+ "missing_branches": {tuple(b) for b in f["missing_branches"]}})
159
+ cur["missing_lines"] &= {int(n) for n in f["missing_lines"]}
160
+ cur["missing_branches"] &= {tuple(b) for b in f["missing_branches"]}
161
+ lt = sum(f["lines"] for f in files.values())
162
+ bt = sum(f["branches"] for f in files.values())
163
+ lm = sum(len(f["missing_lines"]) for f in files.values())
164
+ bm = sum(len(f["missing_branches"]) for f in files.values())
165
+ out: dict[str, Any] = {
166
+ "tool": first["tool"],
167
+ "scope": sorted({s for r in reports.values() for s in r.get("scope", [])}),
168
+ "lines": [lt - lm, lt], "branches": [bt - bm, bt],
169
+ "by_tape": {role: {"lines": r["lines"], "branches": r["branches"]}
170
+ for role, r in reports.items()},
171
+ }
172
+ if "missed" in old:
173
+ out["missed"] = old["missed"] # a person's notes
174
+ return out
175
+
176
+
177
+ def merge_mutation(new: Mapping[str, Any], old: Mapping[str, Any] | None = None
178
+ ) -> dict[str, Any]:
179
+ """`new` (a mutate report's `mutation`), keeping each survivor's `why` a person wrote."""
180
+ why = {(s["where"], s["change"]): s["why"] for s in (old or {}).get("survivors", [])
181
+ if "why" in s}
182
+ out = dict(new)
183
+ out["survivors"] = [{**s, **({"why": why[(s["where"], s["change"])]}
184
+ if (s["where"], s["change"]) in why else {})}
185
+ for s in new.get("survivors", [])]
186
+ return out
187
+
188
+
189
+ # --- the file -------------------------------------------------------------------------------
190
+
191
+ def load(path: Path) -> dict[str, Any]:
192
+ data: dict[str, Any] = json.loads(path.read_text(encoding="utf-8"))
193
+ return data
194
+
195
+
196
+ def dump(path: Path, doc: Mapping[str, Any]) -> None:
197
+ path.parent.mkdir(parents=True, exist_ok=True)
198
+ path.write_text(json.dumps(doc, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
199
+
200
+
201
+ def write(path: Path, *, port: str, tapes: Sequence[Mapping[str, Any]],
202
+ coverage: Mapping[str, Mapping[str, Any]] | None = None,
203
+ mutation: Mapping[str, Any] | None = None,
204
+ today: str | None = None) -> dict[str, Any]:
205
+ """Update (or start) the file at `path`: measured fields replaced, the rest kept."""
206
+ doc: dict[str, Any] = load(path) if path.exists() else {"port": port}
207
+ doc.setdefault("port", port)
208
+ old_tapes = {t["file"]: t for t in doc.get("tapes", [])}
209
+ merged = []
210
+ for t in tapes:
211
+ keep = {k: v for k, v in old_tapes.get(t["file"], {}).items()
212
+ if k in ("seed", "origin")}
213
+ merged.append({"file": t["file"], "role": t["role"], "sha256": t["sha256"],
214
+ "calls": t["calls"],
215
+ **({"matched": t["matched"]} if "matched" in t else {}), **keep})
216
+ doc["tapes"] = merged
217
+ if coverage:
218
+ doc["coverage"] = merge_coverage(coverage, doc.get("coverage"))
219
+ if mutation:
220
+ doc["mutation"] = merge_mutation(mutation, doc.get("mutation"))
221
+ if any("matched" in t for t in tapes):
222
+ doc["verified"] = today or _dt.date.today().isoformat()
223
+ problems = validate(doc)
224
+ if problems:
225
+ raise ValueError("the result does not fit the schema:\n" + "\n".join(problems))
226
+ dump(path, doc)
227
+ return doc
228
+
229
+
230
+ def check(path: Path, root: Path, *, command: Sequence[str] | None = None,
231
+ reports: Mapping[str, Path] | None = None, timeout_s: float = 30.0) -> list[str]:
232
+ """Every way the file disagrees with the tapes on disk (and, given a replay command or
233
+ reports, with what the port matches now). Empty when it all holds."""
234
+ if not path.exists():
235
+ return [f"{path}: missing"]
236
+ doc = load(path)
237
+ problems = validate(doc)
238
+ for t in doc.get("tapes", []) if isinstance(doc.get("tapes"), list) else []:
239
+ if not isinstance(t, dict) or "file" not in t:
240
+ continue
241
+ full = root / t["file"]
242
+ if not full.exists():
243
+ problems.append(f"{t['file']}: the tape is missing")
244
+ continue
245
+ if sha256(full) != t.get("sha256"):
246
+ problems.append(f"{t['file']}: sha256 changed")
247
+ calls = count_calls(full)
248
+ if calls != t.get("calls"):
249
+ problems.append(f"{t['file']}: {calls} calls, the file says {t.get('calls')}")
250
+ rep = (reports or {}).get(t["file"]) or (reports or {}).get(full.name)
251
+ matched: int | None = None
252
+ if rep is not None:
253
+ matched = matched_from_report(json.loads(Path(rep).read_text("utf-8")))[1]
254
+ elif command:
255
+ matched = matched_by_replay(full, command, root, timeout_s)[1]
256
+ if matched is not None and matched != t.get("matched"):
257
+ problems.append(f"{t['file']}: {matched} calls match, the file says "
258
+ f"{t.get('matched')}")
259
+ return problems
260
+
261
+
262
+ __all__ = ["ROLES", "SCHEMA_PATH", "check", "count_calls", "measure", "merge_coverage",
263
+ "merge_mutation", "role_of", "schema", "sha256", "validate", "write"]
@@ -0,0 +1,61 @@
1
+ """Mirror: differential runs of one HTTP API across two or more local servers.
2
+
3
+ Typical use::
4
+
5
+ run = mirror_main("cases.toml", {"python": "http://127.0.0.1:8001",
6
+ "rust": "http://127.0.0.1:8002"}, "my-model", "out/")
7
+ delta = compare_runs(load_run("base/run.json"), run)
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from pgchangeling.mirror.cases import Expectation, MirrorCase, load_cases, parse_cases
13
+ from pgchangeling.mirror.compare import compare_case, compare_runs
14
+ from pgchangeling.mirror.models import (
15
+ CaseResult,
16
+ DiffKind,
17
+ Discrepancy,
18
+ MirrorDelta,
19
+ MirrorRun,
20
+ Outcome,
21
+ Verdict,
22
+ verdict_for,
23
+ )
24
+ from pgchangeling.mirror.normalize import normalize_json, parse_path
25
+ from pgchangeling.mirror.render import render_markdown
26
+ from pgchangeling.mirror.runner import (
27
+ UnsafeTargetError,
28
+ check_local_url,
29
+ load_run,
30
+ mirror_main,
31
+ parse_sse,
32
+ run_cases,
33
+ run_to_json,
34
+ )
35
+
36
+ __all__ = [
37
+ "CaseResult",
38
+ "DiffKind",
39
+ "Discrepancy",
40
+ "Expectation",
41
+ "MirrorCase",
42
+ "MirrorDelta",
43
+ "MirrorRun",
44
+ "Outcome",
45
+ "UnsafeTargetError",
46
+ "Verdict",
47
+ "check_local_url",
48
+ "compare_case",
49
+ "compare_runs",
50
+ "load_cases",
51
+ "load_run",
52
+ "mirror_main",
53
+ "normalize_json",
54
+ "parse_cases",
55
+ "parse_path",
56
+ "parse_sse",
57
+ "render_markdown",
58
+ "run_cases",
59
+ "run_to_json",
60
+ "verdict_for",
61
+ ]
@@ -0,0 +1,180 @@
1
+ """Mirror cases and the TOML case-file format.
2
+
3
+ A case file has an optional ``[defaults]`` table, any number of ``[[case]]`` tables and any
4
+ number of ``[[sweep]]`` tables::
5
+
6
+ [defaults]
7
+ path = "/v1/completions"
8
+ json = { model = "{model}", prompt = "Hello", temperature = 0 }
9
+
10
+ [[case]]
11
+ name = "too-long"
12
+ json = { max_tokens = 100000 }
13
+ expect = { status = 400, error_type = "BadRequestError" }
14
+ normalize = ["choices[*].logprobs"]
15
+
16
+ [[sweep]]
17
+ name = "max-tokens"
18
+ param = "max_tokens" # dotted for nested fields
19
+ values = [0, 1, 512, 513] # one case per value, named max-tokens-0, ...
20
+
21
+ Defaults fill keys a case does not set; ``json`` bodies merge, the case winning. The string
22
+ ``{model}`` anywhere in a body is replaced with the served model name at run time.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import copy
28
+ import json
29
+ import tomllib
30
+ from pathlib import Path
31
+ from typing import Any
32
+
33
+ from pydantic import BaseModel, ConfigDict, Field, field_validator
34
+
35
+ from pgchangeling.mirror.normalize import parse_path
36
+
37
+ METHODS = frozenset({"GET", "POST"})
38
+ MODEL_PLACEHOLDER = "{model}"
39
+
40
+
41
+ class Expectation(BaseModel):
42
+ """What an external spec says the response must be. Checked against every side."""
43
+
44
+ model_config = ConfigDict(extra="forbid")
45
+
46
+ status: int | None = None
47
+ error_type: str | None = None
48
+ # Strings no generated text may contain, e.g. the prompt itself (a prompt leak).
49
+ text_excludes: list[str] = Field(default_factory=list)
50
+
51
+
52
+ class MirrorCase(BaseModel):
53
+ model_config = ConfigDict(extra="forbid")
54
+
55
+ name: str = Field(min_length=1)
56
+ method: str = "POST"
57
+ path: str
58
+ body: dict[str, Any] = Field(default_factory=dict)
59
+ stream: bool = False
60
+ tags: list[str] = Field(default_factory=list)
61
+ expect: Expectation | None = None
62
+ normalize: list[str] = Field(default_factory=list) # extra JSON paths to drop
63
+ exact_error_message: bool = False
64
+
65
+ @field_validator("method")
66
+ @classmethod
67
+ def _method(cls, v: str) -> str:
68
+ v = v.upper()
69
+ if v not in METHODS:
70
+ raise ValueError(f"method must be one of {sorted(METHODS)}, got {v!r}")
71
+ return v
72
+
73
+ @field_validator("path")
74
+ @classmethod
75
+ def _path(cls, v: str) -> str:
76
+ if not v.startswith("/") or v.startswith("//") or "://" in v or any(
77
+ c.isspace() for c in v
78
+ ):
79
+ raise ValueError(f"path must be a plain absolute path like /v1/completions: {v!r}")
80
+ return v
81
+
82
+ @field_validator("normalize")
83
+ @classmethod
84
+ def _normalize(cls, v: list[str]) -> list[str]:
85
+ for p in v:
86
+ parse_path(p)
87
+ return v
88
+
89
+ def render_body(self, model: str) -> dict[str, Any]:
90
+ """The request body with ``{model}`` substituted. The case itself is not changed."""
91
+ return _substitute(copy.deepcopy(self.body), model) # type: ignore[no-any-return]
92
+
93
+
94
+ def _substitute(obj: Any, model: str) -> Any:
95
+ if isinstance(obj, str):
96
+ return obj.replace(MODEL_PLACEHOLDER, model)
97
+ if isinstance(obj, dict):
98
+ return {k: _substitute(v, model) for k, v in obj.items()}
99
+ if isinstance(obj, list):
100
+ return [_substitute(v, model) for v in obj]
101
+ return obj
102
+
103
+
104
+ def _value_label(value: Any) -> str:
105
+ if isinstance(value, str):
106
+ return value
107
+ return json.dumps(value)
108
+
109
+
110
+ def _set_dotted(body: dict[str, Any], param: str, value: Any) -> None:
111
+ keys = param.split(".")
112
+ if any(not k for k in keys):
113
+ raise ValueError(f"bad sweep param {param!r}")
114
+ target = body
115
+ for key in keys[:-1]:
116
+ nxt = target.setdefault(key, {})
117
+ if not isinstance(nxt, dict):
118
+ raise ValueError(f"sweep param {param!r} crosses a non-table value")
119
+ target = nxt
120
+ target[keys[-1]] = copy.deepcopy(value)
121
+
122
+
123
+ def _with_defaults(raw: dict[str, Any], defaults: dict[str, Any]) -> dict[str, Any]:
124
+ if "body" in raw or "body" in defaults:
125
+ raise ValueError("the request body key is `json`, not `body`")
126
+ merged = {**copy.deepcopy(defaults), **raw}
127
+ body = {**copy.deepcopy(defaults.get("json", {})), **raw.get("json", {})}
128
+ merged.pop("json", None)
129
+ merged["body"] = body
130
+ return merged
131
+
132
+
133
+ def _case(raw: dict[str, Any], where: str) -> MirrorCase:
134
+ try:
135
+ return MirrorCase.model_validate(raw)
136
+ except ValueError as exc:
137
+ raise ValueError(f"{where}: {exc}") from exc
138
+
139
+
140
+ def parse_cases(text: str) -> list[MirrorCase]:
141
+ """Parse a TOML case file. Raises ValueError on any problem, naming the table."""
142
+ try:
143
+ data = tomllib.loads(text)
144
+ except tomllib.TOMLDecodeError as exc:
145
+ raise ValueError(f"case file is not valid TOML: {exc}") from exc
146
+ unknown = set(data) - {"defaults", "case", "sweep"}
147
+ if unknown:
148
+ raise ValueError(f"unknown top-level keys in case file: {sorted(unknown)}")
149
+ defaults = data.get("defaults", {})
150
+ cases: list[MirrorCase] = []
151
+ for i, raw in enumerate(data.get("case", [])):
152
+ cases.append(_case(_with_defaults(raw, defaults), f"case #{i + 1}"))
153
+ for i, raw in enumerate(data.get("sweep", [])):
154
+ where = f"sweep #{i + 1}"
155
+ raw = dict(raw)
156
+ param = raw.pop("param", None)
157
+ values = raw.pop("values", None)
158
+ if not isinstance(param, str) or not param:
159
+ raise ValueError(f"{where}: needs param = \"<field>\"")
160
+ if not isinstance(values, list) or not values:
161
+ raise ValueError(f"{where}: needs a non-empty values list")
162
+ base = _with_defaults(raw, defaults)
163
+ name = base.get("name", param)
164
+ for value in values:
165
+ one = copy.deepcopy(base)
166
+ _set_dotted(one["body"], param, value)
167
+ one["name"] = f"{name}-{_value_label(value)}"
168
+ one["tags"] = [*one.get("tags", []), f"sweep:{param}"]
169
+ cases.append(_case(one, where))
170
+ seen: set[str] = set()
171
+ for c in cases:
172
+ if c.name in seen:
173
+ raise ValueError(f"duplicate case name {c.name!r}")
174
+ seen.add(c.name)
175
+ return cases
176
+
177
+
178
+ def load_cases(path: str | Path) -> list[MirrorCase]:
179
+ """Load cases from a TOML file. See the module docstring for the format."""
180
+ return parse_cases(Path(path).read_text(encoding="utf-8"))