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,271 @@
1
+ """Does each variant plan? PREPARE (PostgreSQL) or EXPLAIN PLAN (ClickHouse) against an empty sandbox schema.
2
+
3
+ Nothing is executed and no rows exist: the schema is the pulled catalog's tables (and, for PostgreSQL, the tables the
4
+ repository's own migrations define), created in a sandbox started by the existing engines (engines/postgres.py,
5
+ engines/clickhouse.py: the same containers, labels and limits as a benchmark). Binds of every style become typed
6
+ parameters (PostgreSQL `$n`) or stand-in values (ClickHouse), tried in a fixed order when a stand-in has the wrong type.
7
+
8
+ The plan gate of the baseline pass (plangate.py) is the one the baseline pass uses; this one answers the family's own question, "is this
9
+ variant a statement", and writes families_plan.json: {variants: {variant_id: {parsed, planned, error}}}.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import re
16
+ from pathlib import Path
17
+
18
+ import sqlglot
19
+
20
+ STR = re.compile(r"'(?:[^']|'')*'")
21
+ CH_STANDINS = ("NULL", "''", "0", "'2026-01-01 00:00:00'", "'00000000-0000-0000-0000-000000000000'")
22
+ CH_RETRY = re.compile(r"NULL|array|Cannot (convert|parse)|ILLEGAL_TYPE|TYPE_MISMATCH|Illegal type|parse|CANNOT_")
23
+
24
+
25
+ def _outside_strings(sql: str, fn) -> str:
26
+ out, last = [], 0
27
+ for m in STR.finditer(sql):
28
+ out.append(fn(sql[last:m.start()]))
29
+ out.append(m.group(0))
30
+ last = m.end()
31
+ out.append(fn(sql[last:]))
32
+ return "".join(out)
33
+
34
+
35
+ def kind(sql: str) -> str:
36
+ m = re.match(r"\s*(?:--[^\n]*\n\s*|/\*.*?\*/\s*)*\(?\s*(\w+)", sql or "", re.S)
37
+ w = (m.group(1) if m else "").upper()
38
+ return {"SELECT": "select", "WITH": "select", "INSERT": "insert", "UPDATE": "update", "DELETE": "delete"}.get(w, "other")
39
+
40
+
41
+ def pg_binds(sql: str) -> str:
42
+ """Every bind style as $n: `$n`, `@{name}`, `%(name)s`, `:name`, `@name`, `{name:Type}`, `%s`, `?`."""
43
+ n = [0]
44
+ for m in re.finditer(r"\$(\d+)", _outside_strings(sql, lambda s: s)):
45
+ n[0] = max(n[0], int(m.group(1)))
46
+ other = n[0] > 0 or bool(re.search(r"@\{\w+\}|%\(\w+\)s|%s", sql)) # with $n or named binds, `?` is the jsonb operator
47
+ names: dict[str, int] = {}
48
+
49
+ def named(key: str) -> str:
50
+ if key not in names:
51
+ n[0] += 1
52
+ names[key] = n[0]
53
+ return f"${names[key]}"
54
+
55
+ def anon(_m) -> str:
56
+ n[0] += 1
57
+ return f"${n[0]}"
58
+
59
+ def fn(s: str) -> str:
60
+ s = re.sub(r"@\{(\w+)\}", lambda m: named(m.group(1)), s)
61
+ s = re.sub(r"%\((\w+)\)s", lambda m: named(m.group(1)), s)
62
+ s = re.sub(r"(?<![:\w]):(\w+)\b(?!:)", lambda m: named(m.group(1)) if not m.group(1).isdigit() else m.group(0), s)
63
+ s = re.sub(r"@(\w+)\b", lambda m: named(m.group(1)), s)
64
+ s = re.sub(r"\{(\w+):\w[^}]*\}", lambda m: named(m.group(1)), s)
65
+ s = re.sub(r"%s", anon, s)
66
+ if not other:
67
+ s = re.sub(r"(?<![?\w@#-])\?(?![?|&])", anon, s)
68
+ return s
69
+ return _outside_strings(sql, fn)
70
+
71
+
72
+ def ch_binds(sql: str, stand: str = "NULL") -> str:
73
+ def fn(s: str) -> str:
74
+ if stand != "NULL":
75
+ s = re.sub(r"\b(has|hasAny|hasAll|arrayJoin|arrayExists|length|arrayMap|indexOf)\(\s*(\?|\{\w+:\w[^}]*\}|@\w+|\$\d+)", r"\1([]", s)
76
+ s = re.sub(r"\bARRAY JOIN\s+(\?|\{\w+:\w[^}]*\}|@\w+|\$\d+)", r"ARRAY JOIN []", s, flags=re.I)
77
+ s = re.sub(r"\b(LIMIT|OFFSET)\s+(\?|\{\w+:\w[^}]*\}|@\w+|\$\d+|%\(\w+\)s|%s)", r"\1 10", s, flags=re.I)
78
+ s = re.sub(r"\bIN\s+(\?|\{\w+:\w[^}]*\}|@\w+|\$\d+|%\(\w+\)s|%s)", r"IN (NULL)", s, flags=re.I)
79
+
80
+ def typed(m: re.Match) -> str:
81
+ t = m.group(1)
82
+ if t.startswith("Array"):
83
+ return "[]"
84
+ if t.startswith(("Nullable", "Map", "Identifier", "Tuple", "LowCardinality")):
85
+ return "NULL"
86
+ if stand == "NULL":
87
+ return f"CAST(NULL AS Nullable({t}))"
88
+ return {"S": "''", "U": "0", "I": "0", "F": "0", "D": "toDateTime('2026-01-01 00:00:00')"}.get(t[0], "''")
89
+ s = re.sub(r"\{\w+:(\w[^}]*)\}", typed, s)
90
+ s = re.sub(r"\b(LIMIT|OFFSET)\s+:\w+", r"\1 10", s, flags=re.I)
91
+ s = re.sub(r"\bIN\s*\(\s*:\w+\s*\)", r"IN (NULL)", s, flags=re.I)
92
+ s = re.sub(r"(?<![:\w]):[A-Za-z_]\w*\b(?!:)", stand, s)
93
+ s = re.sub(r"%\(\w+\)s|%s|@\w+\b|\$\d+", stand, s)
94
+ s = re.sub(r"(?<![?\w])\?\?", stand, s)
95
+ s = re.sub(r"(?<![?\w])\?(?!\?)", stand, s)
96
+ return s
97
+ return _outside_strings(sql, fn)
98
+
99
+
100
+ def parses(sql: str, engine: str) -> bool:
101
+ try:
102
+ sqlglot.parse_one(sql, dialect="clickhouse" if engine == "clickhouse" else "postgres")
103
+ return True
104
+ except Exception:
105
+ return False
106
+
107
+
108
+ def first_error(text: str) -> str:
109
+ m = re.search(r"DB::Exception: (.*?)(?: \(version|$)", text or "", re.S)
110
+ return " ".join(((m.group(1) if m else text) or "").split())[:200]
111
+
112
+
113
+ class PlanGate:
114
+ """One sandbox of one engine with the schema built, answering plan() per statement."""
115
+
116
+ def __init__(self, engine: str, sandbox):
117
+ self.engine = engine
118
+ self.sb = sandbox
119
+ self.created = 0
120
+ self.failed: list[str] = []
121
+
122
+ # ---- schema --------------------------------------------------------------------------------------
123
+ def build_postgres(self, catalog: dict | None, inventory: dict | None) -> None:
124
+ def q(n: str) -> str:
125
+ return '"' + n.replace('"', '""') + '"'
126
+ for ext in ("pg_trgm", '"uuid-ossp"', "pgcrypto"):
127
+ self.sb._try(f"CREATE EXTENSION IF NOT EXISTS {ext}")
128
+ tabs = []
129
+ for t in (catalog or {}).get("tables") or []:
130
+ tabs.append((t.get("schema") or "public", t["name"], [(c["name"], c.get("type") or "text") for c in t.get("columns") or []]))
131
+ for t in (inventory or {}).get("tables") or []:
132
+ if t.get("test_only") or t.get("engine") not in ("", None, "postgres") or "«" in t.get("name", ""):
133
+ continue
134
+ n = t["name"].replace('"', "")
135
+ sch, nm = n.split(".", 1) if "." in n else ("public", n)
136
+ if t.get("columns"):
137
+ tabs.append((sch, nm, [(c["name"], c.get("type") or "text") for c in t["columns"]]))
138
+ done = set()
139
+ for sch, nm, cols in tabs:
140
+ if (sch, nm) in done or not cols:
141
+ continue
142
+ self.sb._try(f"CREATE SCHEMA IF NOT EXISTS {q(sch)}")
143
+ err = self.sb._try(f"CREATE TABLE {q(sch)}.{q(nm)} ({', '.join(f'{q(c)} {ty}' for c, ty in cols)})")
144
+ if err:
145
+ err = self.sb._try(f"CREATE TABLE {q(sch)}.{q(nm)} ({', '.join(f'{q(c)} text' for c, _ in cols)})")
146
+ if err:
147
+ self.failed.append(f"{sch}.{nm}")
148
+ else:
149
+ done.add((sch, nm))
150
+ self.created += 1
151
+
152
+ def build_clickhouse(self, catalog: dict | None) -> None:
153
+ from ..engines.clickhouse import plain_engine
154
+ tabs = sorted((catalog or {}).get("tables") or [], key=lambda t: t.get("engine") in ("View", "MaterializedView"))
155
+ for d in {t["database"] for t in tabs}:
156
+ self._ch(f"CREATE DATABASE IF NOT EXISTS `{d}`")
157
+ seen: set[str] = set()
158
+ pending = tabs
159
+ for _round in range(3):
160
+ failed = []
161
+ for t in pending:
162
+ sql = plain_engine(t.get("create_sql") or "")
163
+ if "storage_policy" in sql:
164
+ sql = re.sub(r"SETTINGS .*$", "", sql)
165
+ cols = ", ".join(f"`{c['name']}` {c['type']}" for c in t.get("columns") or [])
166
+ if t.get("engine") == "MaterializedView" or (_round == 2 and cols):
167
+ sql = f"CREATE TABLE `{t['database']}`.`{t['name']}` ({cols}) ENGINE=MergeTree ORDER BY tuple()" if cols else ""
168
+ if not sql or self._ch(sql) is not None:
169
+ failed.append(t)
170
+ continue
171
+ self.created += 1
172
+ if t["name"] not in seen and t["database"] != "default":
173
+ seen.add(t["name"])
174
+ # unqualified names resolve in `default`: a copy of each name's first definition is put there
175
+ if t.get("engine") == "View":
176
+ self._ch(re.sub(r"CREATE VIEW \S+", f"CREATE VIEW default.`{t['name']}`", sql, count=1))
177
+ else:
178
+ self._ch(f"CREATE TABLE IF NOT EXISTS default.`{t['name']}` AS `{t['database']}`.`{t['name']}`")
179
+ pending = failed
180
+ if not pending:
181
+ break
182
+ self.failed += [f"{t['database']}.{t['name']}" for t in pending]
183
+
184
+ def _ch(self, sql: str) -> str | None:
185
+ try:
186
+ self.sb._http(sql)
187
+ return None
188
+ except Exception as e: # QueryError: the server's message
189
+ return str(e)
190
+
191
+ # ---- one statement -------------------------------------------------------------------------------
192
+ def plan(self, sql: str) -> dict:
193
+ k = kind(sql)
194
+ out = {"kind": k, "parsed": parses(sql, self.engine), "planned": None, "error": ""}
195
+ if k not in ("select", "insert", "update", "delete"):
196
+ return out
197
+ if self.engine == "clickhouse":
198
+ return {**out, **self._plan_ch(sql, k)}
199
+ s = pg_binds(sql).strip().rstrip(";")
200
+ # one statement per call: an error is then always this statement's (PREPARE plans, it never executes)
201
+ err = self.sb._try(f"PREPARE codecop_family_plan AS {s}")
202
+ if not err:
203
+ self.sb._try("DEALLOCATE codecop_family_plan")
204
+ return {**out, "planned": not err, "error": " ".join(err.split())[:200]}
205
+
206
+ def _plan_ch(self, sql: str, k: str) -> dict:
207
+ best = None
208
+ for stand in CH_STANDINS:
209
+ s = re.sub(r"\s+FORMAT\s+\w+\s*$", "", ch_binds(sql, stand).strip().rstrip(";"), flags=re.I)
210
+ if k == "select":
211
+ err = self._ch("EXPLAIN PLAN " + s)
212
+ elif k == "insert":
213
+ m = re.search(r"\b(SELECT|WITH)\b.*", s, re.S | re.I)
214
+ t = re.match(r"\s*INSERT\s+INTO\s+(?:TABLE\s+)?([`\w.]+)", s, re.I)
215
+ err = None if t else "no target"
216
+ if t:
217
+ try:
218
+ if self.sb._http("EXISTS TABLE " + t.group(1)).strip() == "0":
219
+ err = "UNKNOWN_TABLE " + t.group(1)
220
+ except Exception as e:
221
+ err = str(e)
222
+ if err is None and m and not re.search(r"\bVALUES\b", s[:m.start()], re.I):
223
+ err = self._ch("EXPLAIN PLAN " + m.group(0))
224
+ else:
225
+ return {"planned": None, "error": ""}
226
+ r = {"planned": err is None, "error": first_error(err or "")}
227
+ if best is None or r["planned"]:
228
+ best = r
229
+ if r["planned"] or not CH_RETRY.search(err or ""):
230
+ break
231
+ return best
232
+
233
+
234
+ def run(out_dir: Path, families_doc: dict, *, catalogs: dict[str, dict], inventory: dict | None, versions: dict[str, str],
235
+ log=lambda m: None) -> dict:
236
+ """Plan every variant of every family, one sandbox per engine; write families_plan.json and return it."""
237
+ from ..engines.clickhouse import ClickHouseSandbox
238
+ from ..engines.postgres import PostgresSandbox
239
+ try:
240
+ before = json.loads((Path(out_dir) / "families_plan.json").read_text())
241
+ except (OSError, ValueError):
242
+ before = {}
243
+ result: dict[str, dict] = dict(before.get("variants") or {}) # a variant planned once is not planned again
244
+ report: dict[str, dict] = dict(before.get("engines") or {})
245
+ by_engine: dict[str, dict[str, str]] = {}
246
+ for f in families_doc.get("families") or []:
247
+ eng = f["site"].get("engine") or "postgres"
248
+ for v in f["variants"]:
249
+ if v["id"] not in result:
250
+ by_engine.setdefault(eng, {})[v["id"]] = v["sql"]
251
+ for eng, stmts in by_engine.items():
252
+ if eng not in ("postgres", "clickhouse"):
253
+ continue
254
+ sb = PostgresSandbox(versions.get("postgres", "16")) if eng == "postgres" else ClickHouseSandbox(versions.get("clickhouse", "25.8"))
255
+ sb.start()
256
+ try:
257
+ gate = PlanGate(eng, sb)
258
+ if eng == "postgres":
259
+ gate.build_postgres(catalogs.get("postgres"), inventory)
260
+ else:
261
+ gate.build_clickhouse(catalogs.get("clickhouse"))
262
+ log(f"{eng}: {gate.created} tables created, {len(gate.failed)} not")
263
+ for vid, sql in stmts.items():
264
+ result[vid] = gate.plan(sql)
265
+ report[eng] = {"tables": gate.created, "tables_failed": gate.failed[:50], "variants": len(stmts),
266
+ "planned": sum(1 for v in stmts if result[v].get("planned"))}
267
+ finally:
268
+ sb.stop()
269
+ doc = {"schema_version": 1, "engines": report, "variants": result}
270
+ (Path(out_dir) / "families_plan.json").write_text(json.dumps(doc))
271
+ return doc
@@ -0,0 +1,174 @@
1
+ """The small tag-helper patch for a repository: printed, never applied.
2
+
3
+ A query tag (`codecop:<file>:<line>`, docs/query-tags.md) places a statement production ran on its call site with no
4
+ ambiguity, and is the only way to the ClickHouse reads no text or fragment places. Tagging every call site is not
5
+ realistic (often dozens of distinct callees per engine in one repository); one helper per client type that reads
6
+ its caller's file and line is. This module finds, per language and engine, the client calls the inventory's call
7
+ sites go through most, and prints a unified diff that adds one helper file per (language, engine) and wraps the calls
8
+ in the busiest wrapper functions. The user reviews and applies it; CodeCop never writes to the repository.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import difflib
14
+ import os
15
+ import re
16
+ from collections import Counter, defaultdict
17
+ from pathlib import Path
18
+
19
+ DEFAULTS = {"max_wrappers": 8}
20
+
21
+ HELPERS = {
22
+ ("go", "clickhouse"): ("codecop_tag.go", """package {pkg}
23
+
24
+ import (
25
+ \t"context"
26
+ \t"fmt"
27
+ \t"runtime"
28
+ \t"strings"
29
+
30
+ \t"github.com/ClickHouse/clickhouse-go/v2"
31
+ )
32
+
33
+ // codecopTag sets the query's log_comment to the caller's file and line (docs/query-tags.md), so CodeCop places the
34
+ // statement production ran on the call site that sent it.
35
+ func codecopTag(ctx context.Context) context.Context {{
36
+ \t_, file, line, _ := runtime.Caller(2)
37
+ \tif i := strings.Index(file, "/{trim}/"); i >= 0 {{
38
+ \t\tfile = file[i+1:]
39
+ \t}}
40
+ \treturn clickhouse.Context(ctx, clickhouse.WithSettings(clickhouse.Settings{{"log_comment": fmt.Sprintf("codecop:%s:%d", file, line)}}))
41
+ }}
42
+ """),
43
+ ("go", "postgres"): ("codecop_tag.go", """package {pkg}
44
+
45
+ import (
46
+ \t"fmt"
47
+ \t"runtime"
48
+ \t"strings"
49
+ )
50
+
51
+ // codecopTag prefixes a statement with a comment naming the caller's file and line (docs/query-tags.md). PostgreSQL keeps
52
+ // the comment in the text pg_stat_statements stores for the shape; CodeCop reads it.
53
+ func codecopTag(sql string) string {{
54
+ \t_, file, line, _ := runtime.Caller(2)
55
+ \tif i := strings.Index(file, "/{trim}/"); i >= 0 {{
56
+ \t\tfile = file[i+1:]
57
+ \t}}
58
+ \treturn fmt.Sprintf("/* codecop:%s:%d */ %s", file, line, sql)
59
+ }}
60
+ """),
61
+ ("rust", "clickhouse"): ("codecop_tag.rs", """//! codecop_tag: the caller's file and line as the query's log_comment (docs/query-tags.md).
62
+ #[track_caller]
63
+ pub fn codecop_tag() -> String {{
64
+ let at = std::panic::Location::caller();
65
+ format!("codecop:{{}}:{{}}", at.file(), at.line())
66
+ }}
67
+ """),
68
+ ("rust", "postgres"): ("codecop_tag.rs", """//! codecop_tag: a comment naming the caller's file and line, kept by pg_stat_statements (docs/query-tags.md).
69
+ #[track_caller]
70
+ pub fn codecop_tag(sql: &str) -> String {{
71
+ let at = std::panic::Location::caller();
72
+ format!("/* codecop:{{}}:{{}} */ {{}}", at.file(), at.line(), sql)
73
+ }}
74
+ """),
75
+ ("python", "clickhouse"): ("codecop_tag.py", '''"""codecop_tag: the caller's file and line as the query's log_comment (docs/query-tags.md)."""
76
+ import inspect
77
+ import os
78
+
79
+ _ROOT = os.path.dirname(os.path.abspath(__file__))
80
+
81
+
82
+ def codecop_tag(settings=None):
83
+ frame = inspect.stack()[2]
84
+ return {{**(settings or {{}}), "log_comment": f"codecop:{{os.path.relpath(frame.filename, _ROOT)}}:{{frame.lineno}}"}}
85
+ '''),
86
+ ("python", "postgres"): ("codecop_tag.py", '''"""codecop_tag: a comment naming the caller's file and line, kept by pg_stat_statements (docs/query-tags.md)."""
87
+ import inspect
88
+ import os
89
+
90
+ _ROOT = os.path.dirname(os.path.abspath(__file__))
91
+
92
+
93
+ def codecop_tag(sql):
94
+ frame = inspect.stack()[2]
95
+ return f"/* codecop:{{os.path.relpath(frame.filename, _ROOT)}}:{{frame.lineno}} */ {{sql}}"
96
+ '''),
97
+ }
98
+
99
+
100
+ def wrappers(inventory: dict) -> dict[tuple[str, str], list[dict]]:
101
+ """(language, engine) -> the functions whose client calls carry the most call sites (wrappers first)."""
102
+ out: dict[tuple[str, str], Counter] = defaultdict(Counter)
103
+ where: dict[tuple, dict] = {}
104
+ for s in inventory.get("call_sites") or []:
105
+ if s.get("is_test") or s.get("kind") != "call" or s.get("engine") not in ("clickhouse", "postgres"):
106
+ continue
107
+ key = (s.get("language"), s["engine"])
108
+ if key not in HELPERS:
109
+ continue
110
+ fn = (s["file"], s.get("symbol") or "", s.get("sink") or "")
111
+ out[key][fn] += 1 + (5 if not s.get("known_sink", True) or s.get("resolution") == "parameter" else 0)
112
+ where.setdefault((key, fn), s)
113
+ return {k: [{"file": f, "symbol": sym, "sink": sink, "weight": n, "line": where[(k, (f, sym, sink))]["line"]}
114
+ for (f, sym, sink), n in c.most_common()] for k, c in out.items()}
115
+
116
+
117
+ def _wrap_line(line: str, lang: str, engine: str) -> str | None:
118
+ if lang == "go" and engine == "clickhouse":
119
+ new = re.sub(r"\.(Query|QueryRow|Exec|Select)\(\s*ctx\b", r".\1(codecopTag(ctx)", line, count=1)
120
+ elif lang == "go":
121
+ new = re.sub(r"\.(Query|QueryRow|Exec|QueryContext|QueryRowContext|ExecContext)\((\s*ctx\s*,\s*)(\w+)", r".\1(\2codecopTag(\3)", line, count=1)
122
+ elif lang == "python" and engine == "clickhouse":
123
+ new = re.sub(r"\.(query|command|query_df|query_arrow)\((.*)\)\s*$", lambda m: f".{m.group(1)}({m.group(2)}, settings=codecop_tag())"
124
+ if "settings=" not in m.group(2) else m.group(0), line, count=1)
125
+ elif lang == "python":
126
+ new = re.sub(r"\.(execute|fetch|fetchrow|fetchval)\(\s*(\w+)", r".\1(codecop_tag(\2)", line, count=1)
127
+ elif lang == "rust" and engine == "postgres":
128
+ new = re.sub(r"sqlx::query(_as|_scalar)?(::<[^>]*>)?\(\s*(&?\w+)", r"sqlx::query\1\2(&codecop_tag(\3)", line, count=1)
129
+ else:
130
+ new = re.sub(r"\.query\(\s*(&?\w+)\s*\)", r".query(\1).with_option(\"log_comment\", codecop_tag())", line, count=1)
131
+ return new if new != line else None
132
+
133
+
134
+ def patch(root: Path, inventory: dict, settings: dict | None = None) -> tuple[str, list[dict]]:
135
+ """(unified diff text, the wrappers it changes). Reads the repository; writes nothing."""
136
+ cfg = {**DEFAULTS, **(settings or {})}
137
+ root = Path(root)
138
+ diffs: list[str] = []
139
+ changed: list[dict] = []
140
+ trim = root.name
141
+ for (lang, engine), ws in sorted(wrappers(inventory).items()):
142
+ edits: dict[str, list[str]] = {}
143
+ for w in ws[: int(cfg["max_wrappers"])]:
144
+ path = root / w["file"]
145
+ try:
146
+ lines = edits.get(w["file"]) or path.read_text(encoding="utf-8", errors="replace").splitlines(keepends=True)
147
+ except OSError:
148
+ continue
149
+ i = int(w["line"]) - 1
150
+ for j in range(max(0, i - 2), min(len(lines), i + 4)):
151
+ new = _wrap_line(lines[j], lang, engine)
152
+ if new:
153
+ lines[j] = new
154
+ edits[w["file"]] = lines
155
+ changed.append({**w, "language": lang, "engine": engine, "edited_line": j + 1})
156
+ break
157
+ if not edits:
158
+ continue
159
+ first = sorted(edits)[0]
160
+ name, body = HELPERS[(lang, engine)]
161
+ pkg = os.path.basename(os.path.dirname(first)) or "main"
162
+ if lang == "go":
163
+ src = (root / first).read_text(encoding="utf-8", errors="replace")
164
+ m = re.search(r"^package\s+(\w+)", src, re.M)
165
+ pkg = m.group(1) if m else pkg
166
+ helper_path = os.path.join(os.path.dirname(first), name if not (root / os.path.dirname(first) / name).exists() else f"codecop_tag_{engine}{os.path.splitext(name)[1]}")
167
+ text = body.format(pkg=pkg, trim=trim)
168
+ diffs.append("".join(difflib.unified_diff([], text.splitlines(keepends=True), "/dev/null", f"b/{helper_path}")))
169
+ for f, lines in sorted(edits.items()):
170
+ old = (root / f).read_text(encoding="utf-8", errors="replace").splitlines(keepends=True)
171
+ diffs.append("".join(difflib.unified_diff(old, lines, f"a/{f}", f"b/{f}")))
172
+ head = ("# CodeCop query-tag helpers (docs/query-tags.md). Review, then apply with `git apply`; CodeCop never applies it.\n"
173
+ "# Rust: add `mod codecop_tag;` where the helper lands and import it; Python: import codecop_tag in the edited files.\n")
174
+ return head + "".join(diffs), changed