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.
- second_source/__init__.py +3 -0
- second_source/action/__init__.py +4 -0
- second_source/action/commands.py +88 -0
- second_source/action/event.py +89 -0
- second_source/action/inputs.py +118 -0
- second_source/action/main.py +203 -0
- second_source/action/publish.py +184 -0
- second_source/action/setup.py +143 -0
- second_source/action/sweep.py +85 -0
- second_source/action/wait.py +49 -0
- second_source/benchmark/__init__.py +1 -0
- second_source/benchmark/aidev.py +248 -0
- second_source/benchmark/aidev_local.py +85 -0
- second_source/benchmark/golden.py +314 -0
- second_source/benchmark/redact.py +45 -0
- second_source/benchmark/rescore.py +388 -0
- second_source/benchmark/runner.py +159 -0
- second_source/benchmark/sample.py +243 -0
- second_source/benchmark/stats.py +363 -0
- second_source/cli/__init__.py +1 -0
- second_source/cli/bench.py +427 -0
- second_source/cli/main.py +182 -0
- second_source/core/__init__.py +4 -0
- second_source/core/aggregate.py +102 -0
- second_source/core/checks.py +470 -0
- second_source/core/engine.py +98 -0
- second_source/core/evidence.py +29 -0
- second_source/core/expr.py +206 -0
- second_source/core/hashing.py +41 -0
- second_source/core/model.py +112 -0
- second_source/core/pack.py +156 -0
- second_source/packs/__init__.py +1 -0
- second_source/packs/coding/__init__.py +16 -0
- second_source/packs/coding/checks/ci_config_caution.yaml +23 -0
- second_source/packs/coding/checks/ci_result.yaml +133 -0
- second_source/packs/coding/checks/ci_weakening_caution.yaml +27 -0
- second_source/packs/coding/checks/deployed.yaml +36 -0
- second_source/packs/coding/checks/docs_updated.yaml +22 -0
- second_source/packs/coding/checks/fixes_issue.yaml +58 -0
- second_source/packs/coding/checks/fixes_issue_durable.yaml +60 -0
- second_source/packs/coding/checks/integrity_guard.yaml +34 -0
- second_source/packs/coding/checks/integrity_inspection.yaml +21 -0
- second_source/packs/coding/checks/lint_caution.yaml +22 -0
- second_source/packs/coding/checks/matching_jobs_caution.yaml +22 -0
- second_source/packs/coding/checks/not_reverted.yaml +38 -0
- second_source/packs/coding/checks/tests_added.yaml +25 -0
- second_source/packs/coding/checks/tests_added_guard.yaml +26 -0
- second_source/packs/coding/checks/tests_removed_caution.yaml +23 -0
- second_source/packs/coding/detection.py +94 -0
- second_source/packs/coding/diff_facts.py +665 -0
- second_source/packs/coding/extract.py +911 -0
- second_source/packs/coding/functions.py +241 -0
- second_source/packs/coding/pack.yaml +33 -0
- second_source/packs/coding/trusted_rules.yaml +50 -0
- second_source/pipeline.py +112 -0
- second_source/report/__init__.py +1 -0
- second_source/report/render.py +503 -0
- second_source/sources/__init__.py +1 -0
- second_source/sources/github/__init__.py +4 -0
- second_source/sources/github/auth.py +48 -0
- second_source/sources/github/cache.py +67 -0
- second_source/sources/github/client.py +261 -0
- second_source/sources/github/mappers.py +454 -0
- second_source/sources/github/source.py +385 -0
- second_source/sources/github/urls.py +51 -0
- second_source-0.5.0.dist-info/METADATA +311 -0
- second_source-0.5.0.dist-info/RECORD +71 -0
- second_source-0.5.0.dist-info/WHEEL +4 -0
- second_source-0.5.0.dist-info/entry_points.txt +2 -0
- second_source-0.5.0.dist-info/licenses/LICENSE +202 -0
- second_source-0.5.0.dist-info/licenses/NOTICE +9 -0
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
"""Read pull requests from the AIDev dataset without downloading it.
|
|
2
|
+
|
|
3
|
+
AIDev (``hao-li/AIDev`` on Hugging Face, CC-BY-4.0) is a public dataset of pull requests opened
|
|
4
|
+
by coding agents. Its curated ``pull_request`` table has about 361k rows. Instead of downloading
|
|
5
|
+
the Parquet files, we read 100-row pages through the Hugging Face dataset viewer API, which
|
|
6
|
+
needs no account and no disk. See docs/benchmark.md, section 1.
|
|
7
|
+
|
|
8
|
+
The dataset viewer always serves the latest dataset revision, so samplers record the revision
|
|
9
|
+
(``AidevClient.revision()``) next to their output; a later revision may shift row offsets.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import time
|
|
15
|
+
from collections.abc import Callable
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
import httpx
|
|
20
|
+
|
|
21
|
+
from second_source import __version__
|
|
22
|
+
from second_source.benchmark.redact import redact_secrets
|
|
23
|
+
|
|
24
|
+
DATASET = "hao-li/AIDev"
|
|
25
|
+
CONFIG = "pull_request" # the curated table (repositories with more than 100 stars)
|
|
26
|
+
ROWS_URL = "https://datasets-server.huggingface.co/rows"
|
|
27
|
+
FILTER_URL = "https://datasets-server.huggingface.co/filter"
|
|
28
|
+
COMMITS_CONFIG = "pr_commits" # one row per commit: sha, pr_id, author, committer, message
|
|
29
|
+
INFO_URL = f"https://huggingface.co/api/datasets/{DATASET}"
|
|
30
|
+
MAX_PAGE = 100 # the dataset viewer returns at most 100 rows per request
|
|
31
|
+
USER_AGENT = f"second-source/{__version__}"
|
|
32
|
+
SERVER_ERROR_BACKOFF = 2.0 # seconds before the first retry; doubles on each retry
|
|
33
|
+
RATE_LIMIT_BACKOFF = 30.0 # HTTP 429 comes without a Retry-After header, so wait longer
|
|
34
|
+
|
|
35
|
+
# AIDev's agent labels mapped to the names our detection rules use (packs/coding/detection.py).
|
|
36
|
+
AGENT_NAMES = {
|
|
37
|
+
"Claude_Code": "claude_code",
|
|
38
|
+
"OpenAI_Codex": "codex",
|
|
39
|
+
"Copilot": "copilot",
|
|
40
|
+
"Cursor": "cursor",
|
|
41
|
+
"Devin": "devin",
|
|
42
|
+
"Google_Jules": "jules",
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def repo_of(url: str) -> str:
|
|
47
|
+
"""``owner/name`` of a GitHub pull request URL, lower-cased; "" if it is not one."""
|
|
48
|
+
parts = url.lower().split("/")
|
|
49
|
+
return "/".join(parts[3:5]) if len(parts) > 4 and parts[2].endswith("github.com") else ""
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class AidevError(Exception):
|
|
53
|
+
"""The dataset viewer API failed after retries, or answered with something unexpected."""
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@dataclass(frozen=True)
|
|
57
|
+
class AidevPullRequest:
|
|
58
|
+
"""The fields of one AIDev row that the benchmark uses."""
|
|
59
|
+
|
|
60
|
+
url: str
|
|
61
|
+
agent: str # our agent name (see AGENT_NAMES); the raw label if it is not mapped
|
|
62
|
+
title: str
|
|
63
|
+
body: str
|
|
64
|
+
state: str
|
|
65
|
+
created_at: str | None
|
|
66
|
+
merged_at: str | None
|
|
67
|
+
id: str = "" # AIDev's PR id, the key of its pr_commits table ("" in older sample files)
|
|
68
|
+
|
|
69
|
+
@property
|
|
70
|
+
def merged(self) -> bool:
|
|
71
|
+
return bool(self.merged_at)
|
|
72
|
+
|
|
73
|
+
@property
|
|
74
|
+
def repo(self) -> str:
|
|
75
|
+
"""``owner/name`` from the URL, lower-cased (GitHub names are case-insensitive)."""
|
|
76
|
+
return repo_of(self.url)
|
|
77
|
+
|
|
78
|
+
@classmethod
|
|
79
|
+
def from_row(cls, row: dict[str, Any]) -> AidevPullRequest:
|
|
80
|
+
"""Map a dataset row. Credentials that agents leaked into PR text (for example signed
|
|
81
|
+
screenshot links) are redacted here, before anything is stored."""
|
|
82
|
+
label = row.get("agent") or ""
|
|
83
|
+
return cls(
|
|
84
|
+
url=row["html_url"],
|
|
85
|
+
agent=AGENT_NAMES.get(label, label),
|
|
86
|
+
title=redact_secrets(row.get("title") or ""),
|
|
87
|
+
body=redact_secrets(row.get("body") or ""),
|
|
88
|
+
state=row.get("state") or "",
|
|
89
|
+
created_at=row.get("created_at"),
|
|
90
|
+
merged_at=row.get("merged_at"),
|
|
91
|
+
id=str(row.get("id") or ""),
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
def to_dict(self) -> dict[str, Any]:
|
|
95
|
+
return {
|
|
96
|
+
"url": self.url,
|
|
97
|
+
"agent": self.agent,
|
|
98
|
+
"title": self.title,
|
|
99
|
+
"body": self.body,
|
|
100
|
+
"state": self.state,
|
|
101
|
+
"created_at": self.created_at,
|
|
102
|
+
"merged_at": self.merged_at,
|
|
103
|
+
"id": self.id,
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
@dataclass(frozen=True)
|
|
108
|
+
class Page:
|
|
109
|
+
"""One page of rows plus the table's total row count."""
|
|
110
|
+
|
|
111
|
+
rows: tuple[AidevPullRequest, ...]
|
|
112
|
+
total: int
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
class AidevClient:
|
|
116
|
+
"""Thin client for the dataset viewer ``/rows`` endpoint.
|
|
117
|
+
|
|
118
|
+
The dataset viewer is a free shared service that answers bursts with HTTP 429 and no
|
|
119
|
+
rate-limit headers, so the client paces itself (``min_interval`` seconds between requests)
|
|
120
|
+
and backs off for longer after a 429 than after a server error.
|
|
121
|
+
|
|
122
|
+
The transport, sleep and clock are injectable so tests never touch the network or wait.
|
|
123
|
+
"""
|
|
124
|
+
|
|
125
|
+
def __init__(
|
|
126
|
+
self,
|
|
127
|
+
*,
|
|
128
|
+
transport: httpx.BaseTransport | None = None,
|
|
129
|
+
retries: int = 4,
|
|
130
|
+
min_interval: float = 1.0,
|
|
131
|
+
sleep: Callable[[float], None] = time.sleep,
|
|
132
|
+
clock: Callable[[], float] = time.monotonic,
|
|
133
|
+
timeout: float = 30.0,
|
|
134
|
+
) -> None:
|
|
135
|
+
self._http = httpx.Client(
|
|
136
|
+
transport=transport, headers={"User-Agent": USER_AGENT}, timeout=timeout
|
|
137
|
+
)
|
|
138
|
+
self._retries = retries
|
|
139
|
+
self._min_interval = min_interval
|
|
140
|
+
self._sleep = sleep
|
|
141
|
+
self._clock = clock
|
|
142
|
+
self._last_request: float | None = None
|
|
143
|
+
|
|
144
|
+
def __enter__(self) -> AidevClient:
|
|
145
|
+
return self
|
|
146
|
+
|
|
147
|
+
def __exit__(self, *_exc: object) -> None:
|
|
148
|
+
self.close()
|
|
149
|
+
|
|
150
|
+
def close(self) -> None:
|
|
151
|
+
self._http.close()
|
|
152
|
+
|
|
153
|
+
def page(self, offset: int, length: int = MAX_PAGE) -> Page:
|
|
154
|
+
"""Rows ``offset .. offset+length-1`` of the curated pull request table."""
|
|
155
|
+
if offset < 0 or not 0 < length <= MAX_PAGE:
|
|
156
|
+
raise ValueError(f"invalid page: offset={offset}, length={length}")
|
|
157
|
+
params = {
|
|
158
|
+
"dataset": DATASET,
|
|
159
|
+
"config": CONFIG,
|
|
160
|
+
"split": "train",
|
|
161
|
+
"offset": offset,
|
|
162
|
+
"length": length,
|
|
163
|
+
}
|
|
164
|
+
data = self._get_json(ROWS_URL, params)
|
|
165
|
+
try:
|
|
166
|
+
rows = tuple(AidevPullRequest.from_row(item["row"]) for item in data["rows"])
|
|
167
|
+
return Page(rows=rows, total=int(data["num_rows_total"]))
|
|
168
|
+
except (KeyError, TypeError, ValueError) as error:
|
|
169
|
+
raise AidevError(f"unexpected response shape: {error!r}") from error
|
|
170
|
+
|
|
171
|
+
def commit_messages(self, pr_id: str, limit: int = MAX_PAGE) -> list[dict[str, str]]:
|
|
172
|
+
"""Commits of one PR (``{"sha", "message"}``) from AIDev's ``pr_commits`` table, in
|
|
173
|
+
table order. The sha is kept so labels stay tied to an exact commit.
|
|
174
|
+
|
|
175
|
+
Read with the dataset viewer's filter endpoint, so commit texts can be labelled without
|
|
176
|
+
any GitHub requests. Messages are redacted like PR bodies.
|
|
177
|
+
"""
|
|
178
|
+
if not pr_id.isdigit(): # the id goes into a filter expression
|
|
179
|
+
raise ValueError(f"invalid AIDev pr_id: {pr_id!r}")
|
|
180
|
+
params = {
|
|
181
|
+
"dataset": DATASET,
|
|
182
|
+
"config": COMMITS_CONFIG,
|
|
183
|
+
"split": "train",
|
|
184
|
+
"where": f"\"pr_id\"='{pr_id}'",
|
|
185
|
+
"offset": 0,
|
|
186
|
+
"length": min(limit, MAX_PAGE),
|
|
187
|
+
}
|
|
188
|
+
data = self._get_json(FILTER_URL, params)
|
|
189
|
+
try:
|
|
190
|
+
return [
|
|
191
|
+
{
|
|
192
|
+
"sha": str(item["row"].get("sha") or ""),
|
|
193
|
+
"message": redact_secrets(item["row"].get("message") or ""),
|
|
194
|
+
}
|
|
195
|
+
for item in data["rows"]
|
|
196
|
+
]
|
|
197
|
+
except (KeyError, TypeError) as error:
|
|
198
|
+
raise AidevError(f"unexpected response shape: {error!r}") from error
|
|
199
|
+
|
|
200
|
+
def revision(self) -> str:
|
|
201
|
+
"""The dataset's current git revision (commit sha), recorded next to samples."""
|
|
202
|
+
data = self._get_json(INFO_URL, {})
|
|
203
|
+
try:
|
|
204
|
+
return str(data["sha"])
|
|
205
|
+
except (KeyError, TypeError) as error:
|
|
206
|
+
raise AidevError("dataset info has no revision") from error
|
|
207
|
+
|
|
208
|
+
def _get_json(self, url: str, params: dict[str, Any]) -> Any:
|
|
209
|
+
# Retry server errors, rate limits and network failures with exponential backoff.
|
|
210
|
+
# The dataset viewer answers with an "index is loading" error while it warms up,
|
|
211
|
+
# which is also worth waiting for.
|
|
212
|
+
last_problem = ""
|
|
213
|
+
backoff = 0.0
|
|
214
|
+
for attempt in range(self._retries + 1):
|
|
215
|
+
if attempt:
|
|
216
|
+
self._sleep(backoff * 2.0 ** (attempt - 1))
|
|
217
|
+
self._pace()
|
|
218
|
+
try:
|
|
219
|
+
response = self._http.get(url, params=params)
|
|
220
|
+
except httpx.TransportError as error:
|
|
221
|
+
last_problem = f"network error: {error.__class__.__name__}"
|
|
222
|
+
backoff = SERVER_ERROR_BACKOFF
|
|
223
|
+
continue
|
|
224
|
+
if response.status_code == 200:
|
|
225
|
+
data = response.json()
|
|
226
|
+
if isinstance(data, dict) and "error" in data:
|
|
227
|
+
last_problem = str(data["error"])
|
|
228
|
+
backoff = SERVER_ERROR_BACKOFF
|
|
229
|
+
continue
|
|
230
|
+
return data
|
|
231
|
+
last_problem = f"HTTP {response.status_code}"
|
|
232
|
+
if response.status_code == 429:
|
|
233
|
+
backoff = RATE_LIMIT_BACKOFF
|
|
234
|
+
elif response.status_code >= 500:
|
|
235
|
+
backoff = SERVER_ERROR_BACKOFF
|
|
236
|
+
else:
|
|
237
|
+
break # a client error will not fix itself
|
|
238
|
+
raise AidevError(f"dataset viewer request failed: {last_problem}")
|
|
239
|
+
|
|
240
|
+
def _pace(self) -> None:
|
|
241
|
+
"""Wait until at least ``min_interval`` seconds have passed since the last request."""
|
|
242
|
+
now = self._clock()
|
|
243
|
+
if self._last_request is not None:
|
|
244
|
+
wait = self._last_request + self._min_interval - now
|
|
245
|
+
if wait > 0:
|
|
246
|
+
self._sleep(wait)
|
|
247
|
+
now += wait
|
|
248
|
+
self._last_request = now
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""Read AIDev from a downloaded Parquet file instead of the dataset viewer API.
|
|
2
|
+
|
|
3
|
+
The Hugging Face dataset viewer is a free shared service and goes down for hours at a time
|
|
4
|
+
(HTTP 502/503), which kills an hour-long sampling run part way. The viewer serves the rows of
|
|
5
|
+
the dataset's Parquet conversion, so the same file, downloaded once, gives the same rows at the
|
|
6
|
+
same offsets, locally and in seconds:
|
|
7
|
+
|
|
8
|
+
https://huggingface.co/datasets/hao-li/AIDev/resolve/refs%2Fconvert%2Fparquet/pull_request/train/0000.parquet
|
|
9
|
+
|
|
10
|
+
``ParquetAidev`` offers the two methods samplers use (``page`` and ``revision``), so it is a
|
|
11
|
+
drop-in replacement for ``AidevClient``. Rows go through ``AidevPullRequest.from_row``, so they
|
|
12
|
+
are mapped and redacted exactly as API rows are.
|
|
13
|
+
|
|
14
|
+
pyarrow is an optional dependency (``uv sync --extra local``); it is imported only when a
|
|
15
|
+
Parquet file is used, so the CLI and the GitHub Action never need it.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import hashlib
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
from typing import Any
|
|
23
|
+
|
|
24
|
+
from second_source.benchmark.aidev import MAX_PAGE, AidevError, AidevPullRequest, Page
|
|
25
|
+
|
|
26
|
+
# The columns AidevPullRequest.from_row reads; loading only these keeps memory low.
|
|
27
|
+
COLUMNS = ("html_url", "agent", "title", "body", "state", "created_at", "merged_at", "id")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class ParquetAidev:
|
|
31
|
+
"""The curated ``pull_request`` table, read from a local Parquet file."""
|
|
32
|
+
|
|
33
|
+
def __init__(self, path: Path) -> None:
|
|
34
|
+
try:
|
|
35
|
+
import pyarrow.parquet as pq
|
|
36
|
+
except ImportError as error: # pragma: no cover - depends on the environment
|
|
37
|
+
raise AidevError(
|
|
38
|
+
"reading a Parquet file needs pyarrow: run `uv sync --extra local`"
|
|
39
|
+
) from error
|
|
40
|
+
self._path = path
|
|
41
|
+
try:
|
|
42
|
+
self._table = pq.read_table(path, columns=list(COLUMNS), memory_map=True)
|
|
43
|
+
except (OSError, ValueError) as error:
|
|
44
|
+
raise AidevError(f"cannot read {path}: {error}") from error
|
|
45
|
+
|
|
46
|
+
def __enter__(self) -> ParquetAidev:
|
|
47
|
+
return self
|
|
48
|
+
|
|
49
|
+
def __exit__(self, *_exc: object) -> None:
|
|
50
|
+
self.close()
|
|
51
|
+
|
|
52
|
+
def close(self) -> None:
|
|
53
|
+
"""Nothing to release; present so it can stand in for AidevClient."""
|
|
54
|
+
|
|
55
|
+
def page(self, offset: int, length: int = MAX_PAGE) -> Page:
|
|
56
|
+
"""Rows ``offset .. offset+length-1``, like the dataset viewer's /rows endpoint."""
|
|
57
|
+
if offset < 0 or not 0 < length <= MAX_PAGE:
|
|
58
|
+
raise ValueError(f"invalid page: offset={offset}, length={length}")
|
|
59
|
+
rows: list[dict[str, Any]] = self._table.slice(offset, length).to_pylist()
|
|
60
|
+
return Page(
|
|
61
|
+
rows=tuple(AidevPullRequest.from_row(_as_api_row(row)) for row in rows),
|
|
62
|
+
total=len(self),
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
def revision(self) -> str:
|
|
66
|
+
"""The file's SHA-256, so a sample records exactly which data it was drawn from.
|
|
67
|
+
|
|
68
|
+
A Parquet file carries no dataset revision; the file hash identifies it uniquely.
|
|
69
|
+
"""
|
|
70
|
+
digest = hashlib.sha256()
|
|
71
|
+
with self._path.open("rb") as handle:
|
|
72
|
+
for chunk in iter(lambda: handle.read(1 << 20), b""):
|
|
73
|
+
digest.update(chunk)
|
|
74
|
+
return f"parquet-sha256:{digest.hexdigest()}"
|
|
75
|
+
|
|
76
|
+
def __len__(self) -> int:
|
|
77
|
+
return self._table.num_rows
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _as_api_row(row: dict[str, Any]) -> dict[str, Any]:
|
|
81
|
+
"""Parquet may type timestamps; the API returns ISO strings. Match the API."""
|
|
82
|
+
return {
|
|
83
|
+
key: value.isoformat() if hasattr(value, "isoformat") else value
|
|
84
|
+
for key, value in row.items()
|
|
85
|
+
}
|
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
"""Score claim extraction against a labelled golden set (docs/benchmark.md, section 3).
|
|
2
|
+
|
|
3
|
+
A golden case is a PR text plus the claim types a labeller says it asserts. Scoring compares
|
|
4
|
+
expected and predicted claim types per case as multisets (a PR can fix two issues), then sums
|
|
5
|
+
true positives, false positives and false negatives per claim type.
|
|
6
|
+
|
|
7
|
+
Real cases are split into **dev** (rules may be tuned on it) and **test** (only reported) by a
|
|
8
|
+
hash of the PR URL, so the split never depends on file order and never changes.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import hashlib
|
|
14
|
+
import json
|
|
15
|
+
import re
|
|
16
|
+
from collections import Counter
|
|
17
|
+
from collections.abc import Iterable, Mapping, Sequence
|
|
18
|
+
from dataclasses import dataclass, field
|
|
19
|
+
from datetime import UTC, datetime
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
from second_source.benchmark.aidev import repo_of
|
|
24
|
+
from second_source.benchmark.stats import wilson_interval
|
|
25
|
+
from second_source.packs.coding.extract import HIGH, TextSource, extract_claims, rule_hits
|
|
26
|
+
|
|
27
|
+
DEV, TEST = "dev", "test"
|
|
28
|
+
_WRITTEN_AT = datetime(2026, 1, 1, tzinfo=UTC) # extraction needs a time; its value is irrelevant
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def split_for(url: str) -> str:
|
|
32
|
+
"""Deterministic 50/50 dev/test split from the PR URL."""
|
|
33
|
+
return DEV if hashlib.sha256(url.encode()).digest()[0] % 2 == 0 else TEST
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True)
|
|
37
|
+
class GoldenCase:
|
|
38
|
+
name: str # a URL for real cases, a short description for seed cases
|
|
39
|
+
text: str
|
|
40
|
+
expected: tuple[str, ...]
|
|
41
|
+
agent: str = ""
|
|
42
|
+
notes: str = ""
|
|
43
|
+
origin: str = "body" # "body" or "commit": which kind of text was labelled
|
|
44
|
+
# "url" (the original set) or "repo": hash the repository, so a repository's PRs, and a PR's
|
|
45
|
+
# body and commit messages, always land in the same split.
|
|
46
|
+
split_by: str = "url"
|
|
47
|
+
|
|
48
|
+
@property
|
|
49
|
+
def split(self) -> str:
|
|
50
|
+
url = self.name.split("#", 1)[0] # "<pr url>#commit-2" belongs with its PR
|
|
51
|
+
return split_for(repo_of(url) if self.split_by == "repo" else url)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass
|
|
55
|
+
class Metrics:
|
|
56
|
+
"""Counts for one claim type, with precision and recall."""
|
|
57
|
+
|
|
58
|
+
true_positive: int = 0
|
|
59
|
+
false_positive: int = 0
|
|
60
|
+
false_negative: int = 0
|
|
61
|
+
|
|
62
|
+
@property
|
|
63
|
+
def precision(self) -> float:
|
|
64
|
+
predicted = self.true_positive + self.false_positive
|
|
65
|
+
return self.true_positive / predicted if predicted else 1.0
|
|
66
|
+
|
|
67
|
+
@property
|
|
68
|
+
def recall(self) -> float:
|
|
69
|
+
return self.true_positive / self.support if self.support else 1.0
|
|
70
|
+
|
|
71
|
+
@property
|
|
72
|
+
def support(self) -> int:
|
|
73
|
+
"""How many claims of this type the labels contain."""
|
|
74
|
+
return self.true_positive + self.false_negative
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
@dataclass
|
|
78
|
+
class Score:
|
|
79
|
+
per_type: dict[str, Metrics] = field(default_factory=dict)
|
|
80
|
+
mistakes: list[str] = field(default_factory=list) # one line per case that went wrong
|
|
81
|
+
|
|
82
|
+
def report(self) -> str:
|
|
83
|
+
lines = ["Per-type results:"]
|
|
84
|
+
for claim_type in sorted(self.per_type):
|
|
85
|
+
m = self.per_type[claim_type]
|
|
86
|
+
lines.append(
|
|
87
|
+
f" {claim_type:<13} precision={m.precision:.2f} recall={m.recall:.2f} "
|
|
88
|
+
f"n={m.support} (tp={m.true_positive} fp={m.false_positive} "
|
|
89
|
+
f"fn={m.false_negative})"
|
|
90
|
+
)
|
|
91
|
+
if self.mistakes:
|
|
92
|
+
lines += ["Mismatched cases:", *self.mistakes]
|
|
93
|
+
return "\n".join(lines)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
_REPO_IN_URL = re.compile(r"github\.com/([^/]+/[^/]+)/pull/")
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def predict(
|
|
100
|
+
text: str, url: str = "", *, high_only: bool = False, origin: str = "body"
|
|
101
|
+
) -> Counter[str]:
|
|
102
|
+
"""Claim types extracted from one PR body. The repository is taken from the PR URL, as the
|
|
103
|
+
pipeline does, so "Fixes #12" and "Fixes owner/repo#12" count as one claim. With
|
|
104
|
+
``high_only`` only claims found by trusted rules count (what the benchmark publishes)."""
|
|
105
|
+
found = _REPO_IN_URL.search(url)
|
|
106
|
+
source = TextSource(origin=origin, text=text, written_at=_WRITTEN_AT)
|
|
107
|
+
claims = extract_claims("golden", [source], repo=found.group(1) if found else None)
|
|
108
|
+
if high_only:
|
|
109
|
+
claims = [claim for claim in claims if claim.attributes.get("confidence") == HIGH]
|
|
110
|
+
return Counter(claim.type for claim in claims)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def score(cases: Iterable[GoldenCase], *, high_only: bool = False) -> Score:
|
|
114
|
+
result = Score()
|
|
115
|
+
for case in cases:
|
|
116
|
+
expected = Counter(case.expected)
|
|
117
|
+
predicted = predict(case.text, case.name, high_only=high_only, origin=case.origin)
|
|
118
|
+
for claim_type in expected | predicted:
|
|
119
|
+
metrics = result.per_type.setdefault(claim_type, Metrics())
|
|
120
|
+
hits = min(expected[claim_type], predicted[claim_type])
|
|
121
|
+
metrics.true_positive += hits
|
|
122
|
+
metrics.false_positive += predicted[claim_type] - hits
|
|
123
|
+
metrics.false_negative += expected[claim_type] - hits
|
|
124
|
+
if expected != predicted:
|
|
125
|
+
result.mistakes.append(
|
|
126
|
+
f" {case.name}: expected {dict(expected)}, got {dict(predicted)}"
|
|
127
|
+
)
|
|
128
|
+
return result
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def load_cases(path: Path) -> list[GoldenCase]:
|
|
132
|
+
"""Read real golden cases from JSON Lines (one case per line)."""
|
|
133
|
+
cases = []
|
|
134
|
+
with path.open(encoding="utf-8") as handle:
|
|
135
|
+
for line in handle:
|
|
136
|
+
if line.strip():
|
|
137
|
+
cases.append(_case(json.loads(line)))
|
|
138
|
+
return cases
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _case(record: dict[str, Any]) -> GoldenCase:
|
|
142
|
+
return GoldenCase(
|
|
143
|
+
name=record["url"],
|
|
144
|
+
text=record["body"],
|
|
145
|
+
expected=tuple(record["expected"]),
|
|
146
|
+
agent=record.get("agent", ""),
|
|
147
|
+
notes=record.get("notes", ""),
|
|
148
|
+
origin=record.get("origin", "body"),
|
|
149
|
+
split_by=record.get("split_by", "url"),
|
|
150
|
+
)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def in_split(cases: Sequence[GoldenCase], split: str) -> list[GoldenCase]:
|
|
154
|
+
return [case for case in cases if case.split == split]
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
# ---- building a golden set from two independent labellers ---------------------------------
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
@dataclass
|
|
161
|
+
class MergeResult:
|
|
162
|
+
"""Merged golden records plus what a reader needs to judge the labels."""
|
|
163
|
+
|
|
164
|
+
records: list[dict[str, Any]]
|
|
165
|
+
exact_agreement: int # PRs where both labellers gave the same multiset of claims
|
|
166
|
+
total: int
|
|
167
|
+
unresolved: list[dict[str, Any]] # disagreements without an adjudication yet
|
|
168
|
+
kappa: dict[str, float | None] = field(default_factory=dict) # per claim type, see below
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def merge_labels(
|
|
172
|
+
rows: Sequence[Mapping[str, Any]],
|
|
173
|
+
labels_a: Mapping[str, Mapping[str, Any]],
|
|
174
|
+
labels_b: Mapping[str, Mapping[str, Any]],
|
|
175
|
+
adjudications: Mapping[str, Mapping[str, Any]],
|
|
176
|
+
) -> MergeResult:
|
|
177
|
+
"""Combine two labellers' labels for sampled PRs (rows have url, agent and body).
|
|
178
|
+
|
|
179
|
+
Where the labellers agree, their label is ``expected``. Where they disagree, an
|
|
180
|
+
adjudication ``{"expected": [...], "reason": "..."}`` decides; without one the case is
|
|
181
|
+
reported as unresolved and left out, so nothing is ever guessed.
|
|
182
|
+
"""
|
|
183
|
+
urls = {row["url"] for row in rows}
|
|
184
|
+
if set(labels_a) != urls or set(labels_b) != urls:
|
|
185
|
+
raise ValueError("both labellers must label exactly the sampled PRs")
|
|
186
|
+
|
|
187
|
+
records, unresolved, agreed = [], [], 0
|
|
188
|
+
for row in rows:
|
|
189
|
+
url = row["url"]
|
|
190
|
+
a, b = sorted(labels_a[url]["expected"]), sorted(labels_b[url]["expected"])
|
|
191
|
+
record: dict[str, Any] = {
|
|
192
|
+
"url": url,
|
|
193
|
+
"agent": row["agent"],
|
|
194
|
+
"body": row["body"],
|
|
195
|
+
"origin": row.get("origin", "body"),
|
|
196
|
+
"labeller_a": a,
|
|
197
|
+
"labeller_b": b,
|
|
198
|
+
"notes_a": labels_a[url].get("notes", ""),
|
|
199
|
+
"notes_b": labels_b[url].get("notes", ""),
|
|
200
|
+
}
|
|
201
|
+
if a == b:
|
|
202
|
+
agreed += 1
|
|
203
|
+
record["expected"] = a
|
|
204
|
+
elif url in adjudications:
|
|
205
|
+
record["expected"] = sorted(adjudications[url]["expected"])
|
|
206
|
+
record["adjudication"] = adjudications[url]["reason"]
|
|
207
|
+
else:
|
|
208
|
+
unresolved.append(record)
|
|
209
|
+
continue
|
|
210
|
+
records.append(record)
|
|
211
|
+
kappa = cohens_kappa(
|
|
212
|
+
[sorted(labels_a[row["url"]]["expected"]) for row in rows],
|
|
213
|
+
[sorted(labels_b[row["url"]]["expected"]) for row in rows],
|
|
214
|
+
)
|
|
215
|
+
return MergeResult(records, agreed, len(rows), unresolved, kappa)
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def cohens_kappa(
|
|
219
|
+
labels_a: Sequence[Sequence[str]], labels_b: Sequence[Sequence[str]]
|
|
220
|
+
) -> dict[str, float | None]:
|
|
221
|
+
"""Cohen's kappa per claim type, on "does this item have the type" (yes/no).
|
|
222
|
+
|
|
223
|
+
Exact agreement is inflated when most items have no claim of a type; kappa corrects for
|
|
224
|
+
agreement expected by chance. None when a type never appears (kappa is undefined).
|
|
225
|
+
"""
|
|
226
|
+
types = sorted({t for labels in (*labels_a, *labels_b) for t in labels})
|
|
227
|
+
n = len(labels_a)
|
|
228
|
+
result: dict[str, float | None] = {}
|
|
229
|
+
for claim_type in types:
|
|
230
|
+
a = [claim_type in labels for labels in labels_a]
|
|
231
|
+
b = [claim_type in labels for labels in labels_b]
|
|
232
|
+
observed = sum(x == y for x, y in zip(a, b, strict=True)) / n
|
|
233
|
+
pa, pb = sum(a) / n, sum(b) / n
|
|
234
|
+
expected = pa * pb + (1 - pa) * (1 - pb)
|
|
235
|
+
result[claim_type] = None if expected == 1 else (observed - expected) / (1 - expected)
|
|
236
|
+
return result
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
# ---- precision per extraction rule ----------------------------------------------------------
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
@dataclass
|
|
243
|
+
class RuleMetrics:
|
|
244
|
+
"""How often one rule's hits were right, counted once per case it fired in."""
|
|
245
|
+
|
|
246
|
+
claim_type: str
|
|
247
|
+
correct: int = 0
|
|
248
|
+
wrong: int = 0
|
|
249
|
+
|
|
250
|
+
@property
|
|
251
|
+
def hits(self) -> int:
|
|
252
|
+
return self.correct + self.wrong
|
|
253
|
+
|
|
254
|
+
@property
|
|
255
|
+
def precision(self) -> float:
|
|
256
|
+
return self.correct / self.hits if self.hits else 1.0
|
|
257
|
+
|
|
258
|
+
@property
|
|
259
|
+
def precision_low(self) -> float:
|
|
260
|
+
"""Lower end of the 95% Wilson interval: what the precision is at least, plausibly."""
|
|
261
|
+
return wilson_interval(self.correct, self.hits)[0] if self.hits else 0.0
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
RuleKey = tuple[str, str] # (claim type, rule name): command rules yield several claim types
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def score_rules(cases: Iterable[GoldenCase]) -> dict[RuleKey, RuleMetrics]:
|
|
268
|
+
"""Precision of every extraction rule for each claim type it produces, judged on its own.
|
|
269
|
+
|
|
270
|
+
A rule's hit in a case is correct when the case's labels contain that claim type. Each
|
|
271
|
+
rule counts at most once per case and type, matching how claims are counted.
|
|
272
|
+
"""
|
|
273
|
+
metrics: dict[RuleKey, RuleMetrics] = {}
|
|
274
|
+
for case in cases:
|
|
275
|
+
expected = set(case.expected)
|
|
276
|
+
for claim_type, rule in rule_hits(case.text, origin=case.origin):
|
|
277
|
+
entry = metrics.setdefault((claim_type, rule), RuleMetrics(claim_type))
|
|
278
|
+
if claim_type in expected:
|
|
279
|
+
entry.correct += 1
|
|
280
|
+
else:
|
|
281
|
+
entry.wrong += 1
|
|
282
|
+
return metrics
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def rules_report(metrics: Mapping[RuleKey, RuleMetrics]) -> str:
|
|
286
|
+
lines = [f" {'rule':<30} {'type':<13} hits right precision (95% low)"]
|
|
287
|
+
for (_kind, rule), m in sorted(metrics.items()):
|
|
288
|
+
lines.append(
|
|
289
|
+
f" {rule:<30} {m.claim_type:<13} {m.hits:>4} {m.correct:>5} "
|
|
290
|
+
f"{m.precision:>9.2f} ({m.precision_low:.2f})"
|
|
291
|
+
)
|
|
292
|
+
return "\n".join(lines)
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def select_trusted(
|
|
296
|
+
metrics: Mapping[RuleKey, RuleMetrics], *, min_hits: int, min_precision: float
|
|
297
|
+
) -> list[dict[str, Any]]:
|
|
298
|
+
"""The (claim type, rule) pairs that fired often enough and were right often enough.
|
|
299
|
+
|
|
300
|
+
The criterion is fixed before looking at the held-out split, so that split can then test
|
|
301
|
+
whether the selection holds on unseen text.
|
|
302
|
+
"""
|
|
303
|
+
chosen = []
|
|
304
|
+
for (claim_type, rule), m in sorted(metrics.items()):
|
|
305
|
+
if m.hits >= min_hits and m.precision >= min_precision:
|
|
306
|
+
chosen.append(
|
|
307
|
+
{
|
|
308
|
+
"type": claim_type,
|
|
309
|
+
"rule": rule,
|
|
310
|
+
"hits": m.hits,
|
|
311
|
+
"precision": round(m.precision, 3),
|
|
312
|
+
}
|
|
313
|
+
)
|
|
314
|
+
return chosen
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""Remove credentials from third-party text before we store or publish it.
|
|
2
|
+
|
|
3
|
+
PR descriptions in the AIDev dataset are public text written by agents, and some contain
|
|
4
|
+
credentials by accident. Example: Devin attaches screenshots through pre-signed S3 links,
|
|
5
|
+
whose query strings carry a temporary AWS key ID, a session token and a signature. Those
|
|
6
|
+
credentials are not ours and have long expired, but a repository should never redistribute
|
|
7
|
+
them, and secret scanners rightly flag them.
|
|
8
|
+
|
|
9
|
+
``redact_secrets`` replaces the secret part of each match with ``REDACTED`` and keeps the
|
|
10
|
+
surrounding text, so claim extraction and the golden-set labels are unaffected.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import re
|
|
16
|
+
|
|
17
|
+
REDACTED = "REDACTED"
|
|
18
|
+
|
|
19
|
+
# Signed-URL query parameters (AWS SigV4, Google Cloud Storage V4, Azure SAS).
|
|
20
|
+
_SIGNED_URL_PARAM = re.compile(
|
|
21
|
+
r"(?P<name>X-Amz-(?:Credential|Signature|Security-Token)"
|
|
22
|
+
r"|X-Goog-(?:Credential|Signature)"
|
|
23
|
+
r"|(?<=[?&])sig)="
|
|
24
|
+
r"(?P<value>[^&\s\"'<>)\]]+)",
|
|
25
|
+
re.IGNORECASE,
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
# Credential formats with a recognisable prefix. The prefix is kept so a reader can still see
|
|
29
|
+
# what kind of value was removed.
|
|
30
|
+
_TOKEN = re.compile(
|
|
31
|
+
r"\b(?P<prefix>AKIA|ASIA)[0-9A-Z]{16}\b" # AWS access key IDs (long-term, temporary)
|
|
32
|
+
r"|\b(?P<gh>ghp_|gho_|ghu_|ghs_|ghr_|github_pat_)[A-Za-z0-9_]{20,}" # GitHub tokens
|
|
33
|
+
r"|\b(?P<slack>xox[abprs]-)[0-9A-Za-z-]{10,}" # Slack tokens
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _token_replacement(match: re.Match[str]) -> str:
|
|
38
|
+
prefix = match.group("prefix") or match.group("gh") or match.group("slack")
|
|
39
|
+
return f"{prefix}{REDACTED}"
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def redact_secrets(text: str) -> str:
|
|
43
|
+
"""Return ``text`` with signed-URL credentials and known token formats redacted."""
|
|
44
|
+
text = _SIGNED_URL_PARAM.sub(lambda m: f"{m.group('name')}={REDACTED}", text)
|
|
45
|
+
return _TOKEN.sub(_token_replacement, text)
|