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/writes.py ADDED
@@ -0,0 +1,1208 @@
1
+ """Writes as statements: INSERT, UPDATE, DELETE, upserts and INSERT ... SELECT benchmarked like reads, with no agent.
2
+
3
+ Discovery finds every write and, until this module, none was ever benchmarked (writes are a large share of the
4
+ sites and of PostgreSQL executions in a typical application). Each write statement of the run's engine whose text is fixed in the code
5
+ (literal, constant, a .sql file, or discover's ORM translation whose run-time parts are only values) becomes a candidate
6
+ of its own, `W-001`, made runnable by rule:
7
+
8
+ text driver placeholders (`?`, `%s`, `%(name)s`, `:name`) and ORM value slots (`«expr»` beside a comparison, in a
9
+ VALUES list or a SET) become `$n`; a «…» that is a whole condition, a column list or a table chosen per
10
+ call is a run-time part, and the site says so (`write_has_run_time_parts`)
11
+ slots what each `$n` is: a value compared with a column (`where`), a value written to a column (`set`, `insert`,
12
+ `conflict`), a LIMIT, or none of these (`other`); read from the parsed statement (sqlglot)
13
+ values chosen in the sandbox when it runs (writebench.py): a `where` value from a row the table holds (so the
14
+ statement touches rows, as it does in production), a written value copied from such a row, a fresh one
15
+ for a column a unique index or the primary key holds; tried on a few rows until the statement touches one
16
+ variants "UPDATE/DELETE with no usable index for its predicate": an index on the predicate's equality columns, then
17
+ its range column, when no index of the table starts with them (rule `write_no_usable_index`); the insert
18
+ side of the index is measured as for any index (writecost.py)
19
+
20
+ What decides (outcome, read by blockers.candidate_outcome): every run is inside a transaction that is rolled back (on
21
+ ClickHouse, which has none, on an empty or copied table), so the sandbox's rows are the same for the baseline and every
22
+ variant. A variant counts only when its final table state and RETURNING output equal the baseline's (`same_final_state`)
23
+ and it touches fewer pages; then its cost: rows read, WAL / bytes written, time. A write whose predicate reaches the rows
24
+ it changes through an index, or a single-row INSERT, is at the floor: "nothing to gain, measured".
25
+
26
+ writes.json (FILE) holds the plan: per write call site the candidate it became or why not (one reason, one next step).
27
+ Settings under `[writes]` in codecop.toml (DEFAULTS).
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import copy
33
+ import hashlib
34
+ import re
35
+ from collections import Counter
36
+ from datetime import datetime, timezone
37
+
38
+ import sqlglot
39
+ from sqlglot import exp
40
+
41
+ FILE = "writes.json"
42
+ SCHEMA_VERSION = 1
43
+ STATEMENTS = ("insert", "update", "delete")
44
+ DEFAULTS = {
45
+ "build": True, # make write candidates at all
46
+ "max_candidates": 3000, # the most write candidates one bench makes (heaviest measured first, then by call sites)
47
+ "limit_value": 50, # a LIMIT whose value is a parameter runs with this many
48
+ "probe_rows": 6, # rows tried for the values of a WHERE before the statement is said to touch nothing
49
+ "array_items": 3, # items of an array parameter (`= ANY($1)`)
50
+ "floor_rows": 200, # a write that scans at most this many rows beyond the rows it changes is at the floor
51
+ "index_rule": True, # propose an index for an UPDATE/DELETE whose predicate no index serves
52
+ "roles": "migration", # comma list of call-site roles to leave out; migrations, seeds and backfills run once: nothing to
53
+ # gain there, so they are not benchmarked ("" benchmarks every non-test role)
54
+ }
55
+ # Why a write call site has no write candidate: exactly one reason, one next step (the shared vocabulary's wording)
56
+ REASONS = {
57
+ "write_other_engine": "scan_with_its_engine", # the write is for another engine than this run's
58
+ "write_engine_not_benchmarkable": "none_codecop_side", # an engine CodeCop has no sandbox for (MySQL, ...)
59
+ "write_no_statement_text": "ask_agent_for_statement", # no SQL text at the site
60
+ "write_has_run_time_parts": "ask_agent_for_statement", # a «…» that is not a value: a condition, columns, a table
61
+ "write_does_not_parse": "none_codecop_side", # the parser does not take the statement
62
+ "write_table_not_defined": "pull_its_database", # a table it writes has no definition in catalog or schema
63
+ "write_role_left_out": "change_writes_roles_setting", # its role is in [writes] roles
64
+ "write_over_max": "raise_writes_max_candidates", # over [writes] max_candidates
65
+ "write_same_as_another": "none", # the same text as another site's candidate (shares its outcome)
66
+ }
67
+ WORDS = {
68
+ "write_other_engine": "a write for another engine than this run's",
69
+ "write_engine_not_benchmarkable": "a write on an engine CodeCop has no sandbox for",
70
+ "write_no_statement_text": "no SQL text at the call site",
71
+ "write_has_run_time_parts": "a part of the statement is only known at run time",
72
+ "write_does_not_parse": "the statement does not parse",
73
+ "write_table_not_defined": "a table it writes is in neither the pulled catalog nor the repository's schema",
74
+ "write_role_left_out": "its role is left out ([writes] roles)",
75
+ "write_over_max": "over [writes] max_candidates",
76
+ "write_same_as_another": "the same statement as another call site",
77
+ }
78
+ # outcome reasons of a benchmarked write (blockers.STATES vocabulary; the ones below are new)
79
+ OUTCOME_REASONS = {
80
+ "nothing_to_gain": ("write_at_floor", "write_runs_once"),
81
+ "blocked": ("write_state_differs",),
82
+ "not_judged": ("write_state_not_compared", "write_touches_no_rows", "write_not_replayable"),
83
+ }
84
+ NEXT_STEP = {"write_at_floor": "none", "write_runs_once": "none", "write_state_differs": "read_the_variant_by_hand",
85
+ "write_state_not_compared": "none_codecop_side", "write_touches_no_rows": "add_fixture_rows",
86
+ "write_not_replayable": "none_codecop_side"}
87
+ ONE_OFF_ROLES = ("migration", "script") # a write that runs once: an index never pays for itself
88
+ DIALECT = {"postgres": "postgres", "sqlite": "sqlite", "clickhouse": "clickhouse"}
89
+ INV_FRAGMENT = re.compile(r"«([^«»]*)»")
90
+ VALUE_BEFORE = re.compile(r"(?:=|<>|!=|<=|>=|<|>|\bLIKE|\bILIKE|\bIN|\bANY|\bALL|\bVALUES|\bSET\s+[\w\".]+\s*=)\s*\(?\s*$|[(,]\s*$", re.I)
91
+ LIMIT_BEFORE = re.compile(r"\b(LIMIT|OFFSET)\s*$", re.I)
92
+ VALUE_INNER = re.compile(r"[\w.]+\(\)|(?:[\w.]+\()*[\w.]+(?:\[[\w.'\"]+\])*(?:\.\w+)*\)*")
93
+ DRIVER = re.compile(r"%\((\w+)\)s|%s|(?<![:\w]):([A-Za-z_]\w*)\b(?!\s*\()|\?(?![?|&])|\$(\d+)|@(\w+)\b")
94
+ PG_CASTS = re.compile(r"::\s*[A-Za-z_][\w ]*(?:\[\])?")
95
+
96
+
97
+ def settings_of(config: dict | None) -> dict:
98
+ out = dict(DEFAULTS)
99
+ for k, d in DEFAULTS.items():
100
+ v = (config or {}).get(k)
101
+ if v is None:
102
+ continue
103
+ if isinstance(d, bool):
104
+ if isinstance(v, bool):
105
+ out[k] = v
106
+ elif isinstance(d, str):
107
+ if isinstance(v, str):
108
+ out[k] = v
109
+ elif isinstance(v, (int, float)) and not isinstance(v, bool) and v >= 0:
110
+ out[k] = type(d)(v)
111
+ return out
112
+
113
+
114
+ def now() -> str:
115
+ return datetime.now(timezone.utc).isoformat(timespec="seconds")
116
+
117
+
118
+ def bare(name: str) -> str:
119
+ return re.sub(r"[`\"\[\]]", "", name or "").split(".")[-1].lower()
120
+
121
+
122
+ # ---------------------------------------------------------------------------- the statement's text with $n
123
+
124
+ def _quoted_spans(sql: str):
125
+ """(start, end, quoted) pieces of `sql`: quoted when inside a string literal, a quoted identifier or a comment."""
126
+ i, n, start = 0, len(sql), 0
127
+ while i < n:
128
+ ch = sql[i]
129
+ if ch in "'\"`":
130
+ if start < i:
131
+ yield start, i, False
132
+ j = i + 1
133
+ while j < n:
134
+ if sql[j] == ch:
135
+ if j + 1 < n and sql[j + 1] == ch:
136
+ j += 2
137
+ continue
138
+ break
139
+ j += 1
140
+ yield i, min(j + 1, n), True
141
+ i = start = j + 1
142
+ continue
143
+ if sql.startswith("--", i):
144
+ if start < i:
145
+ yield start, i, False
146
+ j = sql.find("\n", i)
147
+ j = n if j < 0 else j
148
+ yield i, j, True
149
+ i = start = j
150
+ continue
151
+ i += 1
152
+ if start < n:
153
+ yield start, n, False
154
+
155
+
156
+ def write_text(site: dict, engine: str, cfg: dict | None = None) -> tuple[str | None, list[str], str]:
157
+ """The write as the sandbox runs it, every value it takes as `$n`: (sql, notes, why_not as a REASONS code).
158
+
159
+ A ClickHouse `{name:Type}` parameter is kept as it is (it carries its type); every other placeholder becomes `$n`."""
160
+ cfg = settings_of(cfg)
161
+ sql = site.get("sql") or ""
162
+ if not sql.strip():
163
+ return None, [], "write_no_statement_text"
164
+ notes: list[str] = []
165
+ # SQLAlchemy's `col(Model.column).in_(values)` (and `Model.column.in_(...)`) as discover writes it: a list parameter
166
+ ins = 0
167
+
168
+ def in_list(m: re.Match) -> str:
169
+ nonlocal ins
170
+ ins += 1
171
+ return f"{m.group(1)} {'<> ALL' if m.group(2) == 'not_in_' else '= ANY'}(«{m.group(3).strip() or 'values'}»)"
172
+ sql = re.sub(r"«\s*(?:col\()?\s*\w+\.(\w+)\s*\)?\s*\.(in_|not_in_)\(([^«»()]*(?:\([^«»()]*\))?[^«»()]*)\)\s*»", in_list, sql)
173
+ if ins:
174
+ notes.append("an ORM `.in_(values)` runs as `= ANY($n)` with a list of values")
175
+ if "«" in sql:
176
+ out, last, n = [], 0, 0
177
+ taken = {int(x) for x in re.findall(r"\$(\d+)", sql)}
178
+ n = max(taken) if taken else 0
179
+ for m in INV_FRAGMENT.finditer(sql):
180
+ before = sql[last:m.start()]
181
+ inner = m.group(1).strip()
182
+ if not VALUE_INNER.fullmatch(inner) or inner.count("(") != inner.count(")") or inner.startswith("**"):
183
+ return None, [], "write_has_run_time_parts"
184
+ if LIMIT_BEFORE.search(before):
185
+ out.append(before + str(int(cfg["limit_value"])))
186
+ notes.append(f"{LIMIT_BEFORE.search(before).group(1).upper()} «{inner[:40]}» run as {int(cfg['limit_value'])} ([writes] limit_value)")
187
+ elif VALUE_BEFORE.search(before):
188
+ n += 1
189
+ out.append(before + f"${n}")
190
+ else:
191
+ return None, [], "write_has_run_time_parts"
192
+ last = m.end()
193
+ out.append(sql[last:])
194
+ sql = "".join(out)
195
+ if site.get("resolution") in ("orm", "template"):
196
+ notes.append("the ORM call's SQL as CodeCop translated it; every value it passes is a parameter")
197
+ if "«" in sql or "»" in sql or re.search(r"\{\{|\{%|\$\{", sql):
198
+ return None, [], "write_has_run_time_parts"
199
+ if engine == "clickhouse" and re.search(r"\{\w+\s*:\s*[^{}]+\}", sql) and not re.search(r"\$\d+|\?", sql):
200
+ return sql, notes, ""
201
+ # driver placeholders, outside quotes, numbered in order of appearance (a repeated name keeps its number)
202
+ has_dollar = bool(re.search(r"\$\d+", sql))
203
+ out, names, n = [], {}, 0
204
+ for a, b, quoted in _quoted_spans(sql):
205
+ part = sql[a:b]
206
+ if quoted:
207
+ out.append(part)
208
+ continue
209
+ pos = 0
210
+ for m in DRIVER.finditer(part):
211
+ if m.group(3) is not None:
212
+ if not has_dollar:
213
+ continue
214
+ out.append(part[pos:m.start()] + m.group(0))
215
+ pos = m.end()
216
+ continue
217
+ if has_dollar:
218
+ continue # a statement written with $n keeps its own numbers; nothing else is a placeholder
219
+ if m.group(0).startswith(":") and m.start() > 0 and part[m.start() - 1] == ":":
220
+ continue # `::type` is a cast, never a name
221
+ key = m.group(1) or m.group(2) or m.group(4)
222
+ if key and key in names:
223
+ num = names[key]
224
+ else:
225
+ n += 1
226
+ num = n
227
+ if key:
228
+ names[key] = num
229
+ out.append(part[pos:m.start()] + f"${num}")
230
+ pos = m.end()
231
+ out.append(part[pos:])
232
+ text = "".join(out)
233
+ if n and not has_dollar:
234
+ notes.append("the driver's placeholders read as $n")
235
+ return text, notes, ""
236
+
237
+
238
+ # ---------------------------------------------------------------------------- what the statement does
239
+
240
+ def _parseable(sql: str) -> tuple[str, dict[str, int]]:
241
+ """`$n` -> `:codecop_pN` (sqlglot reads `$1,$2` as a dollar-quoted string), ClickHouse `{x:T}` -> `:codecop_x`."""
242
+ names: dict[str, int] = {}
243
+
244
+ def num(m: re.Match) -> str:
245
+ names[f"codecop_p{m.group(1)}"] = int(m.group(1))
246
+ return f" :codecop_p{m.group(1)} "
247
+ text = re.sub(r"\$(\d+)", num, sql)
248
+ text = re.sub(r"\{(\w+)\s*:\s*[^{}]+\}", lambda m: f" :codecop_c_{m.group(1)} ", text)
249
+ return text, names
250
+
251
+
252
+ def parse(sql: str, engine: str):
253
+ text, _ = _parseable(sql)
254
+ try:
255
+ tree = sqlglot.parse_one(text, read=DIALECT.get(engine, "postgres"))
256
+ except Exception: # noqa: BLE001 - a statement the parser does not take gives no shape
257
+ return None
258
+ return tree
259
+
260
+
261
+ def _slot_of(node) -> str | None:
262
+ """The `$n` (as 'pN') or ClickHouse name (as 'c_x') a node is, through casts, ANY() and parentheses."""
263
+ while isinstance(node, (exp.Paren, exp.Cast, exp.TryCast, exp.Any, exp.All)):
264
+ node = node.this
265
+ if isinstance(node, exp.Placeholder) and str(node.this or "").startswith("codecop_"):
266
+ return str(node.this)[len("codecop_"):]
267
+ return None
268
+
269
+
270
+ def _table_name(t: exp.Table) -> str:
271
+ parts = [p.name for p in (t.args.get("catalog"), t.args.get("db"), t.this) if p is not None and getattr(p, "name", None)]
272
+ return ".".join(parts)
273
+
274
+
275
+ def _aliases(tree) -> dict[str, str]:
276
+ out: dict[str, str] = {}
277
+ for t in tree.find_all(exp.Table):
278
+ name = _table_name(t)
279
+ if not name:
280
+ continue
281
+ out.setdefault(bare(name), name)
282
+ if t.alias:
283
+ out[t.alias.lower()] = name
284
+ ctes = {c.alias.lower() for c in tree.find_all(exp.CTE) if c.alias}
285
+ for c in ctes:
286
+ out.pop(c, None)
287
+ return out
288
+
289
+
290
+ def analyse(sql: str, engine: str) -> dict | None:
291
+ """What a write does, from its parsed text. None when it does not parse as a write.
292
+
293
+ {kind: insert_values | insert_multi | insert_select | upsert | update | delete | ch_mutation, target, tables (every
294
+ table it names, CTEs left out), slots: {pN: {role, table, column, op}}, returning, conflict: [cols], where: text of
295
+ the target's WHERE (UPDATE / DELETE), key: {eq: [...], range: [...]} the target's predicate columns, set_columns}"""
296
+ tree = parse(sql, engine)
297
+ if tree is None:
298
+ return None
299
+ root = tree
300
+ if isinstance(root, exp.With):
301
+ root = root.this
302
+ writes = [n for n in tree.walk() if isinstance(n, (exp.Insert, exp.Update, exp.Delete))]
303
+ alter_mut = engine == "clickhouse" and re.match(r"^\s*ALTER\s+TABLE\s+\S+\s+(?:ON\s+CLUSTER\s+\S+\s+)?(UPDATE|DELETE)\b", sql, re.I)
304
+ if not writes and not alter_mut:
305
+ return None
306
+ aliases = _aliases(tree)
307
+ ctes = {c.alias.lower() for c in tree.find_all(exp.CTE) if c.alias}
308
+ info: dict = {"slots": {}, "returning": False, "conflict": [], "where": "", "key": {"eq": [], "range": [], "in": []}, "set_columns": [],
309
+ "tables": sorted({n for k, n in aliases.items() if k == bare(n) and bare(n) not in ctes})}
310
+ if alter_mut:
311
+ m = re.match(r"^\s*ALTER\s+TABLE\s+(\S+)", sql, re.I)
312
+ info.update(kind="ch_mutation", target=re.sub(r"[`\"]", "", m.group(1)), mutation=alter_mut.group(1).lower())
313
+ return info
314
+ main = root if isinstance(root, (exp.Insert, exp.Update, exp.Delete)) else writes[0]
315
+ tgt = main.this
316
+ if isinstance(tgt, exp.Schema):
317
+ cols = [c.name for c in tgt.expressions if isinstance(c, (exp.Identifier, exp.Column))]
318
+ tgt = tgt.this
319
+ else:
320
+ cols = []
321
+ if not isinstance(tgt, exp.Table):
322
+ return None
323
+ target = _table_name(tgt)
324
+ info["target"] = target
325
+ if bare(target) not in [bare(t) for t in info["tables"]]:
326
+ info["tables"].append(target)
327
+ tgt_alias = (tgt.alias or "").lower()
328
+
329
+ def table_of(col: exp.Column, default: str) -> str:
330
+ q = (col.table or "").lower()
331
+ if q:
332
+ return aliases.get(q, q)
333
+ return default
334
+
335
+ def default_table(node) -> str:
336
+ sel = node.find_ancestor(exp.Select)
337
+ if sel is not None and sel is not main:
338
+ froms = [t for t in sel.find_all(exp.Table) if t.find_ancestor(exp.Select) is sel]
339
+ if len(froms) == 1:
340
+ return _table_name(froms[0])
341
+ return target
342
+
343
+ slots = info["slots"]
344
+ if isinstance(main, exp.Insert):
345
+ src = main.expression
346
+ info["returning"] = main.args.get("returning") is not None
347
+ conflict = main.args.get("conflict")
348
+ if isinstance(src, exp.Values):
349
+ rows = [t for t in src.expressions if isinstance(t, exp.Tuple)]
350
+ info["kind"] = "insert_values" if len(rows) <= 1 else "insert_multi"
351
+ for row in rows:
352
+ for i, v in enumerate(row.expressions):
353
+ s = _slot_of(v)
354
+ if s and i < len(cols):
355
+ slots.setdefault(s, {"role": "insert", "table": target, "column": cols[i]})
356
+ elif src is None:
357
+ info["kind"] = "insert_batch" # `INSERT INTO t (cols)`: the client sends the rows (a driver's batch)
358
+ elif src is not None:
359
+ info["kind"] = "insert_select"
360
+ sel = src if isinstance(src, exp.Select) else src.find(exp.Select)
361
+ if sel is not None:
362
+ for i, e in enumerate(sel.expressions):
363
+ s = _slot_of(e.this if isinstance(e, exp.Alias) else e)
364
+ if s and i < len(cols):
365
+ slots.setdefault(s, {"role": "insert", "table": target, "column": cols[i]})
366
+ if conflict is not None:
367
+ info["kind"] = "upsert"
368
+ info["conflict"] = [c.name for c in (conflict.args.get("conflict_keys") or []) if hasattr(c, "name")]
369
+ info["conflict_action"] = "update" if conflict.args.get("action") is not None and "UPDATE" in conflict.sql().upper() else "nothing"
370
+ for e in conflict.find_all(exp.EQ):
371
+ if isinstance(e.this, exp.Column):
372
+ s = _slot_of(e.expression)
373
+ if s:
374
+ slots.setdefault(s, {"role": "set", "table": target, "column": e.this.name})
375
+ elif isinstance(main, exp.Update):
376
+ info["kind"] = "update"
377
+ info["returning"] = main.args.get("returning") is not None
378
+ for e in main.expressions or []:
379
+ if isinstance(e, exp.EQ) and isinstance(e.this, exp.Column):
380
+ info["set_columns"].append(e.this.name)
381
+ s = _slot_of(e.expression)
382
+ if s:
383
+ slots.setdefault(s, {"role": "set", "table": target, "column": e.this.name})
384
+ else:
385
+ info["kind"] = "delete"
386
+ info["returning"] = main.args.get("returning") is not None
387
+ where = main.args.get("where")
388
+ if where is not None and not isinstance(main, exp.Insert):
389
+ info["where"] = where.this.sql(dialect=DIALECT.get(engine, "postgres"))
390
+ if not main.args.get("from") and not main.args.get("using") and not main.args.get("from_"):
391
+ info["probe_sql"] = _probe_sql(main, where, tgt, engine)
392
+ mine = {tgt_alias, bare(target)} - {""}
393
+ info["row_conditions"] = _row_conditions(where.this, mine, engine)
394
+ for c in _conjuncts(where.this):
395
+ col, other, op = _compare(c)
396
+ if col is None:
397
+ continue
398
+ q = (col.table or "").lower()
399
+ if q and q not in mine:
400
+ continue
401
+ if other is not None and isinstance(_strip(other), exp.Column):
402
+ continue
403
+ if op == "eq":
404
+ info["key"]["eq"].append(col.name)
405
+ elif op == "in":
406
+ info["key"]["in"].append(col.name)
407
+ elif op == "range":
408
+ info["key"]["range"].append(col.name)
409
+ # every other placeholder: compared with a column (where), a LIMIT, or other
410
+ for node in tree.walk():
411
+ if isinstance(node, (exp.Limit, exp.Offset)):
412
+ s = _slot_of(node.expression if node.expression is not None else node.this)
413
+ if s:
414
+ slots.setdefault(s, {"role": "limit"})
415
+ continue
416
+ col, other, op = _compare(node)
417
+ if col is None or other is None:
418
+ continue
419
+ s = _slot_of(other)
420
+ if s:
421
+ slots.setdefault(s, {"role": "where", "table": table_of(col, default_table(node)), "column": col.name, "op": op,
422
+ **({"array": True} if isinstance(_strip(other), (exp.Any, exp.All)) or op == "in_array" else {})})
423
+ for p in tree.find_all(exp.Placeholder):
424
+ s = str(p.this or "")
425
+ if s.startswith("codecop_"):
426
+ slots.setdefault(s[len("codecop_"):], {"role": "other"})
427
+ return info
428
+
429
+
430
+ def _row_conditions(cond, mine: set[str], engine: str) -> list[dict]:
431
+ """Conditions of the write's WHERE on its own table that a value set on a row meets: `col IS NULL`, `col = 'lit'`,
432
+ `col IN ('a', ...)`, a boolean column alone or negated. [{column, value (SQL text)}]: the sandbox sets them on the row
433
+ it runs the write on, inside the rolled-back transaction, when no generated row meets them (writebench)."""
434
+ out = []
435
+ d = DIALECT.get(engine, "postgres")
436
+ for c in _conjuncts(cond):
437
+ c = _strip(c) if isinstance(c, exp.Paren) else c
438
+ col, val = None, None
439
+ if isinstance(c, exp.Is) and isinstance(_strip(c.this), exp.Column) and isinstance(c.expression, exp.Null) and not c.args.get("negate"):
440
+ col, val = _strip(c.this), "NULL"
441
+ elif isinstance(c, exp.EQ) and isinstance(_strip(c.this), exp.Column) and isinstance(_strip(c.expression), (exp.Literal, exp.Boolean)):
442
+ col, val = _strip(c.this), _strip(c.expression).sql(dialect=d)
443
+ elif isinstance(c, exp.In) and isinstance(_strip(c.this), exp.Column) and c.expressions and isinstance(c.expressions[0], (exp.Literal, exp.Boolean)):
444
+ col, val = _strip(c.this), c.expressions[0].sql(dialect=d)
445
+ elif isinstance(c, exp.Column):
446
+ col, val = c, "TRUE"
447
+ elif isinstance(c, exp.Not) and isinstance(_strip(c.this), exp.Column):
448
+ col, val = _strip(c.this), "FALSE"
449
+ if col is None or not isinstance(col.this, exp.Identifier):
450
+ continue
451
+ if col.table and col.table.lower() not in mine:
452
+ continue
453
+ out.append({"column": col.name, "value": val})
454
+ return out
455
+
456
+
457
+ def _probe_sql(main, where, tgt: exp.Table, engine: str) -> str | None:
458
+ """`SELECT * FROM <target> WHERE <its WHERE, each comparison of a column with a value parameter made TRUE>`: the rows
459
+ that meet every other condition of the write, so the values chosen from them make the write touch rows. Other
460
+ parameters stay `$n`. None when it cannot be written."""
461
+ def drop(node):
462
+ col, other, _ = _compare(node)
463
+ if col is not None and other is not None and _slot_of(other):
464
+ return exp.true()
465
+ return node
466
+ try:
467
+ cond = where.this.copy().transform(drop)
468
+ t = tgt.copy()
469
+ text = f"SELECT * FROM {t.sql(dialect=DIALECT.get(engine, 'postgres'))} WHERE {cond.sql(dialect=DIALECT.get(engine, 'postgres'))}"
470
+ except Exception: # noqa: BLE001
471
+ return None
472
+ return re.sub(r":codecop_p(\d+)", r"$\1", text)
473
+
474
+
475
+ def _strip(node):
476
+ while isinstance(node, (exp.Paren, exp.Cast, exp.TryCast)):
477
+ node = node.this
478
+ return node
479
+
480
+
481
+ def _conjuncts(node) -> list:
482
+ node = _strip(node) if isinstance(node, exp.Paren) else node
483
+ if isinstance(node, exp.And):
484
+ return _conjuncts(node.this) + _conjuncts(node.expression)
485
+ return [node]
486
+
487
+
488
+ def _compare(node) -> tuple:
489
+ """(column, other side, op) of a comparison of one column, else (None, None, None). op: eq | in | range | like."""
490
+ if isinstance(node, exp.EQ):
491
+ op = "eq"
492
+ elif isinstance(node, (exp.GT, exp.GTE, exp.LT, exp.LTE)):
493
+ op = "range"
494
+ elif isinstance(node, (exp.Like, exp.ILike)):
495
+ op = "like"
496
+ elif isinstance(node, exp.In):
497
+ col = _strip(node.this)
498
+ if isinstance(col, exp.Column):
499
+ q = node.args.get("query")
500
+ vals = node.expressions or []
501
+ if len(vals) == 1:
502
+ return col, vals[0], "in"
503
+ return col, (q if q is not None else None), "in"
504
+ return None, None, None
505
+ elif isinstance(node, exp.NEQ):
506
+ op = "neq"
507
+ else:
508
+ return None, None, None
509
+ a, b = _strip(node.this), _strip(node.expression)
510
+ if isinstance(a, exp.Column) and not isinstance(b, exp.Column):
511
+ return a, node.expression, ("in_array" if op == "eq" and isinstance(_strip(node.expression), (exp.Any, exp.All)) and False else op)
512
+ if isinstance(b, exp.Column) and not isinstance(a, exp.Column):
513
+ flip = {"range": "range"}.get(op, op)
514
+ return b, node.this, flip
515
+ if isinstance(a, exp.Column) and isinstance(b, exp.Column):
516
+ return a, node.expression, op
517
+ return None, None, None
518
+
519
+
520
+ # ---------------------------------------------------------------------------- the rule variant: an index for the predicate
521
+
522
+ INDEX_ON = re.compile(r"CREATE\s+(?:UNIQUE\s+)?INDEX\s+(?:CONCURRENTLY\s+)?(?:IF\s+NOT\s+EXISTS\s+)?(?:[`\"\w.]+\s+)?ON\s+(?:ONLY\s+)?([`\"\w.]+)"
523
+ r"\s*(?:USING\s+\w+\s*)?\(([^;]*?)\)(?:\s*(?:INCLUDE|WHERE|WITH|;|$))", re.I | re.S)
524
+ PK_INLINE = re.compile(r"^\s*[`\"]?(\w+)[`\"]?\s+[^,]*?\bPRIMARY\s+KEY\b", re.I | re.M)
525
+ PK_TABLE = re.compile(r"\bPRIMARY\s+KEY\s*\(([^)]*)\)", re.I)
526
+ UNIQUE_TABLE = re.compile(r"\bUNIQUE\s*(?:NULLS\s+(?:NOT\s+)?DISTINCT\s*)?\(([^)]*)\)", re.I)
527
+ UNIQUE_INLINE = re.compile(r"^\s*[`\"]?(\w+)[`\"]?\s+[^,\n]*?\bUNIQUE\b", re.I | re.M)
528
+
529
+
530
+ def _cols(text: str) -> list[str]:
531
+ out = []
532
+ for part in re.split(r"\s*,\s*", text or ""):
533
+ p = part.strip()
534
+ m = re.match(r'^[`"]?(\w+)[`"]?(?:\s+(?:ASC|DESC|NULLS\s+\w+|\w+_ops))*\s*$', p, re.I)
535
+ out.append(m.group(1).lower() if m else "expr:" + p)
536
+ return out
537
+
538
+
539
+ def index_keys(definition: dict | None, extra: list[str] | None = None) -> list[list[str]]:
540
+ """Every index key of a table's definition (CREATE INDEX statements, PRIMARY KEY and UNIQUE), as column lists."""
541
+ if not definition:
542
+ return []
543
+ text = (definition.get("create_sql") or "") + ";\n" + ";\n".join(extra or [])
544
+ name = bare(definition.get("name") or "")
545
+ keys = []
546
+ for m in INDEX_ON.finditer(text):
547
+ if bare(m.group(1)) == name:
548
+ keys.append(_cols(m.group(2)))
549
+ for m in PK_TABLE.finditer(text):
550
+ keys.append(_cols(m.group(1)))
551
+ for m in UNIQUE_TABLE.finditer(text):
552
+ keys.append(_cols(m.group(1)))
553
+ for c in _inline_keys(definition):
554
+ keys.append([c])
555
+ for c in definition.get("unique_columns") or []:
556
+ keys.append([str(c).lower()])
557
+ return keys
558
+
559
+
560
+ def _inline_keys(definition: dict) -> list[str]:
561
+ """Columns declared PRIMARY KEY or UNIQUE in their own column definition."""
562
+ from .rank import _columns
563
+ got = _columns(definition.get("create_sql") or "", definition.get("name") or "")
564
+ out = []
565
+ for col, text in (got[1] if got else {}).items():
566
+ if re.search(r"\bPRIMARY\s+KEY\b|\bUNIQUE\b", text, re.I):
567
+ out.append(col.strip('"`').lower())
568
+ return out
569
+
570
+
571
+ def unique_columns(definition: dict | None) -> set[str]:
572
+ """Columns that hold one value per row: a one-column primary key or unique key (a value written there must be new)."""
573
+ if not definition:
574
+ return set()
575
+ text = definition.get("create_sql") or ""
576
+ out = set(_inline_keys(definition))
577
+ for m in list(PK_TABLE.finditer(text)) + list(UNIQUE_TABLE.finditer(text)):
578
+ out.update(_cols(m.group(1)))
579
+ for m in re.finditer(r"CREATE\s+UNIQUE\s+INDEX[^;]*?\(([^;]*?)\)", text, re.I):
580
+ out.update(c for c in _cols(m.group(1)) if not c.startswith("expr:"))
581
+ out.update(str(c).lower() for c in definition.get("unique_columns") or [])
582
+ return {c for c in out if not c.startswith("expr:")}
583
+
584
+
585
+ def served(key: list[str], keys: list[list[str]]) -> bool:
586
+ """An index whose leading column is one of the predicate's equality columns (or its range column) serves it."""
587
+ if not key:
588
+ return True
589
+ lead = {k for k in key}
590
+ return any(k and k[0] in lead for k in keys)
591
+
592
+
593
+ def index_variant(info: dict, definition: dict | None, engine: str, sql: str) -> dict | None:
594
+ """The rule variant of an UPDATE / DELETE whose predicate no index of the table serves: an index on its equality
595
+ columns (IN columns next, then one range column). None when an index already starts with one of them, or the
596
+ predicate names no column of the table."""
597
+ if info.get("kind") not in ("update", "delete") or engine not in ("postgres", "sqlite") or not definition:
598
+ return None
599
+ eq = list(dict.fromkeys(c.lower() for c in info["key"]["eq"]))
600
+ ins = [c.lower() for c in info["key"]["in"] if c.lower() not in eq]
601
+ rng = [c.lower() for c in info["key"]["range"] if c.lower() not in eq and c.lower() not in ins][:1]
602
+ key = eq + ins + rng
603
+ if not key:
604
+ return None
605
+ if served(key, index_keys(definition)):
606
+ return None
607
+ t = definition["name"]
608
+ name = re.sub(r"_+", "_", f"codecop_w_{bare(t)}_{'_'.join(key)}").lower()[:55] + "_idx"
609
+ q = (lambda n: ".".join('"' + p.replace('"', '""') + '"' for p in n.split("."))) if engine == "postgres" else (lambda n: '"' + n + '"')
610
+ ddl = f"CREATE INDEX {name} ON {q(t) if engine == 'postgres' else q(bare(t))} ({', '.join(q(c) if engine == 'postgres' else q(c) for c in key)})"
611
+ return {"kind": "index", "sql": sql, "setup_sql": [ddl], "same_results": True, "rule": "write_no_usable_index",
612
+ "change": f"Index on {bare(t)} ({', '.join(key)}): the {info['kind'].upper()}'s predicate has no index to start from",
613
+ "tradeoffs": ["extra_storage", "slower_inserts"]}
614
+
615
+
616
+ # ---------------------------------------------------------------------------- candidates
617
+
618
+ def _roles_left_out(cfg: dict) -> set[str]:
619
+ return {r.strip() for r in str(cfg.get("roles") or "").split(",") if r.strip()}
620
+
621
+
622
+ def is_write(site: dict) -> bool:
623
+ return (site.get("statement") or "") in STATEMENTS
624
+
625
+
626
+ def _origin(site: dict) -> dict:
627
+ return {"role": site.get("role") or "unknown", "kind": ((site.get("origins") or [{}])[0]).get("kind", "unknown"),
628
+ "entry_points": [{k: o.get(k) for k in ("kind", "name", "file", "line")} for o in (site.get("origins") or [])[:3]],
629
+ "path": [], "frequency": {"trigger": "unknown", "every_seconds": 0, "in_loop": bool(site.get("in_loop")), "cache_seconds": 0, "note": ""},
630
+ "verified": False}
631
+
632
+
633
+ def _title(info: dict) -> str:
634
+ kind = info.get("kind") or "write"
635
+ t = bare(info.get("target") or "")
636
+ words = {"insert_values": f"INSERT into {t}", "insert_multi": f"Multi-row INSERT into {t}", "insert_select": f"INSERT ... SELECT into {t}",
637
+ "upsert": f"Upsert into {t}", "update": f"UPDATE of {t}", "delete": f"DELETE from {t}", "ch_mutation": f"Mutation of {t}"}
638
+ out = words.get(kind, f"Write to {t}")
639
+ key = info.get("key") or {}
640
+ by = key.get("eq") or key.get("in") or key.get("range")
641
+ if by and kind in ("update", "delete"):
642
+ out += f" by {', '.join(dict.fromkeys(by))}"
643
+ elif kind in ("update", "delete") and not info.get("where"):
644
+ out += " (every row)"
645
+ return out
646
+
647
+
648
+ def candidate(site: dict, sql: str, info: dict, finding: str, engine: str, definitions: dict[str, dict], notes: list[str],
649
+ cfg: dict) -> dict:
650
+ target_def = definitions.get(bare(info["target"]))
651
+ if info["kind"] in ("insert_values", "insert_multi", "upsert") and target_def and any(s.get("role") == "other" for s in info["slots"].values()):
652
+ # INSERT INTO t VALUES (...) with no column list: the values go to the table's columns in order
653
+ from .rank import _columns
654
+ got = _columns(target_def.get("create_sql") or "", target_def.get("name") or "")
655
+ order = [c.strip('"`') for c in (got[1] if got else {})]
656
+ tree = parse(sql, engine)
657
+ vals = tree.find(exp.Values) if tree is not None else None
658
+ if order and vals is not None and not isinstance(tree.this, exp.Schema):
659
+ for row in vals.expressions:
660
+ for i, v in enumerate(getattr(row, "expressions", []) or []):
661
+ s = _slot_of(v)
662
+ if s and i < len(order) and info["slots"].get(s, {}).get("role") == "other":
663
+ info["slots"][s] = {"role": "insert", "table": info["target"], "column": order[i]}
664
+ variants = []
665
+ from .rank import site_role
666
+ one_off = (site.get("role") or "") in ONE_OFF_ROLES or site_role(site) in ONE_OFF_ROLES
667
+ if cfg["index_rule"] and not one_off:
668
+ v = index_variant(info, target_def, engine, sql)
669
+ if v:
670
+ variants.append(v)
671
+ tables = [definitions[bare(t)]["name"] for t in info["tables"] if bare(t) in definitions]
672
+ return {
673
+ "finding": finding, "id": site.get("id"), "title": _title(info), "severity": "medium", "confidence": "high",
674
+ "baseline_sql": sql, "params": {}, "tables": tables, "variants": variants, "causes": [],
675
+ "assumptions": ["the code's own write, made runnable by rule: run inside a transaction that is rolled back (on ClickHouse, on an "
676
+ "empty or copied table), values taken from the sandbox's rows"] + notes,
677
+ "origin": _origin(site),
678
+ "site": {**{k: site.get(k) for k in ("file", "line", "symbol", "sink", "resolution", "flags", "sql_hash")},
679
+ "same_sql_sites": 1, "score": 0.0, "role": site.get("role") or "unknown", "origins": site.get("origins") or [],
680
+ "origin_count": site.get("origin_count", 0)},
681
+ "original_sql": site.get("sql") or sql, "sql_from": "code", "located": "site", "built_for": "write",
682
+ "write": {"kind": info["kind"], "statement": site.get("statement"), "target": target_def["name"] if target_def else info["target"],
683
+ "slots": info["slots"], "returning": info["returning"], "conflict": info.get("conflict") or [],
684
+ "conflict_action": info.get("conflict_action"), "key": info["key"], "set_columns": info.get("set_columns") or [],
685
+ "where": info.get("where") or "", "in_loop": bool(site.get("in_loop")), "role": site.get("role") or "",
686
+ **({"probe_sql": info["probe_sql"]} if info.get("probe_sql") else {}),
687
+ **({"row_conditions": info["row_conditions"]} if info.get("row_conditions") else {}),
688
+ "unique": sorted(unique_columns(target_def)),
689
+ "settings": {k: cfg[k] for k in ("limit_value", "probe_rows", "array_items")},
690
+ **({"mutation": info["mutation"]} if info.get("mutation") else {})},
691
+ }
692
+
693
+
694
+ def plan(inventory: dict, engine: str, definition_of, settings: dict | None = None, covered: set[str] | None = None,
695
+ heat: dict[str, float] | None = None) -> tuple[list[dict], dict]:
696
+ """(candidates, writes doc) for every write call site of `inventory`. `definition_of(table) -> definition | None`
697
+ (the run's loaded definitions first, then the pulled catalog, then the repository's schema). `heat`: site id ->
698
+ measured weight (production executions), ordering the candidates when there are more than max_candidates."""
699
+ from . import engines
700
+ cfg = settings_of(settings)
701
+ left_out = _roles_left_out(cfg)
702
+ sites = [s for s in (inventory or {}).get("call_sites") or [] if is_write(s) and not s.get("is_test") and s.get("role") != "test"]
703
+ heat = heat or {}
704
+ sites.sort(key=lambda s: (-float(heat.get(s.get("id"), 0)), -int(s.get("origin_count") or 0), s.get("file") or "", int(s.get("line") or 0)))
705
+ rows, cands = [], []
706
+ by_hash: dict[str, str] = {}
707
+ defs: dict[str, dict] = {}
708
+ for s in sites:
709
+ row = {"site_id": s.get("id"), "file": s.get("file"), "line": s.get("line"), "statement": s.get("statement"),
710
+ "engine": s.get("engine") or "", "role": s.get("role") or "", "sql_hash": s.get("sql_hash"), "in_loop": bool(s.get("in_loop"))}
711
+ rows.append(row)
712
+ e = s.get("engine") or ""
713
+ if e and e != engine:
714
+ row["reason"] = "write_engine_not_benchmarkable" if e not in engines.supported() else "write_other_engine"
715
+ continue
716
+ from .rank import site_role
717
+ if (s.get("role") or "") in left_out or site_role(s) in left_out:
718
+ row["reason"] = "write_role_left_out"
719
+ continue
720
+ h = s.get("sql_hash")
721
+ if h and h in by_hash:
722
+ row["finding"] = by_hash[h]
723
+ row["reason"] = "write_same_as_another"
724
+ continue
725
+ if covered and str(s.get("id")) in covered:
726
+ continue
727
+ sql, notes, why = write_text(s, engine, cfg)
728
+ if sql is None:
729
+ row["reason"] = why
730
+ continue
731
+ info = analyse(sql, engine)
732
+ if info is None or not info.get("target"):
733
+ row["reason"] = "write_does_not_parse"
734
+ continue
735
+ row["kind"] = info["kind"]
736
+ missing = []
737
+ for t in info["tables"]:
738
+ if bare(t) in defs:
739
+ continue
740
+ d = definition_of(t)
741
+ if d is None:
742
+ missing.append(t)
743
+ else:
744
+ defs[bare(t)] = d
745
+ if bare(info["target"]) not in defs or missing:
746
+ row["reason"] = "write_table_not_defined"
747
+ row["tables_missing"] = missing[:6] or [info["target"]]
748
+ continue
749
+ if len(cands) >= int(cfg["max_candidates"]):
750
+ row["reason"] = "write_over_max"
751
+ continue
752
+ finding = f"W-{len(cands) + 1:03d}"
753
+ cands.append(candidate(s, sql, info, finding, engine, defs, notes, cfg))
754
+ row["finding"] = finding
755
+ if h:
756
+ by_hash[h] = finding
757
+ why = Counter(r["reason"] for r in rows if r.get("reason") and r["reason"] != "write_same_as_another")
758
+ doc = {"schema_version": SCHEMA_VERSION, "generated_at": now(), "engine": engine, "settings": cfg, "sites": rows,
759
+ "summary": {"write_sites": len(rows), "candidates": len(cands), "sites_with_candidate": sum(1 for r in rows if r.get("finding")),
760
+ "by_kind": dict(Counter(c["write"]["kind"] for c in cands).most_common()),
761
+ "not_built": dict(why.most_common()),
762
+ "index_variants": sum(1 for c in cands for v in c["variants"] if v.get("rule") == "write_no_usable_index")},
763
+ "definitions": {k: {"name": d["name"], "source": d.get("source") or ("real catalog" if d.get("rows") else "repository")} for k, d in defs.items()}}
764
+ return cands, doc
765
+
766
+
767
+ # ---------------------------------------------------------------------------- the outcome of a benchmarked write
768
+
769
+ def is_write_candidate(cand: dict) -> bool:
770
+ return isinstance(cand.get("write"), dict)
771
+
772
+
773
+ def outcome(engine: str, cand: dict, record: dict | None, variants: list[dict], settings: dict, floors: tuple[int, int] = (0, 0),
774
+ benched: bool = True) -> dict:
775
+ """The outcome of one benchmarked write (blockers' vocabulary: fixed / blocked / nothing_to_gain / not_judged).
776
+
777
+ no record bench_not_run
778
+ a table not built, baseline failed sandbox_table_not_loaded / sandbox_could_not_run (with the error's class)
779
+ touched no row, read none write_touches_no_rows (its WHERE matched nothing on the sandbox's rows)
780
+ a variant with the same final state and fewer pages: as any read (insert side measured: fixed, else the trade-off)
781
+ a variant whose final state differs write_state_differs (blocked)
782
+ at the floor nothing_to_gain / write_at_floor: the rows it scans are the rows it changes (+ floor),
783
+ or it scans none (an INSERT ... VALUES)
784
+ else blocked: no_variant_reads_less / no_variant_proposed (measured; the next step is
785
+ a rewrite only an agent can propose)"""
786
+ from . import blockers as B
787
+ if not benched or record is None:
788
+ return B.outcome("not_judged", "bench_not_run", "run")
789
+ nb = record.get("not_benchmarked")
790
+ if nb:
791
+ return B.outcome("not_judged", "sandbox_table_not_loaded" if nb.get("reason") != "definition_incomplete" else "definition_incomplete", "sandbox",
792
+ {"tables": [{"table": t.get("table"), "error_class": B.error_class(t.get("error"), engine)} for t in nb.get("tables") or []],
793
+ "detail": (nb.get("detail") or "")[:300]})
794
+ base = record.get("baseline") or {}
795
+ w = base.get("write") or {}
796
+ if not base.get("ok"):
797
+ return B.outcome("not_judged", "sandbox_could_not_run", "sandbox",
798
+ {"stage": w.get("stage") or "baseline", "error_class": B.error_class(base.get("error"), engine),
799
+ "error": (base.get("error") or "")[:300]})
800
+ measured = {"read_rows": int(base.get("read_rows") or 0), "read_bytes": int(base.get("read_bytes") or 0),
801
+ "affected_rows": int(w.get("affected_rows") or 0), "wal_bytes": w.get("wal_bytes"), "written_bytes": w.get("written_bytes"),
802
+ "duration_ms": base.get("duration_ms"), "kind": (cand.get("write") or {}).get("kind")}
803
+ kind = measured["kind"]
804
+ if measured["affected_rows"] == 0 and kind in ("update", "delete", "ch_mutation", "insert_select") and w.get("predicate_params"):
805
+ return B.outcome("not_judged", "write_touches_no_rows", "sandbox", {**measured, "next_step": NEXT_STEP["write_touches_no_rows"],
806
+ "tried": w.get("tried")})
807
+ differ = [v for v in variants if v.get("results_match") is False]
808
+ wins = [v for v in variants if v.get("verdict") == "win"]
809
+ if wins:
810
+ ok, costly, unmeasured = B.insert_cost_rule(wins, settings, engine)
811
+ if ok:
812
+ best = B._best(ok, measured)
813
+ return B.outcome("fixed", "verified", "sandbox", {**measured, "kind": best["kind"], "write_kind": kind, **B._ratios(best, measured),
814
+ **B._insert_evidence(best), "same_final_state": True})
815
+ if costly:
816
+ best = B._best(costly, measured)
817
+ near = bool((best.get("insert_cost") or {}).get("near_limit"))
818
+ return B.outcome("blocked", "insert_cost_near_limit" if near else "fix_costs_inserts", "sandbox",
819
+ {**measured, "kind": best["kind"], **B._ratios(best, measured), **B._insert_evidence(best), "trade_off": True},
820
+ [{"code": "no_fix_found", "table": None, "read": {"read_rows": measured["read_rows"]}, "from": "computed", "removed_by": []}])
821
+ best = B._best(unmeasured, measured)
822
+ return B.outcome("not_judged", "insert_cost_not_measured", "sandbox", {**measured, "kind": best["kind"], **B._ratios(best, measured),
823
+ **B._insert_evidence(best)})
824
+ if differ:
825
+ v = differ[0]
826
+ return B.outcome("blocked", "write_state_differs", "sandbox", {**measured, "kind": v.get("kind"), "compared": v.get("compared") or ""},
827
+ [{"code": "no_fix_found", "table": None, "read": {"read_rows": measured["read_rows"]}, "from": "computed", "removed_by": []}])
828
+ floor_rows = int(settings.get("write_floor_rows") or DEFAULTS["floor_rows"])
829
+ scanned_beyond = max(measured["read_rows"] - measured["affected_rows"], 0)
830
+ if measured["read_rows"] == 0 or scanned_beyond <= floor_rows:
831
+ how = ("it reads no table rows: one statement writes its rows" if measured["read_rows"] == 0 else
832
+ f"it scans {measured['read_rows']:,} rows to change {measured['affected_rows']:,}")
833
+ return B.outcome("nothing_to_gain", "write_at_floor", "sandbox", {**measured, "floor_rows": floor_rows, "how": how,
834
+ "scans": [s.get("node") for s in base.get("scans") or []][:6]})
835
+ if (cand.get("write") or {}).get("role") in ONE_OFF_ROLES:
836
+ # a migration's or a script's write runs once: what it costs is measured, and no index or rewrite pays that back
837
+ return B.outcome("nothing_to_gain", "write_runs_once", "sandbox", {**measured, "role": cand["write"]["role"],
838
+ "scanned_beyond_changed": scanned_beyond})
839
+ measured_variants = [v for v in variants if v.get("verdict") not in ("failed", "untested")]
840
+ if variants and not measured_variants:
841
+ failed = [v for v in variants if v.get("verdict") == "failed"]
842
+ return B.outcome("not_judged", "sandbox_could_not_run", "sandbox",
843
+ {**measured, "stage": "variant", "error_classes": sorted({B.error_class(B._variant_error(v), engine) for v in failed})})
844
+ blockers = [{"code": "no_fix_found", "table": bare((cand.get("write") or {}).get("target") or ""), "read": {"read_rows": measured["read_rows"],
845
+ "affected_rows": measured["affected_rows"]}, "from": "computed", "removed_by": ["index", "query"]}]
846
+ if not variants:
847
+ return B.outcome("blocked", "no_variant_proposed", "sandbox", {**measured, "scanned_beyond_changed": scanned_beyond}, blockers)
848
+ best = B._best(measured_variants, measured)
849
+ return B.outcome("blocked", "no_variant_reads_less", "sandbox", {**measured, "kind": best["kind"], **B._ratios(best, measured)}, blockers)
850
+
851
+
852
+ # ---------------------------------------------------------------------------- the rank and profile with the writes
853
+
854
+ def extend(rank: dict | None, profile: dict | None, inventory: dict, engine: str, facts=None, settings: dict | None = None,
855
+ schema_settings: dict | None = None) -> tuple[dict, dict | None, dict]:
856
+ """rank and profile with the write candidates: each write table's definition (the run's own; else the pulled
857
+ catalog's; else the repository's schema, `schema only`) and a profile for every table the profile does not describe.
858
+ Copies; the files on disk are not changed. Returns (rank, profile, writes doc)."""
859
+ from . import loopschema
860
+ cfg = settings_of(settings)
861
+ rank = copy.deepcopy(rank) if rank else {"engine": engine, "engine_version": "", "candidates": [], "table_definitions": [],
862
+ "agent": {"runner": "", "model": "", "cost_usd": 0.0}, "shortlist": [], "rejected": []}
863
+ if not cfg["build"]:
864
+ return rank, profile, {"schema_version": SCHEMA_VERSION, "engine": engine, "sites": [], "summary": {"off": True}}
865
+ loaded = {bare(d["name"]): d for d in rank.get("table_definitions") or []}
866
+ added: dict[str, dict] = {}
867
+
868
+ rekeyed: dict[str, dict] = {}
869
+
870
+ def keyed(d: dict) -> dict:
871
+ """A PostgreSQL table written from the repository's schema, with the keys its migrations declare (see _keyed)."""
872
+ if engine != "postgres" or d.get("source") != "repository":
873
+ return d
874
+ return _keyed(d, inventory)
875
+
876
+ def definition_of(t: str) -> dict | None:
877
+ b = bare(t)
878
+ if b in loaded:
879
+ d = keyed(loaded[b])
880
+ if d is not loaded[b]:
881
+ loaded[b] = rekeyed[b] = d
882
+ return d
883
+ if b in added:
884
+ return added[b]
885
+ d = None
886
+ if facts is not None:
887
+ try:
888
+ d = facts.definition(engine, t) or facts.definition(engine, b)
889
+ except Exception: # noqa: BLE001 - a catalog that cannot give it is the same as no catalog entry
890
+ d = None
891
+ if d is None:
892
+ d = loopschema.definition(inventory, re.sub(r'[`"]', "", t), engine)
893
+ if d is not None:
894
+ d = keyed(d)
895
+ if d is not None:
896
+ added[b] = d
897
+ return d
898
+ heat = _site_heat(facts, engine)
899
+ cands, doc = plan(inventory, engine, definition_of, cfg, heat=heat)
900
+ used = {bare(t) for c in cands for t in c["tables"]}
901
+ added = {k: v for k, v in added.items() if k in used}
902
+ if not cands:
903
+ return rank, profile, doc
904
+ rank["candidates"] = [c for c in rank.get("candidates") or [] if not is_write_candidate(c)] + cands
905
+ rank["table_definitions"] = [rekeyed.get(bare(d["name"]), d) for d in rank.get("table_definitions") or []] + [added[t] for t in sorted(added)]
906
+ prof = copy.deepcopy(profile) if profile else {"engine": engine, "tables": []}
907
+ for t in prof.get("tables") or []:
908
+ d = rekeyed.get(bare(t.get("name") or ""))
909
+ for c in t.get("columns") or [] if d else []:
910
+ if str(c.get("name") or "").lower() in {u.lower() for u in d.get("unique_columns") or []}:
911
+ c["kind"] = "unique" # the key it now has: one value per row
912
+ have = {bare(t["name"]) for t in prof.get("tables") or []}
913
+ real = {}
914
+ if facts is not None:
915
+ try:
916
+ real = {bare(k): v for k, v in (facts.tables(engine) or {}).items()}
917
+ except Exception: # noqa: BLE001
918
+ real = {}
919
+ scfg = loopschema.settings_of(schema_settings)
920
+ for t in sorted(added):
921
+ if t in have:
922
+ continue
923
+ d = added[t]
924
+ if d.get("source") == "real catalog" and t in real and facts is not None:
925
+ got = _catalog_table_profile(d, real[t], cands, facts, engine)
926
+ if got is not None:
927
+ prof.setdefault("tables", []).append(got)
928
+ continue
929
+ prof.setdefault("tables", []).append(loopschema.schema_profile(d, inventory, engine, scfg))
930
+ doc["tables_added"] = sorted(added)
931
+ return rank, prof, doc
932
+
933
+
934
+ def _make_key(sql: str, col: str) -> tuple[str, int]:
935
+ """`col` made the table's primary key, with the default such a key has in a migration (a uuid generated, an integer
936
+ from an identity), so an INSERT that leaves it to the database still runs."""
937
+ def one(m: re.Match) -> str:
938
+ typ = m.group(2).strip().lower()
939
+ default = " DEFAULT gen_random_uuid()" if typ == "uuid" else (" GENERATED BY DEFAULT AS IDENTITY" if typ in ("integer", "bigint", "smallint") else "")
940
+ return f"{m.group(1)}{m.group(2)}{default} PRIMARY KEY{m.group(3)}"
941
+ return re.subn(rf'("{re.escape(col)}"\s+)([\w ]+?)(,|\n\))', one, sql, count=1)
942
+
943
+
944
+ def _keyed(d: dict, inventory: dict) -> dict:
945
+ """discover keeps a migration's columns, not its keys: the keys and indexes the DDL declares (_with_ddl_keys), and,
946
+ with still no primary key, `id` as the key (rows generated unique on it), as such tables have. Without it every
947
+ `WHERE id = $1` scans the sandbox's table and an index on id looks like a fix production already has."""
948
+ if "Keys and indexes from the migrations" in (d.get("basis") or "") or "taken as the primary key" in (d.get("basis") or ""):
949
+ return d
950
+ out = _with_ddl_keys(d, inventory)
951
+ if "PRIMARY KEY" not in (out.get("create_sql") or "").upper():
952
+ sql2, n = _make_key(out.get("create_sql") or "", "id")
953
+ if n:
954
+ out = {**out, "create_sql": sql2, "unique_columns": sorted(set(out.get("unique_columns") or []) | {"id"}),
955
+ "basis": (out.get("basis") or "") + " Its `id` column is taken as the primary key (the schema read gave no key)."}
956
+ return out
957
+
958
+
959
+ def _with_ddl_keys(d: dict, inventory: dict) -> dict:
960
+ """A table written from the repository's schema (discover keeps columns, not keys) with the keys and indexes its
961
+ migrations declare: the DDL call sites' CREATE TABLE (a PRIMARY KEY, UNIQUE) and CREATE [UNIQUE] INDEX ... ON it.
962
+ A one-column primary key is made the column's own (rows generated unique on it); every other key becomes an index."""
963
+ name = bare(d.get("name") or "")
964
+ pk: list[str] = []
965
+ keys: list[list[str]] = []
966
+ for s in (inventory or {}).get("call_sites") or []:
967
+ if s.get("statement") != "ddl" or name not in (s.get("sql") or "").lower():
968
+ continue
969
+ text = s.get("sql") or ""
970
+ for m in re.finditer(r"CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?([`\"\w.]+)\s*\(", text, re.I):
971
+ if bare(m.group(1)) != name:
972
+ continue
973
+ depth, i = 1, m.end()
974
+ while i < len(text) and depth:
975
+ depth += {"(": 1, ")": -1}.get(text[i], 0)
976
+ i += 1
977
+ body = text[m.end():i - 1]
978
+ for mm in PK_TABLE.finditer(body):
979
+ pk = [c for c in _cols(mm.group(1)) if not c.startswith("expr:")]
980
+ for mm in re.finditer(r'^\s*"?(\w+)"?\s+[^,\n]*?\bPRIMARY\s+KEY\b', body, re.I | re.M):
981
+ pk = [mm.group(1).lower()]
982
+ for mm in UNIQUE_TABLE.finditer(body):
983
+ keys.append([c for c in _cols(mm.group(1)) if not c.startswith("expr:")])
984
+ for mm in re.finditer(r'^\s*"?(\w+)"?\s+[^,\n]*?\bUNIQUE\b', body, re.I | re.M):
985
+ keys.append([mm.group(1).lower()])
986
+ for m in INDEX_ON.finditer(text):
987
+ if bare(m.group(1)) == name:
988
+ keys.append([c for c in _cols(m.group(2)) if not c.startswith("expr:")])
989
+ if not pk and not keys:
990
+ return d
991
+ sql = d.get("create_sql") or ""
992
+ cols = set(re.findall(r'^\s*"(\w+)"\s', sql, re.M))
993
+ lower = {c.lower(): c for c in cols}
994
+ if len(pk) == 1 and pk[0] in lower and "PRIMARY KEY" not in sql.upper():
995
+ sql, _ = _make_key(sql, lower[pk[0]])
996
+ elif len(pk) > 1:
997
+ keys.insert(0, pk)
998
+ have = {tuple(k) for k in index_keys({**d, "create_sql": sql})}
999
+ target = sql.split("CREATE TABLE", 1)[1].split("(", 1)[0].strip() if "CREATE TABLE" in sql else d["name"]
1000
+ for k in keys:
1001
+ if k and all(c in lower for c in k) and tuple(k) not in have:
1002
+ have.add(tuple(k))
1003
+ sql += f";\nCREATE INDEX ON {target} ({', '.join(chr(34) + lower[c] + chr(34) for c in k)})"
1004
+ return {**d, "create_sql": sql, "unique_columns": sorted(set(d.get("unique_columns") or []) | ({pk[0]} if len(pk) == 1 else set())),
1005
+ "basis": (d.get("basis") or "") + " Keys and indexes from the migrations' DDL."}
1006
+
1007
+
1008
+ def _catalog_table_profile(d: dict, t: dict, cands: list[dict], facts, engine: str) -> dict | None:
1009
+ """A profile of a catalog table from the catalog alone: its real row count and every column a write names."""
1010
+ from . import catalog_profile as CP, profile as profile_mod
1011
+ cols = t.get("columns") or []
1012
+ if not cols:
1013
+ return None
1014
+ sqls = " ".join(c["baseline_sql"] for c in cands if bare(d["name"]) in {bare(x) for x in c["tables"]})
1015
+ rows = int(t.get("rows") or 0)
1016
+ table = {"name": d["name"], "rows": rows, "rows_basis": "real catalog", "rows_confidence": "high", "basis": "catalog, no agent",
1017
+ "columns": [], "fixtures": [], "relations": []}
1018
+ used = CP._used_columns(sqls, cols, [])
1019
+ for c in used:
1020
+ table["columns"].append(CP.column_spec(c, rows, sorting=[], days_back=CP._days_back(t), literals=None))
1021
+ try:
1022
+ profile_mod.apply_facts(table, engine, facts)
1023
+ except Exception: # noqa: BLE001
1024
+ pass
1025
+ return table
1026
+
1027
+
1028
+ def _site_heat(facts, engine: str) -> dict[str, float]:
1029
+ """site id -> production executions of the shapes located to it (ordering only)."""
1030
+ out: dict[str, float] = {}
1031
+ if facts is None:
1032
+ return out
1033
+ try:
1034
+ m = facts.match(engine) or {}
1035
+ except Exception: # noqa: BLE001
1036
+ return out
1037
+ for q in m.get("queries") or []:
1038
+ for sid in q.get("site_ids") or []:
1039
+ out[sid] = out.get(sid, 0.0) + float(q.get("executions") or 0)
1040
+ return out
1041
+
1042
+
1043
+ def load(out_dir) -> dict | None:
1044
+ import json
1045
+ from pathlib import Path
1046
+ p = Path(out_dir) / FILE
1047
+ try:
1048
+ return json.loads(p.read_text())
1049
+ except (OSError, ValueError):
1050
+ return None
1051
+
1052
+
1053
+ def with_outcomes(doc: dict, findings: list[dict]) -> dict:
1054
+ """writes.json's sites with the outcome of their candidate (findings.json), and the roll-up: write sites by state,
1055
+ the not-built ones by reason."""
1056
+ by_finding = {f.get("finding"): f.get("outcome") or {} for f in findings or [] if str(f.get("finding") or "").startswith("W-")}
1057
+ states: Counter = Counter()
1058
+ reasons: Counter = Counter()
1059
+ for r in doc.get("sites") or []:
1060
+ o = by_finding.get(r.get("finding")) if r.get("finding") else None
1061
+ if o:
1062
+ r["outcome"] = {k: o.get(k) for k in ("state", "reason", "from")}
1063
+ states[o.get("state")] += 1
1064
+ if o.get("state") == "not_judged":
1065
+ reasons[o.get("reason")] += 1
1066
+ elif r.get("reason"):
1067
+ r["outcome"] = {"state": "not_judged", "reason": r["reason"], "next_step": REASONS.get(r["reason"], "none")}
1068
+ states["not_judged"] += 1
1069
+ reasons[r["reason"]] += 1
1070
+ doc.setdefault("summary", {})["states"] = dict(states)
1071
+ doc["summary"]["not_judged_reasons"] = dict(reasons.most_common())
1072
+ return doc
1073
+
1074
+
1075
+ def text_hash(sql: str) -> str:
1076
+ return hashlib.sha1(" ".join(sql.split()).encode()).hexdigest()[:12]
1077
+
1078
+
1079
+ def finding_block(cand: dict, record: dict | None) -> dict:
1080
+ """findings.json `write` of a write finding (the console and the management API read it as it is)."""
1081
+ wd = cand.get("write") or {}
1082
+ base = (record or {}).get("baseline") or {}
1083
+ m = base.get("write") or {}
1084
+ out = {"kind": wd.get("kind"), "statement": wd.get("statement"), "target": wd.get("target"), "returning": bool(wd.get("returning")),
1085
+ "conflict": wd.get("conflict") or [], "key": wd.get("key") or {}, "in_loop": bool(wd.get("in_loop")),
1086
+ "measured": bool(base.get("ok"))}
1087
+ if base.get("ok"):
1088
+ out.update({k: m.get(k) for k in ("affected_rows", "wal_bytes", "wal_records", "wal_fpi", "dirtied_blocks", "written_rows",
1089
+ "written_bytes", "trigger_ms", "copy", "tried") if m.get(k) is not None})
1090
+ out["params_used"] = m.get("params_used") or {}
1091
+ out["params_how"] = m.get("params_how") or {}
1092
+ out["state_compared"] = m.get("state_compared") or ""
1093
+ out["rows_scanned"] = int(base.get("read_rows") or 0)
1094
+ out["pages"] = int((base.get("read_bytes") or 0) // 8192) if "shared_hit_blocks" in base else base.get("pages")
1095
+ out["duration_ms"] = base.get("duration_ms")
1096
+ vs = (record or {}).get("variants") or []
1097
+ out["variants"] = [{"index": v.get("index"), "kind": v.get("kind"), "rule": v.get("rule"), "verdict": v.get("verdict"),
1098
+ "same_final_state": v.get("same_final_state"), "compared": v.get("compared") or "",
1099
+ "affected_rows": ((v.get("measurement") or {}).get("write") or {}).get("affected_rows"),
1100
+ "wal_bytes": ((v.get("measurement") or {}).get("write") or {}).get("wal_bytes")} for v in vs]
1101
+ return out
1102
+
1103
+
1104
+ def merge_bench(previous: dict | None, result: dict) -> dict:
1105
+ """bench.json after a `--writes-only` pass: the earlier records kept, every write record (`W-`) replaced by this
1106
+ pass's. A pass at fewer scales puts its records on the earlier bench's scale of the same fraction, else its largest."""
1107
+ from . import bench as bench_mod
1108
+ if not previous or not previous.get("scales"):
1109
+ return result
1110
+ merged = dict(previous)
1111
+ new_scales = result.get("scales") or []
1112
+ by_fraction = {round(float(s.get("fraction") or 0), 6): s for s in new_scales}
1113
+ old = previous.get("scales") or []
1114
+ out = []
1115
+ for i, sc in enumerate(old):
1116
+ f = round(float(sc.get("fraction") or 0), 6)
1117
+ new_sc = by_fraction.get(f)
1118
+ if new_sc is None and i == len(old) - 1 and new_scales:
1119
+ new_sc = new_scales[-1]
1120
+ add = (new_sc or {}).get("findings") or []
1121
+ again = {r.get("finding") for r in add}
1122
+ # a pass over some writes (`--only W-...`) replaces those; every other record stays as it was
1123
+ keep = [r for r in sc.get("findings") or [] if r.get("finding") not in again]
1124
+ tables = {t.get("name"): t for t in sc.get("tables") or []}
1125
+ for t in (new_sc or {}).get("tables") or []:
1126
+ tables.setdefault(t.get("name"), t)
1127
+ out.append({**sc, "findings": keep + [r for r in add if str(r.get("finding") or "").startswith("W-")], "tables": list(tables.values())})
1128
+ merged["scales"] = out
1129
+ merged["outcomes"] = {**(previous.get("outcomes") or {}),
1130
+ **{k: v for k, v in (result.get("outcomes") or {}).items() if k.startswith("W-")}}
1131
+ merged["summary"] = bench_mod.summary(merged)
1132
+ merged["passes"] = list(previous.get("passes") or [{"generated_at": previous.get("generated_at"), "kind": "bench",
1133
+ "duration_s": previous.get("duration_s")}]) + [
1134
+ {"generated_at": result.get("generated_at"), "kind": "writes", "duration_s": result.get("duration_s"),
1135
+ "statements": sum(1 for s in new_scales[-1:] for _ in s.get("findings") or [])}]
1136
+ merged["duration_s"] = round(float(previous.get("duration_s") or 0) + float(result.get("duration_s") or 0), 1)
1137
+ return merged
1138
+
1139
+
1140
+ def summary_for_findings(doc: dict) -> dict:
1141
+ """findings.json `writes`: the roll-up of every write call site (states, reasons), and the plan's counts."""
1142
+ s = doc.get("summary") or {}
1143
+ return {"file": FILE, "write_sites": s.get("write_sites", 0), "candidates": s.get("candidates", 0),
1144
+ "sites_with_candidate": s.get("sites_with_candidate", 0), "by_kind": s.get("by_kind") or {},
1145
+ "states": s.get("states") or {}, "not_judged_reasons": s.get("not_judged_reasons") or {},
1146
+ "not_built": s.get("not_built") or {}, "index_variants": s.get("index_variants", 0),
1147
+ "ch_tiny_inserts": (doc.get("ch_tiny_inserts") or [])[:50],
1148
+ "reasons": {k: {"label": WORDS.get(k, k), "next_step": v} for k, v in REASONS.items()}}
1149
+
1150
+
1151
+ TINY = {"tiny_insert_rows": 1000, "tiny_min_inserts_per_hour": 60}
1152
+
1153
+
1154
+ def ch_tiny_inserts(workload: dict | None, inventory: dict | None, settings: dict | None = None) -> list[dict]:
1155
+ """ClickHouse tables production inserts into many times an hour with few rows each (the pull's per-table insert
1156
+ statistics, `ch.workload.inserts`): each insert makes at least one part the server merges later. Evidence with
1157
+ production counts, never a win: batching on the client or `async_insert` trades insert latency (and, with
1158
+ `wait_for_async_insert = 0`, the moment a row is durable) for fewer parts. Not sandbox-verified in this build."""
1159
+ cfg = {**TINY, **{k: v for k, v in (settings or {}).items() if k in TINY and isinstance(v, (int, float))}}
1160
+ ch = ((workload or {}).get("connections") or {}).get("clickhouse") or {}
1161
+ hours = float(ch.get("window_hours") or 0) or None
1162
+ rows = ch.get("inserts") or []
1163
+ if not rows or not hours:
1164
+ return []
1165
+ sites: dict[str, list[str]] = {}
1166
+ for s in (inventory or {}).get("call_sites") or []:
1167
+ if s.get("statement") == "insert" and not s.get("is_test") and (s.get("engine") or "") in ("clickhouse", ""):
1168
+ for t in s.get("writes") or s.get("tables") or []:
1169
+ sites.setdefault(bare(t), []).append(s.get("id"))
1170
+ total_ms = sum(int(r.get("total_ms") or 0) for r in rows) or 1
1171
+ out = []
1172
+ for r in rows:
1173
+ per_hour = int(r.get("inserts") or 0) / hours
1174
+ med = int(r.get("median_written_rows") or 0)
1175
+ if med >= cfg["tiny_insert_rows"] or per_hour < cfg["tiny_min_inserts_per_hour"]:
1176
+ continue
1177
+ out.append({"table": r.get("table"), "database": r.get("database"), "inserts": int(r.get("inserts") or 0),
1178
+ "inserts_per_hour": round(per_hour, 1), "median_rows": med, "written_rows": int(r.get("written_rows") or 0),
1179
+ "insert_ms": int(r.get("total_ms") or 0), "share_of_insert_time": round(int(r.get("total_ms") or 0) / total_ms, 4),
1180
+ "window_hours": hours, "site_ids": sites.get(bare(r.get("table") or ""), [])[:10],
1181
+ "change": "batch rows on the client, or async_insert", "trade_off": True, "verified": False,
1182
+ "words": f"{per_hour:,.0f} inserts an hour of about {med:,} rows each: each makes a part the server merges later; "
1183
+ "batching or async_insert trades insert latency for fewer parts (a trade-off, not verified here)"})
1184
+ out.sort(key=lambda x: -x["inserts"])
1185
+ return out
1186
+
1187
+
1188
+ def _register_reasons() -> None:
1189
+ """The unjudged reasons writes add, in the shared vocabulary (coverage_reasons)."""
1190
+ try:
1191
+ from . import coverage_reasons as R
1192
+ except ImportError: # an older tree without the shared vocabulary
1193
+ return
1194
+ stage = {"write_other_engine": "runs", "write_engine_not_benchmarkable": "runs", "write_no_statement_text": "obtained",
1195
+ "write_has_run_time_parts": "obtained", "write_does_not_parse": "plans", "write_table_not_defined": "plans",
1196
+ "write_role_left_out": "runs", "write_over_max": "runs"}
1197
+ steps = {"scan_with_its_engine": "scan every engine (--engine auto)", "none_codecop_side": "nothing on the repository's side",
1198
+ "ask_agent_for_statement": "ask the agent by heat", "pull_its_database": "pull its database",
1199
+ "change_writes_roles_setting": "change [writes] roles", "raise_writes_max_candidates": "raise [writes] max_candidates"}
1200
+ for code, st in stage.items():
1201
+ R.register(code, st, WORDS[code][0].upper() + WORDS[code][1:], steps.get(REASONS[code], REASONS[code]), REASONS[code])
1202
+ R.register("write_touches_no_rows", "runs", "Write touches no rows: its WHERE matched no sandbox row", "add fixture rows",
1203
+ "add_fixture_rows")
1204
+ R.register("write_state_not_compared", "outcome", "Write: final state not compared", "nothing on the repository's side", "none_codecop_side")
1205
+ R.register("write_not_replayable", "runs", "Write could not be replayed in the sandbox", "nothing on the repository's side", "none_codecop_side")
1206
+
1207
+
1208
+ _register_reasons()