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
@@ -0,0 +1,379 @@
1
+ """ClickHouse plans: a new sorting key (copy, backfill by partition, swap), and a projection or skip index (add, materialize).
2
+
3
+ A sorting key cannot be changed in place, so a re-key is a second table:
4
+
5
+ create it -> forward new inserts to it (a materialized view) -> backfill old data partition by partition
6
+ -> compare the two tables per partition -> EXCHANGE TABLES -> keep the old copy until nobody wants it back
7
+
8
+ Views follow table names across EXCHANGE TABLES, so after the swap the forwarding view copies inserts the other
9
+ way and the old-key copy stays current: rolling back is the same EXCHANGE again. `codecop apply --check` proves that
10
+ on the sandbox for the server version in use rather than taking it on trust.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import re
16
+ from datetime import date, timedelta
17
+
18
+ from ..access import key_parts
19
+ from .common import estimate_label, estimates, human_bytes, normalize_sql, render_clickhouse_params, short, step
20
+
21
+ DEDUP_ENGINE = re.compile(r"(Replacing|Collapsing|Summing|Aggregating|Graphite)\w*MergeTree", re.I)
22
+ CLAUSE_END = re.compile(r"\b(?:PRIMARY\s+KEY|PARTITION\s+BY|SAMPLE\s+BY|ORDER\s+BY|TTL|SETTINGS|COMMENT)\b", re.I)
23
+ ADDED = re.compile(r"^\s*ALTER\s+TABLE\s+([`\"\w.]+)\s+ADD\s+(PROJECTION|INDEX)\s+(?:IF\s+NOT\s+EXISTS\s+)?([`\"\w]+)", re.I)
24
+ MATERIALIZE = re.compile(r"^\s*ALTER\s+TABLE\s+([`\"\w.]+)\s+MATERIALIZE\s+(PROJECTION|INDEX)\s+([`\"\w]+)", re.I)
25
+ WORD = re.compile(r"[A-Za-z_]\w*")
26
+
27
+
28
+ class PlanError(ValueError):
29
+ """The plan cannot be written for this variant; the message says what is missing."""
30
+
31
+
32
+ def mask_nested(sql: str) -> str:
33
+ """The statement with everything inside parentheses and quotes blanked out, same length: what is left is top level."""
34
+ out, depth, quote = [], 0, ""
35
+ i = 0
36
+ while i < len(sql):
37
+ c = sql[i]
38
+ if quote:
39
+ out.append(" ")
40
+ if c == "\\" and quote == "'" and i + 1 < len(sql):
41
+ out.append(" ")
42
+ i += 1
43
+ elif c == quote:
44
+ quote = ""
45
+ elif c in "'`\"":
46
+ quote = c
47
+ out.append(" ")
48
+ elif c == "(":
49
+ out.append("(" if depth == 0 else " ")
50
+ depth += 1
51
+ elif c == ")":
52
+ depth -= 1
53
+ out.append(")" if depth == 0 else " ")
54
+ else:
55
+ out.append(c if depth == 0 else " ")
56
+ i += 1
57
+ return "".join(out)
58
+
59
+
60
+ def clause(sql: str, keyword: str) -> tuple[int, int] | None:
61
+ """Span of a top-level table clause's expression after the ENGINE (`ORDER BY`, `PARTITION BY`, `PRIMARY KEY`)."""
62
+ masked = mask_nested(sql)
63
+ engine = re.search(r"\bENGINE\s*=", masked, re.I)
64
+ if not engine:
65
+ return None
66
+ m = re.compile(rf"\b{keyword}\b\s*", re.I).search(masked, engine.end())
67
+ if not m:
68
+ return None
69
+ end = CLAUSE_END.search(masked, m.end())
70
+ stop = end.start() if end else len(sql)
71
+ return m.end(), len(sql[:stop].rstrip())
72
+
73
+
74
+ def engine_clause(sql: str) -> str:
75
+ masked = mask_nested(sql)
76
+ m = re.search(r"\bENGINE\s*=\s*", masked, re.I)
77
+ if not m:
78
+ return ""
79
+ end = CLAUSE_END.search(masked, m.end())
80
+ return sql[m.end():end.start() if end else len(sql)].strip()
81
+
82
+
83
+ def rekeyed_create(create_sql: str, table: str, new_table: str, new_key: list[str]) -> tuple[str, list[dict]]:
84
+ """The table's own CREATE statement with another name and another ORDER BY. Everything else is kept as it is."""
85
+ sql = create_sql.strip().rstrip(";")
86
+ head = re.match(r"\s*CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?([`\"\w.]+)", sql, re.I)
87
+ order = clause(sql, r"ORDER\s+BY")
88
+ if not head or not order:
89
+ raise PlanError(f"the definition of {table} has no CREATE TABLE ... ENGINE ... ORDER BY to rewrite")
90
+ warnings = []
91
+ key_sql = "(" + ", ".join(new_key) + ")"
92
+ sql = sql[:order[0]] + key_sql + sql[order[1]:]
93
+ primary = clause(sql, r"PRIMARY\s+KEY")
94
+ if primary:
95
+ old_primary = key_parts(sql[primary[0]:primary[1]])
96
+ if old_primary != new_key[:len(old_primary)]:
97
+ sql = sql[:primary[0]] + key_sql + sql[primary[1]:]
98
+ warnings.append({"code": "primary_key", "detail": "PRIMARY KEY was set to the whole new key: it must be a prefix of ORDER BY"})
99
+ sql = sql[:head.start(1)] + new_table + sql[head.end(1):]
100
+ engine = engine_clause(sql)
101
+ if re.match(r"(Replicated|Shared)", engine, re.I) and re.search(r"\(\s*'", engine) and not re.search(r"\{uuid\}|\{table\}", engine):
102
+ warnings.append({"code": "replica_path", "detail": "the engine names a fixed replica path: give the new table its own"})
103
+ return sql, warnings
104
+
105
+
106
+ def row_hash(create_sql: str) -> str:
107
+ """A hash of a whole row that a NULL cannot blank out.
108
+
109
+ `cityHash64(*)` is NULL for any row with a NULL in it, and sum() skips NULLs, so it would compare nothing for such rows.
110
+ A tuple hashes with its NULLs. Semi-structured columns (JSON, Dynamic, Variant) cannot be hashed inside a tuple on
111
+ every supported version, so a table that has one is hashed through its text form."""
112
+ if re.search(r"\bJSON\b|\bObject\s*\(|\bDynamic\b|\bVariant\s*\(", create_sql):
113
+ return "cityHash64(toString(tuple(*)))"
114
+ return "cityHash64(tuple(*))"
115
+
116
+
117
+ def month_range(first: str, last: str) -> list[str]:
118
+ y, m, out = int(first[:4]), int(first[4:]), []
119
+ while (y, m) <= (int(last[:4]), int(last[4:])) and len(out) < 2000:
120
+ out.append(f"{y:04d}{m:02d}")
121
+ y, m = (y + 1, 1) if m == 12 else (y, m + 1)
122
+ return out
123
+
124
+
125
+ def partitions(sizes: dict) -> list[dict]:
126
+ """The real partitions, when the catalog pins them down: the key's shape, the first and last partition, and their count.
127
+
128
+ The catalog holds totals per table, so each partition's size is the table's divided evenly: an estimate, marked so."""
129
+ key, first, last, count = sizes.get("partition_key") or "", sizes.get("min_partition") or "", sizes.get("max_partition") or "", sizes.get("partitions") or 0
130
+ ids: list[str] = []
131
+ if re.match(r"toYYYYMM\(", key) and re.fullmatch(r"\d{6}", first) and re.fullmatch(r"\d{6}", last):
132
+ ids = month_range(first, last)
133
+ elif re.match(r"(toYYYYMMDD|toDate)\(", key) and re.fullmatch(r"\d{8}", first.replace("-", "")) and re.fullmatch(r"\d{8}", last.replace("-", "")):
134
+ a, b = (date(int(x[:4]), int(x[4:6]), int(x[6:])) for x in (first.replace("-", ""), last.replace("-", "")))
135
+ ids = [(a + timedelta(days=i)).strftime("%Y%m%d") for i in range(min((b - a).days + 1, 4000))]
136
+ elif not key and count <= 1:
137
+ ids = ["all"]
138
+ if not ids or (count and len(ids) != count):
139
+ return [] # gaps or a key we cannot enumerate: the plan lists them with a query instead of guessing
140
+ n = len(ids)
141
+ return [{"id": p, "bytes": (sizes.get("bytes_on_disk") or 0) // n or None, "rows": (sizes.get("rows") or 0) // n or None,
142
+ "sizes_are": "the table's totals divided evenly (estimate)"} for p in ids]
143
+
144
+
145
+ def key_columns(parts: list[str], columns: set[str] | None = None) -> set[str]:
146
+ return {w for p in parts for w in WORD.findall(p) if columns is None or w in columns}
147
+
148
+
149
+ def other_readers(inventory: dict | None, table: str, old_create: str, new_create: str, finding: dict) -> dict:
150
+ """Every other call site that reads or writes the table, and whether its filters still line up with the key after the change."""
151
+ from ..access import table_access
152
+
153
+ readers, writers = [], []
154
+ name = short(table)
155
+ for s in (inventory or {}).get("call_sites") or []:
156
+ if s.get("engine") != "clickhouse" or s.get("is_test") or name not in [short(t) for t in (s.get("tables") or []) + (s.get("writes") or [])]:
157
+ continue
158
+ where = {"file": s["file"], "line": s["line"], "symbol": s.get("symbol") or ""}
159
+ if s.get("statement") in ("insert", "update", "delete") or name in [short(t) for t in s.get("writes") or []]:
160
+ writers.append({**where, "statement": s.get("statement")})
161
+ continue
162
+ if s.get("statement") != "select" or (s["file"] == finding["site"]["file"] and s["line"] == finding["site"]["line"]):
163
+ continue
164
+ try:
165
+ before = table_access(old_create, name, s.get("sql") or "")
166
+ after = table_access(new_create, name, s.get("sql") or "")
167
+ b, a = (sum(1 for f in x["filters"] if f["key"] == "used") for x in (before, after))
168
+ effect = "unknown" if not before["filters"] else "better" if a > b else "worse" if a < b else "same"
169
+ except Exception:
170
+ effect = "unknown"
171
+ readers.append({**where, "effect": effect})
172
+ order = {"worse": 0, "unknown": 1, "better": 2, "same": 3}
173
+ readers.sort(key=lambda r: (order[r["effect"]], r["file"], r["line"]))
174
+ return {"readers": readers, "writers": writers, "counts": {k: sum(1 for r in readers if r["effect"] == k) for k in order}}
175
+
176
+
177
+ def confirm_step(finding: dict, sql: str, expect_text: str, expected: dict | None) -> dict:
178
+ """The benchmarked query under EXPLAIN on the real table, for a person to look at; `--check` measures it on the sandbox."""
179
+ shown = render_clickhouse_params(normalize_sql(sql), finding.get("params") or {})
180
+ return step("confirm", "Confirm the query reads less", "confirm", [f"EXPLAIN indexes = 1 {shown}"], effect="read",
181
+ chips=["parameter values are the sandbox's: use real ones", expect_text],
182
+ expect={"measure": {"sql": sql, "params": finding.get("params") or {}, **(expected or {})}})
183
+
184
+
185
+ def expected_read(variant: dict) -> dict | None:
186
+ """What the benchmark measured for this variant at the largest scale: the number `--check` holds the migrated table to."""
187
+ done = [s for s in variant.get("scales") or [] if s.get("variant") and s["variant"].get("ok")]
188
+ if not done:
189
+ return None
190
+ s = done[-1]
191
+ return {"table_rows": s["rows"], "baseline_read_rows": s["baseline"]["read_rows"], "baseline_read_bytes": s["baseline"]["read_bytes"],
192
+ "read_rows": s["variant"]["read_rows"], "read_bytes": s["variant"]["read_bytes"]}
193
+
194
+
195
+ def rekey_plan(findings: dict, finding: dict, variant: dict, sizes: dict, setup_s: float | None, inventory: dict | None) -> dict:
196
+ new_key = variant.get("new_order_by") or []
197
+ table = next((t for t in finding["tables"] if any(short(t) + "__codecop_variant" in s for s in variant.get("setup_sql") or [])), None) or \
198
+ (finding["tables"][0] if len(finding["tables"]) == 1 else None)
199
+ definition = next((d for d in findings.get("table_definitions") or [] if d["name"] == table), None)
200
+ if not new_key or not table or not definition:
201
+ raise PlanError("the variant does not name one table and one new sorting key")
202
+ create_sql = definition["create_sql"]
203
+ new_table, feed = f"{table}__rekey", f"{table}__rekey_feed"
204
+ new_create, warnings = rekeyed_create(create_sql, table, new_table, new_key)
205
+ order = clause(create_sql.strip().rstrip(";"), r"ORDER\s+BY")
206
+ old_key = key_parts(create_sql.strip().rstrip(";")[order[0]:order[1]]) if order else []
207
+ engine = engine_clause(create_sql)
208
+ dedup = bool(DEDUP_ENGINE.search(engine))
209
+ final = " FINAL" if dedup else ""
210
+ if dedup and key_columns(old_key) != key_columns(new_key):
211
+ warnings.append({"code": "dedup_key_changes", "detail": f"{engine.split('(')[0]} collapses rows by the sorting key: a key with other columns "
212
+ "changes which rows are kept"})
213
+ part_clause = clause(create_sql.strip().rstrip(";"), r"PARTITION\s+BY")
214
+ partitioned = bool(part_clause)
215
+ var_part = re.search(r"\bPARTITION\s+BY\s+(.+?)\s+ORDER\s+BY\b", " ".join(variant.get("setup_sql") or []), re.I | re.S)
216
+ if var_part and partitioned and normalize_sql(var_part.group(1)) != normalize_sql(create_sql.strip().rstrip(";")[part_clause[0]:part_clause[1]]):
217
+ warnings.append({"code": "partitioning_differs", "detail": "the benchmarked variant also changed PARTITION BY; this plan keeps the current one"})
218
+ parts = partitions(sizes) if sizes["source"] == "real catalog" else []
219
+ est = estimates(findings, finding, variant, table, sizes, setup_s)
220
+ if est["extra_disk_bytes"] is None and sizes.get("bytes_on_disk"):
221
+ est["extra_disk_bytes"] = sizes["bytes_on_disk"]
222
+ est["basis"].append("disk: a full second copy of the table")
223
+ est["label"] = estimate_label(est)
224
+ list_sql = (f"SELECT partition_id, sum(rows) AS rows, sum(bytes_on_disk) AS bytes_on_disk FROM system.parts WHERE active AND database = currentDatabase() "
225
+ f"AND table = '{short(table)}' GROUP BY partition_id ORDER BY partition_id")
226
+ compare = ("SELECT partition_id, sumIf(rows, side = 'old') AS old_rows, sumIf(rows, side = 'new') AS new_rows, {ok} AS ok FROM ("
227
+ f"SELECT 'old' AS side, _partition_id AS partition_id, count() AS rows{{sum}} FROM {table}{final} GROUP BY partition_id UNION ALL "
228
+ f"SELECT 'new' AS side, _partition_id AS partition_id, count() AS rows{{sum}} FROM {new_table}{final} GROUP BY partition_id"
229
+ ") GROUP BY partition_id ORDER BY partition_id")
230
+ counts_sql = compare.format(ok="old_rows = new_rows", sum="")
231
+ checksum_sql = compare.format(ok="old_rows = new_rows AND sumIf(checksum, side = 'old') = sumIf(checksum, side = 'new')",
232
+ sum=f", sum({row_hash(create_sql)}) AS checksum")
233
+ code = other_readers(inventory, table, create_sql, new_create, finding)
234
+ views = sizes.get("dependent_views") or []
235
+ newest = parts[-1]["id"] if parts else ""
236
+ backfill_chips = [f"re-run one partition: ALTER TABLE {new_table} DROP PARTITION ID '<id>', then its INSERT again"]
237
+ if dedup:
238
+ backfill_chips.append("a row written while its partition is copied lands twice (feed view and backfill): the next step collapses those")
239
+ else:
240
+ backfill_chips.append("a row inserted while its partition is copied can land twice: pause writes for the newest partition, or dedupe it after")
241
+ warnings.append({"code": "duplicates_possible", "detail": "the engine does not collapse duplicates: the newest partition needs a write pause "
242
+ "while it is copied"})
243
+ steps = [
244
+ step("precheck", "Check the database and list the partitions", "prepare", [
245
+ "SELECT engine FROM system.databases WHERE name = currentDatabase()",
246
+ "SELECT sum(free_space) AS free_bytes FROM system.disks",
247
+ list_sql,
248
+ ], effect="read", expect={"statement": 0, "every_in": {"engine": ["Atomic", "Replicated", "Shared"]}},
249
+ chips=["EXCHANGE TABLES needs an Atomic, Replicated or Shared database"]
250
+ + ([f"needs about {human_bytes(est['extra_disk_bytes'])} free (estimate)"] if est.get("extra_disk_bytes") else [])),
251
+ step("create_table", f"Create {short(new_table)} with the new key", "build", [new_create], undo=[f"DROP TABLE IF EXISTS {new_table}"],
252
+ locks="none", chips=["same columns, engine, partitioning, indexes and settings; only ORDER BY differs"]),
253
+ step("catch_up", "Forward new inserts to the new table", "catch_up",
254
+ [f"CREATE MATERIALIZED VIEW {feed} TO {new_table} AS SELECT * FROM {table}"], undo=[f"DROP VIEW IF EXISTS {feed}"], locks="none",
255
+ chips=["every INSERT into the table from now on also lands in the new one", "ALTER ... UPDATE/DELETE on the old table are not forwarded: hold them until the swap",
256
+ "instead of this view: write to both tables from the application"]),
257
+ step("backfill", "Backfill, one partition at a time", "backfill", [], undo=[f"TRUNCATE TABLE {new_table}"], locks="none",
258
+ estimate={k: est[k] for k in ("is_estimate", "duration_s", "extra_disk_bytes", "basis", "label", "sizes_from")},
259
+ per_partition={"template": f"INSERT INTO {new_table} SELECT * FROM {table} WHERE _partition_id = '{{partition_id}}'",
260
+ "list_sql": list_sql, "partitions": parts, "newest": newest,
261
+ "source": "real catalog" if parts else "listed at run time"},
262
+ chips=backfill_chips),
263
+ *([step("settle", "Collapse rows copied twice in the newest partition", "backfill", [], locks="none: a merge",
264
+ per_partition={"template": f"OPTIMIZE TABLE {new_table} PARTITION ID '{{partition_id}}' FINAL", "list_sql": list_sql,
265
+ "partitions": parts[-1:], "newest": newest, "scope": "newest", "source": "real catalog" if parts else "listed at run time"},
266
+ chips=["only the partition that was still being written during the backfill", "a read without FINAL would otherwise see those rows twice until a merge",
267
+ "removes nothing a FINAL read returns"])] if dedup else []),
268
+ step("verify_counts", "Compare row counts per partition", "verify", [counts_sql], effect="read", expect={"min_rows": 1, "every": {"ok": 1}},
269
+ chips=["ok must be 1 in every row"] + (["FINAL: both tables are compared after collapsing row versions"] if dedup else [])),
270
+ step("verify_checksums", "Compare a checksum per partition", "verify", [checksum_sql], effect="read", expect={"min_rows": 1, "every": {"ok": 1}},
271
+ chips=["reads both tables in full", "ok must be 1 in every row", "a row that arrives mid-query can flip one partition: run it again"]),
272
+ step("swap", "Swap the two tables", "swap", [f"EXCHANGE TABLES {table} AND {new_table}"], undo=[f"EXCHANGE TABLES {table} AND {new_table}"],
273
+ locks="a metadata lock on both tables for the instant of the swap", alternative_sql=[f"RENAME TABLE {table} TO {table}__old_key, {new_table} TO {table}"],
274
+ chips=["atomic: queries see the old table or the new one, never neither", f"afterwards {short(new_table)} holds the OLD key's data",
275
+ "the feed view now copies inserts into the old-key copy, so undoing loses nothing",
276
+ "alternative (Ordinary database, not atomic) is in the file"]
277
+ + ([f"{len(views)} dependent view{'s keep' if len(views) != 1 else ' keeps'} reading the table by name"] if views else [])),
278
+ confirm_step(finding, finding["baseline_sql"], "the key condition should now start with " + new_key[0], expected_read(variant)),
279
+ step("cleanup", "Drop the old-key copy", "cleanup", [f"DROP VIEW IF EXISTS {feed}", f"DROP TABLE IF EXISTS {new_table}"], effect="destructive",
280
+ reversible=False, locks="none",
281
+ chips=["only after the new key has run in production long enough", "frees the second copy's disk", "after this, going back is a new migration"]),
282
+ ]
283
+ rollback = [
284
+ {"when": "before the swap", "possible": True, "loses": "nothing", "sql": [f"DROP VIEW IF EXISTS {feed}", f"DROP TABLE IF EXISTS {new_table}"]},
285
+ {"when": "after the swap, before cleanup", "possible": True, "loses": "nothing: the old-key copy was kept current",
286
+ "sql": [f"EXCHANGE TABLES {table} AND {new_table}"]},
287
+ {"when": "after cleanup", "possible": False, "loses": "the old-key copy is gone", "sql": []},
288
+ ]
289
+ same_query = normalize_sql(variant.get("sql", "").replace(f"{short(table)}__codecop_variant", short(table))) == normalize_sql(finding["baseline_sql"])
290
+ return {
291
+ "recipe": "rekey", "table": table, "new_table": new_table, "old_key": old_key, "new_key": new_key, "engine": engine.split("(")[0], "collapses_duplicates": dedup,
292
+ "sizes": sizes, "estimates": est, "warnings": warnings, "steps": steps, "rollback": rollback,
293
+ "dependent_views": views,
294
+ "code": {"needs_patch": not same_query,
295
+ "call_sites": [{"file": finding["site"]["file"], "line": finding["site"]["line"], "symbol": finding["site"].get("symbol") or "",
296
+ "change": "none: the table keeps its name" if same_query else "the query changes too: see the patch"}],
297
+ "other_readers": code["readers"][:40], "reader_counts": code["counts"], "writers": code["writers"][:20]},
298
+ }
299
+
300
+
301
+ def alter_plan(findings: dict, finding: dict, variant: dict, catalog_sizes, setup_seconds: float | None) -> dict:
302
+ """A projection or a data-skipping index: add it (metadata only), build it for existing parts, partition by partition."""
303
+ setup = [s.strip().rstrip(";") for s in variant.get("setup_sql") or []]
304
+ added = [(m.group(1), m.group(2).upper(), m.group(3)) for s in setup if (m := ADDED.match(s))]
305
+ if not added:
306
+ raise PlanError("the variant's setup has no ALTER TABLE ... ADD PROJECTION or ADD INDEX")
307
+ word = {"PROJECTION": "projection", "INDEX": "skip index"}
308
+ steps, warnings, rollback_sql, all_sizes, total = [], [], [], {}, {"extra_disk_bytes": 0, "low": 0, "high": 0}
309
+ tables = list(dict.fromkeys(t for t, _, _ in added))
310
+ for t in tables:
311
+ all_sizes[t] = catalog_sizes(next((x for x in finding["tables"] if short(x) == short(t)), t))
312
+ steps.append(step("precheck", "Check free disk and running mutations", "prepare", [
313
+ "SELECT sum(free_space) AS free_bytes FROM system.disks",
314
+ "SELECT table, count() AS unfinished FROM system.mutations WHERE database = currentDatabase() AND NOT is_done AND table IN ("
315
+ + ", ".join(f"'{short(t)}'" for t in tables) + ") GROUP BY table",
316
+ ], effect="read", expect={"statement": 1, "max_rows": 0}, chips=["no mutation should be running on the table"]))
317
+ handled = set()
318
+ for i, stmt in enumerate(setup):
319
+ m = ADDED.match(stmt)
320
+ if m:
321
+ table, kind, name = m.group(1), m.group(2).upper(), m.group(3)
322
+ sizes = all_sizes[table]
323
+ est = estimates(findings, finding, {**variant, "storage_delta_bytes": int((variant.get("storage_delta_bytes") or 0) / len(added))},
324
+ next((x for x in finding["tables"] if short(x) == short(table)), table), sizes,
325
+ setup_seconds / len(added) if setup_seconds else None)
326
+ est["label"] = estimate_label(est)
327
+ for k, v in (("extra_disk_bytes", est["extra_disk_bytes"] or 0), ("low", (est["duration_s"] or {}).get("low", 0)),
328
+ ("high", (est["duration_s"] or {}).get("high", 0))):
329
+ total[k] += v
330
+ total.setdefault("basis", []).extend(b for b in est["basis"] if b not in total.get("basis", []))
331
+ drop = f"ALTER TABLE {table} DROP {kind} IF EXISTS {name}"
332
+ rollback_sql.insert(0, drop)
333
+ parts = partitions(sizes) if sizes["source"] == "real catalog" else []
334
+ list_sql = (f"SELECT partition_id, sum(rows) AS rows, sum(bytes_on_disk) AS bytes_on_disk FROM system.parts WHERE active AND "
335
+ f"database = currentDatabase() AND table = '{short(table)}' GROUP BY partition_id ORDER BY partition_id")
336
+ add = re.sub(rf"\bADD\s+{kind}\s+(?!IF\s+NOT\s+EXISTS)", f"ADD {kind} IF NOT EXISTS ", stmt, count=1, flags=re.I)
337
+ steps.append(step(f"add_{short(name)}", f"Add the {word[kind]} {short(name)} to {short(table)}", "build", [add], undo=[drop],
338
+ locks="a metadata change; reads and writes continue", chips=["new parts get it from now on; existing data is untouched"]))
339
+ steps.append(step(f"materialize_{short(name)}", f"Build it for existing data, one partition at a time", "backfill", [], undo=[drop],
340
+ locks="none: a background mutation rewrites parts",
341
+ estimate={k: est[k] for k in ("is_estimate", "duration_s", "extra_disk_bytes", "basis", "label", "sizes_from")},
342
+ per_partition={"template": f"ALTER TABLE {table} MATERIALIZE {kind} {name} IN PARTITION ID '{{partition_id}}'",
343
+ "list_sql": list_sql, "partitions": parts, "newest": parts[-1]["id"] if parts else "",
344
+ "source": "real catalog" if parts else "listed at run time"},
345
+ chips=["runs in the background: each statement returns at once", "to stop one: KILL MUTATION WHERE mutation_id = '<id>'"],
346
+ sandbox_settings={"mutations_sync": 2}))
347
+ exists = (f"SELECT count() AS parts, countIf(has(projections, '{short(name)}')) AS built FROM system.parts WHERE active AND "
348
+ f"database = currentDatabase() AND table = '{short(table)}'" if kind == "PROJECTION" else
349
+ f"SELECT count() AS indexes FROM system.data_skipping_indices WHERE database = currentDatabase() AND table = '{short(table)}' "
350
+ f"AND name = '{short(name)}'")
351
+ steps.append(step(f"verify_{short(name)}", "Check the build finished", "verify", [
352
+ f"SELECT count() AS unfinished, countIf(latest_fail_reason != '') AS failed FROM system.mutations WHERE database = currentDatabase() "
353
+ f"AND table = '{short(table)}' AND NOT is_done", exists,
354
+ ], effect="read", expect={"statement": 0, "every": {"unfinished": 0, "failed": 0}},
355
+ chips=["unfinished must reach 0"] + (["built must equal parts"] if kind == "PROJECTION" else [])))
356
+ handled.add(i)
357
+ elif MATERIALIZE.match(stmt):
358
+ handled.add(i)
359
+ for i, stmt in enumerate(setup):
360
+ if i not in handled:
361
+ steps.insert(1, step(f"setup_{i + 1}", " ".join(stmt.split()[:4])[:60], "build", [stmt], reversible=False,
362
+ chips=["as the sandbox ran it; no automatic undo"]))
363
+ warnings.append({"code": "manual", "detail": "one setup statement is not an ADD or MATERIALIZE: it is run as written"})
364
+ kind_words = sorted({word[k] for _, k, _ in added})
365
+ steps.append(confirm_step(finding, variant["sql"], f"the plan should show the {' / '.join(kind_words)} narrowing the read", expected_read(variant)))
366
+ est_all = {"is_estimate": True, "extra_disk_bytes": total["extra_disk_bytes"] or None,
367
+ "duration_s": {"low": total["low"], "high": total["high"]} if total["high"] else None,
368
+ "sizes_from": sorted({s["source"] for s in all_sizes.values()})[0], "basis": total.get("basis", [])}
369
+ est_all["label"] = estimate_label(est_all)
370
+ same_query = normalize_sql(variant.get("sql", "")) == normalize_sql(finding["baseline_sql"])
371
+ return {
372
+ "recipe": "projection" if added[0][1] == "PROJECTION" else "skip_index", "table": tables[0], "tables": tables,
373
+ "sizes": all_sizes[tables[0]], "estimates": est_all, "warnings": warnings, "steps": steps,
374
+ "rollback": [{"when": "at any point", "possible": True, "loses": "nothing: the table's data is not touched", "sql": rollback_sql}],
375
+ "code": {"needs_patch": not same_query, "call_sites": [{
376
+ "file": finding["site"]["file"], "line": finding["site"]["line"], "symbol": finding["site"].get("symbol") or "",
377
+ "change": "none: the query is unchanged" if same_query else "the query changes too: see the patch"}],
378
+ "other_readers": [], "reader_counts": {}, "writers": []},
379
+ }
@@ -0,0 +1,238 @@
1
+ """What every plan shares: steps, real sizes, estimates, and the plan for setup statements nobody has a recipe for."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+
7
+ APPLY_DIR = "apply"
8
+ PLAN_FILE = "plan.json"
9
+ CHECK_FILE = "check.json"
10
+ # Which variant kinds are delivered as a change to the database. `rewrite` is a change to the code only.
11
+ MIGRATION_KINDS = ("ordering_key", "projection", "skip_index", "index", "materialized_view", "column_type", "partitioning")
12
+
13
+
14
+ def short(name: str) -> str:
15
+ return name.replace("`", "").replace('"', "").split(".")[-1]
16
+
17
+
18
+ def step(id: str, title: str, phase: str, sql: list[str], *, effect: str = "change", reversible: bool = True, undo: list[str] | None = None,
19
+ locks: str = "", expect: dict | None = None, estimate: dict | None = None, per_partition: dict | None = None,
20
+ alternative_sql: list[str] | None = None, chips: list[str] | None = None, sandbox_settings: dict | None = None) -> dict:
21
+ """One step of a plan.
22
+
23
+ effect: `read` (changes nothing), `change`, or `destructive` (data is dropped).
24
+ reversible: whether `undo_sql` takes the database back to where it was before this step.
25
+ expect: for a read, what its rows must look like for the step to pass (see check.evaluate).
26
+ per_partition: {"template": "... '{partition_id}' ...", "list_sql": ..., "partitions": [...]}: one statement per partition."""
27
+ return {"id": id, "title": title, "phase": phase, "effect": effect, "reversible": bool(reversible), "undo_sql": list(undo or []),
28
+ "locks": locks, "sql": [s.strip().rstrip(";") for s in sql], "expect": expect, "estimate": estimate, "per_partition": per_partition,
29
+ "alternative_sql": list(alternative_sql or []), "chips": list(chips or []), "sandbox_settings": sandbox_settings or {}}
30
+
31
+
32
+ def number(steps: list[dict]) -> list[dict]:
33
+ for i, s in enumerate(steps, start=1):
34
+ s["n"] = i
35
+ s["file"] = f"{i:02d}_{s['id']}.sql"
36
+ return steps
37
+
38
+
39
+ def sql_file(plan: dict, s: dict, total: int) -> str:
40
+ """The text of one step's .sql file: a short header, then the statements."""
41
+ head = [f"-- codecop apply · {plan['finding']} · step {s['n']} of {total} · {s['title']}",
42
+ f"-- phase: {s['phase']} · {'reads only' if s['effect'] == 'read' else ('reversible' if s['reversible'] else 'NOT reversible')}"
43
+ + (f" · locks: {s['locks']}" if s["locks"] else "")]
44
+ if s["undo_sql"]:
45
+ head.append("-- undo: " + "; ".join(s["undo_sql"]))
46
+ if s.get("estimate") and s["estimate"].get("label"):
47
+ head.append(f"-- estimate: {s['estimate']['label']}")
48
+ head += [f"-- {c}" for c in s["chips"]]
49
+ body = [x + ";" for x in s["sql"]]
50
+ pp = s.get("per_partition")
51
+ if pp:
52
+ if pp.get("partitions"):
53
+ body += [pp["template"].replace("{partition_id}", p["id"]) + ";" + (f" -- ~{human_bytes(p['bytes'])} (estimate)" if p.get("bytes") else "")
54
+ for p in pp["partitions"]]
55
+ else:
56
+ only = pp.get("scope") == "newest"
57
+ body += ["-- For the newest partition only. List the partitions:" if only else "-- One statement per partition. List the partitions:",
58
+ "-- " + pp["list_sql"] + ";", "-- then run, for the last partition_id:" if only else "-- then run, for each partition_id:",
59
+ pp["template"] + ";"]
60
+ if s["alternative_sql"]:
61
+ body += ["", "-- Alternative:"] + ["-- " + x + ";" for x in s["alternative_sql"]]
62
+ return "\n".join(head + [""] + body) + "\n"
63
+
64
+
65
+ def human_bytes(n) -> str:
66
+ n = float(n or 0)
67
+ for unit, size in (("TB", 1e12), ("GB", 1e9), ("MB", 1e6), ("KB", 1e3)):
68
+ if abs(n) >= size:
69
+ return f"{n / size:.1f} {unit}"
70
+ return f"{n:.0f} B"
71
+
72
+
73
+ def human_duration(seconds: float) -> str:
74
+ seconds = float(seconds or 0)
75
+ for unit, size in (("d", 86400), ("h", 3600), ("min", 60)):
76
+ if seconds >= size:
77
+ return f"{seconds / size:.0f} {unit}" if seconds / size >= 10 else f"{seconds / size:.1f} {unit}"
78
+ return f"{max(seconds, 1):.0f} s"
79
+
80
+
81
+ # ---- sizes ---------------------------------------------------------------
82
+
83
+ def real_table(catalog: dict | None, engine: str, table: str) -> dict | None:
84
+ """The table as `codecop db pull` saw it. Never returns a database name: plans are files a developer passes around."""
85
+ if not catalog:
86
+ return None
87
+ schema, _, name = table.replace('"', "").replace("`", "").rpartition(".")
88
+ found = []
89
+ for conn in (catalog.get("connections") or {}).values():
90
+ if conn.get("engine") != engine:
91
+ continue
92
+ for t in conn.get("tables") or []:
93
+ if t.get("name") != name:
94
+ continue
95
+ if engine == "postgres" and (t.get("schema") or "public") != (schema or "public"):
96
+ continue
97
+ found.append(t)
98
+ if not found:
99
+ return None
100
+ t = max(found, key=lambda t: t.get("bytes_on_disk") or 0)
101
+ return {"source": "real catalog", "rows": int(t.get("rows") or 0), "bytes_on_disk": int(t.get("bytes_on_disk") or 0),
102
+ "uncompressed_bytes": int(t.get("uncompressed_bytes") or 0), "partitions": int(t.get("partitions") or 0),
103
+ "min_partition": t.get("min_partition") or "", "max_partition": t.get("max_partition") or "",
104
+ "partition_key": t.get("partition_key") or "", "parts": int(t.get("parts") or 0), "engine": t.get("engine") or "",
105
+ "index_bytes": int(t.get("index_bytes") or 0), "kind": t.get("kind") or "",
106
+ "dependent_views": sorted({short(f) for f in t.get("feeds") or []}), "same_name_tables": len(found)}
107
+
108
+
109
+ def table_sizes(findings: dict, catalog: dict | None, table: str) -> dict:
110
+ """The best size we have for a table, and where it came from: the real catalog, the profile's estimate, or the sandbox."""
111
+ real = real_table(catalog, findings["engine"], table)
112
+ if real:
113
+ return real
114
+ definition = next((d for d in findings.get("table_definitions") or [] if d["name"] == table), {})
115
+ if definition.get("source") == "real catalog" and definition.get("rows"):
116
+ return {"source": "real catalog", "rows": int(definition["rows"]), "bytes_on_disk": int(definition.get("bytes_on_disk") or 0),
117
+ "uncompressed_bytes": 0, "partitions": 0, "dependent_views": []}
118
+ prof = next((t for t in findings.get("profile") or [] if t["name"] == table), None)
119
+ if prof and prof.get("rows"):
120
+ return {"source": "profile estimate", "rows": int(prof["rows"]), "bytes_on_disk": 0, "uncompressed_bytes": 0, "partitions": 0, "dependent_views": []}
121
+ sb = sandbox_table(findings, table) or {}
122
+ return {"source": "sandbox", "rows": int(sb.get("rows") or 0), "bytes_on_disk": int(sb.get("bytes_on_disk") or 0),
123
+ "uncompressed_bytes": int(sb.get("uncompressed") or 0), "partitions": 0, "dependent_views": []}
124
+
125
+
126
+ def sandbox_table(findings: dict, table: str) -> dict | None:
127
+ return next((t for t in findings.get("sandbox_tables") or [] if t["name"] == table and t.get("ok", True)), None)
128
+
129
+
130
+ def bench_setup_seconds(bench: dict | None, rank: dict | None, finding: dict, variant: dict) -> float | None:
131
+ """How long the variant's setup took on the sandbox at the largest scale, when bench.json and rank.json are there to say."""
132
+ if not bench or not rank or not bench.get("scales"):
133
+ return None
134
+ cand = next((c for c in rank.get("candidates") or [] if c.get("finding") == finding["finding"]), None)
135
+ measured = next((f for f in bench["scales"][-1]["findings"] if f["finding"] == finding["finding"]), None)
136
+ if not cand or not measured:
137
+ return None
138
+ for i, v in enumerate(cand["variants"]):
139
+ if v["kind"] == variant["kind"] and v.get("sql") == variant.get("sql") and (v.get("setup_sql") or []) == (variant.get("setup_sql") or []):
140
+ rec = next((r for r in measured["variants"] if r.get("index") == i), None)
141
+ return float(rec["setup_s"]) if rec and rec.get("setup_s") else None
142
+ return None
143
+
144
+
145
+ def estimates(findings: dict, finding: dict, variant: dict, table: str, sizes: dict, setup_s: float | None, *, slower: float = 1.0) -> dict:
146
+ """Extra disk and duration for building the variant on the real table. Always an estimate: scaled from the sandbox.
147
+
148
+ `slower`: how much slower the safe production form is than what the sandbox ran (CREATE INDEX CONCURRENTLY against a plain build)."""
149
+ sb = sandbox_table(findings, table) or {}
150
+ delta = int(variant.get("storage_delta_bytes") or 0)
151
+ out: dict = {"is_estimate": True, "sizes_from": sizes["source"], "extra_disk_bytes": None, "duration_s": None, "basis": []}
152
+ sb_bytes, sb_rows = int(sb.get("bytes_on_disk") or 0), int(sb.get("rows") or 0)
153
+ if delta > 0 and sizes.get("bytes_on_disk") and sb_bytes:
154
+ out["extra_disk_bytes"] = int(sizes["bytes_on_disk"] * delta / sb_bytes)
155
+ out["basis"].append(f"disk: +{delta / sb_bytes:.0%} of the table in the sandbox, applied to {human_bytes(sizes['bytes_on_disk'])}")
156
+ elif delta > 0 and sizes.get("rows") and sb_rows:
157
+ out["extra_disk_bytes"] = int(delta * sizes["rows"] / sb_rows)
158
+ out["basis"].append(f"disk: {human_bytes(delta)} for {sb_rows:,} sandbox rows, scaled to {sizes['rows']:,} rows")
159
+ seconds = None
160
+ if setup_s and setup_s >= 0.5:
161
+ if sizes.get("uncompressed_bytes") and sb.get("uncompressed"):
162
+ seconds = sizes["uncompressed_bytes"] / (sb["uncompressed"] / setup_s)
163
+ out["basis"].append(f"time: the sandbox built it from {human_bytes(sb['uncompressed'])} uncompressed in {setup_s:g} s on a laptop, "
164
+ f"scaled to {human_bytes(sizes['uncompressed_bytes'])}")
165
+ elif sizes.get("rows") and sb_rows:
166
+ seconds = sizes["rows"] / (sb_rows / setup_s)
167
+ out["basis"].append(f"time: the sandbox built it for {sb_rows:,} rows in {setup_s:g} s on a laptop, scaled to {sizes['rows']:,} rows")
168
+ if seconds is not None:
169
+ seconds *= slower
170
+ out["duration_s"] = {"low": round(seconds * 0.5), "high": round(seconds * 2)}
171
+ return out
172
+
173
+
174
+ def estimate_label(est: dict) -> str:
175
+ bits = []
176
+ if est.get("duration_s"):
177
+ bits.append(f"{human_duration(est['duration_s']['low'])} to {human_duration(est['duration_s']['high'])}")
178
+ if est.get("extra_disk_bytes"):
179
+ bits.append(f"+{human_bytes(est['extra_disk_bytes'])} disk")
180
+ return ", ".join(bits)
181
+
182
+
183
+ # ---- statements ----------------------------------------------------------
184
+
185
+ def normalize_sql(sql: str) -> str:
186
+ return " ".join((sql or "").split()).rstrip(";").strip()
187
+
188
+
189
+ def render_clickhouse_params(sql: str, params: dict) -> str:
190
+ """`{name:Type}` placeholders as literals, for a statement a person pastes into a client."""
191
+ def one(m: re.Match) -> str:
192
+ name, typ = m.group(1), m.group(2)
193
+ if name not in params:
194
+ return m.group(0)
195
+ value = params[name]
196
+ if isinstance(value, (list, tuple)):
197
+ return "[" + ", ".join(repr(v) if isinstance(v, str) else str(v) for v in value) + "]"
198
+ if re.match(r"(?:Nullable\()?(?:U?Int|Float|Decimal|Bool)", typ or "") and re.fullmatch(r"-?\d+(?:\.\d+)?", str(value)):
199
+ return str(value)
200
+ return "'" + str(value).replace("\\", "\\\\").replace("'", "\\'") + "'"
201
+ return re.sub(r"\{(\w+):([^{}]+)\}", one, sql)
202
+
203
+
204
+ CH_CREATED = re.compile(r"^\s*CREATE\s+(?:OR\s+REPLACE\s+)?(MATERIALIZED\s+VIEW|VIEW|TABLE|DICTIONARY)\s+(?:IF\s+NOT\s+EXISTS\s+)?([`\"\w.]+)", re.I)
205
+ PG_CREATED = re.compile(r"^\s*CREATE\s+(?:OR\s+REPLACE\s+)?(UNIQUE\s+INDEX|INDEX|MATERIALIZED\s+VIEW|VIEW|TABLE|STATISTICS|TYPE|EXTENSION)\s+"
206
+ r"(?:CONCURRENTLY\s+)?(?:IF\s+NOT\s+EXISTS\s+)?([\"\w.-]+)", re.I)
207
+
208
+
209
+ def generic_plan(engine: str, finding: dict, variant: dict) -> tuple[list[dict], list[dict]]:
210
+ """Setup statements this tool has no recipe for (a materialized view, a column type, partitioning): each one a step, as written.
211
+
212
+ Returns (steps, warnings). Nothing is chunked or made online here; the plan says so."""
213
+ statements = []
214
+ for script in variant.get("setup_sql") or []:
215
+ if engine == "postgres":
216
+ from ..engines.pg_ddl import split_statements
217
+ statements += split_statements(script)
218
+ else:
219
+ statements.append(script)
220
+ steps, undo_all = [], []
221
+ for i, stmt in enumerate(statements, start=1):
222
+ stmt = stmt.strip().rstrip(";")
223
+ created = (PG_CREATED if engine == "postgres" else CH_CREATED).match(stmt)
224
+ head = " ".join(stmt.split()[:3]).upper()
225
+ if created:
226
+ kind = " ".join(created.group(1).upper().split()).replace("UNIQUE INDEX", "INDEX")
227
+ undo = [f"DROP {kind} IF EXISTS {created.group(2)}"]
228
+ steps.append(step(f"setup_{i}", f"{head.title()} {short(created.group(2))}"[:60], "build", [stmt], undo=undo))
229
+ undo_all = undo + undo_all
230
+ elif re.match(r"\s*INSERT\s+INTO", stmt, re.I):
231
+ target = re.match(r"\s*INSERT\s+INTO\s+([`\"\w.]+)", stmt, re.I).group(1)
232
+ steps.append(step(f"setup_{i}", f"Backfill {short(target)}", "backfill", [stmt], undo=[f"TRUNCATE TABLE {target}"],
233
+ chips=["one unbounded statement: split it by partition or key range before running it on a large table"]))
234
+ else:
235
+ steps.append(step(f"setup_{i}", head.title()[:60], "build", [stmt], reversible=False, chips=["no automatic undo: review"]))
236
+ warnings = [{"code": "manual", "detail": f"{variant['kind'].replace('_', ' ')}: the statements are the ones the sandbox ran, in order; "
237
+ "they are not rewritten into an online form"}]
238
+ return steps, warnings