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
@@ -0,0 +1,531 @@
1
+ """Matching the real workload to the repo's call sites. Runs locally: no database, no agent.
2
+
3
+ Both sides are reduced to a *shape*: the statement with every literal and every driver parameter
4
+ turned into `?`, lists collapsed, case, quoting, whitespace and database prefixes removed. The server
5
+ already did the first step for its side (`normalizeQuery`, pg_stat_statements); the repo side has
6
+ `{name:Type}`, `%(name)s`, `$1`, `?` and run-time fragments marked «...».
7
+
8
+ Three grades, reported separately because they are not equally sure:
9
+
10
+ exact the two shapes are identical. Also exact, with `how` saying which: `reformatted`, when they differ
11
+ only in what the server changes when it logs a statement it parsed (parentheses around every
12
+ condition, AS before an alias, _CAST around a typed parameter, toDateTime around a bound time);
13
+ `identifier`, when the server masked a long quoted identifier as `?` and everything else is equal
14
+ template the call site has run-time fragments («...» from discover, `{{...}}` in a .sql template); its
15
+ shape, with each fragment as a wildcard, matches the whole real statement, and the fixed text is
16
+ most of it
17
+ part the call site's whole SQL is one piece of a longer real statement (a .sql fragment that code
18
+ joins with others at run time): the place is known, the share of the cost is not
19
+ likely same tables and nearly the same tokens (Jaccard >= 0.85): a guess, never used as proof
20
+
21
+ `exact` and `template` are sure and are what ranking and coverage use. `part` and `likely` are reported.
22
+
23
+ A real statement can match several call sites (the same SQL is sent from several places) and a call
24
+ site several real statements (one template, many run-time variants).
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ from datetime import datetime
30
+
31
+ import re
32
+ from collections import defaultdict
33
+
34
+ from .ratios import classify, ratios
35
+
36
+ FRAGMENT = "«»" # «» stands for one run-time fragment in a shape
37
+ IDENT = "¤" # stands for an identifier the server masked (normalizeQuery turns a long quoted name into `?`)
38
+ TEMP_TABLE = re.compile(r"_tmp_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", re.I)
39
+ MIN_PART = 200 # characters a call site's SQL needs before finding it inside a real statement means anything
40
+ GRADES = ("exact", "template", "tag", "part", "likely")
41
+ SURE = ("exact", "template", "tag")
42
+ TAG_LINE_SLACK = 30 # a `codecop:<file>:<line>` tag names the line of the call; a call site of that file this many lines above still counts
43
+ COMMENT = re.compile(r"/\*.*?\*/|--[^\n]*", re.S)
44
+ STRING = re.compile(r"'(?:[^'\\]|\\.|'')*'")
45
+ TAIL = re.compile(r"\s+(?:format\s+\w+|settings\s+[\w\s=,.'?¤]+)\s*$", re.I) # ¤: a setting name the server masked
46
+ TOKEN = re.compile(r"[a-z_][\w.]*|\?|«»|[^\s\w]")
47
+ MIN_FIXED = 40 # characters of fixed text a template needs before its match means anything
48
+ MIN_FIXED_SHARE = 0.5
49
+ LIKELY = 0.85
50
+
51
+
52
+ def shape(sql: str, tables: list[str] | None = None) -> str:
53
+ """The statement with everything that varies between executions removed."""
54
+ s = COMMENT.sub(" ", sql or "")
55
+ s = re.sub(r"«[^»]*»|…", FRAGMENT, s) # «expr» and … -> one fragment marker
56
+ s = re.sub(r"\{\{.*?\}\}|\{%.*?%\}", FRAGMENT, s, flags=re.S) # {{.Name}}, {% if %}: a template action in a .sql file
57
+ s = TEMP_TABLE.sub("_tmp", s) # an external-data temp table has a new name every run
58
+ s = STRING.sub("?", s)
59
+ s = re.sub(r"`\?`|\"\?\"", IDENT, s) # an identifier the server masked
60
+ s = re.sub(r"\{\w+\s*:[^{}]*\}", "?", s) # {name:Type}
61
+ s = re.sub(r"%\(\w+\)s|%s", "?", s) # %(name)s, %s
62
+ s = re.sub(r"\$\d+", "?", s) # $1
63
+ s = re.sub(r"(?<![:\w]):[A-Za-z_]\w*", "?", s) # :name, not ::cast
64
+ s = re.sub(r"(?<![\w.?])-?\d+(?:\.\d+)?(?:e[+-]?\d+)?(?![\w.])", "?", s, flags=re.I)
65
+ s = s.replace("`", "").replace('"', "").lower()
66
+ for _ in range(3):
67
+ s = TAIL.sub("", s.rstrip().rstrip(";"))
68
+ for name in tables or []: # db.table -> table
69
+ if "." in name and not TEMP_TABLE.search(name):
70
+ s = s.replace(name.lower().replace("`", ""), name.rsplit(".", 1)[-1].lower())
71
+ s = re.sub(r"\bdefault\.|\bpublic\.", "", s)
72
+ s = re.sub(r"\?\s*\.\.", "?", s) # normalizeQuery's `?..`
73
+ s = re.sub(r"\s+", " ", s)
74
+ s = re.sub(r"\s*([(),=<>!+\-*/|\[\]])\s*", r"\1", s)
75
+ prev = None
76
+ while prev != s: # (?,?,?) and (?) -> ?
77
+ prev = s
78
+ s = re.sub(r"\?(?:,\?)+", "?", s)
79
+ s = re.sub(r"\(\?\)", "?", s)
80
+ s = re.sub(r"\[\?\]", "?", s)
81
+ s = re.sub(r"\blimit \?(?:,\?| offset \?)?", "limit ?", s)
82
+ s = re.sub(r"\s*\?\s*", "?", s) # `in (?)` and `in ?` are the same
83
+ s = re.sub(r"\s*" + FRAGMENT + r"\s*", FRAGMENT, s)
84
+ return s.strip()
85
+
86
+
87
+ def loose(shape_text: str) -> str:
88
+ """A shape without what the server changes when it logs a statement from its parsed form rather than as sent:
89
+ parentheses, AS, ASC, _CAST around a typed parameter, and toDateTime/toDate around a bound time value."""
90
+ s = shape_text.replace("_cast?", "?")
91
+ s = re.sub(r"\bto(?:datetime(?:64)?|date(?:32)?)\?", "?", s)
92
+ s = s.replace("!=", "<>")
93
+ s = re.sub(r"[()]", " ", s)
94
+ s = re.sub(r"\bas\b|\basc\b", " ", s) # the parsed form writes AS before every alias and ASC after every sort key
95
+ return re.sub(r"\s+", "", s)
96
+
97
+
98
+ def short_tables(names: list[str]) -> frozenset[str]:
99
+ """Table names without database, quotes or case. Temp tables and names only known at run time are left out."""
100
+ return frozenset(n.rsplit(".", 1)[-1].lower().strip("`\"") for n in names or []
101
+ if n and not n.startswith("?") and "«" not in n and "…" not in n and "_tmp_" not in n)
102
+
103
+
104
+ def tables_in(shape_text: str) -> frozenset[str]:
105
+ """Table names after FROM and JOIN in a shape (the real side has no parsed table list for Postgres)."""
106
+ return frozenset(m.rsplit(".", 1)[-1] for m in re.findall(r"\b(?:from|join)\s*([a-z_][\w.]*)", shape_text))
107
+
108
+
109
+ def _template(shape_text: str) -> tuple[re.Pattern, int] | None:
110
+ parts = shape_text.split(FRAGMENT)
111
+ fixed = sum(len(p) for p in parts)
112
+ if len(parts) < 2 or fixed < MIN_FIXED:
113
+ return None
114
+ return re.compile(".*?".join(re.escape(p) for p in parts), re.S), fixed
115
+
116
+
117
+ def _tokens(shape_text: str) -> frozenset[str]:
118
+ return frozenset(TOKEN.findall(shape_text))
119
+
120
+
121
+ def sites_for_tag(tag: str, sites: list[dict]) -> list[dict]:
122
+ """The call sites a call-site tag names (docs/query-tags.md): `<path>:<line>` (the file, or a path that ends with it, and
123
+ the call site on that line or the nearest one above it within TAG_LINE_SLACK lines), or `<function>` (the call site's
124
+ symbol, or its last part: `Repo.Find` is named by `Find`). Empty when the tag names nothing in this inventory."""
125
+ tag = (tag or "").strip()
126
+ m = re.fullmatch(r"(.+?):(\d+)", tag)
127
+ if m:
128
+ path, line = m.group(1).lstrip("./"), int(m.group(2))
129
+ in_file = [s for s in sites if s.get("file") == path or str(s.get("file", "")).endswith("/" + path)]
130
+ exact = [s for s in in_file if s.get("line") == line or (s.get("line", 0) <= line <= (s.get("end_line") or s.get("line", 0)))]
131
+ if exact:
132
+ return exact
133
+ above = [s for s in in_file if 0 <= line - int(s.get("line") or 0) <= TAG_LINE_SLACK]
134
+ return [max(above, key=lambda s: s["line"])] if above else []
135
+ return [s for s in sites if s.get("symbol") and (s["symbol"] == tag or s["symbol"].rsplit(".", 1)[-1] == tag)]
136
+
137
+
138
+
139
+ def covered_hours(workload: dict):
140
+ """The hours the query log really holds inside the requested window.
141
+
142
+ A server keeps its log for a limited time, so a 24 h request can return 10 h of statements.
143
+ Every per-day figure is scaled by this number, so it must be the span that was there, not the
144
+ span that was asked for. Older pulled files recorded only the request; they are corrected here."""
145
+ asked = workload.get("window_hours")
146
+ first, last = workload.get("first_seen"), workload.get("last_seen")
147
+ if not asked or not first or not last:
148
+ return asked
149
+ try:
150
+ span = (datetime.fromisoformat(str(last)[:19]) - datetime.fromisoformat(str(first)[:19])).total_seconds() / 3600
151
+ except ValueError:
152
+ return asked
153
+ if span < 0:
154
+ return asked
155
+ # under an hour of log says too little to scale to a day: call it an hour, the smallest honest unit
156
+ return asked if span >= asked * 0.95 else max(round(span, 2), 1.0)
157
+
158
+ SPREAD_KEYS = ("spread", "no_result_share", "no_read_share", "selected_parts_per_run", "selected_marks_per_run",
159
+ # added with the pruning, empty-run, repeat and column facts; absent when the pull did not have them
160
+ "selected_parts_total_per_run", "selected_marks_total_per_run", "selected_ranges_per_run",
161
+ "empty_run_bytes", "empty_run_rows", "result_run_bytes",
162
+ "runs_per_statement", "active_minutes", "repeats_window_hours",
163
+ "columns_read", "projections_used", "projection_run_share")
164
+ NAMES_PER_SITE = 200 # column and projection names a site carries (the pull caps them per shape already)
165
+
166
+
167
+ def spread_fields(qs: list[dict], executions: int) -> dict:
168
+ """What a pull knows about the runs of these shapes beyond their mean. Empty for a pull that did not ask.
169
+
170
+ `spread` {rows_read, bytes_read, rows_returned: [median, 90th, 99th percentile], method, shapes, of_executions}:
171
+ quantiles can not be added up over shapes, so with several shapes they are those of the shape that read the most,
172
+ and `of_executions` says what share of the runs that shape is. The shares of runs that returned or read nothing
173
+ are counts, so they are exact over all the shapes. Parts and marks selected are averages weighted by runs."""
174
+ out: dict = {}
175
+ known = [q for q in qs if isinstance(q.get("spread"), dict)]
176
+ if known and executions:
177
+ lead = max(known, key=lambda q: (q.get("read_bytes") or 0, q.get("executions") or 0))
178
+ sp = lead["spread"]
179
+ out["spread"] = {"rows_read": list(sp["read_rows"]), "bytes_read": list(sp["read_bytes"]), "rows_returned": list(sp["result_rows"]),
180
+ "method": sp.get("method", ""), "shapes": len(qs), "of_executions": round(min(lead["executions"] / executions, 1.0), 4)}
181
+ if len(known) == len(qs):
182
+ out["no_result_share"] = round(min(sum(int(q["spread"].get("no_result_runs") or 0) for q in qs) / executions, 1.0), 4)
183
+ out["no_read_share"] = round(min(sum(int(q["spread"].get("no_read_runs") or 0) for q in qs) / executions, 1.0), 4)
184
+ # measured: the bytes and rows the runs that returned nothing read (sums, so they add up over shapes)
185
+ if all("no_result_read_bytes" in q["spread"] for q in qs):
186
+ out["empty_run_bytes"] = sum(int(q["spread"]["no_result_read_bytes"] or 0) for q in qs)
187
+ out["empty_run_rows"] = sum(int(q["spread"].get("no_result_read_rows") or 0) for q in qs)
188
+ out["result_run_bytes"] = sum(int(q["spread"].get("result_read_bytes") or 0) for q in qs)
189
+ chosen = [q for q in qs if isinstance(q.get("selected"), dict) and q.get("executions")]
190
+ if chosen:
191
+ runs = sum(q["executions"] for q in chosen)
192
+ out["selected_parts_per_run"] = round(sum(q["selected"]["parts_per_run"] * q["executions"] for q in chosen) / runs, 2)
193
+ out["selected_marks_per_run"] = round(sum(q["selected"]["marks_per_run"] * q["executions"] for q in chosen) / runs, 2)
194
+ for key, field in (("selected_parts_total_per_run", "parts_total_per_run"), ("selected_marks_total_per_run", "marks_total_per_run"),
195
+ ("selected_ranges_per_run", "ranges_per_run")):
196
+ if all(q["selected"].get(field) is not None for q in chosen): # null: the server does not count it
197
+ out[key] = round(sum(q["selected"][field] * q["executions"] for q in chosen) / runs, 2)
198
+ rep = [q["repeats"] for q in qs if isinstance(q.get("repeats"), dict)]
199
+ if rep and len(rep) == len(qs) and sum(r.get("statements") or 0 for r in rep):
200
+ # distinct statements of different shapes are different statements, so they add up; active minutes do not (two shapes
201
+ # can share a minute): the busiest shape's
202
+ out["runs_per_statement"] = round(sum(r.get("runs") or 0 for r in rep) / sum(r.get("statements") or 0 for r in rep), 2)
203
+ out["active_minutes"] = max(int(r.get("minutes") or 0) for r in rep)
204
+ cols = [q["columns"] for q in qs if isinstance(q.get("columns"), dict)]
205
+ if cols:
206
+ out["columns_read"] = sorted({c for x in cols for c in x.get("columns") or []})[:NAMES_PER_SITE]
207
+ out["projections_used"] = sorted({p for x in cols for p in x.get("projections") or []})[:NAMES_PER_SITE]
208
+ runs = sum(int(x.get("runs") or 0) for x in cols)
209
+ if runs:
210
+ out["projection_run_share"] = round(min(sum(int(x.get("projection_runs") or 0) for x in cols) / runs, 1.0), 4)
211
+ return out
212
+
213
+
214
+ # what resource_fields adds to a site or query row (carried to observed candidates' production, observed.py)
215
+ RESOURCE_KEYS = ("max_memory", "avg_memory", "max_ms", "temp_blocks", "total_ms", "result_bytes", "resources")
216
+ RESOURCE_CONTEXT = ("resources", "memory", "failures", "pressure", "capacity", "facts", "settings", "temp")
217
+
218
+
219
+ def resource_fields(qs: list[dict], executions: int) -> dict:
220
+ """What a pull knows about the CPU, memory, time and spill of these shapes, for a call site.
221
+
222
+ Carried from every pull (they were dropped here before): `max_memory` (the most of any shape) and `avg_memory` (mean
223
+ per run, weighted by runs) on ClickHouse; `max_ms` and `temp_blocks` (summed) on PostgreSQL. Under `resources`, from a
224
+ pull with the resource statements: sums add up over shapes (CPU, memory held, spill, failures, waits), quantiles do not
225
+ (those of the shape that read the most, as `spread`), threads are weighted by runs. Absent: not in the pull."""
226
+ out: dict = {}
227
+ if qs and all(q.get("max_memory") is not None for q in qs):
228
+ out["max_memory"] = max(int(q["max_memory"]) for q in qs)
229
+ if executions and all(q.get("avg_memory") is not None for q in qs):
230
+ out["avg_memory"] = int(sum(float(q["avg_memory"]) * int(q.get("executions") or 0) for q in qs) / executions)
231
+ if qs and any(q.get("max_ms") is not None for q in qs):
232
+ out["max_ms"] = max(float(q.get("max_ms") or 0) for q in qs)
233
+ if qs and all(q.get("result_bytes") is not None for q in qs):
234
+ out["result_bytes"] = sum(int(q["result_bytes"]) for q in qs) # ClickHouse: bytes of the results sent
235
+ if qs and any(q.get("temp_blocks") is not None for q in qs):
236
+ out["temp_blocks"] = sum(int(q.get("temp_blocks") or 0) for q in qs)
237
+ lead = max(qs, key=lambda q: (q.get("read_bytes") or 0, q.get("executions") or 0)) if qs else {}
238
+ res: dict = {}
239
+ cpu = [q["cpu"] for q in qs if isinstance(q.get("cpu"), dict)]
240
+ if cpu and len(cpu) == len(qs):
241
+ c = {"user_us": sum(int(x.get("user_us") or 0) for x in cpu), "system_us": sum(int(x.get("system_us") or 0) for x in cpu),
242
+ "counted": all(x.get("counted") for x in cpu), "source": cpu[0].get("source") or "profile_events"}
243
+ if all(x.get("runs") is not None for x in cpu):
244
+ c["runs"] = sum(int(x["runs"]) for x in cpu)
245
+ lc = lead.get("cpu") or {}
246
+ for k in ("q50_us", "q95_us"):
247
+ if lc.get(k) is not None:
248
+ c[k] = int(lc[k])
249
+ if all(x.get("max_us") is not None for x in cpu):
250
+ c["max_us"] = max(int(x["max_us"]) for x in cpu)
251
+ for k in ("os_cpu_us", "cpu_wait_us", "io_wait_us"):
252
+ if all(x.get(k) is not None for x in cpu):
253
+ c[k] = sum(int(x[k]) for x in cpu)
254
+ res["cpu"] = c
255
+ mem = [q["memory"] for q in qs if isinstance(q.get("memory"), dict)]
256
+ if mem and len(mem) == len(qs):
257
+ lm = lead.get("memory") or {}
258
+ res["memory"] = {**{k: int(lm[k]) for k in ("q50", "q95", "q99") if lm.get(k) is not None},
259
+ "max": max(int(x.get("max") or 0) for x in mem), "byte_ms": sum(float(x.get("byte_ms") or 0) for x in mem),
260
+ "of_executions": round(min(int(lead.get("executions") or 0) / executions, 1.0), 4) if executions else None}
261
+ dur = [q["duration"] for q in qs if isinstance(q.get("duration"), dict)]
262
+ if dur and len(dur) == len(qs):
263
+ ld = lead.get("duration") or {}
264
+ res["duration"] = {**{k: ld[k] for k in ("q50", "q95") if ld.get(k) is not None}, "max": max(float(x.get("max") or 0) for x in dur)}
265
+ th = [(q["threads"], int(q.get("executions") or 0)) for q in qs if isinstance(q.get("threads"), dict)]
266
+ if th and len(th) == len(qs) and sum(n for _, n in th):
267
+ res["threads"] = {"avg": round(sum(float(t.get("avg") or 0) * n for t, n in th) / sum(n for _, n in th), 2),
268
+ "max": max(int(t.get("max") or 0) for t, _ in th), "kind": th[0][0].get("kind", "")}
269
+ for key, fields in (("spill", ("runs", "bytes")), ("failures", ("runs", "memory_limit", "timeout"))):
270
+ got = [q[key] for q in qs if isinstance(q.get(key), dict)]
271
+ if got and (key == "failures" or len(got) == len(qs)): # a shape with no failed run has no failures row
272
+ res[key] = {f: sum(int(x.get(f) or 0) for x in got) for f in fields}
273
+ for key in ("disk_read_bytes", "network_send_bytes", "plan_ms", "read_wait_ms", "write_wait_ms", "busy_ms", "temp_bytes", "wal_bytes",
274
+ "major_faults"):
275
+ if qs and all(q.get(key) is not None for q in qs):
276
+ res[key] = sum(q[key] for q in qs)
277
+ if res:
278
+ out["resources"] = res
279
+ return out
280
+
281
+
282
+ def with_repeat_window(fields: dict, workload: dict) -> dict:
283
+ """The hours the repeat counts are over, beside them (it can be shorter than the window: the statement reads every text)."""
284
+ hours = (workload.get("repeats") or {}).get("window_hours")
285
+ return {**fields, "repeats_window_hours": hours} if "runs_per_statement" in fields and hours else fields
286
+
287
+
288
+ def match(inventory: dict, workload: dict, *, engine: str | None = None, include_tests: bool = False) -> dict:
289
+ """Give every call site its real executions and read volume, and say which real statements match nothing."""
290
+ engine = engine or workload.get("engine", "")
291
+ hours = covered_hours(workload)
292
+ queries = [q for q in workload.get("queries") or [] if q.get("text")]
293
+ real = []
294
+ for q in queries:
295
+ text = shape(q["text"], q.get("tables"))
296
+ real.append({"q": q, "shape": text, "loose": loose(text), "tables": short_tables(q.get("tables")) or tables_in(text), "tokens": None})
297
+ by_shape: dict[str, list[dict]] = defaultdict(list)
298
+ by_loose: dict[str, list[dict]] = defaultdict(list)
299
+ for r in real:
300
+ by_shape[r["shape"]].append(r)
301
+ by_loose[r["loose"]].append(r)
302
+
303
+ sites = [c for c in inventory.get("call_sites") or [] if c.get("sql") and (include_tests or not c.get("is_test"))
304
+ and c.get("statement") in ("select", "insert", "update", "delete", "other", None)
305
+ and (not c.get("engine") or c.get("engine") == engine)]
306
+ matched: dict[str, dict] = {} # site id -> {"grade", "hashes"}
307
+ hit: dict[str, dict] = {} # hash -> {"grade", "sites", "how"}
308
+ grade_rank = {g: i for i, g in enumerate(GRADES)}
309
+
310
+ def link(site: dict, r: dict, grade: str, how: str = "") -> None:
311
+ m = matched.setdefault(site["id"], {"grade": grade, "hashes": []})
312
+ if grade_rank[grade] < grade_rank[m["grade"]]:
313
+ m["grade"], m["hashes"] = grade, []
314
+ if grade == m["grade"] and r["q"]["hash"] not in m["hashes"]:
315
+ m["hashes"].append(r["q"]["hash"])
316
+ h = hit.setdefault(r["q"]["hash"], {"grade": grade, "sites": [], "how": how})
317
+ if grade_rank[grade] < grade_rank[h["grade"]]:
318
+ h["grade"], h["sites"], h["how"] = grade, [], how
319
+ if grade == h["grade"] and site["id"] not in h["sites"]:
320
+ h["sites"].append(site["id"])
321
+
322
+ def sure(r: dict) -> bool:
323
+ return r["q"]["hash"] in hit and hit[r["q"]["hash"]]["grade"] in SURE
324
+
325
+ shaped = [(site, shape(site["sql"], site.get("tables"))) for site in sites]
326
+ whole: dict[str, list[dict]] = defaultdict(list) # loose shape -> sites, for sites without fragments
327
+ pending = []
328
+ for site, text in shaped:
329
+ if FRAGMENT in text:
330
+ continue
331
+ key = loose(text)
332
+ whole[key].append(site)
333
+ for r in by_shape.get(text, ()):
334
+ link(site, r, "exact", "as written")
335
+ if site["id"] not in matched:
336
+ for r in by_loose.get(key, ()):
337
+ link(site, r, "exact", "reformatted")
338
+ # a real statement in which the server masked an identifier: every other character has to agree
339
+ for r in real:
340
+ if IDENT in r["loose"] and not sure(r):
341
+ pattern = re.compile(r"[a-z_][\w.]*".join(re.escape(p) for p in r["loose"].split(IDENT)))
342
+ for key, found in whole.items():
343
+ if len(key) >= len(r["loose"]) and pattern.fullmatch(key):
344
+ for site in found:
345
+ link(site, r, "exact", "identifier")
346
+ for site, text in shaped:
347
+ if FRAGMENT not in text:
348
+ if site["id"] not in matched:
349
+ pending.append((site, text))
350
+ continue
351
+ tpl = _template(loose(text))
352
+ found = False
353
+ if tpl is not None:
354
+ pattern, fixed = tpl
355
+ wanted = short_tables(site.get("tables"))
356
+ for r in real:
357
+ if wanted and r["tables"] and not (wanted & r["tables"]):
358
+ continue
359
+ if fixed >= MIN_FIXED_SHARE * len(r["loose"]) and pattern.fullmatch(r["loose"]):
360
+ link(site, r, "template", "fragments")
361
+ found = True
362
+ if not found:
363
+ pending.append((site, text))
364
+ # tag: the application tagged the statement with its call site (log_comment `codecop:<tag>`, pulled by ch.workload.tags).
365
+ # It places a statement whose text matched nothing for sure; a tag that names nothing here is left as it is.
366
+ # A call site with no SQL text at all (an unresolved argument, a builder) can be placed this way, and only this way.
367
+ taggable = [c for c in inventory.get("call_sites") or [] if (include_tests or not c.get("is_test"))
368
+ and (not c.get("engine") or c.get("engine") == engine)]
369
+ for r in real:
370
+ if sure(r):
371
+ continue
372
+ for t in sorted(r["q"].get("tags") or [], key=lambda t: -int(t.get("executions") or 0)):
373
+ for site in sites_for_tag(t.get("tag", ""), taggable):
374
+ link(site, r, "tag", t["tag"])
375
+ # part: a call site whose whole SQL sits inside a longer real statement that nothing matched for sure
376
+ open_real = [r for r in real if not sure(r)]
377
+ for key, found in whole.items():
378
+ if len(key) < MIN_PART:
379
+ continue
380
+ for r in open_real:
381
+ if len(r["loose"]) > len(key) and key in r["loose"]:
382
+ for site in found:
383
+ if site["id"] not in matched or matched[site["id"]]["grade"] not in SURE:
384
+ link(site, r, "part", "contained")
385
+ # likely: only for sites and statements nothing better matched
386
+ for r in real:
387
+ r["tokens"] = _tokens(r["shape"])
388
+ for site, text in pending:
389
+ if site["id"] in matched:
390
+ continue
391
+ wanted = short_tables(site.get("tables"))
392
+ tokens = _tokens(text.replace(FRAGMENT, " "))
393
+ if not wanted or len(tokens) < 8:
394
+ continue
395
+ best, best_score = None, LIKELY
396
+ for r in real:
397
+ if r["q"]["hash"] in hit and hit[r["q"]["hash"]]["grade"] != "likely":
398
+ continue
399
+ if r["tables"] != wanted:
400
+ continue
401
+ union = len(tokens | r["tokens"])
402
+ score = len(tokens & r["tokens"]) / union if union else 0.0
403
+ if score >= best_score:
404
+ best, best_score = r, score
405
+ if best is not None:
406
+ link(site, best, "likely", "tokens")
407
+
408
+ by_hash = {q["hash"]: q for q in queries}
409
+ kinds = {q["hash"]: classify(q["text"]) for q in queries}
410
+ days = (hours / 24.0) if hours else None
411
+ totals = (workload.get("totals") or {}).get("select") or {}
412
+ total_bytes = int(totals.get("read_bytes") or 0) or sum(q["read_bytes"] for q in queries)
413
+ total_exec = int(totals.get("executions") or 0) or sum(q["executions"] for q in queries)
414
+ site_rows = {}
415
+ for site_id, m in matched.items():
416
+ qs = [by_hash[h] for h in m["hashes"]]
417
+ executions = sum(q["executions"] for q in qs)
418
+ read_bytes = sum(q["read_bytes"] for q in qs)
419
+ site_rows[site_id] = {
420
+ "match": m["grade"], "shapes": len(qs), "hashes": m["hashes"][:20],
421
+ "executions": executions, "executions_per_day": round(executions / days, 1) if days else None,
422
+ "read_bytes": read_bytes, "read_rows": sum(q["read_rows"] for q in qs), "total_ms": sum(q["total_ms"] for q in qs),
423
+ "avg_ms": round(sum(q["total_ms"] for q in qs) / executions, 1) if executions else 0.0,
424
+ "p95_ms": max((q.get("p95_ms") or 0) for q in qs) if qs else 0,
425
+ "avg_read_bytes": int(read_bytes / executions) if executions else 0,
426
+ "share_of_read_bytes": round(read_bytes / total_bytes, 6) if total_bytes else 0.0,
427
+ "rank_by_bytes": min(q["rank_by_bytes"] for q in qs),
428
+ "result_rows": sum(int(q.get("result_rows") or 0) for q in qs) if all("result_rows" in q for q in qs) else None,
429
+ # per run: what is read against what is returned (see ratios.py). Aggregate only when every matched shape is one.
430
+ **ratios(sum(q["read_rows"] for q in qs), read_bytes,
431
+ sum(int(q.get("result_rows") or 0) for q in qs) if all("result_rows" in q for q in qs) else None, executions,
432
+ sum(int(q["result_bytes"]) for q in qs) if qs and all(q.get("result_bytes") is not None for q in qs) else None),
433
+ "aggregate": bool(qs) and all(kinds[q["hash"]]["aggregate"] for q in qs),
434
+ "aggregate_kind": next(iter({kinds[q["hash"]]["aggregate_kind"] for q in qs}), "") if len({kinds[q["hash"]]["aggregate_kind"] for q in qs}) == 1 else "",
435
+ **with_repeat_window(spread_fields(qs, executions), workload),
436
+ **resource_fields(qs, executions),
437
+ }
438
+
439
+ def rate(grades: tuple[str, ...]) -> dict:
440
+ qs = [q for q in queries if q["hash"] in hit and hit[q["hash"]]["grade"] in grades]
441
+ return {"shapes": len(qs), "executions": sum(q["executions"] for q in qs), "read_bytes": sum(q["read_bytes"] for q in qs)}
442
+
443
+ top_bytes = sum(q["read_bytes"] for q in queries)
444
+ top_exec = sum(q["executions"] for q in queries)
445
+ rates = {g: rate((g,)) for g in GRADES}
446
+ rates["any"] = rate(GRADES)
447
+ rates["sure"] = rate(SURE)
448
+ for r in rates.values():
449
+ r["share_of_top_read_bytes"] = round(r["read_bytes"] / top_bytes, 4) if top_bytes else 0.0
450
+ r["share_of_top_executions"] = round(r["executions"] / top_exec, 4) if top_exec else 0.0
451
+ r["share_of_all_read_bytes"] = round(r["read_bytes"] / total_bytes, 4) if total_bytes else 0.0
452
+ r["share_of_all_executions"] = round(r["executions"] / total_exec, 4) if total_exec else 0.0
453
+ return {
454
+ "schema_version": 1, "engine": engine, "window_hours": hours, "since": workload.get("since", ""),
455
+ "workload": {"shapes_with_text": len(queries), "shapes_total": int(totals.get("shapes") or 0), "executions": total_exec,
456
+ "read_bytes": total_bytes, "top_read_bytes": top_bytes, "top_executions": top_exec,
457
+ "top_share_of_all_read_bytes": round(top_bytes / total_bytes, 4) if total_bytes else 0.0},
458
+ # the resource facts of the whole pull (window, totals, pressure, capacity, which facts it has): absent before them
459
+ **{k: workload[k] for k in RESOURCE_CONTEXT if isinstance(workload.get(k), dict)},
460
+ "sites_considered": len(sites),
461
+ # call sites of this engine that hold no SQL text (an unresolved argument, a wrapper's parameter): nothing to match
462
+ "sites_without_text": sum(1 for c in inventory.get("call_sites") or [] if not (c.get("sql") or "").strip()
463
+ and (include_tests or not c.get("is_test")) and c.get("engine") == engine),
464
+ "sites_matched": {g: sum(1 for m in matched.values() if m["grade"] == g) for g in GRADES},
465
+ "exact_how": {how: sum(1 for h in hit.values() if h["grade"] == "exact" and h["how"] == how)
466
+ for how in ("as written", "reformatted", "identifier")},
467
+ "rates": rates,
468
+ "sites": site_rows,
469
+ "queries": [{"hash": q["hash"], "match": hit[q["hash"]]["grade"] if q["hash"] in hit else "none",
470
+ "how": hit[q["hash"]]["how"] if q["hash"] in hit else "",
471
+ "site_ids": hit[q["hash"]]["sites"][:20] if q["hash"] in hit else [],
472
+ "executions": q["executions"], "read_bytes": q["read_bytes"], "read_rows": q["read_rows"], "total_ms": q["total_ms"],
473
+ "avg_ms": q["avg_ms"], "p95_ms": q.get("p95_ms"), "rank_by_bytes": q["rank_by_bytes"],
474
+ "result_rows": q.get("result_rows"),
475
+ **ratios(q["read_rows"], q["read_bytes"], q.get("result_rows"), q["executions"], q.get("result_bytes")), **kinds[q["hash"]],
476
+ **with_repeat_window(spread_fields([q], q["executions"]), workload),
477
+ **resource_fields([q], q["executions"]),
478
+ # the call-site tags the application set on it (ch.workload.tags): text that matched codecop:<tag> only
479
+ **({"tags": [t["tag"] for t in q["tags"]][:10]} if q.get("tags") else {}),
480
+ **({"labelled_in_text": True} if q.get("labelled_in_text") else {}),
481
+ "tables": sorted(short_tables(q.get("tables")) or tables_in(shape(q["text"])))} for q in queries],
482
+ }
483
+
484
+
485
+ def site_load(matchdata: dict | None, sure_only: bool = True) -> dict[str, dict]:
486
+ """site id -> its measured load, for scoring. `likely` matches are left out unless asked for."""
487
+ if not matchdata:
488
+ return {}
489
+ return {sid: row for sid, row in (matchdata.get("sites") or {}).items() if not sure_only or row["match"] in SURE}
490
+
491
+
492
+ def match_many(inventories: dict[str, dict], workload: dict, *, engine: str | None = None) -> dict:
493
+ """One workload against several repositories: a database is usually shared.
494
+
495
+ Returns each repository's own match and the union: for every real statement its best grade and the repositories
496
+ that reach it, so the share that no scanned repository accounts for is counted once."""
497
+ per = {name: match(inv, workload, engine=engine) for name, inv in inventories.items()}
498
+ rank = {g: i for i, g in enumerate(GRADES)}
499
+ best: dict[str, dict] = {}
500
+ for name, m in per.items():
501
+ files = {c["id"]: f"{c['file']}:{c['line']}" for c in inventories[name].get("call_sites") or [] if c.get("id")}
502
+ for q in m["queries"]:
503
+ b = best.setdefault(q["hash"], {**q, "match": "none", "how": "", "repos": [], "sites": []})
504
+ if q["match"] == "none":
505
+ continue
506
+ if b["match"] == "none" or rank[q["match"]] < rank[b["match"]]:
507
+ b.update(match=q["match"], how=q["how"], repos=[], sites=[])
508
+ if q["match"] == b["match"]:
509
+ b["repos"].append(name)
510
+ b["sites"].extend(f"{name}: {files.get(sid, sid)}" for sid in q["site_ids"][:5])
511
+ queries = sorted(best.values(), key=lambda q: -q["read_bytes"])
512
+ for q in queries:
513
+ q.pop("site_ids", None)
514
+ first = next(iter(per.values()), {"workload": {}, "window_hours": None})
515
+ total = first["workload"].get("read_bytes") or 0
516
+ total_exec = first["workload"].get("executions") or 0
517
+
518
+ def part(grades: tuple[str, ...]) -> dict:
519
+ rows = [q for q in queries if q["match"] in grades]
520
+ b, n = sum(q["read_bytes"] for q in rows), sum(q["executions"] for q in rows)
521
+ return {"shapes": len(rows), "read_bytes": b, "executions": n, "share_of_all_read_bytes": round(b / total, 4) if total else 0.0,
522
+ "share_of_all_executions": round(n / total_exec, 4) if total_exec else 0.0}
523
+
524
+ return {
525
+ "schema_version": 1, "engine": engine or workload.get("engine", ""), "window_hours": first.get("window_hours"),
526
+ "workload": first["workload"],
527
+ "repositories": {name: {"sites_matched": m["sites_matched"], "rates": {k: m["rates"][k] for k in ("sure", "part", "likely")}}
528
+ for name, m in per.items()},
529
+ "union": {**{g: part((g,)) for g in GRADES}, "sure": part(SURE), "none": part(("none",))},
530
+ "queries": queries,
531
+ }