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/advisor_ch.py ADDED
@@ -0,0 +1,2080 @@
1
+ """ClickHouse access-path advisor: per table, across every statement CodeCop knows, the smallest set of table changes that
2
+ serves the most read load, each proved as a set on the sandbox. Rules only: no agent, no network, no database.
3
+
4
+ Where the scenario rules (scenarios.py, scenario_bind.py) write one variant per statement, this module asks per table:
5
+ which one change serves the most of the table's load. It reads every statement that reads the table (SQL in code,
6
+ ORM-translated SQL, the statements production ran with their measured load), and for each read of the table collects
7
+ its filters by operator, GROUP BY keys, ORDER BY, the columns it reads, its aggregates and FINAL; then compares them with
8
+ the table's sorting key, partition key, skip indexes and projections (real catalog, else the inventory's definitions).
9
+
10
+ Candidates, by operator and by load, de-duplicated into one minimal set per table (`max_candidates_per_table`):
11
+
12
+ skip_index the type that fits the operator: minmax for ranges, set(N) for few values (N from the profile or
13
+ the catalog), bloom_filter for many, ngrambf_v1 for LIKE '%x%' and LIKE 'x%', tokenbf_v1 for
14
+ hasToken, a text index where the server version has one (`text_index_min_version`), bloom on
15
+ mapKeys / mapValues for map lookups; GRANULARITY tried at every value of `granularities`
16
+ projection ordered by the prefix the served statements want, holding only the columns they read
17
+ aggregating_projection GROUP BY (time bucket, few dimensions) of statements that run often and read far more rows than
18
+ they return: the SQL does not change; the engine picks the projection, which the proof checks
19
+ ordering_key a re-keyed copy: only when the load-weighted majority of the table's statements want the same
20
+ prefix, the dedup identity is kept (a permutation of the old key on a deduplicating engine)
21
+ dedup_on_read FINAL on a Replacing table, by rule: key filters into PREWHERE (scenario_sql.prewhere_keys) or
22
+ into the FINAL subquery, per-partition merge when every version of a key is in one partition,
23
+ LIMIT 1 BY / argMax by the sorting key and `_partition_id`, FINAL dropped under aggregates
24
+ duplicates cannot change (strict: only sorting-key columns are read)
25
+
26
+ Proof is a set (`hook`, called by `codecop bench` while the tables are loaded): each candidate is built once on the sandbox
27
+ table, every statement it claims to serve is measured before and after on the typical and the heavy run (same rows),
28
+ and every other runnable statement of the table too (no regression). A statement with no runnable form is "claimed,
29
+ not measured" and never counts toward a verified gain. The insert side (writecost.py) is measured for every table-level
30
+ candidate that reads less, and blockers.insert_cost_rule decides fixed against trade-off.
31
+
32
+ Skip indexes mostly do not prune on generated data: whether they do depends on how values sit inside granules. Each
33
+ skip-index candidate says on what basis its column's placement was set in the sandbox (`locality_basis`): the sorting
34
+ key, the time ranges parts were cut by, a profile expression, unique values (placement does not matter), or values only
35
+ (catalog or profile values placed at random: production's placement unknown). On a values-only basis the measured
36
+ result, either way, is evidence only ("could not be judged on generated data"), never "no change" as if measured.
37
+
38
+ Thresholds are settings under `[advisor]` in codecop.toml (DEFAULTS). Output: advisor.json (`table_suggestions[]`, the shape
39
+ shared with the PostgreSQL advisor; ClickHouse extras under `engine_detail`).
40
+ """
41
+
42
+ from __future__ import annotations
43
+
44
+ import hashlib
45
+ import re
46
+ from collections import defaultdict
47
+ from datetime import datetime, timezone
48
+
49
+ from sqlglot import exp
50
+
51
+ from . import scenario_sql as Q
52
+ from .scenarios import _short, statements as all_statements
53
+
54
+ SCHEMA_VERSION = 1
55
+ FILE = "advisor.json"
56
+ ENGINE = "clickhouse"
57
+ KINDS = ("skip_index", "projection", "aggregating_projection", "ordering_key", "dedup_on_read")
58
+ TABLE_KINDS = ("skip_index", "projection", "aggregating_projection", "ordering_key")
59
+ # a new sort order: judged on selected marks where the sandbox's granules are scaled to production's
60
+ KEY_ORDER_KINDS = ("projection", "aggregating_projection", "ordering_key")
61
+ # the kind as the bench and writecost know it
62
+ BENCH_KIND = {"skip_index": "skip_index", "projection": "projection", "aggregating_projection": "projection",
63
+ "ordering_key": "ordering_key", "dedup_on_read": "rewrite"}
64
+ PREFIX = "codecop_adv"
65
+
66
+ DEFAULTS = {
67
+ "max_candidates_per_table": 12, # candidates kept per table, most load served first
68
+ "max_tables": 200, # tables planned, most load first
69
+ "bloom_fpr": 0.01, # bloom_filter(false positive rate)
70
+ "set_max_distinct": 1000, # equality on a column with at most this many distinct values: set(N), else bloom_filter
71
+ "set_max_values": 1000, # N of set(N) is the column's distinct count, at most this
72
+ "set_lowcardinality_values": 256, # N for a LowCardinality column whose distinct count is not known
73
+ "tokenbf_bytes": 10240, # tokenbf_v1(bytes, hashes, seed)
74
+ "tokenbf_hashes": 3,
75
+ "ngram_size": 3, # ngrambf_v1(n, bytes, hashes, seed)
76
+ "ngrambf_bytes": 10240,
77
+ "ngrambf_hashes": 3,
78
+ "text_index": True, # also try a text index for token search where the server version has one
79
+ "text_index_min_version": "25.9",
80
+ "unique_min_rows_per_value": 0.0, # distinct >= rows / this many ... see unique_max_rows_per_value
81
+ "unique_max_rows_per_value": 4.0, # a column with at most this many rows per value is unique enough: placement does not matter
82
+ "projection_max_columns_share": 0.8, # a projection holding more than this share of the table's columns is a full copy: said
83
+ "agg_max_dimensions": 4, # GROUP BY keys besides the time bucket
84
+ "agg_min_ratio": 100.0, # rows read per row returned, for a measured statement
85
+ "agg_min_runs_per_hour": 1.0, # a measured statement run less often is not pre-aggregated
86
+ "agg_static": True, # code statements with no measured load may still be claimed (weight 0)
87
+ "rekey_min_share": 0.5, # the new key serves at least this share of the table's load ...
88
+ "rekey_min_gain": 0.2, # ... and this much more than the current key does
89
+ "rekey_min_statements_static": 3, # with no measured load: at least this many statements gain from it
90
+ "rekey_min_read_bytes": 1_000_000_000, # with a pull: the table's statements read at least this much in the window
91
+ "projection_over_rekey": 0.9, # a verified projection with this share of a re-key's gain makes the re-key unnecessary
92
+ "regression_ratio": 1.1, # a statement the candidate does not serve may read at most this many times what it did
93
+ "min_read_gain": 0.1, # a candidate reads less when its weighted read is at most 1 - this of the baseline's
94
+ "final_rules": True, # dedup-on-read rules on Replacing tables read with FINAL
95
+ "max_dedup_statements": 6, # ... on at most this many statements per table, most load first
96
+ "max_runnable": 60, # statements built from production's text for the advisor, heaviest first
97
+ "max_statements_per_table": 20, # runnable statements of a table measured with each candidate, heaviest first
98
+ "locality_disagree_factor": 2.0, # a re-key or projection whose sandbox marks and production's row counts differ more: not judged
99
+ "locality_ratio_floor": 0.01, # ... ratios below this are compared as this (two large gains are not a disagreement)
100
+ }
101
+ LIST_DEFAULTS = {
102
+ "granularities": [1, 4, 8],
103
+ # aggregates whose state a projection keeps and the engine merges again (with the -If, -OrNull combinators)
104
+ "agg_functions": ["count", "sum", "min", "max", "avg", "uniq", "uniqexact", "uniqcombined", "uniqhll12", "any", "anylast",
105
+ "argmin", "argmax", "quantile", "quantiles", "median", "grouparray", "groupuniqarray", "topk"],
106
+ # aggregates that duplicates of a row cannot change, over sorting-key columns only (FINAL dropped)
107
+ "duplicate_insensitive": ["min", "max", "uniqexact", "uniq", "uniqcombined", "uniqhll12", "uniqtheta", "groupuniqarray"],
108
+ }
109
+ BUCKETS = re.compile(r"^(?:tostartof\w+|todate|todate32|todatetime|toyyyymm|toyyyymmdd|toyyyymmddhhmmss|tomonday|toyear|"
110
+ r"tohour|datetrunc|date_trunc|tostartofinterval|torelative\w+num)$")
111
+ KEY_SAFE = {"todate", "todate32", "todatetime", "todatetime64", "tostartofday", "tostartofhour", "tostartofminute", "tostartofmonth",
112
+ "tostartofweek", "tostartofyear", "tostartofquarter", "tostartoffiveminutes", "tostartoffifteenminutes",
113
+ "tostartoftenminutes", "tostartofinterval", "tomonday", "toyyyymm", "toyyyymmdd", "parsedatetimebesteffort",
114
+ "parsedatetime64besteffort", "tounixtimestamp", "identity"}
115
+ TOKEN_FUNCS = {"hastoken", "hastokenornull"}
116
+ HAS_FUNCS = {"has", "hasany", "hasall"}
117
+ TIME_TYPE = Q.TIME_TYPE
118
+ NUMERIC = re.compile(r"^(?:Nullable\()?(?:U?Int\d+|Float\d+|Decimal)", re.I)
119
+
120
+
121
+ def settings_of(config: dict | None) -> dict:
122
+ out = {**DEFAULTS, **{k: list(v) for k, v in LIST_DEFAULTS.items()}}
123
+ for k, v in (config or {}).items():
124
+ if k in DEFAULTS:
125
+ d = DEFAULTS[k]
126
+ if isinstance(d, bool):
127
+ if isinstance(v, bool):
128
+ out[k] = v
129
+ elif isinstance(d, str):
130
+ if isinstance(v, str) and re.fullmatch(r"\d+(?:\.\d+)*", v):
131
+ out[k] = v
132
+ elif isinstance(v, (int, float)) and not isinstance(v, bool) and v >= 0:
133
+ out[k] = type(d)(v)
134
+ elif k == "granularities" and isinstance(v, list) and v and all(isinstance(x, int) and not isinstance(x, bool) and x > 0 for x in v):
135
+ out[k] = sorted(set(v))
136
+ elif k in LIST_DEFAULTS and isinstance(v, list) and all(isinstance(x, str) for x in v):
137
+ out[k] = [x.lower() for x in v]
138
+ return out
139
+
140
+
141
+ def version_at_least(version: str, wanted: str) -> bool:
142
+ def parts(s):
143
+ return [int(x) for x in re.findall(r"\d+", str(s or ""))[:3]] or [0]
144
+ return parts(version) >= parts(wanted)
145
+
146
+
147
+ # ---- what one read of a table does ---------------------------------------------------------------------------------
148
+
149
+ def _strip(node):
150
+ while isinstance(node, exp.Paren):
151
+ node = node.this
152
+ return node
153
+
154
+
155
+ def _col(node, rd, info, single) -> str | None:
156
+ node = _strip(node)
157
+ if isinstance(node, exp.Column):
158
+ name, sub = Q.column_of(node, rd, info, single)
159
+ return name if name and not sub else None
160
+ return None
161
+
162
+
163
+ def _bare_chain(node, rd, info, single) -> tuple[str | None, list[str]]:
164
+ """A column of the table, possibly inside functions over that one column: (column, functions outermost first)."""
165
+ names, col = Q._chain(node, ENGINE)
166
+ if col is None:
167
+ return None, []
168
+ name, sub = Q.column_of(col, rd, info, single)
169
+ return (name, names) if name and not sub else (None, [])
170
+
171
+
172
+ def _no_table_columns(nodes, rd, info, single) -> bool:
173
+ return not any(Q.columns_in(n, rd, info, single) for n in nodes if n is not None)
174
+
175
+
176
+ def _like_kind(pattern) -> str:
177
+ p = _strip(pattern)
178
+ if isinstance(p, exp.Literal) and p.is_string:
179
+ text = str(p.this)
180
+ if text.startswith("%") or text.startswith("_"):
181
+ return "like_infix"
182
+ return "like_prefix" if "%" in text or "_" in text else "eq"
183
+ return "like" # a pattern the caller supplies: infix is the safe reading
184
+
185
+
186
+ def classify(c, rd, info, single) -> list[dict]:
187
+ """The filters one conjunct puts on this read's table: [{column, op, expr}]. `expr` is the indexed expression when it
188
+ is not the bare column (mapKeys(m), mapValues(m)). Ops: eq, in, range, like_prefix, like_infix, like, token, has,
189
+ map_key, map_value."""
190
+ c = _strip(c)
191
+ if not Q._own(c, rd.select):
192
+ return []
193
+ out = []
194
+ if isinstance(c, exp.Or):
195
+ cols, ok = set(), True
196
+ for part in _or_parts(c):
197
+ part = _strip(part)
198
+ if isinstance(part, exp.EQ):
199
+ col = _col(part.this, rd, info, single) or _col(part.expression, rd, info, single)
200
+ other = part.expression if _col(part.this, rd, info, single) else part.this
201
+ if col and _no_table_columns([other], rd, info, single):
202
+ cols.add(col)
203
+ continue
204
+ ok = False
205
+ return [{"column": cols.pop(), "op": "in"}] if ok and len(cols) == 1 else []
206
+ if isinstance(c, (exp.EQ, exp.NullSafeEQ)):
207
+ for side, other in ((c.this, c.expression), (c.expression, c.this)):
208
+ if not _no_table_columns([other], rd, info, single):
209
+ continue
210
+ s = _strip(side)
211
+ col = _col(s, rd, info, single)
212
+ if col:
213
+ return [{"column": col, "op": "eq"}]
214
+ if isinstance(s, exp.Bracket) and isinstance(_strip(s.this), exp.Column):
215
+ m = _col(s.this, rd, info, single)
216
+ if m and re.match(r"(?:Nullable\()?Map\(", info.columns.get(m, "")):
217
+ return [{"column": m, "op": "map_key", "expr": f"mapKeys({m})"}, {"column": m, "op": "map_value", "expr": f"mapValues({m})"}]
218
+ col, funcs = _bare_chain(s, rd, info, single)
219
+ if col and funcs and all(f in KEY_SAFE for f in funcs):
220
+ return [{"column": col, "op": "range"}]
221
+ return []
222
+ if isinstance(c, exp.In):
223
+ col = _col(c.this, rd, info, single)
224
+ if col and _no_table_columns(list(c.args.get("expressions") or []), rd, info, single):
225
+ return [{"column": col, "op": "in"}]
226
+ return []
227
+ if isinstance(c, (exp.GT, exp.GTE, exp.LT, exp.LTE, exp.Between)):
228
+ sides = [c.this] if isinstance(c, exp.Between) else [c.this, c.expression]
229
+ others = [c.args.get("low"), c.args.get("high")] if isinstance(c, exp.Between) else None
230
+ for i, side in enumerate(sides):
231
+ rest = others if others is not None else [sides[1 - i]]
232
+ if not _no_table_columns(rest, rd, info, single):
233
+ continue
234
+ s = _strip(side)
235
+ col = _col(s, rd, info, single)
236
+ if col:
237
+ return [{"column": col, "op": "range"}]
238
+ col, funcs = _bare_chain(s, rd, info, single)
239
+ if col and funcs and all(f in KEY_SAFE for f in funcs):
240
+ return [{"column": col, "op": "range"}]
241
+ if isinstance(s, (exp.Anonymous, exp.StrPosition)) and Q.fname(s, ENGINE) in ("position", "strpos", "locate") and isinstance(c, exp.GT):
242
+ args = list(s.iter_expressions())
243
+ col = _col(args[0], rd, info, single) if args else None
244
+ if col:
245
+ return [{"column": col, "op": "like_infix"}]
246
+ return []
247
+ if isinstance(c, exp.Like):
248
+ col = _col(c.this, rd, info, single)
249
+ if col and _no_table_columns([c.expression], rd, info, single):
250
+ return [{"column": col, "op": _like_kind(c.expression)}]
251
+ return []
252
+ if isinstance(c, exp.ArrayContains):
253
+ col = _col(c.this, rd, info, single)
254
+ if col and _no_table_columns([c.expression], rd, info, single):
255
+ return [_has_filter(col, info)]
256
+ return []
257
+ if isinstance(c, (exp.Anonymous, exp.Func)):
258
+ name = Q.fname(c, ENGINE)
259
+ args = list(c.expressions) if isinstance(c, exp.Anonymous) else list(c.iter_expressions())
260
+ if not args:
261
+ return []
262
+ col = _col(args[0], rd, info, single)
263
+ if not col or not _no_table_columns(args[1:], rd, info, single):
264
+ return []
265
+ if name in TOKEN_FUNCS:
266
+ out.append({"column": col, "op": "token"})
267
+ elif name in HAS_FUNCS:
268
+ out.append(_has_filter(col, info))
269
+ elif name == "mapcontains":
270
+ out.append({"column": col, "op": "map_key", "expr": f"mapKeys({col})"})
271
+ elif name == "startswith":
272
+ out.append({"column": col, "op": "like_prefix"})
273
+ elif name in ("endswith", "multisearchany"):
274
+ out.append({"column": col, "op": "like_infix"})
275
+ return out
276
+
277
+
278
+ MAP_TYPE = re.compile(r"^\s*(?:Nullable\(|LowCardinality\()?Map\(")
279
+
280
+
281
+ def _has_filter(col: str, info) -> dict:
282
+ """has(col, x) / mapContains: on a Map column it looks up a key, and a bloom filter index on the bare Map column is
283
+ refused by the server ("Unexpected type Map(...) of bloom filter index"): it indexes mapKeys(col)."""
284
+ if MAP_TYPE.match(info.columns.get(col, "") or ""):
285
+ return {"column": col, "op": "map_key", "expr": f"mapKeys({col})"}
286
+ return {"column": col, "op": "has"}
287
+
288
+
289
+ def _or_parts(node) -> list:
290
+ node = _strip(node)
291
+ if isinstance(node, exp.Or):
292
+ return _or_parts(node.this) + _or_parts(node.expression)
293
+ return [node]
294
+
295
+
296
+ def _group_items(sel: exp.Select) -> list:
297
+ g = sel.args.get("group")
298
+ if g is None:
299
+ return []
300
+ aliases = {e.alias: e.this for e in sel.expressions if isinstance(e, exp.Alias) and e.alias}
301
+ out = []
302
+ for item in g.expressions:
303
+ if isinstance(item, exp.Column) and not item.table and item.name in aliases:
304
+ out.append(aliases[item.name])
305
+ else:
306
+ out.append(item)
307
+ return out
308
+
309
+
310
+ def shape_of(rd, info, single: bool) -> dict:
311
+ """What one read of `info` does: filters, group keys (with time buckets), order, columns read, aggregates, FINAL."""
312
+ sel = rd.select
313
+ filters, seen = [], set()
314
+ for clause, c in Q.filter_nodes(rd):
315
+ for f in classify(c, rd, info, single):
316
+ key = (f["column"], f["op"], f.get("expr"))
317
+ if key not in seen:
318
+ seen.add(key)
319
+ filters.append({**f, "clause": clause})
320
+ group, bucket_of = [], {}
321
+ for item in _group_items(sel):
322
+ item = _strip(item)
323
+ col = _col(item, rd, info, single)
324
+ if col:
325
+ group.append({"column": col})
326
+ continue
327
+ col, funcs = _bare_chain(item, rd, info, single)
328
+ if col and funcs and BUCKETS.match(funcs[0]):
329
+ group.append({"column": col, "bucket": funcs[0]})
330
+ bucket_of[col] = funcs[0]
331
+ else:
332
+ group.append({"column": None, "other": True})
333
+ order = []
334
+ o = sel.args.get("order")
335
+ for item in (o.expressions if o is not None else []):
336
+ col = _col(item.this if isinstance(item, exp.Ordered) else item, rd, info, single)
337
+ if col:
338
+ order.append(col)
339
+ cols, star = Q.selected_columns(sel, rd, info, single)
340
+ for clause in ("where", "prewhere", "group", "having", "order"):
341
+ node = sel.args.get(clause)
342
+ if node is not None:
343
+ cols |= Q.columns_in(node, rd, info, single)
344
+ if star:
345
+ cols |= set(info.columns)
346
+ aggs = []
347
+ for e_ in sel.expressions:
348
+ for f in e_.find_all(exp.AggFunc, exp.Anonymous, exp.Count, exp.Max, exp.Min, exp.Sum, exp.Avg):
349
+ if f.find_ancestor(exp.Select) is not sel or f.find_ancestor(exp.Window) is not None:
350
+ continue
351
+ n = Q.fname(f, ENGINE)
352
+ base = re.sub(r"(?:if|ornull|orzero|state|merge)+$", "", n) if n not in Q.AGG_NAMES else n
353
+ if n in Q.AGG_NAMES or base in Q.AGG_NAMES:
354
+ aggs.append({"function": n, "base": base, "columns": sorted(Q.columns_in(f, rd, info, single))})
355
+ lim = Q.limit_of(sel)
356
+ return {"filters": filters, "group_by": group, "order_by": order, "columns": sorted(cols), "star": star,
357
+ "aggregates": aggs, "aggregate": Q.is_aggregate(sel, ENGINE), "final": rd.final, "joined": rd.joined or bool(sel.args.get("joins")),
358
+ "limit": lim is not None, "distinct": bool(sel.args.get("distinct")),
359
+ "alias": rd.alias if rd.alias and rd.alias.lower() != rd.table.lower() else ""}
360
+
361
+
362
+ def key_service(filters: list[dict], key: list[str]) -> dict[str, str]:
363
+ """For each sorting-key column the read can use: `used` (the prefix rule: every earlier key column pinned with
364
+ equality or IN; a range ends the prefix)."""
365
+ pinned = {f["column"] for f in filters if f["op"] in ("eq", "in")}
366
+ ranged = {f["column"] for f in filters if f["op"] in ("range", "like_prefix")}
367
+ out = {}
368
+ for k in key:
369
+ if k in pinned:
370
+ out[k] = "used"
371
+ continue
372
+ if k in ranged:
373
+ out[k] = "used"
374
+ break
375
+ return out
376
+
377
+
378
+ def wanted_prefix(filters: list[dict], key: list[str]) -> list[str]:
379
+ """Equality and IN columns (in the order of the current key where they are in it, then by name), then one range
380
+ column: the key prefix that would serve every filter of the read that a key can serve."""
381
+ pos = {k: i for i, k in enumerate(key)}
382
+ eq = sorted({f["column"] for f in filters if f["op"] in ("eq", "in")}, key=lambda c: (pos.get(c, len(pos)), c))
383
+ rng = [f["column"] for f in filters if f["op"] in ("range", "like_prefix") and f["column"] not in eq]
384
+ rng = sorted(dict.fromkeys(rng), key=lambda c: (0 if c in pos else 1, pos.get(c, 0), c))
385
+ return eq + rng[:1]
386
+
387
+
388
+ def served_fraction(filters: list[dict], key: list[str]) -> float:
389
+ """The share of the columns a key could serve for this read (wanted_prefix) that this key uses: 1.0 served, 0.0 the
390
+ key does nothing for it. A statement with no such filter is 0."""
391
+ want = set(wanted_prefix(filters, key))
392
+ return len(want & set(key_service(filters, key))) / len(want) if want else 0.0
393
+
394
+
395
+ def served_by(filters: list[dict], key: list[str]) -> bool:
396
+ """Every filter column a key could serve is used by this key."""
397
+ want = set(wanted_prefix(filters, key))
398
+ return bool(want) and want <= set(key_service(filters, key))
399
+
400
+
401
+ # ---- the statements of each table -------------------------------------------------------------------------------
402
+
403
+ def _fold(stmts: list[dict]) -> list[dict]:
404
+ """A code statement whose call site production's statement is matched to (exact, template, tag) is that statement:
405
+ one use, with the measured load. Unmatched code statements stay, with no load."""
406
+ covered = defaultdict(list)
407
+ for st in stmts:
408
+ if st["sql_from"] == "query_log" and st["located"] in ("exact", "template", "tag"):
409
+ for sid in st["site_ids"]:
410
+ covered[sid].append(st["ref"])
411
+ out = []
412
+ for st in stmts:
413
+ if st["sql_from"] != "query_log" and st["site_ids"] and covered.get(st["site_ids"][0]):
414
+ continue
415
+ out.append(st)
416
+ return out
417
+
418
+
419
+ def _finding_maps(rank: dict | None, extra: list[dict] | None = None) -> tuple[dict, dict]:
420
+ by_hash, by_site = {}, {}
421
+ for c in list((rank or {}).get("candidates") or []) + list(extra or []):
422
+ o = c.get("observed") or {}
423
+ if o.get("hash"):
424
+ by_hash.setdefault(str(o["hash"]), c)
425
+ elif c.get("sql_from") != "query_log" and c.get("id"):
426
+ by_site.setdefault(str(c["id"]), c)
427
+ return by_hash, by_site
428
+
429
+
430
+ def finding_of(st: dict, by_hash: dict, by_site: dict) -> dict | None:
431
+ if st.get("hash") and str(st["hash"]) in by_hash:
432
+ return by_hash[str(st["hash"])]
433
+ if st["sql_from"] != "query_log":
434
+ return next((by_site[s] for s in st.get("site_ids") or [] if s in by_site), None)
435
+ return None
436
+
437
+
438
+ def existing_from_inventory(inventory: dict | None) -> dict[str, dict]:
439
+ """Skip indexes and projections the repository's DDL adds (CREATE TABLE ... INDEX, ALTER TABLE ... ADD INDEX /
440
+ PROJECTION): the inventory's table definitions do not carry them."""
441
+ out: dict[str, dict] = defaultdict(lambda: {"skip_indexes": [], "projections": []})
442
+ idx = re.compile(r"\bINDEX\s+(?:IF\s+NOT\s+EXISTS\s+)?[`\"]?(\w+)[`\"]?\s+(.+?)\s+TYPE\s+(\w+(?:\([^)]*\))?)(?:\s+GRANULARITY\s+(\d+))?", re.I | re.S)
443
+ proj = re.compile(r"\bPROJECTION\s+(?:IF\s+NOT\s+EXISTS\s+)?[`\"]?(\w+)[`\"]?\s*\(", re.I)
444
+ for s in (inventory or {}).get("call_sites") or []:
445
+ sql = s.get("sql") or ""
446
+ if s.get("statement") != "ddl" or not re.search(r"\b(?:INDEX|PROJECTION)\b", sql, re.I):
447
+ continue
448
+ m = re.search(r"\b(?:ALTER|CREATE)\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?([`\"\w.{}]+)", sql, re.I)
449
+ if not m:
450
+ continue
451
+ table = _short(m.group(1))
452
+ for x in idx.finditer(sql):
453
+ if re.match(r"\s*(?:DROP|MATERIALIZE|CLEAR)\b", sql[max(0, x.start() - 12):x.start()], re.I):
454
+ continue
455
+ out[table]["skip_indexes"].append({"name": x.group(1), "expr": x.group(2).strip(), "type": x.group(3), "granularity": x.group(4) or "1"})
456
+ for x in proj.finditer(sql):
457
+ out[table]["projections"].append({"name": x.group(1)})
458
+ return dict(out)
459
+
460
+
461
+ def _weight(st: dict) -> int:
462
+ return int((st.get("measured") or {}).get("read_bytes") or 0)
463
+
464
+
465
+ def collect(inventory: dict | None, facts=None, rank: dict | None = None, extra: list[dict] | None = None) -> tuple[dict, dict]:
466
+ """(tables, uses): TableInfo per table name; per table the uses (statement × read of that table) with their shape."""
467
+ stmts = _fold(all_statements(inventory, facts, ENGINE))
468
+ stmts = [s for s in stmts if s.get("engine") == ENGINE and s.get("role") not in ("migration", "script", "tooling")]
469
+ tables = Q.tables_from_inventory(inventory or {})
470
+ if facts:
471
+ tables.update(Q.tables_from_catalog(facts, ENGINE))
472
+ for t in (inventory or {}).get("tables") or []:
473
+ info = tables.get(str(t.get("name") or "").split(".")[-1].strip("`\""))
474
+ if info is not None and info.source == "inventory" and not info.create_sql and t.get("engine"):
475
+ # the inventory keeps the engine's arguments apart: a definition the engine rules and the re-key can read
476
+ cols = ", ".join(f"{c['name']} {c.get('type') or 'String'}" for c in t.get("columns") or [] if isinstance(c, dict) and c.get("name"))
477
+ args = " ".join(str(t.get("engine_args") or "").split())
478
+ info.create_sql = (f"CREATE TABLE {info.name} ({cols}) ENGINE = {t['engine']}({args})"
479
+ + (f" PARTITION BY {t['partition_by']}" if t.get("partition_by") else "")
480
+ + (f" ORDER BY {t['order_by']}" if t.get("order_by") else ""))
481
+ for name, ex in existing_from_inventory(inventory).items():
482
+ info = tables.get(name)
483
+ if info is not None and info.source != "real catalog":
484
+ info.skip_indexes = list(info.skip_indexes) + ex["skip_indexes"]
485
+ info.projections = list(info.projections) + ex["projections"]
486
+ by_hash, by_site = _finding_maps(rank, extra)
487
+ uses: dict[str, list[dict]] = defaultdict(list)
488
+ for st in stmts:
489
+ p = Q.parse(st["text"], ENGINE)
490
+ if not p.ok:
491
+ continue
492
+ rds = Q.reads(p.tree) + Q.cte_reads(p.tree)
493
+ per_select = defaultdict(int)
494
+ for r in rds:
495
+ per_select[id(r.select)] += 1
496
+ cand = finding_of(st, by_hash, by_site)
497
+ seen = set()
498
+ for rd in rds:
499
+ info = tables.get(rd.table) or tables.get(rd.table.lower()) or \
500
+ next((t for n, t in tables.items() if n.lower() == rd.table.lower()), None)
501
+ if info is None or not re.search(r"MergeTree", info.engine or "", re.I):
502
+ continue
503
+ shape = shape_of(rd, info, per_select[id(rd.select)] == 1)
504
+ key = (info.name, tuple((f["column"], f["op"]) for f in shape["filters"]), shape["final"], tuple(shape["columns"]))
505
+ if key in seen:
506
+ continue
507
+ seen.add(key)
508
+ uses[info.name].append({"ref": st["ref"], "sql_from": st["sql_from"], "located": st["located"], "hash": st.get("hash"),
509
+ "site_ids": st["site_ids"], "file": st.get("file"), "line": st.get("line"),
510
+ "finding": cand["finding"] if cand else None, "weight": _weight(st),
511
+ "measured": {k: v for k, v in (st.get("measured") or {}).items() if k in (
512
+ "executions", "read_bytes", "rows_read_per_run", "rows_returned_per_run", "selected_marks_per_run",
513
+ "selected_parts_per_run", "share_of_read_bytes", "window_hours", "no_result_share")},
514
+ "production_facts": _production_facts(st),
515
+ "dynamic": Q.dynamic_filter(rd) or p.dropped, "text": st["text"], "shape": shape})
516
+ return tables, dict(uses)
517
+
518
+
519
+ def _production_facts(st: dict) -> dict:
520
+ """The newer pull fields, read when present: pruning counters, columns read, projections used (realdb pull)."""
521
+ out = {}
522
+ m = st.get("measured") or {}
523
+ for k in ("pruning", "columns_read", "projections_used", "projections", "skip_index_marks", "index_marks"):
524
+ if m.get(k) is not None:
525
+ out[k] = m[k]
526
+ return out
527
+
528
+
529
+ # ---- locality: whether a skip index's sandbox verdict means anything ------------------------------------------------
530
+
531
+ LOCALITY_MEASURED = ("sorting_key", "time_parts", "profile_expression", "unique_values")
532
+ LOCALITY_WORDS = {
533
+ "sorting_key": "the column is in the sorting key: its values sit in granules the same way in the sandbox and in production",
534
+ "time_parts": "the sandbox cuts parts by this time column as rows written over time are",
535
+ "profile_expression": "the agent's profile writes the column as an expression of other columns: placed as described",
536
+ "unique_values": "each value is in a few rows only, so where it sits does not change what the index skips",
537
+ "catalog_only": "values and sizes from the catalog; placed at random in the sandbox: production's placement is not known",
538
+ "agent_values": "values from the agent's profile; placed at random in the sandbox: production's placement is not known",
539
+ "unknown": "the generator's default values, placed at random: production's placement is not known",
540
+ }
541
+
542
+
543
+ def column_profile(profile: dict | None, table: str, column: str) -> tuple[dict | None, dict | None]:
544
+ t = next((x for x in (profile or {}).get("tables") or [] if x.get("name") == table), None)
545
+ if t is None:
546
+ return None, None
547
+ return t, next((c for c in t.get("columns") or [] if c.get("name") == column), None)
548
+
549
+
550
+ def distinct_of(profile: dict | None, table: str, column: str, facts=None) -> int | None:
551
+ _, c = column_profile(profile, table, column)
552
+ if c:
553
+ if c.get("distinct"):
554
+ return int(c["distinct"])
555
+ if c.get("kind") == "categorical" and c.get("values"):
556
+ return len(c["values"])
557
+ if c.get("kind") == "constant":
558
+ return 1
559
+ if facts is not None:
560
+ try:
561
+ sampled = facts.sampled(ENGINE, table) or {}
562
+ except Exception: # a pull without samples
563
+ sampled = {}
564
+ col = (sampled.get("columns") or {}).get(column) if isinstance(sampled.get("columns"), dict) else None
565
+ if isinstance(col, dict) and col.get("distinct"):
566
+ return int(col["distinct"])
567
+ return None
568
+
569
+
570
+ def locality_basis(info, column: str, profile: dict | None, cfg: dict) -> str:
571
+ """On what basis the sandbox placed this column's values in granules (LOCALITY_WORDS)."""
572
+ if column in info.key_cols:
573
+ return "sorting_key"
574
+ t, c = column_profile(profile, info.name, column)
575
+ if column in info.partition_cols or (TIME_TYPE.search(info.columns.get(column, "")) and column in info.time_cols):
576
+ return "time_parts"
577
+ if c and c.get("kind") == "expr" and c.get("sql"):
578
+ return "profile_expression"
579
+ rows = int((t or {}).get("rows") or info.rows or 0)
580
+ if c and (c.get("kind") == "unique" or (c.get("distinct") and rows and rows / max(int(c["distinct"]), 1) <= cfg["unique_max_rows_per_value"])):
581
+ return "unique_values"
582
+ if t is None or c is None:
583
+ return "unknown"
584
+ if t.get("basis") == "catalog, no agent" or c.get("evidence") == "real catalog":
585
+ return "catalog_only"
586
+ return "agent_values"
587
+
588
+
589
+ _UNIT_HOURS = {"second": 1 / 3600, "minute": 1 / 60, "hour": 1, "day": 24, "week": 168, "month": 720, "year": 8760}
590
+
591
+
592
+ def window_hours(text: str) -> float | None:
593
+ """The widest time window a statement states as a literal (`INTERVAL 7 DAY`, `toIntervalHour(6)`, `subtractDays(now(),
594
+ 30)`), in hours; None when its bound is a parameter or there is none."""
595
+ found = []
596
+ for m in re.finditer(r"\bINTERVAL\s+'?(\d+)'?\s+(SECOND|MINUTE|HOUR|DAY|WEEK|MONTH|YEAR)S?\b", text or "", re.I):
597
+ found.append(int(m.group(1)) * _UNIT_HOURS[m.group(2).lower()])
598
+ for m in re.finditer(r"\b(?:toInterval|subtract|add)(Second|Minute|Hour|Day|Week|Month|Year)s?\s*\(\s*(?:[^(),]*\(\s*\)\s*,\s*)?(\d+)\s*\)",
599
+ text or "", re.I):
600
+ found.append(int(m.group(2)) * _UNIT_HOURS[m.group(1).lower()])
601
+ return round(max(found), 3) if found else None
602
+
603
+
604
+ def production_of(res: dict, cfg: dict) -> dict:
605
+ """One locality result (realdb/locality.py) as a suggestion carries it: status, ratio with its spread, floor, the
606
+ granules before and after, parts and rows counted, window, granule basis. Counts and ratios only."""
607
+ from .realdb import locality
608
+ out = {"status": res.get("status"), "statement_id": res.get("statement_id")}
609
+ if res.get("reason"):
610
+ out["reason"] = str(res["reason"])[:200]
611
+ read = locality.read(res, 3, float(cfg.get("bloom_fpr") or 0.01))
612
+ if read:
613
+ out.update({k: read[k] for k in ("ratio", "spread", "floor", "before", "after", "probes", "basis", "by_rank", "thresholds",
614
+ "parts_in_scope") if read.get(k) is not None})
615
+ for k in ("window_hours", "window_basis", "granule_basis", "estimate", "joined_by", "shared_with"):
616
+ if res.get(k) is not None:
617
+ out[k] = res[k]
618
+ if res.get("parts"):
619
+ out["counted_over"] = {k: res["parts"].get(k) for k in ("parts", "rows", "parts_in_scope", "rows_in_scope", "cut", "basis")}
620
+ if res.get("cost"):
621
+ out["cost"] = {k: v for k, v in res["cost"].items() if k in ("wall_s", "cpu_s_server", "cpu_s_upper_bound", "read_rows", "memory_bytes")}
622
+ return out
623
+
624
+
625
+ def attach_production(suggestions: list[dict], facts, cfg: dict, plans: list[dict] | None = None) -> None:
626
+ """Each suggestion counted on production by `codecop db pull --locality` (db_locality.json beside the pulled files)
627
+ carries that answer in engine_detail.production: matched by fingerprint, else by what was counted (the same
628
+ statement over the same table, columns, key prefixes and window: locality.count_key), for a suggestion whose DDL
629
+ changed where the count does not look (a projection's columns after its pinned prefix, a re-advise on a newer pull)."""
630
+ from .realdb import locality
631
+ out_dir = getattr(facts, "out_dir", None) if facts else None
632
+ got = locality.load(out_dir) if out_dir else None
633
+ found = locality.by_fingerprint(got)
634
+ by_count = locality.by_count_key(got)
635
+ if by_count and plans is not None and getattr(facts, "catalog", None):
636
+ from .realdb import PULL_DEFAULTS
637
+ missing = [s for s in suggestions if s["fingerprint"] not in found]
638
+ used = {k: v for k, v in PULL_DEFAULTS.items() if k.startswith("locality")}
639
+ used.update({k: v for k, v in (got.get("settings") or {}).items() if k in used}) # the pull's own window
640
+ reqs, _ = locality.requests({"tables": plans, "table_suggestions": missing}, facts.catalog, used)
641
+ for req in reqs:
642
+ r = by_count.get(locality.count_key(req))
643
+ if r is not None:
644
+ found[req["fingerprint"]] = {**r, "joined_by": "count_key"}
645
+ trials = {}
646
+ if out_dir:
647
+ import json
648
+ from pathlib import Path
649
+ p = Path(out_dir) / locality.TRIAL_FILE
650
+ try:
651
+ trials = (json.loads(p.read_text()).get("trials") or {}) if p.exists() else {}
652
+ except (OSError, ValueError):
653
+ trials = {}
654
+ for s in suggestions:
655
+ r = found.get(s["fingerprint"])
656
+ if r is not None:
657
+ s["engine_detail"]["production"] = production_of(r, cfg)
658
+ t = trials.get(s["fingerprint"])
659
+ if t is not None: # the user's trial on one partition (codecop apply --trial, then --trial-compare): counts only
660
+ s["engine_detail"]["production_trial"] = {k: t.get(k) for k in ("status", "reason", "ratio", "runs_trial", "runs_neighbour",
661
+ "window_hours") if t.get(k) is not None}
662
+
663
+
664
+ # ---- candidates -------------------------------------------------------------------------------------------------
665
+
666
+ INDEXABLE = {"eq", "in", "range", "like_prefix", "like_infix", "like", "token", "has", "map_key", "map_value"}
667
+
668
+
669
+ def index_type(info, f: dict, profile: dict | None, cfg: dict, version: str, facts=None) -> list[tuple[str, str]]:
670
+ """[(type, why)] for one filter, in order of preference (a text index is tried beside tokenbf_v1)."""
671
+ col, op = f["column"], f["op"]
672
+ ctype = info.columns.get(col, "")
673
+ if op == "range":
674
+ return [("minmax", "a range filter")]
675
+ if op in ("like_prefix", "like_infix", "like"):
676
+ if re.search(r"String", ctype):
677
+ return [(f"ngrambf_v1({cfg['ngram_size']}, {cfg['ngrambf_bytes']}, {cfg['ngrambf_hashes']}, 0)", "LIKE: n-grams of the pattern")]
678
+ return []
679
+ if op == "token":
680
+ out = [(f"tokenbf_v1({cfg['tokenbf_bytes']}, {cfg['tokenbf_hashes']}, 0)", "token search")]
681
+ if cfg["text_index"] and version and version_at_least(version, cfg["text_index_min_version"]):
682
+ out.append(("text(tokenizer = 'splitByNonAlpha')", "token search, the server's text index"))
683
+ return out
684
+ if op in ("has", "map_key", "map_value"):
685
+ if MAP_TYPE.match(ctype) and not (f.get("expr") or "").lower().startswith(("mapkeys(", "mapvalues(")):
686
+ return [] # the server builds no bloom filter on a bare Map column: only on mapKeys / mapValues of it
687
+ return [(f"bloom_filter({cfg['bloom_fpr']})", "array or map lookup")]
688
+ if MAP_TYPE.match(ctype) and not f.get("expr"):
689
+ return [] # eq / in on a whole Map column: no skip index type takes a Map
690
+ if op in ("eq", "in"):
691
+ n = distinct_of(None if profile is None else profile, info.name, col, facts)
692
+ if n is None and "LowCardinality" in ctype:
693
+ return [(f"set({cfg['set_lowcardinality_values']})", "few values (a LowCardinality column)")]
694
+ if n is not None and n <= cfg["set_max_distinct"]:
695
+ return [(f"set({max(1, min(n, int(cfg['set_max_values'])))})", f"few values ({n} distinct)")]
696
+ if NUMERIC.match(ctype) and n is None:
697
+ return [("minmax", "a number compared for equality")]
698
+ return [(f"bloom_filter({cfg['bloom_fpr']})", "many values" + (f" ({n} distinct)" if n else ""))]
699
+ return []
700
+
701
+
702
+ def _fp(*parts) -> str:
703
+ return hashlib.sha1("|".join(str(p) for p in parts).encode()).hexdigest()[:12]
704
+
705
+
706
+ def _idx_name(expr: str, typ: str) -> str:
707
+ return f"{PREFIX}_{re.sub(r'[^A-Za-z0-9]+', '_', expr).strip('_')[:40]}_{typ.split('(')[0]}"
708
+
709
+
710
+ def _existing_index(info, expr: str) -> dict | None:
711
+ norm = lambda s: re.sub(r"[\s`\"]", "", str(s or "")).lower() # noqa: E731
712
+ return next((i for i in info.skip_indexes if norm(i.get("expr")) == norm(expr)), None)
713
+
714
+
715
+ def _serves(use: dict, weight_total: int, measured_any: bool) -> dict:
716
+ return {"statement": use["ref"], "finding": use.get("finding"), "sql_from": use["sql_from"], "located": use["located"],
717
+ "file": use.get("file"), "line": use.get("line"), "site_ids": use.get("site_ids") or [],
718
+ "weight": use["weight"], "weight_share": round(use["weight"] / weight_total, 6) if weight_total else None,
719
+ "weight_basis": "measured" if measured_any else "static", "claimed": True}
720
+
721
+
722
+ def skip_index_candidates(info, uses: list[dict], profile, cfg, version, facts=None) -> list[dict]:
723
+ groups: dict[tuple, dict] = {}
724
+ for u in uses:
725
+ sh = u["shape"]
726
+ served = key_service(sh["filters"], info.sorting_key)
727
+ for f in sh["filters"]:
728
+ if f["op"] not in INDEXABLE or f["column"] in served:
729
+ continue
730
+ if f["column"] == (info.sorting_key or [None])[0]:
731
+ continue
732
+ expr = f.get("expr") or f["column"]
733
+ if _existing_index(info, expr):
734
+ continue
735
+ for typ, why in index_type(info, f, profile, cfg, version, facts):
736
+ g = groups.setdefault((expr, typ), {"expr": expr, "column": f["column"], "type": typ, "why": why, "ops": set(), "uses": []})
737
+ g["ops"].add(f["op"])
738
+ if u not in g["uses"]:
739
+ g["uses"].append(u)
740
+ out = []
741
+ for g in groups.values():
742
+ basis = locality_basis(info, g["column"], profile, cfg)
743
+ name = _idx_name(g["expr"], g["type"])
744
+ trials = [{"granularity": n, "ddl": [f"ALTER TABLE {info.name} ADD INDEX {name} {g['expr']} TYPE {g['type']} GRANULARITY {n}",
745
+ f"ALTER TABLE {info.name} MATERIALIZE INDEX {name}"]} for n in cfg["granularities"]]
746
+ out.append({"kind": "skip_index", "table": info.name, "uses": g["uses"], "ddl": trials[0]["ddl"], "trials": trials,
747
+ "engine_detail": {"index": name, "expr": g["expr"], "column": g["column"], "type": g["type"], "why": g["why"],
748
+ "operators": sorted(g["ops"]), "granularities": list(cfg["granularities"]),
749
+ "locality_basis": basis, "locality": LOCALITY_WORDS[basis],
750
+ "measurable": basis in LOCALITY_MEASURED}})
751
+ return out
752
+
753
+
754
+ def _rest_of_key(prefix: list[str], key: list[str]) -> list[str]:
755
+ return list(prefix) + [k for k in key if k not in prefix]
756
+
757
+
758
+ def projection_candidates(info, uses: list[dict], cfg) -> list[dict]:
759
+ """Projections ordered by a prefix the statements want and the key does not serve, holding only the columns the
760
+ statements they serve read. FINAL reads are left out: the engine does not use a projection under FINAL."""
761
+ by_prefix: dict[tuple, list[dict]] = defaultdict(list)
762
+ for u in uses:
763
+ sh = u["shape"]
764
+ if sh["final"] or not sh["filters"] or served_by(sh["filters"], info.sorting_key):
765
+ continue
766
+ pre = tuple(wanted_prefix(sh["filters"], info.sorting_key))
767
+ if not pre or list(pre) == info.sorting_key[:len(pre)]:
768
+ continue
769
+ by_prefix[pre].append(u)
770
+ # a statement whose prefix starts another's is served by the longer one too
771
+ merged: dict[tuple, list[dict]] = {}
772
+ for pre in sorted(by_prefix, key=lambda p: -len(p)):
773
+ host = next((m for m in merged if m[:len(pre)] == pre), None)
774
+ merged.setdefault(host or pre, []).extend(by_prefix[pre])
775
+ out = []
776
+ n_cols = max(len(info.columns), 1)
777
+ for pre, us in merged.items():
778
+ cols = sorted(set(pre) | {c for u in us for c in u["shape"]["columns"]})
779
+ full = len(cols) / n_cols > cfg["projection_max_columns_share"] or any(u["shape"]["star"] for u in us)
780
+ name = f"{PREFIX}_p_{_fp(info.name, pre)[:8]}"
781
+ body = f"SELECT {', '.join(cols) if not full else '*'} ORDER BY ({', '.join(pre)})"
782
+ out.append({"kind": "projection", "table": info.name, "uses": us,
783
+ "ddl": [f"ALTER TABLE {info.name} ADD PROJECTION {name} ({body})", f"ALTER TABLE {info.name} MATERIALIZE PROJECTION {name}"],
784
+ "engine_detail": {"projection": name, "order_by": list(pre), "columns": cols if not full else ["*"],
785
+ "columns_share": round(min(len(cols) / n_cols, 1.0), 3), "full_copy": full,
786
+ **({"needs_setting": "deduplicate_merge_projection_mode = 'rebuild'"} if info.deduplicating else {})}})
787
+ return out
788
+
789
+
790
+ def _clause_text(sql: str, start_kw: str, ends: tuple[str, ...]) -> str | None:
791
+ """The text of the outermost SELECT's clause starting at `start_kw`, up to the next of `ends` (top level only)."""
792
+ from .apply.clickhouse import mask_nested
793
+ masked = mask_nested(sql)
794
+ m = re.search(rf"\b{start_kw}\b", masked, re.I)
795
+ if not m:
796
+ return None
797
+ rest = masked[m.end():]
798
+ stop = min([x.start() for e in ends if (x := re.search(rf"\b{e}\b", rest, re.I))] + [len(rest)])
799
+ return sql[m.end():m.end() + stop].strip()
800
+
801
+
802
+ def _split(text: str) -> list[str]:
803
+ from .discover.schema import _split_top
804
+ return [p.strip() for p in _split_top(text or "") if p.strip()]
805
+
806
+
807
+ def _unalias(item: str) -> tuple[str, str | None]:
808
+ m = re.match(r"^(.*?)\s+AS\s+[`\"]?(\w+)[`\"]?\s*$", item, re.I | re.S)
809
+ return (m.group(1).strip(), m.group(2)) if m else (item.strip(), None)
810
+
811
+
812
+ def aggregating_candidates(info, uses: list[dict], cfg) -> list[dict]:
813
+ """GROUP BY (a time bucket, a few dimensions) over one table, no FINAL, no join, every filter on a group key, every
814
+ aggregate one a projection keeps: a projection that pre-aggregates, keyed by the same expressions. Load: measured
815
+ statements must run often and read far more rows than they return; code statements are claimed with no load."""
816
+ groups: dict[tuple, dict] = {}
817
+ allowed = set(cfg["agg_functions"])
818
+ for u in uses:
819
+ sh = u["shape"]
820
+ if not sh["aggregate"] or sh["final"] or sh["joined"] or sh["distinct"] or not sh["group_by"]:
821
+ continue
822
+ if not any(g.get("bucket") for g in sh["group_by"]):
823
+ continue
824
+ if not sh["aggregates"] or any(_agg_base(a["function"]) not in allowed for a in sh["aggregates"]):
825
+ continue
826
+ keys_raw = {g["column"] for g in sh["group_by"] if g.get("column") and not g.get("bucket")}
827
+ bucketed = {g["column"] for g in sh["group_by"] if g.get("bucket")}
828
+ # an equality filter's column becomes a key of the projection too (the engine aggregates its rows again);
829
+ # a range on the raw column of a time bucket can not be evaluated on the projection's rows
830
+ pinned = [f["column"] for f in sh["filters"] if f["op"] in ("eq", "in") and f["column"] not in keys_raw]
831
+ raw_time = sorted({f["column"] for f in sh["filters"] if f["op"] == "range" and f["column"] in bucketed and f["column"] not in keys_raw})
832
+ other = [f for f in sh["filters"] if f["column"] not in keys_raw and f["column"] not in pinned and f["column"] not in raw_time]
833
+ if other:
834
+ continue # a filter on a column the projection does not keep: the engine cannot use it
835
+ if len(keys_raw) + len(set(pinned)) > cfg["agg_max_dimensions"]:
836
+ continue
837
+ m = u.get("measured") or {}
838
+ if m:
839
+ rr, ret = float(m.get("rows_read_per_run") or 0), float(m.get("rows_returned_per_run") or 0)
840
+ hours = float(m.get("window_hours") or 0)
841
+ per_hour = int(m.get("executions") or 0) / hours if hours else None
842
+ if rr / max(ret, 1.0) < cfg["agg_min_ratio"] or (per_hour is not None and per_hour < cfg["agg_min_runs_per_hour"]):
843
+ continue
844
+ elif not cfg["agg_static"]:
845
+ continue
846
+ text = _query_text(u)
847
+ if text is None or re.search(r"\bARRAY\s+JOIN\b|\bJOIN\b", text, re.I):
848
+ continue
849
+ sel_items = [_unalias(x) for x in _split(_clause_text(text, "SELECT", ("FROM",)) or "")]
850
+ grp_items = _split(_clause_text(text, "GROUP BY", ("HAVING", "ORDER BY", "LIMIT", "SETTINGS", "WITH", "FORMAT", "UNION")) or "")
851
+ if sh.get("alias"):
852
+ strip = re.compile(rf"(?<![\w.]){re.escape(sh['alias'])}\.")
853
+ sel_items = [(strip.sub("", e), a) for e, a in sel_items]
854
+ grp_items = [strip.sub("", g) for g in grp_items]
855
+ alias = {a: e for e, a in sel_items if a}
856
+ keys = [alias.get(g, g) for g in grp_items]
857
+ aggs = [e for e, _ in sel_items if e not in keys and not any(e == alias.get(k) for k in grp_items)]
858
+ if not keys or not aggs or any(re.search(r"\?|\{\w*\s*[:}]|%\(|__qp|«|\$\d|:\w+", x) for x in keys + aggs):
859
+ continue
860
+ keys = list(dict.fromkeys(sorted(set(pinned)) + keys))
861
+ sig = (tuple(sorted(keys)), tuple(raw_time))
862
+ g = groups.setdefault(sig, {"keys": keys, "aggs": [], "uses": [], "raw_time": raw_time})
863
+ for a in aggs:
864
+ if a not in g["aggs"]:
865
+ g["aggs"].append(a)
866
+ g["uses"].append(u)
867
+ out = []
868
+ for g in groups.values():
869
+ name = f"{PREFIX}_agg_{_fp(info.name, *g['keys'])[:8]}"
870
+ body = f"SELECT {', '.join(g['keys'])}, {', '.join(g['aggs'])} GROUP BY {', '.join(g['keys'])}"
871
+ usable = not g["raw_time"]
872
+ out.append({"kind": "aggregating_projection", "table": info.name, "uses": g["uses"],
873
+ "ddl": [f"ALTER TABLE {info.name} ADD PROJECTION {name} ({body})", f"ALTER TABLE {info.name} MATERIALIZE PROJECTION {name}"],
874
+ "engine_detail": {"projection": name, "group_by": g["keys"], "aggregates": g["aggs"], "usable": usable,
875
+ **({} if usable else {"why_not_usable": "raw_time_range", "raw_time_columns": g["raw_time"],
876
+ "words": "the statements bound the raw time column, which the projection does not "
877
+ "keep: the engine can not use it until the bound is on the bucket (a "
878
+ "change to the statement, or a materialized view and a rewrite)"}),
879
+ "sameness": "the statement does not change; the engine chooses the projection and its result is the engine's",
880
+ **({"needs_setting": "deduplicate_merge_projection_mode = 'rebuild'"} if info.deduplicating else {})}})
881
+ return out
882
+
883
+
884
+ def _agg_base(name: str) -> str:
885
+ n = str(name or "").lower()
886
+ while True:
887
+ m = re.match(r"^(.+?)(if|ornull|orzero|ordefault|distinct)$", n)
888
+ if not m:
889
+ return n
890
+ n = m.group(1)
891
+
892
+
893
+ def _query_text(u: dict) -> str | None:
894
+ t = u.get("text") or ""
895
+ if not t or Q.parse(t, ENGINE).holes:
896
+ return None
897
+ return re.sub(r"\?\s*\.\.", "?", t)
898
+
899
+
900
+ def rekey_candidate(info, uses: list[dict], create_sql: str, cfg) -> dict | None:
901
+ """A new sorting key when the load-weighted majority of the table's statements want the same prefix. On a
902
+ deduplicating engine the new key is a permutation of the old one (the same rows collapse); the partition key stays."""
903
+ from .engines.clickhouse import plain_engine
904
+ if not info.sorting_key or not uses:
905
+ return None
906
+ measured = any(u["weight"] for u in uses)
907
+ if measured and sum(u["weight"] for u in uses) < cfg["rekey_min_read_bytes"]:
908
+ return None # a table read this little in the window does not pay for a copy of itself
909
+ w = (lambda u: u["weight"]) if measured else (lambda u: 1) # noqa: E731
910
+ total = sum(w(u) for u in uses) or 1
911
+
912
+ def share(key: list[str]) -> float:
913
+ return sum(w(u) * served_fraction(u["shape"]["filters"], key) for u in uses) / total
914
+
915
+ old = share(info.sorting_key)
916
+ options = []
917
+ for u in uses:
918
+ f = u["shape"]["filters"]
919
+ if not f or served_by(f, info.sorting_key):
920
+ continue
921
+ pre = wanted_prefix(f, info.sorting_key)
922
+ if not pre or (info.deduplicating and not set(pre) <= set(info.sorting_key)):
923
+ continue
924
+ key = _rest_of_key(pre, info.sorting_key)
925
+ if key != info.sorting_key and key not in options:
926
+ options.append(key)
927
+ if not options:
928
+ return None
929
+ best = max(options, key=lambda k: (share(k), -len(k)))
930
+ new = share(best)
931
+ if new < cfg["rekey_min_share"] or new - old < cfg["rekey_min_gain"]:
932
+ return None
933
+ gainers = [u for u in uses if served_fraction(u["shape"]["filters"], best) > served_fraction(u["shape"]["filters"], info.sorting_key)]
934
+ if not measured and len({u["ref"] for u in gainers}) < cfg["rekey_min_statements_static"]:
935
+ return None # with no measured load, a few statements are no majority of anything
936
+ m = Q.ENGINE_CLAUSE.search(plain_engine(create_sql or ""))
937
+ if not m:
938
+ return None
939
+ copy = f"{info.name}__codecop_variant"
940
+ part = f" PARTITION BY {info.partition_expr}" if info.partition_expr else ""
941
+ served = [u for u in uses if served_fraction(u["shape"]["filters"], best) > served_fraction(u["shape"]["filters"], info.sorting_key)]
942
+ return {"kind": "ordering_key", "table": info.name, "uses": served,
943
+ "ddl": [f"CREATE TABLE {copy} AS {info.name} ENGINE = {m.group(1)}{part} ORDER BY ({', '.join(best)})",
944
+ f"INSERT INTO {copy} SELECT * FROM {info.name}"],
945
+ "engine_detail": {"copy": copy, "old_key": list(info.sorting_key), "new_key": best, "served_share_old": round(old, 4),
946
+ "served_share_new": round(new, 4), "share_basis": "measured" if measured else "static (statements counted equally)",
947
+ "sandbox_engine": m.group(1), "dedup_identity_kept": set(best) == set(info.sorting_key)}}
948
+
949
+
950
+ # ---- FINAL / dedup on read --------------------------------------------------------------------------------------
951
+
952
+ def replacing_args(info) -> dict | None:
953
+ """ReplacingMergeTree's version and is_deleted columns, from the definition; None for another engine."""
954
+ from .engines.clickhouse import plain_engine
955
+ m = re.search(r"ReplacingMergeTree\s*(?:\(([^)]*)\))?", plain_engine(info.create_sql or "") or info.engine or "", re.I)
956
+ if not m or not re.search(r"Replacing", info.engine or "", re.I):
957
+ return None
958
+ args = [a.strip().strip("`\"") for a in (m.group(1) or "").split(",") if a.strip()]
959
+ return {"version": args[0] if args else None, "is_deleted": args[1] if len(args) > 1 else None}
960
+
961
+
962
+ def partition_aligned(info) -> bool:
963
+ """Every version of a sorting key is in one partition: the partition key is computed from sorting-key columns only
964
+ (or there is one partition). Then FINAL merging each partition alone keeps the same rows."""
965
+ if not info.partition_expr or info.partition_expr.strip().lower() in ("tuple()", ""):
966
+ return True
967
+ words = set(Q.WORD.findall(info.partition_expr))
968
+ cols = {w for w in words if w in info.columns}
969
+ return bool(cols) and cols <= set(info.sorting_key)
970
+
971
+
972
+ def _settings_added(sql: str, setting: str) -> str:
973
+ body = sql.rstrip().rstrip(";")
974
+ if re.search(r"\bSETTINGS\b(?![^(]*\))", body, re.I) and not re.search(r"\)\s*$", body):
975
+ return f"{body}, {setting}"
976
+ return f"{body} SETTINGS {setting}"
977
+
978
+
979
+ def _final_read(tree, info):
980
+ return [r for r in Q.reads(tree) if r.table.lower() == info.name.lower() and r.final]
981
+
982
+
983
+ def dedup_rewrite_limit_by(sql: str, info, form: str = "limit_by") -> tuple[str, str] | None:
984
+ """`t FINAL` replaced by the latest version of each row by the sorting key within its partition, which is what
985
+ FINAL keeps on a ReplacingMergeTree(ver) with no is_deleted: LIMIT 1 BY key, _partition_id ordered by ver DESC, or
986
+ argMax(col, ver) GROUP BY key, _partition_id. Sorting-key conjuncts (the same for every version) go inside."""
987
+ args = replacing_args(info)
988
+ if not args or not args["version"] or args["is_deleted"] or not info.sorting_key:
989
+ return None
990
+ p = Q.parse(sql, ENGINE)
991
+ if not p.ok or p.holes:
992
+ return None
993
+ rds = _final_read(p.tree, info)
994
+ if len(rds) != 1:
995
+ return None
996
+ rd = rds[0]
997
+ single = sum(1 for r in Q.reads(p.tree) if r.select is rd.select) == 1
998
+ used = set()
999
+ for e_ in rd.select.iter_expressions():
1000
+ used |= Q.columns_in(e_, rd, info, single)
1001
+ if any(isinstance(e_, exp.Star) for e_ in rd.select.expressions):
1002
+ used |= set(info.columns)
1003
+ for j in rd.select.args.get("joins") or []:
1004
+ used |= Q.columns_in(j, rd, info, single)
1005
+ if single:
1006
+ named = set()
1007
+ for e_ in rd.select.iter_expressions():
1008
+ named |= Q.columns_in(e_, rd, None, True)
1009
+ aliases = {e_.alias for e_ in rd.select.expressions if isinstance(e_, exp.Alias)}
1010
+ if named - set(info.columns) - aliases - {"_partition_id", "_part"}:
1011
+ return None # a column the definition does not show (added later by ALTER): the copy would lack it
1012
+ used = [c for c in info.columns if c in used]
1013
+ if not used:
1014
+ return None
1015
+ keys, _ = Q._key_conjuncts(rd, info, single, set(info.sorting_key))
1016
+ alias = rd.alias if rd.alias and rd.alias.lower() != rd.table.lower() else rd.table
1017
+ # the key conjuncts are copied as nodes (a parameter printed and parsed again would not survive), unqualified
1018
+ conds = []
1019
+ for k in keys:
1020
+ kk = k.copy()
1021
+ for c in kk.find_all(exp.Column):
1022
+ c.set("table", None)
1023
+ conds.append(kk)
1024
+ inner_where = " WHERE 1" if conds else ""
1025
+ key = ", ".join(info.sorting_key)
1026
+ ver = args["version"]
1027
+ if form == "limit_by":
1028
+ cols = ", ".join(dict.fromkeys(used + list(info.sorting_key)))
1029
+ inner = f"SELECT {cols} FROM {rd.table}{inner_where} ORDER BY {key}, {ver} DESC LIMIT 1 BY {key}, _partition_id"
1030
+ else:
1031
+ rest = [c for c in used if c not in info.sorting_key]
1032
+ if not rest:
1033
+ return None
1034
+ # one tuple per key: every column of the latest version together (no alias can shadow a column it reads)
1035
+ picked = ", ".join(f"codecop_latest.{i + 1} AS {c}" for i, c in enumerate(rest))
1036
+ inner = (f"SELECT {key}, {picked} FROM (SELECT {key}, argMax(tuple({', '.join(rest)}), {ver}) AS codecop_latest "
1037
+ f"FROM {rd.table}{inner_where} GROUP BY {key}, _partition_id)")
1038
+ parsed = Q.parse(inner, ENGINE)
1039
+ if not parsed.ok:
1040
+ return None
1041
+ if conds:
1042
+ target = next((x for x in parsed.tree.find_all(exp.Select) if x.args.get("where") is not None), None)
1043
+ if target is None:
1044
+ return None
1045
+ target.set("where", exp.Where(this=Q._and(conds)))
1046
+ node = exp.Subquery(this=parsed.tree, alias=exp.TableAlias(this=exp.to_identifier(alias)))
1047
+ src = rd.node.parent if isinstance(rd.node.parent, exp.Final) else rd.node
1048
+ src.replace(node)
1049
+ try:
1050
+ out = p.tree.sql(dialect="clickhouse")
1051
+ except Exception: # a tree sqlglot can not print back: no rewrite
1052
+ return None
1053
+ note = ("FINAL replaced by the latest version of each row: LIMIT 1 BY the sorting key and _partition_id, ordered by "
1054
+ f"{ver} descending") if form == "limit_by" else (f"FINAL replaced by argMax(column, {ver}) grouped by the sorting key "
1055
+ "and _partition_id")
1056
+ return out, note
1057
+
1058
+
1059
+ def push_into_final(sql: str, info) -> tuple[str, str] | None:
1060
+ """`SELECT ... FROM (SELECT ... FROM t FINAL ...) WHERE k = x`: an outer conjunct on a column the subquery passes
1061
+ through as a bare sorting-key column goes into the subquery's PREWHERE, before FINAL (the same for every version)."""
1062
+ p = Q.parse(sql, ENGINE)
1063
+ if not p.ok or p.holes:
1064
+ return None
1065
+ done = 0
1066
+ for rd in _final_read(p.tree, info):
1067
+ inner = rd.select
1068
+ sub = inner.parent
1069
+ if not isinstance(sub, exp.Subquery) or inner.args.get("group") or inner.args.get("limit") or inner.args.get("distinct") \
1070
+ or inner.find(exp.Window) or inner.args.get("joins") or inner.args.get("prewhere") is not None:
1071
+ continue
1072
+ outer = sub.find_ancestor(exp.Select)
1073
+ if outer is None or (outer.args.get("from") or outer.args.get("from_")) is None or outer.args.get("joins"):
1074
+ continue
1075
+ passthrough = {}
1076
+ for e_ in inner.expressions:
1077
+ target = e_.this if isinstance(e_, exp.Alias) else e_
1078
+ if isinstance(target, exp.Column) and target.name in info.sorting_key:
1079
+ passthrough[e_.alias_or_name] = target.name
1080
+ moved = []
1081
+ for c in Q.conjuncts(outer.args.get("where")):
1082
+ cols = list(c.find_all(exp.Column))
1083
+ if cols and all(x.name in passthrough for x in cols) and c.find(exp.Select) is None and not Q.has_hole(c):
1084
+ cc = c.copy()
1085
+ for x in cc.find_all(exp.Column):
1086
+ x.replace(exp.column(passthrough[x.name]))
1087
+ moved.append(cc)
1088
+ if moved:
1089
+ inner.set("prewhere", exp.PreWhere(this=Q._and(moved)))
1090
+ done += 1
1091
+ if not done:
1092
+ return None
1093
+ return p.tree.sql(dialect="clickhouse"), "outer filters on sorting-key columns moved into the FINAL subquery's PREWHERE"
1094
+
1095
+
1096
+ def drop_final(sql: str, info, cfg) -> tuple[str, str] | None:
1097
+ """FINAL removed where duplicates cannot change the result: every column the read uses is a sorting-key column,
1098
+ and the select is an aggregate of duplicate-insensitive functions or DISTINCT over them. No is_deleted (FINAL would
1099
+ drop deleted rows)."""
1100
+ args = replacing_args(info)
1101
+ if not args or args["is_deleted"]:
1102
+ return None
1103
+ p = Q.parse(sql, ENGINE)
1104
+ if not p.ok or p.holes:
1105
+ return None
1106
+ rds = _final_read(p.tree, info)
1107
+ if len(rds) != 1 or rds[0].joined or rds[0].select.args.get("joins"):
1108
+ return None
1109
+ rd = rds[0]
1110
+ sel = rd.select
1111
+ keyset = set(info.sorting_key)
1112
+ used = set()
1113
+ for e_ in sel.iter_expressions():
1114
+ used |= Q.columns_in(e_, rd, info, True)
1115
+ if not used or not used <= keyset or any(isinstance(e_, exp.Star) for e_ in sel.expressions):
1116
+ return None
1117
+ allowed = set(cfg["duplicate_insensitive"])
1118
+ aggs = []
1119
+ for e_ in sel.expressions:
1120
+ for f in e_.find_all(exp.AggFunc, exp.Anonymous, exp.Count, exp.Max, exp.Min):
1121
+ if f.find_ancestor(exp.Select) is sel:
1122
+ aggs.append(f)
1123
+ if aggs:
1124
+ for f in aggs:
1125
+ n = Q.fname(f, ENGINE)
1126
+ if isinstance(f, exp.Count) and isinstance(f.this, exp.Distinct):
1127
+ continue
1128
+ if n not in allowed:
1129
+ return None
1130
+ others = [e_ for e_ in sel.expressions if not list(e_.find_all(exp.AggFunc, exp.Anonymous, exp.Count, exp.Max, exp.Min))]
1131
+ group = {x.sql() for x in (sel.args.get("group").expressions if sel.args.get("group") else [])}
1132
+ if any(o.sql() not in group and (o.this.sql() if isinstance(o, exp.Alias) else o.sql()) not in group and
1133
+ not (isinstance(o, exp.Alias) and o.alias in {g for g in group}) for o in others):
1134
+ return None
1135
+ elif not (sel.args.get("distinct") or sel.args.get("group")):
1136
+ return None
1137
+ node = rd.node
1138
+ if isinstance(node.parent, exp.Final):
1139
+ node.parent.replace(node.copy())
1140
+ else:
1141
+ node.set("final", None)
1142
+ return p.tree.sql(dialect="clickhouse"), "FINAL dropped: only sorting-key columns are read, under DISTINCT or aggregates duplicates cannot change"
1143
+
1144
+
1145
+ def final_candidates(info, uses: list[dict], cfg) -> list[dict]:
1146
+ args = replacing_args(info)
1147
+ if not cfg["final_rules"] or not args:
1148
+ return []
1149
+ out = []
1150
+ # the statements production ran (or that a candidate runs), heaviest first: each rule is one benchmark
1151
+ measured = any(u["weight"] for u in uses)
1152
+ picked = sorted([u for u in uses if u["shape"]["final"] and (u["weight"] or u.get("finding") or not measured)], key=lambda u: -u["weight"])
1153
+ for u in picked[:int(cfg["max_dedup_statements"])]:
1154
+ text = _query_text(u)
1155
+ if text is None:
1156
+ continue
1157
+ tries = []
1158
+ got = Q.prewhere_keys(text, ENGINE, info)
1159
+ if got:
1160
+ tries.append(("prewhere_keys", got))
1161
+ got = push_into_final(text, info)
1162
+ if got:
1163
+ tries.append(("filter_into_final", got))
1164
+ if partition_aligned(info) and info.partition_expr:
1165
+ tries.append(("per_partition_final", (_settings_added(text, "do_not_merge_across_partitions_select_final = 1"),
1166
+ "FINAL merges each partition alone: the partition key is computed from sorting-key "
1167
+ "columns, so every version of a row is in one partition")))
1168
+ for form in ("limit_by", "argmax"):
1169
+ got = dedup_rewrite_limit_by(text, info, form)
1170
+ if got:
1171
+ tries.append((form if form == "argmax" else "limit_1_by", got))
1172
+ got = drop_final(text, info, cfg)
1173
+ if got:
1174
+ tries.append(("drop_final", got))
1175
+ for rule, (sql, note) in tries:
1176
+ out.append({"kind": "dedup_on_read", "table": info.name, "uses": [u], "ddl": [], "rewrite_sql": sql,
1177
+ "engine_detail": {"rule": rule, "note": note, "version_column": args["version"],
1178
+ "partition_aligned": partition_aligned(info)}})
1179
+ return out
1180
+
1181
+
1182
+ # ---- the plan per table --------------------------------------------------------------------------------------------
1183
+
1184
+ def _definition(name: str, rank: dict | None, facts) -> str:
1185
+ for d in (rank or {}).get("table_definitions") or []:
1186
+ if _short(d["name"]).lower() == name.lower():
1187
+ return d.get("create_sql") or ""
1188
+ d = facts.definition(ENGINE, name) if facts else None
1189
+ return (d or {}).get("create_sql") or ""
1190
+
1191
+
1192
+ def _version(rank: dict | None, facts) -> str:
1193
+ v = (rank or {}).get("engine_version") or ""
1194
+ if not v and facts:
1195
+ v = next((c.get("version") for c in (facts.catalog.get("connections") or {}).values() if c.get("engine") == ENGINE), "") or ""
1196
+ return str(v)
1197
+
1198
+
1199
+ def detect(inventory: dict | None, facts=None, rank: dict | None = None, profile: dict | None = None, settings: dict | None = None,
1200
+ extra: list[dict] | None = None, previous: dict | None = None) -> dict:
1201
+ """advisor.json without measurements: per table its uses and its candidates as table suggestions. `previous`: the
1202
+ earlier document of the out dir, whose suggestion ids are kept (keep_ids)."""
1203
+ cfg = settings_of(settings)
1204
+ tables, uses = collect(inventory, facts, rank, extra)
1205
+ version = _version(rank, facts)
1206
+ plans, suggestions = [], []
1207
+ order = sorted(uses, key=lambda t: (-sum(u["weight"] for u in uses[t]), t))[:int(cfg["max_tables"])]
1208
+ for name in order:
1209
+ info = tables[name]
1210
+ us = uses[name]
1211
+ if not info.create_sql:
1212
+ info.create_sql = _definition(name, rank, facts)
1213
+ total = sum(u["weight"] for u in us)
1214
+ measured_any = total > 0
1215
+ cands = skip_index_candidates(info, us, profile, cfg, version, facts) + projection_candidates(info, us, cfg) + \
1216
+ aggregating_candidates(info, us, cfg)
1217
+ rk = rekey_candidate(info, us, info.create_sql or _definition(name, rank, facts), cfg)
1218
+ if rk:
1219
+ cands.append(rk)
1220
+ cands += final_candidates(info, us, cfg)
1221
+
1222
+ def served_weight(c):
1223
+ return sum(u["weight"] for u in c["uses"]) if measured_any else len(c["uses"])
1224
+ table_level = sorted([c for c in cands if c["kind"] in TABLE_KINDS], key=lambda c: (-served_weight(c), KINDS.index(c["kind"])))
1225
+ kept = table_level[:int(cfg["max_candidates_per_table"])]
1226
+ dropped = len(table_level) - len(kept)
1227
+ kept += [c for c in cands if c["kind"] == "dedup_on_read"]
1228
+ for c in kept:
1229
+ sid = _fp(c["kind"], name, *c["ddl"], c.get("rewrite_sql") or "")
1230
+ serves = [_serves(u, total, measured_any) for u in c["uses"]]
1231
+ weight = sum(u["weight"] for u in c["uses"])
1232
+ suggestions.append({
1233
+ "id": None, "fingerprint": sid, "engine": ENGINE, "kind": c["kind"], "table": name, "ddl": c["ddl"],
1234
+ "serves": serves, "read_gain": {"basis": "claimed", "load_share": round(weight / total, 6) if total else None,
1235
+ "load_share_basis": "measured" if measured_any else "static",
1236
+ "statements": len(serves)},
1237
+ "write_cost": {"measured": False, "reason": "bench_not_run"} if c["kind"] in TABLE_KINDS else None,
1238
+ "size": None, "verdict": "claimed", "basis": "rule",
1239
+ "engine_detail": {**c["engine_detail"], **({"rewrite_sql": c["rewrite_sql"]} if c.get("rewrite_sql") else {}),
1240
+ **({"trials": c["trials"]} if c.get("trials") else {})},
1241
+ "outcome": None})
1242
+ plans.append({
1243
+ "table": name, "engine": info.engine, "source": info.source, "rows": info.rows, "sorting_key": info.sorting_key,
1244
+ "partition_key": info.partition_expr, "skip_indexes": [{k: i.get(k) for k in ("name", "type", "expr", "granularity")} for i in info.skip_indexes],
1245
+ "projections": [{"name": p.get("name")} for p in info.projections], "read_bytes": total, "load_basis": "measured" if measured_any else "static",
1246
+ "statements": [{"ref": u["ref"], "finding": u.get("finding"), "sql_from": u["sql_from"], "located": u["located"], "file": u.get("file"),
1247
+ "line": u.get("line"), "weight": u["weight"], "measured": u["measured"], "dynamic": u["dynamic"],
1248
+ **({"time_window_hours": w} if (w := window_hours(u.get("text") or "")) else {}),
1249
+ **({"production_facts": u["production_facts"]} if u["production_facts"] else {}),
1250
+ "filters": [{k: f[k] for k in ("column", "op", "expr") if f.get(k)} for f in u["shape"]["filters"]],
1251
+ "group_by": u["shape"]["group_by"], "order_by": u["shape"]["order_by"], "final": u["shape"]["final"],
1252
+ "columns": len(u["shape"]["columns"]), "key_used": sorted(key_service(u["shape"]["filters"], info.sorting_key)),
1253
+ "wanted_prefix": wanted_prefix(u["shape"]["filters"], info.sorting_key)} for u in us],
1254
+ "candidates_dropped_over_cap": dropped})
1255
+ suggestions.sort(key=lambda s: (-(s["read_gain"]["load_share"] or 0), KINDS.index(s["kind"]), s["table"], s["fingerprint"]))
1256
+ registry = keep_ids(suggestions, previous)
1257
+ attach_production(suggestions, facts, cfg, plans)
1258
+ return {"schema_version": SCHEMA_VERSION, "generated_at": datetime.now(timezone.utc).isoformat(timespec="seconds"), "engine": ENGINE,
1259
+ "engine_version": version, "settings": cfg, "tables": plans, "table_suggestions": suggestions, "summary": summarize(plans, suggestions),
1260
+ "id_registry": registry}
1261
+
1262
+
1263
+ def keep_ids(suggestions: list[dict], previous: dict | None) -> dict:
1264
+ """Each suggestion's id (TS-001...), kept across `codecop advise` runs in the same out dir: a suggestion whose
1265
+ fingerprint (its kind, table, DDL and rewrite) an earlier document gave an id keeps it; a new one gets the next
1266
+ number never given. Ids were positions in the load order, so a pull that added statements renumbered every
1267
+ suggestion and the ids a locality pull printed named other suggestions after it. Results join by fingerprint either
1268
+ way (db_locality.json, bench records). Returns the registry (fingerprint -> id) that advisor.json keeps."""
1269
+ reg: dict[str, str] = {}
1270
+ for fp, sid in ((previous or {}).get("id_registry") or {}).items():
1271
+ if isinstance(fp, str) and isinstance(sid, str):
1272
+ reg[fp] = sid
1273
+ for s in (previous or {}).get("table_suggestions") or []:
1274
+ if s.get("fingerprint") and s.get("id"):
1275
+ reg.setdefault(s["fingerprint"], s["id"])
1276
+ taken = {sid for sid in reg.values()}
1277
+ n = max((int(m.group(1)) for sid in taken if (m := re.fullmatch(r"TS-(\d+)", sid))), default=0)
1278
+ for s in suggestions:
1279
+ if s["fingerprint"] in reg:
1280
+ s["id"] = reg[s["fingerprint"]]
1281
+ continue
1282
+ n += 1
1283
+ s["id"] = reg[s["fingerprint"]] = f"TS-{n:03d}"
1284
+ return reg
1285
+
1286
+
1287
+ def summarize(plans: list[dict], suggestions: list[dict]) -> dict:
1288
+ by_kind = {k: sum(1 for s in suggestions if s["kind"] == k) for k in KINDS}
1289
+ verdicts: dict[str, int] = defaultdict(int)
1290
+ states: dict[str, int] = defaultdict(int)
1291
+ for s in suggestions:
1292
+ verdicts[s["verdict"]] += 1
1293
+ if s.get("outcome"):
1294
+ states[s["outcome"]["state"]] += 1
1295
+ return {"tables": len(plans), "statements": sum(len(p["statements"]) for p in plans), "suggestions": len(suggestions),
1296
+ "by_kind": by_kind, "by_verdict": dict(verdicts), "states": dict(states)}
1297
+
1298
+
1299
+ # ---- the statements the benchmark runs --------------------------------------------------------------------------
1300
+
1301
+ def bind(doc: dict, inventory: dict | None, facts, rank: dict | None, extra: list[dict] | None, dynamic: dict | None = None,
1302
+ previous: dict | None = None, settings: dict | None = None) -> dict:
1303
+ """Every measured statement of a planned table that no ranked, observed or scenario candidate runs gets a runnable
1304
+ form built from production's text (scenario_bind.runnable: the observed stage's fill, gate and values), `AB-001`...
1305
+ Its id is kept across runs (`previous`). Fills `finding` on the statements and on `serves[]`. `doc["runnable"]`."""
1306
+ from . import scenario_bind
1307
+ from .observed import settings_of as dyn_settings
1308
+ cfg = settings_of(settings or doc.get("settings"))
1309
+ ids = {str((r.get("observed") or {}).get("hash")): r["finding"] for r in (previous or {}).get("runnable") or []}
1310
+ used = set(ids.values()) | {c.get("finding") for c in list((rank or {}).get("candidates") or []) + list(extra or [])}
1311
+ built, failed = {}, {}
1312
+ wanted = {sv["statement"] for s in doc["table_suggestions"] for sv in s["serves"]}
1313
+ n = 0
1314
+ dyn = dyn_settings(dynamic)
1315
+ for plan in sorted(doc["tables"], key=lambda p: -p["read_bytes"]):
1316
+ if not facts or not any(s["table"] == plan["table"] for s in doc["table_suggestions"]):
1317
+ continue
1318
+ for st in sorted(plan["statements"], key=lambda s: -s["weight"]):
1319
+ if st.get("finding") or st["sql_from"] != "query_log":
1320
+ continue
1321
+ h = st["ref"].split(":", 1)[1]
1322
+ if h in built:
1323
+ st["finding"] = built[h]["finding"]
1324
+ continue
1325
+ if h in failed or len(built) >= int(cfg["max_runnable"]) or (st["ref"] not in wanted and not st["weight"]):
1326
+ if h in failed:
1327
+ st["why_not_runnable"] = failed[h]
1328
+ continue
1329
+ finding = ids.get(h)
1330
+ if finding is None:
1331
+ n += 1
1332
+ while f"AB-{n:03d}" in used:
1333
+ n += 1
1334
+ finding = f"AB-{n:03d}"
1335
+ used.add(finding)
1336
+ cand, why = scenario_bind.runnable({"hash": h, "site_ids": st.get("site_ids") or [], "located": st["located"]},
1337
+ facts, inventory, ENGINE, finding, dyn)
1338
+ if cand is None:
1339
+ failed[h] = why
1340
+ st["why_not_runnable"] = why
1341
+ continue
1342
+ cand["built_for"] = "advisor"
1343
+ cand["title"] = cand["title"].replace("(built for a scenario)", "(built for the access-path advisor)")
1344
+ built[h] = cand
1345
+ st["finding"] = finding
1346
+ findings_of = {p["table"]: {st["ref"]: st.get("finding") for st in p["statements"]} for p in doc["tables"]}
1347
+ for s in doc["table_suggestions"]:
1348
+ for sv in s["serves"]:
1349
+ sv["finding"] = findings_of.get(s["table"], {}).get(sv["statement"]) or sv.get("finding")
1350
+ doc["runnable"] = list(built.values())
1351
+ doc["summary"]["runnable_built"] = len(built)
1352
+ reasons: dict[str, int] = defaultdict(int)
1353
+ for x in failed.values():
1354
+ reasons[x] += 1
1355
+ doc["summary"]["not_runnable"] = dict(reasons)
1356
+ return doc
1357
+
1358
+
1359
+ # ---- proof on the sandbox ---------------------------------------------------------------------------------------
1360
+
1361
+ def _nums(m) -> dict:
1362
+ return {"ok": m.ok, **{k: getattr(m, k) for k in ("read_rows", "read_bytes", "result_rows", "selected_parts", "selected_marks",
1363
+ "duration_ms", "memory_bytes")}, **({"error": m.error[:300]} if m.error else {})}
1364
+
1365
+
1366
+ def projections_used(sb, sql: str, params: dict) -> list[str] | None:
1367
+ """The projections the server chose for one run of the statement (system.query_log.projections)."""
1368
+ import uuid
1369
+ from .engines.base import QueryError
1370
+ qid = f"codecop-adv-{uuid.uuid4().hex[:12]}"
1371
+ try:
1372
+ sb._http(sb.frozen(sql.strip().rstrip(";")) + " FORMAT Null", params,
1373
+ {"query_id": qid, "log_queries": 1, "use_query_cache": 0, **getattr(sb, "query_limits", {})})
1374
+ sb._http("SYSTEM FLUSH LOGS")
1375
+ rows = sb.rows("SELECT projections FROM system.query_log WHERE type = 'QueryFinish' AND query_id = {q:String}", {"q": qid})
1376
+ except QueryError:
1377
+ return None
1378
+ return [str(p).split(".")[-1] for p in (rows[0].get("projections") or [])] if rows else None
1379
+
1380
+
1381
+ def _params(cand: dict, profile: dict) -> tuple[dict, dict | None]:
1382
+ from . import fidelity
1383
+ typical = fidelity.params_of(cand, profile)
1384
+ heavy = ((profile or {}).get("param_overrides") or {}).get(cand["finding"] + fidelity.HEAVY)
1385
+ return typical, ({**typical, **heavy} if heavy else None)
1386
+
1387
+
1388
+ def _judge(sb, base, var, variant: dict, pending: dict, compare) -> tuple[str, str, bool | None, str]:
1389
+ from . import bench as B
1390
+ match, compared = compare.settle(variant, var, pending)
1391
+ why = compared.removeprefix("not compared: ") if match is None else ""
1392
+ v, r = B.verdict(base, var, True, compare.rows_only, sb.floor_bytes, sb.floor_rows, match=match, why=why)
1393
+ return v, r, (match if var.ok else None), compared
1394
+
1395
+
1396
+ def measure_statements(sb, stmts: list[dict], cands: dict, runs: int, sql_for, setup: list[str] | None, base: dict,
1397
+ check_projection: str | None = None, check_index: str | None = None, serving: set | None = None):
1398
+ """Every statement in `stmts` measured with the candidate in place (the caller applies and undoes its setup around
1399
+ this call; a rewrite has none): the typical run, the heavy run when there is one. Returns (records, pending): the
1400
+ comparisons are settled by `settle_all` once the setup is undone (bench.Comparison's two steps)."""
1401
+ from . import bench as B
1402
+ out, later = [], []
1403
+ for st in stmts:
1404
+ cand = cands[st["finding"]]
1405
+ b = base.get(st["finding"])
1406
+ if b is None or not b["typical"].ok:
1407
+ continue
1408
+ serves = st["ref"] in (serving or set())
1409
+ rec = {"finding": st["finding"], "statement": st["ref"], "serves": serves, "weight": st["weight"]}
1410
+ sql = sql_for(cand)
1411
+ if not sql:
1412
+ out.append({**rec, "skipped": "rule_not_applicable_to_runnable_form"})
1413
+ continue
1414
+ variant = {"sql": sql, "same_results": True, "setup_sql": setup or []}
1415
+ tm = sb.measure(sql, b["params"], runs if serves else 1)
1416
+ cmp_t = B.Comparison(sb, cand, b["typical"], b["params"])
1417
+ pend_t = cmp_t.with_setup(variant, tm)
1418
+ hm = cmp_h = pend_h = None
1419
+ if b.get("heavy") is not None and b["heavy"].ok:
1420
+ hm = sb.measure(sql, b["heavy_params"], 1)
1421
+ cmp_h = B.Comparison(sb, cand, b["heavy"], b["heavy_params"])
1422
+ pend_h = cmp_h.with_setup(variant, hm)
1423
+ if check_projection and serves:
1424
+ used = projections_used(sb, sql, b["params"])
1425
+ rec["engine_used"] = None if used is None else check_projection in used
1426
+ rec["projections_used"] = used
1427
+ if check_index and serves and tm.ok:
1428
+ rec["engine_used"] = check_index in (tm.explain or "")
1429
+ later.append((rec, b, tm, variant, pend_t, cmp_t, hm, pend_h, cmp_h))
1430
+ out.append(rec)
1431
+ return out, later
1432
+
1433
+
1434
+ def settle_all(sb, later: list) -> None:
1435
+ from . import bench as B
1436
+ for rec, b, tm, variant, pend_t, cmp_t, hm, pend_h, cmp_h in later:
1437
+ tv, tr, tmatch, tcmp = _judge(sb, b["typical"], tm, variant, pend_t, cmp_t)
1438
+ rec["typical"] = {"before": _nums(b["typical"]), "after": _nums(tm), "verdict": tv, "reason": tr, "results_match": tmatch, "compared": tcmp}
1439
+ if hm is not None:
1440
+ hv, hr, hmatch, hcmp = _judge(sb, b["heavy"], hm, variant, pend_h, cmp_h)
1441
+ if b["typical"].result_rows == 0 and hmatch is True and tmatch is not False and tm.ok:
1442
+ # the typical run returns nothing, as production's does: its sameness is shown on the heavy run
1443
+ tv, tr = B.verdict(b["typical"], tm, True, cmp_t.rows_only, sb.floor_bytes, sb.floor_rows, match=True, empty_shown=True)
1444
+ rec["typical"].update(verdict=tv, reason=tr)
1445
+ rec["heavy"] = {"before": _nums(b["heavy"]), "after": _nums(hm), "verdict": hv, "reason": hr, "results_match": hmatch, "compared": hcmp}
1446
+ rec["verdict"], rec["reason"] = B.combined_verdict((tv, tr), (hv, hr))
1447
+ else:
1448
+ rec["verdict"], rec["reason"] = tv, tr
1449
+ rec["results_match"] = False if False in (tmatch, (rec.get("heavy") or {}).get("results_match")) else tmatch
1450
+
1451
+
1452
+ def _variant_sql(s: dict):
1453
+ if s["kind"] == "ordering_key":
1454
+ copy = s["engine_detail"]["copy"]
1455
+ return lambda cand: Q.rename_table(cand["baseline_sql"], ENGINE, s["table"], copy)
1456
+ return lambda cand: cand["baseline_sql"]
1457
+
1458
+
1459
+ def _rewrite_sql(s: dict, info):
1460
+ """The rule applied to the runnable statement (its baseline, values in place of `?`)."""
1461
+ rule = s["engine_detail"]["rule"]
1462
+
1463
+ def make(cand):
1464
+ sql = cand["baseline_sql"]
1465
+ if rule == "prewhere_keys":
1466
+ got = Q.prewhere_keys(sql, ENGINE, info)
1467
+ elif rule == "filter_into_final":
1468
+ got = push_into_final(sql, info)
1469
+ elif rule == "per_partition_final":
1470
+ got = (_settings_added(sql, "do_not_merge_across_partitions_select_final = 1"), "") \
1471
+ if partition_aligned(info) and re.search(r"\bFINAL\b", sql, re.I) else None
1472
+ elif rule in ("limit_1_by", "argmax"):
1473
+ got = dedup_rewrite_limit_by(sql, info, "limit_by" if rule == "limit_1_by" else "argmax")
1474
+ elif rule == "drop_final":
1475
+ got = drop_final(sql, info, settings_of(None))
1476
+ else:
1477
+ got = None
1478
+ return got[0] if got else None
1479
+ return make
1480
+
1481
+
1482
+ def table_info(name: str, rank: dict | None, facts, inventory: dict | None = None) -> "Q.TableInfo | None":
1483
+ tables = Q.tables_from_inventory(inventory or {})
1484
+ if facts:
1485
+ tables.update(Q.tables_from_catalog(facts, ENGINE))
1486
+ info = tables.get(name)
1487
+ if info is not None and not info.create_sql:
1488
+ info.create_sql = _definition(name, rank, facts)
1489
+ return info
1490
+
1491
+
1492
+ def prove_table(sb, doc: dict, plan: dict, suggestions: list[dict], stmts: list[dict], cands: dict, profile: dict, runs: int,
1493
+ bench_settings: dict | None, insert_side: bool, info, log=lambda msg: None) -> list[dict]:
1494
+ """Every suggestion of one table, as a set: built once, every runnable statement of the table measured with it."""
1495
+ import time
1496
+ from . import writecost
1497
+ from .engines.base import QueryError, SandboxError
1498
+ base = {}
1499
+ for st in stmts:
1500
+ c = cands[st["finding"]]
1501
+ p, hp = _params(c, profile)
1502
+ t = sb.measure(c["baseline_sql"], p, runs)
1503
+ h = sb.measure(c["baseline_sql"], hp, 1) if hp and t.ok else None
1504
+ base[st["finding"]] = {"typical": t, "heavy": h, "params": p, "heavy_params": hp}
1505
+ out = []
1506
+ cfg = settings_of(doc.get("settings"))
1507
+ for s in suggestions:
1508
+ served = {sv["statement"] for sv in s["serves"]}
1509
+ rec = {"fingerprint": s["fingerprint"], "id": s["id"], "kind": s["kind"], "table": s["table"], "statements": []}
1510
+ ddl = s["ddl"]
1511
+ try:
1512
+ if s["kind"] == "dedup_on_read":
1513
+ mine = [st for st in stmts if st["ref"] in served]
1514
+ got, later = measure_statements(sb, mine, cands, runs, _rewrite_sql(s, info), None, base, serving=served)
1515
+ settle_all(sb, later)
1516
+ rec["statements"] = got
1517
+ out.append(rec)
1518
+ log(f"advisor {s['id']} {s['kind']} ({s['engine_detail']['rule']}) on {s['table']}: " + "; ".join(
1519
+ f"{x['finding']} {x.get('verdict') or x.get('skipped')}" for x in got))
1520
+ continue
1521
+ trials = s["engine_detail"].get("trials") or [{"ddl": s["ddl"]}]
1522
+ chosen = trials[0]
1523
+ if len(trials) > 1:
1524
+ rec["trials"] = []
1525
+ mine = [st for st in stmts if st["ref"] in served]
1526
+ best = None
1527
+ for tr in trials:
1528
+ try:
1529
+ sb.apply_setup(tr["ddl"])
1530
+ got, later = measure_statements(sb, mine, cands, 1, _variant_sql(s), tr["ddl"], base, serving=served)
1531
+ finally:
1532
+ sb.undo_setup(tr["ddl"])
1533
+ settle_all(sb, later)
1534
+ ratio = _weighted([x for x in got if x.get("typical")], "typical")
1535
+ rec["trials"].append({"granularity": tr.get("granularity"), "read_ratio": None if ratio is None else round(ratio, 4)})
1536
+ # the smallest read wins; at an equal read the coarser index (the later trial) is smaller to keep
1537
+ if ratio is not None and (best is None or ratio <= best[0] + 1e-9):
1538
+ best = (ratio, tr)
1539
+ chosen = best[1] if best else trials[0]
1540
+ rec["granularity"] = chosen.get("granularity")
1541
+ ddl = chosen["ddl"]
1542
+ before = sb.storage_bytes([s["table"]], [])
1543
+ started = time.monotonic()
1544
+ notes = sb.apply_setup(ddl)
1545
+ rec["setup_s"] = round(time.monotonic() - started, 1)
1546
+ if notes:
1547
+ rec["setup_notes"] = notes
1548
+ rec["storage_delta_bytes"] = sb.storage_bytes([s["table"]], ddl) - before
1549
+ rec["table_bytes"] = before
1550
+ try:
1551
+ got, later = measure_statements(sb, stmts, cands, runs, _variant_sql(s), ddl, base,
1552
+ check_projection=s["engine_detail"].get("projection"),
1553
+ check_index=s["engine_detail"].get("index"), serving=served)
1554
+ finally:
1555
+ sb.undo_setup(ddl)
1556
+ settle_all(sb, later)
1557
+ rec["statements"] = got
1558
+ rec["ddl"] = ddl
1559
+ scaled = sb._granularity_of(s["table"]) if hasattr(sb, "_granularity_of") else None
1560
+ if scaled:
1561
+ rec["granularity"] = scaled
1562
+ on_marks = bool(scaled) and s["kind"] in KEY_ORDER_KINDS
1563
+ gain = _weighted([x for x in got if x["serves"] and x.get("typical")], "typical", "selected_marks" if on_marks else "read_bytes")
1564
+ prod = (s.get("engine_detail") or {}).get("production") or {}
1565
+ # a skip index the sandbox can not judge (where its values sit) but production's counts say reads less: its
1566
+ # insert side is still the sandbox's to measure
1567
+ prod_gain = s["kind"] == "skip_index" and prod.get("status") == "answered" and prod.get("ratio") is not None \
1568
+ and prod["ratio"] <= 1 - float(cfg["min_read_gain"]) and (prod.get("floor") is None or prod["floor"] <= 1 - float(cfg["min_read_gain"]))
1569
+ if insert_side and ((gain is not None and gain <= 1 - float(cfg["min_read_gain"])) or prod_gain):
1570
+ rec["insert_cost"] = writecost.measure(sb, s["table"], ddl, bench_settings or {}, log)
1571
+ log(f"advisor {s['id']} {s['kind']} on {s['table']}: weighted read x{'-' if gain is None else round(gain, 3)} over "
1572
+ f"{sum(1 for x in got if x['serves'])} served statement(s), {sum(1 for x in got if not x['serves'])} other(s) measured")
1573
+ except QueryError as e:
1574
+ rec["setup_error"] = str(e)[:400]
1575
+ sb.undo_setup(ddl)
1576
+ try: # a failed MATERIALIZE stays queued and fails every later mutation of the table: removed
1577
+ sb.execute("KILL MUTATION WHERE database = {d:String} AND table = {t:String} SYNC", sb._where(s["table"]))
1578
+ except QueryError:
1579
+ pass
1580
+ log(f"advisor {s['id']} {s['kind']} on {s['table']}: setup failed: {str(e)[:200]}")
1581
+ except SandboxError as e:
1582
+ why = sb.revive() if hasattr(sb, "revive") else ""
1583
+ rec["setup_error"] = f"the sandbox server stopped ({why or e})"[:400]
1584
+ log(f"advisor {s['id']} {s['kind']} on {s['table']}: the sandbox stopped ({why or e})")
1585
+ out.append(rec)
1586
+ return out
1587
+
1588
+
1589
+ def _weighted(rows: list[dict], run: str, field: str = "read_bytes") -> float | None:
1590
+ """The load-weighted read ratio (`field` after / before: bytes, or selected marks for a re-key or projection on a
1591
+ sandbox whose granules are scaled to production's) over measured statements; equal weights when none has a load."""
1592
+ rows = [r for r in rows if ((r.get(run) or {}).get("after") or {}).get("ok") and (r[run]["before"].get(field) or 0) > 0]
1593
+ if not rows:
1594
+ return None
1595
+ ws = [r["weight"] for r in rows]
1596
+ if not any(ws):
1597
+ ws = [1] * len(rows)
1598
+ return sum(w * (r[run]["after"].get(field) or 0) / r[run]["before"][field] for w, r in zip(ws, rows)) / sum(ws)
1599
+
1600
+
1601
+ def hook(doc: dict, rank_data: dict, runs: int, bench_settings: dict | None, scales: tuple, rank: dict | None = None, facts=None,
1602
+ inventory: dict | None = None, log=lambda msg: None, on_record=None):
1603
+ """(the bench hook, the results by scale). bench.run calls the hook for each load group while its tables are loaded;
1604
+ each planned table is proved once per scale, in the call where it and its runnable statements are loaded.
1605
+ `on_record(results)` is called after each table, so a caller can keep the records written while the bench runs."""
1606
+ results: dict[float, list[dict]] = {}
1607
+ cands = {c["finding"]: c for c in rank_data.get("candidates") or []}
1608
+ done: dict[float, set] = {}
1609
+ last = max(scales) if scales else None
1610
+ infos: dict[str, object] = {}
1611
+
1612
+ def run(sb, tables, profile, fraction, findings=None):
1613
+ loaded = {_short(t["name"]).lower() for t in tables if t.get("ok")}
1614
+ # the advisor plans by the bare table name; the sandbox holds a database-qualified one (`app.runs`) in
1615
+ # its own database, so the DDL is sent for that name
1616
+ full = {_short(t["name"]).lower(): t["name"] for t in tables if t.get("ok")}
1617
+ seen = done.setdefault(fraction, set())
1618
+ for plan in doc["tables"]:
1619
+ name = plan["table"]
1620
+ if name in seen or name.lower() not in loaded:
1621
+ continue
1622
+ sugg = [s for s in doc["table_suggestions"] if s["table"] == name]
1623
+ if not sugg:
1624
+ continue
1625
+ stmts = [st for st in plan["statements"] if st.get("finding") in cands and (findings is None or st["finding"] in findings)
1626
+ and all(_short(t).lower() in loaded for t in cands[st["finding"]].get("tables") or [])]
1627
+ # one finding runs one statement: several uses of it (one per read of the table) are measured once
1628
+ stmts = list({st["finding"]: st for st in sorted(stmts, key=lambda x: x["weight"])}.values())
1629
+ stmts = sorted(stmts, key=lambda x: -x["weight"])[:int(settings_of(doc.get("settings"))["max_statements_per_table"])]
1630
+ seen.add(name)
1631
+ if not stmts:
1632
+ results.setdefault(fraction, []).extend({"fingerprint": s["fingerprint"], "id": s["id"], "kind": s["kind"], "table": name,
1633
+ "statements": [], "skip": "no_runnable_statement"} for s in sugg)
1634
+ continue
1635
+ if name not in infos:
1636
+ infos[name] = table_info(name, rank or rank_data, facts, inventory)
1637
+ log(f"advisor: {name}: {len(sugg)} candidate(s) over {len(stmts)} runnable statement(s)")
1638
+ where = full.get(name.lower(), name)
1639
+ got = prove_table(sb, doc, plan, [qualified(s, where) for s in sugg], stmts, cands, profile, runs, bench_settings,
1640
+ fraction == last, infos[name], log)
1641
+ for rec in got:
1642
+ rec["table"] = name
1643
+ results.setdefault(fraction, []).extend(got)
1644
+ if on_record is not None:
1645
+ on_record(results)
1646
+ return None
1647
+ return run, results
1648
+
1649
+
1650
+ def qualified(s: dict, where: str) -> dict:
1651
+ """The suggestion with its DDL sent to `where`, the name the sandbox holds the table under (database-qualified
1652
+ when the definition is): `ALTER TABLE runs ...` becomes `ALTER TABLE app.runs ...`. A suggestion that
1653
+ copies the table (ordering_key) is left as planned."""
1654
+ import copy
1655
+ from .engines.clickhouse import quote_table
1656
+ if where == s["table"] or s["kind"] == "ordering_key":
1657
+ return s
1658
+ lead = re.compile(rf"^(\s*ALTER\s+TABLE\s+)[`\"]?{re.escape(s['table'])}[`\"]?(?=\s)", re.I)
1659
+
1660
+ def move(ddl: list[str]) -> list[str]:
1661
+ return [lead.sub(lambda m: m.group(1) + quote_table(where), d) for d in ddl]
1662
+ out = copy.deepcopy(s)
1663
+ out["table"] = where
1664
+ out["ddl"] = move(out.get("ddl") or [])
1665
+ for tr in (out.get("engine_detail") or {}).get("trials") or []:
1666
+ tr["ddl"] = move(tr.get("ddl") or [])
1667
+ return out
1668
+
1669
+
1670
+ def chain(*hooks):
1671
+ """One bench hook from several: each is called; the first one's result is the scale's `groups`."""
1672
+ live = [h for h in hooks if h is not None]
1673
+ if not live:
1674
+ return None
1675
+
1676
+ def run(sb, tables, profile, fraction, findings=None):
1677
+ first = None
1678
+ for i, h in enumerate(live):
1679
+ got = h(sb, tables, profile, fraction, findings=findings)
1680
+ if i == 0:
1681
+ first = got
1682
+ return first
1683
+ return run
1684
+
1685
+
1686
+ def bench_record(results: dict[float, list[dict]]) -> dict:
1687
+ """What bench.json keeps under `advisor`: per scale, each suggestion's proof record."""
1688
+ return {"schema_version": SCHEMA_VERSION, "scales": [{"fraction": f, "results": rs} for f, rs in sorted(results.items())]}
1689
+
1690
+
1691
+ # ---- outcomes ------------------------------------------------------------------------------------------------
1692
+
1693
+ WORDS = {
1694
+ "verified": "reads less on the statements it serves, the same rows, within the insert-cost thresholds",
1695
+ "fix_costs_inserts": "reads less, but costs inserts above the thresholds: a trade-off",
1696
+ "fix_results_differ": "a statement returned other rows with it",
1697
+ "regresses_other_statements": "another statement of the table reads more with it",
1698
+ "no_variant_reads_less": "measured: the statements it serves read no less",
1699
+ "engine_did_not_use_it": "the server did not choose the projection for the statements it was built for",
1700
+ "skip_index_locality_unknown": "could not be judged on generated data: where the column's values sit in production is not known",
1701
+ "claimed_not_measured": "no statement it serves has a runnable form: claimed, not measured",
1702
+ "insert_cost_not_measured": "reads less, but its insert side could not be measured",
1703
+ "sandbox_could_not_run": "the sandbox could not build it",
1704
+ "bench_not_run": "not benchmarked yet",
1705
+ "a_projection_serves_it": "a projection with the same order serves the same statements, for less",
1706
+ "already_cheap_measured": "the statements it serves already read little",
1707
+ "not_usable_as_written": "the statements bound a column the projection does not keep: the engine can not use it",
1708
+ "parameters_match_no_rows": "the statements it serves read nothing on the sandbox: their values match no rows there",
1709
+ "insert_cost_near_limit": "reads less; insert cost near the limit: the measured spread of the insert time crosses it (a trade-off)",
1710
+ # counted on production by aggregates (realdb/locality.py): the read side of an index that is not built
1711
+ "measured_on_production": "Read side measured on production (simulated), insert side verified",
1712
+ "production_floor": "counted on production: the statements already read only granules that hold their rows",
1713
+ "production_counts_disagree": "could not be judged: the sandbox's marks and production's row counts disagree",
1714
+ "table_too_small": "nothing to gain: the table is read whole in a few granules (counted on production's catalog, no statement sent)",
1715
+ }
1716
+ # How the four states take these: a skip index whose read side was counted on production
1717
+ # (measured_on_production) and whose insert side the sandbox measured within the limits is judged, but never fixed:
1718
+ # "blocked" (shown as "Needs another fix") with its own reason, until `codecop apply --trial` evidence or a sandbox proof
1719
+ # on faithful data. Its insert side over a limit is the usual trade-off; not measured, insert_cost_not_measured.
1720
+ STATE_OF = {"measured_on_production": "blocked", "production_floor": "nothing_to_gain", "production_counts_disagree": "not_judged",
1721
+ "table_too_small": "nothing_to_gain",
1722
+ "verified": "fixed", "fix_costs_inserts": "blocked", "fix_results_differ": "blocked", "regresses_other_statements": "blocked",
1723
+ "no_variant_reads_less": "blocked", "engine_did_not_use_it": "blocked", "skip_index_locality_unknown": "not_judged",
1724
+ "claimed_not_measured": "not_judged", "insert_cost_not_measured": "not_judged", "sandbox_could_not_run": "not_judged",
1725
+ "bench_not_run": "not_judged", "a_projection_serves_it": "nothing_to_gain", "already_cheap_measured": "nothing_to_gain",
1726
+ "not_usable_as_written": "not_judged", "parameters_match_no_rows": "not_judged", "insert_cost_near_limit": "blocked"}
1727
+ VERDICT_OF = {"measured_on_production": "measured_on_production", "production_floor": "no_change", "table_too_small": "no_change",
1728
+ "production_counts_disagree": "evidence_only", "verified": "verified", "fix_costs_inserts": "trade_off", "fix_results_differ": "results_differ",
1729
+ "regresses_other_statements": "regresses", "no_variant_reads_less": "no_change", "engine_did_not_use_it": "not_used",
1730
+ "skip_index_locality_unknown": "evidence_only", "claimed_not_measured": "claimed", "insert_cost_not_measured": "not_measured",
1731
+ "sandbox_could_not_run": "failed", "bench_not_run": "claimed", "a_projection_serves_it": "superseded",
1732
+ "already_cheap_measured": "no_change", "not_usable_as_written": "evidence_only", "parameters_match_no_rows": "not_measured",
1733
+ "insert_cost_near_limit": "trade_off"}
1734
+
1735
+
1736
+ def _outcome(reason: str, **evidence) -> dict:
1737
+ return {"state": STATE_OF[reason], "reason": reason, "words": WORDS[reason], **({"evidence": evidence} if evidence else {})}
1738
+
1739
+
1740
+ def _production_evidence(prod: dict) -> dict:
1741
+ """What a production count adds to an outcome's evidence: numbers and codes only."""
1742
+ return {"basis": "production_simulation", "production": {k: prod[k] for k in (
1743
+ "statement_id", "ratio", "spread", "floor", "before", "after", "probes", "by_rank", "thresholds", "window_hours", "window_basis",
1744
+ "granule_basis", "estimate", "counted_over", "cost") if prod.get(k) is not None}}
1745
+
1746
+
1747
+ def judge(s: dict, rec: dict | None, cfg: dict, insert_cfg: dict) -> dict:
1748
+ """One suggestion's outcome from its proof record, in the four states (blockers.STATES), and from production's counts
1749
+ when `codecop db pull --locality` made them (engine_detail.production)."""
1750
+ out = _judge_sandbox(s, rec, cfg, insert_cfg)
1751
+ prod = (s.get("engine_detail") or {}).get("production") or {}
1752
+ if prod.get("status") == "nothing_to_gain" and out["state"] == "not_judged":
1753
+ # its table is too small for any index or key to matter (locality.too_small): no statement was spent on it
1754
+ return _outcome("table_too_small", basis="production_catalog", production={k: prod[k] for k in ("status", "reason") if prod.get(k)})
1755
+ if prod and out["reason"] in ("skip_index_locality_unknown", "bench_not_run", "claimed_not_measured") and "production" not in (out.get("evidence") or {}):
1756
+ # not counted on production, or counted to its floor only: why (a refusal, the budget, a LIKE, minmax on equality)
1757
+ out.setdefault("evidence", {})["production"] = {k: prod[k] for k in ("status", "reason", "floor", "basis") if prod.get(k) is not None}
1758
+ return out
1759
+
1760
+
1761
+ def _skip_index_on_production(s: dict, rec: dict | None, cfg: dict, insert_cfg: dict, prod: dict) -> dict | None:
1762
+ """A skip index the sandbox can not judge, counted on production: production's floor or ratio decide the read side;
1763
+ the sandbox still proves the DDL builds, the rows are the same and what inserts cost. Never `fixed` by itself."""
1764
+ pev = _production_evidence(prod)
1765
+ gain = 1 - float(cfg["min_read_gain"])
1766
+ if prod.get("floor") is not None and prod["floor"] > gain:
1767
+ return _outcome("production_floor", **pev)
1768
+ if prod.get("ratio") is None:
1769
+ return None # the floor leaves room and this index type is not simulated: the sandbox's rule stands
1770
+ if prod["ratio"] > gain:
1771
+ return _outcome("no_variant_reads_less", **pev)
1772
+ if rec is None or rec.get("skip") == "no_runnable_statement":
1773
+ return _outcome("bench_not_run" if rec is None else "insert_cost_not_measured", **pev,
1774
+ insert_cost={"measured": False, "reason": "bench_not_run" if rec is None else "no_runnable_statement"})
1775
+ if rec.get("setup_error"):
1776
+ from .blockers import error_class
1777
+ return _outcome("sandbox_could_not_run", error=error_class(rec["setup_error"]), **pev)
1778
+ if any(r.get("results_match") is False for r in rec.get("statements") or []):
1779
+ return _outcome("fix_results_differ", statements=[r["finding"] for r in rec["statements"] if r.get("results_match") is False], **pev)
1780
+ ic = rec.get("insert_cost")
1781
+ if not ic or not ic.get("measured"):
1782
+ return _outcome("insert_cost_not_measured", **pev, insert_cost={k: (ic or {}).get(k) for k in ("measured", "reason")})
1783
+ from .writecost import near_limit, within
1784
+ if within(ic, insert_cfg) is False:
1785
+ return _outcome("insert_cost_near_limit" if near_limit(ic, insert_cfg) else "fix_costs_inserts", **pev, trade_off=True,
1786
+ insert_cost={k: ic.get(k) for k in ("insert_time_ratio", "insert_time_ratio_range", "storage_ratio", "parts_ratio") if k in ic})
1787
+ return _outcome("measured_on_production", **pev,
1788
+ insert_cost={k: ic.get(k) for k in ("insert_time_ratio", "insert_time_ratio_range", "storage_ratio", "parts_ratio") if k in ic})
1789
+
1790
+
1791
+ VERIFIED_WHERE = {"same_rows": "sandbox: the served statements returned the same rows with the change",
1792
+ "engine_used": "sandbox: the server chose the projection (projections only)",
1793
+ "read_reduction": "production: granules counted by aggregates over production's own parts (nothing built)",
1794
+ "insert_cost": "sandbox"}
1795
+
1796
+
1797
+ def _key_order_on_production(rec: dict, cfg: dict, insert_cfg: dict, prod: dict, ev: dict, worse: list[dict]) -> dict:
1798
+ """A re-key or projection whose sandbox marks and production's exact counts disagree in direction (one reads less,
1799
+ the other not). The read side is production's: its counts are over production's own granules, where the sandbox's
1800
+ marks are over generated data whose clustering, cardinality and size are not production's (a sandbox at the
1801
+ granularity floor or with values placed without the tenant can read several times more granules for the same
1802
+ prefix). What the sandbox proved still has to hold: the same rows on every served statement measured (and for a
1803
+ projection, that the server chose it), no other statement of the table reading more, the insert side within the
1804
+ limits. Never fixed by itself: `measured_on_production` (blocked) until the user's trial on one partition."""
1805
+ ev = {**ev, "basis": "production_counts_sandbox_rows", "verified_where": VERIFIED_WHERE}
1806
+ if float(prod["ratio"]) > 1 - float(cfg["min_read_gain"]):
1807
+ return _outcome("no_variant_reads_less", **ev)
1808
+ served = [r for r in rec.get("statements") or [] if r["serves"] and r.get("typical")]
1809
+ if not any(r.get("results_match") is True and r["typical"]["after"].get("ok") for r in served):
1810
+ return _outcome("production_counts_disagree", **ev) # the same rows not shown: nothing to stand on
1811
+ if worse:
1812
+ return _outcome("regresses_other_statements", **ev, statements=[r["finding"] for r in worse])
1813
+ ic = rec.get("insert_cost")
1814
+ if not ic or not ic.get("measured"):
1815
+ return _outcome("insert_cost_not_measured", **ev, insert_cost={k: (ic or {}).get(k) for k in ("measured", "reason")})
1816
+ from .writecost import near_limit, within
1817
+ keep = {k: ic.get(k) for k in ("insert_time_ratio", "insert_time_ratio_range", "storage_ratio", "parts_ratio") if k in ic}
1818
+ if within(ic, insert_cfg) is False:
1819
+ return _outcome("insert_cost_near_limit" if near_limit(ic, insert_cfg) else "fix_costs_inserts", **ev, trade_off=True, insert_cost=keep)
1820
+ return _outcome("measured_on_production", **ev, insert_cost=keep)
1821
+
1822
+
1823
+ def _disagreement_signs(rec: dict | None, prod: dict) -> list[str]:
1824
+ """What the records say about why the sandbox and production disagree (codes; each can move the sandbox's
1825
+ marks by several times): the sandbox's granules at the floor, few granules for the prefix in the sandbox, production
1826
+ counted over a cut of its parts."""
1827
+ out = []
1828
+ g = (rec or {}).get("granularity") or {}
1829
+ if g.get("floor_hit"):
1830
+ out.append("sandbox_granularity_floor") # granules larger than production's, scaled: a prefix reads a whole one
1831
+ before = [r["typical"]["before"].get("selected_marks") for r in (rec or {}).get("statements") or [] if r.get("serves") and r.get("typical")]
1832
+ if before and max(b or 0 for b in before) <= 4:
1833
+ out.append("sandbox_few_granules") # the statements read a handful of granules: a ratio of small numbers
1834
+ if (prod.get("counted_over") or {}).get("cut"):
1835
+ out.append("production_parts_cut") # counted over the newest parts inside the row budget
1836
+ return out
1837
+
1838
+
1839
+ def _on_trial(s: dict, rec: dict | None, cfg: dict, insert_cfg: dict, trial: dict) -> dict:
1840
+ """The user's trial on one production partition decides the read side: marks per run inside the trial partition
1841
+ against a neighbour. With the insert side within the limits on the sandbox, that is a verified win (fixed)."""
1842
+ tev = {"basis": "production_trial", "trial": {k: trial[k] for k in ("ratio", "runs_trial", "runs_neighbour", "window_hours") if k in trial}}
1843
+ if trial["ratio"] > 1 - float(cfg["min_read_gain"]):
1844
+ return _outcome("no_variant_reads_less", **tev)
1845
+ ic = (rec or {}).get("insert_cost")
1846
+ if not ic or not ic.get("measured"):
1847
+ return _outcome("insert_cost_not_measured", **tev, insert_cost={k: (ic or {}).get(k) for k in ("measured", "reason")})
1848
+ from .writecost import near_limit, within
1849
+ if within(ic, insert_cfg) is False:
1850
+ return _outcome("insert_cost_near_limit" if near_limit(ic, insert_cfg) else "fix_costs_inserts", **tev, trade_off=True,
1851
+ insert_cost={k: ic.get(k) for k in ("insert_time_ratio", "insert_time_ratio_range", "storage_ratio", "parts_ratio") if k in ic})
1852
+ return _outcome("verified", **tev)
1853
+
1854
+
1855
+ def _judge_sandbox(s: dict, rec: dict | None, cfg: dict, insert_cfg: dict) -> dict:
1856
+ prod = (s.get("engine_detail") or {}).get("production") or {}
1857
+ trial = (s.get("engine_detail") or {}).get("production_trial") or {}
1858
+ if s["kind"] in ("skip_index", "projection", "aggregating_projection") and trial.get("status") == "answered" and trial.get("ratio") is not None:
1859
+ return _on_trial(s, rec, cfg, insert_cfg, trial)
1860
+ if s["kind"] == "skip_index" and not s["engine_detail"].get("measurable") and prod.get("status") == "answered" \
1861
+ and (prod.get("ratio") is not None or prod.get("floor") is not None):
1862
+ got = _skip_index_on_production(s, rec, cfg, insert_cfg, prod)
1863
+ if got is not None:
1864
+ return got
1865
+ if s["kind"] == "aggregating_projection" and not s["engine_detail"].get("usable", True) and not (rec or {}).get("statements"):
1866
+ return _outcome("not_usable_as_written", columns=s["engine_detail"].get("raw_time_columns"))
1867
+ if rec is None:
1868
+ return _outcome("bench_not_run" if any(sv.get("finding") for sv in s["serves"]) else "claimed_not_measured")
1869
+ if rec.get("skip") == "no_runnable_statement":
1870
+ return _outcome("claimed_not_measured")
1871
+ if rec.get("setup_error"):
1872
+ from .blockers import error_class
1873
+ return _outcome("sandbox_could_not_run", error=error_class(rec["setup_error"]))
1874
+ rows = rec.get("statements") or []
1875
+ served = [r for r in rows if r["serves"] and r.get("typical")]
1876
+ if not served:
1877
+ return _outcome("claimed_not_measured")
1878
+ if all(not (r[run]["before"].get("read_bytes") or r[run]["before"].get("result_rows")) for r in served for run in ("typical", "heavy") if r.get(run)):
1879
+ return _outcome("parameters_match_no_rows", measured=len(served))
1880
+ if any(r.get("results_match") is False for r in rows):
1881
+ return _outcome("fix_results_differ", statements=[r["finding"] for r in rows if r.get("results_match") is False])
1882
+ kind = s["kind"]
1883
+ if kind in ("projection", "aggregating_projection") and not any(r.get("engine_used") for r in served):
1884
+ return _outcome("engine_did_not_use_it", measured=len(served))
1885
+ counted = [r for r in served if kind not in ("projection", "aggregating_projection") or r.get("engine_used")]
1886
+ # a re-key or projection on a sandbox whose granules are scaled to production's is judged on selected marks; bytes
1887
+ # are kept beside them (an aggregating projection's bytes are bound to the sandbox's scale). Skip indexes never are.
1888
+ on_marks = kind in KEY_ORDER_KINDS and bool(rec.get("granularity"))
1889
+ field = "selected_marks" if on_marks else "read_bytes"
1890
+ gain_t = _weighted(counted, "typical", field)
1891
+ heavy_rows = [r for r in counted if r.get("heavy")]
1892
+ gain_h = _weighted(heavy_rows, "heavy", field) if heavy_rows else None
1893
+
1894
+ def marks_win(r: dict) -> bool:
1895
+ b, a = (r["typical"]["before"].get(field) or 0), (r["typical"]["after"].get(field) or 0)
1896
+ return bool(b) and a / b <= 1 - cfg["min_read_gain"] and r.get("results_match") is not False and r["typical"]["after"].get("ok")
1897
+ wins = [r for r in counted if (marks_win(r) if on_marks else r.get("verdict") == "win")]
1898
+ worse = [r for r in rows if not r["serves"] and r.get("typical") and r["typical"]["after"].get("ok") and
1899
+ (r["typical"]["before"].get("read_bytes") or 0) > 0 and
1900
+ r["typical"]["after"]["read_bytes"] / r["typical"]["before"]["read_bytes"] > cfg["regression_ratio"]]
1901
+ ev = {"read_ratio_typical": None if gain_t is None else round(gain_t, 4), "read_ratio_heavy": None if gain_h is None else round(gain_h, 4),
1902
+ "served_measured": len(counted), "served_wins": len(wins), "others_measured": sum(1 for r in rows if not r["serves"] and r.get("typical"))}
1903
+ if on_marks:
1904
+ b = _weighted(counted, "typical")
1905
+ ev.update(judged_on="selected_marks", read_ratio_bytes=None if b is None else round(b, 4),
1906
+ granularity={k: rec["granularity"].get(k) for k in ("index_granularity", "rows_per_mark_real", "share", "floor_hit")})
1907
+ reads_less = gain_t is not None and gain_t <= 1 - cfg["min_read_gain"] and bool(wins) and (gain_h is None or gain_h <= 1.0)
1908
+ if kind == "skip_index" and not s["engine_detail"].get("measurable"):
1909
+ return _outcome("skip_index_locality_unknown", **ev, locality_basis=s["engine_detail"].get("locality_basis"), measured_gain=reads_less)
1910
+ prod = (s.get("engine_detail") or {}).get("production") or {}
1911
+ if kind in KEY_ORDER_KINDS and prod.get("status") == "answered" and prod.get("ratio") is not None and gain_t is not None:
1912
+ # the second opinion: production's rows per key prefix. More than locality_disagree_factor apart:
1913
+ # not judged, both numbers shown
1914
+ lo = float(cfg["locality_ratio_floor"])
1915
+ a, c = max(gain_t, lo), max(float(prod["ratio"]), lo)
1916
+ ev.update(_production_evidence(prod))
1917
+ ev["basis"] = "sandbox_marks_and_production_counts" if on_marks else "sandbox_and_production_counts"
1918
+ if max(a, c) / min(a, c) > float(cfg["locality_disagree_factor"]):
1919
+ ev.update(sandbox_ratio=round(gain_t, 4), production_ratio=prod["ratio"], disagreement=round(max(a, c) / min(a, c), 2),
1920
+ why_they_may_differ=_disagreement_signs(rec, prod))
1921
+ exact = str(prod.get("granule_basis") or "").startswith("exact") and not prod.get("estimate")
1922
+ if not exact:
1923
+ return _outcome("production_counts_disagree", **ev)
1924
+ if not (reads_less and float(prod["ratio"]) <= 1 - cfg["min_read_gain"]):
1925
+ return _key_order_on_production(rec, cfg, insert_cfg, prod, ev, worse)
1926
+ # both read less, by different amounts: the sandbox's win stands (verified below); production's exact count
1927
+ # is shown beside it as the expected size on production's data
1928
+ ev["size_on_production"] = "production counts (simulated by aggregates; nothing built)"
1929
+ if worse:
1930
+ return _outcome("regresses_other_statements", **ev, statements=[r["finding"] for r in worse])
1931
+ if not reads_less:
1932
+ if all("already reads little" in (r.get("reason") or "") for r in served):
1933
+ return _outcome("already_cheap_measured", **ev)
1934
+ return _outcome("no_variant_reads_less", **ev)
1935
+ if kind == "dedup_on_read":
1936
+ return _outcome("verified", **ev)
1937
+ ic = rec.get("insert_cost")
1938
+ if ic is None:
1939
+ return _outcome("verified", **ev, insert_cost={"measured": False, "reason": "not_measured"})
1940
+ if not ic.get("measured"):
1941
+ return _outcome("insert_cost_not_measured", **ev, insert_cost={k: ic.get(k) for k in ("measured", "reason")})
1942
+ from .writecost import near_limit, within
1943
+ if within(ic, insert_cfg) is False:
1944
+ return _outcome("insert_cost_near_limit" if near_limit(ic, insert_cfg) else "fix_costs_inserts", **ev, trade_off=True,
1945
+ insert_cost={k: ic.get(k) for k in ("insert_time_ratio", "insert_time_ratio_range", "storage_ratio", "parts_ratio")
1946
+ if k in ic})
1947
+ return _outcome("verified", **ev)
1948
+
1949
+
1950
+ def outcomes(doc: dict, bench: dict | None, bench_settings: dict | None = None) -> dict:
1951
+ """Each suggestion's measured numbers, verdict and outcome, from bench.json's `advisor` record (the largest scale
1952
+ that proved it). In place; returns doc."""
1953
+ from .writecost import settings_of as wc_settings
1954
+ cfg = settings_of(doc.get("settings"))
1955
+ insert_cfg = wc_settings(bench_settings)
1956
+ recs = {}
1957
+ for sc in ((bench or {}).get("advisor") or {}).get("scales") or []: # the largest scale last: its record wins
1958
+ for r in sc.get("results") or []:
1959
+ recs[r["fingerprint"]] = {**r, "fraction": sc.get("fraction")}
1960
+ for s in doc["table_suggestions"]:
1961
+ rec = recs.get(s["fingerprint"])
1962
+ s["outcome"] = judge(s, rec, cfg, insert_cfg)
1963
+ s["verdict"] = VERDICT_OF[s["outcome"]["reason"]]
1964
+ pe = (s["outcome"].get("evidence") or {}).get("production")
1965
+ if pe and pe.get("ratio") is not None:
1966
+ # counted on production, not built: an expected ratio with its spread, never a measured win
1967
+ s["read_gain"] = {**s["read_gain"], "read_ratio_production": pe["ratio"], "production_spread": pe.get("spread"),
1968
+ "production_floor": pe.get("floor"), "production_basis": "simulated by aggregates on production"
1969
+ + (" (estimate: granules from rows per mark)" if pe.get("estimate") else "")}
1970
+ if not rec:
1971
+ continue
1972
+ by_ref = {r["statement"]: r for r in rec.get("statements") or []}
1973
+ for sv in s["serves"]:
1974
+ r = by_ref.get(sv["statement"])
1975
+ if r and r.get("typical"):
1976
+ sv["claimed"] = False
1977
+ sv["measured"] = {run: {"before_bytes": r[run]["before"].get("read_bytes"), "after_bytes": r[run]["after"].get("read_bytes"),
1978
+ "before_rows": r[run]["before"].get("read_rows"), "after_rows": r[run]["after"].get("read_rows"),
1979
+ "verdict": r[run]["verdict"], "results_match": r[run]["results_match"]}
1980
+ for run in ("typical", "heavy") if r.get(run)}
1981
+ sv["verdict"] = r.get("verdict")
1982
+ if "engine_used" in r:
1983
+ sv["engine_used"] = r["engine_used"]
1984
+ elif r and r.get("skipped"):
1985
+ sv["skipped"] = r["skipped"]
1986
+ s["others_measured"] = [{"statement": r["statement"], "finding": r["finding"], "read_ratio": _ratio(r)}
1987
+ for r in rec.get("statements") or [] if not r["serves"] and r.get("typical")]
1988
+ ev = s["outcome"].get("evidence") or {}
1989
+ s["read_gain"] = {**s["read_gain"], "basis": "measured", "read_ratio_typical": ev.get("read_ratio_typical"),
1990
+ "read_ratio_heavy": ev.get("read_ratio_heavy"), "measured_load_share": _measured_share(s),
1991
+ "statements_measured": ev.get("served_measured", 0)}
1992
+ if rec.get("storage_delta_bytes") is not None:
1993
+ s["size"] = {"bytes_sandbox": rec["storage_delta_bytes"], "table_bytes_sandbox": rec.get("table_bytes"),
1994
+ "basis": "sandbox scale" + (f" {rec.get('fraction')}" if rec.get("fraction") is not None else "")}
1995
+ if rec.get("insert_cost") is not None:
1996
+ ic = rec["insert_cost"]
1997
+ s["write_cost"] = {k: ic.get(k) for k in ("measured", "reason", "rows", "blocks", "insert_time_ratio", "written_bytes_ratio",
1998
+ "storage_ratio", "parts_ratio", "within", "thresholds", "rounds",
1999
+ "insert_time_ratio_range", "near_limit") if k in ic}
2000
+ elif s["kind"] in TABLE_KINDS:
2001
+ s["write_cost"] = {"measured": False, "reason": "reads_no_less" if s["verdict"] != "verified" else "not_measured"}
2002
+ if rec.get("trials"):
2003
+ s["engine_detail"]["trials_measured"] = rec["trials"]
2004
+ s["engine_detail"]["granularity_chosen"] = rec.get("granularity")
2005
+ s["ddl"] = rec.get("ddl") or s["ddl"]
2006
+ for k in ("setup_s", "setup_notes"):
2007
+ if rec.get(k):
2008
+ s["engine_detail"][f"{k}_sandbox" if k == "setup_s" else k] = rec[k]
2009
+ _supersede(doc, cfg)
2010
+ doc["summary"] = {**doc.get("summary", {}), **summarize(doc["tables"], doc["table_suggestions"])}
2011
+ return doc
2012
+
2013
+
2014
+ def _ratio(r: dict) -> float | None:
2015
+ b, a = (r["typical"]["before"].get("read_bytes") or 0), (r["typical"]["after"].get("read_bytes") or 0)
2016
+ return round(a / b, 4) if b else None
2017
+
2018
+
2019
+ def _measured_share(s: dict) -> float | None:
2020
+ """The share of the table's load carried by the served statements that were measured (claimed ones left out)."""
2021
+ if not any(sv.get("weight_share") is not None for sv in s["serves"]):
2022
+ return None
2023
+ return round(sum(sv.get("weight_share") or 0 for sv in s["serves"] if sv.get("claimed") is False), 6)
2024
+
2025
+
2026
+ def _supersede(doc: dict, cfg: dict) -> None:
2027
+ """A verified re-key matched by a verified projection with the same leading order (`projection_over_rekey` of its
2028
+ gain and of its served load) is not needed: the projection is the smaller change."""
2029
+ for rk in [s for s in doc["table_suggestions"] if s["kind"] == "ordering_key" and s["verdict"] == "verified"]:
2030
+ new = rk["engine_detail"]["new_key"]
2031
+ g_rk = 1 - (rk["read_gain"].get("read_ratio_typical") or 1)
2032
+ for p in doc["table_suggestions"]:
2033
+ if p["kind"] != "projection" or p["table"] != rk["table"] or p["verdict"] != "verified":
2034
+ continue
2035
+ order = p["engine_detail"]["order_by"]
2036
+ if new[:len(order)] != order:
2037
+ continue
2038
+ g_p = 1 - (p["read_gain"].get("read_ratio_typical") or 1)
2039
+ w_p, w_rk = (sum(sv.get("weight") or 0 for sv in x["serves"]) for x in (p, rk))
2040
+ if g_p >= cfg["projection_over_rekey"] * g_rk and w_p >= cfg["projection_over_rekey"] * w_rk:
2041
+ rk["outcome"] = _outcome("a_projection_serves_it", projection=p["id"])
2042
+ rk["verdict"] = VERDICT_OF["a_projection_serves_it"]
2043
+ break
2044
+
2045
+
2046
+ # ---- what findings.json and the bundle carry -------------------------------------------------------------------
2047
+
2048
+ SUGGESTION_FIELDS = ("id", "fingerprint", "engine", "kind", "table", "ddl", "serves", "read_gain", "write_cost", "size", "verdict", "basis",
2049
+ "engine_detail", "outcome", "others_measured")
2050
+
2051
+
2052
+ def for_findings(doc: dict | None) -> list[dict]:
2053
+ """The suggestions in the shared shape (run_bundle.schema.json $defs.table_suggestion; advisor.py's `shared` sends
2054
+ the same), ClickHouse extras under `engine_detail`. Local: a FINAL rewrite's statement is still in it; `for_upload`
2055
+ is what findings.json and the bundle carry."""
2056
+ out = []
2057
+ for s in (doc or {}).get("table_suggestions") or []:
2058
+ x = {k: s.get(k) for k in SUGGESTION_FIELDS if k in s}
2059
+ ed = s.get("engine_detail") or {}
2060
+ x["name"] = ed.get("index") or ed.get("projection") or ed.get("copy")
2061
+ x["engine_detail"] = {k: v for k, v in ed.items() if k != "trials"}
2062
+ out.append(x)
2063
+ return out
2064
+
2065
+
2066
+ UPLOAD_FORBIDDEN = ("sql", "rewrite_sql", "text", "params", "baseline_sql", "normalized_text")
2067
+
2068
+
2069
+ def for_upload(doc: dict | None) -> list[dict] | None:
2070
+ """The suggestions as the bundle carries them: no statement text, no rewritten SQL, no parameter values. The DDL
2071
+ stays: it names the table and its columns only."""
2072
+ if not doc:
2073
+ return None
2074
+ out = []
2075
+ for s in for_findings(doc):
2076
+ ed = {k: v for k, v in (s.get("engine_detail") or {}).items() if k not in UPLOAD_FORBIDDEN}
2077
+ serves = [{k: sv.get(k) for k in ("statement", "finding", "sql_from", "located", "file", "line", "site_ids", "weight", "weight_share",
2078
+ "weight_basis", "claimed", "measured", "verdict", "engine_used") if k in sv} for sv in s.get("serves") or []]
2079
+ out.append({**{k: v for k, v in s.items() if k not in ("engine_detail", "serves")}, "engine_detail": ed, "serves": serves})
2080
+ return out