second-source 0.5.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.
Files changed (71) hide show
  1. second_source/__init__.py +3 -0
  2. second_source/action/__init__.py +4 -0
  3. second_source/action/commands.py +88 -0
  4. second_source/action/event.py +89 -0
  5. second_source/action/inputs.py +118 -0
  6. second_source/action/main.py +203 -0
  7. second_source/action/publish.py +184 -0
  8. second_source/action/setup.py +143 -0
  9. second_source/action/sweep.py +85 -0
  10. second_source/action/wait.py +49 -0
  11. second_source/benchmark/__init__.py +1 -0
  12. second_source/benchmark/aidev.py +248 -0
  13. second_source/benchmark/aidev_local.py +85 -0
  14. second_source/benchmark/golden.py +314 -0
  15. second_source/benchmark/redact.py +45 -0
  16. second_source/benchmark/rescore.py +388 -0
  17. second_source/benchmark/runner.py +159 -0
  18. second_source/benchmark/sample.py +243 -0
  19. second_source/benchmark/stats.py +363 -0
  20. second_source/cli/__init__.py +1 -0
  21. second_source/cli/bench.py +427 -0
  22. second_source/cli/main.py +182 -0
  23. second_source/core/__init__.py +4 -0
  24. second_source/core/aggregate.py +102 -0
  25. second_source/core/checks.py +470 -0
  26. second_source/core/engine.py +98 -0
  27. second_source/core/evidence.py +29 -0
  28. second_source/core/expr.py +206 -0
  29. second_source/core/hashing.py +41 -0
  30. second_source/core/model.py +112 -0
  31. second_source/core/pack.py +156 -0
  32. second_source/packs/__init__.py +1 -0
  33. second_source/packs/coding/__init__.py +16 -0
  34. second_source/packs/coding/checks/ci_config_caution.yaml +23 -0
  35. second_source/packs/coding/checks/ci_result.yaml +133 -0
  36. second_source/packs/coding/checks/ci_weakening_caution.yaml +27 -0
  37. second_source/packs/coding/checks/deployed.yaml +36 -0
  38. second_source/packs/coding/checks/docs_updated.yaml +22 -0
  39. second_source/packs/coding/checks/fixes_issue.yaml +58 -0
  40. second_source/packs/coding/checks/fixes_issue_durable.yaml +60 -0
  41. second_source/packs/coding/checks/integrity_guard.yaml +34 -0
  42. second_source/packs/coding/checks/integrity_inspection.yaml +21 -0
  43. second_source/packs/coding/checks/lint_caution.yaml +22 -0
  44. second_source/packs/coding/checks/matching_jobs_caution.yaml +22 -0
  45. second_source/packs/coding/checks/not_reverted.yaml +38 -0
  46. second_source/packs/coding/checks/tests_added.yaml +25 -0
  47. second_source/packs/coding/checks/tests_added_guard.yaml +26 -0
  48. second_source/packs/coding/checks/tests_removed_caution.yaml +23 -0
  49. second_source/packs/coding/detection.py +94 -0
  50. second_source/packs/coding/diff_facts.py +665 -0
  51. second_source/packs/coding/extract.py +911 -0
  52. second_source/packs/coding/functions.py +241 -0
  53. second_source/packs/coding/pack.yaml +33 -0
  54. second_source/packs/coding/trusted_rules.yaml +50 -0
  55. second_source/pipeline.py +112 -0
  56. second_source/report/__init__.py +1 -0
  57. second_source/report/render.py +503 -0
  58. second_source/sources/__init__.py +1 -0
  59. second_source/sources/github/__init__.py +4 -0
  60. second_source/sources/github/auth.py +48 -0
  61. second_source/sources/github/cache.py +67 -0
  62. second_source/sources/github/client.py +261 -0
  63. second_source/sources/github/mappers.py +454 -0
  64. second_source/sources/github/source.py +385 -0
  65. second_source/sources/github/urls.py +51 -0
  66. second_source-0.5.0.dist-info/METADATA +311 -0
  67. second_source-0.5.0.dist-info/RECORD +71 -0
  68. second_source-0.5.0.dist-info/WHEEL +4 -0
  69. second_source-0.5.0.dist-info/entry_points.txt +2 -0
  70. second_source-0.5.0.dist-info/licenses/LICENSE +202 -0
  71. second_source-0.5.0.dist-info/licenses/NOTICE +9 -0
@@ -0,0 +1,388 @@
1
+ """Re-score benchmark results offline, from their evidence snapshots, with the current code.
2
+
3
+ A run that takes days can span an upgrade, so its records come from different code versions
4
+ and cannot be summarised together. Re-scoring replays the verification on each record's saved
5
+ claims and evidence, with no GitHub requests, so every published verdict comes from one version.
6
+
7
+ What it can and cannot change:
8
+
9
+ - **Claims are kept as extracted.** The snapshot has no PR text, so extraction is not re-run;
10
+ a change to extraction needs a fresh run, not a re-score.
11
+ - **Diff counts must come from the current code.** Per-file counts (skips, test cases, gates)
12
+ are made once, when the patch is read, and the patch is never stored. A record whose counts
13
+ carry another fingerprint (``diff_facts.FACTS_VERSION``), or none, needs its file list
14
+ re-read: ``fetch_file_facts`` does that (counts only), and also records the repository's
15
+ current name and file count. Without it, stale counts are dropped and the guards report the
16
+ files as not inspected, never as clean.
17
+ - **Inputs a snapshot lacks are rebuilt, and checked.** Records written before snapshots kept
18
+ claim times and evidence versions get them rebuilt (the PR's open or merge time; first
19
+ record wins), so every required check whose version is unchanged must reproduce its stored
20
+ result and reason. Only guards (whose inputs are the re-read diff counts) and checks with a
21
+ new version (a deliberate change of rules) may decide differently. A claim that fails this
22
+ becomes UNVERIFIABLE (reason ``RESCORE_MISMATCH``, never a verdict no run firmly supports),
23
+ keeps both results
24
+ (``stored_result``, ``rescore_mismatch``) for investigation, and the summary counts it. A
25
+ record that cannot be rebuilt at all gives ``RESCORE_ERROR`` on every claim.
26
+ - **Re-score the original results, never a re-scored file**: its stored results are no longer
27
+ the original run's.
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import re
33
+ from collections import Counter
34
+ from collections.abc import Callable, Iterable, Mapping
35
+ from datetime import UTC, datetime
36
+ from typing import Any
37
+
38
+ from second_source import __version__
39
+ from second_source.core.engine import Engine
40
+ from second_source.core.model import Claim, Episode, Evidence, Result, Verdict
41
+ from second_source.packs.coding import diff_facts
42
+ from second_source.pipeline import default_engine
43
+ from second_source.report.render import WORDS, _plain, withdrawn_reasons
44
+ from second_source.sources.github import mappers
45
+ from second_source.sources.github.client import GitHubClient
46
+ from second_source.sources.github.urls import parse_pull_request
47
+
48
+ FILE_EVIDENCE = "changed_file"
49
+ SUMMARY_EVIDENCE = "changed_files_summary"
50
+ MAX_FILE_PAGES = 30 # the same 3,000-file cap as a normal check
51
+ RESCORE_MISMATCH = "RESCORE_MISMATCH"
52
+ RESCORE_ERROR = "RESCORE_ERROR"
53
+
54
+
55
+ class AlreadyRescored(ValueError):
56
+ """The input is a re-scored file; its stored results are not the original run's."""
57
+
58
+
59
+ def needs_file_facts(record: Mapping[str, Any]) -> bool:
60
+ """True when the record's diff counts were not made by the current code."""
61
+ if "report" not in record:
62
+ return False
63
+ return _facts_version(record.get("evidence", [])) != diff_facts.FACTS_VERSION
64
+
65
+
66
+ def _facts_version(snapshot: Iterable[Mapping[str, Any]]) -> str | None:
67
+ summary = next((i for i in snapshot if i["type"] == SUMMARY_EVIDENCE), None)
68
+ return summary["attributes"].get("facts_version") if summary else None
69
+
70
+
71
+ def fetch_file_facts(
72
+ client: GitHubClient, url: str, clock: Callable[[], datetime] = lambda: datetime.now(UTC)
73
+ ) -> dict[str, Any]:
74
+ """The PR's changed files reduced to counts by the current code (no code is kept), its
75
+ repository's current name and its file count (two requests, plus file-list pages)."""
76
+ ref = parse_pull_request(url)
77
+ observed_at = clock()
78
+ pull = client.get(f"/repos/{ref.full_name}/pulls/{ref.number}")
79
+ files = client.get_paginated(
80
+ f"/repos/{ref.full_name}/pulls/{ref.number}/files", max_pages=MAX_FILE_PAGES
81
+ )
82
+ return {
83
+ "url": url,
84
+ "observed_at": observed_at.isoformat(),
85
+ "facts_version": diff_facts.FACTS_VERSION,
86
+ "repo": ((pull.get("base") or {}).get("repo") or {}).get("full_name"),
87
+ "changed_files": pull.get("changed_files"),
88
+ "files": [
89
+ dict(mappers.changed_file_evidence(file, observed_at).attributes) for file in files
90
+ ],
91
+ }
92
+
93
+
94
+ def rescore(
95
+ record: Mapping[str, Any],
96
+ *,
97
+ file_facts: Mapping[str, Any] | None = None,
98
+ engine: Engine | None = None,
99
+ pack_version: str,
100
+ ) -> dict[str, Any]:
101
+ """The record with its verdicts recomputed by the current code (see the module notes)."""
102
+ if "rescored_from" in record:
103
+ raise AlreadyRescored(f"{record.get('url')} was already re-scored")
104
+ if "report" not in record:
105
+ return dict(record)
106
+ engine = engine or default_engine()
107
+ if file_facts is not None and file_facts.get("facts_version") != diff_facts.FACTS_VERSION:
108
+ file_facts = None # made by other code: as stale as the snapshot's own counts
109
+ try:
110
+ new_claims, evidence = _replay(record, file_facts, engine)
111
+ except (KeyError, ValueError, TypeError) as error:
112
+ return _failed(record, f"{type(error).__name__}: {error}", pack_version)
113
+ counts = Counter(Result(claim["result"]) for claim in new_claims)
114
+ report = record["report"]
115
+ return {
116
+ **record,
117
+ **_versions(record, pack_version),
118
+ "report": {
119
+ **report,
120
+ "claims": new_claims,
121
+ "summary": {WORDS[result]: count for result, count in counts.items()},
122
+ },
123
+ "evidence": [_snapshot_item(e) for e in evidence],
124
+ }
125
+
126
+
127
+ def _replay(
128
+ record: Mapping[str, Any], file_facts: Mapping[str, Any] | None, engine: Engine
129
+ ) -> tuple[list[dict[str, Any]], list[Evidence]]:
130
+ report = record["report"]
131
+ checked_at = _time(report["checked_at"])
132
+ episode = _episode(report, record["dataset_agent"], file_facts)
133
+ evidence = _evidence(record["evidence"], checked_at, episode, file_facts)
134
+ stored = report["claims"]
135
+ claims = [_claim(item, episode, evidence) for item in stored]
136
+ stale = set(report.get("stale", []))
137
+ if "fetched" in report:
138
+ # A type the original run never asked for is unknown, not empty.
139
+ stale |= (
140
+ set(engine.evidence_types_for(claims))
141
+ - set(report["fetched"])
142
+ - {
143
+ SUMMARY_EVIDENCE # rebuilt from the file list
144
+ }
145
+ )
146
+ verdicts = engine.verify(episode, claims, evidence, now=checked_at, stale=frozenset(stale))
147
+ required = {
148
+ check.id: check.required for claim in claims for check in engine.checks_for(claim.type)
149
+ }
150
+ new_claims = []
151
+ for item, verdict in zip(stored, verdicts, strict=True):
152
+ if _reproduces(item, verdict, required):
153
+ new_claims.append(_claim_json(item, verdict))
154
+ else:
155
+ new_claims.append(_unreproduced(item, RESCORE_MISMATCH, verdict.result.value))
156
+ return new_claims, evidence
157
+
158
+
159
+ def _reproduces(item: Mapping[str, Any], verdict: Verdict, required: Mapping[str, bool]) -> bool:
160
+ """True when every required run at an unchanged version gives the stored result and reason,
161
+ and every run without a stored counterpart is a guard (new since the original run)."""
162
+ before = {(run["id"], run["version"]): run for run in item.get("checks", [])}
163
+ stored_ids = {run["id"] for run in item.get("checks", [])}
164
+ for run in verdict.check_runs:
165
+ if not required.get(run.check_id, True) or run.role == "guard":
166
+ # Optional runs only add cautions. Guards read only diff counts, which are either
167
+ # the current code's (re-read) or dropped (not inspected), never claim times, so
168
+ # their new result is the current code's answer; and they cannot contradict.
169
+ continue
170
+ old = before.get((run.check_id, run.check_version))
171
+ if old is not None:
172
+ if (old["result"], old["reason"]) != (run.result.value, run.reason):
173
+ return False
174
+ elif run.check_id not in stored_ids and run.role != "guard":
175
+ return False # a deciding check the original run did not have
176
+ return True
177
+
178
+
179
+ def _claim_json(item: Mapping[str, Any], verdict: Verdict) -> dict[str, Any]:
180
+ return {
181
+ **item,
182
+ "result": verdict.result.value,
183
+ "reasons": list(verdict.reasons),
184
+ "withdrawn": list(withdrawn_reasons(verdict)),
185
+ "caveats": list(verdict.caveats),
186
+ "checks": [
187
+ {
188
+ "id": run.check_id,
189
+ "version": run.check_version,
190
+ "level": run.level.value,
191
+ "role": run.role,
192
+ "result": run.result.value,
193
+ "reason": run.reason,
194
+ "explanation": run.explanation,
195
+ "inputs_hash": run.inputs_hash,
196
+ }
197
+ for run in verdict.check_runs
198
+ ],
199
+ }
200
+
201
+
202
+ def _unreproduced(item: Mapping[str, Any], reason: str, new_result: str) -> dict[str, Any]:
203
+ """Neither run can be trusted: unverifiable, with both results kept for investigation."""
204
+ return {
205
+ **item,
206
+ "result": Result.UNVERIFIABLE.value,
207
+ "reasons": [reason],
208
+ "withdrawn": [],
209
+ "caveats": [],
210
+ "stored_result": item["result"],
211
+ "rescore_mismatch": new_result,
212
+ }
213
+
214
+
215
+ def _failed(record: Mapping[str, Any], error: str, pack_version: str) -> dict[str, Any]:
216
+ claims = [_unreproduced(item, RESCORE_ERROR, "ERROR") for item in record["report"]["claims"]]
217
+ return {
218
+ **record,
219
+ **_versions(record, pack_version),
220
+ "rescore_error": error,
221
+ "report": {**record["report"], "claims": claims, "summary": {"unverifiable": len(claims)}},
222
+ }
223
+
224
+
225
+ def _versions(record: Mapping[str, Any], pack_version: str) -> dict[str, Any]:
226
+ return {
227
+ "tool_version": __version__,
228
+ "pack_version": pack_version,
229
+ "rescored_from": {
230
+ "tool_version": record.get("tool_version"),
231
+ "pack_version": record.get("pack_version"),
232
+ },
233
+ }
234
+
235
+
236
+ def rescore_all(
237
+ records: Iterable[Mapping[str, Any]],
238
+ facts_by_url: Mapping[str, Mapping[str, Any]],
239
+ *,
240
+ pack_version: str,
241
+ ) -> tuple[list[dict[str, Any]], int]:
242
+ """Every record re-scored, and how many claims could not be reproduced (mismatches)."""
243
+ engine = default_engine()
244
+ out = [
245
+ rescore(r, file_facts=facts_by_url.get(r["url"]), engine=engine, pack_version=pack_version)
246
+ for r in records
247
+ ]
248
+ mismatches = sum(
249
+ "rescore_mismatch" in claim for r in out if "report" in r for claim in r["report"]["claims"]
250
+ )
251
+ return out, mismatches
252
+
253
+
254
+ # ---- rebuilding the engine's inputs from a snapshot -----------------------------------------
255
+
256
+
257
+ def _evidence(
258
+ snapshot: Iterable[Mapping[str, Any]],
259
+ checked_at: datetime,
260
+ episode: Episode,
261
+ file_facts: Mapping[str, Any] | None,
262
+ ) -> list[Evidence]:
263
+ snapshot = list(snapshot)
264
+ current = _facts_version(snapshot) == diff_facts.FACTS_VERSION
265
+ records = []
266
+ for item in snapshot:
267
+ if item["type"] == SUMMARY_EVIDENCE:
268
+ continue # always rebuilt below, from the file counts
269
+ attributes = _revived(item["attributes"])
270
+ if item["type"] == FILE_EVIDENCE and not current:
271
+ # Counts made by other code are not trusted: keep the path facts, drop the rest,
272
+ # so the guards see the file as not inspected.
273
+ attributes = {k: attributes[k] for k in _PATH_FACTS if k in attributes}
274
+ records.append(
275
+ Evidence(
276
+ record_type=item["type"],
277
+ external_ref=item["ref"],
278
+ observed_at=_time(item["observed_at"]) if "observed_at" in item else checked_at,
279
+ attributes=attributes,
280
+ occurred_at=_time(item["occurred_at"]) if item.get("occurred_at") else None,
281
+ version=int(item.get("version", 1)),
282
+ )
283
+ )
284
+ expected = None
285
+ if file_facts is not None:
286
+ observed_at = _time(file_facts["observed_at"])
287
+ records = [r for r in records if r.record_type != FILE_EVIDENCE] + [
288
+ Evidence(FILE_EVIDENCE, attrs["path"], observed_at, _revived(attrs))
289
+ for attrs in file_facts["files"]
290
+ ]
291
+ if isinstance(file_facts.get("changed_files"), int):
292
+ expected = file_facts["changed_files"]
293
+ elif current:
294
+ # Keep the original run's count of files GitHub never listed (the 3,000-file cap).
295
+ old = next(i for i in snapshot if i["type"] == SUMMARY_EVIDENCE)["attributes"]
296
+ listed = sum(1 for i in snapshot if i["type"] == FILE_EVIDENCE)
297
+ unlisted = old.get("uninspected", 0) - sum(
298
+ 1
299
+ for i in snapshot
300
+ if i["type"] == FILE_EVIDENCE and not i["attributes"].get("patch_available")
301
+ )
302
+ expected = listed + max(unlisted, 0)
303
+ files = [r for r in records if r.record_type == FILE_EVIDENCE]
304
+ if files or any(i["type"] == SUMMARY_EVIDENCE for i in snapshot):
305
+ number = int(episode.attributes["number"])
306
+ records.append(
307
+ mappers.files_summary_evidence(files, number, checked_at, expected_files=expected)
308
+ )
309
+ return records
310
+
311
+
312
+ _PATH_FACTS = ("path", "status", "additions", "deletions")
313
+
314
+
315
+ def _episode(
316
+ report: Mapping[str, Any], dataset_agent: str, file_facts: Mapping[str, Any] | None
317
+ ) -> Episode:
318
+ ref = report["pull_request"]["ref"]
319
+ url_repo, number = ref.lower().rsplit("#", 1)
320
+ # The repository's current name, as the live run used it (renamed repositories still
321
+ # answer at their old URL, and evidence about them carries the current name).
322
+ repo = (
323
+ (file_facts or {}).get("repo") or report["pull_request"].get("repo") or url_repo
324
+ ).lower()
325
+ agent = (report.get("agent") or {}).get("name") or dataset_agent
326
+ return Episode(
327
+ id=ref.lower(),
328
+ kind="pull_request",
329
+ agent=agent,
330
+ opened_at=_time(report["pull_request"]["opened_at"]),
331
+ # What checks read from the episode (mappers.episode_from_pull sets the same keys).
332
+ attributes={"repo": repo, "number": int(number), "url": report["pull_request"]["url"]},
333
+ )
334
+
335
+
336
+ def _claim(item: Mapping[str, Any], episode: Episode, evidence: list[Evidence]) -> Claim:
337
+ return Claim(
338
+ id=item["id"],
339
+ episode_id=episode.id,
340
+ type=item["type"],
341
+ made_at=_made_at(item, episode, evidence),
342
+ attributes=_revived(item["attributes"]),
343
+ origin=item["origin"],
344
+ span=item["span"],
345
+ )
346
+
347
+
348
+ def _made_at(item: Mapping[str, Any], episode: Episode, evidence: list[Evidence]) -> datetime:
349
+ """The stored claim time; for older records, rebuilt: merge claims at the merge, text claims
350
+ at the PR's opening (a commit or comment claim was later; ``_reproduces`` guards against
351
+ the difference)."""
352
+ if item.get("made_at"):
353
+ return _time(item["made_at"])
354
+ if item["origin"] == "merge":
355
+ state = next((e for e in evidence if e.record_type == "pr_state"), None)
356
+ merged_at = state.attributes.get("merged_at") if state else None
357
+ if isinstance(merged_at, datetime):
358
+ return merged_at
359
+ return episode.opened_at
360
+
361
+
362
+ def _snapshot_item(record: Evidence) -> dict[str, Any]:
363
+ item: dict[str, Any] = {
364
+ "type": record.record_type,
365
+ "ref": record.external_ref,
366
+ "attributes": {key: _plain(value) for key, value in record.attributes.items()},
367
+ "observed_at": record.observed_at.isoformat(),
368
+ "version": record.version,
369
+ }
370
+ if record.occurred_at is not None:
371
+ item["occurred_at"] = record.occurred_at.isoformat()
372
+ return item
373
+
374
+
375
+ # Snapshots store times as ISO strings (render._plain); checks compare them as timestamps.
376
+ _ISO_TIME = re.compile(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})")
377
+
378
+
379
+ def _revived(attributes: Mapping[str, Any]) -> dict[str, Any]:
380
+ """Attributes with ISO timestamp strings made datetimes again, as the mappers made them."""
381
+ return {
382
+ key: _time(value) if isinstance(value, str) and _ISO_TIME.fullmatch(value) else value
383
+ for key, value in attributes.items()
384
+ }
385
+
386
+
387
+ def _time(value: str) -> datetime:
388
+ return datetime.fromisoformat(value.replace("Z", "+00:00"))
@@ -0,0 +1,159 @@
1
+ """Batch runner: check many sampled pull requests and append one result per PR (section 5).
2
+
3
+ Design points:
4
+
5
+ - **Same pipeline as the CLI.** Every published number can be reproduced with
6
+ ``second-source check <url>``.
7
+ - **Resumable.** Results are appended to a JSON Lines file and flushed after every PR. PRs that
8
+ already have a result are skipped, so an interrupted run simply continues.
9
+ - **Rate limits stop the run cleanly.** A PR whose checking was cut short by the rate limit is
10
+ *not* recorded (its verdicts would be unverifiable only for lack of quota); it is retried on
11
+ the next run.
12
+ - **Evidence is kept.** Each result stores a compact snapshot of the evidence records its
13
+ verdicts came from (check names and conclusions, changed paths, issue states). GitHub deletes
14
+ old workflow runs, so without it a published verdict could not be audited a year later.
15
+ - **Errors are recorded, not fatal.** A deleted PR or a broken URL becomes an error record, so
16
+ one bad row never blocks a run, and the summary can count them.
17
+ - **Only permanent errors are final.** A deleted PR (``not_found``) or an invalid URL will not
18
+ change, so it counts as done. Any other error (an unexpected GitHub response, often a bug on
19
+ our side) is retried on the next run; the newer record replaces the older one when results
20
+ are read.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import json
26
+ from collections.abc import Callable, Iterable
27
+ from dataclasses import dataclass
28
+ from datetime import UTC, datetime
29
+ from functools import lru_cache
30
+ from pathlib import Path
31
+ from typing import Any
32
+
33
+ from second_source import __version__
34
+ from second_source.benchmark.aidev import AidevPullRequest
35
+ from second_source.packs import coding
36
+ from second_source.pipeline import check_pull_request
37
+ from second_source.report.render import evidence_snapshot, to_json
38
+ from second_source.sources.github.client import GitHubError, RateLimited
39
+ from second_source.sources.github.source import GitHubSource, PullRequestNotFound
40
+ from second_source.sources.github.urls import parse_pull_request
41
+
42
+ RESULT_SCHEMA_VERSION = "2" # 2: adds the evidence snapshot
43
+ # Always snapshot the PR's file list (one request), even when no claim needs it: integrity
44
+ # checks (CI config changed, tests removed) can then be re-scored offline.
45
+ SNAPSHOT_EVIDENCE = frozenset({"changed_file"})
46
+
47
+
48
+ @dataclass
49
+ class RunSummary:
50
+ checked: int = 0
51
+ skipped: int = 0 # already had a result from an earlier run
52
+ errors: int = 0
53
+ stopped: str | None = None # why the run ended early (rate limit, limit reached)
54
+
55
+
56
+ PERMANENT_ERRORS = ("not_found", "invalid url")
57
+
58
+
59
+ def _is_final(record: dict[str, Any]) -> bool:
60
+ """True for a checked PR or a permanent error; other errors are retried."""
61
+ error = record.get("error")
62
+ return error is None or str(error).startswith(PERMANENT_ERRORS)
63
+
64
+
65
+ def completed_urls(path: Path) -> set[str]:
66
+ """URLs that already have a final result in ``path`` (an absent file means none)."""
67
+ if not path.exists():
68
+ return set()
69
+ return {record["url"] for record in read_results(path) if _is_final(record)}
70
+
71
+
72
+ def run_benchmark(
73
+ rows: Iterable[AidevPullRequest],
74
+ out: Path,
75
+ *,
76
+ source: GitHubSource,
77
+ clock: Callable[[], datetime] = lambda: datetime.now(UTC),
78
+ limit: int | None = None,
79
+ progress: Callable[[str], None] = lambda _message: None,
80
+ ) -> RunSummary:
81
+ """Check each row's PR and append the result to ``out``.
82
+
83
+ ``limit`` caps how many PRs are checked in this run (useful for anonymous, 60-request
84
+ runs); already-completed PRs do not count towards it.
85
+ """
86
+ summary = RunSummary()
87
+ done = completed_urls(out)
88
+ out.parent.mkdir(parents=True, exist_ok=True)
89
+
90
+ with out.open("a", encoding="utf-8") as handle:
91
+ for row in rows:
92
+ if row.url in done:
93
+ summary.skipped += 1
94
+ continue
95
+ if limit is not None and summary.checked + summary.errors >= limit:
96
+ summary.stopped = f"reached the limit of {limit} pull requests"
97
+ break
98
+
99
+ record, stop = _check_one(row, source, clock)
100
+ if stop:
101
+ summary.stopped = stop
102
+ break
103
+ handle.write(json.dumps(record, sort_keys=True, ensure_ascii=False) + "\n")
104
+ handle.flush() # a crash loses at most the PR in progress
105
+ done.add(row.url)
106
+ if "error" in record:
107
+ summary.errors += 1
108
+ progress(f"error {row.url}: {record['error']}")
109
+ else:
110
+ summary.checked += 1
111
+ progress(f"ok {row.url} ({record['report']['api_requests']} requests)")
112
+ return summary
113
+
114
+
115
+ def _check_one(
116
+ row: AidevPullRequest, source: GitHubSource, clock: Callable[[], datetime]
117
+ ) -> tuple[dict[str, Any], str | None]:
118
+ """Return (record, stop reason). A stop reason means: record nothing and end the run."""
119
+ base = {
120
+ "schema_version": RESULT_SCHEMA_VERSION,
121
+ "url": row.url,
122
+ "dataset_agent": row.agent,
123
+ # Which code produced the verdicts: a run resumed after an upgrade mixes versions, and
124
+ # the summary must be able to tell (stats split or warn on them).
125
+ "tool_version": __version__,
126
+ "pack_version": _pack_version(),
127
+ }
128
+ try:
129
+ ref = parse_pull_request(row.url)
130
+ except ValueError as error:
131
+ return {**base, "error": f"invalid url: {error}"}, None
132
+ try:
133
+ report = check_pull_request(ref, source, now=clock(), extra_evidence=SNAPSHOT_EVIDENCE)
134
+ except RateLimited:
135
+ return base, "GitHub rate limit reached"
136
+ except PullRequestNotFound:
137
+ return {**base, "error": "not_found"}, None
138
+ except GitHubError as error:
139
+ return {**base, "error": f"github: {error}"}, None
140
+ if report.rate_limited:
141
+ return base, "GitHub rate limit reached"
142
+ return {**base, "report": to_json(report), "evidence": evidence_snapshot(report)}, None
143
+
144
+
145
+ @lru_cache(maxsize=1)
146
+ def _pack_version() -> str:
147
+ return coding.load().version
148
+
149
+
150
+ def read_results(path: Path) -> list[dict[str, Any]]:
151
+ """One record per URL, the newest one (a retried error is replaced by its later result),
152
+ in the order URLs first appear."""
153
+ latest: dict[str, dict[str, Any]] = {}
154
+ with path.open(encoding="utf-8") as handle:
155
+ for line in handle:
156
+ if line.strip():
157
+ record = json.loads(line)
158
+ latest[record["url"]] = record # dicts keep first-insertion order
159
+ return list(latest.values())