codecop 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (222) hide show
  1. codecop/__init__.py +7 -0
  2. codecop/access.py +140 -0
  3. codecop/access_postgres.py +284 -0
  4. codecop/advisor.py +1512 -0
  5. codecop/advisor_bench.py +493 -0
  6. codecop/advisor_ch.py +2080 -0
  7. codecop/advisor_view.py +381 -0
  8. codecop/advisors.py +184 -0
  9. codecop/agent.py +221 -0
  10. codecop/agentfacts.py +745 -0
  11. codecop/apply/__init__.py +327 -0
  12. codecop/apply/check.py +344 -0
  13. codecop/apply/cli.py +162 -0
  14. codecop/apply/clickhouse.py +379 -0
  15. codecop/apply/common.py +238 -0
  16. codecop/apply/html.py +264 -0
  17. codecop/apply/patch.py +213 -0
  18. codecop/apply/postgres.py +102 -0
  19. codecop/apply/trial.py +166 -0
  20. codecop/assemble.py +104 -0
  21. codecop/baseline.py +1043 -0
  22. codecop/bench.py +2464 -0
  23. codecop/blockers.py +935 -0
  24. codecop/budget.py +980 -0
  25. codecop/catalog_profile.py +525 -0
  26. codecop/changed.py +261 -0
  27. codecop/cicmd.py +1002 -0
  28. codecop/cli.py +5421 -0
  29. codecop/client.py +729 -0
  30. codecop/coverage.py +1067 -0
  31. codecop/coverage_reasons.py +116 -0
  32. codecop/crashlog.py +70 -0
  33. codecop/datagen.py +766 -0
  34. codecop/datagen_postgres.py +630 -0
  35. codecop/datagen_sqlite.py +323 -0
  36. codecop/dbcli.py +885 -0
  37. codecop/definitions.py +457 -0
  38. codecop/discover/__init__.py +702 -0
  39. codecop/discover/arms.py +160 -0
  40. codecop/discover/base.py +234 -0
  41. codecop/discover/dialect.py +296 -0
  42. codecop/discover/elixir.py +64 -0
  43. codecop/discover/engine_go.py +320 -0
  44. codecop/discover/go.py +1947 -0
  45. codecop/discover/java.py +1528 -0
  46. codecop/discover/loops.py +1671 -0
  47. codecop/discover/named_go.py +258 -0
  48. codecop/discover/origins.py +4565 -0
  49. codecop/discover/origins_ts.py +1584 -0
  50. codecop/discover/orm_django.py +2772 -0
  51. codecop/discover/orm_django_models.py +814 -0
  52. codecop/discover/orm_django_sql.py +662 -0
  53. codecop/discover/orm_ent.py +565 -0
  54. codecop/discover/orm_ex_ecto.py +2138 -0
  55. codecop/discover/orm_go.py +2134 -0
  56. codecop/discover/orm_go_bun.py +602 -0
  57. codecop/discover/orm_go_run.py +636 -0
  58. codecop/discover/orm_go_types.py +1082 -0
  59. codecop/discover/orm_java.py +1450 -0
  60. codecop/discover/orm_jdbi.py +743 -0
  61. codecop/discover/orm_jooq.py +806 -0
  62. codecop/discover/orm_jpa.py +1307 -0
  63. codecop/discover/orm_mybatis.py +730 -0
  64. codecop/discover/orm_py.py +557 -0
  65. codecop/discover/orm_py_peewee.py +1266 -0
  66. codecop/discover/orm_py_prisma.py +298 -0
  67. codecop/discover/orm_rb_activerecord.py +1906 -0
  68. codecop/discover/orm_rust.py +1248 -0
  69. codecop/discover/orm_rust_seaorm.py +734 -0
  70. codecop/discover/orm_sqlalchemy.py +2475 -0
  71. codecop/discover/orm_stats.py +307 -0
  72. codecop/discover/orm_tables.py +29 -0
  73. codecop/discover/orm_ts.py +503 -0
  74. codecop/discover/orm_ts_drizzle.py +697 -0
  75. codecop/discover/orm_ts_knex.py +1117 -0
  76. codecop/discover/orm_ts_kysely.py +861 -0
  77. codecop/discover/orm_ts_prisma.py +1045 -0
  78. codecop/discover/orm_ts_schema.py +169 -0
  79. codecop/discover/orm_ts_sequelize.py +1401 -0
  80. codecop/discover/orm_ts_typeorm.py +1067 -0
  81. codecop/discover/probes.py +323 -0
  82. codecop/discover/python.py +595 -0
  83. codecop/discover/ruby.py +793 -0
  84. codecop/discover/rust.py +2378 -0
  85. codecop/discover/schema.py +520 -0
  86. codecop/discover/schema_ent.py +145 -0
  87. codecop/discover/schema_ts.py +420 -0
  88. codecop/discover/tsresolve.py +257 -0
  89. codecop/discover/typescript.py +1728 -0
  90. codecop/discover/xml_mapper.py +526 -0
  91. codecop/engines/__init__.py +515 -0
  92. codecop/engines/base.py +498 -0
  93. codecop/engines/clickhouse.py +1558 -0
  94. codecop/engines/pg_ddl.py +444 -0
  95. codecop/engines/pg_hints.py +137 -0
  96. codecop/engines/postgres.py +1060 -0
  97. codecop/engines/sqlite.py +742 -0
  98. codecop/families/__init__.py +3 -0
  99. codecop/families/build.py +280 -0
  100. codecop/families/cli.py +177 -0
  101. codecop/families/coverage_hook.py +62 -0
  102. codecop/families/driver.py +221 -0
  103. codecop/families/goslice.py +229 -0
  104. codecop/families/goslice_tool/go.mod +3 -0
  105. codecop/families/goslice_tool/main.go +403 -0
  106. codecop/families/holes.py +451 -0
  107. codecop/families/images/Dockerfile.go +5 -0
  108. codecop/families/images/Dockerfile.python +4 -0
  109. codecop/families/images/Dockerfile.rust +4 -0
  110. codecop/families/isolate.py +171 -0
  111. codecop/families/locate.py +270 -0
  112. codecop/families/model.py +301 -0
  113. codecop/families/plangate.py +271 -0
  114. codecop/families/tagpatch.py +174 -0
  115. codecop/fidelity.py +671 -0
  116. codecop/fixgroups.py +130 -0
  117. codecop/formerly.py +91 -0
  118. codecop/grantscript.py +254 -0
  119. codecop/groupbench.py +1375 -0
  120. codecop/groups.py +594 -0
  121. codecop/groups_view.py +186 -0
  122. codecop/heat.py +1405 -0
  123. codecop/heatcli.py +219 -0
  124. codecop/joins.py +1749 -0
  125. codecop/joins_view.py +127 -0
  126. codecop/kinds/__init__.py +507 -0
  127. codecop/kinds/calls/__init__.py +501 -0
  128. codecop/kinds/calls/extract.py +1097 -0
  129. codecop/kinds/calls/harness.py +408 -0
  130. codecop/kinds/calls/measure.py +342 -0
  131. codecop/kinds/calls/rules.py +139 -0
  132. codecop/kinds/calls/runners/RunCalls.java +167 -0
  133. codecop/kinds/calls/runners/run_go.go +141 -0
  134. codecop/kinds/calls/runners/run_node.js +186 -0
  135. codecop/kinds/calls/runners/run_python.py +319 -0
  136. codecop/kinds/calls/runners/run_rust.rs +200 -0
  137. codecop/kinds/calls/standin.py +340 -0
  138. codecop/kinds/pipeline.py +288 -0
  139. codecop/kinds/regex/__init__.py +1167 -0
  140. codecop/kinds/regex/engines/RegexHarness.java +129 -0
  141. codecop/kinds/regex/engines/run_go.go +294 -0
  142. codecop/kinds/regex/engines/run_node.js +99 -0
  143. codecop/kinds/regex/engines/run_python.py +295 -0
  144. codecop/kinds/regex/engines/run_rust.rs +149 -0
  145. codecop/kinds/regex/extract.py +1438 -0
  146. codecop/kinds/regex/harness.py +235 -0
  147. codecop/kinds/regex/measure.py +270 -0
  148. codecop/kinds/regex/shapes.py +418 -0
  149. codecop/kinds/regex/syntax.py +1721 -0
  150. codecop/kinds/testkind.py +107 -0
  151. codecop/kinds/transaction/__init__.py +228 -0
  152. codecop/kinds/transaction/bind.py +355 -0
  153. codecop/kinds/transaction/measure.py +264 -0
  154. codecop/kinds/transaction/plan.py +462 -0
  155. codecop/kinds/transaction/rules.py +540 -0
  156. codecop/kinds/transaction/sandbox.py +94 -0
  157. codecop/kinds/transaction/scenarios.py +520 -0
  158. codecop/kinds/transaction/schedule.py +483 -0
  159. codecop/kinds/transaction/shapes.py +418 -0
  160. codecop/kinds/transaction/verify.py +293 -0
  161. codecop/live.py +237 -0
  162. codecop/loopbench.py +2071 -0
  163. codecop/loopschema.py +591 -0
  164. codecop/mcpserver.py +120 -0
  165. codecop/mechanism.py +214 -0
  166. codecop/members.py +200 -0
  167. codecop/multi.py +443 -0
  168. codecop/observed.py +1868 -0
  169. codecop/parts.py +102 -0
  170. codecop/patterns.py +830 -0
  171. codecop/patterns_view.py +559 -0
  172. codecop/plangate.py +242 -0
  173. codecop/profile.py +439 -0
  174. codecop/prompts/areas.md +19 -0
  175. codecop/prompts/observed_variants.md +20 -0
  176. codecop/prompts/profile.md +60 -0
  177. codecop/prompts/profile_postgres.md +68 -0
  178. codecop/prompts/profile_sizes.md +26 -0
  179. codecop/prompts/profile_sqlite.md +69 -0
  180. codecop/prompts/rank.md +84 -0
  181. codecop/prompts/rank_postgres.md +96 -0
  182. codecop/prompts/rank_sqlite.md +94 -0
  183. codecop/prompts/scenario_variants.md +20 -0
  184. codecop/rank.py +1473 -0
  185. codecop/realdb/__init__.py +688 -0
  186. codecop/realdb/clickhouse.py +1223 -0
  187. codecop/realdb/facts.py +815 -0
  188. codecop/realdb/locality.py +964 -0
  189. codecop/realdb/locks.py +355 -0
  190. codecop/realdb/match.py +531 -0
  191. codecop/realdb/postgres.py +643 -0
  192. codecop/realdb/ratios.py +77 -0
  193. codecop/realdb/sample.py +126 -0
  194. codecop/relations.py +227 -0
  195. codecop/report.py +1854 -0
  196. codecop/resources.py +332 -0
  197. codecop/resources_view.py +266 -0
  198. codecop/rules/entry_points.toml +1013 -0
  199. codecop/rules/sinks.toml +362 -0
  200. codecop/runsonce.py +8 -0
  201. codecop/sandboxschema.py +555 -0
  202. codecop/scenario_agent.py +172 -0
  203. codecop/scenario_bind.py +507 -0
  204. codecop/scenario_sql.py +971 -0
  205. codecop/scenarios.py +675 -0
  206. codecop/scenarios_view.py +274 -0
  207. codecop/schemacli.py +67 -0
  208. codecop/schemas/areas_output.schema.json +21 -0
  209. codecop/schemas/profile_output.schema.json +362 -0
  210. codecop/schemas/rank_output.schema.json +385 -0
  211. codecop/sizes.py +200 -0
  212. codecop/sqlinfo.py +558 -0
  213. codecop/typedparams.py +576 -0
  214. codecop/verdicts.py +212 -0
  215. codecop/writebench.py +720 -0
  216. codecop/writecost.py +440 -0
  217. codecop/writes.py +1208 -0
  218. codecop-0.1.0.dist-info/METADATA +42 -0
  219. codecop-0.1.0.dist-info/RECORD +222 -0
  220. codecop-0.1.0.dist-info/WHEEL +4 -0
  221. codecop-0.1.0.dist-info/entry_points.txt +2 -0
  222. codecop-0.1.0.dist-info/licenses/LICENSE +21 -0
codecop/advisor.py ADDED
@@ -0,0 +1,1512 @@
1
+ """A rule-based PostgreSQL index advisor: one minimal set of indexes per table, for every statement that reads it.
2
+
3
+ No agent, no database. Read by rules from every statement text CodeCop knows (SQL in code, ORM-translated SQL, statements
4
+ production ran) and the tables' definitions (the real catalog when pulled; else rank.json's definitions, else the
5
+ inventory's tables with the indexes discovery found in ORM models, CREATE INDEX statements found by a text search of
6
+ the repository, and the primary and unique keys of the CREATE TABLE text).
7
+
8
+ 1. Shapes. Each statement is parsed (sqlglot, never a regex on its text) and, per table it reads, gives: equality
9
+ columns (`= value`, `= ANY(...)` and IN apart), range columns, the ORDER BY when it is followed by LIMIT (with its
10
+ directions), constant predicates (`deleted_at IS NULL`, `disabled IS FALSE`, `status = 'x'` as a literal), filters
11
+ on an immutable function of a column (`lower(email) = $1`), join keys, GROUP BY columns and the columns it reads.
12
+ 2. Candidates. Per read of a table: equality columns, then the sort columns (ORDER BY ... LIMIT) or one range
13
+ column. A join key when the table has no filter of its own there (it is the probed side). An index on the
14
+ expression for a wrapped column. GROUP BY columns when nothing else is read (an index-only read). A constant
15
+ predicate becomes a partial index's WHERE; a literal equality does so only when no statement of the table compares
16
+ that column with anything else (else it stays a key column). IN columns are left out of the key in front of sort
17
+ columns (they would break the order).
18
+ 3. Weights. A statement's measured load when a pull matched it (bytes read in the window: calls x blocks); else its
19
+ code evidence: one per entry point that reaches it, times `static_loop_factor` in a loop. The whole weight of a
20
+ statement counts towards each table it reads.
21
+ 4. Selection. Per table, greedily: the candidate that adds the most served weight over what the existing indexes
22
+ already give (a score per statement: the share of its wanted key that an index's prefix serves, as
23
+ access_postgres's prefix rule reads it), until `max_indexes_per_table` or no candidate adds more than
24
+ `min_gain_share` of the table's weight. A candidate that is a duplicate or a left prefix of an existing index adds
25
+ nothing and is never proposed. Column orders of the equality block are scored as alternatives; two orders with the
26
+ same weight served are both kept and both measured (`alternatives`). A covering variant (INCLUDE) is a separate,
27
+ labelled candidate: index-only reads are flattered right after VACUUM (advisor_bench.py measures it twice).
28
+ 5. Hand-off. A filter on a cast or date function of a column that an existing index would serve unwrapped is not an
29
+ index to add: it goes to the key-not-usable scenario as evidence (`handoffs`).
30
+ 6. Hygiene, evidence only: exact duplicates and redundant left-prefix indexes from the definitions; with a pull,
31
+ invalid indexes and indexes with no scan since statistics began (never "drop it": check before removing).
32
+
33
+ Thresholds are settings under `[advisor]` in codecop.toml (DEFAULTS). The sandbox proof is advisor_bench.py; the shared
34
+ table-level object (`table_suggestions[]`, also written by the ClickHouse advisor) is described in the console's API.
35
+ """
36
+
37
+ from __future__ import annotations
38
+
39
+ import hashlib
40
+ import itertools
41
+ import os
42
+ import dataclasses
43
+ import re
44
+ from collections import defaultdict
45
+ from dataclasses import dataclass, field
46
+ from datetime import datetime, timezone
47
+
48
+ import sqlglot
49
+ from sqlglot import exp
50
+
51
+ from .engines.pg_ddl import Index, IndexColumn, PgTable, foreign_keys, parse_definition, parse_table, split_statements, statement_kind, unquote
52
+
53
+ SCHEMA_VERSION = 1
54
+ FILE = "advisor.json"
55
+ ENGINE = "postgres"
56
+ DEFAULTS = {
57
+ "max_indexes_per_table": 5, # indexes proposed per table, at most (covering variants not counted)
58
+ "max_key_columns": 5, # key columns of one proposed index
59
+ "max_include_columns": 4, # columns a covering variant may add (INCLUDE)
60
+ "max_permuted_columns": 3, # equality blocks up to this size are scored in every order
61
+ "min_gain_share": 0.0, # a candidate must add more than this share of the table's weight to be kept
62
+ "static_loop_factor": 10.0, # without a pull: a statement in a loop weighs this many times one that is not
63
+ "vm_touch_share": 0.2, # index-only claims: share of heap pages rewritten without VACUUM for the honest run
64
+ "regression_ratio": 1.15, # a statement the index does not serve that touches more than this x its pages got worse
65
+ "max_measured_per_suggestion": 40, # statements measured per suggestion (served first, then the table's others)
66
+ "max_tables": 400, # tables looked at per run, heaviest first
67
+ "min_table_rows": 10_000, # a table with fewer rows (real catalog) gets no suggestion: a scan of it is cheap
68
+ # seconds the bench spends building and measuring suggestions, at most (0: no limit); the rest are listed, marked
69
+ # `advisor_time_budget`. The baseline pass sets it from `[baseline] advisor_seconds` so it never waits on the advisor
70
+ "max_bench_seconds": 0,
71
+ }
72
+ BOOL_DEFAULTS = {"covering": True, "expressions": True, "join_keys": True, "partial_from_literals": True, "bind_code_statements": True,
73
+ "group_only_reads": True,
74
+ # a candidate that only adds equality columns to statements an existing index already pins by equality
75
+ "propose_eq_refinements": False,
76
+ # a key made of boolean columns only (by type) is not proposed
77
+ "skip_boolean_keys": True}
78
+ LIST_DEFAULTS = {
79
+ # functions an expression index can be built on (IMMUTABLE in PostgreSQL); a filter on any other function of a
80
+ # column is not given an expression index
81
+ "immutable_functions": ["lower", "upper", "btrim", "ltrim", "rtrim", "trim", "md5", "abs", "length", "char_length",
82
+ "left", "right", "substr", "substring", "reverse", "jsonb_extract_path_text", "json_extract_path_text"],
83
+ # wrappers a rewrite removes (a cast, a date of a timestamp): an existing index on the column serves the rewritten filter
84
+ "rewrite_wrappers": ["cast", "date", "date_trunc", "to_char", "coalesce", "timezone"],
85
+ # statements of these roles are not weighed (inventory role)
86
+ "skip_roles": ["migration", "script", "tooling", "test"],
87
+ }
88
+ STATES = ("fixed", "blocked", "not_judged", "nothing_to_gain")
89
+ STATE_WORDS = {"fixed": "Fixed", "blocked": "Needs another fix", "not_judged": "Could not be judged", "nothing_to_gain": "Nothing to gain"}
90
+ REASONS = {
91
+ "fixed": ("verified",),
92
+ "blocked": ("no_variant_reads_less", "fix_results_differ", "fix_costs_inserts", "insert_cost_near_limit", "fix_slows_other_statements"),
93
+ "not_judged": ("bench_not_run", "statements_not_runnable", "sandbox_table_not_loaded", "sandbox_could_not_run", "sameness_not_shown",
94
+ "insert_cost_not_measured", "parameters_match_no_rows"),
95
+ "nothing_to_gain": ("already_cheap_measured",),
96
+ }
97
+ KINDS = ("index", "partial_index", "covering_index", "expression_index")
98
+ WIDE_TYPE = re.compile(r"\b(?:json|jsonb|bytea|tsvector|xml)\b|\[\]", re.I)
99
+ FRAGMENT = re.compile(r"«[^»]*»|…|\{\{.*?\}\}|\{%.*?%\}", re.S)
100
+ CODECOP_PARAM = re.compile(r"\{(\w+)(?::([^{}]+))?\}")
101
+
102
+
103
+ def settings_of(config: dict | None) -> dict:
104
+ out = {**DEFAULTS, **BOOL_DEFAULTS, **{k: list(v) for k, v in LIST_DEFAULTS.items()}}
105
+ for k, v in (config or {}).items():
106
+ if k in DEFAULTS and isinstance(v, (int, float)) and not isinstance(v, bool) and v >= 0:
107
+ out[k] = type(DEFAULTS[k])(v)
108
+ elif k in BOOL_DEFAULTS and isinstance(v, bool):
109
+ out[k] = v
110
+ elif k in LIST_DEFAULTS and isinstance(v, list) and all(isinstance(x, str) for x in v):
111
+ out[k] = [x.lower() for x in v]
112
+ return out
113
+
114
+
115
+ def short(name) -> str:
116
+ return str(name or "").replace('"', "").replace("`", "").split(".")[-1].lower()
117
+
118
+
119
+ # ---- statements as text the parser takes -------------------------------------------------------------------------
120
+
121
+ RUNTIME = "codecop_rt"
122
+
123
+
124
+ def prepare_sql(text: str) -> tuple[str, bool]:
125
+ """(sql, has_runtime_parts). Each part known only at run time («expr», a template action) becomes a placeholder of
126
+ its own (`:codecop_rt1`): a value the code supplies, never a literal, so `org_id = «org»` stays an equality and a
127
+ WHERE that is entirely «...» narrows nothing. CodeCop's {name:type} parameters, `%(name)s` and `%s` become placeholders
128
+ the parser knows."""
129
+ runtime = bool(FRAGMENT.search(text or ""))
130
+ n = iter(range(1, 10_000))
131
+ sql = FRAGMENT.sub(lambda m: f" :{RUNTIME}{next(n)} ", text or "")
132
+ sql = CODECOP_PARAM.sub(lambda m: f":{m.group(1)}", sql)
133
+ # sqlc's own forms: @name, sqlc.arg('name'), sqlc.narg('name'), sqlc.slice('name'); sqlc.embed(t) selects t's columns
134
+ sql = re.sub(r"\bsqlc\.(?:n?arg|slice)\(\s*'?(\w+)'?\s*\)", r":\1", sql)
135
+ sql = re.sub(r"\bsqlc\.embed\(\s*(\w+)\s*\)", r"\1.*", sql)
136
+ sql = re.sub(r"(?<![\w@'\"])@(\w+)", r":\1", sql)
137
+ sql = re.sub(r"%\((\w+)\)s", r":\1", sql)
138
+ sql = re.sub(r"(?<![%\w])%s\b", "?", sql)
139
+ return sql, runtime
140
+
141
+
142
+ def parse(text: str):
143
+ sql, runtime = prepare_sql(text)
144
+ try:
145
+ tree = sqlglot.parse_one(sql, read="postgres")
146
+ except Exception: # a statement the parser does not take gives no shape (counted, never guessed)
147
+ return None, runtime
148
+ if tree is not None:
149
+ for ident in tree.find_all(exp.Identifier):
150
+ if not ident.quoted and isinstance(ident.this, str):
151
+ ident.set("this", ident.this.lower()) # the server folds an unquoted name to lower case
152
+ return tree, runtime
153
+
154
+
155
+ # ---- one read of one table --------------------------------------------------------------------------------------
156
+
157
+ @dataclass
158
+ class Read:
159
+ """What one SELECT does with one table."""
160
+ table: str
161
+ eq: dict[str, str] = field(default_factory=dict) # column (or "expr:<text>") -> "param" | "literal"
162
+ in_: list[str] = field(default_factory=list)
163
+ range: list[str] = field(default_factory=list)
164
+ sort: list[dict] = field(default_factory=list) # [{column, desc}], only when the select has a LIMIT
165
+ consts: dict[str, str] = field(default_factory=dict) # normalized predicate text -> column
166
+ literal_eq: dict[str, str] = field(default_factory=dict) # column -> its predicate text (`status = 'unread'`)
167
+ joins: list[str] = field(default_factory=list)
168
+ wrapped: list[dict] = field(default_factory=list) # {expr, func, column, op, immutable}
169
+ group: list[str] = field(default_factory=list)
170
+ reads: set[str] | None = field(default_factory=set) # columns read; None for a star
171
+ params: dict[str, tuple] = field(default_factory=dict) # placeholder -> (table, column, op)
172
+ compared: set[str] = field(default_factory=set) # columns compared with a parameter or another column
173
+ runtime: bool = False
174
+ runtime_where: bool = False # a filter of the select is known only at run time
175
+ partners: dict[str, set] = field(default_factory=dict) # join column -> the aliases it is compared with ("" outer, "?" subquery)
176
+
177
+ @property
178
+ def sortmode(self) -> bool:
179
+ return bool(self.sort)
180
+
181
+ @property
182
+ def has_filter(self) -> bool:
183
+ return bool(self.eq or self.in_ or self.range)
184
+
185
+
186
+ def _cls(*names):
187
+ return tuple(c for c in (getattr(exp, n, None) for n in names) if c is not None)
188
+
189
+
190
+ LITERALS = _cls("Literal", "Boolean", "Null")
191
+ PLACEHOLDERS = _cls("Placeholder", "Parameter")
192
+ RANGE_OPS = _cls("GT", "GTE", "LT", "LTE")
193
+
194
+
195
+ def _strip(node):
196
+ while isinstance(node, exp.Paren):
197
+ node = node.this
198
+ return node
199
+
200
+
201
+ def _is_literal(node) -> bool:
202
+ node = _strip(node)
203
+ if isinstance(node, LITERALS):
204
+ return True
205
+ if isinstance(node, (exp.Cast, exp.Neg)) and node.this is not None:
206
+ return _is_literal(node.this)
207
+ return False
208
+
209
+
210
+ def _placeholder(node) -> str | None:
211
+ node = _strip(node)
212
+ if isinstance(node, exp.Cast):
213
+ node = _strip(node.this)
214
+ if isinstance(node, exp.Any):
215
+ node = _strip(node.this)
216
+ if isinstance(node, exp.Cast):
217
+ node = _strip(node.this)
218
+ if isinstance(node, exp.Parameter):
219
+ return "$" + node.this.sql() if node.this is not None else None
220
+ if isinstance(node, exp.Placeholder):
221
+ return ":" + str(node.this) if node.this else "?"
222
+ return None
223
+
224
+
225
+ def conjuncts(node) -> list:
226
+ node = _strip(node)
227
+ if node is None:
228
+ return []
229
+ if isinstance(node, exp.And):
230
+ return conjuncts(node.this) + conjuncts(node.expression)
231
+ return [node]
232
+
233
+
234
+ def _func_name(node) -> str:
235
+ if isinstance(node, exp.Anonymous):
236
+ return str(node.this or "").lower()
237
+ if isinstance(node, exp.Cast):
238
+ return "cast"
239
+ if isinstance(node, (exp.JSONExtractScalar, exp.JSONBExtractScalar)):
240
+ return "->>"
241
+ if isinstance(node, (exp.JSONExtract, exp.JSONBExtract)):
242
+ return "->"
243
+ return type(node).__name__.lower() if isinstance(node, exp.Func) else ""
244
+
245
+
246
+ def _expr_key(node, mine: set[str]) -> str:
247
+ """The normalized text of a wrapped column (`lower(email)`), qualifiers removed: the expression an index is built on."""
248
+ n = node.copy()
249
+ for c in n.find_all(exp.Column):
250
+ if c.table and c.table.lower() in mine:
251
+ c.set("table", None)
252
+ return _expr_text(n)
253
+
254
+
255
+ def _expr_text(n) -> str:
256
+ """An expression as the advisor compares it: casts and parentheses dropped, lower case (`lower((ap_id)::text)` and
257
+ `LOWER(ap_id)` are one expression for an index on it)."""
258
+ n = n.copy()
259
+ while isinstance(n, (exp.Paren, exp.Cast)):
260
+ n = n.this
261
+ for c in list(n.find_all(exp.Cast)):
262
+ c.replace(c.this)
263
+ for p in list(n.find_all(exp.Paren)):
264
+ if isinstance(p.this, (exp.Column, exp.Func, exp.Literal, exp.Paren)):
265
+ p.replace(p.this) # only around one term: parentheses that group an operation are kept
266
+ return re.sub(r"\s+", " ", n.sql(dialect="postgres")).lower()
267
+
268
+
269
+ def norm_expr(text: str) -> str:
270
+ try:
271
+ return _expr_text(sqlglot.parse_one(text, read="postgres"))
272
+ except Exception:
273
+ return re.sub(r"\s+", " ", text.strip()).lower().strip("()")
274
+
275
+
276
+ def pred_text(node, mine: set[str] | None = None) -> str:
277
+ n = _strip(node).copy()
278
+ for c in n.find_all(exp.Column):
279
+ if c.table and (mine is None or c.table.lower() in mine):
280
+ c.set("table", None)
281
+ return re.sub(r"\s+", " ", n.sql(dialect="postgres"))
282
+
283
+
284
+ def norm_where(text: str) -> list[str]:
285
+ """A partial index's WHERE as its sorted conjuncts, each in the form pred_text writes."""
286
+ if not (text or "").strip():
287
+ return []
288
+ try:
289
+ tree = sqlglot.parse_one(f"SELECT 1 FROM t WHERE {text}", read="postgres")
290
+ except Exception:
291
+ return [re.sub(r"\s+", " ", text.strip())]
292
+ return sorted(pred_text(c) for c in conjuncts(tree.args["where"].this))
293
+
294
+
295
+ def _sources(select) -> dict[str, str]:
296
+ out = {}
297
+ for t in select.find_all(exp.Table):
298
+ if t.find_ancestor(exp.Select) is select and t.name:
299
+ out[t.alias_or_name.lower()] = t.name.lower()
300
+ return out
301
+
302
+
303
+ def _outputs(select, mine: set[str]) -> dict[str, str]:
304
+ """Output name -> our column, for ORDER BY items that name a select-list column."""
305
+ out = {}
306
+ for e in select.expressions:
307
+ body = e.this if isinstance(e, exp.Alias) else e
308
+ if isinstance(body, exp.Column) and (not body.table or body.table.lower() in mine) and isinstance(body.this, exp.Identifier):
309
+ out[(e.alias if isinstance(e, exp.Alias) else body.name).lower()] = body.name
310
+ return out
311
+
312
+
313
+ def reads_of(tree, tables: dict[str, set[str]], cfg: dict | None = None, runtime: bool = False) -> list[Read]:
314
+ """Every read of a known table in a parsed statement. `tables`: short name -> its columns (empty set: unknown)."""
315
+ cfg = cfg or settings_of(None)
316
+ immutable = set(cfg["immutable_functions"]) | {"->>", "->", "lower", "upper"}
317
+ rewrite = set(cfg["rewrite_wrappers"])
318
+ out: list[Read] = []
319
+ here: list[tuple] = []
320
+ if tree is None:
321
+ return out
322
+ for select in tree.find_all(exp.Select):
323
+ sources = _sources(select)
324
+ for short_name, columns in tables.items():
325
+ mine = {a for a, n in sources.items() if n == short_name}
326
+ if not mine:
327
+ continue
328
+ alone = len(sources) == 1
329
+ r = Read(table=short_name, runtime=runtime)
330
+
331
+ def ours(col) -> bool:
332
+ if not isinstance(col, exp.Column) or not isinstance(col.this, exp.Identifier):
333
+ return False
334
+ if col.table:
335
+ return col.table.lower() in mine
336
+ return alone or (bool(columns) and col.name in columns)
337
+
338
+ def our_cols(node) -> list:
339
+ return [c for c in node.find_all(exp.Column) if ours(c) and c.find_ancestor(exp.Select) is select]
340
+
341
+ clauses = [select.args.get("where")] + [j.args.get("on") for j in select.args.get("joins") or []]
342
+ for clause in clauses:
343
+ if clause is None:
344
+ continue
345
+ if any(str(p.this or "").startswith(RUNTIME) for p in clause.find_all(exp.Placeholder)
346
+ if p.find_ancestor(exp.Select) is select and not isinstance(p.parent, (exp.EQ, exp.In) + RANGE_OPS)):
347
+ r.runtime_where = True # a whole condition is assembled at run time: what it filters is not known
348
+ for c in conjuncts(clause.this if isinstance(clause, exp.Where) else clause):
349
+ _conjunct(c, r, ours, our_cols, mine, immutable, rewrite)
350
+ order = select.args.get("order")
351
+ if order is not None and select.args.get("limit") is not None:
352
+ outs = _outputs(select, mine)
353
+ aliases = {e.alias.lower() for e in select.expressions if isinstance(e, exp.Alias) and e.alias}
354
+ sort = []
355
+ for o in order.expressions:
356
+ t = _strip(o.this)
357
+ name = None
358
+ if isinstance(t, exp.Column) and not t.table and t.name.lower() in outs:
359
+ name = outs[t.name.lower()]
360
+ elif isinstance(t, exp.Column) and not t.table and t.name.lower() in aliases:
361
+ name = None # the output of an expression (ORDER BY total_spend, SUM(spend) AS total_spend)
362
+ elif ours(t):
363
+ name = t.name
364
+ if name is None:
365
+ sort = []
366
+ break
367
+ sort.append({"column": name, "desc": bool(o.args.get("desc"))})
368
+ r.sort = sort
369
+ group = select.args.get("group")
370
+ if group is not None:
371
+ r.group = [g.name for g in group.expressions if ours(_strip(g))]
372
+ star = any(isinstance(e, exp.Star) or (isinstance(e, exp.Column) and isinstance(e.this, exp.Star)
373
+ and (not e.table or e.table.lower() in mine)) for e in select.expressions)
374
+ r.reads = None if star else {c.name for c in select.find_all(exp.Column) if ours(c) or
375
+ (c.table and c.table.lower() in mine and isinstance(c.this, exp.Identifier))}
376
+ r.partners = {k: {("" if a not in sources and a != "?" else a) for a in v} for k, v in r.partners.items()}
377
+ here.append((r, mine, sources))
378
+ out.append(_canon(r, columns))
379
+ # a join key is a probe key only when the table is the probed side: its partner is an outer row (a correlated
380
+ # subquery, a semi-join) or a table this select filters; joined to tables nothing filters, it is driven instead
381
+ filtered = {a for r, mine, _ in here if r.has_filter for a in mine}
382
+ for r, mine, sources in here:
383
+ r.joins = [c for c in r.joins if any(a in ("", "?") or a in filtered for a in r.partners.get(c, {""}))]
384
+ for c in r.joins:
385
+ if "" in r.partners.get(c, set()):
386
+ r.eq.setdefault(c, "param") # compared with an outer row (a correlated subquery): one value per run
387
+ here.clear()
388
+ return out
389
+
390
+
391
+ def _canon(r: Read, columns: set[str]) -> Read:
392
+ """Column names as the table's definition writes them: an unquoted name is folded to lower case by the server, so
393
+ `UserId` in a statement is the column `userid` (or `UserId` when the definition quotes it)."""
394
+ if not columns:
395
+ return r
396
+ lower = {c.lower(): c for c in columns}
397
+
398
+ def c(name: str) -> str:
399
+ return name if name.startswith("expr:") else lower.get(name.lower(), name)
400
+ r.eq = {c(k): v for k, v in r.eq.items()}
401
+ r.in_ = [c(x) for x in r.in_]
402
+ r.range = [c(x) for x in r.range]
403
+ r.sort = [{**x, "column": c(x["column"])} for x in r.sort]
404
+ r.consts = {k: c(v) for k, v in r.consts.items()}
405
+ r.literal_eq = {c(k): v for k, v in r.literal_eq.items()}
406
+ r.joins = [c(x) for x in r.joins]
407
+ r.partners = {c(k): v for k, v in r.partners.items()}
408
+ r.group = [c(x) for x in r.group]
409
+ r.reads = None if r.reads is None else {c(x) for x in r.reads}
410
+ r.params = {k: (t, c(col), op) for k, (t, col, op) in r.params.items()}
411
+ r.compared = {c(x) for x in r.compared}
412
+ for w in r.wrapped:
413
+ w["column"] = c(w["column"])
414
+ return r
415
+
416
+
417
+ def _conjunct(c, r: Read, ours, our_cols, mine, immutable, rewrite) -> None:
418
+ c = _strip(c)
419
+ if isinstance(c, (exp.Or,)):
420
+ return # one branch of an OR narrows nothing on its own (an optional filter `$1 IS NULL OR ...`)
421
+ if isinstance(c, exp.Not):
422
+ inner = _strip(c.this)
423
+ if ours(inner):
424
+ r.consts[pred_text(c, mine)] = inner.name
425
+ elif isinstance(inner, exp.Is) and ours(_strip(inner.this)):
426
+ r.consts[pred_text(c, mine)] = _strip(inner.this).name
427
+ return
428
+ if ours(c): # a bare boolean column
429
+ r.consts[pred_text(c, mine)] = c.name
430
+ return
431
+ if isinstance(c, exp.Is):
432
+ col = _strip(c.this)
433
+ if ours(col) and isinstance(_strip(c.expression), (exp.Null, exp.Boolean)):
434
+ r.consts[pred_text(c, mine)] = col.name
435
+ return
436
+ if isinstance(c, exp.NEQ):
437
+ col, other = _strip(c.this), c.expression
438
+ if ours(col) and _is_literal(other):
439
+ r.consts[pred_text(c, mine)] = col.name
440
+ return
441
+ if isinstance(c, exp.In):
442
+ col = _strip(c.this)
443
+ if ours(col) and c.args.get("query") is not None:
444
+ if col.name not in r.joins:
445
+ r.joins.append(col.name) # IN (subquery): a semi-join on the column, a key probed per row like a join's
446
+ r.partners.setdefault(col.name, set()).add("?")
447
+ r.compared.add(col.name)
448
+ return
449
+ if ours(col) and not our_cols(exp.Tuple(expressions=list(c.expressions or [])) if c.expressions else c.args.get("query") or exp.Null()):
450
+ if col.name not in r.in_:
451
+ r.in_.append(col.name)
452
+ for e in c.expressions or []:
453
+ p = _placeholder(e)
454
+ if p:
455
+ r.params[p] = (r.table, col.name, "in")
456
+ r.compared.add(col.name)
457
+ return
458
+ if isinstance(c, exp.Between):
459
+ col = _strip(c.this)
460
+ if ours(col):
461
+ _add_range(r, col.name)
462
+ for side in (c.args.get("low"), c.args.get("high")):
463
+ p = _placeholder(side)
464
+ if p:
465
+ r.params[p] = (r.table, col.name, "range")
466
+ return
467
+ if isinstance(c, exp.EQ) and isinstance(_strip(c.this), exp.Tuple) and isinstance(_strip(c.expression), exp.Tuple):
468
+ for a, b in zip(_strip(c.this).expressions, _strip(c.expression).expressions):
469
+ _conjunct(exp.EQ(this=a, expression=b), r, ours, our_cols, mine, immutable, rewrite)
470
+ return
471
+ if not isinstance(c, (exp.EQ,) + RANGE_OPS):
472
+ return
473
+ op = "eq" if isinstance(c, exp.EQ) else "range"
474
+ for target, other in ((c.this, c.expression), (c.expression, c.this)):
475
+ t, o = _strip(target), _strip(other)
476
+ if ours(t):
477
+ if ours(o):
478
+ return # two columns of one table compared: not an index condition
479
+ if isinstance(o, exp.Column):
480
+ if op == "eq" and t.name not in r.joins:
481
+ r.joins.append(t.name) # a join key
482
+ if op == "eq":
483
+ r.partners.setdefault(t.name, set()).add((o.table or "").lower())
484
+ r.compared.add(t.name)
485
+ return
486
+ if our_cols(o):
487
+ return
488
+ if op == "eq":
489
+ if isinstance(o, exp.Any):
490
+ if t.name not in r.in_:
491
+ r.in_.append(t.name)
492
+ kind = "any"
493
+ elif _is_literal(o):
494
+ r.eq.setdefault(t.name, "literal")
495
+ r.literal_eq[t.name] = pred_text(c, mine)
496
+ kind = "eq"
497
+ else:
498
+ r.eq[t.name] = "param"
499
+ r.compared.add(t.name)
500
+ kind = "eq"
501
+ p = _placeholder(o)
502
+ if p:
503
+ r.params[p] = (r.table, t.name, kind)
504
+ else:
505
+ _add_range(r, t.name)
506
+ r.compared.add(t.name)
507
+ p = _placeholder(o)
508
+ if p:
509
+ r.params[p] = (r.table, t.name, "range")
510
+ return
511
+ cols = our_cols(t) if t is not None else []
512
+ if cols and len({x.name for x in cols}) == 1 and not our_cols(o) and not isinstance(t, exp.Column):
513
+ name = _func_name(t)
514
+ text = _expr_key(t, mine)
515
+ r.wrapped.append({"expr": text, "func": name, "column": cols[0].name, "op": op,
516
+ "immutable": name in immutable and not t.find(exp.Cast), "rewrite": name in rewrite})
517
+ if name in immutable and not t.find(exp.Cast):
518
+ key = "expr:" + text
519
+ if op == "eq":
520
+ r.eq[key] = "literal" if _is_literal(o) else "param"
521
+ else:
522
+ _add_range(r, key)
523
+ r.compared.add(key)
524
+ return
525
+
526
+
527
+ def _add_range(r: Read, col: str) -> None:
528
+ if col not in r.range:
529
+ r.range.append(col)
530
+
531
+
532
+ # ---- candidates and how well an index serves a read --------------------------------------------------------------
533
+
534
+ @dataclass(frozen=True)
535
+ class Key:
536
+ """An index as the advisor reasons about it: btree key columns ((name, desc, sort?)), INCLUDE, partial WHERE."""
537
+ cols: tuple # ((name, desc), ...) ; name "expr:<text>" for an expression
538
+ include: tuple = ()
539
+ where: tuple = () # sorted normalized conjuncts
540
+ method: str = "btree"
541
+ unique: bool = False
542
+
543
+ @property
544
+ def names(self) -> list[str]:
545
+ return [c[0] for c in self.cols]
546
+
547
+ def ident(self) -> tuple:
548
+ return (self.method, tuple(c[0] for c in self.cols), tuple(c[1] for c in self.cols), tuple(sorted(self.include)), self.where)
549
+
550
+
551
+ def key_of_index(ix: Index) -> Key:
552
+ cols = tuple(((c.column if c.column else "expr:" + norm_expr(c.text)), c.desc) for c in ix.columns)
553
+ return Key(cols=cols, include=tuple(ix.include), where=tuple(norm_where(ix.where)), method=ix.method, unique=ix.unique)
554
+
555
+
556
+ def _ideal_len(r: Read, satisfied: set[str]) -> tuple[list[str], list[dict]]:
557
+ need = [c for c in r.eq if c not in satisfied]
558
+ sort = [s for s in r.sort if s["column"] not in r.eq]
559
+ return need, sort
560
+
561
+
562
+ def score(k: Key, r: Read, group_only: bool = False) -> float:
563
+ """How much of what `r` wants from an index `k` gives, 0..1, by the prefix rule (access_postgres)."""
564
+ if k.method != "btree" or not k.cols:
565
+ return 0.0
566
+ if not set(k.where) <= set(r.consts) | set(r.literal_eq.values()):
567
+ return 0.0 # the read does not imply the partial index's predicate
568
+ if group_only:
569
+ g = set(r.group)
570
+ reads = r.reads if r.reads is not None else None
571
+ covered = set(k.names) | set(k.include)
572
+ # only an index of the grouped columns alone is narrow enough to be read whole instead of the table
573
+ return 1.0 if g and set(k.names) == g and reads is not None and reads <= covered else 0.0
574
+ satisfied = {c for c, text in r.literal_eq.items() if text in k.where}
575
+ need, sort = _ideal_len(r, satisfied)
576
+ need_set = set(need) | (set(r.joins) if not r.has_filter else set())
577
+ if not r.has_filter:
578
+ need = list(need_set)
579
+ total = len(need_set) + (len(sort) if sort else (1 if r.range else 0))
580
+ if total == 0:
581
+ return 0.0
582
+ used, i, pinned_in = 0, 0, False
583
+ names = k.names
584
+ allowed = need_set | set(r.in_) | satisfied | set(r.eq) | set(r.joins) # a join key is pinned at probe time
585
+ while i < len(names) and names[i] in allowed:
586
+ if names[i] in need_set:
587
+ used += 1
588
+ if names[i] in r.in_ and names[i] not in need_set:
589
+ pinned_in = True
590
+ i += 1
591
+ all_eq = need_set <= set(names[:i])
592
+ if sort:
593
+ rest = k.cols[i:i + len(sort)]
594
+ if all_eq and not pinned_in and len(rest) == len(sort) and all(c[0] == s["column"] for c, s in zip(rest, sort)) \
595
+ and len({c[1] != s["desc"] for c, s in zip(rest, sort)}) == 1:
596
+ used += len(sort)
597
+ elif i < len(names) and names[i] in r.range:
598
+ used += 0.5 # the range narrows, the sort is still done
599
+ elif r.range and i < len(names) and names[i] in r.range:
600
+ used += 1
601
+ return min(used / total, 1.0)
602
+
603
+
604
+ def _norm_dir(cols: list[tuple]) -> tuple:
605
+ """A key with every direction flipped is the same index read backwards: the canonical form starts ascending."""
606
+ if cols and cols[0][1]:
607
+ cols = [(n, not d) for n, d in cols]
608
+ return tuple(cols)
609
+
610
+
611
+ def prefix_of(a: Key, b: Key) -> bool:
612
+ """`a` is `b` or a left prefix of it, read in one direction, with the same partial predicate and INCLUDE covered."""
613
+ if a.method != b.method or a.where != b.where or len(a.cols) > len(b.cols):
614
+ return False
615
+ if [c[0] for c in a.cols] != [c[0] for c in b.cols[:len(a.cols)]]:
616
+ return False
617
+ flips = {x[1] != y[1] for x, y in zip(a.cols, b.cols)}
618
+ if len(flips) > 1 and any(x[1] or y[1] for x, y in zip(a.cols, b.cols)):
619
+ # directions disagree on some columns and not on others: only equal-direction prefixes are the same order
620
+ return False
621
+ return set(a.include) <= set(b.names) | set(b.include)
622
+
623
+
624
+ def candidates_for(r: Read, cfg: dict, literal_only: set[str]) -> list[tuple[Key, str]]:
625
+ """The ideal index (and its forms) for one read: [(key, kind)]."""
626
+ out: list[tuple[Key, str]] = []
627
+ where_all = tuple(sorted(set(r.consts)))
628
+ eq = [c for c in r.eq if cfg["expressions"] or not c.startswith("expr:")]
629
+ lit_where = tuple(sorted(set(where_all) | {r.literal_eq[c] for c in eq if c in literal_only and c in r.literal_eq}))
630
+ eq_key = [c for c in eq if c not in literal_only or c not in r.literal_eq]
631
+ for keep_lit in ((True, False) if cfg["partial_from_literals"] and len(eq_key) != len(eq) else (True,)):
632
+ cols = eq if keep_lit else eq_key
633
+ where = where_all if keep_lit else lit_where
634
+ if r.has_filter:
635
+ tail: list[tuple] = []
636
+ if r.sort:
637
+ tail = [(s["column"], s["desc"]) for s in r.sort if s["column"] not in cols]
638
+ key = [(c, False) for c in cols] + tail
639
+ else:
640
+ key = [(c, False) for c in cols] + [(c, False) for c in r.in_ if c not in cols] + [(c, False) for c in r.range[:1] if c not in cols]
641
+ key = key[:cfg["max_key_columns"]]
642
+ if key:
643
+ kind = "expression_index" if any(c[0].startswith("expr:") for c in key) else "partial_index" if where else "index"
644
+ out.append((Key(cols=tuple(key), where=where), kind))
645
+ if where and r.sort:
646
+ pass
647
+ elif r.joins and cfg["join_keys"]:
648
+ key = [(c, False) for c in r.joins][:cfg["max_key_columns"]]
649
+ out.append((Key(cols=tuple(key), where=where), "partial_index" if where else "index"))
650
+ elif r.sort and where:
651
+ key = [(s["column"], s["desc"]) for s in r.sort][:cfg["max_key_columns"]]
652
+ out.append((Key(cols=tuple(key), where=where), "partial_index"))
653
+ if not r.has_filter and not r.joins and r.group and cfg["group_only_reads"] and r.reads is not None and set(r.reads) <= set(r.group):
654
+ out.append((Key(cols=tuple((g, False) for g in r.group)[:cfg["max_key_columns"]], where=where_all), "covering_index"))
655
+ return out
656
+
657
+
658
+ def permutations(k: Key, r_eq: set[str], cfg: dict) -> list[Key]:
659
+ """`k` with its leading equality block in every order (when it is short enough)."""
660
+ n = 0
661
+ while n < len(k.cols) and k.cols[n][0] in r_eq and not k.cols[n][1]:
662
+ n += 1
663
+ if n < 2 or n > cfg["max_permuted_columns"]:
664
+ return [k]
665
+ head, tail = k.cols[:n], k.cols[n:]
666
+ return [Key(cols=tuple(p) + tail, include=k.include, where=k.where) for p in itertools.permutations(head)]
667
+
668
+
669
+ # ---- definitions ---------------------------------------------------------------------------------------------------
670
+
671
+ @dataclass
672
+ class TableDef:
673
+ name: str # as created (case kept)
674
+ columns: dict[str, str]
675
+ indexes: list[Index]
676
+ source: str # real catalog | repository | assembled
677
+ index_basis: list[str] = field(default_factory=list)
678
+ foreign_keys: list[dict] = field(default_factory=list)
679
+ catalog_indexes: list[dict] = field(default_factory=list) # pulled: name, is_valid, scans, bytes, is_unique, is_primary
680
+ rows: int | None = None
681
+ create_sql: str = ""
682
+ is_view: bool = False # a view (CREATE VIEW found in the repository): an index can not be built on it
683
+
684
+
685
+ RESERVED = {"all", "analyse", "analyze", "and", "any", "array", "as", "asc", "asymmetric", "both", "case", "cast", "check", "collate", "column",
686
+ "constraint", "create", "current_catalog", "current_date", "current_role", "current_time", "current_timestamp", "current_user",
687
+ "default", "deferrable", "desc", "distinct", "do", "else", "end", "except", "false", "fetch", "for", "foreign", "from", "grant",
688
+ "group", "having", "in", "initially", "intersect", "into", "lateral", "leading", "limit", "localtime", "localtimestamp", "not",
689
+ "null", "offset", "on", "only", "or", "order", "placing", "primary", "references", "returning", "select", "session_user", "some",
690
+ "symmetric", "table", "then", "to", "trailing", "true", "union", "unique", "user", "using", "variadic", "when", "where", "window",
691
+ "with", "authorization", "binary", "collation", "concurrently", "cross", "current_schema", "freeze", "full", "ilike", "inner",
692
+ "is", "isnull", "join", "left", "like", "natural", "notnull", "outer", "overlaps", "right", "similar", "tablesample", "verbose"}
693
+
694
+
695
+ def _ident(name: str) -> str:
696
+ """A name as DDL writes it: bare when the server folds it to itself and it is not a reserved word, else quoted."""
697
+ return name if re.fullmatch(r"[a-z_][a-z0-9_$]*", name) and name not in RESERVED else '"' + name.replace('"', '""') + '"'
698
+
699
+
700
+ def qualified(name: str) -> str:
701
+ return ".".join(_ident(p) for p in name.split("."))
702
+
703
+
704
+ def _table_text(root: str | None, defined_at: list[str]) -> list[str]:
705
+ """CREATE TABLE statements at the places discovery recorded (file:line), read from the repository."""
706
+ from .discover.schema import _balanced
707
+ out = []
708
+ for d in defined_at or []:
709
+ f, _, ln = str(d).rpartition(":")
710
+ if not root or not f or not ln.isdigit():
711
+ continue
712
+ try:
713
+ text = open(os.path.join(root, f), errors="replace").read()
714
+ except OSError:
715
+ continue
716
+ start = sum(len(x) + 1 for x in text.split("\n")[:max(int(ln) - 1, 0)])
717
+ m = re.search(r"CREATE\s+(?:UNLOGGED\s+)?TABLE[^(;]*\(", text[start:start + 600], re.I)
718
+ if not m:
719
+ continue
720
+ open_at = start + m.end() - 1
721
+ end = _balanced(text, open_at)
722
+ if end > 0:
723
+ out.append(text[start + m.start():end])
724
+ return out
725
+
726
+
727
+ def definitions(inventory: dict | None, rank: dict | None = None, facts=None, root: str | None = None,
728
+ wanted: set[str] | None = None) -> dict[str, TableDef]:
729
+ """Short name -> the table's definition with every index known, by the best source there is."""
730
+ out: dict[str, TableDef] = {}
731
+ inv_tables = {short(t.get("name")): t for t in (inventory or {}).get("tables") or [] if not t.get("test_only") and t.get("name")}
732
+ names = set(wanted or inv_tables) | {short(d["name"]) for d in (rank or {}).get("table_definitions") or []}
733
+ # 1. the real catalog
734
+ if facts:
735
+ try:
736
+ real = facts.tables(ENGINE) or {}
737
+ except Exception:
738
+ real = {}
739
+ for key, t in real.items():
740
+ s = short(key)
741
+ if s not in names or not t.get("create_sql"):
742
+ continue
743
+ pt = parse_definition(t["create_sql"], t.get("name") or key)
744
+ out[s] = TableDef(name=pt.name.split(".")[-1] if pt.name else t.get("name"), columns=dict(pt.columns), indexes=list(pt.indexes),
745
+ source="real catalog", index_basis=["catalog"], foreign_keys=foreign_keys(t["create_sql"]),
746
+ catalog_indexes=[{k: i.get(k) for k in ("name", "is_valid", "scans", "bytes", "is_unique", "is_primary")}
747
+ for i in t.get("indexes") or []], rows=t.get("rows"), create_sql=t["create_sql"])
748
+ # 2. rank.json's definitions: what the sandbox builds
749
+ for d in (rank or {}).get("table_definitions") or []:
750
+ s = short(d["name"])
751
+ if s in out or not d.get("create_sql"):
752
+ continue
753
+ pt = parse_definition(d["create_sql"], d["name"])
754
+ out[s] = TableDef(name=pt.name or d["name"], columns=dict(pt.columns), indexes=list(pt.indexes),
755
+ source="assembled" if d.get("inferred") else "repository", index_basis=["rank.json definition"],
756
+ foreign_keys=foreign_keys(d["create_sql"]), rows=d.get("rows"), create_sql=d["create_sql"])
757
+ # 3. the inventory: ORM indexes, CREATE INDEX found by text search, keys of the CREATE TABLE text
758
+ rest = {n for n in names if n not in out and n in inv_tables}
759
+ found: dict[str, list[dict]] = {}
760
+ dropped: dict[str, tuple] = {}
761
+ if rest and root:
762
+ from .engines.pg_hints import index_statements
763
+ views: set[str] = set()
764
+ found, dropped = index_statements(root, rest, views=views)
765
+ for v in views & rest:
766
+ out[v] = TableDef(name=str(inv_tables[v]["name"]).split(".")[-1], columns={}, indexes=[], source="repository",
767
+ index_basis=["view"], is_view=True)
768
+ rest -= views
769
+ for s in sorted(rest):
770
+ t = inv_tables[s]
771
+ cols = {c["name"]: c.get("type") or "text" for c in t.get("columns") or [] if isinstance(c, dict) and c.get("name")}
772
+ name = str(t["name"]).split(".")[-1]
773
+ basis: list[str] = []
774
+ indexes: list[Index] = []
775
+ fks: list[dict] = []
776
+ for text in _table_text(root, t.get("defined_at") or []):
777
+ pt = parse_table(text)
778
+ if pt is None:
779
+ continue
780
+ for ix in pt.indexes:
781
+ if ix.name not in {i.name for i in indexes}:
782
+ indexes.append(ix)
783
+ fks += foreign_keys(text)
784
+ basis.append("create_table")
785
+ for k, ix in enumerate(t.get("indexes") or []):
786
+ cc = [c for c in ix.get("columns") or [] if isinstance(c, str) and c]
787
+ if not cc:
788
+ continue
789
+ indexes.append(Index(name=ix.get("name") or f"{name}_orm_{k}", table=name, unique=bool(ix.get("unique")), primary=bool(ix.get("primary")),
790
+ columns=[IndexColumn(text=c, column=c) for c in cc]))
791
+ basis.append("orm") if "orm" not in basis else None
792
+ for h in found.get(s, []):
793
+ if h.get("test"):
794
+ continue
795
+ stmt = statement_kind(h["sql"])
796
+ from .engines.pg_ddl import parse_index
797
+ ix = parse_index(h["sql"]) if stmt in ("index", "unique_index") else None
798
+ if ix is None:
799
+ continue
800
+ gone = dropped.get(ix.name.lower())
801
+ if gone and gone > (h.get("file", ""), h.get("line", 0)):
802
+ continue # dropped by a later migration
803
+ if ix.name not in {i.name for i in indexes}:
804
+ indexes.append(ix)
805
+ if "text_search" not in basis:
806
+ basis.append("text_search")
807
+ pk = [c.strip().strip('"`') for c in str(t.get("primary_key") or "").split(",") if re.fullmatch(r"\s*[\"`]?\w+[\"`]?\s*", c)]
808
+ if pk and not any(i.primary for i in indexes) and all(c in cols or not cols for c in pk):
809
+ indexes.append(Index(name=f"{name}_pkey", table=name, unique=True, primary=True, columns=[IndexColumn(text=c, column=c) for c in pk]))
810
+ basis.append("primary_key")
811
+ elif not any(i.primary for i in indexes) and "id" in cols:
812
+ indexes.append(Index(name=f"{name}_pkey", table=name, unique=True, primary=True, columns=[IndexColumn(text="id", column="id")]))
813
+ basis.append("primary_key_assumed")
814
+ out[s] = TableDef(name=name, columns=cols, indexes=_one_per_source(indexes, name), source="repository", index_basis=basis, foreign_keys=fks)
815
+ return out
816
+
817
+
818
+ def _one_per_source(indexes: list[Index], table: str) -> list[Index]:
819
+ """One index seen by two sources (an ORM model and the migration that creates it, a CREATE TABLE key and the
820
+ inventory's primary key) is one index: kept once, with its real name when one source has it. Two indexes of the same
821
+ key from one source stay two (a real duplicate, for hygiene)."""
822
+ out: list[Index] = []
823
+ seen: dict[tuple, Index] = {}
824
+ for ix in indexes:
825
+ k = key_of_index(ix)
826
+ ident = (k.method, tuple(k.names), _norm_dir(list(k.cols)), k.where, tuple(sorted(k.include)))
827
+ prev = seen.get(ident)
828
+ synthetic = lambda i: not i.name or i.name.endswith("_pkey") and i.primary or f"{table}_orm_" in i.name # noqa: E731
829
+ if prev is not None and (synthetic(ix) or synthetic(prev)):
830
+ if synthetic(prev) and not synthetic(ix):
831
+ ix.unique, ix.primary = ix.unique or prev.unique, ix.primary or prev.primary
832
+ out[out.index(prev)] = ix
833
+ seen[ident] = ix
834
+ else:
835
+ prev.unique, prev.primary = prev.unique or ix.unique, prev.primary or ix.primary
836
+ continue
837
+ seen.setdefault(ident, ix)
838
+ out.append(ix)
839
+ return out
840
+
841
+
842
+ # ---- statements and their weights --------------------------------------------------------------------------------
843
+
844
+ def statements(inventory: dict | None, facts=None, cfg: dict | None = None) -> list[dict]:
845
+ """Every SELECT text CodeCop knows, once, with its weight: measured (a pull matched it) or static (code evidence)."""
846
+ from .scenarios import statements as all_statements
847
+ cfg = cfg or settings_of(None)
848
+ skip = set(cfg["skip_roles"])
849
+ raw = all_statements(inventory, facts, ENGINE if facts else None)
850
+ pulled = [s for s in raw if s["sql_from"] == "query_log"]
851
+ by_site: dict[str, dict] = {}
852
+ for q in pulled:
853
+ if q.get("located") in ("exact", "template", "tag"):
854
+ for sid in q.get("site_ids") or []:
855
+ by_site.setdefault(sid, q)
856
+ sites = {c.get("id"): c for c in (inventory or {}).get("call_sites") or [] if c.get("id")}
857
+ out: dict[str, dict] = {}
858
+ used_shapes: set[str] = set()
859
+ from .advisors import owns
860
+ for s in raw:
861
+ if s["sql_from"] == "query_log" or not owns(s.get("engine"), ENGINE, inventory):
862
+ continue
863
+ from .rank import site_role
864
+ if (s.get("role") or "") in skip or site_role(s) in skip:
865
+ continue
866
+ site = sites.get((s.get("site_ids") or [None])[0]) or {}
867
+ key = "h:" + (site.get("sql_hash") or hashlib.sha1(s["text"].encode()).hexdigest()[:12])
868
+ q = next((by_site[x] for x in s.get("site_ids") or [] if x in by_site), None)
869
+ st = out.get(key)
870
+ if st is None:
871
+ st = out[key] = {"ref": s["ref"], "refs": [], "sql_from": s["sql_from"], "text": s["text"], "site_ids": [], "file": s.get("file"),
872
+ "line": s.get("line"), "symbol": s.get("symbol"), "hash": None, "static": 0.0, "measured": None}
873
+ st["refs"].append(s["ref"])
874
+ st["site_ids"] += [x for x in s.get("site_ids") or [] if x]
875
+ origins = max(int(site.get("origin_count") or 0), 1)
876
+ st["static"] += origins * (cfg["static_loop_factor"] if site.get("in_loop") else 1.0)
877
+ if q is not None and q["hash"] not in used_shapes:
878
+ used_shapes.add(q["hash"])
879
+ st["hash"] = q["hash"]
880
+ st["measured"] = (st["measured"] or 0) + int((q.get("measured") or {}).get("read_bytes") or 0)
881
+ st["measured_text"] = q["text"]
882
+ for q in pulled:
883
+ if q["hash"] in used_shapes:
884
+ continue
885
+ out["q:" + q["hash"]] = {"ref": q["ref"], "refs": [q["ref"]], "sql_from": "query_log", "text": q["text"], "site_ids": q.get("site_ids") or [],
886
+ "file": None, "line": None, "symbol": None, "hash": q["hash"], "static": 0.0,
887
+ "measured": int((q.get("measured") or {}).get("read_bytes") or 0)}
888
+ return list(out.values())
889
+
890
+
891
+ def update_columns(inventory: dict | None) -> dict[str, set[str]]:
892
+ """Table -> columns some UPDATE statement in the code sets: an index on one of them costs those updates their HOT path."""
893
+ from .advisors import owns
894
+ out: dict[str, set[str]] = defaultdict(set)
895
+ for s in (inventory or {}).get("call_sites") or []:
896
+ if s.get("is_test") or s.get("statement") != "update" or not s.get("sql") or not owns(s.get("engine"), ENGINE, inventory):
897
+ continue
898
+ tree, _ = parse(s["sql"])
899
+ if not isinstance(tree, exp.Update):
900
+ continue
901
+ t = tree.this
902
+ name = short(t.name if isinstance(t, exp.Table) else "")
903
+ for e in tree.expressions or []:
904
+ if isinstance(e, exp.EQ) and isinstance(e.this, exp.Column):
905
+ out[name].add(e.this.name)
906
+ return out
907
+
908
+
909
+ # ---- the advisor ---------------------------------------------------------------------------------------------------
910
+
911
+ def index_name(table: str, k: Key) -> str:
912
+ parts = [re.sub(r"\W+", "_", n.removeprefix("expr:")).strip("_") for n in k.names]
913
+ base = f"codecop_{short(table)}_{'_'.join(parts)}"
914
+ if k.include:
915
+ base += "_cov"
916
+ if k.where:
917
+ base += "_part"
918
+ base = re.sub(r"_+", "_", base).lower()
919
+ if len(base) > 55:
920
+ base = base[:46] + "_" + hashlib.sha1(repr(k.ident()).encode()).hexdigest()[:8]
921
+ return base + "_idx" if not base.endswith("_idx") else base
922
+
923
+
924
+ def ddl_of(table: str, k: Key, name: str) -> str:
925
+ cols = []
926
+ for n, d in k.cols:
927
+ text = f"({n.removeprefix('expr:')})" if n.startswith("expr:") else _ident(n)
928
+ cols.append(text + (" DESC" if d else ""))
929
+ inc = f" INCLUDE ({', '.join(_ident(c) for c in k.include)})" if k.include else ""
930
+ where = f" WHERE {' AND '.join(k.where)}" if k.where else ""
931
+ return f"CREATE INDEX {name} ON {qualified(table)} ({', '.join(cols)}){inc}{where}"
932
+
933
+
934
+ def _key_public(k: Key) -> dict:
935
+ return {"columns": [{"column": n.removeprefix("expr:"), "expression": n.startswith("expr:"), "desc": d} for n, d in k.cols],
936
+ "include": list(k.include), "where": " AND ".join(k.where), "method": k.method}
937
+
938
+
939
+ def _wanted(r: Read) -> dict:
940
+ return {"eq": sorted(r.eq), "in": list(r.in_), "range": list(r.range[:1]), "sort": list(r.sort), "consts": sorted(r.consts),
941
+ "joins": list(r.joins) if not r.has_filter else [], "group": list(r.group)}
942
+
943
+
944
+ def advise(inventory: dict | None, rank: dict | None = None, facts=None, root: str | None = None, settings: dict | None = None) -> dict:
945
+ """advisor.json: per table, the existing indexes, the proposed ones with the statements each serves, and hygiene."""
946
+ cfg = settings_of(settings)
947
+ stmts = statements(inventory, facts, cfg)
948
+ # the tables the statements read
949
+ wanted: set[str] = set()
950
+ parsed = []
951
+ unparsed = 0
952
+ # a text with parts known only at run time is read from the statement as it runs when there is one: the one production
953
+ # ran (a pull), else the runnable form a ranked candidate carries (rank.json; its text was completed by the agent)
954
+ runnable = {c["id"]: c["baseline_sql"] for c in (rank or {}).get("candidates") or []
955
+ if c.get("sql_from") != "query_log" and c.get("id") and c.get("baseline_sql")}
956
+ for st in stmts:
957
+ text, st["text_from"] = st["text"], "code" if st["sql_from"] != "query_log" else "query_log"
958
+ if FRAGMENT.search(st["text"] or ""):
959
+ if st.get("measured_text"):
960
+ text, st["text_from"] = st["measured_text"], "query_log"
961
+ elif any(x in runnable for x in st.get("site_ids") or []):
962
+ text, st["text_from"] = next(runnable[x] for x in st["site_ids"] if x in runnable), "rank"
963
+ tree, runtime = parse(text)
964
+ if tree is None:
965
+ unparsed += 1
966
+ continue
967
+ names = {short(t.name) for t in tree.find_all(exp.Table) if t.name}
968
+ wanted |= names
969
+ parsed.append((st, tree, runtime, text))
970
+ defs = definitions(inventory, rank, facts, root, wanted)
971
+ cols = {s: set(d.columns) for s, d in defs.items()}
972
+ updated = update_columns(inventory)
973
+ per_table: dict[str, list[tuple[dict, Read]]] = defaultdict(list)
974
+ measured_any = any(st.get("measured") for st in stmts)
975
+ infos = []
976
+ for st, tree, runtime, text in parsed:
977
+ # with a pull, a statement no measured shape matched still counts, after every measured one
978
+ st["weight"] = float(st["measured"] or 0) + (float(st["static"] or 1.0) * 1e-9 if measured_any else float(st["static"] or 1.0))
979
+ st["basis"] = "measured" if st.get("measured") else "static"
980
+ st["runtime_parts"] = runtime
981
+ binds: dict[str, tuple] = {}
982
+ names = {short(t.name) for t in tree.find_all(exp.Table) if t.name}
983
+ for r in reads_of(tree, {n: cols[n] for n in names if n in cols}, cfg, runtime):
984
+ per_table[r.table].append((st, r))
985
+ binds.update(r.params)
986
+ for node in list(tree.find_all(exp.Limit)) + list(tree.find_all(exp.Offset)):
987
+ p = _placeholder(node.expression) if node.expression is not None else None
988
+ if p:
989
+ binds[p] = ("", "", "limit" if isinstance(node, exp.Limit) else "offset")
990
+ every = {x for x in (_placeholder(n) for n in tree.find_all(exp.Placeholder, exp.Parameter)) if x}
991
+ infos.append({"ref": st["ref"], "refs": st["refs"], "site_ids": st.get("site_ids") or [], "hash": st.get("hash"), "sql_from": st["sql_from"],
992
+ "text_from": st.get("text_from"), "text": text, "runtime_parts": runtime, "tables": sorted(names & set(cols)),
993
+ "binds": {p: list(v) for p, v in binds.items()}, "unbound": sorted(every - set(binds)),
994
+ "positional": len(re.findall(r"(?<![\w?])\?(?![\w?|&-])", prepare_sql(text)[0])), "weight": st["weight"], "basis": st["basis"],
995
+ "file": st.get("file"), "line": st.get("line")})
996
+ tables_out, suggestions, handoffs = [], [], []
997
+ order = sorted(per_table, key=lambda t: -sum(st["weight"] for st in {id(s): s for s, _ in per_table[t]}.values()))
998
+ n = 0
999
+ for t in order[: cfg["max_tables"]]:
1000
+ d = defs[t]
1001
+ got = _advise_table(t, d, per_table[t], cfg, updated.get(t, set()))
1002
+ tables_out.append(got["table"])
1003
+ handoffs += got["handoffs"]
1004
+ for s in got["suggestions"]:
1005
+ n += 1
1006
+ s["id"] = f"IX-{n:03d}"
1007
+ # identity across runs (the id is a place in this run): what bench records and plans are matched by
1008
+ s["fingerprint"] = hashlib.sha1("|".join([ENGINE, s["kind"], s["table"], *s["ddl"]]).encode()).hexdigest()[:12]
1009
+ suggestions.append(s)
1010
+ for s in got["suggestions"]:
1011
+ if s.get("covering_of_key"):
1012
+ s["covering_of"] = next((x["id"] for x in got["suggestions"] if x.get("_key") == s["covering_of_key"]), None)
1013
+ if s.get("alternative_of_key"):
1014
+ s["alternative_of"] = next((x["id"] for x in got["suggestions"] if x.get("_key") == s["alternative_of_key"]), None)
1015
+ for s in suggestions:
1016
+ s.pop("_key", None)
1017
+ s.pop("covering_of_key", None)
1018
+ s.pop("alternative_of_key", None)
1019
+ hygiene_rows = hygiene(defs, facts)
1020
+ doc = {
1021
+ "schema_version": SCHEMA_VERSION, "engine": ENGINE, "generated_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
1022
+ "settings": cfg,
1023
+ "basis": {"weights": "measured" if measured_any else "static",
1024
+ "definitions_from": sorted({defs[t].source for t in per_table if t in defs}),
1025
+ "statements_read": len(stmts), "statements_parsed": len(parsed), "statements_unparsed": unparsed},
1026
+ "tables": tables_out, "table_suggestions": suggestions, "handoffs": handoffs, "hygiene": hygiene_rows,
1027
+ # the statements as the advisor read them: local only (the bench runs them), never uploaded
1028
+ "statements": infos,
1029
+ }
1030
+ doc["summary"] = summarize(doc)
1031
+ return doc
1032
+
1033
+
1034
+ def _canon_key(k: Key, columns: dict[str, str]) -> Key:
1035
+ lower = {c.lower(): c for c in columns}
1036
+ return Key(cols=tuple((n if n.startswith("expr:") else lower.get(n.lower(), n), dsc) for n, dsc in k.cols),
1037
+ include=tuple(lower.get(x.lower(), x) for x in k.include), where=k.where, method=k.method, unique=k.unique)
1038
+
1039
+
1040
+ def _bool_only(k: Key, d: TableDef) -> bool:
1041
+ """Every key column is a boolean (by the definition's type): such an index selects half the table at best."""
1042
+ types = {c.lower(): (t or "") for c, t in d.columns.items()}
1043
+ return bool(k.cols) and all(re.match(r"\s*bool", types.get(n.lower(), ""), re.I) for n, _ in k.cols)
1044
+
1045
+
1046
+ def _lead_bools(k: Key, d: TableDef) -> int:
1047
+ types = {c.lower(): (t or "") for c, t in d.columns.items()}
1048
+ n = 0
1049
+ for name, _ in k.cols:
1050
+ if not re.match(r"\s*bool", types.get(name.lower(), ""), re.I):
1051
+ break
1052
+ n += 1
1053
+ return n
1054
+
1055
+
1056
+ def not_columns(k: Key, d: TableDef) -> list[str]:
1057
+ """The key and INCLUDE names that are not columns of the table's definition (`total_spend`, the alias of
1058
+ SUM(spend) a statement orders by). Empty when the definition lists no columns (nothing to check against)."""
1059
+ if not d.columns:
1060
+ return []
1061
+ have = {c.lower() for c in d.columns}
1062
+ return [n for n in list(k.names) + list(k.include) if not n.startswith("expr:") and n.lower() not in have]
1063
+
1064
+
1065
+ def _advise_table(t: str, d: TableDef, rows: list[tuple[dict, Read]], cfg: dict, updated: set[str]) -> dict:
1066
+ existing = [(ix, _canon_key(key_of_index(ix), d.columns)) for ix in d.indexes]
1067
+ weight = {}
1068
+ for st, _ in rows:
1069
+ weight[st["ref"]] = st["weight"]
1070
+ total = sum(weight.values()) or 1.0
1071
+ # literal equality columns: a partial index's predicate only when no statement of the table compares the column otherwise
1072
+ compared = set().union(*[r.compared for _, r in rows]) if rows else set()
1073
+ literal_only = {c for _, r in rows for c in r.literal_eq if c not in compared}
1074
+ reads = [(st, r, bool(not r.has_filter and not r.joins and r.group)) for st, r in rows]
1075
+ # what the existing indexes already give each read
1076
+ best = {}
1077
+ served_by = {}
1078
+ for i, (st, r, g) in enumerate(reads):
1079
+ b, by = 0.0, None
1080
+ for ix, k in existing:
1081
+ s = score(k, r, g)
1082
+ if (ix.unique or ix.primary) and k.method == "btree" and k.cols and set(k.where) <= set(r.consts) | set(r.literal_eq.values()) \
1083
+ and set(k.names) <= set(r.eq) | set(r.in_) | (set(r.joins) if not r.has_filter else set()):
1084
+ s = 1.0 # every column of a unique key is pinned: one row at most
1085
+ if s > b:
1086
+ b, by = s, ix.name
1087
+ best[i], served_by[i] = b, by
1088
+ initial = dict(best)
1089
+ pool: dict[tuple, tuple[Key, str]] = {}
1090
+ for st, r, g in reads:
1091
+ if r.runtime_where:
1092
+ continue # its real filter is assembled at run time: it is scored, never the source of a candidate
1093
+ for k, kind in candidates_for(r, cfg, literal_only):
1094
+ if not_columns(Key(cols=k.cols), d):
1095
+ continue # a name the table does not have (an output alias, an aggregate): the index can not be built
1096
+ if not_columns(k, d):
1097
+ k = dataclasses.replace(k, include=tuple(c for c in k.include if c not in not_columns(k, d)))
1098
+ for p in permutations(k, set(r.eq), cfg):
1099
+ if p.ident() not in pool or kind == "covering_index":
1100
+ pool[p.ident()] = (p, kind) # a narrow, read-whole form wins over the same key for a filter
1101
+ chosen: list[dict] = []
1102
+ handoffs = _handoffs(t, d, reads, existing, best)
1103
+
1104
+ def gain_of(k: Key) -> tuple[float, dict[int, float]]:
1105
+ per = {}
1106
+ total_gain = 0.0
1107
+ for i, (st, r, g) in enumerate(reads):
1108
+ s = score(k, r, g)
1109
+ if s > best[i]:
1110
+ per[i] = s
1111
+ total_gain += weight[st["ref"]] * (s - best[i])
1112
+ return total_gain, per
1113
+
1114
+ refinements: dict[tuple, dict] = {}
1115
+ small = d.rows is not None and int(d.rows) < cfg["min_table_rows"]
1116
+ while len(chosen) < cfg["max_indexes_per_table"] and pool and not small:
1117
+ scored = []
1118
+ for ident, (k, kind) in pool.items():
1119
+ narrow = kind == "covering_index" and not k.include # read whole: a wider index with it as prefix does not serve
1120
+ same = (lambda a, b: a.ident() == b.ident() or (a.names == b.names and a.where == b.where)) if narrow else prefix_of
1121
+ if any(same(k, ek) for _, ek in existing) or any(same(k, c["key"]) for c in chosen):
1122
+ continue
1123
+ if d.is_view or (cfg["skip_boolean_keys"] and _bool_only(k, d)):
1124
+ continue # no index on a view; a key of booleans alone is left to a partial index's predicate
1125
+ gsum, per = gain_of(k)
1126
+ if gsum > 0 and not cfg["propose_eq_refinements"] and per and all(
1127
+ initial[i] > 0 and not reads[i][1].sort and not reads[i][1].range and not reads[i][2] for i in per):
1128
+ # every statement it improves already has an existing index pinning an equality column, and it adds only
1129
+ # equality columns: whether that pays depends on selectivity the static pass does not have
1130
+ refinements.setdefault(ident, {"key": _key_public(k), "statements": sorted({reads[i][0]["ref"] for i in per}),
1131
+ "existing": sorted({served_by[i] for i in per if served_by[i]})})
1132
+ continue
1133
+ if gsum > 0:
1134
+ scored.append((gsum, len(k.where), -len(k.cols), ident, k, kind, per))
1135
+ if not scored:
1136
+ break
1137
+ # equal gain: fewer leading boolean columns, then a partial predicate, then fewer columns
1138
+ scored.sort(key=lambda x: (-x[0], _lead_bools(x[4], d), -x[1], -x[2], x[3]))
1139
+ gsum, _, _, ident, k, kind, per = scored[0]
1140
+ if gsum <= cfg["min_gain_share"] * total:
1141
+ break
1142
+ alts = [x for x in scored[1:] if abs(x[0] - gsum) < 1e-9 and set(x[4].names) == set(k.names) and x[4].where == k.where
1143
+ and x[4].names != k.names]
1144
+ entry = {"key": k, "kind": kind, "gain": gsum, "per": per, "alternatives": [(a[4], a[6]) for a in alts[:2]]}
1145
+ chosen.append(entry)
1146
+ for i, s in per.items():
1147
+ best[i] = max(best[i], s)
1148
+ pool.pop(ident, None)
1149
+ for a in alts:
1150
+ pool.pop(a[3], None)
1151
+ out = []
1152
+ table_weight = total
1153
+ for c in chosen:
1154
+ out.append(_suggestion(t, d, c["key"], c["kind"], c["per"], reads, weight, table_weight, existing, updated, cfg, "rule"))
1155
+ for a, per in c["alternatives"]:
1156
+ s = _suggestion(t, d, a, c["kind"], per, reads, weight, table_weight, existing, updated, cfg, "alternative_order")
1157
+ s["alternative_of_key"] = c["key"].ident()
1158
+ s["measure_both"] = True
1159
+ out.append(s)
1160
+ if cfg["covering"]:
1161
+ cov = _covering(c["key"], c["per"], reads, d, cfg)
1162
+ if cov is not None:
1163
+ _, per = gain_of(cov)
1164
+ per = per or {i: 1.0 for i in c["per"]}
1165
+ s = _suggestion(t, d, cov, "covering_index", per, reads, weight, table_weight, existing, updated, cfg, "covering")
1166
+ s["covering_of_key"] = c["key"].ident()
1167
+ out.append(s)
1168
+ table = {
1169
+ "table": d.name, "definition": d.source, "index_basis": d.index_basis, "rows": d.rows,
1170
+ **({"small_table": True} if small else {}),
1171
+ "statements": len({st["ref"] for st, _ in rows}), "statement_refs": sorted({st["ref"] for st, _ in rows}), "weight": round(table_weight, 3),
1172
+ "existing_indexes": [{"name": ix.name, "columns": [c.text + (" DESC" if c.desc else "") for c in ix.columns], "include": ix.include,
1173
+ "where": ix.where, "method": ix.method, "unique": ix.unique, "primary": ix.primary} for ix, _ in existing],
1174
+ "already_served": sorted({st["ref"] for i, (st, r, g) in enumerate(reads) if served_by[i] and initial[i] >= 1.0}),
1175
+ # equality-only refinements of an existing index, not proposed (`propose_eq_refinements`): evidence for the reader
1176
+ "refinements": list(refinements.values())[:10],
1177
+ "unserved_after": sorted({st["ref"] for i, (st, r, g) in enumerate(reads) if best[i] < 1.0 and (r.has_filter or r.joins or r.sort)}),
1178
+ }
1179
+ return {"table": table, "suggestions": out, "handoffs": handoffs}
1180
+
1181
+
1182
+
1183
+ def _initial(reads, existing, i) -> float:
1184
+ st, r, g = reads[i]
1185
+ return max((score(k, r, g) for _, k in existing), default=0.0)
1186
+
1187
+
1188
+ def _covering(k: Key, per: dict[int, float], reads, d: TableDef, cfg: dict) -> Key | None:
1189
+ """The same key with the other columns its fully served reads need (INCLUDE): an index-only read. None when those
1190
+ reads read every column, a wide one, or more than `max_include_columns`."""
1191
+ need: set[str] = set()
1192
+ for i, s in per.items():
1193
+ st, r, g = reads[i]
1194
+ if s < 1.0 or r.reads is None:
1195
+ continue # a read of every column is made index-only by no INCLUDE: it is left out of the union
1196
+ extra = {c for c in r.reads if c not in k.names and (c in d.columns or not d.columns)}
1197
+ if any(WIDE_TYPE.search(d.columns.get(c, "")) for c in extra) or len(need | extra) > cfg["max_include_columns"]:
1198
+ continue
1199
+ need |= extra
1200
+ if not need:
1201
+ return None
1202
+ return Key(cols=k.cols, include=tuple(sorted(need)), where=k.where)
1203
+
1204
+
1205
+ def _suggestion(t, d: TableDef, k: Key, kind: str, per: dict[int, float], reads, weight, table_weight, existing, updated, cfg, source) -> dict:
1206
+ name = index_name(d.name, k)
1207
+ serves: dict[str, dict] = {}
1208
+ for i, s in per.items():
1209
+ st, r, g = reads[i]
1210
+ cur = serves.get(st["ref"])
1211
+ if cur is None or s > cur["score"]:
1212
+ serves[st["ref"]] = {"statement": st["ref"], "site_ids": st.get("site_ids") or [], "sql_from": st["sql_from"],
1213
+ "file": st.get("file"), "line": st.get("line"), "weight": round(weight[st["ref"]], 3),
1214
+ "share": round(weight[st["ref"]] / table_weight, 4) if table_weight else None,
1215
+ "basis": st["basis"], "score": round(s, 3), "wanted": _wanted(r),
1216
+ "runtime_parts": bool(st.get("runtime_parts")), "text_from": st.get("text_from") or "code"}
1217
+ others = sorted({st["ref"] for st, _, _ in reads if st["ref"] not in serves})
1218
+ served_w = sum(x["weight"] for x in serves.values())
1219
+ extends = [ix.name for ix, ek in existing if ek.method == "btree" and not ek.unique and prefix_of(Key(cols=ek.cols, where=ek.where), Key(cols=k.cols, where=k.where))
1220
+ and len(ek.cols) < len(k.cols)]
1221
+ fk = {c for f in d.foreign_keys for c in f["columns"] if short(f["table"]) == short(d.name)}
1222
+ return {
1223
+ "engine": ENGINE, "kind": kind, "table": d.name, "name": name, "ddl": [ddl_of(d.name, k, name)], "key": _key_public(k), "_key": k.ident(),
1224
+ "source": source, "serves": sorted(serves.values(), key=lambda x: -x["weight"]), "other_statements": others,
1225
+ "read_load_share": round(served_w / table_weight, 4) if table_weight else None,
1226
+ "basis": {"weights": "measured" if any(x["basis"] == "measured" for x in serves.values()) else "static", "definition_from": d.source,
1227
+ "index_basis": d.index_basis},
1228
+ "extends": extends, "makes_redundant": extends,
1229
+ "foreign_key_columns": sorted(fk & set(k.names)),
1230
+ "updated_columns": sorted(updated & set(k.names) | (updated & set(k.include))),
1231
+ "index_only_claim": kind == "covering_index",
1232
+ "read_gain": None, "write_cost": None, "size": None, "visibility": None,
1233
+ "verdict": {"state": "not_judged", "reason": "bench_not_run", "from": "run", "evidence": {}},
1234
+ }
1235
+
1236
+
1237
+ def _handoffs(t: str, d: TableDef, reads, existing, best) -> list[dict]:
1238
+ """Filters on a cast or date function of a column that an existing index would serve if the filter named the column."""
1239
+ out = []
1240
+ for i, (st, r, g) in enumerate(reads):
1241
+ for w in r.wrapped:
1242
+ if not w["rewrite"] or w["immutable"]:
1243
+ continue
1244
+ plain = Read(table=r.table, eq=dict(r.eq), in_=list(r.in_), range=list(r.range), sort=list(r.sort), consts=dict(r.consts),
1245
+ literal_eq=dict(r.literal_eq))
1246
+ if w["op"] == "eq" and w["func"] in ("cast", "coalesce", "lower", "upper"):
1247
+ plain.eq[w["column"]] = "param"
1248
+ else:
1249
+ _add_range(plain, w["column"])
1250
+ for ix, k in existing:
1251
+ if score(k, plain) > best[i] + 1e-9:
1252
+ out.append({"table": d.name, "statement": st["ref"], "column": w["column"], "wrapper": w["func"], "index": ix.name,
1253
+ "scenario": "key_unusable", "rule": "key_wrapped", "change": "unwrap_key_column",
1254
+ "proof": "evidence_only"})
1255
+ break
1256
+ seen, uniq = set(), []
1257
+ for h in out:
1258
+ key = (h["statement"], h["column"], h["index"])
1259
+ if key not in seen:
1260
+ seen.add(key)
1261
+ uniq.append(h)
1262
+ return uniq
1263
+
1264
+
1265
+ # ---- hygiene: evidence only ----------------------------------------------------------------------------------------
1266
+
1267
+ ZERO_SCAN_CAVEAT = ("not used since statistics began: the time statistics were last reset is not known; check every "
1268
+ "server (replicas too) and the jobs that run rarely before removing")
1269
+
1270
+
1271
+ def hygiene(defs: dict[str, TableDef], facts=None) -> list[dict]:
1272
+ """Exact duplicates and redundant left-prefix indexes (from the definitions), and with a pull invalid indexes and
1273
+ indexes with no scan. Evidence only: never a fix, never a verdict."""
1274
+ out = []
1275
+ for s, d in sorted(defs.items()):
1276
+ keyed = [(ix, key_of_index(ix)) for ix in d.indexes]
1277
+ # an index known only from an ORM model's column list carries no predicate and no direction: no hygiene claim on it
1278
+ keyed = [(ix, k) for ix, k in keyed if f"{d.name}_orm_" not in ix.name]
1279
+ for (a, ka), (b, kb) in itertools.combinations(keyed, 2):
1280
+ same = ka.method == kb.method and ka.where == kb.where and ka.names == kb.names and _norm_dir(list(ka.cols)) == _norm_dir(list(kb.cols)) \
1281
+ and set(ka.include) == set(kb.include)
1282
+ if same:
1283
+ keep, drop = (a, b) if (a.primary or a.unique) and not (b.primary or b.unique) else (b, a) if (b.primary or b.unique) else (a, b)
1284
+ if drop.primary or (drop.unique and not keep.unique):
1285
+ continue
1286
+ out.append({"code": "duplicate_index", "table": d.name, "index": drop.name, "same_as": keep.name, "definition_from": d.source,
1287
+ "evidence": "same method, columns, directions and predicate", "trade_off": "every write updates both"})
1288
+ continue
1289
+ for x, kx, y, ky in ((a, ka, b, kb), (b, kb, a, ka)):
1290
+ if x.unique or x.primary or kx.method != "btree" or len(kx.cols) >= len(ky.cols):
1291
+ continue
1292
+ if prefix_of(Key(cols=kx.cols, include=kx.include, where=kx.where), Key(cols=ky.cols, include=ky.include, where=ky.where)):
1293
+ out.append({"code": "redundant_prefix_index", "table": d.name, "index": x.name, "covered_by": y.name, "definition_from": d.source,
1294
+ "evidence": "its columns are a left prefix of the other index's, same predicate",
1295
+ "caveat": "a smaller index can still be cheaper for some scans; measure before removing"})
1296
+ for ci in d.catalog_indexes:
1297
+ if ci.get("is_valid") is False:
1298
+ out.append({"code": "invalid_index", "table": d.name, "index": ci.get("name"), "definition_from": "real catalog",
1299
+ "evidence": "is_valid is false: a failed CREATE INDEX CONCURRENTLY left it; it is kept up to date and never read",
1300
+ "bytes": ci.get("bytes")})
1301
+ elif int(ci.get("scans") or 0) == 0 and not ci.get("is_unique") and not ci.get("is_primary"):
1302
+ out.append({"code": "unused_index", "table": d.name, "index": ci.get("name"), "definition_from": "real catalog",
1303
+ "evidence": "idx_scan = 0", "caveat": ZERO_SCAN_CAVEAT, "bytes": ci.get("bytes")})
1304
+ return out
1305
+
1306
+
1307
+ # ---- outcomes, after the sandbox ----------------------------------------------------------------------------------
1308
+
1309
+ def verdict_of(s: dict, measured: dict | None, insert_settings: dict | None = None, bench_ran: bool = False) -> dict:
1310
+ """One of the four states for one suggestion, from what advisor_bench measured (`measured`: its record)."""
1311
+ from . import blockers
1312
+
1313
+ def done(state, reason, src="sandbox", **ev):
1314
+ return {"state": state, "reason": reason, "from": src, "evidence": ev}
1315
+
1316
+ if measured is None:
1317
+ if not bench_ran:
1318
+ return done("not_judged", "bench_not_run", "run", claimed=len(s.get("serves") or []))
1319
+ return done("not_judged", "statements_not_runnable", "run", claimed=len(s.get("serves") or []))
1320
+ if measured.get("skip"):
1321
+ return done("not_judged", measured["skip"], error_class=measured.get("error_class") or "")
1322
+ serves = [x for x in measured.get("statements") or [] if x.get("serves")]
1323
+ others = [x for x in measured.get("statements") or [] if not x.get("serves")]
1324
+ ran = [x for x in serves if x.get("verdict") and x["verdict"] not in ("failed", "untested")]
1325
+ if not ran:
1326
+ return done("not_judged", "statements_not_runnable" if not serves or all(x.get("how") == "bound_here" for x in serves) else "sandbox_could_not_run",
1327
+ claimed=len(s.get("serves") or []), measured=0)
1328
+ honest = [x.get("honest_verdict") or x["verdict"] for x in ran]
1329
+ if "rejected" in honest:
1330
+ return done("blocked", "fix_results_differ", statements=len(ran))
1331
+ regress = [x["statement"] for x in others if x.get("verdict") == "slower"]
1332
+ wins = [x for x, h in zip(ran, honest) if h == "win"]
1333
+ ev = {"statements_measured": len(ran), "statements_won": len(wins), "claimed_not_measured": len(s.get("serves") or []) - len(ran)}
1334
+ if wins:
1335
+ ic = s.get("write_cost")
1336
+ if ic and ic.get("measured"):
1337
+ # the limits as set now: a record measured earlier is judged again with them
1338
+ from .writecost import near_limit, settings_of as wc_settings, within
1339
+ wc = wc_settings(insert_settings)
1340
+ ic = s["write_cost"] = {**ic, "within": within(ic, wc), "near_limit": near_limit(ic, wc)}
1341
+ ok, costly, unmeasured = blockers.insert_cost_rule([{"kind": "index", "insert_cost": ic}], insert_settings or {})
1342
+ if regress:
1343
+ return done("blocked", "fix_slows_other_statements", **ev, slower=regress, trade_off=True)
1344
+ if costly:
1345
+ if (ic or {}).get("near_limit"):
1346
+ return done("blocked", "insert_cost_near_limit", **ev, trade_off=True, insert_time_ratio_range=ic.get("insert_time_ratio_range"))
1347
+ return done("blocked", "fix_costs_inserts", **ev, trade_off=True)
1348
+ if unmeasured:
1349
+ return done("not_judged", "insert_cost_not_measured", **ev)
1350
+ if ic is None:
1351
+ ev["insert_cost"] = {"measured": False, "reason": "not_measured"}
1352
+ return done("fixed", "verified", **ev)
1353
+ if any(h == "mixed" for h in honest):
1354
+ return done("not_judged", "sameness_not_shown", **ev)
1355
+ if all(x.get("reason", "").startswith("the baseline already reads little") for x in ran):
1356
+ return done("nothing_to_gain", "already_cheap_measured", **ev)
1357
+ return done("blocked", "no_variant_reads_less", **ev)
1358
+
1359
+
1360
+ def summarize(doc: dict) -> dict:
1361
+ sugg = doc.get("table_suggestions") or []
1362
+ states = {s: 0 for s in STATES}
1363
+ reasons: dict[str, int] = defaultdict(int)
1364
+ for s in sugg:
1365
+ v = s.get("verdict") or {}
1366
+ if v.get("state") in states:
1367
+ states[v["state"]] += 1
1368
+ reasons[f"{v['state']}:{v.get('reason')}"] += 1
1369
+ return {"tables": len(doc.get("tables") or []), "tables_with_suggestions": len({s["table"] for s in sugg}),
1370
+ "suggestions": len(sugg), "by_kind": {k: sum(1 for s in sugg if s["kind"] == k) for k in KINDS},
1371
+ "statements_served": len({x["statement"] for s in sugg for x in s.get("serves") or []}),
1372
+ "handoffs": len(doc.get("handoffs") or []), "hygiene": {c: sum(1 for h in doc.get("hygiene") or [] if h["code"] == c)
1373
+ for c in ("duplicate_index", "redundant_prefix_index", "invalid_index", "unused_index")},
1374
+ "states": states, "reasons": dict(reasons)}
1375
+
1376
+
1377
+ # ---- the shared shape: findings.json and the bundle ----------------------------------------------------------------
1378
+
1379
+ # This advisor's outcome reasons in the codes both advisors send (run_bundle.schema.json $defs.table_suggestion)
1380
+ SHARED_REASON = {"fix_slows_other_statements": "regresses_other_statements", "statements_not_runnable": "claimed_not_measured"}
1381
+ VERDICT_OF = {"verified": "verified", "no_variant_reads_less": "no_change", "fix_results_differ": "results_differ",
1382
+ "fix_costs_inserts": "trade_off", "insert_cost_near_limit": "trade_off", "regresses_other_statements": "regresses",
1383
+ "bench_not_run": "claimed", "claimed_not_measured": "claimed", "sandbox_table_not_loaded": "failed",
1384
+ "sandbox_could_not_run": "failed", "sameness_not_shown": "evidence_only", "insert_cost_not_measured": "not_measured",
1385
+ "parameters_match_no_rows": "not_measured", "already_cheap_measured": "no_change"}
1386
+ WRITE_COST_KEYS = ("measured", "reason", "rows", "blocks", "rounds", "insert_time_ratio", "insert_time_ratios", "insert_time_ratio_range",
1387
+ "written_bytes_ratio", "wal_bytes_ratio", "storage_ratio", "parts_ratio", "within", "near_limit", "thresholds",
1388
+ "index_bytes", "wal_from")
1389
+ DETAIL_KEYS = ("source", "covering_of", "alternative_of", "measure_both", "extends", "makes_redundant", "foreign_key_columns",
1390
+ "updated_columns", "index_only_claim")
1391
+
1392
+
1393
+ def _scalar(v) -> bool:
1394
+ return v is None or isinstance(v, (int, float, bool, str))
1395
+
1396
+
1397
+ def _plain(d: dict | None, keys=None) -> dict:
1398
+ """Scalars, lists of scalars and a `thresholds` dict of numbers: nothing nested, no error text."""
1399
+ out = {}
1400
+ for k, v in (d or {}).items():
1401
+ if (keys and k not in keys) or k in ("error", "basis", "rule"):
1402
+ continue
1403
+ if _scalar(v) or (isinstance(v, list) and all(_scalar(x) for x in v)):
1404
+ out[k] = v
1405
+ elif k == "thresholds" and isinstance(v, dict):
1406
+ out[k] = {a: b for a, b in v.items() if isinstance(b, (int, float))}
1407
+ return out
1408
+
1409
+
1410
+ def _run(b: dict | None, a: dict | None, verdict, match) -> dict | None:
1411
+ if not isinstance(b, dict) or not isinstance(a, dict) or b.get("ok") is False or a.get("ok") is False:
1412
+ return None
1413
+ return {"before_bytes": b.get("read_bytes"), "after_bytes": a.get("read_bytes"), "before_rows": b.get("read_rows"),
1414
+ "after_rows": a.get("read_rows"), "before_pages": b.get("pages"), "after_pages": a.get("pages"), "verdict": verdict,
1415
+ "results_match": match}
1416
+
1417
+
1418
+ def shared_serve(x: dict) -> dict:
1419
+ """One statement a suggestion serves, in the shared shape: the run the verdict uses is `measured.typical` (for an
1420
+ index-only read, the run with pages not all-visible); PostgreSQL facts under `engine_detail`."""
1421
+ measured_row = x.get("role") == "measured"
1422
+ verdict = (x.get("honest_verdict") or x.get("verdict")) if measured_row else None
1423
+ typical = _run(x.get("before_touched") or x.get("before"), x.get("after_touched") or x.get("after"), verdict,
1424
+ x.get("results_match")) if measured_row else None
1425
+ ed = {k: x.get(k) for k in ("score", "role", "runtime_parts", "text_from", "index_only", "how", "why_not_measured") if x.get(k) is not None}
1426
+ if measured_row and x.get("before_touched"):
1427
+ fresh = _run(x.get("before"), x.get("after"), x.get("verdict"), x.get("results_match"))
1428
+ if fresh:
1429
+ ed["fresh_run"] = {k: fresh[k] for k in ("before_bytes", "after_bytes", "verdict")}
1430
+ return {"statement": x.get("statement"), "finding": x.get("finding"), "sql_from": x.get("sql_from"),
1431
+ "located": "site" if x.get("sql_from") in ("code", "orm") else None, "file": x.get("file"), "line": x.get("line"),
1432
+ "site_ids": list(x.get("site_ids") or []), "weight": x.get("weight"), "weight_share": x.get("share"),
1433
+ "weight_basis": x.get("basis"), "claimed": typical is None, "measured": {"typical": typical} if typical else None,
1434
+ "verdict": verdict, "engine_used": x.get("uses_index") if measured_row and isinstance(x.get("uses_index"), bool) else None,
1435
+ "engine_detail": ed}
1436
+
1437
+
1438
+ def _weighted_ratio(serves: list[dict]) -> float | None:
1439
+ rows = [(float(x.get("weight") or 0), x["measured"]["typical"]) for x in serves if not x["claimed"]]
1440
+ rows = [(w, t) for w, t in rows if (t.get("before_bytes") or 0) > 0 and t.get("after_bytes") is not None]
1441
+ if not rows:
1442
+ return None
1443
+ ws = [w for w, _ in rows] if any(w for w, _ in rows) else [1.0] * len(rows)
1444
+ return round(sum(w * t["after_bytes"] / t["before_bytes"] for w, (_, t) in zip(ws, rows)) / sum(ws), 4)
1445
+
1446
+
1447
+ def shared(s: dict, clean=lambda t: t) -> dict:
1448
+ """One suggestion in the shared shape both advisors send (run_bundle.schema.json $defs.table_suggestion): the
1449
+ common fields as the ClickHouse advisor names them; the index's key and the PostgreSQL facts under `engine_detail`.
1450
+ No statement text, no parameter values: the DDL is the proposed index, a literal replaced by ?."""
1451
+ v = s.get("verdict") or {}
1452
+ reason = SHARED_REASON.get(v.get("reason"), v.get("reason") or "bench_not_run")
1453
+ serves = [shared_serve(x) for x in s.get("serves") or []]
1454
+ measured = [x for x in serves if not x["claimed"]]
1455
+ basis = s.get("basis") or {}
1456
+ key = s.get("key") or {}
1457
+ rg = s.get("read_gain") or {}
1458
+ ed = {"method": key.get("method"),
1459
+ "columns": [(c.get("column") or "") + (" desc" if c.get("desc") else "") for c in key.get("columns") or [] if isinstance(c, dict)],
1460
+ "expressions": [c.get("column") for c in key.get("columns") or [] if isinstance(c, dict) and c.get("expression")],
1461
+ "include": list(key.get("include") or []), "where": clean(key.get("where") or ""),
1462
+ **{k: s.get(k) for k in DETAIL_KEYS if s.get(k) not in (None, [], "")},
1463
+ **{k: basis.get(k) for k in ("weights", "definition_from", "index_basis") if basis.get(k) is not None},
1464
+ **{k: rg.get(k) for k in ("pages_before", "pages_after", "weighted_share_saved", "statements_claimed") if rg.get(k) is not None}}
1465
+ if isinstance(s.get("visibility"), dict):
1466
+ ed["visibility"] = _plain(s["visibility"])
1467
+ ev = {k: x for k, x in (v.get("evidence") or {}).items() if _scalar(x) or (isinstance(x, list) and all(_scalar(y) for y in x))}
1468
+ wc = s.get("write_cost")
1469
+ size = s.get("size") or {}
1470
+ shares = [x["weight_share"] for x in measured if x.get("weight_share") is not None]
1471
+ return {
1472
+ "id": s["id"], "fingerprint": s.get("fingerprint") or hashlib.sha1("|".join([ENGINE, s["kind"], s["table"], *s["ddl"]]).encode()).hexdigest()[:12],
1473
+ "engine": ENGINE, "kind": s["kind"], "table": s["table"], "name": s.get("name"), "ddl": [clean(x) for x in s.get("ddl") or []],
1474
+ "serves": serves,
1475
+ "read_gain": {"basis": "measured" if measured else "claimed", "load_share": s.get("read_load_share"),
1476
+ "load_share_basis": basis.get("weights") or "static", "statements": len(serves),
1477
+ "statements_measured": len(measured), "read_ratio_typical": _weighted_ratio(serves), "read_ratio_heavy": None,
1478
+ "measured_load_share": round(sum(shares), 6) if shares else (0.0 if not measured else None)},
1479
+ "write_cost": _plain(wc, WRITE_COST_KEYS) if isinstance(wc, dict) else None,
1480
+ "size": {"bytes_sandbox": size.get("index_bytes"), "table_bytes_sandbox": None, "basis": size.get("at") or "sandbox scale"}
1481
+ if size.get("index_bytes") is not None else None,
1482
+ "verdict": VERDICT_OF.get(reason, "claimed"),
1483
+ "outcome": {"state": v.get("state") or "not_judged", "reason": reason, "evidence": ev},
1484
+ "basis": "rule",
1485
+ "others_measured": [{"statement": x.get("statement"), "finding": None, "verdict": x.get("verdict"),
1486
+ "read_ratio": round(((x.get("after") or {}).get("read_bytes") or 0) /(x.get("before") or {})["read_bytes"], 4)
1487
+ if (x.get("before") or {}).get("read_bytes") else None}
1488
+ for x in s.get("not_served_checked") or []],
1489
+ "engine_detail": ed,
1490
+ }
1491
+
1492
+
1493
+ def for_upload(doc: dict, databases: set[str] | None = None) -> dict | None:
1494
+ """What findings.json and the bundle carry: {table_suggestions (the shared shape), index_hygiene, advice}. Shapes,
1495
+ codes and numbers: the DDL is the proposed index (names of the repository's tables and columns, never a value: a
1496
+ partial predicate's literal is replaced by ?), nothing from a real catalog's definitions and no database name."""
1497
+ if not doc or not isinstance(doc.get("table_suggestions"), list):
1498
+ return None
1499
+ from .observed import strip_databases
1500
+
1501
+ def clean(text: str) -> str:
1502
+ text = re.sub(r"'(?:[^']|'')*'", "?", text or "")
1503
+ text = re.sub(r"(?<![\w$])-?\d+(?:\.\d+)?(?![\w])", "?", text)
1504
+ return strip_databases(text, databases or set()) if databases else text
1505
+
1506
+ hyg = [{"engine": ENGINE, **{k: h.get(k) for k in ("code", "table", "index", "same_as", "covered_by", "caveat", "bytes") if h.get(k) is not None}}
1507
+ for h in doc.get("hygiene") or []]
1508
+ return {"table_suggestions": [shared(s, clean) for s in doc["table_suggestions"]], "index_hygiene": hyg,
1509
+ "advice": {"summary": doc.get("summary") or summarize(doc),
1510
+ "basis": {k: v for k, v in (doc.get("basis") or {}).items() if k != "definitions_from"},
1511
+ "handoffs": [{k: h.get(k) for k in ("table", "statement", "column", "wrapper", "index", "scenario", "rule", "proof")}
1512
+ for h in doc.get("handoffs") or []]}}