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/__init__.py +353 -0
- pgchangeling/__main__.py +76 -0
- pgchangeling/cli.py +185 -0
- pgchangeling/cover.py +123 -0
- pgchangeling/manifest.py +263 -0
- pgchangeling/mirror/__init__.py +61 -0
- pgchangeling/mirror/cases.py +180 -0
- pgchangeling/mirror/compare.py +332 -0
- pgchangeling/mirror/models.py +118 -0
- pgchangeling/mirror/normalize.py +164 -0
- pgchangeling/mirror/render.py +157 -0
- pgchangeling/mirror/runner.py +209 -0
- pgchangeling/mirror/serve.py +284 -0
- pgchangeling/mutate.py +536 -0
- pgchangeling/py.typed +0 -0
- pgchangeling/runner.py +110 -0
- pgchangeling/verification.schema.json +127 -0
- pgchangeling/verify_cli.py +200 -0
- pgchangeling-0.2.0.dist-info/METADATA +309 -0
- pgchangeling-0.2.0.dist-info/RECORD +24 -0
- pgchangeling-0.2.0.dist-info/WHEEL +4 -0
- pgchangeling-0.2.0.dist-info/entry_points.txt +2 -0
- pgchangeling-0.2.0.dist-info/licenses/LICENSE +202 -0
- pgchangeling-0.2.0.dist-info/licenses/NOTICE +4 -0
pgchangeling/__init__.py
ADDED
|
@@ -0,0 +1,353 @@
|
|
|
1
|
+
"""PGchangeling: prove a port to another language behaves like the original.
|
|
2
|
+
|
|
3
|
+
Tests passing is not enough for a port. A suite covers the paths someone thought of; real
|
|
4
|
+
calls cover the paths that happen. So the proof is shadowing:
|
|
5
|
+
|
|
6
|
+
1. `Recorder` wraps chosen functions of the old code (`module:qualname`) while real work
|
|
7
|
+
runs, and keeps each call's arguments and its result or exception type, as JSON. Calls
|
|
8
|
+
whose values do not survive JSON are skipped and counted, never guessed.
|
|
9
|
+
2. The tape is replayed on the new implementation through an `Adapter`: any program that
|
|
10
|
+
reads one JSON request per line on stdin (`{"fn", "args", "kwargs"}`) and answers one
|
|
11
|
+
JSON line (`{"result": ...}`, `{"error": "TypeName"}` or `{"unsupported": true}`). The
|
|
12
|
+
new code can be Rust, Go or anything else.
|
|
13
|
+
3. Mismatches are compared with a float tolerance and grouped by function and kind, biggest
|
|
14
|
+
group first, so each group becomes one task, with the failing calls as its test. The
|
|
15
|
+
match rate over time is the port's progress line.
|
|
16
|
+
|
|
17
|
+
What makes a mismatch acceptable is a person's call: a stub that makes outputs match
|
|
18
|
+
without doing the work is not a fix.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import functools
|
|
24
|
+
import importlib
|
|
25
|
+
import json
|
|
26
|
+
import math
|
|
27
|
+
import queue
|
|
28
|
+
import subprocess
|
|
29
|
+
import threading
|
|
30
|
+
from collections.abc import Callable, Sequence
|
|
31
|
+
from contextlib import AbstractContextManager, nullcontext
|
|
32
|
+
from pathlib import Path
|
|
33
|
+
from typing import Any
|
|
34
|
+
|
|
35
|
+
from pydantic import BaseModel, Field
|
|
36
|
+
|
|
37
|
+
from pgchangeling.runner import PlainRunner, Runner, scrubbed_env
|
|
38
|
+
|
|
39
|
+
REL_TOL, ABS_TOL = 1e-9, 1e-12
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class Call(BaseModel):
|
|
43
|
+
fn: str
|
|
44
|
+
args: list[Any] = Field(default_factory=list)
|
|
45
|
+
kwargs: dict[str, Any] = Field(default_factory=dict)
|
|
46
|
+
result: Any = None
|
|
47
|
+
error: str | None = None
|
|
48
|
+
# Named module globals (`module:NAME`) as they stood when the call was made; a set is
|
|
49
|
+
# kept as a sorted list. None when the tape records no state.
|
|
50
|
+
state: dict[str, Any] | None = None
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class Result(BaseModel):
|
|
54
|
+
call: Call
|
|
55
|
+
ok: bool
|
|
56
|
+
kind: str # match | value | error | unsupported | crash | protocol
|
|
57
|
+
got: Any = None
|
|
58
|
+
got_error: str | None = None
|
|
59
|
+
detail: str = ""
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class Cluster(BaseModel):
|
|
63
|
+
fn: str
|
|
64
|
+
kind: str
|
|
65
|
+
summary: str
|
|
66
|
+
results: list[Result]
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
# --- recording ------------------------------------------------------------------------------
|
|
70
|
+
|
|
71
|
+
def _plain(value: Any) -> Any:
|
|
72
|
+
"""`value` through a JSON round trip, or raise TypeError or ValueError. Text that cannot
|
|
73
|
+
be written as UTF-8 (a lone surrogate) is refused here, before it can break the tape."""
|
|
74
|
+
text = json.dumps(value, allow_nan=False, ensure_ascii=False)
|
|
75
|
+
text.encode("utf-8") # UnicodeEncodeError is a ValueError
|
|
76
|
+
return json.loads(text)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _state_value(value: Any) -> Any:
|
|
80
|
+
"""A global's value for the tape: sets and frozensets as sorted lists."""
|
|
81
|
+
if isinstance(value, set | frozenset):
|
|
82
|
+
return _plain(sorted(value, key=repr))
|
|
83
|
+
return _plain(value)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _resolve(target: str) -> tuple[Any, str, Callable[..., Any]]:
|
|
87
|
+
module_name, _, qual = target.partition(":")
|
|
88
|
+
if not qual:
|
|
89
|
+
raise ValueError(f"{target!r}: expected module:qualname")
|
|
90
|
+
owner: Any = importlib.import_module(module_name)
|
|
91
|
+
*parents, name = qual.split(".")
|
|
92
|
+
for p in parents:
|
|
93
|
+
owner = getattr(owner, p)
|
|
94
|
+
return owner, name, getattr(owner, name)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class Recorder:
|
|
98
|
+
"""Record calls to `targets` inside the `with` block. Only the outermost recorded call
|
|
99
|
+
on a thread is kept, so a target that calls another target is one call, not two.
|
|
100
|
+
|
|
101
|
+
`around`, when given, makes a context manager that each recorded (outermost) call runs
|
|
102
|
+
inside; the coverage probe uses it. It never changes what the tape holds."""
|
|
103
|
+
|
|
104
|
+
def __init__(self, targets: Sequence[str], *, state: Sequence[str] = (),
|
|
105
|
+
around: Callable[[], AbstractContextManager[Any]] | None = None) -> None:
|
|
106
|
+
self.targets = list(targets)
|
|
107
|
+
self.state_names = list(state)
|
|
108
|
+
self._around = around or nullcontext
|
|
109
|
+
self.calls: list[Call] = []
|
|
110
|
+
self.skipped = 0
|
|
111
|
+
self._saved: list[tuple[Any, str, Any]] = []
|
|
112
|
+
self._depth = threading.local()
|
|
113
|
+
self._lock = threading.Lock()
|
|
114
|
+
|
|
115
|
+
def _wrap(self, target: str, fn: Callable[..., Any], *,
|
|
116
|
+
skip_first: bool = False) -> Callable[..., Any]:
|
|
117
|
+
"""`skip_first`: the wrapped function is a classmethod's, whose first argument is
|
|
118
|
+
the class; it is passed on but not recorded."""
|
|
119
|
+
rec = self
|
|
120
|
+
|
|
121
|
+
@functools.wraps(fn)
|
|
122
|
+
def wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
123
|
+
depth = getattr(rec._depth, "n", 0)
|
|
124
|
+
rec._depth.n = depth + 1
|
|
125
|
+
try:
|
|
126
|
+
if depth:
|
|
127
|
+
return fn(*args, **kwargs)
|
|
128
|
+
try:
|
|
129
|
+
a, k = _plain(list(args[1:] if skip_first else args)), _plain(kwargs)
|
|
130
|
+
except (TypeError, ValueError):
|
|
131
|
+
a = k = None
|
|
132
|
+
before = rec._snapshot() # the state the call starts from
|
|
133
|
+
try:
|
|
134
|
+
with rec._around():
|
|
135
|
+
out = fn(*args, **kwargs)
|
|
136
|
+
except Exception as exc:
|
|
137
|
+
rec._keep(target, a, k, error=type(exc).__name__, state=before)
|
|
138
|
+
raise
|
|
139
|
+
try:
|
|
140
|
+
res = _plain(out)
|
|
141
|
+
except (TypeError, ValueError):
|
|
142
|
+
a = None
|
|
143
|
+
res = None
|
|
144
|
+
rec._keep(target, a, k, result=res, state=before)
|
|
145
|
+
return out
|
|
146
|
+
finally:
|
|
147
|
+
rec._depth.n = depth
|
|
148
|
+
|
|
149
|
+
return wrapper
|
|
150
|
+
|
|
151
|
+
def _keep(self, target: str, args: Any, kwargs: Any, *, result: Any = None,
|
|
152
|
+
error: str | None = None, state: dict[str, Any] | None = None) -> None:
|
|
153
|
+
with self._lock:
|
|
154
|
+
if args is None or kwargs is None:
|
|
155
|
+
self.skipped += 1
|
|
156
|
+
return
|
|
157
|
+
self.calls.append(Call(fn=target, args=args, kwargs=kwargs, result=result,
|
|
158
|
+
error=error, state=state))
|
|
159
|
+
|
|
160
|
+
def _snapshot(self) -> dict[str, Any] | None:
|
|
161
|
+
if not self.state_names:
|
|
162
|
+
return None
|
|
163
|
+
out: dict[str, Any] = {}
|
|
164
|
+
for name in self.state_names:
|
|
165
|
+
owner, attr, _ = _resolve(name) if ":" in name else (None, name, None)
|
|
166
|
+
try:
|
|
167
|
+
out[name] = _state_value(getattr(owner, attr))
|
|
168
|
+
except (TypeError, ValueError, AttributeError):
|
|
169
|
+
out[name] = None
|
|
170
|
+
return out
|
|
171
|
+
|
|
172
|
+
def __enter__(self) -> Recorder:
|
|
173
|
+
for t in self.targets:
|
|
174
|
+
owner, name, fn = _resolve(t)
|
|
175
|
+
raw = vars(owner).get(name) if isinstance(owner, type) else None
|
|
176
|
+
if isinstance(raw, classmethod):
|
|
177
|
+
# Wrap the function, not the bound method, so W.name() still gets W.
|
|
178
|
+
self._saved.append((owner, name, raw))
|
|
179
|
+
setattr(owner, name, classmethod(self._wrap(t, raw.__func__,
|
|
180
|
+
skip_first=True)))
|
|
181
|
+
elif isinstance(raw, staticmethod):
|
|
182
|
+
self._saved.append((owner, name, raw))
|
|
183
|
+
setattr(owner, name, staticmethod(self._wrap(t, raw.__func__)))
|
|
184
|
+
else:
|
|
185
|
+
self._saved.append((owner, name, fn))
|
|
186
|
+
setattr(owner, name, self._wrap(t, fn))
|
|
187
|
+
return self
|
|
188
|
+
|
|
189
|
+
def __exit__(self, *exc: object) -> None:
|
|
190
|
+
for owner, name, fn in reversed(self._saved):
|
|
191
|
+
setattr(owner, name, fn)
|
|
192
|
+
self._saved.clear()
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def save_tape(path: Path | str, calls: Sequence[Call]) -> None:
|
|
196
|
+
Path(path).write_text("".join(c.model_dump_json() + "\n" for c in calls), encoding="utf-8")
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def load_tape(path: Path | str) -> list[Call]:
|
|
200
|
+
# Split on "\n" only: str.splitlines also breaks on U+0085, U+2028 and U+2029, which a
|
|
201
|
+
# recorded string may hold raw inside its JSON.
|
|
202
|
+
return [Call.model_validate_json(line)
|
|
203
|
+
for line in Path(path).read_text(encoding="utf-8").split("\n") if line.strip()]
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
# --- replay ---------------------------------------------------------------------------------
|
|
207
|
+
|
|
208
|
+
class Adapter:
|
|
209
|
+
"""The new implementation, as a long-running JSON-lines process.
|
|
210
|
+
|
|
211
|
+
It starts through `runner` (default: a plain subprocess) with a scrubbed environment:
|
|
212
|
+
the host variables in `pgchangeling.runner.ENV_ALLOWLIST`, those named in `keep_env`,
|
|
213
|
+
then `env`. The plain runner does not isolate the program; see `pgchangeling.runner`.
|
|
214
|
+
"""
|
|
215
|
+
|
|
216
|
+
def __init__(self, argv: Sequence[str], *, cwd: Path | str | None = None,
|
|
217
|
+
timeout_s: float = 30.0, runner: Runner | None = None,
|
|
218
|
+
env: dict[str, str] | None = None, keep_env: Sequence[str] = ()) -> None:
|
|
219
|
+
self.argv, self.cwd, self.timeout_s = list(argv), cwd, timeout_s
|
|
220
|
+
self.runner: Runner = runner or PlainRunner()
|
|
221
|
+
self.env = dict(env or {})
|
|
222
|
+
self.keep_env = list(keep_env)
|
|
223
|
+
|
|
224
|
+
def start(self) -> subprocess.Popen[str]:
|
|
225
|
+
return subprocess.Popen(self.runner.wrap(self.argv), cwd=self.cwd,
|
|
226
|
+
env=scrubbed_env(self.env, self.keep_env),
|
|
227
|
+
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
|
228
|
+
stderr=subprocess.DEVNULL, text=True, bufsize=1)
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def _close(a: Any, b: Any, path: str = "$") -> str | None:
|
|
232
|
+
"""None when equal (floats within tolerance), else where they first differ."""
|
|
233
|
+
if isinstance(a, bool) or isinstance(b, bool):
|
|
234
|
+
return None if a is b or a == b and type(a) is type(b) else path
|
|
235
|
+
if isinstance(a, int) and isinstance(b, int):
|
|
236
|
+
return None if a == b else path # exactly: past 2**53 a float would blur them
|
|
237
|
+
if isinstance(a, int | float) and isinstance(b, int | float):
|
|
238
|
+
try:
|
|
239
|
+
return None if math.isclose(a, b, rel_tol=REL_TOL, abs_tol=ABS_TOL) else path
|
|
240
|
+
except OverflowError: # an int too big for a float cannot equal a float
|
|
241
|
+
return path
|
|
242
|
+
if isinstance(a, dict) and isinstance(b, dict):
|
|
243
|
+
for key in sorted(set(a) | set(b)):
|
|
244
|
+
if key not in a or key not in b:
|
|
245
|
+
return f"{path}.{key}"
|
|
246
|
+
where = _close(a[key], b[key], f"{path}.{key}")
|
|
247
|
+
if where:
|
|
248
|
+
return where
|
|
249
|
+
return None
|
|
250
|
+
if isinstance(a, list) and isinstance(b, list):
|
|
251
|
+
if len(a) != len(b):
|
|
252
|
+
return f"{path}[len]"
|
|
253
|
+
for i, (x, y) in enumerate(zip(a, b, strict=True)):
|
|
254
|
+
where = _close(x, y, f"{path}[{i}]")
|
|
255
|
+
if where:
|
|
256
|
+
return where
|
|
257
|
+
return None
|
|
258
|
+
return None if a == b else path
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def _judge(call: Call, answer: dict[str, Any]) -> Result:
|
|
262
|
+
if answer.get("unsupported"):
|
|
263
|
+
return Result(call=call, ok=False, kind="unsupported", detail="not implemented")
|
|
264
|
+
if "error" in answer:
|
|
265
|
+
got_err = str(answer["error"])
|
|
266
|
+
if call.error == got_err:
|
|
267
|
+
return Result(call=call, ok=True, kind="match", got_error=got_err)
|
|
268
|
+
return Result(call=call, ok=False, kind="error", got_error=got_err,
|
|
269
|
+
detail=f"expected {call.error or 'a result'}, got {got_err}")
|
|
270
|
+
if "result" not in answer:
|
|
271
|
+
return Result(call=call, ok=False, kind="protocol", detail="no result or error")
|
|
272
|
+
got = answer["result"]
|
|
273
|
+
if call.error is not None:
|
|
274
|
+
return Result(call=call, ok=False, kind="error", got=got,
|
|
275
|
+
detail=f"expected {call.error}, got a result")
|
|
276
|
+
where = _close(call.result, got)
|
|
277
|
+
if where is None:
|
|
278
|
+
return Result(call=call, ok=True, kind="match", got=got)
|
|
279
|
+
return Result(call=call, ok=False, kind="value", got=got, detail=f"differs at {where}")
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def replay(tape: Sequence[Call], adapter: Adapter) -> list[Result]:
|
|
283
|
+
proc = adapter.start()
|
|
284
|
+
assert proc.stdin is not None and proc.stdout is not None
|
|
285
|
+
lines: queue.Queue[str | None] = queue.Queue()
|
|
286
|
+
|
|
287
|
+
def pump() -> None:
|
|
288
|
+
assert proc.stdout is not None
|
|
289
|
+
for line in proc.stdout:
|
|
290
|
+
lines.put_nowait(line)
|
|
291
|
+
lines.put_nowait(None)
|
|
292
|
+
|
|
293
|
+
threading.Thread(target=pump, daemon=True).start()
|
|
294
|
+
out: list[Result] = []
|
|
295
|
+
dead = ""
|
|
296
|
+
try:
|
|
297
|
+
for call in tape:
|
|
298
|
+
if dead:
|
|
299
|
+
out.append(Result(call=call, ok=False, kind="crash", detail=dead))
|
|
300
|
+
continue
|
|
301
|
+
try:
|
|
302
|
+
request: dict[str, Any] = {"fn": call.fn, "args": call.args,
|
|
303
|
+
"kwargs": call.kwargs}
|
|
304
|
+
if call.state is not None:
|
|
305
|
+
request["state"] = call.state
|
|
306
|
+
proc.stdin.write(json.dumps(request) + "\n")
|
|
307
|
+
proc.stdin.flush()
|
|
308
|
+
line = lines.get(timeout=adapter.timeout_s)
|
|
309
|
+
except (BrokenPipeError, OSError):
|
|
310
|
+
line = None
|
|
311
|
+
except queue.Empty:
|
|
312
|
+
dead = f"no answer within {adapter.timeout_s:g}s"
|
|
313
|
+
out.append(Result(call=call, ok=False, kind="crash", detail=dead))
|
|
314
|
+
continue
|
|
315
|
+
if line is None:
|
|
316
|
+
dead = f"the implementation exited ({proc.poll()})"
|
|
317
|
+
out.append(Result(call=call, ok=False, kind="crash", detail=dead))
|
|
318
|
+
continue
|
|
319
|
+
try:
|
|
320
|
+
answer = json.loads(line)
|
|
321
|
+
except ValueError:
|
|
322
|
+
out.append(Result(call=call, ok=False, kind="protocol",
|
|
323
|
+
detail=f"not JSON: {line[:80]!r}"))
|
|
324
|
+
continue
|
|
325
|
+
out.append(_judge(call, answer if isinstance(answer, dict) else {}))
|
|
326
|
+
finally:
|
|
327
|
+
if proc.poll() is None:
|
|
328
|
+
proc.kill()
|
|
329
|
+
proc.wait()
|
|
330
|
+
return out
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def match_rate(results: Sequence[Result]) -> float:
|
|
334
|
+
return sum(r.ok for r in results) / len(results) if results else 0.0
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def cluster(results: Sequence[Result]) -> list[Cluster]:
|
|
338
|
+
"""Failed results grouped by function and kind (and, for errors, the pair of exception
|
|
339
|
+
types), biggest group first."""
|
|
340
|
+
groups: dict[tuple[str, str, str], list[Result]] = {}
|
|
341
|
+
for r in results:
|
|
342
|
+
if r.ok:
|
|
343
|
+
continue
|
|
344
|
+
sub = (f"{r.call.error or 'result'} -> {r.got_error or 'result'}"
|
|
345
|
+
if r.kind == "error" else r.detail.split(" at ")[-1] if r.kind == "value"
|
|
346
|
+
else "")
|
|
347
|
+
groups.setdefault((r.call.fn, r.kind, sub), []).append(r)
|
|
348
|
+
out = [Cluster(fn=fn, kind=kind,
|
|
349
|
+
summary=f"{fn}: {kind}" + (f" ({sub})" if sub else "")
|
|
350
|
+
+ f", {len(rs)} call(s)", results=rs)
|
|
351
|
+
for (fn, kind, sub), rs in groups.items()]
|
|
352
|
+
out.sort(key=lambda c: (-len(c.results), c.fn, c.kind))
|
|
353
|
+
return out
|
pgchangeling/__main__.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""Record a tape while a test suite runs, in the target project's own Python:
|
|
2
|
+
|
|
3
|
+
python -m pgchangeling --tape calls.jsonl --target pkg.mod:fn \\
|
|
4
|
+
[--state pkg.mod:GLOBAL] [--coverage] -- -q tests/
|
|
5
|
+
|
|
6
|
+
Runs `pytest.main` with the arguments after `--` inside a `Recorder`. PGchangeling and
|
|
7
|
+
pytest must be importable in that interpreter (for example `pip install pgchangeling` in the
|
|
8
|
+
project's virtual environment). `pgchangeling record ...` does the same.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import argparse
|
|
14
|
+
import sys
|
|
15
|
+
from contextlib import AbstractContextManager, nullcontext
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
from pgchangeling import Recorder, save_tape
|
|
19
|
+
from pgchangeling.cover import (
|
|
20
|
+
CoverageMissing,
|
|
21
|
+
CoverageProbe,
|
|
22
|
+
coverage_path,
|
|
23
|
+
scope_of,
|
|
24
|
+
write_report,
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def main(argv: list[str] | None = None) -> int:
|
|
29
|
+
argv = list(sys.argv[1:] if argv is None else argv)
|
|
30
|
+
rest: list[str] = []
|
|
31
|
+
if "--" in argv:
|
|
32
|
+
i = argv.index("--")
|
|
33
|
+
argv, rest = argv[:i], argv[i + 1:]
|
|
34
|
+
p = argparse.ArgumentParser(prog="python -m pgchangeling")
|
|
35
|
+
p.add_argument("--tape", required=True)
|
|
36
|
+
p.add_argument("--target", action="append", required=True,
|
|
37
|
+
help="module:qualname of a function to record (repeatable)")
|
|
38
|
+
p.add_argument("--state", action="append", default=[],
|
|
39
|
+
help="module:NAME of a global to keep with each call (repeatable)")
|
|
40
|
+
p.add_argument("--coverage", action="store_true",
|
|
41
|
+
help="also measure branch coverage of the target modules inside recorded "
|
|
42
|
+
"calls, into <tape>.coverage.json (needs coverage.py)")
|
|
43
|
+
p.add_argument("--cover", action="append", default=[],
|
|
44
|
+
help="another module or package to measure with --coverage (repeatable)")
|
|
45
|
+
args = p.parse_args(argv)
|
|
46
|
+
probe = None
|
|
47
|
+
if args.coverage:
|
|
48
|
+
try:
|
|
49
|
+
probe = CoverageProbe([*scope_of(args.target), *args.cover])
|
|
50
|
+
except CoverageMissing as exc:
|
|
51
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
52
|
+
return 2
|
|
53
|
+
import pytest
|
|
54
|
+
|
|
55
|
+
rec = Recorder(args.target, state=args.state, around=probe.during if probe else None)
|
|
56
|
+
importing: AbstractContextManager[Any] = probe.during() if probe else nullcontext()
|
|
57
|
+
with importing: # the import runs the module's top level: count it
|
|
58
|
+
rec.__enter__()
|
|
59
|
+
try:
|
|
60
|
+
code = pytest.main(rest)
|
|
61
|
+
finally:
|
|
62
|
+
rec.__exit__(None, None, None)
|
|
63
|
+
save_tape(args.tape, rec.calls)
|
|
64
|
+
print(f"recorded {len(rec.calls)} call(s), skipped {rec.skipped} that do not fit in "
|
|
65
|
+
f"JSON; pytest exit {int(code)}", file=sys.stderr)
|
|
66
|
+
if probe:
|
|
67
|
+
report = probe.report()
|
|
68
|
+
write_report(coverage_path(args.tape), report)
|
|
69
|
+
print(f"coverage: lines {report['lines'][0]} of {report['lines'][1]}, branches "
|
|
70
|
+
f"{report['branches'][0]} of {report['branches'][1]}; wrote "
|
|
71
|
+
f"{coverage_path(args.tape)}", file=sys.stderr)
|
|
72
|
+
return 0
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
if __name__ == "__main__":
|
|
76
|
+
raise SystemExit(main())
|
pgchangeling/cli.py
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
"""The `pgchangeling` command: record a tape, replay it on a port, and run Mirror."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import math
|
|
7
|
+
import os
|
|
8
|
+
import sys
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
import typer
|
|
12
|
+
|
|
13
|
+
from pgchangeling import Adapter, cluster, load_tape, match_rate, replay
|
|
14
|
+
from pgchangeling.runner import runner_from
|
|
15
|
+
from pgchangeling.verify_cli import register
|
|
16
|
+
|
|
17
|
+
app = typer.Typer(no_args_is_help=True,
|
|
18
|
+
help="PGchangeling: prove a port by replaying real calls on the new code.")
|
|
19
|
+
mirror_app = typer.Typer(no_args_is_help=True,
|
|
20
|
+
help="Mirror: differential runs across local HTTP servers.")
|
|
21
|
+
app.add_typer(mirror_app, name="mirror")
|
|
22
|
+
register(app)
|
|
23
|
+
|
|
24
|
+
WRAP_HELP = ("Command prefix that isolates the program, e.g. \"bwrap --ro-bind / / --dev /dev "
|
|
25
|
+
"--unshare-net --\" or \"docker run --rm -i image\". Without it the program runs "
|
|
26
|
+
"as a plain subprocess: not a sandbox.")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@app.callback()
|
|
30
|
+
def _group() -> None:
|
|
31
|
+
"""Keep subcommands even when there are few."""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _line(rate: float, total: int) -> str:
|
|
35
|
+
if total == 0:
|
|
36
|
+
return "The tape is empty. Nothing to replay yet."
|
|
37
|
+
# Counted, not rounded: a headline must never say 100% while any call differs.
|
|
38
|
+
matched = round(rate * total)
|
|
39
|
+
head = f"{matched:,} of {total:,} calls match"
|
|
40
|
+
if matched == total:
|
|
41
|
+
return f"{head}."
|
|
42
|
+
pct = f"{math.floor(rate * 10_000) / 100:.2f}%"
|
|
43
|
+
if rate >= 0.99:
|
|
44
|
+
return f"{head} ({pct}). Nearly there; check the stragglers."
|
|
45
|
+
return f"{head} ({pct})."
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@app.command("record")
|
|
49
|
+
def record_cmd(
|
|
50
|
+
tape: Path = typer.Option(..., help="Where to write the tape (JSON lines)"),
|
|
51
|
+
target: list[str] = typer.Option(..., help="module:qualname to record (repeatable)"),
|
|
52
|
+
state: list[str] = typer.Option([], help="module:NAME of a global to keep with each "
|
|
53
|
+
"call (repeatable)"),
|
|
54
|
+
coverage: bool = typer.Option(False, "--coverage", help="Also measure branch coverage "
|
|
55
|
+
"of the target modules inside recorded calls, into "
|
|
56
|
+
"<tape>.coverage.json (needs the coverage extra)"),
|
|
57
|
+
cover: list[str] = typer.Option([], help="Another module or package to measure with "
|
|
58
|
+
"--coverage (repeatable)"),
|
|
59
|
+
pytest_args: list[str] = typer.Argument(None, help="Arguments for pytest, after --"),
|
|
60
|
+
) -> None:
|
|
61
|
+
"""Record a tape while pytest runs.
|
|
62
|
+
|
|
63
|
+
Run it with the target project's own Python, where the code under test is importable.
|
|
64
|
+
"""
|
|
65
|
+
from pgchangeling.__main__ import main
|
|
66
|
+
|
|
67
|
+
# As `python -m` does: the current directory is importable, so local targets resolve.
|
|
68
|
+
if "" not in sys.path and os.getcwd() not in sys.path:
|
|
69
|
+
sys.path.insert(0, os.getcwd())
|
|
70
|
+
argv = ["--tape", str(tape)]
|
|
71
|
+
for t in target:
|
|
72
|
+
argv += ["--target", t]
|
|
73
|
+
for s in state:
|
|
74
|
+
argv += ["--state", s]
|
|
75
|
+
if coverage:
|
|
76
|
+
argv.append("--coverage")
|
|
77
|
+
for c in cover:
|
|
78
|
+
argv += ["--cover", c]
|
|
79
|
+
raise typer.Exit(main([*argv, "--", *(pytest_args or [])]))
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@app.command("replay")
|
|
83
|
+
def replay_cmd(
|
|
84
|
+
tape: Path = typer.Argument(..., help="Tape from `pgchangeling record`"),
|
|
85
|
+
command: list[str] = typer.Argument(..., help="The new implementation, after --"),
|
|
86
|
+
out: Path | None = typer.Option(None, help="Write the full report as JSON"),
|
|
87
|
+
timeout: float = typer.Option(30.0, help="Seconds to wait for each answer"),
|
|
88
|
+
show: int = typer.Option(5, help="Mismatch groups to print"),
|
|
89
|
+
wrap: str | None = typer.Option(None, help=WRAP_HELP),
|
|
90
|
+
keep_env: list[str] = typer.Option([], help="Host environment variable to pass on "
|
|
91
|
+
"(repeatable); secrets are never passed"),
|
|
92
|
+
) -> None:
|
|
93
|
+
"""Replay TAPE on COMMAND (a JSON-lines program) and group what differs."""
|
|
94
|
+
calls = load_tape(tape)
|
|
95
|
+
adapter = Adapter(command, timeout_s=timeout, runner=runner_from(wrap), keep_env=keep_env)
|
|
96
|
+
results = replay(calls, adapter)
|
|
97
|
+
rate = match_rate(results)
|
|
98
|
+
groups = cluster(results)
|
|
99
|
+
typer.echo(_line(rate, len(results)))
|
|
100
|
+
for g in groups[:show]:
|
|
101
|
+
first = g.results[0]
|
|
102
|
+
typer.echo(f" {g.summary}: e.g. args {json.dumps(first.call.args)[:80]}"
|
|
103
|
+
f" {first.detail}".rstrip())
|
|
104
|
+
if len(groups) > show:
|
|
105
|
+
typer.echo(f" and {len(groups) - show} more group(s)")
|
|
106
|
+
if out:
|
|
107
|
+
out.write_text(json.dumps({
|
|
108
|
+
"calls": len(results), "match_rate": rate,
|
|
109
|
+
"groups": [g.model_dump() for g in groups]}, indent=2) + "\n")
|
|
110
|
+
raise typer.Exit(0 if rate == 1.0 else 1)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _parse_sides(sides: list[str]) -> dict[str, str]:
|
|
114
|
+
out: dict[str, str] = {}
|
|
115
|
+
for item in sides:
|
|
116
|
+
name, sep, url = item.partition("=")
|
|
117
|
+
if not sep or not name or not url:
|
|
118
|
+
raise typer.BadParameter(f"--side expects name=url, got {item!r}")
|
|
119
|
+
out[name] = url
|
|
120
|
+
return out
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
@mirror_app.command("run")
|
|
124
|
+
def mirror_run(
|
|
125
|
+
cases: Path = typer.Option(..., help="Case file (TOML)"),
|
|
126
|
+
model: str = typer.Option(..., help="Model name put in place of {model} in each body"),
|
|
127
|
+
out: Path = typer.Option(Path("reports/mirror"), help="Directory for run.json and "
|
|
128
|
+
"report.md"),
|
|
129
|
+
side: list[str] = typer.Option([], help="name=http://127.0.0.1:PORT, first is reference"),
|
|
130
|
+
serve: Path | None = typer.Option(None, help="Server spec TOML: start the servers first"),
|
|
131
|
+
tag: list[str] = typer.Option([], help="Only run cases carrying one of these tags"),
|
|
132
|
+
timeout: float = typer.Option(120.0, help="Per-request timeout in seconds"),
|
|
133
|
+
wrap: str | None = typer.Option(None, help=WRAP_HELP),
|
|
134
|
+
) -> None:
|
|
135
|
+
"""Send every case to every side and report where they disagree."""
|
|
136
|
+
from pgchangeling.mirror import load_cases, render_markdown, run_cases, run_to_json
|
|
137
|
+
from pgchangeling.mirror.serve import ServerPool, load_server_specs
|
|
138
|
+
|
|
139
|
+
selected = load_cases(cases)
|
|
140
|
+
if tag:
|
|
141
|
+
selected = [c for c in selected if set(c.tags) & set(tag)]
|
|
142
|
+
if not selected:
|
|
143
|
+
raise typer.BadParameter("no cases selected")
|
|
144
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
145
|
+
|
|
146
|
+
def go(sides: dict[str, str]) -> None:
|
|
147
|
+
run = run_cases(selected, sides, model, timeout)
|
|
148
|
+
(out / "run.json").write_text(run_to_json(run), encoding="utf-8")
|
|
149
|
+
(out / "report.md").write_text(render_markdown(run), encoding="utf-8")
|
|
150
|
+
n = sum(len(r.discrepancies) for r in run.results)
|
|
151
|
+
bad = sum(1 for r in run.results if r.discrepancies)
|
|
152
|
+
typer.echo(f"{len(run.results)} cases, {bad} with discrepancies ({n} total)")
|
|
153
|
+
typer.echo(f"wrote {out / 'report.md'}")
|
|
154
|
+
|
|
155
|
+
if serve:
|
|
156
|
+
with ServerPool(load_server_specs(serve), runner=runner_from(wrap)) as pool:
|
|
157
|
+
for name, secs in pool.startup_seconds.items():
|
|
158
|
+
typer.echo(f"{name} up in {secs:.1f}s")
|
|
159
|
+
go(pool.base_urls())
|
|
160
|
+
else:
|
|
161
|
+
if not side:
|
|
162
|
+
raise typer.BadParameter("give --side name=url at least twice, or --serve")
|
|
163
|
+
go(_parse_sides(side))
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
@mirror_app.command("delta")
|
|
167
|
+
def mirror_delta(baseline: Path, candidate: Path,
|
|
168
|
+
out: Path = typer.Option(Path("reports/mirror/delta.md"))) -> None:
|
|
169
|
+
"""Compare two saved runs: what a candidate fixed, introduced and left alone."""
|
|
170
|
+
from pgchangeling.mirror import compare_runs, load_run, render_markdown
|
|
171
|
+
|
|
172
|
+
delta = compare_runs(load_run(baseline), load_run(candidate))
|
|
173
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
174
|
+
out.write_text(render_markdown(delta), encoding="utf-8")
|
|
175
|
+
typer.echo(f"verdict {delta.verdict.value}; wrote {out}")
|
|
176
|
+
if delta.verdict.value == "REGRESSION":
|
|
177
|
+
raise typer.Exit(1)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def main() -> None:
|
|
181
|
+
app(prog_name="pgchangeling")
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
if __name__ == "__main__":
|
|
185
|
+
main()
|