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/groups.py ADDED
@@ -0,0 +1,594 @@
1
+ """Scan groups: statements that run together and scan the same table under the same filter.
2
+
3
+ A dashboard page, a job cycle or a loop body often sends several statements that read the same rows of one table (the
4
+ same tenant, the same time window) and differ only in what they compute from them. Each statement alone may be as good
5
+ as it can be; together they read those rows N times. The fix is one statement that reads them once (conditional
6
+ aggregates, GROUPING SETS, a shared subquery, one fetch then derive): an application change, because the code must
7
+ call one query instead of N. One statement that reads the same CTE or subquery twice is the same waste inside one
8
+ statement (ClickHouse evaluates a CTE once per reference): a group of one.
9
+
10
+ How "run together" is known (`run_together[]`, and `confidence`, the strongest of them):
11
+
12
+ loop the statements run in the same loop body, every turn (inventory `loop_context`) code_path_traced / _guessed
13
+ entry_point one entry point (a route, a job, an activity) reaches them (inventory `origins`) code_path_traced / _guessed
14
+ function the same function sends them (off by default: such statements are often alternative branches)
15
+ counts production shapes whose run counts agree within a tolerance, from the same client counts_agree
16
+ one_statement a CTE or subquery read twice in one statement one_statement
17
+
18
+ Inside each such set, members must scan the same table with a shared filter: the predicates of each scan (parsed by
19
+ sqlinfo.scan_filters, never matched as text) that all members have, with at least `min_shared_predicates` of them and,
20
+ by default, an equality (the tenant). Statements from code, ORM translations and the statements production ran
21
+ (`sql_from`, `located`, as observed.py labels them) all qualify; a code site and the production shape it was matched to
22
+ are one member.
23
+
24
+ Load, when a query log was pulled: per member and summed, each shape counted once in a group; a shape that is a member
25
+ of several groups is flagged (`shared_with`), and the summary counts the bytes of all groups once.
26
+
27
+ Every threshold is a setting under `[groups]` in codecop.toml (DEFAULTS). Nothing here sends a literal value, a database or
28
+ a host name: predicates are normalized text (every value `?`), tables are named without their database.
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ import hashlib
34
+ import json
35
+ import re
36
+ from collections import defaultdict
37
+ from datetime import datetime, timezone
38
+ from pathlib import Path
39
+
40
+ from . import sqlinfo
41
+
42
+ SCHEMA_VERSION = 1
43
+ FILE = "groups.json"
44
+
45
+ DEFAULTS = {
46
+ "min_members_loop": 2, # statements of one loop body on one table and filter
47
+ "min_members_entry_point": 3, # ... under one entry point (two were mostly a count and its page, or two branches)
48
+ "min_members_function": 2, # ... in one function, when use_same_function is on
49
+ "min_members_counts": 2, # production shapes whose run counts agree
50
+ "max_entry_point_selects": 60, # an entry point reaching more selects on one table is a dispatcher of several views
51
+ "max_entry_point_hop": 4, # calls between an entry point and a statement (deeper: reachable, not called on every request)
52
+ "max_entry_point_functions": 3, # members from more functions than this: a route that dispatches to one of several views
53
+ "max_loop_hop": 3, # calls between a loop body and a statement it runs (deeper: another branch of the work, mostly)
54
+ "together_tolerance": 0.01, # run counts within 1% of the smallest fire together
55
+ "together_slack_runs": 1, # ... plus this many runs (38 and 39 agree)
56
+ "together_min_runs": 10, # shapes run fewer times are not grouped by their counts
57
+ "min_shared_predicates": 1, # predicates every member of a group has on the shared table
58
+ "cte_min_refs": 2, # a CTE (or a subquery written out again) read at least this often in one statement
59
+ "max_members": 50, # members listed per group (`member_count` keeps the full number)
60
+ "max_groups": 1000,
61
+ }
62
+ BOOL_DEFAULTS = {
63
+ "require_equality": True, # the shared filter holds an equality (= or IN) to a parameter: the tenant, the key
64
+ "entry_point_aggregates_only": True, # under an entry point only aggregates count (lists of rows are not combined)
65
+ "loop_aggregates_only": True, # in a loop body likewise: two lookups by key each turn read other rows each
66
+ "skip_key_lookups": True, # a shared filter that is only `id = ?` is a lookup of one row by its key, not a scan
67
+ "use_same_function": False, # statements of one function are often alternative branches
68
+ "together_same_client": True, # shapes that fire together come from the same client (driver), when the log says
69
+ }
70
+ LIST_DEFAULTS = {
71
+ "cte_engines": ["clickhouse"], # engines that evaluate a CTE once per reference (PostgreSQL 12+ materializes one read twice)
72
+ }
73
+ SOURCES = ("loop", "entry_point", "function", "counts", "one_statement")
74
+ CONFIDENCE = ("one_statement", "code_path_traced", "counts_agree", "code_path_guessed")
75
+ KINDS = ("shared_scan", "repeated_read")
76
+ # member roles: what a member computes from the shared rows (a hook for other rules: a count beside its page)
77
+ ROLES = ("aggregate", "count", "page", "rows")
78
+ # Other rules may claim a group shape (the count beside a page is another module's rule): fn(group, members) -> label or None.
79
+ CLASSIFIERS: list = []
80
+
81
+
82
+ def register_classifier(fn) -> None:
83
+ """Add a classifier: called with each group and its member records; a label it returns goes into `labels`."""
84
+ if fn not in CLASSIFIERS:
85
+ CLASSIFIERS.append(fn)
86
+
87
+
88
+ def settings_of(config: dict | None) -> dict:
89
+ """The `[groups]` table of codecop.toml over the defaults. A value of the wrong type is ignored."""
90
+ out = {**DEFAULTS, **BOOL_DEFAULTS, **{k: list(v) for k, v in LIST_DEFAULTS.items()}}
91
+ for k, v in (config or {}).items():
92
+ if k in DEFAULTS and isinstance(v, (int, float)) and not isinstance(v, bool):
93
+ out[k] = type(DEFAULTS[k])(v)
94
+ elif k in BOOL_DEFAULTS and isinstance(v, bool):
95
+ out[k] = v
96
+ elif k in LIST_DEFAULTS and isinstance(v, list) and all(isinstance(x, str) for x in v):
97
+ out[k] = list(v)
98
+ return out
99
+
100
+
101
+ def short(name) -> str:
102
+ return str(name or "").replace("`", "").replace('"', "").rsplit(".", 1)[-1].lower()
103
+
104
+
105
+ def _fp(*parts) -> str:
106
+ return "grp_" + hashlib.sha1("|".join(str(p) for p in parts).encode()).hexdigest()[:12]
107
+
108
+
109
+ # --------------------------------------------------------------------------- members
110
+
111
+ class Unit:
112
+ """One statement: a code site, a production shape, or both when the site was matched to that one shape."""
113
+
114
+ def __init__(self, key: str):
115
+ self.key = key
116
+ self.site_ids: list[str] = []
117
+ self.hash: str | None = None
118
+ self.engine = ""
119
+ self.sql_from = "code"
120
+ self.located = "site"
121
+ self.file = self.symbol = ""
122
+ self.line = 0
123
+ self.text = ""
124
+ self.measured: dict | None = None
125
+ self.agents: tuple = ()
126
+ self._info: dict | None = None
127
+ self.verified = True
128
+
129
+ @property
130
+ def info(self) -> dict:
131
+ if self._info is None:
132
+ self._info = sqlinfo.scan_filters(self.text, self.engine)
133
+ return self._info
134
+
135
+ def predicates(self, table: str) -> dict[str, dict]:
136
+ out = {}
137
+ for s in self.info["scans"]:
138
+ if s["table"] == table:
139
+ for p in s["predicates"]:
140
+ out.setdefault(p["text"], p)
141
+ return out
142
+
143
+ def tables(self) -> list[str]:
144
+ return sorted({s["table"] for s in self.info["scans"]})
145
+
146
+ def role(self) -> str:
147
+ info = self.info
148
+ if info["aggregate"]:
149
+ return "count" if re.match(r"^\s*SELECT\s+count\s*\(\s*\*?\s*\)\s*(?:AS\s+\w+\s*)?FROM\b", self.text or "", re.I) else "aggregate"
150
+ return "page" if info["limit"] else "rows"
151
+
152
+ def record(self) -> dict:
153
+ r = {"key": self.key, "site_ids": self.site_ids[:5], "sql_from": self.sql_from, "located": self.located, "engine": self.engine}
154
+ if self.hash:
155
+ r["hash"] = self.hash
156
+ if self.file:
157
+ r.update(file=self.file, line=self.line, symbol=self.symbol)
158
+ r["role"] = self.role()
159
+ if self.measured:
160
+ r["measured"] = dict(self.measured)
161
+ return r
162
+
163
+
164
+ def _measured(q: dict, total: int, window) -> dict:
165
+ keep = {"executions": int(q.get("executions") or 0), "read_bytes": int(q.get("read_bytes") or 0),
166
+ "share_of_read_bytes": round(int(q.get("read_bytes") or 0) / total, 6) if total else None, "window_hours": window}
167
+ for k in ("bytes_read_per_run", "rows_read_per_run", "rows_returned_per_run", "no_result_share"):
168
+ if q.get(k) is not None:
169
+ keep[k] = q[k]
170
+ return keep
171
+
172
+
173
+ def _agents(db_dir: Path | None) -> dict[tuple[str, str], tuple]:
174
+ """(engine, shape hash) -> the client drivers that sent it, when the pull recorded them (db_workload.json)."""
175
+ if db_dir is None:
176
+ return {}
177
+ p = Path(db_dir) / "db_workload.json"
178
+ if not p.exists():
179
+ return {}
180
+ try:
181
+ w = json.loads(p.read_text())
182
+ except (OSError, ValueError):
183
+ return {}
184
+ out = {}
185
+ for engine, conn in (w.get("connections") or {}).items():
186
+ for q in conn.get("queries") or []:
187
+ c = q.get("clients") or {}
188
+ if isinstance(c, dict) and c.get("agents"):
189
+ out[(engine, str(q.get("hash")))] = tuple(sorted(str(a).split(" ")[0] for a in c["agents"]))
190
+ return out
191
+
192
+
193
+ def units_of(inventory: dict, workloads: list, agents: dict | None = None) -> tuple[dict[str, Unit], dict[str, str]]:
194
+ """Every select statement as a unit: {key: unit}, and site id -> key."""
195
+ agents = agents or {}
196
+ units: dict[str, Unit] = {}
197
+ by_site: dict[str, str] = {}
198
+ site_shapes: dict[str, tuple] = {} # site id -> (workload, its shape hashes)
199
+ shape_sites: dict[tuple, list] = {}
200
+ for w in workloads:
201
+ for sid, row in w.sites.items():
202
+ site_shapes.setdefault(sid, (w, [str(h) for h in row.get("hashes") or []]))
203
+ for q in w.queries:
204
+ shape_sites[(w.engine, str(q.get("hash")))] = [i for i in q.get("site_ids") or [] if q.get("match") in ("exact", "template")]
205
+ sites = {str(s.get("id")): s for s in inventory.get("call_sites") or []}
206
+ for s in inventory.get("call_sites") or []:
207
+ if s.get("is_test") or s.get("statement") != "select" or not s.get("sql"):
208
+ continue
209
+ sid = str(s.get("id"))
210
+ got = site_shapes.get(sid)
211
+ one = got and len(got[1]) == 1 and shape_sites.get((got[0].engine, got[1][0])) == [sid]
212
+ key = f"shape:{got[0].engine}:{got[1][0]}" if one else f"site:{sid}"
213
+ u = units.setdefault(key, Unit(key))
214
+ u.site_ids.append(sid)
215
+ u.engine = s.get("engine") or u.engine
216
+ u.sql_from = "orm" if s.get("orm") else "code"
217
+ u.located = "site"
218
+ u.file, u.line, u.symbol = s.get("file") or "", int(s.get("line") or 0), s.get("symbol") or ""
219
+ u.text = s.get("sql") or ""
220
+ if got:
221
+ w, hashes = got
222
+ rows = [q for q in w.queries if str(q.get("hash")) in hashes]
223
+ if rows:
224
+ total = {"executions": sum(int(q.get("executions") or 0) for q in rows), "read_bytes": sum(int(q.get("read_bytes") or 0) for q in rows)}
225
+ u.measured = {**_measured(rows[0] if len(rows) == 1 else total, w.total_bytes, w.window_hours), "shapes": len(rows)}
226
+ if one:
227
+ u.hash = hashes[0]
228
+ u.agents = agents.get((w.engine, hashes[0]), ())
229
+ text = w.texts.get(hashes[0]) or ""
230
+ if "«" in u.text and text:
231
+ u.text = text # the code holds a template; production's statement is whole
232
+ by_site[sid] = key
233
+ for w in workloads:
234
+ for q in w.queries:
235
+ h = str(q.get("hash"))
236
+ key = f"shape:{w.engine}:{h}"
237
+ if key in units:
238
+ continue
239
+ # a place, even when the match is partial: `located` says how sure it is
240
+ sids = shape_sites.get((w.engine, h)) or [str(i) for i in q.get("site_ids") or []]
241
+ u = units.setdefault(key, Unit(key))
242
+ u.hash, u.engine, u.sql_from = h, w.engine, "query_log"
243
+ u.located = q.get("match") if q.get("match") in ("exact", "template", "tag", "part", "likely") else "none"
244
+ u.site_ids = list(sids)
245
+ u.text = w.texts.get(h) or ""
246
+ first = sites.get(sids[0]) if sids else None
247
+ if first:
248
+ u.file, u.line, u.symbol = first.get("file") or "", int(first.get("line") or 0), first.get("symbol") or ""
249
+ u.measured = {**_measured(q, w.total_bytes, w.window_hours), "shapes": 1}
250
+ u.agents = agents.get((w.engine, h), ())
251
+ return units, by_site
252
+
253
+
254
+ # --------------------------------------------------------------------------- detection
255
+
256
+ def _shared(members: list[Unit], table: str, cfg: dict) -> dict[str, dict] | None:
257
+ common: dict[str, dict] | None = None
258
+ for u in members:
259
+ p = u.predicates(table)
260
+ common = dict(p) if common is None else {k: v for k, v in common.items() if k in p}
261
+ if not common:
262
+ return None
263
+ if common is None or len(common) < cfg["min_shared_predicates"]:
264
+ return None
265
+ if cfg["require_equality"] and not any(p["equality"] and p.get("parameter", True) for p in common.values()):
266
+ return None # the tenant, the key: an equality to a value the caller passes, not only a literal of the code
267
+ if cfg["skip_key_lookups"] and all(p["column"] in ("id", "pk", "uuid") and p["equality"] for p in common.values()):
268
+ return None
269
+ return common
270
+
271
+
272
+ def _cluster(members: list[Unit], table: str, cfg: dict, least: int) -> list[tuple[list[Unit], dict]]:
273
+ """Greedy: the heaviest member first, then every member that keeps a qualifying shared filter."""
274
+ rest = sorted(members, key=lambda u: (-((u.measured or {}).get("read_bytes") or 0), u.key))
275
+ out = []
276
+ while len(rest) >= least:
277
+ group = [rest[0]]
278
+ shared = _shared(group, table, cfg)
279
+ if shared is None:
280
+ rest = rest[1:]
281
+ continue
282
+ for u in rest[1:]:
283
+ if u.file and any((u.file, u.line) == (x.file, x.line) for x in group):
284
+ continue # texts of one call site (a builder's branches) are one statement, not several
285
+ got = _shared(group + [u], table, cfg)
286
+ if got is not None:
287
+ group.append(u)
288
+ shared = got
289
+ if len(group) >= least:
290
+ out.append((group, shared))
291
+ rest = [u for u in rest if u not in group]
292
+ return out
293
+
294
+
295
+ def _code_sets(inventory: dict, units: dict[str, Unit], by_site: dict[str, str], cfg: dict,
296
+ unit_entries: dict[str, set]) -> list[tuple[str, str, list[Unit], bool]]:
297
+ """(source, place, members, traced) from the code: the same loop body, entry point, or function."""
298
+ loops: dict[tuple, set] = defaultdict(set)
299
+ entries: dict[tuple, set] = defaultdict(set)
300
+ functions: dict[tuple, set] = defaultdict(set)
301
+ guessed: set = set()
302
+ for s in inventory.get("call_sites") or []:
303
+ sid = str(s.get("id"))
304
+ key = by_site.get(sid)
305
+ if key is None:
306
+ continue
307
+ for lp in s.get("loop_context") or []:
308
+ if int(lp.get("hop") or 0) > cfg["max_loop_hop"]:
309
+ continue
310
+ place = ("loop", lp.get("file") or "", int(lp.get("line") or 0), lp.get("function") or "")
311
+ loops[place].add(key)
312
+ if lp.get("verified") is False or (isinstance(lp.get("driver"), dict) and lp["driver"].get("verified") is False):
313
+ guessed.add((place, key))
314
+ certain = s.get("origin_count_certain")
315
+ for o in s.get("origins") or []:
316
+ if o.get("kind") in (None, "test"):
317
+ continue
318
+ place = ("entry_point", o.get("kind") or "", o.get("name") or "", o.get("file") or "", int(o.get("line") or 0))
319
+ unit_entries[key].add(place) # every entry point, however deep: what tells two jobs apart
320
+ if o.get("hops") is not None and int(o.get("hops") or 0) > cfg["max_entry_point_hop"]:
321
+ continue
322
+ entries[place].add(key)
323
+ if o.get("verified") is False or (certain is not None and certain < int(s.get("origin_count") or 0)):
324
+ guessed.add((place, key))
325
+ if cfg["use_same_function"] and s.get("symbol"):
326
+ functions[("function", s.get("file") or "", s.get("symbol") or "")].add(key)
327
+ for place, keys in entries.items():
328
+ for k in keys:
329
+ unit_entries[k].add(place)
330
+ out = []
331
+ for source, sets in (("loop", loops), ("entry_point", entries), ("function", functions)):
332
+ for place, keys in sets.items():
333
+ members = [units[k] for k in sorted(keys)]
334
+ traced = not any((place, k) in guessed for k in keys)
335
+ out.append((source, place, members, traced))
336
+ return out
337
+
338
+
339
+ def _split_by_entry_points(members: list[Unit], entry_points: dict[str, set]) -> list[list[Unit]]:
340
+ """Shapes whose counts agree but whose code is reached from different entry points (two jobs that happen to run as
341
+ often) are not one cycle: the members are split into sets that share an entry point; a member whose entry points
342
+ are not known joins each set."""
343
+ known = [u for u in members if entry_points.get(u.key)]
344
+ unknown = [u for u in members if not entry_points.get(u.key)]
345
+ parts: list[tuple[set, list[Unit]]] = []
346
+ for u in known:
347
+ eps = set(entry_points[u.key])
348
+ joined = [p for p in parts if p[0] & eps]
349
+ merged_eps, merged = set(eps), [u]
350
+ for p in joined:
351
+ merged_eps |= p[0]
352
+ merged += p[1]
353
+ parts.remove(p)
354
+ parts.append((merged_eps, merged))
355
+ if not parts:
356
+ return [members]
357
+ return [p[1] + unknown for p in parts]
358
+
359
+
360
+ def _count_sets(units: dict[str, Unit], cfg: dict, entry_points: dict[str, set] | None = None) -> list[tuple[str, str, list[Unit], bool]]:
361
+ """Production shapes whose run counts agree (and that came from the same client, when the log says)."""
362
+ hot = [u for u in units.values() if u.hash and u.measured and u.measured["executions"] >= cfg["together_min_runs"]]
363
+ by_client: dict[tuple, list[Unit]] = defaultdict(list)
364
+ for u in hot:
365
+ by_client[(u.engine, u.agents if cfg["together_same_client"] else ())].append(u)
366
+ out = []
367
+ for (engine, client), us in by_client.items():
368
+ us.sort(key=lambda u: u.measured["executions"])
369
+ cur: list[Unit] = []
370
+ for u in us + [None]:
371
+ if u is not None and cur and u.measured["executions"] <= cur[0].measured["executions"] * (1 + cfg["together_tolerance"]) + cfg["together_slack_runs"]:
372
+ cur.append(u)
373
+ continue
374
+ if len(cur) >= 2:
375
+ for part in _split_by_entry_points(cur, entry_points or {}):
376
+ if len(part) >= 2:
377
+ out.append(("counts", ("counts", engine, cur[0].measured["executions"], cur[-1].measured["executions"]), part, True))
378
+ cur = [u] if u is not None else []
379
+ return out
380
+
381
+
382
+ TABLE_NAME = re.compile(r"^(?!.*__qp\d+__)[a-z_][\w$]*$") # not a run-time part standing for a name
383
+ LEAST = {"loop": "min_members_loop", "entry_point": "min_members_entry_point", "function": "min_members_function", "counts": "min_members_counts"}
384
+
385
+
386
+ def catalog_tables(db_dir) -> dict[str, set[str]] | None:
387
+ """engine -> table names of the pulled catalog, without their database; None without a catalog."""
388
+ if db_dir is None or not (Path(db_dir) / "db_catalog.json").exists():
389
+ return None
390
+ try:
391
+ cat = json.loads((Path(db_dir) / "db_catalog.json").read_text())
392
+ except (OSError, ValueError):
393
+ return None
394
+ out: dict[str, set[str]] = {}
395
+ for engine, c in (cat.get("connections") or {}).items():
396
+ out.setdefault(c.get("engine") or engine, set()).update(short(t.get("name")) for t in c.get("tables") or [] if t.get("name"))
397
+ return out
398
+
399
+
400
+ def detect(inventory: dict, workloads: list | None = None, settings: dict | None = None, db_dir=None,
401
+ known_tables: dict[str, set] | None = None) -> dict:
402
+ """groups.json: every scan group, what each member loads, and the bytes of all groups counted once.
403
+
404
+ `known_tables`: engine -> the real catalog's tables. With it, a table the catalog of that engine does not hold (a temporary table the job creates) is
405
+ not a shared scan: reading it twice is cheap and the catalog can not say how big it is."""
406
+ cfg = settings_of(settings)
407
+ if known_tables is None:
408
+ known_tables = catalog_tables(db_dir) or {}
409
+ workloads = workloads or []
410
+ units, by_site = units_of(inventory, workloads, _agents(db_dir))
411
+ found: dict[tuple, dict] = {}
412
+ set_aside: dict[str, int] = defaultdict(int)
413
+ unit_entries: dict[str, set] = defaultdict(set)
414
+ code_sets = _code_sets(inventory, units, by_site, cfg, unit_entries)
415
+ for source, place, members, traced in code_sets + _count_sets(units, cfg, unit_entries):
416
+ least = cfg[LEAST[source]]
417
+ if len(members) < least:
418
+ continue
419
+ per_table: dict[tuple, list[Unit]] = defaultdict(list)
420
+ for u in members:
421
+ if not u.info["parse_ok"]:
422
+ continue
423
+ if source in ("entry_point", "function") and cfg["entry_point_aggregates_only"] and not u.info["aggregate"]:
424
+ continue
425
+ if source == "loop" and cfg["loop_aggregates_only"] and not u.info["aggregate"]:
426
+ continue
427
+ for t in u.tables():
428
+ if not TABLE_NAME.match(t):
429
+ continue
430
+ known = known_tables.get(u.engine)
431
+ if known is not None and t not in known:
432
+ set_aside["table_not_in_catalog"] += 1
433
+ continue
434
+ per_table[(u.engine, t)].append(u) # a ClickHouse and a PostgreSQL branch of one route are alternatives
435
+ for (_, table), us in per_table.items():
436
+ if source == "entry_point" and len(us) > cfg["max_entry_point_selects"]:
437
+ set_aside["entry_point_reaches_many"] += 1
438
+ continue
439
+ for group, shared in _cluster(us, table, cfg, least):
440
+ if source == "entry_point" and len({(u.file, u.symbol) for u in group}) > cfg["max_entry_point_functions"]:
441
+ set_aside["entry_point_dispatches"] += 1
442
+ continue
443
+ # the same members over several tables (a join, a CTE per table) are one group: the first table is the
444
+ # one with the most shared predicates, the others are listed
445
+ key = ("scan", tuple(sorted(u.key for u in group)))
446
+ g = found.setdefault(key, {"table": table, "members": group, "shared": shared, "run_together": [], "also_tables": []})
447
+ if table != g["table"]:
448
+ if len(shared) > len(g["shared"]):
449
+ g["also_tables"].append(g["table"])
450
+ g["table"], g["shared"] = table, shared
451
+ elif table not in g["also_tables"]:
452
+ g["also_tables"].append(table)
453
+ entry = {"source": source, **_place(place),
454
+ "confidence": "counts_agree" if source == "counts" else "code_path_traced" if traced else "code_path_guessed"}
455
+ if entry not in g["run_together"]:
456
+ g["run_together"].append(entry)
457
+ # a CTE or a subquery read twice in one statement: a group of one
458
+ for u in units.values():
459
+ if not u.text or not u.info["parse_ok"]:
460
+ continue
461
+ # an engine that evaluates a CTE per reference; elsewhere only one written NOT MATERIALIZED is read again
462
+ per_reference = (u.engine or u.info["dialect"]) in cfg["cte_engines"]
463
+ known = known_tables.get(u.engine)
464
+ real = (lambda ts, known=known: [t for t in ts if TABLE_NAME.match(t) and (known is None or t in known)])
465
+ reads = [(name, {**r, "tables": real(r["tables"])}) for name, r in u.info["cte_reads"].items() if r["reads"] >= cfg["cte_min_refs"]
466
+ and real(r["tables"]) and (per_reference or r.get("materialized") is False)]
467
+ subs = [{**r, "tables": real(r["tables"])} for r in u.info["repeated_subqueries"] if r["reads"] >= cfg["cte_min_refs"] and real(r["tables"])]
468
+ for name, r in reads:
469
+ key = (r["tables"][0], (u.key,), "cte", name)
470
+ found[key] = {"table": r["tables"][0], "members": [u], "shared": {}, "kind": "repeated_read",
471
+ "repeated": {"what": "cte", "name": name, "reads": r["reads"], "tables": r["tables"]},
472
+ "run_together": [{"source": "one_statement", "confidence": "one_statement"}]}
473
+ for i, r in enumerate(subs):
474
+ key = (r["tables"][0], (u.key,), "subquery", i)
475
+ found[key] = {"table": r["tables"][0], "members": [u], "shared": {}, "kind": "repeated_read",
476
+ "repeated": {"what": "subquery", "reads": r["reads"], "tables": r["tables"]},
477
+ "run_together": [{"source": "one_statement", "confidence": "one_statement"}]}
478
+ groups = [_group_out(g, cfg) for g in found.values()]
479
+ groups.sort(key=lambda g: (-(g["measured"] or {}).get("read_bytes", 0), CONFIDENCE.index(g["confidence"]), -g["member_count"], g["fingerprint"]))
480
+ groups = groups[: cfg["max_groups"]]
481
+ seen_fp: dict[str, int] = defaultdict(int)
482
+ for g in groups:
483
+ seen_fp[g["fingerprint"]] += 1
484
+ if seen_fp[g["fingerprint"]] > 1:
485
+ g["fingerprint"] += f"~{seen_fp[g['fingerprint']]}"
486
+ # each shape once: a member of several groups is flagged, and the total counts it once
487
+ owners: dict[str, list[str]] = defaultdict(list)
488
+ for i, g in enumerate(groups, 1):
489
+ g["id"] = f"G-{i:03d}"
490
+ for m in g["members"]:
491
+ owners[m["key"]].append(g["id"])
492
+ for g in groups:
493
+ for m in g["members"]:
494
+ others = [x for x in owners[m["key"]] if x != g["id"]]
495
+ if others:
496
+ m["shared_with"] = others[:10]
497
+ if any(m.get("shared_with") for m in g["members"]):
498
+ g["notes"].append("members_shared_with_other_groups")
499
+ labels = [lab for fn in CLASSIFIERS for lab in [fn(g, g["members"])] if lab]
500
+ if labels:
501
+ g["labels"] = labels
502
+ once: dict[str, dict] = {}
503
+ for g in groups:
504
+ for m in g["members"]:
505
+ if m.get("measured"):
506
+ once.setdefault(m["key"], m["measured"])
507
+ totals = [w.total_bytes for w in workloads if w.total_bytes]
508
+ read_once = sum(int(m.get("read_bytes") or 0) for m in once.values())
509
+ summary = {"groups": len(groups), "by_kind": {k: sum(1 for g in groups if g["kind"] == k) for k in KINDS if any(g["kind"] == k for g in groups)},
510
+ "by_confidence": {c: sum(1 for g in groups if g["confidence"] == c) for c in CONFIDENCE if any(g["confidence"] == c for g in groups)},
511
+ "by_source": {s: sum(1 for g in groups if any(r["source"] == s for r in g["run_together"])) for s in SOURCES
512
+ if any(r["source"] == s for g in groups for r in g["run_together"])},
513
+ "measured_groups": sum(1 for g in groups if g["measured"]), "members_measured": len(once),
514
+ "read_bytes_once": read_once, "share_of_read_bytes_once": round(read_once / sum(totals), 6) if totals else None,
515
+ "set_aside": dict(set_aside)}
516
+ return {"schema_version": SCHEMA_VERSION, "generated_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
517
+ "settings": cfg, "window_hours": next((w.window_hours for w in workloads if w.window_hours), None),
518
+ "summary": summary, "groups": groups}
519
+
520
+
521
+ def _place(place: tuple) -> dict:
522
+ kind = place[0]
523
+ if kind == "loop":
524
+ return {"file": place[1], "line": place[2], "function": place[3]}
525
+ if kind == "entry_point":
526
+ return {"kind": place[1], "name": place[2], "file": place[3], "line": place[4]}
527
+ if kind == "function":
528
+ return {"file": place[1], "function": place[2]}
529
+ if kind == "counts":
530
+ return {"runs_min": place[2], "runs_max": place[3]}
531
+ return {}
532
+
533
+
534
+ def _group_out(g: dict, cfg: dict) -> dict:
535
+ members = [u.record() for u in g["members"]]
536
+ kind = g.get("kind") or "shared_scan"
537
+ best = min((r["confidence"] for r in g["run_together"]), key=CONFIDENCE.index)
538
+ identity = sorted(",".join(sorted(m["site_ids"])) or m.get("hash") or m["key"] for m in members)
539
+ extra = [g["repeated"]["what"], g["repeated"].get("name", "")] if kind == "repeated_read" else []
540
+ measured = None
541
+ rows = [m["measured"] for m in members if m.get("measured")]
542
+ if rows:
543
+ read = sum(int(r.get("read_bytes") or 0) for r in rows)
544
+ shares = [r.get("share_of_read_bytes") for r in rows if r.get("share_of_read_bytes") is not None]
545
+ measured = {"members_measured": len(rows), "executions": sum(int(r.get("executions") or 0) for r in rows), "read_bytes": read,
546
+ "share_of_read_bytes": round(sum(shares), 6) if shares else None, "window_hours": rows[0].get("window_hours")}
547
+ shared = sorted(g["shared"].values(), key=lambda p: (not p["equality"], p["column"], p["text"]))
548
+ notes = []
549
+ if any(m["sql_from"] == "query_log" and m["located"] == "none" for m in members):
550
+ notes.append("member_not_located_in_code")
551
+ if len({m["engine"] for m in members if m["engine"]}) > 1:
552
+ notes.append("members_on_several_engines")
553
+ return {"fingerprint": _fp(kind, g["table"], *identity, *extra), "kind": kind, "table": g["table"],
554
+ "engine": next((m["engine"] for m in members if m["engine"]), ""),
555
+ "shared_filter": [{"column": p["column"], "op": p["op"], "text": p["text"], "equality": p["equality"]} for p in shared],
556
+ **({"repeated": g["repeated"]} if kind == "repeated_read" else {}),
557
+ **({"also_tables": sorted(set(g["also_tables"]) - {g["table"]})} if g.get("also_tables") else {}),
558
+ "members": members[: cfg["max_members"]], "member_count": len(members),
559
+ "roles": {r: sum(1 for m in members if m["role"] == r) for r in ROLES if any(m["role"] == r for m in members)},
560
+ "run_together": g["run_together"], "confidence": best, "measured": measured, "notes": notes}
561
+
562
+
563
+ # --------------------------------------------------------------------------- files
564
+
565
+ def stage(out_dir: Path, inventory: dict, settings: dict | None = None) -> dict:
566
+ """Detect from the out dir's inventory and pulled workload, and write groups.json (keeping earlier variants and
567
+ results of groups whose fingerprint is unchanged)."""
568
+ from . import patterns
569
+ db_dir = out_dir if (out_dir / "db_match.json").exists() else out_dir.parent
570
+ data = detect(inventory, patterns.workloads_in(db_dir), settings, db_dir=db_dir)
571
+ path = out_dir / FILE
572
+ if path.exists():
573
+ try:
574
+ old = {g["fingerprint"]: g for g in json.loads(path.read_text()).get("groups") or []}
575
+ except (OSError, ValueError):
576
+ old = {}
577
+ for g in data["groups"]:
578
+ prev = old.get(g["fingerprint"])
579
+ if prev:
580
+ for k in ("agent_variants", "agent_asked"):
581
+ if prev.get(k) is not None:
582
+ g[k] = prev[k]
583
+ path.write_text(json.dumps(data, indent=1, ensure_ascii=False))
584
+ return data
585
+
586
+
587
+ def load(out_dir: Path) -> dict | None:
588
+ p = Path(out_dir) / FILE
589
+ if not p.exists():
590
+ return None
591
+ try:
592
+ return json.loads(p.read_text())
593
+ except (OSError, ValueError):
594
+ return None