codecop 0.1.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 (222) hide show
  1. codecop/__init__.py +7 -0
  2. codecop/access.py +140 -0
  3. codecop/access_postgres.py +284 -0
  4. codecop/advisor.py +1512 -0
  5. codecop/advisor_bench.py +493 -0
  6. codecop/advisor_ch.py +2080 -0
  7. codecop/advisor_view.py +381 -0
  8. codecop/advisors.py +184 -0
  9. codecop/agent.py +221 -0
  10. codecop/agentfacts.py +745 -0
  11. codecop/apply/__init__.py +327 -0
  12. codecop/apply/check.py +344 -0
  13. codecop/apply/cli.py +162 -0
  14. codecop/apply/clickhouse.py +379 -0
  15. codecop/apply/common.py +238 -0
  16. codecop/apply/html.py +264 -0
  17. codecop/apply/patch.py +213 -0
  18. codecop/apply/postgres.py +102 -0
  19. codecop/apply/trial.py +166 -0
  20. codecop/assemble.py +104 -0
  21. codecop/baseline.py +1043 -0
  22. codecop/bench.py +2464 -0
  23. codecop/blockers.py +935 -0
  24. codecop/budget.py +980 -0
  25. codecop/catalog_profile.py +525 -0
  26. codecop/changed.py +261 -0
  27. codecop/cicmd.py +1002 -0
  28. codecop/cli.py +5421 -0
  29. codecop/client.py +729 -0
  30. codecop/coverage.py +1067 -0
  31. codecop/coverage_reasons.py +116 -0
  32. codecop/crashlog.py +70 -0
  33. codecop/datagen.py +766 -0
  34. codecop/datagen_postgres.py +630 -0
  35. codecop/datagen_sqlite.py +323 -0
  36. codecop/dbcli.py +885 -0
  37. codecop/definitions.py +457 -0
  38. codecop/discover/__init__.py +702 -0
  39. codecop/discover/arms.py +160 -0
  40. codecop/discover/base.py +234 -0
  41. codecop/discover/dialect.py +296 -0
  42. codecop/discover/elixir.py +64 -0
  43. codecop/discover/engine_go.py +320 -0
  44. codecop/discover/go.py +1947 -0
  45. codecop/discover/java.py +1528 -0
  46. codecop/discover/loops.py +1671 -0
  47. codecop/discover/named_go.py +258 -0
  48. codecop/discover/origins.py +4565 -0
  49. codecop/discover/origins_ts.py +1584 -0
  50. codecop/discover/orm_django.py +2772 -0
  51. codecop/discover/orm_django_models.py +814 -0
  52. codecop/discover/orm_django_sql.py +662 -0
  53. codecop/discover/orm_ent.py +565 -0
  54. codecop/discover/orm_ex_ecto.py +2138 -0
  55. codecop/discover/orm_go.py +2134 -0
  56. codecop/discover/orm_go_bun.py +602 -0
  57. codecop/discover/orm_go_run.py +636 -0
  58. codecop/discover/orm_go_types.py +1082 -0
  59. codecop/discover/orm_java.py +1450 -0
  60. codecop/discover/orm_jdbi.py +743 -0
  61. codecop/discover/orm_jooq.py +806 -0
  62. codecop/discover/orm_jpa.py +1307 -0
  63. codecop/discover/orm_mybatis.py +730 -0
  64. codecop/discover/orm_py.py +557 -0
  65. codecop/discover/orm_py_peewee.py +1266 -0
  66. codecop/discover/orm_py_prisma.py +298 -0
  67. codecop/discover/orm_rb_activerecord.py +1906 -0
  68. codecop/discover/orm_rust.py +1248 -0
  69. codecop/discover/orm_rust_seaorm.py +734 -0
  70. codecop/discover/orm_sqlalchemy.py +2475 -0
  71. codecop/discover/orm_stats.py +307 -0
  72. codecop/discover/orm_tables.py +29 -0
  73. codecop/discover/orm_ts.py +503 -0
  74. codecop/discover/orm_ts_drizzle.py +697 -0
  75. codecop/discover/orm_ts_knex.py +1117 -0
  76. codecop/discover/orm_ts_kysely.py +861 -0
  77. codecop/discover/orm_ts_prisma.py +1045 -0
  78. codecop/discover/orm_ts_schema.py +169 -0
  79. codecop/discover/orm_ts_sequelize.py +1401 -0
  80. codecop/discover/orm_ts_typeorm.py +1067 -0
  81. codecop/discover/probes.py +323 -0
  82. codecop/discover/python.py +595 -0
  83. codecop/discover/ruby.py +793 -0
  84. codecop/discover/rust.py +2378 -0
  85. codecop/discover/schema.py +520 -0
  86. codecop/discover/schema_ent.py +145 -0
  87. codecop/discover/schema_ts.py +420 -0
  88. codecop/discover/tsresolve.py +257 -0
  89. codecop/discover/typescript.py +1728 -0
  90. codecop/discover/xml_mapper.py +526 -0
  91. codecop/engines/__init__.py +515 -0
  92. codecop/engines/base.py +498 -0
  93. codecop/engines/clickhouse.py +1558 -0
  94. codecop/engines/pg_ddl.py +444 -0
  95. codecop/engines/pg_hints.py +137 -0
  96. codecop/engines/postgres.py +1060 -0
  97. codecop/engines/sqlite.py +742 -0
  98. codecop/families/__init__.py +3 -0
  99. codecop/families/build.py +280 -0
  100. codecop/families/cli.py +177 -0
  101. codecop/families/coverage_hook.py +62 -0
  102. codecop/families/driver.py +221 -0
  103. codecop/families/goslice.py +229 -0
  104. codecop/families/goslice_tool/go.mod +3 -0
  105. codecop/families/goslice_tool/main.go +403 -0
  106. codecop/families/holes.py +451 -0
  107. codecop/families/images/Dockerfile.go +5 -0
  108. codecop/families/images/Dockerfile.python +4 -0
  109. codecop/families/images/Dockerfile.rust +4 -0
  110. codecop/families/isolate.py +171 -0
  111. codecop/families/locate.py +270 -0
  112. codecop/families/model.py +301 -0
  113. codecop/families/plangate.py +271 -0
  114. codecop/families/tagpatch.py +174 -0
  115. codecop/fidelity.py +671 -0
  116. codecop/fixgroups.py +130 -0
  117. codecop/formerly.py +91 -0
  118. codecop/grantscript.py +254 -0
  119. codecop/groupbench.py +1375 -0
  120. codecop/groups.py +594 -0
  121. codecop/groups_view.py +186 -0
  122. codecop/heat.py +1405 -0
  123. codecop/heatcli.py +219 -0
  124. codecop/joins.py +1749 -0
  125. codecop/joins_view.py +127 -0
  126. codecop/kinds/__init__.py +507 -0
  127. codecop/kinds/calls/__init__.py +501 -0
  128. codecop/kinds/calls/extract.py +1097 -0
  129. codecop/kinds/calls/harness.py +408 -0
  130. codecop/kinds/calls/measure.py +342 -0
  131. codecop/kinds/calls/rules.py +139 -0
  132. codecop/kinds/calls/runners/RunCalls.java +167 -0
  133. codecop/kinds/calls/runners/run_go.go +141 -0
  134. codecop/kinds/calls/runners/run_node.js +186 -0
  135. codecop/kinds/calls/runners/run_python.py +319 -0
  136. codecop/kinds/calls/runners/run_rust.rs +200 -0
  137. codecop/kinds/calls/standin.py +340 -0
  138. codecop/kinds/pipeline.py +288 -0
  139. codecop/kinds/regex/__init__.py +1167 -0
  140. codecop/kinds/regex/engines/RegexHarness.java +129 -0
  141. codecop/kinds/regex/engines/run_go.go +294 -0
  142. codecop/kinds/regex/engines/run_node.js +99 -0
  143. codecop/kinds/regex/engines/run_python.py +295 -0
  144. codecop/kinds/regex/engines/run_rust.rs +149 -0
  145. codecop/kinds/regex/extract.py +1438 -0
  146. codecop/kinds/regex/harness.py +235 -0
  147. codecop/kinds/regex/measure.py +270 -0
  148. codecop/kinds/regex/shapes.py +418 -0
  149. codecop/kinds/regex/syntax.py +1721 -0
  150. codecop/kinds/testkind.py +107 -0
  151. codecop/kinds/transaction/__init__.py +228 -0
  152. codecop/kinds/transaction/bind.py +355 -0
  153. codecop/kinds/transaction/measure.py +264 -0
  154. codecop/kinds/transaction/plan.py +462 -0
  155. codecop/kinds/transaction/rules.py +540 -0
  156. codecop/kinds/transaction/sandbox.py +94 -0
  157. codecop/kinds/transaction/scenarios.py +520 -0
  158. codecop/kinds/transaction/schedule.py +483 -0
  159. codecop/kinds/transaction/shapes.py +418 -0
  160. codecop/kinds/transaction/verify.py +293 -0
  161. codecop/live.py +237 -0
  162. codecop/loopbench.py +2071 -0
  163. codecop/loopschema.py +591 -0
  164. codecop/mcpserver.py +120 -0
  165. codecop/mechanism.py +214 -0
  166. codecop/members.py +200 -0
  167. codecop/multi.py +443 -0
  168. codecop/observed.py +1868 -0
  169. codecop/parts.py +102 -0
  170. codecop/patterns.py +830 -0
  171. codecop/patterns_view.py +559 -0
  172. codecop/plangate.py +242 -0
  173. codecop/profile.py +439 -0
  174. codecop/prompts/areas.md +19 -0
  175. codecop/prompts/observed_variants.md +20 -0
  176. codecop/prompts/profile.md +60 -0
  177. codecop/prompts/profile_postgres.md +68 -0
  178. codecop/prompts/profile_sizes.md +26 -0
  179. codecop/prompts/profile_sqlite.md +69 -0
  180. codecop/prompts/rank.md +84 -0
  181. codecop/prompts/rank_postgres.md +96 -0
  182. codecop/prompts/rank_sqlite.md +94 -0
  183. codecop/prompts/scenario_variants.md +20 -0
  184. codecop/rank.py +1473 -0
  185. codecop/realdb/__init__.py +688 -0
  186. codecop/realdb/clickhouse.py +1223 -0
  187. codecop/realdb/facts.py +815 -0
  188. codecop/realdb/locality.py +964 -0
  189. codecop/realdb/locks.py +355 -0
  190. codecop/realdb/match.py +531 -0
  191. codecop/realdb/postgres.py +643 -0
  192. codecop/realdb/ratios.py +77 -0
  193. codecop/realdb/sample.py +126 -0
  194. codecop/relations.py +227 -0
  195. codecop/report.py +1854 -0
  196. codecop/resources.py +332 -0
  197. codecop/resources_view.py +266 -0
  198. codecop/rules/entry_points.toml +1013 -0
  199. codecop/rules/sinks.toml +362 -0
  200. codecop/runsonce.py +8 -0
  201. codecop/sandboxschema.py +555 -0
  202. codecop/scenario_agent.py +172 -0
  203. codecop/scenario_bind.py +507 -0
  204. codecop/scenario_sql.py +971 -0
  205. codecop/scenarios.py +675 -0
  206. codecop/scenarios_view.py +274 -0
  207. codecop/schemacli.py +67 -0
  208. codecop/schemas/areas_output.schema.json +21 -0
  209. codecop/schemas/profile_output.schema.json +362 -0
  210. codecop/schemas/rank_output.schema.json +385 -0
  211. codecop/sizes.py +200 -0
  212. codecop/sqlinfo.py +558 -0
  213. codecop/typedparams.py +576 -0
  214. codecop/verdicts.py +212 -0
  215. codecop/writebench.py +720 -0
  216. codecop/writecost.py +440 -0
  217. codecop/writes.py +1208 -0
  218. codecop-0.1.0.dist-info/METADATA +42 -0
  219. codecop-0.1.0.dist-info/RECORD +222 -0
  220. codecop-0.1.0.dist-info/WHEEL +4 -0
  221. codecop-0.1.0.dist-info/entry_points.txt +2 -0
  222. codecop-0.1.0.dist-info/licenses/LICENSE +21 -0
codecop/cicmd.py ADDED
@@ -0,0 +1,1002 @@
1
+ """`codecop ci`: what a CI job needs after `codecop scan`.
2
+
3
+ codecop ci compare the scan in the out dir against the base branch's latest run on the console:
4
+ which findings are new, which queries read more than before. Writes the
5
+ pull-request comment and sets the exit code from --fail-on.
6
+ codecop ci comment post that comment on the pull request, or update the one posted before.
7
+
8
+ Credentials come from the environment and are never printed: CODECOP_TOKEN (an organisation token with
9
+ `runs:read`) for the console, GITHUB_TOKEN for the comment.
10
+
11
+ Exit codes: 0 nothing over the threshold (or `--fail-on never`), 1 the command itself failed
12
+ (no findings to read, console or GitHub unreachable), 2 wrong usage, 3 the threshold was crossed.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import os
19
+ import re
20
+ import subprocess
21
+ import urllib.error
22
+ import urllib.parse
23
+ import urllib.request
24
+ from pathlib import Path
25
+ from typing import Optional
26
+
27
+ import typer
28
+ from rich.console import Console
29
+
30
+ from . import __version__, fixgroups
31
+
32
+ ci_app = typer.Typer(add_completion=False, no_args_is_help=True,
33
+ help="For CI: compare a scan with the base branch, and keep one pull-request comment up to date.")
34
+ out = Console()
35
+ err = Console(stderr=True)
36
+
37
+ MARKER = "<!-- codecop-scan -->"
38
+ EXIT_THRESHOLD = 3
39
+ SEVERITIES = ("low", "medium", "high", "critical")
40
+ FAIL_ON = ("never", "new", "worse", "any") + SEVERITIES
41
+ WORSE_RATIO = 1.15 # the benchmark's own rule: reading more than 115% of before is worse
42
+ MAX_COMMENT_CHARS = 60000 # GitHub refuses a comment body over 65,536 characters
43
+ MAX_ROWS = 25 # findings listed per table; the rest are counted
44
+
45
+
46
+ # ---- reading the scan -------------------------------------------------------------------
47
+
48
+ def head_runs(out_dir: Path) -> list[dict]:
49
+ """The engine runs an out dir holds: one for a single-engine scan, one per engine directory otherwise."""
50
+ dirs = [out_dir]
51
+ index = out_dir / "engines.json"
52
+ if index.exists():
53
+ dirs = [out_dir / e["dir"] for e in json.loads(index.read_text()).get("engines") or []]
54
+ runs = []
55
+ for d in dirs:
56
+ path = d / "findings.json"
57
+ if not path.exists():
58
+ continue
59
+ data = json.loads(path.read_text())
60
+ runs.append({"engine": data.get("engine") or "", "dir": d, "findings": data})
61
+ return runs
62
+
63
+
64
+ def _num(value) -> float | None:
65
+ return float(value) if isinstance(value, (int, float)) and not isinstance(value, bool) else None
66
+
67
+
68
+ def _cost(finding: dict) -> dict | None:
69
+ """What the query read in the sandbox before any fix: rows, bytes, and the size of the table it ran on."""
70
+ scan = finding.get("scan") if isinstance(finding.get("scan"), dict) else None
71
+ if not scan or _num(scan.get("read_rows")) is None:
72
+ return None
73
+ return {"read_rows": _num(scan.get("read_rows")), "read_bytes": _num(scan.get("read_bytes")),
74
+ "table_rows": _num(scan.get("table_rows"))}
75
+
76
+
77
+ def _row(f: dict, engine: str) -> dict:
78
+ site = f.get("site") or {}
79
+ fix = fixgroups.fix_of(f, engine)
80
+ return {"finding": f.get("finding", ""), "id": f.get("id", ""), "title": f.get("title", ""), "severity": f.get("severity", ""),
81
+ "status": f.get("status", ""), "summary": f.get("summary", ""), "engine": engine,
82
+ "file": site.get("file", ""), "line": site.get("line"), "symbol": site.get("symbol", ""),
83
+ # the fix it shares with other findings, if any (fixgroups.py); only a proven finding is a verified fix (a
84
+ # trade-off, or reads verified with the insert side not measured, is not)
85
+ "fix": {k: fix[k] for k in ("key", "label", "text")} if fix else None, "trade_off": fixgroups.is_trade_off(f),
86
+ "proof": fixgroups.proof_state(f)}
87
+
88
+
89
+ def compare(head: list[dict], base: list[dict] | None, engine: str = "", scope_ids: set[str] | None = None,
90
+ tables_changed: set[str] | None = None) -> dict:
91
+ """New findings and queries that got worse, for one engine. Findings are matched by `id`: the call site's
92
+ fingerprint (its SQL, file and function), which does not move when lines above it do.
93
+
94
+ `base` None: there is nothing to compare with, so nothing is called new or worse.
95
+ A query "got worse" when both runs benchmarked it and it now reads more than WORSE_RATIO times what it read
96
+ on the base, in rows or in bytes. The two sandboxes may have built the table at different sizes, so when
97
+ both know the table's size the comparison is of the share of the table read.
98
+ `tables_changed` (a --changed-since scan: the tables whose definition the change touched): a query whose SQL is the
99
+ same, on tables the change did not touch, measured on tables built at another size, is not called worse. Nothing in
100
+ the change can make it read more; the share of a small table read does not scale (ClickHouse reads whole granules)."""
101
+ touched = {str(t).replace('"', "").split(".")[-1].lower() for t in tables_changed or ()}
102
+ result = {"engine": engine, "compared": base is not None, "new": [], "worse": [], "gone": [], "unchanged": 0}
103
+ if base is None:
104
+ return result
105
+ before = {f.get("id"): f for f in base if f.get("id")}
106
+ head_ids = {f.get("id") for f in head}
107
+
108
+ def place(f: dict) -> tuple:
109
+ site = f.get("site") or {}
110
+ return (site.get("file"), site.get("symbol"))
111
+
112
+ # A query edited in place has a new fingerprint. When exactly one base finding and one head finding that match
113
+ # nothing by id sit in the same function of the same file, they are the same query, changed: compared, not "new".
114
+ loose_base: dict[tuple, list[dict]] = {}
115
+ for fid, f in before.items():
116
+ if fid not in head_ids and all(place(f)):
117
+ loose_base.setdefault(place(f), []).append(f)
118
+ loose_head: dict[tuple, int] = {}
119
+ for f in head:
120
+ if f.get("id") not in before and all(place(f)):
121
+ loose_head[place(f)] = loose_head.get(place(f), 0) + 1
122
+ seen = set()
123
+ for f in head:
124
+ fid = f.get("id")
125
+ seen.add(fid)
126
+ old = before.get(fid)
127
+ edited = False
128
+ if old is None and loose_head.get(place(f)) == 1 and len(loose_base.get(place(f), [])) == 1:
129
+ old, edited = loose_base[place(f)][0], True
130
+ seen.add(old.get("id"))
131
+ if old is None:
132
+ result["new"].append(_row(f, engine))
133
+ continue
134
+ now_cost, old_cost = _cost(f), _cost(old)
135
+ ratio, metric = None, ""
136
+ resized = bool(now_cost and old_cost and now_cost["table_rows"] and old_cost["table_rows"]
137
+ and now_cost["table_rows"] != old_cost["table_rows"])
138
+ if tables_changed is not None and not edited and resized \
139
+ and not touched & {str(t).replace('"', "").split(".")[-1].lower() for t in f.get("tables") or []}:
140
+ result["unchanged"] += 1
141
+ continue
142
+ if now_cost and old_cost:
143
+ scale = 1.0
144
+ if now_cost["table_rows"] and old_cost["table_rows"]:
145
+ scale = old_cost["table_rows"] / now_cost["table_rows"] # bring today's reads to the base's table size
146
+ for name in ("read_rows", "read_bytes"):
147
+ a, b = now_cost[name], old_cost[name]
148
+ if a is None or not b:
149
+ continue
150
+ r = a * scale / b
151
+ if ratio is None or r > ratio:
152
+ ratio, metric = r, name
153
+ if ratio is not None and ratio > WORSE_RATIO:
154
+ result["worse"].append({**_row(f, engine), "metric": metric, "ratio": round(ratio, 3), "before": old_cost, "after": now_cost,
155
+ "query_edited": edited})
156
+ else:
157
+ result["unchanged"] += 1
158
+ # A base finding the scan could have reported again and did not. In a --changed-since scan only the
159
+ # call sites in scope count: the rest were not looked at.
160
+ for fid, f in before.items():
161
+ if fid not in seen and (scope_ids is None or fid in scope_ids):
162
+ result["gone"].append(_row(f, engine))
163
+ return result
164
+
165
+
166
+ def threshold(results: list[dict], fail_on: str) -> list[str]:
167
+ """Why the threshold was crossed, as short reasons; empty when it was not."""
168
+ new = [f for r in results for f in r["new"]]
169
+ worse = [f for r in results for f in r["worse"]]
170
+ reasons = []
171
+ if fail_on in ("new", "any") and new:
172
+ reasons.append(f"{len(new)} new finding{'s' if len(new) != 1 else ''}")
173
+ if fail_on in ("worse", "any") and worse:
174
+ reasons.append(f"{len(worse)} quer{'ies' if len(worse) != 1 else 'y'} got worse")
175
+ if fail_on in SEVERITIES:
176
+ level = SEVERITIES.index(fail_on)
177
+ hits = [f for f in new + worse if f["severity"] in SEVERITIES and SEVERITIES.index(f["severity"]) >= level]
178
+ if hits:
179
+ reasons.append(f"{len(hits)} new or worse at severity {fail_on} or above")
180
+ return reasons
181
+
182
+
183
+ # ---- the base branch's latest run, from the console ---------------------------------------
184
+
185
+ def _runs(client, org: str, project: str, engine: str, branch: str | None):
186
+ """Completed runs with their bundle, of this project and engine, newest first (`branch` None: any branch)."""
187
+ cursor = ""
188
+ for _ in range(20):
189
+ query = {"engine": engine, "state": "completed", "limit": "100"}
190
+ if branch is not None:
191
+ query["branch"] = branch
192
+ if cursor:
193
+ query["cursor"] = cursor
194
+ page = client.request("GET", f"/api/v1/orgs/{urllib.parse.quote(org)}/runs?{urllib.parse.urlencode(query)}", timeout=30)
195
+ for run in page.get("data") or []:
196
+ if (run.get("project") or {}).get("name") == project and run.get("bundle_received_at"):
197
+ yield run
198
+ cursor = page.get("next_cursor") or ""
199
+ if not cursor:
200
+ break
201
+
202
+
203
+ def base_ref_of(root: Path | None, branch: str) -> str | None:
204
+ """The local ref that holds the base branch: `origin/<branch>` (a CI or hosted checkout), else `<branch>`."""
205
+ if root is None:
206
+ return None
207
+ from . import changed
208
+ for ref in (f"origin/{branch}", branch):
209
+ try:
210
+ changed._git(root, "rev-parse", "--verify", "--quiet", f"{ref}^{{commit}}")
211
+ return ref
212
+ except changed.ChangedError:
213
+ continue
214
+ return None
215
+
216
+
217
+ def on_branch(root: Path, commit: str, ref: str) -> bool:
218
+ """Whether `commit` is in the history of `ref` (git merge-base --is-ancestor)."""
219
+ try:
220
+ proc = subprocess.run(["git", "-C", str(root), "merge-base", "--is-ancestor", commit, ref], capture_output=True)
221
+ except OSError:
222
+ return False
223
+ return proc.returncode == 0
224
+
225
+
226
+ def base_run(client, org: str, project: str, branch: str, engine: str, root: Path | None = None) -> dict | None:
227
+ """The run a pull request is compared with, for this project and engine. Needs `runs:read`. The rule, in order:
228
+
229
+ 1. `branch`: the newest completed run the CLI recorded on the base branch;
230
+ 2. `commit_on_base`: else the newest completed run, of any recorded branch, whose commit is in the base branch's
231
+ history in this checkout (`origin/<branch>`, else `<branch>`). A scan of a detached checkout (a hosted runner,
232
+ CI checking out a commit) records its branch as `HEAD`, but its commit says where it was taken.
233
+
234
+ The run comes back with `base_rule` naming which rule found it. None when neither finds one: nothing is called new."""
235
+ for run in _runs(client, org, project, engine, branch):
236
+ return {**run, "base_rule": "branch"}
237
+ ref = base_ref_of(root, branch)
238
+ if ref is None:
239
+ return None
240
+ for run in _runs(client, org, project, engine, None):
241
+ commit = str(run.get("commit") or "")
242
+ if commit and on_branch(root, commit, ref):
243
+ return {**run, "base_rule": "commit_on_base"}
244
+ return None
245
+
246
+
247
+ def org_of(client, org: str | None) -> str:
248
+ if org:
249
+ return org
250
+ me = client.me()
251
+ slug = (me.get("token") or {}).get("org")
252
+ if slug:
253
+ return slug
254
+ orgs = me.get("orgs") or []
255
+ if len(orgs) == 1:
256
+ return orgs[0]["slug"]
257
+ raise typer.BadParameter("this token belongs to more than one organisation: pass --org")
258
+
259
+
260
+ # ---- the comment --------------------------------------------------------------------------
261
+
262
+ def _human(n: float | None) -> str:
263
+ if n is None:
264
+ return "?"
265
+ for unit, size in (("B", 1e9), ("M", 1e6), ("K", 1e3)):
266
+ if abs(n) >= size:
267
+ return f"{n / size:.1f}{unit}"
268
+ return f"{n:.0f}"
269
+
270
+
271
+ def _cell(text) -> str:
272
+ return str(text if text is not None else "").replace("|", "\\|").replace("\n", " ").replace("\r", " ").strip()
273
+
274
+
275
+ def _code(text) -> str:
276
+ return "`" + str(text).replace("`", "'") + "`" if text else ""
277
+
278
+
279
+ def _where(f: dict) -> str:
280
+ place = _code(f"{f['file']}:{f['line']}" if f.get("line") else f["file"])
281
+ return _cell(place + (f" {_code(f['symbol'])}" if f.get("symbol") else ""))
282
+
283
+
284
+ def _reads(c: dict) -> str:
285
+ rows = f"{_human(c['read_rows'])} rows"
286
+ if c.get("table_rows"):
287
+ share = 100 * c["read_rows"] / c["table_rows"]
288
+ rows += f" of {_human(c['table_rows'])} ({share:.0f}%)" if share >= 10 else f" of {_human(c['table_rows'])} ({share:.1f}%)"
289
+ return rows + (f", {_human(c['read_bytes'])} bytes" if c.get("read_bytes") is not None else "")
290
+
291
+
292
+ STATUS_WORDS = {"verified": "Verified win", "unverified": "Unverified", "no_change": "No change", "rejected": "Rejected",
293
+ "failed": "Not benchmarked"}
294
+
295
+
296
+ def _fix_groups(results: list[dict]) -> dict[str, dict]:
297
+ """The verified fixes of the new or worse findings: findings that share one fix (fixgroups.py) are one, with the call
298
+ sites it was verified at. Only a proven finding (`fixgroups.proof_state`) is a verified fix; a compare.json written
299
+ before `proof` existed falls back to verified and not a trade-off."""
300
+ groups: dict[str, dict] = {}
301
+ for r in results:
302
+ for f in r["new"] + r["worse"]:
303
+ if f.get("proof", "proven" if f.get("status") == "verified" and not f.get("trade_off") else "") != "proven":
304
+ continue
305
+ fix = f.get("fix") or {}
306
+ g = groups.setdefault(fix.get("key") or f"#{r.get('engine')}#{f.get('id') or f.get('finding')}",
307
+ {"label": fix.get("label") or "", "text": fix.get("text") or "", "sites": []})
308
+ where = (f.get("file"), f.get("line")) if f.get("file") else ("#", f.get("id") or f.get("finding"))
309
+ if where not in g["sites"]:
310
+ g["sites"].append(where)
311
+ return groups
312
+
313
+
314
+ def verified_fixes(results: list[dict]) -> int:
315
+ """New or worse findings' fixes the sandbox verified in this scan, findings that share one fix counted once: the only
316
+ ones called a win."""
317
+ return len(_fix_groups(results))
318
+
319
+
320
+ def verified_sites(results: list[dict]) -> int:
321
+ """The call sites those fixes were verified at, one by one."""
322
+ return len({s for g in _fix_groups(results).values() for s in g["sites"]})
323
+
324
+
325
+ def headline(results: list[dict]) -> str:
326
+ """The comment's heading, counts first: `### CodeCop · 2 new · 1 worse · 1 verified fix · 2 call sites`, or
327
+ `· No new findings`."""
328
+ new = sum(len(r["new"]) for r in results)
329
+ worse = sum(len(r["worse"]) for r in results)
330
+ fixes = verified_fixes(results)
331
+ parts = ([f"{new} new"] if new else []) + ([f"{worse} worse"] if worse else [])
332
+ if not parts:
333
+ parts = ["No new findings"]
334
+ if fixes:
335
+ sites = verified_sites(results)
336
+ parts.append(f"{fixes} verified fix{'es' if fixes != 1 else ''} · {sites} call site{'s' if sites != 1 else ''}")
337
+ return "### CodeCop · " + " · ".join(parts)
338
+
339
+
340
+ def context_line(head_commit: str, base_branch: str, behind: dict | None, scope: dict | None, agent: dict) -> str:
341
+ """`a1b2c3d` vs `main` scan of `9f8e7d6` (3 commits behind) · 14 call sites in scope of 212 · est. cost $1.84"""
342
+ bits = []
343
+ against = f"`{base_branch}`"
344
+ if behind and behind.get("commit"):
345
+ against += f" scan of {_code(str(behind['commit'])[:7])}"
346
+ n, ahead = behind.get("commits"), behind.get("ahead")
347
+ if isinstance(n, int) and n > 0:
348
+ against += f" ({n} commit{'s' if n != 1 else ''} behind)"
349
+ elif isinstance(ahead, int) and ahead > 0:
350
+ against += f" ({ahead} commit{'s' if ahead != 1 else ''} past the branch point)"
351
+ elif n == 0:
352
+ against += " (at the branch point)"
353
+ bits.append((f"{_code(head_commit[:7])} vs " if head_commit else "vs ") + against)
354
+ if scope:
355
+ bits.append(f"{scope.get('sites', 0):,} call sites in scope of {scope.get('sites_total', 0):,}")
356
+ if agent.get("no_agent"):
357
+ n = (scope or {}).get("sites")
358
+ bits.append("Free look: rules and advisor" + (f", {n:,} call site{'s' if n != 1 else ''} not judged by the agent" if n else ", no agent"))
359
+ elif agent.get("cost_usd") is not None:
360
+ billed = agent.get("billing") == "api_key" and agent.get("key_of") != "codecop"
361
+ bits.append(("cost" if billed else "est. cost") + f" ${agent['cost_usd']:.2f}")
362
+ return " · ".join(bits)
363
+
364
+
365
+ def render(results: list[dict], *, base_branch: str, bases: dict[str, dict | None], scope: dict | None, agent: dict,
366
+ fail_on: str, reasons: list[str], project: str, head_commit: str = "", behind: dict | None = None) -> str:
367
+ """The pull-request comment. Its first line is the marker `codecop ci comment` finds it again by; the second the counts
368
+ (new, worse, verified fixes), the third what was compared with what. `behind`: {commit, commits} of the base run."""
369
+ new = [f for r in results for f in r["new"]]
370
+ worse = [f for r in results for f in r["worse"]]
371
+ gone = [f for r in results for f in r["gone"]]
372
+ compared = [r for r in results if r["compared"]]
373
+ several = len(results) > 1
374
+ lines = [MARKER]
375
+ if not compared:
376
+ total = sum(r.get("head_findings", 0) for r in results)
377
+ lines.append(f"### CodeCop · no run of `{base_branch}` to compare with")
378
+ lines.append(context_line(head_commit, base_branch, None, scope, agent))
379
+ lines.append(f"The console has no completed run of `{base_branch}` for `{project}` yet, so nothing can be called new. "
380
+ f"This scan reported {total} finding{'s' if total != 1 else ''}. A scheduled scan of `{base_branch}` creates the base.")
381
+ else:
382
+ lines.append(headline(results))
383
+ lines.append(context_line(head_commit, base_branch, behind, scope, agent))
384
+ against = []
385
+ for r in compared:
386
+ run = bases.get(r["engine"]) or {}
387
+ link = (run.get("links") or {}).get("console")
388
+ name = f"[{run.get('id', 'a local scan')}]({link})" if link else _code(run.get("id") or "a local scan")
389
+ against.append(f"{name}{' (' + r['engine'] + ')' if several and r['engine'] else ''}"
390
+ + (f" at {_code(str(run.get('commit'))[:10])}" if run.get("commit") else ""))
391
+ lines.append(f"Compared with the latest run of `{base_branch}`: {', '.join(against)}.")
392
+ missing = [r["engine"] for r in results if not r["compared"]]
393
+ if missing:
394
+ lines.append(f"No run of `{base_branch}` for {', '.join(missing)}: not compared.")
395
+ if scope:
396
+ by = scope.get("by_reason") or {}
397
+ tables = scope.get("tables_changed") or []
398
+ lines.append(f"Scanned what this change touches: {scope.get('sites', 0):,} of {scope.get('sites_total', 0):,} call sites "
399
+ f"({by.get('changed_file', 0):,} in {scope.get('files_changed', 0):,} changed files, "
400
+ f"{by.get('reached_from_changed_code', 0):,} reached from {scope.get('functions_changed', 0):,} changed functions"
401
+ + (f", {by.get('table_definition_changed', 0):,} reading {len(tables):,} table{'s' if len(tables) != 1 else ''} "
402
+ f"whose definition changed" if tables else "")
403
+ + "). The rest of the repository was not ranked.")
404
+ if new:
405
+ lines += ["", "#### New findings", "", "| Finding | Severity | Where | What | Sandbox result |", "|---|---|---|---|---|"]
406
+ for f in new[:MAX_ROWS]:
407
+ verdict = STATUS_WORDS.get(f["status"], f["status"]) + (f": {f['summary'][:110]}" if f.get("summary") else "")
408
+ label = f["finding"] + (f" ({f['engine']})" if several and f["engine"] else "")
409
+ lines.append(f"| {_cell(label)} | {_cell(f['severity'])} | {_where(f)} | {_cell(f['title'])} | {_cell(verdict)} |")
410
+ if len(new) > MAX_ROWS:
411
+ lines.append(f"\nand {len(new) - MAX_ROWS} more.")
412
+ shared = sorted((g for g in _fix_groups(results).values() if len(g["sites"]) > 1), key=lambda g: -len(g["sites"]))
413
+ if shared:
414
+ lines += ["", "#### One fix, several call sites", "", "| Fix | Verified at |", "|---|---|"]
415
+ for g in shared[:MAX_ROWS]:
416
+ at = ", ".join(_code(f"{file}:{line}" if line else str(file)) for file, line in g["sites"][:8] if file != "#")
417
+ more = len(g["sites"]) - min(len(g["sites"]), 8)
418
+ lines.append(f"| {_cell(g['label'])}: {_cell(_code(g['text'][:160]))} | {len(g['sites'])} call sites: {_cell(at)}"
419
+ + (f" and {more} more" if more else "") + " |")
420
+ if worse:
421
+ lines += ["", f"#### Queries that read more than on `{base_branch}`", "",
422
+ f"| Finding | Severity | Where | On `{base_branch}` | Now | |", "|---|---|---|---|---|---|"]
423
+ for f in worse[:MAX_ROWS]:
424
+ label = f["finding"] + (f" ({f['engine']})" if several and f["engine"] else "")
425
+ lines.append(f"| {_cell(label)} | {_cell(f['severity'])} | {_where(f)} | {_cell(_reads(f['before']))} | "
426
+ f"{_cell(_reads(f['after']))} | {f['ratio']:.1f}x {'rows' if f['metric'] == 'read_rows' else 'bytes'}"
427
+ f"{', query edited' if f.get('query_edited') else ''} |")
428
+ if len(worse) > MAX_ROWS:
429
+ lines.append(f"\nand {len(worse) - MAX_ROWS} more.")
430
+ if gone:
431
+ lines += ["", f"<details><summary>No longer reported: {len(gone)}</summary>", ""]
432
+ lines += [f"- {_cell(f['finding'])} {_where(f)} {_cell(f['title'])}" for f in gone[:MAX_ROWS]]
433
+ lines += ["", "Not reported again means fixed, or not picked by this run's agent.", "</details>"]
434
+ lines += _not_asked_lines(agent)
435
+ lines.append("")
436
+ notes = ["Sandbox figures are measured on generated data: they compare runs, they are not production numbers."]
437
+ if agent.get("cost_usd") is not None:
438
+ amount = f"${agent['cost_usd']:.2f}"
439
+ key_of = agent.get("key_of") or ""
440
+ if agent.get("billing") == "api_key" and key_of == "codecop":
441
+ notes.append(f"Agent est. cost {amount} at API rates.") # CodeCop's own key paid: nothing billed to you
442
+ elif agent.get("billing") == "api_key":
443
+ notes.append(f"Agent cost {amount}, billed to {key_of or 'the API key'}.")
444
+ else:
445
+ notes.append(f"Agent est. cost {amount} at API rates (not billed per token).")
446
+ if fail_on != "never":
447
+ notes.append(f"`--fail-on {fail_on}`: " + ("**failed** (" + "; ".join(reasons) + ")." if reasons else "passed."))
448
+ if head_commit:
449
+ notes.append(f"Commit {_code(head_commit[:10])}.")
450
+ lines.append("<sub>" + " ".join(notes) + "</sub>")
451
+ body = "\n".join(lines) + "\n"
452
+ if len(body) > MAX_COMMENT_CHARS:
453
+ body = body[:MAX_COMMENT_CHARS] + "\n\n(cut: the comment was too long)\n"
454
+ return body
455
+
456
+
457
+ # a hosted job's billing source -> whose key paid ("qopt" is the stored code of CodeCop's own key)
458
+ KEY_OF = {"org": "your API key", "runner_key": "the runner's API key", "qopt": "codecop", "codecop": "codecop"}
459
+
460
+
461
+ def _agent(runs: list[dict]) -> dict:
462
+ """Agent cost over every engine run, and how it was paid: `api_key` only when every run was. With the run budget's
463
+ summary (findings.json `agent_budget`): the spend of the whole run and what it did not ask, by kind, with its estimate."""
464
+ budgets = [r["findings"].get("agent_budget") for r in runs if isinstance(r["findings"].get("agent_budget"), dict)]
465
+ costs = [(r["findings"].get("agent") or {}).get("cost_usd") for r in runs]
466
+ costs = [c for c in costs if isinstance(c, (int, float))]
467
+ if budgets:
468
+ costs = [float(b.get("spent_usd") or 0) for b in budgets]
469
+ modes = {(r["findings"].get("agent_budget") or {}).get("billing") or r["findings"].get("billing") or "" for r in runs}
470
+ out = {"cost_usd": round(sum(costs), 4) if costs else None, "billing": "api_key" if modes == {"api_key"} else "plan" if modes == {"plan"} else ""}
471
+ if out["billing"] == "api_key":
472
+ # on a hosted runner the agent CLI sees a placeholder key; whose key the gateway puts on the calls is the job's
473
+ # billing source (CODECOP_BILLING_SOURCE): the organisation's, the runner's, or CodeCop's own
474
+ key_of = KEY_OF.get(os.environ.get("CODECOP_BILLING_SOURCE", "").strip(), "")
475
+ if key_of:
476
+ out["key_of"] = key_of
477
+ if budgets:
478
+ by_kind: dict[str, dict] = {}
479
+ limited = 0
480
+ for b in budgets:
481
+ na = b.get("not_asked") or {}
482
+ limited += int((na.get("usage_limit") or {}).get("items") or 0)
483
+ for k, v in (na.get("by_kind") or {}).items():
484
+ t = by_kind.setdefault(k, {"items": 0, "est_low_usd": 0.0, "est_high_usd": 0.0})
485
+ t["items"] += int(v.get("items") or 0)
486
+ t["est_low_usd"] = round(t["est_low_usd"] + float(v.get("est_low_usd") or 0), 2)
487
+ t["est_high_usd"] = round(t["est_high_usd"] + float(v.get("est_high_usd") or 0), 2)
488
+ out["budget_usd"] = budgets[0].get("budget_usd")
489
+ out["not_asked"] = by_kind
490
+ out["not_asked_limit"] = limited
491
+ out["verified_fixes"] = sum(int(b.get("verified_fixes") or 0) for b in budgets)
492
+ if all(b.get("no_agent") for b in budgets):
493
+ out["no_agent"] = True
494
+ return out
495
+
496
+
497
+ NOT_ASKED_WORDS = {"statement": "statements", "observed_variant": "observed statements' variants", "scenario_variant": "scenario variants",
498
+ "loop": "loop members", "group": "scan groups", "table_profile": "table sizes", "areas": "code areas"}
499
+
500
+
501
+ def _not_asked_lines(agent: dict) -> list[str]:
502
+ """What the run did not ask the agent, by kind, with its estimate and the command that asks it."""
503
+ na = agent.get("not_asked") or {}
504
+ if not na:
505
+ return []
506
+ items = sum(v["items"] for v in na.values())
507
+ lo, hi = sum(v["est_low_usd"] for v in na.values()), sum(v["est_high_usd"] for v in na.values())
508
+ lines = ["", f"<details><summary>Not asked yet: {items:,} item{'s' if items != 1 else ''} · est. ${lo:,.2f}–{hi:,.2f}</summary>", "",
509
+ "| What | Items | Estimate |", "|---|---|---|"]
510
+ for k, v in sorted(na.items(), key=lambda kv: -kv[1]["est_high_usd"]):
511
+ lines.append(f"| {_cell(NOT_ASKED_WORDS.get(k, k))} | {v['items']:,} | est. ${v['est_low_usd']:,.2f}–{v['est_high_usd']:,.2f} |")
512
+ if agent.get("not_asked_limit"):
513
+ lines.append(f"\n{agent['not_asked_limit']:,} of them were not asked because the agent's usage limit was reached, not the budget.")
514
+ lines += ["", "A larger `budget` (or `pr-budget`) for this job asks them; answers already given are never paid for again.", "</details>"]
515
+ return lines
516
+
517
+
518
+ def behind_of(root: Path, bases: dict[str, dict | None], scope: dict | None) -> dict | None:
519
+ """{commit, commits, ahead, rule, run}: the base run's commit; how many commits it is behind the merge base of this
520
+ change (`commits`) and how many base-branch commits past it (`ahead`: the base moved on after the branch was made);
521
+ the rule that chose it (`branch`, `commit_on_base`, or `local` for --base-out). Counts are None when git cannot tell
522
+ (the commit was never fetched, or the scan was not a --changed-since scan)."""
523
+ from . import changed
524
+ run = next((b for b in bases.values() if b and b.get("commit")), None)
525
+ if run is None:
526
+ return None
527
+ commit = str(run.get("commit"))
528
+ merge_base = (scope or {}).get("base") or ""
529
+ behind = ahead = None
530
+ if merge_base:
531
+ try:
532
+ behind = int(changed._git(root, "rev-list", "--count", f"{commit}..{merge_base}").strip())
533
+ ahead = int(changed._git(root, "rev-list", "--count", f"{merge_base}..{commit}").strip())
534
+ except (changed.ChangedError, ValueError):
535
+ behind = ahead = None
536
+ return {"commit": commit, "commits": behind, "ahead": ahead, "rule": run.get("base_rule") or "local", "run": run.get("id")}
537
+
538
+
539
+ @ci_app.command("compare")
540
+ def compare_cmd(
541
+ path: Path = typer.Argument(Path("."), help="Repository that was scanned."),
542
+ out_dir: Optional[Path] = typer.Option(None, "--out", help="Directory holding the scan. Default: <path>/.codecop"),
543
+ base_branch: str = typer.Option("main", "--base-branch", help="The branch to compare with: its latest completed run on the console."),
544
+ base_out: Optional[Path] = typer.Option(None, "--base-out", help="Compare with a scan in a local out dir instead of asking the console."),
545
+ server: Optional[str] = typer.Option(None, "--server", help="Console URL. Default: CODECOP_SERVER or the saved one."),
546
+ org: Optional[str] = typer.Option(None, "--org", help="Organisation slug. Default: the token's organisation."),
547
+ project: Optional[str] = typer.Option(None, "--project", help="Project name on the console. Default: the repository's directory name."),
548
+ fail_on: str = typer.Option("never", "--fail-on", help="Exit 3 when: `new` a finding is new; `worse` a query reads more than on the base; "
549
+ "`any` either; `low`, `medium`, `high`, `critical` a new or worse finding has that severity or above. "
550
+ "`never` only reports."),
551
+ markdown: Optional[Path] = typer.Option(None, "--markdown", help="Write the pull-request comment to this file."),
552
+ json_out: Optional[Path] = typer.Option(None, "--json", help="Write the comparison as JSON to this file."),
553
+ quiet: bool = typer.Option(False, "--quiet", help="Do not print the comment to stdout."),
554
+ ) -> None:
555
+ """Compare the scan in the out dir with the base branch: new findings, and queries whose cost got worse."""
556
+ from . import changed
557
+ from . import client as api
558
+ from . import coverage as coverage_mod
559
+
560
+ if fail_on not in FAIL_ON:
561
+ err.print(f"[red]--fail-on must be one of {', '.join(FAIL_ON)}.[/red]")
562
+ raise typer.Exit(2)
563
+ root = path.resolve()
564
+ scan_dir = out_dir or (root / ".codecop")
565
+ runs = head_runs(scan_dir)
566
+ if not runs:
567
+ err.print(f"[red]No findings.json in {scan_dir}.[/red] Run `codecop scan` first; a scan that stopped early has nothing to compare.")
568
+ raise typer.Exit(1)
569
+ name = project or (runs[0]["findings"].get("repo") or {}).get("name") or root.name
570
+ scope = changed.scope_of(scan_dir)
571
+ scope_ids = set(scope["site_ids"]) if scope else None
572
+
573
+ bases: dict[str, dict | None] = {}
574
+ base_findings: dict[str, list | None] = {}
575
+ base_share = None # the base's judged share of the query and write sites (coverage.repository), for the comment's coverage line
576
+ if base_out is not None:
577
+ local = {r["engine"]: r for r in head_runs(base_out)}
578
+ for r in runs:
579
+ found = local.get(r["engine"])
580
+ bases[r["engine"]] = {"id": str(base_out), "commit": (found["findings"].get("repo") or {}).get("commit", "")} if found else None
581
+ base_findings[r["engine"]] = found["findings"].get("findings") or [] if found else None
582
+ base_cov = coverage_mod.from_out_dir(base_out)
583
+ base_share = base_cov["judged_share"] if base_cov else None
584
+ else:
585
+ url = api.server_url(server)
586
+ token = api.load_token(url)
587
+ if not token:
588
+ err.print("[red]No console token.[/red] Set CODECOP_TOKEN to an organisation token with the `runs:read` scope.")
589
+ raise typer.Exit(1)
590
+ c = api.Client(url, token)
591
+ try:
592
+ slug = org_of(c, org or api.org_setting(api.load_settings()))
593
+ for r in runs:
594
+ run = base_run(c, slug, name, base_branch, r["engine"], root)
595
+ bases[r["engine"]] = run
596
+ base_findings[r["engine"]] = None
597
+ if run is not None:
598
+ bundle = c.request("GET", f"/api/v1/orgs/{urllib.parse.quote(slug)}/runs/{urllib.parse.quote(run['id'])}/bundle", timeout=300)
599
+ base_findings[r["engine"]] = ((bundle or {}).get("findings") or {}).get("findings") or []
600
+ base_share = base_share if base_share is not None else \
601
+ (((bundle or {}).get("coverage") or {}).get("repository") or {}).get("judged_share")
602
+ except api.ApiError as e:
603
+ hint = " The token needs the `runs:read` scope." if e.status == 403 else ""
604
+ err.print(f"[red]Could not read the base run from {url}:[/red] {e}.{hint}")
605
+ raise typer.Exit(1)
606
+
607
+ results = []
608
+ for r in runs:
609
+ res = compare(r["findings"].get("findings") or [], base_findings[r["engine"]], r["engine"], scope_ids,
610
+ set(scope.get("tables_changed") or ()) if scope else None)
611
+ res["head_findings"] = len(r["findings"].get("findings") or [])
612
+ res["base_run"] = (bases[r["engine"]] or {}).get("id")
613
+ results.append(res)
614
+ reasons = threshold(results, fail_on)
615
+ head_commit = (runs[0]["findings"].get("repo") or {}).get("commit", "")
616
+ behind = behind_of(root, bases, scope)
617
+ body = render(results, base_branch=base_branch, bases=bases, scope=scope, agent=_agent(runs), fail_on=fail_on, reasons=reasons,
618
+ project=name, head_commit=head_commit, behind=behind)
619
+ head_cov = coverage_mod.from_out_dir(scan_dir)
620
+ if head_cov:
621
+ # a scan scoped to the change judges only what it touches: its share is not comparable with the base's full scan,
622
+ # so no "-25.0" on a pull request that changed no query
623
+ comparable = base_share is not None and not scope
624
+ body = coverage_line(body, coverage_mod.one_line(head_cov, {"judged_share": base_share} if comparable else None))
625
+ summary = {"schema_version": 1, "tool_version": __version__, "project": name, "base_branch": base_branch, "fail_on": fail_on,
626
+ "failed": bool(reasons), "reasons": reasons, "exit_code": EXIT_THRESHOLD if reasons else 0,
627
+ "new": sum(len(r["new"]) for r in results), "worse": sum(len(r["worse"]) for r in results),
628
+ "verified_fixes": verified_fixes(results), "verified_call_sites": verified_sites(results),
629
+ "head_commit": head_commit, "base": behind,
630
+ "gone": sum(len(r["gone"]) for r in results), "compared": any(r["compared"] for r in results),
631
+ "scope": {k: v for k, v in scope.items() if k != "site_ids"} if scope else None, "agent": _agent(runs), "engines": results,
632
+ "coverage": {"judged_share": head_cov["judged_share"], "judged_measured_share": head_cov["judged_measured_share"],
633
+ "sites": head_cov["sites"], "base_judged_share": base_share} if head_cov else None}
634
+ if markdown is not None:
635
+ markdown.parent.mkdir(parents=True, exist_ok=True)
636
+ markdown.write_text(body)
637
+ if json_out is not None:
638
+ json_out.parent.mkdir(parents=True, exist_ok=True)
639
+ json_out.write_text(json.dumps(summary, indent=1, ensure_ascii=False))
640
+ if not quiet:
641
+ print(body)
642
+ if reasons:
643
+ err.print(f"[red]--fail-on {fail_on}:[/red] {'; '.join(reasons)}.")
644
+ raise typer.Exit(EXIT_THRESHOLD)
645
+
646
+
647
+ def coverage_line(body: str, line: str) -> str:
648
+ """The repository coverage line ("coverage 60.0% of 1,000 query and write sites (… measured), -0.4") above the comment's
649
+ closing notes (`<sub>`)."""
650
+ rows = [r for r in body.split("\n") if not r.startswith("coverage ")]
651
+ at = next((i for i in range(len(rows) - 1, -1, -1) if rows[i].startswith("<sub>")), len(rows))
652
+ rows[at:at] = [line, ""]
653
+ return "\n".join(rows)
654
+
655
+
656
+ # ---- inline suggestions ----------------------------------------------------------------------
657
+
658
+ SUGGEST_FILE = "suggestions.json"
659
+ DIFF_CONTEXT = 3 # GitHub's pull-request diff: a review comment may sit on a changed line or its 3 lines of context
660
+
661
+
662
+ def pr_hunks(root: Path, ref: str, context: int = DIFF_CONTEXT) -> dict[str, list[tuple[int, int]]]:
663
+ """{file: [(first, last)]}: the head-side line ranges of each hunk of the pull request's diff (merge base of `ref` and
664
+ HEAD, to HEAD), as GitHub shows it. A suggestion can only be placed inside one of these."""
665
+ from . import changed
666
+ base = changed._git(root, "merge-base", ref, "HEAD").strip()
667
+ files: dict[str, list[tuple[int, int]]] = {}
668
+ current, old_left, new_left = None, 0, 0
669
+ for line in changed._git(root, "diff", f"--unified={context}", "--no-color", "--no-ext-diff", "--relative", "-M", base, "HEAD",
670
+ "--", ".").splitlines():
671
+ if old_left > 0 or new_left > 0: # inside a hunk: a changed line may itself start with `+++ ` or `@@`
672
+ tag = line[:1]
673
+ if tag in (" ", ""):
674
+ old_left, new_left = old_left - 1, new_left - 1
675
+ elif tag == "-":
676
+ old_left -= 1
677
+ elif tag == "+":
678
+ new_left -= 1
679
+ continue
680
+ if line.startswith("+++ "):
681
+ name = line[4:].strip()
682
+ current = None if name == "/dev/null" else name[2:] if name.startswith("b/") else name
683
+ continue
684
+ m = changed.HUNK.match(line)
685
+ if m:
686
+ old_left = int(m.group(1)) if m.group(1) is not None else 1
687
+ start, count = int(m.group(2)), int(m.group(3)) if m.group(3) is not None else 1
688
+ new_left = count
689
+ if current is not None and count > 0:
690
+ files.setdefault(current, []).append((start, start + count - 1))
691
+ return files
692
+
693
+
694
+ def replaced_lines(diff: str) -> list[dict]:
695
+ """The changes of a unified diff (`codecop apply`'s code.diff) as {path, start_line, line, replacement}: the old-side lines
696
+ one change replaces, first to last, and the text that stands in their place. Lines between two changes of one hunk are
697
+ carried in the replacement unchanged. A change that only inserts lines has nothing to replace and is left out."""
698
+ out: list[dict] = []
699
+ path = ""
700
+ old_no = 0
701
+ group: dict | None = None
702
+ pending_context: list[str] = []
703
+
704
+ def close() -> None:
705
+ nonlocal group
706
+ if group and group["first"] is not None:
707
+ out.append({"path": path, "start_line": group["first"], "line": group["last"], "replacement": "".join(group["new"])})
708
+ group = None
709
+
710
+ for raw in diff.splitlines(keepends=True):
711
+ if raw.startswith("+++ "):
712
+ name = raw[4:].strip()
713
+ path = name[2:] if name.startswith("b/") else name
714
+ continue
715
+ if raw.startswith("--- "):
716
+ continue
717
+ m = re.match(r"^@@ -(\d+)(?:,\d+)? \+\d+(?:,\d+)? @@", raw)
718
+ if m:
719
+ close()
720
+ old_no = int(m.group(1))
721
+ pending_context = []
722
+ continue
723
+ if raw.startswith("\\"):
724
+ continue
725
+ tag, text = raw[:1], raw[1:]
726
+ if tag == " ":
727
+ if group is not None:
728
+ pending_context.append(text)
729
+ old_no += 1
730
+ elif tag == "-":
731
+ if group is None:
732
+ group = {"first": None, "last": None, "new": []}
733
+ elif pending_context:
734
+ group["new"] += pending_context
735
+ pending_context = []
736
+ group["first"] = old_no if group["first"] is None else group["first"]
737
+ group["last"] = old_no
738
+ old_no += 1
739
+ elif tag == "+":
740
+ if group is None:
741
+ group = {"first": None, "last": None, "new": []}
742
+ elif pending_context:
743
+ group["new"] += pending_context
744
+ pending_context = []
745
+ group["new"].append(text)
746
+ close()
747
+ # Several changes in one hunk: one suggestion from the first replaced line to the last, context between them kept.
748
+ merged: list[dict] = []
749
+ for c in out:
750
+ if merged and merged[-1]["path"] == c["path"] and c["start_line"] - merged[-1]["line"] <= 2 * DIFF_CONTEXT:
751
+ merged[-1] = {**merged[-1], "line": c["line"], "replacement": merged[-1]["replacement"] + c["replacement"]}
752
+ else:
753
+ merged.append(c)
754
+ return merged
755
+
756
+
757
+ def _proof(finding: dict) -> dict | None:
758
+ """{metric, before, after} of the finding's verified variant at the largest scale the sandbox measured."""
759
+ best = next((v for v in finding.get("variants") or [] if v.get("verdict") == "win"), None)
760
+ last = ((best or {}).get("scales") or [None])[-1] or {}
761
+ b, v = last.get("baseline") or {}, last.get("variant") or {}
762
+ for key, metric in (("read_rows", "rows read"), ("read_bytes", "bytes read")):
763
+ if isinstance(b.get(key), (int, float)) and isinstance(v.get(key), (int, float)):
764
+ return {"metric": metric, "before": b[key], "after": v[key]}
765
+ return None
766
+
767
+
768
+ # What a fix costs besides its gain (report.TRADEOFF_LABEL). `code_change` is how a rewrite is delivered (the suggestion
769
+ # itself), not a cost of it: a rewrite whose only "trade-off" is that it changes code is a plain verified win.
770
+ DELIVERY_ONLY = {"code_change"}
771
+
772
+
773
+ def trade_offs(variant: dict) -> list:
774
+ """The variant's real trade-offs: those that make it a trade-off, not a win (changes results, needs a setting, ...)."""
775
+ return [t for t in variant.get("tradeoffs") or [] if t not in DELIVERY_ONLY]
776
+
777
+
778
+ def _rewrite_patch(findings_doc: dict, finding: dict, root: Path) -> dict | None:
779
+ """The code change for the finding's best sandbox-verified rewrite (no trade-off), made by `codecop apply`'s own planner
780
+ (apply.plan_finding: the same exact-location rules as `codecop apply`). Used when apply planned a schema change for the
781
+ finding (an index or projection won by more) but a rewrite was verified too: the rewrite can be suggested on the
782
+ diff, the schema change is counted and linked. None when there is no such variant or apply could not place it."""
783
+ variant = next((v for v in finding.get("variants") or []
784
+ if v.get("kind") == "rewrite" and v.get("verdict") == "win" and not trade_offs(v)), None)
785
+ if variant is None:
786
+ return None
787
+ from .apply import plan_finding
788
+ try:
789
+ entry = plan_finding(findings_doc, finding, variant, catalog=None, bench=None, rank=None, inventory=None, repo=root)
790
+ except Exception: # noqa: BLE001 - apply refusing to plan is "not located", never a failed command
791
+ return None
792
+ patch = entry.get("patch") or {}
793
+ return patch if patch.get("diff") else None
794
+
795
+
796
+ def _site_in_diff(finding: dict, hunks: dict) -> bool:
797
+ """Whether the finding's call site is on a line of the pull request's diff (a hunk of its file)."""
798
+ site = finding.get("site") if isinstance(finding.get("site"), dict) else {}
799
+ line = site.get("line")
800
+ return isinstance(line, int) and any(lo <= line <= hi for lo, hi in hunks.get(str(site.get("file") or ""), []))
801
+
802
+
803
+ def suggestions(root: Path, out_dir: Path, ref: str) -> dict:
804
+ """suggestions.json for a scan whose `codecop apply` ran: one entry per sandbox-verified rewrite whose code change
805
+ replaces lines that are all inside one hunk of the pull request's diff. The code change is apply's
806
+ code.diff; when apply chose a schema change for a finding that also has a verified rewrite, the rewrite's change is
807
+ made with apply's own planner. Everything not suggested is counted in `skipped` by why: not verified (or a
808
+ trade-off), not located exactly in the code, outside the diff; `schema_change` counts the schema changes (linked in
809
+ the comment, never inline) of findings whose call site is on a line of the pull request's diff, whether or not a
810
+ rewrite of the same finding was suggested. An advisor's table suggestion (no finding of its own) and a finding
811
+ elsewhere in the repository come from the whole scan, not from the pull request: never counted here."""
812
+ import hashlib
813
+ hunks = pr_hunks(root, ref)
814
+ entries: list[dict] = []
815
+ skipped = {"not_verified": 0, "trade_off": 0, "no_exact_location": 0, "outside_diff": 0, "schema_change": 0}
816
+ not_suggested: list[dict] = []
817
+
818
+ def why(key: str, fid: str, reason: str) -> None:
819
+ skipped[key] += 1
820
+ not_suggested.append({"finding_id": fid, "engine": run["engine"], "why": key, "reason": reason})
821
+
822
+ for run in head_runs(out_dir):
823
+ doc = run["findings"]
824
+ findings = {f.get("finding"): f for f in doc.get("findings") or []}
825
+ plan_path = run["dir"] / "apply" / "plan.json"
826
+ plans = {p.get("finding"): p for p in (json.loads(plan_path.read_text()).get("plans") or [])} if plan_path.exists() else {}
827
+ for fid, finding in findings.items():
828
+ if (finding.get("kind") or "query") != "query":
829
+ continue
830
+ if finding.get("status") != "verified":
831
+ skipped["not_verified"] += 1
832
+ continue
833
+ plan = plans.get(fid) or {}
834
+ variant = plan.get("variant") or {}
835
+ migration = "migration" in (plan.get("delivery") or "") and variant.get("verdict") == "win"
836
+ if migration and _site_in_diff(finding, hunks):
837
+ skipped["schema_change"] += 1
838
+ patch = None
839
+ diff_file = run["dir"] / "apply" / plan.get("dir", "") / "code.diff"
840
+ traded = bool(plan and not migration and trade_offs(variant))
841
+ if plan and not migration and variant.get("verdict") == "win" and not traded \
842
+ and (plan.get("patch") or {}).get("diff") and diff_file.exists():
843
+ patch = {**plan["patch"], "diff": diff_file.read_text()}
844
+ else:
845
+ patch = _rewrite_patch(doc, finding, root)
846
+ if patch is None:
847
+ if traded:
848
+ why("trade_off", fid, "the verified rewrite is a trade-off: " + "; ".join(map(str, trade_offs(variant)))[:200])
849
+ elif not migration:
850
+ why("no_exact_location" if plan else "not_verified", fid,
851
+ (plan.get("patch") or {}).get("reason") or ("apply wrote no code change" if plan else "apply planned nothing"))
852
+ continue
853
+ changes = replaced_lines(patch["diff"])
854
+ if len(changes) != 1:
855
+ why("no_exact_location", fid, f"the code change has {len(changes)} separate places, not one")
856
+ continue
857
+ c = changes[0]
858
+ if not any(lo <= c["start_line"] and c["line"] <= hi for lo, hi in hunks.get(c["path"], [])):
859
+ why("outside_diff", fid, f"{c['path']}:{c['start_line']}-{c['line']} is not in the pull request's diff")
860
+ continue
861
+ entries.append({"finding_id": fid, "fingerprint": finding.get("id") or "", "engine": run["engine"],
862
+ "title": finding.get("title") or "", "path": c["path"], "start_line": c["start_line"], "line": c["line"],
863
+ "replacement": c["replacement"],
864
+ "variant_hash": hashlib.sha256((patch.get("new_sql") or c["replacement"]).encode()).hexdigest()[:8],
865
+ "proof": _proof(finding)})
866
+ return {"schema_version": 1, "tool_version": __version__, "ref": ref, "suggestions": entries, "skipped": skipped,
867
+ "not_suggested": not_suggested}
868
+
869
+
870
+ def suggest_line(doc: dict) -> str:
871
+ """The comment's line about what was suggested on the diff and what was not inline (schema changes)."""
872
+ s = doc.get("skipped") or {}
873
+ bits = [f"Suggested on the diff: {len(doc.get('suggestions') or [])}"]
874
+ if s.get("schema_change"):
875
+ bits.append(f"Schema changes: {s['schema_change']} (open in CodeCop)")
876
+ return " · ".join(bits)
877
+
878
+
879
+ def add_to_comment(body: str, line: str) -> str:
880
+ """`line` placed above the comment's closing notes (`<sub>`), replacing a line written there before."""
881
+ rows = [r for r in body.split("\n") if not r.startswith("Suggested on the diff:")]
882
+ at = next((i for i in range(len(rows) - 1, -1, -1) if rows[i].startswith("<sub>")), len(rows))
883
+ rows[at:at] = [line, ""]
884
+ return "\n".join(rows)
885
+
886
+
887
+ @ci_app.command("suggest")
888
+ def suggest_cmd(
889
+ path: Path = typer.Argument(Path("."), help="Repository that was scanned, checked out at the pull request's head."),
890
+ out_dir: Optional[Path] = typer.Option(None, "--out", help="Directory holding the scan and `codecop apply`'s plans. Default: <path>/.codecop"),
891
+ changed_since: str = typer.Option(..., "--changed-since", help="The base the pull request is compared with, e.g. origin/main."),
892
+ json_out: Optional[Path] = typer.Option(None, "--json", help=f"Write the suggestions here. Default: <out>/{SUGGEST_FILE}"),
893
+ markdown: Optional[Path] = typer.Option(None, "--markdown", help="Add the 'Suggested on the diff' line to this comment "
894
+ "(written by `codecop ci compare --markdown`)."),
895
+ ) -> None:
896
+ """Inline fixes for the pull request: each sandbox-verified rewrite whose code change lands on lines of the diff.
897
+
898
+ Reads `codecop apply`'s code.diff files; writes suggestions.json. Posting them is the console's job (or a later step)."""
899
+ from . import changed
900
+ root = path.resolve()
901
+ scan_dir = out_dir or (root / ".codecop")
902
+ if not head_runs(scan_dir):
903
+ err.print(f"[red]No findings.json in {scan_dir}.[/red] Run `codecop scan` and `codecop apply` first.")
904
+ raise typer.Exit(1)
905
+ try:
906
+ doc = suggestions(root, scan_dir, changed_since)
907
+ except changed.ChangedError as e:
908
+ err.print(f"[red]Cannot read the pull request's diff:[/red] {e}")
909
+ raise typer.Exit(2)
910
+ target = json_out or (scan_dir / SUGGEST_FILE)
911
+ target.parent.mkdir(parents=True, exist_ok=True)
912
+ target.write_text(json.dumps(doc, indent=1, ensure_ascii=False))
913
+ if markdown is not None and markdown.exists():
914
+ markdown.write_text(add_to_comment(markdown.read_text(), suggest_line(doc)))
915
+ out.print(f"{len(doc['suggestions'])} suggestion(s) on the diff; skipped: "
916
+ + ", ".join(f"{k.replace('_', ' ')} {v}" for k, v in doc["skipped"].items() if v) + f". Wrote {target}.",
917
+ markup=False)
918
+
919
+
920
+ # ---- GitHub -------------------------------------------------------------------------------
921
+
922
+ class GitHubError(RuntimeError):
923
+ pass
924
+
925
+
926
+ def _github(method: str, url: str, token: str, body: dict | None = None):
927
+ data = json.dumps(body).encode("utf-8") if body is not None else None
928
+ req = urllib.request.Request(url, data=data, method=method, headers={
929
+ "Authorization": f"Bearer {token}", "Accept": "application/vnd.github+json", "X-GitHub-Api-Version": "2022-11-28",
930
+ "User-Agent": f"codecop/{__version__}", **({"Content-Type": "application/json"} if data else {})})
931
+ try:
932
+ with urllib.request.urlopen(req, timeout=30) as resp:
933
+ raw = resp.read()
934
+ return json.loads(raw) if raw else None
935
+ except urllib.error.HTTPError as e:
936
+ try:
937
+ message = str(json.loads(e.read().decode("utf-8", "replace")).get("message", ""))[:200]
938
+ except (ValueError, AttributeError):
939
+ message = ""
940
+ raise GitHubError(f"GitHub answered {e.code} to {method} {urllib.parse.urlsplit(url).path}" + (f": {message}" if message else "")) from e
941
+ except urllib.error.URLError as e:
942
+ raise GitHubError(f"cannot reach {urllib.parse.urlsplit(url).netloc}: {e.reason}") from e
943
+
944
+
945
+ def upsert_comment(api_url: str, repo: str, number: int, token: str, body: str, marker: str = MARKER) -> tuple[str, dict]:
946
+ """Update the comment that carries `marker`, or create it. ('updated' | 'created', the comment)."""
947
+ base = f"{api_url.rstrip('/')}/repos/{repo}"
948
+ for page in range(1, 31):
949
+ comments = _github("GET", f"{base}/issues/{number}/comments?per_page=100&page={page}", token) or []
950
+ for c in comments:
951
+ if marker in (c.get("body") or ""):
952
+ return "updated", _github("PATCH", f"{base}/issues/comments/{c['id']}", token, {"body": body}) or {}
953
+ if len(comments) < 100:
954
+ break
955
+ return "created", _github("POST", f"{base}/issues/{number}/comments", token, {"body": body}) or {}
956
+
957
+
958
+ def _pull_number() -> int | None:
959
+ """The pull request a GitHub Actions job runs for: from the event file, else from refs/pull/<n>/merge."""
960
+ path = os.environ.get("GITHUB_EVENT_PATH")
961
+ if path and Path(path).exists():
962
+ try:
963
+ event = json.loads(Path(path).read_text())
964
+ number = (event.get("pull_request") or {}).get("number") or event.get("number")
965
+ if isinstance(number, int):
966
+ return number
967
+ except ValueError:
968
+ pass
969
+ parts = (os.environ.get("GITHUB_REF") or "").split("/")
970
+ return int(parts[2]) if len(parts) >= 3 and parts[1] == "pull" and parts[2].isdigit() else None
971
+
972
+
973
+ @ci_app.command("comment")
974
+ def comment_cmd(
975
+ file: Path = typer.Option(..., "--file", help="The comment, as written by `codecop ci compare --markdown`."),
976
+ repo: Optional[str] = typer.Option(None, "--repo", help="owner/name. Default: GITHUB_REPOSITORY."),
977
+ pr: Optional[int] = typer.Option(None, "--pr", help="Pull request number. Default: from the GitHub Actions event."),
978
+ api_url: Optional[str] = typer.Option(None, "--api-url", help="Default: GITHUB_API_URL, else https://api.github.com."),
979
+ token_env: str = typer.Option("GITHUB_TOKEN", "--token-env", help="Name of the environment variable holding the GitHub token."),
980
+ ) -> None:
981
+ """Post the comparison on the pull request, or update the comment a previous push posted. One comment per pull request."""
982
+ repo = repo or os.environ.get("GITHUB_REPOSITORY") or ""
983
+ number = pr if isinstance(pr, int) else _pull_number()
984
+ token = os.environ.get(token_env) or ""
985
+ if not repo or "/" not in repo or number is None:
986
+ err.print("[red]Which pull request?[/red] Pass --repo owner/name and --pr N (GitHub Actions sets both for pull_request events).")
987
+ raise typer.Exit(2)
988
+ if not token:
989
+ err.print(f"[red]{token_env} is not set.[/red] The job needs `permissions: pull-requests: write`.")
990
+ raise typer.Exit(1)
991
+ if not file.exists():
992
+ err.print(f"[red]No file {file}.[/red]")
993
+ raise typer.Exit(2)
994
+ body = file.read_text()
995
+ if MARKER not in body:
996
+ body = MARKER + "\n" + body
997
+ try:
998
+ action, comment = upsert_comment(api_url or os.environ.get("GITHUB_API_URL") or "https://api.github.com", repo, number, token, body)
999
+ except GitHubError as e:
1000
+ err.print(f"[red]Comment not posted:[/red] {e}")
1001
+ raise typer.Exit(1)
1002
+ out.print(f"Comment {action} on {repo}#{number}" + (f": {comment.get('html_url')}" if comment.get("html_url") else ""), markup=False)