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/groupbench.py ADDED
@@ -0,0 +1,1375 @@
1
+ """Group benchmark: several statements against one combined statement, proven member by member.
2
+
3
+ The baseline of a group (groups.py) is its members run one after another with one consistent set of parameter values:
4
+ the same tenant, the same time window (the lead member's values; a member's parameter bound to the same column takes
5
+ the lead's value). The group gets fixtures of its own in the data profile, so the rows those values select exist in
6
+ every member's tables, and a heavy run whose values select more rows (`HEAVY_FACTOR`, a setting).
7
+
8
+ A variant replaces some or all members by fewer statements and declares, for each member it replaces, how that member's
9
+ rows are derived from its output:
10
+
11
+ {"sql": <one statement>, "setup": [<statements run first, measured too>], "cleanup": [...],
12
+ "members": [{"key": <member key>, "derive": {"select": [<expr AS name>, ...], "where": <filter or "">,
13
+ "having": <filter on the member's own columns or "">, "order_by": <text or "">, "limit": <text or "">}}]}
14
+
15
+ The harness builds each member's rows from the variant's result (`SELECT <select> FROM (<sql>) WHERE <where>`, then
16
+ the member's own HAVING, ORDER BY and LIMIT over its columns) and compares them with the member's own result by the
17
+ result hash, with the single-statement rules (bench.Comparison: rows ignoring order; a LIMIT without ORDER BY compares
18
+ the count; ties in an ORDER BY compare the rows before the LIMIT; a baseline that disagrees with itself is not judged).
19
+ A variant that cannot reproduce every member it replaces is not a win. Members it does not replace run as they are and
20
+ are not part of its measurement.
21
+
22
+ Measured, for the group and the variant, on the typical and the heavy run: rows and bytes read (summed), peak memory
23
+ (the largest of the statements, which run one after another), parts and marks selected (summed). The verdict is
24
+ bench.verdict on the sums, so on PostgreSQL the pages decide; bench.combined_verdict joins the two runs.
25
+
26
+ Variants come from rules (`MECHANICAL`) for the clear cases, each proven by the harness, and from a paid agent step for
27
+ everything else (`prompt`, `estimate`: never run here).
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import copy
33
+ import hashlib
34
+ import json
35
+ import re
36
+ import time
37
+ import uuid
38
+ from datetime import datetime, timezone
39
+
40
+ import sqlglot
41
+ from sqlglot import exp
42
+
43
+ from . import bench as bench_mod
44
+ from .engines.base import Measurement, QueryError
45
+ from .formerly import code as _code # next-step codes stored before the rename
46
+
47
+
48
+ def _dialect(engine: str) -> str:
49
+ from .engines import sql_dialect
50
+ return sql_dialect(engine)
51
+
52
+
53
+ SCHEMA_VERSION = 1
54
+ DEFAULTS = {
55
+ "heavy_factor": 5.0, # the group's heavy run selects this many times the rows of its typical run
56
+ "typical_share_floor": 1e-4, # a group fixture holds at least this share of a table's rows
57
+ "max_share": 0.05, # ... and at most this share (fixtures share 90% of the row numbers: a large one shrinks the others)
58
+ "max_heavy_share": 0.2, # the heavy run's fixture at most this share
59
+ "min_rows": 50, # ... and at least this many rows
60
+ "max_members_per_variant": 20, # a mechanical variant combines at most this many members
61
+ "runs": 3, # timed runs per statement (the bench's --runs when given)
62
+ "agent_cost_per_member_usd_low": 0.03, # the paid step's estimate per member statement (rank's measured cost per query)
63
+ "agent_cost_per_member_usd_high": 0.06,
64
+ "agent_max_sql_chars": 12000, # a member's statement is cut at this many characters in the prompt
65
+ "agent_groups_per_call": 8, # groups asked about in one agent call of the paid step
66
+ }
67
+ BOOL_DEFAULTS = {"grouping_sets": True, "materialize_cte": True}
68
+ MECHANICAL = ("one_select_all_aggregates", "merged_group_by", "conditional_aggregates", "grouping_sets", "materialize_once")
69
+ # what a group ends with: the four states of blockers.py, and reasons of its own where the single-statement ones do not fit
70
+ REASONS = {
71
+ "fixed": ("verified",),
72
+ "blocked": ("no_variant_reads_less", "fix_results_differ", "group_member_not_reproduced"),
73
+ "not_judged": ("engine_not_benchmarkable", "other_engine_run", "group_member_not_runnable", "group_variants_not_asked", "sameness_not_shown", "sandbox_table_not_loaded",
74
+ "sandbox_could_not_run", "bench_not_run", "parameters_match_no_rows"),
75
+ "nothing_to_gain": ("already_cheap_measured",),
76
+ }
77
+ NEXT_STEP = {
78
+ "verified": "merge_the_call_sites",
79
+ "no_variant_reads_less": "ask_agent_for_group_variant",
80
+ "fix_results_differ": "ask_agent_for_group_variant",
81
+ "group_member_not_reproduced": "ask_agent_for_group_variant",
82
+ "engine_not_benchmarkable": "measure_by_hand",
83
+ "other_engine_run": "run_codecop_bench_for_that_engine",
84
+ "group_member_not_runnable": "connect_read_only_pull",
85
+ "group_variants_not_asked": "ask_agent_for_group_variant",
86
+ "sameness_not_shown": "check_parameters_select_rows",
87
+ "sandbox_table_not_loaded": "fix_table_build",
88
+ "sandbox_could_not_run": "read_the_server_error",
89
+ "bench_not_run": "run_codecop_bench",
90
+ "parameters_match_no_rows": "check_parameters_select_rows",
91
+ "already_cheap_measured": "none",
92
+ }
93
+ WORDS = {
94
+ "verified": "Verified: the combined statement reads less and reproduces every member it replaces",
95
+ "no_variant_reads_less": "Needs another fix: the combined statement does not read meaningfully less",
96
+ "fix_results_differ": "Needs another fix: a member's rows were not reproduced from the combined result",
97
+ "group_member_not_reproduced": "Needs another fix: the combined statement reproduces some members, not all",
98
+ "engine_not_benchmarkable": "Engine not benchmarkable: the group's statements run on an engine CodeCop has no sandbox for (MySQL or SQL Server, say)",
99
+ "other_engine_run": "Not judged in this run: the group's statements run on another engine than this benchmark's; that engine's bench judges it",
100
+ "group_member_not_runnable": "Not judged: a member's statement is not known as it runs (no observed text, no parameters)",
101
+ "group_variants_not_asked": "Not judged: no rule combines these members; the paid agent step was not run",
102
+ "sameness_not_shown": "Not judged: the members' rows could not be compared",
103
+ "sandbox_table_not_loaded": "Not judged: a table of the group could not be built in the sandbox",
104
+ "sandbox_could_not_run": "Not judged: the sandbox refused a statement of the group",
105
+ "bench_not_run": "Not judged: the group was not benchmarked yet",
106
+ "parameters_match_no_rows": "Not judged: the group's parameters select no rows, so sameness is not shown",
107
+ "already_cheap_measured": "Nothing to gain: the group already reads little",
108
+ }
109
+ STATE_WORDS = {"fixed": "Fixed", "blocked": "Needs another fix", "not_judged": "Could not be judged", "nothing_to_gain": "Nothing to gain"}
110
+
111
+
112
+ def settings_of(config: dict | None) -> dict:
113
+ out = {**DEFAULTS, **BOOL_DEFAULTS}
114
+ for k, v in (config or {}).items():
115
+ if k in DEFAULTS and isinstance(v, (int, float)) and not isinstance(v, bool):
116
+ out[k] = type(DEFAULTS[k])(v)
117
+ elif k in BOOL_DEFAULTS and isinstance(v, bool):
118
+ out[k] = v
119
+ return out
120
+
121
+
122
+ def short(name) -> str:
123
+ return str(name or "").replace("`", "").replace('"', "").rsplit(".", 1)[-1].lower()
124
+
125
+
126
+ # --------------------------------------------------------------------------- members as runnable statements
127
+
128
+ def candidates_of(group: dict, candidates: list[dict]) -> dict[str, dict]:
129
+ """member key -> the benchmark candidate that runs it (an observed statement by its shape, a ranked one by its site)."""
130
+ by_hash = {str((c.get("observed") or {}).get("hash")): c for c in candidates if (c.get("observed") or {}).get("hash")}
131
+ by_site = {}
132
+ for c in candidates:
133
+ if c.get("sql_from") != "query_log" and c.get("id"):
134
+ by_site.setdefault(str(c["id"]), c)
135
+ out = {}
136
+ for m in group["members"]:
137
+ c = by_hash.get(str(m.get("hash"))) if m.get("hash") else None
138
+ if c is None and m.get("sql_from") != "query_log":
139
+ # a production statement is run as production ran it, never as the code site it was matched to
140
+ c = next((by_site[s] for s in m.get("site_ids") or [] if s in by_site), None)
141
+ if c is not None and c.get("baseline_sql"):
142
+ out[m["key"]] = c
143
+ return out
144
+
145
+
146
+ PARAM = re.compile(r"\{(\w+)\s*:\s*([^{}]+?)\}")
147
+
148
+
149
+ def _bindings(cand: dict) -> dict[str, tuple]:
150
+ """parameter name -> what it binds: (column, op) when the observed statement says, else the name itself."""
151
+ spec = (cand.get("observed") or {}).get("params") or {}
152
+ out: dict[str, tuple] = {}
153
+ for n, typ in PARAM.findall(cand.get("baseline_sql") or ""):
154
+ if n in out:
155
+ continue
156
+ p = spec.get(n) or {}
157
+ if p.get("column"):
158
+ out[n] = ("col", p["column"], p.get("op") or "")
159
+ continue
160
+ # by name: `val_0` and `val_1` of one statement are two parameters (a tenant, a time), never one; across members
161
+ # the same name and type is taken as the same parameter. The type is part of it: a UUID is never bound as a time.
162
+ typ = re.sub(r"\s+", "", typ).lower()
163
+ key = ("name", re.sub(r"_\d+$", "", n), typ)
164
+ out[n] = ("name", n, typ) if key in out.values() else key
165
+ return out
166
+
167
+
168
+ def unify(members: list[dict], profile: dict | None = None) -> list[dict]:
169
+ """The parameter values each member runs with: the lead's (first) value for every parameter that binds the same
170
+ column the same way (or has the same name), the member's own otherwise."""
171
+ from . import fidelity
172
+ chosen: dict[tuple, object] = {}
173
+ out = []
174
+ for cand in members:
175
+ own = fidelity.params_of(cand, profile or {})
176
+ values = {}
177
+ for name, binding in _bindings(cand).items():
178
+ if name not in own:
179
+ continue
180
+ if binding not in chosen:
181
+ chosen[binding] = own[name]
182
+ values[name] = chosen[binding]
183
+ out.append({**own, **values})
184
+ return out
185
+
186
+
187
+ # --------------------------------------------------------------------------- fixtures for the group's runs
188
+
189
+ def group_fixtures(plan: dict, profile: dict, cfg: dict) -> list[tuple[str, dict]]:
190
+ """(table, fixture) pairs that make the group's values select rows in every member's tables: per table, the pinned
191
+ columns of every member's own fixture there, with the group's values; a heavy copy with values of its own."""
192
+ from . import fidelity
193
+ out = []
194
+ by_table = {t["name"]: t for t in profile.get("tables") or []}
195
+ for heavy in (False, True):
196
+ fid = plan["id"] + ("~heavy" if heavy else "")
197
+ per_table: dict[str, dict] = {}
198
+ for m in plan["members"]:
199
+ cand, values = m["cand"], m["heavy_params" if heavy else "params"]
200
+ mapping = {str(v): str(values.get(k)) for k, v in (cand.get("params") or {}).items() if k in values}
201
+ for t in cand.get("tables") or []:
202
+ table = by_table.get(t)
203
+ if table is None:
204
+ continue
205
+ for f in table.get("fixtures") or []:
206
+ if cand["finding"] not in fidelity._fixture_ids(f.get("id")):
207
+ continue
208
+ cur = per_table.setdefault(t, {"id": fid, "values": {}, "share": 0.0, "min_rows": 1,
209
+ "basis": "group: the members' pinned values, with the group's parameter values"})
210
+ for v in f.get("values") or []:
211
+ cur["values"].setdefault(v["column"], mapping.get(str(v.get("value")), v.get("value")))
212
+ cur["share"] = max(cur["share"], float(f.get("share") or 0))
213
+ cur["min_rows"] = max(cur["min_rows"], int(f.get("min_rows") or 1))
214
+ for t, f in per_table.items():
215
+ factor = cfg["heavy_factor"] if heavy else 1.0
216
+ typical = min(max(f["share"], cfg["typical_share_floor"]), cfg["max_share"])
217
+ f["share"] = round(min(typical * factor, cfg["max_heavy_share"] if heavy else cfg["max_share"]), 6)
218
+ f["min_rows"] = max(int(f["min_rows"] * factor), cfg["min_rows"])
219
+ f["values"] = [{"column": c, "value": v} for c, v in f["values"].items()]
220
+ out.append((t, f))
221
+ return out
222
+
223
+
224
+ def own_values(params: dict, pinned: set[str], plan_id: str, heavy: bool = False) -> dict:
225
+ """The group's own values: every string value a member's fixture pins (a tenant, a key) becomes a value of the
226
+ group's own, so the group's rows are rows of their own and the members' single-statement runs see none of them;
227
+ the heavy run has another one. Numbers, times and values no fixture pins stay."""
228
+ tag = f"~{plan_id.lower()}" + ("h" if heavy else "")
229
+ return {k: (_tagged(v, tag, plan_id) if isinstance(v, str) and v in pinned else v) for k, v in params.items()}
230
+
231
+
232
+ UUID_TEXT = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", re.I)
233
+ _HEAVY_OF: dict[str, str] = {} # a group's typical UUID -> its heavy one (heavy_values cannot read a tag off a UUID)
234
+
235
+
236
+ def _tagged(v: str, tag: str, plan_id: str) -> str:
237
+ """A value of the group's own: `v~g-001`, or for a UUID (a uuid column refuses `...~g-001`) a UUID derived from it,
238
+ the same one every time."""
239
+ if not UUID_TEXT.fullmatch(v):
240
+ return f"{v}{tag}"
241
+ import uuid as uuid_mod
242
+ # "qopt:": the seed from before the rename (formerly qopt), kept so the generated values stay the same
243
+ typical = str(uuid_mod.uuid5(uuid_mod.NAMESPACE_URL, f"qopt:{v}~{plan_id.lower()}"))
244
+ heavy = str(uuid_mod.uuid5(uuid_mod.NAMESPACE_URL, f"qopt:{v}~{plan_id.lower()}h"))
245
+ _HEAVY_OF[typical] = heavy
246
+ return heavy if tag.endswith("h") else typical
247
+
248
+
249
+ def missing_step(m: dict) -> str:
250
+ """What would make a member runnable: a pull (code with no observed statement), a place in code (a production
251
+ statement located nowhere: a call-site tag), or an observed candidate of a shape that has a place."""
252
+ if m.get("sql_from") == "query_log":
253
+ return "add_call_site_tag" if m.get("located") in ("none", "likely") else "observe_more_shapes"
254
+ return "connect_read_only_pull" if not m.get("measured") else "observe_more_shapes"
255
+
256
+
257
+ def heavy_values(params: dict, plan_id: str) -> dict:
258
+ """The variant's parameters on the heavy run: a typical group value is followed by its heavy one."""
259
+ tag = f"~{plan_id.lower()}"
260
+ return {k: (f"{v}h" if isinstance(v, str) and v.endswith(tag) else _HEAVY_OF.get(v, v) if isinstance(v, str) else v)
261
+ for k, v in params.items()}
262
+
263
+
264
+ def _pinned(cands: list[dict], profile: dict) -> set[str]:
265
+ from . import fidelity
266
+ ids = {c["finding"] for c in cands}
267
+ return {str(v.get("value")) for t in profile.get("tables") or [] for f in t.get("fixtures") or []
268
+ if ids & set(fidelity._fixture_ids(f.get("id"))) for v in f.get("values") or []}
269
+
270
+
271
+ def prepare(groups_doc: dict, rank: dict, profile: dict, settings: dict | None = None) -> tuple[dict, list[dict]]:
272
+ """The profile with the groups' fixtures, and the plan of every group whose members can run: members as candidates,
273
+ their unified values, and the mechanical variants. Called before the sandbox is loaded."""
274
+ cfg = settings_of(settings)
275
+ profile = copy.deepcopy(profile)
276
+ plans = []
277
+ for g in groups_doc.get("groups") or []:
278
+ cands = candidates_of(g, rank.get("candidates") or [])
279
+ runnable = [m for m in g["members"] if m["key"] in cands]
280
+ plan = {"id": g["id"], "fingerprint": g["fingerprint"], "kind": g["kind"], "engine": rank.get("engine") or g.get("engine"),
281
+ "table": g["table"], "member_count": g["member_count"], "runnable": len(runnable), "members": []}
282
+ from .loopbench import engine_reason
283
+ why_engine = engine_reason(g.get("engine") or "", rank.get("engine"))
284
+ if why_engine:
285
+ plan["skip"], plan["group_engine"] = why_engine, g.get("engine")
286
+ plans.append(plan)
287
+ continue
288
+ if len(runnable) < (1 if g["kind"] == "repeated_read" else 2):
289
+ plan["skip"] = "group_member_not_runnable"
290
+ plan["missing"] = [missing_step(m) for m in g["members"] if m["key"] not in cands]
291
+ plans.append(plan)
292
+ continue
293
+ ordered = sorted(runnable, key=lambda m: -int((m.get("measured") or {}).get("read_bytes") or 0))
294
+ values = unify([cands[m["key"]] for m in ordered], profile)
295
+ pinned = _pinned([cands[m["key"]] for m in ordered], profile)
296
+ for m, v in zip(ordered, values):
297
+ plan["members"].append({"key": m["key"], "finding": cands[m["key"]]["finding"], "cand": cands[m["key"]],
298
+ "params": own_values(v, pinned, g["id"]), "heavy_params": own_values(v, pinned, g["id"], heavy=True)})
299
+ merged: dict = {}
300
+ for m in plan["members"]:
301
+ for k, v in m["params"].items():
302
+ merged.setdefault(k, v)
303
+ plan["variants"] = mechanical(plan, g, cfg) + [{"kind": "combined", "rule": "agent", **v, "source": "agent", "params": merged} for v in g.get("agent_variants") or [] if v.get("sql")]
304
+ if not plan["variants"]:
305
+ # nothing to measure against: the group is not loaded or run (its fixtures would only take row numbers)
306
+ plan["skip"] = "group_variants_not_asked"
307
+ plans.append(plan)
308
+ continue
309
+ for t, f in group_fixtures(plan, profile, cfg):
310
+ table = next(x for x in profile["tables"] if x["name"] == t)
311
+ table.setdefault("fixtures", []).append(f)
312
+ plans.append(plan)
313
+ return profile, plans
314
+
315
+
316
+ # --------------------------------------------------------------------------- mechanical variants
317
+
318
+ AGG_NAME = re.compile(r"^\s*([A-Za-z_]\w*)\s*\(")
319
+
320
+
321
+ def _calls(text: str) -> tuple[str, list[str]] | None:
322
+ """`name(a)(b)` -> (name, ["a", "b"]): the argument groups of a (parametric) function call."""
323
+ m = AGG_NAME.match(text)
324
+ if not m:
325
+ return None
326
+ groups, i, depth, start = [], m.end() - 1, 0, None
327
+ quote = None
328
+ while i < len(text):
329
+ ch = text[i]
330
+ if quote:
331
+ if ch == quote and text[i - 1] != "\\":
332
+ quote = None
333
+ elif ch in "'\"`":
334
+ quote = ch
335
+ elif ch == "(":
336
+ if depth == 0:
337
+ start = i + 1
338
+ depth += 1
339
+ elif ch == ")":
340
+ depth -= 1
341
+ if depth == 0:
342
+ groups.append(text[start:i])
343
+ rest = text[i + 1:].lstrip()
344
+ if not rest.startswith("("):
345
+ if rest:
346
+ return None
347
+ return m.group(1), groups
348
+ i += 1
349
+ return None
350
+
351
+
352
+ def _split_args(text: str) -> list[str]:
353
+ out, depth, cur, quote = [], 0, "", None
354
+ for i, ch in enumerate(text):
355
+ if quote:
356
+ cur += ch
357
+ if ch == quote and text[i - 1] != "\\":
358
+ quote = None
359
+ continue
360
+ if ch in "'\"`":
361
+ quote = ch
362
+ elif ch in "([":
363
+ depth += 1
364
+ elif ch in ")]":
365
+ depth -= 1
366
+ elif ch == "," and depth == 0:
367
+ out.append(cur.strip())
368
+ cur = ""
369
+ continue
370
+ cur += ch
371
+ if cur.strip():
372
+ out.append(cur.strip())
373
+ return out
374
+
375
+
376
+ def conditional(agg, cond: str, dialect: str):
377
+ """An aggregate computed only over the rows of `cond`: ClickHouse's -If combinator, FILTER elsewhere."""
378
+ text = agg.sql(dialect=dialect)
379
+ if dialect != "clickhouse":
380
+ return sqlglot.parse_one(f"{text} FILTER (WHERE {cond})", read=dialect)
381
+ got = _calls(text)
382
+ if got is None:
383
+ raise ValueError("aggregate not understood")
384
+ name, groups = got
385
+ if re.search(r"\bDISTINCT\b", groups[-1], re.I):
386
+ raise ValueError("DISTINCT inside an aggregate")
387
+ if name.lower() == "count" and groups[-1].strip() in ("", "*"):
388
+ new = f"countIf({cond})"
389
+ elif name.endswith("If"):
390
+ args = _split_args(groups[-1])
391
+ args[-1] = f"({args[-1]}) AND ({cond})"
392
+ new = name + "".join(f"({g})" for g in groups[:-1]) + f"({', '.join(args)})"
393
+ else:
394
+ new = name + "If" + "".join(f"({g})" for g in groups[:-1]) + f"({groups[-1]}, {cond})"
395
+ return sqlglot.parse_one(new, read=dialect)
396
+
397
+
398
+ def _simple(sql: str, dialect: str) -> dict | None:
399
+ """A single-table aggregate select that rules can combine: its parts, or None (why it is not is not needed)."""
400
+ try:
401
+ tree = sqlglot.parse_one(sql, read=dialect)
402
+ except Exception: # a statement the parser does not take is the agent's
403
+ return None
404
+ if not isinstance(tree, exp.Select) or tree.args.get("with_") or tree.args.get("with") or tree.args.get("joins") or tree.args.get("distinct"):
405
+ return None
406
+ src = (tree.args.get("from_") or tree.args.get("from"))
407
+ if src is None:
408
+ return None
409
+ t = src.this
410
+ final = isinstance(t, exp.Final)
411
+ base = t.this if final else t
412
+ if not isinstance(base, exp.Table) or not base.name:
413
+ return None
414
+ if any(True for _ in tree.find_all(exp.Window)) or any(isinstance(s, exp.Select) for s in tree.find_all(exp.Select) if s is not tree):
415
+ return None
416
+ if any(isinstance(f, exp.Anonymous) and f.name.lower() in ("arrayjoin",) for f in tree.find_all(exp.Anonymous)) or tree.find(exp.Explode):
417
+ return None
418
+ limit = tree.args.get("limit")
419
+ if limit is not None and limit.args.get("expressions"):
420
+ return None # LIMIT n BY
421
+ group = tree.args.get("group")
422
+ aggregate = bool(group) or any(e.find(exp.AggFunc) for e in tree.expressions)
423
+ if not aggregate:
424
+ return None
425
+ if group is not None and (group.args.get("grouping_sets") or group.args.get("rollup") or group.args.get("cube") or group.args.get("totals")):
426
+ return None
427
+ items, aliases = [], {}
428
+ for i, e in enumerate(tree.expressions):
429
+ alias = e.alias_or_name if isinstance(e, exp.Alias) else (e.name if isinstance(e, exp.Column) else f"c{i}")
430
+ body = e.this if isinstance(e, exp.Alias) else e
431
+ items.append((alias, body))
432
+ aliases[alias] = body
433
+ def resolved(node, own: str = ""):
434
+ """`node` with references to the select's aliases replaced by their expressions (ClickHouse resolves an alias
435
+ before a column of that name): in the combined statement the aliases are renamed."""
436
+ node = node.copy()
437
+ for c in list(node.find_all(exp.Column)):
438
+ if not c.table and c.name in aliases and c.name != own:
439
+ body = aliases[c.name]
440
+ if isinstance(body, exp.Column) and body.name == c.name:
441
+ continue
442
+ if c is node:
443
+ return body.copy()
444
+ c.replace(body.copy())
445
+ return node
446
+
447
+ items = [(alias, resolved(body, alias)) for alias, body in items]
448
+ keys = [resolved(k) for k in (group.expressions if group is not None else [])]
449
+ out_names = {a for a, _ in items}
450
+
451
+ def only_aliases(node) -> bool:
452
+ return node is None or (not node.find(exp.AggFunc) and all(c.name in out_names and not c.table for c in node.find_all(exp.Column)))
453
+
454
+ having = tree.args.get("having")
455
+ order = tree.args.get("order")
456
+ if not only_aliases(having.this if having is not None else None):
457
+ return None
458
+ if order is not None and not all(only_aliases(o) for o in order.expressions):
459
+ return None
460
+ where = tree.args.get("where")
461
+ prewhere = tree.args.get("prewhere")
462
+ from .sqlinfo import conjuncts
463
+ return {"tree": tree, "table": base.sql(dialect=dialect), "final": final, "from_sql": t.sql(dialect=dialect),
464
+ "keys": keys, "items": items, "having": having.this.sql(dialect=dialect) if having is not None else "",
465
+ "order_by": ", ".join(o.sql(dialect=dialect) for o in order.expressions) if order is not None else "",
466
+ "limit": limit.sql(dialect=dialect).split(None, 1)[1] if limit is not None else "",
467
+ "offset": tree.args.get("offset").sql(dialect=dialect) if tree.args.get("offset") is not None else "",
468
+ "prewhere": [resolved(c).sql(dialect=dialect) for c in conjuncts(prewhere)],
469
+ "where": [resolved(c).sql(dialect=dialect) for c in conjuncts(where)],
470
+ "settings": " ".join(s.sql(dialect=dialect) for s in tree.args.get("settings") or [])}
471
+
472
+
473
+ def _renamed(sql: str, params: dict, names: dict[tuple, str]) -> tuple[str, dict]:
474
+ """The statement with each `{name:Type}` renamed to the group's name for its (type, value): two members that use the
475
+ same value use the same parameter, so their predicates compare as text."""
476
+ used = {}
477
+
478
+ def one(m: re.Match) -> str:
479
+ name, typ = m.group(1), m.group(2).strip()
480
+ if name not in params:
481
+ return m.group(0)
482
+ key = (typ, json.dumps(params[name], sort_keys=True, default=str))
483
+ if key not in names:
484
+ names[key] = f"g{len(names)}"
485
+ used[names[key]] = params[name]
486
+ return "{" + names[key] + ":" + typ + "}"
487
+ return PARAM.sub(one, sql), used
488
+
489
+
490
+ PROTECTED = re.compile(r"codecopp__(\w+?)__([A-Za-z0-9_]+?)__codecopp")
491
+
492
+
493
+ def _protect(sql: str, dialect: str) -> str:
494
+ """`{name:type}` as an identifier the parser keeps (only ClickHouse's parser knows the parameter form)."""
495
+ if dialect == "clickhouse":
496
+ return sql
497
+ # a list type keeps its `[]` (as `_qarr`): `{ids:text[]}` came back as `{ids:text__}` and the server refused it
498
+ return PARAM.sub(lambda m: f"codecopp__{m.group(1)}__{re.sub(r'[^A-Za-z0-9_]', '_', m.group(2).strip().replace('[]', '_qarr'))}__codecopp", sql)
499
+
500
+
501
+ def _unprotect(text: str) -> str:
502
+ return PROTECTED.sub(lambda m: "{" + m.group(1) + ":" + m.group(2).replace("_qarr", "[]") + "}", text or "")
503
+
504
+
505
+ def _unprotect_variant(v: dict, dialect: str) -> dict:
506
+ if dialect == "clickhouse":
507
+ return v
508
+ v["sql"] = _unprotect(v["sql"])
509
+ for d in v["members"]:
510
+ der = d["derive"]
511
+ for k, val in list(der.items()):
512
+ der[k] = [_unprotect(x) for x in val] if isinstance(val, list) else _unprotect(val)
513
+ return v
514
+
515
+
516
+ def mechanical(plan: dict, group: dict, cfg: dict) -> list[dict]:
517
+ """Variants rules can write: combined aggregates over the shared scan, and a CTE read twice materialized once."""
518
+ dialect = _dialect(plan["engine"])
519
+ out = []
520
+ if group["kind"] == "repeated_read":
521
+ if cfg["materialize_cte"]:
522
+ v = materialize_once(plan, group, dialect)
523
+ if v:
524
+ out.append(v)
525
+ return out
526
+ names: dict[tuple, str] = {}
527
+ parsed = []
528
+ for m in plan["members"]:
529
+ sql, used = _renamed(m["cand"]["baseline_sql"], m["params"], names)
530
+ info = _simple(_protect(sql, dialect), dialect)
531
+ if info:
532
+ parsed.append((m, info, used))
533
+ # members that share FROM (table and FINAL), PREWHERE and SETTINGS combine
534
+ buckets: dict[tuple, list] = {}
535
+ for m, info, used in parsed:
536
+ buckets.setdefault((info["from_sql"], tuple(info["prewhere"]), info["settings"]), []).append((m, info, used))
537
+ for (from_sql, prewhere, settings), ms in buckets.items():
538
+ ms = ms[: cfg["max_members_per_variant"]]
539
+ if len(ms) < 2:
540
+ continue
541
+ try:
542
+ v = combine(ms, from_sql, list(prewhere), settings, dialect, cfg)
543
+ except ValueError:
544
+ v = None
545
+ if v:
546
+ out.append(_unprotect_variant(v, dialect))
547
+ return out
548
+
549
+
550
+ def combine(ms: list, from_sql: str, prewhere: list[str], settings: str, dialect: str, cfg: dict) -> dict | None:
551
+ common = [c for c in ms[0][1]["where"] if all(c in info["where"] for _, info, _ in ms[1:])]
552
+ own = [[c for c in info["where"] if c not in common] for _, info, _ in ms]
553
+ key_sets = [tuple(sorted(k.sql(dialect=dialect) for k in info["keys"])) for _, info, _ in ms]
554
+ same_keys = len(set(key_sets)) == 1
555
+ if not same_keys and not cfg["grouping_sets"]:
556
+ return None
557
+ conds = [" AND ".join(f"({c})" for c in o) for o in own]
558
+ any_own = any(conds)
559
+ if any_own and not all(conds):
560
+ # a member without a filter of its own reads every row of the common filter: its aggregates stay plain, the
561
+ # others' become conditional, and the WHERE is the common filter alone
562
+ pass
563
+ if not common and any_own and not all(conds):
564
+ return None
565
+ all_keys: list[str] = []
566
+ for ks in key_sets:
567
+ for k in ks:
568
+ if k not in all_keys:
569
+ all_keys.append(k)
570
+ select, members = [], []
571
+ for i, ((m, info, used), cond) in enumerate(zip(ms, conds)):
572
+ cols = []
573
+ for j, (alias, body) in enumerate(info["items"]):
574
+ e = body.copy()
575
+ if cond:
576
+ for agg in list(e.find_all(exp.AggFunc)):
577
+ if agg.find_ancestor(exp.AggFunc) is not None:
578
+ continue
579
+ new = conditional(agg, cond, dialect)
580
+ if agg is e:
581
+ e = new
582
+ else:
583
+ agg.replace(new)
584
+ select.append(f"{e.sql(dialect=dialect)} AS m{i}_c{j}")
585
+ cols.append(f"m{i}_c{j} AS {_quote(alias, dialect)}")
586
+ where = []
587
+ if cond and (info["keys"] or not same_keys):
588
+ select.append((f"countIf({cond})" if dialect == "clickhouse" else f"count(*) FILTER (WHERE {cond})") + f" AS m{i}_n")
589
+ where.append(f"m{i}_n > 0")
590
+ if not same_keys:
591
+ mask = 0
592
+ for b, k in enumerate(all_keys):
593
+ if k not in key_sets[i]:
594
+ mask |= 1 << (len(all_keys) - 1 - b)
595
+ where.append(f"codecop_set = {mask}")
596
+ members.append({"key": m["key"], "finding": m["finding"],
597
+ "derive": {"select": cols, "where": " AND ".join(where), "having": info["having"], "order_by": info["order_by"],
598
+ "limit": info["limit"], "offset": info["offset"]}})
599
+ if not same_keys:
600
+ select.append(f"grouping({', '.join(all_keys)}) AS codecop_set")
601
+ sql = f"SELECT {', '.join(select)} FROM {from_sql}"
602
+ if prewhere:
603
+ sql += " PREWHERE " + " AND ".join(prewhere)
604
+ filters = list(common)
605
+ if any_own and all(conds):
606
+ filters.append("(" + " OR ".join(f"({c})" for c in conds) + ")")
607
+ if filters:
608
+ sql += " WHERE " + " AND ".join(filters)
609
+ if all_keys:
610
+ if same_keys:
611
+ sql += " GROUP BY " + ", ".join(all_keys)
612
+ else:
613
+ sets_once = list(dict.fromkeys(key_sets)) # a set listed twice would give each of its rows twice
614
+ sql += " GROUP BY GROUPING SETS (" + ", ".join("(" + ", ".join(ks) + ")" for ks in sets_once) + ")"
615
+ sets = settings
616
+ if not same_keys and dialect == "clickhouse":
617
+ sets = ", ".join(x for x in (settings.removeprefix("SETTINGS ").strip(), "force_grouping_standard_compatibility = 1") if x)
618
+ sets = "SETTINGS " + sets
619
+ if sets:
620
+ sql += " " + sets
621
+ rule = ("grouping_sets" if not same_keys else "conditional_aggregates" if any_own
622
+ else "merged_group_by" if all_keys else "one_select_all_aggregates")
623
+ params = {}
624
+ for _, _, used in ms:
625
+ params.update(used)
626
+ return {"kind": "combined", "rule": rule, "source": "mechanical", "sql": sql, "setup": [], "cleanup": [], "params": params,
627
+ "members": members, "replaces": [m["key"] for m, _, _ in ms],
628
+ "change": {"grouping_sets": "one scan, GROUPING SETS for the different keys, conditional aggregates",
629
+ "conditional_aggregates": "one scan, each member's own filter as a conditional aggregate",
630
+ "merged_group_by": "one scan, the members' aggregates in one GROUP BY",
631
+ "one_select_all_aggregates": "one scan, the members' aggregates in one SELECT"}[rule]}
632
+
633
+
634
+ def _quote(name: str, dialect: str) -> str:
635
+ if re.fullmatch(r"[A-Za-z_]\w*", name):
636
+ return name
637
+ q = "`" if dialect == "clickhouse" else '"'
638
+ return q + name.replace(q, q + q) + q
639
+
640
+
641
+ def materialize_once(plan: dict, group: dict, dialect: str) -> dict | None:
642
+ """A CTE (or a subquery written out again) read several times, computed once: on ClickHouse into a table the
643
+ statement then reads (ClickHouse evaluates a CTE per reference), on PostgreSQL as a MATERIALIZED CTE."""
644
+ m = plan["members"][0]
645
+ sql, used = _renamed(m["cand"]["baseline_sql"], m["params"], {})
646
+ try:
647
+ tree = sqlglot.parse_one(_protect(sql, dialect), read=dialect)
648
+ except Exception: # not parsed: the agent's
649
+ return None
650
+ rep = group.get("repeated") or {}
651
+ tag = hashlib.sha1(group["fingerprint"].encode()).hexdigest()[:8]
652
+ if rep.get("what") == "cte":
653
+ ctes = {c.alias_or_name: c for c in tree.find_all(exp.CTE)}
654
+ target = ctes.get(rep.get("name"))
655
+ if target is None:
656
+ return None
657
+ if dialect == "postgres":
658
+ target.set("materialized", True)
659
+ return _identity_variant(plan, m, tree.sql(dialect=dialect), [], [], used, "materialize_once",
660
+ f"the CTE {rep['name']} as MATERIALIZED: computed once")
661
+ # the CTE's body with the CTEs it reads, into a table of its own; the statement reads the table
662
+ needed, todo = [], [target]
663
+ while todo:
664
+ c = todo.pop()
665
+ for t in c.this.find_all(exp.Table):
666
+ if t.name in ctes and not t.db and ctes[t.name] not in needed and ctes[t.name] is not target:
667
+ needed.append(ctes[t.name])
668
+ todo.append(ctes[t.name])
669
+ name = f"codecop_once_{tag}"
670
+ body = target.this.sql(dialect=dialect)
671
+ if needed:
672
+ order = [c for c in tree.find_all(exp.CTE) if c in needed]
673
+ body = "WITH " + ", ".join(c.sql(dialect=dialect) for c in order) + " " + body
674
+ for t in list(tree.find_all(exp.Table)):
675
+ if t.name == rep["name"] and not t.db:
676
+ t.replace(exp.Table(this=exp.to_identifier(name), alias=t.args.get("alias") or exp.TableAlias(this=exp.to_identifier(rep["name"]))))
677
+ target.pop()
678
+ withs = tree.args.get("with_") or tree.args.get("with")
679
+ if withs is not None and not withs.expressions:
680
+ tree.set("with_", None)
681
+ tree.set("with", None)
682
+ setup = [f"CREATE TABLE {name} ENGINE = Memory AS {body}"]
683
+ return _identity_variant(plan, m, tree.sql(dialect=dialect), setup, [f"DROP TABLE IF EXISTS {name}"], used, "materialize_once",
684
+ f"the CTE {rep['name']} computed once into a temporary table, then read")
685
+ if rep.get("what") == "subquery":
686
+ from .sqlinfo import normalized_predicate
687
+ subs = {}
688
+ for sq in tree.find_all(exp.Subquery):
689
+ if isinstance(sq.this, (exp.Select, exp.Union)) and sq.this.find(exp.Table):
690
+ subs.setdefault(normalized_predicate(sq.this, dialect), []).append(sq)
691
+ twice = [v for v in subs.values() if len(v) >= 2]
692
+ if not twice:
693
+ return None
694
+ nodes = twice[0]
695
+ body = nodes[0].this.sql(dialect=dialect)
696
+ name = f"codecop_once_{tag}"
697
+ if any(n.this.sql(dialect=dialect) != body for n in nodes):
698
+ return None # the same shape with other values: not the same rows
699
+ for n in nodes:
700
+ n.this.replace(sqlglot.parse_one(f"SELECT * FROM {name}", read=dialect))
701
+ if dialect == "postgres":
702
+ text = f"WITH {name} AS MATERIALIZED ({body}) " + tree.sql(dialect=dialect)
703
+ return _identity_variant(plan, m, text, [], [], used, "materialize_once", "the repeated subquery as one MATERIALIZED CTE")
704
+ return _identity_variant(plan, m, tree.sql(dialect=dialect), [f"CREATE TABLE {name} ENGINE = Memory AS {body}"],
705
+ [f"DROP TABLE IF EXISTS {name}"], used, "materialize_once",
706
+ "the repeated subquery computed once into a temporary table, then read")
707
+ return None
708
+
709
+
710
+ def _identity_variant(plan, m, sql, setup, cleanup, used, rule, change) -> dict:
711
+ sql, setup = _unprotect(sql), [_unprotect(x) for x in setup]
712
+ return {"kind": "combined", "rule": rule, "source": "mechanical", "sql": sql, "setup": setup, "cleanup": cleanup, "params": used,
713
+ "members": [{"key": m["key"], "finding": m["finding"], "derive": {"select": ["*"], "where": "", "having": "", "order_by": "",
714
+ "limit": "", "offset": ""}}],
715
+ "replaces": [m["key"]], "change": change}
716
+
717
+
718
+ # --------------------------------------------------------------------------- running
719
+
720
+ def derived_sql(variant: dict, derive: dict) -> str:
721
+ sel = ", ".join(derive.get("select") or ["*"])
722
+ sql = f"SELECT {sel} FROM ({variant['sql']}) AS codecop_g"
723
+ if derive.get("where"):
724
+ sql += f" WHERE {derive['where']}"
725
+ if derive.get("having") or derive.get("order_by") or derive.get("limit"):
726
+ sql = f"SELECT * FROM ({sql}) AS codecop_m"
727
+ if derive.get("having"):
728
+ sql += f" WHERE {derive['having']}"
729
+ if derive.get("order_by"):
730
+ sql += f" ORDER BY {derive['order_by']}"
731
+ if derive.get("limit"):
732
+ sql += f" LIMIT {derive['limit']}"
733
+ if derive.get("offset"):
734
+ sql += f" {derive['offset']}"
735
+ return sql
736
+
737
+
738
+ def run_logged(sb, sql: str, params: dict) -> Measurement:
739
+ """A setup statement of a variant (CREATE TABLE ... AS SELECT), measured from the server's query log (ClickHouse);
740
+ elsewhere only run."""
741
+ m = Measurement(ok=False)
742
+ if getattr(sb, "engine", "") != "clickhouse":
743
+ try:
744
+ sb.execute(sql, params)
745
+ m.ok = True
746
+ except QueryError as e:
747
+ m.error = str(e)
748
+ return m
749
+ tag = f"codecop-g-{uuid.uuid4().hex[:12]}"
750
+ try:
751
+ sb._http(sb.frozen(sql), params, {"query_id": tag, "log_queries": 1, **getattr(sb, "query_limits", {})})
752
+ sb._http("SYSTEM FLUSH LOGS")
753
+ rows = sb.rows("SELECT read_rows, read_bytes, memory_usage, query_duration_ms, ProfileEvents['SelectedParts'] AS parts, "
754
+ "ProfileEvents['SelectedMarks'] AS marks FROM system.query_log WHERE type = 'QueryFinish' AND query_id = {q:String}",
755
+ {"q": tag})
756
+ if rows:
757
+ r = rows[0]
758
+ m.read_rows, m.read_bytes, m.memory_bytes = int(r["read_rows"]), int(r["read_bytes"]), int(r["memory_usage"])
759
+ m.duration_ms = float(r["query_duration_ms"])
760
+ m.selected_parts, m.selected_marks = int(r["parts"]), int(r["marks"])
761
+ m.ok = True
762
+ except QueryError as e:
763
+ m.error = str(e)
764
+ return m
765
+
766
+
767
+ def total(ms: list[Measurement]) -> Measurement:
768
+ out = Measurement(ok=all(m.ok for m in ms))
769
+ out.error = "; ".join(m.error for m in ms if m.error)[:600]
770
+ for m in ms:
771
+ out.read_rows += m.read_rows
772
+ out.read_bytes += m.read_bytes
773
+ out.result_rows += m.result_rows
774
+ out.selected_parts += m.selected_parts
775
+ out.selected_marks += m.selected_marks
776
+ out.total_marks += m.total_marks
777
+ out.duration_ms += m.duration_ms
778
+ out.memory_bytes = max(out.memory_bytes, m.memory_bytes)
779
+ return out
780
+
781
+
782
+ MEASURED = ("read_rows", "read_bytes", "memory_bytes", "selected_parts", "selected_marks", "result_rows", "duration_ms")
783
+
784
+
785
+ def _numbers(m: Measurement) -> dict:
786
+ return {"ok": m.ok, **{k: getattr(m, k) for k in MEASURED}, **({"error": m.error[:300]} if m.error else {})}
787
+
788
+
789
+ def _rows(sb, sql: str, params: dict) -> int:
790
+ got = sb.rows(f"SELECT count(*) AS n FROM ({sb.frozen(sql)}) AS codecop_c", params)
791
+ return int((got[0] if got else {}).get("n") or 0)
792
+
793
+
794
+ def run_variant(sb, plan: dict, variant: dict, which: str, base: dict[str, Measurement], runs: int) -> dict:
795
+ """One variant on one run (typical or heavy): measured, and each member it replaces compared."""
796
+ key = "heavy_params" if which == "heavy" else "params"
797
+ members = {m["key"]: m for m in plan["members"]}
798
+ # the variant's own parameters: the mechanical ones were named per value of the typical run; on the heavy run the
799
+ # same names take the heavy values of the same parameters
800
+ vparams = dict(variant.get("params") or {})
801
+ if which == "heavy":
802
+ vparams = heavy_values(vparams, plan["id"])
803
+ setup_ms, rec = [], {"run": which, "members": []}
804
+ try:
805
+ for s in variant.get("setup") or []:
806
+ got = run_logged(sb, s, vparams)
807
+ setup_ms.append(got)
808
+ if not got.ok:
809
+ raise QueryError(got.error)
810
+ main = sb.measure(variant["sql"], vparams, runs)
811
+ allm = setup_ms + [main]
812
+ rec["measurement"] = _numbers(total(allm))
813
+ rec["statements"] = len(allm)
814
+ matches = []
815
+ for d in variant["members"]:
816
+ mem = members.get(d["key"])
817
+ if mem is None or d["key"] not in base:
818
+ continue
819
+ own = base[d["key"]]
820
+ p = {**mem[key], **vparams}
821
+ dsql = derived_sql(variant, d["derive"])
822
+ compare = bench_mod.Comparison(sb, {"baseline_sql": mem["cand"]["baseline_sql"]}, own, p)
823
+ dm = Measurement(ok=False)
824
+ try:
825
+ dm.result_hash = sb.result_hash(dsql, p)
826
+ dm.result_rows = _rows(sb, dsql, p)
827
+ dm.ok = True
828
+ except QueryError as e:
829
+ dm.error = str(e)
830
+ pending = compare.with_setup({"sql": dsql, "same_results": True}, dm)
831
+ match, compared = compare.settle({"sql": dsql, "same_results": True}, dm, pending) if dm.ok else (None, dm.error[:200])
832
+ if dm.ok and match is not False and own.result_rows == 0 and dm.result_rows == 0:
833
+ match, compared = None, "the member returned no rows on this run: nothing to compare"
834
+ matches.append(match)
835
+ rec["members"].append({"key": d["key"], "finding": mem["finding"], "results_match": match, "compared": compared,
836
+ "member_rows": own.result_rows, "derived_rows": dm.result_rows if dm.ok else None,
837
+ **({"error": dm.error[:300]} if not dm.ok else {})})
838
+ rec["all_match"] = False if False in matches else (None if None in matches or not matches else True)
839
+ except QueryError as e:
840
+ rec["measurement"] = {"ok": False, "error": str(e)[:300]}
841
+ rec["all_match"] = None
842
+ finally:
843
+ for s in variant.get("cleanup") or []:
844
+ try:
845
+ sb.execute(s)
846
+ except QueryError:
847
+ pass
848
+ return rec
849
+
850
+
851
+ def run_plan(sb, plan: dict, runs: int, log=lambda msg: None, tables: list[dict] | None = None) -> dict:
852
+ """The group's baseline and every variant, on the typical and the heavy run."""
853
+ started = time.monotonic()
854
+ out = {"id": plan["id"], "fingerprint": plan["fingerprint"], "runs": {}, "variants": []}
855
+ if plan.get("skip"):
856
+ out["skip"] = plan["skip"]
857
+ return out
858
+ bad = [t for t in tables or [] if not t.get("ok") and any(t["name"] in (m["cand"].get("tables") or []) for m in plan["members"])]
859
+ if bad:
860
+ out["skip"] = "sandbox_table_not_loaded"
861
+ out["tables_not_built"] = [t["name"] for t in bad]
862
+ return out
863
+ bases: dict[str, dict[str, Measurement]] = {}
864
+ for which, key in (("typical", "params"), ("heavy", "heavy_params")):
865
+ per = {m["key"]: sb.measure(m["cand"]["baseline_sql"], m[key], runs) for m in plan["members"]}
866
+ bases[which] = per
867
+ out["runs"][which] = {"members": [{"key": k, "finding": next(m["finding"] for m in plan["members"] if m["key"] == k), **_numbers(v)}
868
+ for k, v in per.items()], "total": _numbers(total(list(per.values())))}
869
+ pages = getattr(sb, "pages_decide", False)
870
+ for i, v in enumerate(plan.get("variants") or []):
871
+ rec = {"index": i, "rule": v.get("rule"), "source": v.get("source"), "change": v.get("change"), "replaces": v.get("replaces"),
872
+ "statements_before": len(v.get("replaces") or []), "statements_after": 1 + len(v.get("setup") or [])}
873
+ said = {}
874
+ for which in ("typical", "heavy"):
875
+ r = run_variant(sb, plan, v, which, bases[which], runs)
876
+ rec[which] = r
877
+ replaced = [bases[which][k] for k in v.get("replaces") or [] if k in bases[which]]
878
+ base = total(replaced)
879
+ var = Measurement(ok=bool((r.get("measurement") or {}).get("ok")), error=(r.get("measurement") or {}).get("error", ""))
880
+ for k in MEASURED:
881
+ if k in (r.get("measurement") or {}):
882
+ setattr(var, k, r["measurement"][k])
883
+ rec[which]["baseline"] = _numbers(base)
884
+ match = r.get("all_match")
885
+ why = "" if match is not None else next((x["compared"] for x in r.get("members") or [] if x.get("results_match") is None), "not compared")
886
+ verdict, reason = bench_mod.verdict(base, var, True, False, sb.floor_bytes, sb.floor_rows, match=match, why=why, pages_decide=pages)
887
+ rec[which]["verdict"], rec[which]["reason"] = verdict, reason
888
+ said[which] = (verdict, reason)
889
+ rec["verdict"], rec["reason"] = bench_mod.combined_verdict(said["typical"], said["heavy"])
890
+ rec["members_reproduced"] = _reproduced(rec)
891
+ if getattr(sb, "resource_cfg", None) and rec["verdict"] in ("win", "mixed"):
892
+ # CPU and memory of the members it replaces against the combined statement, as a candidate's variant has them
893
+ from . import resources as resources_mod
894
+ if v.get("setup"):
895
+ rec["resources"] = {"measured": False, "why": "setup_statements"}
896
+ else:
897
+ members = {m["key"]: m for m in plan["members"]}
898
+ before = [(members[k]["cand"]["baseline_sql"], members[k]["params"]) for k in v.get("replaces") or [] if k in members]
899
+ try:
900
+ rec["resources"] = resources_mod.many_vs_one(sb, before, [(v["sql"], dict(v.get("params") or {}))],
901
+ rec["typical"]["baseline"], rec["typical"].get("measurement") or {})
902
+ except QueryError as e:
903
+ rec["resources"] = {"measured": False, "why": "server_error", "error": str(e)[:200]}
904
+ out["variants"].append(rec)
905
+ log(f"group {plan['id']} variant {i + 1} ({v.get('rule')}): {rec['verdict']}: {rec['reason'][:200]}")
906
+ out["seconds"] = round(time.monotonic() - started, 1)
907
+ return out
908
+
909
+
910
+ def _reproduced(rec: dict) -> dict:
911
+ """Per member: reproduced on both runs (True), on neither (False), or not shown (None)."""
912
+ out = {}
913
+ for which in ("typical", "heavy"):
914
+ for x in (rec.get(which) or {}).get("members") or []:
915
+ prev = out.get(x["key"], True)
916
+ cur = x.get("results_match")
917
+ out[x["key"]] = False if (prev is False or cur is False) else (None if (prev is None or cur is None) else True)
918
+ return out
919
+
920
+
921
+ def run_all(sb, plans: list[dict], runs: int, log=lambda msg: None, tables: list[dict] | None = None) -> list[dict]:
922
+ from .engines.base import SandboxError
923
+ out = []
924
+ for plan in plans:
925
+ try:
926
+ out.append(run_plan(sb, plan, runs, log, tables))
927
+ except SandboxError as e:
928
+ why = sb.revive() if hasattr(sb, "revive") else ""
929
+ out.append({"id": plan["id"], "fingerprint": plan["fingerprint"], "skip": "sandbox_could_not_run",
930
+ "error": f"the sandbox server stopped ({why or e})"[:300]})
931
+ except Exception as e: # noqa: BLE001 -- one plan CodeCop could not handle is its own result, not the end of the run
932
+ out.append({"id": plan["id"], "fingerprint": plan["fingerprint"],
933
+ "skip": "sandbox_could_not_run", "error": f"could not be judged: {type(e).__name__}: {e}"[:300]})
934
+ return out
935
+
936
+
937
+ # --------------------------------------------------------------------------- outcome
938
+
939
+ def outcome(group: dict, result: dict | None, plan: dict | None) -> dict:
940
+ """One of the four states, a reason code and its next step, for one group."""
941
+ def done(state, reason, **evidence):
942
+ return {"state": state, "reason": reason, "next_step": NEXT_STEP[reason], "words": WORDS[reason], **({"evidence": evidence} if evidence else {})}
943
+ if plan is not None and plan.get("skip"):
944
+ out = done("not_judged", plan["skip"], runnable=plan.get("runnable"), members=plan.get("member_count"))
945
+ if plan.get("missing"):
946
+ # what makes the members runnable depends on what is known of them
947
+ out["next_step"] = max(set(plan["missing"]), key=plan["missing"].count)
948
+ return out
949
+ if result is None:
950
+ from .loopbench import engine_reason
951
+ why_engine = engine_reason(group.get("engine") or "", None)
952
+ if why_engine:
953
+ return done("not_judged", why_engine, engine=group.get("engine"))
954
+ if plan is not None and not plan.get("variants"):
955
+ return done("not_judged", "group_variants_not_asked", runnable=plan.get("runnable"))
956
+ return done("not_judged", "bench_not_run")
957
+ if result.get("skip"):
958
+ return done("not_judged", result["skip"])
959
+ vs = result.get("variants") or []
960
+ if not vs:
961
+ return done("not_judged", "group_variants_not_asked", runnable=plan.get("runnable") if plan else None)
962
+ wins = [v for v in vs if v["verdict"] == "win"]
963
+ if wins:
964
+ best = max(wins, key=lambda v: _saved(v))
965
+ return done("fixed", "verified", variant=best["index"], saved_bytes_share=round(_saved(best), 4),
966
+ replaces=len(best.get("replaces") or []), of=group["member_count"])
967
+ if any(v["verdict"] == "rejected" for v in vs):
968
+ partial = [v for v in vs if any(x is True for x in (v.get("members_reproduced") or {}).values())]
969
+ return done("blocked", "group_member_not_reproduced" if partial else "fix_results_differ")
970
+ if all(v["verdict"] == "failed" for v in vs):
971
+ return done("not_judged", "sandbox_could_not_run")
972
+ if any(v["verdict"] == "mixed" and "not shown" in v["reason"] for v in vs):
973
+ empty = all(((result.get("runs") or {}).get(w) or {}).get("total", {}).get("result_rows", 0) == 0 for w in ("typical", "heavy"))
974
+ return done("not_judged", "parameters_match_no_rows" if empty else "sameness_not_shown")
975
+ if any("already reads little" in v["reason"] for v in vs):
976
+ return done("nothing_to_gain", "already_cheap_measured")
977
+ return done("blocked", "no_variant_reads_less")
978
+
979
+
980
+ def _saved(v: dict) -> float:
981
+ shares = []
982
+ for which in ("typical", "heavy"):
983
+ r = v.get(which) or {}
984
+ b, m = (r.get("baseline") or {}).get("read_bytes") or 0, (r.get("measurement") or {}).get("read_bytes") or 0
985
+ if b:
986
+ shares.append(1 - m / b)
987
+ return min(shares) if shares else 0.0
988
+
989
+
990
+ # --------------------------------------------------------------------------- the stage
991
+
992
+ def after_scale(groups_doc: dict, plans: list[dict], runs: int, log):
993
+ """The hook bench.run calls at each scale, with the sandbox and its loaded tables: the groups' results."""
994
+ done: dict[float, set[str]] = {}
995
+
996
+ def hook(sb, tables, profile, fraction, findings=None):
997
+ """`findings`: the candidates of the load group whose tables are loaded now (bench.run loads tables in groups;
998
+ None: everything is loaded). A plan runs in the call where all its members are loaded. A scan group's members
999
+ share its table, so they are never split; one that still is (members over two load groups) is not run and
1000
+ says so, rather than being measured on tables that are gone. Each plan is reported once per scale."""
1001
+ if not plans:
1002
+ return None
1003
+ seen = done.setdefault(fraction, set())
1004
+ todo, out = [], []
1005
+ for p in plans:
1006
+ if p["id"] in seen:
1007
+ continue
1008
+ mine = {m["finding"] for m in p.get("members") or []}
1009
+ if findings is None or mine <= set(findings): # a skipped plan (no members) goes with the first call
1010
+ todo.append(p)
1011
+ elif mine & set(findings):
1012
+ out.append({"id": p["id"], "fingerprint": p["fingerprint"], "skip": "sandbox_table_not_loaded",
1013
+ "error": "the group's members were loaded in different table groups, so it cannot run as one unit "
1014
+ "(group_loads = false under [bench] loads every table together)",
1015
+ "tables_not_built": sorted({t for m in p["members"] for t in m["cand"].get("tables") or []})})
1016
+ else:
1017
+ continue
1018
+ seen.add(p["id"])
1019
+ if todo:
1020
+ log(f"{sum(1 for p in todo if not p.get('skip'))} scan group(s) benchmarked as units")
1021
+ return out + run_all(sb, todo, runs, log, tables)
1022
+ # the members of each plan: bench.run keeps them in one load group when it splits a group to fit the memory
1023
+ hook.together = [{m["finding"] for m in p.get("members") or []} for p in plans if p.get("members")]
1024
+ return hook
1025
+
1026
+
1027
+ def results_into(groups_doc: dict, plans: list[dict], bench_result: dict) -> dict:
1028
+ """groups.json with the variants, the largest scale's results and every group's outcome."""
1029
+ plans_by = {p["id"]: p for p in plans}
1030
+ scales = bench_result.get("scales") or []
1031
+ last = next((s.get("groups") for s in reversed(scales) if s.get("groups") is not None), None) or []
1032
+ by_id = {r["id"]: r for r in last}
1033
+ for g in groups_doc.get("groups") or []:
1034
+ plan = plans_by.get(g["id"])
1035
+ if plan is not None:
1036
+ g["variants"] = [public_variant(v) for v in plan.get("variants") or []]
1037
+ g["runnable_members"] = plan.get("runnable")
1038
+ r = by_id.get(g["id"])
1039
+ if r is not None:
1040
+ g["result"] = r
1041
+ g["outcome"] = outcome(g, r, plan)
1042
+ groups_doc["outcomes"] = summarize(groups_doc)
1043
+ groups_doc["bench_generated_at"] = bench_result.get("generated_at")
1044
+ return groups_doc
1045
+
1046
+
1047
+ def public_variant(v: dict) -> dict:
1048
+ return {k: v[k] for k in ("kind", "rule", "source", "sql", "setup", "cleanup", "members", "replaces", "change") if k in v}
1049
+
1050
+
1051
+ def summarize(groups_doc: dict) -> dict:
1052
+ states = {s: 0 for s in REASONS}
1053
+ reasons: dict[str, int] = {}
1054
+ for g in groups_doc.get("groups") or []:
1055
+ o = g.get("outcome")
1056
+ if o:
1057
+ states[o["state"]] += 1
1058
+ reasons[o["reason"]] = reasons.get(o["reason"], 0) + 1
1059
+ return {"states": states, "reasons": reasons}
1060
+
1061
+
1062
+ # --------------------------------------------------------------------------- the paid step (never run here)
1063
+
1064
+ def needs_agent(groups_doc: dict) -> list[dict]:
1065
+ """Groups no rule combined (or whose rule did not win) whose members can run: what the agent would be asked."""
1066
+ out = []
1067
+ for g in groups_doc.get("groups") or []:
1068
+ o = g.get("outcome") or {}
1069
+ if g.get("agent_asked"):
1070
+ continue
1071
+ if o.get("reason") in ("group_variants_not_asked", "no_variant_reads_less", "fix_results_differ", "group_member_not_reproduced") \
1072
+ and (g.get("runnable_members") or 0) >= (1 if g["kind"] == "repeated_read" else 2):
1073
+ out.append(g)
1074
+ return out
1075
+
1076
+
1077
+ def estimate(groups_doc: dict, settings: dict | None = None) -> dict:
1078
+ cfg = settings_of(settings)
1079
+ todo = needs_agent(groups_doc)
1080
+ n = sum(int(g.get("runnable_members") or 0) for g in todo)
1081
+ return {"groups": len(todo), "members": n, "cost_low_usd": round(n * cfg["agent_cost_per_member_usd_low"], 2),
1082
+ "cost_high_usd": round(n * cfg["agent_cost_per_member_usd_high"], 2), "ids": [g["id"] for g in todo]}
1083
+
1084
+
1085
+ def prompt(groups_doc: dict, rank: dict, engine: str, version: str, settings: dict | None = None, only: list[str] | None = None) -> str:
1086
+ """The paid step's prompt: for each group, its members as they run, and the request for one combined statement (or
1087
+ fewer statements) with the derivation of every member's rows from its output."""
1088
+ cfg = settings_of(settings)
1089
+ from . import engines
1090
+ parts = []
1091
+ for g in needs_agent(groups_doc):
1092
+ if only and g["id"] not in only:
1093
+ continue
1094
+ cands = candidates_of(g, rank.get("candidates") or [])
1095
+ lines = [f"### {g['id']} ({g['kind']}): table {g['table']}; shared filter: "
1096
+ + (", ".join(p["text"] for p in g.get("shared_filter") or []) or "(one statement)")]
1097
+ for m in g["members"]:
1098
+ c = cands.get(m["key"])
1099
+ if c is None:
1100
+ continue
1101
+ place = f"{m.get('file')}:{m.get('line')}" if m.get("file") else "no place in code"
1102
+ lines.append(f"member {m['key']} ({c['finding']}, {place}, runs {((m.get('measured') or {}).get('executions')) or '?'}):\n"
1103
+ f"```sql\n{c['baseline_sql'][: cfg['agent_max_sql_chars']]}\n```")
1104
+ parts.append("\n\n".join(lines))
1105
+ eng = engines.get(engine).label if engine else engine
1106
+ return (f"You are combining database statements that run together, for an automated benchmark on {eng} {version}. Each group below lists "
1107
+ "statements one job cycle or one page sends, which scan the same table under the same filter. Propose one statement (or fewer "
1108
+ "statements) that reads the shared rows once and from whose result every member's rows can be derived.\n\n"
1109
+ "## Rules\n- Keep every parameter (`{name:Type}`) with its name and type.\n- For every member you replace, give `derive`: `select` (a list of "
1110
+ "expressions over the combined result's columns, each `AS` the member's own column name, in the member's column order), `where` (a filter "
1111
+ "on the combined result's columns, for example a grouping key or a presence count), and the member's own `having`, `order_by`, `limit`.\n"
1112
+ "- `setup`: statements the combined form needs first (a temporary table), measured too; `cleanup` removes them.\n"
1113
+ "- The harness derives each member's rows and compares them with the member's own result. A combination that cannot reproduce a member "
1114
+ "is not used: leave that member out of `members`.\n- Use only syntax and functions of this engine and version.\n\n## Groups\n\n"
1115
+ + "\n\n".join(parts) + "\n\nReturn JSON: {\"groups\": [{\"id\", \"variants\": [{\"sql\", \"setup\", \"cleanup\", \"change\", "
1116
+ "\"members\": [{\"key\", \"derive\": {\"select\", \"where\", \"having\", \"order_by\", \"limit\"}}]}]}]}.")
1117
+
1118
+
1119
+ AGENT_SCHEMA = {
1120
+ "type": "object", "required": ["groups"], "additionalProperties": False,
1121
+ "properties": {"groups": {"type": "array", "items": {
1122
+ "type": "object", "required": ["id", "variants"], "additionalProperties": False,
1123
+ "properties": {"id": {"type": "string"}, "variants": {"type": "array", "maxItems": 3, "items": {
1124
+ "type": "object", "required": ["sql", "members"], "additionalProperties": False,
1125
+ "properties": {"sql": {"type": "string"}, "setup": {"type": "array", "items": {"type": "string"}},
1126
+ "cleanup": {"type": "array", "items": {"type": "string"}}, "change": {"type": "string"},
1127
+ "members": {"type": "array", "items": {
1128
+ "type": "object", "required": ["key", "derive"], "additionalProperties": False,
1129
+ "properties": {"key": {"type": "string"}, "derive": {
1130
+ "type": "object", "additionalProperties": False,
1131
+ "properties": {k: ({"type": "array", "items": {"type": "string"}} if k == "select" else {"type": "string"})
1132
+ for k in ("select", "where", "having", "order_by", "limit", "offset")}}}}}}}}}}}},
1133
+ }
1134
+
1135
+
1136
+ PROMPT_REV = "groups-2" # bumped when the instructions change in a way that changes answers: stored answers are asked again
1137
+
1138
+
1139
+ def prompt_version() -> str:
1140
+ from . import verdicts
1141
+ return verdicts.prompt_version(PROMPT_REV, json.dumps(AGENT_SCHEMA, sort_keys=True))
1142
+
1143
+
1144
+ def answer_key(g: dict, rank: dict | None, answers) -> str:
1145
+ """What a group's answer depends on: its members' statements as they run (else their keys) and its table's definition."""
1146
+ cands = candidates_of(g, (rank or {}).get("candidates") or [])
1147
+ text = "\n;\n".join(sorted((cands[m["key"]].get("baseline_sql") or m["key"]) if m.get("key") in cands else str(m.get("key"))
1148
+ for m in g.get("members") or []))
1149
+ return answers.key("group", f"{g.get('kind')}\n{text}", [g.get("table") or ""], prompt_version())
1150
+
1151
+
1152
+ def sync_answers(groups_doc: dict, rank: dict | None, answers, fresh=False) -> dict:
1153
+ """groups.json's answers made to agree with the per-statement answer store: a group answered for its members as they
1154
+ run now gets its answer back; one answered for other statements or another definition of its table is asked again;
1155
+ an answer only groups.json holds (an earlier CodeCop) is moved into the store once."""
1156
+ from .verdicts import wants_fresh
1157
+ got = {"restored": 0, "dropped": 0, "migrated": 0}
1158
+ for g in groups_doc.get("groups") or []:
1159
+ k = answer_key(g, rank, answers)
1160
+ rec = answers.get(k, fresh, ref=g.get("id") or "")
1161
+ if rec is not None:
1162
+ g["agent_variants"] = list((rec.get("answer") or {}).get("variants") or [])
1163
+ g["agent_asked"] = True
1164
+ g["agent_answer_key"] = k
1165
+ got["restored"] += 1
1166
+ elif g.get("agent_asked") and (g.get("agent_answer_key") not in (None, k) or wants_fresh(fresh, ref=g.get("id") or "")):
1167
+ g.pop("agent_variants", None)
1168
+ g.pop("agent_asked", None)
1169
+ g.pop("agent_answer_key", None)
1170
+ got["dropped"] += 1
1171
+ elif g.get("agent_asked"):
1172
+ answers.put(k, {"kind": "group", "id": g.get("id"), "answer": {"variants": list(g.get("agent_variants") or [])},
1173
+ "migrated_from": "groups.json"}, save=False)
1174
+ g["agent_answer_key"] = k
1175
+ got["migrated"] += 1
1176
+ if got["migrated"]:
1177
+ answers.save()
1178
+ return got
1179
+
1180
+
1181
+ def ask_agent(groups_doc: dict, rank: dict, root, runner, *, engine: str, version: str, model: str | None = None,
1182
+ max_budget_usd: float | None = None, settings: dict | None = None, only: list[str] | set[str] | None = None,
1183
+ concurrency: int = 1, answers=None) -> dict:
1184
+ """The paid step: agent calls for the groups no rule combined (or the ones the run's queue chose: `only`),
1185
+ agent_groups_per_call groups a call, `concurrency` calls at a time. Changes `groups_doc` in place
1186
+ (`agent_variants`, `agent_asked`, the cost ledger) and puts each answer in the per-statement answer store (`answers`).
1187
+ A call the budget or the agent's usage limit stopped leaves its groups not asked."""
1188
+ import threading
1189
+ from concurrent.futures import ThreadPoolExecutor
1190
+ from .agent import AgentError, UsageLimitError
1191
+ cfg = settings_of(settings)
1192
+ todo = [g for g in needs_agent(groups_doc) if not only or g["id"] in set(only)]
1193
+ if not todo:
1194
+ return {"asked": 0, "with_variants": 0, "cost_usd": 0.0, "calls": 0, "not_asked_budget": 0, "not_asked_limit": 0}
1195
+ per = max(int(cfg["agent_groups_per_call"]), 1)
1196
+ chunks = [todo[i:i + per] for i in range(0, len(todo), per)]
1197
+ ledger = groups_doc.setdefault("agent", {"calls": []})
1198
+ lock = threading.Lock()
1199
+ stop = threading.Event()
1200
+ tot = {"asked": 0, "got": 0, "spent": 0.0, "calls": 0, "budget": 0, "limit": 0}
1201
+
1202
+ def one(chunk: list[dict]) -> None:
1203
+ if stop.is_set():
1204
+ with lock:
1205
+ tot[tot.get("why") or "budget"] += len(chunk) # not asked: for what stopped the step
1206
+ return
1207
+ if hasattr(runner, "tell"):
1208
+ runner.tell("groups", sum(int(g.get("runnable_members") or 1) for g in chunk))
1209
+ ids = [g["id"] for g in chunk]
1210
+ try:
1211
+ result = runner.run(prompt(groups_doc, rank, engine, version, settings, only=ids), AGENT_SCHEMA, root, model=model,
1212
+ max_budget_usd=max_budget_usd)
1213
+ except UsageLimitError:
1214
+ with lock:
1215
+ tot.setdefault("why", "limit")
1216
+ tot["limit"] += len(chunk)
1217
+ stop.set()
1218
+ return
1219
+ except AgentError as e:
1220
+ if "budget" not in str(e).lower():
1221
+ raise
1222
+ stop.set()
1223
+ with lock:
1224
+ tot["budget"] += len(chunk)
1225
+ return
1226
+ by_id = {g["id"]: g for g in chunk}
1227
+ with lock:
1228
+ for entry in (result.output or {}).get("groups") or []:
1229
+ g = by_id.get(entry.get("id"))
1230
+ if g is None:
1231
+ continue
1232
+ keys = {m["key"] for m in g["members"]}
1233
+ vs = []
1234
+ for v in entry.get("variants") or []:
1235
+ members = [m for m in v.get("members") or [] if m.get("key") in keys]
1236
+ if v.get("sql") and members:
1237
+ vs.append({"kind": "combined", "rule": "agent", "sql": v["sql"], "setup": list(v.get("setup") or []),
1238
+ "cleanup": list(v.get("cleanup") or []), "change": (v.get("change") or "")[:120],
1239
+ "members": [{"key": m["key"], "derive": {k: (m.get("derive") or {}).get(k, [] if k == "select" else "")
1240
+ for k in ("select", "where", "having", "order_by", "limit", "offset")}}
1241
+ for m in members], "replaces": [m["key"] for m in members]})
1242
+ g["agent_variants"] = vs
1243
+ tot["got"] += bool(vs)
1244
+ for g in chunk:
1245
+ g["agent_asked"] = True
1246
+ if answers is not None:
1247
+ k = answer_key(g, rank, answers)
1248
+ answers.put(k, {"kind": "group", "id": g["id"], "answer": {"variants": list(g.get("agent_variants") or [])},
1249
+ "model": getattr(result, "model", "")}, save=False)
1250
+ g["agent_answer_key"] = k
1251
+ tot["asked"] += len(chunk)
1252
+ tot["calls"] += 1
1253
+ tot["spent"] += float(result.cost_usd or 0)
1254
+ ledger["calls"].append({"groups": ids, "cost_usd": round(float(result.cost_usd or 0), 6), "model": result.model, "at": now()})
1255
+ if answers is not None:
1256
+ answers.save()
1257
+
1258
+ workers = max(min(int(concurrency or 1), len(chunks)), 1)
1259
+ if workers == 1:
1260
+ for c in chunks:
1261
+ one(c)
1262
+ else:
1263
+ with ThreadPoolExecutor(max_workers=workers) as pool:
1264
+ for f in [pool.submit(one, c) for c in chunks]:
1265
+ f.result()
1266
+ ledger["cost_total_usd"] = round(sum(x["cost_usd"] for x in ledger["calls"]), 4)
1267
+ return {"asked": tot["asked"], "with_variants": tot["got"], "cost_usd": round(tot["spent"], 4), "calls": tot["calls"],
1268
+ "not_asked_budget": tot["budget"], "not_asked_limit": tot["limit"]}
1269
+
1270
+
1271
+ # --------------------------------------------------------------------------- hand-off
1272
+
1273
+ def handoff(g: dict) -> str:
1274
+ """For the developer or their coding agent: which call sites to merge into one call, and how each result maps."""
1275
+ o = g.get("outcome") or {}
1276
+ lines = [f"Scan group {g['id']} ({g['fingerprint']}): {g['member_count']} statement(s) read {g['table']}"
1277
+ + (f" under the same filter ({', '.join(p['text'] for p in g.get('shared_filter') or [])})" if g.get("shared_filter") else "")
1278
+ + ".", f"State: {STATE_WORDS.get(o.get('state'), '?')}. {o.get('words', '')}."]
1279
+ best = None
1280
+ if o.get("state") == "fixed":
1281
+ best = next((v for v in g.get("variants") or [] if v is not None and (o.get("evidence") or {}).get("variant") is not None
1282
+ and (g.get("variants") or []).index(v) == o["evidence"]["variant"]), None)
1283
+ by_key = {m["key"]: m for m in g["members"]}
1284
+ if best:
1285
+ lines.append("")
1286
+ lines.append("This is an application change: the code must call one query instead of " + str(len(best["replaces"])) + ".")
1287
+ lines.append("Merge these call sites into one call:")
1288
+ for d in best["members"]:
1289
+ m = by_key.get(d["key"], {})
1290
+ place = f"{m.get('file')}:{m.get('line')} {m.get('symbol') or ''}".strip() if m.get("file") else f"production statement {m.get('hash')} (no place in code)"
1291
+ lines.append(f" - {place}")
1292
+ lines.append("")
1293
+ lines.append("Run once:")
1294
+ for s in best.get("setup") or []:
1295
+ lines.append(f" {s}")
1296
+ lines.append(f" {best['sql']}")
1297
+ lines.append("")
1298
+ lines.append("Each former call's rows, from that one result:")
1299
+ for d in best["members"]:
1300
+ m = by_key.get(d["key"], {})
1301
+ der = d["derive"]
1302
+ how = f"columns {', '.join(der.get('select') or ['*'])}"
1303
+ if der.get("where"):
1304
+ how += f"; rows where {der['where']}"
1305
+ for k, word in (("having", "then keep rows where"), ("order_by", "ordered by"), ("limit", "limit")):
1306
+ if der.get(k):
1307
+ how += f"; {word} {der[k]}"
1308
+ lines.append(f" - {m.get('file') or m.get('hash')}:{m.get('line') or ''}: {how}")
1309
+ r = (g.get("result") or {}).get("variants") or []
1310
+ rec = r[o["evidence"]["variant"]] if o.get("evidence") and o["evidence"]["variant"] < len(r) else None
1311
+ if rec:
1312
+ lines.append("")
1313
+ for which in ("typical", "heavy"):
1314
+ x = rec.get(which) or {}
1315
+ b, m = x.get("baseline") or {}, x.get("measurement") or {}
1316
+ lines.append(f"Measured ({which} run): {b.get('read_bytes', 0):,} bytes read by the separate statements, "
1317
+ f"{m.get('read_bytes', 0):,} by the combined one; every replaced member's rows reproduced.")
1318
+ else:
1319
+ lines.append(f"Next step: {(_code(o.get('next_step')) or '').replace('_', ' ')}.")
1320
+ lines.append("")
1321
+ lines.append("Check the change: run the members and the combined statement on the same parameters and compare each member's rows "
1322
+ "(codecop bench does this in its sandbox).")
1323
+ return "\n".join(lines) + "\n"
1324
+
1325
+
1326
+ # --------------------------------------------------------------------------- upload
1327
+
1328
+ UPLOAD_GROUP_KEYS = ("id", "fingerprint", "kind", "table", "engine", "member_count", "roles", "confidence", "notes", "labels", "also_tables")
1329
+ UPLOAD_MEMBER_KEYS = ("key", "site_ids", "sql_from", "located", "engine", "hash", "file", "line", "symbol", "role", "shared_with")
1330
+ UPLOAD_MEASURED = ("executions", "read_bytes", "share_of_read_bytes", "window_hours", "bytes_read_per_run", "rows_read_per_run",
1331
+ "rows_returned_per_run", "no_result_share", "shapes", "members_measured")
1332
+
1333
+
1334
+ def _pick(d, keys):
1335
+ return {k: d[k] for k in keys if isinstance(d, dict) and k in d}
1336
+
1337
+
1338
+ def for_upload(doc: dict, with_text: bool = True, databases: set[str] | None = None) -> dict:
1339
+ """groups.json for the bundle, field by field: ids, places, codes, counts and normalized text (every value `?`, no
1340
+ parameter values, tables without their database). `with_text` off ([push] observed_text) drops the combined
1341
+ statements' text too. `databases`: the real database's names, removed from every text."""
1342
+ from .observed import strip_databases
1343
+ from .sqlinfo import _normalize_text
1344
+
1345
+ def clean(text: str) -> str:
1346
+ return strip_databases(text, databases) if databases else text
1347
+ out = []
1348
+ for g in doc.get("groups") or []:
1349
+ q = _pick(g, UPLOAD_GROUP_KEYS)
1350
+ q["shared_filter"] = [{**_pick(p, ("column", "op", "equality")), "text": clean(p.get("text") or "")} for p in g.get("shared_filter") or []]
1351
+ if g.get("repeated"):
1352
+ q["repeated"] = _pick(g["repeated"], ("what", "name", "reads", "tables"))
1353
+ q["run_together"] = [_pick(r, ("source", "confidence", "kind", "name", "file", "line", "function", "runs_min", "runs_max"))
1354
+ for r in g.get("run_together") or []]
1355
+ q["members"] = [{**_pick(m, UPLOAD_MEMBER_KEYS), **({"measured": _pick(m["measured"], UPLOAD_MEASURED)} if m.get("measured") else {})}
1356
+ for m in g.get("members") or []]
1357
+ q["measured"] = _pick(g.get("measured"), UPLOAD_MEASURED) if g.get("measured") else None
1358
+ q["variants"] = [{**_pick(v, ("rule", "source", "replaces")), "change": clean(str(v.get("change") or ""))[:120],
1359
+ **({"normalized_sql": clean(_normalize_text(re.sub(r"\{\w+\s*:\s*[^{}]+\}", "?", v.get("sql") or "")))} if with_text else {}),
1360
+ "statements_after": 1 + len(v.get("setup") or [])} for v in g.get("variants") or []]
1361
+ r = g.get("result") or {}
1362
+ q["result"] = {"variants": [{"rule": v.get("rule"), "verdict": v.get("verdict"), "members_reproduced": v.get("members_reproduced"),
1363
+ **{w: {"baseline": _pick((v.get(w) or {}).get("baseline"), MEASURED),
1364
+ "measurement": _pick((v.get(w) or {}).get("measurement"), MEASURED),
1365
+ "verdict": (v.get(w) or {}).get("verdict")} for w in ("typical", "heavy")}}
1366
+ for v in r.get("variants") or []]} if r else None
1367
+ o = g.get("outcome")
1368
+ q["outcome"] = _pick(o, ("state", "reason", "next_step")) if o else None
1369
+ out.append(q)
1370
+ return {"schema_version": doc.get("schema_version", 1), "generated_at": doc.get("generated_at"), "settings": doc.get("settings") or {},
1371
+ "window_hours": doc.get("window_hours"), "summary": doc.get("summary") or {}, "outcomes": doc.get("outcomes") or {}, "groups": out}
1372
+
1373
+
1374
+ def now() -> str:
1375
+ return datetime.now(timezone.utc).isoformat(timespec="seconds")