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/joins.py ADDED
@@ -0,0 +1,1749 @@
1
+ """The join scenario: a join that does more work than the page needs. Local only: no database, no agent.
2
+
3
+ Common join waste in dashboard-style queries: the joined table is read
4
+ without the bound the driving table has, a filter applies after the join, a big table is joined for one column or as a
5
+ filter, the big table is on the hash-build side, the join multiplies rows before an aggregate, or a LEFT JOIN is never
6
+ used. This module reads every join statement of the inventory (SQL written in code, translated from an ORM, or
7
+ observed in production) through the parser and computes, per JOIN clause, a small set of facts:
8
+
9
+ sides the driving side (FROM) and the joined side: their tables, sorting / partition key (ClickHouse) or
10
+ indexes (PostgreSQL), rows (real catalog when pulled), and whether a side is a table, a subquery or a CTE
11
+ filters which side each filter reaches, as a dimension: `tenant` (a tenant-like column), `time` (a time column),
12
+ `key` (a column of the side's key); where it comes from (`where`, `on`, `inner` inside the side's own
13
+ subquery, `join_key` only through the join condition) and whether a run-time part could add more
14
+ used which columns of each side the statement reads after the join (select list, GROUP BY, ORDER BY, HAVING,
15
+ later joins); the join type, strictness and order; whether aggregation follows the join
16
+
17
+ From the facts come typed signals, each with its evidence (SIGNALS below). The rules and every threshold are settings
18
+ under `[joins]` in codecop.toml (DEFAULTS). A signal is a trigger, not a finding: it says where to look and why, the
19
+ benchmark says whether a change reads less and returns the same rows.
20
+
21
+ Mechanical variants are generated only where sameness follows from the statement and the keys alone:
22
+ push_bound the driving side's tenant/time bound, copied to the joined side, where the join condition
23
+ equates the bounded column with the joined side's column (a = b and a = x imply b = x)
24
+ push_filter a filter on a subquery side's pass-through column moved inside the subquery, where nothing
25
+ between them (LIMIT, window, DISTINCT ON, a LEFT JOIN's null side) changes which rows it keeps
26
+ drop_unused_left_join a LEFT JOIN whose columns are never read, where the joined side is unique on the join key per
27
+ the schema (a unique index, ANY strictness, a GROUP BY or LIMIT 1 BY on exactly those columns)
28
+ swap_sides ClickHouse: an INNER JOIN of two sources whose right (hash-build) side is the bigger one
29
+ Every other signal goes to the ranking agent with its facts in the prompt (`codecop rank --focus join`). Every variant goes
30
+ through the existing benchmark: same rows (multiset), fewer bytes or rows read, on the typical and the heavy run.
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ import copy
36
+ import re
37
+ from collections import Counter, defaultdict
38
+
39
+ from sqlglot import exp
40
+
41
+ from . import sqlinfo
42
+
43
+ SCHEMA_VERSION = 1
44
+ SIGNALS = ("joined_side_unbounded", "filter_after_join", "join_for_one_column", "big_table_on_build_side",
45
+ "aggregate_after_join", "unused_left_join", "dimension_join_repeated")
46
+ VARIANT_KINDS = ("push_bound", "push_filter", "drop_unused_left_join", "swap_sides")
47
+ ENGINES = ("clickhouse", "postgres")
48
+
49
+ DEFAULTS = {
50
+ # Per engine, the signals shown as findings (a mechanical variant is generated and benchmarked for them) and, on top,
51
+ # the ones only handed to the ranking agent with their facts (`codecop rank --focus join`). A signal in neither list is
52
+ # still computed and counted (`muted`). On ClickHouse a joined side without the driving side's tenant/time bound is a
53
+ # reliable signal; a join for one column and an aggregate after a join are often right and often not, so they go to
54
+ # the agent only; a filter after a join and every PostgreSQL signal read without a real catalog are mostly wrong, so
55
+ # they are muted.
56
+ "shown": {"clickhouse": ["joined_side_unbounded", "unused_left_join"], "postgres": []},
57
+ "agent": {"clickhouse": ["joined_side_unbounded", "join_for_one_column", "aggregate_after_join", "unused_left_join",
58
+ "big_table_on_build_side"],
59
+ "postgres": ["join_for_one_column", "aggregate_after_join"]},
60
+ # engines that apply a bound the join condition implies by themselves (a WHERE or ON comparison carried to a table side
61
+ # through `a.k = b.k`): such a joined_side_unbounded is muted there. Measured on ClickHouse 24.8 and 25.8.
62
+ "engine_applies_implied": ["clickhouse"],
63
+ # unused_left_join is shown only where the schema proves the joined side holds one row per key (it can then be
64
+ # dropped and benchmarked); without that proof it goes to the agent
65
+ "unused_left_join_needs_unique": True,
66
+ # column names that hold the tenant (a row's owner), as one regular expression matched against the bare name
67
+ "tenant_columns": r"^(tenant|team|project|org|organization|organisation|workspace|account|site|website|customer|company|"
68
+ r"subscriber|environment|env|space|app|application|instance|cluster)(_?id|_uuid|_key|_slug)?$",
69
+ # column names that hold a time; a column whose type is a date or time counts too
70
+ "time_columns": r"(^|_)(timestamp|ts|time|date|datetime|created|updated|started|ended|start|end|seen|reported|"
71
+ r"inserted|ingested|event_time|received)(_at|_ts|_time|_date|_unix|_nano)?$|_at$|_ts$|_time$|_date$",
72
+ # join_for_one_column: the joined side gives at most this many columns to the rest of the statement
73
+ "one_column_max": 1,
74
+ # ... and is at least this many rows (real catalog), or, with no size known, is read with no bound of its own
75
+ "big_table_rows": 1_000_000,
76
+ # big_table_on_build_side (ClickHouse): the right side has at least this many times the rows of the left
77
+ "build_side_ratio": 10.0,
78
+ # dimension_join_repeated: a table joined (not driving) by at least this many distinct statements ...
79
+ "dimension_min_statements": 5,
80
+ # ... and at most this many rows (real catalog); with no size known, one joined on a unique key
81
+ "dimension_max_rows": 1_000_000,
82
+ # join_for_one_column and aggregate_after_join on PostgreSQL only when the catalog says the joined side is big or
83
+ # production measured the statement: an ORM join for a filter on a small table is the norm there
84
+ "postgres_needs_size": True,
85
+ # a signal whose side has a run-time part (a filter the code adds) in the clause that would bound it is kept,
86
+ # marked `uncertain`; false drops it
87
+ "keep_uncertain": True,
88
+ # time-typed columns that are not a time a row belongs to (a soft delete, an expiry): never a time bound
89
+ "not_time_columns": r"(deleted|archived|removed|disabled|expires|expired|expiry|revoked|locked|banned|verified)_?(at|on|time|date)?$",
90
+ # a lookup column: an equality on it pins the driving side to a few rows
91
+ "id_columns": r"(^|_)(id|uuid|uid)(_\w+)?$",
92
+ # joined_side_unbounded:time also when the driving side's only visible bound could be a run-time part of its WHERE
93
+ # (marked uncertain)
94
+ "hidden_driving_bound": False,
95
+ # mechanical variants: generated for these kinds
96
+ "variants": ["push_bound", "push_filter", "drop_unused_left_join", "swap_sides"],
97
+ # join statements made candidates for the benchmark, heaviest measured first (0: every one with a variant)
98
+ "max_candidates": 0,
99
+ }
100
+ AGENT_SIGNALS = ("joined_side_unbounded", "filter_after_join", "join_for_one_column", "big_table_on_build_side",
101
+ "aggregate_after_join", "unused_left_join")
102
+
103
+ TIME_TYPE = re.compile(r"date|time", re.I)
104
+ AGG_FUNCS = (exp.AggFunc,)
105
+
106
+
107
+ def settings_of(config: dict | None) -> dict:
108
+ """The `[joins]` table of codecop.toml over the defaults. A value of the wrong kind is refused."""
109
+ out = copy.deepcopy(DEFAULTS)
110
+ for key, default in DEFAULTS.items():
111
+ value = (config or {}).get(key)
112
+ if value is None:
113
+ continue
114
+ if isinstance(default, bool):
115
+ if not isinstance(value, bool):
116
+ raise ValueError(f"joins.{key} must be true or false.")
117
+ elif isinstance(default, dict):
118
+ if not isinstance(value, dict) or any(e not in ENGINES or not isinstance(v, list) or any(s not in SIGNALS for s in v)
119
+ for e, v in value.items()):
120
+ raise ValueError(f"joins.{key} must map an engine ({', '.join(ENGINES)}) to a list of: {', '.join(SIGNALS)}.")
121
+ value = {**default, **value}
122
+ elif isinstance(default, list):
123
+ allowed = ENGINES if key == "engine_applies_implied" else VARIANT_KINDS
124
+ if not isinstance(value, list) or any(v not in allowed for v in value):
125
+ raise ValueError(f"joins.{key} must be a list of: {', '.join(allowed)}.")
126
+ elif isinstance(default, str):
127
+ if not isinstance(value, str):
128
+ raise ValueError(f"joins.{key} must be a regular expression.")
129
+ try:
130
+ re.compile(value)
131
+ except re.error as e:
132
+ raise ValueError(f"joins.{key} is not a regular expression: {e}") from None
133
+ elif isinstance(value, bool) or not isinstance(value, (int, float)) or value < 0:
134
+ raise ValueError(f"joins.{key} must be a number of zero or more.")
135
+ out[key] = value
136
+ return out
137
+
138
+
139
+ # ---- what is known about each table ----------------------------------------------------------------------------------
140
+
141
+ def _short(name: str) -> str:
142
+ return str(name or "").replace('"', "").replace("`", "").split(".")[-1].lower()
143
+
144
+
145
+ def _words(text: str) -> list[str]:
146
+ return re.findall(r"[A-Za-z_][\w]*", text or "")
147
+
148
+
149
+ class Book:
150
+ """short table name -> {columns: {name: type}, key: [cols], partition: [cols], indexes: [[cols]], unique: [[cols]],
151
+ rows, bytes, engine, source}. From the inventory's definitions; the real catalog's rows, key and columns win."""
152
+
153
+ def __init__(self, inventory: dict | None, facts=None, engine: str = ""):
154
+ self.tables: dict[str, dict] = {}
155
+ for t in (inventory or {}).get("tables") or []:
156
+ if t.get("test_only") or str(t.get("name", "")).startswith("?"):
157
+ continue
158
+ if engine == "clickhouse" and not t.get("engine") or engine == "postgres" and t.get("engine"):
159
+ continue
160
+ name = _short(t["name"])
161
+ cols = {c["name"]: str(c.get("type") or "") for c in t.get("columns") or [] if c.get("name")}
162
+ from .access import key_parts
163
+ # ClickHouse: the sorting key is the primary key when ORDER BY is not written (or was not read)
164
+ key = [w for part in key_parts(t.get("order_by") or "") for w in _words(part) if not cols or w in cols] or \
165
+ ([w for w in _words(t.get("primary_key") or "") if w in cols] if t.get("engine") else [])
166
+ part = [w for w in _words(t.get("partition_by") or "") if not cols or w in cols]
167
+ indexes = [list(ix.get("columns") or []) for ix in t.get("indexes") or [] if ix.get("columns")]
168
+ unique = [list(ix.get("columns") or []) for ix in t.get("indexes") or [] if ix.get("unique") or ix.get("primary")]
169
+ if t.get("primary_key") and not t.get("engine"):
170
+ pk = [w for w in _words(t["primary_key"]) if not cols or w in cols]
171
+ if pk and pk not in unique:
172
+ unique.append(pk)
173
+ if pk and pk not in indexes:
174
+ indexes.append(pk)
175
+ entry = {"name": t["name"], "columns": cols, "key": key, "partition": part, "indexes": indexes, "unique": unique,
176
+ "rows": None, "bytes": None, "engine": t.get("engine") or "", "source": "repository"}
177
+ if name not in self.tables or len(cols) > len(self.tables[name]["columns"]):
178
+ self.tables[name] = entry
179
+ if facts and engine:
180
+ for name, t in (facts.tables(engine) or {}).items():
181
+ short = _short(name)
182
+ cols = {c["name"]: str(c.get("type") or "") for c in t.get("columns") or [] if c.get("name")}
183
+ key = [w for w in _words(t.get("sorting_key") or "") if not cols or w in cols]
184
+ part = [c["name"] for c in t.get("columns") or [] if c.get("in_partition_key")] or \
185
+ [w for w in _words(t.get("partition_key") or "") if not cols or w in cols]
186
+ old = self.tables.get(short) or {}
187
+ indexes = [list(ix.get("columns") or []) for ix in t.get("indexes") or [] if ix.get("columns")] or old.get("indexes") or []
188
+ unique = [list(ix.get("columns") or []) for ix in t.get("indexes") or [] if ix.get("unique") or ix.get("primary")] \
189
+ or old.get("unique") or []
190
+ self.tables[short] = {"name": name, "columns": cols or old.get("columns") or {}, "key": key or old.get("key") or [],
191
+ "partition": part or old.get("partition") or [], "indexes": indexes, "unique": unique,
192
+ "rows": int(t["rows"]) if t.get("rows") is not None else None,
193
+ "bytes": int(t.get("bytes_on_disk") or 0) or None,
194
+ "engine": t.get("engine") or old.get("engine") or "", "source": "real catalog"}
195
+
196
+ def get(self, name: str) -> dict | None:
197
+ return self.tables.get(_short(name))
198
+
199
+
200
+ # ---- the parsed statement ---------------------------------------------------------------------------------------------
201
+
202
+ def _conjuncts(node: exp.Expression | None) -> list[exp.Expression]:
203
+ if node is None:
204
+ return []
205
+ if isinstance(node, (exp.Where, exp.Having, exp.PreWhere)):
206
+ node = node.this
207
+ while isinstance(node, exp.Paren):
208
+ node = node.this
209
+ if isinstance(node, exp.And):
210
+ return _conjuncts(node.left) + _conjuncts(node.right)
211
+ return [node]
212
+
213
+
214
+ def _hole(node: exp.Expression) -> bool:
215
+ return any(re.fullmatch(r"__qp\d+__", c.name or "") for c in node.find_all(exp.Column, exp.Identifier) if isinstance(c, (exp.Column, exp.Identifier)))
216
+
217
+
218
+ def _own_select(node: exp.Expression) -> exp.Select | None:
219
+ return node.find_ancestor(exp.Select)
220
+
221
+
222
+ OPS = ((exp.EQ, "eq"), (exp.NullSafeEQ, "eq"), (exp.In, "in"), (exp.Between, "range"), (exp.GT, "range"), (exp.GTE, "range"),
223
+ (exp.LT, "range"), (exp.LTE, "range"), (exp.Like, "like"), (exp.ILike, "like"))
224
+
225
+
226
+ def _op(node: exp.Expression) -> str | None:
227
+ return next((name for cls, name in OPS if isinstance(node, cls)), None)
228
+
229
+
230
+ class Side:
231
+ """One source of a SELECT that joins: a table, a subquery or a CTE."""
232
+
233
+ def __init__(self, node: exp.Expression, ctes: dict[str, exp.Expression], book: Book, holes: list[str]):
234
+ self.node = node
235
+ self.alias = ""
236
+ self.kind = "table"
237
+ self.final = False
238
+ self.query: exp.Expression | None = None
239
+ self.table = ""
240
+ if isinstance(node, exp.Final):
241
+ self.final = True
242
+ node = node.this
243
+ self.alias = (node.alias_or_name or "") if hasattr(node, "alias_or_name") else ""
244
+ if isinstance(node, exp.Table):
245
+ if isinstance(node.this, (exp.Anonymous, exp.Func)) and not isinstance(node.this, exp.Identifier):
246
+ self.kind = "function"
247
+ self.alias = node.alias or "?"
248
+ elif node.name in ctes and not node.db:
249
+ self.kind = "cte"
250
+ self.query = ctes[node.name]
251
+ self.alias = node.alias or node.name
252
+ else:
253
+ self.table = sqlinfo.restore(".".join(p for p in (node.db, node.name) if p), holes)
254
+ self.alias = node.alias or node.name
255
+ elif isinstance(node, exp.Subquery):
256
+ self.kind = "subquery"
257
+ self.query = node.this
258
+ self.alias = node.alias or "?"
259
+ else:
260
+ self.kind = "other"
261
+ self.base: list[str] = [] # tables read inside (a table side: itself)
262
+ self.outputs: dict[str, dict] = {} # derived side: output name -> {base: column or None, aggregate: bool}
263
+ self.bodies: list[exp.Expression] = [] # the side's query and every CTE it reads, transitively
264
+ if self.table:
265
+ self.base = [self.table]
266
+ elif self.query is not None:
267
+ todo, names = [self.query], set()
268
+ while todo:
269
+ q = todo.pop()
270
+ if any(q is b for b in self.bodies):
271
+ continue
272
+ self.bodies.append(q)
273
+ for t in q.find_all(exp.Table):
274
+ if t.name in ctes and not t.db and t.name not in names:
275
+ names.add(t.name)
276
+ todo.append(ctes[t.name])
277
+ seen = []
278
+ for q in self.bodies:
279
+ for t in q.find_all(exp.Table):
280
+ if t.name and not (t.name in ctes and not t.db) and not isinstance(t.this, (exp.Anonymous, exp.Func)):
281
+ n = sqlinfo.restore(".".join(p for p in (t.db, t.name) if p), holes)
282
+ if n not in seen:
283
+ seen.append(n)
284
+ self.base = seen
285
+ first = self.query
286
+ while isinstance(first, (exp.Union, exp.Subquery)):
287
+ first = first.this if isinstance(first, exp.Subquery) else first.left
288
+ if isinstance(first, exp.Select):
289
+ aggregated = bool(first.args.get("group")) or any(p.find(*AGG_FUNCS) for p in first.expressions)
290
+ for p in first.expressions:
291
+ inner = p.this if isinstance(p, exp.Alias) else p
292
+ name = p.alias_or_name
293
+ if isinstance(inner, exp.Star):
294
+ self.outputs["*"] = {"base": None, "aggregate": False}
295
+ continue
296
+ self.outputs[name] = {"base": inner.name if isinstance(inner, exp.Column) else None,
297
+ "aggregate": bool(inner.find(*AGG_FUNCS)) or (aggregated and not isinstance(inner, exp.Column))}
298
+ self.columns: dict[str, str] = {}
299
+ for b in self.base:
300
+ for c, t in ((book.get(b) or {}).get("columns") or {}).items():
301
+ self.columns.setdefault(c, t)
302
+
303
+ def has_column(self, name: str) -> bool | None:
304
+ """True / False when known, None when this side's columns are not known."""
305
+ if self.kind in ("subquery", "cte"):
306
+ if "*" in self.outputs:
307
+ return name in self.columns if self.columns else None
308
+ return name in self.outputs if self.outputs else None
309
+ if self.kind == "function":
310
+ return None
311
+ return name in self.columns if self.columns else None
312
+
313
+ def base_column(self, name: str) -> str | None:
314
+ """The table column an output name of this side stands for (itself for a table side)."""
315
+ if self.kind == "table":
316
+ return name
317
+ o = self.outputs.get(name)
318
+ if o is not None:
319
+ return o["base"]
320
+ return name if "*" in self.outputs else None
321
+
322
+ def inner_selects(self) -> list[exp.Select]:
323
+ return [s for q in self.bodies for s in q.find_all(exp.Select)]
324
+
325
+
326
+ class Scope:
327
+ """A SELECT with at least one JOIN: its sides and which side each column belongs to."""
328
+
329
+ def __init__(self, select: exp.Select, ctes: dict[str, exp.Expression], book: Book, holes: list[str], engine: str):
330
+ self.select, self.engine, self.book = select, engine, book
331
+ source = select.args.get("from") or select.args.get("from_")
332
+ self.sides = [Side(source.this, ctes, book, holes)]
333
+ self.joins: list[exp.Join] = []
334
+ for j in select.args.get("joins") or []:
335
+ if (j.args.get("kind") or "").upper() == "ARRAY" or isinstance(j.this, (exp.Column, exp.Unnest, exp.Lateral)):
336
+ continue # ARRAY JOIN, UNNEST, LATERAL: not a second source
337
+ self.sides.append(Side(j.this, ctes, book, holes))
338
+ self.joins.append(j)
339
+ self.by_alias = {}
340
+ for i, s in enumerate(self.sides):
341
+ for name in {s.alias, s.alias.lower(), s.table, _short(s.table)} - {""}:
342
+ self.by_alias.setdefault(name, i)
343
+ aliases = [s.alias.lower() for s in self.sides]
344
+ self.duplicate_alias = len(aliases) != len(set(aliases))
345
+ self.holes = holes
346
+
347
+ def hole_texts(self, node: exp.Expression | None) -> list[str]:
348
+ """The run-time parts inside `node`, as the code wrote them."""
349
+ if node is None:
350
+ return []
351
+ out = []
352
+ for c in node.find_all(exp.Column, exp.Identifier):
353
+ m = re.fullmatch(r"__qp(\d+)__", c.name or "")
354
+ if m and int(m.group(1)) < len(self.holes):
355
+ out.append(self.holes[int(m.group(1))])
356
+ return out
357
+
358
+ def mentions(self, k: int) -> bool:
359
+ """A run-time part of this SELECT names side `k` (`«if(x): AND o.start_time >= …»`): it may read or bound it."""
360
+ s = self.sides[k]
361
+ names = {n for n in (s.alias, _short(s.table)) if n and n != "?"}
362
+ texts = self.hole_texts(self.select)
363
+ return any(re.search(rf"(?<![\w.]){re.escape(n)}\s*\.", t) for n in names for t in texts)
364
+
365
+ def select_hidden(self) -> bool:
366
+ return any(self.hole_texts(p) for p in self.select.expressions)
367
+
368
+ def side_of(self, col: exp.Column) -> int | None:
369
+ q = col.table
370
+ if q:
371
+ return self.by_alias.get(q, self.by_alias.get(q.lower()))
372
+ has = [s.has_column(col.name) for s in self.sides]
373
+ yes = [i for i, h in enumerate(has) if h]
374
+ if len(yes) == 1:
375
+ return yes[0]
376
+ if len(yes) > 1:
377
+ return yes[0] if self.engine == "clickhouse" else None # ClickHouse reads an unqualified shared name from the left
378
+ unknown = [i for i, h in enumerate(has) if h is None]
379
+ return unknown[0] if len(unknown) == 1 else None
380
+
381
+ def own_columns(self, node: exp.Expression) -> list[exp.Column]:
382
+ """Columns of this scope inside `node`: those whose SELECT is this one, plus correlated references to its sides."""
383
+ out = []
384
+ for c in node.find_all(exp.Column):
385
+ if re.fullmatch(r"__qp\d+__|__p_\w+__", c.name or ""):
386
+ continue
387
+ sel = _own_select(c)
388
+ if sel is self.select or (c.table and c.table in self.by_alias and sel is not None and self.select in [a for a in _ancestors(sel)]):
389
+ out.append(c)
390
+ return out
391
+
392
+
393
+ def _ancestors(node: exp.Expression):
394
+ p = node.parent
395
+ while p is not None:
396
+ yield p
397
+ p = p.parent
398
+
399
+
400
+ def _dim(name: str, ctype: str, side_key: set[str], settings: dict) -> list[str]:
401
+ out = []
402
+ if re.search(settings["tenant_columns"], name or "", re.I):
403
+ out.append("tenant")
404
+ if (TIME_TYPE.search(ctype or "") or (not ctype and re.search(settings["time_columns"], name or "", re.I))) \
405
+ and not re.search(settings["not_time_columns"], name or "", re.I):
406
+ out.append("time")
407
+ if name in side_key:
408
+ out.append("key")
409
+ return out
410
+
411
+
412
+ def _side_key(side: Side, book: Book, engine: str) -> tuple[list[str], list[str], list[list[str]]]:
413
+ """(sorting key, partition key, index column lists) of the side's base tables, together."""
414
+ key, part, idx = [], [], []
415
+ for b in side.base:
416
+ t = book.get(b) or {}
417
+ key += [c for c in t.get("key") or [] if c not in key]
418
+ part += [c for c in t.get("partition") or [] if c not in part]
419
+ idx += [list(i) for i in t.get("indexes") or []]
420
+ return key, part, idx
421
+
422
+
423
+ def _keyed_columns(side: Side, book: Book, engine: str) -> set[str]:
424
+ """Columns a bound on which narrows what the engine reads of this side: the sorting key and partition key
425
+ (ClickHouse), the leading column of an index and the partition key (PostgreSQL)."""
426
+ key, part, idx = _side_key(side, book, engine)
427
+ if engine == "clickhouse":
428
+ return set(key) | set(part)
429
+ return {i[0] for i in idx if i} | set(part)
430
+
431
+
432
+ def _constant(node: exp.Expression, scope: Scope) -> bool:
433
+ """No column of this scope's sides in it: a literal, a parameter, a function of them, a subquery of its own."""
434
+ if node is None:
435
+ return False
436
+ for c in scope.own_columns(node):
437
+ if scope.side_of(c) is not None or not c.table:
438
+ return False
439
+ return True
440
+
441
+
442
+ def _filters_in(conj: exp.Expression, scope: Scope) -> list[tuple[int, str, str]]:
443
+ """(side, column, op) for a conjunct that compares one side's column with something constant."""
444
+ op = _op(conj)
445
+ if op is None:
446
+ if isinstance(conj, (exp.Not,)) or conj.find(exp.Or):
447
+ return []
448
+ if isinstance(conj, exp.Is) or isinstance(conj, exp.Anonymous) or isinstance(conj, exp.Func):
449
+ op = "other"
450
+ else:
451
+ return []
452
+ target = conj.this
453
+ if op == "in":
454
+ other_ok = True # IN (list) or IN (subquery of its own)
455
+ for q in conj.args.get("query") and [conj.args["query"]] or []:
456
+ other_ok = other_ok and _constant(q, scope)
457
+ for e in conj.expressions:
458
+ other_ok = other_ok and _constant(e, scope)
459
+ elif op == "range" and isinstance(conj, exp.Between):
460
+ other_ok = _constant(conj.args.get("low"), scope) and _constant(conj.args.get("high"), scope)
461
+ elif op == "other":
462
+ cols = scope.own_columns(conj)
463
+ sides = {scope.side_of(c) for c in cols}
464
+ if len(sides) == 1 and None not in sides:
465
+ return [(next(iter(sides)), c.name, "other") for c in cols]
466
+ return []
467
+ else:
468
+ a, b = conj.this, conj.expression
469
+ if _constant(b, scope):
470
+ target, other_ok = a, True
471
+ elif _constant(a, scope):
472
+ target, other_ok = b, True
473
+ else:
474
+ other_ok = False
475
+ if not other_ok or target is None:
476
+ return []
477
+ cols = scope.own_columns(target)
478
+ sides = {scope.side_of(c) for c in cols}
479
+ if len(sides) != 1 or None in sides:
480
+ return []
481
+ wrapped = not isinstance(target, exp.Column)
482
+ return [(next(iter(sides)), c.name, op if not wrapped or op == "range" else "other") for c in cols]
483
+
484
+
485
+ def _pairs_in(conj: exp.Expression, scope: Scope) -> list[tuple[int, str, int, str]]:
486
+ """(side, column, side, column) for an equality between two sides' bare columns."""
487
+ if not isinstance(conj, (exp.EQ, exp.NullSafeEQ)):
488
+ return []
489
+ a, b = conj.this, conj.expression
490
+ if isinstance(a, exp.Column) and isinstance(b, exp.Column):
491
+ sa, sb = scope.side_of(a), scope.side_of(b)
492
+ if sa is not None and sb is not None and sa != sb:
493
+ return [(sa, a.name, sb, b.name)]
494
+ return []
495
+
496
+
497
+
498
+
499
+ def _inner_filters(side: Side, settings: dict) -> tuple[list[dict], bool]:
500
+ """Filters inside a subquery or CTE side, on its base tables' columns: [{column, op}], and whether a run-time part sits
501
+ in a clause that could hold more."""
502
+ out, hidden = [], False
503
+ for sel in side.inner_selects():
504
+ for clause in (sel.args.get("where"), sel.args.get("prewhere"), sel.args.get("having")):
505
+ if clause is None:
506
+ continue
507
+ if _hole(clause):
508
+ hidden = True
509
+ for conj in _conjuncts(clause):
510
+ op = _op(conj)
511
+ if op is None:
512
+ continue
513
+ if op == "in":
514
+ target = conj.this
515
+ elif isinstance(conj, exp.Between):
516
+ target = conj.this
517
+ else:
518
+ a, b = conj.this, conj.expression
519
+ target = a if not b.find(exp.Column) or _all_holes(b) else b if not a.find(exp.Column) else None
520
+ if target is None:
521
+ # col >= other.col (a correlated or cross-table range) still bounds nothing from constants
522
+ continue
523
+ for c in target.find_all(exp.Column) if target is not None else []:
524
+ if not re.fullmatch(r"__qp\d+__", c.name or ""):
525
+ out.append({"column": c.name, "op": op if isinstance(target, exp.Column) or op == "range" else "other"})
526
+ return out, hidden
527
+
528
+
529
+ def _all_holes(node: exp.Expression) -> bool:
530
+ cols = list(node.find_all(exp.Column))
531
+ return bool(cols) and all(re.fullmatch(r"__qp\d+__|__p_\w+__", c.name or "") for c in cols)
532
+
533
+
534
+ def _used_columns(scope: Scope, skip_join: int) -> tuple[dict[int, set[str]], bool]:
535
+ """Columns of each side the statement reads outside the join condition of join `skip_join` (1-based side index):
536
+ select list, WHERE, GROUP BY, ORDER BY, HAVING, QUALIFY and the other joins. `star`: a bare * reads every side."""
537
+ used: dict[int, set[str]] = defaultdict(set)
538
+ star = False
539
+ sel = scope.select
540
+ parts: list[exp.Expression] = list(sel.expressions)
541
+ for key in ("where", "prewhere", "group", "having", "order", "qualify", "distinct", "limit"):
542
+ if sel.args.get(key) is not None:
543
+ parts.append(sel.args[key])
544
+ for i, j in enumerate(scope.joins, start=1):
545
+ if i != skip_join:
546
+ for key in ("on", "using"):
547
+ v = j.args.get(key)
548
+ if isinstance(v, list):
549
+ parts.extend(v)
550
+ elif v is not None:
551
+ parts.append(v)
552
+ for p in sel.expressions:
553
+ if isinstance(p, exp.Star) or (isinstance(p, exp.Column) and isinstance(p.this, exp.Star) and not p.table):
554
+ star = True
555
+ elif isinstance(p, exp.Column) and isinstance(p.this, exp.Star):
556
+ s = scope.by_alias.get(p.table)
557
+ if s is not None:
558
+ used[s].add("*")
559
+ for part in parts:
560
+ if isinstance(part, exp.Identifier): # USING (col) of another join: that column on both sides it joins
561
+ for s in range(len(scope.sides)):
562
+ if scope.sides[s].has_column(part.name):
563
+ used[s].add(part.name)
564
+ continue
565
+ for c in scope.own_columns(part):
566
+ if not c.table and c.name in scope.by_alias and scope.sides[scope.by_alias[c.name]].alias == c.name:
567
+ used[scope.by_alias[c.name]].add("*") # the alias as a whole row (`fav IS DISTINCT FROM NULL`)
568
+ continue
569
+ s = scope.side_of(c)
570
+ if s is not None:
571
+ used[s].add(c.name)
572
+ elif not c.table and c.name not in {p.alias_or_name for p in sel.expressions if isinstance(p, exp.Alias)}:
573
+ used[-1].add(c.name) # unqualified and not placed: any side whose columns are not known may own it
574
+ if s is None and not c.table:
575
+ for k, side in enumerate(scope.sides): # an output alias of the select list, or a column nobody owns
576
+ if side.has_column(c.name) is not False and side.kind != "table":
577
+ used[k].add(c.name)
578
+ return used, star
579
+
580
+
581
+ def _aggregated(sel: exp.Select) -> bool:
582
+ return bool(sel.args.get("group")) or any(p.find(*AGG_FUNCS) for p in sel.expressions)
583
+
584
+
585
+ def _unique_on(side: Side, cols: set[str], book: Book, strictness: str) -> str | None:
586
+ """How the side is known to hold at most one row per value of `cols` (the join columns), or None."""
587
+ if not cols:
588
+ return None
589
+ if strictness == "ANY":
590
+ return "ANY strictness: at most one row is joined"
591
+ if side.kind == "table":
592
+ t = book.get(side.table) or {}
593
+ for u in t.get("unique") or []:
594
+ if u and set(u) <= cols:
595
+ return f"unique index on ({', '.join(u)})"
596
+ return None
597
+ first = side.query
598
+ while isinstance(first, exp.Subquery):
599
+ first = first.this
600
+ if not isinstance(first, exp.Select):
601
+ return None
602
+ outs = {name: o["base"] or name for name, o in side.outputs.items()}
603
+ group = first.args.get("group")
604
+ if group is not None and group.expressions:
605
+ keys = {g.name for g in group.expressions if isinstance(g, exp.Column)}
606
+ if len(keys) == len(group.expressions):
607
+ mapped = {name for name, base in outs.items() if base in keys and name in cols}
608
+ if mapped and {outs.get(c, c) for c in cols} >= keys:
609
+ return f"GROUP BY ({', '.join(sorted(keys))}) inside the subquery"
610
+ sql = first.sql(dialect="clickhouse")
611
+ m = re.search(r"\bLIMIT\s+1\s+BY\s+([\w\s,.]+?)(?:\s+LIMIT|\s+SETTINGS|$)", sql, re.I)
612
+ if m:
613
+ keys = {w.split(".")[-1].strip() for w in m.group(1).split(",")}
614
+ if keys and {outs.get(c, c) for c in cols} >= keys:
615
+ return f"LIMIT 1 BY ({', '.join(sorted(keys))}) inside the subquery"
616
+ return None
617
+
618
+
619
+ def _rows(side: Side, book: Book) -> tuple[int | None, str]:
620
+ if side.kind != "table":
621
+ return None, ""
622
+ t = book.get(side.table) or {}
623
+ if t.get("rows") is not None:
624
+ return t["rows"], t.get("source") or ""
625
+ return None, ""
626
+
627
+
628
+ def analyze(sql: str, engine: str, book: Book, settings: dict | None = None) -> list[dict]:
629
+ """The facts of every JOIN clause in a statement, each with its signals (before muting). Empty when it does not
630
+ parse or does not join."""
631
+ settings = settings or settings_of(None)
632
+ tree, holes = sqlinfo.parse_tree(sql or "", engine)
633
+ if tree is None:
634
+ return []
635
+ ctes = {c.alias_or_name: c.this for c in tree.find_all(exp.CTE)}
636
+ out = []
637
+ for n, sel in enumerate(s for s in tree.find_all(exp.Select)):
638
+ if not sel.args.get("joins") or not (sel.args.get("from") or sel.args.get("from_")):
639
+ continue
640
+ scope = Scope(sel, ctes, book, holes, engine)
641
+ if len(scope.sides) < 2:
642
+ continue
643
+ out.extend(_scope_facts(scope, n, tree, holes, settings))
644
+ return out
645
+
646
+
647
+ def _side_facts(scope: Scope, i: int, filters: list[dict], used: set[str], book: Book, engine: str) -> dict:
648
+ s = scope.sides[i]
649
+ key, part, idx = _side_key(s, book, engine)
650
+ rows, rows_from = _rows(s, book)
651
+ return {"alias": s.alias, "kind": s.kind, "tables": s.base, "final": s.final, "rows": rows, "rows_from": rows_from,
652
+ "key": key, "partition": part, **({"indexes": idx} if engine == "postgres" else {}),
653
+ "filters": filters, "used": sorted(used)}
654
+
655
+
656
+ def _scope_facts(scope: Scope, n: int, tree: exp.Expression, holes: list[str], settings: dict) -> list[dict]:
657
+ engine, book = scope.engine, scope.book
658
+ sel = scope.select
659
+ where = [*(_conjuncts(sel.args.get("where"))), *(_conjuncts(sel.args.get("prewhere")))]
660
+ where_hidden = any(_hole(c) for c in where)
661
+ # filters per side, from the WHERE, from each join's ON and from inside a derived side
662
+ filt: dict[int, list[dict]] = defaultdict(list)
663
+ pairs: list[tuple[int, str, int, str, int]] = [] # (side, col, side, col, join index or 0 for WHERE)
664
+ for conj in where:
665
+ for s, col, op in _filters_in(conj, scope):
666
+ filt[s].append({"column": col, "op": op, "from": "where"})
667
+ for p in _pairs_in(conj, scope):
668
+ pairs.append((*p, 0))
669
+ on_hidden: dict[int, bool] = {}
670
+ for k, j in enumerate(scope.joins, start=1):
671
+ on = j.args.get("on")
672
+ on_hidden[k] = bool(on is not None and _hole(on))
673
+ for conj in _conjuncts(on):
674
+ for s, col, op in _filters_in(conj, scope):
675
+ filt[s].append({"column": col, "op": op, "from": "on"})
676
+ for p in _pairs_in(conj, scope):
677
+ pairs.append((*p, k))
678
+ for ident in j.args.get("using") or []:
679
+ name = ident.name if hasattr(ident, "name") else str(ident)
680
+ left = next((i for i in range(k) if scope.sides[i].has_column(name) is not False), 0)
681
+ pairs.append((left, name, k, name, k))
682
+ inner_hidden: dict[int, bool] = {}
683
+ for i, s in enumerate(scope.sides):
684
+ got, hidden = _inner_filters(s, settings)
685
+ inner_hidden[i] = hidden
686
+ for f in got:
687
+ filt[i].append({**f, "from": "inner"})
688
+ # each filter's dimensions on its side
689
+ for i, s in enumerate(scope.sides):
690
+ keyed = _keyed_columns(s, book, engine)
691
+ for f in filt[i]:
692
+ base = s.base_column(f["column"]) if f["from"] != "inner" else f["column"]
693
+ f["dims"] = _dim(base or f["column"], s.columns.get(base or "", ""), keyed, settings)
694
+ aggregate = _aggregated(sel)
695
+ facts = []
696
+ for k, j in enumerate(scope.joins, start=1):
697
+ side = (j.args.get("side") or "").upper()
698
+ kind = (j.args.get("kind") or "").upper()
699
+ strict = kind if kind in ("ANY", "ALL", "ASOF", "SEMI", "ANTI") else ""
700
+ jtype = side or ("CROSS" if kind == "CROSS" else "INNER" if kind in ("", "INNER", "ANY", "ALL", "ASOF") else kind)
701
+ if kind in ("SEMI", "ANTI") and not side:
702
+ jtype = kind
703
+ if not j.args.get("on") and not j.args.get("using") and kind != "CROSS" and not side and not any(p[4] == 0 for p in pairs):
704
+ jtype = "CROSS"
705
+ keys = [{"left_side": p[0], "left": p[1], "right_side": p[2], "right": p[3]} for p in pairs
706
+ if (p[4] == k) or (p[4] == 0 and k in (p[0], p[2]))]
707
+ joined_cols = {p["right"] if p["right_side"] == k else p["left"] for p in keys if k in (p["left_side"], p["right_side"])}
708
+ used, star = _used_columns(scope, k)
709
+ others = list(range(k)) # the sides before it
710
+ fact = {
711
+ "scope": n, "position": k, "type": jtype, "strictness": strict, "global": bool(j.args.get("global_") or j.args.get("global")),
712
+ "keys": [{"driving": p["left"] if p["right_side"] == k else p["right"], "joined": p["right"] if p["right_side"] == k else p["left"],
713
+ "driving_side": p["left_side"] if p["right_side"] == k else p["right_side"]} for p in keys],
714
+ "aggregate_after": aggregate, "star": star,
715
+ "driving": _side_facts(scope, 0, filt[0], used.get(0, set()) | (set() if not star else {"*"}), book, engine),
716
+ "joined": _side_facts(scope, k, filt[k], used.get(k, set()) | (set() if not star else {"*"}), book, engine),
717
+ "hidden": {"where": where_hidden, "on": on_hidden.get(k, False), "inner": inner_hidden.get(k, False),
718
+ "driving_inner": any(inner_hidden.get(i) for i in others),
719
+ "dropped": bool(tree.meta.get("dropped_holes")), "select": scope.select_hidden(), "names_joined": scope.mentions(k)},
720
+ "sides": len(scope.sides),
721
+ }
722
+ fact["signals"] = _signals(fact, scope, k, others, filt, pairs, used, star, joined_cols, j, settings)
723
+ facts.append(fact)
724
+ return facts
725
+
726
+
727
+ # ---- signals ----------------------------------------------------------------------------------------------------------
728
+
729
+ def _signals(fact: dict, scope: Scope, k: int, others: list[int], filt: dict, pairs: list, used: dict, star: bool,
730
+ joined_cols: set[str], j: exp.Join, settings: dict) -> list[dict]:
731
+ engine, book = scope.engine, scope.book
732
+ joined = scope.sides[k]
733
+ out: list[dict] = []
734
+ jtype, strict = fact["type"], fact["strictness"]
735
+ jf = filt[k]
736
+ hid = fact["hidden"]
737
+ uncertain_join = hid["on"] or hid["inner"] or hid["dropped"] or hid["names_joined"] or (hid["where"] and jtype in ("INNER", "CROSS"))
738
+ # what the statement reads of the joined side is not known: a run-time part names it, or builds the select list
739
+ use_unknown = hid["select"] or hid["names_joined"] or scope.duplicate_alias
740
+
741
+ # joined_side_unbounded: a tenant / time bound reaches the sides before it and not this one, whose key holds it; and,
742
+ # for an INNER join, the other way round (the driving side read whole while the joined side has the bound)
743
+ directions = [(k, others)] + ([(0, [k])] if jtype == "INNER" and k == 1 else [])
744
+ for target, sources in directions:
745
+ tside = scope.sides[target]
746
+ tkeyed = _keyed_columns(tside, book, engine)
747
+ tfilt = filt[target]
748
+ tcols = {p["joined"] if target == k else p["driving"] for p in fact["keys"]}
749
+ for dim in ("tenant", "time"):
750
+ bound = [(i, f) for i in sources for f in filt[i] if dim in f["dims"] and f["op"] != "other"]
751
+ hidden_bound = False
752
+ if not bound and target == k and dim == "time" and settings["hidden_driving_bound"] and (hid["where"] or hid["driving_inner"]):
753
+ hidden_bound = True # the driving side's WHERE has a run-time part, which may be its time bound
754
+ elif not bound:
755
+ continue
756
+ key_cols = sorted(c for c in tkeyed if dim in _dim(c, tside.columns.get(c, ""), set(), settings))
757
+ if not key_cols or any(dim in f["dims"] for f in tfilt):
758
+ continue
759
+ if engine == "postgres":
760
+ # an index that leads with the join columns serves the join row by row (nested loop): the bound is not needed
761
+ _, _, idx = _side_key(tside, book, engine)
762
+ if any(i and i[0] in tcols for i in idx):
763
+ continue
764
+ implied = []
765
+ for i, f in bound:
766
+ for p in fact["keys"]:
767
+ src_col, dst_col = (p["driving"], p["joined"]) if target == k else (p["joined"], p["driving"])
768
+ if (target == k and p["driving_side"] != i) or (target != k and i != k):
769
+ continue
770
+ src = scope.sides[i]
771
+ if src.base_column(src_col) in (f["column"], src.base_column(f["column"])) and \
772
+ (tside.base_column(dst_col) or dst_col) in key_cols:
773
+ implied.append({"source_side": i, "source_column": f["column"], "target_side": target,
774
+ "target_column": dst_col, "op": f["op"], "from": f["from"]})
775
+ # the bound is a WHERE / ON comparison the join condition carries over to a table side: ClickHouse applies it to
776
+ # that side by itself (measured on 24.8 and 25.8, INNER and LEFT JOIN: the same granules are read with and without)
777
+ applies = bool(implied) and tside.kind == "table" and all(x["from"] in ("where", "on") for x in implied) and \
778
+ {f["column"] for _, f in bound} <= {x["source_column"] for x in implied}
779
+ out.append({"signal": "joined_side_unbounded", "dim": dim, "uncertain": bool(uncertain_join or hidden_bound),
780
+ "evidence": {"side": "joined" if target == k else "driving", "engine_applies": applies,
781
+ "driving_filters": sorted({f["column"] for _, f in bound}) or ["(a run-time part)"],
782
+ "joined_key_columns": key_cols, "joined_tables": tside.base, "implied_by_join_key": implied,
783
+ "join_key_columns": sorted(tcols)}})
784
+ if True:
785
+ if engine == "clickhouse" and joined.kind == "table" and fact["keys"]:
786
+ t = book.get(joined.table) or {}
787
+ key = t.get("key") or []
788
+ lead = [c for c in key[:max(len(joined_cols), 1)]]
789
+ tenant_only = all("tenant" in _dim(c, joined.columns.get(c, ""), set(), settings) for c in lead)
790
+ if lead and set(lead) <= joined_cols and not any(f["column"] in lead for f in jf) and not tenant_only:
791
+ # the driving side is pinned to a few rows: an equality on a column of its own key that is not a tenant or a time
792
+ pinned = [f for i in others for f in filt[i] if f["op"] in ("eq", "in")
793
+ and ("key" in f["dims"] or re.search(settings["id_columns"], f["column"], re.I))
794
+ and not {"tenant", "time"} & set(f["dims"])]
795
+ # a pinned WHERE / ON column the condition equates with a key column: the engine carries that value over itself
796
+ carried = {p["joined"] for p in fact["keys"] for f in pinned
797
+ if f["from"] in ("where", "on") and p["driving"] == f["column"]}
798
+ if pinned:
799
+ out.append({"signal": "joined_side_unbounded", "dim": "join_key", "uncertain": bool(uncertain_join),
800
+ "evidence": {"side": "joined", "engine_applies": bool(carried) and set(lead) <= carried | {
801
+ c for c in lead if "tenant" in _dim(c, joined.columns.get(c, ""), set(), settings)},
802
+ "driving_filters": sorted({f["column"] for f in pinned}), "joined_key_columns": lead,
803
+ "joined_tables": joined.base, "implied_by_join_key": [],
804
+ "join_key_columns": sorted(joined_cols),
805
+ "note": "the joined table's sorting key is reached by the join condition only, and a hash join does not use it"}})
806
+
807
+ # filter_after_join: a WHERE filter on a subquery side's column, applied after the join
808
+ if joined.kind in ("subquery", "cte") or scope.sides[0].kind in ("subquery", "cte"):
809
+ for i in (0, k):
810
+ s = scope.sides[i]
811
+ if s.kind not in ("subquery", "cte"):
812
+ continue
813
+ inner_cols = {f["column"] for f in filt[i] if f["from"] == "inner"}
814
+ for f in filt[i]:
815
+ if f["from"] != "where" or f["op"] == "other":
816
+ continue
817
+ o = s.outputs.get(f["column"]) or ({"base": f["column"], "aggregate": False} if "*" in s.outputs else None)
818
+ if o is None or o["aggregate"] or not o["base"] or o["base"] in inner_cols:
819
+ continue
820
+ why = _push_blocked(s, i, k, jtype, scope)
821
+ out.append({"signal": "filter_after_join", "uncertain": False,
822
+ "evidence": {"side": "driving" if i == 0 else "joined", "column": f["column"], "base_column": o["base"],
823
+ "op": f["op"], "pushable": not why, "why_not": why or ""}})
824
+
825
+ # join_for_one_column / unused_left_join
826
+ # an INNER join's columns hold the driving side's values: reading them does not need the joined side (on a LEFT JOIN
827
+ # they are NULL where nothing matched, so `j.id IS NULL` does read it)
828
+ give = {c for c in used.get(k, set()) if c != "*" and not (jtype == "INNER" and c in joined_cols)}
829
+ # a column nobody could be sure of (unqualified, and the side's columns are not known) may be this side's
830
+ if any(joined.has_column(c) is not False for c in used.get(-1, set())):
831
+ use_unknown = True
832
+ if not star and not use_unknown and "*" not in used.get(k, set()) and jtype in ("INNER", "LEFT") and strict not in ("SEMI", "ANTI"):
833
+ rows, _ = _rows(joined, book)
834
+ own_bound = bool(jf)
835
+ # with no size known, "big" is a table this statement leaves unbounded whose definition keys it by time (a fact
836
+ # table): a side nothing describes (a CTE built elsewhere, a run-time name) is never called big
837
+ known = bool(joined.base) and all(book.get(b) for b in joined.base)
838
+ fact_like = known and any(
839
+ "time" in _dim(c, joined.columns.get(c, ""), set(), settings) for c in _keyed_columns(joined, book, engine))
840
+ # a subquery that aggregates a fact table makes one row per key over its whole window, bounded or not
841
+ aggregating = joined.kind in ("subquery", "cte") and any(o["aggregate"] for o in joined.outputs.values())
842
+ big = rows >= settings["big_table_rows"] if rows is not None else (fact_like and (not own_bound or aggregating))
843
+ if jtype == "LEFT" and not give:
844
+ unique = _unique_on(joined, joined_cols, book, strict)
845
+ out.append({"signal": "unused_left_join", "uncertain": bool(hid["where"] or hid["dropped"]),
846
+ "evidence": {"joined_tables": joined.base, "join_key_columns": sorted(joined_cols),
847
+ "unique_on_join_key": unique or "", "can_multiply_rows": not unique}})
848
+ elif len(give) <= settings["one_column_max"] and big and not (engine == "postgres" and settings["postgres_needs_size"] and rows is None):
849
+ in_where = {c for c in give if _only_in_where(c, k, scope)}
850
+ out.append({"signal": "join_for_one_column", "uncertain": False,
851
+ "evidence": {"joined_tables": joined.base, "columns": sorted(give), "as_filter_only": bool(give) and give == in_where or not give,
852
+ "rows": rows, "own_bound": own_bound, "join_key_columns": sorted(joined_cols)}})
853
+
854
+ # big_table_on_build_side (ClickHouse: the right side of a hash join is the one held in memory)
855
+ if engine == "clickhouse" and jtype in ("INNER", "LEFT", "CROSS") and strict != "ASOF":
856
+ left, right = scope.sides[0], joined
857
+ lr, _ = _rows(left, book)
858
+ rr, _ = _rows(right, book)
859
+ basis = ""
860
+ # sizes from the real catalog only: the statement's shape alone (a small subquery on the left) is not enough
861
+ if lr is not None and rr is not None and lr > 0 and rr >= lr * settings["build_side_ratio"]:
862
+ basis = "catalog rows"
863
+ if basis:
864
+ out.append({"signal": "big_table_on_build_side", "uncertain": False,
865
+ "evidence": {"left_rows": lr, "right_rows": rr, "basis": basis, "right_tables": right.base, "left_kind": left.kind}})
866
+
867
+ # aggregate_after_join: the aggregates read one side only; the other side gives only grouping keys
868
+ if fact["aggregate_after"] and jtype in ("INNER", "LEFT"):
869
+ agg_sides: set[int] = set()
870
+ for p in scope.select.expressions:
871
+ for a in p.find_all(*AGG_FUNCS):
872
+ for c in scope.own_columns(a):
873
+ s = scope.side_of(c)
874
+ if s is not None:
875
+ agg_sides.add(s)
876
+ driving = scope.sides[0]
877
+ driving_grouped = driving.kind in ("subquery", "cte") and any(o["aggregate"] for o in driving.outputs.values())
878
+ group = scope.select.args.get("group")
879
+ group_cols = {c.name for c in scope.own_columns(group)} if group is not None else set()
880
+ if agg_sides == {0} and not driving_grouped and give <= group_cols and not use_unknown:
881
+ rows, _ = _rows(joined, book)
882
+ if not (engine == "postgres" and settings["postgres_needs_size"] and rows is None):
883
+ out.append({"signal": "aggregate_after_join", "uncertain": False,
884
+ "evidence": {"aggregated_side": "driving" if 0 in agg_sides else "other", "joined_gives": sorted(give),
885
+ "joined_tables": joined.base}})
886
+ if not settings["keep_uncertain"]:
887
+ out = [s for s in out if not s.get("uncertain")]
888
+ return out
889
+
890
+
891
+ def _only_in_where(col: str, k: int, scope: Scope) -> bool:
892
+ sel = scope.select
893
+ for p in sel.expressions:
894
+ for c in scope.own_columns(p):
895
+ if c.name == col and scope.side_of(c) == k:
896
+ return False
897
+ for key in ("group", "order", "having"):
898
+ v = sel.args.get(key)
899
+ if v is not None and any(c.name == col and scope.side_of(c) == k for c in scope.own_columns(v)):
900
+ return False
901
+ return True
902
+
903
+
904
+ def _push_blocked(side: Side, i: int, k: int, jtype: str, scope: Scope) -> str:
905
+ """Why a WHERE filter on this subquery side can not be moved inside it with the same rows ("" when it can)."""
906
+ if i == k and jtype in ("LEFT", "FULL"):
907
+ return "the filtered side is the null side of an outer join"
908
+ if i == 0 and jtype in ("RIGHT", "FULL"):
909
+ return "the filtered side is the null side of an outer join"
910
+ q = side.query
911
+ while isinstance(q, exp.Subquery):
912
+ q = q.this
913
+ if not isinstance(q, exp.Select):
914
+ return "the subquery is a UNION"
915
+ if q.args.get("limit") is not None or q.args.get("offset") is not None:
916
+ return "the subquery has a LIMIT"
917
+ if re.search(r"\bLIMIT\s+\d+\s+BY\b", q.sql(dialect="clickhouse"), re.I):
918
+ return "the subquery has LIMIT BY"
919
+ if q.find(exp.Window):
920
+ return "the subquery has a window function"
921
+ if isinstance(q.args.get("distinct"), exp.Distinct) and q.args["distinct"].args.get("on"):
922
+ return "the subquery has DISTINCT ON"
923
+ if q.args.get("joins"):
924
+ return "the subquery joins: which table the column belongs to is not decided here"
925
+ if side.kind == "cte":
926
+ refs = sum(1 for t in scope.select.root().find_all(exp.Table) if t.name == side.alias or t.name == (side.node.name if isinstance(side.node, exp.Table) else ""))
927
+ if refs > 1:
928
+ return "the CTE is read more than once"
929
+ return ""
930
+
931
+
932
+ # ---- variants ---------------------------------------------------------------------------------------------------------
933
+
934
+ def _rebuild(tree: exp.Expression, holes: list[str], engine: str) -> str:
935
+ return sqlinfo.restore(tree.sql(dialect=engine or None), holes)
936
+
937
+
938
+ def variants(sql: str, engine: str, book: Book, facts: list[dict], settings: dict) -> list[dict]:
939
+ """Mechanical rewrites whose sameness follows from the statement and the keys: [{kind, rewrite, sql, setup_sql,
940
+ same_results, change, tradeoffs, signal, position, scope}]. None for a statement with run-time parts."""
941
+ tree0, holes = sqlinfo.parse_tree(sql or "", engine)
942
+ if tree0 is None or holes or sqlinfo.to_parsable(sql)[0] != sql:
943
+ return [] # a run-time part or driver placeholders: the benchmark could not run it as it is
944
+ wanted = set(settings["variants"])
945
+ out = []
946
+ for f in facts:
947
+ for sig in f["signals"]:
948
+ got = None
949
+ if sig["signal"] == "joined_side_unbounded" and sig["evidence"]["implied_by_join_key"] and "push_bound" in wanted:
950
+ got = _push_bound(tree0, engine, book, f, sig, holes, settings, sql)
951
+ elif sig["signal"] == "filter_after_join" and sig["evidence"]["pushable"] and "push_filter" in wanted:
952
+ got = _push_filter(tree0, engine, book, f, sig, holes, settings, sql)
953
+ elif sig["signal"] == "unused_left_join" and sig["evidence"]["unique_on_join_key"] and "drop_unused_left_join" in wanted:
954
+ got = _drop_join(tree0, engine, book, f, holes, settings)
955
+ elif sig["signal"] == "big_table_on_build_side" and f["type"] == "INNER" and f["sides"] == 2 and not f["star"] \
956
+ and not f["strictness"] and "swap_sides" in wanted:
957
+ got = _swap(tree0, engine, book, f, holes, settings)
958
+ if got and got["sql"] and not sqlinfo_same(got["sql"], sql) and all(not sqlinfo_same(got["sql"], v["sql"]) for v in out):
959
+ out.append({**got, "signal": sig["signal"], "scope": f["scope"], "position": f["position"]})
960
+ return out
961
+
962
+
963
+ def sqlinfo_same(a: str, b: str) -> bool:
964
+ return " ".join((a or "").split()).rstrip(";") == " ".join((b or "").split()).rstrip(";")
965
+
966
+
967
+ def _scope_of(tree: exp.Expression, n: int, engine: str, book: Book, holes: list[str], settings: dict) -> Scope | None:
968
+ ctes = {c.alias_or_name: c.this for c in tree.find_all(exp.CTE)}
969
+ sel = next((s for i, s in enumerate(tree.find_all(exp.Select)) if i == n), None)
970
+ if sel is None or not sel.args.get("joins"):
971
+ return None
972
+ return Scope(sel, ctes, book, holes, engine)
973
+
974
+
975
+ def _variant(kind: str, change: str, sql: str, tradeoffs: list[str]) -> dict:
976
+ return {"kind": "rewrite", "rewrite": kind, "sql": sql, "setup_sql": [], "same_results": True, "change": change,
977
+ "tradeoffs": tradeoffs, "source": "codecop"} # read as the same: "qopt" (written before the rename)
978
+
979
+
980
+ # Text splices. A variant that only adds a predicate is written into the original text, so everything else stays as the
981
+ # code sends it; the parser's own printing of a whole statement can change functions and quoting.
982
+ STOP = {"AND", "OR", "WHERE", "PREWHERE", "ON", "HAVING", "GROUP_BY", "ORDER_BY", "LIMIT", "SETTINGS", "UNION", "QUALIFY", "WINDOW",
983
+ "FORMAT", "SEMICOLON", "JOIN", "INNER", "LEFT", "RIGHT", "FULL", "CROSS", "USING", "EXCEPT", "INTERSECT", "OFFSET", "SELECT"}
984
+
985
+
986
+ def _tokens(sql: str, engine: str) -> list:
987
+ import sqlglot
988
+ return list(sqlglot.tokenize(sql, read=engine or None))
989
+
990
+
991
+ def _starts(node: exp.Expression) -> list[int]:
992
+ return [i.meta["start"] for i in node.find_all(exp.Identifier) if isinstance(i.meta.get("start"), int)]
993
+
994
+
995
+ def _span(toks: list, conj: exp.Expression) -> tuple[int, int] | None:
996
+ """Where a conjunct is in the text: from the boundary before its first identifier to the one after it."""
997
+ starts = _starts(conj)
998
+ if not starts:
999
+ return None
1000
+ first = min(starts)
1001
+ i = next((n for n, t in enumerate(toks) if t.start >= first), None)
1002
+ if i is None:
1003
+ return None
1004
+ depth, b = 0, i - 1
1005
+ while b >= 0:
1006
+ name = toks[b].token_type.name
1007
+ if name == "R_PAREN":
1008
+ depth += 1
1009
+ elif name == "L_PAREN":
1010
+ if depth == 0:
1011
+ break
1012
+ depth -= 1
1013
+ elif depth == 0 and name in STOP:
1014
+ break
1015
+ b -= 1
1016
+ begin = toks[b + 1].start
1017
+ depth, between, e = 0, False, i
1018
+ while e < len(toks):
1019
+ name = toks[e].token_type.name
1020
+ if name == "L_PAREN":
1021
+ depth += 1
1022
+ elif name == "R_PAREN":
1023
+ if depth == 0:
1024
+ break
1025
+ depth -= 1
1026
+ elif depth == 0 and name == "BETWEEN":
1027
+ between = True
1028
+ elif depth == 0 and name == "AND" and between:
1029
+ between = False
1030
+ elif depth == 0 and name in STOP:
1031
+ break
1032
+ e += 1
1033
+ finish = toks[e - 1].end + 1
1034
+ return (begin, finish) if begin < finish else None
1035
+
1036
+
1037
+ def _swap_columns(sql: str, span: tuple[int, int], conj: exp.Expression, swap) -> str | None:
1038
+ """The conjunct's text with each column `swap(column)` names replaced (None: left as it is)."""
1039
+ text = sql[span[0]:span[1]]
1040
+ edits = []
1041
+ for c in conj.find_all(exp.Column):
1042
+ new = swap(c)
1043
+ if new is None:
1044
+ continue
1045
+ ids = [x for x in (c.args.get("table"), c.this) if isinstance(x, exp.Identifier) and isinstance(x.meta.get("start"), int)]
1046
+ if not ids:
1047
+ return None
1048
+ a, b = min(x.meta["start"] for x in ids), max(x.meta["end"] for x in ids) + 1
1049
+ if c.this.quoted:
1050
+ b += 1
1051
+ if isinstance(c.args.get("table"), exp.Identifier) and c.args["table"].quoted:
1052
+ a -= 1
1053
+ edits.append((a - span[0], b - span[0], new))
1054
+ if not edits:
1055
+ return None
1056
+ for a, b, new in sorted(edits, reverse=True):
1057
+ text = text[:a] + new + text[b:]
1058
+ return text
1059
+
1060
+
1061
+ def _insert_point(toks: list, clause: exp.Expression, kinds: tuple[str, ...]) -> int | None:
1062
+ """The offset right after the keyword (WHERE, ON) that opens `clause`."""
1063
+ starts = _starts(clause)
1064
+ if not starts:
1065
+ return None
1066
+ first = min(starts)
1067
+ kw = [t for t in toks if t.token_type.name in kinds and t.end < first]
1068
+ return kw[-1].end + 1 if kw else None
1069
+
1070
+
1071
+ def _top_or(node: exp.Expression | None) -> bool:
1072
+ node = node.this if isinstance(node, (exp.Where, exp.Having, exp.PreWhere)) else node
1073
+ return isinstance(node, exp.Or)
1074
+
1075
+
1076
+ def _splice(sql: str, at: int, pred: str) -> str:
1077
+ return sql[:at] + " " + pred + " AND" + sql[at:]
1078
+
1079
+
1080
+ def _push_bound(tree0, engine, book, f, sig, holes, settings, sql="") -> dict | None:
1081
+ scope = _scope_of(tree0, f["scope"], engine, book, holes, settings)
1082
+ if scope is None or not sql:
1083
+ return None
1084
+ toks = _tokens(sql, engine)
1085
+ k = f["position"]
1086
+ join = scope.joins[k - 1]
1087
+ found: list[tuple[int, str]] = []
1088
+ for imp in sig["evidence"]["implied_by_join_key"]:
1089
+ s_i, t_i = imp["source_side"], imp["target_side"]
1090
+ src, tgt = scope.sides[s_i], scope.sides[t_i]
1091
+ if t_i == 0 and f["type"] != "INNER":
1092
+ continue # the preserved side of an outer join keeps its rows whatever the other side holds
1093
+ # the bound as written: a WHERE conjunct on the source side, or one of the source subquery's own WHERE / PREWHERE
1094
+ drive, swap = None, None
1095
+ for conj in [*(_conjuncts(scope.select.args.get("where"))), *(_conjuncts(scope.select.args.get("prewhere")))]:
1096
+ fs = _filters_in(conj, scope)
1097
+ if fs and all(s == s_i for s, _, _ in fs) and any(c == imp["source_column"] for _, c, _ in fs):
1098
+ drive, swap = conj, (lambda c, col=imp["source_column"]: c.name == col and scope.side_of(c) == s_i)
1099
+ break
1100
+ if drive is None and src.kind in ("subquery", "cte"):
1101
+ q = src.query
1102
+ while isinstance(q, exp.Subquery):
1103
+ q = q.this
1104
+ base = src.base_column(imp["source_column"])
1105
+ # every row the subquery returns passed its WHERE / PREWHERE (a LIMIT or GROUP BY after it keeps that true)
1106
+ if isinstance(q, exp.Select) and base and not q.args.get("joins"):
1107
+ for clause in (q.args.get("prewhere"), q.args.get("where")):
1108
+ if clause is None or _top_or(clause):
1109
+ continue
1110
+ for conj in _conjuncts(clause):
1111
+ cols = [c for c in conj.find_all(exp.Column) if not re.fullmatch(r"__qp\d+__", c.name or "")]
1112
+ if _op(conj) in ("eq", "in", "range") and cols and all(c.name == base for c in cols) and isinstance(conj.this, exp.Column):
1113
+ drive, swap = conj, (lambda c, col=base: c.name == col)
1114
+ break
1115
+ if drive is not None:
1116
+ break
1117
+ if drive is None:
1118
+ continue
1119
+ span = _span(toks, drive)
1120
+ if span is None:
1121
+ continue
1122
+ target = f"{tgt.alias}.{imp['target_column']}" if tgt.kind == "table" else (tgt.base_column(imp["target_column"]) or imp["target_column"])
1123
+ pred = _swap_columns(sql, span, drive, lambda c: target if swap(c) else None)
1124
+ if pred is None:
1125
+ continue
1126
+ if tgt.kind == "table" and (f["type"] == "INNER" or t_i == 0):
1127
+ clause, kinds = scope.select.args.get("where") or scope.select.args.get("prewhere"), ("WHERE", "PREWHERE")
1128
+ elif tgt.kind == "table" and f["type"] == "LEFT":
1129
+ clause, kinds = join.args.get("on"), ("ON",)
1130
+ elif tgt.kind in ("subquery", "cte"):
1131
+ q = tgt.query
1132
+ while isinstance(q, exp.Subquery):
1133
+ q = q.this
1134
+ if not isinstance(q, exp.Select) or _push_blocked_inner(q) or q.args.get("joins"):
1135
+ continue
1136
+ clause, kinds = q.args.get("where") or q.args.get("prewhere"), ("WHERE", "PREWHERE")
1137
+ else:
1138
+ continue
1139
+ if clause is None or _top_or(clause):
1140
+ continue
1141
+ at = _insert_point(toks, clause, kinds)
1142
+ if at is None:
1143
+ continue
1144
+ if pred not in [p for _, p in found]:
1145
+ found.append((at, pred))
1146
+ if not found:
1147
+ return None
1148
+ text = sql
1149
+ for at in sorted({a for a, _ in found}, reverse=True): # right to left: an earlier offset does not move
1150
+ text = _splice(text, at, " AND ".join(p for a, p in found if a == at))
1151
+ side = "joined" if sig["evidence"].get("side", "joined") == "joined" else "driving"
1152
+ return _variant("push_bound", f"The {('driving' if side == 'joined' else 'joined')} side's bound also reaches the {side} side "
1153
+ f"through the join key: {' AND '.join(p for _, p in found)}", text, ["code_change"])
1154
+
1155
+
1156
+ def _push_blocked_inner(q: exp.Select) -> str:
1157
+ if q.args.get("limit") is not None or q.find(exp.Window) or re.search(r"\bLIMIT\s+\d+\s+BY\b", q.sql(dialect="clickhouse"), re.I):
1158
+ return "limited"
1159
+ return ""
1160
+
1161
+
1162
+ def _push_filter(tree0, engine, book, f, sig, holes, settings, sql="") -> dict | None:
1163
+ scope = _scope_of(tree0, f["scope"], engine, book, holes, settings)
1164
+ if scope is None or not sql:
1165
+ return None
1166
+ toks = _tokens(sql, engine)
1167
+ ev = sig["evidence"]
1168
+ i = 0 if ev["side"] == "driving" else f["position"]
1169
+ q = scope.sides[i].query
1170
+ while isinstance(q, exp.Subquery):
1171
+ q = q.this
1172
+ if not isinstance(q, exp.Select) or q.args.get("where") is None or _top_or(q.args["where"]):
1173
+ return None
1174
+ group = q.args.get("group")
1175
+ if group is not None and ev["base_column"] not in {g.name for g in group.expressions if isinstance(g, exp.Column)}:
1176
+ return None
1177
+ conjs = [*(_conjuncts(scope.select.args.get("where"))), *(_conjuncts(scope.select.args.get("prewhere")))]
1178
+ for conj in conjs:
1179
+ fs = _filters_in(conj, scope)
1180
+ if not fs or not all(s == i and c == ev["column"] for s, c, _ in fs):
1181
+ continue
1182
+ span = _span(toks, conj)
1183
+ at = _insert_point(toks, q.args["where"], ("WHERE",))
1184
+ if span is None or at is None:
1185
+ return None
1186
+ pred = _swap_columns(sql, span, conj, lambda c: ev["base_column"] if c.name == ev["column"] and scope.side_of(c) == i else None)
1187
+ if pred is None:
1188
+ return None
1189
+ return _variant("push_filter", f"The filter {sql[span[0]:span[1]]} also applies inside the subquery, before the join",
1190
+ _splice(sql, at, pred), ["code_change"])
1191
+ return None
1192
+
1193
+
1194
+ def _drop_join(tree0, engine, book, f, holes, settings) -> dict | None:
1195
+ tree = tree0.copy()
1196
+ scope = _scope_of(tree, f["scope"], engine, book, holes, settings)
1197
+ if scope is None:
1198
+ return None
1199
+ join = scope.joins[f["position"] - 1]
1200
+ name = scope.sides[f["position"]].alias
1201
+ joins = [j for j in scope.select.args["joins"] if j is not join]
1202
+ scope.select.set("joins", joins or None)
1203
+ return _variant("drop_unused_left_join", f"The LEFT JOIN of {name} is removed: none of its columns is read, and it holds one row per join key",
1204
+ _rebuild(tree, holes, engine), ["code_change"])
1205
+
1206
+
1207
+ def _swap(tree0, engine, book, f, holes, settings) -> dict | None:
1208
+ tree = tree0.copy()
1209
+ scope = _scope_of(tree, f["scope"], engine, book, holes, settings)
1210
+ if scope is None or len(scope.sides) != 2:
1211
+ return None
1212
+ source = scope.select.args.get("from") or scope.select.args.get("from_")
1213
+ join = scope.joins[0]
1214
+ left, right = source.this.copy(), join.this.copy()
1215
+ source.set("this", right)
1216
+ join.set("this", left)
1217
+ return _variant("swap_sides", f"The two sides change places, so the smaller one ({scope.sides[0].alias}) is the hash table (the right side)",
1218
+ _rebuild(tree, holes, engine), ["code_change"])
1219
+
1220
+
1221
+ # ---- the whole inventory ----------------------------------------------------------------------------------------------
1222
+
1223
+ def tier_of(s: dict, engine: str, settings: dict) -> str:
1224
+ """`shown` (a finding; a mechanical variant is benchmarked), `agent` (in the rank prompt only) or `muted` (counted)."""
1225
+ name = s["signal"]
1226
+ shown = set(settings["shown"].get(engine) or [])
1227
+ agent = set(settings["agent"].get(engine) or [])
1228
+ if name == "joined_side_unbounded" and (s.get("evidence") or {}).get("engine_applies") and engine in settings["engine_applies_implied"]:
1229
+ return "muted"
1230
+ if name in shown and not (name == "unused_left_join" and settings["unused_left_join_needs_unique"]
1231
+ and (not (s.get("evidence") or {}).get("unique_on_join_key") or s.get("uncertain"))):
1232
+ return "shown"
1233
+ return "agent" if name in agent or name in shown else "muted"
1234
+
1235
+
1236
+ def _statements(inventory: dict, engine: str, observed: dict | None):
1237
+ """(id, sql, sql_from, located, site) for every SELECT that may join: call sites, and observed production statements."""
1238
+ from .observed import sql_from_of
1239
+ for c in inventory.get("call_sites") or []:
1240
+ if c.get("engine") != engine or c.get("statement") != "select" or not c.get("sql") or c.get("is_test"):
1241
+ continue
1242
+ if not re.search(r"\bJOIN\b", c["sql"], re.I) and not re.search(r"\bFROM\b[^()]*,", c["sql"], re.I):
1243
+ continue
1244
+ yield c["id"], c["sql"], sql_from_of({}, c), "site", c
1245
+ for cand in (observed or {}).get("candidates") or []:
1246
+ if (observed or {}).get("engine", engine) != engine or not re.search(r"\bJOIN\b", cand.get("baseline_sql") or "", re.I):
1247
+ continue
1248
+ yield cand["finding"], cand["baseline_sql"], "query_log", cand.get("located") or "none", None
1249
+
1250
+
1251
+ def scan(inventory: dict, engine: str, *, facts=None, settings: dict | None = None, observed: dict | None = None,
1252
+ rank: dict | None = None) -> dict:
1253
+ """joins.json: every join statement of one engine with its facts and signals, the tables joined by many statements,
1254
+ the statements made candidates (with mechanical variants), and the ones that go to the agent."""
1255
+ settings = settings or settings_of(None)
1256
+ book = Book(inventory, facts, engine)
1257
+ load = facts.site_load(engine, located=True) if facts else {}
1258
+ shown = set(settings["shown"].get(engine) or [])
1259
+ agent = set(settings["agent"].get(engine) or [])
1260
+
1261
+ def tier(s: dict) -> str:
1262
+ return tier_of(s, engine, settings)
1263
+
1264
+ observed_load = {c["finding"]: {k: (c.get("observed") or {}).get(k) for k in ("executions", "read_bytes", "share_of_read_bytes")}
1265
+ for c in (observed or {}).get("candidates") or [] if (c.get("observed") or {}).get("read_bytes") is not None}
1266
+ statements = []
1267
+ joined_by: dict[str, set[str]] = defaultdict(set)
1268
+ seen_sql: dict[str, str] = {}
1269
+ for sid, sql, sql_from, located, site in _statements(inventory, engine, observed):
1270
+ h = (site or {}).get("sql_hash") or sid
1271
+ try:
1272
+ facts_ = analyze(sql, engine, book, settings)
1273
+ except (RecursionError, ValueError, AttributeError, TypeError, KeyError, IndexError):
1274
+ continue # a statement the analysis can not read is left out, never guessed
1275
+ if not facts_:
1276
+ continue
1277
+ for f in facts_:
1278
+ for t in f["joined"]["tables"]:
1279
+ joined_by[_short(t)].add(h)
1280
+ if h in seen_sql:
1281
+ continue # the same SQL at another call site: counted once
1282
+ seen_sql[h] = sid
1283
+ # measured load: the call site's from the matched query log, or an observed statement's own shape
1284
+ row = load.get(sid) if site is not None else (observed_load.get(sid) or None)
1285
+ signals = []
1286
+ for f in facts_:
1287
+ for s in f["signals"]:
1288
+ t = tier(s)
1289
+ s["tier"] = t
1290
+ signals.append({**s, "position": f["position"], "scope": f["scope"], "tier": t, "shown": t == "shown"})
1291
+ statements.append({"id": sid, "sql_hash": h, "sql_from": sql_from, "located": located,
1292
+ "file": (site or {}).get("file", ""), "line": (site or {}).get("line", 0),
1293
+ "tables": (site or {}).get("tables") or [], "joins": facts_, "signals": signals,
1294
+ **({"load": {k: row.get(k) for k in ("executions", "read_bytes", "share_of_read_bytes") if k in row}} if row else {}),
1295
+ "_sql": sql})
1296
+ # dimension_join_repeated (evidence only): a table the real catalog says is small, joined by many statements. Without a
1297
+ # catalog nothing says a table is small: a table joined on its unique key is often a lookup by id, not a dimension
1298
+ dims = []
1299
+ for t, hashes in joined_by.items():
1300
+ info = book.get(t) or {}
1301
+ rows = info.get("rows")
1302
+ if len(hashes) >= settings["dimension_min_statements"] and rows is not None and rows <= settings["dimension_max_rows"]:
1303
+ d = {"signal": "dimension_join_repeated", "table": info.get("name") or t, "statements": len(hashes), "rows": rows,
1304
+ "basis": "catalog rows"}
1305
+ d["tier"] = tier(d) if "dimension_join_repeated" in shown | agent else "muted"
1306
+ d["shown"] = d["tier"] == "shown"
1307
+ dims.append(d)
1308
+ dims.sort(key=lambda d: -d["statements"])
1309
+ for st in statements:
1310
+ mine = [{**f, "signals": [s for s in f["signals"] if s["tier"] == "shown"]} for f in st["joins"]]
1311
+ st["variants"] = variants(st["_sql"], engine, book, mine, settings) if any(s["shown"] for s in st["signals"]) else []
1312
+ rank_ids = {c["id"]: c["finding"] for c in (rank or {}).get("candidates") or []}
1313
+ statements.sort(key=lambda s: (-(s.get("load") or {}).get("read_bytes", 0) if s.get("load") else 0, s["file"], s["line"]))
1314
+ cands, agent_queue = [], []
1315
+ for st in statements:
1316
+ st["rank_finding"] = rank_ids.get(st["id"], "")
1317
+ if st["variants"]:
1318
+ cands.append(st)
1319
+ if any(s["tier"] in ("shown", "agent") and s["signal"] in AGENT_SIGNALS for s in st["signals"]):
1320
+ agent_queue.append(st["id"])
1321
+ if settings["max_candidates"]:
1322
+ cands = cands[:int(settings["max_candidates"])]
1323
+ counts = Counter(s["signal"] for st in statements for s in st["signals"])
1324
+ by_tier = Counter(f"{s['signal']}:{s['tier']}" for st in statements for s in st["signals"])
1325
+ by_dim = Counter(f"{s['signal']}:{s.get('dim')}" for st in statements for s in st["signals"] if s.get("dim"))
1326
+ for st in statements:
1327
+ st.pop("_sql", None)
1328
+ return {"schema_version": SCHEMA_VERSION, "engine": engine, "settings": settings,
1329
+ "summary": {"join_statements": len(statements),
1330
+ "with_signal": sum(1 for s in statements if any(x["shown"] for x in s["signals"])),
1331
+ "for_agent": len(agent_queue), "with_variants": len(cands),
1332
+ "signals": dict(counts), "signal_tiers": dict(by_tier), "signal_dims": dict(by_dim),
1333
+ "muted": sorted({s["signal"] for st in statements for s in st["signals"] if s["tier"] == "muted"}),
1334
+ "dimension_tables": len(dims), "sizes_from": "real catalog" if facts else "none (schema only)"},
1335
+ "statements": statements, "dimension_tables": dims,
1336
+ "candidates": [s["id"] for s in cands], "agent": agent_queue}
1337
+
1338
+
1339
+ # ---- what the agent is shown ------------------------------------------------------------------------------------------
1340
+
1341
+ SIGNAL_TEXT = {
1342
+ "joined_side_unbounded": "the joined side is read without the {dim} bound the driving side has ({filters}); its key holds {key}",
1343
+ "filter_after_join": "a filter on {column} applies after the join, outside the subquery that reads it"
1344
+ " ({why})",
1345
+ "join_for_one_column": "the joined table ({tables}) gives {n} column(s) to the result ({columns}){filter}",
1346
+ "big_table_on_build_side": "the right (hash-build) side {tables} is the bigger one ({basis})",
1347
+ "aggregate_after_join": "the aggregates read one side only; the join to {tables} multiplies rows before they are aggregated",
1348
+ "unused_left_join": "LEFT JOIN of {tables} whose columns are never read ({unique})",
1349
+ }
1350
+
1351
+
1352
+ def signal_text(s: dict) -> str:
1353
+ ev = s.get("evidence") or {}
1354
+ name = s["signal"]
1355
+ if name == "joined_side_unbounded":
1356
+ side = ev.get("side") or "joined"
1357
+ other = "driving" if side == "joined" else "joined"
1358
+ text = (f"the {side} side ({', '.join(ev.get('joined_tables') or [])}) is read without the {s.get('dim')} bound the {other} side has "
1359
+ f"({', '.join(ev.get('driving_filters') or [])}); its key holds {', '.join(ev.get('joined_key_columns') or [])}")
1360
+ if s.get("dim") == "join_key":
1361
+ text = (f"the joined table's sorting key ({', '.join(ev.get('joined_key_columns') or [])}) is reached only through the join "
1362
+ f"condition while the driving side is pinned ({', '.join(ev.get('driving_filters') or [])}); a hash join reads it whole")
1363
+ if ev.get("implied_by_join_key"):
1364
+ text += "; the join condition equates them, so copying the bound gives the same rows"
1365
+ if ev.get("engine_applies"):
1366
+ text += " (ClickHouse applies this one by itself)"
1367
+ elif name == "filter_after_join":
1368
+ text = SIGNAL_TEXT[name].format(column=ev.get("column"), why="it can move inside" if ev.get("pushable") else ev.get("why_not"))
1369
+ elif name == "join_for_one_column":
1370
+ text = SIGNAL_TEXT[name].format(tables=", ".join(ev.get("joined_tables") or []), n=len(ev.get("columns") or []),
1371
+ columns=", ".join(ev.get("columns") or []) or "none",
1372
+ filter="; used as a filter only (IN / EXISTS gives the same rows when the key is unique)"
1373
+ if ev.get("as_filter_only") else "")
1374
+ elif name == "big_table_on_build_side":
1375
+ text = SIGNAL_TEXT[name].format(tables=", ".join(ev.get("right_tables") or []), basis=ev.get("basis"))
1376
+ elif name == "aggregate_after_join":
1377
+ text = SIGNAL_TEXT[name].format(tables=", ".join(ev.get("joined_tables") or []))
1378
+ elif name == "unused_left_join":
1379
+ text = SIGNAL_TEXT[name].format(tables=", ".join(ev.get("joined_tables") or []),
1380
+ unique=ev.get("unique_on_join_key") or "nothing says it holds one row per key: dropping it may change the row count")
1381
+ else:
1382
+ text = name
1383
+ return text + (" (a run-time part may add the bound)" if s.get("uncertain") else "")
1384
+
1385
+
1386
+ def prompt_note(st: dict) -> str:
1387
+ """The join facts of one statement, one line per signal shown or handed to the agent, for the rank prompt."""
1388
+ lines = [f"- join {s['position']}: {s['signal']}: {signal_text(s)}" for s in st.get("signals") or []
1389
+ if s.get("tier") in ("shown", "agent")]
1390
+ return ("join signals (computed by CodeCop from the parsed statement; judge them):\n" + "\n".join(lines)) if lines else ""
1391
+
1392
+
1393
+ FOCUS_TEXT = """
1394
+ ## Focus: joins
1395
+
1396
+ Every query below joins, and CodeCop's static analysis flagged each join with the signals listed under it. For each one,
1397
+ judge whether the join does more work than the result needs, and propose `rewrite` variants that return the same rows:
1398
+ bound the joined side by the same tenant or time range as the driving side (only where the data guarantees it), move a
1399
+ filter inside the subquery it applies to, replace a join used only for a filter or one column by `IN (subquery)` or a
1400
+ dictionary lookup, aggregate before joining, put the smaller side on the right (ClickHouse builds the hash table from the
1401
+ right side), or drop a join nothing reads. A rewrite that can multiply or drop rows is measured and rejected: say in
1402
+ `assumptions` what makes it safe. Reject a query whose signals do not hold with the usual codes.
1403
+ """
1404
+
1405
+
1406
+ def restrict(inventory: dict, doc: dict) -> dict:
1407
+ """The inventory with only the call sites whose join statement goes to the agent (doc["agent"]), each carrying its join
1408
+ note: what `codecop rank --focus join` ranks. A copy."""
1409
+ queued = set(doc.get("agent") or [])
1410
+ by_hash = {st["sql_hash"]: prompt_note(st) for st in doc.get("statements") or [] if st["id"] in queued}
1411
+ hashes = set(by_hash)
1412
+ out = dict(inventory)
1413
+ out["call_sites"] = [{**c, "join_note": by_hash.get(c.get("sql_hash"), "")} for c in inventory.get("call_sites") or []
1414
+ if c.get("sql_hash") in hashes]
1415
+ return out
1416
+
1417
+
1418
+ # ---- candidates for the benchmark -------------------------------------------------------------------------------------
1419
+
1420
+ def outcome_for(st: dict) -> dict:
1421
+ """The outcome of a join statement with signals that no candidate carries: what to do next."""
1422
+ from .blockers import JOIN_NEXT_STEP, outcome
1423
+ return outcome("not_judged", "join_not_asked", "run", {"next_step": JOIN_NEXT_STEP,
1424
+ "signals": sorted({s["signal"] for s in st["signals"]
1425
+ if s.get("tier") in ("shown", "agent")})})
1426
+
1427
+
1428
+ def finding_block(doc: dict, cand: dict, variants_: list[dict]) -> dict | None:
1429
+ """findings[].join: the signals of the finding's join statement (shown or for the agent) and its picture, with what
1430
+ CodeCop's own variant changes. None for a finding that is not a join statement CodeCop flagged."""
1431
+ st = next((s for s in doc.get("statements") or [] if s["id"] in (cand.get("id"), cand.get("finding"))), None)
1432
+ mine = [v for v in variants_ if v.get("join")]
1433
+ if st is None and not mine:
1434
+ return None
1435
+ best = next((v for v in mine if v.get("verdict") == "win"), None) or (mine[0] if mine else None)
1436
+ change = {**best, **best["join"]} if best else None
1437
+ sigs = [s for s in (st or {}).get("signals") or [] if s.get("tier") in ("shown", "agent")]
1438
+ if st is not None and not sigs and not mine:
1439
+ return None
1440
+ return {"signals": [{k: s.get(k) for k in ("signal", "dim", "tier", "uncertain", "position", "evidence")} for s in sigs]
1441
+ or [{"signal": v["join"]["signal"], "tier": "shown", "position": v["join"]["position"]} for v in mine],
1442
+ "drawing": drawing({"joins": [{**j, "signals": [s for s in j["signals"] if s.get("tier") in ("shown", "agent")]}
1443
+ for j in (st or {}).get("joins") or []]}, change) if st else [],
1444
+ "variants": [{"rewrite": v.get("rewrite"), "verdict": v.get("verdict"), "change": v.get("change")} for v in mine]}
1445
+
1446
+
1447
+ def report_block(doc: dict, findings: list[dict], max_statements: int = 0) -> dict:
1448
+ """findings.json `joins`: the run's join statements with a shown or agent signal, each with its picture, the finding that
1449
+ carries it (if any) and its outcome; the counts per signal and tier; the dimension tables. `max_statements` (0: all)."""
1450
+ by_id = {}
1451
+ for f in findings:
1452
+ by_id.setdefault(f["id"], f)
1453
+ by_id.setdefault(f["finding"], f)
1454
+ rows = []
1455
+ for st in doc.get("statements") or []:
1456
+ sigs = [s for s in st["signals"] if s.get("tier") in ("shown", "agent")]
1457
+ if not sigs:
1458
+ continue
1459
+ f = by_id.get(st["id"])
1460
+ best = next((v for v in (f or {}).get("variants") or [] if v.get("join") and v.get("verdict") == "win"), None) or \
1461
+ next((v for v in (f or {}).get("variants") or [] if v.get("join")), None)
1462
+ change = {**(best or {}), **(best or {}).get("join", {})} if best else None
1463
+ rows.append({"id": st["id"], "finding": (f or {}).get("finding", ""), "file": st["file"], "line": st["line"],
1464
+ "sql_from": st["sql_from"], "located": st["located"],
1465
+ "signals": [{k: s.get(k) for k in ("signal", "dim", "tier", "uncertain", "position", "evidence")} for s in sigs],
1466
+ "drawing": drawing({"joins": [{**j, "signals": [s for s in j["signals"] if s.get("tier") in ("shown", "agent")]}
1467
+ for j in st["joins"]]}, change),
1468
+ "outcome": (f or {}).get("outcome") or outcome_for(st),
1469
+ **({"load": st["load"]} if st.get("load") else {})})
1470
+ if max_statements:
1471
+ rows = rows[:int(max_statements)]
1472
+ tiers = (doc.get("summary") or {}).get("signal_tiers") or {}
1473
+ return {"engine": doc.get("engine"), "summary": doc.get("summary") or {}, "statements": rows,
1474
+ "dimension_tables": [d for d in doc.get("dimension_tables") or [] if d.get("tier") in ("shown", "agent")],
1475
+ "tiers": {"shown": (doc.get("settings") or {}).get("shown", {}).get(doc.get("engine"), []),
1476
+ "agent": (doc.get("settings") or {}).get("agent", {}).get(doc.get("engine"), [])},
1477
+ "counts": tiers}
1478
+
1479
+
1480
+ def drawing(st_or_facts: dict | list, variant: dict | None = None) -> list[dict]:
1481
+ """The compact picture of each join: two sides, their sizes, which filters reach which side, what a variant changes."""
1482
+ facts = st_or_facts.get("joins") if isinstance(st_or_facts, dict) else st_or_facts
1483
+ out = []
1484
+ for f in facts or []:
1485
+ if not f.get("signals"):
1486
+ continue
1487
+
1488
+ def side(s: dict) -> dict:
1489
+ return {"name": ", ".join(s["tables"]) if s["kind"] == "table" else f"{s['kind']} {s['alias']} ({', '.join(s['tables']) or '-'})",
1490
+ "rows": s.get("rows"), "rows_from": s.get("rows_from") or "", "final": s.get("final", False),
1491
+ "key": s.get("key") or [], "filters": [{"column": x["column"], "dims": x.get("dims") or [], "from": x["from"]}
1492
+ for x in s.get("filters") or []],
1493
+ "used": s.get("used") or []}
1494
+ out.append({"position": f["position"], "type": f["type"], "strictness": f.get("strictness") or "",
1495
+ "keys": [[k["driving"], k["joined"]] for k in f.get("keys") or []],
1496
+ "driving": side(f["driving"]), "joined": side(f["joined"]),
1497
+ "signals": [s["signal"] for s in f["signals"]],
1498
+ **({"change": {"rewrite": variant.get("rewrite"), "text": variant.get("change"),
1499
+ **({"verdict": variant["verdict"]} if variant.get("verdict") else {})}}
1500
+ if variant and variant.get("position") == f["position"] and variant.get("scope") == f["scope"] else {})})
1501
+ return out
1502
+
1503
+
1504
+ POSITIONAL = re.compile(r"\$\d+\b|(?<![\w?])\?(?![\w?])")
1505
+
1506
+
1507
+ def _as_variants(found: list[dict]) -> list[dict]:
1508
+ return [{k: v for k, v in x.items() if k not in ("signal", "scope", "position")}
1509
+ | {"join": {"signal": x["signal"], "scope": x["scope"], "position": x["position"]}} for x in found]
1510
+
1511
+
1512
+ def candidate_variants(cand: dict, book: Book, engine: str, settings: dict) -> tuple[list[dict], list[dict]]:
1513
+ """(join facts, mechanical variants) of a candidate's own baseline: a variant is always written from the statement the
1514
+ benchmark runs, never from another text of the same call site."""
1515
+ facts_ = analyze(cand.get("baseline_sql") or "", engine, book, settings)
1516
+ for f in facts_:
1517
+ f["signals"] = [s for s in f["signals"] if tier_of(s, engine, settings) == "shown"]
1518
+ return facts_, _as_variants(variants(cand.get("baseline_sql") or "", engine, book, facts_, settings))
1519
+
1520
+
1521
+ def candidates(doc: dict, inventory: dict, rank: dict | None, engine: str) -> tuple[list[dict], dict[str, list[dict]]]:
1522
+ """(new candidates, finding -> extra variants for an existing candidate). A statement that is already a candidate (the
1523
+ agent's or production's) gets the mechanical variants of that candidate's own baseline; any other join statement with a
1524
+ variant gets a candidate of its own (`J-NNN`), from the SQL written at its call site."""
1525
+ from .rank import site_role
1526
+ settings = doc.get("settings") or settings_of(None)
1527
+ book = Book(inventory, None, engine) if not doc.get("_book") else doc["_book"]
1528
+ by_site = {c["id"]: c for c in inventory.get("call_sites") or []}
1529
+ existing = {c["id"] for c in (rank or {}).get("candidates") or []} | {c["finding"] for c in (rank or {}).get("candidates") or []}
1530
+ st_by = {st["id"]: st for st in doc.get("statements") or []}
1531
+ new, extra = [], defaultdict(list)
1532
+ for c in (rank or {}).get("candidates") or []:
1533
+ try:
1534
+ _, vs = candidate_variants(c, book, engine, settings)
1535
+ except (RecursionError, ValueError, AttributeError, TypeError, KeyError, IndexError):
1536
+ continue
1537
+ if vs:
1538
+ extra[c["finding"]].extend(vs)
1539
+ n = 0
1540
+ for sid in doc.get("candidates") or []:
1541
+ st = st_by.get(sid)
1542
+ if st is None or sid in existing:
1543
+ continue
1544
+ vs = _as_variants(st["variants"])
1545
+ site = by_site.get(sid)
1546
+ if site is None or POSITIONAL.search(sqlinfo._strip_text(site.get("sql") or "")):
1547
+ continue # positional parameters: nothing says which value goes where, so the benchmark could not run it
1548
+ n += 1
1549
+ params = _params_for(site.get("sql") or "", engine)
1550
+ new.append({
1551
+ "finding": f"J-{n:03d}", "id": sid, "title": "Join: " + ", ".join(sorted({s["signal"].replace("_", " ") for s in st["signals"] if s.get("shown")})),
1552
+ "severity": "medium", "confidence": "medium", "baseline_sql": site["sql"], "original_sql": site["sql"],
1553
+ "params": params, "tables": [t for t in site.get("tables") or []], "variants": vs,
1554
+ "origin": {"role": site_role(site), "kind": ((site.get("origins") or [{}])[0]).get("kind", "unknown"),
1555
+ "entry_points": [{k: o.get(k) for k in ("kind", "name", "file", "line")} for o in (site.get("origins") or [])[:3]],
1556
+ "path": [], "verified": False},
1557
+ "causes": [], "assumptions": ["Variants generated by CodeCop from the statement and the keys; the benchmark checks the rows."],
1558
+ "site": {"file": site.get("file", ""), "line": site.get("line", 0), "symbol": site.get("symbol", "")},
1559
+ "sql_from": st["sql_from"], "located": "site", "join": {"signals": [s for s in st["signals"] if s.get("shown")]},
1560
+ "shortlist_note": "a join statement CodeCop flagged; its variants are mechanical (no agent)",
1561
+ })
1562
+ return new, dict(extra)
1563
+
1564
+
1565
+ def _params_for(sql: str, engine: str) -> dict:
1566
+ """Values for the statement's named parameters ({name:Type}): a neutral value of the type. The data profile gives the
1567
+ compared columns those values (profile_for)."""
1568
+ out = {}
1569
+ for m in re.finditer(r"\{(\w+)\s*:\s*([^{}]+)\}", sql or ""):
1570
+ name, t = m.group(1), m.group(2).strip()
1571
+ if "DateTime" in t or t.startswith("Date"):
1572
+ out[name] = "2000-01-01 00:00:00"
1573
+ elif "UUID" in t:
1574
+ out[name] = ["00000000-0000-0000-0000-000000000007"] if t.startswith("Array(") else "00000000-0000-0000-0000-000000000007"
1575
+ elif re.match(r"(Nullable\()?U?Int|Float|Decimal", t):
1576
+ out[name] = 7
1577
+ elif t.startswith("Array("):
1578
+ out[name] = ["v"]
1579
+ else:
1580
+ out[name] = "v"
1581
+ return out
1582
+
1583
+
1584
+ def augment(rank: dict | None, profile: dict | None, doc: dict, inventory: dict, facts, engine: str) -> tuple[dict, dict, list[str]]:
1585
+ """rank.json and profile.json with the join candidates added (their tables' definitions, from the real catalog or from
1586
+ the repository's own, and a schema-only data profile for a table nothing describes) and mechanical variants appended
1587
+ to existing candidates. Copies; nothing on disk changes."""
1588
+ rank = copy.deepcopy(rank) if rank else {"engine": engine, "engine_version": "", "candidates": [], "table_definitions": [],
1589
+ "agent": {"runner": "", "model": "", "cost_usd": 0.0}, "shortlist": [], "rejected": []}
1590
+ profile = copy.deepcopy(profile) if profile else {"engine": engine, "tables": []}
1591
+ notes: list[str] = []
1592
+ new, extra = candidates({**doc, "_book": Book(inventory, facts, engine)}, inventory, rank, engine)
1593
+ appended = 0
1594
+ for c in rank["candidates"]:
1595
+ if c["finding"] in extra:
1596
+ have = {" ".join((v.get("sql") or "").split()) for v in c["variants"]}
1597
+ more = [v for v in extra[c["finding"]] if " ".join(v["sql"].split()) not in have]
1598
+ c["variants"] = c["variants"] + more
1599
+ appended += len(more)
1600
+ if appended:
1601
+ notes.append(f"{appended} join variants CodeCop generated added to existing candidates")
1602
+ have = {d["name"] for d in rank.get("table_definitions") or []}
1603
+ described = {t["name"] for t in profile.get("tables") or []}
1604
+ added = 0
1605
+ for cand in new:
1606
+ ok = True
1607
+ for name in cand["tables"]:
1608
+ if name in have:
1609
+ continue
1610
+ d = facts.definition(engine, name) if facts else None
1611
+ d = d or repository_definition(inventory, name, engine)
1612
+ if d is None:
1613
+ ok = False
1614
+ break
1615
+ rank["table_definitions"].append(d)
1616
+ have.add(name)
1617
+ if not ok:
1618
+ notes.append(f"{cand['finding']}: a table it reads has no definition the sandbox can build; not benchmarked")
1619
+ continue
1620
+ rank["candidates"].append(cand)
1621
+ added += 1
1622
+ for name in cand["tables"]:
1623
+ if name not in described:
1624
+ profile["tables"].append(schema_profile(name, rank, cand, facts, engine))
1625
+ described.add(name)
1626
+ link_profile(cand, profile, Book(inventory, facts, engine), engine)
1627
+ if added:
1628
+ notes.append(f"{added} join statements added to the benchmark with variants CodeCop generated")
1629
+ return rank, profile, notes
1630
+
1631
+
1632
+ def link_profile(cand: dict, profile: dict, book: Book, engine: str, settings: dict | None = None) -> None:
1633
+ """What the generated data must keep for the candidate's joins to match rows the application writes: a relation per join
1634
+ key (the side joined on a unique column or `id` is the parent; tenant columns the condition equates are shared with the
1635
+ parent), and the candidate's pinned values on every table the condition ties to a pinned column. Only tables that
1636
+ profile.json describes with no relations of the agent's are changed."""
1637
+ settings = settings or settings_of(None)
1638
+ tables = {_short(t["name"]): t for t in profile.get("tables") or []}
1639
+ try:
1640
+ facts_ = analyze(cand.get("baseline_sql") or "", engine, book, settings)
1641
+ except (RecursionError, ValueError, AttributeError, TypeError, KeyError, IndexError):
1642
+ return
1643
+ for f in facts_:
1644
+ d, j = f["driving"], f["joined"]
1645
+ if len(d["tables"]) != 1 or len(j["tables"]) != 1:
1646
+ continue
1647
+ a, b = _short(d["tables"][0]), _short(j["tables"][0])
1648
+ if a == b or a not in tables or b not in tables:
1649
+ continue
1650
+ tenant, other = [], []
1651
+ for k in f["keys"]:
1652
+ (tenant if re.search(settings["tenant_columns"], k["driving"], re.I) and re.search(settings["tenant_columns"], k["joined"], re.I)
1653
+ else other).append((k["driving"], k["joined"]))
1654
+ # pinned values cross a tenant equality: both tables hold the candidate's tenant
1655
+ for ta, tb, pairs in ((a, b, tenant), (b, a, [(y, x) for x, y in tenant])):
1656
+ for fx in tables[ta].get("fixtures") or []:
1657
+ if fx.get("id") != cand["finding"]:
1658
+ continue
1659
+ vals = [{"column": cb, "value": v["value"]} for v in fx["values"] for ca, cb in pairs if v["column"] == ca]
1660
+ if vals and not any(x.get("id") == cand["finding"] for x in tables[tb].get("fixtures") or []):
1661
+ tables[tb].setdefault("fixtures", []).append({**fx, "values": vals, "basis": fx.get("basis", "") + "; the join condition equates it"})
1662
+ if not other:
1663
+ continue
1664
+ unique_b = any(set(u) <= {y for _, y in other} for u in (book.get(b) or {}).get("unique") or []) or any(y == "id" for _, y in other)
1665
+ unique_a = any(set(u) <= {x for x, _ in other} for u in (book.get(a) or {}).get("unique") or []) or any(x == "id" for x, _ in other)
1666
+ child, parent, pairs = (a, b, other) if unique_b or not unique_a else (b, a, [(y, x) for x, y in other])
1667
+ col, pcol = pairs[0]
1668
+ t = tables[child]
1669
+ if any(r.get("column") == col for r in t.get("relations") or []):
1670
+ continue
1671
+ same = [{"column": x if child == a else y, "parent_column": y if child == a else x} for x, y in tenant]
1672
+ t.setdefault("relations", []).append({"column": col, "parent_table": tables[parent]["name"], "parent_column": pcol,
1673
+ "same_as_parent": same, "basis": "CodeCop: the statement's join condition"})
1674
+
1675
+
1676
+ def repository_definition(inventory: dict, name: str, engine: str) -> dict | None:
1677
+ """A CREATE TABLE the sandbox can build, written from the repository's own definition (its columns, engine and keys)."""
1678
+ t = next((x for x in inventory.get("tables") or [] if _short(x["name"]) == _short(name) and not x.get("test_only")
1679
+ and (bool(x.get("engine")) == (engine == "clickhouse"))), None)
1680
+ if t is None or not t.get("columns"):
1681
+ return None
1682
+ if engine == "clickhouse":
1683
+ cols = ",\n ".join(f"`{c['name']}` {c['type']}" for c in t["columns"] if c.get("type"))
1684
+ eng = t["engine"] if t["engine"] and "MergeTree" in t["engine"] else "MergeTree"
1685
+ args = t.get("engine_args") or ""
1686
+ if args and not args.startswith("("):
1687
+ args = f"({args})"
1688
+ if eng.startswith(("Replicated", "Shared")):
1689
+ eng, args = eng.replace("Replicated", "").replace("Shared", ""), ""
1690
+ sql = (f"CREATE TABLE {name} (\n {cols}\n) ENGINE = {eng}{args or '()'}"
1691
+ + (f" PARTITION BY {t['partition_by']}" if t.get("partition_by") else "")
1692
+ + f" ORDER BY {t['order_by'] or 'tuple()'}"
1693
+ + (f" PRIMARY KEY {t['primary_key']}" if t.get("primary_key") else ""))
1694
+ else:
1695
+ types = {"bigautofield": "bigint", "autofield": "integer", "charfield": "text", "textfield": "text", "integerfield": "integer",
1696
+ "booleanfield": "boolean", "datetimefield": "timestamptz", "datefield": "date", "foreignkey": "bigint",
1697
+ "uuidfield": "uuid", "jsonfield": "jsonb", "floatfield": "double precision", "decimalfield": "numeric"}
1698
+
1699
+ def pg_type(raw: str) -> str:
1700
+ low = raw.lower()
1701
+ for k, v in types.items():
1702
+ if low.endswith(k) or k in low:
1703
+ return v
1704
+ return raw if re.fullmatch(r"[A-Za-z ]+(\(\d+(,\s*\d+)?\))?(\[\])?", raw) else "text"
1705
+ cols = ",\n ".join(f'"{c["name"]}" {pg_type(c.get("type") or "text")}' for c in t["columns"])
1706
+ pk = t.get("primary_key") or ""
1707
+ sql = f'CREATE TABLE {name} (\n {cols}' + (f",\n PRIMARY KEY ({pk})" if pk else "") + "\n)"
1708
+ extra = [f"CREATE {'UNIQUE ' if ix.get('unique') and not ix.get('primary') else ''}INDEX ON {name} ({', '.join(ix['columns'])})"
1709
+ for ix in t.get("indexes") or [] if ix.get("columns") and not ix.get("primary")]
1710
+ sql = ";\n".join([sql] + extra)
1711
+ return {"name": name, "create_sql": sql, "inferred": True, "source": "repository",
1712
+ "basis": f"Written by CodeCop from the repository's definition at {(t.get('defined_at') or [''])[0]}."}
1713
+
1714
+
1715
+ def schema_profile(name: str, rank: dict, cand: dict, facts, engine: str) -> dict:
1716
+ """A data profile for one table from its columns alone (no agent, no sample): the generator kind follows the type, the
1717
+ candidate's parameter values are put on a share of the rows, and the join's key columns are related to the other side."""
1718
+ from .catalog_profile import column_spec
1719
+ d = next((x for x in rank["table_definitions"] if x["name"] == name), {})
1720
+ from .relations import table_columns
1721
+ cols, _ = table_columns(d, engine) if d else ([], [])
1722
+ t = facts.tables(engine).get(_short(name)) if facts else None
1723
+ rows = int((t or {}).get("rows") or 0) or 100_000
1724
+ types = {}
1725
+ if engine == "clickhouse":
1726
+ from .rank import _columns
1727
+ got = _columns(d.get("create_sql") or "", d.get("name") or "")
1728
+ # name -> the column's whole line: its type is what follows the name, up to a default, codec or comment
1729
+ types = {n: re.split(r"\s+(?:DEFAULT|MATERIALIZED|ALIAS|EPHEMERAL|CODEC|COMMENT|TTL)\b", re.sub(r"^\s*[`\"]?[\w.]+[`\"]?\s+", "", text),
1730
+ maxsplit=1, flags=re.I)[0].strip() for n, text in (got[1] if got else {}).items()}
1731
+ specs = []
1732
+ sql = cand.get("baseline_sql") or ""
1733
+ words = {w.lower() for w in re.findall(r"[A-Za-z_]\w*", sql)}
1734
+ sorting = [w for w in re.findall(r"[A-Za-z_]\w*", (re.search(r"ORDER BY\s*\(?([^)]*)", d.get("create_sql") or "") or [None, ""])[1] or "")]
1735
+ for c in cols:
1736
+ if c.lower() not in words and c not in sorting:
1737
+ continue
1738
+ spec = column_spec({"name": c, "type": types.get(c, "String")}, rows, sorting=sorting, days_back=30, literals=None)
1739
+ specs.append(spec)
1740
+ pinned = []
1741
+ for m in re.finditer(r"(\w+)\s*(=|==|IN\s*\(?)\s*\{(\w+)\s*:\s*([^{}]+)\}", sql, re.I):
1742
+ col, pname = m.group(1), m.group(3)
1743
+ if col in cols and pname in (cand.get("params") or {}) and not any(p["column"] == col for p in pinned):
1744
+ value = cand["params"][pname]
1745
+ pinned.append({"column": col, "value": value[0] if isinstance(value, list) and value else value})
1746
+ fixtures = [{"id": cand["finding"], "values": pinned, "share": 0.05, "min_rows": 10,
1747
+ "basis": "schema only: the candidate's parameter values on 5% of the rows"}] if pinned else []
1748
+ return {"name": name, "rows": rows, "rows_basis": "real catalog" if t else "schema only: 100,000 rows", "rows_confidence": "low",
1749
+ "basis": "schema only, no agent", "columns": specs, "fixtures": fixtures, "relations": []}