Skip to content

Commit 9e2f126

Browse files
fix: compare consumer type diagnostics against the baseline
1 parent 45b9531 commit 9e2f126

3 files changed

Lines changed: 157 additions & 19 deletions

File tree

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
from __future__ import annotations
2+
3+
import os
4+
import sys
5+
import json
6+
import shutil
7+
import tarfile
8+
import tempfile
9+
import subprocess
10+
from typing import Any
11+
from pathlib import Path
12+
from collections import Counter
13+
14+
ROOT = Path(__file__).resolve().parents[1]
15+
CONFIG = ROOT / "scripts/pyrightconfig.breaking-changes.json"
16+
17+
18+
def snapshot_baseline(ref: str, destination: Path) -> None:
19+
commit = subprocess.check_output(
20+
["git", "rev-parse", "--verify", "--end-of-options", f"{ref}^{{commit}}"], cwd=ROOT, text=True
21+
).strip()
22+
with tempfile.TemporaryFile() as archive:
23+
subprocess.run(["git", "archive", commit, "src", "tests"], cwd=ROOT, stdout=archive, check=True)
24+
archive.seek(0)
25+
with tarfile.open(fileobj=archive) as contents:
26+
for member in contents:
27+
path = Path(member.name)
28+
if path.is_absolute() or ".." in path.parts or not (member.isfile() or member.isdir()):
29+
raise RuntimeError(f"Unsupported baseline archive entry: {member.name}")
30+
target = destination / path
31+
if member.isdir():
32+
target.mkdir(parents=True, exist_ok=True)
33+
else:
34+
target.parent.mkdir(parents=True, exist_ok=True)
35+
source = contents.extractfile(member)
36+
assert source is not None
37+
with source, target.open("wb") as output:
38+
shutil.copyfileobj(source, output)
39+
40+
41+
def check(snapshot: Path) -> list[dict[str, Any]]:
42+
# Keep the current checker configuration and dependencies fixed. Only the
43+
# SDK source changes; all tests and their helpers come from the baseline.
44+
# Preserve relative include and import paths by keeping the config in scripts/.
45+
config_path = snapshot / "scripts" / CONFIG.name
46+
config_path.parent.mkdir(parents=True, exist_ok=True)
47+
shutil.copyfile(CONFIG, config_path)
48+
result = subprocess.run(
49+
[str(ROOT / "scripts/run-pyright"), "--outputjson", "--pythonpath", sys.executable],
50+
cwd=ROOT,
51+
env={**os.environ, "PYRIGHT_PROJECT": str(config_path)},
52+
capture_output=True,
53+
text=True,
54+
)
55+
if result.returncode not in (0, 1):
56+
raise RuntimeError(f"Pyright failed ({result.returncode}): {result.stderr}\n{result.stdout}")
57+
report = json.loads(result.stdout)
58+
errors = [diagnostic for diagnostic in report["generalDiagnostics"] if diagnostic["severity"] == "error"]
59+
if (
60+
report["summary"]["filesAnalyzed"] == 0
61+
or report["summary"]["errorCount"] != len(errors)
62+
or result.returncode != bool(errors)
63+
):
64+
raise RuntimeError("Pyright returned an incomplete or inconsistent report")
65+
return errors
66+
67+
68+
def diagnostic_key(diagnostic: dict[str, Any], snapshot: Path) -> str:
69+
# Compare full messages and locations, not just counts or rule names: a
70+
# different error on an already failing line is still a regression.
71+
key = {field: diagnostic.get(field) for field in ("file", "range", "rule", "message", "severity")}
72+
return json.dumps(key, sort_keys=True).replace(str(snapshot), "<snapshot>")
73+
74+
75+
def new_errors(baseline: list[dict[str, Any]], candidate: list[dict[str, Any]], snapshot: Path) -> list[dict[str, Any]]:
76+
remaining = Counter(diagnostic_key(diagnostic, snapshot) for diagnostic in baseline)
77+
added = []
78+
for diagnostic in candidate:
79+
key = diagnostic_key(diagnostic, snapshot)
80+
if remaining[key]:
81+
remaining[key] -= 1
82+
else:
83+
added.append(diagnostic)
84+
return added
85+
86+
87+
def main(ref: str) -> int:
88+
with tempfile.TemporaryDirectory(prefix="openai-consumer-compatibility-") as directory:
89+
snapshot = Path(directory).resolve()
90+
snapshot_baseline(ref, snapshot)
91+
print("==> Checking previous callers against the baseline SDK", flush=True)
92+
baseline = check(snapshot)
93+
shutil.rmtree(snapshot / "src")
94+
shutil.copytree(ROOT / "src", snapshot / "src", ignore=shutil.ignore_patterns("__pycache__", "*.pyc"))
95+
print("==> Checking the same callers against the candidate SDK", flush=True)
96+
candidate = check(snapshot)
97+
added = new_errors(baseline, candidate, snapshot)
98+
print(f"Baseline: {len(baseline)} errors; candidate: {len(candidate)} errors; new: {len(added)}")
99+
for diagnostic in added:
100+
path = Path(diagnostic["file"]).relative_to(snapshot)
101+
start = diagnostic["range"]["start"]
102+
print(f"{path}:{start['line'] + 1}:{start['character'] + 1}: {diagnostic['message']}")
103+
print(f" [{diagnostic.get('rule', 'unknown')}]")
104+
return 1 if added else 0
105+
106+
107+
if __name__ == "__main__":
108+
if len(sys.argv) != 2:
109+
raise SystemExit("Usage: check-consumer-compatibility.py BASE_REF")
110+
raise SystemExit(main(sys.argv[1]))

‎scripts/detect-breaking-changes‎

Lines changed: 4 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,9 @@
11
#!/usr/bin/env bash
22

3-
set -e
3+
set -euo pipefail
44

55
cd "$(dirname "$0")/.."
66

7-
echo "==> Detecting breaking changes"
8-
9-
TEST_PATHS=(
10-
tests/api_resources
11-
tests/test_client.py
12-
tests/test_response.py
13-
tests/test_legacy_response.py
14-
)
15-
16-
for PATHSPEC in "${TEST_PATHS[@]}"; do
17-
# Try to check out previous versions of the test files
18-
# with the current SDK.
19-
git checkout "$1" -- "${PATHSPEC}" 2>/dev/null || true
20-
done
21-
22-
# Check unchanged previous-version callers with Pyright. Repository development
23-
# uses ty; this isolated gate protects consumers who use another checker.
24-
uv run --locked --all-extras scripts/run-pyright
7+
# Repository development uses ty. Compare unchanged callers with Pyright to
8+
# detect new consumer errors without failing on existing fixture diagnostics.
9+
uv run --locked --all-extras python scripts/check-consumer-compatibility.py "$1"
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
from __future__ import annotations
2+
3+
import json
4+
import runpy
5+
import subprocess
6+
from pathlib import Path
7+
8+
import pytest
9+
10+
SCRIPT = Path(__file__).resolve().parents[1] / "scripts/check-consumer-compatibility.py"
11+
12+
13+
@pytest.mark.parametrize("change", ["none", "message", "location", "duplicate"])
14+
def test_existing_diagnostics_do_not_hide_new_errors(tmp_path: Path, change: str) -> None:
15+
detector = runpy.run_path(str(SCRIPT))
16+
original = {
17+
"file": str(tmp_path / "consumer.py"),
18+
"range": {"start": {"line": 3, "character": 0}, "end": {"line": 3, "character": 10}},
19+
"severity": "error",
20+
"rule": "reportMissingTypeArgument",
21+
"message": 'Expected type arguments for generic class "dict"',
22+
}
23+
changed = dict(original)
24+
if change == "message":
25+
changed["message"] = 'Expected type arguments for generic class "Model"'
26+
elif change == "location":
27+
changed["file"] = str(tmp_path / "another_consumer.py")
28+
candidate = [original, changed] if change == "duplicate" else [changed]
29+
assert detector["new_errors"]([original], candidate, tmp_path) == ([] if change == "none" else [changed])
30+
31+
32+
@pytest.mark.parametrize("failure", ["crash", "invalid_json", "no_files", "missing_errors"])
33+
def test_checker_failures_cannot_pass_the_gate(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, failure: str) -> None:
34+
detector = runpy.run_path(str(SCRIPT))
35+
output = json.dumps({"generalDiagnostics": [], "summary": {"filesAnalyzed": 0, "errorCount": 0}})
36+
if failure == "invalid_json":
37+
output = "not JSON"
38+
elif failure == "missing_errors":
39+
output = json.dumps({"generalDiagnostics": [], "summary": {"filesAnalyzed": 1, "errorCount": 1}})
40+
result = subprocess.CompletedProcess([], 2 if failure == "crash" else 0, stdout=output, stderr="")
41+
monkeypatch.setattr(subprocess, "run", lambda *_args, **_kwargs: result)
42+
with pytest.raises((RuntimeError, ValueError)):
43+
detector["check"](tmp_path)

0 commit comments

Comments
 (0)