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/scenarios.py ADDED
@@ -0,0 +1,675 @@
1
+ """Scenarios: kinds of waste that dashboard and analytics systems fix, detected by rule on every statement CodeCop knows,
2
+ each a candidate with evidence, and proved by the single-statement benchmark where a rule (or later the agent) can
3
+ write the variant. Local: no database, no agent, no network.
4
+
5
+ Four scenarios, chosen from common waste in dashboard and analytics products:
6
+
7
+ empty_reads Empty runs that still read. Most runs of the statement return nothing (`no_result_share` from the
8
+ pull) and the median run, an empty one, still reads a lot. Variants: the key predicates in PREWHERE
9
+ (rule), a narrow probe before the wide read (rule), fewer columns (agent), and, as evidence only, not
10
+ re-reading closed buckets (application). Measured on the empty typical run and on the heavy run.
11
+ key_unusable The key cannot serve the filter, or the time bound is missing. From the parsed predicate: a sorting-key or
12
+ partition-key column inside a function the key analysis does not see through; a map, JSON or subcolumn
13
+ lookup compared where a typed key column of the same name exists; a table partitioned or sorted by time
14
+ read with no bound on that column; and, from the pull, rows read far above rows returned. Variants: the
15
+ unwrapped predicate (rule, when the wrapper is the identity on the column's type), a skip index, a
16
+ projection and a re-keyed copy (rule, table-level: their insert side is measured too, writecost.py).
17
+ heavy_columns Heavy columns read for rows that are not shown, and narrow copies that already exist. A page (ORDER BY ...
18
+ LIMIT) that reads wide columns for every filtered row: the page picked on the key first (rule). A
19
+ statement whose columns all exist in a materialized view's target fed from the same table: evidence only,
20
+ unless the catalog shows lineage, row-preserving SELECT, the same columns and a complete copy.
21
+ count_page Count next to a page. In one function, a count over the same table and filter as a paged select: one
22
+ statement with count() OVER () needs the multi-statement benchmark (evidence), totals made optional is a
23
+ trade-off. A count over a sorted subquery with no LIMIT: the ORDER BY removed (rule, provable).
24
+
25
+ Every statement text CodeCop knows is read by one rule engine: SQL in code (`sql_from: code`), ORM-translated SQL (`orm`)
26
+ and statements production ran (`query_log`, with `located` from the match). A hit on a pulled statement and a hit on the
27
+ code text of a call site it is matched to are one candidate. Each candidate is bound to a statement the benchmark can
28
+ run (a ranked or observed candidate, or one built here from production's statement, `SB-001`); its rule variants are
29
+ added to that statement's variants at bench time, each tagged with the scenario candidate, so its outcome is one of the
30
+ four states with a reason (blockers.py). Thresholds are settings under `[scenarios]` in codecop.toml (DEFAULTS).
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ import hashlib
36
+ import re
37
+ from collections import Counter, defaultdict
38
+ from datetime import datetime, timezone
39
+
40
+ from . import scenario_sql as Q
41
+
42
+ SCHEMA_VERSION = 1
43
+ SCENARIOS = ("empty_reads", "key_unusable", "heavy_columns", "count_page")
44
+ LABEL = {"empty_reads": "Empty runs that still read", "key_unusable": "Key not usable, or time bound missing",
45
+ "heavy_columns": "Heavy columns read for rows not shown", "count_page": "Count next to a page"}
46
+ RULES = {"empty_reads": ("empty_runs",),
47
+ "key_unusable": ("key_wrapped", "map_lookup", "no_time_bound", "reads_far_above_returns"),
48
+ "heavy_columns": ("wide_before_limit", "wide_in_aggregate_before_limit", "narrow_copy"),
49
+ "count_page": ("count_next_to_page", "count_over_sorted_subquery")}
50
+ RULE_SCENARIO = {r: s for s, rules in RULES.items() for r in rules}
51
+ PROOFS = ("sandbox", "needs_agent", "evidence_only", "trade_off")
52
+ # change -> (what it touches, how CodeCop can prove it)
53
+ CHANGES = {
54
+ "filter_first_prewhere": ("query", "sandbox"), "probe_before_wide_read": ("query", "sandbox"),
55
+ "narrow_columns": ("query", "needs_agent"), "skip_closed_buckets": ("application", "evidence_only"),
56
+ "unwrap_key_column": ("query", "sandbox"), "rewrite_wrapped_predicate": ("query", "needs_agent"),
57
+ "compare_typed_column": ("query", "evidence_only"), "add_time_bound": ("query", "needs_agent"),
58
+ "skip_index": ("table", "sandbox"), "projection": ("table", "sandbox"), "sorting_key": ("table", "sandbox"),
59
+ "late_materialization": ("query", "sandbox"), "late_materialization_aggregate": ("query", "needs_agent"),
60
+ "read_narrow_copy": ("query", "evidence_only"), "count_over_window": ("query", "evidence_only"),
61
+ "totals_optional": ("application", "trade_off"), "drop_inner_order": ("query", "sandbox"),
62
+ # PostgreSQL's empty reads: an index that serves the predicate (table-level: its insert side counts), the same cheap
63
+ # existence probe, and the hand-off to the application (poll less, or run on the event that writes the rows)
64
+ "index_for_filter": ("table", "sandbox"), "poll_less_or_on_event": ("application", "evidence_only"),
65
+ }
66
+ EMPTY_CHANGES = {"clickhouse": ["filter_first_prewhere", "probe_before_wide_read", "narrow_columns", "skip_closed_buckets"],
67
+ "postgres": ["index_for_filter", "probe_before_wide_read", "poll_less_or_on_event"]}
68
+ TABLE_LEVEL = ("skip_index", "projection", "ordering_key")
69
+
70
+ DEFAULTS = {
71
+ # empty_reads
72
+ "empty_min_share": 0.8, # share of runs that return nothing
73
+ "empty_min_runs_per_hour": 6.0, # a statement run less often is not a poll
74
+ "empty_min_median_bytes": 1_000_000, # bytes the median (empty) run reads
75
+ # key_unusable
76
+ "far_min_rows_read": 50_000, # rows read per run
77
+ "far_min_ratio": 100.0, # rows read per row returned
78
+ "far_min_marks": 100.0, # marks selected per run (when the pull has them)
79
+ "time_bound_min_table_rows": 100_000, # a table with fewer rows (catalog) is not reported for a missing bound
80
+ "require_static_where": True, # no rule on a filter that has a run-time part: the bound may be in it
81
+ "map_lookup_requires_key_column": True, # a lookup counts only when the column of that name is in a key or index
82
+ "key_wrapped_requires_parameter": True, # a wrapped key column counts only when compared with a value the caller supplies
83
+ # heavy_columns
84
+ "heavy_min_bytes_per_row": 1024.0, # a column this wide per row (catalog) is heavy; without sizes: by type
85
+ "copy_min_row_ratio": 0.99, # a narrow copy is complete when it holds this share of the source's rows
86
+ # count_page
87
+ "count_page_scope": "function", # function | entry_point
88
+ "count_page_min_table_rows": 100_000, # pairs on smaller tables (catalog) are dropped
89
+ "count_page_min_filter_overlap": 0.5, # share of filter columns the two statements have in common
90
+ # variants
91
+ "max_table_variants": 3, # skip index, projection, re-key: at most this many per candidate
92
+ "build_runnable": True, # build a runnable statement from production's text when no candidate exists
93
+ "max_runnable": 40, # ... at most this many, heaviest first
94
+ }
95
+ LIST_DEFAULTS = {
96
+ "skip_roles": ["migration", "script", "tooling"], # code statements of these roles (inventory) are counted, not candidates
97
+ "order": list(SCENARIOS), # first fit: each measured byte is counted by the first scenario it fits
98
+ # functions the ClickHouse key analysis sees through (monotonic): a key column inside them still prunes
99
+ # pinned columns that name a scope (a tenant, a project), not one entity: a missing time bound under them reads a range
100
+ "time_bound_scope_columns": ["tenant", "project", "workspace", "org", "organization", "team", "account", "site", "website",
101
+ "customer", "subscriber", "gateway", "environment", "env", "cluster", "service", "app", "namespace"],
102
+ "key_safe_functions": ["todate", "todate32", "todatetime", "todatetime64", "tostartofday", "tostartofhour", "tostartofminute",
103
+ "tostartoffiveminutes", "tostartoftenminutes", "tostartoffifteenminutes", "tostartofmonth",
104
+ "tostartofquarter", "tostartofyear", "tostartofweek", "tostartofinterval", "tomonday", "toyyyymm",
105
+ "toyyyymmdd", "toyear", "tounixtimestamp", "tounixtimestamp64milli", "tounixtimestamp64micro",
106
+ "tounixtimestamp64nano", "torelativedaynum", "torelativehournum", "torelativeminutenum",
107
+ "torelativemonthnum", "torelativeweeknum", "torelativeyearnum", "tsordstodate", "date", "identity"],
108
+ }
109
+
110
+
111
+ def settings_of(config: dict | None) -> dict:
112
+ out = {**DEFAULTS, **{k: list(v) for k, v in LIST_DEFAULTS.items()}}
113
+ for k, v in (config or {}).items():
114
+ if k in DEFAULTS:
115
+ d = DEFAULTS[k]
116
+ if isinstance(d, bool):
117
+ if isinstance(v, bool):
118
+ out[k] = v
119
+ elif isinstance(d, str):
120
+ if isinstance(v, str) and v in ("function", "entry_point"):
121
+ out[k] = v
122
+ elif isinstance(v, (int, float)) and not isinstance(v, bool) and v >= 0:
123
+ out[k] = type(d)(v)
124
+ elif k in LIST_DEFAULTS and isinstance(v, list) and all(isinstance(x, str) for x in v):
125
+ out[k] = [x.lower() for x in v] if k in ("key_safe_functions", "time_bound_scope_columns", "skip_roles") else [x for x in v if x in SCENARIOS] or list(SCENARIOS)
126
+ return out
127
+
128
+
129
+ # ---- the statements ------------------------------------------------------------------------------------------------
130
+
131
+ def _hours_since(since, until) -> float | None:
132
+ """Hours from pg_stat_statements' last reset to the pull: what its cumulative counts cover."""
133
+ try:
134
+ a = datetime.fromisoformat(str(since).replace(" ", "T")[:26].rstrip("+"))
135
+ b = datetime.fromisoformat(str(until).replace(" ", "T")[:26].rstrip("+"))
136
+ except (TypeError, ValueError):
137
+ return None
138
+ h = (b.replace(tzinfo=None) - a.replace(tzinfo=None)).total_seconds() / 3600
139
+ return round(h, 2) if h > 0 else None
140
+
141
+
142
+ def _short(name: str) -> str:
143
+ return str(name or "").replace("`", "").replace('"', "").split(".")[-1]
144
+
145
+
146
+ def _workload_texts(facts, engine: str) -> dict[str, dict]:
147
+ conn = next((w for w in ((facts.workload or {}).get("connections") or {}).values() if w.get("engine") == engine), None)
148
+ if conn is None and getattr(facts, "out_dir", None) is not None:
149
+ from .dbcli import load_workload
150
+ try:
151
+ whole = load_workload(facts.out_dir)
152
+ except (OSError, ValueError):
153
+ whole = {}
154
+ conn = next((w for w in (whole.get("connections") or {}).values() if w.get("engine") == engine), None)
155
+ return {str(q.get("hash")): q for q in (conn or {}).get("queries") or []}
156
+
157
+
158
+ def statements(inventory: dict | None, facts=None, engine: str | None = None) -> list[dict]:
159
+ """Every statement text CodeCop knows, with its two labels and, for a pulled statement, its measured load."""
160
+ out = []
161
+ for s in (inventory or {}).get("call_sites") or []:
162
+ if s.get("is_test") or s.get("statement") != "select" or not (s.get("sql") or "").strip():
163
+ continue
164
+ out.append({"ref": f"site:{s.get('id')}", "sql_from": "orm" if s.get("resolution") == "orm" else "code", "located": "site",
165
+ "engine": s.get("engine") or "", "text": s["sql"], "site_ids": [s.get("id")], "hash": None,
166
+ "file": s.get("file"), "line": s.get("line"), "symbol": s.get("symbol"), "role": s.get("role"),
167
+ "origins": s.get("origins") or [], "tables": [_short(t) for t in s.get("tables") or []], "measured": None,
168
+ "resolution": s.get("resolution")})
169
+ if facts:
170
+ from .observed import _databases, strip_databases
171
+ databases = _databases(facts.catalog)
172
+ engines = [engine] if engine else list((facts.matchdata.get("engines") or {}))
173
+ for eng in engines:
174
+ m = facts.match(eng) or {}
175
+ texts = _workload_texts(facts, eng)
176
+ total = int((m.get("workload") or {}).get("read_bytes") or 0)
177
+ hours = float(m.get("window_hours") or 0) or None
178
+ since_hours = _hours_since(m.get("since"), (facts.workload or {}).get("generated_at") or (facts.matchdata or {}).get("generated_at")) \
179
+ if hours is None else None
180
+ for q in m.get("queries") or []:
181
+ w = texts.get(str(q.get("hash"))) or {}
182
+ if (w.get("kind") or "select") != "select" or not w.get("text"):
183
+ continue
184
+ grade = q.get("match") or "none"
185
+ sids = list(q.get("site_ids") or []) if grade in ("exact", "template", "tag", "part") else []
186
+ meas = {k: q.get(k) for k in ("executions", "read_bytes", "read_rows", "rows_read_per_run", "bytes_read_per_run",
187
+ "rows_returned_per_run", "no_result_share", "no_read_share", "selected_marks_per_run",
188
+ "selected_parts_per_run", "aggregate", "spread") if q.get(k) is not None}
189
+ if eng == "postgres" and meas.get("no_result_share") is None and int(q.get("executions") or 0) > 0 \
190
+ and q.get("result_rows") is not None:
191
+ # pg_stat_statements counts rows returned in total, not per run: every run that returned something
192
+ # returned at least one row, so at least 1 - rows / calls of the runs returned nothing (a lower bound)
193
+ meas["no_result_share"] = round(max(0.0, 1.0 - int(q["result_rows"]) / int(q["executions"])), 6)
194
+ meas["no_result_share_basis"] = "at_least"
195
+ meas["stats_source"] = "pg_stat_statements"
196
+ meas["share_of_read_bytes"] = round(int(q.get("read_bytes") or 0) / total, 6) if total else None
197
+ meas["window_hours"] = hours
198
+ if since_hours:
199
+ meas["hours_since_reset"] = since_hours # pg_stat_statements: cumulative since this many hours
200
+ meas["workload_read_bytes"] = total
201
+ out.append({"ref": f"shape:{q.get('hash')}", "sql_from": "query_log", "located": grade, "engine": eng,
202
+ "text": strip_databases(w["text"], databases), "site_ids": sids, "hash": str(q.get("hash")),
203
+ "file": None, "line": None, "symbol": None, "tables": sorted({_short(t) for t in q.get("tables") or w.get("tables") or []}),
204
+ "measured": meas, "possible": list(q.get("site_ids") or []) if grade == "likely" else []})
205
+ return out
206
+
207
+
208
+ # ---- rules --------------------------------------------------------------------------------------------------------
209
+
210
+ def _fp(*parts) -> str:
211
+ return "scn_" + hashlib.sha1("|".join(str(p) for p in parts).encode()).hexdigest()[:12]
212
+
213
+
214
+ def _hit(rule: str, st: dict, table: str | None, evidence: dict, changes: list[str], proof_of: dict | None = None) -> dict:
215
+ return {"rule": rule, "scenario": RULE_SCENARIO[rule], "ref": st["ref"], "table": table, "evidence": evidence,
216
+ "changes": [{"change": c, "touches": CHANGES[c][0], "proof": (proof_of or {}).get(c, CHANGES[c][1])} for c in changes]}
217
+
218
+
219
+ def _median(sp: dict | None, key: str):
220
+ v = (sp or {}).get(key)
221
+ return v[0] if isinstance(v, list) and v else None
222
+
223
+
224
+ def measured_rules(st: dict, cfg: dict) -> list[dict]:
225
+ m = st.get("measured") or {}
226
+ if not m:
227
+ return []
228
+ out = []
229
+ hours = m.get("window_hours") or m.get("hours_since_reset") or 0
230
+ runs = int(m.get("executions") or 0)
231
+ per_hour = runs / hours if hours else None
232
+ share = m.get("no_result_share")
233
+ median_bytes = _median(m.get("spread"), "bytes_read")
234
+ basis = "median" if median_bytes is not None else "mean"
235
+ if median_bytes is None:
236
+ median_bytes = m.get("bytes_read_per_run")
237
+ if share is not None and share >= cfg["empty_min_share"] and (per_hour is None or per_hour >= cfg["empty_min_runs_per_hour"]) \
238
+ and (median_bytes or 0) >= cfg["empty_min_median_bytes"]:
239
+ est = min(share * runs * float(median_bytes or 0), float(m.get("read_bytes") or 0))
240
+ eng = st.get("engine") or "clickhouse"
241
+ out.append(_hit("empty_runs", st, (st.get("tables") or [None])[0], {
242
+ **({"no_result_share_basis": m["no_result_share_basis"]} if m.get("no_result_share_basis") else {}),
243
+ "executions": runs, "runs_per_hour": round(per_hour, 2) if per_hour is not None else None, "no_result_share": share,
244
+ "median_run_bytes": int(median_bytes or 0), "median_basis": basis,
245
+ "empty_runs_bytes_estimate": int(est), "estimate_assumption": (
246
+ "every run that returned nothing read what the median run read; the median run is an empty one when at least "
247
+ "half of the runs return nothing" if basis == "median" else
248
+ "every run that returned nothing read the mean run's bytes (the pull has no spread for this statement)"),
249
+ "read_bytes": int(m.get("read_bytes") or 0), "share_of_read_bytes": m.get("share_of_read_bytes"),
250
+ **({"stats_note": "pg_stat_statements: totals since its last reset, no per-run distribution; the share of empty runs is a "
251
+ "lower bound (rows returned / calls) and a run's bytes are the mean run's"} if eng == "postgres" else {})},
252
+ EMPTY_CHANGES.get(eng, EMPTY_CHANGES["clickhouse"])))
253
+ rr, ret = float(m.get("rows_read_per_run") or 0), float(m.get("rows_returned_per_run") or 0)
254
+ marks = m.get("selected_marks_per_run")
255
+ if rr >= cfg["far_min_rows_read"] and rr / max(ret, 1.0) >= cfg["far_min_ratio"] and not m.get("aggregate") \
256
+ and (marks is None or marks >= cfg["far_min_marks"]):
257
+ out.append(_hit("reads_far_above_returns", st, (st.get("tables") or [None])[0], {
258
+ "executions": runs, "rows_read_per_run": rr, "rows_returned_per_run": ret, "rows_read_per_row_returned": round(rr / max(ret, 1.0), 1),
259
+ "marks_per_run": marks, "read_bytes": int(m.get("read_bytes") or 0), "share_of_read_bytes": m.get("share_of_read_bytes")},
260
+ ["skip_index", "projection", "sorting_key", "add_time_bound"]))
261
+ return out
262
+
263
+
264
+ def _info(tables: dict, name: str):
265
+ return tables.get(name) or tables.get(name.lower()) or next((t for n, t in tables.items() if n.lower() == name.lower()), None)
266
+
267
+
268
+ def _time_bound_hit(st: dict, rd, info, single: bool, cfg: dict, seen: set, optional: list[str] | None = None) -> dict | None:
269
+ """no_time_bound for one read of a MergeTree table partitioned or keyed by time. `optional`: the optional clauses left
270
+ out of the statement; the hit then says whether one of them can add the bound (it is still the default request's)."""
271
+ eng = st.get("engine") or "clickhouse"
272
+ bounded, tcols = Q.time_bound(rd, info, single, cfg["time_bound_scope_columns"])
273
+ if bounded or eng != "clickhouse" or not re.search(r"MergeTree|merge_tree", info.engine or "", re.I):
274
+ return None
275
+ rows = info.rows
276
+ if rows is not None and rows < cfg["time_bound_min_table_rows"]:
277
+ return None
278
+ key = ("no_time_bound", info.name, id(rd.select))
279
+ if key in seen:
280
+ return None
281
+ seen.add(key)
282
+ extra = {}
283
+ if optional is not None:
284
+ adds = sorted({c for c in tcols if any(re.search(rf"\b{re.escape(c)}\b", h) for h in optional)})
285
+ extra = {"optional_parts": len(optional), "bound_only_when_optional": adds,
286
+ "why": ("bounded only when an optional filter is set (" + ", ".join(adds) + "); the request without it reads every partition")
287
+ if adds else "no optional filter of the statement bounds the time column"}
288
+ return _hit("no_time_bound", st, info.name, {"time_columns": tcols, "joined_side": rd.joined, "partition_key": info.partition_expr,
289
+ "sorting_key": info.sorting_expr, "table_rows": rows, "definition": info.source, **extra},
290
+ ["add_time_bound"])
291
+
292
+
293
+ def parsed_rules(st: dict, tables: dict, cfg: dict) -> tuple[list[dict], str | None]:
294
+ """The rules that read the parsed statement. Returns (hits, why nothing could be read) ."""
295
+ eng = st.get("engine") or "clickhouse"
296
+ p = Q.parse(st["text"], eng)
297
+ if not p.ok:
298
+ return [], "unparsed"
299
+ out = []
300
+ rds = Q.reads(p.tree)
301
+ per_select = Counter(id(r.select) for r in rds)
302
+ safe = set(cfg["key_safe_functions"]) if eng == "clickhouse" else set()
303
+ seen = set()
304
+ for rd in rds:
305
+ info = _info(tables, rd.table)
306
+ if info is None:
307
+ continue
308
+ single = per_select[id(rd.select)] == 1
309
+ dyn = Q.dynamic_filter(rd) or p.dropped
310
+ if dyn and cfg["require_static_where"]:
311
+ # the only run-time parts are optional clauses whose text discover kept (a helper that appends each filter
312
+ # under its own `if`): the statement sent with none of them set has no time bound unless the rest has one,
313
+ # and whether an optional part can add one is read from its text
314
+ if p.only_optional_cut and not Q.dynamic_filter(rd):
315
+ hit = _time_bound_hit(st, rd, info, single, cfg, seen, optional=p.cut)
316
+ if hit:
317
+ out.append(hit)
318
+ continue
319
+ for w in Q.wrapped_key_filters(rd, info, eng, safe, single, cfg["key_wrapped_requires_parameter"]):
320
+ key = ("key_wrapped", info.name, w.column)
321
+ if key in seen:
322
+ continue
323
+ seen.add(key)
324
+ out.append(_hit("key_wrapped", st, info.name, {"column": w.column, "functions": w.functions, "clause": w.clause,
325
+ "in": "sorting key" if w.column in info.key_cols else "partition key",
326
+ "unwrappable": w.unwrap, "why": w.why, "definition": info.source},
327
+ ["unwrap_key_column" if w.unwrap else "rewrite_wrapped_predicate"]))
328
+ for lk in Q.map_lookup_filters(rd, info, eng, single, cfg["map_lookup_requires_key_column"]):
329
+ key = ("map_lookup", info.name, lk.path)
330
+ if key in seen:
331
+ continue
332
+ seen.add(key)
333
+ out.append(_hit("map_lookup", st, info.name, {"lookup": lk.path, "column": lk.column, "column_in_key": lk.in_key,
334
+ "clause": lk.clause, "definition": info.source}, ["compare_typed_column"]))
335
+ hit = _time_bound_hit(st, rd, info, single, cfg, seen)
336
+ if hit:
337
+ out.append(hit)
338
+ sel = Q.outer_select(p.tree)
339
+ if sel is not None:
340
+ own = [r for r in rds if r.select is sel]
341
+ # a column store reads a column for every row the filter keeps before LIMIT; a row store with an index on the order
342
+ # reads the page's rows only: the heavy-column rules are ClickHouse's
343
+ if eng == "clickhouse" and len(own) == 1 and Q.limit_of(sel) is not None and Q.real_limit(sel) and sel.args.get("order") is not None:
344
+ rd = own[0]
345
+ info = _info(tables, rd.table)
346
+ if info is not None:
347
+ cols, star = Q.selected_columns(sel, rd, info, True)
348
+ if star:
349
+ cols |= set(info.columns)
350
+ wide = sorted(c for c in cols if info.wide(c, cfg["heavy_min_bytes_per_row"])[0])
351
+ if wide:
352
+ agg = Q.is_aggregate(sel, eng)
353
+ heavy_agg = Q.heavy_in_aggregate(sel, rd, info, eng, cfg["heavy_min_bytes_per_row"], True) if agg else []
354
+ if not agg:
355
+ out.append(_hit("wide_before_limit", st, info.name, {
356
+ "wide_columns": wide[:8], "sized_by": sorted({info.wide(c, cfg["heavy_min_bytes_per_row"])[1] for c in wide}),
357
+ "bytes_per_row": {c: round(info.row_bytes[c]) for c in wide if c in info.row_bytes}, "final": rd.final,
358
+ "sorting_key": info.sorting_key}, ["late_materialization"]))
359
+ elif heavy_agg:
360
+ out.append(_hit("wide_in_aggregate_before_limit", st, info.name, {
361
+ "wide_columns": heavy_agg[:8], "bytes_per_row": {c: round(info.row_bytes[c]) for c in heavy_agg if c in info.row_bytes}},
362
+ ["late_materialization_aggregate"]))
363
+ if eng == "clickhouse" and Q.real_limit(sel) and not any(h["rule"] in ("wide_before_limit", "wide_in_aggregate_before_limit") for h in out):
364
+ # a page whose rows come out of an aggregate (in a CTE or a subquery) that carries wide columns through
365
+ # argMax / any / groupArray for every group, before the page keeps a few
366
+ for rd in rds + Q.cte_reads(p.tree):
367
+ info = _info(tables, rd.table)
368
+ if info is None or rd.select is sel or not Q.is_aggregate(rd.select, eng):
369
+ continue
370
+ heavy_agg = Q.heavy_in_aggregate(rd.select, rd, info, eng, cfg["heavy_min_bytes_per_row"], per_select.get(id(rd.select), 1) <= 1)
371
+ if heavy_agg:
372
+ out.append(_hit("wide_in_aggregate_before_limit", st, info.name, {
373
+ "wide_columns": heavy_agg[:8], "bytes_per_row": {c: round(info.row_bytes[c]) for c in heavy_agg if c in info.row_bytes},
374
+ "inner": True}, ["late_materialization_aggregate"]))
375
+ break
376
+ if Q.wrapped_count(p.tree, eng):
377
+ if Q.inner_order_without_limit(p.tree):
378
+ out.append(_hit("count_over_sorted_subquery", st, (st.get("tables") or [None])[0], {"inner": "ORDER BY, no LIMIT"},
379
+ ["drop_inner_order"]))
380
+ elif Q.inner_is_runtime(p.tree):
381
+ out.append(_hit("count_over_sorted_subquery", st, (st.get("tables") or [None])[0],
382
+ {"inner": "assembled at run time: whether it sorts is not visible in code"},
383
+ ["drop_inner_order"], {"drop_inner_order": "needs_agent"}))
384
+ return out, None
385
+
386
+
387
+ def narrow_copy_rules(st: dict, tables: dict, catalog_tables: dict, cfg: dict) -> list[dict]:
388
+ """A statement on a wide table whose columns all exist in the target of a materialized view fed from that table.
389
+ Says exactly what the catalog shows and what it does not."""
390
+ if not catalog_tables:
391
+ return []
392
+ eng = st.get("engine") or "clickhouse"
393
+ p = Q.parse(st["text"], eng)
394
+ if not p.ok:
395
+ return []
396
+ out = []
397
+ rds = Q.reads(p.tree)
398
+ per_select = Counter(id(r.select) for r in rds)
399
+ for name in sorted({r.table for r in rds}):
400
+ src = _info(tables, name)
401
+ if src is None or not src.feeds or src.source != "real catalog":
402
+ continue
403
+ used, star = set(), False
404
+ for rd in [r for r in rds if r.table == name]:
405
+ single = per_select[id(rd.select)] == 1
406
+ used |= {c for node in rd.select.iter_expressions() for c in Q.columns_in(node, rd, src, single)}
407
+ if any(isinstance(e_, __import__("sqlglot").exp.Star) for e_ in rd.select.expressions):
408
+ star = True
409
+ if star or not used:
410
+ continue
411
+ for mv_name in src.feeds:
412
+ mv = catalog_tables.get(_short(mv_name)) or {}
413
+ ver = verify_copy(mv, src, catalog_tables, used, cfg)
414
+ if ver is None or not ver["columns_covered"]:
415
+ continue
416
+ out.append(_hit("narrow_copy", st, name, {"copy": ver["target"], "view": _short(mv_name), "verified": ver["verified"],
417
+ "not_verified": ver["not_verified"], "source_rows": src.rows, "copy_rows": ver["target_rows"],
418
+ "columns": sorted(used)[:20]},
419
+ ["read_narrow_copy"], {"read_narrow_copy": "sandbox" if not ver["not_verified"] else "evidence_only"}))
420
+ return out
421
+
422
+
423
+ def verify_copy(mv: dict, src, catalog_tables: dict, used: set[str], cfg: dict) -> dict | None:
424
+ """What the catalog shows about a materialized view as a copy of `src`: {target, verified[], not_verified[],
425
+ columns_covered, target_rows, select}. The checks: it reads `src` (lineage), its SELECT keeps every row (no WHERE,
426
+ GROUP BY, DISTINCT, LIMIT, JOIN, ARRAY JOIN or aggregate), each column the statement uses is a column of the target
427
+ computed as the same source column, and the target holds at least `copy_min_row_ratio` of the source's rows."""
428
+ from sqlglot import exp
429
+ text = mv.get("create_sql") or ""
430
+ m = re.search(r"\bTO\s+([`\"\w.]+)", text, re.I)
431
+ body = re.search(r"\bAS\s+(SELECT\b.*)$", text, re.I | re.S)
432
+ if not m or not body:
433
+ return None
434
+ target = _short(m.group(1))
435
+ t = catalog_tables.get(target) or {}
436
+ p = Q.parse(body.group(1), "clickhouse")
437
+ verified, not_verified = [], []
438
+ if not p.ok:
439
+ return {"target": target, "verified": [], "not_verified": ["view_select_unparsed"], "columns_covered": False, "target_rows": t.get("rows")}
440
+ sel = Q.outer_select(p.tree)
441
+ froms = {r.table for r in Q.reads(p.tree)}
442
+ (verified if froms == {src.name} else not_verified).append("reads_the_same_table")
443
+ keeps = sel is not None and not any(sel.args.get(k) for k in ("where", "prewhere", "group", "distinct", "limit", "joins", "having")) \
444
+ and not sel.find(exp.Unnest) and not Q.is_aggregate(sel, "clickhouse") and "array join" not in body.group(1).lower()
445
+ (verified if keeps else not_verified).append("keeps_every_row")
446
+ mapping = {}
447
+ for e_ in (sel.expressions if sel is not None else []):
448
+ alias = e_.alias_or_name
449
+ inner = e_.this if isinstance(e_, exp.Alias) else e_
450
+ mapping[alias] = inner.name if isinstance(inner, exp.Column) else None
451
+ target_cols = {c["name"] for c in t.get("columns") or []}
452
+ same = [c for c in used if c in target_cols and (mapping.get(c) == c or (not mapping and c in target_cols))]
453
+ covered = len(same) == len(used)
454
+ (verified if covered else not_verified).append("same_columns")
455
+ rows_src, rows_t = int(src.rows or 0), int(t.get("rows") or 0)
456
+ (verified if rows_src and rows_t >= rows_src * cfg["copy_min_row_ratio"] else not_verified).append("complete_copy")
457
+ if src.deduplicating:
458
+ (verified if re.search(r"Replacing", t.get("engine") or "") and t.get("sorting_key") == src.sorting_expr else not_verified).append(
459
+ "same_deduplication")
460
+ any_cover = all(c in target_cols for c in used)
461
+ return {"target": target, "verified": verified, "not_verified": not_verified, "columns_covered": any_cover, "target_rows": rows_t,
462
+ "select": body.group(1)}
463
+
464
+
465
+ def count_page_rules(stmts: list[dict], tables: dict, cfg: dict) -> list[dict]:
466
+ """A count-only statement and a paged statement on the same table, in one function (or under one entry point)."""
467
+ groups: dict[tuple, list[dict]] = defaultdict(list)
468
+ for st in stmts:
469
+ if st["sql_from"] == "query_log":
470
+ continue
471
+ if cfg["count_page_scope"] == "entry_point":
472
+ for o in st.get("origins") or []:
473
+ if o.get("kind") == "http":
474
+ groups[("ep", o.get("name"), o.get("file"), o.get("line"))].append(st)
475
+ elif st.get("symbol"):
476
+ groups[("fn", st.get("file"), st.get("symbol"))].append(st)
477
+ out = []
478
+ for key, members in groups.items():
479
+ if len(members) < 2:
480
+ continue
481
+ parsed = []
482
+ for st in members:
483
+ p = Q.parse(st["text"], st.get("engine") or "clickhouse")
484
+ sel = Q.outer_select(p.tree) if p.ok else None
485
+ if sel is None:
486
+ continue
487
+ parsed.append((st, p, sel))
488
+ counts = [(st, p, sel) for st, p, sel in parsed if Q.count_only(sel, st.get("engine") or "") and not Q.wrapped_count(p.tree, st.get("engine") or "")]
489
+ pages = [(st, p, sel) for st, p, sel in parsed if not Q.count_only(sel, st.get("engine") or "") and Q.real_limit(sel)]
490
+ for st, p, sel in counts:
491
+ ctabs = {r.table.lower() for r in Q.reads(p.tree)}
492
+ cf = Q.where_columns(sel)
493
+ for pst, pp, psel in pages:
494
+ ptabs = {r.table.lower() for r in Q.reads(pp.tree)}
495
+ common = ctabs & ptabs
496
+ if not common:
497
+ continue
498
+ pf = Q.where_columns(psel)
499
+ if bool(cf) != bool(pf):
500
+ continue
501
+ overlap = len(cf & pf) / max(len(cf | pf), 1) if cf or pf else 1.0
502
+ if overlap < cfg["count_page_min_filter_overlap"]:
503
+ continue
504
+ rows = [(_info(tables, t).rows if _info(tables, t) else None) for t in common]
505
+ known = [r for r in rows if r is not None]
506
+ if known and max(known) < cfg["count_page_min_table_rows"]:
507
+ continue
508
+ out.append({**_hit("count_next_to_page", st, sorted(common)[0], {
509
+ "page_site": pst["site_ids"][0], "page_file": pst.get("file"), "page_line": pst.get("line"),
510
+ "scope": cfg["count_page_scope"], "filter_overlap": round(overlap, 2), "table_rows": max(known) if known else None,
511
+ "page_offset": psel.args.get("offset") is not None}, ["count_over_window", "totals_optional"])})
512
+ break
513
+ return out
514
+
515
+
516
+ # ---- candidates ---------------------------------------------------------------------------------------------------
517
+
518
+ def detect(inventory: dict | None, facts=None, settings: dict | None = None, engine: str | None = None) -> dict:
519
+ """The scenario hits of every statement, merged into candidates, and the accounting of measured bytes. Binding to a
520
+ runnable statement and the variants are added by `bind` (they need rank.json and observed.json)."""
521
+ cfg = settings_of(settings)
522
+ stmts = statements(inventory, facts, engine)
523
+ tables = Q.tables_from_inventory(inventory or {})
524
+ catalog_tables_raw = {}
525
+ if facts:
526
+ for eng in ([engine] if engine else list((facts.matchdata.get("engines") or {})) or ["clickhouse"]):
527
+ tables.update(Q.tables_from_catalog(facts, eng))
528
+ catalog_tables_raw.update(facts.tables(eng))
529
+ hits, unparsed = [], Counter()
530
+ set_aside = Counter()
531
+ skip = set(cfg["skip_roles"])
532
+ # call sites whose own text is fixed SQL: the parsed rules read that text (its literals are literals), not the server's
533
+ # normalized text of the statement matched to it, where every literal is a `?` (`length(key) = 64` looks like a lookup)
534
+ fixed_text = {st["site_ids"][0] for st in stmts if st["sql_from"] != "query_log" and st.get("resolution") in ("literal", "constant", "file")}
535
+ for st in stmts:
536
+ if st["sql_from"] != "query_log" and st.get("role") in skip:
537
+ set_aside[f"role_{st['role']}"] += 1 # code that runs once or only for tooling: counted, not a candidate
538
+ continue
539
+ hits += measured_rules(st, cfg)
540
+ if st["sql_from"] == "query_log" and st["located"] in ("exact", "template") and st["site_ids"] and set(st["site_ids"]) <= fixed_text:
541
+ set_aside["parsed_on_code_text"] += 1
542
+ got, why = [], None
543
+ else:
544
+ got, why = parsed_rules(st, tables, cfg)
545
+ if why:
546
+ unparsed[st["sql_from"]] += 1
547
+ hits += got
548
+ hits += narrow_copy_rules(st, tables, catalog_tables_raw, cfg)
549
+ hits += count_page_rules([st for st in stmts if st["sql_from"] == "query_log" or st.get("role") not in skip], tables, cfg)
550
+ by_ref = {st["ref"]: st for st in stmts}
551
+ # shapes each call site is matched to (exact, template, tag): a site's static hit is also the shape's
552
+ site_to_shapes: dict[str, list[str]] = defaultdict(list)
553
+ for st in stmts:
554
+ if st["sql_from"] == "query_log" and st["located"] in ("exact", "template", "tag"):
555
+ for sid in st["site_ids"]:
556
+ site_to_shapes[sid].append(st["ref"])
557
+ groups: dict[tuple, dict] = {}
558
+ for h in hits:
559
+ st = by_ref[h["ref"]]
560
+ anchor = h["ref"]
561
+ if st["sql_from"] != "query_log":
562
+ shapes = sorted(site_to_shapes.get(st["site_ids"][0], []), key=lambda s: -int((by_ref[s].get("measured") or {}).get("read_bytes") or 0))
563
+ same = [s for s in shapes if any(x["ref"] == s and x["scenario"] == h["scenario"] for x in hits)]
564
+ if same or shapes:
565
+ anchor = (same or shapes)[0] # the statement production ran from this call site: its measured load
566
+ g = groups.setdefault((h["scenario"], anchor), {"scenario": h["scenario"], "anchor": anchor, "hits": [], "refs": set()})
567
+ g["hits"].append(h)
568
+ g["refs"].add(h["ref"])
569
+ cands = []
570
+ for (scen, anchor), g in groups.items():
571
+ st = by_ref[anchor]
572
+ rules = sorted({h["rule"] for h in g["hits"]}, key=lambda r: RULES[scen].index(r))
573
+ changes, seen = [], set()
574
+ for h in g["hits"]:
575
+ for c in h["changes"]:
576
+ if c["change"] not in seen:
577
+ seen.add(c["change"])
578
+ changes.append(dict(c))
579
+ also = sorted({by_ref[r]["site_ids"][0] for r in g["refs"] if r != anchor and by_ref[r]["sql_from"] != "query_log"})
580
+ sites = list(st["site_ids"])
581
+ first = None
582
+ if inventory:
583
+ ids = {s.get("id"): s for s in inventory.get("call_sites") or []}
584
+ first = ids.get(sites[0]) if sites else None
585
+ place = {"file": (first or {}).get("file") or st.get("file"), "line": (first or {}).get("line") or st.get("line"),
586
+ "symbol": (first or {}).get("symbol") or st.get("symbol")} if (first or st.get("file")) else {}
587
+ cands.append({
588
+ "fingerprint": _fp(scen, st.get("hash") or "", *sorted(sites) if st["sql_from"] != "query_log" or not st.get("hash") else []),
589
+ "scenario": scen, "label": LABEL[scen], "rules": rules,
590
+ "statement": {"ref": anchor, "hash": st.get("hash"), "sql_from": st["sql_from"], "located": st["located"], "engine": st.get("engine"),
591
+ "site_ids": sites, **place, "tables": st.get("tables") or [], "possible_places": st.get("possible") or []},
592
+ "also_fires_on_code": also,
593
+ "measured": _measured_out(st.get("measured")),
594
+ "evidence": [{"rule": h["rule"], "table": h["table"], **h["evidence"]} for h in g["hits"]],
595
+ "changes": changes, "proof": _proof(changes),
596
+ })
597
+ order = {s: i for i, s in enumerate(cfg["order"])}
598
+ cands.sort(key=lambda c: (-int((c["measured"] or {}).get("read_bytes") or 0), order.get(c["scenario"], 9), c["fingerprint"]))
599
+ for i, c in enumerate(cands, 1):
600
+ c["id"] = f"SC-{i:03d}"
601
+ acc = accounting(cands, stmts, cfg)
602
+ by_src = Counter(st["sql_from"] for st in stmts)
603
+ summary = {"statements": dict(by_src), "unparsed": dict(unparsed), "set_aside": dict(set_aside), "candidates": len(cands),
604
+ "by_scenario": {s: sum(1 for c in cands if c["scenario"] == s) for s in SCENARIOS},
605
+ "by_rule": dict(Counter(r for c in cands for r in c["rules"])),
606
+ "by_proof": dict(Counter(c["proof"] for c in cands)),
607
+ "empty_runs_bytes_estimate": sum(int(e.get("empty_runs_bytes_estimate") or 0) for c in cands for e in c["evidence"]
608
+ if e["rule"] == "empty_runs")}
609
+ return {"schema_version": SCHEMA_VERSION, "generated_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
610
+ "settings": cfg, "summary": summary, "accounting": acc, "candidates": cands}
611
+
612
+
613
+ def _measured_out(m: dict | None) -> dict | None:
614
+ if not m:
615
+ return None
616
+ return {k: m.get(k) for k in ("executions", "read_bytes", "share_of_read_bytes", "window_hours", "rows_read_per_run",
617
+ "rows_returned_per_run", "bytes_read_per_run", "no_result_share", "no_result_share_basis",
618
+ "stats_source", "hours_since_reset", "selected_marks_per_run") if m.get(k) is not None}
619
+
620
+
621
+ def _proof(changes: list[dict]) -> str:
622
+ got = {c["proof"] for c in changes}
623
+ for p in PROOFS:
624
+ if p in got:
625
+ return p
626
+ return "evidence_only"
627
+
628
+
629
+ def accounting(cands: list[dict], stmts: list[dict], cfg: dict) -> list[dict]:
630
+ """Per engine: every measured byte counted once by the first scenario it fits (`order`), what each scenario fits
631
+ with overlaps, and the pairwise overlap in bytes."""
632
+ out = []
633
+ shapes = [st for st in stmts if st["sql_from"] == "query_log" and st.get("measured")]
634
+ for eng in sorted({st["engine"] for st in shapes}):
635
+ mine = [st for st in shapes if st["engine"] == eng]
636
+ fits: dict[str, set[str]] = defaultdict(set)
637
+ site_scen: dict[str, set[str]] = defaultdict(set)
638
+ for c in cands:
639
+ if c["statement"]["sql_from"] == "query_log" and c["statement"]["engine"] == eng:
640
+ fits[c["statement"]["ref"]].add(c["scenario"])
641
+ elif c["statement"]["sql_from"] != "query_log":
642
+ for sid in c["statement"]["site_ids"]:
643
+ site_scen[sid].add(c["scenario"])
644
+ for st in mine:
645
+ if st["located"] in ("exact", "template", "tag"):
646
+ for sid in st["site_ids"]:
647
+ fits[st["ref"]] |= site_scen.get(sid, set())
648
+ in_shapes = sum(int(st["measured"].get("read_bytes") or 0) for st in mine)
649
+ # shares are of every byte the workload read in the window (the pull's total), so they compare with the patterns'
650
+ total = max(next((int(st["measured"].get("workload_read_bytes") or 0) for st in mine), 0), in_shapes)
651
+ first: dict[str, list] = defaultdict(lambda: [0, 0, 0])
652
+ fit_bytes: dict[str, list] = defaultdict(lambda: [0, 0, 0])
653
+ overlap = {a: {b: 0 for b in cfg["order"]} for a in cfg["order"]}
654
+ for st in mine:
655
+ b, n = int(st["measured"].get("read_bytes") or 0), int(st["measured"].get("executions") or 0)
656
+ got = [s for s in cfg["order"] if s in fits.get(st["ref"], set())]
657
+ k = got[0] if got else "none"
658
+ first[k][0] += 1
659
+ first[k][1] += n
660
+ first[k][2] += b
661
+ for s in got:
662
+ fit_bytes[s][0] += 1
663
+ fit_bytes[s][1] += n
664
+ fit_bytes[s][2] += b
665
+ for t in got:
666
+ overlap[s][t] += b
667
+ rows = [{"scenario": s, "shapes": first[s][0], "executions": first[s][1], "read_bytes": first[s][2],
668
+ "share_of_read_bytes": round(first[s][2] / total, 6) if total else None,
669
+ "fits": {"shapes": fit_bytes[s][0], "read_bytes": fit_bytes[s][2], "share_of_read_bytes": round(fit_bytes[s][2] / total, 6) if total else None}}
670
+ for s in list(cfg["order"]) + ["none"] if s in first or s in fit_bytes]
671
+ out.append({"engine": eng, "window_hours": next((st["measured"].get("window_hours") for st in mine), None), "shapes": len(mine),
672
+ "read_bytes_total": total, "read_bytes_in_shapes": in_shapes,
673
+ "note": "statements that are reads with a text in the pull; shares are of every byte read in the window", "first_fit": rows,
674
+ "overlap_bytes": {a: {b: v for b, v in row.items() if v} for a, row in overlap.items() if any(row.values())}})
675
+ return out