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/multi.py ADDED
@@ -0,0 +1,443 @@
1
+ """`codecop scan --engine auto` and `--engine a,b`: one full pipeline per engine, side by side.
2
+
3
+ A single-engine scan keeps writing its stage files straight into the out
4
+ directory, which is what `codecop push` and the server read. A multi-engine scan
5
+ leaves that layout alone and gives every engine its own directory:
6
+
7
+ <out>/inventory.json shared: discover runs once
8
+ <out>/engines.json index: which engines ran, where, and how it ended
9
+ <out>/postgres/rank.json ... the usual stage files, one set per engine
10
+ <out>/clickhouse/rank.json ...
11
+
12
+ Each engine directory is a complete single-engine out directory (its
13
+ inventory.json is a link to the shared one), so `codecop report --out <out>/postgres`,
14
+ `codecop show` and `codecop push --out <out>/postgres` work on it unchanged, and each
15
+ engine uploads as its own run.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import json
21
+ import shutil
22
+ from datetime import datetime, timezone
23
+ from pathlib import Path
24
+
25
+ from . import crashlog, engines, live, rank
26
+
27
+ INCOMPLETE = 4 # cli.INCOMPLETE: an engine reached its report with a step that could not finish
28
+
29
+ MIN_SITES = 1 # `auto` runs an engine that has at least this many shortlistable SELECT sites
30
+
31
+
32
+ def versions(spec: str | None, names: list[str]) -> dict[str, str]:
33
+ """`--engine-version` for several engines: "postgres=17,clickhouse=25.8". A bare version applies when one engine runs."""
34
+ out: dict[str, str] = {}
35
+ for part in (spec or "").split(","):
36
+ part = part.strip()
37
+ if "=" in part:
38
+ name, version = part.split("=", 1)
39
+ out[engines.get(name.strip()).name] = version.strip()
40
+ elif part and len(names) == 1:
41
+ out[names[0]] = part
42
+ return out
43
+
44
+
45
+ SCAN_DEFAULTS = {
46
+ "engine": "auto", # `codecop scan` with no --engine: every engine of the repository in one scan
47
+ "auto_min_sites": MIN_SITES, # an engine runs under `auto` with at least this many SELECT sites outside tests
48
+ "auto_embedded": True, # `auto` also runs an in-process engine (SQLite) that has sites beside a server engine
49
+ "default_engine": "", # the engine of statements nothing decides; empty: inferred from the repository
50
+ # Wall time, not cost: the same questions under the same budget and gate ([agent] concurrency), asked side by side.
51
+ "engines_side_by_side": True, # the engines of a multi-engine scan run at once, each in its own process; their sandbox
52
+ # work (baseline, bench) still takes turns, one engine at a time
53
+ "steps_side_by_side": True, # in one engine: the other kinds of finding beside the query pipeline, the loop
54
+ # questions beside the table sizes
55
+ }
56
+
57
+
58
+ def scan_settings(config: dict | None) -> dict:
59
+ out = dict(SCAN_DEFAULTS)
60
+ for k, v in (config or {}).items():
61
+ if k in out and type(v) is type(SCAN_DEFAULTS[k]):
62
+ out[k] = v
63
+ return out
64
+
65
+
66
+ def pick(spec: str, inventory: dict, include: list[str] | None = None, settings: dict | None = None) -> tuple[list[str], dict[str, int]]:
67
+ """The engines to run and the SELECT sites each has. `auto` takes every supported engine with enough sites."""
68
+ cfg = scan_settings(settings)
69
+ counts = {name: rank.shortlist(inventory, name, 1, include or None)[1] for name in engines.supported()}
70
+ least = max(int(cfg["auto_min_sites"]), 1)
71
+ if spec.strip().lower() == "auto":
72
+ # every engine the repository's code reads in one scan (the denominator counts them all). An engine that runs in
73
+ # the application's process (SQLite) beside a server engine runs too unless `[scan] auto_embedded = false`
74
+ found = [n for n in engines.supported() if counts[n] >= least]
75
+ if not cfg["auto_embedded"]:
76
+ found = [n for n in found if engines.get(n).auto] or found
77
+ return found, counts
78
+ names = []
79
+ for part in spec.split(","):
80
+ name = engines.get(part.strip()).name
81
+ if name and name not in names:
82
+ names.append(name)
83
+ return names, counts
84
+
85
+
86
+ def default_engines(inventory: dict, names: list[str], settings: dict | None = None, facts=None) -> dict:
87
+ """Give an engine to the statements discover left without one (a default engine for unknown-engine sites),
88
+ in place, and say how on each site (`engine_basis` scan_default, `engine_scope` tables | repository). In order: the
89
+ configured `[scan] default_engine`; the engine whose tables the statement reads (every table it names is a table of
90
+ that engine only, in the pulled catalog or the repository's schema); the engine discover inferred for the repository
91
+ (`summary.engine_default.choice`). Only engines of this scan are given. Returns {engine: sites} given."""
92
+ cfg = scan_settings(settings)
93
+ known: dict[str, set[str]] = {}
94
+ for t in inventory.get("tables") or []:
95
+ eng = "clickhouse" if t.get("engine") else ""
96
+ known.setdefault(str(t.get("name") or "").replace('"', "").split(".")[-1].lower(), set()).add(eng or "sql")
97
+ if facts is not None:
98
+ for e in names:
99
+ try:
100
+ for name in facts.tables(e):
101
+ known.setdefault(name.split(".")[-1].lower(), set()).add(e)
102
+ except Exception: # noqa: BLE001 -- a catalog without this engine
103
+ pass
104
+ choice = (((inventory.get("summary") or {}).get("engine_default") or {}).get("choice") or {}).get("engine") or ""
105
+ configured = cfg["default_engine"] if cfg["default_engine"] in names else ""
106
+ given: dict[str, int] = {}
107
+ for s in inventory.get("call_sites") or []:
108
+ if s.get("engine") or not (s.get("sql") or "").strip() or s.get("is_test"):
109
+ continue # (test code is not in the denominator: its statements keep what discover said)
110
+ eng, scope = configured, "repository"
111
+ if not eng:
112
+ owners = set()
113
+ for t in s.get("tables") or []:
114
+ got = known.get(str(t).replace('"', "").replace("`", "").split(".")[-1].lower()) or set()
115
+ got = {("postgres" if "postgres" in names else "") if g == "sql" else g for g in got} - {""}
116
+ owners |= got if got else {"?"}
117
+ owners &= set(names) | {"?"}
118
+ if len(owners) == 1 and "?" not in owners:
119
+ eng, scope = next(iter(owners)), "tables"
120
+ elif choice in names and not (choice == "postgres" and s.get("binds") == "qmark"):
121
+ eng = choice # PostgreSQL never takes `?` placeholders (discover refuses it the same way)
122
+ if eng:
123
+ s["engine"], s["engine_basis"], s["engine_scope"] = eng, "scan_default", scope
124
+ given[eng] = given.get(eng, 0) + 1
125
+ return given
126
+
127
+
128
+ def family_outcomes(path: Path, out_dir: Path, console) -> None:
129
+ """families.json again after the engines ran: each variant takes the outcome the baseline pass measured for it (every
130
+ engine's findings.json), and each family its roll-up. Local, no sandbox; a failure is said, never the scan's."""
131
+ if not (out_dir / "families.json").exists():
132
+ return
133
+ try:
134
+ from .cli import load_config
135
+ from .families import build
136
+ cfg = load_config(Path(path).resolve()).get("families") or {}
137
+ doc = build.build(out_dir, root=Path(path).resolve(), settings=cfg)
138
+ console.print(f"Statement families with measured variants: {doc['summary'].get('rollup')}", highlight=False)
139
+ except Exception as e: # noqa: BLE001
140
+ console.print(f"[yellow]Statement families not updated with the measurements: {e}[/yellow]")
141
+
142
+
143
+ def link_inventory(out_dir: Path, sub: Path) -> None:
144
+ sub.mkdir(parents=True, exist_ok=True)
145
+ target = sub / "inventory.json"
146
+ if target.is_symlink() or target.exists():
147
+ return
148
+ try:
149
+ target.symlink_to(Path("..") / "inventory.json")
150
+ except OSError:
151
+ shutil.copyfile(out_dir / "inventory.json", target)
152
+
153
+
154
+ def summarize(sub: Path) -> dict:
155
+ """How one engine's run ended, read from its stage files."""
156
+ def read(name: str):
157
+ path = sub / f"{name}.json"
158
+ return json.loads(path.read_text()) if path.exists() else None
159
+
160
+ findings, ranked = read("findings"), read("rank")
161
+ if findings:
162
+ by_status: dict[str, int] = {}
163
+ for f in findings["findings"]:
164
+ by_status[f["status"]] = by_status.get(f["status"], 0) + 1
165
+ return {"stage": "report", "engine_version": findings.get("engine_version", ""), "findings": len(findings["findings"]),
166
+ "by_status": by_status, "agent_cost_usd": findings.get("agent", {}).get("cost_usd", 0)}
167
+ if ranked:
168
+ return {"stage": "rank", "engine_version": ranked.get("engine_version", ""), "findings": len(ranked["candidates"]),
169
+ "by_status": {}, "agent_cost_usd": round(ranked.get("agent", {}).get("cost_usd", 0), 2)}
170
+ return {"stage": "discover", "engine_version": "", "findings": 0, "by_status": {}, "agent_cost_usd": 0}
171
+
172
+
173
+ def _spent(sub: Path) -> float:
174
+ """What the last run in an engine's directory spent (agent_ledger.json, budget.py)."""
175
+ try:
176
+ runs = json.loads((sub / "agent_ledger.json").read_text()).get("runs") or []
177
+ except (OSError, ValueError):
178
+ return 0.0
179
+ return sum(float(c.get("cost_usd") or 0) for c in (runs[-1].get("calls") or [])) if runs else 0.0
180
+
181
+
182
+ def _left(budget, spent: float) -> str | None:
183
+ """The budget the next engine gets: what is left of a numeric one; None to leave it as it is."""
184
+ if not isinstance(budget, str) or not spent:
185
+ return None
186
+ try:
187
+ value = float(budget)
188
+ except ValueError:
189
+ return None # "none": no ceiling
190
+ return f"{max(value - spent, 0.0):.4f}"
191
+
192
+
193
+ def _side_by_side(run_one, names: list[str], pool, out_dir: Path, console, kw_of, options: dict) -> dict[str, str]:
194
+ """Every engine's scan at once, each in a process of its own (forked: the same code and settings), all under `pool`
195
+ (budget.Pool). The first engine makes its plan, and answers the over-budget question if it has one, before the others
196
+ start; they take its answer ("budget" when it had none to give, so no second question interrupts the run). Returns
197
+ engine -> ok | incomplete | failed."""
198
+ import multiprocessing as mp
199
+ import os
200
+ import sys
201
+
202
+ def child(name: str, opts: dict) -> None:
203
+ import typer
204
+ code = 0
205
+ try:
206
+ run_one(**kw_of(name, opts))
207
+ except typer.Exit as e:
208
+ code = int(e.exit_code or 0)
209
+ except KeyboardInterrupt:
210
+ code = 130
211
+ except BaseException as e: # noqa: BLE001 -- one engine failing must not lose the other's results
212
+ code = 1
213
+ sub = out_dir / name
214
+ where = crashlog.record(sub, f"{name} scan", e)
215
+ crashlog.mark(sub, "scan", crashlog.reason_of(e))
216
+ console.print(f"[red]{name} scan failed:[/red] {crashlog.reason_of(e)}" + (f" (traceback: {where})" if where else ""))
217
+ finally:
218
+ for stream in (sys.stdout, sys.stderr):
219
+ try:
220
+ stream.flush()
221
+ except Exception: # noqa: BLE001
222
+ pass
223
+ os._exit(code)
224
+
225
+ ctx = mp.get_context("fork")
226
+ for name in names:
227
+ link_inventory(out_dir, out_dir / name)
228
+ console.rule(f"[bold]{', '.join(engines.get(n).label for n in names)}[/bold] side by side → "
229
+ + ", ".join(str(out_dir / n) for n in names), align="left")
230
+ procs: dict = {}
231
+ try:
232
+ for i, name in enumerate(names):
233
+ if i == 1:
234
+ while not pool.planned.wait(1.0) and procs[names[0]].is_alive():
235
+ pass
236
+ options = {**options, "over_choice": options.get("over_choice") or pool.choice or "budget"}
237
+ procs[name] = ctx.Process(target=child, args=(name, options), name=f"scan-{name}")
238
+ procs[name].start()
239
+ for p in procs.values():
240
+ p.join()
241
+ except KeyboardInterrupt:
242
+ for p in procs.values():
243
+ p.join(30)
244
+ if p.is_alive():
245
+ p.terminate()
246
+ raise
247
+ return {n: "ok" if p.exitcode == 0 else "incomplete" if p.exitcode == INCOMPLETE else "failed" for n, p in procs.items()}
248
+
249
+
250
+ def agent_together(out_dir: Path, names: list[str], scan_id: str) -> dict | None:
251
+ """The agent's wall time over every engine of one scan (the union of their calls' intervals: calls side by side, of one
252
+ engine or of several, count once), from each engine's agent_ledger.json."""
253
+ spans = []
254
+ for name in names:
255
+ try:
256
+ runs = json.loads((out_dir / name / "agent_ledger.json").read_text()).get("runs") or []
257
+ except (OSError, ValueError):
258
+ continue
259
+ for r in runs:
260
+ if scan_id and r.get("run_id") != scan_id:
261
+ continue
262
+ for c in r.get("calls") or []:
263
+ try:
264
+ a = datetime.fromisoformat(str(c["at"]).replace("Z", "+00:00")).timestamp()
265
+ except (KeyError, ValueError, TypeError):
266
+ continue
267
+ if c.get("duration_s"):
268
+ spans.append((a, a + float(c["duration_s"])))
269
+ if not spans:
270
+ return None
271
+ wall, cur = 0.0, None
272
+ for a, b in sorted(spans):
273
+ if cur is None or a > cur[1]:
274
+ wall += (cur[1] - cur[0]) if cur else 0.0
275
+ cur = [a, b]
276
+ else:
277
+ cur[1] = max(cur[1], b)
278
+ wall += cur[1] - cur[0]
279
+ summed = sum(b - a for a, b in spans)
280
+ return {"wall_s": round(wall, 1), "calls": len(spans), "sum_s": round(summed, 1), "at_a_time": round(summed / wall, 2) if wall else 0}
281
+
282
+
283
+ def _in_own_process(fn, **kw) -> None:
284
+ """`fn(**kw)` in a forked process of its own, waited for; its typer.Exit code is raised here again. Discover parses
285
+ every source file: the parsers' native memory stays with the process that parsed (on a large repository well over a
286
+ gigabyte that freeing and malloc_trim do not give back), and every later stage and engine process would carry it.
287
+ The scan reads discover's result from inventory.json, so nothing is lost. In-process where fork is not available."""
288
+ import os
289
+ import sys
290
+
291
+ import typer
292
+ if not hasattr(os, "fork"):
293
+ fn(**kw)
294
+ return
295
+ import multiprocessing as mp
296
+
297
+ def child() -> None:
298
+ code = 0
299
+ try:
300
+ fn(**kw)
301
+ except typer.Exit as e:
302
+ code = int(e.exit_code or 0)
303
+ except KeyboardInterrupt:
304
+ code = 130
305
+ except BaseException: # noqa: BLE001 -- said on stderr, the parent stops with the code
306
+ import traceback
307
+ traceback.print_exc()
308
+ code = 1
309
+ finally:
310
+ for stream in (sys.stdout, sys.stderr):
311
+ try:
312
+ stream.flush()
313
+ except Exception: # noqa: BLE001
314
+ pass
315
+ os._exit(code)
316
+
317
+ p = mp.get_context("fork").Process(target=child, name="discover")
318
+ p.start()
319
+ p.join()
320
+ if p.exitcode:
321
+ raise typer.Exit(p.exitcode if p.exitcode > 0 else 1)
322
+
323
+
324
+ def scan_engines(run_one, run_discover, *, path: Path, out: Path | None, out_dir: Path, engine: str, engine_version: str | None,
325
+ include: list[str], resume: bool, offline: bool, console, options: dict, pool=None) -> None:
326
+ """Discover once, then call `run_one` (the single-engine scan) for every engine, each in its own directory: one after
327
+ the other, or with a `pool` (budget.Pool) side by side (_side_by_side)."""
328
+ import time as _time
329
+
330
+ import typer
331
+
332
+ began = _time.monotonic()
333
+ discover_s = 0.0
334
+ if not (resume and (out_dir / "inventory.json").exists()):
335
+ console.rule("[bold]discover (shared by all engines)[/bold]", align="left")
336
+ _in_own_process(run_discover, path=path, out=out, fmt="table", engine=None, include=include, limit=10,
337
+ default_engine=None, max_file_bytes=None, kinds=options.get("only"))
338
+ discover_s = _time.monotonic() - began
339
+ settings = options.pop("scan_settings", None)
340
+ inventory = json.loads((out_dir / "inventory.json").read_text())
341
+ if not offline:
342
+ from .families.cli import scan_step as families_step
343
+ families_step(path, out_dir, inventory, console) # statement families of run-time-built sites (families.json)
344
+ names, counts = pick(engine, inventory, include, settings)
345
+ # the statements discover left without an engine: given one by the tables they read or the repository's engine
346
+ facts = None
347
+ try:
348
+ from .realdb import facts as facts_mod
349
+ if (out_dir / "db_catalog.json").exists():
350
+ facts = facts_mod.load(out_dir) or None
351
+ except Exception: # noqa: BLE001 -- no pull: the repository's schema decides alone
352
+ facts = None
353
+ given = default_engines(inventory, names, settings, facts) if names else {}
354
+ if given:
355
+ (out_dir / "inventory.json").write_text(json.dumps(inventory, indent=1, ensure_ascii=False))
356
+ console.print("Statements with no engine of their own: " + ", ".join(f"{n} {c}" for n, c in given.items())
357
+ + " (by the tables they read, else the repository's engine; [scan] default_engine sets it).")
358
+ names, counts = pick(engine, inventory, include, settings)
359
+ console.print("SELECT sites: " + ", ".join(f"{n} {c}" for n, c in counts.items())
360
+ + f". Running: {', '.join(names) or 'none'}.")
361
+ if not names and engine.strip().lower() == "auto" and not offline:
362
+ # no engine has SELECT sites (a repository of writes only, or of the other kinds of finding): one scan of the
363
+ # repository's own engine, as a named engine runs it, so its other stages still run
364
+ choice = (((inventory.get("summary") or {}).get("engine_default") or {}).get("choice") or {}).get("engine") or ""
365
+ names = [choice if choice in engines.supported() else "clickhouse"]
366
+ if offline or not names:
367
+ return
368
+ if len(names) == 1 and engine.strip().lower() == "auto":
369
+ # one engine: the single-engine layout (stage files in the out dir), as `--engine <name>` writes it
370
+ try:
371
+ run_one(path=path, out=out, engine=names[0], engine_version=engine_version, include=include, resume=resume, offline=False,
372
+ scan_id=None, skip_discover=True, **options)
373
+ finally:
374
+ family_outcomes(path, out_dir, console)
375
+ return
376
+ version_of = versions(engine_version, names)
377
+ # One scan, however many engines: every engine's run carries the same id, so the console lists them as one row.
378
+ scan_id = (live.load_scan_id(out_dir) if resume else "") or live.new_scan_id()
379
+ live.save_scan_id(out_dir, scan_id)
380
+ index = {"schema_version": 1, "generated_at": datetime.now(timezone.utc).isoformat(timespec="seconds"), "scan_id": scan_id,
381
+ "engines": []}
382
+ # side by side (a pool: one gate, one budget, one sandbox at a time): every engine at once, each in its own process
383
+ done = _side_by_side(run_one, names, pool, out_dir, console,
384
+ lambda name, opts: dict(path=path, out=out_dir / name, engine=name, engine_version=version_of.get(name),
385
+ include=include, resume=resume, offline=False, scan_id=scan_id, skip_discover=True,
386
+ **opts), options) if pool is not None and len(names) > 1 else None
387
+ for name in names:
388
+ sub = out_dir / name
389
+ link_inventory(out_dir, sub)
390
+ if done is None:
391
+ console.rule(f"[bold]{engines.get(name).label}[/bold] → {sub}", align="left")
392
+ status = "ok" if done is None else done[name]
393
+ try:
394
+ # discover ran once for all engines; the run budget is one for the whole scan: each engine gets what is left
395
+ if done is None:
396
+ run_one(path=path, out=sub, engine=name, engine_version=version_of.get(name), include=include, resume=resume,
397
+ offline=False, scan_id=scan_id, skip_discover=True, **options)
398
+ except typer.Exit as e:
399
+ status = "ok" if not e.exit_code else "incomplete" if e.exit_code == INCOMPLETE else "failed"
400
+ except Exception as e: # one engine failing must not lose the other's results
401
+ status = "failed"
402
+ where = crashlog.record(sub, f"{name} scan", e)
403
+ crashlog.mark(sub, "scan", crashlog.reason_of(e))
404
+ console.print(f"[red]{name} scan failed:[/red] {crashlog.reason_of(e)}" + (f" (traceback: {where})" if where else ""))
405
+ spent = _spent(sub)
406
+ left = _left(options.get("budget"), spent) if done is None else None
407
+ if left is not None:
408
+ options = {**options, "budget": left}
409
+ missed = crashlog.lines(sub)
410
+ if missed and status == "ok":
411
+ status = "incomplete"
412
+ index["engines"].append({"engine": name, "dir": name, "status": status, "select_sites": counts.get(name, 0), **summarize(sub),
413
+ **({"agent_spent_usd": round(spent, 4)} if spent else {}),
414
+ **({"could_not_finish": missed} if missed else {})})
415
+ (out_dir / "engines.json").write_text(json.dumps(index, indent=1))
416
+ # where the whole scan's time went: each engine's own timings.json under one total
417
+ per = {}
418
+ for e in index["engines"]:
419
+ try:
420
+ per[e["engine"]] = json.loads((out_dir / e["dir"] / "timings.json").read_text())
421
+ except (OSError, ValueError):
422
+ per[e["engine"]] = None
423
+ together = agent_together(out_dir, names, scan_id)
424
+ (out_dir / "timings.json").write_text(json.dumps({"schema_version": 1, "total_s": round(_time.monotonic() - began, 1),
425
+ "discover_s": round(discover_s, 1), "side_by_side": done is not None,
426
+ **({"agent": together} if together else {}), "engines": per}, indent=1))
427
+ family_outcomes(path, out_dir, console)
428
+ from . import coverage as coverage_mod
429
+ whole = coverage_mod.refresh_engines(out_dir) # one coverage number for the whole repository
430
+ console.rule("[bold]engines[/bold]", align="left")
431
+ if whole:
432
+ console.print(f" repository: {coverage_mod.one_line(whole)} → {out_dir / 'coverage.json'}")
433
+ for e in index["engines"]:
434
+ console.print(f" {e['engine']}: {e['status']}, reached {e['stage']}, {e['findings']} findings {e['by_status'] or ''} → {out_dir / e['dir']}")
435
+ for line in e.get("could_not_finish") or []:
436
+ console.print(f" {line}", markup=False, highlight=False)
437
+ console.print(f"Index: [bold]{out_dir / 'engines.json'}[/bold]. Upload one engine with `codecop push --out {out_dir}/<engine>`.")
438
+ bad = [e for e in index["engines"] if e["status"] != "ok"]
439
+ if bad:
440
+ logs = [str(out_dir / e["dir"] / crashlog.ERRORS_FILE) for e in bad if (out_dir / e["dir"] / crashlog.ERRORS_FILE).exists()]
441
+ console.print(f"[red]Not complete:[/red] {', '.join(e['engine'] + ' ' + e['status'] for e in bad)}."
442
+ + (f" Tracebacks: {', '.join(logs)}" if logs else ""))
443
+ raise typer.Exit(INCOMPLETE)