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/client.py ADDED
@@ -0,0 +1,729 @@
1
+ """Talking to the CodeCop server: sign-in (OAuth device flow) and run upload.
2
+
3
+ The contract is the console's API. Nothing here is needed for local use: every
4
+ stage works offline and writes files; this module only sends them.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import gzip
10
+ import hashlib
11
+ import json
12
+ import os
13
+ import platform
14
+ import stat
15
+ import time
16
+ import tomllib
17
+ import urllib.error
18
+ import urllib.request
19
+ from datetime import datetime, timezone
20
+ from pathlib import Path
21
+
22
+ from . import __version__, engines, formerly
23
+
24
+ DEFAULT_SERVER = "http://127.0.0.1:8080"
25
+ KEYRING_SERVICE = "codecop"
26
+ FORBIDDEN_KEYS = {"dsn", "password"}
27
+
28
+
29
+ class ApiError(RuntimeError):
30
+ def __init__(self, status: int, code: str, message: str):
31
+ super().__init__(f"{code}: {message}" if message else code)
32
+ self.status, self.code = status, code
33
+
34
+
35
+ # ---- local settings and token storage -----------------------------------
36
+
37
+ def config_dir() -> Path:
38
+ return Path(os.environ.get("CODECOP_CONFIG_DIR") or Path.home() / ".config" / "codecop")
39
+
40
+
41
+ def load_settings() -> dict:
42
+ path = formerly.config_file_to_read(config_dir(), "config.toml")
43
+ return tomllib.loads(path.read_text()) if path.exists() else {}
44
+
45
+
46
+ def org_setting(settings: dict) -> str | None:
47
+ """The organisation chosen at `codecop login`. A config.toml written before organisations says `team`:
48
+ read for one release, and replaced by `org` the next time the file is saved."""
49
+ return settings.get("org") or settings.get("team") or None
50
+
51
+
52
+ def save_settings(settings: dict) -> None:
53
+ """A flat table of strings and string lists is all this file holds."""
54
+ directory = config_dir()
55
+ directory.mkdir(parents=True, exist_ok=True)
56
+ lines = []
57
+ for key, value in settings.items():
58
+ if isinstance(value, list):
59
+ lines.append(f"{key} = [{', '.join(json.dumps(v) for v in value)}]")
60
+ else:
61
+ lines.append(f"{key} = {json.dumps(value)}")
62
+ (directory / "config.toml").write_text("\n".join(lines) + "\n")
63
+
64
+
65
+ def server_url(override: str | None = None) -> str:
66
+ return (override or os.environ.get("CODECOP_SERVER") or load_settings().get("server") or DEFAULT_SERVER).rstrip("/")
67
+
68
+
69
+ def store_token(server: str, token: str) -> str:
70
+ """Put the token in the OS keychain. Without a keychain, fall back to a file only the user can read."""
71
+ try:
72
+ import keyring
73
+ keyring.set_password(KEYRING_SERVICE, server, token)
74
+ return "the OS keychain"
75
+ except Exception: # no keyring backend (headless Linux, CI): any failure means "use the file"
76
+ path = config_dir() / "credentials.json"
77
+ path.parent.mkdir(parents=True, exist_ok=True)
78
+ data = json.loads(path.read_text()) if path.exists() else {}
79
+ data[server] = token
80
+ path.write_text(json.dumps(data))
81
+ path.chmod(stat.S_IRUSR | stat.S_IWUSR)
82
+ return str(path)
83
+
84
+
85
+ def load_token(server: str) -> str | None:
86
+ if os.environ.get("CODECOP_TOKEN"):
87
+ return os.environ["CODECOP_TOKEN"] # CI: an organisation token from the environment
88
+ try:
89
+ import keyring
90
+ token = keyring.get_password(KEYRING_SERVICE, server)
91
+ if token:
92
+ return token
93
+ token = keyring.get_password(formerly.OLD_KEYRING_SERVICE, server) # stored before the rename
94
+ if token:
95
+ return token
96
+ except Exception:
97
+ pass
98
+ for path in (config_dir() / "credentials.json", formerly.old_credentials(config_dir())):
99
+ if path is not None and path.exists():
100
+ token = json.loads(path.read_text()).get(server)
101
+ if token:
102
+ return token
103
+ return None
104
+
105
+
106
+ def forget_token(server: str) -> None:
107
+ try:
108
+ import keyring
109
+ keyring.delete_password(KEYRING_SERVICE, server)
110
+ except Exception:
111
+ pass
112
+ try: # a token stored before the rename would otherwise still be found by load_token
113
+ import keyring
114
+ keyring.delete_password(formerly.OLD_KEYRING_SERVICE, server)
115
+ except Exception:
116
+ pass
117
+ for path in (config_dir() / "credentials.json", formerly.old_credentials(config_dir())):
118
+ if path is not None and path.exists():
119
+ data = json.loads(path.read_text())
120
+ if data.pop(server, None) is not None:
121
+ path.write_text(json.dumps(data))
122
+
123
+
124
+ # ---- upload consent: asked once per repository and server, shared by `push` and `scan` ----
125
+
126
+ def consent_key(server: str, repo_name: str) -> str:
127
+ return f"{server}|{repo_name}"
128
+
129
+
130
+ def has_consent(settings: dict, server: str, repo_name: str) -> bool:
131
+ return consent_key(server, repo_name) in set(settings.get("upload_consent", []))
132
+
133
+
134
+ def record_consent(settings: dict, server: str, repo_name: str) -> None:
135
+ settings["upload_consent"] = sorted(set(settings.get("upload_consent", [])) | {consent_key(server, repo_name)})
136
+ save_settings(settings)
137
+
138
+
139
+ # ---- HTTP ---------------------------------------------------------------
140
+
141
+ class Client:
142
+ def __init__(self, server: str, token: str | None = None):
143
+ self.server, self.token = server.rstrip("/"), token
144
+
145
+ def request(self, method: str, path: str, body=None, *, compress: bool = False, timeout: int = 120,
146
+ data: bytes | None = None, headers: dict | None = None):
147
+ """One request. `body` is sent as JSON; `data` is sent as it is (one part of an upload)."""
148
+ headers = {"Accept": "application/json", "User-Agent": f"codecop/{__version__}", **(headers or {})}
149
+ if body is not None:
150
+ data = json.dumps(body, ensure_ascii=False).encode("utf-8")
151
+ headers["Content-Type"] = "application/json"
152
+ if compress:
153
+ data = gzip.compress(data, compresslevel=6)
154
+ headers["Content-Encoding"] = "gzip"
155
+ elif data is not None:
156
+ headers.setdefault("Content-Type", "application/octet-stream")
157
+ if self.token:
158
+ headers["Authorization"] = f"Bearer {self.token}"
159
+ req = urllib.request.Request(self.server + path, data=data, method=method, headers=headers)
160
+ try:
161
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
162
+ raw = resp.read()
163
+ if resp.headers.get("Content-Encoding", "").lower() == "gzip":
164
+ raw = gzip.decompress(raw)
165
+ return json.loads(raw) if raw else None
166
+ except urllib.error.HTTPError as e:
167
+ raw = e.read().decode("utf-8", "replace")
168
+ try:
169
+ err = json.loads(raw)
170
+ except json.JSONDecodeError:
171
+ raise ApiError(e.code, f"http_{e.code}", raw[:200]) from e
172
+ # the CLI's endpoints answer {"error", "message"}; the management API answers a problem document
173
+ raise ApiError(e.code, str(err.get("error") or err.get("code") or "error"),
174
+ str(err.get("message") or err.get("detail") or "")) from e
175
+ except urllib.error.URLError as e:
176
+ if isinstance(e.reason, (ConnectionError, TimeoutError)) and data is not None and len(data) > 65536:
177
+ raise ApiError(0, "connection_lost", _lost(self.server, e.reason)) from e
178
+ raise ApiError(0, "unreachable", f"Cannot reach {self.server}: {e.reason}") from e
179
+ except (ConnectionError, TimeoutError) as e:
180
+ raise ApiError(0, "connection_lost", _lost(self.server, e)) from e
181
+
182
+ # device flow
183
+ def device_start(self) -> dict:
184
+ return self.request("POST", "/api/v1/device/code", {"client_name": f"CodeCop {__version__} on {platform.node()}"})
185
+
186
+ def device_poll(self, start: dict, on_wait=None) -> dict:
187
+ """Poll until the user approves in the browser, the code expires, or access is denied."""
188
+ interval = max(int(start.get("interval", 5)), 1)
189
+ deadline = time.monotonic() + int(start.get("expires_in", 600))
190
+ while time.monotonic() < deadline:
191
+ time.sleep(interval)
192
+ try:
193
+ return self.request("POST", "/api/v1/device/token", {"device_code": start["device_code"]})
194
+ except ApiError as e:
195
+ if e.code == "authorization_pending":
196
+ if on_wait:
197
+ on_wait()
198
+ continue
199
+ if e.code == "slow_down":
200
+ interval += 5
201
+ continue
202
+ raise
203
+ raise ApiError(400, "expired_token", "The code expired before it was approved.")
204
+
205
+ def me(self) -> dict:
206
+ return self.request("GET", "/api/v1/me")
207
+
208
+ def create_run(self, bundle: dict, org: str | None, *, timeout: int = 120, heartbeat_s: int | None = None) -> dict:
209
+ body = {"project": bundle["repo"]["name"], "commit": bundle["repo"].get("commit", ""),
210
+ "branch": bundle["repo"].get("branch", ""), "engine": bundle["engine"],
211
+ "engine_version": bundle.get("engine_version", ""), "tool_version": bundle["tool_version"],
212
+ "agent": (bundle.get("agent") or {}).get("runner", "")}
213
+ if bundle.get("scan_id"):
214
+ body["scan_id"] = bundle["scan_id"] # the `codecop scan` this run is one engine of
215
+ if heartbeat_s or bundle.get("heartbeat_s"):
216
+ body["heartbeat_s"] = heartbeat_s or bundle["heartbeat_s"] # a live run: how often the server will hear from us
217
+ if org:
218
+ body["org"] = org
219
+ return self.request("POST", "/api/v1/runs", body, timeout=timeout)
220
+
221
+ def send_events(self, run_id: str, events: list[dict], *, timeout: int = 120) -> None:
222
+ self.request("POST", f"/api/v1/runs/{run_id}/events", {"events": events}, timeout=timeout)
223
+
224
+ def heartbeat(self, run_id: str, every_s: int, *, timeout: int = 5) -> None:
225
+ """An empty events post: the run is still being worked on (the console's API, "Heartbeat")."""
226
+ self.request("POST", f"/api/v1/runs/{run_id}/events", {"events": [], "heartbeat_s": every_s}, timeout=timeout)
227
+
228
+ def upload_bundle(self, run_id: str, bundle: dict, *, packed: "Packed | None" = None, on_progress=None) -> dict:
229
+ """Send the bundle, compressed, in parts (the console's API, "Upload in parts").
230
+
231
+ The size is announced first, so a bundle the server will not take is refused with the reason before any
232
+ of it is sent. Each part is its own request and is tried again when the connection fails; a part the
233
+ server already has (an earlier attempt) is not sent again. A server from before parts gets one request."""
234
+ packed = packed or pack(bundle)
235
+ try:
236
+ upload = self.request("POST", f"/api/v1/runs/{run_id}/upload",
237
+ {"sha256": packed.sha256, "bytes": len(packed.body), "raw_bytes": packed.raw_bytes,
238
+ "heartbeat_s": UPLOAD_HEARTBEAT_S})
239
+ except ApiError as e:
240
+ # 405, or a 404 that is not "No such run.": a server from before parts. One request, already compressed.
241
+ if not (e.status == 405 or (e.status == 404 and e.code != "not_found")):
242
+ raise
243
+ return self.request("PUT", f"/api/v1/runs/{run_id}/bundle", data=packed.body,
244
+ headers={"Content-Type": "application/json", "Content-Encoding": "gzip"}, timeout=600)
245
+ size, total, have = int(upload["part_bytes"]), int(upload["parts"]), set(upload.get("received") or [])
246
+ base = f"/api/v1/runs/{run_id}/upload/{upload['upload_id']}"
247
+ if on_progress:
248
+ on_progress(len(have), total, len(have))
249
+ for part in range(total):
250
+ if part in have:
251
+ continue
252
+ self._send_part(f"{base}/parts/{part}", packed.body[part * size:(part + 1) * size])
253
+ have.add(part)
254
+ if on_progress:
255
+ on_progress(len(have), total, 0)
256
+ return self.request("POST", f"{base}/complete", {}, timeout=600)
257
+
258
+ def _send_part(self, path: str, chunk: bytes) -> None:
259
+ digest = hashlib.sha256(chunk).hexdigest()
260
+ for attempt in range(PART_ATTEMPTS):
261
+ try:
262
+ self.request("PUT", path, data=chunk, headers={"X-Part-Sha256": digest}, timeout=PART_TIMEOUT_S)
263
+ return
264
+ except ApiError as e:
265
+ # Worth another try: the network failed, the server was busy, or the part arrived damaged.
266
+ again = e.status == 0 or e.status >= 500 or e.code == "invalid_part"
267
+ if not again or attempt == PART_ATTEMPTS - 1:
268
+ raise
269
+ time.sleep(min(2 ** attempt, 15))
270
+
271
+ def upload_state(self, run_id: str) -> dict | None:
272
+ """The upload in progress for a run: its parts and which arrived. None when there is none."""
273
+ try:
274
+ return self.request("GET", f"/api/v1/runs/{run_id}/upload")
275
+ except ApiError as e:
276
+ if e.status in (404, 405):
277
+ return None
278
+ raise
279
+
280
+ def cancel_upload(self, run_id: str, reason: str) -> dict:
281
+ """Drop the parts sent so far and end the run as abandoned, with the reason."""
282
+ try:
283
+ self.request("DELETE", f"/api/v1/runs/{run_id}/upload")
284
+ except ApiError as e:
285
+ if e.status not in (404, 405):
286
+ raise
287
+ return self.request("POST", f"/api/v1/runs/{run_id}/abandon", {"reason": reason})
288
+
289
+
290
+ def _lost(server: str, reason) -> str:
291
+ return (f"The connection to {server} was lost while sending ({reason}), so the server's answer, if it had one, "
292
+ f"did not arrive. Run `codecop push --resume` to send what is missing")
293
+
294
+
295
+ # ---- packing, and what a push that did not finish leaves behind ------------------------------
296
+
297
+ # The CLI's patience when sending. The part size is the server's to say; these can be set in the environment.
298
+ UPLOAD_HEARTBEAT_S = int(os.environ.get("CODECOP_UPLOAD_HEARTBEAT_S") or 30) # the server hears from a push at least this often
299
+ PART_ATTEMPTS = max(1, int(os.environ.get("CODECOP_UPLOAD_PART_ATTEMPTS") or 5))
300
+ PART_TIMEOUT_S = int(os.environ.get("CODECOP_UPLOAD_PART_TIMEOUT_S") or 300)
301
+ UPLOAD_STATE_FILE = "upload.json"
302
+
303
+
304
+ class Packed:
305
+ """A bundle ready to send: the compressed bytes, their SHA-256, and the size before compression."""
306
+
307
+ def __init__(self, body: bytes, raw_bytes: int, seconds: float):
308
+ self.body, self.raw_bytes, self.seconds = body, raw_bytes, seconds
309
+ self.sha256 = hashlib.sha256(body).hexdigest()
310
+
311
+
312
+ def pack(bundle: dict) -> Packed:
313
+ """Compress the bundle. The same bundle always packs to the same bytes (no timestamp in the gzip header), so an
314
+ upload that was interrupted is continued by packing again."""
315
+ started = time.monotonic()
316
+ raw = json.dumps(bundle, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
317
+ return Packed(gzip.compress(raw, compresslevel=6, mtime=0), len(raw), time.monotonic() - started)
318
+
319
+
320
+ def load_upload_state(out_dir: Path) -> dict | None:
321
+ """The push that did not finish: {"server", "project", "run_id", "url", "sha256"}; None when there is none."""
322
+ path = out_dir / UPLOAD_STATE_FILE
323
+ try:
324
+ state = json.loads(path.read_text()) if path.exists() else None
325
+ except (OSError, ValueError):
326
+ return None
327
+ return state if isinstance(state, dict) and state.get("run_id") else None
328
+
329
+
330
+ def save_upload_state(out_dir: Path, state: dict) -> None:
331
+ (out_dir / UPLOAD_STATE_FILE).write_text(json.dumps(state, indent=1) + "\n")
332
+
333
+
334
+ def clear_upload_state(out_dir: Path) -> None:
335
+ (out_dir / UPLOAD_STATE_FILE).unlink(missing_ok=True)
336
+
337
+
338
+ # ---- bundle -------------------------------------------------------------
339
+
340
+ PATTERN_KEYS = ("id", "fingerprint", "kind", "label", "member_count", "member_places", "entry_points", "confidence",
341
+ "confidence_notes", "changes", "unknowns", "tables")
342
+ LOOP_KEYS = ("file", "line", "function", "ordinal", "kind", "kind_basis", "form", "hop", "collection", "verified", "over", "vars", "bound")
343
+ MEMBER_KEYS = ("site_id", "file", "line", "symbol", "tables", "role", "hop", "depends_on_loop_var", "verified", "path")
344
+ MEASURED_KEYS = ("match", "shapes", "executions", "executions_per_day", "read_bytes", "share_of_read_bytes", "rows_returned_per_run",
345
+ "bytes_read_per_run", "no_result_share", "aggregate", "window_hours", "basis", "driver_executions", "driver_rows_per_run",
346
+ "executions_per_driver_run", "expected_per_driver_run", "code_and_log", "runs_min", "runs_max", "shapes_located")
347
+
348
+
349
+ def _pick(d: dict | None, keys) -> dict | None:
350
+ return None if not isinstance(d, dict) else {k: d[k] for k in keys if k in d}
351
+
352
+
353
+ def patterns_for_upload(data: dict, with_text: bool = True, databases: set[str] | None = None) -> dict:
354
+ """patterns.json for the bundle, rebuilt field by field: ids, places, kinds, codes and counts. No SQL text (call sites
355
+ are named by id), no database or host name (a measured-only pattern names tables without their database). The loop
356
+ benchmark's `batch` (loopbench.for_upload) carries its batched statement as normalized text only (every value ?),
357
+ and only with `with_text` ([push] observed_text)."""
358
+ from .loopbench import for_upload as batch_for_upload
359
+ out = []
360
+ for p in data.get("patterns") or []:
361
+ q = _pick(p, PATTERN_KEYS)
362
+ q["loops"] = [_pick(lp, LOOP_KEYS) for lp in p.get("loops") or []]
363
+ q["driver"] = _pick(p.get("driver"), ("site_ids", "via", "hops", "verified", "file", "line", "symbol", "tables"))
364
+ q["members"] = [{**_pick(m, MEMBER_KEYS), **({"measured": _pick(m["measured"], MEASURED_KEYS)} if m.get("measured") else {})}
365
+ for m in p.get("members") or []]
366
+ q["code"] = _pick(p.get("code"), ("evidence", "hop_min", "hop_max", "guessed_why"))
367
+ q["measured"] = _pick(p.get("measured"), MEASURED_KEYS)
368
+ batch = batch_for_upload(p.get("batch"), with_text=with_text, databases=databases)
369
+ if batch:
370
+ q["batch"] = batch
371
+ out.append(q)
372
+ acc = [{**_pick(a, ("engine", "window_hours", "shapes", "read_bytes_total", "read_bytes_in_shapes", "executions_total")),
373
+ "by_kind": [_pick(r, ("kind", "shapes", "executions", "read_bytes", "share_of_read_bytes")) for r in a.get("by_kind") or []]}
374
+ for a in data.get("accounting") or []]
375
+ return {"schema_version": data.get("schema_version", 1), "generated_at": data.get("generated_at"), "settings": data.get("settings") or {},
376
+ "window_hours": data.get("window_hours"), "summary": data.get("summary") or {}, "accounting": acc, "patterns": out,
377
+ **({"batch_outcomes": data["batch_outcomes"]} if isinstance(data.get("batch_outcomes"), dict) else {})}
378
+
379
+
380
+ def _read(out_dir: Path, name: str) -> dict | None:
381
+ path = out_dir / f"{name}.json"
382
+ return json.loads(path.read_text()) if path.exists() else None
383
+
384
+
385
+ def engine_dir_inventory(out_dir: Path) -> dict | None:
386
+ """An engine's directory of a multi-engine scan (`<out>/<engine>/`, listed in `<out>/engines.json`) whose inventory.json
387
+ link did not come along (a copied or unpacked out dir): the shared inventory at the out root. None otherwise."""
388
+ parent = Path(out_dir).resolve().parent
389
+ index = _read(parent, "engines")
390
+ if not index or Path(out_dir).resolve().name not in {str(e.get("dir")) for e in index.get("engines") or []}:
391
+ return None
392
+ return _read(parent, "inventory")
393
+
394
+
395
+ def engine_dirs(out_dir: Path) -> list[Path]:
396
+ """The engine directories of a multi-engine scan rooted at `out_dir` (engines.json) that reached their report
397
+ (findings.json); [] when `out_dir` is not such a root."""
398
+ index = _read(Path(out_dir), "engines")
399
+ if not index or (Path(out_dir) / "rank.json").exists():
400
+ return []
401
+ return [Path(out_dir) / str(e["dir"]) for e in index.get("engines") or []
402
+ if e.get("dir") and (Path(out_dir) / str(e["dir"]) / "findings.json").exists()]
403
+
404
+
405
+ # Under `database` (what came from a real database) these may not appear at all: where the server is, who signs in,
406
+ # which database, any definition, any query text. `normalized_text` is allowed only in `unmatched_queries`, which
407
+ # exists only when the user asked for it.
408
+ DATABASE_FORBIDDEN_KEYS = {"host", "hostname", "port", "user", "username", "database", "databases", "databases_described", "create_sql",
409
+ "create_table_query", "definition", "text", "query", "source", "hashes", "connection"}
410
+
411
+
412
+ SCENARIO_FORBIDDEN_KEYS = {"sql", "setup_sql", "text", "normalized_text", "baseline_sql", "original_sql", "params", "query", "clients",
413
+ "labels", "agents", "host", "database", "user"}
414
+
415
+
416
+ TABLE_SUGGESTION_SECTIONS = ("table_suggestions", "index_hygiene", "table_advice")
417
+ TABLE_SUGGESTION_FORBIDDEN_KEYS = {"sql", "setup_sql", "text", "normalized_text", "baseline_sql", "original_sql", "params", "run_sql", "run_params",
418
+ "query", "create_sql", "definition", "statements", "measured_text", "parsed_text", "host", "database", "user",
419
+ "values"}
420
+
421
+
422
+ RESOURCE_SOURCES = ("profile_events", "pg_stat_kcache", "query_log")
423
+
424
+
425
+ def _resource_source(path: str, key: str, value) -> bool:
426
+ """A call site's CPU or memory figure says what counted it (facts.resources_measured): `source` there is one fixed
427
+ word, never an env file's name, so it may stand in the database section."""
428
+ return key == "source" and path.endswith((".cpu", ".memory")) and ".sites." in path and value in RESOURCE_SOURCES
429
+
430
+
431
+ def find_forbidden(value, path: str = "") -> list[str]:
432
+ """Paths of keys that must never be uploaded (connection strings, passwords; and, in what came from a real
433
+ database, anything that identifies the server or carries a definition or a query text)."""
434
+ hits = []
435
+ if isinstance(value, dict):
436
+ for k, v in value.items():
437
+ here = f"{path}.{k}" if path else k
438
+ if (path.split(".")[0].split("[")[0] in ("scenarios", "table_suggestions")) and (k.lower() in SCENARIO_FORBIDDEN_KEYS or k == "rewrite_sql"):
439
+ hits.append(here) # the scenarios section carries codes and numbers: never SQL text or values
440
+ continue
441
+ if (path.split(".")[0].split("[")[0] in TABLE_SUGGESTION_SECTIONS or path.startswith(("findings.table_suggestions", "findings.advisor"))) \
442
+ and k.lower() in TABLE_SUGGESTION_FORBIDDEN_KEYS | {"rewrite_sql"} and not (k == "statements" and not isinstance(v, (list, dict))):
443
+ hits.append(here) # table suggestions carry the proposed DDL (literals as ?), codes and numbers: no statement text
444
+ continue
445
+ if k == "params":
446
+ continue # query parameter names and values: a parameter may legitimately be called `password`
447
+ if k.lower() in FORBIDDEN_KEYS:
448
+ hits.append(here)
449
+ if (path == "database" or path.startswith("database.")) and not _resource_source(path, k, v) and (
450
+ k.lower() in DATABASE_FORBIDDEN_KEYS
451
+ or (k == "normalized_text" and ".unmatched_queries[" not in here and ".observed_queries[" not in here)):
452
+ hits.append(here)
453
+ hits.extend(find_forbidden(v, here))
454
+ elif isinstance(value, list):
455
+ for i, v in enumerate(value):
456
+ hits.extend(find_forbidden(v, f"{path}[{i}]"))
457
+ return hits
458
+
459
+
460
+ STAGE_NAMES = ("discover", "rank", "profile", "bench", "report")
461
+ REAL_DEFINITION_PLACEHOLDER ="-- the real definition, read from the database catalog, is kept on the machine that ran the scan"
462
+
463
+
464
+ def _without_real_definitions(findings: dict) -> dict:
465
+ """findings.json for upload: a table definition read from the real catalog keeps its name and size, not its text."""
466
+ out = dict(findings)
467
+ out["table_definitions"] = [
468
+ {**d, "create_sql": REAL_DEFINITION_PLACEHOLDER} if d.get("source") == "real catalog" else d for d in findings.get("table_definitions") or []]
469
+ return out
470
+
471
+
472
+ OBSERVED_TEXT_KEPT = "-- the statement production ran stays on the machine that ran the scan ([push] observed_text = false)"
473
+ PUSH_DEFAULTS = {"observed_text": True, "observed_text_max_chars": 20_000}
474
+
475
+
476
+ def push_settings(config: dict | None) -> dict:
477
+ """The `[push]` table of codecop.toml: observed_text (upload the normalized text of the statements production ran, default
478
+ true), observed_text_max_chars (each text is cut at this many characters in the upload, default 20000)."""
479
+ out = dict(PUSH_DEFAULTS)
480
+ for key, default in PUSH_DEFAULTS.items():
481
+ value = (config or {}).get(key)
482
+ if value is None:
483
+ continue
484
+ if isinstance(default, bool) != isinstance(value, bool) or (not isinstance(default, bool) and (not isinstance(value, int) or value < 0)):
485
+ raise ValueError(f"push.{key} must be {'true or false' if isinstance(default, bool) else 'a whole number of zero or more'}.")
486
+ out[key] = value
487
+ return out
488
+
489
+
490
+ def _without_observed_text(findings: dict) -> dict:
491
+ """findings.json for an upload with [push] observed_text off: the statements production ran (an observed candidate's
492
+ baseline and variants, the fragments as production filled them, the unlocated statements) keep their numbers and labels,
493
+ not their text."""
494
+ out = dict(findings)
495
+ rows = []
496
+ for f in findings.get("findings") or []:
497
+ if f.get("sql_from") == "query_log":
498
+ f = {**f, "baseline_sql": OBSERVED_TEXT_KEPT, "variants": [{**v, "sql": OBSERVED_TEXT_KEPT} for v in f.get("variants") or []],
499
+ "observed": {k: v for k, v in (f.get("observed") or {}).items() if k not in ("normalized_text", "fragments_text")}}
500
+ rows.append(f)
501
+ out["findings"] = rows
502
+ if isinstance(out.get("observed"), dict) and isinstance(out["observed"].get("unlocated"), dict):
503
+ u = out["observed"]["unlocated"]
504
+ out["observed"] = {**out["observed"], "unlocated": {**u, "statements": [{k: v for k, v in s.items() if k != "normalized_text"}
505
+ for s in u.get("statements") or []]}}
506
+ return out
507
+
508
+
509
+ BUDGET_KEYS = ("billing", "cost_basis", "budget_usd", "budget_basis", "spent_usd", "calls", "calls_failed", "stopped_by_budget",
510
+ "spent_by_step", "planned", "judged_items", "reused_items", "verified_fixes", "cost_per_verified_fix_usd",
511
+ "cost_per_verified_fix_basis", "cost_per_judged_item_usd", "reads_covered_by_verified_fixes", "not_asked", "no_agent", "ledger_total_usd",
512
+ "verified_by_kind", "stopped_first", "usage_limits")
513
+ LIMIT_KEYS = ("kind", "at", "resets_at", "limit_type") # stopped_by_usage_limit: the event, never the CLI's message text
514
+ BUDGET_ITEM_KEYS = ("kind", "step", "ref", "label", "file", "line", "share", "path", "units", "est_low_usd", "est_high_usd", "why", "next_step")
515
+
516
+
517
+ def _agent_budget(out_dir: Path, findings: dict | None) -> dict | None:
518
+ """bundle.agent.budget: the run budget's summary (findings.json `agent_budget`, else agent_plan.json `after`), labels
519
+ and numbers only. None for a run from before the budget."""
520
+ s = (findings or {}).get("agent_budget")
521
+ if not isinstance(s, dict):
522
+ plan = _read(out_dir, "agent_plan") or {}
523
+ s = plan.get("after") if isinstance(plan, dict) else None
524
+ if not isinstance(s, dict):
525
+ return None
526
+ out = {k: s[k] for k in BUDGET_KEYS if k in s and not (k in ("usage_limits", "stopped_first") and not s[k])}
527
+ if isinstance(s.get("stopped_by_usage_limit"), dict):
528
+ out["stopped_by_usage_limit"] = {k: s["stopped_by_usage_limit"][k] for k in LIMIT_KEYS if s["stopped_by_usage_limit"].get(k)}
529
+ out["not_asked_items"] = [{k: i[k] for k in BUDGET_ITEM_KEYS if k in i} for i in (s.get("not_asked_items") or [])[:200]]
530
+ return out
531
+
532
+
533
+ def _with_repository(cov: dict | None, out_dir: Path) -> dict | None:
534
+ """The coverage object with `repository`: the judged share of every query and write site of the whole repository
535
+ (coverage.repository; for one engine of an `--engine auto` scan, the whole). Counts only: no site rows, no text."""
536
+ if not isinstance(cov, dict):
537
+ return cov
538
+ from .coverage import from_out_dir
539
+ try:
540
+ repo_cov = from_out_dir(out_dir)
541
+ except Exception: # noqa: BLE001 - an upload never fails on its coverage count
542
+ repo_cov = None
543
+ if repo_cov:
544
+ stored = (((_read(out_dir, "findings") or {}).get("coverage") or {}).get("repository") or {})
545
+ repo_cov["previous_judged_share"] = stored.get("previous_judged_share")
546
+ cov = {**cov, "repository": repo_cov}
547
+ return cov
548
+
549
+
550
+ def build_bundle(out_dir: Path, include_unmatched_queries: bool = False, observed_text: bool = True,
551
+ observed_text_max_chars: int = 20_000) -> tuple[dict, list[dict]]:
552
+ """The run bundle and the stage events, from the files a run left on disk.
553
+
554
+ From a real database (`codecop db pull`) the bundle carries counts and sizes, the call-site tags, and (unless
555
+ `observed_text` is off: `[push] observed_text`) the normalized text of the statements production ran: every literal
556
+ already `?`, database prefixes removed. Definitions, literal values, partition ids, and the server's address,
557
+ account and database names stay in the out dir. `include_unmatched_queries` adds the older `unmatched_queries` list."""
558
+ inventory = _read(out_dir, "inventory") or engine_dir_inventory(out_dir)
559
+ if inventory is None:
560
+ raise FileNotFoundError(f"No inventory.json in {out_dir}. Run `codecop scan` first.")
561
+ rank, profile, bench, findings = (_read(out_dir, n) for n in ("rank", "profile", "bench", "findings"))
562
+ stages = [("discover", inventory, lambda d: f"{d['summary']['sites']:,} SQL sites in {d['summary']['files_scanned']:,} files"),
563
+ ("rank", rank, lambda d: f"{len(d['candidates'])} candidates from {len(d['shortlist'])} shortlisted"),
564
+ ("profile", profile, lambda d: f"{len(d['tables'])} tables profiled"),
565
+ ("bench", bench, lambda d: f"{len(d['scales'])} scales on {engines.get(d.get('engine', 'clickhouse')).label} {d.get('server_version', '')}"),
566
+ ("report", findings, lambda d: f"{len(d['findings'])} findings")]
567
+ events, seq = [], 0
568
+ last_done, first_missing = inventory, None
569
+ for name, data, describe in stages:
570
+ if data is None:
571
+ first_missing = first_missing or name
572
+ continue
573
+ events.append({"seq": seq, "stage": name, "status": "finished", "at": data["generated_at"], "message": describe(data)})
574
+ seq += 1
575
+ last_done = data
576
+ usage = {"input_tokens": 0, "output_tokens": 0}
577
+ cost = 0.0
578
+ for stage in (rank, profile):
579
+ agent = (stage or {}).get("agent") or {}
580
+ # rank keeps a ledger over every invocation: what the out dir cost, not only the batches of the last result
581
+ cost += float(agent.get("cost_total_usd", agent.get("cost_usd")) or 0)
582
+ for key in usage:
583
+ usage[key] += int((agent.get("usage") or {}).get(key) or 0)
584
+ # the other paid steps keep their own ledgers in their stage files: one total for what this out dir cost
585
+ for name in ("observed", "scenarios", "loops", "groups"):
586
+ doc = _read(out_dir, name) or {}
587
+ cost += float(((doc.get("agent") or {}) if isinstance(doc, dict) else {}).get("cost_total_usd") or 0)
588
+ agent_budget = _agent_budget(out_dir, findings)
589
+ # What kind of run the files are. An out dir with an inventory and nothing after it, where no stage is recorded as
590
+ # having failed (`codecop discover`, `codecop scan --offline`), is an inventory: it completed, and the later stages were
591
+ # not run. It is not a ClickHouse run that failed in rank, which is what it used to be sent as.
592
+ failure = _read(out_dir, "failure") or {}
593
+ inventory_only = rank is None and findings is None and not failure
594
+ completed = findings is not None or inventory_only
595
+ failed_stage = None if completed else (failure.get("stage") if failure.get("stage") in STAGE_NAMES else first_missing)
596
+ stage_state = {}
597
+ for name, data, _ in stages:
598
+ stage_state[name] = "finished" if data is not None else "failed" if name == failed_stage else "not_run"
599
+ by_engine = (inventory.get("summary") or {}).get("by_engine") or {}
600
+ known = [e for e, n in sorted(by_engine.items(), key=lambda kv: (-int(kv[1] or 0), kv[0])) if e and e != "unknown" and n]
601
+ from .coverage import from_stages
602
+ from .realdb.facts import load as load_facts, upload_summary
603
+ db_dir = out_dir if (out_dir / "db_catalog.json").exists() or (out_dir / "db_match.json").exists() else out_dir.parent
604
+ facts = load_facts(db_dir) or None
605
+ bundle = {
606
+ "schema_version": 1,
607
+ "tool_version": __version__,
608
+ # `inventory`: discover only. `scan`: the pipeline was started (and finished, or stopped at `failed_stage`).
609
+ "kind": "inventory" if inventory_only else "scan",
610
+ "status": "completed" if completed else "failed",
611
+ "failed_stage": failed_stage,
612
+ "error": None if completed else (failure.get("error") or f"The run stopped before the {first_missing} stage."),
613
+ # per stage: finished, failed, or not_run. A stage that was never started is not a failure.
614
+ "stages": stage_state,
615
+ "repo": {k: inventory["repo"].get(k, "") for k in ("name", "commit", "branch")},
616
+ # the engine that was ranked and benchmarked; "" when no engine was (an inventory). `engines` is every engine
617
+ # the repository's call sites use, most sites first.
618
+ "engine": (rank or {}).get("engine") or failure.get("engine") or "",
619
+ "engines": known,
620
+ "engine_version": (findings or {}).get("engine_version") or (rank or {}).get("engine_version", ""),
621
+ "engine_version_requested": (findings or {}).get("engine_version_requested") or (rank or {}).get("engine_version_requested", ""),
622
+ "engine_version_note": (findings or {}).get("engine_version_note") or "",
623
+ "started_at": inventory["generated_at"],
624
+ "finished_at": last_done.get("generated_at") or datetime.now(timezone.utc).isoformat(timespec="seconds"),
625
+ "agent": {"runner": ((rank or {}).get("agent") or {}).get("runner", ""),
626
+ "model": ((rank or {}).get("agent") or {}).get("model", ""), "cost_usd": round(cost, 4), **usage,
627
+ # the run budget (budget.py): what was planned, spent and bought, and what was not asked yet
628
+ **({"budget": agent_budget} if agent_budget else {})},
629
+ "inventory": {**inventory, "repo": {k: inventory["repo"].get(k, "") for k in ("name", "commit", "branch")}},
630
+ # counted again from the stage files, so a run from before coverage existed still carries it
631
+ "coverage": _with_repository(from_stages(inventory, rank, profile, bench, facts), out_dir),
632
+ "findings": {**_without_real_definitions(findings if observed_text else _without_observed_text(findings)),
633
+ "repo": {k: (findings.get("repo") or {}).get(k, "") for k in ("name", "commit", "branch")}} if findings else None,
634
+ }
635
+ database = upload_summary(db_dir, include_unmatched_queries, observed_text, observed_text_max_chars)
636
+ if database:
637
+ bundle["database"] = database
638
+ patterns = _read(out_dir, "patterns") or (_read(out_dir.parent, "patterns") if not (out_dir / "inventory.json").exists() else None)
639
+ if patterns and isinstance(patterns.get("patterns"), list):
640
+ from .observed import _databases
641
+ bundle["patterns"] = patterns_for_upload(patterns, with_text=observed_text, databases=_databases(facts.catalog) if facts else None)
642
+ scenarios = _read(out_dir, "scenarios") or (_read(out_dir.parent, "scenarios") if not (out_dir / "inventory.json").exists() else None)
643
+ if scenarios:
644
+ from .scenarios_view import for_upload as scenarios_for_upload
645
+ rebuilt = scenarios_for_upload(scenarios)
646
+ if rebuilt:
647
+ bundle["scenarios"] = rebuilt
648
+ groups = _read(out_dir, "groups") or (_read(out_dir.parent, "groups") if not (out_dir / "inventory.json").exists() else None)
649
+ if groups and isinstance(groups.get("groups"), list):
650
+ from .groupbench import for_upload as groups_for_upload
651
+ from .observed import _databases
652
+ bundle["groups"] = groups_for_upload(groups, with_text=observed_text, databases=_databases(facts.catalog) if facts else None)
653
+ # statement families of run-time-built call sites (families/build.py), as written: the console's family panel
654
+ families = _read(out_dir, "families") or (_read(out_dir.parent, "families") if not (out_dir / "inventory.json").exists() else None)
655
+ if families and isinstance(families.get("families"), list):
656
+ if not observed_text: # statement text from the query log travels only when the user allows observed text
657
+ for f in families["families"]:
658
+ for v in f.get("variants") or []:
659
+ if v.get("basis") == "production":
660
+ v["sql"] = ""
661
+ bundle["families"] = families
662
+ # the access-path advisors, both engines, in the one shape (advisors.py; run_bundle.schema.json $defs.table_suggestion)
663
+ from . import advisors
664
+ stage = advisors.wrap(_read(out_dir, "advisor") or (_read(out_dir.parent, "advisor") if not (out_dir / "inventory.json").exists() else None))
665
+ if stage and stage.get("engines"):
666
+ from .observed import _databases
667
+ sh = advisors.shared(stage, databases=_databases(facts.catalog) if facts else None)
668
+ bundle["table_suggestions"] = sh["table_suggestions"]
669
+ if sh["index_hygiene"]:
670
+ bundle["index_hygiene"] = sh["index_hygiene"]
671
+ bundle["table_advice"] = advisors.table_advice(sh["advice"])
672
+ if bundle.get("findings"):
673
+ # findings.json carries the same suggestions; the bundle sends them once, at the top
674
+ bundle["findings"] = {k: v for k, v in bundle["findings"].items() if k not in ("table_suggestions", "advisor", "agent_budget")}
675
+ from .live import load_scan_id
676
+ scan_id = load_scan_id(out_dir)
677
+ if scan_id:
678
+ bundle["scan_id"] = scan_id
679
+ return bundle, events
680
+
681
+
682
+ def describe_upload(bundle: dict, packed: "Packed | None" = None) -> list[str]:
683
+ """What a push would send, in plain words, for the consent prompt and --dry-run."""
684
+ inv = bundle["inventory"]
685
+ sites = inv["call_sites"]
686
+ files = sorted({c["file"] for c in sites})
687
+ lines = [
688
+ f"Repository name, branch and commit: {bundle['repo']['name']} @ {bundle['repo'].get('branch') or '?'} {bundle['repo'].get('commit', '')[:10]}",
689
+ f"{len(sites):,} call sites from {len(files):,} files: file path, line, function name and the SQL text of each",
690
+ f"{len(inv.get('tables', []))} table definitions found in the repo (names, columns, engines, keys)",
691
+ ]
692
+ if bundle.get("findings"):
693
+ f = bundle["findings"]
694
+ lines.append(f"{len(f['findings'])} findings: the agent's explanation, the benchmarked SQL, setup statements, plans and measurements")
695
+ lines.append(f"The data profile for {len(f.get('profile', []))} tables (estimated sizes and value distributions, no rows)")
696
+ db = bundle.get("database")
697
+ if db:
698
+ lines.append(f"From the real database: rows and bytes of {len(db.get('tables', []))} tables (names, no definitions)")
699
+ for engine, w in (db.get("workload") or {}).items():
700
+ texts = len(w.get("unmatched_queries") or [])
701
+ observed = len(w.get("observed_queries") or [])
702
+ lines.append(f"Measured {engine} load for {len(w.get('sites') or {})} call sites (executions, bytes read, timings) and match rates"
703
+ + (f"; the normalized text of {texts} real queries that match no call site (you asked for this)" if texts else ""))
704
+ if observed:
705
+ lines.append(f"The normalized text of {observed} {engine} statements production ran, as the server logged them: every "
706
+ "literal value already replaced by `?`, database prefixes removed ([push] observed_text = false keeps them here)")
707
+ else:
708
+ lines.append(f"The text of the {engine} statements production ran stays here ([push] observed_text is off)")
709
+ if w.get("tags"):
710
+ lines.append(f"Call-site tags of {len(w['tags'])} statements (only text matching codecop:<tag>) and the call sites they name")
711
+ named = sum(1 for row in (w.get("sites") or {}).values() if row.get("columns_read") or row.get("projections_used"))
712
+ if named:
713
+ lines.append(f"The columns and projections {named} call sites read, as table.column and table.projection (no database name)")
714
+ if any(t.get("inserts") for t in db.get("tables") or []):
715
+ lines.append("Inserts per table (counts, rows and bytes written, time spent)")
716
+ lines.append("Never sent from the real database: literal values, its address, account and database names, partition ids and when "
717
+ "they changed, runs per minute, table definitions, the application's own log_comment labels, client and driver names")
718
+ batched = [p for p in (bundle.get("patterns") or {}).get("patterns") or [] if (p.get("batch") or {}).get("members")]
719
+ if batched:
720
+ lines.append(f"{len(batched)} loop patterns with a batched-statement benchmark: places, codes, item counts, statements and reads "
721
+ "before and after, per-item sameness counts, the batched statement as normalized text (every value ?); "
722
+ "no parameter or item values")
723
+ if bundle.get("groups"):
724
+ lines.append(f"{len(bundle['groups']['groups'])} scan groups: call-site ids and places, shared filters as normalized text (every value ?), "
725
+ "load, the combined statements' normalized text and the group benchmark's numbers; no parameter values")
726
+ packed = packed or pack(bundle)
727
+ lines.append(f"About {packed.raw_bytes / 1e6:.1f} MB, sent compressed as {len(packed.body) / 1e6:.1f} MB")
728
+ lines.append("Not sent: source files, row data, connection strings, agent credentials. Your machine's absolute paths are removed.")
729
+ return lines