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/apply/check.py ADDED
@@ -0,0 +1,344 @@
1
+ """`codecop apply --check`: run a plan end to end on the sandbox and say what happened.
2
+
3
+ Only ever a sandbox container this process started (engines/): never a database from an env file.
4
+
5
+ For each plan the finding's tables are rebuilt and loaded as the benchmark loaded them, then the plan's own
6
+ statements run in order. A plan passes when every step ran, every verification query came back as the plan
7
+ says it must, the benchmarked query reads what the benchmark measured for the variant (within a tolerance,
8
+ because merges are not deterministic) with the same result, and the rollback did what it says.
9
+
10
+ A re-key is also exercised the way production would: rows are inserted into the table while the migration
11
+ is in flight (after the forwarding view exists, after the backfill, after the swap), a view on the table
12
+ counts every insert it sees, and the swap is undone and redone before the old copy is dropped.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import re
18
+ import time
19
+ from datetime import datetime, timezone
20
+
21
+ from .. import __version__, engines
22
+ from ..engines.base import QueryError, SandboxError
23
+ from .common import short
24
+ from .html import fingerprint
25
+
26
+ TOLERANCE = 1.25 # the migrated table may read this much more than the benchmark's variant did
27
+ SLACK = {"clickhouse": 16384, "postgres": 100} # ...or this many rows more (two granules; a few heap pages), whichever is larger
28
+ LIVE_ROWS = 1000
29
+
30
+
31
+ def evaluate(results: list[list[dict]], expect: dict | None) -> tuple[bool, str]:
32
+ """Does a read step's result look the way the plan says? `expect` is the plan's small vocabulary:
33
+ statement (which statement's rows, default the last), min_rows, max_rows, every {column: value}, every_in {column: [values]}."""
34
+ if not expect or "measure" in expect:
35
+ return True, ""
36
+ rows = results[expect.get("statement", len(results) - 1)] if results else []
37
+ if "min_rows" in expect and len(rows) < expect["min_rows"]:
38
+ return False, f"{len(rows)} rows, expected at least {expect['min_rows']}"
39
+ if "max_rows" in expect and len(rows) > expect["max_rows"]:
40
+ return False, f"{len(rows)} rows, expected at most {expect['max_rows']}"
41
+ for column, value in (expect.get("every") or {}).items():
42
+ bad = [r for r in rows if _norm(r.get(column)) != _norm(value)]
43
+ if bad:
44
+ return False, f"{len(bad)} of {len(rows)} rows have {column} != {value}"
45
+ for column, values in (expect.get("every_in") or {}).items():
46
+ bad = [r.get(column) for r in rows if r.get(column) not in values]
47
+ if bad or not rows:
48
+ return False, f"{column} is {bad[0] if bad else 'missing'}, expected one of {', '.join(map(str, values))}"
49
+ return True, f"{len(rows)} row{'s' if len(rows) != 1 else ''} as expected"
50
+
51
+
52
+ def _norm(value):
53
+ if isinstance(value, bool):
54
+ return "1" if value else "0"
55
+ return str(value).lower() if isinstance(value, str) and value.lower() in ("true", "false") else str(value)
56
+
57
+
58
+ class Runner:
59
+ """Runs one plan's statements on a sandbox, adapting only what a single-node sandbox forces."""
60
+
61
+ def __init__(self, sb, engine: str):
62
+ self.sb, self.engine = sb, engine
63
+
64
+ def change(self, sql: str, settings: dict | None = None) -> None:
65
+ if self.engine == "clickhouse":
66
+ from ..engines.clickhouse import plain_engine
67
+ if re.match(r"\s*CREATE\s+TABLE", sql, re.I):
68
+ sql = plain_engine(sql) # Replicated*/Shared* need a cluster; the sandbox is one server
69
+ self.sb.execute(sql, settings=settings or None)
70
+ else:
71
+ self.sb.execute(sql)
72
+
73
+ def read(self, sql: str) -> list[dict]:
74
+ return self.sb.rows(sql)
75
+
76
+ def scalar(self, sql: str):
77
+ rows = self.read(sql)
78
+ return next(iter(rows[0].values())) if rows else None
79
+
80
+
81
+ def _measure(sb, sql: str, params: dict) -> dict:
82
+ m = sb.measure(sql, params, 1)
83
+ return {"ok": m.ok, "error": m.error[:300], "read_rows": m.read_rows, "read_bytes": m.read_bytes, "result_rows": m.result_rows,
84
+ "result_hash": m.result_hash}
85
+
86
+
87
+ def _compare(engine: str, expected: dict, before: dict, after: dict, reference_hash: str, same_results: bool) -> dict:
88
+ out = {"before": {k: before.get(k) for k in ("read_rows", "read_bytes", "result_rows")},
89
+ "after": {k: after.get(k) for k in ("read_rows", "read_bytes", "result_rows")},
90
+ "bench": {k: expected.get(k) for k in ("read_rows", "read_bytes", "baseline_read_rows", "table_rows")} if expected.get("read_rows") is not None else None,
91
+ "ok": False, "detail": ""}
92
+ if not after["ok"]:
93
+ out["detail"] = "the query failed: " + after["error"][:200]
94
+ return out
95
+ if out["bench"]:
96
+ limit = max(expected["read_rows"] * TOLERANCE, expected["read_rows"] + SLACK.get(engine, 100))
97
+ reads_ok = after["read_rows"] <= limit
98
+ out["limit_rows"] = int(limit)
99
+ word = f"reads {after['read_rows']:,} rows; the benchmark measured {expected['read_rows']:,} for this variant"
100
+ else:
101
+ reads_ok = before["ok"] and after["read_rows"] <= before["read_rows"] * 0.8
102
+ word = f"reads {after['read_rows']:,} rows, {before.get('read_rows', 0):,} before"
103
+ results_ok = (not same_results) or not reference_hash or after["result_hash"] == reference_hash
104
+ out["same_results"] = None if not same_results or not reference_hash else results_ok
105
+ out["ok"] = reads_ok and results_ok
106
+ out["detail"] = word + ("" if results_ok else "; the result differs from before the migration")
107
+ return out
108
+
109
+
110
+ def _live_column(sb, table: str, key: list[str], partition_by: str) -> tuple[str, str] | None:
111
+ """A sorting-key column whose value can be changed to make rows that are new, without moving them to another partition."""
112
+ types = sb.column_types(table)
113
+ for part in key:
114
+ name = part.strip("`")
115
+ typ = types.get(name, "")
116
+ if name not in types or re.search(rf"\b{re.escape(name)}\b", partition_by or ""):
117
+ continue
118
+ if re.fullmatch(r"(?:LowCardinality\()?String\)?", typ):
119
+ return name, f"concat({name}, '~codecop-live-{{n}}')"
120
+ if re.fullmatch(r"U?Int64", typ):
121
+ return name, f"{name} + 1000000007 * {{n}}"
122
+ return None
123
+
124
+
125
+ def _check_rekey(run: Runner, plan: dict, finding: dict, result: dict, log) -> None:
126
+ """A re-key, with writes arriving while it runs. Fills result["steps"], ["probes"], ["measure"], ["rollback"]."""
127
+ sb = run.sb
128
+ table, new_table = plan["table"], plan["new_table"]
129
+ final = " FINAL" if any("FINAL" in s for st in plan["steps"] if st["id"] == "verify_counts" for s in st["sql"]) else ""
130
+ count = lambda t: int(run.scalar(f"SELECT count() AS n FROM {t}{final}")) # noqa: E731
131
+ key_of = lambda t: run.scalar(f"SELECT sorting_key FROM system.tables WHERE database = currentDatabase() AND name = '{short(t)}'") # noqa: E731
132
+ squash = lambda text: re.sub(r"\s+", "", str(text or "")) # noqa: E731
133
+ probes = result["probes"]
134
+ steps = {s["id"]: s for s in plan["steps"]}
135
+ old_key_text, start_rows = key_of(table), count(table)
136
+ partition_by = run.scalar(f"SELECT partition_key FROM system.tables WHERE database = currentDatabase() AND name = '{short(table)}'") or ""
137
+ live = _live_column(sb, table, plan["old_key"], partition_by)
138
+ probe_view, probe_table = f"{table}__codecop_probe_mv", f"{table}__codecop_probe"
139
+ run.change(f"CREATE TABLE {probe_table} (k UInt8, n UInt64) ENGINE = SummingMergeTree ORDER BY k")
140
+ run.change(f"CREATE MATERIALIZED VIEW {probe_view} TO {probe_table} AS SELECT 1 AS k, count() AS n FROM {table}")
141
+ written = 0
142
+
143
+ def write_live(n: int, label: str) -> None:
144
+ """Insert rows into the table the application writes to, as production would while the migration runs."""
145
+ nonlocal written
146
+ if not live:
147
+ probes.append({"id": f"live_{n}", "label": label, "ok": None, "detail": "skipped: no key column this probe can vary"})
148
+ return
149
+ before = count(table)
150
+ # new rows land where production's would: in the newest partition
151
+ newest = run.scalar(f"SELECT max(partition_id) AS p FROM system.parts WHERE active AND database = currentDatabase() AND table = '{short(table)}'")
152
+ run.change(f"INSERT INTO {table} SELECT * REPLACE ({live[1].format(n=n)} AS {live[0]}) FROM {table} WHERE _partition_id = '{newest}' LIMIT {LIVE_ROWS}")
153
+ added = count(table) - before
154
+ written += added
155
+ probes.append({"id": f"live_{n}", "label": label, "ok": added == LIVE_ROWS, "detail": f"{added:,} new rows written to {short(table)}"})
156
+
157
+ def verify(label: str, pid: str) -> None:
158
+ ok, detail = evaluate([run.read(steps["verify_checksums"]["sql"][0])], steps["verify_checksums"]["expect"])
159
+ probes.append({"id": pid, "label": label, "ok": ok, "detail": "row counts and checksums equal in every partition" if ok else detail})
160
+
161
+ reference = {"hash": ""}
162
+
163
+ def after(step_id: str) -> None:
164
+ if step_id == "catch_up" and plan.get("collapses_duplicates"):
165
+ write_live(1, "Writes after the forwarding view, before the backfill")
166
+ elif step_id == "catch_up":
167
+ # the plan itself asks for a write pause while a partition is copied: a row written now would be copied twice
168
+ probes.append({"id": "live_1", "label": "Writes during the backfill", "ok": None,
169
+ "detail": "not tried: this engine keeps duplicates, and the plan asks for a write pause while a partition is copied"})
170
+ elif step_id == "backfill":
171
+ write_live(2, "Writes after the backfill")
172
+ elif step_id == "verify_checksums":
173
+ reference["hash"] = _measure(sb, finding["baseline_sql"], finding.get("params") or {})["result_hash"]
174
+ elif step_id == "swap":
175
+ now = key_of(table)
176
+ probes.append({"id": "key_after_swap", "label": "The table has the new key", "ok": squash(now) != squash(old_key_text) and squash(now) == key_of_plan,
177
+ "detail": f"ORDER BY ({now})"})
178
+ elif step_id == "confirm":
179
+ write_live(3, "Writes after the swap")
180
+ verify("Old-key copy still current after the swap", "old_copy_current")
181
+ seen = int(run.scalar(f"SELECT sum(n) AS n FROM {probe_table}") or 0)
182
+ probes.append({"id": "views_follow", "label": "A view on the table saw every insert once", "ok": seen == written,
183
+ "detail": f"{seen:,} rows seen by the view, {written:,} written"})
184
+
185
+ def before(step_id: str) -> None:
186
+ if step_id == "cleanup":
187
+ # the rollback drill: undo the swap, look, then redo it so the cleanup step runs on the swapped state
188
+ undo = next(r for r in plan["rollback"] if r["when"].startswith("after the swap"))
189
+ for sql in undo["sql"]:
190
+ run.change(sql)
191
+ back, rows = key_of(table), count(table)
192
+ ok = squash(back) == squash(old_key_text) and rows == start_rows + written
193
+ verify("Both copies equal after undoing the swap", "rollback_equal")
194
+ result["rollback"] = {"ok": ok and probes[-1]["ok"], "detail": f"swap undone: ORDER BY ({back}), {rows:,} rows, none lost"
195
+ if ok else f"after undoing the swap: ORDER BY ({back}), {rows:,} rows, expected {start_rows + written:,}"}
196
+ for sql in steps["swap"]["sql"]:
197
+ run.change(sql)
198
+ run.change(f"DROP VIEW IF EXISTS {probe_view}")
199
+ run.change(f"DROP TABLE IF EXISTS {probe_table}")
200
+
201
+ key_of_plan = squash(", ".join(plan["new_key"]))
202
+ _run_steps(run, plan, finding, result, log, after=after, before=before, reference=reference)
203
+ if result["steps"] and result["steps"][-1]["id"] == "cleanup" and result["steps"][-1]["ok"]:
204
+ left = int(run.scalar(f"SELECT count() AS n FROM system.tables WHERE database = currentDatabase() AND name IN ('{short(new_table)}', '{short(new_table)}_feed')"))
205
+ rows = count(table)
206
+ probes.append({"id": "end_state", "label": "End state", "ok": left == 0 and rows == start_rows + written and squash(key_of(table)) == key_of_plan,
207
+ "detail": f"{short(table)}: ORDER BY ({key_of(table)}), {rows:,} rows; the copy and the view are gone"})
208
+
209
+
210
+ def _run_steps(run: Runner, plan: dict, finding: dict, result: dict, log, *, after=lambda step_id: None, before=lambda step_id: None,
211
+ reference: dict | None = None) -> None:
212
+ sb = run.sb
213
+ params = finding.get("params") or {}
214
+ variant_same = plan.get("same_results", True)
215
+ first = _measure(sb, finding["baseline_sql"], params)
216
+ result["baseline"] = {k: first.get(k) for k in ("ok", "read_rows", "read_bytes", "result_rows")}
217
+ reference = reference if reference is not None else {"hash": first["result_hash"]}
218
+ failed = False
219
+ for s in plan["steps"]:
220
+ rec = {"n": s["n"], "id": s["id"], "ok": False, "ms": 0.0, "detail": "", "statements": 0}
221
+ result["steps"].append(rec)
222
+ if failed:
223
+ rec["detail"] = "not run: an earlier step failed"
224
+ rec["skipped"] = True
225
+ continue
226
+ started = time.monotonic()
227
+ try:
228
+ before(s["id"])
229
+ measure = (s.get("expect") or {}).get("measure")
230
+ if measure:
231
+ got = _measure(sb, measure["sql"], measure.get("params") or params)
232
+ result["measure"] = _compare(run.engine, measure, first, got, reference["hash"], variant_same)
233
+ rec.update(ok=result["measure"]["ok"], detail=result["measure"]["detail"], statements=1)
234
+ else:
235
+ results = []
236
+ for sql in s["sql"]:
237
+ if s["effect"] == "read":
238
+ results.append(run.read(sql))
239
+ else:
240
+ run.change(sql, s.get("sandbox_settings"))
241
+ rec["statements"] += 1
242
+ pp = s.get("per_partition")
243
+ if pp:
244
+ ids = [str(r["partition_id"]) for r in run.read(pp["list_sql"])]
245
+ ids = ids[-1:] if pp.get("scope") == "newest" else ids
246
+ for pid in ids:
247
+ run.change(pp["template"].replace("{partition_id}", pid), s.get("sandbox_settings"))
248
+ rec["statements"] += len(ids)
249
+ rec["detail"] = "ran for the newest sandbox partition" if pp.get("scope") == "newest" else f"ran once per sandbox partition ({len(ids)})"
250
+ ok, detail = evaluate(results, s.get("expect"))
251
+ rec.update(ok=ok, detail=detail or rec["detail"])
252
+ if rec["ok"]:
253
+ after(s["id"])
254
+ except QueryError as e:
255
+ rec.update(ok=False, detail=str(e)[:300])
256
+ rec["ms"] = round((time.monotonic() - started) * 1000, 1)
257
+ log(f"{plan['finding']} step {s['n']} {s['id']}: {'ok' if rec['ok'] else 'FAILED'} {rec['detail'][:120]}")
258
+ failed = failed or not rec["ok"]
259
+
260
+
261
+ def _exists_sql(engine: str, plan: dict) -> list[tuple[str, str]]:
262
+ """Queries that return 0 when what the plan built is gone, for the rollback drill."""
263
+ out = []
264
+ if engine == "postgres":
265
+ for name in plan.get("indexes") or []:
266
+ out.append((name, f"SELECT count(*) AS n FROM pg_class WHERE oid = to_regclass('{name}')"))
267
+ else:
268
+ for s in plan["steps"]:
269
+ m = re.match(r"\s*ALTER\s+TABLE\s+([`\"\w.]+)\s+ADD\s+(PROJECTION|INDEX)\s+(?:IF\s+NOT\s+EXISTS\s+)?([`\"\w]+)", (s["sql"] or [""])[0], re.I)
270
+ if m:
271
+ system = "projections" if m.group(2).upper() == "PROJECTION" else "data_skipping_indices"
272
+ out.append((m.group(3), f"SELECT count() AS n FROM system.{system} WHERE database = currentDatabase() AND table = '{short(m.group(1))}' "
273
+ f"AND name = '{short(m.group(3))}'"))
274
+ return out
275
+
276
+
277
+ def _check_simple(run: Runner, plan: dict, finding: dict, result: dict, log) -> None:
278
+ """An index, a projection, or statements run as written: the steps, then the rollback, then a look that it is gone."""
279
+ _run_steps(run, plan, finding, result, log)
280
+ if not all(s["ok"] for s in result["steps"]):
281
+ return
282
+ undo = next((r for r in plan["rollback"] if r["possible"] and r["sql"]), None)
283
+ if not undo:
284
+ return
285
+ try:
286
+ for sql in undo["sql"]:
287
+ run.change(sql, {"mutations_sync": 2} if run.engine == "clickhouse" else None)
288
+ left = [(name, int(run.scalar(sql) or 0)) for name, sql in _exists_sql(run.engine, plan)]
289
+ still = [name for name, n in left if n]
290
+ result["rollback"] = {"ok": not still, "detail": (f"{', '.join(n for n, _ in left)} dropped" if left else "rollback statements ran")
291
+ if not still else f"still there after the rollback: {', '.join(still)}"}
292
+ except QueryError as e:
293
+ result["rollback"] = {"ok": False, "detail": str(e)[:300]}
294
+
295
+
296
+ def run(findings: dict, plans: list[dict], *, bench: dict | None = None, engine_version: str | None = None, runtime: str | None = None,
297
+ log=lambda msg: None) -> dict:
298
+ """Validate every plan with steps on one sandbox. Returns check.json's content."""
299
+ from .. import bench as bench_mod
300
+
301
+ engine_name = findings["engine"]
302
+ engine = engines.get(engine_name)
303
+ version = engine_version or findings.get("engine_version") or ""
304
+ out = {"schema_version": 1, "tool_version": __version__, "generated_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
305
+ "engine": engine_name, "engine_version": version, "where": "local sandbox container", "tolerance": TOLERANCE, "results": []}
306
+ # an advisor plan (advisor.json) has no finding to rebuild the sandbox from: `codecop bench` built and measured it already
307
+ todo = [p for p in plans if p.get("steps") and p["finding"] in {f["finding"] for f in findings["findings"]}]
308
+ if not todo:
309
+ return out
310
+ max_rows = (bench or {}).get("max_rows") or max((t.get("target_rows") or 0 for t in findings.get("sandbox_tables") or []), default=2_000_000)
311
+ fraction = ((bench or {}).get("scales") or [{}])[-1].get("fraction") or 1.0
312
+ profile = {"tables": findings.get("profile") or []}
313
+ by_id = {f["finding"]: f for f in findings["findings"]}
314
+ with engine.sandbox(version, runtime=runtime) as sb:
315
+ out["server_version"], out["runtime"] = sb.server_version(), sb.runtime
316
+ runner = Runner(sb, engine_name)
317
+ for plan in todo:
318
+ finding = by_id[plan["finding"]]
319
+ result = {"finding": plan["finding"], "recipe": plan["recipe"], "fingerprint": fingerprint(plan), "ok": False, "steps": [], "probes": [], "measure": None, "rollback": None,
320
+ "tables": [], "error": ""}
321
+ out["results"].append(result)
322
+ started = time.monotonic()
323
+ try:
324
+ definitions = [d for d in findings.get("table_definitions") or [] if d["name"] in finding["tables"]]
325
+ loaded = bench_mod.load_tables(sb, {"table_definitions": definitions, "candidates": [finding]}, profile, max_rows, fraction, log)
326
+ result["tables"] = [{"name": t["name"], "rows": t.get("rows", 0), "ok": t["ok"], "error": t.get("error", "")[:200]} for t in loaded]
327
+ if not all(t["ok"] for t in loaded):
328
+ result["error"] = "a table could not be built on the sandbox"
329
+ continue
330
+ (_check_rekey if plan["recipe"] == "rekey" else _check_simple)(runner, plan, finding, result, log)
331
+ except (QueryError, SandboxError) as e:
332
+ result["error"] = str(e)[:400]
333
+ if isinstance(e, SandboxError):
334
+ try:
335
+ sb.revive()
336
+ except SandboxError:
337
+ break
338
+ finally:
339
+ result["duration_s"] = round(time.monotonic() - started, 1)
340
+ result["ok"] = (not result["error"] and bool(result["steps"]) and all(s["ok"] for s in result["steps"])
341
+ and all(p["ok"] is not False for p in result["probes"]) and (result["measure"] or {}).get("ok", False)
342
+ and (result["rollback"] or {"ok": True})["ok"])
343
+ out["ok"] = bool(out["results"]) and all(r["ok"] for r in out["results"])
344
+ return out
codecop/apply/cli.py ADDED
@@ -0,0 +1,162 @@
1
+ """`codecop apply`: write the migration plan or the patch for verified findings. Writes files; runs nothing on a real database."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from pathlib import Path
7
+ from typing import Optional
8
+
9
+ import typer
10
+ from rich.console import Console
11
+ from rich.table import Table
12
+
13
+ from . import APPLY_DIR, CHECK_FILE, build, load, write
14
+ from .common import human_bytes, human_duration
15
+ from .html import fingerprint, inject
16
+
17
+ console = Console()
18
+ err = Console(stderr=True)
19
+
20
+
21
+ def decorate(out_dir: Path) -> int:
22
+ """Add the plans in <out>/apply/ to <out>/report.html, if both are there. Returns how many were placed."""
23
+ report, findings_path = out_dir / "report.html", out_dir / "findings.json"
24
+ plan_doc, check_doc = load(out_dir)
25
+ if not plan_doc or not report.exists() or not findings_path.exists():
26
+ return 0
27
+ findings = json.loads(findings_path.read_text())
28
+ ids = {f["finding"]: f["id"] for f in findings["findings"]}
29
+ # a table suggestion's plan is filed under its id and its fingerprint (identity across runs)
30
+ ids.update({s["id"]: s.get("fingerprint") or s["id"] for s in findings.get("table_suggestions") or [] if s.get("id")})
31
+ page, placed = inject(report.read_text(), plan_doc, check_doc, ids)
32
+ if placed:
33
+ report.write_text(page)
34
+ return placed
35
+
36
+
37
+ def render_report(out_dir: Path) -> int:
38
+ """report.html again from findings.json, with the plans in it."""
39
+ from .. import patterns_view, report as report_mod
40
+
41
+ findings = json.loads((out_dir / "findings.json").read_text())
42
+ pats = patterns_view.load(out_dir) or patterns_view.load(out_dir.parent)
43
+ detail = int(((pats or {}).get("settings") or {}).get("report_detail") or 30)
44
+ from .. import advisor_view, advisors
45
+ (out_dir / "report.html").write_text(report_mod.render_html(findings, patterns_view.html_section(pats, detail)
46
+ + advisor_view.html_section(advisors.load(out_dir), detail)))
47
+ return decorate(out_dir)
48
+
49
+
50
+ def _estimate(plan: dict) -> str:
51
+ est = plan.get("estimates") or {}
52
+ bits = []
53
+ if est.get("duration_s"):
54
+ bits.append(f"{human_duration(est['duration_s']['low'])} to {human_duration(est['duration_s']['high'])}")
55
+ if est.get("extra_disk_bytes"):
56
+ bits.append(f"+{human_bytes(est['extra_disk_bytes'])}")
57
+ return ", ".join(bits) + (" (estimate)" if bits else "")
58
+
59
+
60
+ def _trial(out_dir: Path, wanted: list[str]) -> None:
61
+ from .. import advisors
62
+ from ..realdb import CATALOG_FILE
63
+ from . import trial as trial_mod
64
+ stage = advisors.load(out_dir)
65
+ doc = advisors.doc_of(stage, "clickhouse") if stage else None
66
+ if not doc:
67
+ err.print(f"[red]No ClickHouse advisor document in {out_dir / 'advisor.json'}.[/red] Run `codecop advise` first.")
68
+ raise typer.Exit(2)
69
+ catalog = json.loads((out_dir / CATALOG_FILE).read_text()) if (out_dir / CATALOG_FILE).exists() else None
70
+ picked = trial_mod.chosen(doc, wanted)
71
+ if not picked:
72
+ err.print("[yellow]No skip index or projection to trial[/yellow]" + (" by that id." if wanted else
73
+ ": none was counted on production with a gain or verified. Name one with --finding TS-..."))
74
+ raise typer.Exit(0 if not wanted else 2)
75
+ trials = [trial_mod.plan(s, doc, catalog) for s in picked]
76
+ files = trial_mod.write(out_dir, trials)
77
+ for t in trials:
78
+ console.print(trial_mod.text(t), markup=False, highlight=False, soft_wrap=True)
79
+ console.print(f"Wrote {len(files)} trial file(s) under [bold]{out_dir / APPLY_DIR / trial_mod.TRIAL_DIR}[/bold]. Nothing was run.")
80
+
81
+
82
+ def apply(
83
+ path: Path = typer.Argument(Path("."), help="Repository that was scanned. Read only: patches are written to the out dir."),
84
+ out: Optional[Path] = typer.Option(None, "--out", help="Directory holding findings.json. Plans go to <out>/apply/. Default: <path>/.codecop"),
85
+ finding: list[str] = typer.Option([], "--finding", help="Only this finding (Q-001). Repeatable. Default: every finding with a verified variant."),
86
+ variant: Optional[int] = typer.Option(None, "--variant", help="With --finding: plan this variant (1 = the first shown) instead of the best verified one."),
87
+ check: bool = typer.Option(False, "--check", help="Run each plan end to end on the local sandbox container and compare with the benchmark."),
88
+ engine_version: Optional[str] = typer.Option(None, "--engine-version", help="Sandbox image version for --check. Default: the one the scan used."),
89
+ trial: bool = typer.Option(False, "--trial", help="ClickHouse skip index or projection: write how to prove it on ONE production "
90
+ "partition (ADD, MATERIALIZE IN PARTITION, the comparison, DROP) with its estimated build cost. Text only: "
91
+ "CodeCop runs none of it. Default: every one counted on production with a gain (--finding TS-003 for one)."),
92
+ ) -> None:
93
+ """Write a reviewable migration plan (ordered SQL files + plan.json) or a patch for each verified finding.
94
+
95
+ Nothing is run against a real database and nothing is written to the repository. --check runs the plan on the sandbox."""
96
+ root = path.resolve()
97
+ out_dir = out or (root / ".codecop")
98
+ if trial is True:
99
+ return _trial(out_dir, finding)
100
+ if not (out_dir / "findings.json").exists():
101
+ err.print(f"[red]No findings.json in {out_dir}.[/red] Run `codecop report` (or `codecop scan`) first.")
102
+ raise typer.Exit(2)
103
+ if variant is not None and len(finding) != 1:
104
+ err.print("[red]--variant needs exactly one --finding.[/red]")
105
+ raise typer.Exit(2)
106
+ doc = build(out_dir, only=finding, variant=None if variant is None else variant - 1, repo=root)
107
+ if not doc["plans"]:
108
+ err.print("[yellow]Nothing to plan.[/yellow] " + "; ".join(f"{s['finding']}: {s['reason']}" for s in doc["skipped"][:6]))
109
+ raise typer.Exit(0 if not finding else 2)
110
+ previous_plans, previous_check = load(out_dir)
111
+ planned = list(doc["plans"]) # what this run was asked for; --check runs only these
112
+ if finding and previous_plans and previous_plans.get("schema_version") == doc["schema_version"]:
113
+ # one finding re-planned: the others keep the plan they had
114
+ mine = {p["finding"] for p in doc["plans"]}
115
+ doc["plans"] = sorted(doc["plans"] + [p for p in previous_plans["plans"] if p["finding"] not in mine], key=lambda p: p["finding"])
116
+ doc["skipped"] += [x for x in previous_plans.get("skipped") or [] if x["finding"] not in mine and x["finding"] not in {y["finding"] for y in doc["skipped"]}]
117
+ files = write(out_dir, doc)
118
+ check_doc = None
119
+ if check:
120
+ from ..engines.base import SandboxError
121
+ from . import check as check_mod
122
+
123
+ findings = json.loads((out_dir / "findings.json").read_text())
124
+ bench = json.loads((out_dir / "bench.json").read_text()) if (out_dir / "bench.json").exists() else None
125
+ try:
126
+ check_doc = check_mod.run(findings, planned, bench=bench, engine_version=engine_version, log=lambda msg: err.print(f"[dim] {msg}[/dim]"))
127
+ except SandboxError as e:
128
+ err.print(f"[red]Sandbox failed:[/red] {e}")
129
+ raise typer.Exit(1)
130
+ ran = {r["finding"] for r in check_doc["results"]}
131
+ check_doc["results"] += [r for r in (previous_check or {}).get("results") or [] if r["finding"] not in ran]
132
+ (out_dir / APPLY_DIR / CHECK_FILE).write_text(json.dumps(check_doc, indent=1, ensure_ascii=False))
133
+ else:
134
+ _, check_doc = load(out_dir)
135
+ results = {r["finding"]: r for r in (check_doc or {}).get("results") or []}
136
+ table = Table(title="Plans", title_justify="left")
137
+ for col in ("finding", "delivered as", "plan", "steps", "estimate", "code change", "sandbox check"):
138
+ table.add_column(col, overflow="fold")
139
+ for p in doc["plans"]:
140
+ patch = p.get("patch")
141
+ code = ("-" if not patch else "diff: located exactly" if patch["status"] == "exact" else
142
+ "diff + reorder bound arguments" if patch["status"] == "needs_argument_change" else f"no diff: {patch['reason']}")
143
+ if not patch and p.get("code"):
144
+ code = p["code"]["call_sites"][0]["change"]
145
+ r = results.get(p["finding"])
146
+ if r and r.get("fingerprint") != fingerprint(p):
147
+ r = None
148
+ irreversible = sum(1 for s in p["steps"] if not s["reversible"])
149
+ table.add_row(
150
+ p["finding"], p["delivery"], p["recipe"].replace("_", " ") if p["status"] == "planned" else f"[red]no plan[/red]: {p['reason']}",
151
+ f"{len(p['steps'])} ({irreversible} not reversible)" if p["steps"] else "-", _estimate(p) or "-", code,
152
+ "-" if not p["steps"] else "not run" if not r else "[green]passed[/green]" if r["ok"] else
153
+ "[red]failed[/red]: " + (r.get("error") or next((s["detail"] for s in r["steps"] if not s["ok"]), "") or
154
+ next((x["detail"] for x in r["probes"] if x["ok"] is False), "") or ((r.get("measure") or {}).get("detail", "")))[:160])
155
+ console.print(table)
156
+ for s in doc["skipped"]:
157
+ console.print(f"[dim]{s['finding']}: not planned, {s['reason']}[/dim]")
158
+ placed = render_report(out_dir)
159
+ console.print(f"Wrote {len(files)} files under [bold]{out_dir / APPLY_DIR}[/bold]. Nothing was run on a real database; the repository was not changed.")
160
+ console.print(f"Report: [bold]{out_dir / 'report.html'}[/bold] ({placed} plan{'s' if placed != 1 else ''} shown)")
161
+ if check and not all(results[p["finding"]]["ok"] for p in planned if p["steps"] and p["finding"] in results):
162
+ raise typer.Exit(1)